Debian Codegraph @

src/platforms/rcore_android.c

raw symbols SCIP
1 /**********************************************************************************************
2 *
3 * rcore_android - Functions to manage window, graphics device and inputs
4 *
5 * PLATFORM: ANDROID
6 * - Android (ARM, ARM64)
7 *
8 * LIMITATIONS:
9 * - Limitation 01
10 * - Limitation 02
11 *
12 * POSSIBLE IMPROVEMENTS:
13 * - Improvement 01
14 * - Improvement 02
15 *
16 * CONFIGURATION:
17 * #define RCORE_PLATFORM_CUSTOM_FLAG
18 * Custom flag for rcore on target platform -not used-
19 *
20 * DEPENDENCIES:
21 * - Android NDK: Provides C API to access Android functionality
22 * - gestures: Gestures system for touch-ready devices (or simulated from mouse inputs)
23 *
24 *
25 * LICENSE: zlib/libpng
26 *
27 * Copyright (c) 2013-2026 Ramon Santamaria (@raysan5) and contributors
28 *
29 * This software is provided "as-is", without any express or implied warranty. In no event
30 * will the authors be held liable for any damages arising from the use of this software.
31 *
32 * Permission is granted to anyone to use this software for any purpose, including commercial
33 * applications, and to alter it and redistribute it freely, subject to the following restrictions:
34 *
35 * 1. The origin of this software must not be misrepresented; you must not claim that you
36 * wrote the original software. If you use this software in a product, an acknowledgment
37 * in the product documentation would be appreciated but is not required.
38 *
39 * 2. Altered source versions must be plainly marked as such, and must not be misrepresented
40 * as being the original software.
41 *
42 * 3. This notice may not be removed or altered from any source distribution.
43 *
44 **********************************************************************************************/
45
46 #include <android_native_app_glue.h> // Required for: android_app struct and activity management
47 #include <android/window.h> // Required for: AWINDOW_FLAG_FULLSCREEN definition and others
48 #include <android/log.h> // Required for: Android log system: __android_log_vprint()
49 #include <android/asset_manager.h> // Required for: AAssetManager
50 //#include <android/sensor.h> // Required for: Android sensors functions (accelerometer, gyroscope, light...)
51
52 #include <errno.h> // Required for: error types
53 #include <jni.h> // Required for: JNIEnv and JavaVM [Used in OpenURL() and GetCurrentMonitor()]
54
55 #include <EGL/egl.h> // Native platform windowing system interface
56
57 //----------------------------------------------------------------------------------
58 // Types and Structures Definition
59 //----------------------------------------------------------------------------------
60 typedef struct {
61 // Application data
62 struct android_app *app; // Android activity
63 struct android_poll_source *source; // Android events polling source
64 bool appEnabled; // Flag to detect if app is active ** = true
65 bool contextRebindRequired; // Used to know context rebind required
66
67 // Display data
68 EGLDisplay device; // Native display device (physical screen connection)
69 EGLSurface surface; // Surface to draw on, framebuffers (connected to context)
70 EGLContext context; // Graphic context, mode in which drawing can be done
71 EGLConfig config; // Graphic config
72 } PlatformData;
73
74 typedef struct {
75 // Store data for both Hover and Touch events
76 // Used to ignore Hover events which are interpreted as Touch events
77 int32_t pointCount; // Number of touch points active
78 int32_t pointId[MAX_TOUCH_POINTS]; // Point identifiers
79 Vector2 position[MAX_TOUCH_POINTS]; // Touch position on screen
80
81 int32_t hoverPoints[MAX_TOUCH_POINTS]; // Hover Points
82 } TouchRaw;
83
84 //----------------------------------------------------------------------------------
85 // Global Variables Definition
86 //----------------------------------------------------------------------------------
87 extern CoreData CORE; // Global CORE state context
88 static PlatformData platform = { 0 }; // Platform specific data
89
90 //----------------------------------------------------------------------------------
91 // Local Variables Definition
92 //----------------------------------------------------------------------------------
93 #define KEYCODE_MAP_SIZE 162
94 static const KeyboardKey mapKeycode[KEYCODE_MAP_SIZE] = {
95 KEY_NULL, // AKEYCODE_UNKNOWN
96 0, // AKEYCODE_SOFT_LEFT
97 0, // AKEYCODE_SOFT_RIGHT
98 0, // AKEYCODE_HOME
99 KEY_BACK, // AKEYCODE_BACK
100 0, // AKEYCODE_CALL
101 0, // AKEYCODE_ENDCALL
102 KEY_ZERO, // AKEYCODE_0
103 KEY_ONE, // AKEYCODE_1
104 KEY_TWO, // AKEYCODE_2
105 KEY_THREE, // AKEYCODE_3
106 KEY_FOUR, // AKEYCODE_4
107 KEY_FIVE, // AKEYCODE_5
108 KEY_SIX, // AKEYCODE_6
109 KEY_SEVEN, // AKEYCODE_7
110 KEY_EIGHT, // AKEYCODE_8
111 KEY_NINE, // AKEYCODE_9
112 0, // AKEYCODE_STAR
113 0, // AKEYCODE_POUND
114 KEY_UP, // AKEYCODE_DPAD_UP
115 KEY_DOWN, // AKEYCODE_DPAD_DOWN
116 KEY_LEFT, // AKEYCODE_DPAD_LEFT
117 KEY_RIGHT, // AKEYCODE_DPAD_RIGHT
118 0, // AKEYCODE_DPAD_CENTER
119 KEY_VOLUME_UP, // AKEYCODE_VOLUME_UP
120 KEY_VOLUME_DOWN, // AKEYCODE_VOLUME_DOWN
121 0, // AKEYCODE_POWER
122 0, // AKEYCODE_CAMERA
123 0, // AKEYCODE_CLEAR
124 KEY_A, // AKEYCODE_A
125 KEY_B, // AKEYCODE_B
126 KEY_C, // AKEYCODE_C
127 KEY_D, // AKEYCODE_D
128 KEY_E, // AKEYCODE_E
129 KEY_F, // AKEYCODE_F
130 KEY_G, // AKEYCODE_G
131 KEY_H, // AKEYCODE_H
132 KEY_I, // AKEYCODE_I
133 KEY_J, // AKEYCODE_J
134 KEY_K, // AKEYCODE_K
135 KEY_L, // AKEYCODE_L
136 KEY_M, // AKEYCODE_M
137 KEY_N, // AKEYCODE_N
138 KEY_O, // AKEYCODE_O
139 KEY_P, // AKEYCODE_P
140 KEY_Q, // AKEYCODE_Q
141 KEY_R, // AKEYCODE_R
142 KEY_S, // AKEYCODE_S
143 KEY_T, // AKEYCODE_T
144 KEY_U, // AKEYCODE_U
145 KEY_V, // AKEYCODE_V
146 KEY_W, // AKEYCODE_W
147 KEY_X, // AKEYCODE_X
148 KEY_Y, // AKEYCODE_Y
149 KEY_Z, // AKEYCODE_Z
150 KEY_COMMA, // AKEYCODE_COMMA
151 KEY_PERIOD, // AKEYCODE_PERIOD
152 KEY_LEFT_ALT, // AKEYCODE_ALT_LEFT
153 KEY_RIGHT_ALT, // AKEYCODE_ALT_RIGHT
154 KEY_LEFT_SHIFT, // AKEYCODE_SHIFT_LEFT
155 KEY_RIGHT_SHIFT, // AKEYCODE_SHIFT_RIGHT
156 KEY_TAB, // AKEYCODE_TAB
157 KEY_SPACE, // AKEYCODE_SPACE
158 0, // AKEYCODE_SYM
159 0, // AKEYCODE_EXPLORER
160 0, // AKEYCODE_ENVELOPE
161 KEY_ENTER, // AKEYCODE_ENTER
162 KEY_BACKSPACE, // AKEYCODE_DEL
163 KEY_GRAVE, // AKEYCODE_GRAVE
164 KEY_MINUS, // AKEYCODE_MINUS
165 KEY_EQUAL, // AKEYCODE_EQUALS
166 KEY_LEFT_BRACKET, // AKEYCODE_LEFT_BRACKET
167 KEY_RIGHT_BRACKET, // AKEYCODE_RIGHT_BRACKET
168 KEY_BACKSLASH, // AKEYCODE_BACKSLASH
169 KEY_SEMICOLON, // AKEYCODE_SEMICOLON
170 KEY_APOSTROPHE, // AKEYCODE_APOSTROPHE
171 KEY_SLASH, // AKEYCODE_SLASH
172 0, // AKEYCODE_AT
173 0, // AKEYCODE_NUM
174 0, // AKEYCODE_HEADSETHOOK
175 0, // AKEYCODE_FOCUS
176 0, // AKEYCODE_PLUS
177 KEY_MENU, // AKEYCODE_MENU
178 0, // AKEYCODE_NOTIFICATION
179 0, // AKEYCODE_SEARCH
180 0, // AKEYCODE_MEDIA_PLAY_PAUSE
181 0, // AKEYCODE_MEDIA_STOP
182 0, // AKEYCODE_MEDIA_NEXT
183 0, // AKEYCODE_MEDIA_PREVIOUS
184 0, // AKEYCODE_MEDIA_REWIND
185 0, // AKEYCODE_MEDIA_FAST_FORWARD
186 0, // AKEYCODE_MUTE
187 KEY_PAGE_UP, // AKEYCODE_PAGE_UP
188 KEY_PAGE_DOWN, // AKEYCODE_PAGE_DOWN
189 0, // AKEYCODE_PICTSYMBOLS
190 0, // AKEYCODE_SWITCH_CHARSET
191 0, // AKEYCODE_BUTTON_A
192 0, // AKEYCODE_BUTTON_B
193 0, // AKEYCODE_BUTTON_C
194 0, // AKEYCODE_BUTTON_X
195 0, // AKEYCODE_BUTTON_Y
196 0, // AKEYCODE_BUTTON_Z
197 0, // AKEYCODE_BUTTON_L1
198 0, // AKEYCODE_BUTTON_R1
199 0, // AKEYCODE_BUTTON_L2
200 0, // AKEYCODE_BUTTON_R2
201 0, // AKEYCODE_BUTTON_THUMBL
202 0, // AKEYCODE_BUTTON_THUMBR
203 0, // AKEYCODE_BUTTON_START
204 0, // AKEYCODE_BUTTON_SELECT
205 0, // AKEYCODE_BUTTON_MODE
206 KEY_ESCAPE, // AKEYCODE_ESCAPE
207 KEY_DELETE, // AKEYCODE_FORWARD_DELL
208 KEY_LEFT_CONTROL, // AKEYCODE_CTRL_LEFT
209 KEY_RIGHT_CONTROL, // AKEYCODE_CTRL_RIGHT
210 KEY_CAPS_LOCK, // AKEYCODE_CAPS_LOCK
211 KEY_SCROLL_LOCK, // AKEYCODE_SCROLL_LOCK
212 KEY_LEFT_SUPER, // AKEYCODE_META_LEFT
213 KEY_RIGHT_SUPER, // AKEYCODE_META_RIGHT
214 0, // AKEYCODE_FUNCTION
215 KEY_PRINT_SCREEN, // AKEYCODE_SYSRQ
216 KEY_PAUSE, // AKEYCODE_BREAK
217 KEY_HOME, // AKEYCODE_MOVE_HOME
218 KEY_END, // AKEYCODE_MOVE_END
219 KEY_INSERT, // AKEYCODE_INSERT
220 0, // AKEYCODE_FORWARD
221 0, // AKEYCODE_MEDIA_PLAY
222 0, // AKEYCODE_MEDIA_PAUSE
223 0, // AKEYCODE_MEDIA_CLOSE
224 0, // AKEYCODE_MEDIA_EJECT
225 0, // AKEYCODE_MEDIA_RECORD
226 KEY_F1, // AKEYCODE_F1
227 KEY_F2, // AKEYCODE_F2
228 KEY_F3, // AKEYCODE_F3
229 KEY_F4, // AKEYCODE_F4
230 KEY_F5, // AKEYCODE_F5
231 KEY_F6, // AKEYCODE_F6
232 KEY_F7, // AKEYCODE_F7
233 KEY_F8, // AKEYCODE_F8
234 KEY_F9, // AKEYCODE_F9
235 KEY_F10, // AKEYCODE_F10
236 KEY_F11, // AKEYCODE_F11
237 KEY_F12, // AKEYCODE_F12
238 KEY_NUM_LOCK, // AKEYCODE_NUM_LOCK
239 KEY_KP_0, // AKEYCODE_NUMPAD_0
240 KEY_KP_1, // AKEYCODE_NUMPAD_1
241 KEY_KP_2, // AKEYCODE_NUMPAD_2
242 KEY_KP_3, // AKEYCODE_NUMPAD_3
243 KEY_KP_4, // AKEYCODE_NUMPAD_4
244 KEY_KP_5, // AKEYCODE_NUMPAD_5
245 KEY_KP_6, // AKEYCODE_NUMPAD_6
246 KEY_KP_7, // AKEYCODE_NUMPAD_7
247 KEY_KP_8, // AKEYCODE_NUMPAD_8
248 KEY_KP_9, // AKEYCODE_NUMPAD_9
249 KEY_KP_DIVIDE, // AKEYCODE_NUMPAD_DIVIDE
250 KEY_KP_MULTIPLY, // AKEYCODE_NUMPAD_MULTIPLY
251 KEY_KP_SUBTRACT, // AKEYCODE_NUMPAD_SUBTRACT
252 KEY_KP_ADD, // AKEYCODE_NUMPAD_ADD
253 KEY_KP_DECIMAL, // AKEYCODE_NUMPAD_DOT
254 0, // AKEYCODE_NUMPAD_COMMA
255 KEY_KP_ENTER, // AKEYCODE_NUMPAD_ENTER
256 KEY_KP_EQUAL // AKEYCODE_NUMPAD_EQUALS
257 };
258
259 static TouchRaw touchRaw = { 0 };
260
261 //----------------------------------------------------------------------------------
262 // Module Internal Functions Declaration
263 //----------------------------------------------------------------------------------
264 int InitPlatform(void); // Initialize platform (graphics, inputs and more)
265 void ClosePlatform(void); // Close platform
266
267 static void AndroidCommandCallback(struct android_app *app, int32_t cmd); // Process Android activity lifecycle commands
268 static int32_t AndroidInputCallback(struct android_app *app, AInputEvent *event); // Process Android inputs
269 static GamepadButton AndroidTranslateGamepadButton(int button); // Map Android gamepad button to raylib gamepad button
270
271 static void SetupFramebuffer(int width, int height); // Setup main framebuffer (required by InitPlatform())
272
273 static int android_read(void *cookie, char *buf, int size);
274 static int android_write(void *cookie, const char *buf, int size);
275 static fpos_t android_seek(void *cookie, fpos_t offset, int whence);
276 static int android_close(void *cookie);
277
278 // WARNING: fopen() calls are intercepted via linker flag -Wl,--wrap=fopen: the linker renames
279 // the original fopen -> __real_fopen and redirects all call sites to __wrap_fopen
280 // The flag MUST be applied at every final link step that needs wrapping;
281 // it has no effect when only building a static archive (.a)
282 //
283 // STATIC library (.a) — wrapping deferred to consumer's final link step:
284 // both raylib and consumer fopen calls are wrapped together in one link
285 // CMake: handled automatically — the PUBLIC flag propagates as INTERFACE_LINK_OPTIONS
286 // to the consumer's final link via target_link_libraries
287 // Make: pass -Wl,--wrap=fopen to the linker command producing the final artifact
288 // build.zig: pass -Wl,--wrap=fopen to the linker command producing the final artifact
289 // custom: pass -Wl,--wrap=fopen to the linker command producing the final artifact
290 //
291 // SHARED library (.so) — wrapping is self-contained:
292 // only fopen calls linked into the .so are wrapped; the consumer's own fopen calls
293 // are NOT wrapped unless the consumer also links with -Wl,--wrap=fopen independently
294 // CMake: handled automatically — CMakeLists.txt sets target_link_options(raylib PUBLIC
295 // -Wl,--wrap=fopen) which applies the flag to the .so link;
296 // only raylib internals are wrapped, app code requires a separate flag
297 // Make: handled automatically — src/Makefile sets LDFLAGS += -Wl,--wrap=fopen;
298 // only raylib internals are wrapped, app code requires a separate flag
299 // build.zig: NOT supported — std.Build has no dedicated linker wrap helper, the flag
300 // is not correctly applied at the .so link step
301 // custom: apply -Wl,--wrap=fopen to the linker command producing the .so
302 FILE *__real_fopen(const char *fileName, const char *mode); // Real fopen, provided by the linker (--wrap=fopen)
303 FILE *__wrap_fopen(const char *fileName, const char *mode); // Replacement for fopen()
304
305 FILE *funopen(const void *cookie, int (*readfn)(void *, char *, int), int (*writefn)(void *, const char *, int),
306 fpos_t (*seekfn)(void *, fpos_t, int), int (*closefn)(void *));
307
308 //----------------------------------------------------------------------------------
309 // Module Functions Declaration
310 //----------------------------------------------------------------------------------
311 // NOTE: Functions declaration is provided by raylib.h
312
313 //----------------------------------------------------------------------------------
314 // Module Functions Definition: Application
315 //----------------------------------------------------------------------------------
316
317 // To allow easier porting to android, allow the user to define a
318 // custom main function which is called from android_main
319 extern int main(int argc, char *argv[]);
320
321 // Android main function
322 void android_main(struct android_app *app)
323 {
324 char arg0[] = "raylib"; // NOTE: argv[] are mutable
325 platform.app = app;
326
327 // NOTE: Return from main is ignored
328 (void)main(1, (char *[]) { arg0, NULL });
329
330 // Request to end the native activity
331 ANativeActivity_finish(app->activity);
332
333 // Android ALooper_pollOnce() variables
334 int pollResult = 0;
335 int pollEvents = 0;
336
337 // Waiting for application events before complete finishing
338 while (!app->destroyRequested)
339 {
340 // Poll all events until return value TIMEOUT is reached, meaning no events left to process
341 while ((pollResult = ALooper_pollOnce(0, NULL, &pollEvents, (void **)&platform.source)) > ALOOPER_POLL_TIMEOUT)
342 {
343 if (platform.source != NULL) platform.source->process(app, platform.source);
344 }
345 }
346 }
347
348 // NOTE: Add this to header (if apps really need it)
349 struct android_app *GetAndroidApp(void)
350 {
351 return platform.app;
352 }
353
354 //----------------------------------------------------------------------------------
355 // Module Functions Definition: Window and Graphics Device
356 //----------------------------------------------------------------------------------
357
358 // Check if application should close
359 bool WindowShouldClose(void)
360 {
361 if (CORE.Window.ready) return CORE.Window.shouldClose;
362 else return true;
363 }
364
365 // Toggle fullscreen mode
366 void ToggleFullscreen(void)
367 {
368 TRACELOG(LOG_WARNING, "ToggleFullscreen() not available on target platform");
369 }
370
371 // Toggle borderless windowed mode
372 void ToggleBorderlessWindowed(void)
373 {
374 TRACELOG(LOG_WARNING, "ToggleBorderlessWindowed() not available on target platform");
375 }
376
377 // Set window state: maximized, if resizable
378 void MaximizeWindow(void)
379 {
380 TRACELOG(LOG_WARNING, "MaximizeWindow() not available on target platform");
381 }
382
383 // Set window state: minimized
384 void MinimizeWindow(void)
385 {
386 TRACELOG(LOG_WARNING, "MinimizeWindow() not available on target platform");
387 }
388
389 // Restore window from being minimized/maximized
390 void RestoreWindow(void)
391 {
392 TRACELOG(LOG_WARNING, "RestoreWindow() not available on target platform");
393 }
394
395 // Set window configuration state using flags
396 void SetWindowState(unsigned int flags)
397 {
398 if (!CORE.Window.ready) TRACELOG(LOG_WARNING, "WINDOW: SetWindowState does nothing before window initialization, Use \"SetConfigFlags\" instead");
399
400 // State change: FLAG_WINDOW_ALWAYS_RUN
401 if (FLAG_IS_SET(flags, FLAG_WINDOW_ALWAYS_RUN)) FLAG_SET(CORE.Window.flags, FLAG_WINDOW_ALWAYS_RUN);
402 }
403
404 // Clear window configuration state flags
405 void ClearWindowState(unsigned int flags)
406 {
407 // State change: FLAG_WINDOW_ALWAYS_RUN
408 if (FLAG_IS_SET(flags, FLAG_WINDOW_ALWAYS_RUN)) FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_ALWAYS_RUN);
409 }
410
411 // Set icon for window
412 void SetWindowIcon(Image image)
413 {
414 TRACELOG(LOG_WARNING, "SetWindowIcon() not available on target platform");
415 }
416
417 // Set icon for window
418 void SetWindowIcons(Image *images, int count)
419 {
420 TRACELOG(LOG_WARNING, "SetWindowIcons() not available on target platform");
421 }
422
423 // Set title for window
424 void SetWindowTitle(const char *title)
425 {
426 CORE.Window.title = title;
427 }
428
429 // Set window position on screen (windowed mode)
430 void SetWindowPosition(int x, int y)
431 {
432 TRACELOG(LOG_WARNING, "SetWindowPosition() not available on target platform");
433 }
434
435 // Set monitor for the current window
436 void SetWindowMonitor(int monitor)
437 {
438 TRACELOG(LOG_WARNING, "SetWindowMonitor() not available on target platform");
439 }
440
441 // Set window minimum dimensions (FLAG_WINDOW_RESIZABLE)
442 void SetWindowMinSize(int width, int height)
443 {
444 CORE.Window.screenMin.width = width;
445 CORE.Window.screenMin.height = height;
446 }
447
448 // Set window maximum dimensions (FLAG_WINDOW_RESIZABLE)
449 void SetWindowMaxSize(int width, int height)
450 {
451 CORE.Window.screenMax.width = width;
452 CORE.Window.screenMax.height = height;
453 }
454
455 // Set window dimensions
456 void SetWindowSize(int width, int height)
457 {
458 TRACELOG(LOG_WARNING, "SetWindowSize() not available on target platform");
459 }
460
461 // Set window opacity, value opacity is between 0.0 and 1.0
462 void SetWindowOpacity(float opacity)
463 {
464 TRACELOG(LOG_WARNING, "SetWindowOpacity() not available on target platform");
465 }
466
467 // Set window focused
468 void SetWindowFocused(void)
469 {
470 TRACELOG(LOG_WARNING, "SetWindowFocused() not available on target platform");
471 }
472
473 // Get native window handle
474 void *GetWindowHandle(void)
475 {
476 TRACELOG(LOG_WARNING, "GetWindowHandle() not implemented on target platform");
477 return NULL;
478 }
479
480 // Get number of monitors
481 int GetMonitorCount(void)
482 {
483 TRACELOG(LOG_WARNING, "GetMonitorCount() not implemented on target platform");
484 return 1;
485 }
486
487 // Get current monitor where window is placed
488 int GetCurrentMonitor(void)
489 {
490 int displayId = -1;
491 JNIEnv *env = NULL;
492 JavaVM *vm = platform.app->activity->vm;
493 (*vm)->AttachCurrentThread(vm, &env, NULL);
494
495 jobject activity = platform.app->activity->clazz;
496 jclass activityClass = (*env)->GetObjectClass(env, activity);
497
498 jmethodID getDisplayMethod = (*env)->GetMethodID(env, activityClass, "getDisplay", "()Landroid/view/Display;");
499
500 jobject display = (*env)->CallObjectMethod(env, activity, getDisplayMethod);
501
502 if (display == NULL)
503 {
504 TRACELOG(LOG_ERROR, "GetCurrentMonitor() couldn't get the display object");
505 }
506 else
507 {
508 jclass displayClass = (*env)->FindClass(env, "android/view/Display");
509 jmethodID getDisplayIdMethod = (*env)->GetMethodID(env, displayClass, "getDisplayId", "()I");
510 displayId = (int)(*env)->CallIntMethod(env, display, getDisplayIdMethod);
511 (*env)->DeleteLocalRef(env, displayClass);
512 }
513
514 (*env)->DeleteLocalRef(env, activityClass);
515 (*env)->DeleteLocalRef(env, display);
516
517 (*vm)->DetachCurrentThread(vm);
518 return displayId;
519 }
520
521 // Get selected monitor position
522 Vector2 GetMonitorPosition(int monitor)
523 {
524 TRACELOG(LOG_WARNING, "GetMonitorPosition() not implemented on target platform");
525 return (Vector2){ 0, 0 };
526 }
527
528 // Get selected monitor width (currently used by monitor)
529 int GetMonitorWidth(int monitor)
530 {
531 TRACELOG(LOG_WARNING, "GetMonitorWidth() not implemented on target platform");
532 return 0;
533 }
534
535 // Get selected monitor height (currently used by monitor)
536 int GetMonitorHeight(int monitor)
537 {
538 TRACELOG(LOG_WARNING, "GetMonitorHeight() not implemented on target platform");
539 return 0;
540 }
541
542 // Get selected monitor physical width in millimetres
543 // NOTE: It seems to return a slightly underestimated value on some devices
544 int GetMonitorPhysicalWidth(int monitor)
545 {
546 int widthPixels = ANativeWindow_getWidth(platform.app->window);
547 float dpi = AConfiguration_getDensity(platform.app->config);
548 return (widthPixels/dpi)*25.4f;
549 }
550
551 // Get selected monitor physical height in millimetres
552 // NOTE: It seems to return a slightly underestimated value on some devices
553 int GetMonitorPhysicalHeight(int monitor)
554 {
555 int heightPixels = ANativeWindow_getHeight(platform.app->window);
556 float dpi = AConfiguration_getDensity(platform.app->config);
557 return (heightPixels/dpi)*25.4f;
558 }
559
560 // Get selected monitor refresh rate
561 int GetMonitorRefreshRate(int monitor)
562 {
563 TRACELOG(LOG_WARNING, "GetMonitorRefreshRate() not implemented on target platform");
564 return 0;
565 }
566
567 // Get the human-readable, UTF-8 encoded name of the selected monitor
568 const char *GetMonitorName(int monitor)
569 {
570 TRACELOG(LOG_WARNING, "GetMonitorName() not implemented on target platform");
571 return "";
572 }
573
574 // Get window position XY on monitor
575 Vector2 GetWindowPosition(void)
576 {
577 TRACELOG(LOG_WARNING, "GetWindowPosition() not implemented on target platform");
578 return (Vector2){ 0, 0 };
579 }
580
581 // Get window scale DPI factor for current monitor
582 Vector2 GetWindowScaleDPI(void)
583 {
584 int density = AConfiguration_getDensity(platform.app->config);
585 float scale = (float)density/160;
586 return (Vector2){ scale, scale };
587 }
588
589 // Set clipboard text content
590 void SetClipboardText(const char *text)
591 {
592 TRACELOG(LOG_WARNING, "SetClipboardText() not implemented on target platform");
593 }
594
595 // Get clipboard text content
596 // NOTE: returned string is allocated and freed by GLFW
597 const char *GetClipboardText(void)
598 {
599 TRACELOG(LOG_WARNING, "GetClipboardText() not implemented on target platform");
600 return NULL;
601 }
602
603 // Get clipboard image
604 Image GetClipboardImage(void)
605 {
606 Image image = { 0 };
607
608 TRACELOG(LOG_WARNING, "GetClipboardImage() not implemented on target platform");
609
610 return image;
611 }
612
613 // Show mouse cursor
614 void ShowCursor(void)
615 {
616 CORE.Input.Mouse.cursorHidden = false;
617 }
618
619 // Hides mouse cursor
620 void HideCursor(void)
621 {
622 CORE.Input.Mouse.cursorHidden = true;
623 }
624
625 // Enables cursor (unlock cursor)
626 void EnableCursor(void)
627 {
628 // Set cursor position in the middle
629 SetMousePosition(CORE.Window.screen.width/2, CORE.Window.screen.height/2);
630
631 CORE.Input.Mouse.cursorLocked = false;
632 }
633
634 // Disables cursor (lock cursor)
635 void DisableCursor(void)
636 {
637 // Set cursor position in the middle
638 SetMousePosition(CORE.Window.screen.width/2, CORE.Window.screen.height/2);
639
640 CORE.Input.Mouse.cursorLocked = true;
641 }
642
643 // Swap back buffer with front buffer (screen drawing)
644 void SwapScreenBuffer(void)
645 {
646 if (platform.surface != EGL_NO_SURFACE) eglSwapBuffers(platform.device, platform.surface);
647 }
648
649 //----------------------------------------------------------------------------------
650 // Module Functions Definition: Misc
651 //----------------------------------------------------------------------------------
652
653 // Get elapsed time measure in seconds since InitTimer()
654 double GetTime(void)
655 {
656 double time = 0.0;
657 struct timespec ts = { 0 };
658 clock_gettime(CLOCK_MONOTONIC, &ts);
659 unsigned long long int nanoSeconds = (unsigned long long int)ts.tv_sec*1000000000LLU + (unsigned long long int)ts.tv_nsec;
660
661 time = (double)(nanoSeconds - CORE.Time.base)*1e-9; // Elapsed time since InitTimer()
662
663 return time;
664 }
665
666 // Open URL with default system browser (if available)
667 // NOTE: This function is only safe to use if the provided URL is safe
668 // A user could craft a malicious string performing another action
669 // Avoid calling this function with user input non-validated strings
670 void OpenURL(const char *url)
671 {
672 // Security check to (partially) avoid malicious code
673 if (strchr(url, '\'') != NULL) TRACELOG(LOG_WARNING, "SYSTEM: Provided URL could be potentially malicious, avoid [\'] character");
674 else
675 {
676 JNIEnv *env = NULL;
677 JavaVM *vm = platform.app->activity->vm;
678 (*vm)->AttachCurrentThread(vm, &env, NULL);
679
680 jstring urlString = (*env)->NewStringUTF(env, url);
681 jclass uriClass = (*env)->FindClass(env, "android/net/Uri");
682 jmethodID uriParse = (*env)->GetStaticMethodID(env, uriClass, "parse", "(Ljava/lang/String;)Landroid/net/Uri;");
683 jobject uri = (*env)->CallStaticObjectMethod(env, uriClass, uriParse, urlString);
684
685 jclass intentClass = (*env)->FindClass(env, "android/content/Intent");
686 jfieldID actionViewId = (*env)->GetStaticFieldID(env, intentClass, "ACTION_VIEW", "Ljava/lang/String;");
687 jobject actionView = (*env)->GetStaticObjectField(env, intentClass, actionViewId);
688 jmethodID newIntent = (*env)->GetMethodID(env, intentClass, "<init>", "(Ljava/lang/String;Landroid/net/Uri;)V");
689 jobject intent = (*env)->AllocObject(env, intentClass);
690
691 (*env)->CallVoidMethod(env, intent, newIntent, actionView, uri);
692 jclass activityClass = (*env)->FindClass(env, "android/app/Activity");
693 jmethodID startActivity = (*env)->GetMethodID(env, activityClass, "startActivity", "(Landroid/content/Intent;)V");
694 (*env)->CallVoidMethod(env, platform.app->activity->clazz, startActivity, intent);
695
696 (*vm)->DetachCurrentThread(vm);
697 }
698 }
699
700 //----------------------------------------------------------------------------------
701 // Module Functions Definition: Inputs
702 //----------------------------------------------------------------------------------
703
704 // Set internal gamepad mappings
705 int SetGamepadMappings(const char *mappings)
706 {
707 TRACELOG(LOG_WARNING, "SetGamepadMappings() not implemented on target platform");
708 return 0;
709 }
710
711 // Set gamepad vibration
712 void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor, float duration)
713 {
714 TRACELOG(LOG_WARNING, "SetGamepadVibration() not implemented on target platform");
715 }
716
717 // Set mouse position XY
718 void SetMousePosition(int x, int y)
719 {
720 CORE.Input.Mouse.currentPosition = (Vector2){ (float)x, (float)y };
721 CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;
722 }
723
724 // Set mouse cursor
725 void SetMouseCursor(int cursor)
726 {
727 TRACELOG(LOG_WARNING, "SetMouseCursor() not implemented on target platform");
728 }
729
730 // Get physical key name
731 const char *GetKeyName(int key)
732 {
733 TRACELOG(LOG_WARNING, "GetKeyName() not implemented on target platform");
734 return "";
735 }
736
737 // Register all input events
738 void PollInputEvents(void)
739 {
740 #if SUPPORT_GESTURES_SYSTEM
741 // NOTE: Gestures update must be called every frame to reset gestures correctly
742 // because ProcessGestureEvent() is called on an event, not every frame
743 UpdateGestures();
744 #endif
745
746 // Reset keys/chars pressed registered
747 CORE.Input.Keyboard.keyPressedQueueCount = 0;
748 CORE.Input.Keyboard.charPressedQueueCount = 0;
749 // Reset key repeats
750 for (int i = 0; i < MAX_KEYBOARD_KEYS; i++) CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
751
752 // Reset last gamepad button/axis registered state
753 CORE.Input.Gamepad.lastButtonPressed = 0; // GAMEPAD_BUTTON_UNKNOWN
754 //CORE.Input.Gamepad.axisCount = 0;
755
756 for (int i = 0; i < MAX_GAMEPADS; i++)
757 {
758 if (CORE.Input.Gamepad.ready[i]) // Check if gamepad is available
759 {
760 // Register previous gamepad states
761 for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++)
762 CORE.Input.Gamepad.previousButtonState[i][k] = CORE.Input.Gamepad.currentButtonState[i][k];
763 }
764 }
765
766 // Register previous touch states
767 for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i];
768
769 // Reset touch positions
770 //for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.position[i] = (Vector2){ 0, 0 };
771
772 // Register previous keys states
773 // NOTE: Android supports up to 260 keys
774 for (int i = 0; i < 260; i++)
775 {
776 CORE.Input.Keyboard.previousKeyState[i] = CORE.Input.Keyboard.currentKeyState[i];
777 CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
778 }
779
780 // Android ALooper_pollOnce() variables
781 int pollResult = 0;
782 int pollEvents = 0;
783
784 // Poll Events (registered events) until TIMEOUT is reached which indicates there are no events left to poll
785 // NOTE: Activity is paused if not enabled (platform.appEnabled) and always run flag is not set (FLAG_WINDOW_ALWAYS_RUN)
786 while ((pollResult = ALooper_pollOnce((platform.appEnabled || FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_ALWAYS_RUN))? 0 : -1, NULL, &pollEvents, ((void **)&platform.source)) > ALOOPER_POLL_TIMEOUT))
787 {
788 // Process this event
789 if (platform.source != NULL) platform.source->process(platform.app, platform.source);
790
791 // NOTE: Allow closing the window in case a configuration change happened
792 // The android_main function should be allowed to return to its caller in order for the
793 // Android OS to relaunch the activity
794 if (platform.app->destroyRequested != 0)
795 {
796 CORE.Window.shouldClose = true;
797 }
798 }
799 }
800
801 //----------------------------------------------------------------------------------
802 // Module Internal Functions Definition
803 //----------------------------------------------------------------------------------
804
805 // Initialize platform: graphics, inputs and more
806 int InitPlatform(void)
807 {
808 // Initialize display basic configuration
809 //----------------------------------------------------------------------------
810 CORE.Window.currentFbo.width = CORE.Window.screen.width;
811 CORE.Window.currentFbo.height = CORE.Window.screen.height;
812
813 // Set desired windows flags before initializing anything
814 ANativeActivity_setWindowFlags(platform.app->activity, AWINDOW_FLAG_FULLSCREEN, 0); //AWINDOW_FLAG_SCALED, AWINDOW_FLAG_DITHER
815
816 int orientation = AConfiguration_getOrientation(platform.app->config);
817
818 if (orientation == ACONFIGURATION_ORIENTATION_PORT) TRACELOG(LOG_INFO, "ANDROID: Window orientation set as portrait");
819 else if (orientation == ACONFIGURATION_ORIENTATION_LAND) TRACELOG(LOG_INFO, "ANDROID: Window orientation set as landscape");
820
821 // TODO: Automatic orientation doesn't seem to work
822 if (CORE.Window.screen.width <= CORE.Window.screen.height)
823 {
824 AConfiguration_setOrientation(platform.app->config, ACONFIGURATION_ORIENTATION_PORT);
825 TRACELOG(LOG_WARNING, "ANDROID: Window orientation changed to portrait");
826 }
827 else
828 {
829 AConfiguration_setOrientation(platform.app->config, ACONFIGURATION_ORIENTATION_LAND);
830 TRACELOG(LOG_WARNING, "ANDROID: Window orientation changed to landscape");
831 }
832
833 //AConfiguration_getDensity(platform.app->config);
834 //AConfiguration_getKeyboard(platform.app->config);
835 //AConfiguration_getScreenSize(platform.app->config);
836 //AConfiguration_getScreenLong(platform.app->config);
837
838 // Set some default window flags
839 FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_HIDDEN); // false
840 FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_MINIMIZED); // false
841 FLAG_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED); // true
842 FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED); // false
843 //----------------------------------------------------------------------------
844
845 // Initialize App command system
846 // NOTE: On APP_CMD_INIT_WINDOW -> InitGraphicsDevice(), InitTimer(), LoadFontDefault()...
847 //----------------------------------------------------------------------------
848 platform.app->onAppCmd = AndroidCommandCallback;
849 //----------------------------------------------------------------------------
850
851 // Initialize input events system
852 //----------------------------------------------------------------------------
853 platform.app->onInputEvent = AndroidInputCallback;
854 //----------------------------------------------------------------------------
855
856 // Initialize storage system
857 //----------------------------------------------------------------------------
858 CORE.Storage.basePath = platform.app->activity->internalDataPath; // Define base path for storage
859 //----------------------------------------------------------------------------
860
861 TRACELOG(LOG_INFO, "PLATFORM: ANDROID: Initialized successfully");
862
863 // Android ALooper_pollOnce() variables
864 int pollResult = 0;
865 int pollEvents = 0;
866
867 // Wait for window to be initialized (display and context)
868 while (!CORE.Window.ready)
869 {
870 // Process events until TIMEOUT is reached, which indicates no more events queued
871 while ((pollResult = ALooper_pollOnce(0, NULL, &pollEvents, ((void **)&platform.source)) > ALOOPER_POLL_TIMEOUT))
872 {
873 // Process this event
874 if (platform.source != NULL) platform.source->process(platform.app, platform.source);
875
876 // NOTE: It's highly likely destroyRequested will never be non-zero at the start of the activity lifecycle
877 //if (platform.app->destroyRequested != 0) CORE.Window.shouldClose = true;
878 }
879 }
880
881 for (int i = 0; i < MAX_TOUCH_POINTS; i++) touchRaw.hoverPoints[i] = -1;
882
883 return 0;
884 }
885
886 // Close platform
887 void ClosePlatform(void)
888 {
889 // Close surface, context and display
890 if (platform.device != EGL_NO_DISPLAY)
891 {
892 eglMakeCurrent(platform.device, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
893
894 if (platform.surface != EGL_NO_SURFACE)
895 {
896 eglDestroySurface(platform.device, platform.surface);
897 platform.surface = EGL_NO_SURFACE;
898 }
899
900 if (platform.context != EGL_NO_CONTEXT)
901 {
902 eglDestroyContext(platform.device, platform.context);
903 platform.context = EGL_NO_CONTEXT;
904 }
905
906 eglTerminate(platform.device);
907 platform.device = EGL_NO_DISPLAY;
908 }
909
910 // NOTE: Reset global state in case the activity is being relaunched
911 if (platform.app->destroyRequested != 0)
912 {
913 CORE = (CoreData){ 0 };
914 platform = (PlatformData){ 0 };
915 }
916 }
917
918 // Initialize display device and framebuffer
919 // NOTE: width and height represent the screen (framebuffer) desired size, not actual display size
920 // If width or height are 0, default display size will be used for framebuffer size
921 // NOTE: returns false in case graphic device could not be created
922 static int InitGraphicsDevice(void)
923 {
924 FLAG_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
925
926 EGLint samples = 0;
927 EGLint sampleBuffer = 0;
928 if (FLAG_IS_SET(CORE.Window.flags, FLAG_MSAA_4X_HINT))
929 {
930 samples = 4;
931 sampleBuffer = 1;
932 TRACELOG(LOG_INFO, "DISPLAY: Trying to enable MSAA x4");
933 }
934
935 const EGLint framebufferAttribs[] = {
936 EGL_RENDERABLE_TYPE, (rlGetVersion() == RL_OPENGL_ES_30)? EGL_OPENGL_ES3_BIT : EGL_OPENGL_ES2_BIT, // Type of context support
937 EGL_RED_SIZE, 8, // RED color bit depth (alternative: 5)
938 EGL_GREEN_SIZE, 8, // GREEN color bit depth (alternative: 6)
939 EGL_BLUE_SIZE, 8, // BLUE color bit depth (alternative: 5)
940 //EGL_TRANSPARENT_TYPE, EGL_NONE, // Request transparent framebuffer (EGL_TRANSPARENT_RGB does not work on RPI)
941 EGL_DEPTH_SIZE, 24, // Depth buffer size (Required to use Depth testing!)
942 //EGL_STENCIL_SIZE, 8, // Stencil buffer size
943 EGL_SAMPLE_BUFFERS, sampleBuffer, // Activate MSAA
944 EGL_SAMPLES, samples, // 4x Antialiasing if activated (Free on MALI GPUs)
945 EGL_NONE
946 };
947
948 const EGLint contextAttribs[] = {
949 EGL_CONTEXT_CLIENT_VERSION, 2,
950 EGL_NONE
951 };
952
953 EGLint numConfigs = 0;
954
955 // Get an EGL device connection
956 platform.device = eglGetDisplay(EGL_DEFAULT_DISPLAY);
957
958 if (platform.device == EGL_NO_DISPLAY)
959 {
960 TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
961 return -1;
962 }
963
964 // Initialize the EGL device connection
965 if (eglInitialize(platform.device, NULL, NULL) == EGL_FALSE)
966 {
967 // If all of the calls to eglInitialize returned EGL_FALSE then an error has occurred
968 TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
969 return -1;
970 }
971
972 // Get an appropriate EGL framebuffer configuration
973 eglChooseConfig(platform.device, framebufferAttribs, &platform.config, 1, &numConfigs);
974
975 // Set rendering API
976 eglBindAPI(EGL_OPENGL_ES_API);
977
978 // Create an EGL rendering context
979 platform.context = eglCreateContext(platform.device, platform.config, EGL_NO_CONTEXT, contextAttribs);
980 if (platform.context == EGL_NO_CONTEXT)
981 {
982 TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL context");
983 return -1;
984 }
985
986 // Create an EGL window surface
987 //---------------------------------------------------------------------------------
988 EGLint displayFormat = 0;
989
990 // EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is guaranteed to be accepted by ANativeWindow_setBuffersGeometry()
991 // As soon as an EGLConfig is picked, it's safe to reconfigure the ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID
992 eglGetConfigAttrib(platform.device, platform.config, EGL_NATIVE_VISUAL_ID, &displayFormat);
993
994 // At this point render size vs screen size needs to be managed
995 // NOTE: This function use and modify global module variables:
996 // -> CORE.Window.screen.width/CORE.Window.screen.height
997 // -> CORE.Window.render.width/CORE.Window.render.height
998 // -> CORE.Window.screenScale
999 SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height);
1000
1001 ANativeWindow_setBuffersGeometry(platform.app->window, CORE.Window.render.width, CORE.Window.render.height, displayFormat);
1002 //ANativeWindow_setBuffersGeometry(platform.app->window, 0, 0, displayFormat); // Force use of native display size
1003
1004 platform.surface = eglCreateWindowSurface(platform.device, platform.config, platform.app->window, NULL);
1005
1006 // There must be at least one frame displayed before the buffers are swapped
1007 //eglSwapInterval(platform.device, 1);
1008
1009 if (eglMakeCurrent(platform.device, platform.surface, platform.surface, platform.context) == EGL_FALSE)
1010 {
1011 TRACELOG(LOG_WARNING, "DISPLAY: Failed to attach EGL rendering context to EGL surface");
1012 return -1;
1013 }
1014 else
1015 {
1016 CORE.Window.render.width = CORE.Window.screen.width;
1017 CORE.Window.render.height = CORE.Window.screen.height;
1018 CORE.Window.currentFbo.width = CORE.Window.render.width;
1019 CORE.Window.currentFbo.height = CORE.Window.render.height;
1020
1021 TRACELOG(LOG_INFO, "DISPLAY: Device initialized successfully");
1022 TRACELOG(LOG_INFO, " > Display size: %i x %i", CORE.Window.display.width, CORE.Window.display.height);
1023 TRACELOG(LOG_INFO, " > Screen size: %i x %i", CORE.Window.screen.width, CORE.Window.screen.height);
1024 TRACELOG(LOG_INFO, " > Render size: %i x %i", CORE.Window.render.width, CORE.Window.render.height);
1025 TRACELOG(LOG_INFO, " > Viewport offsets: %i, %i", CORE.Window.renderOffset.x, CORE.Window.renderOffset.y);
1026 }
1027
1028 // Load OpenGL extensions
1029 // NOTE: GL procedures address loader is required to load extensions
1030 rlLoadExtensions(eglGetProcAddress);
1031
1032 CORE.Window.ready = true;
1033
1034 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED)) MinimizeWindow();
1035
1036 return 0;
1037 }
1038
1039 // ANDROID: Process activity lifecycle commands
1040 static void AndroidCommandCallback(struct android_app *app, int32_t cmd)
1041 {
1042 switch (cmd)
1043 {
1044 case APP_CMD_START:
1045 {
1046 //rendering = true;
1047 } break;
1048 case APP_CMD_RESUME: break;
1049 case APP_CMD_INIT_WINDOW:
1050 {
1051 if (app->window != NULL)
1052 {
1053 if (platform.contextRebindRequired)
1054 {
1055 // Reset screen scaling to full display size
1056 EGLint displayFormat = 0;
1057 eglGetConfigAttrib(platform.device, platform.config, EGL_NATIVE_VISUAL_ID, &displayFormat);
1058
1059 // Adding renderOffset here feels rather hackish, but the viewport scaling is wrong after the
1060 // context rebinding if the screen is scaled unless offsets are added. There's probably a more
1061 // appropriate way to fix this
1062 ANativeWindow_setBuffersGeometry(app->window,
1063 CORE.Window.render.width + CORE.Window.renderOffset.x,
1064 CORE.Window.render.height + CORE.Window.renderOffset.y,
1065 displayFormat);
1066
1067 // Recreate display surface and re-attach OpenGL context
1068 platform.surface = eglCreateWindowSurface(platform.device, platform.config, app->window, NULL);
1069 eglMakeCurrent(platform.device, platform.surface, platform.surface, platform.context);
1070
1071 platform.contextRebindRequired = false;
1072 }
1073 else
1074 {
1075 CORE.Window.display.width = ANativeWindow_getWidth(platform.app->window);
1076 CORE.Window.display.height = ANativeWindow_getHeight(platform.app->window);
1077
1078 // Initialize graphics device (display device and OpenGL context)
1079 InitGraphicsDevice();
1080
1081 // Initialize OpenGL context (states and resources)
1082 // NOTE: CORE.Window.currentFbo.width and CORE.Window.currentFbo.height not used, stored as globals in rlgl
1083 rlglInit(CORE.Window.currentFbo.width, CORE.Window.currentFbo.height);
1084
1085 // Setup default viewport
1086 // NOTE: It updated CORE.Window.render.width and CORE.Window.render.height
1087 SetupViewport(CORE.Window.currentFbo.width, CORE.Window.currentFbo.height);
1088
1089 // Initialize hi-res timer
1090 InitTimer();
1091
1092 #if SUPPORT_MODULE_RTEXT
1093 // Load default font
1094 // WARNING: External function: Module required: rtext
1095 LoadFontDefault();
1096 #if SUPPORT_MODULE_RSHAPES
1097 // Set font white rectangle for shapes drawing, so shapes and text can be batched together
1098 // WARNING: rshapes module is required, if not available, default internal white rectangle is used
1099 Rectangle rec = GetFontDefault().recs[95];
1100 if (FLAG_IS_SET(CORE.Window.flags, FLAG_MSAA_4X_HINT))
1101 {
1102 // NOTE: Trying to maxime rec padding to avoid pixel bleeding on MSAA filtering
1103 SetShapesTexture(GetFontDefault().texture, (Rectangle){ rec.x + 2, rec.y + 2, 1, 1 });
1104 }
1105 else
1106 {
1107 // NOTE: Setting up a 1px padding on char rectangle to avoid pixel bleeding
1108 SetShapesTexture(GetFontDefault().texture, (Rectangle){ rec.x + 1, rec.y + 1, rec.width - 2, rec.height - 2 });
1109 }
1110 #endif
1111 #else
1112 #if SUPPORT_MODULE_RSHAPES
1113 // Set default texture and rectangle to be used for shapes drawing
1114 // NOTE: rlgl default texture is a 1x1 pixel UNCOMPRESSED_R8G8B8A8
1115 Texture2D texture = { rlGetTextureIdDefault(), 1, 1, 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 };
1116 SetShapesTexture(texture, (Rectangle){ 0.0f, 0.0f, 1.0f, 1.0f }); // WARNING: Module required: rshapes
1117 #endif
1118 #endif
1119
1120 // Initialize random seed
1121 SetRandomSeed((unsigned int)time(NULL));
1122 }
1123 }
1124 } break;
1125 case APP_CMD_GAINED_FOCUS:
1126 {
1127 platform.appEnabled = true;
1128 FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED);
1129 //ResumeMusicStream();
1130 } break;
1131 case APP_CMD_PAUSE: break;
1132 case APP_CMD_LOST_FOCUS:
1133 {
1134 platform.appEnabled = false;
1135 FLAG_SET(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED);
1136 //PauseMusicStream();
1137 } break;
1138 case APP_CMD_TERM_WINDOW:
1139 {
1140 // Detach OpenGL context and destroy display surface
1141 // NOTE 1: This case is used when the user exits the app without closing it, context is detached to ensure everything is recoverable upon resuming
1142 // NOTE 2: Detaching context before destroying display surface avoids losing our resources (textures, shaders, VBOs...)
1143 // NOTE 3: In some cases (too many context loaded), OS could unload context automatically... :(
1144 if (platform.device != EGL_NO_DISPLAY)
1145 {
1146 eglMakeCurrent(platform.device, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1147
1148 if (platform.surface != EGL_NO_SURFACE)
1149 {
1150 eglDestroySurface(platform.device, platform.surface);
1151 platform.surface = EGL_NO_SURFACE;
1152 }
1153
1154 platform.contextRebindRequired = true;
1155 }
1156 // If 'platform.device' is already set to 'EGL_NO_DISPLAY'
1157 // this means that the user has already called 'CloseWindow()'
1158
1159 } break;
1160 case APP_CMD_SAVE_STATE: break;
1161 case APP_CMD_STOP: break;
1162 case APP_CMD_DESTROY: break;
1163 case APP_CMD_CONFIG_CHANGED:
1164 {
1165 //AConfiguration_fromAssetManager(platform.app->config, platform.app->activity->assetManager);
1166 //print_cur_config(platform.app);
1167
1168 // Check screen orientation here!
1169 } break;
1170 default: break;
1171 }
1172 }
1173
1174 // ANDROID: Map Android gamepad button to raylib gamepad button
1175 static GamepadButton AndroidTranslateGamepadButton(int button)
1176 {
1177 switch (button)
1178 {
1179 case AKEYCODE_BUTTON_A: return GAMEPAD_BUTTON_RIGHT_FACE_DOWN;
1180 case AKEYCODE_BUTTON_B: return GAMEPAD_BUTTON_RIGHT_FACE_RIGHT;
1181 case AKEYCODE_BUTTON_X: return GAMEPAD_BUTTON_RIGHT_FACE_LEFT;
1182 case AKEYCODE_BUTTON_Y: return GAMEPAD_BUTTON_RIGHT_FACE_UP;
1183 case AKEYCODE_BUTTON_L1: return GAMEPAD_BUTTON_LEFT_TRIGGER_1;
1184 case AKEYCODE_BUTTON_R1: return GAMEPAD_BUTTON_RIGHT_TRIGGER_1;
1185 case AKEYCODE_BUTTON_L2: return GAMEPAD_BUTTON_LEFT_TRIGGER_2;
1186 case AKEYCODE_BUTTON_R2: return GAMEPAD_BUTTON_RIGHT_TRIGGER_2;
1187 case AKEYCODE_BUTTON_THUMBL: return GAMEPAD_BUTTON_LEFT_THUMB;
1188 case AKEYCODE_BUTTON_THUMBR: return GAMEPAD_BUTTON_RIGHT_THUMB;
1189 case AKEYCODE_BUTTON_START: return GAMEPAD_BUTTON_MIDDLE_RIGHT;
1190 case AKEYCODE_BUTTON_SELECT: return GAMEPAD_BUTTON_MIDDLE_LEFT;
1191 case AKEYCODE_BUTTON_MODE: return GAMEPAD_BUTTON_MIDDLE;
1192 // On some (most?) gamepads dpad events are reported as axis motion instead
1193 case AKEYCODE_DPAD_DOWN: return GAMEPAD_BUTTON_LEFT_FACE_DOWN;
1194 case AKEYCODE_DPAD_RIGHT: return GAMEPAD_BUTTON_LEFT_FACE_RIGHT;
1195 case AKEYCODE_DPAD_LEFT: return GAMEPAD_BUTTON_LEFT_FACE_LEFT;
1196 case AKEYCODE_DPAD_UP: return GAMEPAD_BUTTON_LEFT_FACE_UP;
1197 default: return GAMEPAD_BUTTON_UNKNOWN;
1198 }
1199 }
1200
1201 // ANDROID: Get input events
1202 static int32_t AndroidInputCallback(struct android_app *app, AInputEvent *event)
1203 {
1204 // If additional inputs are required check:
1205 // REF: https://developer.android.com/ndk/reference/group/input
1206 // REF: https://developer.android.com/training/game-controllers/controller-input
1207
1208 int type = AInputEvent_getType(event);
1209 int source = AInputEvent_getSource(event);
1210
1211 if (type == AINPUT_EVENT_TYPE_MOTION)
1212 {
1213 if (FLAG_IS_SET(source, AINPUT_SOURCE_JOYSTICK) ||
1214 FLAG_IS_SET(source, AINPUT_SOURCE_GAMEPAD))
1215 {
1216 // Assuming a single gamepad, "detected" on its input event
1217 CORE.Input.Gamepad.ready[0] = true;
1218
1219 CORE.Input.Gamepad.axisState[0][GAMEPAD_AXIS_LEFT_X] = AMotionEvent_getAxisValue(
1220 event, AMOTION_EVENT_AXIS_X, 0);
1221 CORE.Input.Gamepad.axisState[0][GAMEPAD_AXIS_LEFT_Y] = AMotionEvent_getAxisValue(
1222 event, AMOTION_EVENT_AXIS_Y, 0);
1223 CORE.Input.Gamepad.axisState[0][GAMEPAD_AXIS_RIGHT_X] = AMotionEvent_getAxisValue(
1224 event, AMOTION_EVENT_AXIS_Z, 0);
1225 CORE.Input.Gamepad.axisState[0][GAMEPAD_AXIS_RIGHT_Y] = AMotionEvent_getAxisValue(
1226 event, AMOTION_EVENT_AXIS_RZ, 0);
1227 CORE.Input.Gamepad.axisState[0][GAMEPAD_AXIS_LEFT_TRIGGER] = AMotionEvent_getAxisValue(
1228 event, AMOTION_EVENT_AXIS_BRAKE, 0)*2.0f - 1.0f;
1229 CORE.Input.Gamepad.axisState[0][GAMEPAD_AXIS_RIGHT_TRIGGER] = AMotionEvent_getAxisValue(
1230 event, AMOTION_EVENT_AXIS_GAS, 0)*2.0f - 1.0f;
1231
1232 // dpad is reported as an axis on android
1233 float dpadX = AMotionEvent_getAxisValue(event, AMOTION_EVENT_AXIS_HAT_X, 0);
1234 float dpadY = AMotionEvent_getAxisValue(event, AMOTION_EVENT_AXIS_HAT_Y, 0);
1235
1236 if (dpadX == 1.0f)
1237 {
1238 CORE.Input.Gamepad.currentButtonState[0][GAMEPAD_BUTTON_LEFT_FACE_RIGHT] = 1;
1239 CORE.Input.Gamepad.currentButtonState[0][GAMEPAD_BUTTON_LEFT_FACE_LEFT] = 0;
1240 }
1241 else if (dpadX == -1.0f)
1242 {
1243 CORE.Input.Gamepad.currentButtonState[0][GAMEPAD_BUTTON_LEFT_FACE_RIGHT] = 0;
1244 CORE.Input.Gamepad.currentButtonState[0][GAMEPAD_BUTTON_LEFT_FACE_LEFT] = 1;
1245 }
1246 else
1247 {
1248 CORE.Input.Gamepad.currentButtonState[0][GAMEPAD_BUTTON_LEFT_FACE_RIGHT] = 0;
1249 CORE.Input.Gamepad.currentButtonState[0][GAMEPAD_BUTTON_LEFT_FACE_LEFT] = 0;
1250 }
1251
1252 if (dpadY == 1.0f)
1253 {
1254 CORE.Input.Gamepad.currentButtonState[0][GAMEPAD_BUTTON_LEFT_FACE_DOWN] = 1;
1255 CORE.Input.Gamepad.currentButtonState[0][GAMEPAD_BUTTON_LEFT_FACE_UP] = 0;
1256 }
1257 else if (dpadY == -1.0f)
1258 {
1259 CORE.Input.Gamepad.currentButtonState[0][GAMEPAD_BUTTON_LEFT_FACE_DOWN] = 0;
1260 CORE.Input.Gamepad.currentButtonState[0][GAMEPAD_BUTTON_LEFT_FACE_UP] = 1;
1261 }
1262 else
1263 {
1264 CORE.Input.Gamepad.currentButtonState[0][GAMEPAD_BUTTON_LEFT_FACE_DOWN] = 0;
1265 CORE.Input.Gamepad.currentButtonState[0][GAMEPAD_BUTTON_LEFT_FACE_UP] = 0;
1266 }
1267
1268 return 1; // Handled gamepad axis motion
1269 }
1270 }
1271 else if (type == AINPUT_EVENT_TYPE_KEY)
1272 {
1273 int32_t keycode = AKeyEvent_getKeyCode(event);
1274 //int32_t AKeyEvent_getMetaState(event);
1275
1276 // Handle gamepad button presses and releases
1277 // NOTE: Skip gamepad handling if this is a keyboard event, as some devices
1278 // report both AINPUT_SOURCE_KEYBOARD and AINPUT_SOURCE_GAMEPAD flags
1279 if ((FLAG_IS_SET(source, AINPUT_SOURCE_JOYSTICK) ||
1280 FLAG_IS_SET(source, AINPUT_SOURCE_GAMEPAD)) &&
1281 !FLAG_IS_SET(source, AINPUT_SOURCE_KEYBOARD))
1282 {
1283 // Assuming a single gamepad, "detected" on its input event
1284 CORE.Input.Gamepad.ready[0] = true;
1285
1286 GamepadButton button = AndroidTranslateGamepadButton(keycode);
1287
1288 if (button == GAMEPAD_BUTTON_UNKNOWN) return 1;
1289
1290 if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_DOWN)
1291 {
1292 CORE.Input.Gamepad.currentButtonState[0][button] = 1;
1293 }
1294 else CORE.Input.Gamepad.currentButtonState[0][button] = 0; // Key up
1295
1296 return 1; // Handled gamepad button
1297 }
1298
1299 KeyboardKey key = ((keycode > 0) && (keycode < KEYCODE_MAP_SIZE))? mapKeycode[keycode] : KEY_NULL;
1300 if (key != KEY_NULL)
1301 {
1302 // Save current key and its state
1303 // NOTE: Android key action is 0 for down and 1 for up
1304 if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_DOWN)
1305 {
1306 CORE.Input.Keyboard.currentKeyState[key] = 1; // Key down
1307
1308 CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = key;
1309 CORE.Input.Keyboard.keyPressedQueueCount++;
1310 }
1311 else if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_MULTIPLE) CORE.Input.Keyboard.keyRepeatInFrame[key] = 1;
1312 else CORE.Input.Keyboard.currentKeyState[key] = 0; // Key up
1313 }
1314
1315 if (keycode == AKEYCODE_POWER)
1316 {
1317 // Let the OS handle input to avoid app stuck. Behaviour: CMD_PAUSE -> CMD_SAVE_STATE -> CMD_STOP -> CMD_CONFIG_CHANGED -> CMD_LOST_FOCUS
1318 // Resuming Behaviour: CMD_START -> CMD_RESUME -> CMD_CONFIG_CHANGED -> CMD_CONFIG_CHANGED -> CMD_GAINED_FOCUS
1319 // It seems like locking mobile, screen size (CMD_CONFIG_CHANGED) is affected
1320 // NOTE: AndroidManifest.xml must have <activity android:configChanges="orientation|keyboardHidden|screenSize" >
1321 // Before that change, activity was calling CMD_TERM_WINDOW and CMD_DESTROY when locking mobile, so that was not a normal behaviour
1322 return 0;
1323 }
1324 else if ((keycode == AKEYCODE_BACK) || (keycode == AKEYCODE_MENU))
1325 {
1326 // Eat BACK_BUTTON and AKEYCODE_MENU, do nothing... and don't let to be handled by OS!
1327 return 1;
1328 }
1329 else if ((keycode == AKEYCODE_VOLUME_UP) || (keycode == AKEYCODE_VOLUME_DOWN))
1330 {
1331 // Set default OS behaviour
1332 return 0;
1333 }
1334
1335 return 0;
1336 }
1337
1338 // Register touch points count
1339 touchRaw.pointCount = AMotionEvent_getPointerCount(event);
1340
1341 for (int i = 0; (i < touchRaw.pointCount) && (i < MAX_TOUCH_POINTS); i++)
1342 {
1343 // Register touch points id
1344 touchRaw.pointId[i] = AMotionEvent_getPointerId(event, i);
1345
1346 // Register touch points position
1347 touchRaw.position[i] = (Vector2){ AMotionEvent_getX(event, i), AMotionEvent_getY(event, i) };
1348
1349 // Normalize CORE.Input.Touch.position[i] for CORE.Window.screen.width and CORE.Window.screen.height
1350 float widthRatio = (float)(CORE.Window.screen.width + CORE.Window.renderOffset.x)/(float)CORE.Window.display.width;
1351 float heightRatio = (float)(CORE.Window.screen.height + CORE.Window.renderOffset.y)/(float)CORE.Window.display.height;
1352 touchRaw.position[i].x = touchRaw.position[i].x*widthRatio - (float)CORE.Window.renderOffset.x/2;
1353 touchRaw.position[i].y = touchRaw.position[i].y*heightRatio - (float)CORE.Window.renderOffset.y/2;
1354 }
1355
1356 int32_t action = AMotionEvent_getAction(event);
1357 unsigned int flags = action & AMOTION_EVENT_ACTION_MASK;
1358 int32_t pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
1359
1360 if (flags == AMOTION_EVENT_ACTION_HOVER_ENTER)
1361 {
1362 // The new pointer is hover
1363 // So add it to hoverPoints
1364 for (int i = 0; i < MAX_TOUCH_POINTS; i++)
1365 {
1366 if (touchRaw.hoverPoints[i] == -1)
1367 {
1368 touchRaw.hoverPoints[i] = touchRaw.pointId[pointerIndex];
1369 break;
1370 }
1371 }
1372 }
1373
1374 #if SUPPORT_GESTURES_SYSTEM
1375 GestureEvent gestureEvent = { 0 };
1376
1377 gestureEvent.pointCount = 0;
1378
1379 // Register touch actions
1380 if (flags == AMOTION_EVENT_ACTION_DOWN) gestureEvent.touchAction = TOUCH_ACTION_DOWN;
1381 else if (flags == AMOTION_EVENT_ACTION_UP) gestureEvent.touchAction = TOUCH_ACTION_UP;
1382 else if (flags == AMOTION_EVENT_ACTION_MOVE) gestureEvent.touchAction = TOUCH_ACTION_MOVE;
1383 else if (flags == AMOTION_EVENT_ACTION_CANCEL) gestureEvent.touchAction = TOUCH_ACTION_CANCEL;
1384
1385 for (int i = 0; (i < touchRaw.pointCount) && (i < MAX_TOUCH_POINTS); i++)
1386 {
1387 // If the touchPoint is hover, Ignore it
1388 bool hover = false;
1389 for (int j = 0; j < MAX_TOUCH_POINTS; j++)
1390 {
1391 // Check if the touchPoint is in hoverPointers
1392 if (touchRaw.hoverPoints[j] == touchRaw.pointId[i])
1393 {
1394 hover = true;
1395 break;
1396 }
1397 }
1398 if (hover) continue;
1399
1400 gestureEvent.pointId[gestureEvent.pointCount] = touchRaw.pointId[i];
1401 gestureEvent.position[gestureEvent.pointCount] = touchRaw.position[i];
1402 gestureEvent.position[gestureEvent.pointCount].x /= (float)GetScreenWidth();
1403 gestureEvent.position[gestureEvent.pointCount].y /= (float)GetScreenHeight();
1404 gestureEvent.pointCount++;
1405 }
1406
1407 // Gesture data is sent to gestures system for processing
1408 ProcessGestureEvent(gestureEvent);
1409 #endif
1410
1411 if (flags == AMOTION_EVENT_ACTION_HOVER_EXIT)
1412 {
1413 // Hover exited. So, remove it from hoverPoints
1414 for (int i = 0; i < MAX_TOUCH_POINTS; i++)
1415 {
1416 if (touchRaw.hoverPoints[i] == touchRaw.pointId[pointerIndex])
1417 {
1418 touchRaw.hoverPoints[i] = -1;
1419 break;
1420 }
1421 }
1422 }
1423
1424 if ((flags == AMOTION_EVENT_ACTION_POINTER_UP) || (flags == AMOTION_EVENT_ACTION_UP))
1425 {
1426 // One of the touchpoints is released, remove it from touch point arrays
1427 for (int i = pointerIndex; (i < touchRaw.pointCount - 1) && (i < MAX_TOUCH_POINTS - 1); i++)
1428 {
1429 touchRaw.pointId[i] = touchRaw.pointId[i+1];
1430 touchRaw.position[i] = touchRaw.position[i+1];
1431 }
1432 touchRaw.pointCount--;
1433 }
1434
1435 CORE.Input.Touch.pointCount = 0;
1436 for (int i = 0; (i < touchRaw.pointCount) && (i < MAX_TOUCH_POINTS); i++)
1437 {
1438 // If the touchPoint is hover, Ignore it
1439 bool hover = false;
1440 for (int j = 0; j < MAX_TOUCH_POINTS; j++)
1441 {
1442 // Check if the touchPoint is in hoverPointers
1443 if (touchRaw.hoverPoints[j] == touchRaw.pointId[i])
1444 {
1445 hover = true;
1446 break;
1447 }
1448 }
1449 if (hover) continue;
1450
1451 CORE.Input.Touch.pointId[CORE.Input.Touch.pointCount] = touchRaw.pointId[i];
1452 CORE.Input.Touch.position[CORE.Input.Touch.pointCount] = touchRaw.position[i];
1453 CORE.Input.Touch.pointCount++;
1454 }
1455
1456 // When all touchpoints are tapped and released really quickly, this event is generated
1457 if (flags == AMOTION_EVENT_ACTION_CANCEL) CORE.Input.Touch.pointCount = 0;
1458
1459 if (CORE.Input.Touch.pointCount > 0) CORE.Input.Touch.currentTouchState[MOUSE_BUTTON_LEFT] = 1;
1460 else CORE.Input.Touch.currentTouchState[MOUSE_BUTTON_LEFT] = 0;
1461
1462 // Stores the previous position of touch[0] only while it's active to calculate the delta
1463 if (flags == AMOTION_EVENT_ACTION_MOVE) CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;
1464 else CORE.Input.Mouse.previousPosition = CORE.Input.Touch.position[0];
1465
1466 // Map touch[0] as mouse input for convenience
1467 CORE.Input.Mouse.currentPosition = CORE.Input.Touch.position[0];
1468 CORE.Input.Mouse.currentWheelMove = (Vector2){ 0.0f, 0.0f };
1469
1470 return 0;
1471 }
1472
1473 // Compute framebuffer size relative to screen size and display size
1474 // NOTE: Global variables CORE.Window.render.width/CORE.Window.render.height and CORE.Window.renderOffset.x/CORE.Window.renderOffset.y can be modified
1475 static void SetupFramebuffer(int width, int height)
1476 {
1477 // Calculate CORE.Window.render.width and CORE.Window.render.height, having the display size (input params) and the desired screen size (global var)
1478 if ((CORE.Window.screen.width > CORE.Window.display.width) || (CORE.Window.screen.height > CORE.Window.display.height))
1479 {
1480 TRACELOG(LOG_WARNING, "DISPLAY: Downscaling required: Screen size (%ix%i) is bigger than display size (%ix%i)", CORE.Window.screen.width, CORE.Window.screen.height, CORE.Window.display.width, CORE.Window.display.height);
1481
1482 // Downscaling to fit display with border-bars
1483 float widthRatio = (float)CORE.Window.display.width/(float)CORE.Window.screen.width;
1484 float heightRatio = (float)CORE.Window.display.height/(float)CORE.Window.screen.height;
1485
1486 if (widthRatio <= heightRatio)
1487 {
1488 CORE.Window.render.width = CORE.Window.display.width;
1489 CORE.Window.render.height = (int)round((float)CORE.Window.screen.height*widthRatio);
1490 CORE.Window.renderOffset.x = 0;
1491 CORE.Window.renderOffset.y = (CORE.Window.display.height - CORE.Window.render.height);
1492 }
1493 else
1494 {
1495 CORE.Window.render.width = (int)round((float)CORE.Window.screen.width*heightRatio);
1496 CORE.Window.render.height = CORE.Window.display.height;
1497 CORE.Window.renderOffset.x = (CORE.Window.display.width - CORE.Window.render.width);
1498 CORE.Window.renderOffset.y = 0;
1499 }
1500
1501 // Screen scaling required
1502 float scaleRatio = (float)CORE.Window.render.width/(float)CORE.Window.screen.width;
1503 CORE.Window.screenScale = MatrixScale(scaleRatio, scaleRatio, 1.0f);
1504
1505 // NOTE: Rendering to full display resolution
1506 // Above parameters need to be calculate for downscale matrix and offsets
1507 CORE.Window.render.width = CORE.Window.display.width;
1508 CORE.Window.render.height = CORE.Window.display.height;
1509
1510 TRACELOG(LOG_WARNING, "DISPLAY: Downscale matrix generated, content will be rendered at (%ix%i)", CORE.Window.render.width, CORE.Window.render.height);
1511 }
1512 else if ((CORE.Window.screen.width < CORE.Window.display.width) || (CORE.Window.screen.height < CORE.Window.display.height))
1513 {
1514 // Required screen size is smaller than display size
1515 TRACELOG(LOG_INFO, "DISPLAY: Upscaling required: Screen size (%ix%i) smaller than display size (%ix%i)", CORE.Window.screen.width, CORE.Window.screen.height, CORE.Window.display.width, CORE.Window.display.height);
1516
1517 if ((CORE.Window.screen.width == 0) || (CORE.Window.screen.height == 0))
1518 {
1519 CORE.Window.screen.width = CORE.Window.display.width;
1520 CORE.Window.screen.height = CORE.Window.display.height;
1521 }
1522
1523 // Upscaling to fit display with border-bars
1524 float displayRatio = (float)CORE.Window.display.width/(float)CORE.Window.display.height;
1525 float screenRatio = (float)CORE.Window.screen.width/(float)CORE.Window.screen.height;
1526
1527 if (displayRatio <= screenRatio)
1528 {
1529 CORE.Window.render.width = CORE.Window.screen.width;
1530 CORE.Window.render.height = (int)round((float)CORE.Window.screen.width/displayRatio);
1531 CORE.Window.renderOffset.x = 0;
1532 CORE.Window.renderOffset.y = (CORE.Window.render.height - CORE.Window.screen.height);
1533 }
1534 else
1535 {
1536 CORE.Window.render.width = (int)round((float)CORE.Window.screen.height*displayRatio);
1537 CORE.Window.render.height = CORE.Window.screen.height;
1538 CORE.Window.renderOffset.x = (CORE.Window.render.width - CORE.Window.screen.width);
1539 CORE.Window.renderOffset.y = 0;
1540 }
1541 }
1542 else
1543 {
1544 CORE.Window.render.width = CORE.Window.screen.width;
1545 CORE.Window.render.height = CORE.Window.screen.height;
1546 CORE.Window.renderOffset.x = 0;
1547 CORE.Window.renderOffset.y = 0;
1548 }
1549 }
1550
1551 // Replacement for fopen(), used as linker wrap entry point (-Wl,--wrap=fopen)
1552 // REF: https://developer.android.com/ndk/reference/group/asset
1553 __attribute__((visibility("default"))) FILE *__wrap_fopen(const char *fileName, const char *mode)
1554 {
1555 FILE *file = NULL;
1556
1557 // NOTE: AAsset provides access to read-only asset, write operations use regular fopen
1558 if (mode[0] == 'w')
1559 {
1560 file = __real_fopen(TextFormat("%s/%s", platform.app->activity->internalDataPath, fileName), mode);
1561 if (file == NULL) file = __real_fopen(fileName, mode);
1562 }
1563 else
1564 {
1565 AAsset *asset = AAssetManager_open(platform.app->activity->assetManager, fileName, AASSET_MODE_UNKNOWN);
1566
1567 if (asset != NULL)
1568 {
1569 // Get pointer to file in the assets
1570 file = funopen(asset, android_read, android_write, android_seek, android_close);
1571 }
1572 else
1573 {
1574 // Do a regular open if file is not found in the assets
1575 file = __real_fopen(TextFormat("%s/%s", platform.app->activity->internalDataPath, fileName), mode);
1576 if (file == NULL) file = __real_fopen(fileName, mode);
1577 }
1578 }
1579
1580 return file;
1581 }
1582
1583 static int android_read(void *cookie, char *data, int dataSize)
1584 {
1585 return AAsset_read((AAsset *)cookie, data, dataSize);
1586 }
1587
1588 static int android_write(void *cookie, const char *data, int dataSize)
1589 {
1590 TRACELOG(LOG_WARNING, "ANDROID: Failed to provide write access to APK");
1591
1592 return EACCES;
1593 }
1594
1595 static fpos_t android_seek(void *cookie, fpos_t offset, int whence)
1596 {
1597 return AAsset_seek((AAsset *)cookie, offset, whence);
1598 }
1599
1600 static int android_close(void *cookie)
1601 {
1602 AAsset_close((AAsset *)cookie);
1603 return 0;
1604 }
1605
1606 // EOF