From abfbc42df703c382a56cf1e06e4302cadbfe3395 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 25 Sep 2018 12:53:31 +0200 Subject: PNG image size optimization --- src/core.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index fc1a5a09..5f155a0a 100644 --- a/src/core.c +++ b/src/core.c @@ -1375,8 +1375,7 @@ const char *GetDirectoryPath(const char *fileName) memset(filePath, 0, 256); lastSlash = strprbrk(fileName, "\\/"); - if (!lastSlash) - return NULL; + if (!lastSlash) return NULL; strncpy(filePath, fileName, strlen(fileName) - (strlen(lastSlash) - 1)); filePath[strlen(fileName) - strlen(lastSlash)] = '\0'; -- cgit v1.2.3 From 1836e02c1ef9909d25bbb89b9d9fdd6ec934aada Mon Sep 17 00:00:00 2001 From: ChrisDill Date: Thu, 27 Sep 2018 15:52:56 +0100 Subject: Added monitor functions - Get number of monitors - Get size, physical size and name of primary monitor. Could pass monitor id instead not sure. --- src/core.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ src/raylib.h | 6 ++++++ 2 files changed, 55 insertions(+) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index fc1a5a09..e785e735 100644 --- a/src/core.c +++ b/src/core.c @@ -770,6 +770,55 @@ int GetScreenHeight(void) return screenHeight; } +// Get number of monitors +int GetMonitorCount(void) +{ + int monitorCount; + glfwGetMonitors(&monitorCount); + return monitorCount; +} + +// Get primary monitor width +int GetMonitorWidth(void) +{ + GLFWmonitor *monitor = glfwGetPrimaryMonitor(); + const GLFWvidmode * mode = glfwGetVideoMode(monitor); + return mode->width; +} + +// Get primary monitor height +int GetMonitorHeight(void) +{ + GLFWmonitor *monitor = glfwGetPrimaryMonitor(); + const GLFWvidmode * mode = glfwGetVideoMode(monitor); + return mode->height; +} + +// Get primary montior physical width in millimetres +int GetMonitorPhysicalWidth(void) +{ + int physicalWidth; + GLFWmonitor *monitor = glfwGetPrimaryMonitor(); + glfwGetMonitorPhysicalSize(monitor, &physicalWidth, NULL); + return physicalWidth; +} + +// Get primary monitor physical height in millimetres +int GetMonitorPhysicalHeight(void) +{ + int physicalHeight; + GLFWmonitor *monitor = glfwGetPrimaryMonitor(); + glfwGetMonitorPhysicalSize(monitor, NULL, &physicalHeight); + return physicalHeight; +} + +// Get the human-readable, UTF-8 encoded name of the primary monitor +const char *GetMonitorName(void) +{ + GLFWmonitor *monitor = glfwGetPrimaryMonitor(); + return glfwGetMonitorName(monitor); +} + // Show mouse cursor void ShowCursor() { diff --git a/src/raylib.h b/src/raylib.h index a44b77ee..ee8744e7 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -814,6 +814,12 @@ RLAPI void SetWindowMinSize(int width, int height); // Set window RLAPI void SetWindowSize(int width, int height); // Set window dimensions RLAPI int GetScreenWidth(void); // Get current screen width RLAPI int GetScreenHeight(void); // Get current screen height +RLAPI int GetMonitorCount(void); // Get number of connected monitors +RLAPI int GetMonitorWidth(void); // Get primary monitor width +RLAPI int GetMonitorHeight(void); // Get primary monitor height +RLAPI int GetMonitorPhysicalWidth(void); // Get primary monitor physical width in millimetres +RLAPI int GetMonitorPhysicalHeight(void); // Get primary monitor physical height in millimetres +RLAPI const char *GetMonitorName(void); // Get the human-readable, UTF-8 encoded name of the primary monitor // Cursor-related functions RLAPI void ShowCursor(void); // Shows cursor -- cgit v1.2.3 From ed79d53e1a177596d312453db8db4bc69f2b8656 Mon Sep 17 00:00:00 2001 From: ChrisDill Date: Thu, 27 Sep 2018 16:23:11 +0100 Subject: Changed tabs to spaces - Fixed tabs used instead of 4 spaces --- src/core.c | 32 ++++++++++++++++---------------- src/raylib.h | 10 +++++----- 2 files changed, 21 insertions(+), 21 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 5b9db9fa..9086ad65 100644 --- a/src/core.c +++ b/src/core.c @@ -773,9 +773,9 @@ int GetScreenHeight(void) // Get number of monitors int GetMonitorCount(void) { - int monitorCount; - glfwGetMonitors(&monitorCount); - return monitorCount; + int monitorCount; + glfwGetMonitors(&monitorCount); + return monitorCount; } // Get primary monitor width @@ -789,34 +789,34 @@ int GetMonitorWidth(void) // Get primary monitor height int GetMonitorHeight(void) { - GLFWmonitor *monitor = glfwGetPrimaryMonitor(); - const GLFWvidmode * mode = glfwGetVideoMode(monitor); - return mode->height; + GLFWmonitor *monitor = glfwGetPrimaryMonitor(); + const GLFWvidmode * mode = glfwGetVideoMode(monitor); + return mode->height; } // Get primary montior physical width in millimetres int GetMonitorPhysicalWidth(void) { - int physicalWidth; - GLFWmonitor *monitor = glfwGetPrimaryMonitor(); - glfwGetMonitorPhysicalSize(monitor, &physicalWidth, NULL); - return physicalWidth; + int physicalWidth; + GLFWmonitor *monitor = glfwGetPrimaryMonitor(); + glfwGetMonitorPhysicalSize(monitor, &physicalWidth, NULL); + return physicalWidth; } // Get primary monitor physical height in millimetres int GetMonitorPhysicalHeight(void) { - int physicalHeight; - GLFWmonitor *monitor = glfwGetPrimaryMonitor(); - glfwGetMonitorPhysicalSize(monitor, NULL, &physicalHeight); - return physicalHeight; + int physicalHeight; + GLFWmonitor *monitor = glfwGetPrimaryMonitor(); + glfwGetMonitorPhysicalSize(monitor, NULL, &physicalHeight); + return physicalHeight; } // Get the human-readable, UTF-8 encoded name of the primary monitor const char *GetMonitorName(void) { - GLFWmonitor *monitor = glfwGetPrimaryMonitor(); - return glfwGetMonitorName(monitor); + GLFWmonitor *monitor = glfwGetPrimaryMonitor(); + return glfwGetMonitorName(monitor); } // Show mouse cursor diff --git a/src/raylib.h b/src/raylib.h index ee8744e7..fb4fb842 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -814,11 +814,11 @@ RLAPI void SetWindowMinSize(int width, int height); // Set window RLAPI void SetWindowSize(int width, int height); // Set window dimensions RLAPI int GetScreenWidth(void); // Get current screen width RLAPI int GetScreenHeight(void); // Get current screen height -RLAPI int GetMonitorCount(void); // Get number of connected monitors -RLAPI int GetMonitorWidth(void); // Get primary monitor width -RLAPI int GetMonitorHeight(void); // Get primary monitor height -RLAPI int GetMonitorPhysicalWidth(void); // Get primary monitor physical width in millimetres -RLAPI int GetMonitorPhysicalHeight(void); // Get primary monitor physical height in millimetres +RLAPI int GetMonitorCount(void); // Get number of connected monitors +RLAPI int GetMonitorWidth(void); // Get primary monitor width +RLAPI int GetMonitorHeight(void); // Get primary monitor height +RLAPI int GetMonitorPhysicalWidth(void); // Get primary monitor physical width in millimetres +RLAPI int GetMonitorPhysicalHeight(void); // Get primary monitor physical height in millimetres RLAPI const char *GetMonitorName(void); // Get the human-readable, UTF-8 encoded name of the primary monitor // Cursor-related functions -- cgit v1.2.3 From ed95337eb884baac8de84ae0e973a5ecb0d530e2 Mon Sep 17 00:00:00 2001 From: ChrisDill Date: Sat, 29 Sep 2018 14:10:29 +0100 Subject: Added platform check - Added PLATFORM_DESKTOP check for Monitor functions to try to fix issue on android. - Not sure what return types should be when not on desktop. Added rough guess for now. --- src/core.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 9086ad65..65c18fec 100644 --- a/src/core.c +++ b/src/core.c @@ -773,50 +773,68 @@ int GetScreenHeight(void) // Get number of monitors int GetMonitorCount(void) { +#if defined(PLATFORM_DESKTOP) int monitorCount; glfwGetMonitors(&monitorCount); return monitorCount; +#endif + return 1; } // Get primary monitor width int GetMonitorWidth(void) { +#if defined(PLATFORM_DESKTOP) GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode * mode = glfwGetVideoMode(monitor); return mode->width; +#endif + return GetScreenWidth(); } // Get primary monitor height int GetMonitorHeight(void) { +#if defined(PLATFORM_DESKTOP) GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode * mode = glfwGetVideoMode(monitor); return mode->height; +#endif + return GetScreenHeight(); } // Get primary montior physical width in millimetres int GetMonitorPhysicalWidth(void) { +#if defined(PLATFORM_DESKTOP) int physicalWidth; GLFWmonitor *monitor = glfwGetPrimaryMonitor(); glfwGetMonitorPhysicalSize(monitor, &physicalWidth, NULL); return physicalWidth; +#endif + return 0; } // Get primary monitor physical height in millimetres int GetMonitorPhysicalHeight(void) { +#if defined(PLATFORM_DESKTOP) int physicalHeight; GLFWmonitor *monitor = glfwGetPrimaryMonitor(); glfwGetMonitorPhysicalSize(monitor, NULL, &physicalHeight); return physicalHeight; +#endif + return 0; } // Get the human-readable, UTF-8 encoded name of the primary monitor const char *GetMonitorName(void) { +#if defined(PLATFORM_DESKTOP) GLFWmonitor *monitor = glfwGetPrimaryMonitor(); return glfwGetMonitorName(monitor); +#endif + return ""; } // Show mouse cursor -- cgit v1.2.3 From 6b84b76b70be35b471ef31afc0f0dc4e16cfe383 Mon Sep 17 00:00:00 2001 From: ChrisDill Date: Sat, 29 Sep 2018 14:28:07 +0100 Subject: Forgot #else in platform check - Added else so return not compiled twice. --- src/core.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 65c18fec..e370d5e3 100644 --- a/src/core.c +++ b/src/core.c @@ -777,8 +777,9 @@ int GetMonitorCount(void) int monitorCount; glfwGetMonitors(&monitorCount); return monitorCount; -#endif +#else return 1; +#endif } // Get primary monitor width @@ -788,8 +789,9 @@ int GetMonitorWidth(void) GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode * mode = glfwGetVideoMode(monitor); return mode->width; -#endif +#else return GetScreenWidth(); +#endif } // Get primary monitor height @@ -799,8 +801,9 @@ int GetMonitorHeight(void) GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode * mode = glfwGetVideoMode(monitor); return mode->height; -#endif +#else return GetScreenHeight(); +#endif } // Get primary montior physical width in millimetres @@ -811,8 +814,9 @@ int GetMonitorPhysicalWidth(void) GLFWmonitor *monitor = glfwGetPrimaryMonitor(); glfwGetMonitorPhysicalSize(monitor, &physicalWidth, NULL); return physicalWidth; -#endif +#else return 0; +#endif } // Get primary monitor physical height in millimetres @@ -823,8 +827,9 @@ int GetMonitorPhysicalHeight(void) GLFWmonitor *monitor = glfwGetPrimaryMonitor(); glfwGetMonitorPhysicalSize(monitor, NULL, &physicalHeight); return physicalHeight; -#endif +#else return 0; +#endif } // Get the human-readable, UTF-8 encoded name of the primary monitor @@ -833,8 +838,9 @@ const char *GetMonitorName(void) #if defined(PLATFORM_DESKTOP) GLFWmonitor *monitor = glfwGetPrimaryMonitor(); return glfwGetMonitorName(monitor); -#endif +#else return ""; +#endif } // Show mouse cursor -- cgit v1.2.3 From 67dc50ef0077b194fa51014880e531b126d0b059 Mon Sep 17 00:00:00 2001 From: ChrisDill Date: Sun, 30 Sep 2018 15:20:02 +0100 Subject: Changed monitor functions to use a index - Using same idea as SetWindowMonitor to take in a index with 0 being the primary monitor. --- src/core.c | 93 ++++++++++++++++++++++++++++++++++++++---------------------- src/raylib.h | 10 +++---- 2 files changed, 64 insertions(+), 39 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index e370d5e3..203da4d9 100644 --- a/src/core.c +++ b/src/core.c @@ -783,64 +783,89 @@ int GetMonitorCount(void) } // Get primary monitor width -int GetMonitorWidth(void) +int GetMonitorWidth(int monitor) { #if defined(PLATFORM_DESKTOP) - GLFWmonitor *monitor = glfwGetPrimaryMonitor(); - const GLFWvidmode * mode = glfwGetVideoMode(monitor); - return mode->width; -#else - return GetScreenWidth(); + int monitorCount; + GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); + + if ((monitor >= 0) && (monitor < monitorCount)) + { + const GLFWvidmode *mode = glfwGetVideoMode(monitors[monitor]); + return mode->width; + } + else TraceLog(LOG_WARNING, "Selected monitor not found"); #endif + return 0; } -// Get primary monitor height -int GetMonitorHeight(void) -{ +// Get primary monitor width +int GetMonitorHeight(int monitor) +{ #if defined(PLATFORM_DESKTOP) - GLFWmonitor *monitor = glfwGetPrimaryMonitor(); - const GLFWvidmode * mode = glfwGetVideoMode(monitor); - return mode->height; -#else - return GetScreenHeight(); + int monitorCount; + GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); + + if ((monitor >= 0) && (monitor < monitorCount)) + { + const GLFWvidmode *mode = glfwGetVideoMode(monitors[monitor]); + return mode->height; + } + else TraceLog(LOG_WARNING, "Selected monitor not found"); #endif + return 0; } // Get primary montior physical width in millimetres -int GetMonitorPhysicalWidth(void) +int GetMonitorPhysicalWidth(int monitor) { #if defined(PLATFORM_DESKTOP) - int physicalWidth; - GLFWmonitor *monitor = glfwGetPrimaryMonitor(); - glfwGetMonitorPhysicalSize(monitor, &physicalWidth, NULL); - return physicalWidth; -#else - return 0; + int monitorCount; + GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); + + if ((monitor >= 0) && (monitor < monitorCount)) + { + int physicalWidth; + glfwGetMonitorPhysicalSize(monitors[monitor], &physicalWidth, NULL); + return physicalWidth; + } + else TraceLog(LOG_WARNING, "Selected monitor not found"); #endif + return 0; } // Get primary monitor physical height in millimetres -int GetMonitorPhysicalHeight(void) +int GetMonitorPhysicalHeight(int monitor) { -#if defined(PLATFORM_DESKTOP) - int physicalHeight; - GLFWmonitor *monitor = glfwGetPrimaryMonitor(); - glfwGetMonitorPhysicalSize(monitor, NULL, &physicalHeight); - return physicalHeight; -#else - return 0; +#if defined(PLATFORM_DESKTOP) + int monitorCount; + GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); + + if ((monitor >= 0) && (monitor < monitorCount)) + { + int physicalHeight; + glfwGetMonitorPhysicalSize(monitors[monitor], NULL, &physicalHeight); + return physicalHeight; + } + else TraceLog(LOG_WARNING, "Selected monitor not found"); #endif + return 0; } // Get the human-readable, UTF-8 encoded name of the primary monitor -const char *GetMonitorName(void) +const char *GetMonitorName(int monitor) { #if defined(PLATFORM_DESKTOP) - GLFWmonitor *monitor = glfwGetPrimaryMonitor(); - return glfwGetMonitorName(monitor); -#else - return ""; + int monitorCount; + GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); + + if ((monitor >= 0) && (monitor < monitorCount)) + { + return glfwGetMonitorName(monitors[monitor]); + } + else TraceLog(LOG_WARNING, "Selected monitor not found"); #endif + return ""; } // Show mouse cursor diff --git a/src/raylib.h b/src/raylib.h index fb4fb842..17c4234e 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -815,11 +815,11 @@ RLAPI void SetWindowSize(int width, int height); // Set window RLAPI int GetScreenWidth(void); // Get current screen width RLAPI int GetScreenHeight(void); // Get current screen height RLAPI int GetMonitorCount(void); // Get number of connected monitors -RLAPI int GetMonitorWidth(void); // Get primary monitor width -RLAPI int GetMonitorHeight(void); // Get primary monitor height -RLAPI int GetMonitorPhysicalWidth(void); // Get primary monitor physical width in millimetres -RLAPI int GetMonitorPhysicalHeight(void); // Get primary monitor physical height in millimetres -RLAPI const char *GetMonitorName(void); // Get the human-readable, UTF-8 encoded name of the primary monitor +RLAPI int GetMonitorWidth(int monitor); // Get primary monitor width +RLAPI int GetMonitorHeight(int monitor); // Get primary monitor height +RLAPI int GetMonitorPhysicalWidth(int monitor); // Get primary monitor physical width in millimetres +RLAPI int GetMonitorPhysicalHeight(int monitor); // Get primary monitor physical height in millimetres +RLAPI const char *GetMonitorName(int monitor); // Get the human-readable, UTF-8 encoded name of the primary monitor // Cursor-related functions RLAPI void ShowCursor(void); // Shows cursor -- cgit v1.2.3 From 1fe6d9fc06156257d5210cfa71ecb839fb190722 Mon Sep 17 00:00:00 2001 From: Ahmad Fatoum Date: Sun, 7 Oct 2018 00:47:57 +0200 Subject: core: workaround window not being rendered till moved on macOS Mojave Apple ought to fix their OpenGL implementation, but with OpenGL now deprecated this might not happen. This has been reported upstream in GLFW in glfw/glfw#1334. The workaround comes from kovidgoyal/kitty@b82e74f99 This also fixes the HiDPI (Retina) scaling issues reported in #497, so the workaround is enabled anywhere __APPLE__ is defined. --- src/core.c | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 203da4d9..558cc854 100644 --- a/src/core.c +++ b/src/core.c @@ -134,12 +134,6 @@ #define CHDIR chdir #endif -#if defined(__linux__) || defined(PLATFORM_WEB) - #include // Required for: timespec, nanosleep(), select() - POSIX -#elif defined(__APPLE__) - #include // Required for: usleep() -#endif - #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) #if defined(PLATFORM_WEB) #define GLFW_INCLUDE_ES2 @@ -155,6 +149,15 @@ #endif #endif +#if defined(__linux__) || defined(PLATFORM_WEB) + #include // Required for: timespec, nanosleep(), select() - POSIX +#elif defined(__APPLE__) + #include // Required for: usleep() + #include // Required for: objc_msgsend(), sel_registerName() + #define GLFW_EXPOSE_NATIVE_NSGL + #include // Required for: glfwGetNSGLContext() +#endif + #if defined(PLATFORM_ANDROID) //#include // Android sensors functions (accelerometer, gyroscope, light...) #include // Defines AWINDOW_FLAG_FULLSCREEN and others @@ -233,6 +236,11 @@ static bool windowReady = false; // Check if window has been init static bool windowMinimized = false; // Check if window has been minimized static const char *windowTitle = NULL; // Window text title... +#if defined(__APPLE__) +static int windowNeedsUpdating = 2; // Times the Cocoa window needs to be updated initially +#endif + + #if defined(PLATFORM_ANDROID) static struct android_app *androidApp; // Android activity static struct android_poll_source *source; // Android events polling source @@ -2870,6 +2878,15 @@ static void SwapBuffers(void) { #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) glfwSwapBuffers(window); +#if __APPLE__ + // workaround for missing/erroneous initial rendering on macOS + if (windowNeedsUpdating) { + // Desugared version of Objective C: [glfwGetNSGLContext(window) update] + ((id (*)(id, SEL))objc_msgSend)(glfwGetNSGLContext(window), + sel_registerName("update")); + windowNeedsUpdating--; + } +#endif #endif #if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(PLATFORM_UWP) -- cgit v1.2.3 From 2feea87b616292b5bce4454a42c2d048f1cce7d8 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 Oct 2018 12:29:02 +0200 Subject: Multiple changes, check description REVIEW: Reorganized global variables for consistency ADDED: GetWindowHandle() to get native window handle ADDED: GetDirectoryFiles() to get files list for a DIR --- src/core.c | 244 +++++++++++++++++++-------- src/external/glfw/include/GLFW/glfw3native.h | 7 +- src/raylib.h | 7 +- 3 files changed, 181 insertions(+), 77 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 558cc854..45524988 100644 --- a/src/core.c +++ b/src/core.c @@ -123,6 +123,7 @@ #include // Required for: strrchr(), strcmp() //#include // Macros for reporting and retrieving error conditions through error codes #include // Required for: tolower() [Used in IsFileExtension()] +#include // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] #if defined(_WIN32) #include // Required for: _getch(), _chdir() @@ -141,6 +142,18 @@ //#define GLFW_INCLUDE_NONE // Disable the standard OpenGL header inclusion on GLFW3 #include // GLFW3 library: Windows, OpenGL context and Input management // NOTE: GLFW3 already includes gl.h (OpenGL) headers + + // Support retrieving native window handlers + #if defined(_WIN32) + #define GLFW_EXPOSE_NATIVE_WIN32 + #elif defined(__linux__) + #define GLFW_EXPOSE_NATIVE_X11 + //GLFW_EXPOSE_NATIVE_WAYLAND + //GLFW_EXPOSE_NATIVE_MIR + #elif defined(__APPLE__) + #define GLFW_EXPOSE_NATIVE_COCOA + #endif + #include // WARNING: It requires customization to avoid windows.h inclusion! #if !defined(SUPPORT_BUSY_WAIT_LOOP) && defined(_WIN32) // NOTE: Those functions require linking with winmm library @@ -228,10 +241,12 @@ //---------------------------------------------------------------------------------- // Global Variables Definition //---------------------------------------------------------------------------------- + +// Window/Graphics related variables +//----------------------------------------------------------------------------------- #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) static GLFWwindow *window; // Native window (graphic device) #endif - static bool windowReady = false; // Check if window has been initialized successfully static bool windowMinimized = false; // Check if window has been minimized static const char *windowTitle = NULL; // Window text title... @@ -240,6 +255,31 @@ static const char *windowTitle = NULL; // Window text title... static int windowNeedsUpdating = 2; // Times the Cocoa window needs to be updated initially #endif +static unsigned int displayWidth, displayHeight;// Display width and height (monitor, device-screen, LCD, ...) +static int screenWidth, screenHeight; // Screen width and height (used render area) +static int renderWidth, renderHeight; // Framebuffer width and height (render area, including black bars if required) +static int renderOffsetX = 0; // Offset X from render area (must be divided by 2) +static int renderOffsetY = 0; // Offset Y from render area (must be divided by 2) +static bool fullscreen = false; // Fullscreen mode (useful only for PLATFORM_DESKTOP) +static Matrix downscaleView; // Matrix to downscale view (in case screen size bigger than display size) + +#if defined(PLATFORM_RPI) +static EGL_DISPMANX_WINDOW_T nativeWindow; // Native window (graphic device) +#endif + +#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(PLATFORM_UWP) +static EGLDisplay display; // Native display device (physical screen connection) +static EGLSurface surface; // Surface to draw on, framebuffers (connected to context) +static EGLContext context; // Graphic context, mode in which drawing can be done +static EGLConfig config; // Graphic config +static uint64_t baseTime; // Base time measure for hi-res timer +static bool windowShouldClose = false; // Flag to set window for closing +#endif + +#if defined(PLATFORM_UWP) +extern EGLNativeWindowType uwpWindow; // Native EGL window handler for UWP (external, defined in UWP App) +#endif +//----------------------------------------------------------------------------------- #if defined(PLATFORM_ANDROID) static struct android_app *androidApp; // Android activity @@ -251,104 +291,86 @@ static bool appEnabled = true; // Used to detec if app is activ static bool contextRebindRequired = false; // Used to know context rebind required #endif -#if defined(PLATFORM_RPI) -static EGL_DISPMANX_WINDOW_T nativeWindow; // Native window (graphic device) +// Inputs related variables +//----------------------------------------------------------------------------------- +// Keyboard states +static char previousKeyState[512] = { 0 }; // Registers previous frame key state +static char currentKeyState[512] = { 0 }; // Registers current frame key state +static int lastKeyPressed = -1; // Register last key pressed +static int exitKey = KEY_ESCAPE; // Default exit key (ESC) -// Keyboard input variables +#if defined(PLATFORM_RPI) // NOTE: For keyboard we will use the standard input (but reconfigured...) static struct termios defaultKeyboardSettings; // Used to store default keyboard settings static int defaultKeyboardMode; // Used to store default keyboard mode +#endif + +// Mouse states +static Vector2 mousePosition; // Mouse position on screen +static float mouseScale = 1.0f; // Mouse default scale +static bool cursorHidden = false; // Track if cursor is hidden +static bool cursorOnScreen = false; // Tracks if cursor is inside client area +static Vector2 touchPosition[MAX_TOUCH_POINTS]; // Touch position on screen + +#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) || defined(PLATFORM_WEB) || defined(PLATFORM_UWP) +static char previousMouseState[3] = { 0 }; // Registers previous mouse button state +static char currentMouseState[3] = { 0 }; // Registers current mouse button state +static int previousMouseWheelY = 0; // Registers previous mouse wheel variation +static int currentMouseWheelY = 0; // Registers current mouse wheel variation +#endif -// Mouse input variables +#if defined(PLATFORM_RPI) static int mouseStream = -1; // Mouse device file descriptor static bool mouseReady = false; // Flag to know if mouse is ready static pthread_t mouseThreadId; // Mouse reading thread id - -// Touch input variables static int touchStream = -1; // Touch device file descriptor static bool touchReady = false; // Flag to know if touch interface is ready static pthread_t touchThreadId; // Touch reading thread id - -// Gamepad input variables -static int gamepadStream[MAX_GAMEPADS] = { -1 };// Gamepad device file descriptor -static pthread_t gamepadThreadId; // Gamepad reading thread id -static char gamepadName[64]; // Gamepad name holder #endif - -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(PLATFORM_UWP) -static EGLDisplay display; // Native display device (physical screen connection) -static EGLSurface surface; // Surface to draw on, framebuffers (connected to context) -static EGLContext context; // Graphic context, mode in which drawing can be done -static EGLConfig config; // Graphic config -static uint64_t baseTime; // Base time measure for hi-res timer -static bool windowShouldClose = false; // Flag to set window for closing -#endif - -#if defined(PLATFORM_UWP) -extern EGLNativeWindowType uwpWindow; // Native EGL window handler for UWP (external, defined in UWP App) +#if defined(PLATFORM_WEB) +static bool toggleCursorLock = false; // Ask for cursor pointer lock on next click #endif -// Screen related variables -static unsigned int displayWidth, displayHeight; // Display width and height (monitor, device-screen, LCD, ...) -static int screenWidth, screenHeight; // Screen width and height (used render area) -static int renderWidth, renderHeight; // Framebuffer width and height (render area, including black bars if required) -static int renderOffsetX = 0; // Offset X from render area (must be divided by 2) -static int renderOffsetY = 0; // Offset Y from render area (must be divided by 2) -static bool fullscreen = false; // Fullscreen mode (useful only for PLATFORM_DESKTOP) -static Matrix downscaleView; // Matrix to downscale view (in case screen size bigger than display size) - -static bool cursorHidden = false; // Track if cursor is hidden -static bool cursorOnScreen = false; // Tracks if cursor is inside client area +// Gamepads states +static int lastGamepadButtonPressed = -1; // Register last gamepad button pressed +static int gamepadAxisCount = 0; // Register number of available gamepad axis #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) || defined(PLATFORM_WEB) || defined(PLATFORM_UWP) -// Register mouse states -static char previousMouseState[3] = { 0 }; // Registers previous mouse button state -static char currentMouseState[3] = { 0 }; // Registers current mouse button state -static int previousMouseWheelY = 0; // Registers previous mouse wheel variation -static int currentMouseWheelY = 0; // Registers current mouse wheel variation - -// Register gamepads states static bool gamepadReady[MAX_GAMEPADS] = { false }; // Flag to know if gamepad is ready static float gamepadAxisState[MAX_GAMEPADS][MAX_GAMEPAD_AXIS]; // Gamepad axis state static char previousGamepadState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; // Previous gamepad buttons state static char currentGamepadState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; // Current gamepad buttons state - -// Keyboard configuration -static int exitKey = KEY_ESCAPE; // Default exit key (ESC) #endif -// Register keyboard states -static char previousKeyState[512] = { 0 }; // Registers previous frame key state -static char currentKeyState[512] = { 0 }; // Registers current frame key state - -static int lastKeyPressed = -1; // Register last key pressed -static int lastGamepadButtonPressed = -1; // Register last gamepad button pressed -static int gamepadAxisCount = 0; // Register number of available gamepad axis - -static Vector2 mousePosition; // Mouse position on screen -static float mouseScale = 1.0f; // Mouse default scale - -#if defined(PLATFORM_WEB) -static bool toggleCursorLock = false; // Ask for cursor pointer lock on next click -#endif - -static Vector2 touchPosition[MAX_TOUCH_POINTS]; // Touch position on screen - -#if defined(PLATFORM_DESKTOP) -static char **dropFilesPath; // Store dropped files paths as strings -static int dropFilesCount = 0; // Count stored strings +#if defined(PLATFORM_RPI) +static int gamepadStream[MAX_GAMEPADS] = { -1 };// Gamepad device file descriptor +static pthread_t gamepadThreadId; // Gamepad reading thread id +static char gamepadName[64]; // Gamepad name holder #endif +//----------------------------------------------------------------------------------- +// Timming system variables +//----------------------------------------------------------------------------------- static double currentTime = 0.0; // Current time measure static double previousTime = 0.0; // Previous time measure static double updateTime = 0.0; // Time measure for frame update static double drawTime = 0.0; // Time measure for frame draw static double frameTime = 0.0; // Time measure for one frame static double targetTime = 0.0; // Desired time for one frame, if 0 not applied +//----------------------------------------------------------------------------------- +// Config internal variables +//----------------------------------------------------------------------------------- static unsigned char configFlags = 0; // Configuration flags (bit based) static bool showLogo = false; // Track if showing logo at init is enabled +#if defined(PLATFORM_DESKTOP) +static char **dropFilesPath; // Store dropped files paths as strings +static int dropFilesCount = 0; // Count dropped files strings +#endif +static char **dirFilesPath; // Store directory files paths as strings +static int dirFilesCount = 0; // Count directory files strings + #if defined(SUPPORT_SCREEN_CAPTURE) static int screenshotCounter = 0; // Screenshots counter #endif @@ -357,6 +379,7 @@ static int screenshotCounter = 0; // Screenshots counter static int gifFramesCounter = 0; // GIF frames counter static bool gifRecording = false; // GIF recording state #endif +//----------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- // Other Modules Functions Declaration (required by core) @@ -370,15 +393,18 @@ extern void UnloadDefaultFont(void); // [Module: text] Unloads default fo // Module specific Functions Declaration //---------------------------------------------------------------------------------- static bool InitGraphicsDevice(int width, int height); // Initialize graphics device -static void SetupFramebufferSize(int displayWidth, int displayHeight); +static void SetupFramebuffer(int width, int height); // Setup main framebuffer +static void SetupViewport(void); // Set viewport parameters +static void SwapBuffers(void); // Copy back buffer to front buffers + static void InitTimer(void); // Initialize timer static void Wait(float ms); // Wait for some milliseconds (stop program execution) + static bool GetKeyStatus(int key); // Returns if a key has been pressed static bool GetMouseButtonStatus(int button); // Returns if a mouse button has been pressed static void PollInputEvents(void); // Register user events -static void SwapBuffers(void); // Copy back buffer to front buffers + static void LogoAnimation(void); // Plays raylib logo appearing animation -static void SetupViewport(void); // Set viewport parameters #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) static void ErrorCallback(int error, const char *description); // GLFW3 Error Callback, runs on GLFW3 error @@ -391,7 +417,6 @@ static void CursorEnterCallback(GLFWwindow *window, int enter); static void WindowSizeCallback(GLFWwindow *window, int width, int height); // GLFW3 WindowSize Callback, runs when window is resized static void WindowIconifyCallback(GLFWwindow *window, int iconified); // GLFW3 WindowIconify Callback, runs when window is minimized/restored #endif - #if defined(PLATFORM_DESKTOP) static void WindowDropCallback(GLFWwindow *window, int count, const char **paths); // GLFW3 Window Drop Callback, runs when drop files into window #endif @@ -778,6 +803,26 @@ int GetScreenHeight(void) return screenHeight; } +// Get native window handle +void *GetWindowHandle(void) +{ +#if defined(_WIN32) + // NOTE: Returned handle is: void *HWND (windows.h) + return glfwGetWin32Window(window); +#elif defined(__linux__) + // NOTE: Returned handle is: unsigned long Window (X.h) + // typedef unsigned long XID; + // typedef XID Window; + unsigned long id = (unsigned long)glfwGetX11Window(window); + return NULL; // TODO: Find a way to return value... cast to void *? +#elif defined(__APPLE__) + // NOTE: Returned handle is: void *id + return glfwGetCocoaWindow(window); +#else + return NULL; +#endif +} + // Get number of monitors int GetMonitorCount(void) { @@ -1500,6 +1545,57 @@ const char *GetWorkingDirectory(void) return currentDir; } +// Get filenames in a directory path (max 256 files) +// NOTE: Files count is returned by parameters pointer +char **GetDirectoryFiles(const char *dirPath, int *fileCount) +{ + #define MAX_FILEPATH_LENGTH 256 + #define MAX_DIRECTORY_FILES 512 + + ClearDirectoryFiles(); + + // Memory allocation for MAX_DIRECTORY_FILES + dirFilesPath = (char **)malloc(sizeof(char *)*MAX_DIRECTORY_FILES); + for (int i = 0; i < MAX_DIRECTORY_FILES; i++) dirFilesPath[i] = (char *)malloc(sizeof(char)*MAX_FILEPATH_LENGTH); + + int counter = 0; + struct dirent *ent; + DIR *dir = opendir(dirPath); + + if (dir != NULL) // It's a directory + { + // TODO: Reading could be done in two passes, + // first one to count files and second one to read names + // That way we can allocate required memory, instead of a limited pool + + while ((ent = readdir(dir)) != NULL) + { + strcpy(dirFilesPath[counter], ent->d_name); + counter++; + } + + closedir(dir); + } + else TraceLog(LOG_WARNING, "Can not open directory...\n"); // Maybe it's a file... + + dirFilesCount = counter; + *fileCount = dirFilesCount; + + return dirFilesPath; +} + +// Clear directory files paths buffers +void ClearDirectoryFiles(void) +{ + if (dirFilesCount > 0) + { + for (int i = 0; i < dirFilesCount; i++) free(dirFilesPath[i]); + + free(dirFilesPath); + dirFilesCount = 0; + } +} + // Change working directory, returns true if success bool ChangeDirectory(const char *dir) { @@ -2099,7 +2195,7 @@ static bool InitGraphicsDevice(int width, int height) // At this point we need to manage render size vs screen size // NOTE: This function uses and modifies global module variables: // screenWidth/screenHeight - renderWidth/renderHeight - downscaleView - SetupFramebufferSize(displayWidth, displayHeight); + SetupFramebuffer(displayWidth, displayHeight); window = glfwCreateWindow(displayWidth, displayHeight, windowTitle, glfwGetPrimaryMonitor(), NULL); @@ -2333,7 +2429,7 @@ static bool InitGraphicsDevice(int width, int height) } } - //SetupFramebufferSize(displayWidth, displayHeight); + //SetupFramebuffer(displayWidth, displayHeight); EGLint numConfigs = 0; if ((eglChooseConfig(display, framebufferAttribs, &config, 1, &numConfigs) == EGL_FALSE) || (numConfigs == 0)) @@ -2439,7 +2535,7 @@ static bool InitGraphicsDevice(int width, int height) // At this point we need to manage render size vs screen size // NOTE: This function use and modify global module variables: screenWidth/screenHeight and renderWidth/renderHeight and downscaleView - SetupFramebufferSize(displayWidth, displayHeight); + SetupFramebuffer(displayWidth, displayHeight); ANativeWindow_setBuffersGeometry(androidApp->window, renderWidth, renderHeight, displayFormat); //ANativeWindow_setBuffersGeometry(androidApp->window, 0, 0, displayFormat); // Force use of native display size @@ -2452,7 +2548,7 @@ static bool InitGraphicsDevice(int width, int height) // At this point we need to manage render size vs screen size // NOTE: This function use and modify global module variables: screenWidth/screenHeight and renderWidth/renderHeight and downscaleView - SetupFramebufferSize(displayWidth, displayHeight); + SetupFramebuffer(displayWidth, displayHeight); dstRect.x = 0; dstRect.y = 0; @@ -2554,7 +2650,7 @@ static void SetupViewport(void) // Compute framebuffer size relative to screen size and display size // NOTE: Global variables renderWidth/renderHeight and renderOffsetX/renderOffsetY can be modified -static void SetupFramebufferSize(int displayWidth, int displayHeight) +static void SetupFramebuffer(int width, int height) { // Calculate renderWidth and renderHeight, we have the display size (input params) and the desired screen size (global var) if ((screenWidth > displayWidth) || (screenHeight > displayHeight)) diff --git a/src/external/glfw/include/GLFW/glfw3native.h b/src/external/glfw/include/GLFW/glfw3native.h index 4372cb76..84bb3399 100644 --- a/src/external/glfw/include/GLFW/glfw3native.h +++ b/src/external/glfw/include/GLFW/glfw3native.h @@ -90,7 +90,12 @@ extern "C" { #undef APIENTRY #undef GLFW_APIENTRY_DEFINED #endif - #include +// RAY: Actually, only HWND handler needs to be defined +// Including windows.h could suppose symbols re-definition issues (i.e Rectangle type) +//#include + typedef void *PVOID; + typedef PVOID HANDLE; + typedef HANDLE HWND; #elif defined(GLFW_EXPOSE_NATIVE_COCOA) #include #if defined(__OBJC__) diff --git a/src/raylib.h b/src/raylib.h index 20a3ca26..6549ba1d 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -814,6 +814,7 @@ RLAPI void SetWindowMinSize(int width, int height); // Set window RLAPI void SetWindowSize(int width, int height); // Set window dimensions RLAPI int GetScreenWidth(void); // Get current screen width RLAPI int GetScreenHeight(void); // Get current screen height +RLAPI void *GetWindowHandle(void); // Get native window handle RLAPI int GetMonitorCount(void); // Get number of connected monitors RLAPI int GetMonitorWidth(int monitor); // Get primary monitor width RLAPI int GetMonitorHeight(int monitor); // Get primary monitor height @@ -872,10 +873,12 @@ RLAPI const char *GetExtension(const char *fileName); // Get pointer RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string RLAPI const char *GetDirectoryPath(const char *fileName); // Get full path for a given fileName (uses static string) RLAPI const char *GetWorkingDirectory(void); // Get current working directory (uses static string) +RLAPI char **GetDirectoryFiles(const char *dirPath, int *count); // Get filenames in a directory path (memory should be freed) +RLAPI void ClearDirectoryFiles(void); // Clear directory files paths buffers (free memory) RLAPI bool ChangeDirectory(const char *dir); // Change working directory, returns true if success RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window -RLAPI char **GetDroppedFiles(int *count); // Get dropped files names -RLAPI void ClearDroppedFiles(void); // Clear dropped files paths buffer +RLAPI char **GetDroppedFiles(int *count); // Get dropped files names (memory should be freed) +RLAPI void ClearDroppedFiles(void); // Clear dropped files paths buffer (free memory) // Persistent storage management RLAPI void StorageSaveValue(int position, int value); // Save integer value to storage file (to defined position) -- cgit v1.2.3 From ca1e309d9d132debb40f55f57a177af085e49194 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 Oct 2018 13:14:15 +0200 Subject: Corrected issue with GetWindowHandle() Not supported for the moment, issues with Linux (symbol `Font` redefined) and OSX (NSGL type redefined) --- src/core.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 45524988..e9de01d6 100644 --- a/src/core.c +++ b/src/core.c @@ -147,11 +147,11 @@ #if defined(_WIN32) #define GLFW_EXPOSE_NATIVE_WIN32 #elif defined(__linux__) - #define GLFW_EXPOSE_NATIVE_X11 + //#define GLFW_EXPOSE_NATIVE_X11 // WARNING: Exposing Xlib.h > X.h results in dup symbols for Font type //GLFW_EXPOSE_NATIVE_WAYLAND //GLFW_EXPOSE_NATIVE_MIR #elif defined(__APPLE__) - #define GLFW_EXPOSE_NATIVE_COCOA + //#define GLFW_EXPOSE_NATIVE_COCOA // WARNING: NSGL typedef redefinition with different types ('struct objc_object *' vs 'void *') > glfw3native issue? #endif #include // WARNING: It requires customization to avoid windows.h inclusion! @@ -813,11 +813,11 @@ void *GetWindowHandle(void) // NOTE: Returned handle is: unsigned long Window (X.h) // typedef unsigned long XID; // typedef XID Window; - unsigned long id = (unsigned long)glfwGetX11Window(window); + //unsigned long id = (unsigned long)glfwGetX11Window(window); return NULL; // TODO: Find a way to return value... cast to void *? #elif defined(__APPLE__) // NOTE: Returned handle is: void *id - return glfwGetCocoaWindow(window); + return NULL; //glfwGetCocoaWindow(window); #else return NULL; #endif -- cgit v1.2.3 From 97f6454982e439850ff86b2552c9c6b4e0d8076b Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 Oct 2018 13:29:42 +0200 Subject: Corrected issue with native handler on OSX --- src/core.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index e9de01d6..f1505691 100644 --- a/src/core.c +++ b/src/core.c @@ -145,15 +145,14 @@ // Support retrieving native window handlers #if defined(_WIN32) - #define GLFW_EXPOSE_NATIVE_WIN32 + #define GLFW_EXPOSE_NATIVE_WIN32 + #include // WARNING: It requires customization to avoid windows.h inclusion! #elif defined(__linux__) //#define GLFW_EXPOSE_NATIVE_X11 // WARNING: Exposing Xlib.h > X.h results in dup symbols for Font type //GLFW_EXPOSE_NATIVE_WAYLAND //GLFW_EXPOSE_NATIVE_MIR - #elif defined(__APPLE__) - //#define GLFW_EXPOSE_NATIVE_COCOA // WARNING: NSGL typedef redefinition with different types ('struct objc_object *' vs 'void *') > glfw3native issue? #endif - #include // WARNING: It requires customization to avoid windows.h inclusion! + #if !defined(SUPPORT_BUSY_WAIT_LOOP) && defined(_WIN32) // NOTE: Those functions require linking with winmm library @@ -167,8 +166,9 @@ #elif defined(__APPLE__) #include // Required for: usleep() #include // Required for: objc_msgsend(), sel_registerName() + #define GLFW_EXPOSE_NATIVE_COCOA #define GLFW_EXPOSE_NATIVE_NSGL - #include // Required for: glfwGetNSGLContext() + #include // Required for: glfwGetCocoaWindow(), glfwGetNSGLContext() #endif #if defined(PLATFORM_ANDROID) @@ -817,7 +817,7 @@ void *GetWindowHandle(void) return NULL; // TODO: Find a way to return value... cast to void *? #elif defined(__APPLE__) // NOTE: Returned handle is: void *id - return NULL; //glfwGetCocoaWindow(window); + return glfwGetCocoaWindow(window); #else return NULL; #endif -- cgit v1.2.3 From 2d324f22a7d0e91ce5592f9529d92791797ee7df Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 Oct 2018 16:12:09 +0200 Subject: Corrected issue with native window handler on OSX Could not be retrieved for now... --- src/core.c | 65 +++++++++++++++++++++++++++++++------------------------------- 1 file changed, 33 insertions(+), 32 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index f1505691..1324b883 100644 --- a/src/core.c +++ b/src/core.c @@ -135,42 +135,38 @@ #define CHDIR chdir #endif -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - #if defined(PLATFORM_WEB) - #define GLFW_INCLUDE_ES2 - #endif +#if defined(PLATFORM_DESKTOP) //#define GLFW_INCLUDE_NONE // Disable the standard OpenGL header inclusion on GLFW3 #include // GLFW3 library: Windows, OpenGL context and Input management // NOTE: GLFW3 already includes gl.h (OpenGL) headers - + // Support retrieving native window handlers #if defined(_WIN32) #define GLFW_EXPOSE_NATIVE_WIN32 #include // WARNING: It requires customization to avoid windows.h inclusion! + + #if !defined(SUPPORT_BUSY_WAIT_LOOP) + // NOTE: Those functions require linking with winmm library + unsigned int __stdcall timeBeginPeriod(unsigned int uPeriod); + unsigned int __stdcall timeEndPeriod(unsigned int uPeriod); + #endif #elif defined(__linux__) - //#define GLFW_EXPOSE_NATIVE_X11 // WARNING: Exposing Xlib.h > X.h results in dup symbols for Font type - //GLFW_EXPOSE_NATIVE_WAYLAND - //GLFW_EXPOSE_NATIVE_MIR - #endif - - - #if !defined(SUPPORT_BUSY_WAIT_LOOP) && defined(_WIN32) - // NOTE: Those functions require linking with winmm library - unsigned int __stdcall timeBeginPeriod(unsigned int uPeriod); - unsigned int __stdcall timeEndPeriod(unsigned int uPeriod); + #include // Required for: timespec, nanosleep(), select() - POSIX + + //#define GLFW_EXPOSE_NATIVE_X11 // WARNING: Exposing Xlib.h > X.h results in dup symbols for Font type + //#define GLFW_EXPOSE_NATIVE_WAYLAND + //#define GLFW_EXPOSE_NATIVE_MIR + #include // Required for: glfwGetX11Window() + #elif defined(__APPLE__) + #include // Required for: usleep() + #include // Required for: objc_msgsend(), sel_registerName() + + //#define GLFW_EXPOSE_NATIVE_COCOA // WARNING: typedef redefinition with different types ('void *' vs 'struct objc_object *') + #define GLFW_EXPOSE_NATIVE_NSGL + #include // Required for: glfwGetCocoaWindow(), glfwGetNSGLContext() #endif #endif -#if defined(__linux__) || defined(PLATFORM_WEB) - #include // Required for: timespec, nanosleep(), select() - POSIX -#elif defined(__APPLE__) - #include // Required for: usleep() - #include // Required for: objc_msgsend(), sel_registerName() - #define GLFW_EXPOSE_NATIVE_COCOA - #define GLFW_EXPOSE_NATIVE_NSGL - #include // Required for: glfwGetCocoaWindow(), glfwGetNSGLContext() -#endif - #if defined(PLATFORM_ANDROID) //#include // Android sensors functions (accelerometer, gyroscope, light...) #include // Defines AWINDOW_FLAG_FULLSCREEN and others @@ -205,8 +201,12 @@ #endif #if defined(PLATFORM_WEB) - #include - #include + #define GLFW_INCLUDE_ES2 // GLFW3: Enable OpenGL ES 2.0 (translated to WebGL) + #include // GLFW3 library: Windows, OpenGL context and Input management + #include // Required for: timespec, nanosleep(), select() - POSIX + + #include // Emscripten library - LLVM to JavaScript compiler + #include // Emscripten HTML5 library #endif //---------------------------------------------------------------------------------- @@ -817,7 +817,7 @@ void *GetWindowHandle(void) return NULL; // TODO: Find a way to return value... cast to void *? #elif defined(__APPLE__) // NOTE: Returned handle is: void *id - return glfwGetCocoaWindow(window); + return NULL; //glfwGetCocoaWindow(window); // #else return NULL; #endif @@ -2975,11 +2975,12 @@ static void SwapBuffers(void) #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) glfwSwapBuffers(window); #if __APPLE__ - // workaround for missing/erroneous initial rendering on macOS - if (windowNeedsUpdating) { + // Workaround for missing/erroneous initial rendering on macOS + if (windowNeedsUpdating) + { // Desugared version of Objective C: [glfwGetNSGLContext(window) update] - ((id (*)(id, SEL))objc_msgSend)(glfwGetNSGLContext(window), - sel_registerName("update")); + ((id (*)(id, SEL))objc_msgSend)(glfwGetNSGLContext(window), sel_registerName("update")); + windowNeedsUpdating--; } #endif -- cgit v1.2.3 From 6e4bd60978d880d57808317e0890f14614dcc215 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 Oct 2018 16:25:47 +0200 Subject: Trying to include dirent.h for MSVC --- src/core.c | 7 ++- src/external/dirent.h | 127 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 1 deletion(-) create mode 100644 src/external/dirent.h (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 1324b883..bd21c143 100644 --- a/src/core.c +++ b/src/core.c @@ -123,7 +123,12 @@ #include // Required for: strrchr(), strcmp() //#include // Macros for reporting and retrieving error conditions through error codes #include // Required for: tolower() [Used in IsFileExtension()] -#include // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] + +#if defined(_MSC_VER) + #include // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] +#else + #include // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] +#endif #if defined(_WIN32) #include // Required for: _getch(), _chdir() diff --git a/src/external/dirent.h b/src/external/dirent.h new file mode 100644 index 00000000..2d7a1b73 --- /dev/null +++ b/src/external/dirent.h @@ -0,0 +1,127 @@ +/* + * DIRENT.H (formerly DIRLIB.H) + * This file has no copyright assigned and is placed in the Public Domain. + * This file is part of the mingw-runtime package. + * No warranty is given; refer to the file DISCLAIMER within the package. + * + */ + +#ifndef _DIRENT_H_ +#define _DIRENT_H_ + +/* All the headers include this file. */ +#include + +#include + +#ifndef RC_INVOKED + +#pragma pack(push,_CRT_PACKING) + +#ifdef __cplusplus +extern "C" { +#endif + +struct dirent +{ + long d_ino; /* Always zero. */ + unsigned short d_reclen; /* Always zero. */ + unsigned short d_namlen; /* Length of name in d_name. */ + char d_name[260]; /* [FILENAME_MAX] */ /* File name. */ +}; + +/* + * This is an internal data structure. Good programmers will not use it + * except as an argument to one of the functions below. + * dd_stat field is now int (was short in older versions). + */ +typedef struct +{ + /* disk transfer area for this dir */ + struct _finddata_t dd_dta; + + /* dirent struct to return from dir (NOTE: this makes this thread + * safe as long as only one thread uses a particular DIR struct at + * a time) */ + struct dirent dd_dir; + + /* _findnext handle */ + intptr_t dd_handle; + + /* + * Status of search: + * 0 = not started yet (next entry to read is first entry) + * -1 = off the end + * positive = 0 based index of next entry + */ + int dd_stat; + + /* given path for dir with search pattern (struct is extended) */ + char dd_name[1]; +} DIR; + +DIR* __cdecl __MINGW_NOTHROW opendir (const char*); +struct dirent* __cdecl __MINGW_NOTHROW readdir (DIR*); +int __cdecl __MINGW_NOTHROW closedir (DIR*); +void __cdecl __MINGW_NOTHROW rewinddir (DIR*); +long __cdecl __MINGW_NOTHROW telldir (DIR*); +void __cdecl __MINGW_NOTHROW seekdir (DIR*, long); + + +/* wide char versions */ + +struct _wdirent +{ + long d_ino; /* Always zero. */ + unsigned short d_reclen; /* Always zero. */ + unsigned short d_namlen; /* Length of name in d_name. */ + wchar_t d_name[260]; /* [FILENAME_MAX] */ /* File name. */ +}; + +/* + * This is an internal data structure. Good programmers will not use it + * except as an argument to one of the functions below. + */ +typedef struct +{ + /* disk transfer area for this dir */ + struct _wfinddata_t dd_dta; + + /* dirent struct to return from dir (NOTE: this makes this thread + * safe as long as only one thread uses a particular DIR struct at + * a time) */ + struct _wdirent dd_dir; + + /* _findnext handle */ + intptr_t dd_handle; + + /* + * Status of search: + * 0 = not started yet (next entry to read is first entry) + * -1 = off the end + * positive = 0 based index of next entry + */ + int dd_stat; + + /* given path for dir with search pattern (struct is extended) */ + wchar_t dd_name[1]; +} _WDIR; + +_WDIR* __cdecl __MINGW_NOTHROW _wopendir (const wchar_t*); +struct _wdirent* __cdecl __MINGW_NOTHROW _wreaddir (_WDIR*); +int __cdecl __MINGW_NOTHROW _wclosedir (_WDIR*); +void __cdecl __MINGW_NOTHROW _wrewinddir (_WDIR*); +long __cdecl __MINGW_NOTHROW _wtelldir (_WDIR*); +void __cdecl __MINGW_NOTHROW _wseekdir (_WDIR*, long); + + +#ifdef __cplusplus +} +#endif + +#pragma pack(pop) + +#endif /* Not RC_INVOKED */ + +#endif /* Not _DIRENT_H_ */ + -- cgit v1.2.3 From 2652e7d1c1051852e7f2ebf0e71396ac645c6713 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 Oct 2018 18:08:39 +0200 Subject: Avoid multiple gl.h inclusions Expose native Cocoa Window again... --- src/core.c | 9 +++++---- src/external/glfw/include/GLFW/glfw3native.h | 5 ++++- 2 files changed, 9 insertions(+), 5 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index bd21c143..356e6821 100644 --- a/src/core.c +++ b/src/core.c @@ -141,7 +141,8 @@ #endif #if defined(PLATFORM_DESKTOP) - //#define GLFW_INCLUDE_NONE // Disable the standard OpenGL header inclusion on GLFW3 + #define GLFW_INCLUDE_NONE // Disable the standard OpenGL header inclusion on GLFW3 + // NOTE: Already provided by rlgl implementation (on glad.h) #include // GLFW3 library: Windows, OpenGL context and Input management // NOTE: GLFW3 already includes gl.h (OpenGL) headers @@ -166,7 +167,7 @@ #include // Required for: usleep() #include // Required for: objc_msgsend(), sel_registerName() - //#define GLFW_EXPOSE_NATIVE_COCOA // WARNING: typedef redefinition with different types ('void *' vs 'struct objc_object *') + #define GLFW_EXPOSE_NATIVE_COCOA #define GLFW_EXPOSE_NATIVE_NSGL #include // Required for: glfwGetCocoaWindow(), glfwGetNSGLContext() #endif @@ -821,8 +822,8 @@ void *GetWindowHandle(void) //unsigned long id = (unsigned long)glfwGetX11Window(window); return NULL; // TODO: Find a way to return value... cast to void *? #elif defined(__APPLE__) - // NOTE: Returned handle is: void *id - return NULL; //glfwGetCocoaWindow(window); // + // NOTE: Returned handle is: (objc_object *) + return (void *)glfwGetCocoaWindow(window); #else return NULL; #endif diff --git a/src/external/glfw/include/GLFW/glfw3native.h b/src/external/glfw/include/GLFW/glfw3native.h index 84bb3399..463a7a71 100644 --- a/src/external/glfw/include/GLFW/glfw3native.h +++ b/src/external/glfw/include/GLFW/glfw3native.h @@ -101,7 +101,10 @@ extern "C" { #if defined(__OBJC__) #import #else - typedef void* id; + // RAY: Added protection in case OBJC types defined + #if !defined(OBJC_TYPES_DEFINED) + typedef void* id; + #endif #endif #elif defined(GLFW_EXPOSE_NATIVE_X11) #include -- cgit v1.2.3 From 717cf77129bd30099e489a29ae19dc053923264d Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 Oct 2018 18:38:39 +0200 Subject: Corrected issue with dirent.h inclusion... ...and MacOSX OBJC types definition... --- src/core.c | 2 +- src/external/glfw/include/GLFW/glfw3native.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 356e6821..cdbed2f8 100644 --- a/src/core.c +++ b/src/core.c @@ -125,7 +125,7 @@ #include // Required for: tolower() [Used in IsFileExtension()] #if defined(_MSC_VER) - #include // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] + #include "external/dirent.h" // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] #else #include // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] #endif diff --git a/src/external/glfw/include/GLFW/glfw3native.h b/src/external/glfw/include/GLFW/glfw3native.h index 463a7a71..d585496c 100644 --- a/src/external/glfw/include/GLFW/glfw3native.h +++ b/src/external/glfw/include/GLFW/glfw3native.h @@ -102,7 +102,7 @@ extern "C" { #import #else // RAY: Added protection in case OBJC types defined - #if !defined(OBJC_TYPES_DEFINED) + #if !OBJC_TYPES_DEFINED typedef void* id; #endif #endif -- cgit v1.2.3 From 4f5937e89bc0cfddd6c3a36292d3262a9b75de92 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 Oct 2018 18:51:41 +0200 Subject: OSX native window keeps breaking... --- src/core.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index cdbed2f8..f9de55e5 100644 --- a/src/core.c +++ b/src/core.c @@ -167,7 +167,7 @@ #include // Required for: usleep() #include // Required for: objc_msgsend(), sel_registerName() - #define GLFW_EXPOSE_NATIVE_COCOA + //#define GLFW_EXPOSE_NATIVE_COCOA // WARNING: Fails due to type redefinition #define GLFW_EXPOSE_NATIVE_NSGL #include // Required for: glfwGetCocoaWindow(), glfwGetNSGLContext() #endif @@ -823,7 +823,7 @@ void *GetWindowHandle(void) return NULL; // TODO: Find a way to return value... cast to void *? #elif defined(__APPLE__) // NOTE: Returned handle is: (objc_object *) - return (void *)glfwGetCocoaWindow(window); + return NULL; // TODO: return (void *)glfwGetCocoaWindow(window); #else return NULL; #endif -- cgit v1.2.3 From a511337ce880f6e910cc0b5b20195c6cf1ec70e7 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 10 Oct 2018 12:01:59 +0200 Subject: ADDED: GetFileNameWithoutExt --- src/core.c | 35 +++++++++++++++++++++++++++++++++++ src/raylib.h | 1 + 2 files changed, 36 insertions(+) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index f9de55e5..37772e7e 100644 --- a/src/core.c +++ b/src/core.c @@ -1523,6 +1523,41 @@ const char *GetFileName(const char *filePath) return fileName + 1; } +// Get filename string without extension (memory should be freed) +const char *GetFileNameWithoutExt(const char *filePath) +{ + char *result, *lastDot, *lastSep; + + char nameDot = '.'; // Default filename to extension separator character + char pathSep = '/'; // Default filepath separator character + + // Error checks and allocate string + if (filePath == NULL) return NULL; + + // Try to allocate new string, same size as original + // NOTE: By default strlen() does not count the '\0' character + if ((result = malloc(strlen(filePath) + 1)) == NULL) return NULL; + + strcpy(result, filePath); // Make a copy of the string + + // NOTE: strrchr() returns a pointer to the last occurrence of character + lastDot = strrchr(result, nameDot); + lastSep = (pathSep == 0) ? NULL : strrchr(result, pathSep); + + if (lastDot != NULL) // Check if it has an extension separator... + { + if (lastSep != NULL) // ...and it's before the extenstion separator... + { + if (lastSep < lastDot) + { + *lastDot = '\0'; // ...then remove it + } + } + else *lastDot = '\0'; // Has extension separator with no path separator + } + + return result; // Return the modified string +} // Get directory for a given fileName (with path) const char *GetDirectoryPath(const char *fileName) diff --git a/src/raylib.h b/src/raylib.h index 2bc37906..3bd16f00 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -871,6 +871,7 @@ RLAPI int GetRandomValue(int min, int max); // Returns a r RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension RLAPI const char *GetExtension(const char *fileName); // Get pointer to extension for a filename string RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string +RLAPI const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (memory should be freed) RLAPI const char *GetDirectoryPath(const char *fileName); // Get full path for a given fileName (uses static string) RLAPI const char *GetWorkingDirectory(void); // Get current working directory (uses static string) RLAPI char **GetDirectoryFiles(const char *dirPath, int *count); // Get filenames in a directory path (memory should be freed) -- cgit v1.2.3 From 126ab49221ff4cc988ed83efc110d88e96c7f962 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 10 Oct 2018 23:55:36 +0200 Subject: Minor tweaks --- src/core.c | 3 ++- src/rlgl.h | 14 +++++--------- src/textures.c | 2 +- 3 files changed, 8 insertions(+), 11 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 37772e7e..e99b24b5 100644 --- a/src/core.c +++ b/src/core.c @@ -1569,8 +1569,9 @@ const char *GetDirectoryPath(const char *fileName) lastSlash = strprbrk(fileName, "\\/"); if (!lastSlash) return NULL; + // NOTE: Be careful, strncpy() is not safe, it does not care about '\0' strncpy(filePath, fileName, strlen(fileName) - (strlen(lastSlash) - 1)); - filePath[strlen(fileName) - strlen(lastSlash)] = '\0'; + filePath[strlen(fileName) - strlen(lastSlash)] = '\0'; // Add '\0' manually return filePath; } diff --git a/src/rlgl.h b/src/rlgl.h index 3f5c67a9..61834f83 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -1631,17 +1631,13 @@ void rlglInit(int width, int height) #elif defined(GRAPHICS_API_OPENGL_ES2) char *extensions = (char *)glGetString(GL_EXTENSIONS); // One big const string - // NOTE: We have to duplicate string because glGetString() returns a const value - // If not duplicated, it fails in some systems (Raspberry Pi) - // Equivalent to function: char *strdup(const char *str) - char *extensionsDup; - size_t len = strlen(extensions) + 1; - void *newstr = malloc(len); - if (newstr == NULL) extensionsDup = NULL; - extensionsDup = (char *)memcpy(newstr, extensions, len); + // NOTE: We have to duplicate string because glGetString() returns a const string + int len = strlen(extensions) + 1; + char *extensionsDup = (char *)malloc(len); + strcpy(extensionsDup, extensions); // NOTE: String could be splitted using strtok() function (string.h) - // NOTE: strtok() modifies the received string, it can not be const + // NOTE: strtok() modifies the passed string, it can not be const char *extList[512]; // Allocate 512 strings pointers (2 KB) diff --git a/src/textures.c b/src/textures.c index 7ee07d12..4c276324 100644 --- a/src/textures.c +++ b/src/textures.c @@ -323,7 +323,7 @@ Image LoadImageRaw(const char *fileName, int width, int height, int format, int // NOTE: fread() returns num read elements instead of bytes, // to get bytes we need to read (1 byte size, elements) instead of (x byte size, 1 element) - size_t bytes = fread(image.data, 1, size, rawFile); + int bytes = fread(image.data, 1, size, rawFile); // Check if data has been read successfully if (bytes < size) -- cgit v1.2.3 From c2b36af60f1b2823cdeb6c8ae73a4957026d46ce Mon Sep 17 00:00:00 2001 From: ChrisDill Date: Fri, 12 Oct 2018 13:53:36 +0100 Subject: Added GetLastWriteTime to allow for file reloading - Added a function to get the last write time of a file. I used this so I can reload files or resources if the time since they were last loaded changes. --- src/core.c | 13 +++++++++++++ src/raylib.h | 1 + 2 files changed, 14 insertions(+) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index e99b24b5..3b54c05c 100644 --- a/src/core.c +++ b/src/core.c @@ -123,6 +123,7 @@ #include // Required for: strrchr(), strcmp() //#include // Macros for reporting and retrieving error conditions through error codes #include // Required for: tolower() [Used in IsFileExtension()] +#include // Required for stat() [Used in GetLastWriteTime()] #if defined(_MSC_VER) #include "external/dirent.h" // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] @@ -1681,6 +1682,18 @@ void ClearDroppedFiles(void) #endif } +// Get the last write time of a file +long GetLastWriteTime(const char *fileName) +{ + struct stat result = {0}; + if (stat(fileName, &result) == 0) + { + time_t mod = result.st_mtime; + return mod; + } + return 0; +} + // Save integer value to storage file (to defined position) // NOTE: Storage positions is directly related to file memory layout (4 bytes each integer) void StorageSaveValue(int position, int value) diff --git a/src/raylib.h b/src/raylib.h index 9d870255..1765b40b 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -880,6 +880,7 @@ RLAPI bool ChangeDirectory(const char *dir); // Change work RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window RLAPI char **GetDroppedFiles(int *count); // Get dropped files names (memory should be freed) RLAPI void ClearDroppedFiles(void); // Clear dropped files paths buffer (free memory) +RLAPI long GetLastWriteTime(const char *fileName); // Get last write time of a file // Persistent storage management RLAPI void StorageSaveValue(int position, int value); // Save integer value to storage file (to defined position) -- cgit v1.2.3 From c7b601b62465c7d38daed6fcc916bd94fdead1cf Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sat, 13 Oct 2018 15:59:17 +0200 Subject: Renamed new PR function RENAME: GetLastWriteTime() to GetFileModTime() --- src/core.c | 11 +++++++---- src/raylib.h | 2 +- 2 files changed, 8 insertions(+), 5 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 3b54c05c..7162f47d 100644 --- a/src/core.c +++ b/src/core.c @@ -1682,15 +1682,18 @@ void ClearDroppedFiles(void) #endif } -// Get the last write time of a file -long GetLastWriteTime(const char *fileName) +// Get file modification time (last write time) +RLAPI long GetFileModTime(const char *fileName) { - struct stat result = {0}; + struct stat result = { 0 }; + if (stat(fileName, &result) == 0) { time_t mod = result.st_mtime; - return mod; + + return (long)mod; } + return 0; } diff --git a/src/raylib.h b/src/raylib.h index 1765b40b..e0b6a5a4 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -880,7 +880,7 @@ RLAPI bool ChangeDirectory(const char *dir); // Change work RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window RLAPI char **GetDroppedFiles(int *count); // Get dropped files names (memory should be freed) RLAPI void ClearDroppedFiles(void); // Clear dropped files paths buffer (free memory) -RLAPI long GetLastWriteTime(const char *fileName); // Get last write time of a file +RLAPI long GetFileModTime(const char *fileName); // Get file modification time (last write time) // Persistent storage management RLAPI void StorageSaveValue(int position, int value); // Save integer value to storage file (to defined position) -- cgit v1.2.3 From d8331bde3a6c9781278106497be023b349b0a3fa Mon Sep 17 00:00:00 2001 From: Michael Vetter Date: Sun, 14 Oct 2018 14:14:04 +0200 Subject: Add FileExists() function --- src/core.c | 18 +++++++++++++++++- src/raylib.h | 1 + 2 files changed, 18 insertions(+), 1 deletion(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 7162f47d..54a788bf 100644 --- a/src/core.c +++ b/src/core.c @@ -135,8 +135,9 @@ #include // Required for: _getch(), _chdir() #define GETCWD _getcwd // NOTE: MSDN recommends not to use getcwd(), chdir() #define CHDIR _chdir + #include // Required for _access() [Used in FileExists()] #else - #include "unistd.h" // Required for: getch(), chdir() (POSIX) + #include "unistd.h" // Required for: getch(), chdir() (POSIX), access() #define GETCWD getcwd #define CHDIR chdir #endif @@ -1514,6 +1515,21 @@ static const char *strprbrk(const char *s, const char *charset) return latestMatch; } +// Return true if the file exists +bool FileExists(const char *fileName) +{ + bool result = false; + +#if defined(_WIN32) + if (_access(fileName, 0) != -1) +#else + if (access(fileName, F_OK) != -1) +#endif + result = true; + + return result; +} + // Get pointer to filename for a path string const char *GetFileName(const char *filePath) { diff --git a/src/raylib.h b/src/raylib.h index 963df077..8aa5e7be 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -870,6 +870,7 @@ RLAPI int GetRandomValue(int min, int max); // Returns a r // Files management functions RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension RLAPI const char *GetExtension(const char *fileName); // Get pointer to extension for a filename string +RLAPI bool FileExists(const char *fileName); // Return true if file exists RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string RLAPI const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (memory should be freed) RLAPI const char *GetDirectoryPath(const char *fileName); // Get full path for a given fileName (uses static string) -- cgit v1.2.3 From b8b8936cd780b34edb2899eb32b756a1aebef9d3 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 16 Oct 2018 10:53:01 +0200 Subject: Review defines --- src/audio.c | 2 +- src/core.c | 32 ++++++++++++++++---------------- src/raylib.h | 8 ++++---- src/rlgl.h | 12 ++++++------ 4 files changed, 27 insertions(+), 27 deletions(-) (limited to 'src/core.c') diff --git a/src/audio.c b/src/audio.c index 95e59931..f3db1124 100644 --- a/src/audio.c +++ b/src/audio.c @@ -132,7 +132,7 @@ #include "external/dr_mp3.h" // MP3 loading functions #endif -#ifdef _MSC_VER +#if defined(_MSC_VER) #undef bool #endif diff --git a/src/core.c b/src/core.c index 54a788bf..70a7bf68 100644 --- a/src/core.c +++ b/src/core.c @@ -125,7 +125,7 @@ #include // Required for: tolower() [Used in IsFileExtension()] #include // Required for stat() [Used in GetLastWriteTime()] -#if defined(_MSC_VER) +#if defined(_WIN32) && defined(_MSC_VER) #include "external/dirent.h" // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] #else #include // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] @@ -1465,6 +1465,21 @@ void TakeScreenshot(const char *fileName) #endif } +// Check if the file exists +bool FileExists(const char *fileName) +{ + bool result = false; + +#if defined(_WIN32) + if (_access(fileName, 0) != -1) +#else + if (access(fileName, F_OK) != -1) +#endif + result = true; + + return result; +} + // Check file extension bool IsFileExtension(const char *fileName, const char *ext) { @@ -1515,21 +1530,6 @@ static const char *strprbrk(const char *s, const char *charset) return latestMatch; } -// Return true if the file exists -bool FileExists(const char *fileName) -{ - bool result = false; - -#if defined(_WIN32) - if (_access(fileName, 0) != -1) -#else - if (access(fileName, F_OK) != -1) -#endif - result = true; - - return result; -} - // Get pointer to filename for a path string const char *GetFileName(const char *filePath) { diff --git a/src/raylib.h b/src/raylib.h index 8aa5e7be..42bc38e7 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -311,7 +311,7 @@ // NOTE: MSC C++ compiler does not support compound literals (C99 feature) // Plain structures in C++ (without constructors) can be initialized from { } initializers. -#ifdef __cplusplus +#if defined(__cplusplus) #define CLITERAL #else #define CLITERAL (Color) @@ -786,7 +786,7 @@ typedef enum { // Callbacks to be implemented by users typedef void (*TraceLogCallback)(int msgType, const char *text, va_list args); -#ifdef __cplusplus +#if defined(__cplusplus) extern "C" { // Prevents name mangling of functions #endif @@ -868,9 +868,9 @@ RLAPI void TakeScreenshot(const char *fileName); // Takes a scr RLAPI int GetRandomValue(int min, int max); // Returns a random value between min and max (both included) // Files management functions +RLAPI bool FileExists(const char *fileName); // Check if file exists RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension RLAPI const char *GetExtension(const char *fileName); // Get pointer to extension for a filename string -RLAPI bool FileExists(const char *fileName); // Return true if file exists RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string RLAPI const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (memory should be freed) RLAPI const char *GetDirectoryPath(const char *fileName); // Get full path for a given fileName (uses static string) @@ -1277,7 +1277,7 @@ RLAPI void StopAudioStream(AudioStream stream); // Stop au RLAPI void SetAudioStreamVolume(AudioStream stream, float volume); // Set volume for audio stream (1.0 is max level) RLAPI void SetAudioStreamPitch(AudioStream stream, float pitch); // Set pitch for audio stream (1.0 is base level) -#ifdef __cplusplus +#if defined(__cplusplus) } #endif diff --git a/src/rlgl.h b/src/rlgl.h index 61834f83..d2b52a47 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -378,7 +378,7 @@ typedef unsigned char byte; } VrDevice; #endif -#ifdef __cplusplus +#if defined(__cplusplus) extern "C" { // Prevents name mangling of functions #endif @@ -516,7 +516,7 @@ void TraceLog(int msgType, const char *text, ...); // Show trace log messag int GetPixelDataSize(int width, int height, int format);// Get pixel data size in bytes (image or texture) #endif -#ifdef __cplusplus +#if defined(__cplusplus) } #endif @@ -553,7 +553,7 @@ int GetPixelDataSize(int width, int height, int format);// Get pixel data size i #else // APIENTRY for OpenGL function pointer declarations is required #ifndef APIENTRY - #ifdef _WIN32 + #if defined(_WIN32) #define APIENTRY __stdcall #else #define APIENTRY @@ -1620,7 +1620,7 @@ void rlglInit(int width, int height) // NOTE: We don't need to check again supported extensions but we do (GLAD already dealt with that) glGetIntegerv(GL_NUM_EXTENSIONS, &numExt); -#ifdef _MSC_VER +#if defined(_MSC_VER) const char **extList = malloc(sizeof(const char *)*numExt); #else const char *extList[numExt]; @@ -3803,7 +3803,7 @@ static unsigned int LoadShaderProgram(unsigned int vShaderId, unsigned int fShad glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); -#ifdef _MSC_VER +#if defined(_MSC_VER) char *log = malloc(maxLength); #else char log[maxLength]; @@ -3812,7 +3812,7 @@ static unsigned int LoadShaderProgram(unsigned int vShaderId, unsigned int fShad TraceLog(LOG_INFO, "%s", log); -#ifdef _MSC_VER +#if defined(_MSC_VER) free(log); #endif glDeleteProgram(program); -- cgit v1.2.3 From 764766bfb2160cdbe3196abe3c90ad86197fc8d6 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 18 Oct 2018 16:00:11 +0200 Subject: Some formatting tweaks --- src/audio.c | 4 ++-- src/core.c | 2 +- src/raylib.h | 2 +- src/text.c | 21 +++++++++++---------- src/textures.c | 8 ++++---- 5 files changed, 19 insertions(+), 18 deletions(-) (limited to 'src/core.c') diff --git a/src/audio.c b/src/audio.c index a646c981..dcde6e65 100644 --- a/src/audio.c +++ b/src/audio.c @@ -431,7 +431,7 @@ static mal_uint32 OnAudioBufferDSPRead(mal_dsp *pDSP, mal_uint32 frameCount, voi mal_uint32 totalFramesRemaining = (frameCount - framesRead); if (totalFramesRemaining > 0) { - memset((unsigned char*)pFramesOut + (framesRead*frameSizeInBytes), 0, totalFramesRemaining*frameSizeInBytes); + memset((unsigned char *)pFramesOut + (framesRead*frameSizeInBytes), 0, totalFramesRemaining*frameSizeInBytes); // For static buffers we can fill the remaining frames with silence for safety, but we don't want // to report those frames as "read". The reason for this is that the caller uses the return value @@ -1062,7 +1062,7 @@ void WaveCrop(Wave *wave, int initSample, int finalSample) void *data = malloc(sampleCount*wave->sampleSize/8*wave->channels); - memcpy(data, (unsigned char*)wave->data + (initSample*wave->channels*wave->sampleSize/8), sampleCount*wave->channels*wave->sampleSize/8); + memcpy(data, (unsigned char *)wave->data + (initSample*wave->channels*wave->sampleSize/8), sampleCount*wave->channels*wave->sampleSize/8); free(wave->data); wave->data = data; diff --git a/src/core.c b/src/core.c index 70a7bf68..41aa181b 100644 --- a/src/core.c +++ b/src/core.c @@ -478,7 +478,7 @@ void android_main(struct android_app *app) androidApp = app; // TODO: Should we maybe report != 0 return codes somewhere? - (void)main(1, (char*[]) { arg0, NULL }); + (void)main(1, (char *[]) { arg0, NULL }); } // TODO: Add this to header (if apps really need it) diff --git a/src/raylib.h b/src/raylib.h index 42bc38e7..aa5bd16f 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1083,7 +1083,7 @@ RLAPI void UnloadFont(Font font); // Text drawing functions RLAPI void DrawFPS(int posX, int posY); // Shows current FPS RLAPI void DrawText(const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) -RLAPI void DrawTextEx(Font font, const char* text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text using font and additional parameters +RLAPI void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text using font and additional parameters // Text misc. functions RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font diff --git a/src/text.c b/src/text.c index d8fb3c98..5d5de6fa 100644 --- a/src/text.c +++ b/src/text.c @@ -589,10 +589,10 @@ void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, f int length = strlen(text); int textOffsetX = 0; // Offset between characters int textOffsetY = 0; // Required for line break! - float scaleFactor; + float scaleFactor = 0.0f; - unsigned char letter; // Current character - int index; // Index position in sprite font + unsigned char letter = 0; // Current character + int index = 0; // Index position in sprite font scaleFactor = fontSize/font.baseSize; @@ -656,7 +656,7 @@ const char *FormatText(const char *text, ...) // Get a piece of a text string const char *SubText(const char *text, int position, int length) { - static char buffer[MAX_SUBTEXT_LENGTH]; + static char buffer[MAX_SUBTEXT_LENGTH] = { 0 }; int textLength = strlen(text); if (position >= textLength) @@ -703,8 +703,8 @@ Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing int tempLen = 0; // Used to count longer text line num chars int lenCounter = 0; - float textWidth = 0; - float tempTextWidth = 0; // Used to count longer text line width + float textWidth = 0.0f; + float tempTextWidth = 0.0f; // Used to count longer text line width float textHeight = (float)font.baseSize; float scaleFactor = fontSize/(float)font.baseSize; @@ -912,17 +912,18 @@ static Font LoadBMFont(const char *fileName) Font font = { 0 }; font.texture.id = 0; - char buffer[MAX_BUFFER_SIZE]; + char buffer[MAX_BUFFER_SIZE] = { 0 }; char *searchPoint = NULL; int fontSize = 0; - int texWidth, texHeight; + int texWidth = 0; + int texHeight = 0; char texFileName[129]; int charsCount = 0; - int base; // Useless data + int base = 0; // Useless data - FILE *fntFile; + FILE *fntFile = NULL; fntFile = fopen(fileName, "rt"); diff --git a/src/textures.c b/src/textures.c index 4c276324..a0e74637 100644 --- a/src/textures.c +++ b/src/textures.c @@ -2780,7 +2780,7 @@ static Image LoadDDS(const char *fileName) TraceLog(LOG_DEBUG, "Pitch or linear size: %i", ddsHeader.pitchOrLinearSize); - image.data = (unsigned char*)malloc(size*sizeof(unsigned char)); + image.data = (unsigned char *)malloc(size*sizeof(unsigned char)); fread(image.data, size, 1, ddsFile); @@ -2877,7 +2877,7 @@ static Image LoadPKM(const char *fileName) int size = image.width*image.height*bpp/8; // Total data size in bytes - image.data = (unsigned char*)malloc(size*sizeof(unsigned char)); + image.data = (unsigned char *)malloc(size*sizeof(unsigned char)); fread(image.data, size, 1, pkmFile); @@ -2971,7 +2971,7 @@ static Image LoadKTX(const char *fileName) int dataSize; fread(&dataSize, sizeof(unsigned int), 1, ktxFile); - image.data = (unsigned char*)malloc(dataSize*sizeof(unsigned char)); + image.data = (unsigned char *)malloc(dataSize*sizeof(unsigned char)); fread(image.data, dataSize, 1, ktxFile); @@ -3213,7 +3213,7 @@ static Image LoadPVR(const char *fileName) } int dataSize = image.width*image.height*bpp/8; // Total data size in bytes - image.data = (unsigned char*)malloc(dataSize*sizeof(unsigned char)); + image.data = (unsigned char *)malloc(dataSize*sizeof(unsigned char)); // Read data from file fread(image.data, dataSize, 1, pvrFile); -- cgit v1.2.3 From 161b18edea6649a108ef3f7aa37464688adcba07 Mon Sep 17 00:00:00 2001 From: Ray Date: Sat, 20 Oct 2018 12:30:37 +0200 Subject: Reviewed possible issue with external libs --- src/Makefile | 3 --- src/core.c | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) (limited to 'src/core.c') diff --git a/src/Makefile b/src/Makefile index 2932e7bb..0cfc82c1 100644 --- a/src/Makefile +++ b/src/Makefile @@ -342,9 +342,6 @@ endif INCLUDE_PATHS = -I. -Iexternal/glfw/include ifeq ($(PLATFORM),PLATFORM_DESKTOP) - ifeq ($(PLATFORM_OS),WINDOWS) - INCLUDE_PATHS += -Iexternal - endif ifeq ($(PLATFORM_OS),BSD) INCLUDE_PATHS += -I/usr/local/include LDFLAGS += -L. -Lsrc -L/usr/local/lib -L$(RAYLIB_RELEASE_PATH) diff --git a/src/core.c b/src/core.c index 41aa181b..91022b11 100644 --- a/src/core.c +++ b/src/core.c @@ -125,7 +125,7 @@ #include // Required for: tolower() [Used in IsFileExtension()] #include // Required for stat() [Used in GetLastWriteTime()] -#if defined(_WIN32) && defined(_MSC_VER) +#if defined(PLATFORM_DESKTOP) && defined(_WIN32) && defined(_MSC_VER) #include "external/dirent.h" // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] #else #include // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] -- cgit v1.2.3 From e07ec6a2e8facaa6dd4d9229c0e4c8e080e1fcf4 Mon Sep 17 00:00:00 2001 From: Berni8k Date: Sun, 21 Oct 2018 00:09:17 +0100 Subject: Overhaul mouse and touch for RaspberryPi \n\nNow all '/dev/input/event*' devices are now used for input. No longer uses '/dev/input/mouse*', keyboard and gamepad continue to use existing method\nMultitouch is now supported on RPi with 10 point multitouch\nFixed bugs with IsMouseButtonPressed(Used to constantly fire when holding button) and GetMouseWheelMove(Did not work)\n Fixed exesive CPU usage of GamepadThread --- src/core.c | 492 ++++++++++++++++++++++++++++++++++++++++++----------------- src/raylib.h | 2 +- 2 files changed, 349 insertions(+), 145 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 91022b11..cb6c7e41 100644 --- a/src/core.c +++ b/src/core.c @@ -189,6 +189,7 @@ #include // POSIX standard function definitions - read(), close(), STDIN_FILENO #include // POSIX terminal control definitions - tcgetattr(), tcsetattr() #include // POSIX threads management (mouse input) + #include // POSIX directory browsing #include // UNIX System call for device-specific input/output operations - ioctl() #include // Linux: KDSKBMODE, K_MEDIUMRAM constants definition @@ -223,9 +224,8 @@ #if defined(PLATFORM_RPI) // Old device inputs system #define DEFAULT_KEYBOARD_DEV STDIN_FILENO // Standard input - #define DEFAULT_MOUSE_DEV "/dev/input/mouse0" // Mouse input - #define DEFAULT_TOUCH_DEV "/dev/input/event4" // Touch input virtual device (created by ts_uinput) #define DEFAULT_GAMEPAD_DEV "/dev/input/js" // Gamepad input (base dev for all gamepads: js0, js1, ...) + #define DEFAULT_EVDEV_PATH "/dev/input/" // Path to the linux input events // New device input events (evdev) (must be detected) //#define DEFAULT_KEYBOARD_DEV "/dev/input/eventN" @@ -329,11 +329,22 @@ static int currentMouseWheelY = 0; // Registers current mouse wheel #if defined(PLATFORM_RPI) static int mouseStream = -1; // Mouse device file descriptor -static bool mouseReady = false; // Flag to know if mouse is ready -static pthread_t mouseThreadId; // Mouse reading thread id -static int touchStream = -1; // Touch device file descriptor -static bool touchReady = false; // Flag to know if touch interface is ready -static pthread_t touchThreadId; // Touch reading thread id +static char currentMouseStateEvdev[3] = { 0 }; // Holds the new mouse state for the next polling event to grab (Can't be written directly due to multithreading, app could miss the update) +typedef struct { + pthread_t threadId; // Event reading thread id + int fd; // File descriptor to the device it is assigned to + float sensitivity; // Sensitivitzy multiplier for relative mouse movements + Rectangle absRange; // Range of values for absolute pointing devices (touchscreens) + int touchSlot; // Hold the touch slot number of the currently being sent multitouch block + bool isMouse; // True if device supports relative X Y movements + bool isTouch; // True if device supports absolute X Y movements and has BTN_TOUCH + bool isMultitouch; // True if device supports multiple absolute movevents and has BTN_TOUCH + bool isKeyboard; // True if device has letter keycodes + bool isGamepad; // True if device has gamepad buttons +}InputEventWorker; + +static InputEventWorker eventWorkers[10]; // List of worker threads for every monitored "/dev/input/event" + #endif #if defined(PLATFORM_WEB) static bool toggleCursorLock = false; // Ask for cursor pointer lock on next click @@ -447,9 +458,8 @@ static void InitKeyboard(void); // Init raw keyboard sys static void ProcessKeyboard(void); // Process keyboard events static void RestoreKeyboard(void); // Restore keyboard system static void InitMouse(void); // Mouse initialization (including mouse thread) -static void *MouseThread(void *arg); // Mouse reading thread -static void InitTouch(void); // Touch device initialization (including touch thread) -static void *TouchThread(void *arg); // Touch device reading thread +static void EventThreadSpawn(char* device); // Indetifies a input device and spawns a thread to handle it if needed +static void *EventThread(void *arg); // Input device event reading thread static void InitGamepad(void); // Init raw gamepad input static void *GamepadThread(void *arg); // Mouse reading thread #endif @@ -566,7 +576,6 @@ void InitWindow(int width, int height, const char *title) #if defined(PLATFORM_RPI) // Init raw input system InitMouse(); // Mouse init - InitTouch(); // Touch init InitKeyboard(); // Keyboard init InitGamepad(); // Gamepad init #endif @@ -661,8 +670,13 @@ void CloseWindow(void) windowShouldClose = true; // Added to force threads to exit when the close window is called - pthread_join(mouseThreadId, NULL); - pthread_join(touchThreadId, NULL); + for (int i = 0; i < sizeof(eventWorkers)/sizeof(InputEventWorker); ++i) + { + if(eventWorkers[i].threadId == 0) + { + pthread_join(eventWorkers[i].threadId, NULL); + } + } pthread_join(gamepadThreadId, NULL); #endif @@ -1984,7 +1998,7 @@ bool IsMouseButtonPressed(int button) #else if ((currentMouseState[button] != previousMouseState[button]) && (currentMouseState[button] == 1)) pressed = true; #endif - + return pressed; } @@ -2128,7 +2142,9 @@ Vector2 GetTouchPosition(int index) position.x = position.x*((float)renderWidth/(float)displayWidth) - renderOffsetX/2; position.y = position.y*((float)renderHeight/(float)displayHeight) - renderOffsetY/2; } -#else // PLATFORM_DESKTOP, PLATFORM_RPI +#elif defined(PLATFORM_RPI) + position = touchPosition[index]; +#else // PLATFORM_DESKTOP if (index == 0) position = GetMousePosition(); #endif @@ -2895,6 +2911,21 @@ static void PollInputEvents(void) gamepadAxisCount = 0; #endif +#if defined(PLATFORM_RPI) + // Register previous keys states + for (int i = 0; i < 512; i++) previousKeyState[i] = currentKeyState[i]; + + // Register previous mouse states + previousMouseWheelY = currentMouseWheelY; + currentMouseWheelY = 0; + for (int i = 0; i < 3; i++) + { + previousMouseState[i] = currentMouseState[i]; + currentMouseState[i] = currentMouseStateEvdev[i]; + } + +#endif + #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) // Mouse input polling double mouseX; @@ -3829,182 +3860,351 @@ static void RestoreKeyboard(void) // Mouse initialization (including mouse thread) static void InitMouse(void) { - // NOTE: We can use /dev/input/mice to read from all available mice - if ((mouseStream = open(DEFAULT_MOUSE_DEV, O_RDONLY|O_NONBLOCK)) < 0) + char Path[256]; + DIR *d; + struct dirent *dir; + + // Reset variables + for (int i = 0; i < MAX_TOUCH_POINTS; ++i) + { + touchPosition[i].x = -1; + touchPosition[i].y = -1; + } + + // Open the linux directory of "/dev/input" + d = opendir(DEFAULT_EVDEV_PATH); + if (d) { - TraceLog(LOG_WARNING, "Mouse device could not be opened, no mouse available"); + while ((dir = readdir(d)) != NULL) + { + if(strncmp("event", dir->d_name, strlen("event")) == 0) // Search for devices named "event*" + { + sprintf(Path, "%s%s", DEFAULT_EVDEV_PATH, dir->d_name); + EventThreadSpawn(Path); // Identify the device and spawn a thread for it + } + } + closedir(d); } else { - mouseReady = true; - - int error = pthread_create(&mouseThreadId, NULL, &MouseThread, NULL); - - if (error != 0) TraceLog(LOG_WARNING, "Error creating mouse input event thread"); - else TraceLog(LOG_INFO, "Mouse device initialized successfully"); + TraceLog(LOG_WARNING, "Unable to open linux event directory %s", DEFAULT_EVDEV_PATH); } } -// Mouse reading thread -// NOTE: We need a separate thread to avoid loosing mouse events, -// if too much time passes between reads, queue gets full and new events override older ones... -static void *MouseThread(void *arg) -{ - const unsigned char XSIGN = (1 << 4); - const unsigned char YSIGN = (1 << 5); - - typedef struct { - char buttons; - char dx, dy; - } MouseEvent; - - MouseEvent mouse; +static void EventThreadSpawn(char* device) +{ + #define BITS_PER_LONG (sizeof(long) * 8) + #define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1) + #define OFF(x) ((x)%BITS_PER_LONG) + #define BIT(x) (1UL<> OFF(bit)) & 1) + struct input_absinfo absinfo; + unsigned long ev_bits[NBITS(EV_MAX)]; + unsigned long abs_bits[NBITS(ABS_MAX)]; + unsigned long rel_bits[NBITS(REL_MAX)]; + unsigned long key_bits[NBITS(KEY_MAX)]; + bool hasAbs = false; + bool hasRel = false; + bool hasAbsMulti = false; + int FreeWorkerId = -1; + int fd = -1; + InputEventWorker* Worker; + + /////////////////////////////////// Open the device and allocate worker ///////////////////////////////////////////// + + // Find a free spot in the workers array + for (int i = 0; i < sizeof(eventWorkers)/sizeof(InputEventWorker); ++i) + { + if(eventWorkers[i].threadId == 0) + { + FreeWorkerId = i; + break; + } + } - int mouseRelX = 0; - int mouseRelY = 0; + // Select the free worker from array + if(FreeWorkerId >= 0) + { + Worker = &(eventWorkers[FreeWorkerId]); // Grab a pointer to the worker + memset(Worker, 0, sizeof(InputEventWorker)); // Clear the worker + } + else + { + TraceLog(LOG_WARNING, "Error creating input device thread for '%s': Out of worker slots", device); + return; + } - while (!windowShouldClose) + // Open the device + fd = open(device, O_RDONLY | O_NONBLOCK); + if(fd < 0) { - if (read(mouseStream, &mouse, sizeof(MouseEvent)) == (int)sizeof(MouseEvent)) - { - if ((mouse.buttons & 0x08) == 0) break; // This bit should always be set + TraceLog(LOG_WARNING, "Error creating input device thread for '%s': Can't open device (Err: %d)", device, Worker->fd); + return; + } + Worker->fd = fd; - // Check Left button pressed - if ((mouse.buttons & 0x01) > 0) currentMouseState[0] = 1; - else currentMouseState[0] = 0; + // At this point we have a connection to the device, + // but we don't yet know what the device is (Could be + // many things, even as simple as a power button) - // Check Right button pressed - if ((mouse.buttons & 0x02) > 0) currentMouseState[1] = 1; - else currentMouseState[1] = 0; + /////////////////////////////////// Identify the device ///////////////////////////////////////////// - // Check Middle button pressed - if ((mouse.buttons & 0x04) > 0) currentMouseState[2] = 1; - else currentMouseState[2] = 0; + ioctl(fd, EVIOCGBIT(0, sizeof(ev_bits)), ev_bits); // Read a bitfield of the avalable device properties + + // Check for absolute input devices + if (TEST_BIT(ev_bits, EV_ABS)) + { + ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(abs_bits)),abs_bits); - mouseRelX = (int)mouse.dx; - mouseRelY = (int)mouse.dy; + // Check for absolute movement support (usualy touchscreens, but also joysticks) + if (TEST_BIT(abs_bits, ABS_X) && TEST_BIT(abs_bits, ABS_Y)) + { + hasAbs = true; + // Get the scaling values + ioctl(fd, EVIOCGABS(ABS_X), &absinfo); + Worker->absRange.x = absinfo.minimum; + Worker->absRange.width = absinfo.maximum - absinfo.minimum; + ioctl(fd, EVIOCGABS(ABS_Y), &absinfo); + Worker->absRange.y = absinfo.minimum; + Worker->absRange.height = absinfo.maximum - absinfo.minimum; + } + + // Check for multiple absolute movement support (usualy multitouch touchscreens) + if (TEST_BIT(abs_bits, ABS_MT_POSITION_X) && TEST_BIT(abs_bits, ABS_MT_POSITION_Y)) + { + hasAbsMulti = true; + // Get the scaling values + ioctl(fd, EVIOCGABS(ABS_X), &absinfo); + Worker->absRange.x = absinfo.minimum; + Worker->absRange.width = absinfo.maximum - absinfo.minimum; + ioctl(fd, EVIOCGABS(ABS_Y), &absinfo); + Worker->absRange.y = absinfo.minimum; + Worker->absRange.height = absinfo.maximum - absinfo.minimum; + } + } - if ((mouse.buttons & XSIGN) > 0) mouseRelX = -1*(255 - mouseRelX); - if ((mouse.buttons & YSIGN) > 0) mouseRelY = -1*(255 - mouseRelY); + // Check for relative movement support (usualy mouse) + if (TEST_BIT(ev_bits, EV_REL)) + { + ioctl(fd, EVIOCGBIT(EV_REL, sizeof(rel_bits)),rel_bits); + if (TEST_BIT(rel_bits, REL_X) && TEST_BIT(rel_bits, REL_Y)) + { + hasRel = true; + } + } - // NOTE: Mouse movement is normalized to not be screen resolution dependant - // We suppose 2*255 (max relative movement) is equivalent to screenWidth (max pixels width) - // Result after normalization is multiplied by MOUSE_SENSITIVITY factor + // Check for button support to determine the device type(usualy on all input devices) + if (TEST_BIT(ev_bits, EV_KEY)) + { + ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(key_bits)),key_bits); - mousePosition.x += (float)mouseRelX*((float)screenWidth/(2*255))*MOUSE_SENSITIVITY; - mousePosition.y -= (float)mouseRelY*((float)screenHeight/(2*255))*MOUSE_SENSITIVITY; + if(hasAbs || hasAbsMulti) + { + if(TEST_BIT(key_bits, BTN_TOUCH)) + Worker->isTouch = true; // This is a touchscreen + if(TEST_BIT(key_bits, BTN_TOOL_FINGER)) + Worker->isTouch = true; // This is a drawing tablet + if(TEST_BIT(key_bits, BTN_TOOL_PEN)) + Worker->isTouch = true; // This is a drawing tablet + if(TEST_BIT(key_bits, BTN_STYLUS)) + Worker->isTouch = true; // This is a drawing tablet + if(Worker->isTouch || hasAbsMulti) + Worker->isMultitouch = true; // This is a multitouch capable device + } - if (mousePosition.x < 0) mousePosition.x = 0; - if (mousePosition.y < 0) mousePosition.y = 0; + if(hasRel) + { + if (TEST_BIT(key_bits, BTN_LEFT)) + Worker->isMouse = true; // This is a mouse + if (TEST_BIT(key_bits, BTN_RIGHT)) + Worker->isMouse = true; // This is a mouse + } - if (mousePosition.x > screenWidth) mousePosition.x = screenWidth; - if (mousePosition.y > screenHeight) mousePosition.y = screenHeight; - } - //else read(mouseStream, &mouse, 1); // Try to sync up again + if (TEST_BIT(key_bits, BTN_A)) + Worker->isGamepad = true; // This is a gamepad + if (TEST_BIT(key_bits, BTN_TRIGGER)) + Worker->isGamepad = true; // This is a gamepad + if (TEST_BIT(key_bits, BTN_START)) + Worker->isGamepad = true; // This is a gamepad + if (TEST_BIT(key_bits, BTN_TL)) + Worker->isGamepad = true; // This is a gamepad + if (TEST_BIT(key_bits, BTN_TL)) + Worker->isGamepad = true; // This is a gamepad + + if (TEST_BIT(key_bits, KEY_SPACE)) + Worker->isKeyboard = true; // This is a keyboard } - return NULL; -} -// Touch initialization (including touch thread) -static void InitTouch(void) -{ - if ((touchStream = open(DEFAULT_TOUCH_DEV, O_RDONLY|O_NONBLOCK)) < 0) + /////////////////////////////////// Decide what to do with the device ///////////////////////////////////////////// + if(Worker->isTouch || Worker->isMouse) { - TraceLog(LOG_WARNING, "Touch device could not be opened, no touchscreen available"); + // Looks like a interesting device + TraceLog(LOG_INFO, "Opening input device '%s' (%s%s%s%s%s)", device, + Worker->isMouse ? "mouse " : "", + Worker->isMultitouch ? "multitouch " : "", + Worker->isTouch ? "touchscreen " : "", + Worker->isGamepad ? "gamepad " : "", + Worker->isKeyboard ? "keyboard " : "" + ); + // Create a thread for this device + int error = pthread_create(&Worker->threadId, NULL, &EventThread, (void*)Worker); + if(error != 0) + { + TraceLog(LOG_WARNING, "Error creating input device thread for '%s': Can't create thread (Err: %d)", device, error); + Worker->threadId = 0; + close(fd); + } } else { - touchReady = true; - - int error = pthread_create(&touchThreadId, NULL, &TouchThread, NULL); - - if (error != 0) TraceLog(LOG_WARNING, "Error creating touch input event thread"); - else TraceLog(LOG_INFO, "Touch device initialized successfully"); + // We are not interested in this device + close(fd); } } -// Touch reading thread. -// This reads from a Virtual Input Event /dev/input/event4 which is -// created by the ts_uinput daemon. This takes, filters and scales -// raw input from the Touchscreen (which appears in /dev/input/event3) -// based on the Calibration data referenced by tslib. -static void *TouchThread(void *arg) +static void *EventThread(void *arg) { struct input_event ev; GestureEvent gestureEvent; + InputEventWorker* Worker = (InputEventWorker*)arg; + bool GestureNeedsUpdate = false; while (!windowShouldClose) { - if (read(touchStream, &ev, sizeof(ev)) == (int)sizeof(ev)) + if (read(Worker->fd, &ev, sizeof(ev)) == (int)sizeof(ev)) { - // if pressure > 0 then simulate left mouse button click - if (ev.type == EV_ABS && ev.code == 24 && ev.value == 0 && currentMouseState[0] == 1) + /////////////////////////////// Relative movement parsing //////////////////////////////////// + if(ev.type == EV_REL) { - currentMouseState[0] = 0; - gestureEvent.touchAction = TOUCH_UP; - gestureEvent.pointCount = 1; - gestureEvent.pointerId[0] = 0; - gestureEvent.pointerId[1] = 1; - gestureEvent.position[0] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[1] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[0].x /= (float)GetScreenWidth(); - gestureEvent.position[0].y /= (float)GetScreenHeight(); - gestureEvent.position[1].x /= (float)GetScreenWidth(); - gestureEvent.position[1].y /= (float)GetScreenHeight(); - ProcessGestureEvent(gestureEvent); + if(ev.code == REL_X) + { + mousePosition.x += ev.value; + touchPosition[0].x = mousePosition.x; + gestureEvent.touchAction = TOUCH_MOVE; + GestureNeedsUpdate = true; + } + + if(ev.code == REL_Y) + { + mousePosition.y += ev.value; + touchPosition[0].y = mousePosition.y; + gestureEvent.touchAction = TOUCH_MOVE; + GestureNeedsUpdate = true; + } + + if(ev.code == REL_WHEEL) + { + currentMouseWheelY += ev.value; + } } - if (ev.type == EV_ABS && ev.code == 24 && ev.value > 0 && currentMouseState[0] == 0) + + /////////////////////////////// Absolute movement parsing //////////////////////////////////// + if(ev.type == EV_ABS) { - currentMouseState[0] = 1; - gestureEvent.touchAction = TOUCH_DOWN; - gestureEvent.pointCount = 1; - gestureEvent.pointerId[0] = 0; - gestureEvent.pointerId[1] = 1; - gestureEvent.position[0] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[1] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[0].x /= (float)GetScreenWidth(); - gestureEvent.position[0].y /= (float)GetScreenHeight(); - gestureEvent.position[1].x /= (float)GetScreenWidth(); - gestureEvent.position[1].y /= (float)GetScreenHeight(); - ProcessGestureEvent(gestureEvent); + // Basic movement + if(ev.code == ABS_X) + { + mousePosition.x = (ev.value - Worker->absRange.x) * screenWidth / Worker->absRange.width; //Scale acording to absRange + gestureEvent.touchAction = TOUCH_MOVE; + GestureNeedsUpdate = true; + } + + if(ev.code == ABS_Y) + { + mousePosition.y = (ev.value - Worker->absRange.y) * screenHeight / Worker->absRange.height; //Scale acording to absRange + gestureEvent.touchAction = TOUCH_MOVE; + GestureNeedsUpdate = true; + } + + //Multitouch movement + if(ev.code == ABS_MT_SLOT) + { + Worker->touchSlot = ev.value; //Remeber the slot number for the folowing events + } + + if(ev.code == ABS_MT_POSITION_X) + { + if(Worker->touchSlot < MAX_TOUCH_POINTS) + touchPosition[Worker->touchSlot].x = (ev.value - Worker->absRange.x) * screenWidth / Worker->absRange.width; //Scale acording to absRange + } + + if(ev.code == ABS_MT_POSITION_Y) + { + if(Worker->touchSlot < MAX_TOUCH_POINTS) + touchPosition[Worker->touchSlot].y = (ev.value - Worker->absRange.y) * screenHeight / Worker->absRange.height; //Scale acording to absRange + } + + if(ev.code == ABS_MT_TRACKING_ID) + { + if( (ev.value < 0) && (Worker->touchSlot < MAX_TOUCH_POINTS) ) + { + //Touch has ended for this point + touchPosition[Worker->touchSlot].x = -1; + touchPosition[Worker->touchSlot].y = -1; + } + } } - // x & y values supplied by event4 have been scaled & de-jittered using tslib calibration data - if (ev.type == EV_ABS && ev.code == 0) + + /////////////////////////////// Button parsing //////////////////////////////////// + if(ev.type == EV_KEY) { - mousePosition.x = ev.value; - if (mousePosition.x < 0) mousePosition.x = 0; - if (mousePosition.x > screenWidth) mousePosition.x = screenWidth; - gestureEvent.touchAction = TOUCH_MOVE; - gestureEvent.pointCount = 1; - gestureEvent.pointerId[0] = 0; - gestureEvent.pointerId[1] = 1; - gestureEvent.position[0] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[1] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[0].x /= (float)GetScreenWidth(); - gestureEvent.position[0].y /= (float)GetScreenHeight(); - gestureEvent.position[1].x /= (float)GetScreenWidth(); - gestureEvent.position[1].y /= (float)GetScreenHeight(); - ProcessGestureEvent(gestureEvent); + if((ev.code == BTN_TOUCH) || (ev.code == BTN_LEFT)) + { + currentMouseStateEvdev[MOUSE_LEFT_BUTTON] = ev.value; + if(ev.value > 0) + gestureEvent.touchAction = TOUCH_DOWN; + else + gestureEvent.touchAction = TOUCH_UP; + GestureNeedsUpdate = true; + } + + if(ev.code == BTN_RIGHT) + { + currentMouseStateEvdev[MOUSE_RIGHT_BUTTON] = ev.value; + } + + if(ev.code == BTN_MIDDLE) + { + currentMouseStateEvdev[MOUSE_MIDDLE_BUTTON] = ev.value; + } + } - if (ev.type == EV_ABS && ev.code == 1) + + /////////////////////////////// Screen confinement //////////////////////////////////// + if(mousePosition.x < 0) + mousePosition.x = 0; + if(mousePosition.x > screenWidth / mouseScale) + mousePosition.x = screenWidth / mouseScale; + + if(mousePosition.y < 0) + mousePosition.y = 0; + if(mousePosition.y > screenHeight / mouseScale) + mousePosition.y = screenHeight / mouseScale; + + /////////////////////////////// Gesture update //////////////////////////////////// + if(GestureNeedsUpdate) { - mousePosition.y = ev.value; - if (mousePosition.y < 0) mousePosition.y = 0; - if (mousePosition.y > screenHeight) mousePosition.y = screenHeight; - gestureEvent.touchAction = TOUCH_MOVE; - gestureEvent.pointCount = 1; + gestureEvent.pointCount = 0; + if(touchPosition[0].x >= 0) gestureEvent.pointCount++; + if(touchPosition[1].x >= 0) gestureEvent.pointCount++; + if(touchPosition[2].x >= 0) gestureEvent.pointCount++; + if(touchPosition[3].x >= 0) gestureEvent.pointCount++; gestureEvent.pointerId[0] = 0; gestureEvent.pointerId[1] = 1; - gestureEvent.position[0] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[1] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[0].x /= (float)GetScreenWidth(); - gestureEvent.position[0].y /= (float)GetScreenHeight(); - gestureEvent.position[1].x /= (float)GetScreenWidth(); - gestureEvent.position[1].y /= (float)GetScreenHeight(); + gestureEvent.pointerId[2] = 2; + gestureEvent.pointerId[3] = 3; + gestureEvent.position[0] = touchPosition[0]; + gestureEvent.position[1] = touchPosition[1]; + gestureEvent.position[2] = touchPosition[2]; + gestureEvent.position[3] = touchPosition[3]; ProcessGestureEvent(gestureEvent); } - + } + else + { + usleep(5000); //Sleep for 5ms to avoid hogging CPU time } } return NULL; @@ -4090,6 +4290,10 @@ static void *GamepadThread(void *arg) } } } + else + { + usleep(1000); //Sleep for 1ms to avoid hogging CPU time + } } } diff --git a/src/raylib.h b/src/raylib.h index aa5bd16f..8256b745 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -223,7 +223,7 @@ #define MOUSE_MIDDLE_BUTTON 2 // Touch points registered -#define MAX_TOUCH_POINTS 2 +#define MAX_TOUCH_POINTS 10 // Gamepad Number #define GAMEPAD_PLAYER1 0 -- cgit v1.2.3 From 3d825eb973096a1b1271374d02f3cbfa7200ee28 Mon Sep 17 00:00:00 2001 From: Berni8k Date: Sun, 21 Oct 2018 15:06:40 +0100 Subject: Added RaspberryPi option to ignore duplicate touchscreens (On by default) --- src/core.c | 41 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index cb6c7e41..cc292012 100644 --- a/src/core.c +++ b/src/core.c @@ -226,6 +226,7 @@ #define DEFAULT_KEYBOARD_DEV STDIN_FILENO // Standard input #define DEFAULT_GAMEPAD_DEV "/dev/input/js" // Gamepad input (base dev for all gamepads: js0, js1, ...) #define DEFAULT_EVDEV_PATH "/dev/input/" // Path to the linux input events + #define USE_LAST_TOUCH_DEVICE true // If true: When multiple touchscreens are connected then only use the one with the highest event number // New device input events (evdev) (must be detected) //#define DEFAULT_KEYBOARD_DEV "/dev/input/eventN" @@ -328,12 +329,11 @@ static int currentMouseWheelY = 0; // Registers current mouse wheel #endif #if defined(PLATFORM_RPI) -static int mouseStream = -1; // Mouse device file descriptor static char currentMouseStateEvdev[3] = { 0 }; // Holds the new mouse state for the next polling event to grab (Can't be written directly due to multithreading, app could miss the update) typedef struct { pthread_t threadId; // Event reading thread id int fd; // File descriptor to the device it is assigned to - float sensitivity; // Sensitivitzy multiplier for relative mouse movements + int eventNum; // Number of 'event' device Rectangle absRange; // Range of values for absolute pointing devices (touchscreens) int touchSlot; // Hold the touch slot number of the currently being sent multitouch block bool isMouse; // True if device supports relative X Y movements @@ -3944,6 +3944,16 @@ static void EventThreadSpawn(char* device) } Worker->fd = fd; + //Grab number on the end of the devices name "event" + int DevNum; + char* ptrDevName = strrchr(device, 't'); + Worker->eventNum = -1; + if(ptrDevName != NULL) + { + if(sscanf(ptrDevName, "t%d", &DevNum) == 1) + Worker->eventNum = DevNum; + } + // At this point we have a connection to the device, // but we don't yet know what the device is (Could be // many things, even as simple as a power button) @@ -4048,6 +4058,7 @@ static void EventThreadSpawn(char* device) Worker->isGamepad ? "gamepad " : "", Worker->isKeyboard ? "keyboard " : "" ); + // Create a thread for this device int error = pthread_create(&Worker->threadId, NULL, &EventThread, (void*)Worker); if(error != 0) @@ -4056,6 +4067,31 @@ static void EventThreadSpawn(char* device) Worker->threadId = 0; close(fd); } + + // Kill off duplicate touchscreens if needed + if(USE_LAST_TOUCH_DEVICE) + { + // Find touchscreen with the highest index + int MaxTouchNumber = -1; + for (int i = 0; i < sizeof(eventWorkers)/sizeof(InputEventWorker); ++i) + { + if(eventWorkers[i].isTouch && (eventWorkers[i].eventNum > MaxTouchNumber)) + MaxTouchNumber = eventWorkers[i].eventNum; + } + // Find toucnscreens with lower indexes + for (int i = 0; i < sizeof(eventWorkers)/sizeof(InputEventWorker); ++i) + { + if(eventWorkers[i].isTouch && (eventWorkers[i].eventNum < MaxTouchNumber)) + { + if(eventWorkers[i].threadId != 0) + { + TraceLog(LOG_WARNING, "Duplicate touchscreen found, killing toucnscreen on event%d", i); + pthread_cancel(eventWorkers[i].threadId); + close(eventWorkers[i].fd); + } + } + } + } } else { @@ -4207,6 +4243,7 @@ static void *EventThread(void *arg) usleep(5000); //Sleep for 5ms to avoid hogging CPU time } } + close(Worker->fd); return NULL; } -- cgit v1.2.3 From b5bcf2c934a6b0c6b3e8bc9766abc658905fd694 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 22 Oct 2018 11:48:16 +0200 Subject: Review code formatting for RPI inputs --- src/core.c | 353 ++++++++++++++++++++++++++++--------------------------------- 1 file changed, 164 insertions(+), 189 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index cc292012..a0e53c87 100644 --- a/src/core.c +++ b/src/core.c @@ -222,11 +222,12 @@ // Defines and Macros //---------------------------------------------------------------------------------- #if defined(PLATFORM_RPI) + #define USE_LAST_TOUCH_DEVICE // When multiple touchscreens are connected, only use the one with the highest event number + // Old device inputs system #define DEFAULT_KEYBOARD_DEV STDIN_FILENO // Standard input #define DEFAULT_GAMEPAD_DEV "/dev/input/js" // Gamepad input (base dev for all gamepads: js0, js1, ...) #define DEFAULT_EVDEV_PATH "/dev/input/" // Path to the linux input events - #define USE_LAST_TOUCH_DEVICE true // If true: When multiple touchscreens are connected then only use the one with the highest event number // New device input events (evdev) (must be detected) //#define DEFAULT_KEYBOARD_DEV "/dev/input/eventN" @@ -458,7 +459,7 @@ static void InitKeyboard(void); // Init raw keyboard sys static void ProcessKeyboard(void); // Process keyboard events static void RestoreKeyboard(void); // Restore keyboard system static void InitMouse(void); // Mouse initialization (including mouse thread) -static void EventThreadSpawn(char* device); // Indetifies a input device and spawns a thread to handle it if needed +static void EventThreadSpawn(char *device); // Indetifies a input device and spawns a thread to handle it if needed static void *EventThread(void *arg); // Input device event reading thread static void InitGamepad(void); // Init raw gamepad input static void *GamepadThread(void *arg); // Mouse reading thread @@ -672,7 +673,7 @@ void CloseWindow(void) for (int i = 0; i < sizeof(eventWorkers)/sizeof(InputEventWorker); ++i) { - if(eventWorkers[i].threadId == 0) + if (eventWorkers[i].threadId == 0) { pthread_join(eventWorkers[i].threadId, NULL); } @@ -785,7 +786,7 @@ void SetWindowMonitor(int monitor) { #if defined(PLATFORM_DESKTOP) int monitorCount; - GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); + GLFWmonitor **monitors = glfwGetMonitors(&monitorCount); if ((monitor >= 0) && (monitor < monitorCount)) { @@ -862,7 +863,7 @@ int GetMonitorWidth(int monitor) { #if defined(PLATFORM_DESKTOP) int monitorCount; - GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); + GLFWmonitor **monitors = glfwGetMonitors(&monitorCount); if ((monitor >= 0) && (monitor < monitorCount)) { @@ -879,7 +880,7 @@ int GetMonitorHeight(int monitor) { #if defined(PLATFORM_DESKTOP) int monitorCount; - GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); + GLFWmonitor **monitors = glfwGetMonitors(&monitorCount); if ((monitor >= 0) && (monitor < monitorCount)) { @@ -896,7 +897,7 @@ int GetMonitorPhysicalWidth(int monitor) { #if defined(PLATFORM_DESKTOP) int monitorCount; - GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); + GLFWmonitor **monitors = glfwGetMonitors(&monitorCount); if ((monitor >= 0) && (monitor < monitorCount)) { @@ -914,7 +915,7 @@ int GetMonitorPhysicalHeight(int monitor) { #if defined(PLATFORM_DESKTOP) int monitorCount; - GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); + GLFWmonitor **monitors = glfwGetMonitors(&monitorCount); if ((monitor >= 0) && (monitor < monitorCount)) { @@ -932,7 +933,7 @@ const char *GetMonitorName(int monitor) { #if defined(PLATFORM_DESKTOP) int monitorCount; - GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); + GLFWmonitor **monitors = glfwGetMonitors(&monitorCount); if ((monitor >= 0) && (monitor < monitorCount)) { @@ -3268,7 +3269,7 @@ static void WindowSizeCallback(GLFWwindow *window, int width, int height) } // GLFW3 WindowIconify Callback, runs when window is minimized/restored -static void WindowIconifyCallback(GLFWwindow* window, int iconified) +static void WindowIconifyCallback(GLFWwindow *window, int iconified) { if (iconified) windowMinimized = true; // The window was iconified else windowMinimized = false; // The window was restored @@ -3861,8 +3862,8 @@ static void RestoreKeyboard(void) static void InitMouse(void) { char Path[256]; - DIR *d; - struct dirent *dir; + DIR *directory; + struct dirent *entity; // Reset variables for (int i = 0; i < MAX_TOUCH_POINTS; ++i) @@ -3872,18 +3873,19 @@ static void InitMouse(void) } // Open the linux directory of "/dev/input" - d = opendir(DEFAULT_EVDEV_PATH); - if (d) + directory = opendir(DEFAULT_EVDEV_PATH); + if (directory) { - while ((dir = readdir(d)) != NULL) + while ((entity = readdir(directory)) != NULL) { - if(strncmp("event", dir->d_name, strlen("event")) == 0) // Search for devices named "event*" + if (strncmp("event", entity->d_name, strlen("event")) == 0) // Search for devices named "event*" { - sprintf(Path, "%s%s", DEFAULT_EVDEV_PATH, dir->d_name); - EventThreadSpawn(Path); // Identify the device and spawn a thread for it + sprintf(Path, "%s%s", DEFAULT_EVDEV_PATH, entity->d_name); + EventThreadSpawn(Path); // Identify the device and spawn a thread for it } } - closedir(d); + + closedir(directory); } else { @@ -3891,43 +3893,45 @@ static void InitMouse(void) } } -static void EventThreadSpawn(char* device) +static void EventThreadSpawn(char *device) { - #define BITS_PER_LONG (sizeof(long) * 8) - #define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1) - #define OFF(x) ((x)%BITS_PER_LONG) - #define BIT(x) (1UL<> OFF(bit)) & 1) + struct input_absinfo absinfo; - unsigned long ev_bits[NBITS(EV_MAX)]; - unsigned long abs_bits[NBITS(ABS_MAX)]; - unsigned long rel_bits[NBITS(REL_MAX)]; - unsigned long key_bits[NBITS(KEY_MAX)]; + unsigned long evBits[NBITS(EV_MAX)]; + unsigned long absBits[NBITS(ABS_MAX)]; + unsigned long relBits[NBITS(REL_MAX)]; + unsigned long keyBits[NBITS(KEY_MAX)]; bool hasAbs = false; bool hasRel = false; bool hasAbsMulti = false; - int FreeWorkerId = -1; + int freeWorkerId = -1; int fd = -1; - InputEventWorker* Worker; + + InputEventWorker *worker; /////////////////////////////////// Open the device and allocate worker ///////////////////////////////////////////// // Find a free spot in the workers array for (int i = 0; i < sizeof(eventWorkers)/sizeof(InputEventWorker); ++i) { - if(eventWorkers[i].threadId == 0) + if (eventWorkers[i].threadId == 0) { - FreeWorkerId = i; + freeWorkerId = i; break; } } // Select the free worker from array - if(FreeWorkerId >= 0) + if (freeWorkerId >= 0) { - Worker = &(eventWorkers[FreeWorkerId]); // Grab a pointer to the worker - memset(Worker, 0, sizeof(InputEventWorker)); // Clear the worker + worker = &(eventWorkers[freeWorkerId]); // Grab a pointer to the worker + memset(worker, 0, sizeof(InputEventWorker)); // Clear the worker } else { @@ -3937,296 +3941,265 @@ static void EventThreadSpawn(char* device) // Open the device fd = open(device, O_RDONLY | O_NONBLOCK); - if(fd < 0) + if (fd < 0) { - TraceLog(LOG_WARNING, "Error creating input device thread for '%s': Can't open device (Err: %d)", device, Worker->fd); + TraceLog(LOG_WARNING, "Error creating input device thread for '%s': Can't open device (Err: %d)", device, worker->fd); return; } - Worker->fd = fd; + worker->fd = fd; //Grab number on the end of the devices name "event" - int DevNum; - char* ptrDevName = strrchr(device, 't'); - Worker->eventNum = -1; - if(ptrDevName != NULL) + int devNum = 0; + char *ptrDevName = strrchr(device, 't'); + worker->eventNum = -1; + + if (ptrDevName != NULL) { - if(sscanf(ptrDevName, "t%d", &DevNum) == 1) - Worker->eventNum = DevNum; + if (sscanf(ptrDevName, "t%d", &devNum) == 1) + worker->eventNum = devNum; } // At this point we have a connection to the device, // but we don't yet know what the device is (Could be // many things, even as simple as a power button) - /////////////////////////////////// Identify the device ///////////////////////////////////////////// + /////////////////////////////////// Identify the device ///////////////////////////////////////////// - ioctl(fd, EVIOCGBIT(0, sizeof(ev_bits)), ev_bits); // Read a bitfield of the avalable device properties + ioctl(fd, EVIOCGBIT(0, sizeof(evBits)), evBits); // Read a bitfield of the avalable device properties // Check for absolute input devices - if (TEST_BIT(ev_bits, EV_ABS)) + if (TEST_BIT(evBits, EV_ABS)) { - ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(abs_bits)),abs_bits); + ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absBits)), absBits); // Check for absolute movement support (usualy touchscreens, but also joysticks) - if (TEST_BIT(abs_bits, ABS_X) && TEST_BIT(abs_bits, ABS_Y)) + if (TEST_BIT(absBits, ABS_X) && TEST_BIT(absBits, ABS_Y)) { hasAbs = true; + // Get the scaling values ioctl(fd, EVIOCGABS(ABS_X), &absinfo); - Worker->absRange.x = absinfo.minimum; - Worker->absRange.width = absinfo.maximum - absinfo.minimum; + worker->absRange.x = absinfo.minimum; + worker->absRange.width = absinfo.maximum - absinfo.minimum; ioctl(fd, EVIOCGABS(ABS_Y), &absinfo); - Worker->absRange.y = absinfo.minimum; - Worker->absRange.height = absinfo.maximum - absinfo.minimum; + worker->absRange.y = absinfo.minimum; + worker->absRange.height = absinfo.maximum - absinfo.minimum; } // Check for multiple absolute movement support (usualy multitouch touchscreens) - if (TEST_BIT(abs_bits, ABS_MT_POSITION_X) && TEST_BIT(abs_bits, ABS_MT_POSITION_Y)) + if (TEST_BIT(absBits, ABS_MT_POSITION_X) && TEST_BIT(absBits, ABS_MT_POSITION_Y)) { hasAbsMulti = true; + // Get the scaling values ioctl(fd, EVIOCGABS(ABS_X), &absinfo); - Worker->absRange.x = absinfo.minimum; - Worker->absRange.width = absinfo.maximum - absinfo.minimum; + worker->absRange.x = absinfo.minimum; + worker->absRange.width = absinfo.maximum - absinfo.minimum; ioctl(fd, EVIOCGABS(ABS_Y), &absinfo); - Worker->absRange.y = absinfo.minimum; - Worker->absRange.height = absinfo.maximum - absinfo.minimum; + worker->absRange.y = absinfo.minimum; + worker->absRange.height = absinfo.maximum - absinfo.minimum; } } // Check for relative movement support (usualy mouse) - if (TEST_BIT(ev_bits, EV_REL)) + if (TEST_BIT(evBits, EV_REL)) { - ioctl(fd, EVIOCGBIT(EV_REL, sizeof(rel_bits)),rel_bits); - if (TEST_BIT(rel_bits, REL_X) && TEST_BIT(rel_bits, REL_Y)) - { - hasRel = true; - } + ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relBits)), relBits); + + if (TEST_BIT(relBits, REL_X) && TEST_BIT(relBits, REL_Y)) hasRel = true; } // Check for button support to determine the device type(usualy on all input devices) - if (TEST_BIT(ev_bits, EV_KEY)) + if (TEST_BIT(evBits, EV_KEY)) { - ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(key_bits)),key_bits); + ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keyBits)), keyBits); - if(hasAbs || hasAbsMulti) + if (hasAbs || hasAbsMulti) { - if(TEST_BIT(key_bits, BTN_TOUCH)) - Worker->isTouch = true; // This is a touchscreen - if(TEST_BIT(key_bits, BTN_TOOL_FINGER)) - Worker->isTouch = true; // This is a drawing tablet - if(TEST_BIT(key_bits, BTN_TOOL_PEN)) - Worker->isTouch = true; // This is a drawing tablet - if(TEST_BIT(key_bits, BTN_STYLUS)) - Worker->isTouch = true; // This is a drawing tablet - if(Worker->isTouch || hasAbsMulti) - Worker->isMultitouch = true; // This is a multitouch capable device + if (TEST_BIT(keyBits, BTN_TOUCH)) worker->isTouch = true; // This is a touchscreen + if (TEST_BIT(keyBits, BTN_TOOL_FINGER)) worker->isTouch = true; // This is a drawing tablet + if (TEST_BIT(keyBits, BTN_TOOL_PEN)) worker->isTouch = true; // This is a drawing tablet + if (TEST_BIT(keyBits, BTN_STYLUS)) worker->isTouch = true; // This is a drawing tablet + if (worker->isTouch || hasAbsMulti) worker->isMultitouch = true; // This is a multitouch capable device } - if(hasRel) + if (hasRel) { - if (TEST_BIT(key_bits, BTN_LEFT)) - Worker->isMouse = true; // This is a mouse - if (TEST_BIT(key_bits, BTN_RIGHT)) - Worker->isMouse = true; // This is a mouse + if (TEST_BIT(keyBits, BTN_LEFT)) worker->isMouse = true; // This is a mouse + if (TEST_BIT(keyBits, BTN_RIGHT)) worker->isMouse = true; // This is a mouse } - if (TEST_BIT(key_bits, BTN_A)) - Worker->isGamepad = true; // This is a gamepad - if (TEST_BIT(key_bits, BTN_TRIGGER)) - Worker->isGamepad = true; // This is a gamepad - if (TEST_BIT(key_bits, BTN_START)) - Worker->isGamepad = true; // This is a gamepad - if (TEST_BIT(key_bits, BTN_TL)) - Worker->isGamepad = true; // This is a gamepad - if (TEST_BIT(key_bits, BTN_TL)) - Worker->isGamepad = true; // This is a gamepad - - if (TEST_BIT(key_bits, KEY_SPACE)) - Worker->isKeyboard = true; // This is a keyboard + if (TEST_BIT(keyBits, BTN_A)) worker->isGamepad = true; // This is a gamepad + if (TEST_BIT(keyBits, BTN_TRIGGER)) worker->isGamepad = true; // This is a gamepad + if (TEST_BIT(keyBits, BTN_START)) worker->isGamepad = true; // This is a gamepad + if (TEST_BIT(keyBits, BTN_TL)) worker->isGamepad = true; // This is a gamepad + if (TEST_BIT(keyBits, BTN_TL)) worker->isGamepad = true; // This is a gamepad + + if (TEST_BIT(keyBits, KEY_SPACE)) worker->isKeyboard = true; // This is a keyboard } /////////////////////////////////// Decide what to do with the device ///////////////////////////////////////////// - if(Worker->isTouch || Worker->isMouse) + if (worker->isTouch || worker->isMouse) { // Looks like a interesting device TraceLog(LOG_INFO, "Opening input device '%s' (%s%s%s%s%s)", device, - Worker->isMouse ? "mouse " : "", - Worker->isMultitouch ? "multitouch " : "", - Worker->isTouch ? "touchscreen " : "", - Worker->isGamepad ? "gamepad " : "", - Worker->isKeyboard ? "keyboard " : "" - ); + worker->isMouse ? "mouse " : "", + worker->isMultitouch ? "multitouch " : "", + worker->isTouch ? "touchscreen " : "", + worker->isGamepad ? "gamepad " : "", + worker->isKeyboard ? "keyboard " : ""); // Create a thread for this device - int error = pthread_create(&Worker->threadId, NULL, &EventThread, (void*)Worker); - if(error != 0) + int error = pthread_create(&worker->threadId, NULL, &EventThread, (void *)worker); + if (error != 0) { TraceLog(LOG_WARNING, "Error creating input device thread for '%s': Can't create thread (Err: %d)", device, error); - Worker->threadId = 0; + worker->threadId = 0; close(fd); } - // Kill off duplicate touchscreens if needed - if(USE_LAST_TOUCH_DEVICE) +#if defined(USE_LAST_TOUCH_DEVICE) + // Find touchscreen with the highest index + int maxTouchNumber = -1; + + for (int i = 0; i < sizeof(eventWorkers)/sizeof(InputEventWorker); ++i) { - // Find touchscreen with the highest index - int MaxTouchNumber = -1; - for (int i = 0; i < sizeof(eventWorkers)/sizeof(InputEventWorker); ++i) - { - if(eventWorkers[i].isTouch && (eventWorkers[i].eventNum > MaxTouchNumber)) - MaxTouchNumber = eventWorkers[i].eventNum; - } - // Find toucnscreens with lower indexes - for (int i = 0; i < sizeof(eventWorkers)/sizeof(InputEventWorker); ++i) + if (eventWorkers[i].isTouch && (eventWorkers[i].eventNum > maxTouchNumber)) maxTouchNumber = eventWorkers[i].eventNum; + } + + // Find toucnscreens with lower indexes + for (int i = 0; i < sizeof(eventWorkers)/sizeof(InputEventWorker); ++i) + { + if (eventWorkers[i].isTouch && (eventWorkers[i].eventNum < maxTouchNumber)) { - if(eventWorkers[i].isTouch && (eventWorkers[i].eventNum < MaxTouchNumber)) + if (eventWorkers[i].threadId != 0) { - if(eventWorkers[i].threadId != 0) - { - TraceLog(LOG_WARNING, "Duplicate touchscreen found, killing toucnscreen on event%d", i); - pthread_cancel(eventWorkers[i].threadId); - close(eventWorkers[i].fd); - } + TraceLog(LOG_WARNING, "Duplicate touchscreen found, killing toucnscreen on event%d", i); + pthread_cancel(eventWorkers[i].threadId); + close(eventWorkers[i].fd); } } } +#endif } - else - { - // We are not interested in this device - close(fd); - } + else close(fd); // We are not interested in this device } static void *EventThread(void *arg) { - struct input_event ev; + struct input_event event; GestureEvent gestureEvent; - InputEventWorker* Worker = (InputEventWorker*)arg; + InputEventWorker *worker = (InputEventWorker *)arg; bool GestureNeedsUpdate = false; while (!windowShouldClose) { - if (read(Worker->fd, &ev, sizeof(ev)) == (int)sizeof(ev)) + if (read(worker->fd, &event, sizeof(event)) == (int)sizeof(event)) { /////////////////////////////// Relative movement parsing //////////////////////////////////// - if(ev.type == EV_REL) + if (event.type == EV_REL) { - if(ev.code == REL_X) + if (event.code == REL_X) { - mousePosition.x += ev.value; + mousePosition.x += event.value; touchPosition[0].x = mousePosition.x; gestureEvent.touchAction = TOUCH_MOVE; GestureNeedsUpdate = true; } - if(ev.code == REL_Y) + if (event.code == REL_Y) { - mousePosition.y += ev.value; + mousePosition.y += event.value; touchPosition[0].y = mousePosition.y; gestureEvent.touchAction = TOUCH_MOVE; GestureNeedsUpdate = true; } - if(ev.code == REL_WHEEL) + if (event.code == REL_WHEEL) { - currentMouseWheelY += ev.value; + currentMouseWheelY += event.value; } } /////////////////////////////// Absolute movement parsing //////////////////////////////////// - if(ev.type == EV_ABS) + if (event.type == EV_ABS) { // Basic movement - if(ev.code == ABS_X) + if (event.code == ABS_X) { - mousePosition.x = (ev.value - Worker->absRange.x) * screenWidth / Worker->absRange.width; //Scale acording to absRange + mousePosition.x = (event.value - worker->absRange.x)*screenWidth/worker->absRange.width; // Scale acording to absRange gestureEvent.touchAction = TOUCH_MOVE; GestureNeedsUpdate = true; } - if(ev.code == ABS_Y) + if (event.code == ABS_Y) { - mousePosition.y = (ev.value - Worker->absRange.y) * screenHeight / Worker->absRange.height; //Scale acording to absRange + mousePosition.y = (event.value - worker->absRange.y)*screenHeight/worker->absRange.height; // Scale acording to absRange gestureEvent.touchAction = TOUCH_MOVE; GestureNeedsUpdate = true; } - //Multitouch movement - if(ev.code == ABS_MT_SLOT) + // Multitouch movement + if (event.code == ABS_MT_SLOT) { - Worker->touchSlot = ev.value; //Remeber the slot number for the folowing events + worker->touchSlot = event.value; // Remeber the slot number for the folowing events } - if(ev.code == ABS_MT_POSITION_X) + if (event.code == ABS_MT_POSITION_X) { - if(Worker->touchSlot < MAX_TOUCH_POINTS) - touchPosition[Worker->touchSlot].x = (ev.value - Worker->absRange.x) * screenWidth / Worker->absRange.width; //Scale acording to absRange + if (worker->touchSlot < MAX_TOUCH_POINTS) + touchPosition[worker->touchSlot].x = (event.value - worker->absRange.x)*screenWidth/worker->absRange.width; // Scale acording to absRange } - if(ev.code == ABS_MT_POSITION_Y) + if (event.code == ABS_MT_POSITION_Y) { - if(Worker->touchSlot < MAX_TOUCH_POINTS) - touchPosition[Worker->touchSlot].y = (ev.value - Worker->absRange.y) * screenHeight / Worker->absRange.height; //Scale acording to absRange + if (worker->touchSlot < MAX_TOUCH_POINTS) + touchPosition[worker->touchSlot].y = (event.value - worker->absRange.y)*screenHeight/worker->absRange.height; // Scale acording to absRange } - if(ev.code == ABS_MT_TRACKING_ID) + if (event.code == ABS_MT_TRACKING_ID) { - if( (ev.value < 0) && (Worker->touchSlot < MAX_TOUCH_POINTS) ) + if ( (event.value < 0) && (worker->touchSlot < MAX_TOUCH_POINTS) ) { - //Touch has ended for this point - touchPosition[Worker->touchSlot].x = -1; - touchPosition[Worker->touchSlot].y = -1; + // Touch has ended for this point + touchPosition[worker->touchSlot].x = -1; + touchPosition[worker->touchSlot].y = -1; } } } /////////////////////////////// Button parsing //////////////////////////////////// - if(ev.type == EV_KEY) + if (event.type == EV_KEY) { - if((ev.code == BTN_TOUCH) || (ev.code == BTN_LEFT)) + if((event.code == BTN_TOUCH) || (event.code == BTN_LEFT)) { - currentMouseStateEvdev[MOUSE_LEFT_BUTTON] = ev.value; - if(ev.value > 0) - gestureEvent.touchAction = TOUCH_DOWN; - else - gestureEvent.touchAction = TOUCH_UP; + currentMouseStateEvdev[MOUSE_LEFT_BUTTON] = event.value; + if (event.value > 0) gestureEvent.touchAction = TOUCH_DOWN; + else gestureEvent.touchAction = TOUCH_UP; GestureNeedsUpdate = true; } - if(ev.code == BTN_RIGHT) - { - currentMouseStateEvdev[MOUSE_RIGHT_BUTTON] = ev.value; - } - - if(ev.code == BTN_MIDDLE) - { - currentMouseStateEvdev[MOUSE_MIDDLE_BUTTON] = ev.value; - } + if (event.code == BTN_RIGHT) currentMouseStateEvdev[MOUSE_RIGHT_BUTTON] = event.value; + if (event.code == BTN_MIDDLE) currentMouseStateEvdev[MOUSE_MIDDLE_BUTTON] = event.value; } /////////////////////////////// Screen confinement //////////////////////////////////// - if(mousePosition.x < 0) - mousePosition.x = 0; - if(mousePosition.x > screenWidth / mouseScale) - mousePosition.x = screenWidth / mouseScale; + if (mousePosition.x < 0) mousePosition.x = 0; + if (mousePosition.x > screenWidth/mouseScale) mousePosition.x = screenWidth/mouseScale; - if(mousePosition.y < 0) - mousePosition.y = 0; - if(mousePosition.y > screenHeight / mouseScale) - mousePosition.y = screenHeight / mouseScale; + if (mousePosition.y < 0) mousePosition.y = 0; + if (mousePosition.y > screenHeight/mouseScale) mousePosition.y = screenHeight/mouseScale; /////////////////////////////// Gesture update //////////////////////////////////// - if(GestureNeedsUpdate) + if (GestureNeedsUpdate) { gestureEvent.pointCount = 0; - if(touchPosition[0].x >= 0) gestureEvent.pointCount++; - if(touchPosition[1].x >= 0) gestureEvent.pointCount++; - if(touchPosition[2].x >= 0) gestureEvent.pointCount++; - if(touchPosition[3].x >= 0) gestureEvent.pointCount++; + if (touchPosition[0].x >= 0) gestureEvent.pointCount++; + if (touchPosition[1].x >= 0) gestureEvent.pointCount++; + if (touchPosition[2].x >= 0) gestureEvent.pointCount++; + if (touchPosition[3].x >= 0) gestureEvent.pointCount++; gestureEvent.pointerId[0] = 0; gestureEvent.pointerId[1] = 1; gestureEvent.pointerId[2] = 2; @@ -4240,10 +4213,12 @@ static void *EventThread(void *arg) } else { - usleep(5000); //Sleep for 5ms to avoid hogging CPU time + usleep(5000); // Sleep for 5ms to avoid hogging CPU time } } - close(Worker->fd); + + close(worker->fd); + return NULL; } -- cgit v1.2.3 From 72431c6c36a166b00e52527962ab4d978ab0111d Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 24 Oct 2018 13:45:17 +0200 Subject: Code tweaks --- src/core.c | 23 ++++++++++++----------- src/text.c | 13 +++++++------ 2 files changed, 19 insertions(+), 17 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index a0e53c87..ffbf110e 100644 --- a/src/core.c +++ b/src/core.c @@ -331,18 +331,19 @@ static int currentMouseWheelY = 0; // Registers current mouse wheel #if defined(PLATFORM_RPI) static char currentMouseStateEvdev[3] = { 0 }; // Holds the new mouse state for the next polling event to grab (Can't be written directly due to multithreading, app could miss the update) + typedef struct { - pthread_t threadId; // Event reading thread id - int fd; // File descriptor to the device it is assigned to - int eventNum; // Number of 'event' device - Rectangle absRange; // Range of values for absolute pointing devices (touchscreens) - int touchSlot; // Hold the touch slot number of the currently being sent multitouch block - bool isMouse; // True if device supports relative X Y movements - bool isTouch; // True if device supports absolute X Y movements and has BTN_TOUCH - bool isMultitouch; // True if device supports multiple absolute movevents and has BTN_TOUCH - bool isKeyboard; // True if device has letter keycodes - bool isGamepad; // True if device has gamepad buttons -}InputEventWorker; + pthread_t threadId; // Event reading thread id + int fd; // File descriptor to the device it is assigned to + int eventNum; // Number of 'event' device + Rectangle absRange; // Range of values for absolute pointing devices (touchscreens) + int touchSlot; // Hold the touch slot number of the currently being sent multitouch block + bool isMouse; // True if device supports relative X Y movements + bool isTouch; // True if device supports absolute X Y movements and has BTN_TOUCH + bool isMultitouch; // True if device supports multiple absolute movevents and has BTN_TOUCH + bool isKeyboard; // True if device has letter keycodes + bool isGamepad; // True if device has gamepad buttons +} InputEventWorker; static InputEventWorker eventWorkers[10]; // List of worker threads for every monitored "/dev/input/event" diff --git a/src/text.c b/src/text.c index 6e86958e..a010666e 100644 --- a/src/text.c +++ b/src/text.c @@ -316,6 +316,7 @@ Font LoadFontEx(const char *fileName, int fontSize, int charsCount, int *fontCha font.texture = LoadTextureFromImage(atlas); UnloadImage(atlas); } + else font = GetFontDefault(); return font; } @@ -331,9 +332,9 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c #define SDF_PIXEL_DIST_SCALE 64.0f #define BITMAP_ALPHA_THRESHOLD 80 - + CharInfo *chars = NULL; - + // Load font data (including pixel data) from TTF file // NOTE: Loaded information should be enough to generate font image atlas, // using any packaging method @@ -349,7 +350,7 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c fread(fontBuffer, size, 1, fontFile); fclose(fontFile); - + // Init font for data reading stbtt_fontinfo fontInfo; if (!stbtt_InitFont(&fontInfo, fontBuffer, 0)) TraceLog(LOG_WARNING, "Failed to init font!"); @@ -368,11 +369,11 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c // Fill fontChars in case not provided externally // NOTE: By default we fill charsCount consecutevely, starting at 32 (Space) int genFontChars = false; - if (fontChars == NULL) genFontChars = true; - if (genFontChars) + if (fontChars == NULL) { fontChars = (int *)malloc(charsCount*sizeof(int)); for (int i = 0; i < charsCount; i++) fontChars[i] = i + 32; + genFontChars = true; } chars = (CharInfo *)malloc(charsCount*sizeof(CharInfo)); @@ -417,7 +418,7 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c stbtt_GetCodepointHMetrics(&fontInfo, ch, &chars[i].advanceX, NULL); chars[i].advanceX *= scaleFactor; } - + free(fontBuffer); if (genFontChars) free(fontChars); } -- cgit v1.2.3