diff --git a/CMakeLists.txt b/CMakeLists.txt index ca29ce0d6245..82ebca2c1f8a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -29,6 +29,10 @@ include(CompilerFlags) # Registers build options that are exposed to cmake include(CMakeOptions.txt) +if ("${PLATFORM}" STREQUAL "iOS") + enable_language(OBJC) +endif() + if (UNIX AND NOT APPLE AND NOT "${PLATFORM}" MATCHES "DRM" AND NOT "${PLATFORM}" MATCHES "Web" AND NOT "${PLATFORM}" MATCHES "SDL") if (NOT GLFW_BUILD_WAYLAND AND NOT GLFW_BUILD_X11) message(FATAL_ERROR "Cannot disable both Wayland and X11") diff --git a/CMakeOptions.txt b/CMakeOptions.txt index 9e253dc55f87..e50c0f3b266d 100644 --- a/CMakeOptions.txt +++ b/CMakeOptions.txt @@ -6,7 +6,7 @@ if(EMSCRIPTEN) # When configuring web builds with "emcmake cmake -B build -S .", set PLATFORM to Web by default SET(PLATFORM Web CACHE STRING "Platform to build for.") endif() -enum_option(PLATFORM "Desktop;Win32;Web;WebRGFW;Android;Raspberry Pi;DRM;SDL;RGFW;Memory" "Platform to build for.") +enum_option(PLATFORM "Desktop;Win32;Web;WebRGFW;Android;iOS;Raspberry Pi;DRM;SDL;RGFW;Memory" "Platform to build for.") enum_option(OPENGL_VERSION "OFF;4.3;3.3;2.1;1.1;ES 2.0;ES 3.0;Software" "Force a specific OpenGL Version?") diff --git a/cmake/LibraryConfigurations.cmake b/cmake/LibraryConfigurations.cmake index 262150be0d8a..3a5bf430d8fa 100644 --- a/cmake/LibraryConfigurations.cmake +++ b/cmake/LibraryConfigurations.cmake @@ -133,6 +133,24 @@ elseif (${PLATFORM} STREQUAL "Android") set(LIBS_PRIVATE log android EGL GLESv2 OpenSLES atomic c) set(LIBS_PUBLIC m) +elseif (${PLATFORM} STREQUAL "iOS") + set(PLATFORM_CPP "PLATFORM_IOS") + set(GRAPHICS "GRAPHICS_API_OPENGL_ES3") + + find_library(UIKIT_LIBRARY UIKit) + find_library(QUARTZCORE_LIBRARY QuartzCore) + find_library(OPENGL_ES_LIBRARY OpenGLES) + find_library(COREMOTION_LIBRARY CoreMotion) + find_library(FOUNDATION_LIBRARY Foundation) + + set(LIBS_PRIVATE + ${UIKIT_LIBRARY} + ${QUARTZCORE_LIBRARY} + ${OPENGL_ES_LIBRARY} + ${COREMOTION_LIBRARY} + ${FOUNDATION_LIBRARY} + ) + elseif ("${PLATFORM}" STREQUAL "DRM") set(PLATFORM_CPP "PLATFORM_DRM") diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 55428e882c96..320f237b1396 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -36,6 +36,10 @@ set(raylib_sources rtextures.c ) +if (${PLATFORM} STREQUAL "iOS") + list(APPEND raylib_sources platforms/rcore_ios_main.m) +endif() + # Only build raudio if it's enabled if (NOT DEFINED SUPPORT_MODULE_RAUDIO OR SUPPORT_MODULE_RAUDIO) list(APPEND raylib_sources raudio.c) @@ -112,6 +116,11 @@ target_link_libraries(raylib PUBLIC ${LIBS_PUBLIC}) # and you will be able to select more build options include(CompileDefinitions) +if (${PLATFORM} STREQUAL "iOS") + target_compile_definitions(raylib PRIVATE GLES_SILENCE_DEPRECATION=1) + target_compile_options(raylib PRIVATE -Wno-deprecated-declarations) +endif() + # Registering include directories target_include_directories(raylib PUBLIC diff --git a/src/platforms/rcore_ios.c b/src/platforms/rcore_ios.c new file mode 100644 index 000000000000..1f33d75578bd --- /dev/null +++ b/src/platforms/rcore_ios.c @@ -0,0 +1,559 @@ +/********************************************************************************************** +* +* rcore_ios - Functions to manage window, graphics device and inputs +* +* PLATFORM: IOS +* - iOS (arm64) +* - iOS Simulator +* +* LIMITATIONS: +* - No keyboard input support +* - No gamepad input support +* +* DEPENDENCIES: +* - UIKit/QuartzCore/OpenGLES (provided by iOS SDK) +* - raylib_ios_main.m provides the native window and GL bridge +* +* LICENSE: zlib/libpng +* +* Copyright (c) 2013-2026 Ramon Santamaria (@raysan5) and contributors +* +**********************************************************************************************/ + +#include +#include +#include +#include +#include + +#if defined(__APPLE__) + #include +#endif + +// UIKit/OpenGL bridge functions implemented in [rcore_ios_main.m] +RLAPI bool ios_initialize_window(int requestedWidth, int requestedHeight, int *screenWidth, int *screenHeight, int *renderWidth, int *renderHeight, float *scaleX, float *scaleY); +RLAPI void ios_close_platform(void); +RLAPI void ios_make_current_context(void); +RLAPI void ios_present_frame(void); +RLAPI void *ios_get_window_handle(void); +RLAPI void ios_get_window_metrics(int *screenWidth, int *screenHeight, int *renderWidth, int *renderHeight, float *scaleX, float *scaleY); +RLAPI void *ios_get_proc_address(const char *name); +RLAPI void ios_open_url(const char *url); +RLAPI void ios_set_target_fps(float fps); + +//---------------------------------------------------------------------------------- +// Types and Structures Definition +//---------------------------------------------------------------------------------- +typedef struct { + bool initialized; + struct { + // TODO: Use CORE.Input.Touch data... why is it required to duplicate this data? + int32_t pointCount; // Number of active touch points + int32_t pointId[MAX_TOUCH_POINTS]; // Touch point ids + Vector2 position[MAX_TOUCH_POINTS]; // Touch point positions + int32_t hoverPoints[MAX_TOUCH_POINTS]; // Hover point slots + } TouchRaw; +} PlatformData; + +//---------------------------------------------------------------------------------- +// Global Variables Definition +//---------------------------------------------------------------------------------- +extern CoreData CORE; // Global CORE state context + +static PlatformData platform = { 0 }; // Platform specific data + +//---------------------------------------------------------------------------------- +// Module Internal Functions Declaration +//---------------------------------------------------------------------------------- +int InitPlatform(void); // Initialize platform (graphics, inputs and more) +bool InitGraphicsDevice(void); // Initialize graphics device + +static int FindTouchSlot(intptr_t touchId, bool allowAllocate); +static void UpdateMouseFromTouches(void); + +//---------------------------------------------------------------------------------- +// Module Functions Definition: Window and Graphics Device +//---------------------------------------------------------------------------------- + +// Check if application should close +bool WindowShouldClose(void) +{ + if (CORE.Window.ready) return CORE.Window.shouldClose; + else return true; +} + +// Toggle fullscreen mode +void ToggleFullscreen(void) +{ + TRACELOG(LOG_WARNING, "ToggleFullscreen() not available on target platform"); +} + +// Toggle borderless windowed mode +void ToggleBorderlessWindowed(void) +{ + TRACELOG(LOG_WARNING, "ToggleBorderlessWindowed() not available on target platform"); +} + +// Set window state: maximized, if resizable +void MaximizeWindow(void) +{ + TRACELOG(LOG_WARNING, "MaximizeWindow() not available on target platform"); +} + +// Set window state: minimized +void MinimizeWindow(void) +{ + TRACELOG(LOG_WARNING, "MinimizeWindow() not available on target platform"); +} + +// Restore window from being minimized/maximized +void RestoreWindow(void) +{ + TRACELOG(LOG_WARNING, "RestoreWindow() not available on target platform"); +} + +// Set window configuration state using flags +void SetWindowState(unsigned int flags) +{ + TRACELOG(LOG_WARNING, "SetWindowState() not available on target platform"); +} + +// Clear window configuration state flags +void ClearWindowState(unsigned int flags) +{ + TRACELOG(LOG_WARNING, "ClearWindowState() not available on target platform"); +} + +// Set icon for window +void SetWindowIcon(Image image) +{ + TRACELOG(LOG_WARNING, "SetWindowIcon() not available on target platform"); +} + +// Set icons for window +void SetWindowIcons(Image *images, int count) +{ + TRACELOG(LOG_WARNING, "SetWindowIcons() not available on target platform"); +} + +// Set title for window +void SetWindowTitle(const char *title) +{ + CORE.Window.title = title; +} + +// Set window position on screen (windowed mode) +void SetWindowPosition(int x, int y) +{ + TRACELOG(LOG_WARNING, "SetWindowPosition() not available on target platform"); +} + +// Set monitor for the current window +void SetWindowMonitor(int monitor) +{ + TRACELOG(LOG_WARNING, "SetWindowMonitor() not available on target platform"); +} + +// Set window minimum dimensions (FLAG_WINDOW_RESIZABLE) +void SetWindowMinSize(int width, int height) +{ + CORE.Window.screenMin.width = width; + CORE.Window.screenMin.height = height; +} + +// Set window maximum dimensions (FLAG_WINDOW_RESIZABLE) +void SetWindowMaxSize(int width, int height) +{ + CORE.Window.screenMax.width = width; + CORE.Window.screenMax.height = height; +} + +// Set window dimensions +void SetWindowSize(int width, int height) +{ + TRACELOG(LOG_WARNING, "SetWindowSize() not available on target platform"); +} + +// Set window opacity [0.0f..1.0f] +void SetWindowOpacity(float opacity) +{ + TRACELOG(LOG_WARNING, "SetWindowOpacity() not available on target platform"); +} + +// Set window focused +void SetWindowFocused(void) +{ + TRACELOG(LOG_WARNING, "SetWindowFocused() not available on target platform"); +} + +// Get native window handle +void *GetWindowHandle(void) +{ + return ios_get_window_handle(); +} + +// Get number of monitors +int GetMonitorCount(void) { return 1; } + +// Get current monitor where window is placed +int GetCurrentMonitor(void) { return 0; } + +// Get selected monitor position +Vector2 GetMonitorPosition(int monitor) { return (Vector2){ 0, 0 }; } + +// Get selected monitor width (currently used by monitor) +int GetMonitorWidth(int monitor) { return CORE.Window.screen.width; } + +// Get selected monitor height (currently used by monitor) +int GetMonitorHeight(int monitor) { return CORE.Window.screen.height; } + +// Get selected monitor physical width in millimetres +int GetMonitorPhysicalWidth(int monitor) { return 0; } + +// Get selected monitor physical height in millimetres +int GetMonitorPhysicalHeight(int monitor) { return 0; } + +// Get selected monitor refresh rate +int GetMonitorRefreshRate(int monitor) { return 0; } + +// Get the human-readable, UTF-8 encoded name of the selected monitor +const char *GetMonitorName(int monitor) { return ""; } + +// Get window position XY on monitor +Vector2 GetWindowPosition(void) { return (Vector2){ 0, 0 }; } + +// Get window scale DPI factor for current monitor +Vector2 GetWindowScaleDPI(void) +{ + int screenWidth = 0, screenHeight = 0; + int renderWidth = 0, renderHeight = 0; + float scaleX = 1.0f, scaleY = 1.0f; + + ios_get_window_metrics(&screenWidth, &screenHeight, &renderWidth, &renderHeight, &scaleX, &scaleY); + + (void)screenWidth; (void)screenHeight; + (void)renderWidth; (void)renderHeight; + + return (Vector2){ scaleX, scaleY }; +} + +// Set clipboard text content +void SetClipboardText(const char *text) +{ + TRACELOG(LOG_WARNING, "SetClipboardText() not implemented on target platform"); +} + +// Get clipboard text content +const char *GetClipboardText(void) +{ + TRACELOG(LOG_WARNING, "GetClipboardText() not implemented on target platform"); + return NULL; +} + +// Get clipboard image +Image GetClipboardImage(void) +{ + Image image = { 0 }; + TRACELOG(LOG_WARNING, "GetClipboardImage() not implemented on target platform"); + return image; +} + +// Show mouse cursor +void ShowCursor(void) { CORE.Input.Mouse.cursorHidden = false; } + +// Hide mouse cursor +void HideCursor(void) { CORE.Input.Mouse.cursorHidden = true; } + +// Enable cursor (unlock cursor) +void EnableCursor(void) +{ + SetMousePosition(CORE.Window.screen.width/2, CORE.Window.screen.height/2); + CORE.Input.Mouse.cursorHidden = false; +} + +// Disable cursor (lock cursor) +void DisableCursor(void) +{ + SetMousePosition(CORE.Window.screen.width/2, CORE.Window.screen.height/2); + CORE.Input.Mouse.cursorHidden = true; +} + +// Swap back buffer with front buffer (screen drawing) +void SwapScreenBuffer(void) +{ + if (CORE.Time.target > 0) ios_set_target_fps((float)(1.0/CORE.Time.target)); + + ios_present_frame(); +} + +//---------------------------------------------------------------------------------- +// Module Functions Definition: Misc +//---------------------------------------------------------------------------------- + +// Get elapsed time measure in seconds since InitTimer() +double GetTime(void) +{ + struct timespec ts = { 0 }; + clock_gettime(CLOCK_MONOTONIC, &ts); + unsigned long long int nanoSeconds = (unsigned long long int)ts.tv_sec*1000000000LLU + (unsigned long long int)ts.tv_nsec; + + return (double)(nanoSeconds - CORE.Time.base)*1e-9; // Elapsed time since InitTimer() +} + +// Open URL with default system browser (if available) +// NOTE: This function is only safe to use if you control the URL given. +// A user could craft a malicious string performing another action. +// Only call this function yourself not with user input or make sure to check +// the string yourself. Ref: https://github.com/raysan5/raylib/issues/686 +void OpenURL(const char *url) +{ + // Security check to (partially) avoid malicious code + // TODO: Security concerns, this cod should b reviewed (not only for iOS) + if (strchr(url, '\'') != NULL) TRACELOG(LOG_WARNING, "SYSTEM: Provided URL could be potentially malicious, avoid [\'] character"); + else ios_open_url(url); +} + +//---------------------------------------------------------------------------------- +// Module Functions Definition: Inputs +//---------------------------------------------------------------------------------- + +// Set internal gamepad mappings +int SetGamepadMappings(const char *mappings) +{ + TRACELOG(LOG_WARNING, "SetGamepadMappings() not implemented on target platform"); + return 0; +} + +// Set gamepad vibration +void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor, float duration) +{ + TRACELOG(LOG_WARNING, "SetGamepadVibration() not implemented on target platform"); +} + +// Set mouse position XY +void SetMousePosition(int x, int y) +{ + CORE.Input.Mouse.currentPosition = (Vector2){ (float)x, (float)y }; + CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition; +} + +// Set mouse cursor +void SetMouseCursor(int cursor) +{ + TRACELOG(LOG_WARNING, "SetMouseCursor() not implemented on target platform"); +} + +// Get physical key name +const char *GetKeyName(int key) +{ + TRACELOG(LOG_WARNING, "GetKeyName() not implemented on target platform"); + return ""; +} + +// Register all input events +void PollInputEvents(void) +{ +#if defined(SUPPORT_GESTURES_SYSTEM) + // NOTE: Gestures update must be called every frame to reset gestures correctly + // because ProcessGestureEvent() is called on an event, not every frame + UpdateGestures(); +#endif + + // Reset keys/chars pressed registered + CORE.Input.Keyboard.keyPressedQueueCount = 0; + CORE.Input.Keyboard.charPressedQueueCount = 0; + + // Reset key repeats + for (int i = 0; i < MAX_KEYBOARD_KEYS; i++) CORE.Input.Keyboard.keyRepeatInFrame[i] = 0; + + // Reset last gamepad button/axis registered state + CORE.Input.Gamepad.lastButtonPressed = 0; // GAMEPAD_BUTTON_UNKNOWN + + // Register previous touch states + for (int i = 0; i < MAX_TOUCH_POINTS; i++) + CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i]; + + // Register previous keys states + for (int i = 0; i < MAX_KEYBOARD_KEYS; i++) + { + CORE.Input.Keyboard.previousKeyState[i] = CORE.Input.Keyboard.currentKeyState[i]; + CORE.Input.Keyboard.keyRepeatInFrame[i] = 0; + } + + UpdateMouseFromTouches(); +} + +//---------------------------------------------------------------------------------- +// Module Internal Functions Definition +//---------------------------------------------------------------------------------- + +// Initialize platform: graphics, inputs and more +int InitPlatform(void) +{ + FLAG_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE); + + if (FLAG_IS_SET(CORE.Window.flags, FLAG_MSAA_4X_HINT)) TRACELOG(LOG_INFO, "DISPLAY: Trying to enable MSAA x4"); + + int screenWidth = 0, screenHeight = 0; + int renderWidth = 0, renderHeight = 0; + float scaleX = 1.0f, scaleY = 1.0f; + + if (!ios_initialize_window(CORE.Window.screen.width, CORE.Window.screen.height, + &screenWidth, &screenHeight, &renderWidth, &renderHeight, &scaleX, &scaleY)) + { + TRACELOG(LOG_FATAL, "PLATFORM: Failed to initialize iOS window and graphics context"); + return -1; + } + + ios_make_current_context(); + + CORE.Window.screen.width = screenWidth; + CORE.Window.screen.height = screenHeight; + CORE.Window.display.width = (int)((float)screenWidth*scaleX); + CORE.Window.display.height = (int)((float)screenHeight*scaleY); + CORE.Window.render.width = renderWidth; + CORE.Window.render.height = renderHeight; + CORE.Window.currentFbo.width = CORE.Window.render.width; + CORE.Window.currentFbo.height = CORE.Window.render.height; + CORE.Window.screenScale = MatrixScale(scaleX, scaleY, 1.0f); + + rlLoadExtensions(ios_get_proc_address); + + for (int i = 0; i < MAX_TOUCH_POINTS; i++) platform.TouchRaw.hoverPoints[i] = -1; + + platform.initialized = true; + CORE.Window.ready = true; + + InitTimer(); + CORE.Storage.basePath = GetWorkingDirectory(); + + TRACELOG(LOG_INFO, "PLATFORM: IOS: Initialized successfully"); + TRACELOG(LOG_INFO, " > Screen size: %i x %i", CORE.Window.screen.width, CORE.Window.screen.height); + TRACELOG(LOG_INFO, " > Render size: %i x %i", CORE.Window.render.width, CORE.Window.render.height); + + return 0; +} + +// Close platform +void ClosePlatform(void) +{ + ios_close_platform(); + + CORE = (CoreData){ 0 }; + platform = (PlatformData){ 0 }; +} + +// Find or allocate a touch slot for the given touchId +static int FindTouchSlot(intptr_t touchId, bool allowAllocate) +{ + for (int i = 0; i < platform.TouchRaw.pointCount; i++) + { + if (platform.TouchRaw.pointId[i] == (int32_t)touchId) return i; + } + + if (!allowAllocate) return -1; + if (platform.TouchRaw.pointCount < MAX_TOUCH_POINTS) return platform.TouchRaw.pointCount; + + return -1; +} + +// Sync mouse position/state from primary touch point +static void UpdateMouseFromTouches(void) +{ + if (platform.TouchRaw.pointCount > 0) + { + CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition; + CORE.Input.Mouse.currentPosition = platform.TouchRaw.position[0]; + CORE.Input.Mouse.currentWheelMove = (Vector2){ 0.0f, 0.0f }; + } +} + +//---------------------------------------------------------------------------------- +// iOS Bridge Callbacks (called from rcore_ios_main.m) +//---------------------------------------------------------------------------------- + +void ios_handle_touch_began(intptr_t touchId, float x, float y) +{ + int index = FindTouchSlot(touchId, true); + if (index < 0) return; + + platform.TouchRaw.pointId[index] = (int32_t)touchId; + platform.TouchRaw.position[index] = (Vector2){ x, y }; + + CORE.Input.Touch.pointId[index] = (int)touchId; + CORE.Input.Touch.position[index] = (Vector2){ x, y }; + CORE.Input.Touch.currentTouchState[index] = 1; + CORE.Input.Touch.previousTouchState[index] = 0; + + CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_LEFT] = 1; + CORE.Input.Mouse.previousButtonState[MOUSE_BUTTON_LEFT] = 0; + + if (platform.TouchRaw.pointCount < MAX_TOUCH_POINTS) platform.TouchRaw.pointCount++; + + CORE.Input.Touch.pointCount = platform.TouchRaw.pointCount; + + UpdateMouseFromTouches(); +} + +void ios_handle_touch_moved(intptr_t touchId, float x, float y) +{ + int index = FindTouchSlot(touchId, false); + if (index < 0) return; + + platform.TouchRaw.position[index] = (Vector2){ x, y }; + CORE.Input.Touch.pointId[index] = (int)touchId; + CORE.Input.Touch.position[index] = (Vector2){ x, y }; + CORE.Input.Touch.currentTouchState[index] = 1; + CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_LEFT] = 1; + CORE.Input.Touch.pointCount = platform.TouchRaw.pointCount; + + UpdateMouseFromTouches(); +} + +void ios_handle_touch_ended(intptr_t touchId, float x, float y) +{ + int index = FindTouchSlot(touchId, false); + if (index < 0) return; + + platform.TouchRaw.position[index] = (Vector2){ x, y }; + CORE.Input.Touch.position[index] = (Vector2){ x, y }; + CORE.Input.Touch.currentTouchState[index] = 0; + CORE.Input.Touch.previousTouchState[index] = 1; + CORE.Input.Touch.pointId[index] = 0; + + // Compact the touch arrays — shift remaining points down + for (int i = index; i < platform.TouchRaw.pointCount - 1; i++) + { + platform.TouchRaw.pointId[i] = platform.TouchRaw.pointId[i + 1]; + platform.TouchRaw.position[i] = platform.TouchRaw.position[i + 1]; + + CORE.Input.Touch.pointId[i] = CORE.Input.Touch.pointId[i + 1]; + CORE.Input.Touch.position[i] = CORE.Input.Touch.position[i + 1]; + CORE.Input.Touch.currentTouchState[i] = CORE.Input.Touch.currentTouchState[i + 1]; + CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.previousTouchState[i + 1]; + } + + if (platform.TouchRaw.pointCount > 0) platform.TouchRaw.pointCount--; + CORE.Input.Touch.pointCount = platform.TouchRaw.pointCount; + + CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_LEFT] = (platform.TouchRaw.pointCount > 0)? 1 : 0; + CORE.Input.Mouse.previousButtonState[MOUSE_BUTTON_LEFT] = 1; + + UpdateMouseFromTouches(); +} + +void ios_handle_touch_cancelled(intptr_t touchId, float x, float y) +{ + ios_handle_touch_ended(touchId, x, y); +} + +void ios_request_close(void) +{ + CORE.Window.shouldClose = true; +} + +void ios_set_window_focused(bool focused) +{ + if (focused) FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED); + else FLAG_SET(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED); +} diff --git a/src/platforms/rcore_ios_main.m b/src/platforms/rcore_ios_main.m new file mode 100644 index 000000000000..c6e29985f649 --- /dev/null +++ b/src/platforms/rcore_ios_main.m @@ -0,0 +1,645 @@ +/********************************************************************************************** +* +* rcore_ios_main.m - Functions required by iOS platform implementation +* +* PLATFORM: IOS +* - iOS (arm64) +* - iOS Simulator +* +* LIMITATIONS: +* - No keyboard input support +* - No gamepad input support +* +* DEPENDENCIES: +* - UIKit/QuartzCore/OpenGLES (provided by iOS SDK) +* +* LICENSE: zlib/libpng +* +* Copyright (c) 2013-2026 Ramon Santamaria (@raysan5) and contributors +* +**********************************************************************************************/ + +#import +#import +#import +#import +#import +#import +#import + +#include +#include +#include +#include + +extern int raylib_main(int argc, char *argv[]); + +extern void ios_handle_touch_began(intptr_t touchId, float x, float y); +extern void ios_handle_touch_moved(intptr_t touchId, float x, float y); +extern void ios_handle_touch_ended(intptr_t touchId, float x, float y); +extern void ios_handle_touch_cancelled(intptr_t touchId, float x, float y); +extern void ios_request_close(void); +extern void ios_set_window_focused(bool focused); + +typedef struct IOSBridgeState { + int argc; + char **argv; + UIWindow *window; + UIViewController *viewController; + UIView *glView; + EAGLContext *context; + GLuint framebuffer; + GLuint colorBuffer; + GLuint depthBuffer; + int screenWidth; + int screenHeight; + int renderWidth; + int renderHeight; + float scaleX; + float scaleY; + bool shuttingDown; + bool initialized; +} IOSBridgeState; + +static IOSBridgeState ios = {0}; + +@interface RaylibController : NSObject + ++ (instancetype)sharedController; + +- (void)startInternal; + +- (void)startDisplayLink:(float)minFPS; + +- (void)stopDisplayLink; + +- (void)waitForVSync; + +- (void)setTargetFPS:(float)fps; + +@end + +@implementation RaylibController { + CADisplayLink *_displayLink; + dispatch_semaphore_t _frameSemaphore; + dispatch_queue_t _raylibQueue; + int64_t _vsyncCount; + int64_t _lastConsumedVsync; + float _minimumFPS; + BOOL _raylibStarted; +} + ++ (instancetype)sharedController { + static RaylibController *instance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + instance = [[self alloc] init]; + }); + + return instance; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _frameSemaphore = dispatch_semaphore_create(0); + _raylibQueue = + dispatch_queue_create("com.raylib.engine", DISPATCH_QUEUE_SERIAL); + _vsyncCount = 0; + _lastConsumedVsync = 0; + _raylibStarted = NO; + _minimumFPS = 60.0f; + } + + return self; +} + +- (void)startInternal { + if (_raylibStarted) + return; + + _raylibStarted = YES; + + dispatch_async(_raylibQueue, ^{ + [[NSThread currentThread] setName:@"com.raylib.engine"]; + + // NSLog(@"[raylib][IOS] raylib thread: %@", [NSThread currentThread].name); + + raylib_main(ios.argc, ios.argv); + }); +} + +- (void)startDisplayLink:(float)minFPS { + if (![NSThread isMainThread]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self startDisplayLink:_minimumFPS]; + }); + + return; + } + + _minimumFPS = minFPS; + + if (_displayLink != nil) + return; + + _displayLink = + [CADisplayLink displayLinkWithTarget:self + selector:@selector(onDisplayFrame:)]; + + NSInteger maxFPS = [UIScreen mainScreen].maximumFramesPerSecond; + + // Use the display native refresh rate + // NOTE: Driven dynamically via setTargetFPS, no hardcoded maxFPS + //_displayLink.preferredFrameRateRange = + // CAFrameRateRangeMake(_minimumFPS, maxFPS, maxFPS); + + [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] + forMode:NSRunLoopCommonModes]; +} + +- (void)onDisplayFrame:(CADisplayLink *)link { + (void)link; + + __atomic_fetch_add(&_vsyncCount, 1, __ATOMIC_RELEASE); + dispatch_semaphore_signal(_frameSemaphore); +} + +- (void)stopDisplayLink { + if (![NSThread isMainThread]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self stopDisplayLink]; + }); + + return; + } + + if (_displayLink == nil) + return; + + [_displayLink invalidate]; + _displayLink = nil; + + dispatch_semaphore_signal(_frameSemaphore); +} + +- (void)waitForVSync { + int64_t current = __atomic_load_n(&_vsyncCount, __ATOMIC_ACQUIRE); + + while ((current - _lastConsumedVsync) < 1 && !ios.shuttingDown) { + dispatch_semaphore_wait(_frameSemaphore, DISPATCH_TIME_FOREVER); + current = __atomic_load_n(&_vsyncCount, __ATOMIC_ACQUIRE); + } + + _lastConsumedVsync = current; +} + +- (void)setTargetFPS:(float)fps { + _minimumFPS = fps; + if (_displayLink != nil) + _displayLink.preferredFrameRateRange = + CAFrameRateRangeMake(fps, fps, fps); +} + +@end + +@interface RaylibGLView : UIView +@end + +@implementation RaylibGLView + ++ (Class)layerClass { + return [CAEAGLLayer class]; +} + +@end + +@interface RaylibViewController : UIViewController +@end + +@implementation RaylibViewController + +- (BOOL)prefersStatusBarHidden { + return YES; +} + +- (void)loadView { + self.view = [[RaylibGLView alloc] initWithFrame:[UIScreen mainScreen].bounds]; + self.view.multipleTouchEnabled = YES; +} + +- (void)viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; + ios_set_window_focused(true); +} + +- (void)viewWillDisappear:(BOOL)animated { + [super viewWillDisappear:animated]; + ios_set_window_focused(false); +} + +- (void)forwardTouches:(NSSet *)touches action:(int)action { + for (UITouch *touch in touches) { + CGPoint point = [touch locationInView:self.view]; + intptr_t touchId = (intptr_t)(__bridge void *)touch; + + switch (action) { + case 0: + ios_handle_touch_began(touchId, point.x, point.y); + break; + case 1: + ios_handle_touch_moved(touchId, point.x, point.y); + break; + case 2: + ios_handle_touch_ended(touchId, point.x, point.y); + break; + case 3: + ios_handle_touch_cancelled(touchId, point.x, point.y); + break; + default: + break; + } + } +} + +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { + (void)event; + [self forwardTouches:touches action:0]; +} + +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { + (void)event; + [self forwardTouches:touches action:1]; +} + +- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { + (void)event; + [self forwardTouches:touches action:2]; +} + +- (void)touchesCancelled:(NSSet *)touches + withEvent:(UIEvent *)event { + (void)event; + [self forwardTouches:touches action:3]; +} + +@end + +static void shutdown_internal(void) { + [[RaylibController sharedController] stopDisplayLink]; + + if (ios.context != nil) { + [EAGLContext setCurrentContext:ios.context]; + + if (ios.framebuffer != 0) + glDeleteFramebuffers(1, &ios.framebuffer); + if (ios.colorBuffer != 0) + glDeleteRenderbuffers(1, &ios.colorBuffer); + if (ios.depthBuffer != 0) + glDeleteRenderbuffers(1, &ios.depthBuffer); + + ios.framebuffer = 0; + ios.colorBuffer = 0; + ios.depthBuffer = 0; + ios.context = nil; + } + + ios.glView = nil; + ios.viewController = nil; + ios.window = nil; + ios.initialized = false; +} + +void ios_close_platform(void) { + if (!ios.initialized || ios.shuttingDown) + return; + + ios.shuttingDown = true; + + if ([NSThread isMainThread]) + shutdown_internal(); + else + dispatch_async(dispatch_get_main_queue(), ^{ + shutdown_internal(); + }); +} + +@interface RaylibAppDelegate : UIResponder +@end + +@interface RaylibSceneDelegate : UIResponder +@property(strong, nonatomic) UIWindow *window; +@end + +@implementation RaylibAppDelegate + +- (BOOL)application:(UIApplication *)application + didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + (void)application; + (void)launchOptions; + + return YES; +} + +- (UISceneConfiguration *)application:(UIApplication *)application + configurationForConnectingSceneSession: + (UISceneSession *)connectingSceneSession + options:(UISceneConnectionOptions *)options { + (void)application; + (void)connectingSceneSession; + (void)options; + + UISceneConfiguration *configuration = [UISceneConfiguration + configurationWithName:@"Default Configuration" + sessionRole:UIWindowSceneSessionRoleApplication]; + configuration.delegateClass = [RaylibSceneDelegate class]; + return configuration; +} + +- (void)applicationWillResignActive:(UIApplication *)application { + (void)application; + ios_set_window_focused(false); +} + +- (void)applicationDidBecomeActive:(UIApplication *)application { + (void)application; + ios_set_window_focused(true); +} + +- (void)applicationWillTerminate:(UIApplication *)application { + (void)application; + ios_request_close(); +} + +@end + +@implementation RaylibSceneDelegate + +- (void)scene:(UIScene *)scene + willConnectToSession:(UISceneSession *)session + options:(UISceneConnectionOptions *)connectionOptions { + (void)session; + (void)connectionOptions; + + if (![scene isKindOfClass:[UIWindowScene class]]) + return; + + UIWindowScene *windowScene = (UIWindowScene *)scene; + self.window = [[UIWindow alloc] initWithWindowScene:windowScene]; + ios.window = self.window; + + if (ios.viewController == nil) { + ios.viewController = [[RaylibViewController alloc] init]; + } + self.window.rootViewController = ios.viewController; + [self.window makeKeyAndVisible]; + + [[RaylibController sharedController] startDisplayLink:60.0f]; + + [[RaylibController sharedController] startInternal]; +} + +- (void)sceneDidBecomeActive:(UIScene *)scene { + (void)scene; + ios_set_window_focused(true); +} + +- (void)sceneWillResignActive:(UIScene *)scene { + (void)scene; + ios_set_window_focused(false); +} + +- (void)sceneDidDisconnect:(UIScene *)scene { + (void)scene; + ios_request_close(); + ios_close_platform(); +} + +@end + +static BOOL ios_setup_gl(void) { + if (!ios.window || !ios.viewController) + return NO; + + ios.glView = ios.viewController.view; + CAEAGLLayer *eaglLayer = (CAEAGLLayer *)ios.glView.layer; + eaglLayer.opaque = YES; + eaglLayer.drawableProperties = @{ + kEAGLDrawablePropertyRetainedBacking : @NO, + kEAGLDrawablePropertyColorFormat : kEAGLColorFormatRGBA8 + }; + + // Ensure layer uses native scale for proper retina resolution + CGFloat nativeScale = [UIScreen mainScreen].nativeScale; + eaglLayer.contentsScale = nativeScale; + ios.glView.contentScaleFactor = nativeScale; + + ios.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3]; + if (!ios.context) { + ios.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; + } + + if (!ios.context) + return NO; + + [EAGLContext setCurrentContext:ios.context]; + + glGenFramebuffers(1, &ios.framebuffer); + glGenRenderbuffers(1, &ios.colorBuffer); + glGenRenderbuffers(1, &ios.depthBuffer); + + glBindFramebuffer(GL_FRAMEBUFFER, ios.framebuffer); + + glBindRenderbuffer(GL_RENDERBUFFER, ios.colorBuffer); + if (![ios.context renderbufferStorage:GL_RENDERBUFFER + fromDrawable:eaglLayer]) { + return NO; + } + + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_RENDERBUFFER, ios.colorBuffer); + + glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, + &ios.renderWidth); + glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, + &ios.renderHeight); + + glBindRenderbuffer(GL_RENDERBUFFER, ios.depthBuffer); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, ios.renderWidth, + ios.renderHeight); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, + GL_RENDERBUFFER, ios.depthBuffer); + + GLenum fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if (fbStatus != GL_FRAMEBUFFER_COMPLETE) { + NSLog(@"[raylib][IOS] Framebuffer incomplete: 0x%04X", fbStatus); + } else { + NSLog(@"[raylib][IOS] Framebuffer complete (%d x %d)", ios.renderWidth, + ios.renderHeight); + } + + [EAGLContext setCurrentContext:nil]; + + return fbStatus == GL_FRAMEBUFFER_COMPLETE; +} + +bool ios_initialize_window(int requestedWidth, int requestedHeight, + int *screenWidth, int *screenHeight, + int *renderWidth, int *renderHeight, float *scaleX, + float *scaleY) { + (void)requestedWidth; + (void)requestedHeight; + + __block bool ok = false; + dispatch_sync(dispatch_get_main_queue(), ^{ + if (ios.window == nil) { + ios.window = + [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; + } + + if (ios.viewController == nil) { + ios.viewController = [[RaylibViewController alloc] init]; + } + + ios.window.rootViewController = ios.viewController; + [ios.window makeKeyAndVisible]; + + ok = ios_setup_gl(); + + UIScreen *screen = [UIScreen mainScreen]; + CGSize boundsSize = screen.bounds.size; + ios.screenWidth = (int)boundsSize.width; + ios.screenHeight = (int)boundsSize.height; + ios.scaleX = (float)screen.nativeScale; + ios.scaleY = (float)screen.nativeScale; + + if (screenWidth) + *screenWidth = ios.screenWidth; + + if (screenHeight) + *screenHeight = ios.screenHeight; + + if (renderWidth) + *renderWidth = ios.renderWidth; + + if (renderHeight) + *renderHeight = ios.renderHeight; + + if (scaleX) + *scaleX = ios.scaleX; + + if (scaleY) + *scaleY = ios.scaleY; + }); + + ios.initialized = ok; + return ok; +} + +void ios_make_current_context(void) { + if (ios.context != nil) + [EAGLContext setCurrentContext:ios.context]; + + if (ios.framebuffer != 0) + glBindFramebuffer(GL_FRAMEBUFFER, ios.framebuffer); + if (ios.colorBuffer != 0) + glBindRenderbuffer(GL_RENDERBUFFER, ios.colorBuffer); + + glViewport(0, 0, ios.renderWidth, ios.renderHeight); + // NSLog(@"[raylib][IOS] IOSMakeCurrentContext: thread=%@, fb=%u, rb=%u, " + // @"viewport=%dx%d", + // [NSThread currentThread], ios.framebuffer, ios.colorBuffer, + // ios.renderWidth, ios.renderHeight); +} + +void ios_present_frame(void) { + if (ios.context == nil || ios.shuttingDown) + return; + + if ([EAGLContext currentContext] != ios.context) { + [EAGLContext setCurrentContext:ios.context]; + } + + // NSLog(@"[raylib][IOS] IOSPresentFrame: thread=%@, currentContext=%@", + // [NSThread currentThread], [EAGLContext currentContext]); + + [ios.context presentRenderbuffer:GL_RENDERBUFFER]; + +#if RLGL_SHOW_GL_DETAILS_INFO + GLenum err = glGetError(); + if (err != GL_NO_ERROR) + NSLog(@"[raylib][IOS] glGetError after present: 0x%04X", err); +#endif + + if (!ios.shuttingDown) { + [[RaylibController sharedController] waitForVSync]; + } +} + +void *ios_get_window_handle(void) { return (__bridge void *)ios.window; } + +void ios_get_window_metrics(int *screenWidth, int *screenHeight, + int *renderWidth, int *renderHeight, float *scaleX, + float *scaleY) { + if (screenWidth) + *screenWidth = ios.screenWidth; + + if (screenHeight) + *screenHeight = ios.screenHeight; + + if (renderWidth) + *renderWidth = ios.renderWidth; + + if (renderHeight) + *renderHeight = ios.renderHeight; + + if (scaleX) + *scaleX = ios.scaleX; + + if (scaleY) + *scaleY = ios.scaleY; +} + +void *ios_get_proc_address(const char *name) { + return dlsym(RTLD_DEFAULT, name); +} + +void ios_open_url(const char *url) { + if (!url) { + NSLog(@"[raylib][IOS] invalid URL: null"); + return; + } + + NSURLComponents *components = [NSURLComponents + componentsWithString:[NSString stringWithUTF8String:url]]; + + if (components == nil || components.scheme == nil) { + + NSLog(@"[raylib][IOS] invalid URL: %s, Scheme: %s", url, + components ? components.scheme.UTF8String : "nil"); + return; + } + + if (components.URL != nil) { + + dispatch_async(dispatch_get_main_queue(), ^{ + [[UIApplication sharedApplication] openURL:components.URL + options:@{} + completionHandler:nil]; + }); + } +} + +void ios_set_target_fps(float fps) { + [[RaylibController sharedController] setTargetFPS:fps]; +} + +int main(int argc, char *argv[]) { + ios.argc = argc; + ios.argv = argv; + + @autoreleasepool { + return UIApplicationMain(argc, argv, nil, + NSStringFromClass([RaylibAppDelegate class])); + } +} \ No newline at end of file diff --git a/src/rcore.c b/src/rcore.c index a37400cf1c83..96c51a2ccec8 100644 --- a/src/rcore.c +++ b/src/rcore.c @@ -526,6 +526,8 @@ const char *TextFormat(const char *text, ...); // Formatting of text with variab #include "platforms/rcore_drm.c" #elif defined(PLATFORM_ANDROID) #include "platforms/rcore_android.c" +#elif defined(PLATFORM_IOS) + #include "platforms/rcore_ios.c" #elif defined(PLATFORM_MEMORY) #include "platforms/rcore_memory.c" #else @@ -604,6 +606,8 @@ void InitWindow(int width, int height, const char *title) TRACELOG(LOG_INFO, "Platform backend: ANDROID"); #elif defined(PLATFORM_MEMORY) TRACELOG(LOG_INFO, "Platform backend: MEMORY (No OS)"); +#elif defined(PLATFORM_IOS) + TRACELOG(LOG_INFO, "Platform backend: iOS"); #else // TODO: Include your custom platform backend! // i.e software rendering backend or console backend! diff --git a/src/rlgl.h b/src/rlgl.h index e1c0089dc7f6..7c591840ccd4 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -876,9 +876,16 @@ RLAPI void rlLoadDrawQuad(void); // Load and draw a quad #endif #if defined(GRAPHICS_API_OPENGL_ES3) - #include // OpenGL ES 3.0 library - #define GL_GLEXT_PROTOTYPES - #include // OpenGL ES 2.0 extensions library + #if defined(PLATFORM_IOS) + #include // OpenGL ES 3.0 library + #define GL_GLEXT_PROTOTYPES + #include // OpenGL ES extensions used by raylib + #include // OpenGL ES 3.0 extensions library + #else + #include // OpenGL ES 3.0 library + #define GL_GLEXT_PROTOTYPES + #include // OpenGL ES 2.0 extensions library + #endif #elif defined(GRAPHICS_API_OPENGL_ES2) // NOTE: OpenGL ES 2.0 can be enabled on Desktop platforms, // in that case, functions are loaded from a custom glad for OpenGL ES 2.0