Debian Codegraph @

src/platforms/rcore_desktop_sdl.c

raw symbols SCIP
1 /**********************************************************************************************
2 *
3 * rcore_desktop_sdl - Functions to manage window, graphics device and inputs
4 *
5 * PLATFORM: DESKTOP: SDL
6 * - Windows (Win32, Win64)
7 * - Linux (X11/Wayland desktop mode)
8 * - Others (not tested)
9 *
10 * LIMITATIONS:
11 * - Limitation 01
12 * - Limitation 02
13 *
14 * POSSIBLE IMPROVEMENTS:
15 * - Improvement 01
16 * - Improvement 02
17 *
18 * CONFIGURATION:
19 * #define RCORE_PLATFORM_CUSTOM_FLAG
20 * Custom flag for rcore on target platform -not used-
21 *
22 * DEPENDENCIES:
23 * - SDL 2 or SDL 3 (main library): Windowing and inputs management
24 * - gestures: Gestures system for touch-ready devices (or simulated from mouse inputs)
25 *
26 *
27 * LICENSE: zlib/libpng
28 *
29 * Copyright (c) 2013-2026 Ramon Santamaria (@raysan5) and contributors
30 *
31 * This software is provided "as-is", without any express or implied warranty. In no event
32 * will the authors be held liable for any damages arising from the use of this software.
33 *
34 * Permission is granted to anyone to use this software for any purpose, including commercial
35 * applications, and to alter it and redistribute it freely, subject to the following restrictions:
36 *
37 * 1. The origin of this software must not be misrepresented; you must not claim that you
38 * wrote the original software. If you use this software in a product, an acknowledgment
39 * in the product documentation would be appreciated but is not required.
40 *
41 * 2. Altered source versions must be plainly marked as such, and must not be misrepresented
42 * as being the original software.
43 *
44 * 3. This notice may not be removed or altered from any source distribution.
45 *
46 **********************************************************************************************/
47
48 #ifdef USING_SDL3_PACKAGE
49 #define USING_SDL3_PROJECT
50 #endif
51 #ifndef SDL_ENABLE_OLD_NAMES
52 #define SDL_ENABLE_OLD_NAMES // In case on SDL3, some in-between compatibily is needed
53 #endif
54 // SDL base library (window/rendered, input, timing... functionality)
55 #ifdef USING_SDL3_PROJECT
56 #include "SDL3/SDL.h"
57 #elif defined(USING_SDL2_PROJECT)
58 #include "SDL2/SDL.h"
59 #else
60 #include "SDL.h"
61 #endif
62
63 #if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
64 #if defined(GRAPHICS_API_OPENGL_ES2)
65 // It seems it does not need to be included to work
66 //#include "SDL_opengles2.h"
67 #else
68 // SDL OpenGL functionality (if required, instead of internal renderer)
69 #ifdef USING_SDL3_PROJECT
70 #include "SDL3/SDL_opengl.h"
71 #elif defined(USING_SDL2_PROJECT)
72 #include "SDL2/SDL_opengl.h"
73 #else
74 #include "SDL_opengl.h"
75 #endif
76 #endif
77 #endif
78
79 //----------------------------------------------------------------------------------
80 // Defines and Macros
81 //----------------------------------------------------------------------------------
82 #ifndef MAX_CLIPBOARD_BUFFER_LENGTH
83 #define MAX_CLIPBOARD_BUFFER_LENGTH 1024 // Size of the clipboard buffer used on GetClipboardText()
84 #endif
85
86 #if ((defined(SDL_MAJOR_VERSION) && (SDL_MAJOR_VERSION == 3)) && (defined(SDL_MINOR_VERSION) && (SDL_MINOR_VERSION >= 1)))
87 #ifndef USING_VERSION_SDL3
88 #define USING_VERSION_SDL3
89 #endif
90 #endif
91
92 #define SCANCODE_MAPPED_NUM 232
93
94 //----------------------------------------------------------------------------------
95 // Types and Structures Definition
96 //----------------------------------------------------------------------------------
97 typedef struct {
98 SDL_Window *window;
99 SDL_GLContext glContext;
100
101 SDL_GameController *gamepad[MAX_GAMEPADS];
102 SDL_JoystickID gamepadId[MAX_GAMEPADS]; // Joystick instance ids, they do not start from 0
103 SDL_Cursor *cursor;
104 } PlatformData;
105
106 //----------------------------------------------------------------------------------
107 // Global Variables Definition
108 //----------------------------------------------------------------------------------
109 extern CoreData CORE; // Global CORE state context
110
111 static PlatformData platform = { 0 }; // Platform specific data
112
113 static const KeyboardKey mapScancodeToKey[SCANCODE_MAPPED_NUM] = {
114 KEY_NULL, // SDL_SCANCODE_UNKNOWN
115 0,
116 0,
117 0,
118 KEY_A, // SDL_SCANCODE_A
119 KEY_B, // SDL_SCANCODE_B
120 KEY_C, // SDL_SCANCODE_C
121 KEY_D, // SDL_SCANCODE_D
122 KEY_E, // SDL_SCANCODE_E
123 KEY_F, // SDL_SCANCODE_F
124 KEY_G, // SDL_SCANCODE_G
125 KEY_H, // SDL_SCANCODE_H
126 KEY_I, // SDL_SCANCODE_I
127 KEY_J, // SDL_SCANCODE_J
128 KEY_K, // SDL_SCANCODE_K
129 KEY_L, // SDL_SCANCODE_L
130 KEY_M, // SDL_SCANCODE_M
131 KEY_N, // SDL_SCANCODE_N
132 KEY_O, // SDL_SCANCODE_O
133 KEY_P, // SDL_SCANCODE_P
134 KEY_Q, // SDL_SCANCODE_Q
135 KEY_R, // SDL_SCANCODE_R
136 KEY_S, // SDL_SCANCODE_S
137 KEY_T, // SDL_SCANCODE_T
138 KEY_U, // SDL_SCANCODE_U
139 KEY_V, // SDL_SCANCODE_V
140 KEY_W, // SDL_SCANCODE_W
141 KEY_X, // SDL_SCANCODE_X
142 KEY_Y, // SDL_SCANCODE_Y
143 KEY_Z, // SDL_SCANCODE_Z
144 KEY_ONE, // SDL_SCANCODE_1
145 KEY_TWO, // SDL_SCANCODE_2
146 KEY_THREE, // SDL_SCANCODE_3
147 KEY_FOUR, // SDL_SCANCODE_4
148 KEY_FIVE, // SDL_SCANCODE_5
149 KEY_SIX, // SDL_SCANCODE_6
150 KEY_SEVEN, // SDL_SCANCODE_7
151 KEY_EIGHT, // SDL_SCANCODE_8
152 KEY_NINE, // SDL_SCANCODE_9
153 KEY_ZERO, // SDL_SCANCODE_0
154 KEY_ENTER, // SDL_SCANCODE_RETURN
155 KEY_ESCAPE, // SDL_SCANCODE_ESCAPE
156 KEY_BACKSPACE, // SDL_SCANCODE_BACKSPACE
157 KEY_TAB, // SDL_SCANCODE_TAB
158 KEY_SPACE, // SDL_SCANCODE_SPACE
159 KEY_MINUS, // SDL_SCANCODE_MINUS
160 KEY_EQUAL, // SDL_SCANCODE_EQUALS
161 KEY_LEFT_BRACKET, // SDL_SCANCODE_LEFTBRACKET
162 KEY_RIGHT_BRACKET, // SDL_SCANCODE_RIGHTBRACKET
163 KEY_BACKSLASH, // SDL_SCANCODE_BACKSLASH
164 0, // SDL_SCANCODE_NONUSHASH
165 KEY_SEMICOLON, // SDL_SCANCODE_SEMICOLON
166 KEY_APOSTROPHE, // SDL_SCANCODE_APOSTROPHE
167 KEY_GRAVE, // SDL_SCANCODE_GRAVE
168 KEY_COMMA, // SDL_SCANCODE_COMMA
169 KEY_PERIOD, // SDL_SCANCODE_PERIOD
170 KEY_SLASH, // SDL_SCANCODE_SLASH
171 KEY_CAPS_LOCK, // SDL_SCANCODE_CAPSLOCK
172 KEY_F1, // SDL_SCANCODE_F1
173 KEY_F2, // SDL_SCANCODE_F2
174 KEY_F3, // SDL_SCANCODE_F3
175 KEY_F4, // SDL_SCANCODE_F4
176 KEY_F5, // SDL_SCANCODE_F5
177 KEY_F6, // SDL_SCANCODE_F6
178 KEY_F7, // SDL_SCANCODE_F7
179 KEY_F8, // SDL_SCANCODE_F8
180 KEY_F9, // SDL_SCANCODE_F9
181 KEY_F10, // SDL_SCANCODE_F10
182 KEY_F11, // SDL_SCANCODE_F11
183 KEY_F12, // SDL_SCANCODE_F12
184 KEY_PRINT_SCREEN, // SDL_SCANCODE_PRINTSCREEN
185 KEY_SCROLL_LOCK, // SDL_SCANCODE_SCROLLLOCK
186 KEY_PAUSE, // SDL_SCANCODE_PAUSE
187 KEY_INSERT, // SDL_SCANCODE_INSERT
188 KEY_HOME, // SDL_SCANCODE_HOME
189 KEY_PAGE_UP, // SDL_SCANCODE_PAGEUP
190 KEY_DELETE, // SDL_SCANCODE_DELETE
191 KEY_END, // SDL_SCANCODE_END
192 KEY_PAGE_DOWN, // SDL_SCANCODE_PAGEDOWN
193 KEY_RIGHT, // SDL_SCANCODE_RIGHT
194 KEY_LEFT, // SDL_SCANCODE_LEFT
195 KEY_DOWN, // SDL_SCANCODE_DOWN
196 KEY_UP, // SDL_SCANCODE_UP
197 KEY_NUM_LOCK, // SDL_SCANCODE_NUMLOCKCLEAR
198 KEY_KP_DIVIDE, // SDL_SCANCODE_KP_DIVIDE
199 KEY_KP_MULTIPLY, // SDL_SCANCODE_KP_MULTIPLY
200 KEY_KP_SUBTRACT, // SDL_SCANCODE_KP_MINUS
201 KEY_KP_ADD, // SDL_SCANCODE_KP_PLUS
202 KEY_KP_ENTER, // SDL_SCANCODE_KP_ENTER
203 KEY_KP_1, // SDL_SCANCODE_KP_1
204 KEY_KP_2, // SDL_SCANCODE_KP_2
205 KEY_KP_3, // SDL_SCANCODE_KP_3
206 KEY_KP_4, // SDL_SCANCODE_KP_4
207 KEY_KP_5, // SDL_SCANCODE_KP_5
208 KEY_KP_6, // SDL_SCANCODE_KP_6
209 KEY_KP_7, // SDL_SCANCODE_KP_7
210 KEY_KP_8, // SDL_SCANCODE_KP_8
211 KEY_KP_9, // SDL_SCANCODE_KP_9
212 KEY_KP_0, // SDL_SCANCODE_KP_0
213 KEY_KP_DECIMAL, // SDL_SCANCODE_KP_PERIOD
214 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
218 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0,
227 KEY_LEFT_CONTROL, //SDL_SCANCODE_LCTRL
228 KEY_LEFT_SHIFT, //SDL_SCANCODE_LSHIFT
229 KEY_LEFT_ALT, //SDL_SCANCODE_LALT
230 KEY_LEFT_SUPER, //SDL_SCANCODE_LGUI
231 KEY_RIGHT_CONTROL, //SDL_SCANCODE_RCTRL
232 KEY_RIGHT_SHIFT, //SDL_SCANCODE_RSHIFT
233 KEY_RIGHT_ALT, //SDL_SCANCODE_RALT
234 KEY_RIGHT_SUPER //SDL_SCANCODE_RGUI
235 };
236
237 static const int CursorsLUT[] = {
238 SDL_SYSTEM_CURSOR_ARROW, // 0 MOUSE_CURSOR_DEFAULT
239 SDL_SYSTEM_CURSOR_ARROW, // 1 MOUSE_CURSOR_ARROW
240 SDL_SYSTEM_CURSOR_IBEAM, // 2 MOUSE_CURSOR_IBEAM
241 SDL_SYSTEM_CURSOR_CROSSHAIR, // 3 MOUSE_CURSOR_CROSSHAIR
242 SDL_SYSTEM_CURSOR_HAND, // 4 MOUSE_CURSOR_POINTING_HAND
243 SDL_SYSTEM_CURSOR_SIZEWE, // 5 MOUSE_CURSOR_RESIZE_EW
244 SDL_SYSTEM_CURSOR_SIZENS, // 6 MOUSE_CURSOR_RESIZE_NS
245 SDL_SYSTEM_CURSOR_SIZENWSE, // 7 MOUSE_CURSOR_RESIZE_NWSE
246 SDL_SYSTEM_CURSOR_SIZENESW, // 8 MOUSE_CURSOR_RESIZE_NESW
247 SDL_SYSTEM_CURSOR_SIZEALL, // 9 MOUSE_CURSOR_RESIZE_ALL
248 SDL_SYSTEM_CURSOR_NO // 10 MOUSE_CURSOR_NOT_ALLOWED
249 //SDL_SYSTEM_CURSOR_WAIT, // No equivalent implemented on MouseCursor enum on raylib.h
250 //SDL_SYSTEM_CURSOR_WAITARROW, // No equivalent implemented on MouseCursor enum on raylib.h
251 };
252
253 // SDL3 migration layer made to avoid 'ifdefs' inside functions
254 #if defined(USING_VERSION_SDL3)
255
256 // SDL3 migration:
257 // SDL_WINDOW_FULLSCREEN_DESKTOP has been removed,
258 // SDL_GetWindowFullscreenMode() can be called
259 // to see whether an exclusive fullscreen mode will be used
260 // or the borderless fullscreen desktop mode
261 #define SDL_WINDOW_FULLSCREEN_DESKTOP SDL_WINDOW_FULLSCREEN
262
263 #define SDL_IGNORE false
264 #define SDL_DISABLE false
265 #define SDL_ENABLE true
266
267 // SDL3 Migration: SDL_INIT_TIMER - no longer needed before calling SDL_AddTimer()
268 #define SDL_INIT_TIMER 0x0 // It's a flag, so no problem in setting it to zero to be used in a bitor (|)
269
270 // SDL3 Migration: The SDL_WINDOW_SHOWN flag has been removed. Windows are shown by default and can be created hidden by using the SDL_WINDOW_HIDDEN flag
271 #define SDL_WINDOW_SHOWN 0x0 // It's a flag, so no problem in setting it to zero to be used in a bitor (|)
272
273 // SDL3 Migration: Renamed
274 // IMPORTANT: Might need to call SDL_CleanupEvent somewhere see :https://github.com/libsdl-org/SDL/issues/3540#issuecomment-1793449852
275 #define SDL_DROPFILE SDL_EVENT_DROP_FILE
276
277 // SDL2 implementation for SDL3 function
278 const char *SDL_GameControllerNameForIndex(int joystickIndex)
279 {
280 // NOTE: SDL3 uses the IDs itself (SDL_JoystickID) instead of SDL2 joystick_index
281 const char *name = NULL;
282 int numJoysticks = 0;
283 SDL_JoystickID *joysticks = SDL_GetJoysticks(&numJoysticks);
284
285 if (joysticks)
286 {
287 if (joystickIndex < numJoysticks)
288 {
289 SDL_JoystickID instance_id = joysticks[joystickIndex];
290 name = SDL_GetGamepadNameForID(instance_id);
291 }
292
293 SDL_free(joysticks);
294 }
295
296 return name;
297 }
298
299 int SDL_GetNumVideoDisplays(void)
300 {
301 int monitorCount = 0;
302 SDL_DisplayID *displays = SDL_GetDisplays(&monitorCount);
303
304 // Safe because If 'mem' is NULL, SDL_free does nothing
305 SDL_free(displays);
306
307 return monitorCount;
308 }
309
310 // SLD3 Migration: To emulate SDL2 this function should return 'SDL_DISABLE' or 'SDL_ENABLE'
311 // representing the *processing state* of the event before this function makes any changes to it
312 Uint8 SDL_EventState(Uint32 type, int state)
313 {
314 Uint8 stateBefore = SDL_EventEnabled(type);
315
316 switch (state)
317 {
318 case SDL_DISABLE: SDL_SetEventEnabled(type, false); break;
319 case SDL_ENABLE: SDL_SetEventEnabled(type, true); break;
320 default: TRACELOG(LOG_WARNING, "SDL: Event state of unknow type");
321 }
322
323 return stateBefore;
324 }
325
326 void SDL_GetCurrentDisplayMode_Adapter(SDL_DisplayID displayID, SDL_DisplayMode *mode)
327 {
328 const SDL_DisplayMode *currentMode = SDL_GetCurrentDisplayMode(displayID);
329
330 if (currentMode == NULL) TRACELOG(LOG_WARNING, "SDL: No possible to get current display mode");
331 else *mode = *currentMode;
332 }
333
334 // SDL3 Migration: Renamed
335 #define SDL_GetCurrentDisplayMode SDL_GetCurrentDisplayMode_Adapter
336
337 SDL_Surface *SDL_CreateRGBSurface(Uint32 flags, int width, int height, int depth, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask)
338 {
339 return SDL_CreateSurface(width, height, SDL_GetPixelFormatForMasks(depth, Rmask, Gmask, Bmask, Amask));
340 }
341
342 // SDL3 Migration:
343 // SDL_GetDisplayDPI() not reliable across platforms, approximately replaced by multiplying
344 // SDL_GetWindowDisplayScale() times 160 on iPhone and Android, and 96 on other platforms
345 // returns 0 on success or a negative error code on failure
346 int SDL_GetDisplayDPI(int displayIndex, float *ddpi, float *hdpi, float *vdpi)
347 {
348 float dpi = SDL_GetWindowDisplayScale(platform.window)*96.0;
349
350 if (ddpi != NULL) *ddpi = dpi;
351 if (hdpi != NULL) *hdpi = dpi;
352 if (vdpi != NULL) *vdpi = dpi;
353
354 return 0;
355 }
356
357 SDL_Surface *SDL_CreateRGBSurfaceWithFormat(Uint32 flags, int width, int height, int depth, Uint32 format)
358 {
359 return SDL_CreateSurface(width, height, format);
360 }
361
362 SDL_Surface *SDL_CreateRGBSurfaceFrom(void *pixels, int width, int height, int depth, int pitch, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask)
363 {
364 return SDL_CreateSurfaceFrom(width, height, SDL_GetPixelFormatForMasks(depth, Rmask, Gmask, Bmask, Amask), pixels, pitch);
365 }
366
367 SDL_Surface *SDL_CreateRGBSurfaceWithFormatFrom(void *pixels, int width, int height, int depth, int pitch, Uint32 format)
368 {
369 return SDL_CreateSurfaceFrom(width, height, format, pixels, pitch);
370 }
371
372 int SDL_NumJoysticks(void)
373 {
374 int numJoysticks;
375 SDL_JoystickID *joysticks = SDL_GetJoysticks(&numJoysticks);
376 SDL_free(joysticks);
377 return numJoysticks;
378 }
379
380 // SDL_SetRelativeMouseMode
381 // returns 0 on success or a negative error code on failure
382 // If relative mode is not supported, this returns -1
383 int SDL_SetRelativeMouseMode_Adapter(SDL_bool enabled)
384 {
385 // SDL_SetWindowRelativeMouseMode(SDL_Window *window, bool enabled)
386 // \returns true on success or false on failure; call SDL_GetError() for more
387 if (SDL_SetWindowRelativeMouseMode(platform.window, enabled))
388 {
389 return 0; // success
390 }
391 else
392 {
393 return -1; // failure
394 }
395 }
396
397 #define SDL_SetRelativeMouseMode SDL_SetRelativeMouseMode_Adapter
398
399 bool SDL_GetRelativeMouseMode_Adapter(void)
400 {
401 return SDL_GetWindowRelativeMouseMode(platform.window);
402 }
403
404 #define SDL_GetRelativeMouseMode SDL_GetRelativeMouseMode_Adapter
405
406 int SDL_GetNumTouchFingers(SDL_TouchID touchID)
407 {
408 // SDL_Finger **SDL_GetTouchFingers(SDL_TouchID touchID, int *count)
409 int count = 0;
410 SDL_Finger **fingers = SDL_GetTouchFingers(touchID, &count);
411 SDL_free(fingers);
412 return count;
413 }
414
415 #else // SDL2 fallback
416
417 // Since SDL2 doesn't have this function, leaving a stub
418 // SDL_GetClipboardData function is available since SDL 3.1.3. (e.g. SDL3)
419 void *SDL_GetClipboardData(const char *mime_type, size_t *size)
420 {
421 TRACELOG(LOG_WARNING, "SDL: Getting clipboard data that is not text not available in SDL2");
422
423 // TODO: Implement getting clipboard data
424
425 return NULL;
426 }
427 #endif // USING_VERSION_SDL3
428
429 //----------------------------------------------------------------------------------
430 // Module Internal Functions Declaration
431 //----------------------------------------------------------------------------------
432 int InitPlatform(void); // Initialize platform (graphics, inputs and more)
433 void ClosePlatform(void); // Close platform
434
435 static KeyboardKey ConvertScancodeToKey(SDL_Scancode sdlScancode); // Help convert SDL scancodes to raylib key
436 static int GetCodepointNextSDL(const char *text, int *codepointSize); // Get next codepoint in a byte sequence and bytes processed
437 static void UpdateTouchPointsSDL(SDL_TouchFingerEvent event); // Update CORE input touch point info from SDL touch data
438
439 //----------------------------------------------------------------------------------
440 // Module Functions Declaration
441 //----------------------------------------------------------------------------------
442 // NOTE: Functions declaration is provided by raylib.h
443
444 //----------------------------------------------------------------------------------
445 // Module Functions Definition: Window and Graphics Device
446 //----------------------------------------------------------------------------------
447
448 // Check if application should close
449 bool WindowShouldClose(void)
450 {
451 if (CORE.Window.ready) return CORE.Window.shouldClose;
452 else return true;
453 }
454
455 // Toggle fullscreen mode
456 void ToggleFullscreen(void)
457 {
458 const int monitor = SDL_GetWindowDisplayIndex(platform.window);
459 const int monitorCount = SDL_GetNumVideoDisplays();
460
461 #if defined(USING_VERSION_SDL3) // SDL3 Migration: Monitor is an id instead of index now, returns 0 on failure
462 if (SDL_GetDisplayProperties(monitor) != 0) // Returns 0 on failure, so a value other than zero indicates that the monitor id is valid
463 #else
464 if ((monitor >= 0) && (monitor < monitorCount))
465 #endif
466 {
467 if (FLAG_IS_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE))
468 {
469 SDL_SetWindowFullscreen(platform.window, 0);
470 FLAG_CLEAR(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
471 }
472 else
473 {
474 SDL_SetWindowFullscreen(platform.window, SDL_WINDOW_FULLSCREEN);
475 FLAG_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
476 }
477 }
478 else TRACELOG(LOG_WARNING, "SDL: Failed to find selected monitor");
479 }
480
481 // Toggle borderless windowed mode
482 void ToggleBorderlessWindowed(void)
483 {
484 const int monitor = SDL_GetWindowDisplayIndex(platform.window);
485 const int monitorCount = SDL_GetNumVideoDisplays();
486
487 #if defined(USING_VERSION_SDL3) // SDL3 Migration: Monitor is an id instead of index now, returns 0 on failure
488 if (SDL_GetDisplayProperties(monitor) != 0) // Returns 0 on failure, so a value other than zero indicates that the monitor id is valid
489 #else
490 if ((monitor >= 0) && (monitor < monitorCount))
491 #endif
492 {
493 if (FLAG_IS_SET(CORE.Window.flags, FLAG_BORDERLESS_WINDOWED_MODE))
494 {
495 SDL_SetWindowFullscreen(platform.window, 0);
496 FLAG_CLEAR(CORE.Window.flags, FLAG_BORDERLESS_WINDOWED_MODE);
497 }
498 else
499 {
500 SDL_SetWindowFullscreen(platform.window, SDL_WINDOW_FULLSCREEN_DESKTOP);
501 FLAG_SET(CORE.Window.flags, FLAG_BORDERLESS_WINDOWED_MODE);
502 }
503 }
504 else TRACELOG(LOG_WARNING, "SDL: Failed to find selected monitor");
505 }
506
507 // Set window state: maximized, if resizable
508 void MaximizeWindow(void)
509 {
510 SDL_MaximizeWindow(platform.window);
511 if (!FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED)) FLAG_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED);
512 }
513
514 // Set window state: minimized
515 void MinimizeWindow(void)
516 {
517 SDL_MinimizeWindow(platform.window);
518 if (!FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED)) FLAG_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED);
519 }
520
521 // Restore window from being minimized/maximized
522 void RestoreWindow(void)
523 {
524 SDL_RestoreWindow(platform.window);
525 // CORE.Window.flags will be removed on PollInputEvents()
526 }
527
528 // Set window configuration state using flags
529 void SetWindowState(unsigned int flags)
530 {
531 if (!CORE.Window.ready) TRACELOG(LOG_WARNING, "WINDOW: SetWindowState does nothing before window initialization, Use \"SetConfigFlags\" instead");
532
533 FLAG_SET(CORE.Window.flags, flags);
534
535 if (FLAG_IS_SET(flags, FLAG_VSYNC_HINT))
536 {
537 SDL_GL_SetSwapInterval(1);
538 }
539 if (FLAG_IS_SET(flags, FLAG_FULLSCREEN_MODE))
540 {
541 const int monitor = SDL_GetWindowDisplayIndex(platform.window);
542 const int monitorCount = SDL_GetNumVideoDisplays();
543
544 #if defined(USING_VERSION_SDL3) // SDL3 Migration: Monitor is an id instead of index now, returns 0 on failure
545 if (SDL_GetDisplayProperties(monitor) != 0) // Returns 0 on failure, so a value other than zero indicates that the monitor id is valid
546 #else
547 if ((monitor >= 0) && (monitor < monitorCount))
548 #endif
549 {
550 SDL_SetWindowFullscreen(platform.window, SDL_WINDOW_FULLSCREEN);
551 FLAG_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
552 }
553 else TRACELOG(LOG_WARNING, "SDL: Failed to find selected monitor");
554 }
555 if (FLAG_IS_SET(flags, FLAG_WINDOW_RESIZABLE))
556 {
557 SDL_SetWindowResizable(platform.window, SDL_TRUE);
558 }
559 if (FLAG_IS_SET(flags, FLAG_WINDOW_UNDECORATED))
560 {
561 SDL_SetWindowBordered(platform.window, SDL_FALSE);
562 }
563 if (FLAG_IS_SET(flags, FLAG_WINDOW_HIDDEN))
564 {
565 SDL_HideWindow(platform.window);
566 }
567 if (FLAG_IS_SET(flags, FLAG_WINDOW_MINIMIZED))
568 {
569 SDL_MinimizeWindow(platform.window);
570 }
571 if (FLAG_IS_SET(flags, FLAG_WINDOW_MAXIMIZED))
572 {
573 SDL_MaximizeWindow(platform.window);
574 }
575 if (FLAG_IS_SET(flags, FLAG_WINDOW_UNFOCUSED))
576 {
577 TRACELOG(LOG_WARNING, "SetWindowState() - FLAG_WINDOW_UNFOCUSED is not supported on PLATFORM_DESKTOP_SDL");
578 }
579 if (FLAG_IS_SET(flags, FLAG_WINDOW_TOPMOST))
580 {
581 SDL_SetWindowAlwaysOnTop(platform.window, SDL_FALSE);
582 }
583 if (FLAG_IS_SET(flags, FLAG_WINDOW_ALWAYS_RUN))
584 {
585 FLAG_SET(CORE.Window.flags, FLAG_WINDOW_ALWAYS_RUN);
586 }
587 if (FLAG_IS_SET(flags, FLAG_WINDOW_TRANSPARENT))
588 {
589 TRACELOG(LOG_WARNING, "SetWindowState() - FLAG_WINDOW_TRANSPARENT is not supported on PLATFORM_DESKTOP_SDL");
590 }
591 if (FLAG_IS_SET(flags, FLAG_WINDOW_HIGHDPI))
592 {
593 // NOTE: Such a function does not seem to exist
594 TRACELOG(LOG_WARNING, "SetWindowState() - FLAG_WINDOW_HIGHDPI is not supported on PLATFORM_DESKTOP_SDL");
595 }
596 if (FLAG_IS_SET(flags, FLAG_WINDOW_MOUSE_PASSTHROUGH))
597 {
598 //SDL_SetWindowGrab(platform.window, SDL_FALSE);
599 TRACELOG(LOG_WARNING, "SetWindowState() - FLAG_WINDOW_MOUSE_PASSTHROUGH is not supported on PLATFORM_DESKTOP_SDL");
600 }
601 if (FLAG_IS_SET(flags, FLAG_BORDERLESS_WINDOWED_MODE))
602 {
603 const int monitor = SDL_GetWindowDisplayIndex(platform.window);
604 const int monitorCount = SDL_GetNumVideoDisplays();
605
606 #if defined(USING_VERSION_SDL3) // SDL3 Migration: Monitor is an id instead of index now, returns 0 on failure
607 if (SDL_GetDisplayProperties(monitor) != 0) // Returns 0 on failure, so a value other than zero indicates that the monitor id is valid
608 #else
609 if ((monitor >= 0) && (monitor < monitorCount))
610 #endif
611 {
612 SDL_SetWindowFullscreen(platform.window, SDL_WINDOW_FULLSCREEN_DESKTOP);
613 }
614 else TRACELOG(LOG_WARNING, "SDL: Failed to find selected monitor");
615 }
616 if (FLAG_IS_SET(flags, FLAG_MSAA_4X_HINT))
617 {
618 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); // Enable multisampling buffers
619 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); // Enable multisampling
620 }
621 if (FLAG_IS_SET(flags, FLAG_INTERLACED_HINT))
622 {
623 TRACELOG(LOG_WARNING, "SetWindowState() - FLAG_INTERLACED_HINT is not supported on PLATFORM_DESKTOP_SDL");
624 }
625 }
626
627 // Clear window configuration state flags
628 void ClearWindowState(unsigned int flags)
629 {
630 FLAG_CLEAR(CORE.Window.flags, flags);
631
632 if (FLAG_IS_SET(flags, FLAG_VSYNC_HINT))
633 {
634 SDL_GL_SetSwapInterval(0);
635 }
636 if (FLAG_IS_SET(flags, FLAG_FULLSCREEN_MODE))
637 {
638 SDL_SetWindowFullscreen(platform.window, 0);
639 }
640 if (FLAG_IS_SET(flags, FLAG_WINDOW_RESIZABLE))
641 {
642 SDL_SetWindowResizable(platform.window, SDL_FALSE);
643 }
644 if (FLAG_IS_SET(flags, FLAG_WINDOW_UNDECORATED))
645 {
646 SDL_SetWindowBordered(platform.window, SDL_TRUE);
647 }
648 if (FLAG_IS_SET(flags, FLAG_WINDOW_HIDDEN))
649 {
650 SDL_ShowWindow(platform.window);
651 }
652 if (FLAG_IS_SET(flags, FLAG_WINDOW_MINIMIZED))
653 {
654 SDL_RestoreWindow(platform.window);
655 }
656 if (FLAG_IS_SET(flags, FLAG_WINDOW_MAXIMIZED))
657 {
658 SDL_RestoreWindow(platform.window);
659 }
660 if (FLAG_IS_SET(flags, FLAG_WINDOW_UNFOCUSED))
661 {
662 //SDL_RaiseWindow(platform.window);
663 TRACELOG(LOG_WARNING, "ClearWindowState() - FLAG_WINDOW_UNFOCUSED is not supported on PLATFORM_DESKTOP_SDL");
664 }
665 if (FLAG_IS_SET(flags, FLAG_WINDOW_TOPMOST))
666 {
667 SDL_SetWindowAlwaysOnTop(platform.window, SDL_FALSE);
668 }
669 if (FLAG_IS_SET(flags, FLAG_WINDOW_TRANSPARENT))
670 {
671 TRACELOG(LOG_WARNING, "ClearWindowState() - FLAG_WINDOW_TRANSPARENT is not supported on PLATFORM_DESKTOP_SDL");
672 }
673 if (FLAG_IS_SET(flags, FLAG_WINDOW_HIGHDPI))
674 {
675 // NOTE: There also doesn't seem to be a feature to disable high DPI once enabled
676 TRACELOG(LOG_WARNING, "ClearWindowState() - FLAG_WINDOW_HIGHDPI is not supported on PLATFORM_DESKTOP_SDL");
677 }
678 if (FLAG_IS_SET(flags, FLAG_WINDOW_MOUSE_PASSTHROUGH))
679 {
680 //SDL_SetWindowGrab(platform.window, SDL_TRUE);
681 TRACELOG(LOG_WARNING, "ClearWindowState() - FLAG_WINDOW_MOUSE_PASSTHROUGH is not supported on PLATFORM_DESKTOP_SDL");
682 }
683 if (FLAG_IS_SET(flags, FLAG_BORDERLESS_WINDOWED_MODE))
684 {
685 SDL_SetWindowFullscreen(platform.window, 0);
686 }
687 if (FLAG_IS_SET(flags, FLAG_MSAA_4X_HINT))
688 {
689 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); // Disable multisampling buffers
690 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); // Disable multisampling
691 }
692 if (FLAG_IS_SET(flags, FLAG_INTERLACED_HINT))
693 {
694 TRACELOG(LOG_WARNING, "ClearWindowState() - FLAG_INTERLACED_HINT is not supported on PLATFORM_DESKTOP_SDL");
695 }
696 }
697
698 // Set icon for window
699 void SetWindowIcon(Image image)
700 {
701 SDL_Surface *iconSurface = NULL;
702
703 unsigned int rmask = 0, gmask = 0, bmask = 0, amask = 0;
704 int depth = 0; // Depth in bits
705 int pitch = 0; // Pixel spacing (pitch) in bytes
706
707 switch (image.format)
708 {
709 case PIXELFORMAT_UNCOMPRESSED_GRAYSCALE:
710 {
711 rmask = 0xFF, gmask = 0;
712 bmask = 0, amask = 0;
713 depth = 8, pitch = image.width;
714 } break;
715 case PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA:
716 {
717 rmask = 0xFF, gmask = 0xFF00;
718 bmask = 0, amask = 0;
719 depth = 16, pitch = image.width*2;
720 } break;
721 case PIXELFORMAT_UNCOMPRESSED_R5G6B5:
722 {
723 rmask = 0xF800, gmask = 0x07E0;
724 bmask = 0x001F, amask = 0;
725 depth = 16, pitch = image.width*2;
726 } break;
727 case PIXELFORMAT_UNCOMPRESSED_R8G8B8:
728 {
729 // WARNING: SDL2 could be using BGR but SDL3 RGB
730 rmask = 0xFF0000, gmask = 0x00FF00;
731 bmask = 0x0000FF, amask = 0;
732 depth = 24, pitch = image.width*3;
733 } break;
734 case PIXELFORMAT_UNCOMPRESSED_R5G5B5A1:
735 {
736 rmask = 0xF800, gmask = 0x07C0;
737 bmask = 0x003E, amask = 0x0001;
738 depth = 16, pitch = image.width*2;
739 } break;
740 case PIXELFORMAT_UNCOMPRESSED_R4G4B4A4:
741 {
742 rmask = 0xF000, gmask = 0x0F00;
743 bmask = 0x00F0, amask = 0x000F;
744 depth = 16, pitch = image.width*2;
745 } break;
746 case PIXELFORMAT_UNCOMPRESSED_R8G8B8A8:
747 {
748 rmask = 0xFF000000, gmask = 0x00FF0000;
749 bmask = 0x0000FF00, amask = 0x000000FF;
750 depth = 32, pitch = image.width*4;
751 } break;
752 case PIXELFORMAT_UNCOMPRESSED_R32:
753 {
754 rmask = 0xFFFFFFFF, gmask = 0;
755 bmask = 0, amask = 0;
756 depth = 32, pitch = image.width*4;
757 } break;
758 case PIXELFORMAT_UNCOMPRESSED_R32G32B32:
759 {
760 rmask = 0xFFFFFFFF, gmask = 0xFFFFFFFF;
761 bmask = 0xFFFFFFFF, amask = 0;
762 depth = 96, pitch = image.width*12;
763 } break;
764 case PIXELFORMAT_UNCOMPRESSED_R32G32B32A32:
765 {
766 rmask = 0xFFFFFFFF, gmask = 0xFFFFFFFF;
767 bmask = 0xFFFFFFFF, amask = 0xFFFFFFFF;
768 depth = 128, pitch = image.width*16;
769 } break;
770 case PIXELFORMAT_UNCOMPRESSED_R16:
771 {
772 rmask = 0xFFFF, gmask = 0;
773 bmask = 0, amask = 0;
774 depth = 16, pitch = image.width*2;
775 } break;
776 case PIXELFORMAT_UNCOMPRESSED_R16G16B16:
777 {
778 rmask = 0xFFFF, gmask = 0xFFFF;
779 bmask = 0xFFFF, amask = 0;
780 depth = 48, pitch = image.width*6;
781 } break;
782 case PIXELFORMAT_UNCOMPRESSED_R16G16B16A16:
783 {
784 rmask = 0xFFFF, gmask = 0xFFFF;
785 bmask = 0xFFFF, amask = 0xFFFF;
786 depth = 64, pitch = image.width*8;
787 } break;
788 default: return; // Compressed formats are not supported
789 }
790
791 iconSurface = SDL_CreateRGBSurfaceFrom( image.data, image.width, image.height, depth, pitch, rmask, gmask, bmask, amask );
792
793 if (iconSurface)
794 {
795 SDL_SetWindowIcon(platform.window, iconSurface);
796 SDL_FreeSurface(iconSurface);
797 }
798 }
799
800 // Set icon for window
801 void SetWindowIcons(Image *images, int count)
802 {
803 TRACELOG(LOG_WARNING, "SetWindowIcons() not available on target platform");
804 }
805
806 // Set title for window
807 void SetWindowTitle(const char *title)
808 {
809 SDL_SetWindowTitle(platform.window, title);
810
811 CORE.Window.title = title;
812 }
813
814 // Set window position on screen (windowed mode)
815 void SetWindowPosition(int x, int y)
816 {
817 SDL_SetWindowPosition(platform.window, x, y);
818
819 CORE.Window.position.x = x;
820 CORE.Window.position.y = y;
821 }
822
823 // Set monitor for the current window
824 void SetWindowMonitor(int monitor)
825 {
826 const int monitorCount = SDL_GetNumVideoDisplays();
827 #if defined(USING_VERSION_SDL3) // SDL3 Migration: Monitor is an id instead of index now, returns 0 on failure
828 if (SDL_GetDisplayProperties(monitor) != 0) // Returns 0 on failure, so a value other than zero indicates that the monitor id is valid
829 #else
830 if ((monitor >= 0) && (monitor < monitorCount))
831 #endif
832 {
833 // NOTE 1: SDL started supporting moving exclusive fullscreen windows between displays on SDL3,
834 // see commit https://github.com/libsdl-org/SDL/commit/3f5ef7dd422057edbcf3e736107e34be4b75d9ba
835 // NOTE 2: A workaround for SDL2 is leaving fullscreen, moving the window, then entering full screen again
836 const bool wasFullscreen = (FLAG_IS_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE))? true : false;
837
838 const int screenWidth = CORE.Window.screen.width;
839 const int screenHeight = CORE.Window.screen.height;
840 SDL_Rect usableBounds;
841
842 #if defined(USING_VERSION_SDL3) // Different style for success checking
843 if (SDL_GetDisplayUsableBounds(monitor, &usableBounds))
844 #else
845 if (SDL_GetDisplayUsableBounds(monitor, &usableBounds) == 0)
846 #endif
847 {
848 if (wasFullscreen == 1) ToggleFullscreen(); // Leave fullscreen
849
850 // If the screen size is larger than the monitor usable area, anchor it on the top left corner, otherwise, center it
851 if ((screenWidth >= usableBounds.w) || (screenHeight >= usableBounds.h))
852 {
853 // NOTE 1: There's a known issue where if the window larger than the target display bounds,
854 // when moving the windows to that display, the window could be clipped back
855 // ending up positioned partly outside the target display
856 // NOTE 2: The workaround for that is, previously to moving the window,
857 // setting the window size to the target display size, so they match
858 // NOTE 3: It wasn't done here because it can not bee assumed that changing
859 // the window size automatically is acceptable behavior by the user
860 SDL_SetWindowPosition(platform.window, usableBounds.x, usableBounds.y);
861 CORE.Window.position.x = usableBounds.x;
862 CORE.Window.position.y = usableBounds.y;
863 }
864 else
865 {
866 const int x = usableBounds.x + (usableBounds.w/2) - (screenWidth/2);
867 const int y = usableBounds.y + (usableBounds.h/2) - (screenHeight/2);
868 SDL_SetWindowPosition(platform.window, x, y);
869 CORE.Window.position.x = x;
870 CORE.Window.position.y = y;
871 }
872
873 if (wasFullscreen == 1) ToggleFullscreen(); // Re-enter fullscreen
874 }
875 else TRACELOG(LOG_WARNING, "SDL: Failed to get selected display usable bounds");
876 }
877 else TRACELOG(LOG_WARNING, "SDL: Failed to find selected monitor");
878 }
879
880 // Set window minimum dimensions (FLAG_WINDOW_RESIZABLE)
881 void SetWindowMinSize(int width, int height)
882 {
883 SDL_SetWindowMinimumSize(platform.window, width, height);
884
885 CORE.Window.screenMin.width = width;
886 CORE.Window.screenMin.height = height;
887 }
888
889 // Set window maximum dimensions (FLAG_WINDOW_RESIZABLE)
890 void SetWindowMaxSize(int width, int height)
891 {
892 SDL_SetWindowMaximumSize(platform.window, width, height);
893
894 CORE.Window.screenMax.width = width;
895 CORE.Window.screenMax.height = height;
896 }
897
898 // Set window dimensions
899 void SetWindowSize(int width, int height)
900 {
901 SDL_SetWindowSize(platform.window, width, height);
902
903 CORE.Window.screen.width = width;
904 CORE.Window.screen.height = height;
905 }
906
907 // Set window opacity, value opacity is between 0.0 and 1.0
908 void SetWindowOpacity(float opacity)
909 {
910 if (opacity >= 1.0f) opacity = 1.0f;
911 else if (opacity <= 0.0f) opacity = 0.0f;
912
913 SDL_SetWindowOpacity(platform.window, opacity);
914 }
915
916 // Set window focused
917 void SetWindowFocused(void)
918 {
919 SDL_RaiseWindow(platform.window);
920 }
921
922 // Get native window handle
923 void *GetWindowHandle(void)
924 {
925 return (void *)platform.window;
926 }
927
928 // Get number of monitors
929 int GetMonitorCount(void)
930 {
931 int monitorCount = 0;
932
933 monitorCount = SDL_GetNumVideoDisplays();
934
935 return monitorCount;
936 }
937
938 // Get current monitor where window is placed
939 int GetCurrentMonitor(void)
940 {
941 int currentMonitor = 0;
942
943 // Be aware that this returns an ID in SDL3 and a Index in SDL2
944 currentMonitor = SDL_GetWindowDisplayIndex(platform.window);
945
946 return currentMonitor;
947 }
948
949 // Get selected monitor position
950 Vector2 GetMonitorPosition(int monitor)
951 {
952 const int monitorCount = SDL_GetNumVideoDisplays();
953 #if defined(USING_VERSION_SDL3) // SDL3 Migration: Monitor is an id instead of index now, returns 0 on failure
954 if (SDL_GetDisplayProperties(monitor) != 0) // Returns 0 on failure, so a value other than zero indicates that the monitor id is valid
955 #else
956 if ((monitor >= 0) && (monitor < monitorCount))
957 #endif
958 {
959 SDL_Rect displayBounds;
960
961 #if defined(USING_VERSION_SDL3)
962 if (SDL_GetDisplayUsableBounds(monitor, &displayBounds))
963 #else
964 if (SDL_GetDisplayUsableBounds(monitor, &displayBounds) == 0)
965 #endif
966 {
967 return (Vector2){ (float)displayBounds.x, (float)displayBounds.y };
968 }
969 else TRACELOG(LOG_WARNING, "SDL: Failed to get selected display usable bounds");
970 }
971 else TRACELOG(LOG_WARNING, "SDL: Failed to find selected monitor");
972 return (Vector2){ 0.0f, 0.0f };
973 }
974
975 // Get selected monitor width (currently used by monitor)
976 int GetMonitorWidth(int monitor)
977 {
978 int width = 0;
979
980 const int monitorCount = SDL_GetNumVideoDisplays();
981 #if defined(USING_VERSION_SDL3) // SDL3 Migration: Monitor is an id instead of index now, returns 0 on failure
982 if (SDL_GetDisplayProperties(monitor) != 0) // Returns 0 on failure, so a value other than zero indicates that the monitor id is valid
983 #else
984 if ((monitor >= 0) && (monitor < monitorCount))
985 #endif
986 {
987 SDL_DisplayMode mode;
988 SDL_GetCurrentDisplayMode(monitor, &mode);
989 width = mode.w;
990 }
991 else TRACELOG(LOG_WARNING, "SDL: Failed to find selected monitor");
992
993 return width;
994 }
995
996 // Get selected monitor height (currently used by monitor)
997 int GetMonitorHeight(int monitor)
998 {
999 int height = 0;
1000
1001 const int monitorCount = SDL_GetNumVideoDisplays();
1002 #if defined(USING_VERSION_SDL3) // SDL3 Migration: Monitor is an id instead of index now, returns 0 on failure
1003 if (SDL_GetDisplayProperties(monitor) != 0) // Returns 0 on failure, so a value other than zero indicates that the monitor id is valid
1004 #else
1005 if ((monitor >= 0) && (monitor < monitorCount))
1006 #endif
1007 {
1008 SDL_DisplayMode mode;
1009 SDL_GetCurrentDisplayMode(monitor, &mode);
1010 height = mode.h;
1011 }
1012 else TRACELOG(LOG_WARNING, "SDL: Failed to find selected monitor");
1013
1014 return height;
1015 }
1016
1017 // Get selected monitor physical width in millimetres
1018 int GetMonitorPhysicalWidth(int monitor)
1019 {
1020 int width = 0;
1021
1022 const int monitorCount = SDL_GetNumVideoDisplays();
1023 #if defined(USING_VERSION_SDL3) // SDL3 Migration: Monitor is an id instead of index now, returns 0 on failure
1024 if (SDL_GetDisplayProperties(monitor) != 0) // Returns 0 on failure, so a value other than zero indicates that the monitor id is valid
1025 #else
1026 if ((monitor >= 0) && (monitor < monitorCount))
1027 #endif
1028 {
1029 float ddpi = 0.0f;
1030 SDL_GetDisplayDPI(monitor, &ddpi, NULL, NULL);
1031 SDL_DisplayMode mode;
1032 SDL_GetCurrentDisplayMode(monitor, &mode);
1033 // Calculate size on inches, then convert to millimeter
1034 if (ddpi > 0.0f) width = (int)((mode.w/ddpi)*25.4f);
1035 }
1036 else TRACELOG(LOG_WARNING, "SDL: Failed to find selected monitor");
1037
1038 return width;
1039 }
1040
1041 // Get selected monitor physical height in millimetres
1042 int GetMonitorPhysicalHeight(int monitor)
1043 {
1044 int height = 0;
1045
1046 const int monitorCount = SDL_GetNumVideoDisplays();
1047 #if defined(USING_VERSION_SDL3) // SDL3 Migration: Monitor is an id instead of index now, returns 0 on failure
1048 if (SDL_GetDisplayProperties(monitor) != 0) // Returns 0 on failure, so a value other than zero indicates that the monitor id is valid
1049 #else
1050 if ((monitor >= 0) && (monitor < monitorCount))
1051 #endif
1052 {
1053 float ddpi = 0.0f;
1054 SDL_GetDisplayDPI(monitor, &ddpi, NULL, NULL);
1055 SDL_DisplayMode mode;
1056 SDL_GetCurrentDisplayMode(monitor, &mode);
1057 // Calculate size on inches, then convert to millimeter
1058 if (ddpi > 0.0f) height = (int)((mode.h/ddpi)*25.4f);
1059 }
1060 else TRACELOG(LOG_WARNING, "SDL: Failed to find selected monitor");
1061
1062 return height;
1063 }
1064
1065 // Get selected monitor refresh rate
1066 int GetMonitorRefreshRate(int monitor)
1067 {
1068 int refresh = 0;
1069
1070 const int monitorCount = SDL_GetNumVideoDisplays();
1071 #if defined(USING_VERSION_SDL3) // SDL3 Migration: Monitor is an id instead of index now, returns 0 on failure
1072 if (SDL_GetDisplayProperties(monitor) != 0) // Returns 0 on failure, so a value other than zero indicates that the monitor id is valid
1073 #else
1074 if ((monitor >= 0) && (monitor < monitorCount))
1075 #endif
1076 {
1077 SDL_DisplayMode mode;
1078 SDL_GetCurrentDisplayMode(monitor, &mode);
1079 refresh = mode.refresh_rate;
1080 }
1081 else TRACELOG(LOG_WARNING, "SDL: Failed to find selected monitor");
1082
1083 return refresh;
1084 }
1085
1086 // Get the human-readable, UTF-8 encoded name of the selected monitor
1087 const char *GetMonitorName(int monitor)
1088 {
1089 const int monitorCount = SDL_GetNumVideoDisplays();
1090
1091 #if defined(USING_VERSION_SDL3) // SDL3 Migration: Monitor is an id instead of index now, returns 0 on failure
1092 if (SDL_GetDisplayProperties(monitor) != 0) // Returns 0 on failure, so a value other than zero indicates that the monitor id is valid
1093 #else
1094 if ((monitor >= 0) && (monitor < monitorCount))
1095 #endif
1096 {
1097 return SDL_GetDisplayName(monitor);
1098 }
1099 else TRACELOG(LOG_WARNING, "SDL: Failed to find selected monitor");
1100
1101 return "";
1102 }
1103
1104 // Get window position XY on monitor
1105 Vector2 GetWindowPosition(void)
1106 {
1107 int x = 0;
1108 int y = 0;
1109
1110 SDL_GetWindowPosition(platform.window, &x, &y);
1111
1112 return (Vector2){ (float)x, (float)y };
1113 }
1114
1115 // Get window scale DPI factor for current monitor
1116 Vector2 GetWindowScaleDPI(void)
1117 {
1118 Vector2 scale = { 1.0f, 1.0f };
1119
1120 #if defined(USING_VERSION_SDL3)
1121 // NOTE: SDL_GetWindowDisplayScale added on SDL3
1122 // REF: https://wiki.libsdl.org/SDL3/SDL_GetWindowDisplayScale
1123 scale.x = SDL_GetWindowDisplayScale(platform.window);
1124 scale.y = scale.x;
1125 #else
1126 // NOTE: SDL_GetWindowDisplayScale not available on SDL2
1127 // TODO: Implement the window scale factor calculation manually
1128 TRACELOG(LOG_WARNING, "GetWindowScaleDPI() not implemented on target platform");
1129 #endif
1130
1131 return scale;
1132 }
1133
1134 // Set clipboard text content
1135 void SetClipboardText(const char *text)
1136 {
1137 SDL_SetClipboardText(text);
1138 }
1139
1140 // Get clipboard text content
1141 const char *GetClipboardText(void)
1142 {
1143 static char buffer[MAX_CLIPBOARD_BUFFER_LENGTH] = { 0 };
1144
1145 char *clipboard = SDL_GetClipboardText();
1146
1147 int clipboardSize = snprintf(buffer, sizeof(buffer), "%s", clipboard);
1148 if (clipboardSize >= MAX_CLIPBOARD_BUFFER_LENGTH)
1149 {
1150 char *truncate = buffer + MAX_CLIPBOARD_BUFFER_LENGTH - 4;
1151 sprintf(truncate, "...");
1152 }
1153
1154 SDL_free(clipboard);
1155
1156 return buffer;
1157 }
1158
1159 // Get clipboard image
1160 Image GetClipboardImage(void)
1161 {
1162 Image image = { 0 };
1163
1164 #if SUPPORT_CLIPBOARD_IMAGE
1165 #if !SUPPORT_MODULE_RTEXTURES
1166 TRACELOG(LOG_WARNING, "Enabling SUPPORT_CLIPBOARD_IMAGE requires SUPPORT_MODULE_RTEXTURES to work properly");
1167 return image;
1168 #endif
1169
1170 // It's nice to have support Bitmap on Linux as well, but not as necessary as Windows
1171 #if !SUPPORT_FILEFORMAT_BMP && defined(_WIN32)
1172 TRACELOG(LOG_WARNING, "WARNING: Enabling SUPPORT_CLIPBOARD_IMAGE requires SUPPORT_FILEFORMAT_BMP, specially on Windows");
1173 return image;
1174 #endif
1175
1176 // From what I've tested applications on Wayland saves images on clipboard as PNG
1177 #if (!SUPPORT_FILEFORMAT_PNG || !SUPPORT_FILEFORMAT_JPG) && !defined(_WIN32)
1178 TRACELOG(LOG_WARNING, "WARNING: Getting image from the clipboard might not work without SUPPORT_FILEFORMAT_PNG or SUPPORT_FILEFORMAT_JPG");
1179 #endif
1180 // Let's hope compiler put these arrays in static memory
1181 const char *imageFormats[] = {
1182 "image/bmp",
1183 "image/png",
1184 "image/jpg",
1185 "image/tiff",
1186 };
1187 const char *imageExtensions[] = {
1188 ".bmp",
1189 ".png",
1190 ".jpg",
1191 ".tiff",
1192 };
1193
1194 size_t dataSize = 0;
1195 void *fileData = NULL;
1196
1197 for (int i = 0; i < SDL_arraysize(imageFormats); i++)
1198 {
1199 // NOTE: This pointer should be free with SDL_free() at some point
1200 fileData = SDL_GetClipboardData(imageFormats[i], &dataSize);
1201
1202 if (fileData)
1203 {
1204 image = LoadImageFromMemory(imageExtensions[i], fileData, (int)dataSize);
1205 if (IsImageValid(image))
1206 {
1207 TRACELOG(LOG_INFO, "Clipboard: Got image from clipboard successfully: %s", imageExtensions[i]);
1208 return image;
1209 }
1210 }
1211 }
1212
1213 if (!IsImageValid(image)) TRACELOG(LOG_WARNING, "Clipboard: Couldn't get clipboard data. ERROR: %s", SDL_GetError());
1214 #endif // SUPPORT_CLIPBOARD_IMAGE
1215
1216 return image;
1217 }
1218
1219 // Show mouse cursor
1220 void ShowCursor(void)
1221 {
1222 #if defined(USING_VERSION_SDL3)
1223 SDL_ShowCursor();
1224 #else
1225 SDL_ShowCursor(SDL_ENABLE);
1226 #endif
1227 CORE.Input.Mouse.cursorHidden = false;
1228 }
1229
1230 // Hides mouse cursor
1231 void HideCursor(void)
1232 {
1233 #if defined(USING_VERSION_SDL3)
1234 SDL_HideCursor();
1235 #else
1236 SDL_ShowCursor(SDL_DISABLE);
1237 #endif
1238 CORE.Input.Mouse.cursorHidden = true;
1239 }
1240
1241 // Enables cursor (unlock cursor)
1242 void EnableCursor(void)
1243 {
1244 SDL_SetRelativeMouseMode(SDL_FALSE);
1245
1246 ShowCursor();
1247 CORE.Input.Mouse.cursorLocked = false;
1248 }
1249
1250 // Disables cursor (lock cursor)
1251 void DisableCursor(void)
1252 {
1253 SDL_SetRelativeMouseMode(SDL_TRUE);
1254
1255 HideCursor();
1256 CORE.Input.Mouse.cursorLocked = true;
1257 }
1258
1259 // Swap back buffer with front buffer (screen drawing)
1260 void SwapScreenBuffer(void)
1261 {
1262 #if defined(GRAPHICS_API_OPENGL_SOFTWARE)
1263 // NOTE: Using a preprocessor condition here because rlCopyFramebuffer() is only declared for software rendering
1264 SDL_Surface *surface = SDL_GetWindowSurface(platform.window);
1265 rlCopyFramebuffer(0, 0, CORE.Window.render.width, CORE.Window.render.height, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, surface->pixels);
1266 SDL_UpdateWindowSurface(platform.window);
1267 #else
1268 SDL_GL_SwapWindow(platform.window);
1269 #endif
1270 }
1271
1272 //----------------------------------------------------------------------------------
1273 // Module Functions Definition: Misc
1274 //----------------------------------------------------------------------------------
1275
1276 // Get elapsed time measure in seconds
1277 double GetTime(void)
1278 {
1279 double time = ((double)SDL_GetPerformanceCounter()/(double)SDL_GetPerformanceFrequency()) - CORE.Time.base;
1280
1281 return time;
1282 }
1283
1284 // Open URL with default system browser (if available)
1285 // NOTE: This function is only safe to use if the provided URL is safe
1286 // A user could craft a malicious string performing another action
1287 // Avoid calling this function with user input non-validated strings
1288 // REF: https://github.com/raysan5/raylib/issues/686
1289 void OpenURL(const char *url)
1290 {
1291 // Security check to (partially) avoid malicious code
1292 if (strchr(url, '\'') != NULL) TRACELOG(LOG_WARNING, "SYSTEM: Provided URL could be potentially malicious, avoid [\'] character");
1293 else SDL_OpenURL(url);
1294 }
1295
1296 //----------------------------------------------------------------------------------
1297 // Module Functions Definition: Inputs
1298 //----------------------------------------------------------------------------------
1299
1300 // Set internal gamepad mappings
1301 int SetGamepadMappings(const char *mappings)
1302 {
1303 const int mappingsLength = strlen(mappings);
1304 char *buffer = (char *)RL_CALLOC(mappingsLength + 1, sizeof(char));
1305 memcpy(buffer, mappings, mappingsLength);
1306 char *p = strtok(buffer, "\n");
1307 bool succeed = true;
1308
1309 while (p != NULL)
1310 {
1311 if (SDL_GameControllerAddMapping(p) == -1)
1312 {
1313 succeed = false;
1314 }
1315 p = strtok(NULL, "\n");
1316 }
1317
1318 RL_FREE(buffer);
1319
1320 // To make return value is consistent with the GLFW version.
1321 return (succeed)? 1 : 0;
1322 }
1323
1324 // Set gamepad vibration
1325 void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor, float duration)
1326 {
1327 if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (duration > 0.0f))
1328 {
1329 if (leftMotor < 0.0f) leftMotor = 0.0f;
1330 if (leftMotor > 1.0f) leftMotor = 1.0f;
1331 if (rightMotor < 0.0f) rightMotor = 0.0f;
1332 if (rightMotor > 1.0f) rightMotor = 1.0f;
1333 if (duration > MAX_GAMEPAD_VIBRATION_TIME) duration = MAX_GAMEPAD_VIBRATION_TIME;
1334
1335 SDL_GameControllerRumble(platform.gamepad[gamepad], (Uint16)(leftMotor*65535.0f), (Uint16)(rightMotor*65535.0f), (Uint32)(duration*1000.0f));
1336 }
1337 }
1338
1339 // Set mouse position XY
1340 void SetMousePosition(int x, int y)
1341 {
1342 SDL_WarpMouseInWindow(platform.window, x, y);
1343
1344 CORE.Input.Mouse.currentPosition = (Vector2){ (float)x, (float)y };
1345 CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;
1346 }
1347
1348 // Set mouse cursor
1349 void SetMouseCursor(int cursor)
1350 {
1351 platform.cursor = SDL_CreateSystemCursor(CursorsLUT[cursor]);
1352 SDL_SetCursor(platform.cursor);
1353
1354 CORE.Input.Mouse.cursor = cursor;
1355 }
1356
1357 // Get physical key name
1358 const char *GetKeyName(int key)
1359 {
1360 return SDL_GetKeyName(key);
1361 }
1362
1363 // Register all input events
1364 void PollInputEvents(void)
1365 {
1366 #if SUPPORT_GESTURES_SYSTEM
1367 // NOTE: Gestures update must be called every frame to reset gestures correctly
1368 // because ProcessGestureEvent() is called on an event, not every frame
1369 UpdateGestures();
1370 #endif
1371
1372 // Reset keys/chars pressed registered
1373 CORE.Input.Keyboard.keyPressedQueueCount = 0;
1374 CORE.Input.Keyboard.charPressedQueueCount = 0;
1375
1376 // Reset mouse wheel
1377 CORE.Input.Mouse.currentWheelMove.x = 0;
1378 CORE.Input.Mouse.currentWheelMove.y = 0;
1379
1380 // Register previous mouse position
1381 if (CORE.Input.Mouse.cursorLocked) CORE.Input.Mouse.currentPosition = (Vector2){ 0.0f, 0.0f };
1382 else CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;
1383
1384 // Reset last gamepad button/axis registered state
1385 for (int i = 0; (i < SDL_NumJoysticks()) && (i < MAX_GAMEPADS); i++)
1386 {
1387 // Check if gamepad is available
1388 if (CORE.Input.Gamepad.ready[i])
1389 {
1390 // Register previous gamepad button states
1391 for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++)
1392 {
1393 CORE.Input.Gamepad.previousButtonState[i][k] = CORE.Input.Gamepad.currentButtonState[i][k];
1394 }
1395 }
1396 }
1397
1398 // Register previous touch states
1399 for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i];
1400
1401 // Map touch position to mouse position for convenience
1402 if (CORE.Input.Touch.pointCount == 0) CORE.Input.Touch.position[0] = CORE.Input.Mouse.currentPosition;
1403
1404 int touchAction = -1; // 0-TOUCH_ACTION_UP, 1-TOUCH_ACTION_DOWN, 2-TOUCH_ACTION_MOVE
1405 bool realTouch = false; // Flag to differentiate real touch gestures from mouse ones
1406
1407 // Register previous keys states
1408 // NOTE: Android supports up to 260 keys
1409 for (int i = 0; i < MAX_KEYBOARD_KEYS; i++)
1410 {
1411 CORE.Input.Keyboard.previousKeyState[i] = CORE.Input.Keyboard.currentKeyState[i];
1412 CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
1413 }
1414
1415 // Register previous mouse states
1416 for (int i = 0; i < MAX_MOUSE_BUTTONS; i++) CORE.Input.Mouse.previousButtonState[i] = CORE.Input.Mouse.currentButtonState[i];
1417
1418 // Poll input events for current platform
1419 //-----------------------------------------------------------------------------
1420 // WARNING: Indexes into this array are obtained by using SDL_Scancode values, not SDL_Keycode values
1421 //const Uint8 *keys = SDL_GetKeyboardState(NULL);
1422 //for (int i = 0; i < 256; i++) CORE.Input.Keyboard.currentKeyState[i] = keys[i];
1423
1424 CORE.Window.resizedLastFrame = false;
1425
1426 if ((CORE.Window.eventWaiting) || (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED) && !FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_ALWAYS_RUN)))
1427 {
1428 SDL_WaitEvent(NULL);
1429 CORE.Time.previous = GetTime();
1430 }
1431
1432 SDL_Event event = { 0 };
1433 while (SDL_PollEvent(&event) != 0)
1434 {
1435 // All input events can be processed after polling
1436 switch (event.type)
1437 {
1438 case SDL_QUIT: CORE.Window.shouldClose = true; break;
1439
1440 case SDL_DROPFILE: // Dropped file
1441 {
1442 if (CORE.Window.dropFileCount == 0)
1443 {
1444 // When a new file is dropped, reserve a fixed number of slots for all possible dropped files
1445 // at the moment limit the number of drops at once to 1024 files but this behaviour should probably be reviewed
1446 // TODO: Pointers should probably be reallocated for any new file added...
1447 CORE.Window.dropFilepaths = (char **)RL_CALLOC(1024, sizeof(char *));
1448
1449 CORE.Window.dropFilepaths[CORE.Window.dropFileCount] = (char *)RL_CALLOC(MAX_FILEPATH_LENGTH, sizeof(char));
1450
1451 #if defined(USING_VERSION_SDL3)
1452 // const char *data; // The text for SDL_EVENT_DROP_TEXT and the file name for SDL_EVENT_DROP_FILE, NULL for other events
1453 // Event memory is now managed by SDL, so it should not be freed in SDL_EVENT_DROP_FILE,
1454 // in case data needs to be hold onto the text in SDL_EVENT_TEXT_EDITING and SDL_EVENT_TEXT_INPUT events,
1455 // a copy is required, SDL_TEXTINPUTEVENT_TEXT_SIZE is no longer necessary and has been removed
1456 strncpy(CORE.Window.dropFilepaths[CORE.Window.dropFileCount], event.drop.data, MAX_FILEPATH_LENGTH - 1);
1457 #else
1458 strncpy(CORE.Window.dropFilepaths[CORE.Window.dropFileCount], event.drop.file, MAX_FILEPATH_LENGTH - 1);
1459 SDL_free(event.drop.file);
1460 #endif
1461
1462 CORE.Window.dropFileCount++;
1463 }
1464 else if (CORE.Window.dropFileCount < 1024)
1465 {
1466 CORE.Window.dropFilepaths[CORE.Window.dropFileCount] = (char *)RL_CALLOC(MAX_FILEPATH_LENGTH, sizeof(char));
1467
1468 #if defined(USING_VERSION_SDL3)
1469 strncpy(CORE.Window.dropFilepaths[CORE.Window.dropFileCount], event.drop.data, MAX_FILEPATH_LENGTH - 1);
1470 #else
1471 strncpy(CORE.Window.dropFilepaths[CORE.Window.dropFileCount], event.drop.file, MAX_FILEPATH_LENGTH - 1);
1472 SDL_free(event.drop.file);
1473 #endif
1474
1475 CORE.Window.dropFileCount++;
1476 }
1477 else TRACELOG(LOG_WARNING, "FILE: Maximum drag and drop files at once is limited to 1024 files!");
1478
1479 } break;
1480
1481 // Window events are also polled (minimized, maximized, close...)
1482
1483 #ifndef USING_VERSION_SDL3
1484 // The SDL_WINDOWEVENT_* events have been moved to top level events, and SDL_WINDOWEVENT has been removed
1485 // In general, handling this change means checking for the individual events instead of first checking for SDL_WINDOWEVENT
1486 // and then checking for window events; Events >= SDL_EVENT_WINDOW_FIRST and <= SDL_EVENT_WINDOW_LAST can be compared
1487 // to see whether it's a window event
1488 case SDL_WINDOWEVENT:
1489 {
1490 switch (event.window.event)
1491 {
1492 #endif
1493 case SDL_WINDOWEVENT_RESIZED:
1494 case SDL_WINDOWEVENT_SIZE_CHANGED:
1495 {
1496 const int width = event.window.data1;
1497 const int height = event.window.data2;
1498 SetupViewport(width, height);
1499
1500 // Consider content scaling if required
1501 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI))
1502 {
1503 CORE.Window.screen.width = (int)(width/GetWindowScaleDPI().x);
1504 CORE.Window.screen.height = (int)(height/GetWindowScaleDPI().y);
1505 }
1506 else
1507 {
1508 CORE.Window.screen.width = width;
1509 CORE.Window.screen.height = height;
1510 }
1511 CORE.Window.currentFbo.width = width;
1512 CORE.Window.currentFbo.height = height;
1513 CORE.Window.resizedLastFrame = true;
1514
1515 #ifndef USING_VERSION_SDL3
1516 // Manually detect if the window was maximized (due to SDL2 restore being unreliable on some platforms)
1517 // to remove the FLAG_WINDOW_MAXIMIZED accordingly
1518 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED))
1519 {
1520 int borderTop = 0;
1521 int borderLeft = 0;
1522 int borderBottom = 0;
1523 int borderRight = 0;
1524 SDL_GetWindowBordersSize(platform.window, &borderTop, &borderLeft, &borderBottom, &borderRight);
1525 SDL_Rect usableBounds;
1526 SDL_GetDisplayUsableBounds(SDL_GetWindowDisplayIndex(platform.window), &usableBounds);
1527
1528 if ((width + borderLeft + borderRight != usableBounds.w) && (height + borderTop + borderBottom != usableBounds.h)) FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED);
1529 }
1530 #endif
1531
1532 #if defined(GRAPHICS_API_OPENGL_SOFTWARE)
1533 swResize(width, height);
1534 #endif
1535 } break;
1536
1537 case SDL_WINDOWEVENT_ENTER: CORE.Input.Mouse.cursorOnScreen = true; break;
1538 case SDL_WINDOWEVENT_LEAVE: CORE.Input.Mouse.cursorOnScreen = false; break;
1539
1540 case SDL_WINDOWEVENT_MINIMIZED:
1541 {
1542 if (!FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED)) FLAG_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED);
1543 } break;
1544 case SDL_WINDOWEVENT_MAXIMIZED:
1545 {
1546 if (!FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED)) FLAG_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED);
1547 } break;
1548 case SDL_WINDOWEVENT_RESTORED:
1549 {
1550 if (!FLAG_IS_SET(SDL_GetWindowFlags(platform.window), SDL_WINDOW_MINIMIZED))
1551 {
1552 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED)) FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_MINIMIZED);
1553 }
1554
1555 #ifdef USING_VERSION_SDL3
1556 if (!FLAG_IS_SET(SDL_GetWindowFlags(platform.window), SDL_WINDOW_MAXIMIZED))
1557 {
1558 if (FLAG_IS_SET(CORE.Window.flags, SDL_WINDOW_MAXIMIZED)) FLAG_CLEAR(CORE.Window.flags, SDL_WINDOW_MAXIMIZED);
1559 }
1560 #endif
1561 } break;
1562
1563 case SDL_WINDOWEVENT_HIDDEN:
1564 {
1565 if (!FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIDDEN)) FLAG_SET(CORE.Window.flags, FLAG_WINDOW_HIDDEN);
1566 } break;
1567 case SDL_WINDOWEVENT_SHOWN:
1568 {
1569 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIDDEN)) FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_HIDDEN);
1570 } break;
1571
1572 case SDL_WINDOWEVENT_FOCUS_GAINED:
1573 {
1574 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED)) FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED);
1575 } break;
1576 case SDL_WINDOWEVENT_FOCUS_LOST:
1577 {
1578 if (!FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED)) FLAG_SET(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED);
1579 } break;
1580
1581 #ifndef USING_VERSION_SDL3
1582 default: break;
1583 }
1584 } break;
1585 #endif
1586
1587 // Keyboard events
1588 case SDL_KEYDOWN:
1589 {
1590 #if defined(USING_VERSION_SDL3)
1591 // SDL3 Migration: The following structures have been removed: SDL_Keysym
1592 KeyboardKey key = ConvertScancodeToKey(event.key.scancode);
1593 #else
1594 KeyboardKey key = ConvertScancodeToKey(event.key.keysym.scancode);
1595 #endif
1596
1597 if (key != KEY_NULL)
1598 {
1599 // If key was up, add it to the key pressed queue
1600 if ((CORE.Input.Keyboard.currentKeyState[key] == 0) && (CORE.Input.Keyboard.keyPressedQueueCount < MAX_KEY_PRESSED_QUEUE))
1601 {
1602 CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = key;
1603 CORE.Input.Keyboard.keyPressedQueueCount++;
1604 }
1605
1606 CORE.Input.Keyboard.currentKeyState[key] = 1;
1607 }
1608
1609 if (event.key.repeat) CORE.Input.Keyboard.keyRepeatInFrame[key] = 1;
1610
1611 // Check for registered exit key to request exit game loop on next iteration
1612 if (CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey]) CORE.Window.shouldClose = true;
1613
1614 } break;
1615
1616 case SDL_KEYUP:
1617 {
1618
1619 #if defined(USING_VERSION_SDL3)
1620 KeyboardKey key = ConvertScancodeToKey(event.key.scancode);
1621 #else
1622 KeyboardKey key = ConvertScancodeToKey(event.key.keysym.scancode);
1623 #endif
1624 if (key != KEY_NULL) CORE.Input.Keyboard.currentKeyState[key] = 0;
1625 } break;
1626
1627 case SDL_TEXTINPUT:
1628 {
1629 // NOTE: event.text.text data comes an UTF-8 text sequence but register codepoints (int)
1630
1631 // Check if there is space available in the queue
1632 if (CORE.Input.Keyboard.charPressedQueueCount < MAX_CHAR_PRESSED_QUEUE)
1633 {
1634 // Add character (codepoint) to the queue
1635
1636 #if defined(USING_VERSION_SDL3)
1637 size_t textLen = strlen(event.text.text);
1638 unsigned int codepoint = (unsigned int)SDL_StepUTF8(&event.text.text, &textLen);
1639 #else
1640 int codepointSize = 0;
1641 int codepoint = GetCodepointNextSDL(event.text.text, &codepointSize);
1642 #endif
1643
1644 CORE.Input.Keyboard.charPressedQueue[CORE.Input.Keyboard.charPressedQueueCount] = codepoint;
1645 CORE.Input.Keyboard.charPressedQueueCount++;
1646 }
1647 } break;
1648
1649 // Check mouse events
1650 case SDL_MOUSEBUTTONDOWN:
1651 {
1652 // NOTE: SDL2 mouse button order is LEFT, MIDDLE, RIGHT, but raylib uses LEFT, RIGHT, MIDDLE like GLFW
1653 // The following conditions align SDL with raylib.h MouseButton enum order
1654 int btn = event.button.button - 1;
1655 if (btn == 2) btn = 1;
1656 else if (btn == 1) btn = 2;
1657
1658 CORE.Input.Mouse.currentButtonState[btn] = 1;
1659 CORE.Input.Touch.currentTouchState[btn] = 1;
1660
1661 touchAction = 1;
1662 } break;
1663 case SDL_MOUSEBUTTONUP:
1664 {
1665 // NOTE: SDL2 mouse button order is LEFT, MIDDLE, RIGHT, but raylib uses LEFT, RIGHT, MIDDLE like GLFW
1666 // The following conditions align SDL with raylib.h MouseButton enum order
1667 int btn = event.button.button - 1;
1668 if (btn == 2) btn = 1;
1669 else if (btn == 1) btn = 2;
1670
1671 CORE.Input.Mouse.currentButtonState[btn] = 0;
1672 CORE.Input.Touch.currentTouchState[btn] = 0;
1673
1674 touchAction = 0;
1675 } break;
1676 case SDL_MOUSEWHEEL:
1677 {
1678 CORE.Input.Mouse.currentWheelMove.x = (float)event.wheel.x;
1679 CORE.Input.Mouse.currentWheelMove.y = (float)event.wheel.y;
1680 } break;
1681 case SDL_MOUSEMOTION:
1682 {
1683 if (CORE.Input.Mouse.cursorLocked)
1684 {
1685 CORE.Input.Mouse.currentPosition.x = (float)event.motion.xrel;
1686 CORE.Input.Mouse.currentPosition.y = (float)event.motion.yrel;
1687 CORE.Input.Mouse.previousPosition = (Vector2){ 0.0f, 0.0f };
1688 }
1689 else
1690 {
1691 CORE.Input.Mouse.currentPosition.x = (float)event.motion.x;
1692 CORE.Input.Mouse.currentPosition.y = (float)event.motion.y;
1693 }
1694
1695 CORE.Input.Touch.position[0] = CORE.Input.Mouse.currentPosition;
1696 touchAction = 2;
1697 } break;
1698
1699 case SDL_FINGERDOWN:
1700 {
1701 UpdateTouchPointsSDL(event.tfinger);
1702 touchAction = 1;
1703 realTouch = true;
1704 } break;
1705 case SDL_FINGERUP:
1706 {
1707 UpdateTouchPointsSDL(event.tfinger);
1708 touchAction = 0;
1709 realTouch = true;
1710 } break;
1711 case SDL_FINGERMOTION:
1712 {
1713 UpdateTouchPointsSDL(event.tfinger);
1714 touchAction = 2;
1715 realTouch = true;
1716 } break;
1717
1718 // Check gamepad events
1719 case SDL_JOYDEVICEADDED:
1720 {
1721 int jid = event.jdevice.which; // Joystick device index
1722
1723 // check if already added at InitPlatform
1724 for (int i = 0; i < MAX_GAMEPADS; i++)
1725 {
1726 if (jid == platform.gamepadId[i])
1727 {
1728 return;
1729 }
1730 }
1731
1732 int nextAvailableSlot = 0;
1733 while (nextAvailableSlot < MAX_GAMEPADS && CORE.Input.Gamepad.ready[nextAvailableSlot])
1734 {
1735 ++nextAvailableSlot;
1736 }
1737
1738 if ((nextAvailableSlot < MAX_GAMEPADS) && !CORE.Input.Gamepad.ready[nextAvailableSlot])
1739 {
1740 platform.gamepad[nextAvailableSlot] = SDL_GameControllerOpen(jid);
1741 platform.gamepadId[nextAvailableSlot] = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(platform.gamepad[nextAvailableSlot]));
1742
1743 if (platform.gamepad[nextAvailableSlot])
1744 {
1745 CORE.Input.Gamepad.ready[nextAvailableSlot] = true;
1746 CORE.Input.Gamepad.axisCount[nextAvailableSlot] = SDL_JoystickNumAxes(SDL_GameControllerGetJoystick(platform.gamepad[nextAvailableSlot]));
1747 CORE.Input.Gamepad.axisState[nextAvailableSlot][GAMEPAD_AXIS_LEFT_TRIGGER] = -1.0f;
1748 CORE.Input.Gamepad.axisState[nextAvailableSlot][GAMEPAD_AXIS_RIGHT_TRIGGER] = -1.0f;
1749 memset(CORE.Input.Gamepad.name[nextAvailableSlot], 0, MAX_GAMEPAD_NAME_LENGTH);
1750 const char *controllerName = SDL_GameControllerNameForIndex(nextAvailableSlot);
1751 if (controllerName != NULL) strncpy(CORE.Input.Gamepad.name[nextAvailableSlot], controllerName, MAX_GAMEPAD_NAME_LENGTH - 1);
1752 else strncpy(CORE.Input.Gamepad.name[nextAvailableSlot], "noname", 6);
1753 }
1754 else TRACELOG(LOG_WARNING, "PLATFORM: Unable to open game controller [ERROR: %s]", SDL_GetError());
1755 }
1756 } break;
1757 case SDL_JOYDEVICEREMOVED:
1758 {
1759 int jid = event.jdevice.which; // Joystick instance id
1760
1761 for (int i = 0; i < MAX_GAMEPADS; i++)
1762 {
1763 if (platform.gamepadId[i] == jid)
1764 {
1765 SDL_GameControllerClose(platform.gamepad[i]);
1766 CORE.Input.Gamepad.ready[i] = false;
1767 memset(CORE.Input.Gamepad.name[i], 0, MAX_GAMEPAD_NAME_LENGTH);
1768 platform.gamepadId[i] = -1;
1769 break;
1770 }
1771 }
1772 } break;
1773 case SDL_CONTROLLERBUTTONDOWN:
1774 {
1775 int button = -1;
1776
1777 #if defined(USING_VERSION_SDL3)
1778 switch (event.gbutton.button)
1779 #else
1780 switch (event.jbutton.button)
1781 #endif
1782 {
1783 case SDL_CONTROLLER_BUTTON_Y: button = GAMEPAD_BUTTON_RIGHT_FACE_UP; break;
1784 case SDL_CONTROLLER_BUTTON_B: button = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break;
1785 case SDL_CONTROLLER_BUTTON_A: button = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break;
1786 case SDL_CONTROLLER_BUTTON_X: button = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break;
1787
1788 case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: button = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break;
1789 case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: button = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break;
1790
1791 case SDL_CONTROLLER_BUTTON_BACK: button = GAMEPAD_BUTTON_MIDDLE_LEFT; break;
1792 case SDL_CONTROLLER_BUTTON_GUIDE: button = GAMEPAD_BUTTON_MIDDLE; break;
1793 case SDL_CONTROLLER_BUTTON_START: button = GAMEPAD_BUTTON_MIDDLE_RIGHT; break;
1794
1795 case SDL_CONTROLLER_BUTTON_DPAD_UP: button = GAMEPAD_BUTTON_LEFT_FACE_UP; break;
1796 case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: button = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break;
1797 case SDL_CONTROLLER_BUTTON_DPAD_DOWN: button = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break;
1798 case SDL_CONTROLLER_BUTTON_DPAD_LEFT: button = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break;
1799
1800 case SDL_CONTROLLER_BUTTON_LEFTSTICK: button = GAMEPAD_BUTTON_LEFT_THUMB; break;
1801 case SDL_CONTROLLER_BUTTON_RIGHTSTICK: button = GAMEPAD_BUTTON_RIGHT_THUMB; break;
1802 default: break;
1803 }
1804
1805 if (button >= 0)
1806 {
1807 for (int i = 0; i < MAX_GAMEPADS; i++)
1808 {
1809 #if defined(USING_VERSION_SDL3)
1810 if (platform.gamepadId[i] == event.gbutton.which)
1811 #else
1812 if (platform.gamepadId[i] == event.jbutton.which)
1813 #endif
1814 {
1815 CORE.Input.Gamepad.currentButtonState[i][button] = 1;
1816 CORE.Input.Gamepad.lastButtonPressed = button;
1817 break;
1818 }
1819 }
1820 }
1821 } break;
1822 case SDL_CONTROLLERBUTTONUP:
1823 {
1824 int button = -1;
1825
1826 #if defined(USING_VERSION_SDL3)
1827 switch (event.gbutton.button)
1828 #else
1829 switch (event.jbutton.button)
1830 #endif
1831 {
1832 case SDL_CONTROLLER_BUTTON_Y: button = GAMEPAD_BUTTON_RIGHT_FACE_UP; break;
1833 case SDL_CONTROLLER_BUTTON_B: button = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break;
1834 case SDL_CONTROLLER_BUTTON_A: button = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break;
1835 case SDL_CONTROLLER_BUTTON_X: button = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break;
1836
1837 case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: button = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break;
1838 case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: button = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break;
1839
1840 case SDL_CONTROLLER_BUTTON_BACK: button = GAMEPAD_BUTTON_MIDDLE_LEFT; break;
1841 case SDL_CONTROLLER_BUTTON_GUIDE: button = GAMEPAD_BUTTON_MIDDLE; break;
1842 case SDL_CONTROLLER_BUTTON_START: button = GAMEPAD_BUTTON_MIDDLE_RIGHT; break;
1843
1844 case SDL_CONTROLLER_BUTTON_DPAD_UP: button = GAMEPAD_BUTTON_LEFT_FACE_UP; break;
1845 case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: button = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break;
1846 case SDL_CONTROLLER_BUTTON_DPAD_DOWN: button = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break;
1847 case SDL_CONTROLLER_BUTTON_DPAD_LEFT: button = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break;
1848
1849 case SDL_CONTROLLER_BUTTON_LEFTSTICK: button = GAMEPAD_BUTTON_LEFT_THUMB; break;
1850 case SDL_CONTROLLER_BUTTON_RIGHTSTICK: button = GAMEPAD_BUTTON_RIGHT_THUMB; break;
1851 default: break;
1852 }
1853
1854 if (button >= 0)
1855 {
1856 for (int i = 0; i < MAX_GAMEPADS; i++)
1857 {
1858 #if defined(USING_VERSION_SDL3)
1859 if (platform.gamepadId[i] == event.gbutton.which)
1860 #else
1861 if (platform.gamepadId[i] == event.jbutton.which)
1862 #endif
1863 {
1864 CORE.Input.Gamepad.currentButtonState[i][button] = 0;
1865 if (CORE.Input.Gamepad.lastButtonPressed == button) CORE.Input.Gamepad.lastButtonPressed = 0;
1866 break;
1867 }
1868 }
1869 }
1870 } break;
1871 case SDL_CONTROLLERAXISMOTION:
1872 {
1873 int axis = -1;
1874
1875 switch (event.jaxis.axis)
1876 {
1877 case SDL_CONTROLLER_AXIS_LEFTX: axis = GAMEPAD_AXIS_LEFT_X; break;
1878 case SDL_CONTROLLER_AXIS_LEFTY: axis = GAMEPAD_AXIS_LEFT_Y; break;
1879 case SDL_CONTROLLER_AXIS_RIGHTX: axis = GAMEPAD_AXIS_RIGHT_X; break;
1880 case SDL_CONTROLLER_AXIS_RIGHTY: axis = GAMEPAD_AXIS_RIGHT_Y; break;
1881 case SDL_CONTROLLER_AXIS_TRIGGERLEFT: axis = GAMEPAD_AXIS_LEFT_TRIGGER; break;
1882 case SDL_CONTROLLER_AXIS_TRIGGERRIGHT: axis = GAMEPAD_AXIS_RIGHT_TRIGGER; break;
1883 default: break;
1884 }
1885
1886 if (axis >= 0)
1887 {
1888 for (int i = 0; i < MAX_GAMEPADS; i++)
1889 {
1890 if (platform.gamepadId[i] == event.jaxis.which)
1891 {
1892 // SDL axis value range is -32768 to 32767, normalizing it to raylib's -1.0 to 1.0f range
1893 float value = event.jaxis.value/(float)32767;
1894 CORE.Input.Gamepad.axisState[i][axis] = value;
1895
1896 // Register button state for triggers in addition to their axes
1897 if ((axis == GAMEPAD_AXIS_LEFT_TRIGGER) || (axis == GAMEPAD_AXIS_RIGHT_TRIGGER))
1898 {
1899 int button = (axis == GAMEPAD_AXIS_LEFT_TRIGGER)? GAMEPAD_BUTTON_LEFT_TRIGGER_2 : GAMEPAD_BUTTON_RIGHT_TRIGGER_2;
1900 int pressed = (value > 0.1f);
1901 CORE.Input.Gamepad.currentButtonState[i][button] = pressed;
1902 if (pressed) CORE.Input.Gamepad.lastButtonPressed = button;
1903 else if (CORE.Input.Gamepad.lastButtonPressed == button) CORE.Input.Gamepad.lastButtonPressed = 0;
1904 }
1905 break;
1906 }
1907 }
1908 }
1909 } break;
1910 default: break;
1911 }
1912
1913 #if SUPPORT_GESTURES_SYSTEM
1914 if (touchAction > -1)
1915 {
1916 // Process mouse events as touches to be able to use mouse-gestures
1917 GestureEvent gestureEvent = { 0 };
1918
1919 // Register touch actions
1920 gestureEvent.touchAction = touchAction;
1921
1922 // Assign a pointer ID
1923 gestureEvent.pointId[0] = 0;
1924
1925 // Register touch points count
1926 gestureEvent.pointCount = 1;
1927
1928 // Register touch points position, only one point registered
1929 if (touchAction == 2 || realTouch) gestureEvent.position[0] = CORE.Input.Touch.position[0];
1930 else gestureEvent.position[0] = GetMousePosition();
1931
1932 // Normalize gestureEvent.position[0] for CORE.Window.screen.width and CORE.Window.screen.height
1933 gestureEvent.position[0].x /= (float)GetScreenWidth();
1934 gestureEvent.position[0].y /= (float)GetScreenHeight();
1935
1936 // Gesture data is sent to gestures-system for processing
1937 ProcessGestureEvent(gestureEvent);
1938
1939 touchAction = -1;
1940 }
1941 #endif
1942 }
1943 //-----------------------------------------------------------------------------
1944 }
1945
1946 //----------------------------------------------------------------------------------
1947 // Module Internal Functions Definition
1948 //----------------------------------------------------------------------------------
1949
1950 // Initialize platform: graphics, inputs and more
1951 int InitPlatform(void)
1952 {
1953 // Initialize SDL internal global state, only required systems
1954 // NOTE: Not all systems need to be initialized, SDL_INIT_AUDIO is not required, managed by miniaudio
1955 int result = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_EVENTS | SDL_INIT_GAMECONTROLLER);
1956 if (result < 0) { TRACELOG(LOG_WARNING, "SDL: Failed to initialize SDL"); return -1; }
1957
1958 // Initialize graphic device: display/window and graphic context
1959 //----------------------------------------------------------------------------
1960 unsigned int flags = 0;
1961 FLAG_SET(flags, SDL_WINDOW_SHOWN);
1962 FLAG_SET(flags, SDL_WINDOW_INPUT_FOCUS);
1963 FLAG_SET(flags, SDL_WINDOW_MOUSE_FOCUS);
1964 FLAG_SET(flags, SDL_WINDOW_MOUSE_CAPTURE); // Window has mouse captured
1965
1966 // Check window creation flags
1967 if (FLAG_IS_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE)) FLAG_SET(flags, SDL_WINDOW_FULLSCREEN);
1968
1969 //if (!FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIDDEN)) FLAG_SET(flags, SDL_WINDOW_HIDDEN);
1970 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_UNDECORATED)) FLAG_SET(flags, SDL_WINDOW_BORDERLESS);
1971 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_RESIZABLE)) FLAG_SET(flags, SDL_WINDOW_RESIZABLE);
1972 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED)) FLAG_SET(flags, SDL_WINDOW_MINIMIZED);
1973 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED)) FLAG_SET(flags, SDL_WINDOW_MAXIMIZED);
1974 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED))
1975 {
1976 FLAG_CLEAR(flags, SDL_WINDOW_INPUT_FOCUS);
1977 FLAG_CLEAR(flags, SDL_WINDOW_MOUSE_FOCUS);
1978 }
1979 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_TOPMOST)) FLAG_SET(flags, SDL_WINDOW_ALWAYS_ON_TOP);
1980 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MOUSE_PASSTHROUGH)) FLAG_CLEAR(flags, SDL_WINDOW_MOUSE_CAPTURE);
1981 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI)) FLAG_SET(flags, SDL_WINDOW_ALLOW_HIGHDPI);
1982
1983 //if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_TRANSPARENT)) FLAG_SET(flags, SDL_WINDOW_TRANSPARENT); // Alternative: SDL_GL_ALPHA_SIZE = 8
1984 //if (FLAG_IS_SET(CORE.Window.flags, FLAG_FULLSCREEN_DESKTOP)) FLAG_SET(flags, SDL_WINDOW_FULLSCREEN_DESKTOP);
1985
1986 // NOTE: Some OpenGL context attributes must be set before window creation
1987
1988 if (rlGetVersion() != RL_OPENGL_SOFTWARE)
1989 {
1990 // Add the flag telling the window to use an OpenGL context
1991 flags |= SDL_WINDOW_OPENGL;
1992
1993 // Check selection OpenGL version
1994 if (rlGetVersion() == RL_OPENGL_21)
1995 {
1996 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
1997 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
1998 }
1999 else if (rlGetVersion() == RL_OPENGL_33)
2000 {
2001 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
2002 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
2003 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
2004 }
2005 else if (rlGetVersion() == RL_OPENGL_43)
2006 {
2007 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
2008 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
2009 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
2010 #if RLGL_ENABLE_OPENGL_DEBUG_CONTEXT
2011 SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); // Enable OpenGL Debug Context
2012 #endif
2013 }
2014 else if (rlGetVersion() == RL_OPENGL_ES_20) // Request OpenGL ES 2.0 context
2015 {
2016 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
2017 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
2018 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
2019 }
2020 else if (rlGetVersion() == RL_OPENGL_ES_30) // Request OpenGL ES 3.0 context
2021 {
2022 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
2023 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
2024 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
2025 }
2026
2027 if (FLAG_IS_SET(CORE.Window.flags, FLAG_MSAA_4X_HINT))
2028 {
2029 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
2030 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
2031 }
2032 }
2033
2034 // Init window
2035 #if defined(USING_VERSION_SDL3)
2036 platform.window = SDL_CreateWindow(CORE.Window.title, CORE.Window.screen.width, CORE.Window.screen.height, flags);
2037
2038
2039 // NOTE: SDL3 no longer enables text input by default,
2040 // it is needed to be enabled manually to keep GetCharPressed() working
2041 // REF: https://github.com/libsdl-org/SDL/commit/72fc6f86e5d605a3787222bc7dc18c5379047f4a
2042 const char *enableOSK = SDL_GetHint(SDL_HINT_ENABLE_SCREEN_KEYBOARD);
2043 if (enableOSK == NULL) SDL_SetHint(SDL_HINT_ENABLE_SCREEN_KEYBOARD, "0");
2044 if (!SDL_StartTextInput(platform.window)) TRACELOG(LOG_WARNING, "SDL: Failed to start text input: %s", SDL_GetError());
2045 if (enableOSK == NULL) SDL_SetHint(SDL_HINT_ENABLE_SCREEN_KEYBOARD, NULL);
2046 #else
2047 platform.window = SDL_CreateWindow(CORE.Window.title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, CORE.Window.screen.width, CORE.Window.screen.height, flags);
2048 #endif
2049
2050 // Init OpenGL context
2051 if (rlGetVersion() != RL_OPENGL_SOFTWARE)
2052 {
2053 platform.glContext = SDL_GL_CreateContext(platform.window);
2054 }
2055
2056 if ((platform.window != NULL) && ((rlGetVersion() == RL_OPENGL_SOFTWARE) || (platform.glContext != NULL)))
2057 {
2058 CORE.Window.ready = true;
2059
2060 SDL_DisplayMode displayMode = { 0 };
2061 SDL_GetCurrentDisplayMode(GetCurrentMonitor(), &displayMode);
2062
2063 CORE.Window.display.width = displayMode.w;
2064 CORE.Window.display.height = displayMode.h;
2065
2066 CORE.Window.render.width = CORE.Window.screen.width;
2067 CORE.Window.render.height = CORE.Window.screen.height;
2068 CORE.Window.currentFbo.width = CORE.Window.render.width;
2069 CORE.Window.currentFbo.height = CORE.Window.render.height;
2070
2071 TRACELOG(LOG_INFO, "DISPLAY: Device initialized successfully %s",
2072 FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI)? "(HighDPI)" : "");
2073 TRACELOG(LOG_INFO, " > Display size: %i x %i", CORE.Window.display.width, CORE.Window.display.height);
2074 TRACELOG(LOG_INFO, " > Screen size: %i x %i", CORE.Window.screen.width, CORE.Window.screen.height);
2075 TRACELOG(LOG_INFO, " > Render size: %i x %i", CORE.Window.render.width, CORE.Window.render.height);
2076 TRACELOG(LOG_INFO, " > Viewport offsets: %i, %i", CORE.Window.renderOffset.x, CORE.Window.renderOffset.y);
2077
2078 if (platform.glContext != NULL)
2079 {
2080 SDL_GL_SetSwapInterval((FLAG_IS_SET(CORE.Window.flags, FLAG_VSYNC_HINT))? 1: 0);
2081
2082 // Load OpenGL extensions
2083 // NOTE: GL procedures address loader is required to load extensions
2084 rlLoadExtensions(SDL_GL_GetProcAddress);
2085 }
2086 }
2087 else
2088 {
2089 TRACELOG(LOG_FATAL, "PLATFORM: Failed to initialize graphics device");
2090 return -1;
2091 }
2092
2093 //----------------------------------------------------------------------------
2094
2095 // Initialize input events system
2096 //----------------------------------------------------------------------------
2097 // Initialize gamepads
2098 for (int i = 0; i < MAX_GAMEPADS; i++)
2099 {
2100 platform.gamepadId[i] = -1; // Set all gamepad initial instance ids as invalid to not conflict with instance id zero
2101 }
2102
2103 int numJoysticks = SDL_NumJoysticks();
2104
2105 for (int i = 0; (i < numJoysticks) && (i < MAX_GAMEPADS); i++)
2106 {
2107 platform.gamepad[i] = SDL_GameControllerOpen(i);
2108 platform.gamepadId[i] = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(platform.gamepad[i]));
2109
2110 if (platform.gamepad[i])
2111 {
2112 CORE.Input.Gamepad.ready[i] = true;
2113 CORE.Input.Gamepad.axisCount[i] = SDL_JoystickNumAxes(SDL_GameControllerGetJoystick(platform.gamepad[i]));
2114 CORE.Input.Gamepad.axisState[i][GAMEPAD_AXIS_LEFT_TRIGGER] = -1.0f;
2115 CORE.Input.Gamepad.axisState[i][GAMEPAD_AXIS_RIGHT_TRIGGER] = -1.0f;
2116 strncpy(CORE.Input.Gamepad.name[i], SDL_GameControllerNameForIndex(i), MAX_GAMEPAD_NAME_LENGTH - 1);
2117 CORE.Input.Gamepad.name[i][MAX_GAMEPAD_NAME_LENGTH - 1] = '\0';
2118 }
2119 else TRACELOG(LOG_WARNING, "PLATFORM: Unable to open game controller [ERROR: %s]", SDL_GetError());
2120 }
2121
2122 // Disable mouse events being interpreted as touch events
2123 // NOTE: This is wanted because there are SDL_FINGER* events available which provide unique data
2124 // Due to the way PollInputEvents() and rgestures.h are currently implemented, setting this won't break SUPPORT_MOUSE_GESTURES
2125 SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
2126
2127 SDL_EventState(SDL_DROPFILE, SDL_ENABLE);
2128 //----------------------------------------------------------------------------
2129
2130 // Initialize timing system
2131 //----------------------------------------------------------------------------
2132 // Get base time from window initialization
2133 CORE.Time.base = (double)SDL_GetPerformanceCounter()/(double)SDL_GetPerformanceFrequency();
2134
2135 #if defined(_WIN32) && SUPPORT_WINMM_HIGHRES_TIMER && !SUPPORT_BUSY_WAIT_LOOP
2136 SDL_SetHint(SDL_HINT_TIMER_RESOLUTION, "1"); // SDL equivalent of timeBeginPeriod() and timeEndPeriod()
2137 #endif
2138
2139 // NOTE: No need to call InitTimer(), let SDL manage it internally
2140 //----------------------------------------------------------------------------
2141
2142 // Initialize storage system
2143 //----------------------------------------------------------------------------
2144 // Define base path for storage
2145 CORE.Storage.basePath = SDL_GetBasePath(); // Alternative: GetWorkingDirectory();
2146 //----------------------------------------------------------------------------
2147
2148 #if defined(USING_VERSION_SDL3)
2149 TRACELOG(LOG_INFO, "PLATFORM: DESKTOP (SDL3): Initialized successfully");
2150 #else
2151 TRACELOG(LOG_INFO, "PLATFORM: DESKTOP (SDL2): Initialized successfully");
2152 #endif
2153
2154 return 0;
2155 }
2156
2157 // Close platform
2158 void ClosePlatform(void)
2159 {
2160 SDL_FreeCursor(platform.cursor); // Free cursor
2161 if (platform.glContext != NULL) SDL_GL_DeleteContext(platform.glContext); // Deinitialize OpenGL context
2162 SDL_DestroyWindow(platform.window);
2163 SDL_Quit(); // Deinitialize SDL internal global state
2164 }
2165
2166 // Scancode to keycode mapping
2167 static KeyboardKey ConvertScancodeToKey(SDL_Scancode sdlScancode)
2168 {
2169 if ((sdlScancode >= 0) && (sdlScancode < SCANCODE_MAPPED_NUM))
2170 {
2171 return mapScancodeToKey[sdlScancode];
2172 }
2173
2174 return KEY_NULL; // No equivalent key in raylib
2175 }
2176
2177 // Get next codepoint in a byte sequence and bytes processed
2178 static int GetCodepointNextSDL(const char *text, int *codepointSize)
2179 {
2180 const char *ptr = text;
2181 int codepoint = 0x3f; // Codepoint (defaults to '?')
2182 *codepointSize = 1;
2183
2184 // Get current codepoint and bytes processed
2185 if (0xf0 == (0xf8 & ptr[0]))
2186 {
2187 // 4 byte UTF-8 codepoint
2188 if (((ptr[1] & 0xC0) ^ 0x80) || ((ptr[2] & 0xC0) ^ 0x80) || ((ptr[3] & 0xC0) ^ 0x80)) { return codepoint; } // 10xxxxxx checks
2189 codepoint = ((0x07 & ptr[0]) << 18) | ((0x3f & ptr[1]) << 12) | ((0x3f & ptr[2]) << 6) | (0x3f & ptr[3]);
2190 *codepointSize = 4;
2191 }
2192 else if (0xe0 == (0xf0 & ptr[0]))
2193 {
2194 // 3 byte UTF-8 codepoint */
2195 if (((ptr[1] & 0xC0) ^ 0x80) || ((ptr[2] & 0xC0) ^ 0x80)) { return codepoint; } // 10xxxxxx checks
2196 codepoint = ((0x0f & ptr[0]) << 12) | ((0x3f & ptr[1]) << 6) | (0x3f & ptr[2]);
2197 *codepointSize = 3;
2198 }
2199 else if (0xc0 == (0xe0 & ptr[0]))
2200 {
2201 // 2 byte UTF-8 codepoint
2202 if ((ptr[1] & 0xC0) ^ 0x80) { return codepoint; } // 10xxxxxx checks
2203 codepoint = ((0x1f & ptr[0]) << 6) | (0x3f & ptr[1]);
2204 *codepointSize = 2;
2205 }
2206 else if (0x00 == (0x80 & ptr[0]))
2207 {
2208 // 1 byte UTF-8 codepoint
2209 codepoint = ptr[0];
2210 *codepointSize = 1;
2211 }
2212
2213 return codepoint;
2214 }
2215
2216 // Update CORE input touch point info from SDL touch data
2217 static void UpdateTouchPointsSDL(SDL_TouchFingerEvent event)
2218 {
2219 #if defined(USING_VERSION_SDL3) // SDL3
2220 int count = 0;
2221 SDL_Finger **fingers = SDL_GetTouchFingers(event.touchID, &count);
2222 CORE.Input.Touch.pointCount = count;
2223
2224 for (int i = 0; i < CORE.Input.Touch.pointCount; i++)
2225 {
2226 SDL_Finger *finger = fingers[i];
2227 CORE.Input.Touch.pointId[i] = finger->id;
2228 CORE.Input.Touch.position[i].x = finger->x*CORE.Window.screen.width;
2229 CORE.Input.Touch.position[i].y = finger->y*CORE.Window.screen.height;
2230 CORE.Input.Touch.currentTouchState[i] = 1;
2231 }
2232
2233 SDL_free(fingers);
2234
2235 #else // SDL2
2236
2237 CORE.Input.Touch.pointCount = SDL_GetNumTouchFingers(event.touchId);
2238
2239 for (int i = 0; i < CORE.Input.Touch.pointCount; i++)
2240 {
2241 SDL_Finger *finger = SDL_GetTouchFinger(event.touchId, i);
2242 CORE.Input.Touch.pointId[i] = (int)finger->id;
2243 CORE.Input.Touch.position[i].x = finger->x*CORE.Window.screen.width;
2244 CORE.Input.Touch.position[i].y = finger->y*CORE.Window.screen.height;
2245 CORE.Input.Touch.currentTouchState[i] = 1;
2246 }
2247 #endif
2248
2249 for (int i = CORE.Input.Touch.pointCount; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.currentTouchState[i] = 0;
2250 }