baxi 1 hafta önce
ebeveyn
işleme
f92dad8451
100 değiştirilmiş dosya ile 17703 ekleme ve 0 silme
  1. 32 0
      unity_ios/Classes/CrashReporter.h
  2. 108 0
      unity_ios/Classes/CrashReporter.mm
  3. 102 0
      unity_ios/Classes/PLCrashReporter.h
  4. 37 0
      unity_ios/Classes/PluginBase/AppDelegateListener.h
  5. 63 0
      unity_ios/Classes/PluginBase/AppDelegateListener.mm
  6. 29 0
      unity_ios/Classes/PluginBase/LifeCycleListener.h
  7. 39 0
      unity_ios/Classes/PluginBase/LifeCycleListener.mm
  8. 67 0
      unity_ios/Classes/PluginBase/RenderPluginDelegate.h
  9. 90 0
      unity_ios/Classes/PluginBase/RenderPluginDelegate.mm
  10. 51 0
      unity_ios/Classes/PluginBase/UnityViewControllerListener.h
  11. 80 0
      unity_ios/Classes/PluginBase/UnityViewControllerListener.mm
  12. 23 0
      unity_ios/Classes/Prefix.pch
  13. 238 0
      unity_ios/Classes/Preprocessor.h
  14. 118 0
      unity_ios/Classes/Quaternion4.h
  15. 43 0
      unity_ios/Classes/RedefinePlatforms.h
  16. 5 0
      unity_ios/Classes/UI/ActivityIndicator.h
  17. 49 0
      unity_ios/Classes/UI/ActivityIndicator.mm
  18. 75 0
      unity_ios/Classes/UI/Keyboard.h
  19. 1274 0
      unity_ios/Classes/UI/Keyboard.mm
  20. 20 0
      unity_ios/Classes/UI/OrientationSupport.h
  21. 165 0
      unity_ios/Classes/UI/OrientationSupport.mm
  22. 18 0
      unity_ios/Classes/UI/StoreReview.m
  23. 105 0
      unity_ios/Classes/UI/UnityAppController+ViewHandling.h
  24. 475 0
      unity_ios/Classes/UI/UnityAppController+ViewHandling.mm
  25. 5 0
      unity_ios/Classes/UI/UnityScene.h
  26. 126 0
      unity_ios/Classes/UI/UnityScene.mm
  27. 268 0
      unity_ios/Classes/UI/UnityView+Keyboard.mm
  28. 15 0
      unity_ios/Classes/UI/UnityView+iOS.h
  29. 137 0
      unity_ios/Classes/UI/UnityView+iOS.mm
  30. 15 0
      unity_ios/Classes/UI/UnityView+tvOS.h
  31. 66 0
      unity_ios/Classes/UI/UnityView+tvOS.mm
  32. 71 0
      unity_ios/Classes/UI/UnityView.h
  33. 437 0
      unity_ios/Classes/UI/UnityView.mm
  34. 62 0
      unity_ios/Classes/UI/UnityViewControllerBase+iOS.h
  35. 320 0
      unity_ios/Classes/UI/UnityViewControllerBase+iOS.mm
  36. 7 0
      unity_ios/Classes/UI/UnityViewControllerBase+tvOS.h
  37. 9 0
      unity_ios/Classes/UI/UnityViewControllerBase+tvOS.mm
  38. 7 0
      unity_ios/Classes/UI/UnityViewControllerBase+visionOS.h
  39. 9 0
      unity_ios/Classes/UI/UnityViewControllerBase+visionOS.mm
  40. 42 0
      unity_ios/Classes/UI/UnityViewControllerBase.h
  41. 90 0
      unity_ios/Classes/UI/UnityViewControllerBase.mm
  42. 35 0
      unity_ios/Classes/UndefinePlatforms.h
  43. 16 0
      unity_ios/Classes/Unity/AVCapture.h
  44. 50 0
      unity_ios/Classes/Unity/AVCapture.mm
  45. 19 0
      unity_ios/Classes/Unity/CMVideoSampling.h
  46. 79 0
      unity_ios/Classes/Unity/CMVideoSampling.mm
  47. 47 0
      unity_ios/Classes/Unity/CVTextureCache.h
  48. 144 0
      unity_ios/Classes/Unity/CVTextureCache.mm
  49. 72 0
      unity_ios/Classes/Unity/CameraCapture.h
  50. 853 0
      unity_ios/Classes/Unity/CameraCapture.mm
  51. 628 0
      unity_ios/Classes/Unity/DeviceSettings.mm
  52. 71 0
      unity_ios/Classes/Unity/DisplayManager.h
  53. 850 0
      unity_ios/Classes/Unity/DisplayManager.mm
  54. 133 0
      unity_ios/Classes/Unity/Filesystem.mm
  55. 268 0
      unity_ios/Classes/Unity/FullScreenVideoPlayer.mm
  56. 442 0
      unity_ios/Classes/Unity/IUnityEventQueue.h
  57. 64 0
      unity_ios/Classes/Unity/IUnityGraphics.h
  58. 117 0
      unity_ios/Classes/Unity/IUnityGraphicsMetal.h
  59. 206 0
      unity_ios/Classes/Unity/IUnityInterface.h
  60. 37 0
      unity_ios/Classes/Unity/IUnityLog.h
  61. 24 0
      unity_ios/Classes/Unity/IUnityMemoryManager.h
  62. 99 0
      unity_ios/Classes/Unity/IUnityPhysicsBackendSystem.h
  63. 511 0
      unity_ios/Classes/Unity/IUnityProfiler.h
  64. 174 0
      unity_ios/Classes/Unity/IUnityProfilerCallbacks.h
  65. 379 0
      unity_ios/Classes/Unity/IUnityRenderingExtensions.h
  66. 375 0
      unity_ios/Classes/Unity/InternalProfiler.cpp
  67. 32 0
      unity_ios/Classes/Unity/InternalProfiler.h
  68. 228 0
      unity_ios/Classes/Unity/MetalHelper.mm
  69. 28 0
      unity_ios/Classes/Unity/NoGraphicsHelper.mm
  70. 35 0
      unity_ios/Classes/Unity/ObjCRuntime.h
  71. 106 0
      unity_ios/Classes/Unity/OnDemandResources.mm
  72. 145 0
      unity_ios/Classes/Unity/UnityForwardDecls.h
  73. 441 0
      unity_ios/Classes/Unity/UnityInterface.h
  74. 378 0
      unity_ios/Classes/Unity/UnityRendering.h
  75. 53 0
      unity_ios/Classes/Unity/UnityReplayKit.h
  76. 563 0
      unity_ios/Classes/Unity/UnityReplayKit.mm
  77. 207 0
      unity_ios/Classes/Unity/UnityReplayKit_Scripting.mm
  78. 134 0
      unity_ios/Classes/Unity/UnitySharedDecls.h
  79. 5 0
      unity_ios/Classes/Unity/UnityTrampolineCompatibility.h
  80. 558 0
      unity_ios/Classes/Unity/UnityWebRequest.mm
  81. 53 0
      unity_ios/Classes/Unity/VideoPlayer.h
  82. 495 0
      unity_ios/Classes/Unity/VideoPlayer.mm
  83. 16 0
      unity_ios/Classes/UnityAppController+Rendering+visionOS.h
  84. 117 0
      unity_ios/Classes/UnityAppController+Rendering+visionOS.mm
  85. 61 0
      unity_ios/Classes/UnityAppController+Rendering.h
  86. 393 0
      unity_ios/Classes/UnityAppController+Rendering.mm
  87. 10 0
      unity_ios/Classes/UnityAppController+Thermal.h
  88. 73 0
      unity_ios/Classes/UnityAppController+Thermal.mm
  89. 10 0
      unity_ios/Classes/UnityAppController+UnityInterface.h
  90. 19 0
      unity_ios/Classes/UnityAppController+UnityInterface.mm
  91. 177 0
      unity_ios/Classes/UnityAppController.h
  92. 904 0
      unity_ios/Classes/UnityAppController.mm
  93. 53 0
      unity_ios/Classes/UnityTrampolineConfigure.h
  94. 40 0
      unity_ios/Classes/Vector3.h
  95. 34 0
      unity_ios/Classes/iPhone_Sensors.h
  96. 1168 0
      unity_ios/Classes/iPhone_Sensors.mm
  97. 175 0
      unity_ios/Classes/main.mm
  98. BIN
      unity_ios/Data/Managed/Metadata/global-metadata.dat
  99. BIN
      unity_ios/Data/Managed/Resources/mscorlib.dll-resources.dat
  100. 307 0
      unity_ios/Data/Managed/mono/4.0/machine.config

+ 32 - 0
unity_ios/Classes/CrashReporter.h

@@ -0,0 +1,32 @@
+#pragma once
+
+// Enabling this will force app to do a hard crash instead of a nice exit when UnhandledException
+// is thrown. This will force iOS to generate a standard crash report, that can be submitted to
+// iTunes by app users and inspected by developers.
+#define ENABLE_IOS_CRASH_REPORTING 1
+
+// Enabling this will add a custom Objective-C Uncaught Exception handler, which will print out
+// exception information to console.
+#define ENABLE_OBJC_UNCAUGHT_EXCEPTION_HANDLER 1
+
+// Enable custom crash reporter to capture crashes. Crash logs will be available to scripts via
+// CrashReport API.
+#define ENABLE_CUSTOM_CRASH_REPORTER 0
+
+// Enable submission of custom crash reports to Unity servers. This will enable custom crash
+// reporter.
+#define ENABLE_CRASH_REPORT_SUBMISSION 0
+
+
+#if ENABLE_CRASH_REPORT_SUBMISSION && !ENABLE_CUSTOM_CRASH_REPORTER
+    #undef ENABLE_CUSTOM_CRASH_REPORTER
+    #define ENABLE_CUSTOM_CRASH_REPORTER 1
+#endif
+
+#if PLATFORM_TVOS
+    #undef ENABLE_CUSTOM_CRASH_REPORTER
+    #define ENABLE_CUSTOM_CRASH_REPORTER 0
+#endif
+
+extern "C" void UnityInstallPostCrashCallback();
+void InitCrashHandling();

+ 108 - 0
unity_ios/Classes/CrashReporter.mm

@@ -0,0 +1,108 @@
+#import "PLCrashReporter.h"
+#import "CrashReporter.h"
+
+#include "UndefinePlatforms.h"
+#include <mach-o/ldsyms.h>
+#include "RedefinePlatforms.h"
+
+extern "C" NSString* UnityGetCrashReportsPath();
+
+static NSUncaughtExceptionHandler* gsCrashReporterUEHandler = NULL;
+
+static decltype(_mh_execute_header) * sExecuteHeader = NULL;
+extern "C" void UnitySetExecuteMachHeader(const decltype(_mh_execute_header)* header)
+{
+    sExecuteHeader = header;
+}
+
+UNITY_EXPORT extern "C" const decltype(_mh_execute_header) * UnityGetExecuteMachHeader() {
+    return sExecuteHeader;
+}
+
+static void SavePendingCrashReport()
+{
+    if (![[UnityPLCrashReporter sharedReporter] hasPendingCrashReport])
+        return;
+
+    NSFileManager *fm = [NSFileManager defaultManager];
+    NSError *error;
+
+    if (![fm createDirectoryAtPath: UnityGetCrashReportsPath() withIntermediateDirectories: YES attributes: nil error: &error])
+    {
+        ::printf("CrashReporter: could not create crash report directory: %s\n", [[error localizedDescription] UTF8String]);
+        return;
+    }
+
+    NSData *data = [[UnityPLCrashReporter sharedReporter] loadPendingCrashReportDataAndReturnError: &error];
+    if (data == nil)
+    {
+        ::printf("CrashReporter: failed to load crash report data: %s\n", [[error localizedDescription] UTF8String]);
+        return;
+    }
+
+    NSString* file = [UnityGetCrashReportsPath() stringByAppendingPathComponent: @"crash-"];
+    unsigned long long seconds = (unsigned long long)[[NSDate date] timeIntervalSince1970];
+    file = [file stringByAppendingString: [NSString stringWithFormat: @"%llu", seconds]];
+    file = [file stringByAppendingString: @".plcrash"];
+    if ([data writeToFile: file atomically: YES])
+    {
+        ::printf("CrashReporter: saved pending crash report.\n");
+        if (![[UnityPLCrashReporter sharedReporter] purgePendingCrashReportAndReturnError: &error])
+        {
+            ::printf("CrashReporter: couldn't remove pending report: %s\n", [[error localizedDescription] UTF8String]);
+        }
+    }
+    else
+    {
+        ::printf("CrashReporter: couldn't save crash report.\n");
+    }
+
+    // Now copy out a pending version that we can delete if/when we send it
+    file = [UnityGetCrashReportsPath() stringByAppendingPathComponent: @"crash-pending.plcrash"];
+    if ([data writeToFile: file atomically: YES])
+    {
+        ::printf("CrashReporter: saved copy of pending crash report.\n");
+    }
+    else
+    {
+        ::printf("CrashReporter: couldn't save copy of pending crash report.\n");
+    }
+}
+
+static void InitCrashReporter()
+{
+    NSError *error;
+
+    UnityInstallPostCrashCallback();
+    if ([[UnityPLCrashReporter sharedReporter] enableCrashReporterAndReturnError: &error])
+        ::printf("CrashReporter: initialized\n");
+    else
+        NSLog(@"CrashReporter: could not enable crash reporter: %@", error);
+
+    SavePendingCrashReport();
+}
+
+static void UncaughtExceptionHandler(NSException *exception)
+{
+    NSLog(@"Uncaught exception: %@: %@\n%@", [exception name], [exception reason], [exception callStackSymbols]);
+    if (gsCrashReporterUEHandler)
+        gsCrashReporterUEHandler(exception);
+}
+
+static void InitObjCUEHandler()
+{
+    // Crash reporter sets its own handler, so we have to save it and call it manually
+    gsCrashReporterUEHandler = NSGetUncaughtExceptionHandler();
+    NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
+}
+
+void InitCrashHandling()
+{
+#if ENABLE_CUSTOM_CRASH_REPORTER
+    InitCrashReporter();
+#endif
+
+#if ENABLE_OBJC_UNCAUGHT_EXCEPTION_HANDLER
+    InitObjCUEHandler();
+#endif
+}

+ 102 - 0
unity_ios/Classes/PLCrashReporter.h

@@ -0,0 +1,102 @@
+/*
+ * Author: Landon Fuller <landonf@plausiblelabs.com>
+ *
+ * Copyright (c) 2008-2009 Plausible Labs Cooperative, Inc.
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use,
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following
+ * conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#import <Foundation/Foundation.h>
+
+/**
+ * @ingroup functions
+ *
+ * Prototype of a callback function used to execute additional user code with signal information as provided
+ * by PLCrashReporter. Called upon completion of crash handling, after the crash report has been written to disk.
+ *
+ * @param info The signal info.
+ * @param uap The crash's threads context.
+ * @param context The API client's supplied context value.
+ *
+ * @sa @ref async_safety
+ * @sa PLCrashReporter::setPostCrashCallbacks:
+ */
+typedef void (*UnityPLCrashReporterPostCrashSignalCallback)(siginfo_t *info, ucontext_t *uap, void *context);
+
+/**
+ * @ingroup types
+ *
+ * This structure contains callbacks supported by PLCrashReporter to allow the host application to perform
+ * additional tasks prior to program termination after a crash has occured.
+ *
+ * @sa @ref async_safety
+ */
+typedef struct UnityPLCrashReporterCallbacks
+{
+    /** The version number of this structure. If not one of the defined version numbers for this type, the behavior
+     * is undefined. The current version of this structure is 0. */
+    uint16_t version;
+
+    /** An arbitrary user-supplied context value. This value may be NULL. */
+    void *context;
+
+    /** The callback used to report caught signal information. In version 0 of this structure, all crashes will be
+     * reported via this function. */
+    UnityPLCrashReporterPostCrashSignalCallback handleSignal;
+} UnityPLCrashReporterCallbacks;
+
+@interface UnityPLCrashReporter : NSObject
+{
+    @private
+    /** YES if the crash reporter has been enabled */
+    BOOL _enabled;
+
+    /** Application identifier */
+    NSString *_applicationIdentifier;
+
+    /** Application version */
+    NSString *_applicationVersion;
+
+    /** Path to the crash reporter internal data directory */
+    NSString *_crashReportDirectory;
+}
+
++ (UnityPLCrashReporter *)sharedReporter;
+
+- (BOOL)hasPendingCrashReport;
+
+- (NSData *)loadPendingCrashReportData;
+- (NSData *)loadPendingCrashReportDataAndReturnError:(NSError **)outError;
+
+- (NSData *)generateLiveReport;
+- (NSData *)generateLiveReportAndReturnError:(NSError **)outError;
+
+- (BOOL)purgePendingCrashReport;
+- (BOOL)purgePendingCrashReportAndReturnError:(NSError **)outError;
+
+- (BOOL)enableCrashReporter;
+- (BOOL)enableCrashReporterAndReturnError:(NSError **)outError;
+
+- (void)setCrashCallbacks:(UnityPLCrashReporterCallbacks *)callbacks;
+
+@end

+ 37 - 0
unity_ios/Classes/PluginBase/AppDelegateListener.h

@@ -0,0 +1,37 @@
+#pragma once
+
+#include "LifeCycleListener.h"
+
+
+@protocol AppDelegateListener<LifeCycleListener>
+@optional
+// these do not have apple defined notifications, so we use our own notifications
+
+// notification will be posted from
+// - (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation
+// notification user data is the NSDictionary containing all the params
+- (void)onOpenURL:(NSNotification*)notification;
+
+// notification will be posted from
+// - (BOOL)application:(UIApplication*)application willFinishLaunchingWithOptions:(NSDictionary*)launchOptions
+// notification user data is the NSDictionary containing launchOptions
+- (void)applicationWillFinishLaunchingWithOptions:(NSNotification*)notification;
+// notification will be posted from
+// - (void)application:(UIApplication*)application handleEventsForBackgroundURLSession:(nonnull NSString *)identifier completionHandler:(nonnull void (^)())completionHandler
+// notification user data is NSDictionary with one item where key is session identifier and value is completion handler
+- (void)onHandleEventsForBackgroundURLSession:(NSNotification*)notification;
+
+// these are just hooks to existing notifications
+- (void)applicationDidReceiveMemoryWarning:(NSNotification*)notification;
+- (void)applicationSignificantTimeChange:(NSNotification*)notification;
+@end
+
+void UnityRegisterAppDelegateListener(id<AppDelegateListener> obj);
+void UnityUnregisterAppDelegateListener(id<AppDelegateListener> obj);
+
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityDidRegisterForRemoteNotificationsWithDeviceToken;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityDidFailToRegisterForRemoteNotificationsWithError;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityDidReceiveRemoteNotification;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityOnOpenURL;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityWillFinishLaunchingWithOptions;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityHandleEventsForBackgroundURLSession;

+ 63 - 0
unity_ios/Classes/PluginBase/AppDelegateListener.mm

@@ -0,0 +1,63 @@
+#include "AppDelegateListener.h"
+
+#define DEFINE_NOTIFICATION(name) extern "C" __attribute__((visibility ("default"))) NSString* const name = @#name;
+
+DEFINE_NOTIFICATION(kUnityDidRegisterForRemoteNotificationsWithDeviceToken);
+DEFINE_NOTIFICATION(kUnityDidFailToRegisterForRemoteNotificationsWithError);
+DEFINE_NOTIFICATION(kUnityDidReceiveRemoteNotification);
+DEFINE_NOTIFICATION(kUnityOnOpenURL);
+DEFINE_NOTIFICATION(kUnityWillFinishLaunchingWithOptions);
+DEFINE_NOTIFICATION(kUnityHandleEventsForBackgroundURLSession);
+
+#undef DEFINE_NOTIFICATION
+
+void UnityRegisterAppDelegateListener(id<AppDelegateListener> obj)
+{
+    #define REGISTER_SELECTOR(sel, notif_name)                  \
+    if([obj respondsToSelector:sel])                            \
+        [[NSNotificationCenter defaultCenter]   addObserver:obj \
+                                                selector:sel    \
+                                                name:notif_name \
+                                                object:nil      \
+        ];                                                      \
+
+    UnityRegisterLifeCycleListener(obj);
+
+    REGISTER_SELECTOR(@selector(onOpenURL:), kUnityOnOpenURL);
+
+    REGISTER_SELECTOR(@selector(applicationDidReceiveMemoryWarning:), UIApplicationDidReceiveMemoryWarningNotification);
+    REGISTER_SELECTOR(@selector(applicationSignificantTimeChange:), UIApplicationSignificantTimeChangeNotification);
+
+#if !PLATFORM_TVOS && !PLATFORM_VISIONOS
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    // these notifications are deprecated, but we keep registration for backward compatibility
+    REGISTER_SELECTOR(@selector(applicationWillChangeStatusBarFrame:), UIApplicationWillChangeStatusBarFrameNotification);
+    REGISTER_SELECTOR(@selector(applicationWillChangeStatusBarOrientation:), UIApplicationWillChangeStatusBarOrientationNotification);
+#pragma pop
+#endif
+
+    REGISTER_SELECTOR(@selector(applicationWillFinishLaunchingWithOptions:), kUnityWillFinishLaunchingWithOptions);
+    REGISTER_SELECTOR(@selector(onHandleEventsForBackgroundURLSession:), kUnityHandleEventsForBackgroundURLSession);
+
+    #undef REGISTER_SELECTOR
+}
+
+void UnityUnregisterAppDelegateListener(id<AppDelegateListener> obj)
+{
+    UnityUnregisterLifeCycleListener(obj);
+
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityOnOpenURL object: nil];
+
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationDidReceiveMemoryWarningNotification object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationSignificantTimeChangeNotification object: nil];
+
+#if !PLATFORM_TVOS && !PLATFORM_VISIONOS
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    // these notifications are deprecated, but we keep registration for backward compatibility
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillChangeStatusBarFrameNotification object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillChangeStatusBarOrientationNotification object: nil];
+#pragma pop
+#endif
+}

+ 29 - 0
unity_ios/Classes/PluginBase/LifeCycleListener.h

@@ -0,0 +1,29 @@
+#pragma once
+
+// important app life-cycle events
+
+@protocol LifeCycleListener<NSObject>
+@optional
+- (void)didFinishLaunching:(NSNotification*)notification;
+- (void)didBecomeActive:(NSNotification*)notification;
+- (void)willResignActive:(NSNotification*)notification;
+- (void)didEnterBackground:(NSNotification*)notification;
+- (void)willEnterForeground:(NSNotification*)notification;
+- (void)willTerminate:(NSNotification*)notification;
+- (void)unityDidUnload:(NSNotification*)notification;
+- (void)unityDidQuit:(NSNotification*)notification;
+@end
+
+void UnityRegisterLifeCycleListener(id<LifeCycleListener> obj);
+void UnityUnregisterLifeCycleListener(id<LifeCycleListener> obj);
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern __attribute__((visibility("default"))) NSString* const kUnityDidUnload;
+extern __attribute__((visibility("default"))) NSString* const kUnityDidQuit;
+
+#ifdef __cplusplus
+} // extern "C"
+#endif

+ 39 - 0
unity_ios/Classes/PluginBase/LifeCycleListener.mm

@@ -0,0 +1,39 @@
+#include "LifeCycleListener.h"
+
+#define DEFINE_NOTIFICATION(name) extern "C" __attribute__((visibility ("default"))) NSString* const name = @#name;
+DEFINE_NOTIFICATION(kUnityDidUnload);
+DEFINE_NOTIFICATION(kUnityDidQuit);
+
+void UnityRegisterLifeCycleListener(id<LifeCycleListener> obj)
+{
+    #define REGISTER_SELECTOR(sel, notif_name)                  \
+    if([obj respondsToSelector:sel])                            \
+        [[NSNotificationCenter defaultCenter]   addObserver:obj \
+                                                selector:sel    \
+                                                name:notif_name \
+                                                object:nil      \
+        ];                                                      \
+
+    REGISTER_SELECTOR(@selector(didFinishLaunching:), UIApplicationDidFinishLaunchingNotification);
+    REGISTER_SELECTOR(@selector(didBecomeActive:), UIApplicationDidBecomeActiveNotification);
+    REGISTER_SELECTOR(@selector(willResignActive:), UIApplicationWillResignActiveNotification);
+    REGISTER_SELECTOR(@selector(didEnterBackground:), UIApplicationDidEnterBackgroundNotification);
+    REGISTER_SELECTOR(@selector(willEnterForeground:), UIApplicationWillEnterForegroundNotification);
+    REGISTER_SELECTOR(@selector(willTerminate:), UIApplicationWillTerminateNotification);
+    REGISTER_SELECTOR(@selector(unityDidUnload:), kUnityDidUnload);
+    REGISTER_SELECTOR(@selector(unityDidQuit:), kUnityDidQuit);
+
+    #undef REGISTER_SELECTOR
+}
+
+void UnityUnregisterLifeCycleListener(id<LifeCycleListener> obj)
+{
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationDidFinishLaunchingNotification object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationDidBecomeActiveNotification object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillResignActiveNotification object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationDidEnterBackgroundNotification object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillEnterForegroundNotification object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillTerminateNotification object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityDidUnload object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityDidQuit object: nil];
+}

+ 67 - 0
unity_ios/Classes/PluginBase/RenderPluginDelegate.h

@@ -0,0 +1,67 @@
+#pragma once
+
+#import <UnityFramework/LifeCycleListener.h>
+
+struct UnityDisplaySurfaceBase; // Unity/UnityRendering.h
+struct RenderingSurfaceParams;  // Unity/DisplayManager.h
+
+// due to delicate nature of render loop we have just one delegate in app
+// if you need to use several rendering delegates you need to do one of:
+// 1. create custom delegate that will have code to combine effects by itself
+// 2. use helper that simply holds array of delegates (which will work only in easiest cases)
+@protocol RenderPluginDelegate<LifeCycleListener, NSObject>
+
+@required
+// this will be called right after gles intialization.
+// surface pointer will never be changed, so you should keep it.
+// the only valid fields in there as of now are layer and context
+- (void)mainDisplayInited:(struct UnityDisplaySurfaceBase*)surface;
+
+@optional
+
+// this will be called before recreating main display surface (from [UnityView recreateRenderingSurface])
+// you can tweak params here.
+- (void)onBeforeMainDisplaySurfaceRecreate:(struct RenderingSurfaceParams*)params;
+
+// this will be called right after recreating main display surface (from [UnityView recreateRenderingSurface])
+// as [UnityView recreateRenderingSurface] is the only place where unity itself will trigger surface recreate
+// you can use this method to update your rendering depending on changes
+- (void)onAfterMainDisplaySurfaceRecreate;
+
+// this will be called after frame render and msaa resolve but before blitting to system FB
+// you can expect that frame contents are ready (though still in target resolution)
+// use it for anylizing/postprocessing rendered frame, taking screenshot and the like
+// you should use targetFB if it is not 0
+// otherwise use systemFB
+- (void)onFrameResolved;
+@end
+
+
+// simple helper for common plugin stuff
+// you can implement protocol directly, but subclassing this will provide some common implementation
+@interface RenderPluginDelegate : NSObject<RenderPluginDelegate>
+{
+    struct UnityDisplaySurfaceBase* mainDisplaySurface;
+}
+- (void)mainDisplayInited:(struct UnityDisplaySurfaceBase*)surface;
+@end
+
+
+// simple helper to have an array of render delegates.
+// be warned that it works in simplest cases only, when there is no interop between delegates
+@interface RenderPluginArrayDelegate : RenderPluginDelegate
+{
+    NSArray* delegateArray;
+}
+@property(nonatomic, retain) NSArray* delegateArray;
+- (void)mainDisplayInited:(struct UnityDisplaySurfaceBase*)surface;
+- (void)onBeforeMainDisplaySurfaceRecreate:(struct RenderingSurfaceParams*)params;
+- (void)onAfterMainDisplaySurfaceRecreate;
+- (void)onFrameResolved;
+
+- (void)didBecomeActive:(NSNotification*)notification;
+- (void)willResignActive:(NSNotification*)notification;
+- (void)didEnterBackground:(NSNotification*)notification;
+- (void)willEnterForeground:(NSNotification*)notification;
+- (void)willTerminate:(NSNotification*)notification;
+@end

+ 90 - 0
unity_ios/Classes/PluginBase/RenderPluginDelegate.mm

@@ -0,0 +1,90 @@
+#include "RenderPluginDelegate.h"
+
+@implementation RenderPluginDelegate
+
+- (void)mainDisplayInited:(struct UnityDisplaySurfaceBase*)surface
+{
+    mainDisplaySurface = surface;
+
+    // TODO: move lifecycle to init?
+    UnityRegisterLifeCycleListener(self);
+}
+
+@end
+
+
+#define CALL_METHOD_ON_ARRAY(method)                    \
+do{                                                     \
+    for(id<RenderPluginDelegate> del in delegateArray)  \
+    {                                                   \
+        if([del respondsToSelector:@selector(method)])  \
+            [del method];                               \
+    }                                                   \
+} while(0)
+
+#define CALL_METHOD_ON_ARRAY_ARG(method, arg)           \
+do{                                                     \
+    for(id<RenderPluginDelegate> del in delegateArray)  \
+    {                                                   \
+        if([del respondsToSelector:@selector(method:)]) \
+            [del method:arg];                           \
+    }                                                   \
+} while(0)
+
+
+@implementation RenderPluginArrayDelegate
+
+@synthesize delegateArray;
+
+- (void)mainDisplayInited:(struct UnityDisplaySurfaceBase*)surface
+{
+    [super mainDisplayInited: surface];
+    CALL_METHOD_ON_ARRAY_ARG(mainDisplayInited, surface);
+}
+
+- (void)onBeforeMainDisplaySurfaceRecreate:(struct RenderingSurfaceParams*)params
+{
+    CALL_METHOD_ON_ARRAY_ARG(onBeforeMainDisplaySurfaceRecreate, params);
+}
+
+- (void)onAfterMainDisplaySurfaceRecreate;
+{
+    CALL_METHOD_ON_ARRAY(onAfterMainDisplaySurfaceRecreate);
+}
+
+- (void)onFrameResolved;
+{
+    CALL_METHOD_ON_ARRAY(onFrameResolved);
+}
+
+
+- (void)didBecomeActive:(NSNotification*)notification
+{
+    CALL_METHOD_ON_ARRAY_ARG(didBecomeActive, notification);
+}
+
+- (void)willResignActive:(NSNotification*)notification
+{
+    CALL_METHOD_ON_ARRAY_ARG(willResignActive, notification);
+}
+
+- (void)didEnterBackground:(NSNotification*)notification
+{
+    CALL_METHOD_ON_ARRAY_ARG(didEnterBackground, notification);
+}
+
+- (void)willEnterForeground:(NSNotification*)notification
+{
+    CALL_METHOD_ON_ARRAY_ARG(willEnterForeground, notification);
+}
+
+- (void)willTerminate:(NSNotification*)notification
+{
+    CALL_METHOD_ON_ARRAY_ARG(willTerminate, notification);
+}
+
+@end
+
+
+#undef CALL_METHOD_ON_ARRAY
+#undef CALL_METHOD_ON_ARRAY_ARG

+ 51 - 0
unity_ios/Classes/PluginBase/UnityViewControllerListener.h

@@ -0,0 +1,51 @@
+#pragma once
+
+#import <Foundation/NSNotification.h>
+
+// view changes on the main view controller
+
+@protocol UnityViewControllerListener<NSObject>
+@optional
+- (void)viewWillLayoutSubviews:(NSNotification*)notification;
+- (void)viewDidLayoutSubviews:(NSNotification*)notification;
+- (void)viewWillDisappear:(NSNotification*)notification;
+- (void)viewDidDisappear:(NSNotification*)notification;
+- (void)viewWillAppear:(NSNotification*)notification;
+- (void)viewDidAppear:(NSNotification*)notification;
+
+- (void)interfaceWillChangeOrientation:(NSNotification*)notification;
+- (void)interfaceDidChangeOrientation:(NSNotification*)notification;
+@end
+
+@protocol UnityViewControllerNotifications<NSObject>
+@optional
+- (void)onViewWillLayoutSubviews;
+- (void)onViewDidLayoutSubviews;
+- (void)onViewDidDisappear:(BOOL)animated;
+- (void)onViewWillDisappear:(BOOL)animated;
+- (void)onViewDidAppear:(BOOL)animated;
+- (void)onViewWillAppear:(BOOL)animated;
+@end
+
+// this default delegate will send notifications for UnityViewControllerListener
+@interface UnityViewControllerNotificationsDefaultSender : NSObject<UnityViewControllerNotifications>
+- (void)onViewWillLayoutSubviews;
+- (void)onViewDidLayoutSubviews;
+- (void)onViewDidDisappear:(BOOL)animated;
+- (void)onViewWillDisappear:(BOOL)animated;
+- (void)onViewDidAppear:(BOOL)animated;
+- (void)onViewWillAppear:(BOOL)animated;
+@end
+
+
+void UnityRegisterViewControllerListener(id<UnityViewControllerListener> obj);
+void UnityUnregisterViewControllerListener(id<UnityViewControllerListener> obj);
+
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityViewWillLayoutSubviews;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityViewDidLayoutSubviews;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityViewWillDisappear;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityViewDidDisappear;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityViewWillAppear;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityViewDidAppear;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityInterfaceWillChangeOrientation;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityInterfaceDidChangeOrientation;

+ 80 - 0
unity_ios/Classes/PluginBase/UnityViewControllerListener.mm

@@ -0,0 +1,80 @@
+#include "UnityViewControllerListener.h"
+#include <UIKit/UIApplication.h>
+
+#define DEFINE_NOTIFICATION(name) extern "C" __attribute__((visibility ("default"))) NSString* const name = @#name;
+
+DEFINE_NOTIFICATION(kUnityViewWillLayoutSubviews);
+DEFINE_NOTIFICATION(kUnityViewDidLayoutSubviews);
+DEFINE_NOTIFICATION(kUnityViewWillDisappear);
+DEFINE_NOTIFICATION(kUnityViewDidDisappear);
+DEFINE_NOTIFICATION(kUnityViewWillAppear);
+DEFINE_NOTIFICATION(kUnityViewDidAppear);
+DEFINE_NOTIFICATION(kUnityInterfaceWillChangeOrientation);
+DEFINE_NOTIFICATION(kUnityInterfaceDidChangeOrientation);
+
+#undef DEFINE_NOTIFICATION
+
+void UnityRegisterViewControllerListener(id<UnityViewControllerListener> obj)
+{
+    #define REGISTER_SELECTOR(sel, notif_name)                                                          \
+    if([obj respondsToSelector:sel])                                                                    \
+        [[NSNotificationCenter defaultCenter] addObserver:obj selector:sel name:notif_name object:nil]; \
+
+    REGISTER_SELECTOR(@selector(viewWillLayoutSubviews:), kUnityViewWillLayoutSubviews);
+    REGISTER_SELECTOR(@selector(viewDidLayoutSubviews:), kUnityViewDidLayoutSubviews);
+    REGISTER_SELECTOR(@selector(viewWillDisappear:), kUnityViewWillDisappear);
+    REGISTER_SELECTOR(@selector(viewDidDisappear:), kUnityViewDidDisappear);
+    REGISTER_SELECTOR(@selector(viewWillAppear:), kUnityViewWillAppear);
+    REGISTER_SELECTOR(@selector(viewDidAppear:), kUnityViewDidAppear);
+    REGISTER_SELECTOR(@selector(interfaceWillChangeOrientation:), kUnityInterfaceWillChangeOrientation);
+    REGISTER_SELECTOR(@selector(interfaceDidChangeOrientation:), kUnityInterfaceDidChangeOrientation);
+
+    #undef REGISTER_SELECTOR
+}
+
+void UnityUnregisterViewControllerListener(id<UnityViewControllerListener> obj)
+{
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityViewWillLayoutSubviews object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityViewDidLayoutSubviews object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityViewWillDisappear object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityViewDidDisappear object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityViewWillAppear object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityViewDidAppear object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityInterfaceWillChangeOrientation object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityInterfaceDidChangeOrientation object: nil];
+}
+
+extern void AppController_SendUnityViewControllerNotification(NSString* name);
+
+@implementation UnityViewControllerNotificationsDefaultSender
+- (void)onViewWillLayoutSubviews
+{
+    AppController_SendUnityViewControllerNotification(kUnityViewWillLayoutSubviews);
+}
+
+- (void)onViewDidLayoutSubviews
+{
+    AppController_SendUnityViewControllerNotification(kUnityViewDidLayoutSubviews);
+}
+
+- (void)onViewDidDisappear:(BOOL)animated
+{
+    AppController_SendUnityViewControllerNotification(kUnityViewDidDisappear);
+}
+
+- (void)onViewWillDisappear:(BOOL)animated
+{
+    AppController_SendUnityViewControllerNotification(kUnityViewWillDisappear);
+}
+
+- (void)onViewDidAppear:(BOOL)animated
+{
+    AppController_SendUnityViewControllerNotification(kUnityViewDidAppear);
+}
+
+- (void)onViewWillAppear:(BOOL)animated
+{
+    AppController_SendUnityViewControllerNotification(kUnityViewWillAppear);
+}
+
+@end

+ 23 - 0
unity_ios/Classes/Prefix.pch

@@ -0,0 +1,23 @@
+//
+// Prefix header
+//
+
+#include "Preprocessor.h"
+
+#ifdef __OBJC__
+    #import <Foundation/Foundation.h>
+    #import <UIKit/UIKit.h>
+#endif
+
+#include "UnityTrampolineConfigure.h"
+#include "UnityInterface.h"
+
+#ifndef __OBJC__
+    #if defined(__cplusplus)
+        #include "pch-cpp.hpp"
+    #else
+        #include "pch-c.h"
+    #endif
+#endif
+
+#define printf_console printf

+ 238 - 0
unity_ios/Classes/Preprocessor.h

@@ -0,0 +1,238 @@
+#pragma once
+
+#include <Availability.h>
+#include <TargetConditionals.h>
+
+//------------------------------------------------------------------------------
+//
+// ensuring proper compiler/xcode/whatever selection
+//
+
+#ifndef __clang__
+#error Please use clang compiler.
+#endif
+
+#if __clang_major__ < 13
+#error Please use Xcode 13.0 or newer
+#endif
+
+#if !defined(__IPHONE_15_0) || __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_15_0
+#error Please use iOS SDK 15.0 or newer
+#endif
+
+#if defined(TARGET_OS_TV) && TARGET_OS_TV && !defined(__TVOS_15_0)
+#error Please use tvOS SDK 15.0 or newer
+#endif
+
+#if TARGET_OS_IOS && (!defined(__IPHONE_15_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_15_0)
+#error Please target iOS 15.0 or newer
+#endif
+
+#if TARGET_OS_TV && (!defined(__TVOS_15_0) || __TV_OS_VERSION_MIN_REQUIRED < __TVOS_15_0)
+#error Please target tvOS 15.0 or newer
+#endif
+
+//------------------------------------------------------------------------------
+//
+// defines for target platform
+// Note: visionOS defines _OS_XR and _OS_IOS
+//
+
+#define UNITY_TRAMPOLINE_IN_USE 1
+
+// #define PLATFORM_* values are set by Build Program when Xcode project is generated (including "append") according to the selected platform.
+#define PLATFORM_IOS 1
+#define PLATFORM_OSX    0
+#define PLATFORM_TVOS 0
+#define PLATFORM_VISIONOS 0
+
+#if !(TARGET_OS_IOS || TARGET_OS_OSX || TARGET_OS_TV || TARGET_OS_VISION)
+    #error one of TARGET_OS_IOS, TARGET_OS_OSX, TARGET_OS_TV, TARGET_OS_VISION should be defined
+#endif
+
+#if !(PLATFORM_IOS || PLATFORM_OSX || PLATFORM_TVOS || PLATFORM_VISIONOS)
+    #error at least one of PLATFORM_IOS, PLATFORM_OSX, PLATFORM_TVOS, PLATFORM_VISIONOS must be defined
+#endif
+
+//------------------------------------------------------------------------------
+//
+// defines for sdk/target version
+//
+
+// It's hard to figure out which SDK we are using as the availability macros defined in the SDK
+// have various quirks.
+//
+// It's not possible to use *_VERSION_MAX_ALLOWED macros because they not always corresponded to
+// the SDK version. In particular, __TV_OS_VERSION_MAX_ALLOWED was out of sync in all Xcode dot
+// releases except the first so far.
+//
+// The highest __IPHONE_X_Y or __TVOS_X_Y macro that is defined in Availability.h correctly
+// corresponds to the version of the SDK (at least in each Xcode version since 6.0 up to 9.0).
+// However, some other headers (e.g. System/Library/Frameworks/QuartzCore.framework/Headers/CABase.h
+// in SDKs up to 9.3) may define the macros itself and this does not correspond to the what's in
+// Availability.h. Thus we make sure to include "Preprocessor.h" before the CABase.h header.
+#if defined(CABASE_H)
+#error "Please include Preprocessor.h before other includes"
+#endif
+
+#if defined(__IPHONE_10_0)
+    #define UNITY_HAS_IOSSDK_10_0  1
+#else
+    #define UNITY_HAS_IOSSDK_10_0  0
+#endif
+#if defined(__IPHONE_10_2)
+    #define UNITY_HAS_IOSSDK_10_2  1
+#else
+    #define UNITY_HAS_IOSSDK_10_2  0
+#endif
+#if defined(__IPHONE_10_3)
+    #define UNITY_HAS_IOSSDK_10_3  1
+#else
+    #define UNITY_HAS_IOSSDK_10_3  0
+#endif
+#if defined(__IPHONE_11_0)
+    #define UNITY_HAS_IOSSDK_11_0  1
+#else
+    #define UNITY_HAS_IOSSDK_11_0  0
+#endif
+#if defined(__IPHONE_11_1)
+    #define UNITY_HAS_IOSSDK_11_1  1
+#else
+    #define UNITY_HAS_IOSSDK_11_1  0
+#endif
+#if defined(__IPHONE_12_0)
+    #define UNITY_HAS_IOSSDK_12_0  1
+#else
+    #define UNITY_HAS_IOSSDK_12_0  0
+#endif
+#if defined(__IPHONE_13_0)
+    #define UNITY_HAS_IOSSDK_13_0  1
+#else
+    #define UNITY_HAS_IOSSDK_13_0  0
+#endif
+#if defined(__IPHONE_14_0)
+    #define UNITY_HAS_IOSSDK_14_0  1
+#else
+    #define UNITY_HAS_IOSSDK_14_0  0
+#endif
+#if defined(__IPHONE_15_0)
+    #define UNITY_HAS_IOSSDK_15_0  1
+#else
+    #define UNITY_HAS_IOSSDK_15_0  0
+#endif
+#if defined(__IPHONE_16_0)
+    #define UNITY_HAS_IOSSDK_16_0  1
+#else
+    #define UNITY_HAS_IOSSDK_16_0  0
+#endif
+#if defined(__IPHONE_17_0)
+    #define UNITY_HAS_IOSSDK_17_0  1
+#else
+    #define UNITY_HAS_IOSSDK_17_0  0
+#endif
+#if defined(__IPHONE_18_0)
+    #define UNITY_HAS_IOSSDK_18_0  1
+#else
+    #define UNITY_HAS_IOSSDK_18_0  0
+#endif
+
+#if defined(__TVOS_10_0)
+    #define UNITY_HAS_TVOSSDK_10_0 1
+#else
+    #define UNITY_HAS_TVOSSDK_10_0 0
+#endif
+#if defined(__TVOS_10_2)
+    #define UNITY_HAS_TVOSSDK_10_2 1
+#else
+    #define UNITY_HAS_TVOSSDK_10_2 0
+#endif
+#if defined(__TVOS_11_0)
+    #define UNITY_HAS_TVOSSDK_11_0 1
+#else
+    #define UNITY_HAS_TVOSSDK_11_0 0
+#endif
+#if defined(__TVOS_12_0)
+    #define UNITY_HAS_TVOSSDK_12_0 1
+#else
+    #define UNITY_HAS_TVOSSDK_12_0 0
+#endif
+#if defined(__TVOS_13_0)
+    #define UNITY_HAS_TVOSSDK_13_0 1
+#else
+    #define UNITY_HAS_TVOSSDK_13_0 0
+#endif
+#if defined(__TVOS_14_0)
+    #define UNITY_HAS_TVOSSDK_14_0 1
+#else
+    #define UNITY_HAS_TVOSSDK_14_0 0
+#endif
+#if defined(__TVOS_15_0)
+    #define UNITY_HAS_TVOSSDK_15_0 1
+#else
+    #define UNITY_HAS_TVOSSDK_15_0 0
+#endif
+#if defined(__TVOS_16_0)
+    #define UNITY_HAS_TVOSSDK_16_0 1
+#else
+    #define UNITY_HAS_TVOSSDK_16_0 0
+#endif
+#if defined(__TVOS_17_0)
+    #define UNITY_HAS_TVOSSDK_17_0 1
+#else
+    #define UNITY_HAS_TVOSSDK_17_0 0
+#endif
+
+#if defined(__VISIONOS_2_0)
+    #define UNITY_HAS_VISIONOSSDK_2_0 1
+#else
+    #define UNITY_HAS_VISIONOSSDK_2_0 0
+#endif
+
+
+//------------------------------------------------------------------------------
+//
+// defines for used unity features
+//
+
+// The following UNITY_USES_* flags disable functionality in the trampoline project whenever the user does not use it from his scripts.
+// We detect the API usage and adjust the value of these flags whenever the project is built (including "append")
+
+#define UNITY_USES_REMOTE_NOTIFICATIONS 0
+#define UNITY_USES_WEBCAM 0
+#define UNITY_USES_MICROPHONE 0
+#define UNITY_USES_REPLAY_KIT 0
+#define UNITY_USES_LOCATION 0
+#define UNITY_USES_GLES 0
+#define UNITY_USES_IAD 0
+
+//------------------------------------------------------------------------------
+//
+// defines for used features
+//
+
+#define UNITY_DEVELOPER_BUILD 0
+#define USE_IL2CPP_PCH 0
+#define UNITY_SNAPSHOT_VIEW_ON_APPLICATION_PAUSE 0
+
+#define UNITY_EXPORT __attribute__((visibility("default")))
+
+// we now support metal always everywhere, but we keep the define for native plugins using it
+#define UNITY_CAN_USE_METAL 1
+
+#define UNITY_SUPPORT_ROTATION PLATFORM_IOS
+#if PLATFORM_TVOS
+    #define UNITY_TVOS_ORIENTATION landscapeLeft
+#endif
+#if PLATFORM_VISIONOS
+    #define UNITY_VISIONOS_ORIENTATION landscapeLeft
+#endif
+
+
+#if PLATFORM_IOS || PLATFORM_TVOS || PLATFORM_VISIONOS
+    #define UNITY_REPLAY_KIT_AVAILABLE UNITY_USES_REPLAY_KIT
+#else
+    #define UNITY_REPLAY_KIT_AVAILABLE 0
+#endif
+
+// On tvOS simulator we implement a fake remote as tvOS simulator does not support controllers (yet)
+#define UNITY_TVOS_SIMULATOR_FAKE_REMOTE (PLATFORM_TVOS && TARGET_OS_SIMULATOR)

+ 118 - 0
unity_ios/Classes/Quaternion4.h

@@ -0,0 +1,118 @@
+#pragma once
+
+struct Quaternion4f
+{
+    float x, y, z, w;
+};
+
+static Quaternion4f gQuatRot[4] =
+{   // { x*sin(theta/2), y*sin(theta/2), z*sin(theta/2), cos(theta/2) }
+    // => { 0, 0, sin(theta/2), cos(theta/2) } (since <vec> = { 0, 0, +/-1})
+    { 0.f, 0.f, 0.f /*sin(0)*/, 1.f /*cos(0)*/},    // ROTATION_0, theta = 0 rad
+    { 0.f, 0.f, (float)sqrt(2) * 0.5f /*sin(pi/4)*/, -(float)sqrt(2) * 0.5f /*cos(pi/4)*/}, // ROTATION_90, theta = pi/4 rad
+    { 0.f, 0.f, 1.f /*sin(pi/2)*/, 0.f /*cos(pi/2)*/},  // ROTATION_180, theta = pi rad
+    { 0.f, 0.f, -(float)sqrt(2) * 0.5f /*sin(3pi/4)*/, -(float)sqrt(2) * 0.5f /*cos(3pi/4)*/}    // ROTATION_270, theta = 3pi/2 rad
+};
+
+inline void QuatMultiply(Quaternion4f& result, const Quaternion4f& lhs, const Quaternion4f& rhs)
+{
+    result.x = lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y;
+    result.y = lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z;
+    result.z = lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x;
+    result.w = lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z;
+}
+
+inline Quaternion4f QuatMultiply(const Quaternion4f& lhs, const Quaternion4f& rhs)
+{
+    Quaternion4f output;
+    QuatMultiply(output, lhs, rhs);
+    return output;
+}
+
+inline Quaternion4f QuatMake(float x, float y, float z, float w)
+{
+    Quaternion4f q = {x, y, z, w};
+    return q;
+}
+
+inline Quaternion4f QuatIdentity()
+{
+    return gQuatRot[0];
+}
+
+inline Quaternion4f QuatScale(const Quaternion4f& q, float s)
+{
+    return QuatMake(s * q.x, s * q.y, s * q.z, s * q.w);
+}
+
+inline float QuatNormSquared(const Quaternion4f& q)
+{
+    return q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;
+}
+
+inline Quaternion4f QuatConjugate(const Quaternion4f& q)
+{
+    return QuatMake(-q.x, -q.y, -q.z, q.w);
+}
+
+inline Quaternion4f QuatInverse(const Quaternion4f& q)
+{
+    return QuatScale(QuatConjugate(q), 1.0f / QuatNormSquared(q));
+}
+
+inline Vector3f QuatToEuler(const Quaternion4f& q)
+{
+    return VecMake(
+        atan2f(2.0f * (q.w * q.y + q.x * q.z),
+            1.0f - 2.0f * (q.y * q.y + q.x * q.x)),
+        asinf(2.0f * (q.w * q.x - q.z * q.y)),
+        atan2f(2.0f * (q.w * q.z + q.y * q.x),
+            1.0f - 2.0f * (q.x * q.x + q.z * q.z)));
+}
+
+inline float QuatNorm(const Quaternion4f& q)
+{
+    return sqrtf(QuatNormSquared(q));
+}
+
+inline Quaternion4f QuatNormalize(const Quaternion4f& q)
+{
+    return QuatScale(q, 1.0f / QuatNorm(q));
+}
+
+inline Quaternion4f QuatDifference(const Quaternion4f& a, const Quaternion4f& b)
+{
+    return QuatMultiply(QuatInverse(b), a);
+}
+
+inline Quaternion4f QuatRotationFromTo(const Vector3f& src, const Vector3f& dest)
+{
+    // Based on Stan Melax's article in Game Programming Gems
+    float mag0 = VecMagnitude(src);
+    if (mag0 < FLT_EPSILON)
+        return QuatIdentity();
+
+    float mag1 = VecMagnitude(dest);
+    if (mag1 < FLT_EPSILON)
+        return QuatIdentity();
+
+    Vector3f v0 = VecScale(1.0f / mag0, src);
+    Vector3f v1 = VecScale(1.0f / mag1, dest);
+
+    float d = VecDotProduct(v0, v1);
+
+    // If dot == 1, vectors are the same
+    if (d >= (1.0f - 1e-6f))
+        return QuatIdentity();
+
+    if (d < (1e-6f - 1.0f))
+        return gQuatRot[2];
+
+    float s = sqrtf((1.0f + d) * 2.0f);
+    float i = 1.0f / s;
+
+    Vector3f c = VecCrossProduct(v0, v1);
+
+    return QuatNormalize(QuatMake(
+        c.x * i, c.y * i, c.z * i, s * 0.5f));
+}

+ 43 - 0
unity_ios/Classes/RedefinePlatforms.h

@@ -0,0 +1,43 @@
+// DO NOT PUT #pragma once or include guard check here
+// This header is designed to be able to be included multiple times
+
+// This header is used to redefine iOS/tvOS platforms after they were temporary undefined by UndefinePlatforms.h
+// Please make sure to always use this paired with the UndefinePlatforms.h header.
+// Note: PLATFORM_IOS and PLATFORM_TVOS are redefined in 
+// /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/mach-o/loader.h
+//
+// ex.
+//
+// #include "UndefinePlatforms.h"
+// #include "Some3rdParty.h"
+// #include "RedefinePlatforms.h"
+
+#ifndef DETAIL__PLATFORMS_HAD_BEEN_UNDEFINED_BY_UNDEFINEPLATFORMS_H
+    #error "RedefinePlatforms.h can only be used after UndefinePlatforms.h got included before."
+#endif
+
+#undef DETAIL__PLATFORMS_HAD_BEEN_UNDEFINED_BY_UNDEFINEPLATFORMS_H
+
+#undef PLATFORM_IOS
+#if defined(DETAIL__TEMP_PLATFORM_IOS_WAS_1)
+    #undef DETAIL__TEMP_PLATFORM_IOS_WAS_1
+    #define PLATFORM_IOS 1
+#else
+    #define PLATFORM_IOS 0
+#endif
+
+#undef PLATFORM_TVOS
+#if defined(DETAIL__TEMP_PLATFORM_TVOS_WAS_1)
+    #undef DETAIL__TEMP_PLATFORM_TVOS_WAS_1
+    #define PLATFORM_TVOS 1
+#else
+    #define PLATFORM_TVOS 0
+#endif
+
+#undef PLATFORM_VISIONOS
+#if defined(DETAIL__TEMP_PLATFORM_VISIONOS_WAS_1)
+#undef DETAIL__TEMP_PLATFORM_VISIONOS_WAS_1
+#define PLATFORM_VISIONOS 1
+#else
+#define PLATFORM_VISIONOS 0
+#endif

+ 5 - 0
unity_ios/Classes/UI/ActivityIndicator.h

@@ -0,0 +1,5 @@
+#pragma once
+
+void    ShowActivityIndicator(UIView* parent, int style);
+void    ShowActivityIndicator(UIView* parent);
+void    HideActivityIndicator();

+ 49 - 0
unity_ios/Classes/UI/ActivityIndicator.mm

@@ -0,0 +1,49 @@
+#include "ActivityIndicator.h"
+
+static UIActivityIndicatorView* _activityIndicator = nil;
+
+void ShowActivityIndicator(UIView* parent, int style)
+{
+    if (_activityIndicator != nil)
+        return;
+
+    if (style >= 0)
+    {
+        _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: (UIActivityIndicatorViewStyle)style];
+#if !PLATFORM_VISIONOS
+        _activityIndicator.contentScaleFactor = [UIScreen mainScreen].scale;
+#endif
+    }
+
+    if (_activityIndicator != nil)
+    {
+        [parent addSubview: _activityIndicator];
+        _activityIndicator.center = CGPointMake(parent.bounds.size.width / 2, parent.bounds.size.height / 2);
+        [_activityIndicator startAnimating];
+    }
+}
+
+void ShowActivityIndicator(UIView* parent)
+{
+    ShowActivityIndicator(parent, UnityGetShowActivityIndicatorOnLoading());
+}
+
+void HideActivityIndicator()
+{
+    if (_activityIndicator)
+    {
+        [_activityIndicator stopAnimating];
+        [_activityIndicator removeFromSuperview];
+        _activityIndicator = nil;
+    }
+}
+
+UNITY_EXPORT extern "C" void UnityStartActivityIndicator()
+{
+    ShowActivityIndicator(UnityGetGLView());
+}
+
+UNITY_EXPORT extern "C" void UnityStopActivityIndicator()
+{
+    HideActivityIndicator();
+}

+ 75 - 0
unity_ios/Classes/UI/Keyboard.h

@@ -0,0 +1,75 @@
+#pragma once
+
+#import <AVFoundation/AVFoundation.h>
+
+typedef struct
+{
+    const char* text;
+    const char* placeholder;
+
+    UIKeyboardType              keyboardType;
+    UITextAutocorrectionType    autocorrectionType;
+    UITextSpellCheckingType     spellcheckingType;
+    UIKeyboardAppearance        appearance;
+
+    BOOL multiline;
+    BOOL secure;
+    int characterLimit;
+    BOOL oneTimeCode;
+}
+KeyboardShowParam;
+
+
+@interface KeyboardDelegate : NSObject<UITextFieldDelegate, UITextViewDelegate>
+{
+}
+- (void)setPendingSelectionRequest;
+- (BOOL)textFieldShouldReturn:(UITextField*)textField;
+- (void)textInputDone:(id)sender;
+- (void)textInputCancel:(id)sender;
+- (void)textInputLostFocus;
+- (void)textViewDidChange:(UITextView *)textView;
+- (void)becomeFirstResponder;
+- (void)layoutSubviews;
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+- (void)textInputModeDidChange:(NSNotification*)notification;
+- (void)keyboardWillShow:(NSNotification*)notification;
+- (void)keyboardDidShow:(NSNotification*)notification;
+- (void)keyboardWillHide:(NSNotification*)notification;
+- (void)keyboardDidHide:(NSNotification*)notification;
+- (void)keyboardDidChangeFrame:(NSNotification*)notification;
+#endif
+
+// on older devices initial keyboard creation might be slow, so it is good to init in on initial loading.
+// on the other hand, if you dont use keyboard (or use it rarely), you can avoid having all related stuff in memory:
+//     keyboard will be created on demand anyway (in Instance method)
++ (void)Initialize;
++ (KeyboardDelegate*)Instance;
++ (void)Destroy;
+
+- (id)init;
+- (void)setKeyboardParams:(KeyboardShowParam)param;
+- (void)show;
+- (void)hide;
+- (void)shouldHideInput:(BOOL)hide;
+
++ (void)StartReorientation;
++ (void)FinishReorientation;
+
+- (CGRect)queryArea;
+- (NSString*)getText;
+- (void)setText:(NSString*)newText;
+- (BOOL)hasExternalKeyboard;
+- (UITextField*)getTextField;
+
+@property (readonly, nonatomic, getter = queryArea)               CGRect          area;
+@property (readonly, nonatomic)                                 BOOL            active;
+@property (readonly, nonatomic)                                 KeyboardStatus  status;
+@property (retain, nonatomic, getter = getText, setter = setText:)  NSString*       text;
+@property (assign, nonatomic)   int characterLimit;
+@property (readonly, nonatomic)                                 BOOL        canGetSelection;
+@property (nonatomic, getter = querySelection, setter = assignSelection:)  NSRange   selection;
+@property (nonatomic)                                           BOOL        hasUsedDictation;
+
+@end

+ 1274 - 0
unity_ios/Classes/UI/Keyboard.mm

@@ -0,0 +1,1274 @@
+#include "Keyboard.h"
+#include "DisplayManager.h"
+#include "UnityAppController.h"
+#include "UnityForwardDecls.h"
+#include <string>
+#import <GameController/GameController.h>
+
+#ifndef FILTER_EMOJIS_IOS_KEYBOARD
+#define FILTER_EMOJIS_IOS_KEYBOARD 0
+#endif
+
+
+static KeyboardDelegate*    _keyboard = nil;
+
+static bool                 _shouldHideInput = false;
+static bool                 _shouldHideInputChanged = false;
+static const unsigned       kSingleLineFontSize = 20;
+
+extern "C" void UnityKeyboard_StatusChanged(int status);
+extern "C" void UnityKeyboard_TextChanged(NSString* text);
+extern "C" void UnityKeyboard_LayoutChanged(NSString* layout);
+
+
+static unsigned GetToolbarHeight()
+{
+    if (@available(iOS 26, *))
+        return 48;
+    return 40;
+}
+
+
+@interface AdjustableWidthTextField : UITextField
+@property (nonatomic) CGFloat width;
+@end
+
+@implementation AdjustableWidthTextField
+
+- (instancetype)init
+{
+    self = [super initWithFrame:CGRectZero];
+    self.width = 0;
+    self.translatesAutoresizingMaskIntoConstraints = NO;
+
+    if (@available(iOS 26, *))
+        self.backgroundColor = UIColor.clearColor;
+
+    [NSLayoutConstraint activateConstraints:@[
+        [self.topAnchor constraintEqualToAnchor:self.topAnchor],
+        [self.bottomAnchor constraintEqualToAnchor:self.bottomAnchor],
+        [self.leadingAnchor constraintEqualToAnchor:self.leadingAnchor],
+        [self.trailingAnchor constraintEqualToAnchor:self.trailingAnchor],
+    ]];
+    return self;
+}
+
+- (CGSize)intrinsicContentSize
+{
+    CGSize baseSize = [super intrinsicContentSize];
+    return CGSizeMake(self.width, baseSize.height);
+}
+
+@end
+
+@implementation KeyboardDelegate
+{
+    // UI handling
+    // in case of single line we use UITextField inside UIToolbar
+    // in case of multi-line input we use UITextView with UIToolbar as accessory view
+    // tvOS does not support multiline input thus only UITextField option is implemented
+    // tvOS does not support UIToolbar so we rely on tvOS default processing
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+    UITextView*     textView;
+
+    UIToolbar*      viewToolbar;
+    UIToolbar*      fieldToolbar;
+
+    // toolbar items are kept around to prevent releasing them
+    UIBarButtonItem *multiLineDone, *multiLineCancel;
+    UIBarButtonItem *singleLineDone, *singleLineCancel, *singleLineInputField;
+
+    CGFloat singleLineSystemButtonsSpace;
+#endif
+
+    AdjustableWidthTextField*    textField;
+
+    // inputView is view used for actual input (it will be responder): UITextField [single-line] or UITextView [multi-line]
+    // editView is the "root" view for keyboard: UIToolbar [single-line] or UITextView [multi-line]
+    UIView*         inputView;
+    UIView*         editView;
+    // dummy view used for positioning editView when the on-screen keyboard is floating
+    UIView*         dummyAccessoryPositionView;
+
+    KeyboardShowParam cachedKeyboardParam;
+
+    CGRect          _area;
+    CGRect          lastKeyboardRect;
+    NSString*       initialText;
+
+    UIKeyboardType  keyboardType;
+
+    BOOL            _multiline;
+    BOOL            _inputHidden;
+    BOOL            _active;
+    KeyboardStatus          _status;
+    int             _characterLimit;
+
+    // not pretty but seems like easiest way to keep "we are rotating" status
+    BOOL            _rotating;
+    NSRange         _hiddenSelection;
+    NSRange         _selectionRequest;
+
+    // used for < iOS 14 external keyboard
+    CGFloat         _heightOfKeyboard;
+}
+
+@synthesize area;
+@synthesize active      = _active;
+@synthesize status      = _status;
+@synthesize text;
+@synthesize selection;
+@synthesize hasUsedDictation;
+
+- (void)setPendingSelectionRequest
+{
+    if (_selectionRequest.location != NSNotFound)
+    {
+        _keyboard.selection = _selectionRequest;
+        _selectionRequest.location = NSNotFound;
+    }
+}
+
+- (BOOL)textFieldShouldReturn:(UITextField*)textFieldObj
+{
+    [self textInputDone: nil];
+    return YES;
+}
+
+- (void)textInputDone:(id)sender
+{
+    if (_status == Visible)
+    {
+        _status = Done;
+        UnityKeyboard_StatusChanged(_status);
+    }
+    [self hide];
+}
+
+- (void)becomeFirstResponder
+{
+    if (_status == Visible)
+    {
+        [_keyboard->inputView becomeFirstResponder];
+    }
+}
+
+- (void)textInputCancel:(id)sender
+{
+    _status = Canceled;
+    UnityKeyboard_StatusChanged(_status);
+    [self hide];
+}
+
+- (void)textInputLostFocus
+{
+    if (_status == Visible)
+    {
+        _status = LostFocus;
+        UnityKeyboard_StatusChanged(_status);
+    }
+    [self hide];
+}
+
+- (void)textViewDidChange:(UITextView *)textView
+{
+  if (textView.markedTextRange == nil && textView.text.length > _characterLimit && _characterLimit != 0)
+  {
+    textView.text = [textView.text substringToIndex: _characterLimit];
+  }
+
+  UnityKeyboard_TextChanged(textView.text);
+}
+
+- (void)textFieldDidChange:(UITextField*)textField
+{
+  if (textField.markedTextRange == nil && textField.text.length > _characterLimit && _characterLimit != 0)
+  {
+    textField.text = [textField.text substringToIndex: _characterLimit];
+  }
+
+  UnityKeyboard_TextChanged(textField.text);
+}
+
+- (BOOL)textViewShouldBeginEditing:(UITextView*)view
+{
+    return YES;
+}
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+- (void)textInputModeDidChange:(NSNotification*)notification
+{
+    [self setPendingSelectionRequest];
+    // Apple reports back the primary language of the current keyboard text input mode using BCP 47 language code i.e "en-GB"
+    // but this also (undocumented) will return "dictation" when using voice dictation and "emoji" when using the emoji keyboard.
+    if ([_keyboard->inputView.textInputMode.primaryLanguage isEqualToString: @"dictation"])
+    {
+        hasUsedDictation = YES;
+    }
+}
+
+- (void)keyboardWillShow:(NSNotification *)notification
+{
+    if (notification.userInfo == nil || inputView == nil)
+        return;
+
+    [self setPendingSelectionRequest];
+    [self positionInput];
+
+    auto appController = GetAppController();
+    if (@available(iOS 16, tvOS 16, *)) {}
+    else if (!appController.didResignActive) // A workaround for iPadOS 15 to fully animate keyboard after going from detached to docked
+        [inputView reloadInputViews];
+}
+
+- (void)reportLayout:(NSString*)layout
+{
+    // Under some conditions keyboardDidShow is sent multiple times in a row
+    // only report layout to Unity if it actually changed
+    // to avoid possibly expensive consequences
+    static NSString* lastReportedLayout = nil;
+
+    if (lastReportedLayout != layout)
+    {
+        lastReportedLayout = layout;
+        UnityKeyboard_LayoutChanged(layout);
+    }
+}
+
+- (void)keyboardDidShow:(NSNotification*)notification
+{
+    _active = YES;
+    [self reportLayout:textField.textInputMode.primaryLanguage];
+}
+
+- (void)keyboardWillHide:(NSNotification*)notification
+{
+    if (_keyboard)
+    {
+        // Reset selection to avoid selection graphics staying on the screen
+        if (_keyboard.selection.length > 0)
+        {
+            NSRange range = NSMakeRange(_keyboard.text.length, 0);
+            _keyboard.selection = range;
+        }
+    }
+    [self reportLayout:nil];
+    [self systemHideKeyboard];
+}
+
+- (void)keyboardDidHide:(NSNotification*)notification
+{
+    // The audio engine starts and restarts by listening to AVAudioSessionInterruptionNotifications, However
+    // Apple does *not* guarantee that the AVAudioSessionInterruptionTypeEnded will be sent, especially if
+    // the app is in the foreground - This can happen when using the dictate function on the keyboard
+    // so we send the notification ourselves to ensure the audio restarts.
+    if (hasUsedDictation)
+    {
+        [[NSNotificationCenter defaultCenter] postNotificationName: AVAudioSessionInterruptionNotification
+         object: [AVAudioSession sharedInstance]
+         userInfo: @{AVAudioSessionInterruptionTypeKey: [NSNumber numberWithUnsignedInteger: AVAudioSessionInterruptionTypeEnded]}];
+    }
+}
+
+- (void)keyboardDidChangeFrame:(NSNotification*)notification
+{
+    CGRect srcRect  = [[notification.userInfo objectForKey: UIKeyboardFrameEndUserInfoKey] CGRectValue];
+    CGRect rect     = [UnityGetGLView() convertRect: srcRect fromView: nil];
+
+    if (!CGRectEqualToRect(lastKeyboardRect, rect))
+    {
+        [self positionInput];
+    }
+    lastKeyboardRect = rect;
+}
+
+- (void)positionInput
+{
+    /*
+    The logic in this function and everywhere around it is extremely fragile
+    When changing make sure to test:
+     - Area API
+     - Orientation changes
+     - Size changes in Stage Manager
+     - Split Screen
+     - Ducking/Undocking the keyboard
+     - All the combinations of all of the above
+    */
+
+    if ([self hasExternalKeyboard])
+    {
+        [self systemHideKeyboard];
+        _active = NO;
+        return;
+    }
+
+    if (!inputView.isFirstResponder)
+    {
+        _area = CGRectMake(0, 0, 0, 0);
+        _active = NO;  // in case of floating keyboard this looks to be the only place to detect it closed
+        return;
+    }
+    UIView* unityView = UnityGetGLView();
+    CGRect unityViewRect = unityView.frame;
+    CGRect accessoryRect = [dummyAccessoryPositionView.superview convertRect: dummyAccessoryPositionView.frame toView: unityView];
+    float width = unityViewRect.size.width;
+    float xPos = accessoryRect.origin.x;
+    float yPos = accessoryRect.origin.y;
+    const float safeAreaInsetLeft = [unityView safeAreaInsets].left;
+    const float safeAreaInsetRight = [unityView safeAreaInsets].right;
+    const float safeAreaInsetBottom = [unityView safeAreaInsets].bottom;
+
+    if (_rotating || yPos == 0)
+    {
+        // hacky way to reposition input view just before the screen rotation animation starts
+        // this way position animates nicely throughout the screen rotation animation
+        yPos = unityViewRect.size.height - safeAreaInsetBottom;
+        if (_rotating)
+            xPos = safeAreaInsetLeft;
+    }
+
+    // Only add safe area offset if the input bar is placed at the bottom of the view
+    float offsetY = yPos == unityViewRect.size.height ? safeAreaInsetBottom : 0;
+
+    const auto kToolBarHeight = GetToolbarHeight();
+    if (_multiline)
+    {
+        // use smaller area for iphones and bigger one for ipads
+        int height = UnityDeviceDPI() > 300 ? 75 : 100;
+
+        editView.frame = CGRectMake(xPos + safeAreaInsetLeft, yPos - kToolBarHeight - height - offsetY, width - safeAreaInsetLeft - safeAreaInsetRight, height);
+        viewToolbar.frame = CGRectMake(xPos, yPos - kToolBarHeight - offsetY, width, kToolBarHeight);;
+    }
+    else
+    {
+        // add some space between keyboard and toolbar, which is now transparent
+        if (@available(iOS 26, *))
+            offsetY += 10;
+
+        editView.frame  = CGRectMake(xPos, yPos - kToolBarHeight - offsetY, width, kToolBarHeight);
+        textField.width = unityViewRect.size.width - safeAreaInsetLeft - safeAreaInsetRight - self->singleLineSystemButtonsSpace;
+        [textField invalidateIntrinsicContentSize];
+    }
+
+    [self updateInputHidden];
+    // updating area of the keyboard
+    _area = CGRectMake(xPos, yPos, width - safeAreaInsetLeft - safeAreaInsetRight, unityViewRect.size.height - yPos);
+    if (!editView.hidden)
+        _area = CGRectUnion(_area, editView.frame);
+    _active = YES;  // at this point input field is first responder, so keyboard is active
+}
+
+#endif
+
++ (void)Initialize
+{
+    NSAssert(_keyboard == nil, @"[KeyboardDelegate Initialize] called after creating keyboard");
+    if (!_keyboard)
+        _keyboard = [[KeyboardDelegate alloc] init];
+}
+
++ (KeyboardDelegate*)Instance
+{
+    if (!_keyboard)
+        _keyboard = [[KeyboardDelegate alloc] init];
+
+    return _keyboard;
+}
+
++ (void)Destroy
+{
+    _keyboard = nil;
+}
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+- (UIToolbar*)createToolbarWithItems:(NSArray*)items
+{
+    // Default position ensures the input view slides from the bottom of the screen together with the keyboard
+    CGSize windowSize = [UnityGetGLView() bounds].size;
+    UIToolbar* toolbar = [[UIToolbar alloc] initWithFrame: CGRectMake(0, windowSize.height, windowSize.width, GetToolbarHeight())];
+    UnitySetViewTouchProcessing(toolbar, touchesIgnored);
+    toolbar.hidden = NO;
+    toolbar.items = items;
+    return toolbar;
+}
+
+- (void)createToolbars
+{
+    multiLineDone   = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemDone target: self action: @selector(textInputDone:)];
+    multiLineCancel = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemCancel target: self action: @selector(textInputCancel:)];
+    viewToolbar     = [self createToolbarWithItems: @[multiLineDone, multiLineCancel]];
+
+    singleLineInputField = [[UIBarButtonItem alloc] initWithCustomView: textField];
+    singleLineDone       = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemDone target: self action: @selector(textInputDone:)];
+    singleLineCancel     = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemCancel target: self action: @selector(textInputCancel:)];
+    fieldToolbar         = [self createToolbarWithItems: @[singleLineInputField, singleLineDone, singleLineCancel]];
+
+    // Gather round boys, let's hear the story of apple ingenious api.
+    // Did you see UIBarButtonItem above? oh the marvel of design
+    // Maybe you thought it will have some connection to UIView or something?
+    //   Yes, internally, in private members, hidden like dirty laundry in a room of a youngster
+    // But, you may ask, why do we care? Oh, easy - sometimes you want to use non-english language
+    // And in these languages, not good enough to be english, done/cancel items can have different sizes
+    // And we insist on having input field size set because, yes, we cannot quite do a layout inside UIToolbar
+    //   [because there are no views we can actually touch, thanks for asking]
+    // Obviously, localizing system strings is also well hidden, and what works now might stop working tomorrow
+    // That's why we keep UIBarButtonSystemItemDone/UIBarButtonSystemItemCancel above
+    //   and try to translate "Done"/"Cancel" in a way that "should" work
+    //   if localization fails we will still have "some" values (coming from english)
+    UIFont* font = [UIFont systemFontOfSize: kSingleLineFontSize];
+    NSBundle* uikitBundle = [NSBundle bundleForClass: UIApplication.class];
+    NSString* doneStr   = [uikitBundle localizedStringForKey: @"Done" value: nil table: nil];
+    NSString* cancelStr = [uikitBundle localizedStringForKey: @"Cancel" value: nil table: nil];
+
+    // mind you, all of that is highly empirical.
+    // we assume space between items to be 18 [both between buttons and on the sides]
+    // we also assume that button width would be more or less the title width exactly (it should be quite close though)
+
+    // some language fonts (i.e korean, vietnamese..) can have non integer width (i.e 34.5999), thus we round up the width to fit the buttons
+    const CGFloat doneW   = ceil([doneStr   sizeWithAttributes: @{NSFontAttributeName: font}].width);
+    const CGFloat cancelW = ceil([cancelStr sizeWithAttributes: @{NSFontAttributeName: font}].width);
+
+    singleLineSystemButtonsSpace = doneW + cancelW + 3 * 18;
+}
+
+#endif
+
+- (id)init
+{
+    NSAssert(_keyboard == nil, @"You can have only one instance of KeyboardDelegate");
+    self = [super init];
+    if (self)
+    {
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+        // Default position ensures the input view slides from the bottom of the screen together with the keyboard
+        CGSize windowSize = [UnityGetGLView() bounds].size;
+        textView = [[UITextView alloc] initWithFrame: CGRectMake(0, windowSize.height, 480, 30)];
+        textView.delegate = self;
+        textView.font = [UIFont systemFontOfSize: 18.0];
+        textView.hidden = YES;
+        // For some unknown reason, the `textView` has visual issues when
+        // using Dark Mode (some parts of the view become transparent). See case 1367091.
+        // However, setting alpha to a value different than 1 fixes the issue.
+        textView.alpha = 0.99;
+
+        dummyAccessoryPositionView = [[UIView alloc] initWithFrame: CGRectMake(0, windowSize.height, 0, 0)];
+        dummyAccessoryPositionView.backgroundColor = [UIColor clearColor];
+        dummyAccessoryPositionView.userInteractionEnabled = NO;
+        dummyAccessoryPositionView.translatesAutoresizingMaskIntoConstraints = NO;
+#endif
+
+        textField = [[AdjustableWidthTextField alloc] init];
+        textField.delegate = self;
+        if (@available(iOS 26, *))
+            textField.borderStyle = UITextBorderStyleNone;
+        else
+            textField.borderStyle = UITextBorderStyleRoundedRect;
+        textField.font = [UIFont systemFontOfSize: kSingleLineFontSize];
+        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
+        textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
+
+        [textField addTarget: self action: @selector(textFieldDidChange:) forControlEvents: UIControlEventEditingChanged];
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+        [self createToolbars];
+#if !PLATFORM_VISIONOS
+        textView.inputAccessoryView = dummyAccessoryPositionView;
+        textField.inputAccessoryView = dummyAccessoryPositionView;
+#endif
+#endif
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardWillShow:) name: UIKeyboardWillShowNotification object: nil];
+        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardDidShow:) name: UIKeyboardDidShowNotification object: nil];
+        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardWillHide:) name: UIKeyboardWillHideNotification object: nil];
+        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardDidHide:) name: UIKeyboardDidHideNotification object: nil];
+        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardDidChangeFrame:) name: UIKeyboardDidChangeFrameNotification object: nil];
+        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(textInputModeDidChange:) name: UITextInputCurrentInputModeDidChangeNotification object: nil];
+        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardDidConnect:) name: GCKeyboardDidConnectNotification object: nil];
+#endif
+
+        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(textInputDone:) name: UITextFieldTextDidEndEditingNotification object: nil];
+        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(textInputDone:) name: UITextViewTextDidEndEditingNotification object: nil];
+    }
+
+    return self;
+}
+
+- (void)layoutSubviews
+{
+#if PLATFORM_IOS
+    // Needed for updating keyboard when resizing the view in stage manager and orientation change
+    [_keyboard positionInput];
+#endif
+}
+
+- (void)keyboardDidConnect:(NSNotification *)notification {
+    [self systemHideKeyboard];
+}
+
+- (void)setTextInputTraits:(id<UITextInputTraits>)traits
+    withParam:(KeyboardShowParam)param
+{
+    UITextAutocapitalizationType capitalization = [KeyboardDelegate capitalizationForKeyboardParam: param];
+
+    if (!_inputHidden)
+        traits.secureTextEntry = param.secure;
+    if (param.secure)
+    {
+        traits.autocorrectionType = UITextAutocorrectionTypeNo;
+        traits.spellCheckingType  = UITextSpellCheckingTypeNo;
+        traits.autocapitalizationType = UITextAutocapitalizationTypeNone;
+    }
+    else
+    {
+        traits.autocorrectionType = param.autocorrectionType;
+        traits.spellCheckingType  = param.spellcheckingType;
+        traits.autocapitalizationType = capitalization;
+    }
+    traits.keyboardType = param.keyboardType;
+    traits.keyboardAppearance = param.appearance;
+}
+
++ (UITextAutocapitalizationType)capitalizationForKeyboardParam:(KeyboardShowParam)param
+{
+    if (param.secure)
+        return UITextAutocapitalizationTypeNone;
+
+    UITextAutocapitalizationType capitalization;
+    switch (param.keyboardType)
+    {
+        case UIKeyboardTypeURL:
+        case UIKeyboardTypeEmailAddress:
+        case UIKeyboardTypeWebSearch:
+            capitalization = UITextAutocapitalizationTypeNone;
+            break;
+        default:
+            capitalization = UITextAutocapitalizationTypeSentences;
+    }
+
+    return capitalization;
+}
+
+- (void)setKeyboardParams:(KeyboardShowParam)param
+{
+#if PLATFORM_IOS
+    if (@available(iOS 26, *))
+    {
+        if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad)
+        {
+            // iOS bug: number/phone pad have special behavior that leads to crash with floating keyboard in windowed mode
+            //   input field activation shows minimalist overlay bubble, tapping ouside which dismissed it
+            //   the keyboard only opens on tapping the input field again,
+            //   but if accessory view is set on field, it crashes inside Apple code
+            // plus did not find a way to detect when first bubble is dismissed (it's keyboard close from our perspective)
+            switch (param.keyboardType)
+            {
+                case UIKeyboardTypeDecimalPad:
+                case UIKeyboardTypePhonePad:
+                case UIKeyboardTypeNumberPad:
+                    param.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
+                    break;
+                default:
+                    break;
+            }
+        }
+    }
+#endif
+
+    [NSObject cancelPreviousPerformRequestsWithTarget: self];
+    if (cachedKeyboardParam.multiline != param.multiline ||
+        cachedKeyboardParam.secure != param.secure ||
+        cachedKeyboardParam.keyboardType != param.keyboardType ||
+        cachedKeyboardParam.autocorrectionType != param.autocorrectionType ||
+        cachedKeyboardParam.appearance != param.appearance)
+    {
+        [self hideUIDelayed];
+    }
+
+    cachedKeyboardParam = param;
+
+    if (_active)
+        [self hide];
+
+    initialText = param.text ? [[NSString alloc] initWithUTF8String: param.text] : @"";
+
+    _characterLimit = param.characterLimit;
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+    _multiline = param.multiline;
+    if (_multiline)
+    {
+        [self setTextInputTraits: textView withParam: param];
+    }
+    else
+    {
+        if (param.oneTimeCode)
+            textField.textContentType = UITextContentTypeOneTimeCode;
+
+        [self setTextInputTraits: textField withParam: param];
+        textField.placeholder = [NSString stringWithUTF8String: param.placeholder];
+    }
+
+    inputView = _multiline ? textView : textField;
+    editView = _multiline ? textView : fieldToolbar;
+
+    // Initially hide input fields in case external keyboard is connected.
+    // This is needed for certain cases where external keyboard is connected
+    // and soft keyboard is reopened without closing it first.
+    // If external keyboard does not exist, these values will be updated by keyboardWillShow
+    editView.hidden = YES;
+    viewToolbar.hidden = YES;
+
+#else // PLATFORM_TVOS
+    [self setTextInputTraits: textField withParam: param];
+    textField.placeholder = [NSString stringWithUTF8String: param.placeholder];
+    inputView = textField;
+    editView = textField;
+#endif
+
+    [self shouldHideInput: _shouldHideInput];
+
+    [KeyboardDelegate Instance].text = initialText;
+
+    _status     = Visible;
+    UnityKeyboard_StatusChanged(_status);
+    _active = !self.hasExternalKeyboard;
+    _selectionRequest.location = NSNotFound;
+}
+
+// we need to show/hide keyboard to react to orientation too, so extract we extract UI fiddling
+
+- (void)showUI
+{
+    // if we unhide everything now the input will be shown smaller then needed quickly (and resized later)
+    // so unhide only when keyboard is actually shown (we will update it when reacting to ios notifications)
+    [NSObject cancelPreviousPerformRequestsWithTarget: self];
+    if (!inputView.isFirstResponder)
+    {
+        editView.hidden = YES;
+
+        UIView* unityView = UnityGetGLView();
+        [unityView addSubview: editView];
+#if PLATFORM_IOS
+        [unityView addSubview: viewToolbar];
+#endif
+        [inputView becomeFirstResponder];
+
+
+#if PLATFORM_TVOS
+        // make keyboard usable via controller by allowing exit to home temporarily
+        // val 3, as second lowest bit indicates a temporary disable
+        if (UnityGetAppleTVRemoteAllowExitToMenu() == 0)
+            UnitySetAppleTVRemoteAllowExitToMenu(3);
+#endif
+    }
+
+    // we need to reload input views when switching the keyboard type for already active keyboard
+    // otherwise the changed traits may not be immediately applied
+    editView.hidden = self.inputHidden;
+    [inputView reloadInputViews];
+}
+
+- (void)hideUI
+{
+    [NSObject cancelPreviousPerformRequestsWithTarget: self];
+    [self performSelector: @selector(hideUIDelayed) withObject: nil afterDelay: 0.05]; // to avoid unnecessary hiding
+}
+
+- (BOOL)inputHidden
+{
+    if (self.hasExternalKeyboard)
+        return YES;
+    return _inputHidden;
+}
+
+- (void)hideUIDelayed
+{
+    [inputView resignFirstResponder];
+
+    [editView removeFromSuperview];
+    editView.hidden = YES;
+
+#if PLATFORM_IOS
+    [viewToolbar removeFromSuperview];
+    viewToolbar.hidden = YES;
+#endif
+
+    // Keyboard notifications are not supported on tvOS so keyboardWillHide: will never be called which would set _active to false.
+    // To work around that limitation we will update _active from here.
+    #if PLATFORM_TVOS
+    BOOL wasActive = _active;
+    _active = editView.isFirstResponder;
+    // if closing, restore exit value to what it was (getter ignores temp value and returns what it is meant to be)
+    if (!_active && wasActive)
+        UnitySetAppleTVRemoteAllowExitToMenu(UnityGetAppleTVRemoteAllowExitToMenu());
+    #endif
+}
+
+- (void)systemHideKeyboard
+{
+    // when we are rotating os will bombard us with keyboardWillHide: and keyboardDidChangeFrame:
+    // ignore all of them (we do it here only to simplify code: we call systemHideKeyboard only from these notification handlers)
+    if (_rotating)
+        return;
+
+    _active = editView.isFirstResponder;
+    editView.hidden = YES;
+    // Default position ensures the input view slides from the bottom of the screen together with the keyboard
+    CGSize windowSize = [UnityGetGLView() frame].size;
+    editView.frame = CGRectMake(0, windowSize.height, editView.frame.size.width, editView.frame.size.height);
+
+    #if PLATFORM_IOS || PLATFORM_VISIONOS
+    viewToolbar.hidden = YES;
+    #endif
+
+    _area = CGRectMake(0, 0, 0, 0);
+    lastKeyboardRect = CGRectMake(0, 0, 0, 0);
+}
+
+- (void)show
+{
+    [self showUI];
+}
+
+- (void)hide
+{
+    [self hideUI];
+}
+
+- (void)updateInputHidden
+{
+    if (_shouldHideInputChanged)
+    {
+        [self shouldHideInput: _shouldHideInput];
+        _shouldHideInputChanged = false;
+    }
+
+    textField.returnKeyType = _inputHidden ? UIReturnKeyDone : UIReturnKeyDefault;
+
+    #if PLATFORM_IOS || PLATFORM_VISIONOS
+
+    UIView* unityView = UnityGetGLView();
+    NSMutableArray<UIAccessibilityElement*>* elements = unityView.accessibilityElements ? [unityView.accessibilityElements mutableCopy] : [NSMutableArray array];
+
+    viewToolbar.hidden  = !_multiline || self.inputHidden;
+
+    [elements removeObject: (UIAccessibilityElement*)viewToolbar];
+
+    if (!viewToolbar.hidden)
+    {
+        [elements addObject: (UIAccessibilityElement*)viewToolbar];
+    }
+
+    [elements removeObject: (UIAccessibilityElement*)fieldToolbar];
+
+    editView.hidden     = self.inputHidden;
+
+    if (!_multiline && !editView.hidden)
+    {
+        [elements addObject: (UIAccessibilityElement*)fieldToolbar];
+    }
+
+    unityView.accessibilityElements = elements;
+
+    #else
+
+    editView.hidden     = self.inputHidden;
+
+    #endif
+
+    [self setTextInputTraits: textField withParam: cachedKeyboardParam];
+}
+
+- (CGRect)queryArea
+{
+    return _area;
+}
+
+- (NSRange)querySelection
+{
+    UIView<UITextInput>* textInput;
+
+#if PLATFORM_TVOS
+    textInput = textField;
+#else
+    textInput = _multiline ? textView : textField;
+#endif
+
+    UITextPosition* beginning = textInput.beginningOfDocument;
+
+    UITextRange* selectedRange = textInput.selectedTextRange;
+    UITextPosition* selectionStart = selectedRange.start;
+    UITextPosition* selectionEnd = selectedRange.end;
+
+    const NSInteger location = [textInput offsetFromPosition: beginning toPosition: selectionStart];
+    const NSInteger length = [textInput offsetFromPosition: selectionStart toPosition: selectionEnd];
+
+    return NSMakeRange(location, length);
+}
+
+- (void)assignSelection:(NSRange)range
+{
+    UIView<UITextInput>* textInput;
+
+#if PLATFORM_TVOS
+    textInput = textField;
+#else
+    textInput = _multiline ? textView : textField;
+#endif
+
+    UITextPosition* begin = [textInput beginningOfDocument];
+    UITextPosition* caret = [textInput positionFromPosition: begin offset: range.location];
+    UITextPosition* select = [textInput positionFromPosition: caret offset: range.length];
+    UITextRange* textRange = [textInput textRangeFromPosition: caret toPosition: select];
+
+    [textInput setSelectedTextRange: textRange];
+    if (_inputHidden)
+        _hiddenSelection = range;
+    _selectionRequest = range;
+}
+
++ (void)StartReorientation
+{
+    if (_keyboard && _keyboard.active)
+    {
+        _keyboard->_rotating = YES;
+    }
+}
+
++ (void)FinishReorientation
+{
+    if (_keyboard && _keyboard.active)
+    {
+        _keyboard->_rotating = NO;
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+        _keyboard->editView.hidden = _keyboard.inputHidden;
+#endif
+    }
+}
+
+- (NSString*)getText
+{
+    if (_status == Canceled)
+        return initialText;
+    else
+    {
+#if PLATFORM_TVOS
+        return [textField text];
+#else
+        return _multiline ? [textView text] : [textField text];
+#endif
+    }
+}
+
+- (void)setText:(NSString*)newText
+{
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+    if (_multiline)
+        textView.text = newText;
+    else
+        textField.text = newText;
+#else
+    textField.text = newText;
+#endif
+
+    // for hidden selection place cursor at the end when text changes
+    _hiddenSelection.location = newText.length;
+    _hiddenSelection.length = 0;
+}
+
+- (void)shouldHideInput:(BOOL)hide
+{
+    if (hide)
+    {
+        switch (keyboardType)
+        {
+            case UIKeyboardTypeDefault:                 hide = YES; break;
+            case UIKeyboardTypeASCIICapable:            hide = YES; break;
+            case UIKeyboardTypeNumbersAndPunctuation:   hide = YES; break;
+            case UIKeyboardTypeURL:                     hide = YES; break;
+            case UIKeyboardTypeNumberPad:               hide = NO;  break;
+            case UIKeyboardTypePhonePad:                hide = NO;  break;
+            case UIKeyboardTypeNamePhonePad:            hide = NO;  break;
+            case UIKeyboardTypeEmailAddress:            hide = YES; break;
+            case UIKeyboardTypeTwitter:                 hide = YES; break;
+            case UIKeyboardTypeWebSearch:               hide = YES; break;
+            case UIKeyboardTypeDecimalPad:              hide = NO; break;
+            default:                                    hide = NO;  break;
+        }
+    }
+
+    _inputHidden = hide;
+}
+
+- (BOOL)hasExternalKeyboard
+{
+    return [GCKeyboard coalescedKeyboard] != nil;
+}
+
+- (UITextField*)getTextField
+{
+    return textField;
+}
+
+static bool StringContainsEmoji(NSString *string);
+- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string_
+{
+    BOOL stringContainsEmoji = NO;
+
+#if FILTER_EMOJIS_IOS_KEYBOARD
+    stringContainsEmoji = StringContainsEmoji(string_);
+#endif
+
+    if (range.length + range.location > textField.text.length)
+        return NO;
+
+    return [self currentText: textField.text shouldChangeInRange: range replacementText: string_] && !stringContainsEmoji;
+}
+
+- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text_
+{
+    BOOL stringContainsEmoji = NO;
+
+#if FILTER_EMOJIS_IOS_KEYBOARD
+    stringContainsEmoji = StringContainsEmoji(text_);
+#endif
+
+    if (range.length + range.location > textView.text.length)
+        return NO;
+
+    return [self currentText: textView.text shouldChangeInRange: range replacementText: text_] && !stringContainsEmoji;
+}
+
+- (BOOL)currentText:(NSString*)currentText shouldChangeInRange:(NSRange)range  replacementText:(NSString*)text_
+{
+    NSUInteger newLength = currentText.length + (text_.length - range.length);
+
+    if (newLength > _characterLimit && _characterLimit != 0 && newLength >= currentText.length)
+    {
+        // If the user inserts any emoji that exceeds the character limit it should quickly reject it, else it'll crash. We need to check regardless of FILTER_EMOJIS_IOS_KEYBOARD status as sometimes this method gets called before we've filtered out an emoji.
+        if (StringContainsEmoji(text_))
+            return NO;
+
+        NSString* newReplacementText = @"";
+        if ((currentText.length - range.length) < _characterLimit)
+            newReplacementText = [text_ substringWithRange: NSMakeRange(0, _characterLimit - (currentText.length - range.length))];
+
+        NSString* newText = [currentText stringByReplacingCharactersInRange: range withString: newReplacementText];
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+        if (_multiline)
+            [textView setText: newText];
+        else
+            [textField setText: newText];
+#else
+        [textField setText: newText];
+#endif
+
+        // If we're trying to exceed the max length of the field BUT the text can merge into
+        // precomposed characters then we should allow the input.
+        NSString* precomposedNewText = [currentText precomposedStringWithCompatibilityMapping];
+        __block int count = 0;
+        [precomposedNewText enumerateSubstringsInRange: NSMakeRange(0, [precomposedNewText length]) options: NSStringEnumerationByComposedCharacterSequences
+         usingBlock: ^(NSString *inSubstring, NSRange inSubstringRange, NSRange inEnclosingRange, BOOL *outStop) {
+             count++;
+         }];
+        // count of characters of precomposed string will equal the character limit
+        // if there has been characters merged bringing us under the limit.
+        return count <= _characterLimit;
+    }
+    else
+    {
+        if (_inputHidden && _hiddenSelection.length > 0)
+        {
+            NSString* newText = [currentText stringByReplacingCharactersInRange: _hiddenSelection withString: text_];
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+            if (_multiline)
+                [textView setText: newText];
+            else
+                [textField setText: newText];
+#else
+            [textField setText: newText];
+#endif
+            _hiddenSelection.location = _hiddenSelection.location + text_.length;
+            _hiddenSelection.length = 0;
+            self.selection = _hiddenSelection;
+            return NO;
+        }
+
+        _hiddenSelection.location = range.location + text_.length;
+        _hiddenSelection.length = 0;
+        return YES;
+    }
+}
+
+@end
+
+//==============================================================================
+//
+//  Unity Interface:
+
+UNITY_EXPORT extern "C" void UnityKeyboard_Create(unsigned keyboardType, int autocorrection, int multiline, int secure, int alert, const char* text, const char* placeholder, int characterLimit)
+{
+#if PLATFORM_TVOS
+    // Not supported. The API for showing keyboard for editing multi-line text is not available on tvOS
+    multiline = false;
+#endif
+
+    static const UIKeyboardType keyboardTypes[] =
+    {
+        UIKeyboardTypeDefault,
+        UIKeyboardTypeASCIICapable,
+        UIKeyboardTypeNumbersAndPunctuation,
+        UIKeyboardTypeURL,
+        UIKeyboardTypeNumberPad,
+        UIKeyboardTypePhonePad,
+        UIKeyboardTypeNamePhonePad,
+        UIKeyboardTypeEmailAddress,
+        UIKeyboardTypeDefault, // Default is used in case Wii U specific NintendoNetworkAccount type is selected (indexed at 8 in UnityEngine.TouchScreenKeyboardType)
+        UIKeyboardTypeTwitter,
+        UIKeyboardTypeWebSearch,
+        UIKeyboardTypeDecimalPad,
+        UIKeyboardTypeNumberPad, // Keyboard type 12, OneTimeCode, does not directly translate to a UIKeyboardType.
+    };
+
+    const auto maxKeyboardType = sizeof(keyboardTypes) /  sizeof(UIKeyboardTypeDefault) - 1;
+    if (keyboardType > maxKeyboardType)
+    {
+        assert(false && "Unsupported keyboard type");
+        keyboardType = 0;
+    }
+
+    // on iOS 15, QuickType bar was decoupled from autocorrection (so it still shows candidates)
+    // for a principle of "the least surprise" we keep it coupled internally, so autocorrection == spellchecking
+    // TODO: should we expose the control of it?
+    static const UITextAutocorrectionType autocorrectionTypes[] =
+    {
+        UITextAutocorrectionTypeNo,
+        UITextAutocorrectionTypeDefault,
+    };
+
+    static const UITextSpellCheckingType spellcheckingTypes[] =
+    {
+        UITextSpellCheckingTypeNo,
+        UITextSpellCheckingTypeDefault,
+    };
+
+    static const UIKeyboardAppearance keyboardAppearances[] =
+    {
+        UIKeyboardAppearanceDefault,
+        UIKeyboardAppearanceAlert,
+    };
+
+    KeyboardShowParam param =
+    {
+        text, placeholder,
+        keyboardTypes[keyboardType],
+        autocorrectionTypes[autocorrection],
+        spellcheckingTypes[autocorrection],
+        keyboardAppearances[alert],
+        (BOOL)multiline, (BOOL)secure,
+        characterLimit,
+        keyboardType == 12
+    };
+
+    [[KeyboardDelegate Instance] setKeyboardParams: param];
+}
+
+UNITY_EXPORT extern "C" void UnityKeyboard_Show()
+{
+    // do not send hide if didnt create keyboard
+    // TODO: probably assert?
+    if (!_keyboard)
+        return;
+
+    [[KeyboardDelegate Instance] show];
+}
+
+UNITY_EXPORT extern "C" void UnityKeyboard_Hide()
+{
+    // do not send hide if didnt create keyboard
+    // TODO: probably assert?
+    if (!_keyboard)
+        return;
+
+    [[KeyboardDelegate Instance] textInputLostFocus];
+}
+
+UNITY_EXPORT extern "C" void UnityKeyboard_SetText(const char* text)
+{
+    [KeyboardDelegate Instance].text = [NSString stringWithUTF8String: text];
+}
+
+UNITY_EXPORT extern "C" NSString* UnityKeyboard_GetText()
+{
+    return [KeyboardDelegate Instance].text;
+}
+
+UNITY_EXPORT extern "C" int UnityKeyboard_IsActive()
+{
+    return (_keyboard && _keyboard.active) ? 1 : 0;
+}
+
+UNITY_EXPORT extern "C" int UnityKeyboard_Status()
+{
+    return _keyboard ? _keyboard.status : Canceled;
+}
+
+UNITY_EXPORT extern "C" void UnityKeyboard_SetInputHidden(int hidden)
+{
+    _shouldHideInput        = hidden;
+    _shouldHideInputChanged = true;
+
+    // update hidden status only if keyboard is on screen to avoid showing input view out of nowhere
+    if (_keyboard && _keyboard.active)
+        [_keyboard updateInputHidden];
+}
+
+UNITY_EXPORT extern "C" int UnityKeyboard_IsInputHidden()
+{
+    return _shouldHideInput ? 1 : 0;
+}
+
+UNITY_EXPORT extern "C" void UnityKeyboard_GetRect(float* x, float* y, float* w, float* h)
+{
+    CGRect area = _keyboard ? _keyboard.area : CGRectMake(0, 0, 0, 0);
+
+    // convert to unity coord system
+
+    float   multX   = (float)GetMainDisplaySurface()->targetW / UnityGetGLView().bounds.size.width;
+    float   multY   = (float)GetMainDisplaySurface()->targetH / UnityGetGLView().bounds.size.height;
+
+    *x = 0;
+    *y = area.origin.y * multY;
+    *w = area.size.width * multX;
+    *h = area.size.height * multY;
+}
+
+UNITY_EXPORT extern "C" void UnityKeyboard_SetCharacterLimit(unsigned characterLimit)
+{
+    [KeyboardDelegate Instance].characterLimit = characterLimit;
+}
+
+UNITY_EXPORT extern "C" int UnityKeyboard_CanGetSelection()
+{
+    return (_keyboard) ? 1 : 0;
+}
+
+UNITY_EXPORT extern "C" void UnityKeyboard_GetSelection(int* location, int* length)
+{
+    if (_keyboard)
+    {
+        NSRange selection = _keyboard.selection;
+
+        *location = (int)selection.location;
+        *length = (int)selection.length;
+    }
+    else
+    {
+        *location = 0;
+        *length = 0;
+    }
+}
+
+UNITY_EXPORT extern "C" int UnityKeyboard_CanSetSelection()
+{
+    return (_keyboard) ? 1 : 0;
+}
+
+UNITY_EXPORT extern "C" void UnityKeyboard_SetSelection(int location, int length)
+{
+    if (_keyboard)
+    {
+        _keyboard.selection = NSMakeRange(location, length);
+    }
+}
+
+//==============================================================================
+//
+//  Emoji Filtering: unicode magic
+
+static bool StringContainsEmoji(NSString *string)
+{
+    __block BOOL returnValue = NO;
+
+    [string enumerateSubstringsInRange: NSMakeRange(0, string.length)
+ options: NSStringEnumerationByComposedCharacterSequences
+ usingBlock:^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop)
+    {
+        const unichar hs = [substring characterAtIndex: 0];
+        const unichar ls = substring.length > 1 ? [substring characterAtIndex: 1] : 0;
+
+            #define IS_IN(val, min, max) (((val) >= (min)) && ((val) <= (max)))
+
+        if (IS_IN(hs, 0xD800, 0xDBFF))
+        {
+            if (substring.length > 1)
+            {
+                const int uc = ((hs - 0xD800) * 0x400) + (ls - 0xDC00) + 0x10000;
+
+                // Musical: [U+1D000, U+1D24F]
+                // Enclosed Alphanumeric Supplement: [U+1F100, U+1F1FF]
+                // Enclosed Ideographic Supplement: [U+1F200, U+1F2FF]
+                // Miscellaneous Symbols and Pictographs: [U+1F300, U+1F5FF]
+                // Supplemental Symbols and Pictographs: [U+1F900, U+1F9FF]
+                // Emoticons: [U+1F600, U+1F64F]
+                // Transport and Map Symbols: [U+1F680, U+1F6FF]
+                if (IS_IN(uc, 0x1D000, 0x1F9FF))
+                    returnValue = YES;
+            }
+        }
+        else if (substring.length > 1 && ls == 0x20E3)
+        {
+            // emojis for numbers: number + modifier ls = U+20E3
+            returnValue = YES;
+        }
+        else
+        {
+            if (        // Latin-1 Supplement
+                hs == 0x00A9 || hs == 0x00AE
+                // General Punctuation
+                ||  hs == 0x203C || hs == 0x2049
+                // Letterlike Symbols
+                ||  hs == 0x2122 || hs == 0x2139
+                // Arrows
+                ||  IS_IN(hs, 0x2194, 0x2199) || IS_IN(hs, 0x21A9, 0x21AA)
+                // Miscellaneous Technical
+                ||  IS_IN(hs, 0x231A, 0x231B) || IS_IN(hs, 0x23E9, 0x23F3) || IS_IN(hs, 0x23F8, 0x23FA) || hs == 0x2328 || hs == 0x23CF
+                // Geometric Shapes
+                ||  IS_IN(hs, 0x25AA, 0x25AB) || IS_IN(hs, 0x25FB, 0x25FE) || hs == 0x25B6 || hs == 0x25C0
+                // Miscellaneous Symbols
+                ||  IS_IN(hs, 0x2600, 0x2604) || IS_IN(hs, 0x2614, 0x2615) || IS_IN(hs, 0x2622, 0x2623) || IS_IN(hs, 0x262E, 0x262F)
+                ||  IS_IN(hs, 0x2638, 0x263A) || IS_IN(hs, 0x2648, 0x2653) || IS_IN(hs, 0x2665, 0x2666) || IS_IN(hs, 0x2692, 0x2694)
+                ||  IS_IN(hs, 0x2696, 0x2697) || IS_IN(hs, 0x269B, 0x269C) || IS_IN(hs, 0x26A0, 0x26A1) || IS_IN(hs, 0x26AA, 0x26AB)
+                ||  IS_IN(hs, 0x26B0, 0x26B1) || IS_IN(hs, 0x26BD, 0x26BE) || IS_IN(hs, 0x26C4, 0x26C5) || IS_IN(hs, 0x26CE, 0x26CF)
+                ||  IS_IN(hs, 0x26D3, 0x26D4) || IS_IN(hs, 0x26D3, 0x26D4) || IS_IN(hs, 0x26E9, 0x26EA) || IS_IN(hs, 0x26F0, 0x26F5)
+                ||  IS_IN(hs, 0x26F7, 0x26FA)
+                ||  hs == 0x260E || hs == 0x2611 || hs == 0x2618 || hs == 0x261D || hs == 0x2620 || hs == 0x2626 || hs == 0x262A
+                ||  hs == 0x2660 || hs == 0x2663 || hs == 0x2668 || hs == 0x267B || hs == 0x267F || hs == 0x2699 || hs == 0x26C8
+                ||  hs == 0x26D1 || hs == 0x26FD
+                // Dingbats
+                ||  IS_IN(hs, 0x2708, 0x270D) || IS_IN(hs, 0x2733, 0x2734) || IS_IN(hs, 0x2753, 0x2755)
+                ||  IS_IN(hs, 0x2763, 0x2764) || IS_IN(hs, 0x2795, 0x2797)
+                ||  hs == 0x2702 || hs == 0x2705 || hs == 0x270F || hs == 0x2712 || hs == 0x2714 || hs == 0x2716 || hs == 0x271D
+                ||  hs == 0x2721 || hs == 0x2728 || hs == 0x2744 || hs == 0x2747 || hs == 0x274C || hs == 0x274E || hs == 0x2757
+                ||  hs == 0x27A1 || hs == 0x27B0 || hs == 0x27BF
+                // CJK Symbols and Punctuation
+                ||  hs == 0x3030 || hs == 0x303D
+                // Enclosed CJK Letters and Months
+                ||  hs == 0x3297 || hs == 0x3299
+                // Supplemental Arrows-B
+                ||  IS_IN(hs, 0x2934, 0x2935)
+                // Miscellaneous Symbols and Arrows
+                ||  IS_IN(hs, 0x2B05, 0x2B07) || IS_IN(hs, 0x2B1B, 0x2B1C) || hs == 0x2B50 || hs == 0x2B55
+            )
+            {
+                returnValue = YES;
+            }
+        }
+
+            #undef IS_IN
+    }];
+
+    return returnValue;
+}

+ 20 - 0
unity_ios/Classes/UI/OrientationSupport.h

@@ -0,0 +1,20 @@
+#pragma once
+
+#include <CoreGraphics/CGAffineTransform.h>
+
+#if !PLATFORM_TVOS
+ScreenOrientation       ConvertToUnityScreenOrientation(UIInterfaceOrientation hwOrient);
+UIInterfaceOrientation  ConvertToIosScreenOrientation(ScreenOrientation orient);
+#endif
+
+#if !PLATFORM_TVOS
+UIInterfaceOrientation  UIViewControllerInterfaceOrientation(UIViewController* controller);
+#endif
+ScreenOrientation       UIViewControllerOrientation(UIViewController* controller);
+
+CGAffineTransform       TransformForOrientation(ScreenOrientation curOrient);
+CGAffineTransform       TransformBetweenOrientations(ScreenOrientation fromOrient, ScreenOrientation toOrient);
+
+ScreenOrientation       OrientationAfterTransform(ScreenOrientation curOrient, CGAffineTransform transform);
+
+void                    OrientView(UIViewController* host, UIView* view, ScreenOrientation to);

+ 165 - 0
unity_ios/Classes/UI/OrientationSupport.mm

@@ -0,0 +1,165 @@
+#include "OrientationSupport.h"
+#include <math.h>
+
+CGAffineTransform TransformForOrientation(ScreenOrientation orient)
+{
+    switch (orient)
+    {
+        case portrait:              return CGAffineTransformIdentity;
+        case portraitUpsideDown:    return CGAffineTransformMakeRotation(M_PI);
+        case landscapeLeft:         return CGAffineTransformMakeRotation(M_PI_2);
+        case landscapeRight:        return CGAffineTransformMakeRotation(-M_PI_2);
+
+        default:                    return CGAffineTransformIdentity;
+    }
+    return CGAffineTransformIdentity;
+}
+
+CGAffineTransform TransformBetweenOrientations(ScreenOrientation fromOrient, ScreenOrientation toOrient)
+{
+    CGAffineTransform fromTransform = TransformForOrientation(fromOrient);
+    CGAffineTransform toTransform   = TransformForOrientation(toOrient);
+
+    return CGAffineTransformConcat(CGAffineTransformInvert(fromTransform), toTransform);
+}
+
+#if !PLATFORM_TVOS
+UIInterfaceOrientation ConvertToIosScreenOrientation(ScreenOrientation orient)
+{
+    switch (orient)
+    {
+        case portrait:              return UIInterfaceOrientationPortrait;
+        case portraitUpsideDown:    return UIInterfaceOrientationPortraitUpsideDown;
+        // landscape left/right have switched values in device/screen orientation
+        // though unity docs are adjusted with device orientation values, so swap here
+        case landscapeLeft:         return UIInterfaceOrientationLandscapeRight;
+        case landscapeRight:        return UIInterfaceOrientationLandscapeLeft;
+
+        case orientationUnknown:    return (UIInterfaceOrientation)UIInterfaceOrientationUnknown;
+
+        default:                    return UIInterfaceOrientationPortrait;
+    }
+
+    return UIInterfaceOrientationPortrait;
+}
+
+ScreenOrientation ConvertToUnityScreenOrientation(UIInterfaceOrientation orient)
+{
+    switch (orient)
+    {
+        case UIInterfaceOrientationPortrait:            return portrait;
+        case UIInterfaceOrientationPortraitUpsideDown:  return portraitUpsideDown;
+        // landscape left/right have switched values in device/screen orientation
+        // though unity docs are adjusted with device orientation values, so swap here
+        case UIInterfaceOrientationLandscapeLeft:       return landscapeRight;
+        case UIInterfaceOrientationLandscapeRight:      return landscapeLeft;
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wswitch"
+        case UIInterfaceOrientationUnknown:             return orientationUnknown;
+#pragma clang diagnostic pop
+
+        default:                                        return portrait;
+    }
+}
+
+// Replacement for UIViewController.interfaceOrientation which is obsolete since iOS 8.0
+UIInterfaceOrientation UIViewControllerInterfaceOrientation(UIViewController* c)
+{
+#if !PLATFORM_VISIONOS
+    CGPoint fixedPoint = [c.view.window.screen.coordinateSpace convertPoint: CGPointMake(0.0, 0.0) toCoordinateSpace: c.view.window.screen.fixedCoordinateSpace];
+
+    if (fabs(fixedPoint.x) < FLT_EPSILON)
+    {
+        if (fabs(fixedPoint.y) < FLT_EPSILON)
+            return UIInterfaceOrientationPortrait;
+        else
+            return UIInterfaceOrientationLandscapeLeft;
+    }
+    else
+    {
+        if (fabs(fixedPoint.y) < FLT_EPSILON)
+            return UIInterfaceOrientationLandscapeRight;
+        else
+            return UIInterfaceOrientationPortraitUpsideDown;
+    }
+#else
+    return UIInterfaceOrientationLandscapeLeft;
+#endif
+}
+
+#endif
+
+ScreenOrientation UIViewControllerOrientation(UIViewController* controller)
+{
+#if PLATFORM_TVOS
+    return UNITY_TVOS_ORIENTATION;
+#elif PLATFORM_VISIONOS
+    return UNITY_VISIONOS_ORIENTATION;
+#else
+    return ConvertToUnityScreenOrientation(UIViewControllerInterfaceOrientation(controller));
+#endif
+}
+
+ScreenOrientation OrientationAfterTransform(ScreenOrientation curOrient, CGAffineTransform transform)
+{
+    int rotDeg = (int)::roundf(::atan2f(transform.b, transform.a) * (180 / M_PI));
+    assert(rotDeg == 0 || rotDeg == 90 || rotDeg == -90 || rotDeg == 180 || rotDeg == -180);
+
+    if (rotDeg == 0)
+    {
+        return curOrient;
+    }
+    else if ((rotDeg == 180) || (rotDeg == -180))
+    {
+        if (curOrient == portrait)
+            return portraitUpsideDown;
+        else if (curOrient == portraitUpsideDown)
+            return portrait;
+        else if (curOrient == landscapeRight)
+            return landscapeLeft;
+        else if (curOrient == landscapeLeft)
+            return landscapeRight;
+    }
+    else if (rotDeg == 90)
+    {
+        if (curOrient == portrait)
+            return landscapeLeft;
+        else if (curOrient == portraitUpsideDown)
+            return landscapeRight;
+        else if (curOrient == landscapeRight)
+            return portrait;
+        else if (curOrient == landscapeLeft)
+            return portraitUpsideDown;
+    }
+    else if (rotDeg == -90)
+    {
+        if (curOrient == portrait)
+            return landscapeRight;
+        else if (curOrient == portraitUpsideDown)
+            return landscapeLeft;
+        else if (curOrient == landscapeRight)
+            return portraitUpsideDown;
+        else if (curOrient == landscapeLeft)
+            return portrait;
+    }
+
+    ::printf("rotation unhandled: %d\n", rotDeg);
+    return curOrient;
+}
+
+void OrientView(UIViewController* host, UIView* view, ScreenOrientation to)
+{
+    ScreenOrientation fromController = UIViewControllerOrientation(host);
+
+    CGAffineTransform transform = TransformBetweenOrientations(fromController, to);
+
+    // this is for unity-inited orientation. In that case we need to manually adjust bounds if changing portrait/landscape
+    // the easiest way would be to manually rotate current bounds (to acknowledge the fact that we do NOT rotate controller itself)
+    // NB: as we use current view bounds we need to use view transform to properly adjust them
+    CGRect rect = view.bounds;
+    CGSize ext  = CGSizeApplyAffineTransform(rect.size, CGAffineTransformConcat(CGAffineTransformInvert(view.transform), transform));
+
+    view.transform  = transform;
+    view.bounds     = CGRectMake(0, 0, ::fabs(ext.width), ::fabs(ext.height));
+}

+ 18 - 0
unity_ios/Classes/UI/StoreReview.m

@@ -0,0 +1,18 @@
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+
+// This definition is here only for compiler to know about selector requestReview
+@interface UnityStoreReviewController
++ requestReview;
+@end
+
+UNITY_EXPORT bool UnityRequestStoreReview()
+{
+    Class classSKStoreReviewController = NSClassFromString(@"SKStoreReviewController");
+    if (!classSKStoreReviewController || ![classSKStoreReviewController respondsToSelector: @selector(requestReview)])
+        return false;
+
+    [classSKStoreReviewController performSelector: @selector(requestReview)];
+    return true;
+}
+
+#endif // PLATFORM_IOS || PLATFORM_VISIONOS

+ 105 - 0
unity_ios/Classes/UI/UnityAppController+ViewHandling.h

@@ -0,0 +1,105 @@
+#pragma once
+
+#include "UnityAppController.h"
+#include <AvailabilityMacros.h>
+
+
+@interface UnityAppController (ViewHandling)
+
+// tweaking view hierarchy and handling of orientation
+
+// there are 3 main uses cases regarding UI handling:
+//
+// 1. normal game case: you shouldnt care about all this at all
+//
+// 2. you need some not-so-trivial overlayed views and/or minor UI tweaking
+//    most likely all you need is to subscribe to "orientation changed" notification
+//    or in case you have per-orientation UI logic override willTransitionToViewController
+//
+// 3. you create UI-rich app where unity view is just one of many
+//    in that case you might want to create your own controllers and implement transitions on top
+//    also instead of orientUnity: (and Screen.orientation in script) you should use orientInterface
+
+
+// override this if you need customized unityview (subclassing)
+// if you simply want different root view, tweak view hierarchy in createAutorotatingUnityViewController
+- (UnityView*)createUnityView;
+
+// for view controllers we discern between platforms that do support orientation (e.g. iOS) and the ones that dont (e.g. tvOS)
+// both have concept of "default" view controller: for iOS it will be auto-rotating one (with possible constraints) and "simple" controller otherwise
+// in case of supporting orientation we will discern case of fixed-orientation view controller (that seems to be the only way to handle it robustly)
+// _unityView will be inited at the point of calling any of "create view controller" methods
+// please note that these are actual "create" methods: there is no need to tweak hierarchy right away
+
+- (UIViewController*)createUnityViewControllerDefault;
+#if UNITY_SUPPORT_ROTATION
+- (UIViewController*)createUnityViewControllerForOrientation:(UIInterfaceOrientation)orient;
+#endif
+
+#if UNITY_SUPPORT_ROTATION
+// if you override these you need to call super
+// if your root controller is not subclassed from UnityViewControllerBase, call these when rotation is happening
+- (void)interfaceWillChangeOrientationTo:(UIInterfaceOrientation)toInterfaceOrientation;
+- (void)interfaceDidChangeOrientationFrom:(UIInterfaceOrientation)fromInterfaceOrientation;
+#endif
+
+// handling of changing ViewControllers:
+// willStartWithViewController: will be called on startup, when creating view hierarchy
+// willTransitionToViewController:fromViewController: didTransitionToViewController:fromViewController:
+// are called before/after we are doing some magic to switch to new root controller due to forced orientation change
+
+// by default:
+// willStartWithViewController: will make _unityView as root view
+// willTransitionToViewController:fromViewController: will do nothing
+// didTransitionToViewController:fromViewController: will send orientation events to unity view
+// you can use them to tweak view hierarchy if needed
+
+- (void)willStartWithViewController:(UIViewController*)controller;
+- (void)willTransitionToViewController:(UIViewController*)toController fromViewController:(UIViewController*)fromController;
+- (void)didTransitionToViewController:(UIViewController*)toController fromViewController:(UIViewController*)fromController;
+
+
+// override this if you want to have custom snapshot view.
+// by default it will capture the frame drawn inside applicationWillResignActive specifically to let app respond to OnApplicationPause
+// will be called on every applicationWillResignActive; returned view will be released in applicationDidBecomeActive
+// NB: case of returning nil will be handled gracefully
+- (UIView*)createSnapshotView;
+
+// you should not override these methods
+
+// creates initial UI hierarchy (e.g. splash screen) and calls willStartWithViewController
+- (void)createUI;
+// shows game itself (hides splash, and bring _rootView to front)
+- (void)showGameUI;
+
+// returns the topmost presentedViewController if there is one, or just rootViewController
+- (UIViewController*)topMostController;
+
+// will create the correct view controller for requested orientation/autorotation
+- (UIViewController*)createRootViewController;
+
+// old deprecated methods: no longer used
+// the caveat is: there are some issues in clang related to method deprecation
+// which results in warnings not being generated for overriding deprecated methods (in some circumstances).
+// so instead of deprecating these methods we just remove them and will check at runtime if user have them and whine about it
+
+//- (UnityView*)createUnityViewImpl DEPRECATED_MSG_ATTRIBUTE("Will not be called. Override createUnityView");
+//- (void)createViewHierarchyImpl DEPRECATED_MSG_ATTRIBUTE("Will not be called. Override willStartWithViewController");
+//- (void)createViewHierarchy DEPRECATED_MSG_ATTRIBUTE("Is not implemented. Use createUI");
+
+@end
+
+#if UNITY_SUPPORT_ROTATION
+@interface UnityAppController (OrientationSupport)
+// will create the correct view controller for given orientation
+- (UIViewController*)createRootViewControllerForOrientation:(UIInterfaceOrientation)orientation;
+
+// forcibly orient interface
+- (void)orientInterface:(UIInterfaceOrientation)orient;
+
+// check unity requested orientation and applies it
+- (void)checkOrientationRequest;
+
+- (void)orientUnity:(UIInterfaceOrientation)orient __deprecated_msg("use orientInterface instead.");
+@end
+#endif

+ 475 - 0
unity_ios/Classes/UI/UnityAppController+ViewHandling.mm

@@ -0,0 +1,475 @@
+#include "UnityAppController+ViewHandling.h"
+#include "UnityAppController+Rendering.h"
+
+#include "UI/OrientationSupport.h"
+#include "UI/UnityView.h"
+#include "UI/UnityViewControllerBase.h"
+#include "Unity/DisplayManager.h"
+
+
+// TEMP: ?
+#include "UI/ActivityIndicator.h"
+#include "UI/Keyboard.h"
+#include <utility>
+
+static BOOL _shouldUseDefaultViewControllerForFixedOrientations = NO;
+
+@implementation UnityAppController (ViewHandling)
+
+#if UNITY_SUPPORT_ROTATION
+// special case for when we DO know the app orientation, but dont get it through normal mechanism (UIViewController orientation handling)
+// how can this happen:
+// 1. On startup: ios is not sending "change orientation" notifications on startup (but rather we "start" in correct one already)
+// 2. When using presentation controller it can override orientation constraints, so on dismissing we need to tweak app orientation;
+//      pretty much like startup situation UIViewController would have correct orientation, and app will be out-of-sync
+- (void)updateAppOrientation:(UIInterfaceOrientation)orientation
+{
+    // update our (AppContoller) view of orientation
+    _curOrientation = orientation;
+
+    // do unity view "orientation magic"
+    [_unityView willRotateToOrientation: orientation fromOrientation: (UIInterfaceOrientation)UIInterfaceOrientationUnknown];
+    [_unityView didRotate];
+
+    // after we have updated unity view, this will poke unity itself about the changes in orient/extents
+    [_unityView updateUnityBackbufferSize];
+}
+
+#endif
+
+- (UnityView*)createUnityView
+{
+    return [[UnityView alloc] initFromMainScreen];
+}
+
+- (UIViewController*)createUnityViewControllerDefault
+{
+#if PLATFORM_IOS
+    UnityViewControllerBase* ret = [[UnityDefaultViewController alloc] initShouldHandleFixedOrientation: _shouldUseDefaultViewControllerForFixedOrientations];
+#else
+    UnityViewControllerBase* ret = [[UnityDefaultViewController alloc] init];
+#endif
+
+    ret.notificationDelegate = [[UnityViewControllerNotificationsDefaultSender alloc] init];
+
+#if PLATFORM_TVOS
+    ret.controllerUserInteractionEnabled = YES;
+#endif
+
+    return ret;
+}
+
+#if UNITY_SUPPORT_ROTATION
+- (UIViewController*)createUnityViewControllerForOrientation:(UIInterfaceOrientation)orient
+{
+    UnityViewControllerBase* ret = [AllocUnitySingleOrientationViewController(orient) init];
+    ret.notificationDelegate = [[UnityViewControllerNotificationsDefaultSender alloc] init];
+    return ret;
+}
+
+#endif
+
+- (UIViewController*)createRootViewController
+{
+    UIViewController* ret = nil;
+    if (!UNITY_SUPPORT_ROTATION || UnityShouldAutorotate() || _shouldUseDefaultViewControllerForFixedOrientations)
+        ret = [self createUnityViewControllerDefault];
+
+#if UNITY_SUPPORT_ROTATION
+    if (ret == nil)
+        ret = [self createRootViewControllerForOrientation: ConvertToIosScreenOrientation((ScreenOrientation)UnityRequestedScreenOrientation())];
+#endif
+
+    return ret;
+}
+
+- (UIViewController*)topMostController
+{
+    UIViewController *topController = self.window.rootViewController;
+    while (topController.presentedViewController)
+        topController = topController.presentedViewController;
+    return topController;
+}
+
+- (void)willStartWithViewController:(UIViewController*)controller
+{
+#if !PLATFORM_VISIONOS
+    _unityView.contentScaleFactor   = UnityScreenScaleFactor([UIScreen mainScreen]);
+#else
+    _unityView.contentScaleFactor   = 1.0f;
+#endif
+    _unityView.autoresizingMask     = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
+
+    _rootController.view = _rootView = _unityView;
+}
+
+- (void)willTransitionToViewController:(UIViewController*)toController fromViewController:(UIViewController*)fromController
+{
+}
+
+- (void)didTransitionToViewController:(UIViewController*)toController fromViewController:(UIViewController*)fromController
+{
+#if UNITY_SUPPORT_ROTATION && !PLATFORM_VISIONOS
+    // when transitioning between view controllers ios will not send reorient events (because they are bound to controllers, not view)
+    // so we imitate them here so unity view can update its size/orientation
+    UIInterfaceOrientation newOrientation = UIViewControllerInterfaceOrientation(toController);
+    [_unityView willRotateToOrientation: newOrientation  fromOrientation: ConvertToIosScreenOrientation(_unityView.contentOrientation)];
+    [_unityView didRotate];
+
+    // NB: this is both important and insane at the same time (that we have several places to keep current orentation and we need to sync them)
+    _curOrientation = newOrientation;
+#endif
+}
+
+- (UIView*)createSnapshotView
+{
+    // Note that on iPads with iOS 9 or later (up to iOS 10.2 at least) there's a bug in the iOS compositor: any use of -[UIView snapshotViewAfterScreenUpdates]
+    // causes black screen being shown temporarily when 4 finger gesture to swipe to another app in the task switcher is being performed slowly
+    return [_rootView snapshotViewAfterScreenUpdates: YES];
+}
+
+- (void)createUI
+{
+    NSAssert(_unityView != nil, @"_unityView should be inited at this point");
+    NSAssert(_window != nil, @"_window should be inited at this point");
+
+#if PLATFORM_IOS
+    if (@available(iOS 16.0, *))    _shouldUseDefaultViewControllerForFixedOrientations = YES;
+    else                            _shouldUseDefaultViewControllerForFixedOrientations = NO;
+#endif
+
+    _rootController = [self createRootViewController];
+
+    [self willStartWithViewController: _rootController];
+
+    NSAssert(_rootView != nil, @"_rootView  should be inited at this point");
+    NSAssert(_rootController != nil, @"_rootController should be inited at this point");
+
+    // CODE ARCHEOLOGY: We used to add _rootView (unityView) to the subviews of _window so that unityView would get its
+    // initial actual device values (e.g. safeAreaInsets) before initializing graphics. This is not needed anymore after
+    // we made a change where iOS is handling splash screen. Now unityView will be configured at
+    // [_window makeKeyAndVisible] call. makeKeyAndVisible will configure _window.rootViewController.view, which is
+    // _rootController.view, which is unityView (_rootView)
+
+    // We should have rootViewController set always, otherwise UIKit might trow exception when doing anything with UI
+    _window.rootViewController = _rootController;
+
+    [UIView setAnimationsEnabled: NO];
+
+    // make window visible only after we have set up initial controller we want to show
+    [_window makeKeyAndVisible];
+
+#if UNITY_SUPPORT_ROTATION
+    // to be able to query orientation from view controller we should actually show it.
+    // at this point we can only show splash screen, so update app orientation after we started showing it
+    // NB: _window.rootViewController = splash view controller (not _rootController)
+    [self updateAppOrientation: ConvertToIosScreenOrientation(UIViewControllerOrientation(_window.rootViewController))];
+#endif
+
+    NSNumber* style = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"Unity_LoadingActivityIndicatorStyle"];
+    ShowActivityIndicator(_rootView, style ? [style intValue] : -1);
+
+    NSNumber* vcControlled = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"UIViewControllerBasedStatusBarAppearance"];
+    if (vcControlled && ![vcControlled boolValue])
+        printf_console("\nSetting UIViewControllerBasedStatusBarAppearance to NO is no longer supported.\n"
+            "Apple actively discourages that, and all application-wide methods of changing status bar appearance are deprecated\n\n"
+        );
+}
+
+- (void)showGameUI
+{
+    HideActivityIndicator();
+
+    // make sure that we start up with correctly created/inited rendering surface
+    // NB: recreateRenderingSurface won't go into rendering because AppReady state is not set
+#if UNITY_SUPPORT_ROTATION
+    [self checkOrientationRequest];
+#endif
+
+    // recreateRenderingSurface expects layer's drawableSize to be set to proper value
+    //   and updateLayerDrawableSizeFromBounds does exactly that
+    // note that normally we go through recreateRenderingSurfaceIfNeeded
+    //   which does call updateLayerDrawableSizeFromBounds
+    [_unityView updateLayerDrawableSizeFromBounds];
+    [_unityView updateUnityBackbufferSize];
+    [_unityView recreateRenderingSurface];
+
+    // UI hierarchy
+    _window.rootViewController = _rootController;
+    [_window bringSubviewToFront: _rootView];
+
+#if UNITY_SUPPORT_ROTATION
+    // to be able to query orientation from view controller we should actually show it.
+    // at this point we finally started to show game view controller. Just in case update orientation again
+    [self updateAppOrientation: ConvertToIosScreenOrientation(UIViewControllerOrientation(_rootController))];
+#endif
+
+    // why we set level ready only now:
+    // surface recreate will try to repaint if this var is set (poking unity to do it)
+    // but this frame now is actually the first one we want to process/draw
+    // so all the recreateSurface before now (triggered by reorientation) should simply change extents
+
+    [self advanceEngineLoadState: kUnityEngineLoadStateAppReady];
+
+    // this is/was needed as a workaround for various issues with first frame rendering
+    //   on older iOS, not doing this "render twice" would result in black frame showing
+    // that does not seem necessary now, but we keep it "just in case" when using CADisplayLink
+    // when using CAMetalDisplayLink we cannot render to backbuffer (drawable) out of the displaylink callback, hence we must skip this
+
+    if(!self.unityUsesMetalDisplayLink)
+    {
+        // why we skip present:
+        // this will be the first frame to draw, so Start methods will be called
+        // and we want to properly handle resolution request in Start (which might trigger surface recreate)
+        // NB: we want to draw right after showing window, to avoid black frame creeping in
+
+        if (!UnityIsPaused())
+            UnityRepaint();
+
+        [self repaint];
+    }
+
+    [UIView setAnimationsEnabled: YES];
+}
+
+#if UNITY_SUPPORT_ROTATION
+- (void)transitionToViewController:(UIViewController*)vc
+{
+    [self willTransitionToViewController: vc fromViewController: _rootController];
+
+    // first: remove from view hierarchy.
+    // if we simply hide the window before assigning the new view controller, it will cause black frame flickering
+    // on the other hand, hiding the window is important by itself to better signal the intent to iOS
+    //   e.g. unless we hide the window view, safeArea might stop working (due to bug in iOS if we're to speculate)
+    // due to that we do this hide/unhide sequence: we want to to make it hidden, but still unhide it before changing window view controller.
+    _window.hidden = YES;
+    _window.hidden = NO;
+
+    _rootController.view = nil;
+    _window.rootViewController = nil;
+
+    // second: assign new root controller (and view hierarchy with that), restore bounds
+    //   this is very important to first set _rootController, and only then window root controller
+    //   as the latter will poke [UIApplicationDelegate application:supportedInterfaceOrientationsForWindow:]
+    //   and unity implementation expects _rootController to be already set
+    _window.rootViewController = _rootController = vc;
+    _rootController.view = _rootView;
+
+    // CODE ARCHEOLOGY: in here we were tweaking window bounds to agree with screen bounds (and did some iOS8 specific workaround)
+    // This is no longer needed it seems, and is actually harmful for the "split view" supporting apps
+    // If you have fullscreen window, it will be automatically resized to take the whole screen
+    // and otherwise we must not touch it, as it will be controlled by multitasking
+
+    // third: restore window as key and layout subviews to finalize size changes
+    [_window makeKeyAndVisible];
+    [_window layoutSubviews];
+
+    // In iOS16+ after we setup a new contoller and when we have multiple windows visible, iOS not fully prepares
+    // view controller according it's orientation requirements. And then inside didTransitionToViewController:
+    // from UIViewControllerInterfaceOrientation we get bad orientation as it uses scree.coordinationSpace which is not
+    // yet changed. So we want to delay didTransitionToViewController call. And in this case we get a call to view
+    // controllers -viewWillTransitionToSize: method and at this time the orientation change is already happened and
+    // then we send didTransitionToViewController. If view controller changes are setup correctly from iOS, then iOS do
+    // not call -viewWillTransitionToSize:.
+    UIInterfaceOrientation newOrientation = UIViewControllerInterfaceOrientation(vc);
+    BOOL orientationChangedToSupported = vc.supportedInterfaceOrientations & (1 << newOrientation);
+    if (!UnityiOSVersionIsAtLeast(16) || orientationChangedToSupported)
+    {
+        [self didTransitionToViewController: vc fromViewController: _rootController];
+    }
+}
+
+- (void)interfaceWillChangeOrientationTo:(UIInterfaceOrientation)toInterfaceOrientation
+{
+    UIInterfaceOrientation fromInterfaceOrientation = _curOrientation;
+
+    _curOrientation = toInterfaceOrientation;
+    [_unityView willRotateToOrientation: toInterfaceOrientation fromOrientation: fromInterfaceOrientation];
+}
+
+- (void)interfaceDidChangeOrientationFrom:(UIInterfaceOrientation)fromInterfaceOrientation
+{
+    [_unityView didRotate];
+}
+
+#endif
+
+- (void)notifyHideHomeButtonChange
+{
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+    // setNeedsUpdateOfHomeIndicatorAutoHidden is not implemented on iOS 11.0.
+    // The bug has been fixed in iOS 11.0.1. See http://www.openradar.me/35127134
+    if ([_rootController respondsToSelector: @selector(setNeedsUpdateOfHomeIndicatorAutoHidden)])
+        [_rootController setNeedsUpdateOfHomeIndicatorAutoHidden];
+#endif
+}
+
+- (void)notifyDeferSystemGesturesChange
+{
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+    [_rootController setNeedsUpdateOfScreenEdgesDeferringSystemGestures];
+#endif
+}
+
+@end
+
+
+#if UNITY_SUPPORT_ROTATION
+
+@implementation UnityAppController (OrientationSupport)
+- (UIViewController*)createRootViewControllerForOrientation:(UIInterfaceOrientation)orientation
+{
+    return [self createUnityViewControllerForOrientation: orientation];
+}
+
+- (void)checkOrientationRequest
+{
+    // if no orientation/allowed-orientation change - do nothing
+    if (!UnityHasOrientationRequest() && !UnityShouldChangeAllowedOrientations())
+        return;
+
+    // if there is a presentation controller, it takes over orientation control
+    //   in this case we should completely ignore all orientation changes
+    // mind you, we just *delay* them, and they will be satisfied once presentation controller is dismissed
+    // extra care like this is needed, because below we might recreate ViewController completely breaking
+    //   presentation controller dismissal
+    if (_rootController.presentedViewController)
+        return;
+
+    // to reiterate: we have different processing on newish iOS where we stick to just one view controller
+    // in this case we leave all the processing to iOS
+    if(_shouldUseDefaultViewControllerForFixedOrientations)
+    {
+        NSAssert([self.rootViewController isKindOfClass: [UnityDefaultViewController class]],
+            @"UnityDefaultViewController should be root controller");
+
+        [(UnityDefaultViewController*)self.rootViewController updateSupportedOrientations];
+        [UIViewController attemptRotationToDeviceOrientation];
+
+        // note that we could have a big if-else block and call it once at the end of the method
+        // but it was deemed too ugly
+        UnityOrientationRequestWasCommitted();
+        return;
+    }
+
+    // normally we want to call attemptRotationToDeviceOrientation to tell iOS that we changed orientation constraints
+    // but if the current orientation is disabled we need special processing, as iOS will simply ignore us
+    //   the only good/robust way is to simply recreate "autorotating" view controller and transition to it if needed
+
+    // please note that we want to trigger "orientation request" code path if we recreate autorotating view controller
+    bool changeOrient = UnityHasOrientationRequest();
+
+    // if we should recreate autorotating view controller - see below
+    bool shouldTransferToNewAutorotVC = false;
+
+    // first we check if we need to update orientations enabled for autorotation
+    // this needs to be done *only* if we are to continue autorotating
+    //   otherwise we will transition from this view controller
+    //   and iOS will reread enabled orientations on next ViewController activation
+    const bool autorot = UnityShouldAutorotate(), autorotChanged = UnityAutorotationStatusChanged();
+    if (UnityShouldChangeAllowedOrientations() && autorot)
+    {
+        NSUInteger rootOrient = 1 << UIViewControllerInterfaceOrientation(self.rootViewController);
+        if (!autorotChanged && (rootOrient & EnabledAutorotationInterfaceOrientations()))
+        {
+            // instead of querying unity for supported orientations, we keep them in the default (autorotating) controller
+            // this is THE place where we should update those (otherwise, filled on creation)
+            if ([self.rootViewController isKindOfClass: [UnityDefaultViewController class]])
+                [(UnityDefaultViewController*)self.rootViewController updateSupportedOrientations];
+
+            // if we are currently autorotating AND changed allowed orientations while keeping current interface orientation allowed:
+            // we can simply trigger attemptRotationToDeviceOrientation and we are done
+            // please note that this can happen when current *device* orientation is disabled (and we want to enable it)
+            [UIViewController attemptRotationToDeviceOrientation];
+        }
+        else
+        {
+            // otherwise we recreate default autorotating view controller
+            // to spell it out, we recreate if:
+            // - we continue doing autorotation, but the current orientation is disabled
+            // - we were not autorotating but start now
+            shouldTransferToNewAutorotVC = true;
+            changeOrient = true;
+        }
+    }
+
+    if (changeOrient)
+    {
+        // on some devices like iPhone XS layoutSubview is not called when transitioning from different orientations with the same resolution
+        // therefore forcing layoutSubview on all orientation changes
+        [_unityView setNeedsLayout];
+
+        if (autorot)
+        {
+            // just started autorotating or decided to recreate autorot controller above
+            if (autorotChanged || shouldTransferToNewAutorotVC)
+                [self transitionToViewController: [self createUnityViewControllerDefault]];
+            [UIViewController attemptRotationToDeviceOrientation];
+        }
+        else
+        {
+            UIInterfaceOrientation requestedOrient = ConvertToIosScreenOrientation((ScreenOrientation)UnityRequestedScreenOrientation());
+            // on one hand orientInterface: should be perfectly fine "reorienting" to current orientation
+            // in reality, ios might be confused by transitionToViewController: shenanigans coupled with "nothing have changed actually"
+            // as an example: prior to ios12 that might result in status bar going "bad" (becoming transparent)
+            // NOTE: if we have switched from autorotation to fixed orientation, we must do the switch to pick new VC
+            if (_curOrientation != requestedOrient || autorotChanged)
+                [self orientInterface: requestedOrient];
+        }
+    }
+
+    UnityOrientationRequestWasCommitted();
+}
+
+- (void)orientInterface:(UIInterfaceOrientation)orient
+{
+    if (self.engineLoadState >= kUnityEngineLoadStateAppReady)
+        UnityFinishRendering();
+
+    [KeyboardDelegate StartReorientation];
+
+    [CATransaction begin];
+    {
+        UIInterfaceOrientation oldOrient = _curOrientation;
+        UIInterfaceOrientation newOrient = orient;
+
+        [self interfaceWillChangeOrientationTo: newOrient];
+        // TODO: we should handle _shouldUseDefaultViewControllerForFixedOrientations = YES
+        // TODO: though i am not sure how this should be done
+        // TODO: currently in normal orientation processing this will not be called when _shouldUseDefaultViewControllerForFixedOrientations is true
+        // TODO: but native plugins can still call it directly
+        [self transitionToViewController: [self createRootViewControllerForOrientation: newOrient]];
+        [self interfaceDidChangeOrientationFrom: oldOrient];
+
+#if !PLATFORM_VISIONOS
+    #pragma clang diagnostic push
+    #pragma clang diagnostic ignored "-Wdeprecated-declarations"
+        // this was deprecated in favor of [UIWindowScene setInterfaceOrientation:]
+        // this API works perfectly fine for now, so we use it until we rewrite/modernize trampoline to be Scene-based
+        [UIApplication sharedApplication].statusBarOrientation = orient;
+    #pragma clang diagnostic pop
+#endif
+    }
+    [CATransaction commit];
+
+    [KeyboardDelegate FinishReorientation];
+}
+
+- (void)orientUnity:(UIInterfaceOrientation)orient
+{
+    [self orientInterface: orient];
+}
+
+@end
+
+#endif
+
+UNITY_EXPORT extern "C" void UnityNotifyHideHomeButtonChange()
+{
+    [GetAppController() notifyHideHomeButtonChange];
+}
+
+UNITY_EXPORT extern "C" void UnityNotifyDeferSystemGesturesChange()
+{
+    [GetAppController() notifyDeferSystemGesturesChange];
+}

+ 5 - 0
unity_ios/Classes/UI/UnityScene.h

@@ -0,0 +1,5 @@
+#import <UIKit/UIKit.h>
+
+@interface UnityScene : UIResponder <UIWindowSceneDelegate>
+
+@end

+ 126 - 0
unity_ios/Classes/UI/UnityScene.mm

@@ -0,0 +1,126 @@
+#import "UnityScene.h"
+#import "UnityViewControllerBase.h"
+#include "UnityAppController.h"
+#include "Unity/UnityInterface.h"
+#import "PluginBase/AppDelegateListener.h"
+
+@implementation UnityScene {
+    UIOpenURLContext *_pendingURLContext;
+    NSUserActivity *_pendingUserActivity;
+}
+
+- (void)sceneDidBecomeActive:(UIScene *)scene {
+    ::printf("-> sceneDidBecomeActive()\n");
+    auto appController = GetAppController();
+    if ([appController respondsToSelector:@selector(applicationDidBecomeActive:)])
+    {
+        [appController applicationDidBecomeActive:UIApplication.sharedApplication];
+    }
+}
+
+- (void)sceneWillResignActive:(UIScene *)scene {
+    ::printf("-> sceneWillResignActive()\n");
+    auto appController = GetAppController();
+    if ([appController respondsToSelector:@selector(applicationWillResignActive:)])
+    {
+        [appController applicationWillResignActive:UIApplication.sharedApplication];
+    }
+}
+
+- (void)sceneWillEnterForeground:(UIScene *)scene {
+    ::printf("-> sceneWillEnterForeground()\n");
+    auto appController = GetAppController();
+    UIWindowScene *windowScene = (UIWindowScene *)scene;
+    [appController initUnityWithScene: windowScene];
+
+    if (_pendingURLContext != nil)
+        [self applyURL: _pendingURLContext.URL sourceApplication: _pendingURLContext.options.sourceApplication annotation: _pendingURLContext.options.annotation];
+    else if (_pendingUserActivity != nil)
+        [self applyURL: _pendingUserActivity.webpageURL sourceApplication: nil annotation: nil];
+
+    _pendingURLContext = nil;
+    _pendingUserActivity = nil;
+
+    if ([appController respondsToSelector:@selector(applicationWillEnterForeground:)])
+    {
+        [appController applicationWillEnterForeground:UIApplication.sharedApplication];
+    }
+}
+
+- (void)sceneDidEnterBackground:(UIScene *)scene {
+    ::printf("-> sceneDidEnterBackground()\n");
+    auto appController = GetAppController();
+    if ([appController respondsToSelector:@selector(applicationDidEnterBackground:)])
+    {
+        [appController applicationDidEnterBackground:UIApplication.sharedApplication];
+    }
+}
+
+- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
+    UIOpenURLContext *ctx = [self firstValidContextFromContexts: URLContexts];
+    if (ctx != nil)
+        [self applyURL: ctx.URL sourceApplication: ctx.options.sourceApplication annotation: ctx.options.annotation];
+}
+
+- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
+    _pendingURLContext = [self firstValidContextFromContexts: connectionOptions.URLContexts];
+    _pendingUserActivity = [self firstBrowsingActivityFromActivities: connectionOptions.userActivities];
+
+    // Set the URL immediately so Application.absoluteURL is available during first-scene Awake().
+    // Requires minimal engine init first (UnitySetAbsoluteURL accesses PlayerSettings).
+    // The kUnityOnOpenURL notification is deferred to sceneWillEnterForeground (after full init) for listeners/plugins.
+    NSURL *url = [self pendingURL];
+    if (url != nil)
+    {
+        [GetAppController() initUnityApplicationNoGraphics];
+        UnitySetAbsoluteURL(url.absoluteString.UTF8String);
+    }
+}
+
+- (void)scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivity {
+    if (userActivity != nil)
+        [self applyURL: userActivity.webpageURL sourceApplication: nil annotation: nil];
+}
+
+- (UIOpenURLContext *)firstValidContextFromContexts:(NSSet<UIOpenURLContext *> *)contexts {
+    for (UIOpenURLContext *ctx in contexts)
+    {
+        if (ctx.URL != nil && ctx.URL.absoluteString != nil)
+            return ctx;
+    }
+    return nil;
+}
+
+- (NSURL *)pendingURL {
+    if (_pendingURLContext != nil)
+        return _pendingURLContext.URL;
+    if (_pendingUserActivity != nil)
+        return _pendingUserActivity.webpageURL;
+    return nil;
+}
+
+- (NSUserActivity *)firstBrowsingActivityFromActivities:(NSSet<NSUserActivity *> *)activities {
+    for (NSUserActivity *activity in activities)
+    {
+        if ([activity.activityType isEqualToString: NSUserActivityTypeBrowsingWeb] && activity.webpageURL != nil && activity.webpageURL.absoluteString != nil)
+            return activity;
+    }
+    return nil;
+}
+
+- (void)applyURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
+    if (url == nil || url.absoluteString == nil)
+        return;
+
+    UnitySetAbsoluteURL(url.absoluteString.UTF8String);
+
+    NSMutableDictionary<NSString*, id>* notifData = [NSMutableDictionary dictionaryWithCapacity: 3];
+    notifData[@"url"] = url;
+    if (sourceApplication != nil)
+        notifData[@"sourceApplication"] = sourceApplication;
+    if (annotation != nil)
+        notifData[@"annotation"] = annotation;
+
+    AppController_SendNotificationWithArg(kUnityOnOpenURL, notifData);
+}
+@end

+ 268 - 0
unity_ios/Classes/UI/UnityView+Keyboard.mm

@@ -0,0 +1,268 @@
+#import "UnityView.h"
+#include "UI/Keyboard.h"
+#include <sys/time.h>
+#include <map>
+#include <vector>
+
+static NSArray* keyboardCommands = nil;
+
+extern "C" int UnityGetAppleTVRemoteAllowExitToMenu();
+extern "C" void UnitySetAppleTVRemoteAllowExitToMenu(int val);
+
+@implementation UnityView (Keyboard)
+
+// Keyboard shortcuts don't provide events for key up
+// Keyboard shortcut callbacks are called with 0.4 (first time) and 0.1 (following times) seconds interval while pressing the key
+// Below we implement key expiration mechanism where key up event is generated if shortcut callback
+// is not called for specific key for more than <kKeyTimeoutInSeconds>
+
+typedef std::map<int, double> KeyMap;
+static const double kKeyTimeoutInSeconds = 0.5;
+
+static KeyMap& GetKeyMap()
+{
+    static KeyMap s_Map;
+    return s_Map;
+}
+
+static double GetTimeInSeconds()
+{
+    timeval now;
+    gettimeofday(&now, NULL);
+
+    return now.tv_sec + now.tv_usec / 1000000.0;
+}
+
+- (void)createKeyboard
+{
+    // only English keyboard layout is supported
+    NSString* baseLayout = @"1234567890-=qwertyuiop[]asdfghjkl;'\\`zxcvbnm,./!@#$%^&*()_+{}:\"|<>?~ \t\r\b\\";
+    NSString* numpadLayout = @"1234567890-=*+/.\r";
+    NSString* upperCaseLetters = @"QWERTYUIOPASDFGHJKLZXCVBNM";
+    NSString* shortcutCharacters = @"axcv";
+
+    size_t sizeOfKeyboardCommands = baseLayout.length + numpadLayout.length + upperCaseLetters.length + 11;
+    NSMutableArray* commands = [NSMutableArray arrayWithCapacity: sizeOfKeyboardCommands];
+
+    void (^addKey)(NSString *keyName, UIKeyModifierFlags modifierFlags) = ^(NSString *keyName, UIKeyModifierFlags modifierFlags)
+    {
+        UIKeyCommand* command = [UIKeyCommand keyCommandWithInput: keyName modifierFlags: modifierFlags action: @selector(handleCommand:)];
+        command.wantsPriorityOverSystemBehavior = YES;
+        [commands addObject: command];
+    };
+
+    for (NSInteger i = 0; i < baseLayout.length; ++i)
+    {
+        NSString* input = [baseLayout substringWithRange: NSMakeRange(i, 1)];
+        addKey(input, kNilOptions);
+    }
+    for (NSInteger i = 0; i < shortcutCharacters.length; ++i)
+    {
+        NSString* input = [shortcutCharacters substringWithRange: NSMakeRange(i, 1)];
+        [commands addObject: [UIKeyCommand keyCommandWithInput: input modifierFlags: UIKeyModifierCommand action: @selector(handleCommand:)]];
+    }
+    for (NSInteger i = 0; i < numpadLayout.length; ++i)
+    {
+        NSString* input = [numpadLayout substringWithRange: NSMakeRange(i, 1)];
+        addKey(input, UIKeyModifierNumericPad);
+    }
+    for (NSInteger i = 0; i < upperCaseLetters.length; ++i)
+    {
+        NSString* input = [upperCaseLetters substringWithRange: NSMakeRange(i, 1)];
+        addKey(input, UIKeyModifierShift);
+    }
+
+    // pageUp, pageDown
+    addKey(UIKeyInputPageUp, kNilOptions);
+    addKey(UIKeyInputPageDown, kNilOptions);
+
+    // up, down, left, right, esc
+    addKey(UIKeyInputUpArrow, kNilOptions);
+    addKey(UIKeyInputDownArrow, kNilOptions);
+    addKey(UIKeyInputLeftArrow, kNilOptions);
+    addKey(UIKeyInputRightArrow, kNilOptions);
+    addKey(UIKeyInputEscape, kNilOptions);
+
+    // caps Lock, shift, control, option, command
+    addKey(@"", UIKeyModifierAlphaShift);
+    addKey(@"", UIKeyModifierShift);
+    addKey(@"", UIKeyModifierControl);
+    addKey(@"", UIKeyModifierAlternate);
+    addKey(@"", UIKeyModifierCommand);
+
+    keyboardCommands = commands.copy;
+}
+
+- (NSArray*)keyCommands
+{
+    //keyCommands take control of buttons over UITextView, that's why need to return nil if text input field is active or we have an external keyboard attached AND a first responder
+    if ([[KeyboardDelegate Instance] status] == Visible || ([[KeyboardDelegate Instance] hasExternalKeyboard] && [self hasFirstResponderInHeirachy: UnityGetGLView()]))
+        return nil;
+
+    if (keyboardCommands == nil)
+    {
+        [self createKeyboard];
+    }
+    return keyboardCommands;
+}
+
+- (bool)hasFirstResponderInHeirachy:(UIView*)view
+{
+    if (view.isFirstResponder)
+        return true;
+
+    for (UIView* subview in view.subviews)
+    {
+        if ([self hasFirstResponderInHeirachy: subview])
+            return true;
+    }
+
+    return false;
+}
+
+- (bool)isValidCodeForButton:(int)code
+{
+    return (code > 0 && code < 128);
+}
+
+- (void)handleCommand:(UIKeyCommand *)command
+{
+    NSString* input = command.input;
+    UIKeyModifierFlags modifierFlags = command.modifierFlags;
+
+    char inputChar = ([input length] == 1) ? [input characterAtIndex: 0] : 0;
+    int code = (int)inputChar; // ASCII code
+
+    if (![self isValidCodeForButton: code])
+    {
+        code = 0;
+    }
+
+    if ((modifierFlags & UIKeyModifierAlphaShift) != 0)
+        code = UnityStringToKey("caps lock");
+    if ((modifierFlags & UIKeyModifierShift) != 0)
+        code = UnityStringToKey("left shift");
+    if ((modifierFlags & UIKeyModifierControl) != 0)
+        code = UnityStringToKey("left ctrl");
+    if ((modifierFlags & UIKeyModifierAlternate) != 0)
+        code = UnityStringToKey("left alt");
+    if ((modifierFlags & UIKeyModifierCommand) != 0)
+        code = UnityStringToKey("left cmd");
+
+    if ((modifierFlags & UIKeyModifierNumericPad) != 0)
+    {
+        switch (inputChar)
+        {
+            case '0':
+                code = UnityStringToKey("[0]");
+                break;
+            case '1':
+                code = UnityStringToKey("[1]");
+                break;
+            case '2':
+                code = UnityStringToKey("[2]");
+                break;
+            case '3':
+                code = UnityStringToKey("[3]");
+                break;
+            case '4':
+                code = UnityStringToKey("[4]");
+                break;
+            case '5':
+                code = UnityStringToKey("[5]");
+                break;
+            case '6':
+                code = UnityStringToKey("[6]");
+                break;
+            case '7':
+                code = UnityStringToKey("[7]");
+                break;
+            case '8':
+                code = UnityStringToKey("[8]");
+                break;
+            case '9':
+                code = UnityStringToKey("[9]");
+                break;
+            case '-':
+                code = UnityStringToKey("[-]");
+                break;
+            case '=':
+                code = UnityStringToKey("equals");
+                break;
+            case '*':
+                code = UnityStringToKey("[*]");
+                break;
+            case '+':
+                code = UnityStringToKey("[+]");
+                break;
+            case '/':
+                code = UnityStringToKey("[/]");
+                break;
+            case '.':
+                code = UnityStringToKey("[.]");
+                break;
+            case '\r':
+                code = UnityStringToKey("enter");
+                break;
+            default:
+                break;
+        }
+    }
+
+    if (input == UIKeyInputUpArrow)
+        code = UnityStringToKey("up");
+    else if (input == UIKeyInputDownArrow)
+        code = UnityStringToKey("down");
+    else if (input == UIKeyInputRightArrow)
+        code = UnityStringToKey("right");
+    else if (input == UIKeyInputLeftArrow)
+        code = UnityStringToKey("left");
+    else if (input == UIKeyInputEscape)
+        code = UnityStringToKey("escape");
+    else if ([input isEqualToString: @"UIKeyInputPageUp"])
+        code = UnityStringToKey("page up");
+    else if ([input isEqualToString: @"UIKeyInputPageDown"])
+        code = UnityStringToKey("page down");
+
+    UnitySendKeyboardCommand(command, code);
+
+    KeyMap::iterator item = GetKeyMap().find(code);
+    if (item == GetKeyMap().end())
+    {
+        // New key is down, register it and its time
+        UnitySetKeyboardKeyState(code, true);
+        GetKeyMap()[code] = GetTimeInSeconds();
+    }
+    else
+    {
+        // Still holding the key, update its time
+        item->second = GetTimeInSeconds();
+    }
+}
+
+- (void)processKeyboard
+{
+    KeyMap& map = GetKeyMap();
+    if (map.size() == 0)
+        return;
+    std::vector<int> keysToUnpress;
+    double nowTime = GetTimeInSeconds();
+    for (KeyMap::iterator item = map.begin();
+         item != map.end();
+         item++)
+    {
+        // Key has expired, register it for key up event
+        if (nowTime - item->second > kKeyTimeoutInSeconds)
+            keysToUnpress.push_back(item->first);
+    }
+
+    for (std::vector<int>::iterator item = keysToUnpress.begin();
+         item != keysToUnpress.end();
+         item++)
+    {
+        map.erase(*item);
+        UnitySetKeyboardKeyState(*item, false);
+    }
+}
+
+@end

+ 15 - 0
unity_ios/Classes/UI/UnityView+iOS.h

@@ -0,0 +1,15 @@
+#pragma once
+
+@interface UnityView (iOS)
+
+// will simply update content orientation (it might be tweaked in layoutSubviews, due to disagreement between unity and view controller)
+- (void)willRotateToOrientation:(UIInterfaceOrientation)toOrientation fromOrientation:(UIInterfaceOrientation)fromOrientation;
+// will recreate gles backing if needed and repaint once to make sure we dont have black frame creeping in
+- (void)didRotate;
+
+- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event;
+- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event;
+- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event;
+- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event;
+
+@end

+ 137 - 0
unity_ios/Classes/UI/UnityView+iOS.mm

@@ -0,0 +1,137 @@
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+
+#import "UnityView.h"
+#import "UnityAppController+Rendering.h"
+#include "OrientationSupport.h"
+#import <GameController/GameController.h>
+
+@interface UnityView ()
+@property (nonatomic, readwrite) ScreenOrientation contentOrientation;
+@end
+
+// indirect mouse input on iOS: GCMouse.scroll gives real wheel deltas per notch (a pan recognizer
+// only gives an uneven pan), and UIHoverGestureRecognizer gives the cursor position uGUI routes on.
+@implementation UnityView (iOSScrollWheel)
+
+- (void)setupIndirectMouseInput
+{
+    // wheel deltas: attach to the current mouse and any that becomes current
+    [[NSNotificationCenter defaultCenter] addObserver: self
+                                             selector: @selector(mouseDidBecomeCurrent:)
+                                                 name: GCMouseDidBecomeCurrentNotification
+                                               object: nil];
+    if (GCMouse.current != nil)
+        [self attachScrollHandlerToMouse: GCMouse.current];
+
+    // cursor position for routing
+    UIHoverGestureRecognizer* hover = [[UIHoverGestureRecognizer alloc] initWithTarget: self action: @selector(handleHover:)];
+    [self addGestureRecognizer: hover];
+}
+
+// both registrations outlive the view (observer is unretained, handler lives on the shared GCMouse),
+// so clear them or a stale view could call a torn down player in UaaL
+- (void)teardownIndirectMouseInput
+{
+    [[NSNotificationCenter defaultCenter] removeObserver: self
+                                                    name: GCMouseDidBecomeCurrentNotification
+                                                  object: nil];
+    // the mouse is shared: after a UaaL reload a newer view may own the slot, so only clear ours
+    for (GCMouse* mouse in GCMouse.mice)
+    {
+        if (mouse.mouseInput.scroll.valueChangedHandler == self.indirectScrollHandler)
+            mouse.mouseInput.scroll.valueChangedHandler = nil;
+    }
+    self.indirectScrollHandler = nil;
+}
+
+- (void)mouseDidBecomeCurrent:(NSNotification*)note
+{
+    GCMouse* mouse = note.object;
+    if (mouse != nil)
+        [self attachScrollHandlerToMouse: mouse];
+}
+
+- (void)attachScrollHandlerToMouse:(GCMouse*)mouse
+{
+    // one block per view, reused across mice so teardown can match ours by pointer. dispatch to the
+    // main thread since GCMouse may fire on any queue. kScrollScale is a placeholder until measured.
+    if (self.indirectScrollHandler == nil)
+    {
+        __weak UnityView* weakSelf = self;
+        self.indirectScrollHandler = ^(GCControllerDirectionPad* dpad, float xValue, float yValue) {
+            const float kScrollScale = 1.0f;
+            const float dx = xValue * kScrollScale;
+            const float dy = yValue * kScrollScale;
+            dispatch_async(dispatch_get_main_queue(), ^{
+                // only forward while the pointer is over this view, else a scroll over a sibling
+                // view would still drive Unity in UaaL
+                UnityView* strongSelf = weakSelf;
+                if (strongSelf == nil || !strongSelf.indirectPointerInside)
+                    return;
+                UnitySendScrollWheel(dx, dy);
+            });
+        };
+    }
+    mouse.mouseInput.scroll.valueChangedHandler = self.indirectScrollHandler;
+}
+
+- (void)handleHover:(UIHoverGestureRecognizer*)recognizer
+{
+    // began/changed = inside, ended/cancelled/failed = left; the scroll handler gates on this
+    self.indirectPointerInside = recognizer.state == UIGestureRecognizerStateBegan ||
+        recognizer.state == UIGestureRecognizerStateChanged;
+    if (!self.indirectPointerInside)
+        return;
+
+    // pass the raw UIKit point; UnitySendMousePosition applies the touch path's transform so it
+    // matches ScreenManager extents
+    CGPoint location = [recognizer locationInView: self];
+    UnitySendMousePosition((float)location.x, (float)location.y);
+}
+
+@end
+
+@implementation UnityView (iOS)
+- (void)willRotateToOrientation:(UIInterfaceOrientation)toOrientation fromOrientation:(UIInterfaceOrientation)fromOrientation;
+{
+    // to support the case of interface and unity content orientation being different
+    // we will cheat a bit:
+    // we will calculate transform between interface orientations and apply it to unity view orientation
+    // you can still tweak unity view as you see fit in AppController, but this is what you want in 99% of cases
+
+    ScreenOrientation to    = ConvertToUnityScreenOrientation(toOrientation);
+    ScreenOrientation from  = ConvertToUnityScreenOrientation(fromOrientation);
+
+    if (fromOrientation == UIInterfaceOrientationUnknown)
+        _curOrientation = to;
+    else
+        _curOrientation = OrientationAfterTransform(_curOrientation, TransformBetweenOrientations(from, to));
+
+    _viewIsRotating = YES;
+}
+
+- (void)didRotate
+{
+    // if we are using metal display link we will delay actual unity-side resizing to happen before rendering
+    if (_shouldRecreateView && !GetAppController().unityUsesMetalDisplayLink)
+    {
+        // recreateRenderingSurface expects layer's drawableSize to be set to proper value
+        //   and updateLayerDrawableSizeFromBounds does exactly that
+        // note that normally we go through recreateRenderingSurfaceIfNeeded
+        //   which does call updateLayerDrawableSizeFromBounds
+        [self updateLayerDrawableSizeFromBounds];
+        [self updateUnityBackbufferSize];
+        [self recreateRenderingSurface];
+    }
+
+    _viewIsRotating = NO;
+}
+
+- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event      { UnitySendTouchesBegin(touches, event); }
+- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event      { UnitySendTouchesEnded(touches, event); }
+- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event  { UnitySendTouchesCancelled(touches, event); }
+- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event      { UnitySendTouchesMoved(touches, event); }
+
+@end
+
+#endif // PLATFORM_IOS || PLATFORM_VISIONOS

+ 15 - 0
unity_ios/Classes/UI/UnityView+tvOS.h

@@ -0,0 +1,15 @@
+#pragma once
+
+@interface UnityView (tvOS)
+
+- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event;
+- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event;
+- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event;
+- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event;
+
+#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
+- (void)pressesBegan:(NSSet<UIPress*>*)presses withEvent:(UIEvent*)event;
+- (void)pressesEnded:(NSSet<UIPress*>*)presses withEvent:(UIEvent*)event;
+#endif
+
+@end

+ 66 - 0
unity_ios/Classes/UI/UnityView+tvOS.mm

@@ -0,0 +1,66 @@
+#if PLATFORM_TVOS
+
+#import "UnityView.h"
+#include "iphone_Sensors.h"
+
+@implementation UnityView (tvOS)
+
+- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
+{
+#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
+    ReportSimulatedRemoteTouchesBegan(self, touches);
+#endif
+
+    if (UnityGetAppleTVRemoteTouchesEnabled())
+        UnitySendTouchesBegin(touches, event);
+}
+
+- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
+{
+#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
+    ReportSimulatedRemoteTouchesEnded(self, touches);
+#endif
+
+    if (UnityGetAppleTVRemoteTouchesEnabled())
+        UnitySendTouchesEnded(touches, event);
+}
+
+- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event
+{
+#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
+    ReportSimulatedRemoteTouchesEnded(self, touches);
+#endif
+
+    if (UnityGetAppleTVRemoteTouchesEnabled())
+        UnitySendTouchesCancelled(touches, event);
+}
+
+- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
+{
+#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
+    ReportSimulatedRemoteTouchesMoved(self, touches);
+#endif
+
+    if (UnityGetAppleTVRemoteTouchesEnabled())
+        UnitySendTouchesMoved(touches, event);
+}
+
+#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
+- (void)pressesBegan:(NSSet<UIPress*>*)presses withEvent:(UIEvent*)event
+{
+    for (UIPress *press in presses)
+        ReportSimulatedRemoteButtonPress(press.type);
+}
+
+- (void)pressesEnded:(NSSet<UIPress*>*)presses withEvent:(UIEvent*)event
+{
+    for (UIPress *press in presses)
+        ReportSimulatedRemoteButtonRelease(press.type);
+}
+
+#endif
+
+@end
+
+
+#endif // PLATFORM_TVOS

+ 71 - 0
unity_ios/Classes/UI/UnityView.h

@@ -0,0 +1,71 @@
+#pragma once
+
+@interface UnityRenderingView : UIView
+{
+}
++ (void)InitializeForAPI:(UnityRenderingAPI)api;
+@end
+
+@interface UnityView : UnityRenderingView
+{
+    @private ScreenOrientation _curOrientation;
+    @private BOOL _shouldRecreateView;
+    @private BOOL _viewIsRotating;
+}
+
+// we take scale factor into account because gl backbuffer size depends on it
+- (id)initWithFrame:(CGRect)frame scaleFactor:(CGFloat)scale;
+- (id)initWithFrame:(CGRect)frame;
+- (id)initFromMainScreen;
+- (void)resumeRendering;
+
+// in here we will go through subviews and call onUnityUpdateViewLayout selector (if present)
+// that allows to handle simple overlay child view layout without doing view controller magic
+- (void)layoutSubviews;
+
+- (void)recreateRenderingSurfaceIfNeeded;
+- (void)recreateRenderingSurface;
+
+// will match script-side Screen.orientation
+@property (nonatomic, readonly) ScreenOrientation contentOrientation;
+@property BOOL skipRendering;
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+// state for the GCMouse indirect mouse path (see UnityView+iOS.mm)
+// true while the pointer is over this view; gates whether we forward scroll
+@property (nonatomic, assign) BOOL indirectPointerInside;
+// the scroll block we installed on GCMouse; teardown clears only this one
+@property (nonatomic, copy) id indirectScrollHandler;
+#endif
+
+@end
+
+@interface UnityView (Deprecated)
+- (void)recreateGLESSurfaceIfNeeded __deprecated_msg("use recreateRenderingSurfaceIfNeeded instead.");
+- (void)recreateGLESSurface __deprecated_msg("use recreateRenderingSurface instead.");
+@end
+
+@interface UnityView (Keyboard)
+- (void)processKeyboard;
+@end
+
+@interface UnityView (UnityAppController)
+- (void)boundsUpdated __deprecated_msg("use updateUnityBackbufferSize instead.");
+// if we know that unity view bounds have changed but we need to update unity-side size/orientation immediately
+- (void)updateUnityBackbufferSize;
+// update layer's drawableSize from bounds size: needed when bounds are changed (either by iOS or by us)
+- (void)updateLayerDrawableSizeFromBounds;
+@end
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+    #include "UnityView+iOS.h"
+#elif PLATFORM_TVOS
+    #include "UnityView+tvOS.h"
+#endif
+
+void ReportSafeAreaChangeForView(UIView* view);
+
+// Computes safe area for a view in Unity coordinate system (origin of the view
+// is bottom-left, as compared to standard top-left)
+CGRect ComputeSafeArea(UIView* view);
+CGSize GetCutoutToScreenRatio();

+ 437 - 0
unity_ios/Classes/UI/UnityView.mm

@@ -0,0 +1,437 @@
+#include "UnityView.h"
+#include "UnityAppController.h"
+#include "UnityAppController+Rendering.h"
+#include "OrientationSupport.h"
+#include "Unity/DisplayManager.h"
+#include "Unity/ObjCRuntime.h"
+#include "UI/Keyboard.h"
+
+#import <Metal/Metal.h>
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+@interface UnityView (iOSScrollWheel)
+- (void)setupIndirectMouseInput;
+- (void)teardownIndirectMouseInput;
+@end
+#endif
+
+@implementation UnityView
+{
+    CGSize _surfaceSize;
+}
+
+@synthesize contentOrientation  = _curOrientation;
+
+// we need to support both CADisplayLink and CAMetalDisplayLink
+// alas they have a bit of an "opposite" approach to backbuffer (drawable) management so we have several complications
+// - for CADisplayLink the callback is more or less just "oh it is time: you asked to be poked every N ms"
+//     we will query drawable from the view's layer (we delay this as much as possible to not introduce sync point)
+//   so we should NOT tweak drawable size at "random" times
+//   our approach was:
+//     whenever iOS is telling us that view should be resized, we poke unity native side
+//     * this is a bit more complicated: we were doing so only in layoutSubviews and some corner cases with orientation change
+//     and on the next displaylink callback we recreate the "connection" between native side and trampoline (using "new" drawable extents)
+//
+// - for CAMetalDisplayLink the callback gives us a ready CAMetalDrawable
+//     that is all the syncing is handled by iOS (this is very good) and it now acts like a compositor of sorts
+//   there are several caveats though (read above: we have a "unity approach" already in place)
+//   first of all: we can never "skip" rendering (before it was fine, simply because if we don't query drawable, the contents are preserved by iOS)
+//   second: we should update drawable size whenever iOS is telling us that the view bounds are tweaked
+//     recall that we get ready-made drawable in the callback - at this point we can not tweak anything regarding drawable
+//     and yet we should delay updating unity on "backbuffer" change, since it might have drawable of the old size currently
+//
+// So our plan is:
+// - override "change bounds" methods to track drawable size (with _surfaceSize)
+//     note that we will update drawableSize immediately when using CAMetalDisplayLink, but not when using CADisplayLink
+// - on displaylink callback as before we will update connection to unity render surfaces
+//     when using CADisplayLink we will also update drawableSize here before poking unity
+//
+
+// this will do update drawable size to agree with bounds
+// CAMetalDisplayLink: will be called from onUpdateDrawableSize, called in all "something view related changed" callbacks
+// CADisplayLink: we will call it from the display link callback, to not touch drawableSize while we are potentially rendering to drawable
+//   using old extents
+- (void)updateLayerDrawableSizeFromBounds
+{
+    if (![self.layer isKindOfClass: [CAMetalLayer class]])
+    {
+        // UnityView either has CAMetalLayer backing, when running on Metal, or CALayer, when running in 'nographics' mode
+        return;
+    }
+
+    CAMetalLayer* metalLayer = (CAMetalLayer*)self.layer;
+    @synchronized(metalLayer)
+    {
+        const CGSize size  = self.bounds.size;
+        const float  scale = self.contentScaleFactor;
+        const CGSize systemRenderSize = CGSizeMake(::roundf(size.width * scale), ::roundf(size.height * scale));
+
+        if (systemRenderSize.width <= 0 || systemRenderSize.height <= 0)
+        {
+            _shouldRecreateView = NO;
+        }
+        else if (systemRenderSize.width == metalLayer.drawableSize.width && systemRenderSize.height == metalLayer.drawableSize.height)
+        {
+            _shouldRecreateView = NO;
+        }
+        else
+        {
+            metalLayer.drawableSize = systemRenderSize;
+            _shouldRecreateView = YES;
+        }
+    }
+}
+
+- (void)onUpdateDrawableSize
+{
+    // when using metal display link, update drawable size immediately so that we are getting callback with correct size
+    // when using old display link we will do this on frame start along with updating proxy textures (so that they all agree)
+    if(GetAppController().unityUsesMetalDisplayLink)
+        [self updateLayerDrawableSizeFromBounds];
+}
+
+// this reports "backbuffer" update to unity: this should be done right before player loop
+- (void)updateUnityBackbufferSize
+{
+    const CGSize size  = self.bounds.size;
+
+    // this is needed for CADisplayLink handling since in this case we do not track view extents changes
+    if (size.width != _surfaceSize.width || size.height != _surfaceSize.height)
+        _shouldRecreateView = YES;
+    _surfaceSize = size;
+
+    const float  scale = self.contentScaleFactor;
+    const CGSize systemRenderSize = CGSizeMake(::roundf(size.width * scale), ::roundf(size.height * scale));
+
+    _curOrientation = (ScreenOrientation)UnityReportResizeView((unsigned)systemRenderSize.width, (unsigned)systemRenderSize.height, _curOrientation);
+    ReportSafeAreaChangeForView(self);
+}
+
+// this was part of public interface, so keep it around just in case
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-implementations"
+- (void)boundsUpdated
+{
+    [self updateUnityBackbufferSize];
+}
+#pragma clang diagnostic pop
+
+- (void)initImpl:(CGRect)frame scaleFactor:(CGFloat)scale
+{
+#if !PLATFORM_TVOS
+    self.multipleTouchEnabled   = YES;
+    self.exclusiveTouch         = YES;
+#endif
+    self.contentScaleFactor     = scale;
+    self.skipRendering = NO;
+
+#if PLATFORM_TVOS
+    _curOrientation = UNITY_TVOS_ORIENTATION;
+#elif PLATFORM_VISIONOS
+    _curOrientation = UNITY_VISIONOS_ORIENTATION;
+#endif
+
+    [self updateUnityBackbufferSize];
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+    [self setupIndirectMouseInput];
+#endif
+}
+
+- (id)initWithFrame:(CGRect)frame scaleFactor:(CGFloat)scale;
+{
+    if ((self = [super initWithFrame: frame]))
+        [self initImpl: frame scaleFactor: scale];
+    return self;
+}
+- (id)initWithFrame:(CGRect)frame
+{
+    if ((self = [super initWithFrame: frame]))
+        [self initImpl: frame scaleFactor: 1.0f];
+    return self;
+}
+
+- (id)initFromMainScreen
+{
+#if !PLATFORM_VISIONOS
+    CGRect  frame   = [UIScreen mainScreen].bounds;
+    CGFloat scale   = UnityScreenScaleFactor([UIScreen mainScreen]);
+#else
+    CGRect  frame   = CGRectMake(0.0f, 0.0f, 1920.0f, 1080.0f);
+    CGFloat scale   = 1.0f;
+#endif
+    if ((self = [super initWithFrame: frame]))
+        [self initImpl: frame scaleFactor: scale];
+    return self;
+}
+
+- (void)dealloc
+{
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+    [self teardownIndirectMouseInput];
+#endif
+}
+
+- (void)resumeRendering
+{
+    self.skipRendering = NO;
+}
+
+- (void)recreateRenderingSurfaceIfNeeded
+{
+    // when using metal display link, update drawable size immediately so that we are getting callback with correct size
+    // when using old display link we will do this on frame start along with updating proxy textures (so that they all agree)
+    if(!GetAppController().unityUsesMetalDisplayLink)
+        [self updateLayerDrawableSizeFromBounds];
+
+    [self updateUnityBackbufferSize];
+
+    unsigned requestedW, requestedH; UnityGetRenderingResolution(&requestedW, &requestedH);
+    int requestedMSAA = UnityGetDesiredMSAASampleCount(1);
+    int requestedSRGB = UnityGetSRGBRequested();
+    int requestedWideColor = UnityGetWideColorRequested();
+    int requestedHDR = UnityGetHDRModeRequested();
+    int requestedMemorylessDepth = UnityMetalMemorylessDepth();
+
+    UnityDisplaySurfaceBase* surf = GetMainDisplaySurface();
+
+    if (_shouldRecreateView == YES
+        ||  surf->targetW != requestedW || surf->targetH != requestedH
+        ||  surf->disableDepthAndStencil != UnityDisableDepthAndStencilBuffers()
+        ||  surf->msaaSamples != requestedMSAA
+        ||  surf->srgb != requestedSRGB
+        ||  surf->wideColor != requestedWideColor
+        ||  surf->hdr != requestedHDR
+        ||  surf->memorylessDepth != requestedMemorylessDepth
+    )
+    {
+        [self recreateRenderingSurface];
+    }
+}
+
+- (void)recreateRenderingSurface
+{
+    auto controller = GetAppController();
+    if (controller.engineLoadState >= kUnityEngineLoadStateRenderingInitialized)
+    {
+        unsigned requestedW, requestedH;
+        UnityGetRenderingResolution(&requestedW, &requestedH);
+
+        RenderingSurfaceParams params =
+        {
+            .msaaSampleCount        = UnityGetDesiredMSAASampleCount(1),
+            .renderW                = (int)requestedW,
+            .renderH                = (int)requestedH,
+            .srgb                   = UnityGetSRGBRequested(),
+            .wideColor              = UnityGetWideColorRequested(),
+            .hdr                    = UnityGetHDRModeRequested(),
+            .metalFramebufferOnly   = UnityMetalFramebufferOnly(),
+            .metalMemorylessDepth   = UnityMetalMemorylessDepth(),
+            .disableDepthAndStencil = UnityDisableDepthAndStencilBuffers(),
+        };
+
+        APP_CONTROLLER_RENDER_PLUGIN_METHOD_ARG(onBeforeMainDisplaySurfaceRecreate, &params);
+        [GetMainDisplay() recreateSurface: params];
+        APP_CONTROLLER_RENDER_PLUGIN_METHOD(onAfterMainDisplaySurfaceRecreate);
+
+        // TODO: it should be done better
+        if (   controller.engineLoadState >= kUnityEngineLoadStateAppReady && !GetAppController().unityUsesMetalDisplayLink
+            && (_viewIsRotating || UnityIsPaused()))
+        {
+            UnityDisplayLinkCallback(GetAppController().unityDisplayLink.timestamp);
+            UnityRepaint();
+
+            id<MTLCommandBuffer> cb = [UnityGetMetalCommandQueue() commandBuffer];
+            cb.label = @"Present";
+            [[DisplayManager Instance] presentWith:cb];
+            [cb commit];
+        }
+    }
+
+    _shouldRecreateView = NO;
+}
+
+- (void)safeAreaInsetsDidChange
+{
+    ReportSafeAreaChangeForView(self);
+}
+
+- (void)layoutSubviews
+{
+    [super layoutSubviews];
+    [self onUpdateDrawableSize];
+    [[KeyboardDelegate Instance] layoutSubviews];
+
+    for (UIView* subView in self.subviews)
+    {
+        if ([subView respondsToSelector: @selector(onUnityUpdateViewLayout)])
+            [subView performSelector: @selector(onUnityUpdateViewLayout)];
+    }
+}
+
+- (void)setContentScaleFactor:(CGFloat)contentScaleFactor
+{
+    [super setContentScaleFactor:contentScaleFactor];
+    [self onUpdateDrawableSize];
+}
+
+- (void)setFrame:(CGRect)frame
+{
+    [super setFrame:frame];
+    [self onUpdateDrawableSize];
+}
+
+- (void)setBounds:(CGRect)bounds
+{
+    [super setBounds:bounds];
+    [self onUpdateDrawableSize];
+}
+
+
+@end
+
+@implementation UnityView (Deprecated)
+- (void)recreateGLESSurfaceIfNeeded { [self recreateRenderingSurfaceIfNeeded]; }
+- (void)recreateGLESSurface         { [self recreateRenderingSurface]; }
+@end
+
+static Class UnityRenderingView_LayerClassMTL(id self_, SEL _cmd)
+{
+    return NSClassFromString(@"CAMetalLayer");
+}
+
+static Class UnityRenderingView_LayerClassNULL(id self_, SEL _cmd)
+{
+    return NSClassFromString(@"CALayer");
+}
+
+@implementation UnityRenderingView
++ (Class)layerClass
+{
+    return nil;
+}
+
++ (void)InitializeForAPI:(UnityRenderingAPI)api
+{
+    IMP layerClassImpl = api == apiMetal ? (IMP)UnityRenderingView_LayerClassMTL : (IMP)UnityRenderingView_LayerClassNULL;
+    class_replaceMethod(object_getClass([UnityRenderingView class]), @selector(layerClass), layerClassImpl, UIView_LayerClass_Enc);
+}
+
+@end
+
+void ReportSafeAreaChangeForView(UIView* view)
+{
+    CGRect safeArea = ComputeSafeArea(view);
+    UnityReportSafeAreaChange(safeArea.origin.x, safeArea.origin.y,
+        safeArea.size.width, safeArea.size.height);
+
+#if !PLATFORM_VISIONOS
+    if (UnityDeviceHasCutout())
+    {
+        CGSize cutoutSizeRatio = GetCutoutToScreenRatio();
+
+        if (!CGSizeEqualToSize(CGSizeZero, cutoutSizeRatio))
+        {
+            const float w = ([UIScreen mainScreen].nativeBounds.size.width * cutoutSizeRatio.width);
+            const float h = ([UIScreen mainScreen].nativeBounds.size.height * cutoutSizeRatio.height);
+
+            // Apple's cutouts are currently centred on the horizontal, and stuck to the top of the vertical, hence this positioning.
+            const float x = (([UIScreen mainScreen].nativeBounds.size.width - w) / 2);
+            const float y = ([UIScreen mainScreen].nativeBounds.size.height - h);
+            UnityReportDisplayCutouts(&x, &y, &w, &h, 1);
+            return;
+        }
+    }
+#endif
+
+    UnityReportDisplayCutouts(nullptr, nullptr, nullptr, nullptr, 0);
+}
+
+CGRect ComputeSafeArea(UIView* view)
+{
+    CGSize screenSize = view.bounds.size;
+    CGRect screenRect = CGRectMake(0, 0, screenSize.width, screenSize.height);
+
+    UIEdgeInsets insets = [view safeAreaInsets];
+    float insetLeft = insets.left, insetBottom = insets.bottom, insetTop = insets.top;
+    float insetHeight = insetBottom + insetTop;
+    float insetWidth = insetLeft + insets.right;
+
+    // Unity uses bottom left as the origin
+    screenRect = CGRectOffset(screenRect, insetLeft, insetBottom);
+    screenRect.size.width -= insetWidth;
+    screenRect.size.height -= insetHeight;
+
+    const float scale = view.contentScaleFactor;
+
+    // Truncate safe area size because in some cases (for example when Display zoom is turned on)
+    // it might become larger than Screen.width/height which are returned as ints.
+    screenRect.origin.x = (unsigned)::roundf(screenRect.origin.x * scale);
+    screenRect.origin.y = (unsigned)::roundf(screenRect.origin.y * scale);
+    screenRect.size.width = (unsigned)::roundf(screenRect.size.width * scale);
+    screenRect.size.height = (unsigned)::roundf(screenRect.size.height * scale);
+
+    return screenRect;
+}
+
+// Apple does not provide the cutout width and height in points/pixels. They *do* however list the
+// size of the cutout and screen in mm for accessory makers. We can use this information to calculate the percentage of the screen is cutout.
+// This information can be found here - https://developer.apple.com/accessories/Accessory-Design-Guidelines.pdf
+CGSize GetCutoutToScreenRatio()
+{
+    switch (UnityDeviceGeneration())
+    {
+        case deviceiPhone14:
+        case deviceiPhone16e:
+        case deviceiPhone17e:
+            return CGSizeMake(0.415, 0.04);
+        case deviceiPhone14Plus:
+            return CGSizeMake(0.377, 0.036);
+        case deviceiPhone14Pro:
+        case deviceiPhone15:
+        case deviceiPhone15Pro:
+        case deviceiPhone16:
+        case deviceiPhone16Pro:
+        case deviceiPhone17:
+        case deviceiPhone17Pro:
+            return CGSizeMake(0.318, 0.057);
+        case deviceiPhone14ProMax:
+        case deviceiPhone15ProMax:
+        case deviceiPhone15Plus:
+        case deviceiPhone16Plus:
+        case deviceiPhone16ProMax:
+        case deviceiPhone17ProMax:
+            return CGSizeMake(0.292, 0.052);
+        case deviceiPhoneAir:
+            return CGSizeMake(0.299, 0.062);
+        case deviceiPhone13ProMax:
+            return CGSizeMake(0.373, 0.036);
+        case deviceiPhone13Pro:
+        case deviceiPhone13:
+            return CGSizeMake(0.4148, 0.0399);
+        case deviceiPhone13Mini:
+            return CGSizeMake(0.4644, 0.0462);
+        case deviceiPhone12ProMax:
+            return CGSizeMake(0.4897, 0.0346);
+        case deviceiPhone12Pro:
+        case deviceiPhone12:
+            return CGSizeMake(0.5393, 0.0379);
+        case deviceiPhone12Mini:
+            return CGSizeMake(0.604, 0.0424);
+        case deviceiPhone11ProMax:
+            return CGSizeMake(0.5057, 0.0335);
+        case deviceiPhone11Pro:
+            return CGSizeMake(0.5583, 0.037);
+        case deviceiPhone11:
+        case deviceiPhoneXR:
+            return CGSizeMake(0.5568, 0.0398);
+        case deviceiPhoneXSMax:
+            return CGSizeMake(0.4884, 0.0333);
+        case deviceiPhoneX:
+        case deviceiPhoneXS:
+            return CGSizeMake(0.5391, 0.0368);
+        default:
+            NSCAssert(!UnityDeviceHasCutout(), @"Device has a cutout, but no ratio has been added for it.");
+            return CGSizeZero;
+    }
+}

+ 62 - 0
unity_ios/Classes/UI/UnityViewControllerBase+iOS.h

@@ -0,0 +1,62 @@
+#pragma once
+
+@interface UnityViewControllerBase (iOS)
+- (BOOL)shouldAutorotate;
+
+- (BOOL)prefersStatusBarHidden;
+- (UIStatusBarStyle)preferredStatusBarStyle;
+@end
+
+// we have several ViewController implementations, to better handle all the possible scenarios of setting orientation
+// long long ago we had just once controller, handling everything
+// then we have found that iOS does not "like" this, or rather it might behave in a way we don't want
+//   thus we split into one "default" view controller (handling orientation)
+//   and then per-orientation "fixed orientation" view controllers
+// when we were changing orientation forcibly (or autorotation constraints) we were changing view controller to another one
+// it turned out later that sometimes (on some devices) iOS 17 does not like this as in it could error/hang
+//   probably because it ended up having two orientation "processes": one from old controller and another from new one
+//   for example sometimes it was printing the error message: "A new orientation transaction token is being requested while a valid one already exists"
+// thus we are returning back to using just one view controller (on iOS 16+)
+// this makes sense especially since in iOS 16 special api to poke iOS about changing autorotation constraint was added
+// so we can use it directly (and hope for the best) instead of doing this dance of recreating view controllers
+// to support both old and new way without introducing too much copy-paste code, we will tweak
+//   UnityDefaultViewController to include "forced orientation" field that can be used in determining supported orientations
+// should we handle fixed orientation in UnityDefaultViewController is defined by the app (as in, AppController will decide when creating root view controller)
+//   as we don't want to push the decision that low-level
+
+// view controllers constrained to one orientation
+
+@interface UnityFixedOrientationViewController : UnityViewControllerBase
+
+- (instancetype)initWithOrientation:(UIInterfaceOrientation)interfaceOrientation;
+
+@end
+
+@interface UnityPortraitOnlyViewController : UnityFixedOrientationViewController
+@end
+@interface UnityPortraitUpsideDownOnlyViewController : UnityFixedOrientationViewController
+@end
+@interface UnityLandscapeLeftOnlyViewController : UnityFixedOrientationViewController
+@end
+@interface UnityLandscapeRightOnlyViewController : UnityFixedOrientationViewController
+@end
+
+// this is default view controller implementation (autorotation enabled)
+// it also has the ability to support fixed orientation; this will be enabled by AppController when creating view controller on iOS 16+
+
+@interface UnityDefaultViewController : UnityViewControllerBase
+
+- (instancetype)initShouldHandleFixedOrientation:(BOOL)shouldHandleFixedOrientation;
+
+// we have well defined points where we should update supported orientations:
+// on init and inside [UnityAppController checkOrientationRequest]
+//   note that pre iOS 16 the latter will recreate default view controller if supported orientations conflict with the current orientation
+//   on iOS 16+ we are keeping one view controller and let it handle supported orientations by itself
+// this is done as opposed to [UnityDefaultViewController supportedInterfaceOrientations] poking unity for that
+//   as this might happen in "random" places, out-of-sync with our handling of "orientation constraints were changed at unity side"
+- (void)updateSupportedOrientations;
+
+@property (nonatomic,readonly) BOOL willHandleFixedOrientation;
+@end
+
+NSUInteger EnabledAutorotationInterfaceOrientations();

+ 320 - 0
unity_ios/Classes/UI/UnityViewControllerBase+iOS.mm

@@ -0,0 +1,320 @@
+#if PLATFORM_IOS
+
+#import "UnityViewControllerBase.h"
+#import "UnityAppController.h"
+
+#include "OrientationSupport.h"
+#include "Keyboard.h"
+#include "UnityView.h"
+#include "PluginBase/UnityViewControllerListener.h"
+#include "UnityAppController.h"
+#include "UnityAppController+ViewHandling.h"
+#include "Unity/ObjCRuntime.h"
+
+// when orientation changes with animation, pause rendering for this long so resolution change happens during animation with less visual distortion
+const NSTimeInterval REORIENTATION_RENDERING_PAUSE = 0.15;
+
+// when returning from presenting UIViewController we might need to update app orientation to "correct" one, as we wont get rotation notification
+@interface UnityAppController ()
+- (void)updateAppOrientation:(UIInterfaceOrientation)orientation;
+@end
+
+#ifndef __IPHONE_16_0
+@interface UIViewController ()
+- (void)setNeedsUpdateOfSupportedInterfaceOrientations;
+@end
+#endif
+
+
+@implementation UnityViewControllerBase (iOS)
+
+- (BOOL)shouldAutorotate
+{
+    return YES;
+}
+
+- (BOOL)prefersStatusBarHidden
+{
+    static bool _PrefersStatusBarHidden = true;
+
+    static bool _PrefersStatusBarHiddenInited = false;
+    if (!_PrefersStatusBarHiddenInited)
+    {
+        NSNumber* hidden = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"UIStatusBarHidden"];
+        _PrefersStatusBarHidden = hidden ? [hidden boolValue] : YES;
+
+        _PrefersStatusBarHiddenInited = true;
+    }
+    return _PrefersStatusBarHidden;
+}
+
+- (UIStatusBarStyle)preferredStatusBarStyle
+{
+    static UIStatusBarStyle _PreferredStatusBarStyle = UIStatusBarStyleDefault;
+
+    static bool _PreferredStatusBarStyleInited = false;
+    if (!_PreferredStatusBarStyleInited)
+    {
+        NSString* style = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"UIStatusBarStyle"];
+        if (style && [style isEqualToString: @"UIStatusBarStyleLightContent"])
+            _PreferredStatusBarStyle = UIStatusBarStyleLightContent;
+        if (style && [style isEqualToString: @"UIStatusBarStyleDarkContent"])
+            _PreferredStatusBarStyle = UIStatusBarStyleDarkContent;
+
+        _PreferredStatusBarStyleInited = true;
+    }
+
+    return _PreferredStatusBarStyle;
+}
+
+- (UIRectEdge)preferredScreenEdgesDeferringSystemGestures
+{
+    UIRectEdge res = UIRectEdgeNone;
+    if (UnityGetDeferSystemGesturesTopEdge())
+        res |= UIRectEdgeTop;
+    if (UnityGetDeferSystemGesturesBottomEdge())
+        res |= UIRectEdgeBottom;
+    if (UnityGetDeferSystemGesturesLeftEdge())
+        res |= UIRectEdgeLeft;
+    if (UnityGetDeferSystemGesturesRightEdge())
+        res |= UIRectEdgeRight;
+    return res;
+}
+
+- (BOOL)prefersHomeIndicatorAutoHidden
+{
+    return UnityGetHideHomeButton();
+}
+
+@end
+
+@implementation UnityDefaultViewController
+{
+    // these will be updated in one place where we "sync" UI side orientation handling to unity side
+    NSUInteger _supportedOrientations;
+
+    // this will be updated in one place where we "sync" UI side orientation handling to unity side
+    UIInterfaceOrientation _fixedOrientation;
+
+    // this indicates if we are asked to handle fixed orientation too - app should decide
+    BOOL _willHandleFixedOrientation;
+}
+
+- (BOOL)willHandleFixedOrientation
+{
+    return _willHandleFixedOrientation;
+}
+
+- (void)readOrientationFromUnity
+{
+    if(UnityShouldAutorotate())
+    {
+        _fixedOrientation = UIInterfaceOrientationUnknown;
+        _supportedOrientations = EnabledAutorotationInterfaceOrientations();
+    }
+    else
+    {
+        _fixedOrientation = ConvertToIosScreenOrientation((ScreenOrientation)UnityRequestedScreenOrientation());
+        _supportedOrientations = (1 << _fixedOrientation);
+    }
+}
+
+- (instancetype)initShouldHandleFixedOrientation:(BOOL)shouldHandleFixedOrientation
+{
+    if ((self = [super init]))
+    {
+        _willHandleFixedOrientation = shouldHandleFixedOrientation;
+        NSAssert(UnityShouldAutorotate() || _willHandleFixedOrientation,
+            @"UnityDefaultViewController should be used either if unity is set to autorotate, or if asked explicitly to handle fixed orientation");
+
+        [self readOrientationFromUnity];
+    }
+    return self;
+}
+
+- (void)updateSupportedOrientations
+{
+    [self readOrientationFromUnity];
+
+    if (@available(iOS 16.0, *))
+        [self setNeedsUpdateOfSupportedInterfaceOrientations];
+}
+
+- (NSUInteger)supportedInterfaceOrientations
+{
+    return _supportedOrientations;
+}
+
+- (void)viewWillAppear:(BOOL)animated
+{
+    ScreenOrientation currentOrientation = UIViewControllerOrientation(self);
+    [GetAppController() updateAppOrientation: ConvertToIosScreenOrientation(currentOrientation)];
+    [super viewWillAppear: animated];
+}
+
+- (void)viewDidAppear:(BOOL)animated
+{
+    ScreenOrientation currentOrientation = UIViewControllerOrientation(self);
+    [GetAppController() updateAppOrientation: ConvertToIosScreenOrientation(currentOrientation)];
+    [super viewDidAppear: animated];
+}
+
+- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
+{
+    // CODE ARCHEOLOGY: we were using UIViewControllerOrientation, but on showing view with "Requires full screen"
+    // CODE ARCHEOLOGY:   we will get the size/orientation *already* set, and the rotation logic would break
+    const ScreenOrientation curOrient = GetAppController().unityView.contentOrientation;
+    const ScreenOrientation newOrient = OrientationAfterTransform(curOrient, [coordinator targetTransform]);
+
+    // delay resolution change, ideally we want it to happen in the middle of rotation animation
+    // we force rendering back upon completion, just in case transition happens sooner
+    // NOTE: with CAMetalDisplayLink we cannot just skip rendering, hence the if
+    if(!GetAppController().unityUsesMetalDisplayLink)
+    {
+        GetAppController().unityView.skipRendering = YES;
+        [GetAppController().unityView performSelector: @selector(resumeRendering) withObject: nil afterDelay: REORIENTATION_RENDERING_PAUSE];
+    }
+
+    // in case of presentation controller it will take control over orientations
+    // so to avoid crazy corner cases, make default view controller to ignore "wrong" orientations
+    // as they will come only in case of presentation view controller and will be reverted anyway
+    // NB: we still want to pass message to super, we just want to skip unity-specific magic
+    NSUInteger targetMask = 1 << ConvertToIosScreenOrientation(newOrient);
+    if (([self supportedInterfaceOrientations] & targetMask) != 0)
+    {
+        [UIView setAnimationsEnabled: UnityUseAnimatedAutorotation() ? YES : NO];
+        [KeyboardDelegate StartReorientation];
+
+        [GetAppController() interfaceWillChangeOrientationTo: ConvertToIosScreenOrientation(newOrient)];
+
+        [coordinator animateAlongsideTransition: nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
+            [self.view setNeedsLayout];
+            [GetAppController() interfaceDidChangeOrientationFrom: ConvertToIosScreenOrientation(curOrient)];
+
+            [KeyboardDelegate FinishReorientation];
+            [UIView setAnimationsEnabled: YES];
+            GetAppController().unityView.skipRendering = NO;
+        }];
+    }
+    [super viewWillTransitionToSize: size withTransitionCoordinator: coordinator];
+}
+
+@end
+
+@interface UnityFixedOrientationViewController()
+{
+    UIInterfaceOrientation _fixedOrientation;
+}
+
+@end
+
+@implementation UnityFixedOrientationViewController
+
+- (instancetype)initWithOrientation:(UIInterfaceOrientation)interfaceOrientation
+{
+    self = [super init];
+    if (self)
+    {
+        _fixedOrientation = interfaceOrientation;
+    }
+    return self;
+}
+
+- (NSUInteger)supportedInterfaceOrientations
+{
+    return 1 << _fixedOrientation;
+}
+
+- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
+{
+    return _fixedOrientation;
+}
+
+- (void)viewWillAppear:(BOOL)animated
+{
+    [GetAppController() updateAppOrientation: _fixedOrientation];
+    [super viewWillAppear: animated];
+}
+
+- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
+{
+    // Adding a call to notify about changed orientation. In iOS16 there was a runtime change where view controller
+    // is not fully set up as soon as we make the view controller change in AppController at -transitionToViewController:.
+    // And instead iOS calls this method, in other cases this method is not called. So we want to call
+    // didTransitionToViewController here as this is the place where we get updated orientation.
+    //
+    // NB: Look for additional explanation at UnityAppController+ViewHandling.mm method -transitionToViewController: before
+    // call to same method.
+    [GetAppController() didTransitionToViewController: self fromViewController: self];
+
+    [super viewWillTransitionToSize: size withTransitionCoordinator: coordinator];
+}
+
+@end
+
+@implementation UnityPortraitOnlyViewController
+
+- (instancetype)init
+{
+    self = [super initWithOrientation: UIInterfaceOrientationPortrait];
+    return self;
+}
+
+@end
+
+@implementation UnityPortraitUpsideDownOnlyViewController
+
+- (instancetype)init
+{
+    self = [super initWithOrientation: UIInterfaceOrientationPortraitUpsideDown];
+    return self;
+}
+
+@end
+
+@implementation UnityLandscapeLeftOnlyViewController
+
+- (instancetype)init
+{
+    self = [super initWithOrientation: UIInterfaceOrientationLandscapeLeft];
+    return self;
+}
+
+@end
+
+@implementation UnityLandscapeRightOnlyViewController
+
+- (instancetype)init
+{
+    self = [super initWithOrientation: UIInterfaceOrientationLandscapeRight];
+    return self;
+}
+
+@end
+
+NSUInteger EnabledAutorotationInterfaceOrientations()
+{
+    NSUInteger ret = 0;
+
+    if (UnityIsOrientationEnabled(portrait))
+        ret |= (1 << UIInterfaceOrientationPortrait);
+    if (UnityDeviceSupportsUpsideDown() && UnityIsOrientationEnabled(portraitUpsideDown))
+        ret |= (1 << UIInterfaceOrientationPortraitUpsideDown);
+    if (UnityIsOrientationEnabled(landscapeLeft))
+        ret |= (1 << UIInterfaceOrientationLandscapeRight);
+    if (UnityIsOrientationEnabled(landscapeRight))
+        ret |= (1 << UIInterfaceOrientationLandscapeLeft);
+
+    // Handling unexpected case where autorotation is on and all the orientations are off by defaulting to current orientation.
+    // Previously we returned 0 and iOS were handling it by keeping orientation as is. From iOS16 behaviour changed and the bug was raised.
+    // Either way iOS requires us to provide non 0 value to supportedInterfaceOrientations.
+    if (ret == 0)
+    {
+        NSLog(@"[Error] All orientations are off for autorotation. Preventing crash by using current orientation.");
+        ret = (1 << [GetAppController() interfaceOrientation]);
+    }
+
+    return ret;
+}
+
+#endif // PLATFORM_IOS

+ 7 - 0
unity_ios/Classes/UI/UnityViewControllerBase+tvOS.h

@@ -0,0 +1,7 @@
+#pragma once
+
+//for tvOS we need just one view controller subclass as there is no screen orientation here
+@interface UnityDefaultViewController : UnityViewControllerBase
+{
+}
+@end

+ 9 - 0
unity_ios/Classes/UI/UnityViewControllerBase+tvOS.mm

@@ -0,0 +1,9 @@
+#if PLATFORM_TVOS
+
+#import "UnityViewControllerBase.h"
+#import "UnityAppController.h"
+
+@implementation UnityDefaultViewController
+@end
+
+#endif // PLATFORM_TVOS

+ 7 - 0
unity_ios/Classes/UI/UnityViewControllerBase+visionOS.h

@@ -0,0 +1,7 @@
+#pragma once
+
+//for visionos we need just one view controller subclass as there is no screen orientation here
+@interface UnityDefaultViewController : UnityViewControllerBase
+{
+}
+@end

+ 9 - 0
unity_ios/Classes/UI/UnityViewControllerBase+visionOS.mm

@@ -0,0 +1,9 @@
+#if PLATFORM_VISIONOS
+
+#import "UnityViewControllerBase.h"
+#import "UnityAppController.h"
+
+@implementation UnityDefaultViewController
+@end
+
+#endif // PLATFORM_VISIONOS

+ 42 - 0
unity_ios/Classes/UI/UnityViewControllerBase.h

@@ -0,0 +1,42 @@
+#pragma once
+
+#import <UIKit/UIKit.h>
+#import "PluginBase/UnityViewControllerListener.h"
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+    #define UNITY_VIEW_CONTROLLER_BASE_CLASS UIViewController
+#elif PLATFORM_TVOS
+    #import <GameController/GCEventViewController.h>
+    #define UNITY_VIEW_CONTROLLER_BASE_CLASS GCEventViewController
+#endif
+
+@interface UnityViewControllerBase : UNITY_VIEW_CONTROLLER_BASE_CLASS
+{
+    id<UnityViewControllerNotifications> _notificationDelegate;
+}
+- (void)viewWillLayoutSubviews;
+- (void)viewDidLayoutSubviews;
+- (void)viewDidDisappear:(BOOL)animated;
+- (void)viewWillDisappear:(BOOL)animated;
+- (void)viewDidAppear:(BOOL)animated;
+- (void)viewWillAppear:(BOOL)animated;
+
+@property (nonatomic, retain) id<UnityViewControllerNotifications> notificationDelegate;
+
+@end
+
+#if PLATFORM_IOS
+#include "UnityViewControllerBase+iOS.h"
+#elif PLATFORM_TVOS
+#include "UnityViewControllerBase+tvOS.h"
+#elif PLATFORM_VISIONOS
+#include "UnityViewControllerBase+visionOS.h"
+#endif
+
+// this should be used to create view controller that plays nicely with unity and account for player settings
+UnityViewControllerBase* AllocUnityViewController(void);
+
+UnityViewControllerBase* AllocUnityDefaultViewController(void);
+#if UNITY_SUPPORT_ROTATION
+UnityViewControllerBase* AllocUnitySingleOrientationViewController(UIInterfaceOrientation orient);
+#endif

+ 90 - 0
unity_ios/Classes/UI/UnityViewControllerBase.mm

@@ -0,0 +1,90 @@
+#import "UnityViewControllerBase.h"
+#import "UnityAppController.h"
+#import "UnityAppController+ViewHandling.h"
+
+#include "OrientationSupport.h"
+
+
+@implementation UnityViewControllerBase
+
+@synthesize notificationDelegate = _notificationDelegate;
+
+- (id)init
+{
+    if ((self = [super init]))
+        self.modalPresentationStyle = UIModalPresentationFullScreen;
+    return self;
+}
+
+- (void)viewWillLayoutSubviews
+{
+    [super viewWillLayoutSubviews];
+    [_notificationDelegate onViewWillLayoutSubviews];
+}
+
+- (void)viewDidLayoutSubviews
+{
+    [super viewDidLayoutSubviews];
+    [_notificationDelegate onViewDidLayoutSubviews];
+}
+
+- (void)viewDidDisappear:(BOOL)animated
+{
+    [super viewDidDisappear: animated];
+    [_notificationDelegate onViewDidDisappear: animated];
+}
+
+- (void)viewWillDisappear:(BOOL)animated
+{
+    [super viewWillDisappear: animated];
+    [_notificationDelegate onViewWillDisappear: animated];
+}
+
+- (void)viewDidAppear:(BOOL)animated
+{
+    [super viewDidAppear: animated];
+    [_notificationDelegate onViewDidAppear: animated];
+}
+
+- (void)viewWillAppear:(BOOL)animated
+{
+    [super viewWillAppear: animated];
+    [_notificationDelegate onViewWillAppear: animated];
+}
+
+@end
+
+UnityViewControllerBase* AllocUnityDefaultViewController()
+{
+    return [UnityDefaultViewController alloc];
+}
+
+#if UNITY_SUPPORT_ROTATION
+UnityViewControllerBase* AllocUnitySingleOrientationViewController(UIInterfaceOrientation orient)
+{
+    switch (orient)
+    {
+        case UIInterfaceOrientationPortrait:            return [UnityPortraitOnlyViewController alloc];
+        case UIInterfaceOrientationPortraitUpsideDown:  return [UnityPortraitUpsideDownOnlyViewController alloc];
+        case UIInterfaceOrientationLandscapeLeft:       return [UnityLandscapeLeftOnlyViewController alloc];
+        case UIInterfaceOrientationLandscapeRight:      return [UnityLandscapeRightOnlyViewController alloc];
+
+        default:                                        assert(false && "bad UIInterfaceOrientation provided");
+    }
+    return nil;
+}
+
+#endif
+
+UnityViewControllerBase* AllocUnityViewController()
+{
+#if UNITY_SUPPORT_ROTATION
+    if (UnityShouldAutorotate())
+        return AllocUnityDefaultViewController();
+
+    UIInterfaceOrientation orient = ConvertToIosScreenOrientation((ScreenOrientation)UnityRequestedScreenOrientation());
+    return AllocUnitySingleOrientationViewController(orient);
+#else
+    return AllocUnityDefaultViewController();
+#endif
+}

+ 35 - 0
unity_ios/Classes/UndefinePlatforms.h

@@ -0,0 +1,35 @@
+// DO NOT PUT #pragma once or include guard check here
+// This header is designed to be able to be included multiple times
+
+// This header is used to temporary undefine iOS/tvOS platform definitions in case there is a naming conflict with
+// 3rd party code. Please make sure to always use this paired with the RedefinePlatforms.h header.
+// Note: PLATFORM_IOS and PLATFORM_TVOS are redefined in 
+// /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/mach-o/loader.h
+//
+//
+// ex.
+//
+// #include "UndefinePlatforms.h"
+// #include "Some3rdParty.h"
+// #include "RedefinePlatforms.h"
+
+#ifdef DETAIL__PLATFORMS_HAD_BEEN_UNDEFINED_BY_UNDEFINEPLATFORMS_H
+#error "UndefinePlatforms.h has been included more than once or RedefinePlatforms.h is missing."
+#endif
+
+#if PLATFORM_IOS
+    #define DETAIL__TEMP_PLATFORM_IOS_WAS_1
+#endif
+#undef PLATFORM_IOS
+
+#if PLATFORM_TVOS
+    #define DETAIL__TEMP_PLATFORM_TVOS_WAS_1
+#endif
+#undef PLATFORM_TVOS
+
+#if PLATFORM_VISIONOS
+#define DETAIL__TEMP_PLATFORM_VISIONOS_WAS_1
+#endif
+#undef PLATFORM_VISIONOS
+
+#define DETAIL__PLATFORMS_HAD_BEEN_UNDEFINED_BY_UNDEFINEPLATFORMS_H

+ 16 - 0
unity_ios/Classes/Unity/AVCapture.h

@@ -0,0 +1,16 @@
+#pragma once
+
+enum
+{
+    avCapturePermissionUnknown  = 0,
+    avCapturePermissionGranted  = 1,
+    avCapturePermissionDenied   = 2,
+};
+enum
+{
+    avVideoCapture = 1,
+    avAudioCapture = 2,
+};
+
+extern "C" int  UnityGetAVCapturePermission(int captureType);
+extern "C" void UnityRequestAVCapturePermission(int captureType, void* userData);

+ 50 - 0
unity_ios/Classes/Unity/AVCapture.mm

@@ -0,0 +1,50 @@
+#include "AVCapture.h"
+
+#if !UNITY_TRAMPOLINE_IN_USE
+// in trampoline this is declared in UnityInterface.h
+extern "C" void UnityReportAVCapturePermission(void* userData);
+#endif
+
+#include <AVFoundation/AVFoundation.h>
+
+
+static NSString* MediaTypeFromEnum(int captureType)
+{
+    if (captureType == avAudioCapture)
+        return AVMediaTypeAudio;
+    else if (captureType == avVideoCapture)
+        return AVMediaTypeVideo;
+    return nil;
+}
+
+UNITY_EXPORT extern "C" int UnityGetAVCapturePermission(int captureType)
+{
+    NSString* mediaType = MediaTypeFromEnum(captureType);
+    if (mediaType == nil)
+        return avCapturePermissionDenied;
+
+#if PLATFORM_OSX || ((PLATFORM_IOS || PLATFORM_VISIONOS) && (UNITY_USES_WEBCAM || UNITY_USES_MICROPHONE))
+    NSInteger status = AVAuthorizationStatusAuthorized;
+    status = [AVCaptureDevice authorizationStatusForMediaType: mediaType];
+
+    if (status == AVAuthorizationStatusNotDetermined)
+        return avCapturePermissionUnknown;
+    else if (status == AVAuthorizationStatusAuthorized)
+        return avCapturePermissionGranted;
+#endif
+
+    return avCapturePermissionDenied;
+}
+
+UNITY_EXPORT extern "C" void UnityRequestAVCapturePermission(int captureType, void* userData)
+{
+#if PLATFORM_OSX || ((PLATFORM_IOS || PLATFORM_VISIONOS) && (UNITY_USES_WEBCAM || UNITY_USES_MICROPHONE))
+    NSString* mediaType = MediaTypeFromEnum(captureType);
+    if (mediaType == nil)
+        return;
+
+    [AVCaptureDevice requestAccessForMediaType: mediaType completionHandler:^(BOOL granted) {
+        UnityReportAVCapturePermission(userData);
+    }];
+#endif
+}

+ 19 - 0
unity_ios/Classes/Unity/CMVideoSampling.h

@@ -0,0 +1,19 @@
+#pragma once
+
+// small helper for getting texture from CMSampleBuffer
+
+typedef struct
+    CMVideoSampling
+{
+    void*   cvTextureCache;
+    void*   cvTextureCacheTexture;
+    void*   cvImageBuffer;
+}
+CMVideoSampling;
+
+void CMVideoSampling_Initialize(CMVideoSampling* sampling);
+void CMVideoSampling_Uninitialize(CMVideoSampling* sampling);
+
+intptr_t  CMVideoSampling_ImageBuffer(CMVideoSampling* sampling, CVImageBufferRef buffer, size_t* w, size_t* h);
+intptr_t  CMVideoSampling_SampleBuffer(CMVideoSampling* sampling, void* buffer, size_t* w, size_t* h); // buffer is CMSampleBufferRef
+intptr_t  CMVideoSampling_LastSampledTexture(CMVideoSampling* sampling);

+ 79 - 0
unity_ios/Classes/Unity/CMVideoSampling.mm

@@ -0,0 +1,79 @@
+#include "CMVideoSampling.h"
+
+#include "CVTextureCache.h"
+#include <AVFoundation/AVFoundation.h>
+
+#include "DisplayManager.h" // for GetMainDisplaySurface() to have proper linear/srgb handling
+
+void CMVideoSampling_Initialize(CMVideoSampling* sampling)
+{
+    ::memset(sampling, 0x00, sizeof(CMVideoSampling));
+    sampling->cvTextureCache = CreateCVTextureCache();
+}
+
+void CMVideoSampling_Uninitialize(CMVideoSampling* sampling)
+{
+    if (sampling->cvImageBuffer)
+    {
+        CFRelease(sampling->cvImageBuffer);
+        sampling->cvImageBuffer = 0;
+    }
+    if (sampling->cvTextureCacheTexture)
+    {
+        CFRelease(sampling->cvTextureCacheTexture);
+        sampling->cvTextureCacheTexture = 0;
+    }
+    if (sampling->cvTextureCache)
+    {
+        CFRelease(sampling->cvTextureCache);
+        sampling->cvTextureCache = 0;
+    }
+}
+
+intptr_t CMVideoSampling_ImageBuffer(CMVideoSampling* sampling, CVImageBufferRef buffer, size_t* w, size_t* h)
+{
+    intptr_t retTex = 0;
+
+    if (sampling->cvImageBuffer)
+        CFRelease(sampling->cvImageBuffer);
+    sampling->cvImageBuffer = buffer;
+    CFRetain(sampling->cvImageBuffer);
+
+    *w = CVPixelBufferGetWidth((CVImageBufferRef)sampling->cvImageBuffer);
+    *h = CVPixelBufferGetHeight((CVImageBufferRef)sampling->cvImageBuffer);
+    if (sampling->cvTextureCacheTexture)
+    {
+        CFRelease(sampling->cvTextureCacheTexture);
+        FlushCVTextureCache(sampling->cvTextureCache);
+        sampling->cvTextureCacheTexture = nil;
+    }
+
+    OSType pixelFormat = CVPixelBufferGetPixelFormatType(buffer);
+    if (pixelFormat == kCVPixelFormatType_32BGRA || pixelFormat == kCVPixelFormatType_DepthFloat16)
+    {
+        MTLPixelFormat metalFormat32BGRA = GetMainDisplaySurface()->srgb ? MTLPixelFormatBGRA8Unorm_sRGB : MTLPixelFormatBGRA8Unorm;
+        MTLPixelFormat metalFormat = pixelFormat == kCVPixelFormatType_32BGRA ? metalFormat32BGRA : MTLPixelFormatR16Float;
+
+        sampling->cvTextureCacheTexture = CreateTextureFromCVTextureCache2(sampling->cvTextureCache, sampling->cvImageBuffer, *w, *h, metalFormat);
+    }
+    else
+    {
+        #define FourCC2Str(fourcc) (const char[]){*(((char*)&fourcc)+3), *(((char*)&fourcc)+2), *(((char*)&fourcc)+1), *(((char*)&fourcc)+0),0}
+        ::printf("CMVideoSampling_SampleBuffer: unexpected pixel format \'%s\'\n", FourCC2Str(pixelFormat));
+    }
+
+    if (sampling->cvTextureCacheTexture)
+        retTex = GetTextureFromCVTextureCache(sampling->cvTextureCacheTexture);
+
+    return retTex;
+}
+
+intptr_t CMVideoSampling_SampleBuffer(CMVideoSampling* sampling, void* buffer, size_t* w, size_t* h)
+{
+    return CMVideoSampling_ImageBuffer(sampling, CMSampleBufferGetImageBuffer((CMSampleBufferRef)buffer), w, h);
+}
+
+intptr_t CMVideoSampling_LastSampledTexture(CMVideoSampling* sampling)
+{
+    return GetTextureFromCVTextureCache(sampling->cvTextureCacheTexture);
+}

+ 47 - 0
unity_ios/Classes/Unity/CVTextureCache.h

@@ -0,0 +1,47 @@
+#pragma once
+#include <stdint.h>
+
+// returns CVMetalTextureCacheRef
+void*       CreateCVTextureCache();
+// cache = CVMetalTextureCacheRef
+void        FlushCVTextureCache(void* cache);
+
+// returns CVMetalTextureRef
+// cache = CVMetalTextureCacheRef
+// image = CVImageBufferRef/CVPixelBufferRef
+void*       CreateTextureFromCVTextureCache2(void* cache, void* image, size_t w, size_t h, uint64_t metalFormat);
+
+// texture = CVMetalTextureRef
+MTLTextureRef   GetMetalTextureFromCVTextureCache(void* texture);
+
+// texture = CVMetalTextureRef
+uintptr_t       GetTextureFromCVTextureCache(void* texture);
+
+// returns CVPixelBufferRef
+void*       CreatePixelBufferForCVTextureCache2(size_t w, size_t h, uint32_t cvFormat);
+// returns CVMetalTextureRef
+// cache = CVMetalTextureCacheRef
+// pb = CVPixelBufferRef (out)
+void*       CreateReadableRTFromCVTextureCache2(void* cache, size_t w, size_t h, uint32_t cvFormat, uint64_t metalFormat, void** pb);
+
+// texture = CVMetalTextureRef
+int         IsCVTextureFlipped(void* texture);
+
+//
+// deprecated
+//
+
+// returns CVPixelBufferRef
+// enforces kCVPixelFormatType_32BGRA
+void*       CreatePixelBufferForCVTextureCache(size_t w, size_t h);
+// returns CVMetalTextureRef
+// cache = CVMetalTextureCacheRef
+// pb = CVPixelBufferRef (out)
+// enforces rgba texture with bgra backing
+void*       CreateReadableRTFromCVTextureCache(void* cache, size_t w, size_t h, void** pb);
+
+// returns CVMetalTextureRef
+// cache = CVMetalTextureCacheRef
+// image = CVImageBufferRef/CVPixelBufferRef
+void*       CreateBGRA32TextureFromCVTextureCache(void* cache, void* image, size_t w, size_t h);
+void*       CreateHalfFloatTextureFromCVTextureCache(void* cache, void* image, size_t w, size_t h);

+ 144 - 0
unity_ios/Classes/Unity/CVTextureCache.mm

@@ -0,0 +1,144 @@
+#include "CVTextureCache.h"
+
+#include "DisplayManager.h"
+#include <CoreVideo/CVMetalTextureCache.h>
+
+void* CreateCVTextureCache()
+{
+    void* ret = 0;
+
+    CVReturn err = 0;
+    if (UnitySelectedRenderingAPI() == apiMetal)
+        err = CVMetalTextureCacheCreate(kCFAllocatorDefault, 0, UnityGetMetalDevice(), 0, (CVMetalTextureCacheRef*)&ret);
+
+    if (err)
+    {
+        ::printf("Error at CVMetalTextureCacheCreate: %d", err);
+        ret = 0;
+    }
+    return ret;
+}
+
+void FlushCVTextureCache(void* cache)
+{
+    if (UnitySelectedRenderingAPI() == apiMetal)
+        CVMetalTextureCacheFlush((CVMetalTextureCacheRef)cache, 0);
+}
+
+void* CreateTextureFromCVTextureCache2(void* cache, void* image, size_t w, size_t h, uint64_t metalFormat)
+{
+    void* texture = 0;
+
+    CVReturn err = 0;
+    if (UnitySelectedRenderingAPI() == apiMetal)
+    {
+        err = CVMetalTextureCacheCreateTextureFromImage(
+            kCFAllocatorDefault, (CVMetalTextureCacheRef)cache, (CVImageBufferRef)image, 0,
+            (MTLPixelFormat)metalFormat, w, h, 0, (CVMetalTextureRef*)&texture
+        );
+    }
+
+    if (err)
+    {
+        ::printf("Error at CVMetalTextureCacheCreateTextureFromImage: %d\n", err);
+        texture = 0;
+    }
+
+    return texture;
+}
+
+id<MTLTexture> GetMetalTextureFromCVTextureCache(void* texture)
+{
+    assert(UnitySelectedRenderingAPI() == apiMetal);
+    return CVMetalTextureGetTexture((CVMetalTextureRef)texture);
+}
+
+uintptr_t GetTextureFromCVTextureCache(void* texture)
+{
+    if (UnitySelectedRenderingAPI() == apiMetal)
+        return (uintptr_t)(__bridge void*)GetMetalTextureFromCVTextureCache(texture);
+    return 0;
+}
+
+void* CreatePixelBufferForCVTextureCache2(size_t w, size_t h, uint32_t cvFormat)
+{
+    CVPixelBufferRef pb = 0;
+    NSDictionary* options = @{  (__bridge NSString*)kCVPixelBufferPixelFormatTypeKey: @(cvFormat),
+                                (__bridge NSString*)kCVPixelBufferWidthKey: @(w),
+                                (__bridge NSString*)kCVPixelBufferHeightKey: @(h),
+                                (__bridge NSString*)kCVPixelBufferMetalCompatibilityKey: @(YES),
+                                (__bridge NSString*)kCVPixelBufferIOSurfacePropertiesKey: @{}};
+
+    CVPixelBufferCreate(kCFAllocatorDefault, w, h, cvFormat, (__bridge CFDictionaryRef)options, &pb);
+    return pb;
+}
+
+void* CreateReadableRTFromCVTextureCache2(void* cache, size_t w, size_t h, uint32_t cvFormat, uint64_t metalFormat, void** pb)
+{
+    *pb = CreatePixelBufferForCVTextureCache2(w, h, cvFormat);
+    return CreateTextureFromCVTextureCache2(cache, *pb, w, h, metalFormat);
+}
+
+int IsCVTextureFlipped(void* texture)
+{
+    if (UnitySelectedRenderingAPI() == apiMetal)
+        return CVMetalTextureIsFlipped((CVMetalTextureRef)texture);
+    return 0;
+}
+
+//
+// deprecated
+//
+
+void* CreatePixelBufferForCVTextureCache(size_t w, size_t h)
+{
+    return CreatePixelBufferForCVTextureCache2(w, h, kCVPixelFormatType_32BGRA);
+}
+
+void* CreateReadableRTFromCVTextureCache(void* cache, size_t w, size_t h, void** pb)
+{
+    *pb = CreatePixelBufferForCVTextureCache2(w, h, kCVPixelFormatType_32BGRA);
+    return CreateBGRA32TextureFromCVTextureCache(cache, *pb, w, h);
+}
+
+void* CreateBGRA32TextureFromCVTextureCache(void* cache, void* image, size_t w, size_t h)
+{
+    void* texture = 0;
+
+    CVReturn err = 0;
+    if (UnitySelectedRenderingAPI() == apiMetal)
+    {
+        err = CVMetalTextureCacheCreateTextureFromImage(
+            kCFAllocatorDefault, (CVMetalTextureCacheRef)cache, (CVImageBufferRef)image, 0,
+            (MTLPixelFormat)((UnityDisplaySurfaceMTL*)GetMainDisplaySurface())->colorFormat, w, h, 0, (CVMetalTextureRef*)&texture
+        );
+    }
+
+    if (err)
+    {
+        ::printf("Error at CVMetalTextureCacheCreateTextureFromImage: %d\n", err);
+        texture = 0;
+    }
+    return texture;
+}
+
+void* CreateHalfFloatTextureFromCVTextureCache(void* cache, void* image, size_t w, size_t h)
+{
+    void* texture = 0;
+
+    CVReturn err = 0;
+    if (UnitySelectedRenderingAPI() == apiMetal)
+    {
+        err = CVMetalTextureCacheCreateTextureFromImage(
+            kCFAllocatorDefault, (CVMetalTextureCacheRef)cache, (CVImageBufferRef)image, 0,
+            MTLPixelFormatR16Float, w, h, 0, (CVMetalTextureRef*)&texture
+        );
+    }
+
+    if (err)
+    {
+        ::printf("Error at CVMetalTextureCacheCreateTextureFromImage: %d\n", err);
+        texture = 0;
+    }
+    return texture;
+}

+ 72 - 0
unity_ios/Classes/Unity/CameraCapture.h

@@ -0,0 +1,72 @@
+#pragma once
+
+#if !PLATFORM_TVOS && UNITY_USES_WEBCAM
+
+#import <AVFoundation/AVFoundation.h>
+
+#if PLATFORM_VISIONOS
+@interface CameraCaptureController : NSObject<AVCaptureVideoDataOutputSampleBufferDelegate>
+#else
+@interface CameraCaptureController : NSObject<AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureDataOutputSynchronizerDelegate>
+#endif
+
+- (bool)initCapture:(AVCaptureDevice*)device;
+- (bool)initCapture:(AVCaptureDevice*)device preset:(NSString*)preset fps:(float)fps;
+- (void)setCaptureFPS:(float)fps;
+- (bool)initColorAndDepthCameraCapture:(AVCaptureDevice*)device preset:(NSString*)preset fps:(float)fps isDepth:(bool)isDepth;
+- (void)initColorAndDepthCameraCaptureSession;
+- (void)clearColorAndDepthCameraCaptureSession;
+- (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection;
+#if !PLATFORM_VISIONOS
+- (void)depthDataOutput:(AVCaptureDepthDataOutput*)captureDepthOutput didOutputDepthData:(AVDepthData*)depthData  timestamp:(CMTime)timestamp connection:(AVCaptureConnection*)connection;
+- (void)dataOutputSynchronizer:(AVCaptureDataOutputSynchronizer *)synchronizer didOutputSynchronizedDataCollection:(AVCaptureSynchronizedDataCollection *)synchronizedDataCollection;
++ (BOOL)focusPointSupported:(AVCaptureDevice*)captureDevice withFocusMode:(AVCaptureFocusMode)focusMode;
+#endif
++ (NSMutableArray<CameraCaptureController*>*)getActiveColorAndDepthCameraControllers;
++ (void)addColorAndDepthCameraController:(CameraCaptureController*)controller;
++ (void)removeColorAndDepthCameraController:(CameraCaptureController*)controller;
++ (void)clearColorAndDepthCameraControllers;
++ (CameraCaptureController*)findColorAndDepthCameraController:(AVCaptureDevice*)device isDepth:(bool)isDepth;
+- (void)capturePixelBufferToMemBuffer:(uint8_t*)dst;
+- (int)isCVTextureFlipped;
+- (int)setFocusPointWithX:(float)x Y:(float)y;
+- (int)setFocusPoint;
+
+- (void)start;
+- (void)pause;
+- (void)stop;
+
+@property (nonatomic, retain) AVCaptureDevice*          captureDevice;
+@property (nonatomic, retain) AVCaptureSession*         captureSession;
+@property (nonatomic, retain) AVCaptureDeviceInput*     captureInput;
+@property (nonatomic, retain) AVCaptureVideoDataOutput* captureOutput;
+#if !PLATFORM_VISIONOS
+@property (nonatomic, retain) AVCaptureDepthDataOutput* captureDepthOutput;
+@property (nonatomic, retain) AVCaptureDataOutputSynchronizer*    captureSynchronizer;
+#endif
+
+- (float)pickAvailableFrameRate:(float)fps;
+
+@end
+
+enum WebCamKind
+{
+    kWebCamUnknown = 0,
+    kWebCamWideAngle = 1,
+    kWebCamTelephoto = 2,
+    kWebCamColorAndDepth = 3,
+    kWebCamUltraWideAngle = 4,
+};
+
+@interface CameraCaptureDevice : NSObject
+- (bool)isColorAndDepthCaptureDevice;
+- (WebCamKind)getKind;
+- (void)fillCaptureDeviceResolutions;
+- (NSString*)pickPresetFromWidth:(int)w height:(int)h;
+- (bool)initCaptureForController:(CameraCaptureController*)controller width:(int)w height:(int)h fps:(float)fps isDepth:(bool)isDepth;
++ (bool)initialized;
++ (void)createCameraCaptureDevicesArray;
++ (void)addCameraCaptureDevice:(AVCaptureDevice*)device;
+@end
+
+#endif

+ 853 - 0
unity_ios/Classes/Unity/CameraCapture.mm

@@ -0,0 +1,853 @@
+#if !PLATFORM_TVOS && UNITY_USES_WEBCAM
+
+#include "CameraCapture.h"
+#include "AVCapture.h"
+#include "CMVideoSampling.h"
+#include "CVTextureCache.h"
+
+#import <CoreVideo/CoreVideo.h>
+
+#include <cmath>
+
+static NSMutableArray<CameraCaptureController*> *activeColorAndDepthCameraControllers = nil;
+
+@implementation CameraCaptureController
+{
+    AVCaptureDevice*            _captureDevice;
+    AVCaptureSession*           _captureSession;
+    AVCaptureDeviceInput*       _captureInput;
+    AVCaptureVideoDataOutput*   _captureOutput;
+#if !PLATFORM_VISIONOS
+    AVCaptureDepthDataOutput*   _captureDepthOutput;
+    AVCaptureDataOutputSynchronizer*    _captureSynchronizer;
+#endif
+
+    @public bool                _isDepth;
+
+    uint8_t*                    _pixelBufferCopy;
+    CMVideoSampling             _cmVideoSampling;
+    NSString*                   _preset;
+    CGPoint                     _focusPoint;
+#if !PLATFORM_VISIONOS
+    AVCaptureFocusMode          _focusMode;
+#endif
+    @public void*               _userData;
+    @public size_t              _width, _height;
+}
+
+- (bool)initCapture:(AVCaptureDevice*)device
+{
+    if (UnityGetAVCapturePermission(avVideoCapture) == avCapturePermissionDenied)
+        return false;
+
+    self.captureDevice = device;
+
+#if PLATFORM_VISIONOS
+    self.captureInput   = [[AVCaptureDeviceInput alloc] initWithDevice: device error:nil];
+#else
+    self.captureInput   = [AVCaptureDeviceInput deviceInputWithDevice: device error: nil];
+#endif
+    self.captureOutput  = [[AVCaptureVideoDataOutput alloc] init];
+
+    if (self.captureOutput == nil || self.captureInput == nil)
+        return false;
+
+    self.captureOutput.alwaysDiscardsLateVideoFrames = YES;
+    NSDictionary* options = @{ (NSString*)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA) };
+    [self.captureOutput setVideoSettings: options];
+
+    CMVideoSampling_Initialize(&self->_cmVideoSampling);
+
+    _width = _height = 0;
+    _focusPoint = CGPointMake(0.5, 0.5); // default focus point is center
+#if !PLATFORM_VISIONOS
+    _focusMode = AVCaptureFocusModeContinuousAutoFocus;
+#endif
+    _pixelBufferCopy = nullptr;
+
+    return true;
+}
+
+- (void)setCaptureFPS:(float)fps
+{
+    if ([self.captureDevice lockForConfiguration: nil])
+    {
+        if (self.captureDevice.activeFormat)
+        {
+            fps = [self pickAvailableFrameRate: fps];
+            self.captureDevice.activeVideoMinFrameDuration = CMTimeMake(1, fps);
+            self.captureDevice.activeVideoMaxFrameDuration = CMTimeMake(1, fps);
+        }
+        else
+        {
+#if !PLATFORM_VISIONOS
+            // In some corner cases (seeing this on iPod iOS 6.1.5) activeFormat is null.
+        #pragma clang diagnostic push
+        #pragma clang diagnostic ignored "-Wdeprecated-declarations"
+            self.captureOutput.minFrameDuration = CMTimeMake(1, fps);
+        #pragma clang diagnostic pop
+#endif
+        }
+        [self.captureDevice unlockForConfiguration];
+    }
+}
+
+- (bool)initCapture:(AVCaptureDevice*)device preset:(NSString*)preset fps:(float)fps
+{
+    if (![self initCapture: device])
+        return false;
+
+    self.captureSession = [[AVCaptureSession alloc] init];
+    if ([self.captureSession canAddInput: self.captureInput])
+        [self.captureSession addInput: self.captureInput];
+    else
+        return false;
+    if ([self.captureSession canAddOutput: self.captureOutput])
+        [self.captureSession addOutput: self.captureOutput];
+    else
+        return false;
+
+    // queue on main thread to simplify gles life
+    [self.captureOutput setSampleBufferDelegate: self queue: dispatch_get_main_queue()];
+
+    self->_preset = preset;
+#if !PLATFORM_VISIONOS
+    [self.captureSession setSessionPreset: preset];
+#endif
+    [self setCaptureFPS: fps];
+
+    return true;
+}
+
+- (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection
+{
+    intptr_t tex = (intptr_t)CMVideoSampling_SampleBuffer(&self->_cmVideoSampling, sampleBuffer, &_width, &_height);
+    UnityDidCaptureVideoFrame(tex, self->_userData);
+}
+
+- (void)capturePixelBufferToMemBuffer:(uint8_t*)dst
+{
+    CVPixelBufferRef pbuf = (CVPixelBufferRef)self->_cmVideoSampling.cvImageBuffer;
+    const size_t srcRowSize = CVPixelBufferGetBytesPerRow(pbuf);
+    const size_t bufSize    = srcRowSize * self->_height;
+    if (self->_pixelBufferCopy == nullptr)
+    {
+        self->_pixelBufferCopy = (uint8_t*)::malloc(bufSize);
+    }
+
+    // while not the best way memory-wise, we want to minimize stalling
+    CVPixelBufferLockBaseAddress(pbuf, kCVPixelBufferLock_ReadOnly);
+    {
+        ::memcpy(self->_pixelBufferCopy, CVPixelBufferGetBaseAddress(pbuf), bufSize);
+    }
+    CVPixelBufferUnlockBaseAddress(pbuf, kCVPixelBufferLock_ReadOnly);
+
+    OSType pixelFormat = CVPixelBufferGetPixelFormatType(pbuf);
+    size_t bpp = 0;
+    switch (pixelFormat)
+    {
+        case kCVPixelFormatType_32BGRA:
+            bpp = 4;
+            break;
+        case kCVPixelFormatType_DepthFloat16:
+            bpp = 2;
+            break;
+        default:
+            assert(false);
+            break;
+    }
+    const size_t dstRowSize = self->_width * bpp;
+
+    uint8_t* src = self->_pixelBufferCopy + (self->_height - 1) * srcRowSize;
+    for (size_t i = 0; i < self->_height; ++i)
+    {
+        ::memcpy(dst, src, dstRowSize);
+        dst += dstRowSize;
+        src -= srcRowSize;
+    }
+}
+
+- (int)isCVTextureFlipped
+{
+    return IsCVTextureFlipped(self->_cmVideoSampling.cvTextureCacheTexture);
+}
+
+#if !PLATFORM_VISIONOS
++ (BOOL)focusPointSupported:(AVCaptureDevice*)captureDevice withFocusMode:(AVCaptureFocusMode)focusMode
+{
+    return captureDevice.focusPointOfInterestSupported && [captureDevice isFocusModeSupported: focusMode];
+}
+#endif
+
+- (int)setFocusPointWithX:(float)x Y:(float)y
+{
+#if !PLATFORM_VISIONOS
+    if (x < 0 || x > 1 || y < 0 || y > 1)
+    {
+        _focusPoint = CGPointMake(0.5, 0.5); // default value for iOS
+        _focusMode = AVCaptureFocusModeContinuousAutoFocus;
+    }
+    else
+    {
+        _focusPoint = CGPointMake(x, 1.0 - y);
+        _focusMode = AVCaptureFocusModeAutoFocus;
+    }
+#endif
+    return [self setFocusPoint];
+}
+
+- (int)setFocusPoint
+{
+#if !PLATFORM_VISIONOS
+    if (self.captureDevice != nil && [CameraCaptureController focusPointSupported: self.captureDevice withFocusMode: _focusMode])
+    {
+        if ([self.captureDevice lockForConfiguration: nil])
+        {
+            self.captureDevice.focusPointOfInterest = _focusPoint;
+            self.captureDevice.focusMode = _focusMode;
+            [self.captureDevice unlockForConfiguration];
+            return 1;
+        }
+    }
+#endif
+    return 0;
+}
+
++ (NSMutableArray<CameraCaptureController*>*)getActiveColorAndDepthCameraControllers
+{
+    if (activeColorAndDepthCameraControllers == nil)
+    {
+        activeColorAndDepthCameraControllers = [[NSMutableArray alloc] init];
+    }
+    return activeColorAndDepthCameraControllers;
+}
+
++ (void)addColorAndDepthCameraController:(CameraCaptureController*)controller
+{
+    CameraCaptureController* prevController = [self findColorAndDepthCameraController: controller.captureDevice isDepth: controller->_isDepth];
+    if (prevController != nil)
+        [prevController pause];
+    CameraCaptureController* otherController = [self findColorAndDepthCameraController: controller.captureDevice isDepth: !controller->_isDepth];
+    if (otherController != nil)
+    {
+        [otherController.captureSession stopRunning];
+        [otherController clearColorAndDepthCameraCaptureSession];
+    }
+    [[self getActiveColorAndDepthCameraControllers] addObject: controller];
+}
+
++ (void)removeColorAndDepthCameraController:(CameraCaptureController*)controller
+{
+    [[self getActiveColorAndDepthCameraControllers] removeObject: controller];
+    CameraCaptureController* otherController = [self findColorAndDepthCameraController: controller.captureDevice isDepth: !controller->_isDepth];
+    if (otherController != nil)
+    {
+        if (otherController.captureSession == nil)
+            [otherController initColorAndDepthCameraCaptureSession];
+        
+        if (!otherController.captureSession.running)
+        {
+            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
+                [otherController.captureSession startRunning];
+            });
+        }
+    }
+}
+
++ (void)clearColorAndDepthCameraControllers
+{
+    NSMutableArray<CameraCaptureController*>* activeColorAndDepthCameraControllers = [self getActiveColorAndDepthCameraControllers];
+    for (CameraCaptureController *controller in activeColorAndDepthCameraControllers)
+    {
+        if (controller.captureSession != nil)
+        {
+            [controller.captureSession stopRunning];
+            [controller clearColorAndDepthCameraCaptureSession];
+        }
+    }
+    [activeColorAndDepthCameraControllers removeAllObjects];
+}
+
++ (CameraCaptureController*)findColorAndDepthCameraController:(AVCaptureDevice*)device isDepth:(bool)isDepth
+{
+    for (CameraCaptureController *controller in [self getActiveColorAndDepthCameraControllers])
+    {
+        if (controller.captureDevice == device && controller->_isDepth == isDepth)
+            return controller;
+    }
+    return nil;
+}
+
+- (bool)initColorAndDepthCameraCapture:(AVCaptureDevice*)device preset:(NSString*)preset fps:(float)fps isDepth:(bool)isDepth
+{
+    if (![self initCapture: device])
+        return false;
+
+#if !PLATFORM_VISIONOS
+    self.captureDepthOutput  = [[AVCaptureDepthDataOutput alloc] init];
+    if (self.captureDepthOutput == nil)
+        return false;
+    self.captureDepthOutput.filteringEnabled = YES; // getting filtered depth data to avoid invalid values
+    self.captureDepthOutput.alwaysDiscardsLateDepthData = YES;
+#endif
+    self->_preset = preset;
+    [self initColorAndDepthCameraCaptureSession];
+    [self setCaptureFPS: fps];
+
+#if !PLATFORM_VISIONOS
+    NSArray<AVCaptureOutput*> *outputs = [NSArray arrayWithObjects: self.captureOutput, self.captureDepthOutput, nil];
+    self.captureSynchronizer = [[AVCaptureDataOutputSynchronizer alloc] initWithDataOutputs: outputs];
+
+    // queue on main thread to simplify gles life
+    [self.captureSynchronizer setDelegate: self queue: dispatch_get_main_queue()];
+#endif
+
+    _isDepth = isDepth;
+
+    return true;
+}
+
+- (void)initColorAndDepthCameraCaptureSession
+{
+    self.captureSession = [[AVCaptureSession alloc] init];
+#if !PLATFORM_VISIONOS
+    [self.captureSession setSessionPreset: self->_preset];
+#endif
+    [self.captureSession addInput: self.captureInput];
+    [self.captureSession addOutput: self.captureOutput];
+#if !PLATFORM_VISIONOS
+    [self.captureSession addOutput: self.captureDepthOutput];
+#endif
+}
+
+- (void)clearColorAndDepthCameraCaptureSession
+{
+    [self.captureSession removeInput: self.captureInput];
+    [self.captureSession removeOutput: self.captureOutput];
+#if !PLATFORM_VISIONOS
+    [self.captureSession removeOutput: self.captureDepthOutput];
+#endif
+    self.captureSession = nil;
+}
+
+#if !PLATFORM_VISIONOS
+- (void)dataOutputSynchronizer:(AVCaptureDataOutputSynchronizer *)synchronizer didOutputSynchronizedDataCollection:(AVCaptureSynchronizedDataCollection *)synchronizedDataCollection
+{
+    AVCaptureSynchronizedSampleBufferData *sampleData = (AVCaptureSynchronizedSampleBufferData*)[synchronizedDataCollection synchronizedDataForCaptureOutput: self.captureOutput];
+
+    if (CMSampleBufferGetImageBuffer(sampleData.sampleBuffer) != nil)
+    {
+        CameraCaptureController* colorController = !self->_isDepth ? self : [CameraCaptureController findColorAndDepthCameraController: self.captureDevice isDepth: false];
+        if (colorController != nil)
+        {
+            intptr_t tex = (intptr_t)CMVideoSampling_SampleBuffer(&colorController->_cmVideoSampling, sampleData.sampleBuffer, &(colorController->_width), &(colorController->_height));
+            UnityDidCaptureVideoFrame(tex, colorController->_userData);
+        }
+    }
+
+    AVCaptureSynchronizedDepthData *depthData = (AVCaptureSynchronizedDepthData*)[synchronizedDataCollection synchronizedDataForCaptureOutput: self.captureDepthOutput];
+    if (depthData.depthData.depthDataMap != nil)
+    {
+        CameraCaptureController* depthController = self->_isDepth ? self : [CameraCaptureController findColorAndDepthCameraController: self.captureDevice isDepth: true];
+        if (depthController != nil)
+        {
+            intptr_t tex = (intptr_t)CMVideoSampling_ImageBuffer(&depthController->_cmVideoSampling, [depthData.depthData depthDataByConvertingToDepthDataType: kCVPixelFormatType_DepthFloat16].depthDataMap, &(depthController->_width), &(depthController->_height));
+            UnityDidCaptureVideoFrame(tex, depthController->_userData);
+        }
+    }
+}
+#endif
+
+- (void)start
+{
+#if !PLATFORM_VISIONOS
+    if (self.captureDepthOutput != nil)
+    {
+        [CameraCaptureController addColorAndDepthCameraController: self];
+    }
+    else
+#endif
+    {
+        [CameraCaptureController clearColorAndDepthCameraControllers];
+    }
+    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
+        [self.captureSession startRunning];
+    });
+}
+
+- (void)pause
+{
+    [self.captureSession stopRunning];
+#if !PLATFORM_VISIONOS
+    if (self.captureDepthOutput != nil)
+#endif
+    {
+        [CameraCaptureController removeColorAndDepthCameraController: self];
+    }
+}
+
+- (void)stop
+{
+    [self.captureSession stopRunning];
+    [self.captureSession removeInput: self.captureInput];
+    [self.captureSession removeOutput: self.captureOutput];
+
+    self.captureInput = nil;
+    self.captureOutput = nil;
+
+#if !PLATFORM_VISIONOS
+    if (self.captureDepthOutput != nil)
+    {
+        self.captureSynchronizer = nil;
+        [self.captureSession removeOutput: self.captureDepthOutput];
+        self.captureDepthOutput = nil;
+        [CameraCaptureController removeColorAndDepthCameraController: self];
+    }
+#else
+    [CameraCaptureController removeColorAndDepthCameraController: self];
+#endif
+
+    self.captureDevice = nil;
+    self.captureSession = nil;
+
+    if (self->_pixelBufferCopy != nullptr)
+    {
+        ::free(self->_pixelBufferCopy);
+        self->_pixelBufferCopy = nullptr;
+    }
+
+    CMVideoSampling_Uninitialize(&self->_cmVideoSampling);
+}
+
+- (float)pickAvailableFrameRate:(float)fps
+{
+    AVFrameRateRange* bestRange = nil;
+    float minDiff = INFINITY;
+    float epsilon = 0.1;
+
+    fps = fps > epsilon ? fps : 24;
+    for (AVFrameRateRange* rate in self.captureDevice.activeFormat.videoSupportedFrameRateRanges)
+    {
+        if (fps + epsilon > rate.minFrameRate && fps - epsilon < rate.maxFrameRate)
+            return fps;
+        else
+        {
+            float diff = ::fmin(::fabs(fps - rate.minFrameRate), ::fabs(fps - rate.maxFrameRate));
+            if (diff < minDiff)
+            {
+                minDiff = diff;
+                bestRange = rate;
+            }
+        }
+    }
+    return fps > bestRange.maxFrameRate ? bestRange.maxFrameRate : bestRange.minFrameRate;
+}
+
+@synthesize captureDevice   = _captureDevice;
+@synthesize captureSession  = _captureSession;
+@synthesize captureOutput   = _captureOutput;
+@synthesize captureInput    = _captureInput;
+#if !PLATFORM_VISIONOS
+@synthesize captureDepthOutput = _captureDepthOutput;
+@synthesize captureSynchronizer = _captureSynchronizer;
+#endif
+
+@end
+
+#if !PLATFORM_VISIONOS
+// Preset for getting depth data with max resolution available
+static NSString* const depthCaptureSessionPreset = AVCaptureSessionPresetPhoto;
+#endif
+static NSMutableArray<CameraCaptureDevice*> *videoCaptureDevices = nil;
+
+@implementation CameraCaptureDevice
+{
+    @public AVCaptureDevice* _device;
+    @public int _frontFacing;
+    @public int _autoFocusPointSupported;
+    @public WebCamKind _kind;
+    @public NSMutableArray<NSValue*>* _resolutions;
+    NSMutableArray<NSString*>* _resPresets;
+}
+
+- (bool)isColorAndDepthCaptureDevice
+{
+#if !PLATFORM_VISIONOS
+    for (AVCaptureDeviceFormat *format in [self->_device formats])
+    {
+        if ([format supportedDepthDataFormats].count > 0)
+            return true;
+    }
+#endif
+    return false;
+}
+
+- (WebCamKind)getKind
+{
+#if !PLATFORM_VISIONOS
+    AVCaptureDeviceType type = _device.deviceType;
+    if ([type isEqualToString: AVCaptureDeviceTypeBuiltInWideAngleCamera])
+        return kWebCamWideAngle;
+    if ([type isEqualToString: AVCaptureDeviceTypeBuiltInUltraWideCamera])
+        return kWebCamUltraWideAngle;
+    if ([type isEqualToString: AVCaptureDeviceTypeBuiltInTelephotoCamera])
+        return kWebCamTelephoto;
+    if ([type isEqualToString: AVCaptureDeviceTypeBuiltInDualCamera] && [self isColorAndDepthCaptureDevice])
+        return kWebCamColorAndDepth;
+    if ([type isEqualToString: AVCaptureDeviceTypeBuiltInDualWideCamera])
+        return kWebCamWideAngle;
+    if ([type isEqualToString: AVCaptureDeviceTypeBuiltInTripleCamera])
+        return kWebCamUltraWideAngle;
+#if defined(__IPHONE_17_0) || defined(__TVOS_17_0)
+    if (@available(iOS 17.0, *))
+    {
+
+        if ([type isEqualToString: AVCaptureDeviceTypeContinuityCamera])
+            return kWebCamWideAngle;
+    }
+#endif
+#endif
+#if PLATFORM_IOS && defined(__IPHONE_15_4)
+    if (@available(iOS 15.4, *))
+    {
+        if ([type isEqualToString: AVCaptureDeviceTypeBuiltInLiDARDepthCamera])
+            return kWebCamColorAndDepth;
+    }
+    if ([type isEqualToString: AVCaptureDeviceTypeBuiltInTrueDepthCamera] && [self isColorAndDepthCaptureDevice])
+        return kWebCamColorAndDepth;
+#endif
+
+    return kWebCamUnknown;
+}
+
+- (void)fillCaptureDeviceResolutions
+{
+#if PLATFORM_VISIONOS
+    const int count = 0;
+#else
+    static NSString* preset[] =
+    {
+        AVCaptureSessionPresetLow, // usually 192x144
+        AVCaptureSessionPreset352x288,
+        AVCaptureSessionPresetMedium, // usually 480x320
+        AVCaptureSessionPreset640x480,
+        AVCaptureSessionPreset1280x720,
+        AVCaptureSessionPreset1920x1080, // usually the same as AVCaptureSessionPresetHigh
+        AVCaptureSessionPreset3840x2160,
+    };
+    const int count = sizeof(preset) / sizeof(preset[0]);
+#endif
+
+    self->_resolutions = [NSMutableArray arrayWithCapacity: count];
+    self->_resPresets = [NSMutableArray arrayWithCapacity: count];
+#if PLATFORM_VISIONOS
+    AVCaptureInput* captureInput = [[AVCaptureDeviceInput alloc] initWithDevice: self->_device error: nil];
+#else
+    AVCaptureInput* captureInput = [AVCaptureDeviceInput deviceInputWithDevice: self->_device error: nil];
+#endif
+
+    //Don't attempt to setup an AVCaptureSession if the user has explicitly denied permission to use the camera.
+    if (captureInput != nil)
+    {
+        AVCaptureSession* captureSession = [[AVCaptureSession alloc] init];
+        if ([captureSession canAddInput: captureInput])
+            [captureSession addInput: captureInput];
+
+#if !PLATFORM_VISIONOS
+        if (self->_kind == kWebCamColorAndDepth)
+        {
+            AVCaptureDepthDataOutput* captureDepthOutput = [[AVCaptureDepthDataOutput alloc] init];
+            if ([captureSession canSetSessionPreset: depthCaptureSessionPreset])
+            {
+                [captureSession setSessionPreset: AVCaptureSessionPresetPhoto];
+                [captureSession addOutput: captureDepthOutput];
+                CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(self->_device.activeDepthDataFormat.formatDescription); // for ColorAndDepth camera return depth buffer resolution
+                [self->_resolutions addObject: [NSValue valueWithCGSize: CGSizeMake(dim.width, dim.height)]];
+                [self->_resPresets addObject: AVCaptureSessionPresetPhoto];
+            }
+        }
+        else
+        {
+            for (int i = 0; i < count; ++i)
+            {
+                if ([captureSession canSetSessionPreset: preset[i]])
+                {
+                    [captureSession setSessionPreset: preset[i]];
+                    CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(self->_device.activeFormat.formatDescription);
+                    [self->_resolutions addObject: [NSValue valueWithCGSize: CGSizeMake(dim.width, dim.height)]];
+                    [self->_resPresets addObject: preset[i]];
+                }
+            }
+        }
+#endif
+    }
+}
+
+- (NSString*)pickPresetFromWidth:(int)w height:(int)h
+{
+#if !PLATFORM_VISIONOS
+    if (self->_kind == kWebCamColorAndDepth)
+    {
+        return depthCaptureSessionPreset;
+    }
+#endif
+
+    int requestedWidth = w > 0 ? w : 640;
+    int requestedHeight = h > 0 ? h : 480;
+    if (requestedHeight > requestedWidth) // hardware camera frame is landscape oriented
+        std::swap(requestedWidth, requestedHeight);
+    NSInteger ret = -1;
+    double bestMatch = std::numeric_limits<double>::max();
+    for (NSInteger i = 0, n = [_resolutions count]; i < n; ++i)
+    {
+        double width = [self->_resolutions[i] CGSizeValue].width;
+        double height = [self->_resolutions[i] CGSizeValue].height;
+        double match = std::abs(std::log(requestedWidth / width)) + std::abs(std::log(requestedHeight / height));
+        if (match < bestMatch)
+        {
+            ret = i;
+            bestMatch = match;
+        }
+    }
+
+#if PLATFORM_VISIONOS
+    return nil;
+#else
+    NSAssert(ret != -1, @"Cannot pick capture preset");
+    return ret != -1 ? self->_resPresets[ret] : AVCaptureSessionPresetHigh;
+#endif
+}
+
+- (CameraCaptureDevice*)initWithDevice:(AVCaptureDevice*)device
+{
+    self->_device = device;
+    self->_frontFacing = device.position == AVCaptureDevicePositionFront ? 1 : 0;
+#if PLATFORM_VISIONOS
+    self->_autoFocusPointSupported = 0;
+#else
+    self->_autoFocusPointSupported = [CameraCaptureController focusPointSupported: device withFocusMode: AVCaptureFocusModeAutoFocus] ? 1 : 0;
+#endif
+    self->_kind = [self getKind];
+    [self fillCaptureDeviceResolutions];
+    return self;
+}
+
+- (bool)initCaptureForController:(CameraCaptureController*)controller width:(int)w height:(int)h fps:(float)fps isDepth:(bool)isDepth
+{
+    bool initResult = false;
+    NSString *preset = [self pickPresetFromWidth: w height: h];
+
+    if ([self isColorAndDepthCaptureDevice])
+    {
+        initResult = [controller initColorAndDepthCameraCapture: self->_device preset: preset fps: fps isDepth: isDepth];
+    }
+    else
+    {
+        assert(!isDepth);
+        initResult = [controller initCapture: self->_device preset: preset fps: fps];
+    }
+    return initResult;
+}
+
++ (bool)initialized
+{
+    return videoCaptureDevices != nil;
+}
+
++ (void)createCameraCaptureDevicesArray
+{
+    videoCaptureDevices = [NSMutableArray arrayWithCapacity: 8];
+}
+
++ (void)addCameraCaptureDevice:(AVCaptureDevice*)device
+{
+    [videoCaptureDevices addObject: [[CameraCaptureDevice alloc] initWithDevice: device]];
+}
+
+@end
+
+
+UNITY_EXPORT extern "C" void UnityEnumVideoCaptureDevices(void* udata, void(*callback)(void* udata, const char* name, int frontFacing, int autoFocusPointSupported, int kind, const int* resolutions, int resCount))
+{
+    if (![CameraCaptureDevice initialized])
+    {
+        [CameraCaptureDevice createCameraCaptureDevicesArray];
+
+#if PLATFORM_VISIONOS
+        AVCaptureDevice* systemPreferredCamera = [AVCaptureDevice systemPreferredCamera];
+        if (systemPreferredCamera != nil)
+            [CameraCaptureDevice addCameraCaptureDevice: systemPreferredCamera];
+#else
+        NSMutableArray<AVCaptureDeviceType>* captureDevices = [NSMutableArray arrayWithObjects: AVCaptureDeviceTypeBuiltInWideAngleCamera, AVCaptureDeviceTypeBuiltInTelephotoCamera, nil];
+
+        [captureDevices addObject: AVCaptureDeviceTypeBuiltInDualCamera];
+        [captureDevices addObject: AVCaptureDeviceTypeBuiltInTrueDepthCamera];
+        [captureDevices addObject: AVCaptureDeviceTypeBuiltInUltraWideCamera];
+        [captureDevices addObject: AVCaptureDeviceTypeBuiltInDualWideCamera];
+        [captureDevices addObject: AVCaptureDeviceTypeBuiltInTripleCamera];
+
+        AVCaptureDeviceDiscoverySession *captureDeviceDiscoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes: captureDevices mediaType: AVMediaTypeVideo position: AVCaptureDevicePositionUnspecified];
+        for (AVCaptureDevice* device in [captureDeviceDiscoverySession devices])
+        {
+            [CameraCaptureDevice addCameraCaptureDevice: device];
+        }
+#endif
+    }
+
+    // we should not provide camera devices information while access has not been granted
+    // but we need to try to enumerate camera devices anyway to trigger permission request dialog
+    if ([AVCaptureDevice authorizationStatusForMediaType: AVMediaTypeVideo] != AVAuthorizationStatusAuthorized)
+        return;
+
+    const unsigned kMaxResolutions = 16;
+    int resolutions[kMaxResolutions * 2];
+    for (CameraCaptureDevice *cameraCaptureDevice in videoCaptureDevices)
+    {
+        int resCount = (int)[cameraCaptureDevice->_resolutions count];
+        assert(resCount <= kMaxResolutions && "Increase the constant above");
+        for (int i = 0; i < resCount; ++i)
+        {
+            resolutions[i * 2] = (int)[cameraCaptureDevice->_resolutions[i] CGSizeValue].width;
+            resolutions[i * 2 + 1] = (int)[cameraCaptureDevice->_resolutions[i] CGSizeValue].height;
+        }
+        NSString* localizedName = cameraCaptureDevice->_device.localizedName;
+        const char* deviceName = localizedName != nil ? localizedName.UTF8String : "";
+        callback(udata, deviceName, cameraCaptureDevice->_frontFacing, cameraCaptureDevice->_autoFocusPointSupported, cameraCaptureDevice->_kind, resolutions, resCount);
+    }
+}
+
+UNITY_EXPORT extern "C" void* UnityInitCameraCapture(int deviceIndex, int w, int h, int fps, int isDepth, void* udata)
+{
+    if (videoCaptureDevices != nil && deviceIndex < videoCaptureDevices.count)
+    {
+        CameraCaptureController* controller = [CameraCaptureController alloc];
+        bool initResult = [videoCaptureDevices[deviceIndex] initCaptureForController: controller width: w height: h fps: (float)fps isDepth: (isDepth != 0)];
+        if (initResult)
+        {
+            controller->_userData = udata;
+            return (__bridge_retained void*)controller;
+        }
+        controller = nil;
+    }
+    return 0;
+}
+
+UNITY_EXPORT extern "C" void UnityStartCameraCapture(void* capture)
+{
+    [(__bridge CameraCaptureController*)capture start];
+}
+
+UNITY_EXPORT extern "C" void UnityPauseCameraCapture(void* capture)
+{
+    [(__bridge CameraCaptureController*)capture pause];
+}
+
+UNITY_EXPORT extern "C" void UnityStopCameraCapture(void* capture)
+{
+    CameraCaptureController* controller = (__bridge_transfer CameraCaptureController*)capture;
+    [controller stop];
+    controller = nil;
+}
+
+UNITY_EXPORT extern "C" void UnityCameraCaptureExtents(void* capture, int* w, int* h)
+{
+    CameraCaptureController* controller = (__bridge CameraCaptureController*)capture;
+    if (controller == nil)
+        return;
+    *w = (int)controller->_width;
+    *h = (int)controller->_height;
+}
+
+UNITY_EXPORT extern "C" void UnityCameraCaptureReadToMemory(void* capture, void* dst_, int w, int h)
+{
+    CameraCaptureController* controller = (__bridge CameraCaptureController*)capture;
+    if (controller == nil)
+        return;
+    assert(w == controller->_width && h == controller->_height);
+    [controller capturePixelBufferToMemBuffer: (uint8_t*)dst_];
+}
+
+UNITY_EXPORT extern "C" int UnityCameraCaptureVideoRotationDeg(void* capture)
+{
+    CameraCaptureController* controller = (__bridge CameraCaptureController*)capture;
+    if (controller == nil)
+        return 0;
+
+    // all cams are landscape.
+    switch (UnityCurrentOrientation())
+    {
+        case portrait:              return 90;
+        case portraitUpsideDown:    return 270;
+        case landscapeLeft:         return controller.captureDevice.position == AVCaptureDevicePositionFront ? 180 : 0;
+        case landscapeRight:        return controller.captureDevice.position == AVCaptureDevicePositionFront ? 0 : 180;
+
+        default:                    assert(false && "bad orientation returned from UnityCurrentOrientation()"); break;
+    }
+    return 0;
+}
+
+UNITY_EXPORT extern "C" int UnityCameraCaptureVerticallyMirrored(void* capture)
+{
+    CameraCaptureController* controller = (__bridge CameraCaptureController*)capture;
+    if (controller == nil)
+        return 0;
+    return [controller isCVTextureFlipped];
+}
+
+UNITY_EXPORT extern "C" int UnityCameraCaptureSetAutoFocusPoint(void* capture, float x, float y)
+{
+    CameraCaptureController* controller = (__bridge CameraCaptureController*)capture;
+    if (controller == nil)
+        return 0;
+    return [controller setFocusPointWithX: x Y: y];
+}
+
+#else
+
+// Stubs for when UNITY_USES_WEBCAM is not defined
+
+UNITY_EXPORT extern "C" void UnityEnumVideoCaptureDevices(void* udata, void(*callback)(void* udata, const char* name, int frontFacing, int autoFocusPointSupported, int kind, const int* resolutions, int resCount))
+{
+}
+
+UNITY_EXPORT extern "C" void* UnityInitCameraCapture(int deviceIndex, int w, int h, int fps, int isDepth, void* udata)
+{
+    return 0;
+}
+
+UNITY_EXPORT extern "C" void UnityStartCameraCapture(void* capture)
+{
+}
+
+UNITY_EXPORT extern "C" void UnityPauseCameraCapture(void* capture)
+{
+}
+
+UNITY_EXPORT extern "C" void UnityStopCameraCapture(void* capture)
+{
+}
+
+UNITY_EXPORT extern "C" void UnityCameraCaptureExtents(void* capture, int* w, int* h)
+{
+}
+
+UNITY_EXPORT extern "C" void UnityCameraCaptureReadToMemory(void* capture, void* dst_, int w, int h)
+{
+}
+
+UNITY_EXPORT extern "C" int UnityCameraCaptureVideoRotationDeg(void* capture)
+{
+    return 0;
+}
+
+UNITY_EXPORT extern "C" int UnityCameraCaptureVerticallyMirrored(void* capture)
+{
+    return 0;
+}
+
+UNITY_EXPORT extern "C" int UnityCameraCaptureSetAutoFocusPoint(void* capture, float x, float y)
+{
+    return 0;
+}
+
+#endif

+ 628 - 0
unity_ios/Classes/Unity/DeviceSettings.mm

@@ -0,0 +1,628 @@
+#include <sys/types.h>
+#include <sys/sysctl.h>
+
+#include "UnityAppController.h"
+#include "UnityView.h"
+#include "DisplayManager.h"
+
+// ad/vendor ids
+#if UNITY_USES_IAD
+#include <AdSupport/ASIdentifierManager.h>
+#include <AppTrackingTransparency/ATTrackingManager.h>
+static id QueryASIdentifierManager()
+{
+    static bool _queryAttempted = false;
+    static id _manager = nil;
+
+    if (_queryAttempted)
+        return _manager;
+
+    _queryAttempted = true;
+    NSBundle* bundle = [NSBundle bundleWithPath: @"/System/Library/Frameworks/AdSupport.framework"];
+    if (bundle)
+    {
+        [bundle load];
+        _manager = [NSClassFromString(@"ASIdentifierManager") performSelector: @selector(sharedManager)];
+        return _manager;
+    }
+
+    return nil;
+}
+
+static bool QueryAttTrackingAuthorization()
+{
+    static bool _status = false;
+
+    // if authorization is revoked, app is restarted, so we can cache
+    if (!_status)
+    {
+        static Class _ATTrackingManager = nil;
+        static bool _classLoadAttempted = false;
+
+        if (!_classLoadAttempted)
+        {
+            _classLoadAttempted = true;
+            NSBundle* bundle = [NSBundle bundleWithPath: @"/System/Library/Frameworks/AppTrackingTransparency.framework"];
+            if (bundle)
+            {
+                [bundle load];
+                _ATTrackingManager = NSClassFromString(@"ATTrackingManager");
+            }
+        }
+
+        if (_ATTrackingManager)
+        {
+            id status = [_ATTrackingManager valueForKey: @"trackingAuthorizationStatus"];
+            if (status && [status isKindOfClass: NSNumber.class])
+            {
+                NSNumber* tackingStatus = status;
+                _status = ATTrackingManagerAuthorizationStatusAuthorized == tackingStatus.unsignedIntValue;
+            }
+        }
+    }
+
+    return _status;
+}
+
+#endif
+
+UNITY_EXPORT extern "C" const char* UnityAdIdentifier()
+{
+    static const char* _ADID = NULL;
+
+#if UNITY_USES_IAD
+    static const NSString* _ADIDNSString = nil;
+
+    // ad id can be reset during app lifetime
+    id manager = QueryASIdentifierManager();
+    if (manager)
+    {
+        NSString* adid = [[manager performSelector: @selector(advertisingIdentifier)] UUIDString];
+        // Do stuff to avoid UTF8String leaks. We still leak if ADID changes, but that shouldn't happen too often.
+        if (![_ADIDNSString isEqualToString: adid])
+        {
+            _ADIDNSString = adid;
+            free((void*)_ADID);
+            _ADID = AllocCString(adid);
+        }
+    }
+#endif
+
+    return _ADID;
+}
+
+UNITY_EXPORT extern "C" int UnityGetLowPowerModeEnabled()
+{
+    return [NSProcessInfo processInfo].lowPowerModeEnabled ? 1 : 0;
+}
+
+UNITY_EXPORT extern "C" int UnityGetWantsSoftwareDimming()
+{
+#if !PLATFORM_TVOS && !PLATFORM_VISIONOS
+    UIScreen* mainScreen = [UIScreen mainScreen];
+    return mainScreen.wantsSoftwareDimming ? 1 : 0;
+#else
+    return 0;
+#endif
+}
+
+UNITY_EXPORT extern "C" void UnitySetWantsSoftwareDimming(int enabled)
+{
+#if !PLATFORM_TVOS && !PLATFORM_VISIONOS
+    UIScreen* mainScreen = [UIScreen mainScreen];
+    mainScreen.wantsSoftwareDimming = enabled;
+#endif
+}
+
+UNITY_EXPORT extern "C" int UnityGetIosAppOnMac()
+{
+    return [NSProcessInfo processInfo].iOSAppOnMac ? 1 : 0;
+}
+
+UNITY_EXPORT extern "C" int UnityAdTrackingEnabled()
+{
+
+#if UNITY_USES_IAD
+    return QueryAttTrackingAuthorization() ? 1 : 0;
+#endif
+
+    return 0;
+}
+
+UNITY_EXPORT extern "C" const char* UnityVendorIdentifier()
+{
+    static const char*  _VendorID           = NULL;
+
+    if (_VendorID == NULL)
+        _VendorID = AllocCString([[UIDevice currentDevice].identifierForVendor UUIDString]);
+
+    return _VendorID;
+}
+
+// UIDevice properties
+
+#define QUERY_UIDEVICE_PROPERTY(FUNC, PROP)                                         \
+    extern "C" const char* FUNC()                                                   \
+    {                                                                               \
+        static const char* value = NULL;                                            \
+        if (value == NULL && [UIDevice instancesRespondToSelector:@selector(PROP)]) \
+            value = AllocCString([UIDevice currentDevice].PROP);                    \
+        return value;                                                               \
+    }
+
+UNITY_EXPORT QUERY_UIDEVICE_PROPERTY(UnityDeviceName, name)
+UNITY_EXPORT QUERY_UIDEVICE_PROPERTY(UnitySystemName, systemName)
+UNITY_EXPORT QUERY_UIDEVICE_PROPERTY(UnitySystemVersion, systemVersion)
+
+#undef QUERY_UIDEVICE_PROPERTY
+
+// hw info
+
+UNITY_EXPORT extern "C" const char* UnityDeviceModel()
+{
+    static const char* _DeviceModel = NULL;
+
+    if (_DeviceModel == NULL)
+    {
+        size_t size;
+        ::sysctlbyname("hw.machine", NULL, &size, NULL, 0);
+
+        char* model = (char*)::malloc(size + 1);
+        ::sysctlbyname("hw.machine", model, &size, NULL, 0);
+        model[size] = 0;
+
+#if TARGET_OS_SIMULATOR
+        if (!strncmp(model, "arm64", 5) || !strncmp(model, "x86_64", 6))
+        {
+            NSString* simModel = [[NSProcessInfo processInfo] environment][@"SIMULATOR_MODEL_IDENTIFIER"];
+            if ([simModel length] > 0)
+            {
+                _DeviceModel = AllocCString(simModel);
+                ::free(model);
+                return _DeviceModel;
+            }
+        }
+#endif
+
+        _DeviceModel = AllocCString([NSString stringWithUTF8String: model]);
+        ::free(model);
+    }
+
+    return _DeviceModel;
+}
+
+UNITY_EXPORT extern "C" int UnityDeviceCPUCount()
+{
+    static int _DeviceCPUCount = -1;
+
+    if (_DeviceCPUCount <= 0)
+    {
+        // maybe would be better to use HW_AVAILCPU
+        int     ctlName[]   = {CTL_HW, HW_NCPU};
+        size_t  dataLen     = sizeof(_DeviceCPUCount);
+
+        ::sysctl(ctlName, 2, &_DeviceCPUCount, &dataLen, NULL, 0);
+    }
+    return _DeviceCPUCount;
+}
+
+UNITY_EXPORT extern "C" int UnityGetPhysicalMemory()
+{
+    return (int)(NSProcessInfo.processInfo.physicalMemory / (1024ULL * 1024ULL));
+}
+
+// misc
+UNITY_EXPORT extern "C" const char* UnitySystemLanguage()
+{
+    static const char* _SystemLanguage = NULL;
+
+    if (_SystemLanguage == NULL)
+    {
+        NSArray* lang = [NSLocale preferredLanguages];
+        if (lang.count > 0)
+            _SystemLanguage = AllocCString(lang[0]);
+    }
+
+    return _SystemLanguage;
+}
+
+enum DeviceType : uint8_t
+{
+    deviceTypeUnknown = 0,
+    iPhone = 1,
+    iPad = 2,
+    iPod = 3,
+    AppleTV = 4
+};
+
+struct DeviceTableEntry
+{
+    DeviceType deviceType;
+    uint8_t majorGen;
+    uint8_t minorGenMin;
+    uint8_t minorGenMax;
+    DeviceGeneration device;
+};
+
+DeviceTableEntry DeviceTable[] =
+{
+    { iPhone, 2, 1, 1, deviceiPhone3GS },
+    { iPhone, 3, 1, 3, deviceiPhone4 },
+    { iPhone, 4, 1, 1, deviceiPhone4S },
+    { iPhone, 5, 3, 4, deviceiPhone5C },
+    { iPhone, 5, 1, 2, deviceiPhone5 },
+    { iPhone, 6, 1, 2, deviceiPhone5S },
+    { iPhone, 7, 2, 2, deviceiPhone6 },
+    { iPhone, 7, 1, 1, deviceiPhone6Plus },
+    { iPhone, 8, 1, 1, deviceiPhone6S },
+    { iPhone, 8, 2, 2, deviceiPhone6SPlus },
+    { iPhone, 8, 4, 4, deviceiPhoneSE1Gen },
+    { iPhone, 9, 1, 1, deviceiPhone7 },
+    { iPhone, 9, 3, 3, deviceiPhone7 },
+    { iPhone, 9, 2, 2, deviceiPhone7Plus },
+    { iPhone, 9, 4, 4, deviceiPhone7Plus },
+    { iPhone, 10, 1, 1, deviceiPhone8 },
+    { iPhone, 10, 4, 4, deviceiPhone8 },
+    { iPhone, 10, 2, 2, deviceiPhone8Plus },
+    { iPhone, 10, 5, 5, deviceiPhone8Plus },
+    { iPhone, 10, 3, 3, deviceiPhoneX },
+    { iPhone, 10, 6, 6, deviceiPhoneX },
+    { iPhone, 11, 8, 8, deviceiPhoneXR },
+    { iPhone, 11, 2, 2, deviceiPhoneXS },
+    { iPhone, 11, 4, 4, deviceiPhoneXSMax },
+    { iPhone, 11, 6, 6, deviceiPhoneXSMax },
+    { iPhone, 12, 1, 1, deviceiPhone11 },
+    { iPhone, 12, 3, 3, deviceiPhone11Pro },
+    { iPhone, 12, 5, 5, deviceiPhone11ProMax },
+    { iPhone, 12, 8, 8, deviceiPhoneSE2Gen },
+    { iPhone, 13, 1, 1, deviceiPhone12Mini },
+    { iPhone, 13, 2, 2, deviceiPhone12 },
+    { iPhone, 13, 3, 3, deviceiPhone12Pro },
+    { iPhone, 13, 4, 4, deviceiPhone12ProMax },
+    { iPhone, 14, 4, 4, deviceiPhone13Mini },
+    { iPhone, 14, 5, 5, deviceiPhone13 },
+    { iPhone, 14, 2, 2, deviceiPhone13Pro },
+    { iPhone, 14, 3, 3, deviceiPhone13ProMax },
+    { iPhone, 14, 6, 6, deviceiPhoneSE3Gen },
+    { iPhone, 14, 7, 7, deviceiPhone14 },
+    { iPhone, 14, 8, 8, deviceiPhone14Plus },
+    { iPhone, 15, 2, 2, deviceiPhone14Pro },
+    { iPhone, 15, 3, 3, deviceiPhone14ProMax },
+    { iPhone, 15, 4, 4, deviceiPhone15 },
+    { iPhone, 15, 5, 5, deviceiPhone15Plus },
+    { iPhone, 16, 1, 1, deviceiPhone15Pro },
+    { iPhone, 16, 2, 2, deviceiPhone15ProMax },
+    { iPhone, 17, 3, 3, deviceiPhone16 },
+    { iPhone, 17, 5, 5, deviceiPhone16e },
+    { iPhone, 17, 4, 4, deviceiPhone16Plus },
+    { iPhone, 17, 1, 1, deviceiPhone16Pro },
+    { iPhone, 17, 2, 2, deviceiPhone16ProMax },
+    { iPhone, 18, 3, 3, deviceiPhone17 },
+    { iPhone, 18, 4, 4, deviceiPhoneAir },
+    { iPhone, 18, 1, 1, deviceiPhone17Pro },
+    { iPhone, 18, 2, 2, deviceiPhone17ProMax },
+    { iPhone, 18, 5, 5, deviceiPhone17e },
+
+    { iPod, 4, 1, 1, deviceiPodTouch4Gen },
+    { iPod, 5, 1, 1, deviceiPodTouch5Gen },
+    { iPod, 7, 1, 1, deviceiPodTouch6Gen },
+    { iPod, 9, 1, 1, deviceiPodTouch7Gen },
+
+    { iPad, 2, 5, 7, deviceiPadMini1Gen },
+    { iPad, 4, 4, 6, deviceiPadMini2Gen },
+    { iPad, 4, 7, 9, deviceiPadMini3Gen },
+    { iPad, 5, 1, 2, deviceiPadMini4Gen },
+    { iPad, 11, 1, 2, deviceiPadMini5Gen },
+    { iPad, 14, 1, 2, deviceiPadMini6Gen },
+    { iPad, 2, 1, 4, deviceiPad2Gen },
+    { iPad, 3, 1, 3, deviceiPad3Gen },
+    { iPad, 3, 4, 6, deviceiPad4Gen },
+    { iPad, 6, 11, 12, deviceiPad5Gen },
+    { iPad, 7, 5, 6, deviceiPad6Gen },
+    { iPad, 7, 11, 12, deviceiPad7Gen },
+    { iPad, 12, 1, 2, deviceiPad9Gen },
+    { iPad, 4, 1, 3, deviceiPadAir1 },
+    { iPad, 5, 3, 4, deviceiPadAir2 },
+    { iPad, 11, 3, 4, deviceiPadAir3Gen },
+    { iPad, 6, 7, 8, deviceiPadPro1Gen },
+    { iPad, 7, 1, 2, deviceiPadPro2Gen },
+    { iPad, 6, 3, 4, deviceiPadPro10Inch1Gen },
+    { iPad, 7, 3, 4, deviceiPadPro10Inch2Gen },
+    { iPad, 8, 1, 4, deviceiPadPro11Inch },
+    { iPad, 8, 9, 10, deviceiPadPro11Inch2Gen },
+    { iPad, 13, 6, 7, deviceiPadPro11Inch3Gen },
+    { iPad, 8, 5, 8, deviceiPadPro3Gen },
+    { iPad, 8, 11, 12, deviceiPadPro4Gen },
+    { iPad, 13, 10, 11, deviceiPadPro5Gen },
+    { iPad, 11, 6, 7, deviceiPad8Gen },
+    { iPad, 13, 1, 2, deviceiPadAir4Gen },
+    { iPad, 13, 16, 17, deviceiPadAir5Gen },
+    { iPad, 14, 5, 6, deviceiPadPro6Gen },
+    { iPad, 14, 3, 4, deviceiPadPro11Inch4Gen },
+    { iPad, 13, 18, 19, deviceiPad10Gen },
+
+
+    { AppleTV, 5, 3, 3, deviceAppleTVHD },
+    { AppleTV, 6, 2, 2, deviceAppleTV4K },
+    { AppleTV, 11, 1, 1, deviceAppleTV4K2Gen },
+    { AppleTV, 14, 1, 1, deviceAppleTV4K3Gen },
+};
+
+UNITY_EXPORT extern "C" int ParseDeviceGeneration(const char* model)
+{
+    DeviceType deviceType = deviceTypeUnknown;
+
+    if (!strncmp(model, "iPhone", 6))
+    {
+        deviceType = iPhone;
+        model += 6;
+    }
+    else if (!strncmp(model, "iPad", 4))
+    {
+        deviceType = iPad;
+        model += 4;
+    }
+    else if (!strncmp(model, "iPod", 4))
+    {
+        deviceType = iPod;
+        model += 4;
+    }
+    else if (!strncmp(model, "AppleTV", 7))
+    {
+        deviceType = AppleTV;
+        model += 7;
+    }
+
+    char* endPtr;
+    int majorGen = (int)strtol(model, &endPtr, 10);
+    int minorGen = (int)strtol(endPtr + 1, &endPtr, 10);
+
+    if (strlen(endPtr) == 0)
+    {
+        for (int i = 0; i < sizeof(DeviceTable) / sizeof(DeviceTable[0]); ++i)
+        {
+            if (deviceType != DeviceTable[i].deviceType)
+                continue;
+            if (majorGen != DeviceTable[i].majorGen)
+                continue;
+            if (minorGen < DeviceTable[i].minorGenMin || minorGen > DeviceTable[i].minorGenMax)
+                continue;
+            return DeviceTable[i].device;
+        }
+    }
+
+    if (deviceType == iPhone)
+        return deviceiPhoneUnknown;
+    else if (deviceType == iPad)
+        return deviceiPadUnknown;
+    else if (deviceType == iPod)
+        return deviceiPodTouchUnknown;
+
+    return deviceUnknown;
+}
+
+UNITY_EXPORT extern "C" int UnityDeviceGeneration()
+{
+    static int _DeviceGeneration = deviceUnknown;
+
+    if (_DeviceGeneration == deviceUnknown)
+    {
+        const char* model = UnityDeviceModel();
+        _DeviceGeneration = ParseDeviceGeneration(model);
+    }
+    return _DeviceGeneration;
+}
+
+// Currently a manual process to add devices that have a cutout (notch). If you add one here you need to also update UnityView GetCutoutToScreenRatio()
+UNITY_EXPORT extern "C" int UnityDeviceHasCutout()
+{
+    switch (UnityDeviceGeneration())
+    {
+        case deviceiPhoneX: case deviceiPhoneXS: case deviceiPhoneXSMax: case deviceiPhoneXR:
+        case deviceiPhone11: case deviceiPhone11Pro: case deviceiPhone11ProMax:
+        case deviceiPhone12: case deviceiPhone12Mini: case deviceiPhone12Pro: case deviceiPhone12ProMax:
+        case deviceiPhone13: case deviceiPhone13Mini: case deviceiPhone13Pro: case deviceiPhone13ProMax:
+        case deviceiPhone14: case deviceiPhone14Plus: case deviceiPhone14Pro: case deviceiPhone14ProMax:
+        case deviceiPhone15: case deviceiPhone15Plus: case deviceiPhone15Pro: case deviceiPhone15ProMax:
+        case deviceiPhone16: case deviceiPhone16Plus: case deviceiPhone16Pro: case deviceiPhone16ProMax: case deviceiPhone16e:
+        case deviceiPhone17: case deviceiPhoneAir:    case deviceiPhone17Pro: case deviceiPhone17ProMax: case deviceiPhone17e:
+            return 1;
+        default:
+            return 0;
+    }
+}
+
+// Devices with a cutout do not support Portrait UpsideDown orientation.
+UNITY_EXPORT extern "C" int UnityDeviceSupportsUpsideDown()
+{
+    return UnityDeviceHasCutout() ? 0 : 1;
+}
+
+UNITY_EXPORT extern "C" int UnityDeviceSupportedOrientations()
+{
+    int orientations = (1 << portrait) | (1 << landscapeLeft) | (1 << landscapeRight);
+    if (UnityDeviceSupportsUpsideDown())
+        orientations |= (1 << portraitUpsideDown);
+
+    return orientations;
+}
+
+UNITY_EXPORT extern "C" int UnityDeviceIsForceTouchSupported()
+{
+    return UnityGetUnityView().traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable;
+}
+
+UNITY_EXPORT extern "C" int UnityDeviceIsStylusTouchSupported()
+{
+    if (strncmp(UnityDeviceModel(), "iPad", 4) != 0)
+        return 0;
+
+    switch (UnityDeviceGeneration())
+    {
+        case deviceiPad2Gen:
+        case deviceiPad3Gen:
+        case deviceiPad4Gen:
+        case deviceiPad5Gen:
+        case deviceiPadMini1Gen:
+        case deviceiPadMini2Gen:
+        case deviceiPadMini3Gen:
+        case deviceiPadMini4Gen:
+        case deviceiPadAir1:
+        case deviceiPadAir2:
+            return 0;
+        default:
+            return 1;
+    }
+}
+
+UNITY_EXPORT extern "C" int UnityDeviceCanShowWideColor()
+{
+#if PLATFORM_VISIONOS
+    return 1;
+#else
+    return UnityGetUnityView().traitCollection.displayGamut == UIDisplayGamutP3;
+#endif
+}
+
+UNITY_EXPORT extern "C" float UnityDeviceDPI()
+{
+    static float _DeviceDPI = -1.0f;
+
+    if (_DeviceDPI < 0.0f)
+    {
+        switch (UnityDeviceGeneration())
+        {
+            // iPhone
+            case deviceiPhone3GS:
+                _DeviceDPI = 163.0f; break;
+            case deviceiPhone4:
+            case deviceiPhone4S:
+            case deviceiPhone5:
+            case deviceiPhone5C:
+            case deviceiPhone5S:
+            case deviceiPhone6:
+            case deviceiPhone6S:
+            case deviceiPhoneSE1Gen:
+            case deviceiPhone7:
+            case deviceiPhone8:
+            case deviceiPhoneXR:
+            case deviceiPhone11:
+            case deviceiPhoneSE2Gen:
+            case deviceiPhoneSE3Gen:
+                _DeviceDPI = 326.0f; break;
+            case deviceiPhone6Plus:
+            case deviceiPhone6SPlus:
+            case deviceiPhone7Plus:
+            case deviceiPhone8Plus:
+                _DeviceDPI = 401.0f; break;
+            case deviceiPhoneX:
+            case deviceiPhoneXS:
+            case deviceiPhoneXSMax:
+            case deviceiPhone11Pro:
+            case deviceiPhone11ProMax:
+            case deviceiPhone12ProMax:
+            case deviceiPhone13ProMax:
+            case deviceiPhone14Plus:
+                _DeviceDPI = 458.0f; break;
+            case deviceiPhone12:
+            case deviceiPhone12Pro:
+            case deviceiPhone13:
+            case deviceiPhone13Pro:
+            case deviceiPhone14:
+            case deviceiPhone14Pro:
+            case deviceiPhone14ProMax:
+            case deviceiPhone15:
+            case deviceiPhone15Plus:
+            case deviceiPhone15Pro:
+            case deviceiPhone15ProMax:
+            case deviceiPhone16:
+            case deviceiPhone16e:
+            case deviceiPhone16Plus:
+            case deviceiPhone16Pro:
+            case deviceiPhone16ProMax:
+            case deviceiPhone17:
+            case deviceiPhoneAir:
+            case deviceiPhone17Pro:
+            case deviceiPhone17ProMax:
+            case deviceiPhone17e:
+                _DeviceDPI = 460.0f; break;
+            case deviceiPhone12Mini:
+            case deviceiPhone13Mini:
+                _DeviceDPI = 476.0f; break;
+
+            // iPad
+            case deviceiPad2Gen:
+                _DeviceDPI = 132.0f; break;
+            case deviceiPad3Gen:
+            case deviceiPad4Gen:        // iPad retina
+            case deviceiPadAir1:
+            case deviceiPadAir2:
+            case deviceiPadAir3Gen:
+            case deviceiPadPro1Gen:
+            case deviceiPadPro10Inch1Gen:
+            case deviceiPadPro2Gen:
+            case deviceiPadPro10Inch2Gen:
+            case deviceiPad5Gen:
+            case deviceiPad6Gen:
+            case deviceiPadPro11Inch:
+            case deviceiPadPro3Gen:
+            case deviceiPadPro11Inch2Gen:
+            case deviceiPadPro11Inch3Gen:
+            case deviceiPadPro4Gen:
+            case deviceiPadPro5Gen:
+            case deviceiPad8Gen:
+            case deviceiPadAir4Gen:
+            case deviceiPad9Gen:
+            case deviceiPadAir5Gen:
+                _DeviceDPI = 264.0f; break;
+            case deviceiPad7Gen:
+                _DeviceDPI = 326.0f; break;
+
+            // iPad mini
+            case deviceiPadMini1Gen:
+                _DeviceDPI = 163.0f; break;
+            case deviceiPadMini2Gen:
+            case deviceiPadMini3Gen:
+            case deviceiPadMini4Gen:
+            case deviceiPadMini5Gen:
+            case deviceiPadMini6Gen:
+                _DeviceDPI = 326.0f; break;
+
+            // iPod
+            case deviceiPodTouch4Gen:
+            case deviceiPodTouch5Gen:
+            case deviceiPodTouch6Gen:
+            case deviceiPodTouch7Gen:
+                _DeviceDPI = 326.0f; break;
+
+            // unknown (new) devices
+            case deviceiPhoneUnknown:
+                _DeviceDPI = 326.0f; break;
+            case deviceiPadUnknown:
+            case deviceiPadPro6Gen:
+            case deviceiPadPro11Inch4Gen:
+            case deviceiPad10Gen:
+                _DeviceDPI = 264.0f; break;
+            case deviceiPodTouchUnknown:
+                _DeviceDPI = 326.0f; break;
+        }
+
+        // If we didn't find DPI, set it to "unknown" value.
+        if (_DeviceDPI < 0.0f)
+            _DeviceDPI = 0.0f;
+    }
+
+    return _DeviceDPI;
+}
+
+// device id with fallback for pre-ios7
+
+UNITY_EXPORT extern "C" const char* UnityDeviceUniqueIdentifier()
+{
+    static const char* _DeviceID = NULL;
+
+    if (_DeviceID == NULL)
+        _DeviceID = UnityVendorIdentifier();
+
+    return _DeviceID;
+}

+ 71 - 0
unity_ios/Classes/Unity/DisplayManager.h

@@ -0,0 +1,71 @@
+#pragma once
+
+#include "UnityRendering.h"
+#include <UIKit/UIKit.h>
+
+@class UnityView;
+
+@interface DisplayConnection : NSObject
+#if !PLATFORM_VISIONOS
+- (id)init:(UIScreen*)targetScreen;
+#else
+- (id)init;
+#endif
+- (void)dealloc;
+
+- (void)createView:(BOOL)useForRendering showRightAway:(BOOL)showRightAway;
+- (void)createView:(BOOL)useForRendering;
+- (void)createWithWindow:(UIWindow*)window andView:(UIView*)view;
+- (UnityDisplaySurfaceBase*)initRendering;
+- (void)recreateSurface:(RenderingSurfaceParams)params;
+- (void)destroySurface;
+
+- (void)shouldShowWindow:(BOOL)show;
+- (void)requestRenderingResolution:(CGSize)res;
+
+#if !PLATFORM_VISIONOS
+@property (readonly, copy, nonatomic)   UIScreen*               screen;
+#endif
+@property (readonly, copy, nonatomic)   UIWindow*               window;
+@property (readonly, copy, nonatomic)   UIView*                 view;
+
+
+@property (readonly, nonatomic)         CGSize                      screenSize;
+@property (readonly, nonatomic)         UnityDisplaySurfaceBase*    surface;
+
+@end
+
+
+@interface DisplayManager : NSObject
+#if !PLATFORM_VISIONOS
+- (id)objectForKeyedSubscript:(id)key;
+- (BOOL)displayAvailable:(UIScreen*)targetScreen;
+- (void)prepareForFirstScene;
+- (void)updateDisplayListCacheInUnity;
+- (void)enumerateDisplaysWithBlock:(void (^)(DisplayConnection* conn))block;
+- (void)enumerateNonMainDisplaysWithBlock:(void (^)(DisplayConnection* conn))block;
+#endif
+
+- (void)startFrameRendering;
+- (void)presentWith:(id<MTLCommandBuffer>)cb;
+- (void)endFrameRendering;
+
++ (void)Initialize;
++ (DisplayManager*)Instance;
++ (void)Destroy;
+
+@property (readonly, nonatomic) DisplayConnection*  mainDisplay;
+
+@property (readonly, nonatomic) NSUInteger          displayCount;
+
+@end
+
+inline DisplayConnection*           GetMainDisplay()
+{
+    return [DisplayManager Instance].mainDisplay;
+}
+
+inline UnityDisplaySurfaceBase*     GetMainDisplaySurface()
+{
+    return GetMainDisplay().surface;
+}

+ 850 - 0
unity_ios/Classes/Unity/DisplayManager.mm

@@ -0,0 +1,850 @@
+#include "DisplayManager.h"
+
+#include "UnityAppController.h"
+#include "UI/UnityView.h"
+#include "UI/UnityAppController+ViewHandling.h"
+
+#import <CoreGraphics/CoreGraphics.h>
+#import <Metal/Metal.h>
+#import <QuartzCore/QuartzCore.h>
+
+#if !(defined(__IPHONE_16_0) || defined(__TVOS_16_0))
+@interface CAMetalLayer (UnityForSdk16)
+{
+}
+@property BOOL wantsExtendedDynamicRangeContent API_AVAILABLE(ios(16.0), macCatalyst(16.0)) API_UNAVAILABLE(tvos, watchos);
+@end
+@interface UIScreen (UnityForSdk16)
+{
+}
+@property CGFloat potentialEDRHeadroom API_AVAILABLE(ios(16.0), tvos(16.0), macCatalyst(16.0)) API_UNAVAILABLE(watchos);
+@property CGFloat currentEDRHeadroom API_AVAILABLE(ios(16.0), tvos(16.0), macCatalyst(16.0)) API_UNAVAILABLE(watchos);
+@end
+#endif
+
+static DisplayManager* _DisplayManager = nil;
+
+@interface DisplayConnection ()
+@property (readonly, nonatomic) UnityDisplaySurfaceMTL*     surfaceMTL;
+@end
+
+@implementation DisplayConnection
+{
+    BOOL                        _needRecreateSurface;
+    CGSize                      _requestedRenderingSize;
+
+#if !PLATFORM_VISIONOS
+    UIScreen*                   _screen;
+#endif
+    UIWindow*                   _window;
+    UIView*                     _view;
+
+    CGSize                      _screenSize;
+
+    UnityDisplaySurfaceBase*    _surface;
+}
+
+#if !PLATFORM_VISIONOS
+@synthesize screen      = _screen;
+#endif
+@synthesize window      = _window;
+@synthesize view        = _view;
+@synthesize screenSize  = _screenSize;
+@synthesize surface     = _surface;
+
+@synthesize surfaceMTL;
+- (UnityDisplaySurfaceMTL*)surfaceMTL
+{
+    assert(_surface->api == apiMetal);
+    return (UnityDisplaySurfaceMTL*)_surface;
+}
+
+#if !PLATFORM_VISIONOS
+- (id)init:(UIScreen*)targetScreen
+{
+    if ((self = [super init]))
+    {
+        self->_screen = targetScreen;
+
+#if !PLATFORM_TVOS
+        targetScreen.currentMode = targetScreen.preferredMode;
+#endif
+
+        // UIScreenOverscanCompensationNone == UIScreenOverscanCompensationInsetApplicationFrame so it will work with pre-ios9 just fine
+        targetScreen.overscanCompensation = UIScreenOverscanCompensationNone;
+
+        self->_screenSize = targetScreen.currentMode.size;
+
+        self->_needRecreateSurface = NO;
+        self->_requestedRenderingSize = CGSizeMake(-1, -1);
+    }
+    return self;
+}
+#else
+- (id)init
+{
+    if ((self = [super init]))
+    {
+        self->_screenSize = CGSizeMake(1920, 1080);
+        self->_needRecreateSurface = NO;
+        self->_requestedRenderingSize = CGSizeMake(-1, -1);
+    }
+    return self;
+}
+#endif
+
+- (void)createWithWindow:(UIWindow*)window andView:(UIView*)view
+{
+    _window = window;
+    _view   = view;
+
+    CGSize layerSize = _view.layer.bounds.size;
+    _screenSize = CGSizeMake(::roundf(layerSize.width * _view.contentScaleFactor), ::roundf(layerSize.height * _view.contentScaleFactor));
+
+    if ([_view.layer isKindOfClass: [CAMetalLayer class]])
+    {
+        // UnityView either has CAMetalLayer backing, when running on Metal, or CALayer, when running in 'nographics' mode
+        ((CAMetalLayer*)_view.layer).drawableSize = layerSize;
+    }
+}
+
+- (void)createView:(BOOL)useForRendering
+{
+    [self createView: useForRendering showRightAway: YES];
+}
+
+#if !PLATFORM_VISIONOS
+- (UIWindowScene*) sceneForScreen:(UIScreen*)screen {
+    for (UIScene* scene in UIApplication.sharedApplication.connectedScenes) {
+        if ([scene isKindOfClass:[UIWindowScene class]]) {
+            UIWindowScene* windowScene = (UIWindowScene *)scene;
+            if (windowScene.screen == screen) {
+                return windowScene;
+            }
+        }
+    }
+    return nil;
+}
+#endif
+
+- (void)createView:(BOOL)useForRendering showRightAway:(BOOL)showRightAway;
+{
+#if !PLATFORM_VISIONOS
+    NSAssert(_screen != [UIScreen mainScreen], @"DisplayConnection for mainScreen should be created with createWithWindow:andView:");
+#endif
+    if (_view == nil)
+    {
+#if !PLATFORM_VISIONOS
+        UIWindow* window = [[UIWindow alloc] initWithFrame: _screen.bounds];
+        UIWindowScene* scene = [self sceneForScreen: _screen];
+        window.windowScene = scene;
+
+        UIView* view = [(useForRendering ? [UnityRenderingView alloc] : [UIView alloc]) initWithFrame: _screen.bounds];
+        view.contentScaleFactor = UnityScreenScaleFactor(_screen);
+#else
+        UIWindow* window = [[UIWindow alloc] init];
+        UIView* view = [(useForRendering ? [UnityRenderingView alloc] : [UIView alloc]) init];
+#endif
+
+        [self createWithWindow: window andView: view];
+
+        if (showRightAway)
+        {
+            [window addSubview: view];
+            window.hidden = NO;
+        }
+    }
+}
+
+- (void)shouldShowWindow:(BOOL)show
+{
+    if (_window.hidden != show)
+        return;
+
+    _window.hidden = !show;
+
+#if !PLATFORM_VISIONOS
+    _window.windowScene = show ? [self sceneForScreen: _screen] : nil;
+#endif
+}
+
+- (UnityDisplaySurfaceBase*)initRendering
+{
+    if (_surface)
+        return _surface;
+
+    UnityDisplaySurfaceBase* ret = NULL;
+    const int api = UnitySelectedRenderingAPI();
+    if (api == apiMetal)
+    {
+        UnityDisplaySurfaceMTL* surf = new UnityDisplaySurfaceMTL();
+        surf->swapchain.layer = (CAMetalLayer*)_view.layer;
+        surf->device = UnityGetMetalDevice();
+        ret = surf;
+    }
+    else
+        ret = new UnityDisplaySurfaceBase();
+
+    ret->api = api;
+    return ret;
+}
+
+- (void)recreateSurface:(RenderingSurfaceParams)params
+{
+    UnityDisplaySurfaceBase* surface = [self initRendering];
+
+    // On metal we depend on hardware screen compositor to handle upscaling this way avoiding additional blit
+    CGSize layerSize = _view.layer.bounds.size;
+    float scale = _view.contentScaleFactor;
+    _screenSize = CGSizeMake(::roundf(layerSize.width * scale), ::roundf(layerSize.height * scale));
+
+    bool hdrChanged         = surface->hdr != params.hdr;
+    bool systemSizeChanged  = surface->systemW != _screenSize.width || surface->systemH != _screenSize.height;
+    bool msaaChanged        = surface->msaaSamples != params.msaaSampleCount;
+    bool depthFmtChanged    = surface->disableDepthAndStencil != params.disableDepthAndStencil;
+    bool memorylessChanged  = surface->memorylessDepth != params.metalMemorylessDepth;
+
+    bool renderSizeChanged  = false;
+    if ((params.renderW > 0 && surface->targetW != params.renderW)         // changed resolution
+        ||  (params.renderH > 0 && surface->targetH != params.renderH)     // changed resolution
+        ||  (params.renderW <= 0 && surface->targetW != surface->systemW) // no longer need intermediate fb
+        ||  (params.renderH <= 0 && surface->targetH != surface->systemH) // no longer need intermediate fb
+    )
+    {
+        renderSizeChanged = true;
+    }
+
+    bool recreateSystemSurface      = systemSizeChanged || hdrChanged;
+    bool recreateRenderingSurface   = systemSizeChanged || renderSizeChanged || msaaChanged || hdrChanged || memorylessChanged;
+
+    surface->disableDepthAndStencil = params.disableDepthAndStencil;
+
+    surface->systemW = (unsigned)_screenSize.width;
+    surface->systemH = (unsigned)_screenSize.height;
+
+    surface->targetW = params.renderW > 0 ? params.renderW : surface->systemW;
+    surface->targetH = params.renderH > 0 ? params.renderH : surface->systemH;
+
+    surface->msaaSamples = params.msaaSampleCount;
+    surface->srgb = params.srgb;
+    surface->wideColor = params.wideColor;
+    surface->hdr = params.hdr;
+    surface->memorylessDepth = params.metalMemorylessDepth;
+
+    const int api = UnitySelectedRenderingAPI();
+    if (api == apiMetal)
+        ((UnityDisplaySurfaceMTL*)surface)->framebufferOnly = params.metalFramebufferOnly;
+
+    if (recreateSystemSurface)
+        CreateSystemRenderingSurface(surface);
+    if (recreateSystemSurface || recreateRenderingSurface)
+        CreateUnityRenderBuffers(surface);
+
+    if (api == apiMetal && (recreateSystemSurface || recreateRenderingSurface))
+    {
+        UnityDisplaySurfaceMTL* mtlSurf = (UnityDisplaySurfaceMTL*)surface;
+#if !PLATFORM_TVOS
+        if (@available(iOS 16.0, *))
+        {
+            mtlSurf->swapchain.layer.wantsExtendedDynamicRangeContent = surface->hdr != 0;
+        }
+#endif
+        UnitySetHDRMode(surface->hdr);
+    }
+    _surface = surface;
+#if !PLATFORM_VISIONOS
+    UnityInvalidateDisplayDataCache((__bridge void*)_screen);
+#endif
+}
+
+- (void)destroySurface
+{
+    if (_surface)
+    {
+        DestroyUnityRenderBuffers(_surface);
+
+        const int api = UnitySelectedRenderingAPI();
+        if (api == apiMetal)
+        {
+            self.surfaceMTL->device = nil;
+            self.surfaceMTL->swapchain.layer  = nil;
+        }
+    }
+
+    delete _surface;
+    _surface = 0;
+}
+
+- (void)dealloc
+{
+    NSAssert(_surface == 0, @"At this point surface should be already destroyed!");
+
+    _view   = nil;
+    _window = nil;
+}
+
+- (void)presentWith:(id<MTLCommandBuffer>)cb toMainScreen:(BOOL)mainScreen
+{
+#if !PLATFORM_VISIONOS
+    CGFloat maxEDR = 1.f;
+    CGFloat currentEDR = 1.f;
+    if (_screen.captured)
+    {
+        maxEDR = 1.f;
+        currentEDR = 1.f;
+    }
+    else
+    {
+        if (@available(iOS 16.0, tvOS 16.0, *))
+        {
+            maxEDR = _screen.potentialEDRHeadroom;
+            currentEDR = _screen.currentEDRHeadroom;
+        }
+    }
+    UnitySetEDRValues(maxEDR, currentEDR);
+#endif
+
+    if(UnitySelectedRenderingAPI() == apiMetal)
+    {
+        PreparePresentMTL(self.surfaceMTL, cb);
+
+        if(mainScreen)
+            APP_CONTROLLER_RENDER_PLUGIN_METHOD(onFrameResolved);
+
+        PresentMTL(self.surfaceMTL, cb);
+    }
+
+    if (_needRecreateSurface)
+    {
+        RenderingSurfaceParams params =
+        {
+            .msaaSampleCount        = _surface->msaaSamples,
+            .renderW                = (int)_requestedRenderingSize.width,
+            .renderH                = (int)_requestedRenderingSize.height,
+            .srgb                   = _surface->srgb,
+            .wideColor              = _surface->wideColor,
+            .hdr                    = _surface->hdr,
+            .metalFramebufferOnly   = 0,
+            .metalMemorylessDepth   = 0,
+            .disableDepthAndStencil = _surface->disableDepthAndStencil,
+        };
+        [self recreateSurface: params];
+
+        _needRecreateSurface = NO;
+        _requestedRenderingSize = CGSizeMake(_surface->targetW, _surface->targetH);
+    }
+}
+
+- (void)requestRenderingResolution:(CGSize)res
+{
+    _requestedRenderingSize = res;
+    _needRecreateSurface    = YES;
+}
+
+@end
+
+
+#if !PLATFORM_VISIONOS
+@implementation DisplayManager
+{
+    NSMapTable*         _displayConnection;
+    DisplayConnection*  _mainDisplay;
+}
+
+@synthesize mainDisplay     = _mainDisplay;
+@synthesize displayCount;
+- (NSUInteger)displayCount { return _displayConnection.count; }
+
+
+- (void)registerScreen:(UIScreen*)screen
+{
+    if([_displayConnection objectForKey:screen] == nil)
+        [_displayConnection setObject: [[DisplayConnection alloc] init: screen] forKey: screen];
+}
+
+- (id)init
+{
+    if ((self = [super init]))
+    {
+        const NSPointerFunctionsOptions options = NSPointerFunctionsStrongMemory | NSPointerFunctionsObjectPointerPersonality;
+        _displayConnection = [NSMapTable mapTableWithKeyOptions: options valueOptions: options];
+
+        [self registerScreen: [UIScreen mainScreen]];
+        _mainDisplay = self[[UIScreen mainScreen]];
+    }
+    return self;
+}
+
+- (void)prepareForFirstScene
+{
+    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(screenDidConnect:) name: UIScreenDidConnectNotification object: nil];
+    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(screenDidDisconnect:) name: UIScreenDidDisconnectNotification object: nil];
+
+    for (UIScreen* screen in [UIScreen screens])
+        [self registerScreen: screen];
+
+    [self updateDisplayListCacheInUnity];
+}
+
+- (void)dealloc
+{
+    [[NSNotificationCenter defaultCenter] removeObserver: self];
+}
+
+- (BOOL)displayAvailable:(UIScreen*)targetScreen;
+{
+    return self[targetScreen] != nil;
+}
+
+- (DisplayConnection*)display:(UIScreen*)targetScreen
+{
+    return self[targetScreen];
+}
+
+- (id)objectForKeyedSubscript:(id)key
+{
+    NSAssert([key isKindOfClass: [UIScreen class]], @"DisplayManager allows only UIScreen as subscript");
+    return [_displayConnection objectForKey: (UIScreen*)key];
+}
+
+- (void)updateDisplayListCacheInUnity
+{
+    // [UIScreen screens] might be out of sync to what is indicated to the
+    // application via UIScreenDidConnectNotification and UIScreenDidDisconnectNotification
+    // notifications. For example, on disconnection [UIScreen screens] might still
+    // have the screen that the display manager no longer knows about.
+
+    const unsigned MAX_DISPLAYS_SUPPORTED = 8; // sync this to the value on Unity side
+    void* screens[MAX_DISPLAYS_SUPPORTED];
+    unsigned screenCount = 0;
+
+    UIScreen* mainScreen = [UIScreen mainScreen];
+    screens[screenCount++] = (__bridge void*)mainScreen;
+
+    for (UIScreen* screen in _displayConnection)
+    {
+        if (screen == mainScreen)
+            continue;
+        screens[screenCount++] = (__bridge void*)screen;
+    }
+
+    UnityUpdateDisplayListCache(screens, screenCount);
+}
+
+- (void)enumerateDisplaysWithBlock:(void (^)(DisplayConnection* conn))block
+{
+    for (UIScreen* screen in _displayConnection)
+    {
+        // if we want simple mirroring unity wont create rendering backing for display
+        // in that case we dont want to touch Display
+        DisplayConnection* conn = [_displayConnection objectForKey: screen];
+        if (conn.surface != nil)
+            block(conn);
+    }
+}
+
+- (void)enumerateNonMainDisplaysWithBlock:(void (^)(DisplayConnection* conn))block
+{
+    for (UIScreen* screen in _displayConnection)
+    {
+        DisplayConnection* conn = [_displayConnection objectForKey: screen];
+        if (conn != _mainDisplay && conn.surface != nil)
+            block(conn);
+    }
+}
+
+- (void)startFrameRendering
+{
+    [self enumerateDisplaysWithBlock:^(DisplayConnection* conn) {
+        StartFrameRendering(conn.surface);
+    }];
+}
+
+- (void)endFrameRendering
+{
+    [self enumerateDisplaysWithBlock:^(DisplayConnection* conn) {
+        EndFrameRendering(conn.surface);
+    }];
+}
+
+- (void)presentWith:(id<MTLCommandBuffer>)cb
+{
+    [_mainDisplay presentWith:cb toMainScreen:YES];
+    [self enumerateNonMainDisplaysWithBlock:^(DisplayConnection* conn) {
+        [conn presentWith:cb toMainScreen:NO];
+    }];
+}
+
+- (void)screenDidConnect:(NSNotification*)notification
+{
+    [self registerScreen: (UIScreen*)[notification object]];
+    [self updateDisplayListCacheInUnity];
+}
+
+- (void)screenDidDisconnect:(NSNotification*)notification
+{
+    UIScreen*           screen  = (UIScreen*)[notification object];
+    DisplayConnection*  conn    = (DisplayConnection*)self[screen];
+
+    if (conn != nil && conn.surface != nil)
+        UnityDisableRenderBuffers(conn.surface->unityColorBuffer, conn.surface->unityDepthBuffer);
+
+    [conn destroySurface];
+    conn = nil;
+
+    [_displayConnection removeObjectForKey: screen];
+    [self updateDisplayListCacheInUnity];
+}
+
++ (void)Initialize
+{
+    NSAssert(_DisplayManager == nil, @"[DisplayManager Initialize] called after creating handler");
+    if (!_DisplayManager)
+        _DisplayManager = [[DisplayManager alloc] init];
+}
+
++ (DisplayManager*)Instance
+{
+    if (!_DisplayManager)
+        _DisplayManager = [[DisplayManager alloc] init];
+
+    return _DisplayManager;
+}
+
++ (void)Destroy
+{
+    _DisplayManager = nil;
+}
+
+@end
+#else
+// xros DisplayManager
+@implementation DisplayManager
+{
+    DisplayConnection*  _mainDisplay;
+}
+
+@synthesize mainDisplay     = _mainDisplay;
+@synthesize displayCount;
+- (NSUInteger)displayCount { return 1; }
+
+- (id)init
+{
+    if ((self = [super init]))
+    {
+        _mainDisplay = [[DisplayConnection alloc] init];
+
+        // Unity needs a non-zero screen in order for renderloop to run
+        const int screenCount = 1;
+        void* screens[screenCount] = {(void*)0x1};
+        UnityUpdateDisplayListCache(screens, screenCount);
+    }
+    return self;
+}
+
+- (void)dealloc
+{
+}
+
+- (void)startFrameRendering
+{
+    StartFrameRendering(_mainDisplay.surface);
+}
+
+- (void)endFrameRendering
+{
+    EndFrameRendering(_mainDisplay.surface);
+}
+
+- (void)presentWith:(id<MTLCommandBuffer>)cb
+{
+    [_mainDisplay presentWith:cb toMainScreen:YES];
+}
+
++ (void)Initialize
+{
+    NSAssert(_DisplayManager == nil, @"[DisplayManager Initialize] called after creating handler");
+    if (!_DisplayManager)
+        _DisplayManager = [[DisplayManager alloc] init];
+}
+
++ (DisplayManager*)Instance
+{
+    if (!_DisplayManager)
+        _DisplayManager = [[DisplayManager alloc] init];
+
+    return _DisplayManager;
+}
+@end
+#endif
+
+//==============================================================================
+//
+//  Unity Interface:
+
+static void EnsureDisplayIsInited(DisplayConnection* conn)
+{
+    // main screen view will be created in AppController,
+    // so we can assume that we need to init secondary display from script
+    // meaning: gles + show right away
+
+    if (conn.view == nil)
+        [conn createView: YES];
+
+    int api = UnitySelectedRenderingAPI();
+
+    bool needRecreate = false;
+    if (conn.surface == 0)
+        needRecreate = true;
+    else if (api == apiMetal)
+        needRecreate = conn.surfaceMTL->swapchain.layer == nil;
+
+    if (needRecreate)
+    {
+        RenderingSurfaceParams params =
+        {
+            .msaaSampleCount        = UnityGetDesiredMSAASampleCount(1),
+            .renderW                = -1,   // native resolution at first (can be changed later)
+            .renderH                = -1,   // native resolution at first (can be changed later)
+            .srgb                   = UnityGetSRGBRequested(),
+            .wideColor              = 0,    // i am not sure how to handle wide color here (and if it is even supported for airplay)
+            .hdr                    = 0,
+            .metalFramebufferOnly   = UnityMetalFramebufferOnly(),
+            .metalMemorylessDepth   = UnityMetalMemorylessDepth(),
+            .disableDepthAndStencil = UnityDisableDepthAndStencilBuffers(),
+        };
+
+        [conn recreateSurface: params];
+        {
+            DisplayConnection* main = [DisplayManager Instance].mainDisplay;
+            StartFrameRendering(main.surface);
+        }
+    }
+}
+
+#if !PLATFORM_TVOS
+UNITY_EXPORT extern "C" int UnityDisplayManager_DisplayCount()
+{
+    return (int)[DisplayManager Instance].displayCount;
+}
+
+UNITY_EXPORT extern "C" bool UnityDisplayManager_DisplayAvailable(void* nativeDisplay)
+{
+#if !PLATFORM_VISIONOS
+    if (nativeDisplay == NULL)
+        return false;
+
+    return [[DisplayManager Instance] displayAvailable: (__bridge UIScreen*)nativeDisplay];
+#else
+    return false;
+#endif
+}
+
+UNITY_EXPORT extern "C" bool UnityDisplayManager_DisplayActive(void* nativeDisplay)
+{
+#if !PLATFORM_VISIONOS
+    return UnityDisplayManager_DisplayAvailable(nativeDisplay);
+#else
+    return true;
+#endif
+}
+
+UNITY_EXPORT extern "C" void UnityDisplayManager_DisplaySystemResolution(void* nativeDisplay, int* w, int* h)
+{
+#if !PLATFORM_VISIONOS
+    if (nativeDisplay == NULL)
+        return;
+
+    DisplayConnection* conn = [DisplayManager Instance][(__bridge UIScreen*)nativeDisplay];
+    EnsureDisplayIsInited(conn);
+
+    // CODE ARCHEOLOGY: We were creating full-screen buffer for "system" RT, and (possibly) resized for "target" RT,
+    // CODE ARCHEOLOGY:   and if the resolution was changed we were blitting target to system to rescale the image.
+    // CODE ARCHEOLOGY: Since then we have switched to using OS scaling mechanism, i.e. we are creating window
+    // CODE ARCHEOLOGY:   with rendering extents and let iOS do the upscale
+    // CODE ARCHEOLOGY: We should revisit the rendering code to possibly get rid of the code needed for this setup
+    // CODE ARCHEOLOGY:   but for now we do the minimal change to unbreak native resolution query
+
+    // note that we mimic size calculation that we use in other places, i.e. using screen bounds + content scale factor
+    // we should also note that we tweak CAMetalLayer.drawableSize (well, that's the way to trigger native upscale)
+    //   so we have CAMetalLayer.drawableSize = rendering size
+    //   and        CAMetalLayer.size         = system (native) size
+    const CGSize layerSize = conn.view.layer.bounds.size; const float scale = conn.view.contentScaleFactor;
+    *w = (int)::roundf(layerSize.width * scale);
+    *h = (int)::roundf(layerSize.height * scale);
+#endif
+}
+
+UNITY_EXPORT extern "C" void UnityDisplayManager_DisplayRenderingResolution(void* nativeDisplay, int* w, int* h)
+{
+    if (nativeDisplay == NULL)
+        return;
+
+#if !PLATFORM_VISIONOS
+    DisplayConnection* conn = [DisplayManager Instance][(__bridge UIScreen*)nativeDisplay];
+#else
+    DisplayConnection* conn = [DisplayManager Instance].mainDisplay;
+#endif
+    EnsureDisplayIsInited(conn);
+
+    *w = (int)conn.surface->targetW;
+    *h = (int)conn.surface->targetH;
+}
+
+UNITY_EXPORT extern "C" void UnityDisplayManager_DisplayRenderingBuffers(void* nativeDisplay, void** colorBuffer, void** depthBuffer)
+{
+    if (nativeDisplay == NULL)
+        return;
+
+#if !PLATFORM_VISIONOS
+    DisplayConnection* conn = [DisplayManager Instance][(__bridge UIScreen*)nativeDisplay];
+#else
+    DisplayConnection* conn = [DisplayManager Instance].mainDisplay;
+#endif
+    EnsureDisplayIsInited(conn);
+
+    if (colorBuffer)
+        *colorBuffer = conn.surface->unityColorBuffer;
+    if (depthBuffer)
+        *depthBuffer = conn.surface->unityDepthBuffer;
+}
+
+UNITY_EXPORT extern "C" void UnityDisplayManager_SetRenderingResolution(void* nativeDisplay, int w, int h)
+{
+#if !PLATFORM_VISIONOS
+    if (nativeDisplay == NULL)
+        return;
+
+    UIScreen*           screen  = (__bridge UIScreen*)nativeDisplay;
+    DisplayConnection*  conn    = [DisplayManager Instance][screen];
+    EnsureDisplayIsInited(conn);
+
+    if (screen == [UIScreen mainScreen])
+        UnityRequestRenderingResolution(w, h);
+    else
+        [conn requestRenderingResolution: CGSizeMake(w, h)];
+#endif
+}
+
+UNITY_EXPORT extern "C" int UnityDisplayManager_PrimaryDisplayIndex()
+{
+    return 0;
+}
+
+#endif
+
+UNITY_EXPORT extern "C" void UnityActivateScreenForRendering(void* nativeDisplay)
+{
+    if (nativeDisplay == NULL)
+        return;
+
+#if !PLATFORM_VISIONOS
+    DisplayConnection* conn = [DisplayManager Instance][(__bridge UIScreen*)nativeDisplay];
+#else
+    DisplayConnection* conn = [DisplayManager Instance].mainDisplay;
+#endif
+
+    EnsureDisplayIsInited(conn);
+    [conn shouldShowWindow: YES];
+}
+
+#if !PLATFORM_VISIONOS
+UNITY_EXPORT extern "C" float UnityScreenScaleFactor(UIScreen* screen)
+{
+    // NOTE: All views handled by Unity have their contentScaleFactor initialized
+    // to value returned by this function.
+
+    // we should query nativeScale if available to get the true device resolution
+    // this way we avoid unnecessarily large frame buffers and downscaling.
+    //   e.g. iPhone 6+ pretends to be a x3 device, while its physical screen is x2.6 something.
+    // it is available on iOS 8.0+, tvOS 9.0+
+    // for older ios versions we add this selector ourselves (AddNewAPIImplIfNeeded in UnityAppController.mm)
+
+    // On AppleTV screen.nativeScale returns NaN when device is in sleep mode and starting from tvOS 10 (?) it returns 0.
+    if (isnan(screen.nativeScale) || (screen.nativeScale == 0))
+        return 1.0f;
+    else
+    {
+        float scalingFactor = UnityCalculateScalingFactorFromTargetDPI(screen);
+        if (scalingFactor > 0.0f)
+            return scalingFactor;
+        else
+            return screen.nativeScale;
+    }
+
+    return screen.scale;
+}
+
+UNITY_EXPORT extern "C" int UnityMainScreenRefreshRate()
+{
+    return (int)[UIScreen mainScreen].maximumFramesPerSecond;
+}
+
+UNITY_EXPORT extern "C" void UnityStartFrameRendering()
+{
+    [[DisplayManager Instance] startFrameRendering];
+}
+
+UNITY_EXPORT extern "C" void UnityDestroyUnityRenderSurfaces()
+{
+    [[DisplayManager Instance] enumerateDisplaysWithBlock:^(DisplayConnection* conn) {
+        [conn destroySurface];
+    }];
+}
+
+UNITY_EXPORT extern "C" void UnitySetBrightness(float brightness)
+{
+#if !PLATFORM_TVOS
+    brightness = (brightness > 1.0 ? 1.0 : brightness) < 0 ? 0.0 : brightness;
+    UIScreen* screen  = [UIScreen mainScreen];
+    screen.brightness = brightness;
+#endif
+}
+
+UNITY_EXPORT extern "C" float UnityGetBrightness()
+{
+#if !PLATFORM_TVOS
+    UIScreen* screen  = [UIScreen mainScreen];
+    return screen.brightness;
+#else
+    return 1.0f;
+#endif
+}
+
+UNITY_EXPORT extern "C" bool UnityIsFullscreen()
+{
+    CGSize screenSize = [[[[DisplayManager Instance] mainDisplay] screen] bounds].size;
+    CGSize viewSize = [[[[DisplayManager Instance] mainDisplay] view] bounds].size;
+
+    return screenSize.width == viewSize.width && screenSize.height == viewSize.height;
+}
+#else
+UNITY_EXPORT extern "C" int UnityMainScreenRefreshRate()
+{
+    return 90;
+}
+
+UNITY_EXPORT extern "C" void UnityStartFrameRendering()
+{
+    [[DisplayManager Instance] startFrameRendering];
+}
+
+UNITY_EXPORT extern "C" void UnityDestroyUnityRenderSurfaces()
+{
+    [[DisplayManager Instance].mainDisplay destroySurface];
+}
+
+UNITY_EXPORT extern "C" void UnitySetBrightness(float brightness)
+{
+}
+
+UNITY_EXPORT extern "C" float UnityGetBrightness()
+{
+    return 1.0f;
+}
+
+UNITY_EXPORT extern "C" bool UnityIsFullscreen()
+{
+    return false;
+}
+#endif

+ 133 - 0
unity_ios/Classes/Unity/Filesystem.mm

@@ -0,0 +1,133 @@
+#include <sys/xattr.h>
+#include "UnityInterface.h"
+#include <cstring>
+
+static NSString* bundleIdWithData = nil;
+UNITY_EXPORT extern "C" void UnitySetDataBundleDirWithBundleId(const char* bundleId)
+{
+    if (bundleId) bundleIdWithData = [NSString stringWithUTF8String: bundleId];
+    else bundleIdWithData = nil;
+}
+
+UNITY_EXPORT extern "C" const char* UnityDataBundleDir()
+{
+    static const char* dir = NULL;
+    if (dir == NULL)
+    {
+        if (bundleIdWithData == nil)
+            dir = AllocCString([[NSBundle mainBundle] bundlePath]);
+        else
+            dir = AllocCString([[NSBundle bundleWithIdentifier: bundleIdWithData] bundlePath]);
+    }
+    return dir;
+}
+
+#define RETURN_SPECIAL_DIR(dir)             \
+    do {                                    \
+        static const char* var = NULL;      \
+        if (var == NULL)                    \
+            var = AllocCString(NSSearchPathForDirectoriesInDomains(dir, NSUserDomainMask, YES)[0]); \
+        return var;                         \
+    } while (0)
+
+UNITY_EXPORT extern "C" const char* UnityDocumentsDir()
+{
+    RETURN_SPECIAL_DIR(NSDocumentDirectory);
+}
+
+UNITY_EXPORT extern "C" const char* UnityLibraryDir()
+{
+    RETURN_SPECIAL_DIR(NSLibraryDirectory);
+}
+
+UNITY_EXPORT extern "C" const char* UnityCachesDir()
+{
+    RETURN_SPECIAL_DIR(NSCachesDirectory);
+}
+
+#undef RETURN_SPECIAL_DIR
+
+UNITY_EXPORT extern "C" int UnityUpdateNoBackupFlag(const char* path, int setFlag)
+{
+    NSURL* url = [NSURL fileURLWithPath: [NSString stringWithUTF8String: path]];
+    NSError* err = nil;
+    return [url setResourceValue: (setFlag ? @YES : @NO) forKey: NSURLIsExcludedFromBackupKey error: &err] == YES ? 1 : 0;
+}
+
+UNITY_EXPORT extern "C" const char* const* UnityFontFallbacks()
+{
+    /*  The following is the family names of fonts that are used as fallbacks
+        for characters that were not fount in user-specified fonts. Add more
+        fonts and/or reorder the list to fit your needs. For certain character
+
+        NOTE: Some similar Chinese, Japanese and Korean characters share the
+        character number in Unicode, but are written differently. To display
+        such characters properly, correct font must be selected. We reorder
+        the fonts list on the first run of this function.
+    */
+    static const char** cachedFonts = NULL;
+    if (cachedFonts == NULL)
+    {
+        const int fontsToReorderCount = 4;
+        static const char* defaultFonts[] =
+        {
+            // first fontsToReorderCount items will be reordered if needed.
+            "Hiragino Kaku Gothic ProN", // Japanese characters
+            "Heiti TC",             // Traditional Chinese characters (on 9.0 OS substitutes this with "PingFang TC")
+            "Heiti SC",             // Simplified Chinese characters (on 9.0 OS substitutes this with "PingFang SC")
+            "Apple SD Gothic Neo",  // Korean characters
+
+            ".Sukhumvit Set UI",    // Thai characters since 8.2 until 9.x
+            "AppleGothic",
+            "Noto Sans Yi",         // Yi characters on 9.0 (not available on tvOS)
+            "Helvetica",
+            "Helvetica Neue",
+            "Arial Hebrew",         // Hebrew since 9.0
+            "Kohinoor Devanagari",  // Hindi since 9.0
+            "Kohinoor Bangla",      // Bengali since 9.0
+            "Kohinoor Telugu",      // Telugu since 9.0
+            "Lao Sangam MN",        // Lao
+            "Geeza Pro",            // Arabic
+            "Kailasa",              // Tibetan since iOS 10.0
+            ".PhoneFallback",       // Armenian, Braille, Georgian, Thai, various symbols since iOS 10.0
+            // Note that iOS itself prefers Thonburi font for the Thai characters, but our font subsystem
+            // can't display combining characters for some reason
+            ".LastResort",
+            NULL
+        };
+
+        // The default works for Japanese, we won't reorder in that case
+        static const char* koFontOrder[] =
+        {
+            "Apple SD Gothic Neo",  // Korean characters
+            "Hiragino Kaku Gothic ProN", // Japanese characters
+            "Heiti TC",             // Traditional Chinese characters (on 9.0 OS substitutes this with "PingFang TC")
+            "Heiti SC",             // Simplified Chinese characters (on 9.0 OS substitutes this with "PingFang SC")
+        };
+
+        static const char* zhFontOrder[] =
+        {
+            "Heiti TC",             // Traditional Chinese characters (on 9.0 OS substitutes this with "PingFang TC")
+            "Heiti SC",             // Simplified Chinese characters (on 9.0 OS substitutes this with "PingFang SC")
+            "Hiragino Kaku Gothic ProN", // Japanese characters
+            "Apple SD Gothic Neo",  // Korean characters
+        };
+
+        const char* lang = UnitySystemLanguage();
+
+        const char** fontOrderOverride = NULL;
+        if (std::strncmp(lang, "ko", 2) == 0)
+            fontOrderOverride = koFontOrder;
+        if (std::strncmp(lang, "zh", 2) == 0)
+            fontOrderOverride = zhFontOrder;
+
+        if (fontOrderOverride)
+        {
+            for (int i = 0; i < fontsToReorderCount; ++i)
+                defaultFonts[i] = fontOrderOverride[i];
+        }
+
+        cachedFonts = defaultFonts;
+    }
+    return cachedFonts;
+}

+ 268 - 0
unity_ios/Classes/Unity/FullScreenVideoPlayer.mm

@@ -0,0 +1,268 @@
+#import <UIKit/UIKit.h>
+#import <AVFoundation/AVFoundation.h>
+#import <AVKit/AVKit.h>
+#import <UIKit/UIGestureRecognizerSubclass.h>
+
+#include "UnityAppController.h"
+#include "UI/UnityView.h"
+#include "UI/UnityViewControllerBase.h"
+#include "UI/OrientationSupport.h"
+#include "UI/UnityAppController+ViewHandling.h"
+#include "Unity/ObjCRuntime.h"
+#include "Unity/VideoPlayer.h"
+#include "PluginBase/UnityViewControllerListener.h"
+
+@interface UICancelGestureRecognizer : UITapGestureRecognizer
+@end
+
+@interface AVKitVideoPlayback : NSObject<VideoPlayerDelegate, UIViewControllerTransitioningDelegate, UIGestureRecognizerDelegate>
+{
+    AVPlayerViewController*     videoViewController;
+    VideoPlayer*                videoPlayer;
+
+    UIColor*                    bgColor;
+    const NSString*             videoGravity;
+    BOOL                        showControls;
+    BOOL                        cancelOnTouch;
+}
+
+- (void)onPlayerReady;
+- (void)onPlayerDidFinishPlayingVideo;
+
+- (id)initAndPlay:(NSURL*)url bgColor:(UIColor*)color showControls:(BOOL)controls videoGravity:(const NSString*)scaling cancelOnTouch:(BOOL)cot;
+- (void)actuallyStartTheMovie:(NSURL*)url;
+- (void)finish;
+@end
+
+static AVKitVideoPlayback*  _AVKitVideoPlayback = nil;
+
+@implementation AVKitVideoPlayback
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+static void AVPlayerViewController_SetAllowsPictureInPicturePlayback_OldIOSImpl(id self_, SEL _cmd, BOOL allow) {}
+static NSUInteger supportedInterfaceOrientations_DefaultImpl(id self_, SEL _cmd)
+{
+    return GetAppController().rootViewController.supportedInterfaceOrientations;
+}
+
+static bool prefersStatusBarHidden_DefaultImpl(id self_, SEL _cmd)
+{
+    if (_AVKitVideoPlayback) // video is still playing
+        return _AVKitVideoPlayback->videoViewController.showsPlaybackControls ? NO : YES;
+    else                    // video has beed stopped
+        return GetAppController().rootViewController.prefersStatusBarHidden;
+}
+
+#endif
+
++ (void)initialize
+{
+    if (self == [AVKitVideoPlayback class])
+    {
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+        class_replaceMethod([AVPlayerViewController class], @selector(supportedInterfaceOrientations), (IMP)&supportedInterfaceOrientations_DefaultImpl, UIViewController_supportedInterfaceOrientations_Enc);
+        class_replaceMethod([AVPlayerViewController class], @selector(prefersStatusBarHidden), (IMP)&prefersStatusBarHidden_DefaultImpl, UIViewController_prefersStatusBarHidden_Enc);
+#endif
+    }
+}
+
+- (id)initAndPlay:(NSURL*)url bgColor:(UIColor*)color showControls:(BOOL)controls videoGravity:(const NSString*)scaling cancelOnTouch:(BOOL)cot
+{
+    if ((self = [super init]))
+    {
+        UnityPause(1);
+
+        showControls    = controls;
+        videoGravity    = scaling;
+        bgColor         = color;
+        cancelOnTouch   = cot;
+
+        [self performSelector: @selector(actuallyStartTheMovie:) withObject: url afterDelay: 0];
+    }
+    return self;
+}
+
+- (void)dealloc
+{
+    [self finish];
+}
+
+- (void)actuallyStartTheMovie:(NSURL*)url
+{
+    @autoreleasepool
+    {
+        videoViewController = [[AVPlayerViewController alloc] init];
+
+        videoViewController.showsPlaybackControls = showControls;
+        videoViewController.view.backgroundColor = bgColor;
+        videoViewController.videoGravity = (NSString*)videoGravity;
+        videoViewController.transitioningDelegate = self;
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+        videoViewController.allowsPictureInPicturePlayback = NO;
+#endif
+#if PLATFORM_TVOS
+        // In tvOS clicking Menu button while video is playing will exit the app. So when
+        // app disables exiting to menu behavior, we need to catch the click and ignore it.
+        if (!UnityGetAppleTVRemoteAllowExitToMenu())
+        {
+            UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap:)];
+            tapRecognizer.allowedPressTypes = @[@(UIPressTypeMenu)];
+            [videoViewController.view addGestureRecognizer: tapRecognizer];
+        }
+#endif
+
+        if (cancelOnTouch)
+        {
+            UICancelGestureRecognizer *cancelTouch = [[UICancelGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap:)];
+            cancelTouch.delegate = self;
+            [videoViewController.view addGestureRecognizer: cancelTouch];
+        }
+
+        videoPlayer = [[VideoPlayer alloc] init];
+        videoPlayer.delegate = self;
+        [videoPlayer loadVideo: url];
+    }
+}
+
+- (void)handleTap:(UITapGestureRecognizer*)sender
+{
+    if (cancelOnTouch && (sender.state == UIGestureRecognizerStateEnded))
+        [self finish];
+}
+
+- (void)onPlayerReady
+{
+    videoViewController.player = videoPlayer.player;
+
+    CGSize screenSize = GetAppController().rootView.bounds.size;
+    BOOL ret = [VideoPlayer CheckScalingModeAspectFill: videoPlayer.videoSize screenSize: screenSize];
+    if (ret == YES && [videoViewController.videoGravity isEqualToString: AVLayerVideoGravityResizeAspect] == YES)
+    {
+        videoViewController.videoGravity = AVLayerVideoGravityResizeAspectFill;
+    }
+
+    [videoPlayer playVideoPlayer];
+#if PLATFORM_TVOS
+    GetAppController().window.rootViewController = videoViewController;
+#else
+    UIViewController *viewController = [GetAppController() topMostController];
+    if ([viewController isEqual: videoViewController] == NO && [videoViewController isBeingPresented] == NO)
+        [viewController presentViewController: videoViewController animated: NO completion: nil];
+#endif
+}
+
+- (void)onPlayerDidFinishPlayingVideo
+{
+    [self finish];
+}
+
+- (void)onPlayerTryResume
+{
+    if (![videoPlayer isPlaying])
+        [videoPlayer resume];
+}
+
+- (void)onPlayerError:(NSError*)error
+{
+    [self finish];
+}
+
+- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
+{
+    if ([dismissed isEqual: videoViewController] == YES)
+    {
+        [self finish];
+    }
+
+    return nil;
+}
+
+- (void)finish
+{
+    @synchronized(self)
+    {
+#if PLATFORM_TVOS
+        GetAppController().window.rootViewController = GetAppController().rootViewController;
+#else
+        UIViewController *viewController = [GetAppController() topMostController];
+        if ([viewController isEqual: videoViewController] == YES && [viewController isBeingDismissed] == NO)
+            [viewController dismissViewControllerAnimated: NO completion: nil];
+#endif
+
+        [videoPlayer unloadPlayer];
+
+        videoPlayer = nil;
+        videoViewController = nil;
+
+        _AVKitVideoPlayback = nil;
+
+#if PLATFORM_TVOS
+        UnityCancelTouches();
+#endif
+
+        if (UnityIsPaused())
+            UnityPause(0);
+    }
+}
+
+@end
+
+@implementation UICancelGestureRecognizer
+//instead of having lots of UITapGestureRecognizers with different finger numbers
+- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
+{
+    [self setState: UIGestureRecognizerStateRecognized];
+}
+
+@end
+
+UNITY_EXPORT extern "C" void UnityPlayFullScreenVideo(const char* path, const float* color, unsigned controls, unsigned scaling)
+{
+    const BOOL  cancelOnTouch[] = { NO, NO, YES, NO };
+    UIColor*    bgColor         = [UIColor colorWithRed: color[0] green: color[1] blue: color[2] alpha: color[3]];
+
+    const bool isURL = ::strstr(path, "://") != 0;
+    NSURL* url = nil;
+    if (isURL)
+    {
+        url = [NSURL URLWithString: [NSString stringWithUTF8String: path]];
+    }
+    else
+    {
+        NSString* relPath   = path[0] == '/' ? [NSString stringWithUTF8String: path] : [NSString stringWithFormat: @"Data/Raw/%s", path];
+        NSString* fullPath  = [[NSString stringWithUTF8String: UnityDataBundleDir()] stringByAppendingPathComponent: relPath];
+        url = [NSURL fileURLWithPath: fullPath];
+    }
+
+    const BOOL      showControls[]  =   { YES, YES, NO, NO };
+    const NSString* videoGravity[]  =
+    {
+        AVLayerVideoGravityResizeAspectFill,    // ???
+        AVLayerVideoGravityResizeAspect,
+        AVLayerVideoGravityResizeAspectFill,
+        AVLayerVideoGravityResize,
+    };
+
+    if (_AVKitVideoPlayback)
+        [_AVKitVideoPlayback finish];
+    _AVKitVideoPlayback = [[AVKitVideoPlayback alloc] initAndPlay: url bgColor: bgColor
+                           showControls: showControls[controls] videoGravity: videoGravity[scaling] cancelOnTouch: cancelOnTouch[controls]];
+}
+
+UNITY_EXPORT extern "C" void UnityStopFullScreenVideoIfPlaying()
+{
+    if (_AVKitVideoPlayback)
+        [_AVKitVideoPlayback finish];
+}
+
+UNITY_EXPORT extern "C" int UnityIsFullScreenPlaying()
+{
+    return _AVKitVideoPlayback ? 1 : 0;
+}
+
+UNITY_EXPORT extern "C" void TryResumeFullScreenVideo()
+{
+    if (_AVKitVideoPlayback)
+        [_AVKitVideoPlayback onPlayerTryResume];
+}

+ 442 - 0
unity_ios/Classes/Unity/IUnityEventQueue.h

@@ -0,0 +1,442 @@
+// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
+//
+// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
+//
+// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
+
+#ifndef __cplusplus
+#error "This file cannot be compiled in a C environment"
+#endif
+
+#pragma once
+
+#include "IUnityInterface.h"
+
+//  5.2 patch 1 + of Unity will support this.
+//  The lack or presence of this feature can cause the EventQueue
+//  to crash if used against the wrong version of Unity.
+//
+//  Before we had the IUnityInterfaces system this interface changed
+//  to support a cleanup handler on events. This broke our plugins
+//  in older versions of Unity. The registry should help us with
+//  this sort of thing in the future.
+#ifndef EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
+    #define EVENTQUEUE_SUPPORTS_EVENT_CLEANUP 1
+#endif
+
+////////////////////////////////////////////////////////////////////////////////////////
+// NOTE: Do not include any additional headers here. This is an external facing header
+//       so avoid any internal dependencies.
+////////////////////////////////////////////////////////////////////////////////////////
+// The Unity EventQueue is a standard way of passing information between plugins or parts
+// of the engine without any reliance on managed systems, game objects or
+// other pieces of Unity.
+//
+// Events are simply a structure and GUID pair. GUIDs were chosen rather
+// than hashes as it allows plugins to define their own event
+// payloads and use the EventQueue.
+//
+// While the EventQueue itself is self contained and can be used for
+// many different applications within Unity the global event
+// queue that is passed to plugins is always serviced on the main
+// simulation thread and thus serves as a convenient means of
+// pushing asynchronous operations back to the main game thread
+//
+// Payloads should strive to be small. The EventQueue is a 0 allocation
+// system which ensures that the use of events does not fragment
+// or add undue pressure on resource limited systems.
+//
+// This header defines ALL that is required to listen, define
+// and send events from both within Unity and from plugins.
+////////////////////////////////////////////////////////////////////////////////////////
+// USAGE:
+//
+// SENDING
+// ========
+//
+// To Define new Event:
+// --------------------
+// // Structure and GUID
+// struct MyEvent {};
+// REGISTER_EVENT_ID(0x19D736400584B24BULL,0x98B9EFBE26D3F3C9ULL,MyEvent)
+// // hash above is a GUID split into 2 64 bit integers for convenience.
+// // DO NOT DUPLICATE GUIDS!
+//
+// To Send an Event:
+// -----------------
+// // Create Payload and send
+// MyEvent evt;
+// GlobalEventQueue::GetInstance ().SendEvent (evt);
+//
+// LISTENING
+// ==========
+//
+// STATIC FUNCTION: To Listen For An Event:
+// ----------------------------------------
+//
+// void MyListenFunction (const MyEvent & payload)
+// { /* do something useful */ }
+//
+// // No register that function, create delegate, register delegate with EventQueue
+// // Lifetime of delegate is important.
+// StaticFunctionEventHandler<MyEvent> myEventDelegate (&MyListenFunction);
+// GlobalEventQueue::GetInstance ()->AddHandler (&myEventDelegate);
+//
+//
+// CLASS LISTENER: To Listen on an instance of a class:
+// ----------------------------------------------------
+// class MyClass
+// {
+//      // This method will get called, always called HandleEvent
+//      void HandleEvent(const MyEvent & payload);
+//
+//      MyClass()
+//      {
+//          // Hookup to listen can be anywhere but here it's in the ctor.
+//          GlobalEventQueue::GetInstance ()->AddHandler (m_myDelegate.SetObject (this));
+//      }
+//
+//      ~MyClass()
+//      {
+//          // Stop listening.
+//          GlobalEventQueue::GetInstance ()->RemoveHandler (m_myDelegate);
+//      }
+//
+//      // Delegate is a member of the class.
+//      ClassBasedEventHandler<MyEvent,MyClass> m_myDelegate;
+// };
+
+// GUID definition for a new event.
+//
+// There is a tool to compute these, run the tool on the name of your
+// message and insert the hash/type combination in your header file.
+// This defines the EventId for your event payload (struct)
+// Use this for events that do not require a destructor.
+#define REGISTER_EVENT_ID(HASHH, HASHL , TYPE)                  \
+namespace UnityEventQueue                                      \
+{                                                              \
+    template<>                                                 \
+    inline const EventId GetEventId< TYPE > ()                 \
+    {                                                          \
+        return EventId(HASHH,HASHL) ;                          \
+    }                                                          \
+}
+
+#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
+// GUID definition for a new event with a destructor.
+//
+// If your event payload requires a destructor. Define:
+//
+// void Destroy()
+//
+// Which should be a method on your payload and then use this macro.
+// If your event
+// can guarantee that someone is listening before you fire
+// your first event this is all you have to do.
+//
+// However if you do not know if someone is listening when you
+// fire your first event you will need to call RegisterCleanup
+// somewhere to ensure your events get cleaned up properly.
+//
+// There is a tool to compute these, run the tool on the name of your
+// payload and insert the hash/type combination in your header file.
+#define REGISTER_EVENT_ID_WITH_CLEANUP(HASHH, HASHL, TYPE)                             \
+namespace UnityEventQueue                                                            \
+{                                                                                    \
+    typedef StaticFunctionEventHandler< TYPE > DestructorMethod_##HASHH##HASHL;      \
+                                                                                     \
+    template<>                                                                       \
+    inline void GenericDestructorMethodForType< TYPE > ( const TYPE & eventPayload ) \
+    { const_cast<TYPE&>(eventPayload).Destroy(); }                                   \
+                                                                                     \
+    template<>                                                                       \
+    inline EventHandler * GetEventDestructor< TYPE >()                               \
+    {                                                                                \
+        static DestructorMethod_##HASHH##HASHL g_Destructor(&GenericDestructorMethodForType< TYPE >); \
+        return &g_Destructor;                                                        \
+    }                                                                                \
+}                                                                                    \
+REGISTER_EVENT_ID(HASHH,HASHL,TYPE)
+
+#endif
+
+namespace UnityEventQueue
+{
+    // EventId - GUID
+    //
+    // To facilitate custom events the EventId object must be a full fledged GUID
+    // to ensure cross plugin uniqueness constraints.
+    //
+    // Template specialization is used to produce a means of looking up an
+    // EventId from it's payload type at compile time. The net result should compile
+    // down to passing around the GUID.
+    //
+    // REGISTER_EVENT_ID should be placed in
+    // the header file of any payload definition OUTSIDE of all namespaces (all EventIds live
+    // in the UnityEventQueue namespace by default) The payload structure and the registration ID are all that
+    // is required to expose the event to other systems.
+    //
+    // There is a tool to generate registration macros for EventIds.
+    struct EventId
+    {
+    public:
+        EventId(unsigned long long high, unsigned long long low)
+            : mGUIDHigh(high)
+            , mGUIDLow(low)
+        {}
+
+        EventId(const EventId & other)
+        {
+            mGUIDHigh = other.mGUIDHigh;
+            mGUIDLow  = other.mGUIDLow;
+        }
+
+        EventId & operator=(const EventId & other)
+        {
+            mGUIDHigh = other.mGUIDHigh;
+            mGUIDLow  = other.mGUIDLow;
+            return *this;
+        }
+
+        bool Equals(const EventId & other)   const      {   return mGUIDHigh == other.mGUIDHigh && mGUIDLow == other.mGUIDLow;  }
+        bool LessThan(const EventId & other) const      {   return mGUIDHigh < other.mGUIDHigh || (mGUIDHigh == other.mGUIDHigh && mGUIDLow < other.mGUIDLow);  }
+
+        unsigned long long mGUIDHigh;
+        unsigned long long mGUIDLow;
+    };
+    inline bool operator==(const EventId & left, const EventId & right) {  return left.Equals(right);      }
+    inline bool operator!=(const EventId & left, const EventId & right) {  return !left.Equals(right);     }
+    inline bool operator<(const EventId & left, const EventId & right) {  return left.LessThan(right);    }
+    inline bool operator>(const EventId & left, const EventId & right) {  return right.LessThan(left);    }
+    inline bool operator>=(const EventId & left, const EventId & right) {  return !operator<(left, right); }
+    inline bool operator<=(const EventId & left, const EventId & right) {  return !operator>(left, right); }
+    // Generic Version of GetEventId to allow for specialization
+    //
+    // If you get errors about return values related to this method
+    // then you have forgotten to include REGISTER_EVENT_ID() for your
+    // payload / event. This method should never be compiled, ever.
+    template<typename T> const EventId GetEventId();
+    class EventQueue;
+    class EventHandler;
+
+#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
+    // Generic version retrieving a classes destructor.
+    // Any class that does not specialize this will not define a destructor.
+    template<typename T> EventHandler * GetEventDestructor() { return (EventHandler*)NULL; }
+
+    // This is a static method that helps us call a meaningful method on the event
+    // itself improving the cleanliness of the EQ design.
+    template<typename T> void GenericDestructorMethodForType(const T & /*eventPayload*/) {}
+#endif
+
+    // ====================================================================
+    // ADAPTER / DELEGATE - This is the base interface that the EventQueue
+    // uses to know about listeners for events.
+    //
+    // DO NOT USE DIRECTLY!
+    //
+    // Use the StaticFunction of ClassBased EventHandlers to build
+    // adapters to your systems and empower them to receive events.
+    class EventHandler
+    {
+    public:
+        EventHandler()  : m_Next(0) {}
+        virtual ~EventHandler()     {}
+        // This actually kicks the event to the handler function or object.
+        virtual void HandleEvent(EventId & id, void * data) = 0;
+        // This is required when registering this handler
+        virtual EventId HandlerEventId()                       = 0;
+#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
+        // This is required when registering this handler
+        virtual EventHandler * GetMyEventDestructor()          = 0;
+#endif
+        // Internal, do not use, required for walking and calling handlers
+        EventHandler * GetNext()                 { return m_Next; }
+    private:
+        // Intrusive list holding a linked list of handlers for this EventId
+        // Exists to avoid allocations - Do Not Touch.
+        friend class EventHandlerList;
+        EventHandler * m_Next;
+    };
+
+    // ====================================================================
+    // CLASS DELEGATE - Classes can be the target of events.
+    //
+    // Event handlers are the endpoints of the system. To Unity all
+    // event endpoints look like a single virtual function call.
+    //
+    // This adapter will call the HandleEvent( EVENTTYPE & ) method
+    // on the object specified when an event is triggered.
+    template<typename EVENTTYPE, typename OBJECTTYPE>
+    class ClassBasedEventHandler : public EventHandler
+    {
+    public:
+        ClassBasedEventHandler(OBJECTTYPE * handler = NULL) : m_Handler(handler) {}
+
+        // The actual adapter method, calls into the registered object.
+        virtual void HandleEvent(EventId & id, void * data)
+        { (void)id; m_Handler->HandleEvent(*static_cast<EVENTTYPE*>(data));   }
+
+        // Boilerplate required when registering this handler.
+        virtual EventId HandlerEventId()
+        { return GetEventId<EVENTTYPE>(); }
+
+#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
+        // Required boilerplate. Used during registration of this object.
+        virtual EventHandler * GetMyEventDestructor()
+        { return GetEventDestructor<EVENTTYPE>(); }
+#endif
+
+        ClassBasedEventHandler<EVENTTYPE, OBJECTTYPE> *
+        SetObject(OBJECTTYPE * handler)
+        { m_Handler = handler; return this; }
+
+#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
+        OBJECTTYPE * GetHandler()
+        { return m_Handler; }
+#endif
+    protected:
+        OBJECTTYPE * m_Handler;
+    };
+
+    // ====================================================================
+    // FUNCTION DELEGATE - Static functions can be event handlers.
+    //
+    // Event handlers are the endpoints of the system. To Unity all
+    // event endpoints look like a single virtual function call.
+    //
+    // This object wraps a static function turning it into an event endpoint
+    // much like a C# delegate does.
+    // The wrapped function will be called when the event is triggered
+    template<typename EVENTTYPE>
+    class StaticFunctionEventHandler : public EventHandler
+    {
+    public:
+        typedef void (*HandlerFunction)(const EVENTTYPE & payload);
+
+        StaticFunctionEventHandler(HandlerFunction handlerCallback) : m_Handler(handlerCallback)  {}
+
+        virtual void HandleEvent(EventId & id, void * data)
+        { (void)id; m_Handler(*static_cast<EVENTTYPE*>(data)); }
+
+        // Required boilerplate. Used during registration of this object.
+        virtual EventId HandlerEventId()
+        { return GetEventId<EVENTTYPE>(); }
+
+#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
+        // Required boilerplate. Used during registration of this object.
+        virtual EventHandler * GetMyEventDestructor()
+        { return GetEventDestructor<EVENTTYPE>(); }
+#endif
+
+    protected:
+        HandlerFunction m_Handler;
+    };
+
+    // ============================================================
+    // Some built in event types for adding removing event handlers
+    // from secondary threads. Use these instead of calling AddHandler
+    // from a secondary thread.
+    struct AddEventHandler
+    {
+        AddEventHandler(EventHandler * handler) : m_Handler(handler) {}
+        EventHandler * m_Handler;
+    };
+
+    struct RemoveEventHandler
+    {
+        RemoveEventHandler(EventHandler * handler) : m_Handler(handler) {}
+        EventHandler * m_Handler;
+    };
+
+    // ============================================================
+    // The Event Queue is a lock free multiple write single read
+    // deferred event system. It uses GUIDs to map payloads to
+    // event handler delegates. The system has some
+    // templates to make registering for events fairly painless
+    // but takes care to try to keep template cost very low.
+    //
+    // NOTE: payloads should be very very small and never allocate
+    //       or free memory since they can and will be passed across
+    //       dll boundaries.
+    //
+    // There is a hard limit of kMaxEventQueueEventSize bytes for any
+    // payload being passed through this system but payloads that are
+    // this big are probably being handled improperly.
+    UNITY_DECLARE_INTERFACE(IUnityEventQueue)
+    {
+    public:
+        // size of 8196 required for PS4 system events
+        #define kMaxEventQueueEventSize 8196+sizeof(EventId)
+
+        virtual ~IUnityEventQueue() {
+        }
+
+        // The primary entry point for firing any
+        // event through the system. The templated
+        // version is simply syntatic sugar for extracting
+        // the EventId from the event object.
+        //
+        // This can be called from any thread.
+        template<typename T>
+        void SendEvent(T & payload)
+        {
+            // Ensure we never fire an event that we can't handle size wise.
+            Assert(sizeof(T) <= (kMaxEventQueueEventSize - sizeof(EventId)));
+
+            // NOTE: Keep this small to avoid code bloat.
+            //       every line of code in here should be scrutinized
+            //       as this and GetEventId could easily be sources
+            //       of bloat if allowed to grow.
+            SendEventImpl(UnityEventQueue::GetEventId<T>(), (unsigned char*)(&payload), sizeof(T));
+        }
+
+#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
+        // Some events want to have a destructor.
+        //
+        // You do this by creating a public Destroy()
+        // method on your Event payload. You then
+        // register the event with REGISTER_EVENT_ID_WITH_CLEANUP
+        //
+        // If your event will have someone listening to it right away
+        // then you do not need to do anything else.
+        //
+        // However, if there is a danger that your event will be fired
+        // before someone starts listening for it then you must
+        // call this method somewhere. This will manually register your
+        // class for cleanup. There is no harm in calling this even
+        // if it is not required. If in doubt and your event payload
+        // requires some form of destruction, call this method!
+        template<typename T>
+        void RegisterCleanup(T & payload)
+        {
+            EventHandler * eh = UnityEventQueue::GetEventDestructor<T>();
+            if (eh != NULL)
+                SetCleanupImpl(eh);
+        }
+
+#endif
+
+        // These are not thread safe and must be done on the same thread
+        // as the dispatch thread. Doing otherwise risks race conditions.
+        // Fire the add handler / remove handler event if you need to
+        // schedule this from a different thread.
+        virtual void AddHandler(EventHandler * handler)    = 0;
+        virtual void RemoveHandler(EventHandler * handler) = 0;
+    protected:
+        virtual void SendEventImpl(EventId id, unsigned char * data, int size) = 0;
+
+#if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
+        // This is an event destructor. You can register one of these
+        // per event type. This allows events to manage resource if
+        // they absolutely must. In general you should avoid handling
+        // resources in events as events usually imply cross thread activity.
+        virtual void SetCleanupImpl(EventHandler * handler) = 0;
+#endif
+    };
+}
+
+REGISTER_EVENT_ID(0x19D736400584B24BULL, 0x98B9EFBE26D3F3C9ULL, AddEventHandler)
+REGISTER_EVENT_ID(0x8D4A317C4F577F4AULL, 0x851D6E457566A905ULL, RemoveEventHandler)
+
+UNITY_REGISTER_INTERFACE_GUID_IN_NAMESPACE(0x9959C347F5AE374DULL, 0x9BADE6FC8EF49E7FULL, IUnityEventQueue, UnityEventQueue)

+ 64 - 0
unity_ios/Classes/Unity/IUnityGraphics.h

@@ -0,0 +1,64 @@
+// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
+//
+// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
+//
+// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
+
+#pragma once
+#include "IUnityInterface.h"
+
+// Has to match the GfxDeviceRenderer enum
+typedef enum UnityGfxRenderer
+{
+    //kUnityGfxRendererOpenGL            =  0, // Legacy OpenGL, removed
+    //kUnityGfxRendererD3D9              =  1, // Direct3D 9, removed
+    kUnityGfxRendererD3D11             =  2, // Direct3D 11
+    kUnityGfxRendererNull              =  4, // "null" device (used in batch mode)
+    //kUnityGfxRendererOpenGLES20        =  8, // OpenGL ES 2.0, removed
+    kUnityGfxRendererOpenGLES30        = 11, // OpenGL ES 3.0
+    //kUnityGfxRendererGXM               = 12, // PlayStation Vita, removed
+    kUnityGfxRendererPS4               = 13, // PlayStation 4
+    kUnityGfxRendererXboxOne           = 14, // Xbox One
+    kUnityGfxRendererMetal             = 16, // iOS Metal
+    kUnityGfxRendererOpenGLCore        = 17, // OpenGL core
+    kUnityGfxRendererD3D12             = 18, // Direct3D 12
+    kUnityGfxRendererVulkan            = 21, // Vulkan
+    kUnityGfxRendererNvn               = 22, // Nintendo Switch NVN API
+    kUnityGfxRendererXboxOneD3D12      = 23,  // MS XboxOne Direct3D 12
+    kUnityGfxRendererGameCoreXboxOne   = 24, // GameCore Xbox One
+    kUnityGfxRendererGameCoreXboxSeries  = 25, // GameCore XboxSeries
+    kUnityGfxRendererPS5               = 26, // PS5
+    kUnityGfxRendererPS5NGGC           = 27, // PS5 NGGC
+
+    kUnityGfxRendererNvn2              = 29  // Switch2
+} UnityGfxRenderer;
+
+typedef enum UnityGfxDeviceEventType
+{
+    kUnityGfxDeviceEventInitialize     = 0,
+    kUnityGfxDeviceEventShutdown       = 1,
+    kUnityGfxDeviceEventBeforeReset    = 2,
+    kUnityGfxDeviceEventAfterReset     = 3,
+} UnityGfxDeviceEventType;
+
+typedef void (UNITY_INTERFACE_API * IUnityGraphicsDeviceEventCallback)(UnityGfxDeviceEventType eventType);
+
+// Should only be used on the rendering thread unless noted otherwise.
+UNITY_DECLARE_INTERFACE(IUnityGraphics)
+{
+    UnityGfxRenderer(UNITY_INTERFACE_API * GetRenderer)();  // Thread safe
+
+    // This callback will be called when graphics device is created, destroyed, reset, etc.
+    // It is possible to miss the kUnityGfxDeviceEventInitialize event in case plugin is loaded at a later time,
+    // when the graphics device is already created.
+    void(UNITY_INTERFACE_API * RegisterDeviceEventCallback)(IUnityGraphicsDeviceEventCallback callback);
+    void(UNITY_INTERFACE_API * UnregisterDeviceEventCallback)(IUnityGraphicsDeviceEventCallback callback);
+    int(UNITY_INTERFACE_API * ReserveEventIDRange)(int count);  // reserves 'count' event IDs. Plugins should use the result as a base index when issuing events back and forth to avoid event id clashes.
+};
+UNITY_REGISTER_INTERFACE_GUID(0x7CBA0A9CA4DDB544ULL, 0x8C5AD4926EB17B11ULL, IUnityGraphics)
+
+
+// Certain Unity APIs (GL.IssuePluginEvent, CommandBuffer.IssuePluginEvent) can callback into native plugins.
+// Provide them with an address to a function of this signature.
+typedef void (UNITY_INTERFACE_API * UnityRenderingEvent)(int eventId);
+typedef void (UNITY_INTERFACE_API * UnityRenderingEventAndData)(int eventId, void* data);

+ 117 - 0
unity_ios/Classes/Unity/IUnityGraphicsMetal.h

@@ -0,0 +1,117 @@
+// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
+//
+// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
+//
+// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
+
+#pragma once
+#include "IUnityInterface.h"
+
+#ifndef __OBJC__
+    #error metal plugin is objc code.
+#endif
+#ifndef __clang__
+    #error only clang compiler is supported.
+#endif
+
+@class NSBundle;
+@protocol MTLDevice;
+@protocol MTLCommandQueue;
+@protocol MTLCommandBuffer;
+@protocol MTLCommandEncoder;
+@protocol MTLTexture;
+@class MTLRenderPassDescriptor;
+
+UNITY_DECLARE_INTERFACE(IUnityGraphicsMetalV2)
+{
+    // V2
+
+    // Unity has it's own internal logic to happen on command buffer commit, so if you need to commit the current command buffer
+    //   you need to call this function.
+    // It will just commit the current buffer and returns it (so it can be waited on by the caller code)
+    id<MTLCommandBuffer>(UNITY_INTERFACE_API * CommitCurrentCommandBuffer)();
+
+    // returns Unity Metal Command Queue
+    id<MTLCommandQueue>(UNITY_INTERFACE_API * CommandQueue)();
+
+    // V1
+
+    NSBundle* (UNITY_INTERFACE_API * MetalBundle)();
+    id<MTLDevice>(UNITY_INTERFACE_API * MetalDevice)();
+
+    id<MTLCommandBuffer>(UNITY_INTERFACE_API * CurrentCommandBuffer)();
+
+    // for custom rendering support there are two scenarios:
+    // you want to use current in-flight MTLCommandEncoder (NB: it might be nil)
+    id<MTLCommandEncoder>(UNITY_INTERFACE_API * CurrentCommandEncoder)();
+    // or you might want to create your own encoder.
+    // In that case you should end unity's encoder before creating your own and end yours before returning control to unity
+    void(UNITY_INTERFACE_API * EndCurrentCommandEncoder)();
+
+    // returns MTLRenderPassDescriptor used to create current MTLCommandEncoder
+    MTLRenderPassDescriptor* (UNITY_INTERFACE_API * CurrentRenderPassDescriptor)();
+
+    // converting trampoline UnityRenderBufferHandle into native RenderBuffer
+    UnityRenderBuffer(UNITY_INTERFACE_API * RenderBufferFromHandle)(void* bufferHandle);
+
+    // access to RenderBuffer's texure
+    // NB: you pass here *native* RenderBuffer, acquired by calling (C#) RenderBuffer.GetNativeRenderBufferPtr
+    // AAResolvedTextureFromRenderBuffer will return nil in case of non-AA RenderBuffer or if called for depth RenderBuffer
+    // StencilTextureFromRenderBuffer will return nil in case of no-stencil RenderBuffer or if called for color RenderBuffer
+    id<MTLTexture>(UNITY_INTERFACE_API * TextureFromRenderBuffer)(UnityRenderBuffer buffer);
+    id<MTLTexture>(UNITY_INTERFACE_API * AAResolvedTextureFromRenderBuffer)(UnityRenderBuffer buffer);
+    id<MTLTexture>(UNITY_INTERFACE_API * StencilTextureFromRenderBuffer)(UnityRenderBuffer buffer);
+};
+UNITY_REGISTER_INTERFACE_GUID(0xF58857784FEF46ECULL, 0x9DB7A8803B87DA3DULL, IUnityGraphicsMetalV2)
+
+
+UNITY_DECLARE_INTERFACE(IUnityGraphicsMetalV1)
+{
+    NSBundle* (UNITY_INTERFACE_API * MetalBundle)();
+    id<MTLDevice>(UNITY_INTERFACE_API * MetalDevice)();
+
+    id<MTLCommandBuffer>(UNITY_INTERFACE_API * CurrentCommandBuffer)();
+
+    // for custom rendering support there are two scenarios:
+    // you want to use current in-flight MTLCommandEncoder (NB: it might be nil)
+    id<MTLCommandEncoder>(UNITY_INTERFACE_API * CurrentCommandEncoder)();
+    // or you might want to create your own encoder.
+    // In that case you should end unity's encoder before creating your own and end yours before returning control to unity
+    void(UNITY_INTERFACE_API * EndCurrentCommandEncoder)();
+
+    // returns MTLRenderPassDescriptor used to create current MTLCommandEncoder
+    MTLRenderPassDescriptor* (UNITY_INTERFACE_API * CurrentRenderPassDescriptor)();
+
+    // converting trampoline UnityRenderBufferHandle into native RenderBuffer
+    UnityRenderBuffer(UNITY_INTERFACE_API * RenderBufferFromHandle)(void* bufferHandle);
+
+    // access to RenderBuffer's texture
+    // NB: you pass here *native* RenderBuffer, acquired by calling (C#) RenderBuffer.GetNativeRenderBufferPtr
+    // AAResolvedTextureFromRenderBuffer will return nil in case of non-AA RenderBuffer or if called for depth RenderBuffer
+    // StencilTextureFromRenderBuffer will return nil in case of no-stencil RenderBuffer or if called for color RenderBuffer
+    id<MTLTexture>(UNITY_INTERFACE_API * TextureFromRenderBuffer)(UnityRenderBuffer buffer);
+    id<MTLTexture>(UNITY_INTERFACE_API * AAResolvedTextureFromRenderBuffer)(UnityRenderBuffer buffer);
+    id<MTLTexture>(UNITY_INTERFACE_API * StencilTextureFromRenderBuffer)(UnityRenderBuffer buffer);
+};
+UNITY_REGISTER_INTERFACE_GUID(0x29F8F3D03833465EULL, 0x92138551C15D823DULL, IUnityGraphicsMetalV1)
+
+
+// deprecated: please use versioned interface above
+
+UNITY_DECLARE_INTERFACE(IUnityGraphicsMetal)
+{
+    NSBundle* (UNITY_INTERFACE_API * MetalBundle)();
+    id<MTLDevice>(UNITY_INTERFACE_API * MetalDevice)();
+
+    id<MTLCommandBuffer>(UNITY_INTERFACE_API * CurrentCommandBuffer)();
+    id<MTLCommandEncoder>(UNITY_INTERFACE_API * CurrentCommandEncoder)();
+    void(UNITY_INTERFACE_API * EndCurrentCommandEncoder)();
+    MTLRenderPassDescriptor* (UNITY_INTERFACE_API * CurrentRenderPassDescriptor)();
+
+    UnityRenderBuffer(UNITY_INTERFACE_API * RenderBufferFromHandle)(void* bufferHandle);
+
+    id<MTLTexture>(UNITY_INTERFACE_API * TextureFromRenderBuffer)(UnityRenderBuffer buffer);
+    id<MTLTexture>(UNITY_INTERFACE_API * AAResolvedTextureFromRenderBuffer)(UnityRenderBuffer buffer);
+    id<MTLTexture>(UNITY_INTERFACE_API * StencilTextureFromRenderBuffer)(UnityRenderBuffer buffer);
+};
+UNITY_REGISTER_INTERFACE_GUID(0x992C8EAEA95811E5ULL, 0x9A62C4B5B9876117ULL, IUnityGraphicsMetal)

+ 206 - 0
unity_ios/Classes/Unity/IUnityInterface.h

@@ -0,0 +1,206 @@
+// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
+//
+// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
+//
+// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
+
+#pragma once
+
+// Unity native plugin API
+// Compatible with C99
+
+#if defined(__CYGWIN32__)
+    #define UNITY_INTERFACE_API __stdcall
+    #define UNITY_INTERFACE_EXPORT __declspec(dllexport)
+#elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(WINAPI_FAMILY)
+    #define UNITY_INTERFACE_API __stdcall
+    #define UNITY_INTERFACE_EXPORT __declspec(dllexport)
+#elif defined(__MACH__) || defined(__ANDROID__) || defined(__linux__) || defined(LUMIN)
+    #define UNITY_INTERFACE_API
+    #define UNITY_INTERFACE_EXPORT __attribute__ ((visibility ("default")))
+#else
+    #define UNITY_INTERFACE_API
+    #define UNITY_INTERFACE_EXPORT
+#endif
+
+/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// IUnityInterface is a registry of interfaces we choose to expose to plugins.
+//
+// USAGE:
+// ---------
+// To retrieve an interface a user can do the following from a plugin, assuming they have the header file for the interface:
+//
+// IMyInterface * ptr = registry->Get<IMyInterface>();
+/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+// Unity Interface GUID
+// Ensures global uniqueness.
+//
+// Template specialization is used to produce a means of looking up a GUID from its interface type at compile time.
+// The net result should compile down to passing around the GUID.
+//
+// UNITY_REGISTER_INTERFACE_GUID should be placed in the header file of any interface definition outside of all namespaces.
+// The interface structure and the registration GUID are all that is required to expose the interface to other systems.
+struct UnityInterfaceGUID
+{
+#ifdef __cplusplus
+    UnityInterfaceGUID(unsigned long long high, unsigned long long low)
+        : m_GUIDHigh(high)
+        , m_GUIDLow(low)
+    {
+    }
+
+    UnityInterfaceGUID(const UnityInterfaceGUID& other)
+    {
+        m_GUIDHigh = other.m_GUIDHigh;
+        m_GUIDLow  = other.m_GUIDLow;
+    }
+
+    UnityInterfaceGUID& operator=(const UnityInterfaceGUID& other)
+    {
+        m_GUIDHigh = other.m_GUIDHigh;
+        m_GUIDLow  = other.m_GUIDLow;
+        return *this;
+    }
+
+    bool Equals(const UnityInterfaceGUID& other)   const { return m_GUIDHigh == other.m_GUIDHigh && m_GUIDLow == other.m_GUIDLow; }
+    bool LessThan(const UnityInterfaceGUID& other) const { return m_GUIDHigh < other.m_GUIDHigh || (m_GUIDHigh == other.m_GUIDHigh && m_GUIDLow < other.m_GUIDLow); }
+#endif
+    unsigned long long m_GUIDHigh;
+    unsigned long long m_GUIDLow;
+};
+#ifdef __cplusplus
+inline bool operator==(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return left.Equals(right); }
+inline bool operator!=(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return !left.Equals(right); }
+inline bool operator<(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return left.LessThan(right); }
+inline bool operator>(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return right.LessThan(left); }
+inline bool operator>=(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return !operator<(left, right); }
+inline bool operator<=(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return !operator>(left, right); }
+#else
+typedef struct UnityInterfaceGUID UnityInterfaceGUID;
+#endif
+
+
+#ifdef __cplusplus
+    #define UNITY_DECLARE_INTERFACE(NAME) \
+    struct NAME : IUnityInterface
+
+// Generic version of GetUnityInterfaceGUID to allow us to specialize it
+// per interface below. The generic version has no actual implementation
+// on purpose.
+//
+// If you get errors about return values related to this method then
+// you have forgotten to include UNITY_REGISTER_INTERFACE_GUID with
+// your interface, or it is not visible at some point when you are
+// trying to retrieve or add an interface.
+template<typename TYPE>
+inline const UnityInterfaceGUID GetUnityInterfaceGUID();
+
+// This is the macro you provide in your public interface header
+// outside of a namespace to allow us to map between type and GUID
+// without the user having to worry about it when attempting to
+// add or retrieve and interface from the registry.
+    #define UNITY_REGISTER_INTERFACE_GUID(HASHH, HASHL, TYPE)      \
+    template<>                                                     \
+    inline const UnityInterfaceGUID GetUnityInterfaceGUID<TYPE>()  \
+    {                                                              \
+        return UnityInterfaceGUID(HASHH,HASHL);                    \
+    }
+
+// Same as UNITY_REGISTER_INTERFACE_GUID but allows the interface to live in
+// a particular namespace. As long as the namespace is visible at the time you call
+// GetUnityInterfaceGUID< INTERFACETYPE >() or you explicitly qualify it in the template
+// calls this will work fine, only the macro here needs to have the additional parameter
+    #define UNITY_REGISTER_INTERFACE_GUID_IN_NAMESPACE(HASHH, HASHL, TYPE, NAMESPACE) \
+    const UnityInterfaceGUID TYPE##_GUID(HASHH, HASHL);                               \
+    template<>                                                                        \
+    inline const UnityInterfaceGUID GetUnityInterfaceGUID< NAMESPACE :: TYPE >()      \
+    {                                                                                 \
+        return UnityInterfaceGUID(HASHH,HASHL);                                       \
+    }
+
+// These macros allow for C compatibility in user code.
+    #define UNITY_GET_INTERFACE_GUID(TYPE) GetUnityInterfaceGUID< TYPE >()
+
+
+#else
+    #define UNITY_DECLARE_INTERFACE(NAME) \
+    typedef struct NAME NAME;             \
+    struct NAME
+
+// NOTE: This has the downside that one some compilers it will not get stripped from all compilation units that
+//       can see a header containing this constant. However, it's only for C compatibility and thus should have
+//       minimal impact.
+    #define UNITY_REGISTER_INTERFACE_GUID(HASHH, HASHL, TYPE) \
+    const UnityInterfaceGUID TYPE##_GUID = {HASHH, HASHL};
+
+// In general namespaces are going to be a problem for C code any interfaces we expose in a namespace are
+// not going to be usable from C.
+    #define UNITY_REGISTER_INTERFACE_GUID_IN_NAMESPACE(HASHH, HASHL, TYPE, NAMESPACE)
+
+// These macros allow for C compatibility in user code.
+    #define UNITY_GET_INTERFACE_GUID(TYPE) TYPE##_GUID
+#endif
+
+// Using this in user code rather than INTERFACES->Get<TYPE>() will be C compatible for those places in plugins where
+// this may be needed. Unity code itself does not need this.
+#define UNITY_GET_INTERFACE(INTERFACES, TYPE) (TYPE*)INTERFACES->GetInterfaceSplit (UNITY_GET_INTERFACE_GUID(TYPE).m_GUIDHigh, UNITY_GET_INTERFACE_GUID(TYPE).m_GUIDLow);
+
+
+#ifdef __cplusplus
+struct IUnityInterface
+{
+};
+#else
+typedef void IUnityInterface;
+#endif
+
+
+typedef struct IUnityInterfaces
+{
+    // Returns an interface matching the guid.
+    // Returns nullptr if the given interface is unavailable in the active Unity runtime.
+    IUnityInterface* (UNITY_INTERFACE_API * GetInterface)(UnityInterfaceGUID guid);
+
+    // Registers a new interface.
+    void(UNITY_INTERFACE_API * RegisterInterface)(UnityInterfaceGUID guid, IUnityInterface * ptr);
+
+    // Split APIs for C
+    IUnityInterface* (UNITY_INTERFACE_API * GetInterfaceSplit)(unsigned long long guidHigh, unsigned long long guidLow);
+    void(UNITY_INTERFACE_API * RegisterInterfaceSplit)(unsigned long long guidHigh, unsigned long long guidLow, IUnityInterface * ptr);
+
+#ifdef __cplusplus
+    // Helper for GetInterface.
+    template<typename INTERFACE>
+    INTERFACE* Get()
+    {
+        return static_cast<INTERFACE*>(GetInterface(GetUnityInterfaceGUID<INTERFACE>()));
+    }
+
+    // Helper for RegisterInterface.
+    template<typename INTERFACE>
+    void Register(IUnityInterface* ptr)
+    {
+        RegisterInterface(GetUnityInterfaceGUID<INTERFACE>(), ptr);
+    }
+
+#endif
+} IUnityInterfaces;
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// If exported by a plugin, this function will be called when the plugin is loaded.
+void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces* unityInterfaces);
+// If exported by a plugin, this function will be called when the plugin is about to be unloaded.
+void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload();
+
+#ifdef __cplusplus
+}
+#endif
+
+struct RenderSurfaceBase;
+typedef struct RenderSurfaceBase* UnityRenderBuffer;
+typedef unsigned int UnityTextureID;

+ 37 - 0
unity_ios/Classes/Unity/IUnityLog.h

@@ -0,0 +1,37 @@
+// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
+//
+// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
+//
+// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
+
+#pragma once
+#include "IUnityInterface.h"
+
+/// The type of the log message
+typedef enum UnityLogType
+{
+    /// UnityLogType used for Errors.
+    kUnityLogTypeError = 0,
+    /// UnityLogType used for Warnings.
+    kUnityLogTypeWarning = 2,
+    /// UnityLogType used for regular log messages.
+    kUnityLogTypeLog = 3,
+    /// UnityLogType used for Exceptions.
+    kUnityLogTypeException = 4,
+}UnityLogType;
+
+#define UNITY_WRAP_CODE(CODE_) do { CODE_; } while (0)
+#define UNITY_LOG(PTR_, MSG_) UNITY_WRAP_CODE((PTR_)->Log(kUnityLogTypeLog, MSG_, __FILE__, __LINE__))
+#define UNITY_LOG_WARNING(PTR_, MSG_) UNITY_WRAP_CODE((PTR_)->Log(kUnityLogTypeWarning, MSG_, __FILE__, __LINE__))
+#define UNITY_LOG_ERROR(PTR_, MSG_) UNITY_WRAP_CODE((PTR_)->Log(kUnityLogTypeError, MSG_, __FILE__, __LINE__))
+
+UNITY_DECLARE_INTERFACE(IUnityLog)
+{
+    // Writes information message to Unity log.
+    // \param type type log channel type which defines importance of the message.
+    // \param message UTF-8 null terminated string.
+    // \param fileName UTF-8 null terminated string with file name of the point where message is generated.
+    // \param fileLine integer file line number of the point where message is generated.
+    void(UNITY_INTERFACE_API * Log)(UnityLogType type, const char* message, const char *fileName, const int fileLine);
+};
+UNITY_REGISTER_INTERFACE_GUID(0x9E7507fA5B444D5DULL, 0x92FB979515EA83FCULL, IUnityLog)

+ 24 - 0
unity_ios/Classes/Unity/IUnityMemoryManager.h

@@ -0,0 +1,24 @@
+// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
+//
+// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
+//
+// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
+
+#pragma once
+#include "IUnityInterface.h"
+
+#include <stdint.h>
+#include <stddef.h>
+
+typedef struct PluginAllocator UnityAllocator;
+
+UNITY_DECLARE_INTERFACE(IUnityMemoryManager)
+{
+    UnityAllocator* (UNITY_INTERFACE_API * CreateAllocator)(const char* areaName, const char* objectName);
+    void(UNITY_INTERFACE_API * DestroyAllocator)(UnityAllocator * allocator);
+
+    void* (UNITY_INTERFACE_API * Allocate)(UnityAllocator * allocator, size_t size, size_t align, const char* file, int32_t line);
+    void(UNITY_INTERFACE_API * Deallocate)(UnityAllocator * allocator, void* ptr, const char* file, int32_t line);
+    void* (UNITY_INTERFACE_API * Reallocate)(UnityAllocator * allocator, void* ptr, size_t size, size_t align, const char* file, int32_t line);
+};
+UNITY_REGISTER_INTERFACE_GUID(0xBAF9E57C61A811ECULL, 0xC5A7CC7861A811ECULL, IUnityMemoryManager)

+ 99 - 0
unity_ios/Classes/Unity/IUnityPhysicsBackendSystem.h

@@ -0,0 +1,99 @@
+// Unity Physics Backend System Native Plugin API copyright © 2025 Unity Technologies ApS
+//
+// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
+//
+// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
+
+// This interface allows a native plugin to register a custom physics backend implementation.
+// The backend receives all physics commands issued by Unity's Physics Module through a single
+// entry point function, enabling full replacement of the underlying physics SDK.
+//
+// The command dispatch model uses a flat function table indexed by command category (bits 26-29)
+// and command ID (bits 0-25). Each command is a struct inheriting from PhysicsCommands::Command
+// that carries both input parameters and output fields.
+//
+// Example: Registering a physics backend entry point (based on PhysXBackend.cpp)
+//
+//     #include "IUnityPhysicsBackendSystem.h"
+//     #include "PhysicsCommands.h"
+//     #include "PhysXPhysicsExtensionCommands.h" //include only for supporting physx specific features
+//
+//     using namespace PhysicsCommands;
+//
+//     // Per-category function binding tables
+//     FunctionBinding SDKCommands[static_cast<int>(SDK::Count)];
+//     FunctionBinding WorldCommands[static_cast<int>(World::Count)];
+//     FunctionBinding BodyCommands[static_cast<int>(Body::Count)];
+//     FunctionBinding ShapeCommands[static_cast<int>(Shape::Count)];
+//     FunctionBinding QueryCommands[static_cast<int>(Query::Count)];
+//     FunctionBinding JointCommands[static_cast<int>(Joint::Count)];
+//     FunctionBinding ArticulationCommands[static_cast<int>(Articulation::Count)];
+//
+//     //specific command bindings for PhysX specific features such as Vehicles, CharacterController and Immediate mode
+//     FunctionBinding PhysXExtCommands[static_cast<int>(PhysXExtension::Count)];
+// 
+//     // The single entry point that dispatches all commands by category
+//     static void ProcessCommand(void* sdkObject, const Context& ctx, uint32_t cmdFunc, Command& c)
+//     {
+//         const uint32_t commandType = cmdFunc & kFullMask;
+//         const int cmdId = cmdFunc & kReverseFullMask;
+//
+//         switch (commandType)
+//         {
+//             case kSDKFunctionMask:          SDKCommands[cmdId](sdkObject, ctx, c);          break;
+//             case kWorldFunctionMask:        WorldCommands[cmdId](sdkObject, ctx, c);        break;
+//             case kBodyFunctionMask:         BodyCommands[cmdId](sdkObject, ctx, c);         break;
+//             case kShapeFunctionMask:        ShapeCommands[cmdId](sdkObject, ctx, c);        break;
+//             case kQueryFunctionMask:        QueryCommands[cmdId](sdkObject, ctx, c);        break;
+//             case kJointFunctionMask:        JointCommands[cmdId](sdkObject, ctx, c);        break;
+//             case kArticulationFunctionMask: ArticulationCommands[cmdId](sdkObject, ctx, c); break;
+//             case kPhysXExtensionMask:       PhysXExtCommands[cmdId](sdkObject, ctx, c); break;
+//             default: break;
+//         }
+//     }
+//
+//     // During plugin load, register individual command handlers into the binding tables,
+//     // then register the entry point with Unity:
+//
+//     bool s_HasRegistered = false;
+//     extern "C" void UNITY_INTERFACE_EXPORT UnityPluginLoad(IUnityInterfaces* unityInterfaces)
+//     {
+//         if(s_HasRegistered)
+//             return;
+// 
+//         auto* physicsBackend = unityInterfaces->Get<IUnityPhysicsBackendSystem>();
+//
+//         // Initialize all slots to a safe default, then register each command handler:
+//         // SDKCommands[static_cast<int>(SDK::InitializeSdk)] = MyInitializeSdk;
+//         // WorldCommands[static_cast<int>(World::CreateWorld)] = MyCreateWorld;
+//         // ... etc.
+//         // Please note that all commands should be initialized before calling Register.
+//         // Furthermore SDK::InitializeSdk and SDK::GetIntegrationInfo need to provide valid data for registration to be successful.
+//         s_HasRegistered = physicsBackend->Register(reinterpret_cast<BackendEntryPoint>(ProcessCommand));
+//     }
+
+#pragma once
+#include "IUnityInterface.h"
+
+namespace PhysicsCommands
+{
+    typedef struct Context UnityPhysicsContext;
+    typedef struct Command UnityPhysicsCommand;
+}
+
+// Function signature for the physics backend entry point.
+// sdkObject  — opaque handle to the physics SDK instance.
+// ctx        — provides the current world and body handles for the command being dispatched.
+// cmdFunc    — encoded command identifier: upper bits select the category, lower bits select the command index.
+// c          — reference to the command data struct (cast to the appropriate type based on cmdFunc).
+typedef void (*BackendEntryPoint)(void* sdkObject, const PhysicsCommands::Context& ctx, const uint32_t cmdFunc, PhysicsCommands::Command& c);
+
+// Interface for registering a custom physics backend with Unity's Physics Module.
+// A plugin calls Register() with its entry point function to take over all physics command processing.
+UNITY_DECLARE_INTERFACE(IUnityPhysicsBackendSystem)
+{
+    // Registers the backend entry point. Multiple backends can be registered, but each must have a unique ID.
+    // Returns true if registration succeeded.
+    bool(UNITY_INTERFACE_API * Register)(BackendEntryPoint entryPoint);
+};
+UNITY_REGISTER_INTERFACE_GUID(0xED2B16A043DE39F8ULL, 0x924E3DAB294216EAULL, IUnityPhysicsBackendSystem)

+ 511 - 0
unity_ios/Classes/Unity/IUnityProfiler.h

@@ -0,0 +1,511 @@
+// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
+//
+// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
+//
+// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
+
+#pragma once
+#include "IUnityInterface.h"
+
+#include <stdint.h>
+
+// Unity Profiler Native plugin API provides an ability to register callbacks for Unity Profiler events.
+// The basic functionality includes:
+// 1. Ability to create a Unity Profiler Marker.
+// 2. Begin and end sample.
+// 3. Register a thread for profiling.
+// 4. Obtain an information if profiler is available and enabled.
+//
+//  Usage example:
+//
+//  #include <IUnityInterface.h>
+//  #include <IUnityProfiler.h>
+//
+//  static IUnityProfiler* s_UnityProfiler = NULL;
+//  static const UnityProfilerMarkerDesc* s_MyPluginMarker = NULL;
+//  static bool s_IsDevelopmentBuild = false;
+//
+//  static void MyPluginWorkMethod()
+//  {
+//      if (s_IsDevelopmentBuild)
+//          s_UnityProfiler->BeginSample(s_MyPluginMarker);
+//
+//      // Code I want to see in Unity Profiler as "MyPluginMethod".
+//      // ...
+//
+//      if (s_IsDevelopmentBuild)
+//          s_UnityProfiler->EndSample(s_MyPluginMarker);
+//  }
+//
+//  extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces* unityInterfaces)
+//  {
+//      s_UnityProfiler = unityInterfaces->Get<IUnityProfiler>();
+//      if (s_UnityProfiler == NULL)
+//          return;
+//      s_IsDevelopmentBuild = s_UnityProfiler->IsAvailable() != 0;
+//      s_UnityProfiler->CreateMarker(&s_MyPluginMarker, "MyPluginMethod", kUnityProfilerCategoryOther, kUnityProfilerMarkerFlagDefault, 0);
+//  }
+//
+//  extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload()
+//  {
+//  }
+
+
+typedef uint32_t UnityProfilerMarkerId;
+
+enum UnityBuiltinProfilerCategory_
+{
+    kUnityProfilerCategoryRender = 0,
+    kUnityProfilerCategoryScripts = 1,
+    kUnityProfilerCategoryManagedJobs = 2,
+    kUnityProfilerCategoryBurstJobs = 3,
+    kUnityProfilerCategoryGUI = 4,
+    kUnityProfilerCategoryPhysics = 5,
+    kUnityProfilerCategoryAnimation = 6,
+    kUnityProfilerCategoryAI = 7,
+    kUnityProfilerCategoryAudio = 8,
+    kUnityProfilerCategoryAudioJob = 9,
+    kUnityProfilerCategoryAudioUpdateJob = 10,
+    kUnityProfilerCategoryVideo = 11,
+    kUnityProfilerCategoryParticles = 12,
+    kUnityProfilerCategoryGi = 13,
+    kUnityProfilerCategoryNetwork = 14,
+    kUnityProfilerCategoryLoading = 15,
+    kUnityProfilerCategoryOther = 16,
+    kUnityProfilerCategoryGC = 17,
+    kUnityProfilerCategoryVSync = 18,
+    kUnityProfilerCategoryOverhead = 19,
+    kUnityProfilerCategoryPlayerLoop = 20,
+    kUnityProfilerCategoryDirector = 21,
+    kUnityProfilerCategoryVR = 22,
+    kUnityProfilerCategoryAllocation = 23, kUnityProfilerCategoryMemory = 23,
+    kUnityProfilerCategoryInternal = 24,
+    kUnityProfilerCategoryFileIO = 25,
+    kUnityProfilerCategoryUISystemLayout = 26,
+    kUnityProfilerCategoryUISystemRender = 27,
+    kUnityProfilerCategoryVFX = 28,
+    kUnityProfilerCategoryBuildInterface = 29,
+    kUnityProfilerCategoryInput = 30,
+    kUnityProfilerCategoryVirtualTexturing = 31,
+    kUnityProfilerCategoryGPU = 32,
+    kUnityProfilerCategoryPhysics2D = 33,
+    kUnityProfilerCategoryNetworkOperations = 34,
+    kUnityProfilerCategoryUIDetails = 35,
+    kUnityProfilerCategoryDebug = 36,
+    kUnityProfilerCategoryJobs = 37,
+    kUnityProfilerCategoryText = 38,
+};
+typedef uint16_t UnityProfilerCategoryId;
+
+typedef struct UnityProfilerCategoryDesc
+{
+    // Incremental category index.
+    UnityProfilerCategoryId id;
+    // Reserved.
+    uint16_t reserved0;
+    // Internally associated category color which is in 0xRRGGBBAA format.
+    uint32_t rgbaColor;
+    // NULL-terminated string which is associated with the category.
+    const char* name;
+} UnityProfilerCategoryDesc;
+
+#define GET_UNITY_PROFILER_MARKER_VERBOSITY(MARKER_FLAGS) ((MARKER_FLAGS) & (7 << 10))
+
+enum UnityProfilerMarkerFlag_
+{
+    kUnityProfilerMarkerFlagDefault = 0,
+
+    kUnityProfilerMarkerFlagScriptUser = 1 << 1,         // Markers created with C# API.
+    kUnityProfilerMarkerFlagScriptInvoke = 1 << 5,       // Runtime invocations with ScriptingInvocation::Invoke.
+    kUnityProfilerMarkerFlagScriptEnterLeave = 1 << 6,   // Deep profiler.
+
+    kUnityProfilerMarkerFlagAvailabilityEditor = 1 << 2, // Editor-only marker, doesn't present in dev and non-dev players.
+    kUnityProfilerMarkerFlagAvailabilityNonDev = 1 << 3, // Non-development marker, is present everywhere including release builds.
+
+    kUnityProfilerMarkerFlagWarning = 1 << 4,            // Indicates undesirable, performance-wise suboptimal code path.
+
+    kUnityProfilerMarkerFlagCounter = 1 << 7,            // Marker is also used as a counter.
+
+    kUnityProfilerMarkerFlagSampleGPU = 1 << 8,          // Indicates that the marker can be used for GPU sampling
+
+    // Bits 10-12 for verbosity levels. Allows to filter markers during visualization.
+    // Use GET_UNITY_PROFILER_MARKER_VERBOSITY() to extract the verbosity level from the flags.
+    // Set only ONE of these levels for a given marker or their bits will conflict.
+    kUnityProfilerMarkerFlagVerbosityDebug = 1 << 10,    // Internal debug markers - e.g. JobSystem Idle.
+    kUnityProfilerMarkerFlagVerbosityInternal = 2 << 10, // Internal markers - e.g. Mutex/semaphore waits.
+    kUnityProfilerMarkerFlagVerbosityExternal = 3 << 10, // Marker should be echoed to any attached external profilers (such as Superluminal) even if they normally wouldn't capture it. This is usually applied to markers which have additional context that might be useful in those tools
+    kUnityProfilerMarkerFlagVerbosityAdvanced = 4 << 10, // Markers which are useful for advanced users - e.g. Loading.
+
+    // Marker which was created with a recorder to make an early binding.
+    // If we create marker with the same name later, we just pick and initialized this one.
+    // In this way we can setup callback pointers for dynamic markers.
+    kUnityProfilerMarkerFlagPrecreated = 1 << 15
+};
+typedef uint16_t UnityProfilerMarkerFlags;
+
+enum UnityProfilerMarkerEventType_
+{
+    kUnityProfilerMarkerEventTypeBegin = 0,
+    kUnityProfilerMarkerEventTypeEnd = 1,
+    kUnityProfilerMarkerEventTypeSingle = 2
+};
+typedef uint16_t UnityProfilerMarkerEventType;
+
+typedef struct UnityProfilerMarkerDesc
+{
+    // Per-marker callback chain pointer. Don't use.
+    const void* callback;
+    // Event id.
+    UnityProfilerMarkerId id;
+    // UnityProfilerMarkerFlag_ value.
+    UnityProfilerMarkerFlags flags;
+    // Category index the marker belongs to.
+    UnityProfilerCategoryId categoryId;
+    // NULL-terminated string which is associated with the marker.
+    const char* name;
+    // Metadata descriptions chain. Don't use.
+    const void* metaDataDesc;
+} UnityProfilerMarkerDesc;
+
+enum UnityProfilerMarkerDataType_
+{
+    kUnityProfilerMarkerDataTypeNone = 0,
+    kUnityProfilerMarkerDataTypeInstanceId = 1,
+    kUnityProfilerMarkerDataTypeInt32 = 2,
+    kUnityProfilerMarkerDataTypeUInt32 = 3,
+    kUnityProfilerMarkerDataTypeInt64 = 4,
+    kUnityProfilerMarkerDataTypeUInt64 = 5,
+    kUnityProfilerMarkerDataTypeFloat = 6,
+    kUnityProfilerMarkerDataTypeDouble = 7,
+    kUnityProfilerMarkerDataTypeString = 8,
+    kUnityProfilerMarkerDataTypeString16 = 9,
+    kUnityProfilerMarkerDataTypeBlob8 = 11,
+    kUnityProfilerMarkerDataTypeGfxResourceId = 12,
+    kUnityProfilerMarkerDataTypeCount // Total count of data types
+};
+typedef uint8_t UnityProfilerMarkerDataType;
+
+enum UnityProfilerMarkerDataUnit_
+{
+    kUnityProfilerMarkerDataUnitUndefined = 0,
+    kUnityProfilerMarkerDataUnitTimeNanoseconds = 1,
+    kUnityProfilerMarkerDataUnitBytes = 2,
+    kUnityProfilerMarkerDataUnitCount = 3,
+    kUnityProfilerMarkerDataUnitPercent = 4,
+    kUnityProfilerMarkerDataUnitFrequencyHz = 5,
+};
+typedef uint8_t UnityProfilerMarkerDataUnit;
+
+typedef struct UnityProfilerMarkerData
+{
+    UnityProfilerMarkerDataType type;
+    uint8_t reserved0;
+    uint16_t reserved1;
+    uint32_t size;
+    const void* ptr;
+} UnityProfilerMarkerData;
+
+enum UnityProfilerFlowEventType_
+{
+    // Starts flow chain for a current profiler marker scope (__enclosing__ scope).
+    // Mark the scheduler function with "begin" flow to connect it later to execution function on another thread.
+    kUnityProfilerFlowEventTypeBegin = 0,
+    // The flow continues with the next sample.
+    // Marks the __next__ profiler sample connected to the sample which started the flow (kUnityProfilerFlowEventTypeBegin) or previous (in time) kUnityProfilerFlowEventTypeNext flow event.
+    // All parallel flow instances are equivalent and connected to the same previous in time kUnityProfilerFlowEventTypeBegin or kUnityProfilerFlowEventTypeNext events and next (also in time) kUnityProfilerFlowEventTypeNext event.
+    kUnityProfilerFlowEventTypeParallelNext = 1,
+    // Ends flow started by kUnityProfilerFlowEventTypeBegin. Usually represents a sync point (SyncFence)
+    // Marks the __enclosing__ sample as endpoint.
+    kUnityProfilerFlowEventTypeEnd = 2,
+    // The flow continues with the next sample.
+    // Marks the __next__ profiler sample connected to the sample which started the flow (kUnityProfilerFlowEventTypeBegin).
+    kUnityProfilerFlowEventTypeNext = 3,
+};
+typedef uint8_t UnityProfilerFlowEventType;
+
+enum UnityProfilerCounterFlags_
+{
+    kUnityProfilerCounterFlagNone = 0,
+    // Automatic flush of counter value to recorder or profiler at the end of a frame
+    kUnityProfilerCounterFlushOnEndOfFrame = 1 << 1,
+    // Automatic reset counter value to zero on flush
+    kUnityProfilerCounterFlagResetToZeroOnFlush = 1 << 2,
+    // Use atomic to access counters value. Don't use
+    kUnityProfilerCounterFlagAtomic = 1 << 3,
+    // Pull-style counter. Don't use
+    kUnityProfilerCounterFlagGetter = 1 << 4
+};
+typedef uint16_t UnityProfilerCounterFlags;
+
+
+typedef uint64_t UnityProfilerThreadId;
+
+typedef void (*UnityProfilerCounterStatePtrCallback)(void* userData);
+
+#ifdef __cplusplus
+template<typename T> struct UnityProfilerDataUnitHelper;
+template<> struct UnityProfilerDataUnitHelper<int32_t> { static const UnityProfilerMarkerDataType GetProfilerType() { return kUnityProfilerMarkerDataTypeInt32; } };
+template<> struct UnityProfilerDataUnitHelper<uint32_t> { static const UnityProfilerMarkerDataType GetProfilerType() { return kUnityProfilerMarkerDataTypeUInt32; } };
+template<> struct UnityProfilerDataUnitHelper<int64_t> { static const UnityProfilerMarkerDataType GetProfilerType() { return kUnityProfilerMarkerDataTypeInt64; } };
+template<> struct UnityProfilerDataUnitHelper<uint64_t> { static const UnityProfilerMarkerDataType GetProfilerType() { return kUnityProfilerMarkerDataTypeUInt64; } };
+template<> struct UnityProfilerDataUnitHelper<float> { static const UnityProfilerMarkerDataType GetProfilerType() { return kUnityProfilerMarkerDataTypeFloat; } };
+template<> struct UnityProfilerDataUnitHelper<double> { static const UnityProfilerMarkerDataType GetProfilerType() { return kUnityProfilerMarkerDataTypeDouble; } };
+
+template<typename T> struct UnityProfilerCounter;
+#endif
+
+// Available since 2021.2
+UNITY_DECLARE_INTERFACE(IUnityProfilerV2)
+{
+#ifdef __cplusplus
+    void BeginSample(const UnityProfilerMarkerDesc * markerDesc)
+    {
+        (this->EmitEvent)(markerDesc, kUnityProfilerMarkerEventTypeBegin, 0, NULL);
+    }
+
+    void BeginSample(const UnityProfilerMarkerDesc * markerDesc, uint16_t eventDataCount, const UnityProfilerMarkerData * eventData)
+    {
+        (this->EmitEvent)(markerDesc, kUnityProfilerMarkerEventTypeBegin, eventDataCount, eventData);
+    }
+
+    void EndSample(const UnityProfilerMarkerDesc * markerDesc)
+    {
+        (this->EmitEvent)(markerDesc, kUnityProfilerMarkerEventTypeEnd, 0, NULL);
+    }
+#endif
+
+    // Create instrumentation event.
+    // \param markerDesc is a pointer to marker description struct.
+    // \param eventType is an event type - UnityProfilerMarkerEventType_.
+    // \param eventDataCount is an event metadata count passed in eventData. Must be less than eventDataCount specified in CreateMarker.
+    // \param eventData is a metadata array of eventDataCount elements.
+    void(UNITY_INTERFACE_API * EmitEvent)(const UnityProfilerMarkerDesc * markerDesc, UnityProfilerMarkerEventType eventType, uint16_t eventDataCount, const UnityProfilerMarkerData * eventData);
+
+    // Returns 1 if Unity Profiler is enabled, 0 otherwise.
+    int(UNITY_INTERFACE_API * IsEnabled)();
+
+    // Returns 1 if Unity Profiler is available, 0 otherwise.
+    // Profiler is available only in Development builds. Release builds have Unity Profiler compiled out.
+    // However individual markers can be available even in Release builds (e.g. GC.Collect) and be collected with
+    // Recorder API or forwarded to platform and other profilers (via IUnityProfilerCallbacks::RegisterMarkerEventCallback API).
+    // You can choose whenever you want or not emit profiler event in Development and Release builds using the cached result of this method.
+    int(UNITY_INTERFACE_API * IsAvailable)();
+
+    // Creates a new Unity Profiler marker.
+    // \param desc Pointer to the const UnityProfilerMarkerDesc* which is set to the created marker in a case of a successful execution.
+    // \param name Marker name to be displayed in Unity Profiler.
+    // \param flags Marker flags. One of UnityProfilerMarkerFlag_ enum. Use kUnityProfilerMarkerFlagDefault if not sure.
+    // \param eventDataCount Maximum count of potential metadata parameters count.
+    // \return 0 on success and non-zero in case of error.
+    int(UNITY_INTERFACE_API * CreateMarker)(const UnityProfilerMarkerDesc * *desc, const char* name, UnityProfilerCategoryId category, UnityProfilerMarkerFlags flags, int eventDataCount);
+
+    // Set a metadata description for the Unity Profiler marker.
+    // \param markerDesc is a pointer to marker description struct.
+    // \param index metadata index to set name for.
+    // \param metadataType Data type. Must be of UnityProfilerMarkerDataType_ enum.
+    // \param name Metadata name.
+    // \return 0 on success and non-zero in case of error.
+    int(UNITY_INTERFACE_API * SetMarkerMetadataName)(const UnityProfilerMarkerDesc * desc, int index, const char* metadataName, UnityProfilerMarkerDataType metadataType, UnityProfilerMarkerDataUnit metadataUnit);
+
+    // Creates a new Unity Profiler category.
+    // \param category is a pointer to UnityProfilerCategoryId variable which is set to the created category id in case of a successful execution.
+    // \param name Category name to be displayed in Unity Profiler.
+    // \return 0 on success and non-zero in case of error.
+    int(UNITY_INTERFACE_API * CreateCategory)(UnityProfilerCategoryId *category, const char* name, uint32_t unused);
+
+    // Registers current thread with Unity Profiler.
+    // Has no effect in Release Players.
+    // \param threadId Optional Unity Profiler thread identifier which it written on successful method call. Can be used with UnregisterThread.
+    // \param groupName Thread group name. Unity Profiler aggregates threads with the same group.
+    // \param name Thread name.
+    // \return 0 on success and non-zero in case of error.
+    int(UNITY_INTERFACE_API * RegisterThread)(UnityProfilerThreadId * threadId, const char* groupName, const char* name);
+
+    // Unregisters current thread from Unity Profiler and cleans up all associated memory.
+    // Has no effect in Release Players.
+    // \param threadId Unity Profiler thread identifier obtained with RegisterThread call. Use 0 to cleanup the current thread.
+    // \return 0 on success and non-zero in case of error.
+    int(UNITY_INTERFACE_API * UnregisterThread)(UnityProfilerThreadId threadId);
+
+#ifdef __cplusplus
+    // Creates a new Unity Profiler counter wrapper object.
+    // \param category Counter marker category which assignes marker to one of visualized groups on the profiler chart.
+    // \param name Counter marker name to be displayed in Unity Profiler.
+    // \param valueUnit Data unit, defines how data will be visualized. Must be of UnityProfilerMarkerDataUnit_ enum.
+    // \param activateFunc Callback called when new coutner data receiver is connected.
+    // \param deactivateFunc Callback called when coutner data receiver is disconnected.
+    // \param userData User data pointer passed to activate and deactivate callbacks.
+    // \return UnityProfilerCounter counter struct.
+    template<typename T>
+    UnityProfilerCounter<T> CreateCounter(UnityProfilerCategoryId category, const char* name, UnityProfilerMarkerDataUnit dataUnit,
+        UnityProfilerCounterStatePtrCallback activateFunc = nullptr, UnityProfilerCounterStatePtrCallback deactivateFunc = nullptr, void* userData = nullptr)
+    {
+        return UnityProfilerCounter<T>(
+            this,
+            this->CreateCounterValue(
+                category,
+                name,
+                kUnityProfilerMarkerFlagCounter,
+                UnityProfilerDataUnitHelper<T>::GetProfilerType(),
+                dataUnit,
+                sizeof(T),
+                kUnityProfilerCounterFlagNone,
+                activateFunc,
+                deactivateFunc,
+                userData
+            )
+        );
+    }
+
+#endif
+
+    // Creates a new Unity Profiler counter.
+    // \param category Counter marker category which assignes marker to one of visualized groups on the profiler chart.
+    // \param name Counter marker name to be displayed in Unity Profiler.
+    // \param flags Counter marker flags. One of UnityProfilerMarkerFlag_ enum. Use kUnityProfilerMarkerFlagDefault if not sure.
+    // \param valueType Data type. Must be of UnityProfilerMarkerDataType_ enum.
+    // \param valueUnit Data unit, defines how data will be visualized. Must be of UnityProfilerMarkerDataUnit_ enum.
+    // \param valueSize Data size, must be less or equal to 8.
+    // \param counterFlags Counter flags. One of UnityProfilerCounterFlags_ enum. Use kUnityProfilerCounterFlagNone if not sure.
+    // \param activateFunc Callback called when new coutner data receiver is connected.
+    // \param deactivateFunc Callback called when coutner data receiver is disconnected.
+    // \param userData User data pointer passed to activate and deactivate callbacks.
+    // \return CounterValue object address on success and null in case of error.
+    void* (UNITY_INTERFACE_API* CreateCounterValue)(
+        UnityProfilerCategoryId category,
+        const char* name,
+        UnityProfilerMarkerFlags flags,
+        UnityProfilerMarkerDataType valueType,
+        UnityProfilerMarkerDataUnit valueUnit,
+        size_t valueSize,
+        UnityProfilerCounterFlags counterFlags,
+        UnityProfilerCounterStatePtrCallback activateFunc,
+        UnityProfilerCounterStatePtrCallback deactivateFunc,
+        void* userData
+    );
+
+    void(UNITY_INTERFACE_API * FlushCounterValue)(void* counter);
+};
+UNITY_REGISTER_INTERFACE_GUID(0xB957E0189CB6A30BULL, 0x83CE589AE85B9068ULL, IUnityProfilerV2)
+
+#ifdef __cplusplus
+struct UnityProfilerCounterValue
+{
+    UnityProfilerCounterValue()
+        : m_Profiler(nullptr)
+        , m_Value(nullptr)
+    {
+    }
+
+    UnityProfilerCounterValue(IUnityProfilerV2* profiler, void* value)
+        : m_Profiler(profiler)
+        , m_Value(value)
+    {
+    }
+
+    template<typename T>
+    inline T& Value() { return *static_cast<T*>(m_Value); }
+
+    template<typename T>
+    inline const T& Value() const { return *static_cast<T*>(m_Value); }
+
+    inline void Flush()
+    {
+        m_Profiler->FlushCounterValue(m_Value);
+    }
+
+private:
+    void* m_Value;
+    IUnityProfilerV2* m_Profiler;
+};
+
+template<typename T>
+struct UnityProfilerCounter : public UnityProfilerCounterValue
+{
+    UnityProfilerCounter() {}
+    UnityProfilerCounter(IUnityProfilerV2* profiler, void* value) : UnityProfilerCounterValue(profiler, value) {}
+
+    T& operator*() { return Value<T>(); }
+    const T& operator*() const { return Value<T>(); }
+
+    operator T&() { return Value<T>(); }
+    operator T() const { return Value<T>(); }
+
+    T& operator=(const T& s)
+    {
+        Value<T>() = s;
+        return Value<T>();
+    }
+
+    T operator++(int)
+    {
+        T copy(Value<T>());
+        ++(Value<T>());
+        return copy;
+    }
+
+    UnityProfilerCounter<T>& operator++()
+    {
+        ++(Value<T>());
+        return *this;
+    }
+
+    T operator--(int)
+    {
+        T copy(Value<T>());
+        --(Value<T>());
+        return copy;
+    }
+
+    UnityProfilerCounter& operator--()
+    {
+        --(Value<T>());
+        return *this;
+    }
+
+    UnityProfilerCounter& operator-=(T& s)
+    {
+        (Value<T>()) -= s;
+        return *this;
+    }
+
+    UnityProfilerCounter& operator+=(T& s)
+    {
+        (Value<T>()) += s;
+        return *this;
+    }
+};
+#endif
+
+// Available since 2020.1
+UNITY_DECLARE_INTERFACE(IUnityProfiler)
+{
+#ifdef __cplusplus
+    void BeginSample(const UnityProfilerMarkerDesc* markerDesc)
+    {
+        (this->EmitEvent)(markerDesc, kUnityProfilerMarkerEventTypeBegin, 0, NULL);
+    }
+
+    void BeginSample(const UnityProfilerMarkerDesc* markerDesc, uint16_t eventDataCount, const UnityProfilerMarkerData* eventData)
+    {
+        (this->EmitEvent)(markerDesc, kUnityProfilerMarkerEventTypeBegin, eventDataCount, eventData);
+    }
+
+    void EndSample(const UnityProfilerMarkerDesc* markerDesc)
+    {
+        (this->EmitEvent)(markerDesc, kUnityProfilerMarkerEventTypeEnd, 0, NULL);
+    }
+#endif
+
+    void(UNITY_INTERFACE_API * EmitEvent)(const UnityProfilerMarkerDesc* markerDesc, UnityProfilerMarkerEventType eventType, uint16_t eventDataCount, const UnityProfilerMarkerData* eventData);
+
+    int(UNITY_INTERFACE_API * IsEnabled)();
+    int(UNITY_INTERFACE_API * IsAvailable)();
+
+    int(UNITY_INTERFACE_API * CreateMarker)(const UnityProfilerMarkerDesc** desc, const char* name, UnityProfilerCategoryId category, UnityProfilerMarkerFlags flags, int eventDataCount);
+    int(UNITY_INTERFACE_API * SetMarkerMetadataName)(const UnityProfilerMarkerDesc* desc, int index, const char* metadataName, UnityProfilerMarkerDataType metadataType, UnityProfilerMarkerDataUnit metadataUnit);
+
+    int(UNITY_INTERFACE_API * RegisterThread)(UnityProfilerThreadId* threadId, const char* groupName, const char* name);
+    int(UNITY_INTERFACE_API * UnregisterThread)(UnityProfilerThreadId threadId);
+};
+UNITY_REGISTER_INTERFACE_GUID(0x2CE79ED8316A4833ULL, 0x87076B2013E1571FULL, IUnityProfiler)

+ 174 - 0
unity_ios/Classes/Unity/IUnityProfilerCallbacks.h

@@ -0,0 +1,174 @@
+// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
+//
+// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
+//
+// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
+
+#pragma once
+#include "IUnityInterface.h"
+#include "IUnityProfiler.h"
+
+#include <stdint.h>
+
+// Unity Profiler Callbacks native plugin API provides an ability to register callbacks for Unity Profiler events.
+// The basic functionality includes:
+// 1. Profiler category creation callback - provides information about category name and color.
+// 2. Profiler marker creation callback - provides information about new marker which is created internally or with C# API.
+// 3. Marker event callback - allows to intercept begin/end events for the particular marker.
+// 4. Frame event callback - provides information about logical CPU frame.
+//
+//  Usage example:
+//
+//  #include <IUnityInterface.h>
+//  #include <IUnityProfilerCallbacks.h>
+//
+//  static IUnityProfilerCallbacks* s_UnityProfilerCallbacks = NULL;
+//
+//  static void UNITY_INTERFACE_API MyProfilerEventCallback(const UnityProfilerMarkerDesc* markerDesc, UnityProfilerMarkerEventType eventType, unsigned short eventDataCount, const UnityProfilerMarkerData* eventData, void* userData)
+//  {
+//      switch (eventType)
+//      {
+//          case kUnityProfilerMarkerEventTypeBegin:
+//          {
+//              MyProfilerPushMarker(markerDesc->name);
+//              break;
+//          }
+//          case kUnityProfilerMarkerEventTypeEnd:
+//          {
+//              MyProfilerPopMarker(markerDesc->name);
+//              break;
+//          }
+//      }
+//  }
+//
+//  static void UNITY_INTERFACE_API MyProfilerCreateMarkerCallback(const UnityProfilerMarkerDesc* markerDesc, void* userData)
+//  {
+//      s_UnityProfilerCallbacks->RegisterMarkerEventCallback(markerDesc, MyProfilerEventCallback, NULL);
+//  }
+//
+//  extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces* unityInterfaces)
+//  {
+//      s_UnityProfilerCallbacks = unityInterfaces->Get<IUnityProfilerCallbacks>();
+//      s_UnityProfilerCallbacks->RegisterCreateMarkerCallback(&MyProfilerCreateMarkerCallback, NULL);
+//  }
+//
+//  extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload()
+//  {
+//      s_UnityProfilerCallbacks->UnregisterCreateMarkerCallback(&MyProfilerCreateMarkerCallback, NULL);
+//      s_UnityProfilerCallbacks->UnregisterMarkerEventCallback(NULL, &MyProfilerEventCallback, NULL);
+//  }
+
+typedef struct UnityProfilerThreadDesc
+{
+    // Thread id c-casted to uint64_t.
+    UnityProfilerThreadId threadId;
+    // Thread group name. NULL-terminated.
+    const char* groupName;
+    // Thread name. NULL-terminated.
+    const char* name;
+} UnityProfilerThreadDesc;
+
+// Called when a new category is created. Up to 4 installed callbacks are supported.
+// \param categoryDesc is a pointer to category description.
+// \param userData is an optional context pointer passed with RegisterCreateCategoryCallback call.
+typedef void (UNITY_INTERFACE_API * IUnityProfilerCreateCategoryCallback)(const UnityProfilerCategoryDesc* categoryDesc, void* userData);
+
+// Called when a new profiler marker is created. Up to 4 installed callbacks are supported.
+// \param markerDesc is a pointer to marker description.
+// \param userData is an optional context pointer passed with RegisterCreateEventCallback call.
+typedef void (UNITY_INTERFACE_API * IUnityProfilerCreateMarkerCallback)(const UnityProfilerMarkerDesc* markerDesc, void* userData);
+
+// Called when a profiler event occurs.
+// \param markerDesc is an marker description struct.
+// \param eventType is an event type - UnityProfilerMarkerEventType_.
+// \param eventDataCount is an event metadata count.
+// \param eventData is a metadata array of eventDataCount elements.
+// \param userData is an optional context pointer passed with RegisterCreateEventCallback call.
+typedef void (UNITY_INTERFACE_API* IUnityProfilerMarkerEventCallback)(const UnityProfilerMarkerDesc* markerDesc, UnityProfilerMarkerEventType eventType, uint16_t eventDataCount, const UnityProfilerMarkerData* eventData, void* userData);
+
+typedef void (UNITY_INTERFACE_API * IUnityProfilerBulkCounterDataEventCallback)(int counterGroup, size_t size, void* data, void* userData);
+
+// Called when a profiler frame change occurs. Up to 4 installed callbacks are supported.
+// \param userData is an optional context pointer passed with RegisterCreateEventCallback call.
+typedef void (UNITY_INTERFACE_API * IUnityProfilerFrameCallback)(void* userData);
+
+// Called when a profiler frame change occurs. Up to 4 installed callbacks are supported.
+// \param userData is an optional context pointer passed with RegisterCreateEventCallback call.
+typedef void (UNITY_INTERFACE_API * IUnityProfilerThreadCallback)(const UnityProfilerThreadDesc* threadDesc, void* userData);
+
+// Called when a profiler flow event occurs.
+// Flow events connect events across threads allowing to trace related activities initiated from a control(main) thread.
+// \param flowEventType is a flow event type.
+// \param flowId is an unique incremental identifier for the flow chain.
+// \param userData is an optional context pointer passed with RegisterCreateEventCallback call.
+typedef void (UNITY_INTERFACE_API * IUnityProfilerFlowEventCallback)(UnityProfilerFlowEventType flowEventType, uint32_t flowId, void* userData);
+
+// Available since 2019.1
+UNITY_DECLARE_INTERFACE(IUnityProfilerCallbacksV2)
+{
+    // Register a callback which is called when a new category is created.
+    // Returns 0 on success and non-zero in case of error.
+    // Only up to 4 callbacks can be registered.
+    int(UNITY_INTERFACE_API * RegisterCreateCategoryCallback)(IUnityProfilerCreateCategoryCallback callback, void* userData);
+    int(UNITY_INTERFACE_API * UnregisterCreateCategoryCallback)(IUnityProfilerCreateCategoryCallback callback, void* userData);
+
+    // Register a callback which is called when a new marker is created.
+    // E.g. dynamically created in C# with "new PerformanceMarker(string)" or internally.
+    // Also is called for all existing markers when the callback is registered.
+    // Returns 0 on success and non-zero in case of error.
+    // Only up to 4 callbacks can be registered.
+    int(UNITY_INTERFACE_API * RegisterCreateMarkerCallback)(IUnityProfilerCreateMarkerCallback callback, void* userData);
+    int(UNITY_INTERFACE_API * UnregisterCreateMarkerCallback)(IUnityProfilerCreateMarkerCallback callback, void* userData);
+
+    // Register a callback which is called every time "PerformanceMarker.Begin(string)" is called or equivalent internal native counterpart.
+    // Returns 0 on success and non-zero in case of error.
+    // \param markerDesc is a pointer to marker description you want to install callback for.
+    int(UNITY_INTERFACE_API * RegisterMarkerEventCallback)(const UnityProfilerMarkerDesc * markerDesc, IUnityProfilerMarkerEventCallback callback, void* userData);
+    // Unregister per-marker callback.
+    // \param markerDesc is a pointer to marker description you want to remove callback from.
+    // \param userData optional context pointer.
+    // If markerDesc is NULL, callback is removed from all events which have (callback, userData) pair.
+    // If both markerDesc and userData are NULL, callback is removed from all events which have callback function pointer.
+    int(UNITY_INTERFACE_API * UnregisterMarkerEventCallback)(const UnityProfilerMarkerDesc * markerDesc, IUnityProfilerMarkerEventCallback callback, void* userData);
+
+    // Register a callback which is called every time Profiler.BeginSample is called or equivalent internal native counterpart.
+    // Returns 0 on success and non-zero in case of error.
+    // Only up to 4 callbacks can be registered.
+    int(UNITY_INTERFACE_API * RegisterFrameCallback)(IUnityProfilerFrameCallback callback, void* userData);
+    int(UNITY_INTERFACE_API * UnregisterFrameCallback)(IUnityProfilerFrameCallback callback, void* userData);
+
+    // Register a callback which is called every time a new thread is registered with profiler.
+    // Returns 0 on success and non-zero in case of error.
+    // Only up to 4 callbacks can be registered.
+    int(UNITY_INTERFACE_API * RegisterCreateThreadCallback)(IUnityProfilerThreadCallback callback, void* userData);
+    int(UNITY_INTERFACE_API * UnregisterCreateThreadCallback)(IUnityProfilerThreadCallback callback, void* userData);
+
+    // Register a callback which is called every time Unity generates a flow event.
+    // Returns 0 on success and non-zero in case of error.
+    // Note: Flow events are supported only in Development Players and Editor.
+    int(UNITY_INTERFACE_API * RegisterFlowEventCallback)(IUnityProfilerFlowEventCallback callback, void* userData);
+    // Unregister flow event callback.
+    // \param userData optional context pointer.
+    int(UNITY_INTERFACE_API * UnregisterFlowEventCallback)(IUnityProfilerFlowEventCallback callback, void* userData);
+};
+UNITY_REGISTER_INTERFACE_GUID(0x5DEB59E88F2D4571ULL, 0x81E8583069A5E33CULL, IUnityProfilerCallbacksV2)
+
+// Available since 2018.2
+UNITY_DECLARE_INTERFACE(IUnityProfilerCallbacks)
+{
+    int(UNITY_INTERFACE_API * RegisterCreateCategoryCallback)(IUnityProfilerCreateCategoryCallback callback, void* userData);
+    int(UNITY_INTERFACE_API * UnregisterCreateCategoryCallback)(IUnityProfilerCreateCategoryCallback callback, void* userData);
+
+    int(UNITY_INTERFACE_API * RegisterCreateMarkerCallback)(IUnityProfilerCreateMarkerCallback callback, void* userData);
+    int(UNITY_INTERFACE_API * UnregisterCreateMarkerCallback)(IUnityProfilerCreateMarkerCallback callback, void* userData);
+
+    int(UNITY_INTERFACE_API * RegisterMarkerEventCallback)(const UnityProfilerMarkerDesc * markerDesc, IUnityProfilerMarkerEventCallback callback, void* userData);
+    int(UNITY_INTERFACE_API * UnregisterMarkerEventCallback)(const UnityProfilerMarkerDesc * markerDesc, IUnityProfilerMarkerEventCallback callback, void* userData);
+
+    int(UNITY_INTERFACE_API * RegisterFrameCallback)(IUnityProfilerFrameCallback callback, void* userData);
+    int(UNITY_INTERFACE_API * UnregisterFrameCallback)(IUnityProfilerFrameCallback callback, void* userData);
+
+    int(UNITY_INTERFACE_API * RegisterCreateThreadCallback)(IUnityProfilerThreadCallback callback, void* userData);
+    int(UNITY_INTERFACE_API * UnregisterCreateThreadCallback)(IUnityProfilerThreadCallback callback, void* userData);
+};
+UNITY_REGISTER_INTERFACE_GUID(0x572FDB38CE3C4B1FULL, 0xA6071A9A7C4F52D8ULL, IUnityProfilerCallbacks)

+ 379 - 0
unity_ios/Classes/Unity/IUnityRenderingExtensions.h

@@ -0,0 +1,379 @@
+// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
+//
+// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
+//
+// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
+
+#pragma once
+
+
+#include "IUnityGraphics.h"
+#include <stdbool.h>
+
+/*
+    Low-level Native Plugin Rendering Extensions
+    ============================================
+
+    On top of the Low-level native plugin interface, Unity also supports low level rendering extensions that can receive callbacks when certain events happen.
+    This is mostly used to implement and control low-level rendering in your plugin and enable it to work with Unity’s multithreaded rendering.
+
+    Due to the low-level nature of this extension the plugin might need to be preloaded before the devices get created.
+    Currently the convention is name-based namely the plugin name must be prefixed by “GfxPlugin”. Example: GfxPluginMyFancyNativePlugin.
+
+    <code>
+        // Native plugin code example
+
+        enum PluginCustomCommands
+        {
+            kPluginCustomCommandDownscale = kUnityRenderingExtUserEventsStart,
+            kPluginCustomCommandUpscale,
+
+            // insert your own events here
+
+            kPluginCustomCommandCount
+        };
+
+        static IUnityInterfaces* s_UnityInterfaces = NULL;
+
+        extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
+        UnityPluginLoad(IUnityInterfaces* unityInterfaces)
+        {
+            // initialization code here...
+        }
+
+        extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
+        UnityRenderingExtEvent(UnityRenderingExtEventType event, void* data)
+        {
+            switch (event)
+            {
+                case kUnityRenderingExtEventBeforeDrawCall:
+                    // do some stuff
+                    break;
+                case kUnityRenderingExtEventAfterDrawCall:
+                    // undo some stuff
+                    break;
+                case kPluginCustomCommandDownscale:
+                    // downscale some stuff
+                    break;
+                case kPluginCustomCommandUpscale:
+                    // upscale some stuff
+                    break;
+            }
+        }
+    </code>
+*/
+
+
+//     These events will be propagated to all plugins that implement void UnityRenderingExtEvent(UnityRenderingExtEventType event, void* data);
+
+typedef enum UnityRenderingExtEventType
+{
+    kUnityRenderingExtEventSetStereoTarget,                 // issued during SetStereoTarget and carrying the current 'eye' index as parameter
+    kUnityRenderingExtEventSetStereoEye,                    // issued during stereo rendering at the beginning of each eye's rendering loop. It carries the current 'eye' index as parameter
+    kUnityRenderingExtEventStereoRenderingDone,             // issued after the rendering has finished
+    kUnityRenderingExtEventBeforeDrawCall,                  // issued during BeforeDrawCall and carrying UnityRenderingExtBeforeDrawCallParams as parameter
+    kUnityRenderingExtEventAfterDrawCall,                   // issued during AfterDrawCall. This event doesn't carry any parameters
+    kUnityRenderingExtEventCustomGrab,                      // issued during GrabIntoRenderTexture since we can't simply copy the resources
+                                                            //      when custom rendering is used - we need to let plugin handle this. It carries over
+                                                            //      a UnityRenderingExtCustomBlitParams params = { X, source, dest, 0, 0 } ( X means it's irrelevant )
+    kUnityRenderingExtEventCustomBlit,                      // issued by plugin to insert custom blits. It carries over UnityRenderingExtCustomBlitParams as param.
+    kUnityRenderingExtEventUpdateTextureBegin,                                                  // Deprecated.
+    kUnityRenderingExtEventUpdateTextureEnd,                                                    // Deprecated.
+    kUnityRenderingExtEventUpdateTextureBeginV1 = kUnityRenderingExtEventUpdateTextureBegin,    // Deprecated. Issued to update a texture. It carries over UnityRenderingExtTextureUpdateParamsV1
+    kUnityRenderingExtEventUpdateTextureEndV1 = kUnityRenderingExtEventUpdateTextureEnd,        // Deprecated. Issued to signal the plugin that the texture update has finished. It carries over the same UnityRenderingExtTextureUpdateParamsV1 as kUnityRenderingExtEventUpdateTextureBeginV1
+    kUnityRenderingExtEventUpdateTextureBeginV2,                                                // Issued to update a texture. It carries over UnityRenderingExtTextureUpdateParamsV2
+    kUnityRenderingExtEventUpdateTextureEndV2,                                                  // Issued to signal the plugin that the texture update has finished. It carries over the same UnityRenderingExtTextureUpdateParamsV2 as kUnityRenderingExtEventUpdateTextureBeginV2
+
+    // keep this last
+    kUnityRenderingExtEventCount,
+    kUnityRenderingExtUserEventsStart = kUnityRenderingExtEventCount
+} UnityRenderingExtEventType;
+
+
+typedef enum UnityRenderingExtCustomBlitCommands
+{
+    kUnityRenderingExtCustomBlitVRFlush,                    // This event is mostly used in multi GPU configurations ( SLI, etc ) in order to allow the plugin to flush all GPU's targets
+
+    // keep this last
+    kUnityRenderingExtCustomBlitCount,
+    kUnityRenderingExtUserCustomBlitStart = kUnityRenderingExtCustomBlitCount
+} UnityRenderingExtCustomBlitCommands;
+
+/*
+    This will be propagated to all plugins implementing UnityRenderingExtQuery.
+*/
+typedef enum UnityRenderingExtQueryType
+{
+    kUnityRenderingExtQueryOverrideViewport             = 1 << 0,           // The plugin handles setting up the viewport rects. Unity will skip its internal SetViewport calls
+    kUnityRenderingExtQueryOverrideScissor              = 1 << 1,           // The plugin handles setting up the scissor rects. Unity will skip its internal SetScissor calls
+    kUnityRenderingExtQueryOverrideVROcclussionMesh     = 1 << 2,           // The plugin handles its own VR occlusion mesh rendering. Unity will skip rendering its internal VR occlusion mask
+    kUnityRenderingExtQueryOverrideVRSinglePass         = 1 << 3,           // The plugin uses its own single pass stereo technique. Unity will only traverse and render the render node graph once.
+                                                                            //      and it will clear the whole render target not just per-eye on demand.
+    kUnityRenderingExtQueryKeepOriginalDoubleWideWidth_DEPRECATED  = 1 << 4,           // Instructs unity to keep the original double wide width. By default unity will try and have a power-of-two width for mip-mapping requirements.
+    kUnityRenderingExtQueryRequestVRFlushCallback       = 1 << 5,           // Instructs unity to provide callbacks when the VR eye textures need flushing. Useful for multi GPU synchronization.
+    kUnityRenderingExtQueryOverridePresentFrame         = 1 << 6,           // The plugin handles it's own SwapChain Present. Unity will skip its internal Present calls
+} UnityRenderingExtQueryType;
+
+
+typedef enum UnityRenderingExtTextureFormat
+{
+    kUnityRenderingExtFormatNone = 0, kUnityRenderingExtFormatFirst = kUnityRenderingExtFormatNone,
+
+    // sRGB formats
+    kUnityRenderingExtFormatR8_SRGB,
+    kUnityRenderingExtFormatR8G8_SRGB,
+    kUnityRenderingExtFormatR8G8B8_SRGB,
+    kUnityRenderingExtFormatR8G8B8A8_SRGB,
+
+    // 8 bit integer formats
+    kUnityRenderingExtFormatR8_UNorm,
+    kUnityRenderingExtFormatR8G8_UNorm,
+    kUnityRenderingExtFormatR8G8B8_UNorm,
+    kUnityRenderingExtFormatR8G8B8A8_UNorm,
+    kUnityRenderingExtFormatR8_SNorm,
+    kUnityRenderingExtFormatR8G8_SNorm,
+    kUnityRenderingExtFormatR8G8B8_SNorm,
+    kUnityRenderingExtFormatR8G8B8A8_SNorm,
+    kUnityRenderingExtFormatR8_UInt,
+    kUnityRenderingExtFormatR8G8_UInt,
+    kUnityRenderingExtFormatR8G8B8_UInt,
+    kUnityRenderingExtFormatR8G8B8A8_UInt,
+    kUnityRenderingExtFormatR8_SInt,
+    kUnityRenderingExtFormatR8G8_SInt,
+    kUnityRenderingExtFormatR8G8B8_SInt,
+    kUnityRenderingExtFormatR8G8B8A8_SInt,
+
+    // 16 bit integer formats
+    kUnityRenderingExtFormatR16_UNorm,
+    kUnityRenderingExtFormatR16G16_UNorm,
+    kUnityRenderingExtFormatR16G16B16_UNorm,
+    kUnityRenderingExtFormatR16G16B16A16_UNorm,
+    kUnityRenderingExtFormatR16_SNorm,
+    kUnityRenderingExtFormatR16G16_SNorm,
+    kUnityRenderingExtFormatR16G16B16_SNorm,
+    kUnityRenderingExtFormatR16G16B16A16_SNorm,
+    kUnityRenderingExtFormatR16_UInt,
+    kUnityRenderingExtFormatR16G16_UInt,
+    kUnityRenderingExtFormatR16G16B16_UInt,
+    kUnityRenderingExtFormatR16G16B16A16_UInt,
+    kUnityRenderingExtFormatR16_SInt,
+    kUnityRenderingExtFormatR16G16_SInt,
+    kUnityRenderingExtFormatR16G16B16_SInt,
+    kUnityRenderingExtFormatR16G16B16A16_SInt,
+
+    // 32 bit integer formats
+    kUnityRenderingExtFormatR32_UInt,
+    kUnityRenderingExtFormatR32G32_UInt,
+    kUnityRenderingExtFormatR32G32B32_UInt,
+    kUnityRenderingExtFormatR32G32B32A32_UInt,
+    kUnityRenderingExtFormatR32_SInt,
+    kUnityRenderingExtFormatR32G32_SInt,
+    kUnityRenderingExtFormatR32G32B32_SInt,
+    kUnityRenderingExtFormatR32G32B32A32_SInt,
+
+    // HDR formats
+    kUnityRenderingExtFormatR16_SFloat,
+    kUnityRenderingExtFormatR16G16_SFloat,
+    kUnityRenderingExtFormatR16G16B16_SFloat,
+    kUnityRenderingExtFormatR16G16B16A16_SFloat,
+    kUnityRenderingExtFormatR32_SFloat,
+    kUnityRenderingExtFormatR32G32_SFloat,
+    kUnityRenderingExtFormatR32G32B32_SFloat,
+    kUnityRenderingExtFormatR32G32B32A32_SFloat,
+
+    // Luminance and Alpha format
+    kUnityRenderingExtFormatL8_UNorm,
+    kUnityRenderingExtFormatA8_UNorm,
+    kUnityRenderingExtFormatA16_UNorm,
+
+    // BGR formats
+    kUnityRenderingExtFormatB8G8R8_SRGB,
+    kUnityRenderingExtFormatB8G8R8A8_SRGB,
+    kUnityRenderingExtFormatB8G8R8_UNorm,
+    kUnityRenderingExtFormatB8G8R8A8_UNorm,
+    kUnityRenderingExtFormatB8G8R8_SNorm,
+    kUnityRenderingExtFormatB8G8R8A8_SNorm,
+    kUnityRenderingExtFormatB8G8R8_UInt,
+    kUnityRenderingExtFormatB8G8R8A8_UInt,
+    kUnityRenderingExtFormatB8G8R8_SInt,
+    kUnityRenderingExtFormatB8G8R8A8_SInt,
+
+    // 16 bit packed formats
+    kUnityRenderingExtFormatR4G4B4A4_UNormPack16,
+    kUnityRenderingExtFormatB4G4R4A4_UNormPack16,
+    kUnityRenderingExtFormatR5G6B5_UNormPack16,
+    kUnityRenderingExtFormatB5G6R5_UNormPack16,
+    kUnityRenderingExtFormatR5G5B5A1_UNormPack16,
+    kUnityRenderingExtFormatB5G5R5A1_UNormPack16,
+    kUnityRenderingExtFormatA1R5G5B5_UNormPack16,
+
+    // Packed formats
+    kUnityRenderingExtFormatE5B9G9R9_UFloatPack32,
+    kUnityRenderingExtFormatB10G11R11_UFloatPack32,
+
+    kUnityRenderingExtFormatA2B10G10R10_UNormPack32,
+    kUnityRenderingExtFormatA2B10G10R10_UIntPack32,
+    kUnityRenderingExtFormatA2B10G10R10_SIntPack32,
+    kUnityRenderingExtFormatA2R10G10B10_UNormPack32,
+    kUnityRenderingExtFormatA2R10G10B10_UIntPack32,
+    kUnityRenderingExtFormatA2R10G10B10_SIntPack32,
+    kUnityRenderingExtFormatA2R10G10B10_XRSRGBPack32,
+    kUnityRenderingExtFormatA2R10G10B10_XRUNormPack32,
+    kUnityRenderingExtFormatR10G10B10_XRSRGBPack32,
+    kUnityRenderingExtFormatR10G10B10_XRUNormPack32,
+    kUnityRenderingExtFormatA10R10G10B10_XRSRGBPack32,
+    kUnityRenderingExtFormatA10R10G10B10_XRUNormPack32,
+
+    // ARGB formats... TextureFormat legacy
+    kUnityRenderingExtFormatA8R8G8B8_SRGB,
+    kUnityRenderingExtFormatA8R8G8B8_UNorm,
+    kUnityRenderingExtFormatA32R32G32B32_SFloat,
+
+    // Depth Stencil for formats
+    kUnityRenderingExtFormatD16_UNorm,
+    kUnityRenderingExtFormatD24_UNorm,
+    kUnityRenderingExtFormatD24_UNorm_S8_UInt,
+    kUnityRenderingExtFormatD32_SFloat,
+    kUnityRenderingExtFormatD32_SFloat_S8_UInt,
+    kUnityRenderingExtFormatS8_UInt,
+
+    // Compression formats
+    kUnityRenderingExtFormatRGBA_DXT1_SRGB,
+    kUnityRenderingExtFormatRGBA_DXT1_UNorm,
+    kUnityRenderingExtFormatRGBA_DXT3_SRGB,
+    kUnityRenderingExtFormatRGBA_DXT3_UNorm,
+    kUnityRenderingExtFormatRGBA_DXT5_SRGB,
+    kUnityRenderingExtFormatRGBA_DXT5_UNorm,
+    kUnityRenderingExtFormatR_BC4_UNorm,
+    kUnityRenderingExtFormatR_BC4_SNorm,
+    kUnityRenderingExtFormatRG_BC5_UNorm,
+    kUnityRenderingExtFormatRG_BC5_SNorm,
+    kUnityRenderingExtFormatRGB_BC6H_UFloat,
+    kUnityRenderingExtFormatRGB_BC6H_SFloat,
+    kUnityRenderingExtFormatRGBA_BC7_SRGB,
+    kUnityRenderingExtFormatRGBA_BC7_UNorm,
+
+    kUnityRenderingExtFormatRGB_PVRTC_2Bpp_SRGB,
+    kUnityRenderingExtFormatRGB_PVRTC_2Bpp_UNorm,
+    kUnityRenderingExtFormatRGB_PVRTC_4Bpp_SRGB,
+    kUnityRenderingExtFormatRGB_PVRTC_4Bpp_UNorm,
+    kUnityRenderingExtFormatRGBA_PVRTC_2Bpp_SRGB,
+    kUnityRenderingExtFormatRGBA_PVRTC_2Bpp_UNorm,
+    kUnityRenderingExtFormatRGBA_PVRTC_4Bpp_SRGB,
+    kUnityRenderingExtFormatRGBA_PVRTC_4Bpp_UNorm,
+
+    kUnityRenderingExtFormatRGB_ETC_UNorm,
+    kUnityRenderingExtFormatRGB_ETC2_SRGB,
+    kUnityRenderingExtFormatRGB_ETC2_UNorm,
+    kUnityRenderingExtFormatRGB_A1_ETC2_SRGB,
+    kUnityRenderingExtFormatRGB_A1_ETC2_UNorm,
+    kUnityRenderingExtFormatRGBA_ETC2_SRGB,
+    kUnityRenderingExtFormatRGBA_ETC2_UNorm,
+
+    kUnityRenderingExtFormatR_EAC_UNorm,
+    kUnityRenderingExtFormatR_EAC_SNorm,
+    kUnityRenderingExtFormatRG_EAC_UNorm,
+    kUnityRenderingExtFormatRG_EAC_SNorm,
+
+    kUnityRenderingExtFormatRGBA_ASTC4X4_SRGB,
+    kUnityRenderingExtFormatRGBA_ASTC4X4_UNorm,
+    kUnityRenderingExtFormatRGBA_ASTC5X5_SRGB,
+    kUnityRenderingExtFormatRGBA_ASTC5X5_UNorm,
+    kUnityRenderingExtFormatRGBA_ASTC6X6_SRGB,
+    kUnityRenderingExtFormatRGBA_ASTC6X6_UNorm,
+    kUnityRenderingExtFormatRGBA_ASTC8X8_SRGB,
+    kUnityRenderingExtFormatRGBA_ASTC8X8_UNorm,
+    kUnityRenderingExtFormatRGBA_ASTC10X10_SRGB,
+    kUnityRenderingExtFormatRGBA_ASTC10X10_UNorm,
+    kUnityRenderingExtFormatRGBA_ASTC12X12_SRGB,
+    kUnityRenderingExtFormatRGBA_ASTC12X12_UNorm,
+
+    // Video formats
+    kUnityRenderingExtFormatYUV2,
+
+    // Obsoleted
+    //kUnityRenderingExtFormatDepthAuto_removed_donotuse = 142,
+    //kUnityRenderingExtFormatShadowAuto_removed_donotuse = 143,
+    //kUnityRenderingExtFormatVideoAuto_removed_donotuse = 144,
+
+    // ASTC hdr profile
+    kUnityRenderingExtFormatRGBA_ASTC4X4_UFloat = 145,
+    kUnityRenderingExtFormatRGBA_ASTC5X5_UFloat,
+    kUnityRenderingExtFormatRGBA_ASTC6X6_UFloat,
+    kUnityRenderingExtFormatRGBA_ASTC8X8_UFloat,
+    kUnityRenderingExtFormatRGBA_ASTC10X10_UFloat,
+    kUnityRenderingExtFormatRGBA_ASTC12X12_UFloat,
+
+    kUnityRenderingExtFormatLast = kUnityRenderingExtFormatRGBA_ASTC12X12_UFloat, // Remove?
+} UnityRenderingExtTextureFormat;
+
+
+typedef struct UnityRenderingExtBeforeDrawCallParams
+{
+    void*   vertexShader;                           // bound vertex shader (platform dependent)
+    void*   fragmentShader;                         // bound fragment shader (platform dependent)
+    void*   geometryShader;                         // bound geometry shader (platform dependent)
+    void*   hullShader;                             // bound hull shader (platform dependent)
+    void*   domainShader;                           // bound domain shader (platform dependent)
+    int     eyeIndex;                               // the index of the current stereo "eye" being currently rendered.
+} UnityRenderingExtBeforeDrawCallParams;
+
+
+typedef struct UnityRenderingExtCustomBlitParams
+{
+    UnityTextureID source;                          // source texture
+    UnityRenderBuffer destination;                  // destination surface
+    unsigned int command;                           // command for the custom blit - could be any UnityRenderingExtCustomBlitCommands command or custom ones.
+    unsigned int commandParam;                      // custom parameters for the command
+    unsigned int commandFlags;                      // custom flags for the command
+} UnityRenderingExtCustomBlitParams;
+
+// Deprecated. Use UnityRenderingExtTextureUpdateParamsV2 and CommandBuffer.IssuePluginCustomTextureUpdateV2 instead.
+// Only supports DX11, GLES, Metal
+typedef struct UnityRenderingExtTextureUpdateParamsV1
+{
+    void*        texData;                           // source data for the texture update. Must be set by the plugin
+    unsigned int userData;                          // user defined data. Set by the plugin
+
+    unsigned int textureID;                         // texture ID of the texture to be updated.
+    UnityRenderingExtTextureFormat format;          // format of the texture to be updated
+    unsigned int width;                             // width of the texture
+    unsigned int height;                            // height of the texture
+    unsigned int bpp;                               // texture bytes per pixel.
+} UnityRenderingExtTextureUpdateParamsV1;
+
+// Deprecated. Use UnityRenderingExtTextureUpdateParamsV2 and CommandBuffer.IssuePluginCustomTextureUpdateV2 instead.
+// Only supports DX11, GLES, Metal
+typedef UnityRenderingExtTextureUpdateParamsV1 UnityRenderingExtTextureUpdateParams;
+
+// Type of the "data" parameter passed when callbacks registered with CommandBuffer.IssuePluginCustomTextureUpdateV2 are called.
+// Supports DX11, GLES, Metal, and Switch (also possibly PS4, PSVita in the future)
+typedef struct UnityRenderingExtTextureUpdateParamsV2
+{
+    void*        texData;                           // source data for the texture update. Must be set by the plugin
+    intptr_t     textureID;                         // texture ID of the texture to be updated.
+    unsigned int userData;                          // user defined data. Set by the plugin
+    UnityRenderingExtTextureFormat format;          // format of the texture to be updated
+    unsigned int width;                             // width of the texture
+    unsigned int height;                            // height of the texture
+    unsigned int bpp;                               // texture bytes per pixel.
+} UnityRenderingExtTextureUpdateParamsV2;
+
+
+// Certain Unity APIs (GL.IssuePluginEventAndData, CommandBuffer.IssuePluginEventAndData) can callback into native plugins.
+// Provide them with an address to a function of this signature.
+typedef void (UNITY_INTERFACE_API * UnityRenderingEventAndData)(int eventId, void* data);
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// If exported by a plugin, this function will be called for all the events in UnityRenderingExtEventType
+void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityRenderingExtEvent(UnityRenderingExtEventType event, void* data);
+// If exported by a plugin, this function will be called to query the plugin for the queries in UnityRenderingExtQueryType
+bool UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityRenderingExtQuery(UnityRenderingExtQueryType query);
+
+#ifdef __cplusplus
+}
+#endif

+ 375 - 0
unity_ios/Classes/Unity/InternalProfiler.cpp

@@ -0,0 +1,375 @@
+#include "InternalProfiler.h"
+
+#include <stdint.h>
+#include <stdio.h>
+#include <mach/mach_time.h>
+
+
+#define ENABLE_DETAILED_GC_STATS 0
+
+#if ENABLE_INTERNAL_PROFILER
+
+namespace
+{
+    enum
+    {
+        GpuProfilerBlockEachNthFrame = 4
+    };
+
+    mach_timebase_info_data_t timebaseInfo;
+    void ProfilerInit()
+    {
+        mach_timebase_info(&timebaseInfo);
+    }
+
+    static float MachToMillisecondsDelta(int64_t delta)
+    {
+        // Convert to nanoseconds
+        delta *= timebaseInfo.numer;
+        delta /= timebaseInfo.denom;
+        float result = (float)delta / 1000000.0F;
+        return result;
+    }
+
+    struct ProfilerBlock
+    {
+        int64_t maxV, minV, avgV;
+    };
+
+    void ProfilerBlock_Update(struct ProfilerBlock* b, int64_t d, bool reset, bool avoidZero = false)
+    {
+        if (reset)
+        {
+            b->maxV = b->minV = b->avgV = d;
+        }
+        else
+        {
+            b->maxV = (d > b->maxV) ? d : b->maxV;
+            if (avoidZero && (b->minV == 0 || d == 0))
+                b->minV = (d > b->minV) ? d : b->minV;
+            else
+                b->minV = (d < b->minV) ? d : b->minV;
+            b->avgV += d;
+        }
+    }
+
+    ProfilerBlock   _framePB;
+    ProfilerBlock   _playerPB;
+
+    ProfilerBlock   _batchCountPB;
+    ProfilerBlock   _drawCallCountPB;
+    ProfilerBlock   _triCountPB;
+    ProfilerBlock   _vertCountPB;
+
+    ProfilerBlock   _dynamicBatchDtPB;
+    ProfilerBlock   _dynamicBatchCountPB;
+    ProfilerBlock   _dynamicBatchedDrawCallCountPB;
+    ProfilerBlock   _dynamicBatchedTriCountPB;
+    ProfilerBlock   _dynamicBatchedVertCountPB;
+
+    ProfilerBlock   _staticBatchCountPB;
+    ProfilerBlock   _staticBatchedDrawCallCountPB;
+    ProfilerBlock   _staticBatchedTriCountPB;
+    ProfilerBlock   _staticBatchedVertCountPB;
+
+    ProfilerBlock   _fixedBehaviourManagerPB;
+    ProfilerBlock   _fixedPhysicsManagerPB;
+    ProfilerBlock   _dynamicBehaviourManagerPB;
+    ProfilerBlock   _coroutinePB;
+    ProfilerBlock   _skinMeshUpdatePB;
+    ProfilerBlock   _animationUpdatePB;
+    ProfilerBlock   _unityRenderLoopPB;
+    ProfilerBlock   _unityCullingPB;
+    ProfilerBlock   _unityMSAAResolvePB;
+    ProfilerBlock   _fixedUpdateCountPB;
+    ProfilerBlock   _GCCountPB;
+    ProfilerBlock   _GCDurationPB;
+
+
+    int     _frameId            = 0;
+
+    // our rendering is dictated by ios display link
+    // frametime will be time between two frame starts
+    // unity player time will be time between frame start/end
+    int64_t _lastFrameStart     = -1;
+    int64_t _frameStart         = 0;
+    int64_t _frameTime          = 0;
+    int64_t _playerTime         = 0;
+
+    int64_t _msaaResolveStart   = 0;
+    int64_t _msaaResolve        = 0;
+    void*   _msaaResolveCounter = 0;
+
+
+    UnityFrameStats _unityFrameStats;
+}
+
+extern "C" int64_t UnityScriptingGetUsedSize();
+extern "C" int64_t UnityScriptingGetHeapSize();
+static      void    Profiler_SetupScriptingProfile();
+
+void Profiler_InitProfiler()
+{
+    Profiler_SetupScriptingProfile();
+    ProfilerInit();
+
+    if (_msaaResolveCounter == 0)
+        _msaaResolveCounter = UnityCreateProfilerCounter("iOS.MSAAResolve");
+}
+
+void Profiler_UninitProfiler()
+{
+    UnityDestroyProfilerCounter(_msaaResolveCounter);
+}
+
+void Profiler_FrameStart()
+{
+    _frameStart = mach_absolute_time();
+    if (_lastFrameStart < 0)
+    {
+        _lastFrameStart = _frameStart; return;
+    }
+
+    _frameTime = _frameStart - _lastFrameStart;
+    _lastFrameStart  = _frameStart;
+}
+
+void Profiler_FrameEnd()
+{
+    _playerTime = mach_absolute_time() - _frameStart;
+}
+
+void Profiler_FramePresent(const UnityFrameStats* unityFrameStats)
+{
+    if (!unityFrameStats)
+        return;
+    _unityFrameStats = *unityFrameStats;
+
+    const int EachNthFrame = 32;
+    if (_frameId == EachNthFrame)
+    {
+        _frameId = 0;
+
+        ::printf("iPhone Unity internal profiler stats\n");
+        ::printf("frametime>     min: %4.1f   max: %4.1f   avg: %4.1f\n", MachToMillisecondsDelta(_framePB.minV), MachToMillisecondsDelta(_framePB.maxV), MachToMillisecondsDelta(_framePB.avgV / EachNthFrame));
+        ::printf("cpu-player>    min: %4.1f   max: %4.1f   avg: %4.1f\n", MachToMillisecondsDelta(_playerPB.minV), MachToMillisecondsDelta(_playerPB.maxV), MachToMillisecondsDelta(_playerPB.avgV / EachNthFrame));
+
+        ::printf("batches>       min: %3d    max: %3d    avg: %3d\n", (int)_batchCountPB.minV, (int)_batchCountPB.maxV, (int)(_batchCountPB.avgV / EachNthFrame));
+        ::printf("draw calls>    min: %3d    max: %3d    avg: %3d\n", (int)_drawCallCountPB.minV, (int)_drawCallCountPB.maxV, (int)(_drawCallCountPB.avgV / EachNthFrame));
+        ::printf("tris>          min: %5d  max: %5d  avg: %5d\n", (int)_triCountPB.minV, (int)_triCountPB.maxV, (int)(_triCountPB.avgV / EachNthFrame));
+        ::printf("verts>         min: %5d  max: %5d  avg: %5d\n", (int)_vertCountPB.minV, (int)_vertCountPB.maxV, (int)(_vertCountPB.avgV / EachNthFrame));
+        ::printf("dynamic batching> batched draw calls: %3d batches: %3d tris: %5d verts: %5d\n",
+            (int)(_dynamicBatchedDrawCallCountPB.avgV / EachNthFrame),
+            (int)(_dynamicBatchCountPB.avgV / EachNthFrame),
+            (int)(_dynamicBatchedTriCountPB.avgV / EachNthFrame),
+            (int)(_dynamicBatchedVertCountPB.avgV / EachNthFrame));
+        ::printf("static batching>  batched draw calls: %3d batches: %3d tris: %5d verts: %5d\n",
+            (int)(_staticBatchedDrawCallCountPB.avgV / EachNthFrame),
+            (int)(_staticBatchCountPB.avgV / EachNthFrame),
+            (int)(_staticBatchedTriCountPB.avgV / EachNthFrame),
+            (int)(_staticBatchedVertCountPB.avgV / EachNthFrame));
+
+        ::printf("player-detail> physx: %4.1f animation: %4.1f culling %4.1f skinning: %4.1f batching: %4.1f render: %4.1f fixed-update-count: %d .. %d\n",
+            MachToMillisecondsDelta(_fixedPhysicsManagerPB.avgV / EachNthFrame),
+            MachToMillisecondsDelta(_animationUpdatePB.avgV / EachNthFrame),
+            MachToMillisecondsDelta(_unityCullingPB.avgV / EachNthFrame),
+            MachToMillisecondsDelta(_skinMeshUpdatePB.avgV / EachNthFrame),
+            MachToMillisecondsDelta(_dynamicBatchDtPB.avgV / EachNthFrame),
+            MachToMillisecondsDelta((_unityRenderLoopPB.avgV - _dynamicBatchDtPB.avgV - _unityCullingPB.avgV) / EachNthFrame),
+            (int)_fixedUpdateCountPB.minV, (int)_fixedUpdateCountPB.maxV);
+        ::printf("scripting-scripts>  update: %4.1f   fixedUpdate: %4.1f coroutines: %4.1f \n", MachToMillisecondsDelta(_dynamicBehaviourManagerPB.avgV / EachNthFrame), MachToMillisecondsDelta(_fixedBehaviourManagerPB.avgV / EachNthFrame), MachToMillisecondsDelta(_coroutinePB.avgV / EachNthFrame));
+#if UNITY_DEVELOPER_BUILD
+        ::printf("scripting-memory>   used heap: %lld allocated heap: %lld  max number of collections: %d collection total duration: %4.1f\n", UnityScriptingGetUsedSize(), UnityScriptingGetHeapSize(), (int)_GCCountPB.avgV, MachToMillisecondsDelta(_GCDurationPB.avgV));
+#else
+        ::printf("scripting-memory>   information not available on non-development player configuration\n");
+#endif
+        ::printf("----------------------------------------\n");
+    }
+    ProfilerBlock_Update(&_framePB, _frameTime, (_frameId == 0));
+    ProfilerBlock_Update(&_playerPB, _playerTime, (_frameId == 0));
+
+    ProfilerBlock_Update(&_batchCountPB, _unityFrameStats.batchCount, (_frameId == 0));
+    ProfilerBlock_Update(&_drawCallCountPB, _unityFrameStats.drawCallCount, (_frameId == 0));
+    ProfilerBlock_Update(&_triCountPB, _unityFrameStats.triCount, (_frameId == 0));
+    ProfilerBlock_Update(&_vertCountPB, _unityFrameStats.vertCount, (_frameId == 0));
+
+    ProfilerBlock_Update(&_dynamicBatchDtPB, _unityFrameStats.dynamicBatchDt, (_frameId == 0));
+    ProfilerBlock_Update(&_dynamicBatchCountPB, _unityFrameStats.dynamicBatchCount, (_frameId == 0));
+    ProfilerBlock_Update(&_dynamicBatchedDrawCallCountPB, _unityFrameStats.dynamicBatchedDrawCallCount, (_frameId == 0));
+    ProfilerBlock_Update(&_dynamicBatchedTriCountPB, _unityFrameStats.dynamicBatchedTris, (_frameId == 0));
+    ProfilerBlock_Update(&_dynamicBatchedVertCountPB, _unityFrameStats.dynamicBatchedVerts, (_frameId == 0));
+
+    ProfilerBlock_Update(&_staticBatchCountPB, _unityFrameStats.staticBatchCount, (_frameId == 0));
+    ProfilerBlock_Update(&_staticBatchedDrawCallCountPB, _unityFrameStats.staticBatchedDrawCallCount, (_frameId == 0));
+    ProfilerBlock_Update(&_staticBatchedTriCountPB, _unityFrameStats.staticBatchedTris, (_frameId == 0));
+    ProfilerBlock_Update(&_staticBatchedVertCountPB, _unityFrameStats.staticBatchedVerts, (_frameId == 0));
+
+    ProfilerBlock_Update(&_fixedBehaviourManagerPB, _unityFrameStats.fixedBehaviourManagerDt, (_frameId == 0));
+    ProfilerBlock_Update(&_fixedPhysicsManagerPB, _unityFrameStats.fixedPhysicsManagerDt, (_frameId == 0));
+    ProfilerBlock_Update(&_dynamicBehaviourManagerPB, _unityFrameStats.dynamicBehaviourManagerDt, (_frameId == 0));
+    ProfilerBlock_Update(&_coroutinePB, _unityFrameStats.coroutineDt, (_frameId == 0));
+    ProfilerBlock_Update(&_skinMeshUpdatePB, _unityFrameStats.skinMeshUpdateDt, (_frameId == 0));
+    ProfilerBlock_Update(&_animationUpdatePB, _unityFrameStats.animationUpdateDt, (_frameId == 0));
+    ProfilerBlock_Update(&_unityRenderLoopPB, _unityFrameStats.renderDt, (_frameId == 0));
+    ProfilerBlock_Update(&_unityCullingPB, _unityFrameStats.cullingDt, (_frameId == 0));
+    ProfilerBlock_Update(&_unityMSAAResolvePB, _msaaResolve, (_frameId == 0));
+    ProfilerBlock_Update(&_fixedUpdateCountPB, _unityFrameStats.fixedUpdateCount, (_frameId == 0));
+    ProfilerBlock_Update(&_GCCountPB, 0, (_frameId == 0));
+    ProfilerBlock_Update(&_GCDurationPB, 0, (_frameId == 0));
+
+    _msaaResolve = 0;
+    ++_frameId;
+}
+
+void Profiler_StartMSAAResolve()
+{
+    UnityStartProfilerCounter(_msaaResolveCounter);
+    _msaaResolveStart = mach_absolute_time();
+}
+
+void Profiler_EndMSAAResolve()
+{
+    _msaaResolve += (mach_absolute_time() - _msaaResolveStart);
+    UnityEndProfilerCounter(_msaaResolveCounter);
+}
+
+//
+// scriptint memory profiling
+//
+
+extern "C"
+{
+    enum ScriptingGCEvent
+    {
+        SCRIPTING_GC_EVENT_START,
+        SCRIPTING_GC_EVENT_MARK_START,
+        SCRIPTING_GC_EVENT_MARK_END,
+        SCRIPTING_GC_EVENT_RECLAIM_START,
+        SCRIPTING_GC_EVENT_RECLAIM_END,
+        SCRIPTING_GC_EVENT_END,
+        SCRIPTING_GC_EVENT_PRE_STOP_WORLD,
+        SCRIPTING_GC_EVENT_POST_STOP_WORLD,
+        SCRIPTING_GC_EVENT_PRE_START_WORLD,
+        SCRIPTING_GC_EVENT_POST_START_WORLD
+    };
+
+    enum ScriptingProfileFlags
+    {
+        SCRIPTING_PROFILE_NONE              = 0,
+        SCRIPTING_PROFILE_APPDOMAIN_EVENTS  = 1 << 0,
+        SCRIPTING_PROFILE_ASSEMBLY_EVENTS   = 1 << 1,
+        SCRIPTING_PROFILE_MODULE_EVENTS     = 1 << 2,
+        SCRIPTING_PROFILE_CLASS_EVENTS      = 1 << 3,
+        SCRIPTING_PROFILE_JIT_COMPILATION   = 1 << 4,
+        SCRIPTING_PROFILE_INLINING          = 1 << 5,
+        SCRIPTING_PROFILE_EXCEPTIONS        = 1 << 6,
+        SCRIPTING_PROFILE_ALLOCATIONS       = 1 << 7,
+        SCRIPTING_PROFILE_GC                = 1 << 8,
+        SCRIPTING_PROFILE_THREADS           = 1 << 9,
+        SCRIPTING_PROFILE_REMOTING          = 1 << 10,
+        SCRIPTING_PROFILE_TRANSITIONS       = 1 << 11,
+        SCRIPTING_PROFILE_ENTER_LEAVE       = 1 << 12,
+        SCRIPTING_PROFILE_COVERAGE          = 1 << 13,
+        SCRIPTING_PROFILE_INS_COVERAGE      = 1 << 14,
+        SCRIPTING_PROFILE_STATISTICAL       = 1 << 15,
+        SCRIPTING_PROFILE_METHOD_EVENTS     = 1 << 16,
+        SCRIPTING_PROFILE_MONITOR_EVENTS    = 1 << 17,
+        SCRIPTING_PROFILE_IOMAP_EVENTS      = 1 << 18, /* this should likely be removed, too */
+        SCRIPTING_PROFILE_GC_MOVES          = 1 << 19,
+    };
+
+    struct MemoryProfiler
+    {
+        int64_t gc_total_time;
+        int64_t gc_mark_time;
+        int64_t gc_reclaim_time;
+        int64_t gc_stop_world_time;
+        int64_t gc_start_world_time;
+    };
+
+    typedef void (*UnityScriptingProfileFunc)(void* /*MemoryProfiler*/ prof);
+    typedef void (*UnityScriptingProfileGCFunc)(void* /*MemoryProfiler*/ prof, int event, int generation);
+    typedef void (*UnityScriptingProfileGCResizeFunc)(void* /*MemoryProfiler*/ prof, int64_t new_size);
+
+    void    UnityScriptingProfilerInstall(void* /*MemoryProfiler*/ prof, UnityScriptingProfileFunc shutdown_callback);
+    void    UnityScriptingProfilerInstallGC(UnityScriptingProfileGCFunc callback, UnityScriptingProfileGCResizeFunc heap_resize_callback);
+    void    UnityScriptingProfilerSetEvents(int /*ScriptingProfileFlags*/ events);
+}
+
+
+static MemoryProfiler _MemoryProfiler;
+
+static void gc_event(void* profiler_, int event, int generation)
+{
+    MemoryProfiler* profiler = (MemoryProfiler*)profiler_;
+    switch (event)
+    {
+        case SCRIPTING_GC_EVENT_START:
+            profiler->gc_total_time = mach_absolute_time();
+            break;
+        case SCRIPTING_GC_EVENT_END:
+        {
+            profiler->gc_total_time = mach_absolute_time() - profiler->gc_total_time;
+            float delta = profiler->gc_total_time;
+            ProfilerBlock_Update(&_GCDurationPB, delta, false);
+            ProfilerBlock_Update(&_GCCountPB, 1, false);
+            break;
+        }
+        case SCRIPTING_GC_EVENT_MARK_START:
+            profiler->gc_mark_time = mach_absolute_time();
+            break;
+        case SCRIPTING_GC_EVENT_MARK_END:
+            profiler->gc_mark_time = mach_absolute_time() - profiler->gc_mark_time;
+            break;
+        case SCRIPTING_GC_EVENT_RECLAIM_START:
+            profiler->gc_reclaim_time = mach_absolute_time();
+            break;
+        case SCRIPTING_GC_EVENT_RECLAIM_END:
+            profiler->gc_reclaim_time = mach_absolute_time() - profiler->gc_reclaim_time;
+            break;
+        case SCRIPTING_GC_EVENT_PRE_STOP_WORLD:
+            profiler->gc_stop_world_time = mach_absolute_time();
+            break;
+        case SCRIPTING_GC_EVENT_POST_STOP_WORLD:
+            profiler->gc_stop_world_time = mach_absolute_time() - profiler->gc_stop_world_time;
+            break;
+        case SCRIPTING_GC_EVENT_PRE_START_WORLD:
+            profiler->gc_start_world_time = mach_absolute_time();
+            break;
+        case SCRIPTING_GC_EVENT_POST_START_WORLD:
+            profiler->gc_start_world_time = mach_absolute_time() - profiler->gc_start_world_time;
+            break;
+        default:
+            break;
+    }
+
+#if ENABLE_DETAILED_GC_STATS
+    if (event == SCRIPTING_GC_EVENT_END)
+    {
+        ::printf("scripting-gc>   stop time: %4.1f mark time: %4.1f reclaim time: %4.1f start time: %4.1f total time: %4.1f \n",
+            MachToMillisecondsDelta(profiler->gc_stop_world_time),
+            MachToMillisecondsDelta(profiler->gc_mark_time),
+            MachToMillisecondsDelta(profiler->gc_reclaim_time),
+            MachToMillisecondsDelta(profiler->gc_start_world_time),
+            MachToMillisecondsDelta(profiler->gc_total_time)
+        );
+    }
+#endif
+}
+
+static void gc_resize(void* profiler, int64_t new_size)
+{
+}
+
+static void profiler_shutdown(void* profiler)
+{
+}
+
+static void Profiler_SetupScriptingProfile()
+{
+    UnityScriptingProfilerInstall(&_MemoryProfiler, &profiler_shutdown);
+    UnityScriptingProfilerInstallGC(&gc_event, &gc_resize);
+    UnityScriptingProfilerSetEvents(SCRIPTING_PROFILE_GC);
+}
+
+#endif // ENABLE_INTERNAL_PROFILER

+ 32 - 0
unity_ios/Classes/Unity/InternalProfiler.h

@@ -0,0 +1,32 @@
+#pragma once
+
+#define ENABLE_INTERNAL_PROFILER 0
+
+// 4.x ENABLE_BLOCK_ON_GPU_PROFILER and 5.x ENABLE_GPU_TIMING were removed in favor of using xcode tools
+// INCLUDE_OPENGLES_IN_RENDER_TIME was removed
+
+
+#if ENABLE_INTERNAL_PROFILER
+
+void Profiler_InitProfiler();
+void Profiler_UninitProfiler();
+void Profiler_FrameStart();
+void Profiler_FrameEnd();
+void Profiler_FramePresent(const UnityFrameStats*);
+
+void Profiler_StartMSAAResolve();
+void Profiler_EndMSAAResolve();
+
+#else
+
+inline void Profiler_InitProfiler()                             {}
+inline void Profiler_UninitProfiler()                           {}
+inline void Profiler_FrameStart()                               {}
+inline void Profiler_FrameEnd()                                 {}
+inline void Profiler_FramePresent(const struct UnityFrameStats*) {}
+
+inline void Profiler_StartMSAAResolve()                         {}
+inline void Profiler_EndMSAAResolve()                           {}
+
+
+#endif // ENABLE_INTERNAL_PROFILER

+ 228 - 0
unity_ios/Classes/Unity/MetalHelper.mm

@@ -0,0 +1,228 @@
+#include "UnityRendering.h"
+
+#import <Metal/Metal.h>
+#import <QuartzCore/QuartzCore.h>
+
+#include "UnityAppController.h"
+#include "CVTextureCache.h"
+
+#include "ObjCRuntime.h"
+#include <libkern/OSAtomic.h>
+#include <utility>
+
+extern "C" void InitRenderingMTL()
+{
+}
+
+static MTLPixelFormat GetColorFormatForSurface(const UnityDisplaySurfaceMTL* surface)
+{
+    MTLPixelFormat colorFormat = MTLPixelFormatInvalid;
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+    if (surface->hdr)
+    {
+        // 0 = 10 bit, 1 = 16bit
+        if (@available(iOS 16.0, *))
+            colorFormat = UnityHDRSurfaceDepth() == 0 ? MTLPixelFormatRGB10A2Unorm : MTLPixelFormatRGBA16Float;
+    }
+#endif
+
+    if(colorFormat == MTLPixelFormatInvalid && surface->wideColor)
+    {
+        // at some point we tried using MTLPixelFormatBGR10_XR formats, but it seems that apple CoreImage have issues with that
+        //   and we are not alone here, see for example https://forums.developer.apple.com/forums/thread/66166
+        // when application goes to background the colors are changed (more white-ish?)
+        // no matter what we tried, the issue persists
+        // NOTE: the most funny thing is when we set color space to be P3 we get same whitish colors always
+        // NOTE: but this time they become normal when going to background
+        // in all, it seems that using rgba f16 is the most robust option here, so we are back to it again
+        colorFormat = MTLPixelFormatRGBA16Float;
+    }
+
+    if(colorFormat == MTLPixelFormatInvalid)
+        colorFormat = surface->srgb ? MTLPixelFormatBGRA8Unorm_sRGB : MTLPixelFormatBGRA8Unorm;
+
+    return colorFormat;
+}
+
+extern "C" void CreateSystemRenderingSurfaceMTL(UnityDisplaySurfaceMTL* surface)
+{
+    MTLPixelFormat colorFormat = GetColorFormatForSurface(surface);
+    surface->swapchain.layer.presentsWithTransaction = NO;
+    surface->swapchain.layer.drawsAsynchronously = YES;
+
+    if (UnityPreserveFramebufferAlpha())
+    {
+        const CGFloat components[] = {1.0f, 1.0f, 1.0f, 0.0f};
+        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+        CGColorRef color = CGColorCreate(colorSpace, components);
+        surface->swapchain.layer.opaque = NO;
+        surface->swapchain.layer.backgroundColor = color;
+        CGColorRelease(color);
+        CGColorSpaceRelease(colorSpace);
+    }
+
+    CGColorSpaceRef colorSpaceRef = nil;
+    if (surface->hdr)
+    {
+        if (@available(iOS 16.0, *))
+            colorSpaceRef = UnityHDRSurfaceDepth() == 0 ? CGColorSpaceCreateWithName(CFSTR("kCGColorSpaceITUR_2100_PQ")) : CGColorSpaceCreateWithName(CFSTR("kCGColorSpaceExtendedLinearITUR_2020"));
+    }
+    if(colorSpaceRef == nil)
+    {
+        if (surface->wideColor)
+            colorSpaceRef = CGColorSpaceCreateWithName(surface->srgb ? kCGColorSpaceExtendedLinearSRGB : kCGColorSpaceExtendedSRGB);
+        else
+            colorSpaceRef = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
+    }
+
+    surface->swapchain.layer.colorspace = colorSpaceRef;
+    CGColorSpaceRelease(colorSpaceRef);
+
+    surface->swapchain.layer.device = surface->device;
+    surface->swapchain.layer.pixelFormat = colorFormat;
+    surface->swapchain.layer.framebufferOnly = (surface->framebufferOnly != 0);
+    surface->colorFormat = (unsigned)colorFormat;
+}
+
+extern "C" void CreateUnityRenderBuffersMTL(UnityDisplaySurfaceMTL* surface)
+{
+    const int w = surface->targetW, h = surface->targetH;
+    const bool needInterimColor = w != surface->systemW || h != surface->systemH;
+
+    if (needInterimColor)
+    {
+        surface->targetColorRB = UnitySwapchainCreateBackbufferForExtents(&surface->swapchain, surface->targetColorRB, w, h);
+    }
+    else
+    {
+        UnityDestroyExternalSurface(surface->targetColorRB);
+        surface->targetColorRB = 0;
+    }
+
+    if (surface->msaaSamples > 1)
+    {
+        if (needInterimColor)
+            surface->targetAAColorRB = UnitySwapchainCreateAABackbuffer(&surface->swapchain, surface->targetAAColorRB, surface->msaaSamples, surface->targetColorRB);
+        else
+            surface->targetAAColorRB = UnitySwapchainCreateAABackbufferResolveToSwapchain(&surface->swapchain, surface->targetAAColorRB, surface->msaaSamples);
+    }
+    else
+    {
+        UnityDestroyExternalSurface(surface->targetAAColorRB);
+        surface->targetAAColorRB = 0;
+    }
+
+    surface->systemColorBuffer = UnitySwapchainCreateBackbuffer(&surface->swapchain, surface->systemColorBuffer);
+
+    if (surface->targetAAColorRB)
+        surface->unityColorBuffer = surface->targetAAColorRB;
+    else if (surface->targetColorRB)
+        surface->unityColorBuffer = surface->targetColorRB;
+    else
+        surface->unityColorBuffer = surface->systemColorBuffer;
+
+    surface->unityDepthBuffer  = UnitySwapchainCreateDepthForBackbuffer(&surface->swapchain, surface->unityColorBuffer, surface->unityDepthBuffer);
+}
+
+extern "C" void DestroyUnityRenderBuffersMTL(UnityDisplaySurfaceMTL* surface)
+{
+    UnitySwapchainDestroyBackbuffer(&surface->swapchain, surface->systemColorBuffer);
+    UnitySwapchainDestroyBackbuffer(&surface->swapchain, surface->unityDepthBuffer);
+    UnitySwapchainDestroyBackbuffer(&surface->swapchain, surface->targetColorRB);
+    UnitySwapchainDestroyBackbuffer(&surface->swapchain, surface->targetAAColorRB);
+    surface->targetColorRB = surface->targetAAColorRB = surface->systemColorBuffer = surface->unityDepthBuffer = 0;
+
+    surface->unityColorBuffer = 0;
+}
+
+extern "C" void PreparePresentMTL(UnityDisplaySurfaceMTL* surface, MTLCommandBufferRef cb)
+{
+    if (surface->targetColorRB)
+        UnitySwapchainBlitBackbuffer(&surface->swapchain, surface->targetColorRB, cb);
+    APP_CONTROLLER_RENDER_PLUGIN_METHOD(onFrameResolved);
+}
+
+extern "C" void PresentMTL(UnityDisplaySurfaceMTL* surface, MTLCommandBufferRef cb)
+{
+    UnityViewSwapchain* swapchain = &surface->swapchain;
+    @autoreleasepool
+    {
+        if (swapchain->drawable)
+            [cb presentDrawable:swapchain->drawable];
+
+        if (swapchain->drawableTexture)
+            UnityUnregisterMetalTextureForMemoryProfiler(swapchain->drawableTexture);
+
+        swapchain->nextDrawable = nil;
+        swapchain->drawable = nil;
+        swapchain->drawableTexture = nil;
+    }
+
+    surface->calledPresentDrawable = 1;
+}
+
+UNITY_EXPORT extern "C" MTLTextureRef AcquireSwapchainDrawable(UnityViewSwapchain* swapchain)
+{
+    // check if have acquired the backbuffer texture already
+    if (swapchain->drawableTexture)
+        return swapchain->drawableTexture;
+
+    // this is coming from CAMetalDisplayLinkUpdate
+    if (swapchain->nextDrawable)
+        swapchain->drawable = swapchain->nextDrawable;
+
+    // this is coming from CADisplayLink: query next drawable
+    if (!swapchain->drawable)
+        swapchain->drawable = [swapchain->layer nextDrawable];
+
+    id<MTLTexture> drawableTex = [swapchain->drawable texture];
+    if (drawableTex)
+    {
+        UnityUnregisterMetalTextureForMemoryProfiler(swapchain->drawableTexture);
+        swapchain->drawableTexture = drawableTex;
+        UnityRegisterExternalRenderSurfaceTextureForMemoryProfiler(drawableTex);
+    }
+
+#if UNITY_DISPLAY_SURFACE_MTL_BACKWARD_COMPATIBILITY
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#pragma clang diagnostic ignored "-Winvalid-offsetof"
+
+    const uintptr_t surfacePtr = (uintptr_t)swapchain - offsetof(UnityDisplaySurfaceMTL, swapchain);
+    UnityDisplaySurfaceMTL* surface = (UnityDisplaySurfaceMTL*)surfacePtr;
+    surface->layer          = swapchain->layer;
+    surface->nextDrawable   = swapchain->nextDrawable;
+    surface->drawable       = swapchain->drawable;
+    surface->drawableTex    = swapchain->drawableTexture;
+
+#pragma clang diagnostic pop
+#endif
+
+    return drawableTex;
+
+}
+
+UNITY_EXPORT extern "C" MTLTextureRef AcquireDrawableMTL(UnityDisplaySurfaceMTL* surface)
+{
+    if (!surface)
+        return nil;
+
+    return AcquireSwapchainDrawable(&surface->swapchain);
+}
+
+UNITY_EXPORT extern "C" int UnityCommandQueueMaxCommandBufferCountMTL()
+{
+    // customizable argument to pass towards [MTLDevice newCommandQueueWithMaxCommandBufferCount:],
+    // the default value is 64 but with Parallel Render Encoder workloads, it might need to be increased
+
+    return 256;
+}
+
+UNITY_EXPORT extern "C" void StartFrameRenderingMTL(UnityDisplaySurfaceMTL* surface)
+{
+}
+
+UNITY_EXPORT extern "C" void EndFrameRenderingMTL(UnityDisplaySurfaceMTL* surface)
+{
+}

+ 28 - 0
unity_ios/Classes/Unity/NoGraphicsHelper.mm

@@ -0,0 +1,28 @@
+#include "UnityRendering.h"
+
+
+extern "C" void CreateUnityRenderBuffersNULL(UnityDisplaySurfaceBase* surface)
+{
+    UnityRenderBufferDesc sys_desc = { surface->systemW, surface->systemH, 1, 1, 1 };
+    UnityRenderBufferDesc tgt_desc = { surface->targetW, surface->targetH, 1, (unsigned int)surface->msaaSamples, 1 };
+
+    surface->unityColorBuffer   = UnityCreateDummySurface(surface->unityColorBuffer, true, &tgt_desc);
+    surface->unityDepthBuffer   = UnityCreateDummySurface(surface->unityDepthBuffer, false, &tgt_desc);
+
+    surface->systemColorBuffer = UnityCreateDummySurface(surface->systemColorBuffer, true, &sys_desc);
+}
+
+extern "C" void DestroyUnityRenderBuffersNULL(UnityDisplaySurfaceBase* surface)
+{
+    UnityDestroyExternalSurface(surface->unityColorBuffer);
+    UnityDestroyExternalSurface(surface->systemColorBuffer);
+    surface->unityColorBuffer = surface->systemColorBuffer = 0;
+
+    UnityDestroyExternalSurface(surface->unityDepthBuffer);
+    surface->unityDepthBuffer = 0;
+}
+
+extern "C" void InitRenderingNULL() {}
+extern "C" void CreateSystemRenderingSurfaceNULL(UnityDisplaySurfaceBase* surface)  {}
+extern "C" void StartFrameRenderingNULL(UnityDisplaySurfaceBase* surface)           {}
+extern "C" void EndFrameRenderingNULL(UnityDisplaySurfaceBase* surface)             {}

+ 35 - 0
unity_ios/Classes/Unity/ObjCRuntime.h

@@ -0,0 +1,35 @@
+#pragma once
+
+#include <objc/objc.h>
+#include <objc/runtime.h>
+#include <objc/message.h>
+
+// simulator and device differ in how they want objc_msgSendXXX to be called:
+// device wants objc_msgSendXXX to be casted to proper type (same as selector we want to call)
+// while simulator wants to call them directly
+#if TARGET_OS_SIMULATOR
+    #define UNITY_OBJC_SEND_MSG(selectorType, msgSendFunc) msgSendFunc
+#else
+    #define UNITY_OBJC_SEND_MSG(selectorType, msgSendFunc) ((selectorType)msgSendFunc)
+#endif
+
+
+#define UNITY_OBJC_FORWARD_TO_SUPER(self_, super_, selector, selectorType, ...)                 \
+    do {                                                                                        \
+        struct objc_super super = { .receiver = self_, .super_class = super_ };                 \
+        UNITY_OBJC_SEND_MSG(selectorType, objc_msgSendSuper)(&super, selector, __VA_ARGS__);    \
+    } while(0)
+
+#define UNITY_OBJC_CALL_ON_SELF(self_, selector, selectorType, ...)                     \
+    do {                                                                                \
+        UNITY_OBJC_SEND_MSG(selectorType, objc_msgSend)(self_, selector, __VA_ARGS__);  \
+    } while(0)
+
+
+// method type encoding for methods we override
+// to get this you need to do: method_getTypeEncoding(class_getInstanceMethod(class, sel)) or method_getTypeEncoding(class_getClassMethod(class, sel))
+#define UIView_LayerClass_Enc "#8@0:4"
+#define UIViewController_supportedInterfaceOrientations_Enc "Q16@0:8"
+#define UIViewController_prefersStatusBarHidden_Enc "B16@0:8"
+#define UIScreen_maximumFramesPerSecond_Enc "q16@0:8"
+#define UIView_safeAreaInsets_Enc "{UIEdgeInsets=dddd}16@0:8"

+ 106 - 0
unity_ios/Classes/Unity/OnDemandResources.mm

@@ -0,0 +1,106 @@
+#import "Foundation/Foundation.h"
+#if ENABLE_IOS_ON_DEMAND_RESOURCES
+    #import "Foundation/NSBundle.h"
+#endif
+
+
+typedef void (*OnDemandResourcesRequestCompleteHandler)(void* handlerData, const char* error);
+
+
+#if ENABLE_IOS_ON_DEMAND_RESOURCES
+
+
+struct OnDemandResourcesRequestData
+{
+    NSBundleResourceRequest* request;
+};
+
+
+UNITY_EXPORT extern "C" OnDemandResourcesRequestData* UnityOnDemandResourcesCreateRequest(NSSet * tags, OnDemandResourcesRequestCompleteHandler handler, void* handlerData)
+{
+    OnDemandResourcesRequestData* data = new OnDemandResourcesRequestData();
+    data->request = [[NSBundleResourceRequest alloc] initWithTags: tags];
+    [data->request beginAccessingResourcesWithCompletionHandler:^(NSError* error) {
+        dispatch_async(dispatch_get_main_queue(), ^{
+            const char* errorMessage = error ? [[error localizedDescription] UTF8String] : NULL;
+            handler(handlerData, errorMessage);
+        });
+    }];
+    return data;
+}
+
+UNITY_EXPORT extern "C" void UnityOnDemandResourcesRelease(OnDemandResourcesRequestData* data)
+{
+    [data->request endAccessingResources];
+    delete data;
+}
+
+UNITY_EXPORT extern "C" float UnityOnDemandResourcesGetProgress(OnDemandResourcesRequestData* data)
+{
+    return data->request.progress.fractionCompleted;
+}
+
+UNITY_EXPORT extern "C" float UnityOnDemandResourcesGetLoadingPriority(OnDemandResourcesRequestData* data)
+{
+    float priority = (float)data->request.loadingPriority;
+    return priority;
+}
+
+UNITY_EXPORT extern "C" void UnityOnDemandResourcesSetLoadingPriority(OnDemandResourcesRequestData* data, float priority)
+{
+    if (priority < 0.0f)
+        priority = 0.0f;
+
+    if (priority > 1.0f)
+        data->request.loadingPriority = NSBundleResourceRequestLoadingPriorityUrgent;
+    else
+        data->request.loadingPriority = (double)priority;
+}
+
+UNITY_EXPORT extern "C" NSString* UnityOnDemandResourcesGetResourcePath(OnDemandResourcesRequestData * data, const char* resource)
+{
+    NSString* path = [[data->request bundle] pathForResource: [NSString stringWithUTF8String: resource] ofType: nil];
+    return path;
+}
+
+#else // ENABLE_IOS_ON_DEMAND_RESOURCES
+
+
+struct OnDemandResourcesRequestData
+{
+};
+
+
+UNITY_EXPORT extern "C" OnDemandResourcesRequestData* UnityOnDemandResourcesCreateRequest(NSSet * tags, OnDemandResourcesRequestCompleteHandler handler, void* handlerData)
+{
+    OnDemandResourcesRequestData* data = new OnDemandResourcesRequestData();
+    if (handler)
+        handler(handlerData, NULL);
+    return data;
+}
+
+UNITY_EXPORT extern "C" void UnityOnDemandResourcesRelease(OnDemandResourcesRequestData* data)
+{
+    delete data;
+}
+
+UNITY_EXPORT extern "C" float UnityOnDemandResourcesGetProgress(OnDemandResourcesRequestData* data)
+{
+    return 1.0f;
+}
+
+UNITY_EXPORT extern "C" float UnityOnDemandResourcesGetLoadingPriority(OnDemandResourcesRequestData* data)
+{
+    return 0.5;
+}
+
+UNITY_EXPORT extern "C" void UnityOnDemandResourcesSetLoadingPriority(OnDemandResourcesRequestData* data, float priority)
+{
+}
+
+UNITY_EXPORT extern "C" NSString* UnityOnDemandResourcesGetResourcePath(OnDemandResourcesRequestData * data, const char* resource)
+{
+    return [NSString stringWithUTF8String: resource];
+}
+
+#endif // ENABLE_IOS_ON_DEMAND_RESOURCES

+ 145 - 0
unity_ios/Classes/Unity/UnityForwardDecls.h

@@ -0,0 +1,145 @@
+#pragma once
+
+#include <stdint.h>
+#include "UnitySharedDecls.h"
+
+#ifdef __OBJC__
+@class NSArray;
+@class NSBundle;
+@class NSData;
+@class NSDictionary;
+@class NSError;
+@class NSSet;
+@class NSString;
+@class UIEvent;
+@class UIKeyCommand;
+@class UIScreen;
+@class UITouch;
+@class UIView;
+@class UIViewController;
+@class UIWindow;
+
+@class UnityView;
+@class UnityViewControllerBase;
+#else
+typedef struct objc_object NSArray;
+typedef struct objc_object NSBundle;
+typedef struct objc_object NSData;
+typedef struct objc_object NSDictionary;
+typedef struct objc_object NSError;
+typedef struct objc_object NSSet;
+typedef struct objc_object NSString;
+typedef struct objc_object UIEvent;
+typedef struct objc_object UIKeyCommand;
+typedef struct objc_object UIScreen;
+typedef struct objc_object UITouch;
+typedef struct objc_object UIView;
+typedef struct objc_object UIViewController;
+typedef struct objc_object UIWindow;
+
+typedef struct objc_object UnityView;
+typedef struct objc_object UnityViewControllerBase;
+#endif
+
+// unity internal audio effect definition struct
+struct UnityAudioEffectDefinition;
+
+// new unity rendering api
+struct IUnityInterfaces;
+
+// be aware that this struct is shared with unity implementation so you should absolutely not change it
+struct UnityFrameStats
+{
+    uint64_t    fixedBehaviourManagerDt;
+    uint64_t    fixedPhysicsManagerDt;
+    uint64_t    dynamicBehaviourManagerDt;
+    uint64_t    coroutineDt;
+    uint64_t    skinMeshUpdateDt;
+    uint64_t    animationUpdateDt;
+    uint64_t    renderDt;
+    uint64_t    cullingDt;
+    uint64_t    clearDt;
+    int         fixedUpdateCount;
+
+    int         batchCount;
+    uint64_t    drawCallTime;
+    int         drawCallCount;
+    int         triCount;
+    int         vertCount;
+
+    uint64_t    dynamicBatchDt;
+    int         dynamicBatchCount;
+    int         dynamicBatchedDrawCallCount;
+    int         dynamicBatchedTris;
+    int         dynamicBatchedVerts;
+
+    int         staticBatchCount;
+    int         staticBatchedDrawCallCount;
+    int         staticBatchedTris;
+    int         staticBatchedVerts;
+};
+
+
+// be aware that this enum is shared with unity implementation so you should absolutely not change it
+typedef enum
+    LogType
+{
+    logError        = 0,
+    logAssert       = 1,
+    logWarning      = 2,
+    logLog          = 3,
+    logException    = 4,
+    logDebug        = 5,
+}
+LogType;
+
+// this dictates touches processing on os level: should we transform touches to unity view coords or not.
+// N.B. touch.position will always be adjusted to current resolution
+//      i.e. if you touch right border of view, touch.position.x will be Screen.width, not view.width
+//      to get coords in view space (os-coords), use touch.rawPosition
+typedef enum ViewTouchProcessing
+{
+    // the touches originated from view will be ignored by unity
+    touchesIgnored = 0,
+
+    // touches would be processed as if they were originated in unity view:
+    // coords will be transformed from view coords to unity view coords
+    touchesTransformedToUnityViewCoords = 1,
+
+    // touches coords will be kept intact (in originated view coords)
+    // it is default value
+    touchesKeptInOriginalViewCoords = 2,
+}
+ViewTouchProcessing;
+
+// be aware that this enum is shared with unity implementation so you should absolutely not change it
+typedef enum KeyboardStatus
+{
+    Visible     = 0,
+    Done        = 1,
+    Canceled    = 2,
+    LostFocus   = 3,
+}
+KeyboardStatus;
+
+// misc
+#ifdef __cplusplus
+extern "C" {
+    bool UnityiOS81orNewer();
+    bool UnityiOS82orNewer();
+    bool UnityiOS90orNewer();
+    bool UnityiOS91orNewer();
+    bool UnityiOS100orNewer();
+    bool UnityiOS101orNewer();
+    bool UnityiOS102orNewer();
+    bool UnityiOS103orNewer();
+    bool UnityiOS110orNewer();
+    bool UnityiOS111orNewer();
+    bool UnityiOS112orNewer();
+    bool UnityiOS130orNewer();
+    bool UnityiOS140orNewer();
+    bool UnityiOS150orNewer();
+    bool UnityiOS160orNewer();
+    bool UnityiOSVersionIsAtLeast(uint32_t major, uint32_t minor = 0);
+}
+#endif

+ 441 - 0
unity_ios/Classes/Unity/UnityInterface.h

@@ -0,0 +1,441 @@
+#pragma once
+
+#include <stdint.h>
+#include <stdarg.h>
+
+#include "UnityForwardDecls.h"
+#include "UnityRendering.h"
+
+#ifdef __OBJC__
+#import "Foundation/Foundation.h"
+#endif
+
+// unity plugin functions
+
+// audio plugin api
+typedef int     (*UnityPluginGetAudioEffectDefinitionsFunc)(struct UnityAudioEffectDefinition*** descptr);
+
+// OLD rendering plugin api (will become obsolete soon)
+typedef void    (*UnityPluginSetGraphicsDeviceFunc)(void* device, int deviceType, int eventType);
+typedef void    (*UnityPluginRenderMarkerFunc)(int marker);
+
+// new rendering plugin api
+typedef void    (*UnityPluginLoadFunc)(struct IUnityInterfaces* unityInterfaces);
+typedef void    (*UnityPluginUnloadFunc)(void);
+
+
+// log handler function
+#ifdef __cplusplus
+typedef bool (*LogEntryHandler)(LogType logType, const char* log, va_list list);
+#endif
+
+//
+// these are functions referenced in trampoline and implemented in unity player lib
+//
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// life cycle management
+
+void    UnityInitRuntime(int argc, char* argv[]);
+void    UnityInitApplicationNoGraphics(const char* appPathName);
+void    UnityUnloadApplication(void);
+void    UnityQuitApplication(int exitCode);
+void    UnityInitApplicationGraphics(void);
+void    UnityCleanup(void);
+void    UnityLoadApplication(void);
+void    UnityLoadApplicationFromSceneLessState(void);
+void    UnitySetPlayerFocus(int focused);   // send OnApplicationFocus() message to scripts
+void    UnityLowMemory(void);
+void    UnityPause(int pause);
+void    UnitySuppressPauseMessage(void);
+int     UnityIsPaused(void);                // 0 if player is running, 1 if paused
+int     UnityIsFocused(void);               // 1 if player is focused, 0 if in the background
+void    UnityWillPause(void);               // send the message that app will pause
+void    UnityWillResume(void);              // send the message that app will resume
+void    UnityDeliverUIEvents(void);         // unity processing impacting UI will be called in there
+void    UnityWaitForFrame();
+
+void    UnityInputProcess(void);            // no longer used, will be removed soon
+
+// player loop handling:
+// normal player loop
+void    UnityPlayerLoopWithBackbuffer(UnityRenderBufferHandle color, UnityRenderBufferHandle depth);
+// just render, without actually running player loop (used for CAMetalDisplayLink callback when unity is paused)
+void    UnityRenderWithoutPlayerLoopWithBackbuffer(UnityRenderBufferHandle color, UnityRenderBufferHandle depth);
+// batchmode player loop: no rendering to view (useful for background processing)
+void    UnityBatchPlayerLoop(void);
+// checks if we need to quit or unload unity; needs to happen after we are fully done with the current frame
+void    UnityCheckUnloadAndQuit(void);
+// these are deprecated (we do not call them anymore from the trampoline, but we keep them around for the possible plugins usage)
+void    UnityPlayerLoop(void) __attribute__((deprecated("Use UnityPlayerLoopWithBackbuffer instead of UnityPlayerLoop")));
+void    UnityRenderWithoutPlayerLoop(void) __attribute__((deprecated("Use UnityRenderWithoutPlayerLoopWithBackbuffer instead of UnityRenderWithoutPlayerLoop")));
+
+
+// rendering
+
+int     UnityGetRenderingAPI(void);
+void    UnityFinishRendering(void);
+void    UnityDisplayLinkCallback(double /*machAbsoluteTimeSeconds*/); // argument is not used anymore
+
+// controling player internals
+
+// TODO: needs some cleanup
+void    UnitySetAudioSessionActive(int active);
+void    UnityGLInvalidateState(void);
+void    UnityReloadResources(void);
+int     UnityIsCaptureScreenshotRequested(void);
+void    UnityCaptureScreenshot(void);
+void    UnitySendMessage(const char* obj, const char* method, const char* msg);
+void    UnityUpdateMuteState(int mute);
+int     UnityShouldMuteOtherAudioSources(void);
+int     UnityShouldPrepareForIOSRecording(void);
+int     UnityIsAudioManagerAvailableAndEnabled(void);
+
+#ifdef __cplusplus
+void    UnitySetLogEntryHandler(LogEntryHandler newHandler);
+#endif
+
+
+// plugins support
+
+// WARNING: old UnityRegisterRenderingPlugin will become obsolete soon
+void    UnityRegisterRenderingPlugin(UnityPluginSetGraphicsDeviceFunc setDevice, UnityPluginRenderMarkerFunc renderMarker);
+
+void    UnityRegisterRenderingPluginV5(UnityPluginLoadFunc loadPlugin, UnityPluginUnloadFunc unloadPlugin) __attribute__((deprecated("Renamed to UnityRegisterPlugin", "UnityRegisterPlugin")));
+void    UnityRegisterPlugin(UnityPluginLoadFunc loadPlugin, UnityPluginUnloadFunc unloadPlugin);
+void    UnityRegisterAudioPlugin(UnityPluginGetAudioEffectDefinitionsFunc getAudioEffectDefinitions);
+
+
+// resolution/orientation handling
+
+void    UnityGetRenderingResolution(unsigned* w, unsigned* h);
+void    UnityGetSystemResolution(unsigned* w, unsigned* h);
+
+void    UnityRequestRenderingResolution(unsigned w, unsigned h);
+
+int     UnityIsOrientationEnabled(unsigned /*ScreenOrientation*/ orientation);
+
+int     UnityHasOrientationRequest(void);
+int     UnityShouldAutorotate(void);
+int     UnityAutorotationStatusChanged(void);
+int     UnityShouldChangeAllowedOrientations(void);
+int     UnityRequestedScreenOrientation(void); // returns ScreenOrientation
+void    UnityOrientationRequestWasCommitted(void);
+
+int     UnityReportResizeView(unsigned w, unsigned h, unsigned /*ScreenOrientation*/ contentOrientation);   // returns ScreenOrientation
+void    UnityReportSafeAreaChange(float x, float y, float w, float h);
+void    UnityReportBackbufferChange(UnityRenderBufferHandle colorBB, UnityRenderBufferHandle depthBB);
+#if !PLATFORM_VISIONOS
+float   UnityCalculateScalingFactorFromTargetDPI(UIScreen* screen);
+int     UnityResolutionScalingFixedDPIFactorChanged(void);
+#endif
+void    UnityReportDisplayCutouts(const float* x, const float* y, const float* width, const float* height, int count);
+
+// player settings
+
+int     UnityDisableDepthAndStencilBuffers(void);
+int     UnityUseAnimatedAutorotation(void);
+int     UnityGetDesiredMSAASampleCount(int defaultSampleCount);
+int     UnityGetSRGBRequested(void);
+int     UnityGetWideColorRequested(void);
+void    UnitySetEDRValues(float maxEDRValue, float currentEDRValue);
+void    UnitySetHDRMode(int hdrMode);
+int     UnityGetHDRModeRequested(void);
+int     UnityGetShowActivityIndicatorOnLoading(void);
+int     UnityGetAccelerometerFrequency(void);
+int     UnityGetTargetFPS(void);
+int     UnityGetUseCustomAppBackgroundBehavior(void);
+int     UnityGetDeferSystemGesturesTopEdge(void);
+int     UnityGetDeferSystemGesturesBottomEdge(void);
+int     UnityGetDeferSystemGesturesLeftEdge(void);
+int     UnityGetDeferSystemGesturesRightEdge(void);
+int     UnityGetHideHomeButton(void);
+int     UnityMetalFramebufferOnly(void);
+int     UnityMetalMemorylessDepth(void);
+int     UnityPreserveFramebufferAlpha(void);
+void    UnitySetTargetFPS(int targetFPS);
+void    UnitySetAbsoluteURL(const char* url);
+
+#ifdef __cplusplus
+bool    UnityShouldUseMetalDisplayLink(void);
+#endif
+
+// native events
+
+void    UnityInvalidateDisplayDataCache(void* screen);
+void    UnityUpdateDisplayListCache(void** screens, int screenCount);
+
+// profiler
+
+void*   UnityCreateProfilerCounter(const char*);
+void    UnityDestroyProfilerCounter(void*);
+void    UnityStartProfilerCounter(void*);
+void    UnityEndProfilerCounter(void*);
+
+
+// sensors
+
+void    UnitySensorsSetGyroRotationRate(int idx, float x, float y, float z);
+void    UnitySensorsSetGyroRotationRateUnbiased(int idx, float x, float y, float z);
+void    UnitySensorsSetGravity(int idx, float x, float y, float z);
+void    UnitySensorsSetUserAcceleration(int idx, float x, float y, float z);
+void    UnitySensorsSetAttitude(int idx, float x, float y, float z, float w);
+void    UnityDidAccelerate(float x, float y, float z, double timestamp);
+void    UnitySetJoystickPosition(int joyNum, int axis, float pos);
+int     UnityStringToKey(const char *name);
+void    UnitySetKeyState(int key, int /*bool*/ state);
+void    UnitySetKeyboardKeyState(int key, int /*bool*/ state);
+void    UnitySendKeyboardCommand(UIKeyCommand* command, int code);
+int     UnityShouldAdjustPerformanceOnThermalStateChange();
+int     UnityGetThermalStateSeriousFPS();
+int     UnityGetThermalStateCriticalFPS();
+void    UnityThermalStateChanged(int state);
+
+// UnityWebRequest handling
+
+void    UnityReportWebRequestStatus(void* udata, int status);
+void    UnityReportWebRequestNetworkError(void* udata, int status);
+void    UnityReportWebRequestResponseHeader(void* udata, const char* headerName, const char* headerValue);
+void    UnityReportWebRequestReceivedResponse(void* udata, unsigned expectedDataLength);
+void    UnityReportWebRequestReceivedData(void* udata, const void* buffer, unsigned totalRead, unsigned expectedTotal);
+void    UnityReportWebRequestFinishedLoadingData(void* udata);
+void    UnityWebRequestRelease(void* udata);
+void    UnityReportWebRequestSentData(void* udata, unsigned totalWritten, unsigned expectedTotal);
+int     UnityReportWebRequestValidateCertificate(void* udata, const void* certificateData, unsigned certificateSize);
+unsigned long long UnityWebRequestResetUpload(void* udata);
+const void*   UnityWebRequestGetUploadData(void* udata, unsigned* bufferSize);
+void    UnityWebRequestConsumeUploadData(void* udata, unsigned consumedSize);
+
+// AVCapture
+
+void    UnityReportAVCapturePermission(void* userData);
+void    UnityDidCaptureVideoFrame(intptr_t tex, void* udata);
+
+// logging override
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+
+// touches processing
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void    UnitySetViewTouchProcessing(UIView* view, int /*ViewTouchProcessing*/ processingPolicy);
+void    UnityDropViewTouchProcessing(UIView* view);
+
+void    UnitySendTouchesBegin(NSSet* touches, UIEvent* event);
+void    UnitySendTouchesEnded(NSSet* touches, UIEvent* event);
+void    UnitySendTouchesCancelled(NSSet* touches, UIEvent* event);
+void    UnitySendTouchesMoved(NSSet* touches, UIEvent* event);
+void    UnitySendTouchesUnfiltered(NSSet* touches, NSSet* allTouches);
+
+void    UnityCancelTouches(void);
+void    UnitySendScrollWheel(float deltaX, float deltaY);
+void    UnitySendMousePosition(float x, float y);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+
+//
+// these are functions referenced and implemented in trampoline
+//
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// UnityAppController.mm
+UIViewController*       UnityGetGLViewController(void);
+UIView*                 UnityGetGLView(void);
+UnityView*              UnityGetUnityView(void);
+UIWindow*               UnityGetMainWindow(void);
+enum ScreenOrientation  UnityCurrentOrientation(void);
+
+// Unity/DisplayManager.mm
+#if !PLATFORM_VISIONOS
+float                   UnityScreenScaleFactor(UIScreen* screen);
+#endif
+
+// Unity/DeviceSettings.mm
+int                     UnityDeviceHasCutout(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+
+//
+// these are functions referenced in unity player lib and implemented in trampoline
+//
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// iPhone_Sensors.mm
+void            UnityInitJoysticks(void);
+void            UnityCoreMotionStart(void);
+void            UnityCoreMotionStop(void);
+void            UnityUpdateAccelerometerData(void);
+int             UnityIsGyroEnabled(int idx);
+int             UnityIsGyroAvailable(void);
+void            UnityUpdateGyroData(void);
+void            UnitySetGyroUpdateInterval(int idx, float interval);
+float           UnityGetGyroUpdateInterval(int idx);
+void            UnityUpdateJoystickData(void);
+NSArray*        UnityGetJoystickNames(void);
+void            UnityGetJoystickAxisName(int idx, int axis, char* buffer, int maxLen);
+void            UnityGetNiceKeyname(int key, char* buffer, int maxLen);
+
+// UnityAppController+Rendering.mm
+void            UnityGfxInitedCallback(void);
+void            UnityPresentContextCallback();
+void            UnityFramerateChangeCallback(int targetFPS);
+void            UnitySelectRenderingAPI(void);
+int             UnitySelectedRenderingAPI(void);
+int             UnityIsBatchmode(void);
+int             UnityShouldRunInBackground(void);
+
+NSBundle*           UnityGetMetalBundle(void);
+MTLDeviceRef        UnityGetMetalDevice(void);
+MTLCommandQueueRef  UnityGetMetalCommandQueue(void);
+int UnityCommandQueueMaxCommandBufferCountMTL(void);
+
+// deprecated, soon to be removed
+MTLCommandQueueRef  UnityGetMetalDrawableCommandQueue(void);
+
+UnityRenderBufferHandle UnityBackbufferColor(void);
+UnityRenderBufferHandle UnityBackbufferDepth(void);
+
+int             UnityIsWideColorSupported(void);
+
+// UI/ActivityIndicator.mm
+void            UnityStartActivityIndicator(void);
+void            UnityStopActivityIndicator(void);
+
+// UI/Keyboard.mm
+void            UnityKeyboard_Create(unsigned keyboardType, int autocorrection, int multiline, int secure, int alert, const char* text, const char* placeholder, int characterLimit);
+void            UnityKeyboard_Show(void);
+void            UnityKeyboard_Hide(void);
+void            UnityKeyboard_GetRect(float* x, float* y, float* w, float* h);
+void            UnityKeyboard_SetText(const char* text);
+NSString*       UnityKeyboard_GetText(void);
+int             UnityKeyboard_IsActive(void);
+int             UnityKeyboard_Status(void);
+void            UnityKeyboard_SetInputHidden(int hidden);
+int             UnityKeyboard_IsInputHidden(void);
+void            UnityKeyboard_SetCharacterLimit(unsigned characterLimit);
+
+int             UnityKeyboard_CanGetSelection(void);
+void            UnityKeyboard_GetSelection(int* location, int* range);
+int             UnityKeyboard_CanSetSelection(void);
+void            UnityKeyboard_SetSelection(int location, int range);
+
+// UI/UnityViewControllerBase.mm
+void            UnityNotifyHideHomeButtonChange(void);
+void            UnityNotifyDeferSystemGesturesChange(void);
+
+
+// Unity/AVCapture.mm
+int             UnityGetAVCapturePermission(int captureTypes);
+void            UnityRequestAVCapturePermission(int captureTypes, void* userData);
+
+// Unity/CameraCapture.mm
+void            UnityEnumVideoCaptureDevices(void* udata, void(*callback)(void* udata, const char* name, int frontFacing, int autoFocusPointSupported, int kind, const int* resolutions, int resCount));
+void*           UnityInitCameraCapture(int device, int w, int h, int fps, int isDepth, void* udata);
+void            UnityStartCameraCapture(void* capture);
+void            UnityPauseCameraCapture(void* capture);
+void            UnityStopCameraCapture(void* capture);
+void            UnityCameraCaptureExtents(void* capture, int* w, int* h);
+void            UnityCameraCaptureReadToMemory(void* capture, void* dst, int w, int h);
+int             UnityCameraCaptureVideoRotationDeg(void* capture);
+int             UnityCameraCaptureVerticallyMirrored(void* capture);
+int             UnityCameraCaptureSetAutoFocusPoint(void* capture, float x, float y);
+
+
+// Unity/DeviceSettings.mm
+const char*     UnityDeviceUniqueIdentifier(void);
+const char*     UnityVendorIdentifier(void);
+const char*     UnityAdIdentifier(void);
+int             UnityAdTrackingEnabled(void);
+int             UnityGetLowPowerModeEnabled(void);
+int             UnityGetWantsSoftwareDimming(void);
+void            UnitySetWantsSoftwareDimming(int enabled);
+int             UnityGetIosAppOnMac(void);
+const char*     UnityDeviceName(void);
+const char*     UnitySystemName(void);
+const char*     UnitySystemVersion(void);
+const char*     UnityDeviceModel(void);
+int             UnityDeviceCPUCount(void);
+int             UnityGetPhysicalMemory(void);
+int             UnityDeviceGeneration(void);
+float           UnityDeviceDPI(void);
+const char*     UnitySystemLanguage(void);
+int             UnityDeviceSupportsUpsideDown(void);
+
+// Unity/DisplayManager.mm
+void            UnityActivateScreenForRendering(void* nativeDisplay);
+void            UnityStartFrameRendering(void);
+void            UnityDestroyUnityRenderSurfaces(void);
+int             UnityMainScreenRefreshRate(void);
+void            UnitySetBrightness(float brightness);
+float           UnityGetBrightness(void);
+
+// Unity/Filesystem.mm
+const char*     UnityDataBundleDir(void);
+void            UnitySetDataBundleDirWithBundleId(const char * bundleId);
+const char*     UnityDocumentsDir(void);
+const char*     UnityLibraryDir(void);
+const char*     UnityCachesDir(void);
+int             UnityUpdateNoBackupFlag(const char* path, int setFlag); // Returns 1 if successful, otherwise 0
+
+// Unity/FullScreenVideoPlayer.mm
+int             UnityIsFullScreenPlaying(void);
+void            TryResumeFullScreenVideo(void);
+
+//Apple TV Remote
+int         UnityGetAppleTVRemoteAllowExitToMenu(void);
+void        UnitySetAppleTVRemoteAllowExitToMenu(int val);
+int         UnityGetAppleTVRemoteAllowRotation(void);
+void        UnitySetAppleTVRemoteAllowRotation(int val);
+int         UnityGetAppleTVRemoteReportAbsoluteDpadValues(void);
+void        UnitySetAppleTVRemoteReportAbsoluteDpadValues(int val);
+int         UnityGetAppleTVRemoteTouchesEnabled(void);
+void        UnitySetAppleTVRemoteTouchesEnabled(int val);
+
+// Unity/UnityReplayKit.mm
+void         UnityShouldCreateReplayKitOverlay(void);
+
+// Runtime analytics
+void UnitySendEmbeddedLaunchEvent(int launchType); // Tracks events when application is launched from native host app (Unity as a Library)
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+
+#ifdef __OBJC__
+// This is basically a wrapper for [NSString UTF8String] with additional strdup.
+//
+// Apparently multiple calls on UTF8String will leak memory (NSData objects) that are collected
+// only when @autoreleasepool is exited. This function serves as documentation for this and as a
+// handy wrapper.
+inline char* AllocCString(NSString* value)
+{
+    if (value == nil)
+        return 0;
+
+    const char* str = [value UTF8String];
+    return str ? strdup(str) : 0;
+}
+
+#endif

+ 378 - 0
unity_ios/Classes/Unity/UnityRendering.h

@@ -0,0 +1,378 @@
+#pragma once
+
+#include <stdint.h>
+
+#ifdef __OBJC__
+@class CAMetalLayer;
+@protocol CAMetalDrawable;
+@protocol MTLDrawable;
+@protocol MTLDevice;
+@protocol MTLTexture;
+@protocol MTLCommandBuffer;
+@protocol MTLCommandQueue;
+@protocol MTLCommandEncoder;
+
+typedef id<CAMetalDrawable>     CAMetalDrawableRef;
+typedef id<MTLDevice>           MTLDeviceRef;
+typedef id<MTLTexture>          MTLTextureRef;
+typedef id<MTLCommandBuffer>    MTLCommandBufferRef;
+typedef id<MTLCommandQueue>     MTLCommandQueueRef;
+typedef id<MTLCommandEncoder>   MTLCommandEncoderRef;
+#else
+typedef struct objc_object      CAMetalLayer;
+typedef struct objc_object*     CAMetalDrawableRef;
+typedef struct objc_object*     MTLDeviceRef;
+typedef struct objc_object*     MTLTextureRef;
+typedef struct objc_object*     MTLCommandBufferRef;
+typedef struct objc_object*     MTLCommandQueueRef;
+typedef struct objc_object*     MTLCommandEncoderRef;
+#endif
+
+// if this is set, then variables that there were moved from UnityDisplaySurfaceMTL to swapchain
+//   will be still updated when acquiring drawable.
+// NOTE: in this case we assume that all the UnityViewSwapchain pointers passed to unity players are coming from UnityDisplaySurfaceMTL
+// if this is set UnityDisplaySurfaceBase still has removed variables, but they are no longer updated
+#if !defined(UNITY_DISPLAY_SURFACE_MTL_BACKWARD_COMPATIBILITY) && UNITY_TRAMPOLINE_IN_USE
+    #define UNITY_DISPLAY_SURFACE_MTL_BACKWARD_COMPATIBILITY 1
+#endif
+
+// unity internal native render buffer struct (the one you acquire in C# with RenderBuffer.GetNativeRenderBufferPtr())
+struct RenderSurfaceBase;
+typedef struct RenderSurfaceBase* UnityRenderBufferHandle;
+
+// be aware that this struct is shared with unity implementation so you should absolutely not change it
+typedef struct UnityRenderBufferDesc
+{
+    unsigned    width, height, depth;
+    unsigned    samples;
+
+    int         backbuffer;
+} UnityRenderBufferDesc;
+
+// trick to make structure inheritance work transparently between c/cpp
+// for c we use "anonymous struct"
+#ifdef __cplusplus
+    #define START_STRUCT(T, Base)   struct T : Base {
+    #define END_STRUCT(T)           };
+#else
+    #define START_STRUCT(T, Base)   typedef struct T { struct Base;
+    #define END_STRUCT(T)           } T;
+#endif
+
+// we will keep objc objects in struct, so we need to explicitely mark references as strong to not confuse ARC
+// please note that actual object lifetime is managed in objc++ code, so __unsafe_unretained is good enough for objc code
+// DO NOT assign objects to UnityDisplaySurface* members in objc code.
+// DO NOT store objects from UnityDisplaySurface* members in objc code, as this wont be caught by ARC
+#ifdef __OBJC__
+    #ifdef __cplusplus
+        #define OBJC_OBJECT_PTR __strong
+    #else
+        #define OBJC_OBJECT_PTR __unsafe_unretained
+    #endif
+#else
+    #define OBJC_OBJECT_PTR
+#endif
+
+// unity common rendering (display) surface
+typedef struct UnityDisplaySurfaceBase
+{
+    UnityRenderBufferHandle unityColorBuffer;
+    UnityRenderBufferHandle unityDepthBuffer;
+
+    UnityRenderBufferHandle systemColorBuffer;
+
+    unsigned            targetW, targetH;
+    unsigned            systemW, systemH;
+
+    int                 msaaSamples;
+    int                 srgb;                   // [bool]
+    int                 wideColor;              // [bool]
+    int                 hdr;                    // [bool]
+    int                 disableDepthAndStencil; // [bool]
+    int                 allowScreenshot;        // [bool] currently we allow screenshots (from script) only on main display
+    int                 memorylessDepth;        // [bool]
+
+    int                 api;                    // [UnityRenderingAPI]
+
+    // these are no longer supported, we keep them only to avoid breaking compilation
+#if UNITY_DISPLAY_SURFACE_MTL_BACKWARD_COMPATIBILITY
+    UnityRenderBufferHandle systemDepthBuffer   __attribute__((deprecated));
+    int                 useCVTextureCache       __attribute__((deprecated));
+    void*               cvTextureCache          __attribute__((deprecated));
+    void*               cvTextureCacheTexture   __attribute__((deprecated));
+    void*               cvPixelBuffer           __attribute__((deprecated));
+#endif
+
+} UnityDisplaySurfaceBase;
+
+typedef struct UnityViewSwapchain
+{
+    OBJC_OBJECT_PTR CAMetalLayer*       layer;
+
+    // drawable handling:
+    // CADisplayLink: we will call [CAMetalLayer nextDrawable] first time we need to use "backbuffer"
+    // CAMetalDisplayLink: we are getting drawable to render to from the callback
+    //   alas it might happen that we get next callback while still using current drawable (as in - while rendering previous frame)
+    //   thus we will "mimic" the logic for the old display link, by setting "next drawable to use" in callback
+    //   and "acquiring" drawable on first draw to the backbuffer just updates current drawable to the stored one
+    OBJC_OBJECT_PTR CAMetalDrawableRef  drawable;
+    OBJC_OBJECT_PTR CAMetalDrawableRef  nextDrawable;
+    OBJC_OBJECT_PTR MTLTextureRef       drawableTexture;
+} UnityViewSwapchain;
+
+// START_STRUCT confuse clang c compiler (though it is idiomatic c code that works)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wmissing-declarations"
+
+// on iOS/tvOS: we render to the drawable directly
+//              and we need proxy only to delay acquiring drawable until we actually want to render to the "backbuffer"
+//              thus just one proxy and it will be marked as "empty" (we only need it to query texture params, like extents)
+// on macOS:    we render to the offscreen RT and blit to the drawable, thus we need several proxy RT
+//              and all of them will be full blown textures (with GPU backing)
+#if PLATFORM_OSX
+    #define kUnityNumOffscreenSurfaces 2
+#else
+    #define kUnityNumOffscreenSurfaces 1
+#endif
+
+// Metal display surface
+START_STRUCT(UnityDisplaySurfaceMTL, UnityDisplaySurfaceBase)
+UnityViewSwapchain                  swapchain;
+OBJC_OBJECT_PTR MTLDeviceRef        device;
+
+UnityRenderBufferHandle             targetColorRB;
+UnityRenderBufferHandle             targetAAColorRB;
+
+OBJC_OBJECT_PTR MTLTextureRef       drawableProxyRT[kUnityNumOffscreenSurfaces];
+UnityRenderBufferHandle             drawableProxyRS[kUnityNumOffscreenSurfaces];
+
+// This is used on a Mac with drawableProxyRT when off-screen rendering is used
+int                                 proxySwaps;         // Counts times proxy RTs have swapped since surface recreated
+int                                 proxyReady;         // [bool] Proxy RT has swapped since last present; frame ended
+int                                 calledPresentDrawable; // Tracks presenting for editor.
+int                                 vsync;              // Is vsync enabled or not
+
+unsigned                            colorFormat;        // [MTLPixelFormat]
+unsigned                            depthFormat;        // [MTLPixelFormat]
+int                                 framebufferOnly;
+
+// these were moved to a separate structure. to simplify the lives of plugin writers we are keeping them here for some time
+// if these need to be updated XXX need to be defined: we will try to update these, but please move on from using them
+#if UNITY_DISPLAY_SURFACE_MTL_BACKWARD_COMPATIBILITY
+OBJC_OBJECT_PTR CAMetalLayer*       layer           __attribute__((deprecated));
+OBJC_OBJECT_PTR CAMetalDrawableRef  nextDrawable    __attribute__((deprecated));
+OBJC_OBJECT_PTR CAMetalDrawableRef  drawable        __attribute__((deprecated));
+OBJC_OBJECT_PTR MTLTextureRef       drawableTex     __attribute__((deprecated));
+
+// these are no longer used, and should have never been used before - we still keep them around but they stay zero-inited
+OBJC_OBJECT_PTR MTLTextureRef       systemColorRB __attribute__((deprecated));
+int                                 drawableProxyNeedsClear[kUnityNumOffscreenSurfaces] __attribute__((deprecated));
+
+// these we removed in favor of RTs managed inside player library, we now have renderbuffers instead
+OBJC_OBJECT_PTR MTLTextureRef       targetColorRT   __attribute__((deprecated));
+OBJC_OBJECT_PTR MTLTextureRef       targetAAColorRT __attribute__((deprecated));
+
+OBJC_OBJECT_PTR MTLTextureRef       depthRB         __attribute__((deprecated));
+OBJC_OBJECT_PTR MTLTextureRef       stencilRB       __attribute__((deprecated));
+#endif
+
+END_STRUCT(UnityDisplaySurfaceMTL)
+
+// START_STRUCT confuse clang c compiler (though it is idiomatic c code that works)
+#pragma clang diagnostic pop
+
+// be aware that this enum is shared with unity implementation so you should absolutely not change it
+typedef enum UnityRenderingAPI
+{
+    apiMetal        = 4,
+
+    // command line argument: -nographics
+    // does not initialize real graphics device and bypass all the rendering
+    // currently supported only on simulators
+    apiNoGraphics   = -1,
+} UnityRenderingAPI;
+
+typedef struct RenderingSurfaceParams
+{
+    // rendering setup
+    int msaaSampleCount;
+    int renderW;
+    int renderH;
+    int srgb;
+    int wideColor;
+    int hdr;
+    int metalFramebufferOnly;
+    int metalMemorylessDepth;
+
+    // unity setup
+    int disableDepthAndStencil;
+
+    // no longer supported
+#if UNITY_DISPLAY_SURFACE_MTL_BACKWARD_COMPATIBILITY
+    int useCVTextureCache   __attribute__((deprecated));
+#endif
+} RenderingSurfaceParams;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+int UnitySelectedRenderingAPI(void);
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+// metal
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void InitRenderingMTL(void);
+
+void CreateSystemRenderingSurfaceMTL(UnityDisplaySurfaceMTL* surface);
+void CreateUnityRenderBuffersMTL(UnityDisplaySurfaceMTL* surface);
+void DestroyUnityRenderBuffersMTL(UnityDisplaySurfaceMTL* surface);
+void StartFrameRenderingMTL(UnityDisplaySurfaceMTL* surface);
+void EndFrameRenderingMTL(UnityDisplaySurfaceMTL* surface);
+void PreparePresentMTL(UnityDisplaySurfaceMTL* surface, MTLCommandBufferRef cb);
+void PresentMTL(UnityDisplaySurfaceMTL* surface, MTLCommandBufferRef cb);
+
+// Acquires CAMetalDrawable resource for the surface and returns the drawable texture
+// AcquireDrawableMTL is deprecated and not used from unity side anymore
+//   we keep it here only to avoid breaking native plugins that might have used it
+MTLTextureRef AcquireDrawableMTL(UnityDisplaySurfaceMTL* surface);
+MTLTextureRef AcquireSwapchainDrawable(UnityViewSwapchain* swapchain);
+
+unsigned UnityHDRSurfaceDepth(void);
+
+// starting with ios11 apple insists on having just one presentDrawable per command buffer
+// hence we keep normal processing for main screen, but when airplay is used we will create extra command buffers
+void PreparePresentNonMainScreenMTL(UnityDisplaySurfaceMTL* surface);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+// no graphics
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void InitRenderingNULL(void);
+void CreateSystemRenderingSurfaceNULL(UnityDisplaySurfaceBase* surface);
+void CreateUnityRenderBuffersNULL(UnityDisplaySurfaceBase* surface);
+void DestroyUnityRenderBuffersNULL(UnityDisplaySurfaceBase* surface);
+void StartFrameRenderingNULL(UnityDisplaySurfaceBase* surface);
+void EndFrameRenderingNULL(UnityDisplaySurfaceBase* surface);
+void PreparePresentNULL(UnityDisplaySurfaceBase* surface);
+void PresentNULL(UnityDisplaySurfaceBase* surface);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// for Create* functions if surf is null we will actuially create new one, otherwise we update the one provided
+// metal: resolveTex should be non-nil only if tex have AA
+UnityRenderBufferHandle UnityCreateExternalSurfaceMTL(UnityRenderBufferHandle surf, int isColor, MTLTextureRef tex, const UnityRenderBufferDesc* desc);
+// Passing non-nil displaySurface will mark render surface as proxy and will do a delayed drawable acquisition when setting up framebuffer
+UnityRenderBufferHandle UnityCreateExternalColorSurfaceMTL(UnityRenderBufferHandle surf, MTLTextureRef tex, MTLTextureRef resolveTex, const UnityRenderBufferDesc* desc, UnityDisplaySurfaceMTL* displaySurface);
+UnityRenderBufferHandle UnityCreateExternalDepthSurfaceMTL(UnityRenderBufferHandle surf, MTLTextureRef tex, MTLTextureRef stencilTex, const UnityRenderBufferDesc* desc);
+// creates "dummy" surface - will indicate "missing" buffer (e.g. depth-only RT will have color as dummy)
+UnityRenderBufferHandle UnityCreateDummySurface(UnityRenderBufferHandle surf, int isColor, const UnityRenderBufferDesc* desc);
+
+// external render surfaces and textures are "out of scope" for memory profiler, hence we add means to register them separately
+// the separate mechanism is needed because unity cannot know what manages the lifetime of textures in this case
+//   specifically since we allow external render surfaces and textures to share metal textures
+void UnityRegisterExternalRenderSurfaceTextureForMemoryProfiler(MTLTextureRef tex);
+void UnityRegisterExternalTextureForMemoryProfiler(MTLTextureRef tex);
+void UnityUnregisterMetalTextureForMemoryProfiler(MTLTextureRef tex);
+
+// handling of unity "backbuffer"
+// internally we still pretend that backbuffer has depth, can have MSAA, or extents different from the window/view size
+// we had UnityCreateExternal* api before that was slightly too "wordy" to use, and was also using UnityDisplaySurfaceMTL
+//   which is wrong, and introduced to big a coupling
+// now, we have two things happening (with different velocities), triggering the need to update API
+//   even if this is not (might be not) the final form
+// first of all we are working on introducing swift trampoline, where we can simplify rendering logic;
+//   but also we do not want to drag in the whole UnityDisplaySurfaceMTL (it doesn't make sense nowadays)
+// thus we introduce intermediate explicit "swapchain" structure
+// this also plays nicely with moving towards having explicit "swapchain" concept internally,
+//   where (not matching view) resolution, MSAA, etc will be handled separately from "here is the connection to window to give to compositor"
+// hence we introduce the api using new UnityViewSwapchain structure (with minimal connection to view internals)
+// alas we are not yet ready to fully switch to have only swapchain in the platform layer (trampoline)
+//   thus we still keep the possibility to create "AA backbuffer that will be resolved to swapchain" or even custom resolution (copied to actual drawable)
+// another thing to note is that we are still bound to support "old" CADisplayLink, thus we need to be able to delay acquiring drawable
+//   so we still need to make sure we have RenderBuffer connecting to a "swapchain" to do the magic when we want to render to it
+// and that's why we have such a big api surface instead of simple "here is your swapchain, please render to it"
+//   but this will hopefully change soon
+// things of note:
+//   * note that we always pass "current" pointer (rbBackbuffer param)
+//     this api is working similarly to realloc: if you pass null we allocate and create new render buffer, otherwise we update the existing one
+//   * due to this, UnitySwapchainDestroyBackbuffer is called only if we really do not need this type of surface anymore
+
+UnityRenderBufferHandle UnitySwapchainCreateBackbuffer(UnityViewSwapchain* swapchain, UnityRenderBufferHandle rbBackbuffer);
+UnityRenderBufferHandle UnitySwapchainCreateBackbufferForExtents(UnityViewSwapchain* swapchain, UnityRenderBufferHandle rbBackbuffer, unsigned width, unsigned height);
+UnityRenderBufferHandle UnitySwapchainCreateAABackbufferResolveToSwapchain(UnityViewSwapchain* swapchain, UnityRenderBufferHandle rbBackbuffer, unsigned sampleCount);
+UnityRenderBufferHandle UnitySwapchainCreateAABackbuffer(UnityViewSwapchain* swapchain, UnityRenderBufferHandle rbBackbuffer, unsigned sampleCount, UnityRenderBufferHandle rbResolveTo);
+UnityRenderBufferHandle UnitySwapchainCreateDepthForBackbuffer(UnityViewSwapchain* swapchain, UnityRenderBufferHandle rbColorBackbuffer, UnityRenderBufferHandle rbDepthBackbuffer);
+void                    UnitySwapchainDestroyBackbuffer(UnityViewSwapchain* swapchain, UnityRenderBufferHandle rbBackbuffer);
+void                    UnitySwapchainBlitBackbuffer(UnityViewSwapchain* swapchain, UnityRenderBufferHandle rbColorBackbuffer, MTLCommandBufferRef cb);
+
+// disable rendering to render buffers (all Cameras that were rendering to one of buffers would be reset to use backbuffer)
+void    UnityDisableRenderBuffers(UnityRenderBufferHandle color, UnityRenderBufferHandle depth);
+// destroys render buffer
+void    UnityDestroyExternalSurface(UnityRenderBufferHandle surf);
+// sets current render target
+void    UnitySetRenderTarget(UnityRenderBufferHandle color, UnityRenderBufferHandle depth);
+// final blit to backbuffer
+void    UnityBlitToBackbuffer(UnityRenderBufferHandle srcColor, UnityRenderBufferHandle dstColor, UnityRenderBufferHandle dstDepth);
+// get native renderbuffer from handle
+
+// sets vSync on OSX 10.13 and up
+#if PLATFORM_OSX
+void MetalUpdateDisplaySync(void);
+#endif
+
+UnityRenderBufferHandle UnityNativeRenderBufferFromHandle(void *rb);
+
+MTLCommandBufferRef UnityCurrentMTLCommandBuffer(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+// metal/gles unification
+
+#define GLES_METAL_COMMON_IMPL_SURF(f)                                                                  \
+inline void f(UnityDisplaySurfaceBase* surface)                                                         \
+{                                                                                                       \
+    switch(surface->api) {                                                                              \
+        case apiMetal:                          f ## MTL((UnityDisplaySurfaceMTL*)surface);     break;  \
+        case apiNoGraphics:                     f ## NULL(surface);                             break;  \
+    }                                                                                                   \
+}                                                                                                       \
+
+#define GLES_METAL_COMMON_IMPL(f)                                       \
+inline void f()                                                         \
+{                                                                       \
+    switch(UnitySelectedRenderingAPI()) {                               \
+        case apiMetal:                          f ## MTL();     break;  \
+        case apiNoGraphics:                     f ## NULL();    break;  \
+    }                                                                   \
+}                                                                       \
+
+
+GLES_METAL_COMMON_IMPL(InitRendering);
+
+GLES_METAL_COMMON_IMPL_SURF(CreateSystemRenderingSurface);
+GLES_METAL_COMMON_IMPL_SURF(CreateUnityRenderBuffers);
+GLES_METAL_COMMON_IMPL_SURF(DestroyUnityRenderBuffers);
+GLES_METAL_COMMON_IMPL_SURF(StartFrameRendering);
+GLES_METAL_COMMON_IMPL_SURF(EndFrameRendering);
+
+#undef GLES_METAL_COMMON_IMPL_SURF
+#undef GLES_METAL_COMMON_IMPL

+ 53 - 0
unity_ios/Classes/Unity/UnityReplayKit.h

@@ -0,0 +1,53 @@
+#pragma once
+
+#if UNITY_REPLAY_KIT_AVAILABLE
+
+#import <Foundation/Foundation.h>
+#import <ReplayKit/ReplayKit.h>
+
+@interface UnityReplayKit : NSObject<RPPreviewViewControllerDelegate, RPScreenRecorderDelegate>
+{
+}
+
++ (instancetype)sharedInstance;
+
+@property(nonatomic, readonly) BOOL apiAvailable;
+
+@property(nonatomic, readonly) NSString* lastError;
+@property(nonatomic, readonly) RPPreviewViewController* previewController;
+@property(nonatomic, readonly) BOOL recordingPreviewAvailable;
+@property(nonatomic, readonly, getter = isRecording) BOOL recording;
+
+- (BOOL)startRecording;
+- (BOOL)stopRecording;
+- (BOOL)showPreview;
+- (BOOL)discardPreview;
+
+- (void)screenRecorder:(RPScreenRecorder*)screenRecorder didStopRecordingWithError:(NSError*)error previewViewController:(RPPreviewViewController*)previewViewController;
+- (void)previewControllerDidFinish:(RPPreviewViewController*)previewController;
+
+@property(nonatomic, readonly) BOOL broadcastingApiAvailable;
+@property(nonatomic, readonly) BOOL isBroadcasting;
+@property(nonatomic, readonly) BOOL isBroadcastingPaused;
+@property(nonatomic, readonly) BOOL isPreviewControllerActive;
+@property(nonatomic, readonly) NSURL* broadcastURL;
+@property(nonatomic, setter = setCameraEnabled:, getter = isCameraEnabled) BOOL cameraEnabled;
+@property(nonatomic, setter = setMicrophoneEnabled:, getter = isMicrophoneEnabled) BOOL microphoneEnabled;
+
+- (void)startBroadcastingWithCallback:(void *)callback;
+- (void)stopBroadcasting;
+- (void)pauseBroadcasting;
+- (void)resumeBroadcasting;
+- (BOOL)showCameraPreviewAt:(CGPoint)position width:(float)width height:(float)height;
+- (void)hideCameraPreview;
+- (void)createOverlayWindow;
+@end
+
+// starting with iOS13 RPScreenRecorder is not immediately ready for recording
+//   * it seems it does some magic on background thread
+// meaning that our api usage (do init in [UnityReplayKit sharedInstance]) is prone to errors
+// hence we introduce easly RPScreenRecorder "init"
+
+void InitUnityReplayKit();
+
+#endif  // UNITY_REPLAY_KIT_AVAILABLE

+ 563 - 0
unity_ios/Classes/Unity/UnityReplayKit.mm

@@ -0,0 +1,563 @@
+#if UNITY_REPLAY_KIT_AVAILABLE
+
+#import "UnityReplayKit.h"
+#import "UnityAppController.h"
+#import "UI/UnityViewControllerBase.h"
+#import "UnityInterface.h"
+#import <UIKit/UIKit.h>
+
+extern "C" void UnityReplayKitTriggerBroadcastStatusCallback(void* callback, bool hasSucceeded, const char* errorMessage);
+
+static UnityReplayKit* _replayKit = nil;
+
+@protocol UnityReplayKit_RPScreenRecorder<NSObject>
+
+- (void)setMicrophoneEnabled:(BOOL)value;
+- (BOOL)isMicrophoneEnabled;
+- (void)setCameraEnabled:(BOOL)value;
+- (BOOL)isCameraEnabled;
+- (BOOL)isPreviewControllerActive;
+
+@property (nonatomic, setter = setMicrophoneEnabled:, getter = isMicrophoneEnabled) BOOL microphoneEnabled;
+@property (nonatomic, setter = setCameraEnabled:, getter = isCameraEnabled) BOOL cameraEnabled;
+@property (nonatomic, readonly) UIView* cameraPreviewView;
+@property (nonatomic, getter = isPreviewControllerActive) BOOL previewControllerActive;
+
+@end
+
+@protocol UnityReplayKit_RPBroadcastController<NSObject>
+
+@property(nonatomic, readonly) NSURL *broadcastURL;
+@property(nonatomic, readonly, getter = isBroadcasting) BOOL broadcasting;
+@property(nonatomic, readonly) NSString *broadcastExtensionBundleID;
+//@property(nonatomic, weak) id<RPBroadcastControllerDelegate> delegate;
+@property(nonatomic, readonly, getter = isBroadcastingPaused) BOOL paused;
+@property(nonatomic, readonly) NSDictionary<NSString *, NSObject<NSCoding> *> *serviceInfo;
+
+- (BOOL)isBroadcasting;
+- (BOOL)isBroadcastingPaused;
+- (void)finishBroadcastWithHandler:(void (^)(NSError *error))handler;
+- (void)startBroadcastWithHandler:(void (^)(NSError *error))handler;
+- (void)pauseBroadcast;
+- (void)resumeBroadcast;
+
+@end
+
+@interface UnityReplayKit_RPBroadcastActivityViewController : UIViewController<NSObject>
+
+@property (nonatomic, weak) id delegate;
+
+@end
+
+// why do we care about orientation handling:
+// ReplayKit will disable top-window autorotation
+// as users keep asking to do autorotation during broadcast/record we create fake empty window with fake view controller
+// this window will have autorotation disabled instead of unity one
+// but this is not the end of the story: what fake view controller does is also important
+// now it is hard to speculate what *actually* happens but with setup like fake view controller takes over control over "supported orientations"
+// meaning that if we dont do anything suddenly all orientations become enabled.
+// to avoid that we create this monstrosity that pokes unity for orientation.
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+@interface UnityReplayKitViewController : UnityViewControllerBase
+{
+}
+- (NSUInteger)supportedInterfaceOrientations;
+@end
+@implementation UnityReplayKitViewController
+- (NSUInteger)supportedInterfaceOrientations
+{
+    NSUInteger ret = 0;
+    if (UnityShouldAutorotate())
+    {
+        if (UnityIsOrientationEnabled(portrait))
+            ret |= (1 << UIInterfaceOrientationPortrait);
+        if (UnityIsOrientationEnabled(portraitUpsideDown))
+            ret |= (1 << UIInterfaceOrientationPortraitUpsideDown);
+        if (UnityIsOrientationEnabled(landscapeLeft))
+            ret |= (1 << UIInterfaceOrientationLandscapeRight);
+        if (UnityIsOrientationEnabled(landscapeRight))
+            ret |= (1 << UIInterfaceOrientationLandscapeLeft);
+    }
+    else
+    {
+        switch (UnityRequestedScreenOrientation())
+        {
+            case portrait:              ret = (1 << UIInterfaceOrientationPortrait);            break;
+            case portraitUpsideDown:    ret = (1 << UIInterfaceOrientationPortraitUpsideDown);  break;
+            case landscapeLeft:         ret = (1 << UIInterfaceOrientationLandscapeRight);      break;
+            case landscapeRight:        ret = (1 << UIInterfaceOrientationLandscapeLeft);       break;
+        }
+    }
+    return ret;
+}
+
+@end
+#else
+    #define UnityReplayKitViewController UnityViewControllerBase
+#endif
+
+@implementation UnityReplayKit
+{
+    id<UnityReplayKit_RPBroadcastController> broadcastController;
+    void* broadcastStartStatusCallback;
+    UIView* currentCameraPreviewView;
+    bool currentPreviewControllerActive;
+
+    UIWindow* overlayWindow;
+}
+
+- (void)shouldCreateOverlayWindow
+{
+    UnityShouldCreateReplayKitOverlay();
+}
+
+- (void)createOverlayWindow
+{
+    if (self->overlayWindow == nil)
+    {
+        UIWindow* wnd = self->overlayWindow = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];
+        wnd.hidden = wnd.userInteractionEnabled = NO;
+        wnd.backgroundColor = nil;
+
+        wnd.rootViewController = [[UnityReplayKitViewController alloc] init];
+    }
+}
+
++ (UnityReplayKit*)sharedInstance
+{
+    NSAssert(_replayKit != nil, @"InitUnityReplayKit should be called before using ReplayKit api.");
+    return _replayKit;
+}
+
+- (BOOL)apiAvailable
+{
+    return ([RPScreenRecorder class] != nil) && [RPScreenRecorder sharedRecorder].isAvailable;
+}
+
+- (BOOL)recordingPreviewAvailable
+{
+    return _previewController != nil;
+}
+
+- (BOOL)startRecording
+{
+    RPScreenRecorder* recorder = [RPScreenRecorder sharedRecorder];
+    if (recorder == nil)
+    {
+        _lastError = [NSString stringWithUTF8String: "Failed to get Screen Recorder"];
+        return NO;
+    }
+
+    recorder.delegate = self;
+    __block BOOL success = YES;
+    [recorder startRecordingWithHandler:^(NSError* error) {
+        if (error != nil)
+        {
+            _lastError = [error description];
+            success = NO;
+        }
+        else
+        {
+            [self shouldCreateOverlayWindow];
+        }
+    }];
+
+    return success;
+}
+
+- (BOOL)isRecording
+{
+    RPScreenRecorder* recorder = [RPScreenRecorder sharedRecorder];
+    if (recorder == nil)
+    {
+        _lastError = [NSString stringWithUTF8String: "Failed to get Screen Recorder"];
+        return NO;
+    }
+    return recorder.isRecording;
+}
+
+- (BOOL)stopRecording
+{
+    RPScreenRecorder* recorder = [RPScreenRecorder sharedRecorder];
+    if (recorder == nil)
+    {
+        _lastError = [NSString stringWithUTF8String: "Failed to get Screen Recorder"];
+        return NO;
+    }
+
+    __block BOOL success = YES;
+    [recorder stopRecordingWithHandler:^(RPPreviewViewController* previewViewController, NSError* error) {
+        self->overlayWindow = nil;
+        if (error != nil)
+        {
+            _lastError = [error description];
+            success = NO;
+            return;
+        }
+        if (previewViewController != nil)
+        {
+            [previewViewController setPreviewControllerDelegate: self];
+            _previewController = previewViewController;
+        }
+    }];
+
+    return success;
+}
+
+- (void)screenRecorder:(RPScreenRecorder*)screenRecorder didStopRecordingWithError:(NSError*)error previewViewController:(RPPreviewViewController*)previewViewController
+{
+    if (error != nil)
+    {
+        _lastError = [error description];
+    }
+    self->overlayWindow = nil;
+    _previewController = previewViewController;
+}
+
+- (BOOL)showPreview
+{
+    if (_previewController == nil)
+    {
+        _lastError = [NSString stringWithUTF8String: "No recording available"];
+        return NO;
+    }
+
+    [_previewController setModalPresentationStyle: UIModalPresentationFullScreen];
+    [GetAppController().rootViewController presentViewController: _previewController animated: YES completion:^()
+    {
+        _previewController = nil;
+    }];
+
+    currentPreviewControllerActive = YES;
+
+    return YES;
+}
+
+- (BOOL)discardPreview
+{
+    if (_previewController == nil)
+    {
+        return YES;
+    }
+
+    RPScreenRecorder* recorder = [RPScreenRecorder sharedRecorder];
+    if (recorder == nil)
+    {
+        _lastError = [NSString stringWithUTF8String: "Failed to get Screen Recorder"];
+        return NO;
+    }
+
+    [recorder discardRecordingWithHandler:^()
+    {
+        _previewController = nil;
+    }];
+    // TODO - the above callback doesn't seem to be working at the moment.
+    _previewController = nil;
+
+    currentPreviewControllerActive = NO;
+
+    return YES;
+}
+
+- (void)previewControllerDidFinish:(RPPreviewViewController*)previewController
+{
+    if (previewController != nil)
+    {
+        [previewController dismissViewControllerAnimated: YES completion: nil];
+    }
+
+    currentPreviewControllerActive = NO;
+}
+
+- (BOOL)isPreviewControllerActive
+{
+    return currentPreviewControllerActive;
+}
+
+/****************************************
+ *   ReplayKit Broadcasting API         *
+ ****************************************/
+
+- (BOOL)broadcastingApiAvailable
+{
+    return nil != NSClassFromString(@"RPBroadcastController")
+        && nil != NSClassFromString(@"RPBroadcastActivityViewController");
+}
+
+- (NSURL*)broadcastURL
+{
+    if (broadcastController == nil)
+    {
+        return nil;
+    }
+    return [broadcastController broadcastURL];
+}
+
+- (BOOL)isBroadcasting
+{
+    if (broadcastController == nil)
+    {
+        return NO;
+    }
+    return [broadcastController isBroadcasting];
+}
+
+- (BOOL)isBroadcastingPaused
+{
+    if (broadcastController == nil)
+    {
+        return NO;
+    }
+    return [broadcastController isBroadcastingPaused];
+}
+
+- (void)broadcastActivityViewController:(UnityReplayKit_RPBroadcastActivityViewController *)sBroadcastActivityViewController
+    didFinishWithBroadcastController:(id<UnityReplayKit_RPBroadcastController>)inRPBroadcastController
+    error:(NSError *)error
+{
+    dispatch_sync(dispatch_get_main_queue(), ^{
+        UnityPause(0);
+
+        broadcastController = inRPBroadcastController;
+        if (broadcastController == nil)  // broadcast was canceled
+        {
+            _lastError = [error description];
+            UnityReplayKitTriggerBroadcastStatusCallback(broadcastStartStatusCallback, false, [_lastError UTF8String]);
+            broadcastStartStatusCallback = nil;
+            [UnityGetGLViewController() dismissViewControllerAnimated: YES completion: nil];
+        }
+        else                            // start broadcast
+        {
+            [UnityGetGLViewController() dismissViewControllerAnimated: YES completion:^
+            {
+                [broadcastController startBroadcastWithHandler:^(NSError* error)
+                {
+                    if (error != nil)
+                    {
+                        _lastError = [error description];
+                        UnityReplayKitTriggerBroadcastStatusCallback(broadcastStartStatusCallback, false, [_lastError UTF8String]);
+                        broadcastStartStatusCallback = nil; broadcastController = nil;
+                    }
+                    else
+                    {
+                        UnityReplayKitTriggerBroadcastStatusCallback(broadcastStartStatusCallback, true, "");
+                        broadcastStartStatusCallback = nil; _lastError = nil;
+                    }
+                }];
+            }];
+        }
+    });
+}
+
+- (void)startBroadcastingWithCallback:(void *)callback
+{
+    Class class_BroadcastActivityViewController = NSClassFromString(@"RPBroadcastActivityViewController");
+
+    if (class_BroadcastActivityViewController == nil)
+    {
+        return;
+    }
+
+    if (broadcastController != nil && broadcastController.broadcasting)
+    {
+        _lastError = @"Broadcast already in progress";
+        UnityReplayKitTriggerBroadcastStatusCallback(callback, false, [_lastError UTF8String]);
+        return;
+    }
+
+    if (broadcastStartStatusCallback != nullptr)
+    {
+        _lastError = @"The last attempt to start a broadcast didn\'t finish yet.";
+        UnityReplayKitTriggerBroadcastStatusCallback(callback, false, [_lastError UTF8String]);
+        return;
+    }
+
+    [class_BroadcastActivityViewController performSelector: @selector(loadBroadcastActivityViewControllerWithHandler:) withObject:^(UnityReplayKit_RPBroadcastActivityViewController* vc, NSError* error)
+    {
+        if (vc == nil || error != nil)
+        {
+            _lastError = [error description];
+            UnityReplayKitTriggerBroadcastStatusCallback(callback, false, [_lastError UTF8String]);
+            return;
+        }
+
+        [self shouldCreateOverlayWindow];
+        UnityPause(1);
+        vc.delegate = self;
+        broadcastStartStatusCallback = callback;
+
+        // oh apple, how much do you like confusing docs and contradicting behaviours
+        // on ios13 UIModalPresentationPopover meaning was changed; what's more: it is now broken if portrait is disabled
+        // pre ios13 it was intended to be UIModalPresentationPopover for ipads, UIModalPresentationFullScreen for iphones
+        // yet having fully blackscreen (UIModalPresentationFullScreen) was not looking good for lots of people
+        //   so we use popover for both ipad/iphone but ONLY before ios13
+        // note that tvos is fullscreen always (this is the only option here)
+    #if PLATFORM_TVOS
+        vc.modalPresentationStyle = UIModalPresentationFullScreen;
+    #else
+        vc.modalPresentationStyle = UIModalPresentationFormSheet;
+    #endif
+
+        [UnityGetGLViewController() presentViewController: vc animated: YES completion: nil];
+    }];
+    return;
+}
+
+- (void)stopBroadcasting
+{
+    self->overlayWindow = nil;
+
+    if (broadcastController == nil || !broadcastController.broadcasting)
+    {
+        broadcastController = nil;
+        return;
+    }
+
+    [broadcastController finishBroadcastWithHandler:^(NSError* error)
+    {
+        broadcastController = nil;
+        if (error == nil)
+            return;
+        _lastError = [error description];
+    }];
+}
+
+- (void)pauseBroadcasting
+{
+    if (broadcastController == nil || !broadcastController.broadcasting)
+    {
+        return;
+    }
+
+    [broadcastController pauseBroadcast];
+}
+
+- (void)resumeBroadcasting
+{
+    if (broadcastController == nil || !broadcastController.broadcasting)
+    {
+        return;
+    }
+
+    [broadcastController resumeBroadcast];
+}
+
+- (BOOL)isCameraEnabled
+{
+    if (![self apiAvailable])
+    {
+        return NO;
+    }
+
+    id<UnityReplayKit_RPScreenRecorder> screenRecorder = (id)[RPScreenRecorder sharedRecorder];
+    if (![screenRecorder respondsToSelector: @selector(isCameraEnabled)])
+    {
+        return NO;
+    }
+
+    return screenRecorder.cameraEnabled;
+}
+
+- (void)setCameraEnabled:(BOOL)cameraEnabled
+{
+    if (![self apiAvailable])
+    {
+        return;
+    }
+
+    id<UnityReplayKit_RPScreenRecorder> screenRecorder = (id)[RPScreenRecorder sharedRecorder];
+    if (![screenRecorder respondsToSelector: @selector(setCameraEnabled:)])
+    {
+        return;
+    }
+
+    screenRecorder.cameraEnabled = cameraEnabled;
+}
+
+- (BOOL)isMicrophoneEnabled
+{
+    if (![self apiAvailable])
+    {
+        return NO;
+    }
+
+    id<UnityReplayKit_RPScreenRecorder> screenRecorder = (id)[RPScreenRecorder sharedRecorder];
+    if (![screenRecorder respondsToSelector: @selector(isMicrophoneEnabled)])
+    {
+        return NO;
+    }
+
+    return screenRecorder.microphoneEnabled;
+}
+
+- (void)setMicrophoneEnabled:(BOOL)microphoneEnabled
+{
+    if (![self apiAvailable])
+    {
+        return;
+    }
+
+    id<UnityReplayKit_RPScreenRecorder> screenRecorder = (id)[RPScreenRecorder sharedRecorder];
+    if (![screenRecorder respondsToSelector: @selector(setMicrophoneEnabled:)])
+    {
+        return;
+    }
+
+    screenRecorder.microphoneEnabled = microphoneEnabled;
+}
+
+- (BOOL)showCameraPreviewAt:(CGPoint)position width:(float)width height:(float)height
+{
+    if (currentCameraPreviewView == nil)
+    {
+        if (![self apiAvailable])
+        {
+            return NO;
+        }
+
+        id<UnityReplayKit_RPScreenRecorder> screenRecorder = (id)[RPScreenRecorder sharedRecorder];
+        UIView* cameraPreviewView = screenRecorder.cameraPreviewView;
+        if (cameraPreviewView == nil)
+        {
+            return NO;
+        }
+
+        [[UnityGetGLViewController() view] addSubview: cameraPreviewView];
+        currentCameraPreviewView = cameraPreviewView;
+        [cameraPreviewView setUserInteractionEnabled: NO];
+    }
+
+    if (width < 0.0f)
+        width = currentCameraPreviewView.frame.size.width;
+
+    if (height < 0.0f)
+        height = currentCameraPreviewView.frame.size.height;
+
+    [currentCameraPreviewView setFrame: CGRectMake(position.x, position.y, width, height)];
+
+    return YES;
+}
+
+- (void)hideCameraPreview
+{
+    if (currentCameraPreviewView != nil)
+    {
+        [currentCameraPreviewView removeFromSuperview];
+        currentCameraPreviewView = nil;
+    }
+}
+
+@end
+
+static dispatch_once_t onceToken_InitUnityReplayKit;
+void InitUnityReplayKit()
+{
+    dispatch_once(&onceToken_InitUnityReplayKit, ^{
+        _replayKit = [[UnityReplayKit alloc] init];
+        // that seems to be enough to trigger RPScreenRecorder to become "ready"
+        [RPScreenRecorder sharedRecorder].delegate = _replayKit;
+    });
+}
+
+#endif  // UNITY_REPLAY_KIT_AVAILABLE

+ 207 - 0
unity_ios/Classes/Unity/UnityReplayKit_Scripting.mm

@@ -0,0 +1,207 @@
+//==============================================================================
+//
+//  ReplayKit Unity Interface
+
+
+#import "UnityReplayKit.h"
+
+extern "C"
+{
+#if UNITY_REPLAY_KIT_AVAILABLE
+
+    UNITY_EXPORT int UnityReplayKitAPIAvailable()
+    {
+        return [UnityReplayKit sharedInstance].apiAvailable ? 1 : 0;
+    }
+
+    UNITY_EXPORT int UnityReplayKitRecordingAvailable()
+    {
+        return [UnityReplayKit sharedInstance].recordingPreviewAvailable ? 1 : 0;
+    }
+
+    UNITY_EXPORT int UnityReplayKitIsCameraEnabled()
+    {
+        return [UnityReplayKit sharedInstance].cameraEnabled != NO ? 1 : 0;
+    }
+
+    UNITY_EXPORT int UnityReplayKitSetCameraEnabled(bool yes)
+    {
+        BOOL value = yes ? YES : NO;
+        [UnityReplayKit sharedInstance].cameraEnabled = value;
+        return [UnityReplayKit sharedInstance].cameraEnabled == value;
+    }
+
+    UNITY_EXPORT int UnityReplayKitIsMicrophoneEnabled()
+    {
+        return [UnityReplayKit sharedInstance].microphoneEnabled != NO ? 1 : 0;
+    }
+
+    UNITY_EXPORT int UnityReplayKitSetMicrophoneEnabled(bool yes)
+    {
+        if ([UnityReplayKit sharedInstance].isRecording)
+        {
+            printf_console("It is not possible to change microphoneEnabled during recording.\n");
+            return 0;
+        }
+
+        BOOL value = yes ? YES : NO;
+        [UnityReplayKit sharedInstance].microphoneEnabled = value;
+        return [UnityReplayKit sharedInstance].microphoneEnabled == value;
+    }
+
+    UNITY_EXPORT const char* UnityReplayKitLastError()
+    {
+        NSString* err = [UnityReplayKit sharedInstance].lastError;
+        if (err == nil)
+        {
+            return NULL;
+        }
+        const char* error = [err cStringUsingEncoding: NSUTF8StringEncoding];
+        if (error != NULL)
+        {
+            error = strdup(error);
+        }
+        return error;
+    }
+
+    UNITY_EXPORT int UnityReplayKitStartRecording()
+    {
+        return [[UnityReplayKit sharedInstance] startRecording] ? 1 : 0;
+    }
+
+    UNITY_EXPORT int UnityReplayKitIsRecording()
+    {
+        return [UnityReplayKit sharedInstance].isRecording ? 1 : 0;
+    }
+
+    UNITY_EXPORT int UnityReplayKitShowCameraPreviewAt(float x, float y, float width, float height)
+    {
+#if !PLATFORM_VISIONOS
+        float q = 1.0f / UnityScreenScaleFactor([UIScreen mainScreen]);
+#else
+        float q = 1.0f;
+#endif
+        float h = [[UIScreen mainScreen] bounds].size.height;
+        return [[UnityReplayKit sharedInstance] showCameraPreviewAt: CGPointMake(x * q, h - y * q) width: width height: height] ? 1 : 0;
+    }
+
+    UNITY_EXPORT void UnityReplayKitHideCameraPreview()
+    {
+        [[UnityReplayKit sharedInstance] hideCameraPreview];
+    }
+
+    UNITY_EXPORT int UnityReplayKitStopRecording()
+    {
+#if !PLATFORM_TVOS
+        UnityReplayKitHideCameraPreview();
+        UnityReplayKitSetCameraEnabled(false);
+#endif
+        return [[UnityReplayKit sharedInstance] stopRecording] ? 1 : 0;
+    }
+
+    UNITY_EXPORT int UnityReplayKitDiscard()
+    {
+        return [[UnityReplayKit sharedInstance] discardPreview] ? 1 : 0;
+    }
+
+    UNITY_EXPORT int UnityReplayKitPreview()
+    {
+        return [[UnityReplayKit sharedInstance] showPreview] ? 1 : 0;
+    }
+
+    UNITY_EXPORT int UnityReplayKitBroadcastingAPIAvailable()
+    {
+        return [[UnityReplayKit sharedInstance] broadcastingApiAvailable] ? 1 : 0;
+    }
+
+    UNITY_EXPORT void UnityReplayKitStartBroadcasting(void* callback)
+    {
+        [[UnityReplayKit sharedInstance] startBroadcastingWithCallback: callback];
+    }
+
+    UNITY_EXPORT void UnityReplayKitStopBroadcasting()
+    {
+#if !PLATFORM_TVOS
+        UnityReplayKitHideCameraPreview();
+#endif
+        [[UnityReplayKit sharedInstance] stopBroadcasting];
+    }
+
+    UNITY_EXPORT void UnityReplayKitPauseBroadcasting()
+    {
+        [[UnityReplayKit sharedInstance] pauseBroadcasting];
+    }
+
+    UNITY_EXPORT void UnityReplayKitResumeBroadcasting()
+    {
+        [[UnityReplayKit sharedInstance] resumeBroadcasting];
+    }
+
+    UNITY_EXPORT int UnityReplayKitIsBroadcasting()
+    {
+        return [[UnityReplayKit sharedInstance] isBroadcasting] ? 1 : 0;
+    }
+
+    UNITY_EXPORT int UnityReplayKitIsBroadcastingPaused()
+    {
+        return [[UnityReplayKit sharedInstance] isBroadcastingPaused] ? 1 : 0;
+    }
+
+    UNITY_EXPORT int UnityReplayKitIsPreviewControllerActive()
+    {
+        return [[UnityReplayKit sharedInstance] isPreviewControllerActive] ? 1 : 0;
+    }
+
+    UNITY_EXPORT const char* UnityReplayKitGetBroadcastURL()
+    {
+        NSURL *url = [[UnityReplayKit sharedInstance] broadcastURL];
+        if (url != nil)
+        {
+            return [[url absoluteString] UTF8String];
+        }
+        return nullptr;
+    }
+
+    UNITY_EXPORT void UnityReplayKitCreateOverlayWindow()
+    {
+        [[UnityReplayKit sharedInstance] createOverlayWindow];
+    }
+
+#if !PLATFORM_VISIONOS
+    extern "C" float UnityScreenScaleFactor(UIScreen* screen);
+#endif
+
+#else
+
+// Impl when ReplayKit is not available.
+
+    UNITY_EXPORT int UnityReplayKitAPIAvailable()        { return 0; }
+    UNITY_EXPORT int UnityReplayKitRecordingAvailable()  { return 0; }
+    UNITY_EXPORT const char* UnityReplayKitLastError()   { return NULL; }
+    UNITY_EXPORT int UnityReplayKitStartRecording(int enableMicrophone, int enableCamera) { return 0; }
+    UNITY_EXPORT int UnityReplayKitIsRecording()         { return 0; }
+    UNITY_EXPORT int UnityReplayKitStopRecording()       { return 0; }
+    UNITY_EXPORT int UnityReplayKitDiscard()             { return 0; }
+    UNITY_EXPORT int UnityReplayKitPreview()             { return 0; }
+
+    UNITY_EXPORT int UnityReplayKitIsCameraEnabled() { return 0; }
+    UNITY_EXPORT int UnityReplayKitSetCameraEnabled(bool) { return 0; }
+    UNITY_EXPORT int UnityReplayKitIsMicrophoneEnabled() { return 0; }
+    UNITY_EXPORT int UnityReplayKitSetMicrophoneEnabled(bool) { return 0; }
+    UNITY_EXPORT int UnityReplayKitShowCameraPreviewAt(float x, float y, float width, float height) { return 0; }
+    UNITY_EXPORT void UnityReplayKitHideCameraPreview() {}
+    UNITY_EXPORT void UnityReplayKitCreateOverlayWindow() {}
+
+    void UnityReplayKitTriggerBroadcastStatusCallback(void*, bool, const char*);
+    UNITY_EXPORT int UnityReplayKitBroadcastingAPIAvailable() { return 0; }
+    UNITY_EXPORT void UnityReplayKitStartBroadcasting(void* callback) { UnityReplayKitTriggerBroadcastStatusCallback(callback, false, "ReplayKit not implemented."); }
+    UNITY_EXPORT void UnityReplayKitStopBroadcasting() {}
+    UNITY_EXPORT void UnityReplayKitPauseBroadcasting() {}
+    UNITY_EXPORT void UnityReplayKitResumeBroadcasting() {}
+    UNITY_EXPORT int UnityReplayKitIsBroadcasting() { return 0; }
+    UNITY_EXPORT int UnityReplayKitIsBroadcastingPaused() { return 0; }
+    UNITY_EXPORT int UnityReplayKitIsPreviewControllerActive() { return 0; }
+    UNITY_EXPORT const char* UnityReplayKitGetBroadcastURL() { return nullptr; }
+
+#endif  // UNITY_REPLAY_KIT_AVAILABLE
+}  // extern "C"

+ 134 - 0
unity_ios/Classes/Unity/UnitySharedDecls.h

@@ -0,0 +1,134 @@
+#pragma once
+
+// The contents of this file are used when building both Unity library and the trampoline. Do not change it.
+
+// Classes/Unity/UnityForwardDecls
+typedef enum ScreenOrientation
+{
+    orientationUnknown,
+
+    portrait,
+    portraitUpsideDown,
+    landscapeLeft,
+    landscapeRight,
+
+    orientationCount,
+}
+ScreenOrientation;
+
+// be aware that this enum is shared with unity implementation so you should absolutely not change it
+typedef enum DeviceGeneration
+{
+    // iOSDevice.cs
+    deviceUnknown            = 0,
+    deviceiPhone3GS          = 3,
+    deviceiPhone4            = 8,
+    deviceiPodTouch4Gen      = 9,
+    deviceiPad2Gen           = 10,
+    deviceiPhone4S           = 11,
+    deviceiPad3Gen           = 12,
+    deviceiPhone5            = 13,
+    deviceiPodTouch5Gen      = 14,
+    deviceiPadMini1Gen       = 15,
+    deviceiPad4Gen           = 16,
+    deviceiPhone5C           = 17,
+    deviceiPhone5S           = 18,
+    deviceiPadAir1           = 19,
+    deviceiPadMini2Gen       = 20,
+    deviceiPhone6            = 21,
+    deviceiPhone6Plus        = 22,
+    deviceiPadMini3Gen       = 23,
+    deviceiPadAir2           = 24,
+    deviceiPhone6S           = 25,
+    deviceiPhone6SPlus       = 26,
+    deviceiPadPro1Gen        = 27,
+    deviceiPadMini4Gen       = 28,
+    deviceiPhoneSE1Gen       = 29,
+    deviceiPadPro10Inch1Gen  = 30,
+    deviceiPhone7            = 31,
+    deviceiPhone7Plus        = 32,
+    deviceiPodTouch6Gen      = 33,
+    deviceiPad5Gen           = 34,
+    deviceiPadPro2Gen        = 35,
+    deviceiPadPro10Inch2Gen  = 36,
+    deviceiPhone8            = 37,
+    deviceiPhone8Plus        = 38,
+    deviceiPhoneX            = 39,
+    deviceiPhoneXS           = 40,
+    deviceiPhoneXSMax        = 41,
+    deviceiPhoneXR           = 42,
+    deviceiPadPro11Inch      = 43,
+    deviceiPadPro3Gen        = 44,
+    deviceiPad6Gen           = 45,
+    deviceiPadAir3Gen        = 46,
+    deviceiPadMini5Gen       = 47,
+    deviceiPhone11           = 48,
+    deviceiPhone11Pro        = 49,
+    deviceiPhone11ProMax     = 50,
+    deviceiPodTouch7Gen      = 51,
+    deviceiPad7Gen           = 52,
+    deviceiPhoneSE2Gen       = 53,
+    deviceiPadPro11Inch2Gen  = 54,
+    deviceiPadPro4Gen        = 55,
+    deviceiPhone12Mini       = 56,
+    deviceiPhone12           = 57,
+    deviceiPhone12Pro        = 58,
+    deviceiPhone12ProMax     = 59,
+    deviceiPad8Gen           = 60,
+    deviceiPadAir4Gen        = 61,
+    deviceiPad9Gen           = 62,
+    deviceiPadMini6Gen       = 63,
+    deviceiPhone13           = 64,
+    deviceiPhone13Mini       = 65,
+    deviceiPhone13Pro        = 66,
+    deviceiPhone13ProMax     = 67,
+    deviceiPadPro5Gen        = 68,
+    deviceiPadPro11Inch3Gen  = 69,
+    deviceiPhoneSE3Gen       = 70,
+    deviceiPadAir5Gen        = 71,
+    deviceiPhone14           = 72,
+    deviceiPhone14Plus       = 73,
+    deviceiPhone14Pro        = 74,
+    deviceiPhone14ProMax     = 75,
+    deviceiPadPro6Gen        = 76,
+    deviceiPadPro11Inch4Gen  = 77,
+    deviceiPad10Gen          = 78,
+    deviceiPhone15           = 79,
+    deviceiPhone15Plus       = 80,
+    deviceiPhone15Pro        = 81,
+    deviceiPhone15ProMax     = 82,
+    deviceiPhone16           = 83,
+    deviceiPhone16Plus       = 84,
+    deviceiPhone16Pro        = 85,
+    deviceiPhone16ProMax     = 86,
+    deviceiPhone16e          = 87,
+    deviceiPhone17           = 88,
+    deviceiPhoneAir          = 89,
+    deviceiPhone17Pro        = 90,
+    deviceiPhone17ProMax     = 91,
+    deviceiPhone17e          = 92,
+
+    // tvOSDevice.cs
+    deviceAppleTV1Gen       = 1001,
+    deviceAppleTVHD         = 1001,
+    deviceAppleTV2Gen       = 1002,
+    deviceAppleTV4K         = 1002,
+    deviceAppleTV4K2Gen     = 1003,
+    deviceAppleTV4K3Gen     = 1004,
+
+    deviceiPhoneUnknown     = 10001,
+    deviceiPadUnknown       = 10002,
+    deviceiPodTouchUnknown  = 10003,
+}
+DeviceGeneration;
+
+// Classes/UI/SplashScreen.mm
+#ifdef __cplusplus
+struct OrientationMask
+{
+    bool portrait;
+    bool portraitUpsideDown;
+    bool landscapeLeft;
+    bool landscapeRight;
+};
+#endif

+ 5 - 0
unity_ios/Classes/Unity/UnityTrampolineCompatibility.h

@@ -0,0 +1,5 @@
+#pragma once
+
+#if !UNITY_TRAMPOLINE_IN_USE
+#include "UnityPrefix.h"
+#endif

+ 558 - 0
unity_ios/Classes/Unity/UnityWebRequest.mm

@@ -0,0 +1,558 @@
+static NSURLSession* unityWebRequestSession;
+static NSRecursiveLock* unityWebRequestLock;
+
+@interface UnityURLRequest : NSMutableURLRequest
+
+@property (readonly, nonatomic) void* udata;
+@property (readwrite, nonatomic) NSUInteger taskIdentifier;
+@property (readonly, nonatomic) long long estimatedContentLength;
+@property (readonly, nonatomic) long long receivedBytes;
+@property (readwrite, nonatomic) bool wantCertificateCallback;
+@property (readwrite, nonatomic) bool redirecting;
+@property (readonly) bool isDone;
+
+- (id)init:(void*)udata;
+
+@end
+
+static NSMutableArray<UnityURLRequest*>* currentRequests;
+
+@implementation UnityURLRequest
+{
+    void* _udata;
+    NSUInteger _taskIdentifier;
+    long long _estimatedContentLength;
+    long long _receivedBytes;
+    bool _wantCertificateCallback;
+    bool _redirecting;
+    bool _isDone;
+}
+
+@synthesize udata = _udata;
+@synthesize taskIdentifier = _taskIdentifier;
+@synthesize estimatedContentLength = _estimatedContentLength;
+@synthesize receivedBytes = _receivedBytes;
+@synthesize wantCertificateCallback = _wantCertificateCallback;
+@synthesize redirecting = _redirecting;
+@synthesize isDone = _isDone;
+
++ (UnityURLRequest*)requestForTask:(NSURLSessionTask*)task
+{
+    UnityURLRequest* request = nil;
+    [unityWebRequestLock lock];
+    for (unsigned i = 0; i < currentRequests.count; ++i)
+        if (currentRequests[i].taskIdentifier == task.taskIdentifier)
+        {
+            request = currentRequests[i];
+            break;
+        }
+    [unityWebRequestLock unlock];
+    return request;
+}
+
++ (void)removeRequest:(UnityURLRequest* _Nonnull)request
+{
+    // removeObject would remove all identical requests, taskIdentifier is unique
+    for (unsigned i = 0; i < currentRequests.count; ++i)
+        if (currentRequests[i].taskIdentifier == request.taskIdentifier)
+        {
+            [currentRequests removeObjectAtIndex: i];
+            break;
+        }
+}
+
+- (id)init:(void*)udata
+{
+    self = [super init];
+    _udata = udata;
+    _taskIdentifier = 0;
+    _estimatedContentLength = 0;
+    _receivedBytes = 0;
+    _wantCertificateCallback = false;
+    _redirecting = false;
+    _isDone = false;
+    return self;
+}
+
+- (void)updateEstimatedContentLength:(long long)contentLength
+{
+    if (contentLength > _estimatedContentLength)
+        _estimatedContentLength = contentLength;
+}
+
+- (void)updateReceivedBytes:(long long)receivedBytes
+{
+    _receivedBytes += receivedBytes;
+    if (_receivedBytes > _estimatedContentLength)
+        _estimatedContentLength = _receivedBytes;
+}
+
+- (void)markDone
+{
+    _isDone = true;
+}
+
+@end
+
+
+@interface UnityWebRequestDelegate : NSObject<NSURLSessionDataDelegate, NSURLSessionTaskDelegate>
+@end
+
+
+@interface UnityWebRequestUploadStream : NSInputStream
+
++ (id)createForRequest:(void*)request totalBytes:(UInt64)totalBytes;
+- (NSStreamStatus)streamStatus;
+- (void)open;
+- (void)close;
+- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len;
+- (BOOL)getBuffer:(uint8_t * _Nullable *)buffer length:(NSUInteger *)len;
+- (BOOL)hasBytesAvailable;
+- (void)setDelegate:(id<NSStreamDelegate>)delegate;
+- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSRunLoopMode)mode;
+- (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSRunLoopMode)mode;
+
+@end
+
+
+@implementation UnityWebRequestDelegate
+
+- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler
+{
+    [self handleResponse: response task: dataTask];
+    completionHandler(NSURLSessionResponseAllow);
+}
+
+- (void)handleResponse:(NSURLResponse*)response task:(NSURLSessionTask*)task
+{
+    UnityURLRequest* urequest = [UnityURLRequest requestForTask: task];
+    if (urequest == nil)
+        return;
+    if ([response isKindOfClass: [NSHTTPURLResponse class]])
+        [self handleHTTPResponse: (NSHTTPURLResponse*)response urequest: urequest];
+    else
+        [self handleResponse: response urequest: urequest];
+}
+
+- (void)handleHTTPResponse:(NSHTTPURLResponse*)response task:(NSURLSessionTask*)task
+{
+    UnityURLRequest* urequest = [UnityURLRequest requestForTask: task];
+    if (urequest == nil)
+        return;
+    [self handleHTTPResponse: response urequest: urequest];
+}
+
+- (void)handleHTTPResponse:(NSHTTPURLResponse*)response urequest:(UnityURLRequest*)urequest
+{
+    UnityReportWebRequestStatus(urequest.udata, (int)[response statusCode]);
+    NSDictionary* respHeader = [response allHeaderFields];
+    NSEnumerator* headerEnum = [respHeader keyEnumerator];
+    for (id headerKey = [headerEnum nextObject]; headerKey; headerKey = [headerEnum nextObject])
+        UnityReportWebRequestResponseHeader(urequest.udata, [headerKey UTF8String], [[respHeader objectForKey: headerKey] UTF8String]);
+    [self handleResponse: response urequest: urequest];
+}
+
+- (void)handleResponse:(NSURLResponse*)response urequest:(UnityURLRequest*)urequest
+{
+    [urequest updateEstimatedContentLength: response.expectedContentLength];
+    UnityReportWebRequestReceivedResponse(urequest.udata, (unsigned int)urequest.estimatedContentLength);
+}
+
+- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
+{
+    UnityURLRequest* urequest = [UnityURLRequest requestForTask: dataTask];
+    if (urequest == nil)
+        return;
+    [urequest updateEstimatedContentLength: [dataTask countOfBytesExpectedToReceive]];
+    [data enumerateByteRangesUsingBlock:^(const void* bytes, NSRange range, BOOL* stop) {
+        UnityReportWebRequestReceivedData(urequest.udata, bytes, (unsigned int)range.length, (unsigned int)urequest.estimatedContentLength);
+    }];
+}
+
+- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
+{
+    UnityURLRequest* urequest = [UnityURLRequest requestForTask: task];
+    if (urequest == nil)
+    {
+        completionHandler(nil);
+        return;
+    }
+    urequest.redirecting = true;
+    [self handleHTTPResponse: response task: task];
+    completionHandler(nil);
+    [task cancel];
+}
+
+- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential* credential))completionHandler
+{
+    if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust)
+    {
+        UnityURLRequest* urequest = [UnityURLRequest requestForTask: task];
+        if (urequest == nil || !urequest.wantCertificateCallback)
+        {
+            completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
+            return;
+        }
+
+#if !defined(DISABLE_WEBREQUEST_CERTIFICATE_CALLBACK)
+        SecTrustResultType systemResult = kSecTrustResultProceed;
+        CFErrorRef error;
+        SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
+        if (serverTrust == nil)
+            systemResult = kSecTrustResultOtherError;
+        else if (!SecTrustEvaluateWithError(serverTrust, &error))
+        {
+            SecTrustGetTrustResult(serverTrust, &systemResult);
+        }
+
+        switch (systemResult)
+        {
+            case kSecTrustResultUnspecified:
+            case kSecTrustResultProceed:
+            case kSecTrustResultRecoverableTrustFailure:
+                break;
+            default:
+                completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
+                return;
+        }
+
+        SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
+        if (serverCertificate != nil)
+        {
+            CFDataRef serverCertificateData = SecCertificateCopyData(serverCertificate);
+            const UInt8* const data = CFDataGetBytePtr(serverCertificateData);
+            const CFIndex size = CFDataGetLength(serverCertificateData);
+            bool trust = UnityReportWebRequestValidateCertificate(urequest.udata, (const char*)data, (unsigned)size);
+            CFRelease(serverCertificateData);
+            if (trust)
+            {
+                NSURLCredential *credential = [NSURLCredential credentialForTrust: challenge.protectionSpace.serverTrust];
+                completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
+                return;
+            }
+        }
+#endif
+        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
+        return;
+    }
+    else
+        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
+}
+
+- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream * _Nullable))completionHandler
+{
+    UnityURLRequest* urequest = [UnityURLRequest requestForTask: task];
+    UInt64 length = 0;
+    if (urequest != nil)
+        length = UnityWebRequestResetUpload(urequest.udata);
+    if (urequest == nil || length == 0)
+    {
+        [task cancel];
+        completionHandler(nil);
+        return;
+    }
+
+    NSInputStream* stream = [UnityWebRequestUploadStream createForRequest: urequest.udata totalBytes: length];
+    completionHandler(stream);
+}
+
+- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
+{
+    UnityURLRequest* urequest = [UnityURLRequest requestForTask: task];
+    if (urequest == nil)
+        return;
+    [urequest markDone];
+    if (!urequest.redirecting)
+    {
+        if (error != nil)
+            UnityReportWebRequestNetworkError(urequest.udata, (int)[error code]);
+    }
+    UnityReportWebRequestFinishedLoadingData(urequest.udata);
+    UnityWebRequestRelease(urequest.udata);
+}
+
+- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error
+{
+    [unityWebRequestLock lock];
+    unityWebRequestSession = nil;
+    [unityWebRequestLock unlock];
+}
+
+@end
+
+
+@implementation UnityWebRequestUploadStream
+{
+    void* _request;
+    UInt64 _totalBytes;
+    NSStreamStatus _status;
+}
+
++ (id)createForRequest:(void*)request totalBytes:(UInt64)totalBytes
+{
+    return [[UnityWebRequestUploadStream alloc] initWithRequest: request totalBytes: totalBytes];
+}
+
+- (id)initWithRequest:(void*)request totalBytes:(UInt64)totalBytes
+{
+    self = [self init];
+    _request = request;
+    _totalBytes = totalBytes;
+    _status = NSStreamStatusNotOpen;
+    return self;
+}
+
+- (NSStreamStatus)streamStatus
+{
+    return _status;
+}
+
+- (void)open
+{
+    _status = NSStreamStatusOpen;
+}
+
+- (void)close
+{
+    _status = NSStreamStatusClosed;
+}
+
+- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len
+{
+    unsigned dataSize = (unsigned)len;
+    const UInt8* data = (const UInt8*)UnityWebRequestGetUploadData(_request, &dataSize);
+    if (dataSize == 0)
+        return 0;
+    memcpy(buffer, data, dataSize);
+    UnityWebRequestConsumeUploadData(_request, dataSize);
+    _totalBytes -= dataSize;
+    if (_totalBytes == 0)
+        _status = NSStreamStatusAtEnd;
+    return dataSize;
+}
+
+- (BOOL)getBuffer:(uint8_t * _Nullable *)buffer length:(NSUInteger *)len
+{
+    return NO;
+}
+
+- (BOOL)hasBytesAvailable
+{
+    return _totalBytes > 0;
+}
+
+- (void)setDelegate:(id<NSStreamDelegate>)delegate
+{
+}
+
+- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSRunLoopMode)mode
+{
+}
+
+- (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSRunLoopMode)mode
+{
+}
+
+- (id)propertyForKey:(NSStreamPropertyKey)key
+{
+    return nil;
+}
+
+- (BOOL)setProperty:(id)property forKey:(NSStreamPropertyKey)key
+{
+    return NO;
+}
+
+@end
+
+
+const int WEB_ERROR_OK = 0;
+const int WEB_ERROR_MALFORMATTED_URL = 5;
+
+UNITY_EXPORT extern "C" void UnityWebRequestAddCustomHeader(void** headers, const char* headerName, const char* headerValue)
+{
+    @autoreleasepool
+    {
+        NSMutableDictionary* headerDict = (__bridge NSMutableDictionary*)*headers;
+        if (headerDict == nil)
+        {
+            headerDict = [[NSMutableDictionary alloc] init];
+            *headers = (__bridge_retained void*)headerDict;
+        }
+
+        [headerDict setValue: [NSString stringWithUTF8String: headerValue] forKey: [NSString stringWithUTF8String: headerName]];
+    }
+}
+
+UNITY_EXPORT extern "C" int UnityCreateWebRequestBackend(void** connection, void* udata, const char* methodString, const void* headerDict, const char* url)
+{
+    @autoreleasepool
+    {
+        static dispatch_once_t onceToken;
+        dispatch_once(&onceToken, ^{
+            @autoreleasepool
+            {
+                currentRequests = [[NSMutableArray<UnityURLRequest*> alloc] init];
+                unityWebRequestLock = [[NSRecursiveLock alloc] init];
+            }
+        });
+
+        NSDictionary* headers = (__bridge_transfer NSDictionary*)headerDict;
+        NSURL* requestUrl;
+#if defined(__IPHONE_17_0)
+        if (@available(iOS 17.0, tvOS 17.0, *))
+            requestUrl = [NSURL URLWithString: [NSString stringWithUTF8String: url] encodingInvalidCharacters: NO];
+        else
+#endif
+            requestUrl = [NSURL URLWithString: [NSString stringWithUTF8String: url]];
+
+        if (requestUrl == nil)
+            return WEB_ERROR_MALFORMATTED_URL;
+
+        UnityURLRequest* request = [[UnityURLRequest alloc] init: udata];
+        request.URL = requestUrl;
+        request.HTTPMethod = [NSString stringWithUTF8String: methodString];
+        request.allHTTPHeaderFields = headers;
+        [request setCachePolicy: NSURLRequestReloadIgnoringLocalCacheData];
+
+        // set or replace backend under lock
+        // replace means we are redirecting, so we discard previous result
+        [unityWebRequestLock lock];
+        UnityURLRequest* previous = (__bridge_transfer UnityURLRequest*)*connection;
+        *connection = (__bridge_retained void*)request;
+        previous = nil;
+        [unityWebRequestLock unlock];
+        return WEB_ERROR_OK;
+    }
+}
+
+UNITY_EXPORT extern "C" void UnitySendWebRequest(void* const* connection, unsigned length, unsigned long timeoutSec, bool wantCertificateCallback)
+{
+    @autoreleasepool
+    {
+        [unityWebRequestLock lock];
+        UnityURLRequest* request = (__bridge UnityURLRequest*)*connection;
+        if (request == nil)
+        {
+            [unityWebRequestLock unlock];
+            return;
+        }
+
+        request.timeoutInterval = timeoutSec;
+        request.wantCertificateCallback = wantCertificateCallback;
+
+        if (length > 0)
+        {
+            bool useStream = (length > 16384);  // if less then 16K, do not use stream (too much memory pressure)
+            if (!useStream) // Use data
+            {
+                unsigned dataSize = length;
+                const UInt8* data = (const UInt8*)UnityWebRequestGetUploadData(request.udata, &dataSize);
+                if (dataSize < length) // if data size is less than length we should use stream
+                    useStream = true;
+                else
+                {
+                    UnityWebRequestConsumeUploadData(request.udata, (unsigned)dataSize);
+                    request.HTTPBody = [NSData dataWithBytes: data length: dataSize];
+                }
+            }
+            if (useStream)
+                request.HTTPBodyStream = [UnityWebRequestUploadStream createForRequest: request.udata totalBytes: length];
+        }
+        if (unityWebRequestSession == nil)
+        {
+            NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
+            UnityWebRequestDelegate* delegate = [[UnityWebRequestDelegate alloc] init];
+            unityWebRequestSession = [NSURLSession sessionWithConfiguration: config delegate: delegate delegateQueue: nil];
+        }
+        NSURLSessionTask* task = [unityWebRequestSession dataTaskWithRequest: request];
+        request.taskIdentifier = task.taskIdentifier;
+        [currentRequests addObject: request];
+        [unityWebRequestLock unlock];
+        [task resume];
+    }
+}
+
+UNITY_EXPORT extern "C" bool UnityWebRequestIsDone(void* const* connection)
+{
+    @autoreleasepool
+    {
+        [unityWebRequestLock lock];
+        UnityURLRequest* request = (__bridge UnityURLRequest*)*connection;
+        bool done = request == nil ? false : request.isDone;
+        [unityWebRequestLock unlock];
+        return done;
+    }
+}
+
+UNITY_EXPORT extern "C" void UnityDestroyWebRequestBackend(void** connection)
+{
+    @autoreleasepool
+    {
+        [unityWebRequestLock lock];
+        UnityURLRequest* request = (__bridge_transfer UnityURLRequest*)*connection;
+        *connection = NULL;
+        if (request != nil)
+            [UnityURLRequest removeRequest: request];
+        [unityWebRequestLock unlock];
+    }
+}
+
+UNITY_EXPORT extern "C" void UnityCancelWebRequest(void* const* connection)
+{
+    @autoreleasepool
+    {
+        [unityWebRequestLock lock];
+        UnityURLRequest* request = (__bridge UnityURLRequest*)*connection;
+        if (request != nil)
+        {
+            NSUInteger taskId = request.taskIdentifier;
+            [unityWebRequestSession getAllTasksWithCompletionHandler:^(NSArray<NSURLSessionTask*>* _Nonnull tasks) {
+                [tasks enumerateObjectsUsingBlock:^(NSURLSessionTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
+                    if (task.taskIdentifier == taskId)
+                    {
+                        [task cancel];
+                        *stop = YES;
+                    }
+                }];
+            }];
+        }
+        [unityWebRequestLock unlock];
+    }
+}
+
+UNITY_EXPORT extern "C" void UnityWebRequestClearCookieCache(const char* domain)
+{
+    NSArray<NSHTTPCookie*>* cookies;
+    NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
+    if (domain == NULL)
+        cookies = [cookieStorage cookies];
+    else
+    {
+        NSURL* url = [NSURL URLWithString: [NSString stringWithUTF8String: domain]];
+        if (url.path == nil || [url.path isEqualToString: [NSString string]])
+        {
+            NSMutableArray<NSHTTPCookie*>* hostCookies = [[NSMutableArray<NSHTTPCookie *> alloc] init];
+            cookies = [cookieStorage cookies];
+            NSUInteger cookieCount = [cookies count];
+            for (unsigned i = 0; i < cookieCount; ++i)
+                if ([cookies[i].domain isEqualToString: url.host])
+                    [hostCookies addObject: cookies[i]];
+            cookies = hostCookies;
+        }
+        else
+            cookies = [cookieStorage cookiesForURL: url];
+    }
+    NSUInteger cookieCount = [cookies count];
+    for (int i = 0; i < cookieCount; ++i)
+        [cookieStorage deleteCookie: cookies[i]];
+}
+
+UNITY_EXPORT extern "C" void UnityWebRequestCleanupSession()
+{
+    if (unityWebRequestLock == nil)
+        return;
+    [unityWebRequestLock lock];
+    [unityWebRequestSession invalidateAndCancel];
+    [unityWebRequestLock unlock];
+}

+ 53 - 0
unity_ios/Classes/Unity/VideoPlayer.h

@@ -0,0 +1,53 @@
+#pragma once
+
+#import <CoreMedia/CMTime.h>
+
+@class AVPlayer;
+
+
+@interface VideoPlayerView : UIView
+{
+}
+@property(nonatomic, retain) AVPlayer* player;
+@end
+
+@protocol VideoPlayerDelegate<NSObject>
+- (void)onPlayerReady;
+- (void)onPlayerDidFinishPlayingVideo;
+- (void)onPlayerError:(NSError*)error;
+@end
+
+@interface VideoPlayer : NSObject
+{
+    id<VideoPlayerDelegate> delegate;
+}
+@property (nonatomic, retain) id delegate;
+@property (nonatomic, readonly) AVPlayer* player;
+
++ (BOOL)CanPlayToTexture:(NSURL*)url;
++ (BOOL)CheckScalingModeAspectFill:(CGSize)videoSize screenSize:(CGSize)screenSize;
+
+- (BOOL)loadVideo:(NSURL*)url;
+- (BOOL)readyToPlay;
+- (void)unloadPlayer;
+
+- (BOOL)playToView:(VideoPlayerView*)view;
+- (BOOL)playToTexture;
+- (BOOL)playVideoPlayer;
+- (BOOL)isPlaying;
+
+- (intptr_t)curFrameTexture;
+
+- (void)pause;
+- (void)resume;
+
+- (void)rewind;
+- (void)seekToTimestamp:(CMTime)time;
+- (void)seekTo:(float)timeSeconds;
+
+- (BOOL)setAudioVolume:(float)volume;
+
+- (CMTime)duration;
+- (float)durationSeconds;
+- (CGSize)videoSize;
+@end

+ 495 - 0
unity_ios/Classes/Unity/VideoPlayer.mm

@@ -0,0 +1,495 @@
+#include "VideoPlayer.h"
+
+#include "CVTextureCache.h"
+#include "CMVideoSampling.h"
+
+#import <AVFoundation/AVFoundation.h>
+
+
+static void* _ObserveItemStatusContext = (void*)0x1;
+static void* _ObservePlayerItemContext = (void*)0x2;
+
+
+@implementation VideoPlayerView
++ (Class)layerClass
+{
+    return [AVPlayerLayer class];
+}
+
+- (AVPlayer*)player
+{
+    return [(AVPlayerLayer*)[self layer] player];
+}
+
+- (void)setPlayer:(AVPlayer*)player
+{
+    [(AVPlayerLayer*)[self layer] setPlayer: player];
+}
+
+- (void)dealloc
+{
+    self.player = nil;
+}
+
+@end
+
+
+@implementation VideoPlayer
+{
+    AVPlayerItem*   _playerItem;
+    AVPlayer*       _player;
+
+    AVAssetReader*              _reader;
+    AVAssetReaderTrackOutput*   _videoOut;
+
+    CMSampleBufferRef           _cmSampleBuffer;
+    CMVideoSampling             _videoSampling;
+
+    CMTime          _duration;
+    CMTime          _curTime;
+    CMTime          _curFrameTimestamp;
+    CMTime          _lastFrameTimestamp;
+    CGSize          _videoSize;
+
+    BOOL            _playerReady;
+
+    // we need to have both because the order of asset/item getting ready is not strict
+    BOOL            _assetReady;
+    BOOL            _itemReady;
+}
+
+@synthesize delegate;
+@synthesize player = _player;
+
+- (BOOL)readyToPlay         { return _playerReady; }
+- (CGSize)videoSize         { return _videoSize; }
+- (CMTime)duration          { return _duration; }
+- (float)durationSeconds    { return CMTIME_IS_VALID(_duration) ? (float)CMTimeGetSeconds(_duration) : 0.0f; }
+
+
++ (BOOL)CanPlayToTexture:(NSURL*)url    { return [url isFileURL]; }
++ (BOOL)CheckScalingModeAspectFill:(CGSize)videoSize screenSize:(CGSize)screenSize
+{
+    BOOL ret = NO;
+
+    CGFloat screenAspect = (screenSize.width / screenSize.height);
+    CGFloat videoAspect = (videoSize.width / videoSize.height);
+
+    CGFloat width = ceilf(videoSize.width * videoAspect / screenAspect);
+    CGFloat height = ceilf(videoSize.height * videoAspect / screenAspect);
+
+    // Do additional input video and device resolution aspect ratio
+    // rounding check to see if the width and height values are still
+    // the ~same.
+    //
+    // If they still match, we can change the video scaling mode from
+    // aspectFit to aspectFill, this works around some off-by-one scaling
+    // errors with certain screen size and video resolution combos
+    //
+    // TODO: Shouldn't harm to extend width/height check to
+    // match values within -1..+1 range from the original
+
+    if (videoSize.width == width && videoSize.height == height)
+    {
+        ret = YES;
+    }
+
+    return ret;
+}
+
+- (void)reportError:(NSError*)error category:(const char*)category
+{
+    ::printf("[%s]Error: %s\n", category, [[error localizedDescription] UTF8String]);
+    ::printf("%s\n", [[error localizedFailureReason] UTF8String]);
+    [delegate onPlayerError: error];
+}
+
+- (void)reportErrorWithString:(const char*)error category:(const char*)category
+{
+    ::printf("[%s]Error: %s\n", category, error);
+    [delegate onPlayerError: nil];
+}
+
+- (id)init
+{
+    if ((self = [super init]))
+    {
+        _duration = _curTime = kCMTimeZero;
+        _curFrameTimestamp = _lastFrameTimestamp = kCMTimeZero;
+    }
+    return self;
+}
+
+- (void)cleanupCVTextureCache
+{
+    if (_cmSampleBuffer)
+    {
+        CFRelease(_cmSampleBuffer);
+        _cmSampleBuffer = 0;
+    }
+    CMVideoSampling_Uninitialize(&_videoSampling);
+}
+
+- (void)cleanupAssetReader
+{
+    if (_reader)
+        [_reader cancelReading];
+
+    _reader = nil;
+    _videoOut = nil;
+}
+
+- (void)cleanupPlayer
+{
+    if (_player)
+    {
+        [[NSNotificationCenter defaultCenter] removeObserver: self name: AVAudioSessionRouteChangeNotification object: nil];
+        [_player.currentItem removeObserver: self forKeyPath: @"status"];
+        [_player removeObserver: self forKeyPath: @"currentItem"];
+        [_player pause];
+        _player = nil;
+    }
+
+    if (_playerItem)
+    {
+        [[NSNotificationCenter defaultCenter] removeObserver: self name: AVPlayerItemDidPlayToEndTimeNotification object: _playerItem];
+        _playerItem = nil;
+    }
+}
+
+- (void)unloadPlayer
+{
+    [self cleanupCVTextureCache];
+    [self cleanupAssetReader];
+    [self cleanupPlayer];
+
+    _videoSize = CGSizeMake(0, 0);
+    _duration = _curTime = kCMTimeZero;
+    _curFrameTimestamp = _lastFrameTimestamp = kCMTimeZero;
+
+    self->_playerReady = self->_assetReady = self->_itemReady = NO;
+}
+
+- (BOOL)loadVideo:(NSURL*)url
+{
+    AVURLAsset* asset = [AVURLAsset URLAssetWithURL: url options: nil];
+    if (!asset)
+        return NO;
+
+    NSArray* requestedKeys = @[@"tracks", @"playable"];
+    [asset loadValuesAsynchronouslyForKeys: requestedKeys completionHandler:^{
+        dispatch_async(dispatch_get_main_queue(), ^{
+            [self prepareAsset: asset withKeys: requestedKeys];
+        });
+    }];
+    return YES;
+}
+
+- (BOOL)_playWithPrepareBlock:(BOOL (^)())preparePlaybackBlock
+{
+    if (!_playerReady)
+        return NO;
+    if (preparePlaybackBlock && preparePlaybackBlock() == NO)
+        return NO;
+
+    // do not do seekTo and setRate here, it seems that http streaming may hang sometimes if you do so. go figure
+    _curFrameTimestamp = _lastFrameTimestamp = kCMTimeZero;
+    [_player play];
+    return YES;
+}
+
+- (BOOL)playToView:(VideoPlayerView*)view
+{
+    return [self _playWithPrepareBlock:^() {
+        view.player = self->_player;
+        return YES;
+    }];
+}
+
+- (BOOL)playToTexture
+{
+    return [self _playWithPrepareBlock:^() {
+        return [self prepareReader];
+    }];
+}
+
+- (BOOL)playVideoPlayer
+{
+    return [self _playWithPrepareBlock: nil];
+}
+
+- (BOOL)isPlaying   { return _playerReady && _player.rate != 0.0f; }
+- (void)pause
+{
+    if (_playerReady && _player.rate != 0.0f)
+        [_player pause];
+}
+
+- (void)resume
+{
+    if (_playerReady && _player.rate == 0.0f)
+    {
+        [self seekToTimestamp: _player.currentTime];
+        [_player play];
+    }
+}
+
+- (void)rewind                      { [self seekToTimestamp: kCMTimeZero]; }
+- (void)seekTo:(float)timeSeconds   { [self seekToTimestamp: CMTimeMakeWithSeconds(timeSeconds, 1)]; }
+- (void)seekToTimestamp:(CMTime)time
+{
+    [_player seekToTime: time toleranceBefore: kCMTimeZero toleranceAfter: kCMTimeZero];
+    _curFrameTimestamp = _lastFrameTimestamp = time;
+}
+
+- (intptr_t)curFrameTexture
+{
+    if (!_reader)
+        return 0;
+
+    intptr_t curTex = CMVideoSampling_LastSampledTexture(&_videoSampling);
+
+    CMTime time = [_player currentTime];
+
+    // if we have changed audio route and due to current category apple decided to pause playback - resume automatically
+    if (_AudioRouteWasChanged && _player.rate == 0.0f)
+        _player.rate = 1.0f;
+
+    if (CMTimeCompare(time, _curTime) == 0 || _reader.status != AVAssetReaderStatusReading)
+        return curTex;
+
+    _curTime = time;
+    while (_reader.status == AVAssetReaderStatusReading && CMTimeCompare(_curFrameTimestamp, _curTime) <= 0)
+    {
+        if (_cmSampleBuffer)
+            CFRelease(_cmSampleBuffer);
+
+        // TODO: properly handle ending
+        _cmSampleBuffer = [_videoOut copyNextSampleBuffer];
+        if (_cmSampleBuffer == 0)
+        {
+            [self cleanupCVTextureCache];
+            return 0;
+        }
+
+        _curFrameTimestamp = CMSampleBufferGetPresentationTimeStamp(_cmSampleBuffer);
+    }
+
+    if (CMTimeCompare(_lastFrameTimestamp, _curFrameTimestamp) < 0)
+    {
+        _lastFrameTimestamp = _curFrameTimestamp;
+
+        size_t w, h;
+        curTex = CMVideoSampling_SampleBuffer(&_videoSampling, _cmSampleBuffer, &w, &h);
+        _videoSize = CGSizeMake(w, h);
+    }
+
+    return curTex;
+}
+
+- (BOOL)setAudioVolume:(float)volume
+{
+#if  !PLATFORM_VISIONOS
+    if (!_playerReady)
+        return NO;
+
+    NSArray* audio = [_playerItem.asset tracksWithMediaType: AVMediaTypeAudio];
+    NSMutableArray* params = [NSMutableArray array];
+    for (AVAssetTrack* track in audio)
+    {
+        AVMutableAudioMixInputParameters* inputParams = [AVMutableAudioMixInputParameters audioMixInputParameters];
+        [inputParams setVolume: volume atTime: kCMTimeZero];
+        [inputParams setTrackID: [track trackID]];
+        [params addObject: inputParams];
+    }
+
+    AVMutableAudioMix* audioMix = [AVMutableAudioMix audioMix];
+    [audioMix setInputParameters: params];
+
+    [_playerItem setAudioMix: audioMix];
+
+    return YES;
+#else
+    return YES;
+#endif
+}
+
+- (void)playerItemDidReachEnd:(NSNotification*)notification
+{
+    [delegate onPlayerDidFinishPlayingVideo];
+}
+
+static bool _AudioRouteWasChanged = false;
+- (void)audioRouteChanged:(NSNotification*)notification
+{
+    _AudioRouteWasChanged = true;
+}
+
+- (void)observeValueForKeyPath:(NSString*)path ofObject:(id)object change:(NSDictionary*)change context:(void*)context
+{
+    BOOL reportPlayerReady = NO;
+
+    if (context == _ObserveItemStatusContext)
+    {
+        AVPlayerStatus status = (AVPlayerStatus)[[change objectForKey: NSKeyValueChangeNewKey] integerValue];
+        switch (status)
+        {
+            case AVPlayerStatusUnknown:
+                break;
+
+            case AVPlayerStatusReadyToPlay:
+            {
+#if !PLATFORM_VISIONOS
+                NSArray* video = [_playerItem.asset tracksWithMediaType: AVMediaTypeVideo];
+                if ([video count])
+                    _videoSize = [(AVAssetTrack*)[video objectAtIndex: 0] naturalSize];
+#endif
+                _duration           = [_playerItem duration];
+                _assetReady         = YES;
+                reportPlayerReady   = _itemReady;
+            }
+            break;
+
+            case AVPlayerStatusFailed:
+            {
+                AVPlayerItem *playerItem = (AVPlayerItem*)object;
+                [self reportError: playerItem.error category: "prepareAsset"];
+            }
+            break;
+        }
+    }
+    else if (context == _ObservePlayerItemContext)
+    {
+        if ([change objectForKey: NSKeyValueChangeNewKey] != (id)[NSNull null])
+        {
+            _itemReady = YES;
+            reportPlayerReady = _assetReady;
+        }
+    }
+    else
+    {
+        [super observeValueForKeyPath: path ofObject: object change: change context: context];
+    }
+
+    if (reportPlayerReady)
+    {
+        _playerReady = YES;
+        [delegate onPlayerReady];
+    }
+}
+
+- (void)prepareAsset:(AVAsset*)asset withKeys:(NSArray*)requestedKeys
+{
+    // check succesful loading
+    for (NSString* key in requestedKeys)
+    {
+        NSError* error = nil;
+        AVKeyValueStatus keyStatus = [asset statusOfValueForKey: key error: &error];
+        if (keyStatus == AVKeyValueStatusFailed)
+        {
+            [self reportError: error category: "prepareAsset"];
+            return;
+        }
+    }
+
+    if (!asset.playable)
+    {
+        [self reportErrorWithString: "Item cannot be played" category: "prepareAsset"];
+        return;
+    }
+
+    if (_playerItem)
+    {
+        [_playerItem removeObserver: self forKeyPath: @"status"];
+        [[NSNotificationCenter defaultCenter] removeObserver: self name: AVPlayerItemDidPlayToEndTimeNotification object: _playerItem];
+
+        _playerItem = nil;
+    }
+
+    _playerItem = [AVPlayerItem playerItemWithAsset: asset];
+    [_playerItem    addObserver: self forKeyPath: @"status"
+     options: NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
+     context: _ObserveItemStatusContext
+    ];
+    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(playerItemDidReachEnd:)
+     name: AVPlayerItemDidPlayToEndTimeNotification object: _playerItem
+    ];
+
+    if (!_player)
+    {
+        _player = [AVPlayer playerWithPlayerItem: _playerItem];
+        [_player    addObserver: self forKeyPath: @"currentItem"
+         options: NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
+         context: _ObservePlayerItemContext
+        ];
+
+#if !PLATFORM_VISIONOS
+        [_player setAllowsExternalPlayback: NO];
+#endif
+
+        // we want to subscribe to route change notifications, for that we need audio session active
+        // and in case FMOD wasnt used up to this point it is still not active
+        [[AVAudioSession sharedInstance] setActive: YES error: nil];
+        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(audioRouteChanged:)
+         name: AVAudioSessionRouteChangeNotification object: nil
+        ];
+    }
+
+    if (_player.currentItem != _playerItem)
+        [_player replaceCurrentItemWithPlayerItem: _playerItem];
+    else
+        [_player seekToTime: kCMTimeZero];
+}
+
+- (BOOL)prepareReader
+{
+    if (!_playerReady)
+        return NO;
+
+    [self cleanupAssetReader];
+
+    AVURLAsset* asset = (AVURLAsset*)_playerItem.asset;
+    if (![asset.URL isFileURL])
+    {
+        [self reportErrorWithString: "non-file url. no video to texture." category: "prepareReader"];
+        return NO;
+    }
+
+    NSError* error = nil;
+    _reader = [AVAssetReader assetReaderWithAsset: _playerItem.asset error: &error];
+    if (error)
+        [self reportError: error category: "prepareReader"];
+
+    _reader.timeRange = CMTimeRangeMake(kCMTimeZero, _duration);
+
+
+#if !PLATFORM_VISIONOS
+    AVAssetTrack* videoTrack = [[_playerItem.asset tracksWithMediaType: AVMediaTypeVideo] objectAtIndex: 0];
+
+    NSDictionary* options = @{ (NSString*)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA) };
+    _videoOut = [[AVAssetReaderTrackOutput alloc] initWithTrack: videoTrack outputSettings: options];
+    _videoOut.alwaysCopiesSampleData = NO;
+
+    if (![_reader canAddOutput: _videoOut])
+    {
+        [self reportErrorWithString: "canAddOutput returned false" category: "prepareReader"];
+        return NO;
+    }
+    [_reader addOutput: _videoOut];
+
+    if (![_reader startReading])
+    {
+        [self reportError: [_reader error] category: "prepareReader"];
+        return NO;
+    }
+
+    [self cleanupCVTextureCache];
+    CMVideoSampling_Initialize(&_videoSampling);
+
+    return YES;
+#else
+    return NO;
+#endif
+}
+
+@end

+ 16 - 0
unity_ios/Classes/UnityAppController+Rendering+visionOS.h

@@ -0,0 +1,16 @@
+#pragma once
+
+#if PLATFORM_VISIONOS
+
+#import "UnityAppController.h"
+
+
+@interface UnityAppController (Rendering_visionOS)
+
+@property (readonly) BOOL usingCompositorLayer;
+
+- (void)repaintCompositorLayer;
+
+@end
+
+#endif

+ 117 - 0
unity_ios/Classes/UnityAppController+Rendering+visionOS.mm

@@ -0,0 +1,117 @@
+#if PLATFORM_VISIONOS
+
+#import <CompositorServices/CompositorServices.h>
+#import "UnityAppController+Rendering+visionOS.h"
+#import "UnityAppController+Rendering.h"
+
+
+static cp_layer_renderer_t _LayerRenderer;
+static cp_layer_renderer_state _LayerRendererState = cp_layer_renderer_state_running;
+static bool _ShouldDispatchRepaint = false;
+
+extern bool _didResignActive;
+
+
+@implementation UnityAppController (Rendering_visionOS)
+
+- (BOOL)usingCompositorLayer
+{
+    return _LayerRenderer != nil;
+}
+
+- (void)repaintCompositorLayer
+{
+    // Terminate dispatch loop when the app quits.
+    // If _quitHandler is set, we don't call exit() and this loop will continue indefinitely, preventing the app from quitting.
+    if (self.engineLoadState == kUnityEngineLoadStateNotStarted)
+        return;
+
+    auto isRendererRunning = _LayerRendererState == cp_layer_renderer_state_running;
+    auto isAppActive = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
+
+    if (isAppActive)
+    {
+        if (isRendererRunning)
+        {
+            if (UnityIsPaused())
+            {
+                UnityWillResume();
+                UnityPause(0);
+            }
+
+            if(self.engineLoadState >= kUnityEngineLoadStateRenderingInitialized)
+            {
+                UnityDisplayLinkCallback(0.0);
+                [self repaint];
+            }
+        }
+        else
+        {
+            _LayerRendererState = cp_layer_renderer_get_state(_LayerRenderer);
+        }
+    }
+    else
+    {
+        if(_didResignActive)
+        {
+            UnityDisplayLinkCallback(0.0);
+            [self repaint];
+        }
+        else if (!UnityIsPaused())
+        {
+            if (UnityIsFocused())
+                UnitySetPlayerFocus(0);
+
+            UnityPause(1);
+        }
+        else
+        {
+            _LayerRendererState = cp_layer_renderer_get_state(_LayerRenderer);
+        }
+    }
+
+    if (_ShouldDispatchRepaint)
+        dispatch_async(dispatch_get_main_queue(), ^{ [self repaintDisplayLink]; });
+}
+
+@end
+
+
+@interface UnityVisionOSCompositorBridge : NSObject
+
++ (void)setLayerRenderer:(cp_layer_renderer_t)layerRenderer;
++ (void)setLayerRendererState:(NSNumber*)layerRendererState;
+
+@end
+
+@implementation UnityVisionOSCompositorBridge
+
++ (void)setLayerRenderer:(cp_layer_renderer_t)layerRenderer
+{
+    _LayerRenderer = layerRenderer;
+    if (layerRenderer == nil)
+    {
+        _ShouldDispatchRepaint = false;
+        [_UnityAppController createDisplayLink];
+    }
+    else
+    {
+        _ShouldDispatchRepaint = true;
+        [_UnityAppController destroyDisplayLink];
+
+        // Manually call repaintDisplayLink to kick off dispatched repaint loop
+        // Skip this step if the engine is not loaded yet. In a delayed load scenario (like wait for managed debugger),
+        // repaintDisplayLink is called during normal engine load
+        if (_UnityAppController.engineLoadState == kUnityEngineLoadStateAppReady)
+            [_UnityAppController repaintDisplayLink];
+    }
+}
+
++ (void)setLayerRendererState:(NSNumber*) layerRendererStateObject
+{
+    _LayerRendererState = (cp_layer_renderer_state)layerRendererStateObject.intValue;
+}
+
+@end
+
+#endif

+ 61 - 0
unity_ios/Classes/UnityAppController+Rendering.h

@@ -0,0 +1,61 @@
+#pragma once
+
+#include "UnityForwardDecls.h"
+#include "UnityAppController.h"
+#include "UnityRendering.h"
+#if PLATFORM_VISIONOS
+#include "UnityAppController+Rendering+visionOS.h"
+#endif
+
+#if UNITY_USES_METAL_DISPLAY_LINK
+@interface UnityAppController (Rendering) <CAMetalDisplayLinkDelegate>
+#else
+@interface UnityAppController (Rendering)
+#endif
+
+#if !PLATFORM_VISIONOS
+@property (readonly) BOOL usingCompositorLayer;
+#endif
+
+- (void)createDisplayLink;
+- (void)repaintDisplayLink;
+- (void)destroyDisplayLink;
+
+- (void)pauseDisplayLink;
+- (void)unpauseDisplayLink;
+
+- (void)repaint;
+
+#if UNITY_USES_METAL_DISPLAY_LINK
+- (void)metalDisplayLink:(CAMetalDisplayLink *)link needsUpdate:(CAMetalDisplayLinkUpdate *)update API_AVAILABLE(ios(17.0), tvos(17.0));
+#endif
+
+#if !PLATFORM_VISIONOS
+- (void)repaintCompositorLayer;
+#endif
+
+- (void)selectRenderingAPI;
+@property (readonly, nonatomic) UnityRenderingAPI   renderingAPI;
+
+// These methods switch between CADisplayLink and CAMetalDisplayLink at runtime.
+// Both dispatch the actual work to the main thread, outside of the Unity player loop.
+// Switch to CADisplayLink is always possible; if already using CADisplayLink, it's a no-op.
+// Switch to CAMetalDisplayLink checks shouldUseMetalDisplayLink first
+//   and stays on CADisplayLink if it returns false.
+- (void)switchToCADisplayLink;
+#if UNITY_USES_METAL_DISPLAY_LINK
+- (void)switchToMetalDisplayLink API_AVAILABLE(ios(17.0), tvos(17.0));
+#endif
+
+@end
+
+// helper to run unity loop along with proper handling of the rendering
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void UnityRepaint();
+
+#ifdef __cplusplus
+} // extern "C"
+#endif

+ 393 - 0
unity_ios/Classes/UnityAppController+Rendering.mm

@@ -0,0 +1,393 @@
+#include "UnityAppController+Rendering.h"
+#include "UnityAppController+Thermal.h"
+#include "UnityAppController+ViewHandling.h"
+
+#include "Unity/InternalProfiler.h"
+#include "Unity/DisplayManager.h"
+
+#include "UI/UnityView.h"
+
+#include <dlfcn.h>
+
+#import <Metal/Metal.h>
+
+extern bool _didResignActive;
+
+static int _renderingAPI = 0;
+static void SelectRenderingAPIImpl();
+
+
+@implementation UnityAppController (Rendering)
+
+#if !PLATFORM_VISIONOS
+- (BOOL)usingCompositorLayer
+{
+    return NO;
+}
+#endif
+
+- (void)createCADisplayLink
+{
+    _displayLink = [CADisplayLink displayLinkWithTarget: self selector: @selector(repaintDisplayLink)];
+    [self callbackFramerateChange: -1];
+    [_displayLink addToRunLoop: [NSRunLoop currentRunLoop] forMode: NSRunLoopCommonModes];
+
+    printf_console("CADisplayLink created\n");
+}
+
+#if UNITY_USES_METAL_DISPLAY_LINK
+- (void)createMetalDisplayLink API_AVAILABLE(ios(17.0), tvos(17.0))
+{
+    _usesMetalDisplayLink = YES;
+
+    _metalDisplayLink = [[CAMetalDisplayLink alloc] initWithMetalLayer:(CAMetalLayer*)_unityView.layer];
+    _metalDisplayLink.preferredFrameLatency = 2;
+    _metalDisplayLink.paused = NO;
+    _metalDisplayLink.delegate = self;
+
+    [self callbackFramerateChange: -1];
+    [_metalDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
+
+    printf_console("CAMetalDisplayLink created\n");
+}
+#endif
+
+- (void)createDisplayLink
+{
+    _usesMetalDisplayLink = NO; // we will set it to YES inside createMetalDisplayLink
+
+#if UNITY_USES_METAL_DISPLAY_LINK
+    if (@available(iOS 17.0, tvOS 17.0, *))
+    {
+        if ([self shouldUseMetalDisplayLink])
+            [self createMetalDisplayLink];
+    }
+#endif
+
+    if (!_usesMetalDisplayLink)
+        [self createCADisplayLink];
+}
+
+- (void)destroyDisplayLink
+{
+    [_displayLink invalidate];
+    _displayLink = nil;
+
+#if UNITY_USES_METAL_DISPLAY_LINK
+    if (@available(iOS 17.0, tvOS 17.0, *))
+    {
+        [_metalDisplayLink invalidate];
+        _metalDisplayLink = nil;
+    }
+#endif
+}
+
+- (void)pauseDisplayLink
+{
+    _displayLink.paused = YES;
+#if UNITY_USES_METAL_DISPLAY_LINK
+    if (@available(iOS 17.0, tvOS 17.0, *))
+        _metalDisplayLink.paused = YES;
+#endif
+}
+- (void)unpauseDisplayLink
+{
+    _displayLink.paused = NO;
+#if UNITY_USES_METAL_DISPLAY_LINK
+    if (@available(iOS 17.0, tvOS 17.0, *))
+        _metalDisplayLink.paused = NO;
+#endif
+}
+
+- (void)switchToCADisplayLinkImpl
+{
+    if (_usesMetalDisplayLink)
+    {
+    #if UNITY_USES_METAL_DISPLAY_LINK
+        if (@available(iOS 17.0, tvOS 17.0, *))
+        {
+            _metalDisplayLink.paused = YES;
+            [_metalDisplayLink invalidate];
+            _metalDisplayLink = nil;
+        }
+    #endif
+
+        _usesMetalDisplayLink = NO;
+        [self createCADisplayLink];
+    }
+}
+
+- (void)switchToCADisplayLink
+{
+    dispatch_async(dispatch_get_main_queue(), ^() {
+        [self switchToCADisplayLinkImpl];
+    });
+}
+
+#if UNITY_USES_METAL_DISPLAY_LINK
+- (void)switchToMetalDisplayLinkImpl API_AVAILABLE(ios(17.0), tvos(17.0))
+{
+    if (!_usesMetalDisplayLink && [self shouldUseMetalDisplayLink])
+    {
+        _displayLink.paused = YES;
+        [_displayLink invalidate];
+        _displayLink = nil;
+
+        [self createMetalDisplayLink];
+    }
+}
+
+- (void)switchToMetalDisplayLink
+{
+    dispatch_async(dispatch_get_main_queue(), ^() {
+        [self switchToMetalDisplayLinkImpl];
+    });
+}
+#endif
+
+
+- (void)repaintDisplayLink
+{
+    if (self.usingCompositorLayer == NO)
+    {
+        UnityDisplayLinkCallback(_displayLink.timestamp);
+        [self repaint];
+    }
+    else
+    {
+        [self repaintCompositorLayer];
+    }
+}
+
+#if UNITY_USES_METAL_DISPLAY_LINK
+- (void)metalDisplayLink:(CAMetalDisplayLink*)link needsUpdate:(CAMetalDisplayLinkUpdate*)update
+{
+    // we have found an issue on some devices in iOS handling of metal display link
+    // [NSAttributedString initWithData: options: documentAttributes: error:]
+    //   will load webkit on the first call which, in turn, will call metal display link callback
+    //   (most likely because it takes so slow)
+    // When NSAttributedString is used in plugin (called from unity player loop)
+    //   this results in a recursive [metalDisplayLink: needsUpdate:] call
+    // While Unity playerloop returns immediately, our trampoline rendering implementation
+    //   is not "ready" for it, and we will get a crash
+    // While this is purely apple iOS bug, we still want to work around it since
+    // 1. It is hard for users to track down the crash (it will crash in unrelated code)
+    // 2. It is hard for users to fix it (since they need to fix plugins logic considerably to use other means for HTML string)
+    // thus we try to catch this case here: if nextDrawable is still set, we did not yet ended previous frame
+    //   which is only possible if the recursive call was made, so we just ignore this frame.
+    // It will result in metal debug driver logging GPU Timeout Errors, but everything works fine
+    UnityDisplaySurfaceMTL* displaySurface = (UnityDisplaySurfaceMTL*)_mainDisplay.surface;
+    if(displaySurface->swapchain.nextDrawable != nil)
+        return;
+
+    UnityDisplayLinkCallback(0);
+
+    displaySurface->swapchain.nextDrawable = update.drawable;
+    [self repaint];
+}
+#endif
+
+- (void)repaint
+{
+    if (_unityView.skipRendering)
+        return;
+
+#if UNITY_SUPPORT_ROTATION
+    [self checkOrientationRequest];
+#endif
+
+    [_unityView recreateRenderingSurfaceIfNeeded];
+    [_unityView processKeyboard];
+    UnityDeliverUIEvents();
+
+    // we want to support both CADisplayLink and CAMetalDisplayLink
+    // the major complication is that they work quite differently under the hood
+    // CADisplayLink: you can consider this a simple timer-based callback
+    //   so if we get this while in background - we might be not allowed to render at all
+    //   and before we were having an explicit check to repain only if we are not paused
+    // CAMetalDisplayLink: unlike CADisplayLink (where we query drawable from view),
+    //   the callback comes when we are asked explicitly to render view contents (we are given drawable)
+    //   and we cannot bypass rendering when asked at all
+
+    if(UnityIsPaused())
+    {
+        if(self.unityUsesMetalDisplayLink)
+            UnityRenderWithoutPlayerLoopWithBackbuffer(GetMainDisplaySurface()->unityColorBuffer, GetMainDisplaySurface()->unityDepthBuffer);
+    }
+    else
+    {
+        UnityRepaint();
+    }
+
+    id<MTLCommandBuffer> cb = [UnityGetMetalCommandQueue() commandBuffer];
+    cb.label = @"Present";
+    [[DisplayManager Instance] presentWith:cb];
+    [cb commit];
+
+#if !PLATFORM_VISIONOS
+    if (UnityResolutionScalingFixedDPIFactorChanged())
+        _unityView.contentScaleFactor = UnityScreenScaleFactor([UIScreen mainScreen]);
+#endif
+
+    UnityCheckUnloadAndQuit();
+}
+
+#if !PLATFORM_VISIONOS
+- (void)repaintCompositorLayer
+{
+}
+#endif
+
+- (void)callbackGfxInited
+{
+    assert(self.engineLoadState < kUnityEngineLoadStateRenderingInitialized && "Graphics should not have been initialized at this point");
+    InitRendering();
+    [self advanceEngineLoadState: kUnityEngineLoadStateRenderingInitialized];
+
+    [self shouldAttachRenderDelegate];
+    [_unityView updateLayerDrawableSizeFromBounds];
+    [_unityView updateUnityBackbufferSize];
+    [_unityView recreateRenderingSurface];
+    [_renderDelegate mainDisplayInited: _mainDisplay.surface];
+
+    _mainDisplay.surface->allowScreenshot = 1;
+}
+
+- (void)callbackFramerateChange:(int)targetFPS
+{
+    if (targetFPS <= 0)
+        targetFPS = UnityGetTargetFPS();
+
+    // on tvos it is possible to start application without a screen attached
+    // alas, mainScreen is set in this case, but the values provided are bogus
+    //   and in the case of maxFPS = 0 we will end up in endless recursion
+#if !PLATFORM_VISIONOS
+    const int maxFPS = (int)[UIScreen mainScreen].maximumFramesPerSecond;
+#else
+    // no UIScreen on VisionOS
+    const int maxFPS = 90;
+#endif
+    if (maxFPS > 0 && targetFPS > maxFPS)
+    {
+        targetFPS = maxFPS;
+        // note that this changes FPS, resulting in UnityFramerateChangeCallback call, calling this method recursively recursively
+        UnitySetTargetFPS(targetFPS);
+        return;
+    }
+
+    if (UnityShouldAdjustPerformanceOnThermalStateChange())
+        targetFPS = [self adjustFrameRateForThermalState:targetFPS];
+
+    if(_usesMetalDisplayLink)
+    {
+    #if UNITY_USES_METAL_DISPLAY_LINK
+        if (@available(iOS 17.0, tvOS 17.0, *))
+            _metalDisplayLink.preferredFrameRateRange = CAFrameRateRangeMake(targetFPS, targetFPS, targetFPS);
+    #endif
+    }
+    else
+    {
+            _displayLink.preferredFrameRateRange = CAFrameRateRangeMake(targetFPS, targetFPS, targetFPS);
+    }
+}
+
+- (void)selectRenderingAPI
+{
+    NSAssert(_renderingAPI == 0, @"[UnityAppController selectRenderingApi] called twice");
+    SelectRenderingAPIImpl();
+}
+
+- (UnityRenderingAPI)renderingAPI
+{
+    NSAssert(_renderingAPI != 0, @"[UnityAppController renderingAPI] called before [UnityAppController selectRenderingApi]");
+    return (UnityRenderingAPI)_renderingAPI;
+}
+
+@end
+
+
+UNITY_EXPORT extern "C" void UnityGfxInitedCallback()
+{
+    [GetAppController() callbackGfxInited];
+}
+
+UNITY_EXPORT extern "C" void UnityPresentContextCallback()
+{
+}
+
+UNITY_EXPORT extern "C" void UnityFramerateChangeCallback(int targetFPS)
+{
+    [GetAppController() callbackFramerateChange: targetFPS];
+}
+
+static NSBundle*            _MetalBundle        = nil;
+static id<MTLDevice>        _MetalDevice        = nil;
+static id<MTLCommandQueue>  _MetalCommandQueue  = nil;
+
+static void SelectRenderingAPIImpl()
+{
+    assert(_renderingAPI == 0 && "Rendering API selection was done twice");
+
+    _renderingAPI = UnityGetRenderingAPI();
+    if (_renderingAPI == apiMetal)
+    {
+        _MetalBundle        = [NSBundle bundleWithPath: @"/System/Library/Frameworks/Metal.framework"];
+        _MetalDevice        = MTLCreateSystemDefaultDevice();
+        _MetalCommandQueue  = [_MetalDevice newCommandQueueWithMaxCommandBufferCount: UnityCommandQueueMaxCommandBufferCountMTL()];
+
+        assert(_MetalDevice != nil && _MetalCommandQueue != nil && "Could not initialize Metal.");
+    }
+}
+
+UNITY_EXPORT extern "C" NSBundle*            UnityGetMetalBundle()       { return _MetalBundle; }
+UNITY_EXPORT extern "C" MTLDeviceRef         UnityGetMetalDevice()       { return _MetalDevice; }
+UNITY_EXPORT extern "C" MTLCommandQueueRef   UnityGetMetalCommandQueue() { return _MetalCommandQueue; }
+UNITY_EXPORT extern "C" int                  UnitySelectedRenderingAPI() { return _renderingAPI; }
+UNITY_EXPORT extern "C" void                 UnitySelectRenderingAPI()   { SelectRenderingAPIImpl(); }
+
+// deprecated and no longer used by unity itself (will soon be removed)
+UNITY_EXPORT extern "C" MTLCommandQueueRef   UnityGetMetalDrawableCommandQueue() { return UnityGetMetalCommandQueue(); }
+
+
+UNITY_EXPORT extern "C" UnityRenderBufferHandle  UnityBackbufferColor()      { return GetMainDisplaySurface()->unityColorBuffer; }
+UNITY_EXPORT extern "C" UnityRenderBufferHandle  UnityBackbufferDepth()      { return GetMainDisplaySurface()->unityDepthBuffer; }
+
+UNITY_EXPORT extern "C" void                 DisplayManagerEndFrameRendering() { [[DisplayManager Instance] endFrameRendering]; }
+
+UNITY_EXPORT extern "C" void                 UnityPrepareScreenshot()    { UnitySetRenderTarget(GetMainDisplaySurface()->unityColorBuffer, GetMainDisplaySurface()->unityDepthBuffer); }
+
+UNITY_EXPORT extern "C" void UnityRepaint()
+{
+    @autoreleasepool
+    {
+        Profiler_FrameStart();
+        if (UnityIsBatchmode())
+            UnityBatchPlayerLoop();
+        else
+            UnityPlayerLoopWithBackbuffer(GetMainDisplaySurface()->unityColorBuffer, GetMainDisplaySurface()->unityDepthBuffer);
+        Profiler_FrameEnd();
+    }
+}
+
+UNITY_EXPORT extern "C" void UnitySetMaxQueuedFrames(unsigned count)
+{
+    assert(2 <= count && count <= 3);
+
+    UnityAppController* app = GetAppController();
+
+    if (app.unityUsesMetalDisplayLink)
+    {
+    #if UNITY_USES_METAL_DISPLAY_LINK
+        if (@available(iOS 17.0, tvOS 17.0, *))
+            app.unityMetalDisplayLink.preferredFrameLatency = count - 1;
+    #endif
+    }
+    else
+    {
+        dispatch_async(dispatch_get_main_queue(), ^() {
+            CALayer* layer = app.unityView.layer;
+            if ([layer isKindOfClass: [CAMetalLayer class]])
+                ((CAMetalLayer*)layer).maximumDrawableCount = count;
+        });
+    }
+}

+ 10 - 0
unity_ios/Classes/UnityAppController+Thermal.h

@@ -0,0 +1,10 @@
+#pragma once
+
+#include "UnityAppController.h"
+
+@interface UnityAppController (Thermal)
+
+- (void)subscribeToThermalChanges;
+- (int)adjustFrameRateForThermalState:(int)targetFPS;
+
+@end

+ 73 - 0
unity_ios/Classes/UnityAppController+Thermal.mm

@@ -0,0 +1,73 @@
+#include "UnityAppController+Thermal.h"
+#include "UnityAppController+Rendering.h"
+#include "UnityInterface.h"
+
+#import <Foundation/Foundation.h>
+
+@implementation UnityAppController (Thermal)
+
+- (void)subscribeToThermalChanges
+{
+    ::printf_console("Player Setting 'Adjust iOS FPS based on thermal state' is %s\n", UnityShouldAdjustPerformanceOnThermalStateChange() ? "ON" : "OFF");
+
+    [self notifyThermalState: [NSProcessInfo processInfo].thermalState];
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(thermalStateDidChange:) name:NSProcessInfoThermalStateDidChangeNotification object:nil];
+}
+
+- (int)adjustFrameRateForThermalState:(int)targetFPS
+{
+    const NSProcessInfoThermalState thermalState = [NSProcessInfo processInfo].thermalState;
+
+    const int seriousFPS = UnityGetThermalStateSeriousFPS();
+    const int criticalFPS = UnityGetThermalStateCriticalFPS();
+
+    if (thermalState == NSProcessInfoThermalStateSerious && targetFPS > seriousFPS)
+        return seriousFPS;
+    else if (thermalState == NSProcessInfoThermalStateCritical && targetFPS > criticalFPS)
+        return criticalFPS;
+
+    return targetFPS;
+}
+
+- (void)thermalStateDidChange:(NSNotification*)note
+{
+    [self notifyThermalState: [NSProcessInfo processInfo].thermalState];
+}
+
+- (void)notifyThermalState:(NSProcessInfoThermalState)state
+{
+    const char* stateString = [self thermalStateToString:state];
+    ::printf_console("thermalStateDidChange: %s\n", stateString);
+
+    UnityThermalStateChanged(static_cast<int>(state));
+
+#if UNITY_USES_METAL_DISPLAY_LINK
+    if (state == NSProcessInfoThermalStateNominal || state == NSProcessInfoThermalStateFair)
+    {
+        if (@available(iOS 17.0, tvOS 17.0, *))
+            [self switchToMetalDisplayLink];
+    }
+#endif
+
+    if (state == NSProcessInfoThermalStateSerious || state == NSProcessInfoThermalStateCritical)
+        [self switchToCADisplayLink];
+}
+
+- (const char*)thermalStateToString:(NSProcessInfoThermalState)state
+{
+    switch (state)
+    {
+        case NSProcessInfoThermalStateNominal:
+            return "Nominal";
+        case NSProcessInfoThermalStateFair:
+            return "Fair";
+        case NSProcessInfoThermalStateSerious:
+            return "Serious";
+        case NSProcessInfoThermalStateCritical:
+            return "Critical";
+        default:
+            return "Unknown";
+    }
+}
+
+@end

+ 10 - 0
unity_ios/Classes/UnityAppController+UnityInterface.h

@@ -0,0 +1,10 @@
+#pragma once
+
+#include "UnityAppController.h"
+
+
+@interface UnityAppController (UnityInterface)
+
+@property (nonatomic) BOOL  paused;
+
+@end

+ 19 - 0
unity_ios/Classes/UnityAppController+UnityInterface.mm

@@ -0,0 +1,19 @@
+#include "UnityAppController+UnityInterface.h"
+#include "UnityAppController+Rendering.h"
+
+
+@implementation UnityAppController (UnityInterface)
+
+- (BOOL)paused
+{
+    return UnityIsPaused() ? YES : NO;
+}
+
+- (void)setPaused:(BOOL)pause
+{
+    const int newPause  = pause == YES ? 1 : 0;
+
+    UnityPause(newPause);
+}
+
+@end

+ 177 - 0
unity_ios/Classes/UnityAppController.h

@@ -0,0 +1,177 @@
+#pragma once
+
+#import <QuartzCore/CADisplayLink.h>
+
+// we want to use CAMetalDisplayLink if it is available
+// if CADisplayLink is always preferred, this can be changed to #define UNITY_USES_METAL_DISPLAY_LINK 0
+// further, shouldUseMetalDisplayLink method can be overriden/tweaked to disable metal display link at runtime
+//   e.g. you might want to use old display link on slower devices where stable frametime cannot be guaranteed
+#define UNITY_USES_METAL_DISPLAY_LINK (UNITY_HAS_IOSSDK_17_0 || UNITY_HAS_TVOSSDK_17_0)
+#if UNITY_USES_METAL_DISPLAY_LINK
+    #import <QuartzCore/CAMetalDisplayLink.h>
+#endif
+
+#import <UnityFramework/RenderPluginDelegate.h>
+
+@class UnityView;
+@class UnityViewControllerBase;
+@class DisplayConnection;
+
+typedef enum
+{
+    kUnityEngineLoadStateNotStarted = 0,
+    // Minimal initialization done, allowing limited API use, such as reporting URL app was launched with
+    kUnityEngineLoadStateMinimal = 1,
+    // Core of Unity engine is loaded, but no graphics or first scene yet
+    kUnityEngineLoadStateCoreInitialized = 2,
+    // Rendering was initialized, nothing related to rendering should be touched before this state
+    kUnityEngineLoadStateRenderingInitialized = 3,
+    // Unity is fully initialized, it's not safe to call Unity APIs before this state
+    kUnityEngineLoadStateAppReady = 4,
+} UnityEngineLoadState;
+
+__attribute__ ((visibility("default")))
+@interface UnityAppController : NSObject<UIApplicationDelegate>
+{
+    UnityView*          _unityView;
+    CADisplayLink*      _displayLink;
+#if UNITY_USES_METAL_DISPLAY_LINK
+    CAMetalDisplayLink* _metalDisplayLink API_AVAILABLE(ios(17.0), tvos(17.0));
+#endif
+    // since we can have CAMetalDisplayLink not available both at runtime (old ios) and at compile time (old xcode)
+    //   and we can have it disabled completely (not all applications need it)
+    // the code supporting both CAMetalDisplayLink and CADisplayLink can easily become very convoluted
+    // hence we add a boolean to check CAMetalDisplayLink usage without checks for @available and preprocessor ifdefs
+    BOOL                _usesMetalDisplayLink;
+
+    UIWindow*           _window;
+    UIView*             _rootView;
+    UIViewController*   _rootController;
+    UIViewController*   _snapshotViewController;
+
+    DisplayConnection*  _mainDisplay;
+
+    // CODE ARCHEOLOGY: we were caching view controllers, both autorotation one and per-fixed-orientation ones
+    // CODE ARCHEOLOGY: we stopped doing this as the performance impact is negligible,
+    // CODE ARCHEOLOGY: yet it introduces corner cases and in general lots of code
+
+#if UNITY_SUPPORT_ROTATION
+    UIInterfaceOrientation  _curOrientation;
+#endif
+
+    id<RenderPluginDelegate>    _renderDelegate;
+}
+
+// override it to add your render plugin delegate
+- (void)shouldAttachRenderDelegate;
+
+// this one is called at the very end of didFinishLaunchingWithOptions:
+// after views have been created but before initing engine itself
+// override it to register plugins, tweak UI etc
+- (void)preStartUnity;
+
+- (void)initUnityApplicationNoGraphics;
+
+// this one is called at at the very end of didFinishLaunchingWithOptions:
+// it will start showing unity view and rendering unity content
+- (void)initUnityWithScene:(UIWindowScene*)scene;
+
+// this one is called at at the very end of didFinishLaunchingWithOptions:
+// it will start showing unity view and rendering unity content
+- (void)startUnity;
+
+// override it if you want to have custom logic for the decision to use CAMetalDisplayLink or not
+// in any case, CAMetalDisplayLink will be used only if actually supported by the device
+// this will be called once on startup, before any rendering but after initializing unity
+- (BOOL)shouldUseMetalDisplayLink;
+
+- (BOOL)advanceEngineLoadState:(UnityEngineLoadState)newState;
+- (BOOL)downgradeEngineLoadState:(UnityEngineLoadState)newState;
+
+// this is a part of UIApplicationDelegate protocol starting with ios5
+// setter will be generated empty
+@property (retain, nonatomic) UIWindow* window;
+
+@property (readonly, copy, nonatomic) UnityView*            unityView;
+@property (readonly, copy, nonatomic) CADisplayLink*        unityDisplayLink;
+@property (readonly, nonatomic) BOOL                        unityUsesMetalDisplayLink;
+
+#if UNITY_USES_METAL_DISPLAY_LINK
+@property (readonly, copy, nonatomic) CAMetalDisplayLink*   unityMetalDisplayLink API_AVAILABLE(ios(17.0), tvos(17.0));
+#endif
+
+@property (readonly, copy, nonatomic) UIView*               rootView;
+@property (readonly, copy, nonatomic) UIViewController*     rootViewController;
+@property (readonly, copy, nonatomic) DisplayConnection*    mainDisplay;
+
+#if UNITY_SUPPORT_ROTATION
+@property (readonly, nonatomic) UIInterfaceOrientation      interfaceOrientation;
+#endif
+
+@property (readonly) UnityEngineLoadState                   engineLoadState;
+@property (readonly) bool                                   didResignActive;
+@property (nonatomic, retain) id                            renderDelegate;
+@property (nonatomic, copy)                                 void (^quitHandler)(void);
+
+@end
+
+// accessing app controller
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern UnityAppController* _UnityAppController;
+extern UnityAppController* GetAppController(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+// Put this into mm file with your subclass implementation
+// pass subclass name to define
+
+#define IMPL_APP_CONTROLLER_SUBCLASS(ClassName) \
+@interface ClassName(OverrideAppDelegate)       \
+{                                               \
+}                                               \
++(void)load;                                    \
+@end                                            \
+@implementation ClassName(OverrideAppDelegate)  \
++(void)load                                     \
+{                                               \
+    extern const char* AppControllerClassName;  \
+    AppControllerClassName = #ClassName;        \
+}                                               \
+@end                                            \
+
+
+// plugins
+
+#define APP_CONTROLLER_RENDER_PLUGIN_METHOD(method)                         \
+do {                                                                        \
+    id<RenderPluginDelegate> delegate = GetAppController().renderDelegate;  \
+    if([delegate respondsToSelector:@selector(method)])                     \
+        [delegate method];                                                  \
+} while(0)
+
+#define APP_CONTROLLER_RENDER_PLUGIN_METHOD_ARG(method, arg)                \
+do {                                                                        \
+    id<RenderPluginDelegate> delegate = GetAppController().renderDelegate;  \
+    if([delegate respondsToSelector:@selector(method:)])                    \
+        [delegate method:arg];                                              \
+} while(0)
+
+
+// these are simple wrappers about ios api, added for convenience
+void AppController_SendNotification(NSString* name);
+void AppController_SendNotificationWithArg(NSString* name, id arg);
+
+void AppController_SendUnityViewControllerNotification(NSString* name);
+
+// in the case when apple adds new api that has easy fallback path for old ios
+// we will add new api methods at runtime on older ios, so we can switch to new api universally
+// in that case we still need actual declaration: we will do it here as it is the most convenient place
+
+// history:
+// [CADisplayLink preferredFramesPerSecond], [UIScreen maximumFramesPerSecond], [UIView safeAreaInsets]
+//   were removed after we started to enforce xcode9 (sdk 11)

+ 904 - 0
unity_ios/Classes/UnityAppController.mm

@@ -0,0 +1,904 @@
+#import "UnityAppController.h"
+#import "UnityAppController+Thermal.h"
+#import "UnityAppController+ViewHandling.h"
+#import "UnityAppController+Rendering.h"
+#import "iPhone_Sensors.h"
+
+#import <CoreGraphics/CoreGraphics.h>
+#import <QuartzCore/QuartzCore.h>
+#import <QuartzCore/CADisplayLink.h>
+#import <Availability.h>
+#import <AVFoundation/AVFoundation.h>
+#import <GameController/GameController.h>
+
+#include <mach/mach_time.h>
+
+// MSAA_DEFAULT_SAMPLE_COUNT was removed
+// ENABLE_INTERNAL_PROFILER and related defines were moved to iPhone_Profiler.h
+// kFPS define for removed: you can use Application.targetFrameRate (30 fps by default)
+// DisplayLink is the only run loop mode now - all others were removed
+
+#include "CrashReporter.h"
+
+#include "UI/OrientationSupport.h"
+#include "UI/UnityView.h"
+#include "UI/Keyboard.h"
+#include "UI/UnityViewControllerBase.h"
+#include "Unity/InternalProfiler.h"
+#include "Unity/DisplayManager.h"
+#include "Unity/ObjCRuntime.h"
+#include "PluginBase/AppDelegateListener.h"
+
+#include <assert.h>
+#include <stdbool.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <sys/sysctl.h>
+#include <UndefinePlatforms.h>
+#include <os/log.h>
+#include <RedefinePlatforms.h>
+
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+@interface UnityView (iOSScrollWheel)
+- (void)teardownIndirectMouseInput;
+@end
+#endif
+
+// we assume that app delegate is never changed and we can cache it, instead of re-query UIApplication every time
+UnityAppController* _UnityAppController = nil;
+UnityAppController* GetAppController()
+{
+    return _UnityAppController;
+}
+
+// we keep old bools around to support "old" code that might have used them
+bool _ios81orNewer = true, _ios82orNewer = true, _ios83orNewer = true, _ios90orNewer = true, _ios91orNewer = true;
+bool _ios100orNewer = true, _ios101orNewer = true, _ios102orNewer = true, _ios103orNewer = true;
+bool _ios110orNewer = true, _ios111orNewer = true, _ios112orNewer = true;
+bool _ios130orNewer = true, _ios140orNewer = false, _ios150orNewer = false, _ios160orNewer = false;
+bool _unityEngineLoaded = false, _unityEngineInitialized = false, _renderingInited = false, _unityAppReady = false;
+
+static UInt32 _iosMajorVersion = 0;
+static UInt32 _iosMinorVersion = 0;
+// see if there's a need to do internal player pause/resume handling
+//
+// Typically the trampoline code should manage this internally, but
+// there are use cases, videoplayer, plugin code, etc where the player
+// is paused before the internal handling comes relevant. Avoid
+// overriding externally managed player pause/resume handling by
+// caching the state
+bool    _wasPausedExternal      = false;
+// was app "resigned active": some operations do not make sense while app is in background
+bool    _didResignActive        = false;
+
+#if UNITY_SUPPORT_ROTATION
+// Required to enable specific orientation for some presentation controllers: see supportedInterfaceOrientationsForWindow below for details
+NSInteger _forceInterfaceOrientationMask = 0;
+#endif
+
+@implementation UnityAppController
+{
+    UnityEngineLoadState _engineLoadState;
+}
+
+@synthesize unityView                   = _unityView;
+@synthesize unityDisplayLink            = _displayLink;
+@synthesize unityUsesMetalDisplayLink   = _usesMetalDisplayLink;
+
+#if UNITY_USES_METAL_DISPLAY_LINK
+    @synthesize unityMetalDisplayLink   = _metalDisplayLink;
+#endif
+
+@synthesize rootView                = _rootView;
+@synthesize rootViewController      = _rootController;
+@synthesize mainDisplay             = _mainDisplay;
+@synthesize engineLoadState         = _engineLoadState;
+@synthesize renderDelegate          = _renderDelegate;
+@synthesize quitHandler             = _quitHandler;
+
+#if UNITY_SUPPORT_ROTATION
+@synthesize interfaceOrientation    = _curOrientation;
+#endif
+
+- (id)init
+{
+    if ((self = _UnityAppController = [super init]))
+    {
+        // due to clang issues with generating warning for overriding deprecated methods
+        // we will simply assert if deprecated methods are present
+        // NB: methods table is initied at load (before this call), so it is ok to check for override
+        NSAssert(![self respondsToSelector: @selector(createUnityViewImpl)],
+            @"createUnityViewImpl is deprecated and will not be called. Override createUnityView"
+        );
+        NSAssert(![self respondsToSelector: @selector(createViewHierarchyImpl)],
+            @"createViewHierarchyImpl is deprecated and will not be called. Override willStartWithViewController"
+        );
+        NSAssert(![self respondsToSelector: @selector(createViewHierarchy)],
+            @"createViewHierarchy is deprecated and will not be implemented. Use createUI"
+        );
+    }
+    return self;
+}
+
+- (bool)didResignActive
+{
+    return _didResignActive;
+}
+
+- (void)setWindow:(id)object        {}
+- (UIWindow*)window                 { return _window; }
+
+
+- (void)shouldAttachRenderDelegate  {}
+- (void)preStartUnity               {}
+
+- (BOOL)shouldUseMetalDisplayLink
+{
+    // if we start in batchmode (command line argument), we expect to never render to "backbuffer"
+    // metal display link does not make sense in this case
+    if (UnityIsBatchmode())
+        return NO;
+
+    // if we start in nographics mode, all rendering is ignored
+    // metal display link does not make sense in this case
+    if (![_unityView.layer isKindOfClass: [CAMetalLayer class]])
+        return NO;
+
+    // check if we want metal display link (player settings)
+    if (!UnityShouldUseMetalDisplayLink())
+        return NO;
+
+    // currently not supported on visionOS
+    #if PLATFORM_VISIONOS
+        return NO;
+    #endif
+
+    return YES;
+}
+
+- (void)startUnity
+{
+    NSAssert(self.engineLoadState < kUnityEngineLoadStateAppReady, @"[UnityAppController startUnity:] called after Unity has been initialized");
+
+    UnityInitApplicationGraphics();
+
+#if !PLATFORM_VISIONOS
+    // we make sure that first level gets correct display list and orientation
+    [[DisplayManager Instance] prepareForFirstScene];
+#endif
+
+#if PLATFORM_VISIONOS && UNITY_HAS_VISIONOSSDK_2_0
+    // https://developer.apple.com/documentation/visionos-release-notes/visionos-2-release-notes
+    // Game controllers can be used to interact with system UI on visionOS.
+    // Apps built with the visionOS 2 SDK that use the Game Controller
+    // framework for input in one or more of their views must add an instance
+    // of GCEventInteraction to those views (UIKit) or apply a
+    // handlesGameControllerEvents(matching: .gamepad) modifier to those views (SwiftUI).
+    GCEventInteraction* gamepadInteraction = [[GCEventInteraction alloc] init];
+    gamepadInteraction.handledEventTypes = GCUIEventTypeGamepad;
+    NSMutableArray* interactions = [NSMutableArray array];
+    [interactions addObject:gamepadInteraction];
+    [interactions addObjectsFromArray:_rootView.interactions];
+    _rootView.interactions = interactions;
+#endif
+
+    UnityLoadApplication();
+    Profiler_InitProfiler();
+
+    [self createDisplayLink];
+    [self showGameUI];
+
+    UnitySetPlayerFocus(1);
+
+    AVAudioSession* audioSession = [AVAudioSession sharedInstance];
+    // If Unity audio is disabled, we set the category to ambient to make sure we don't mute other app's audio. We set the audio session
+    // to active so we can get outputVolume callbacks. If Unity audio is enabled, FMOD should have already handled all of this AVAudioSession init.
+    if (!UnityIsAudioManagerAvailableAndEnabled())
+    {
+        [audioSession setCategory: AVAudioSessionCategoryAmbient error: nil];
+        [audioSession setActive: YES error: nil];
+    }
+    [audioSession addObserver: self forKeyPath: @"outputVolume" options: 0 context: nil];
+    UnityUpdateMuteState([audioSession outputVolume] < 0.01f ? 1 : 0);
+
+    [self subscribeToThermalChanges];
+#if UNITY_REPLAY_KIT_AVAILABLE
+    void InitUnityReplayKit();  // Classes/Unity/UnityReplayKit.mm
+
+    InitUnityReplayKit();
+#endif
+}
+
+UNITY_EXPORT extern "C" void UnityDestroyDisplayLink()
+{
+    [GetAppController() destroyDisplayLink];
+}
+
+UNITY_EXPORT extern "C" void UnityEngineDidQuit(unsigned level)
+{
+    enum class UnityEngineQuitLevel : unsigned
+    {
+        Unload = 1,
+        AppQuit = 2,
+    };
+
+    if (level > static_cast<unsigned>(UnityEngineQuitLevel::AppQuit))
+        return;
+
+    switch (static_cast<UnityEngineQuitLevel>(level))
+    {
+        case UnityEngineQuitLevel::Unload:
+            [GetAppController() downgradeEngineLoadState: kUnityEngineLoadStateRenderingInitialized];
+            [NSNotificationCenter.defaultCenter postNotificationName: kUnityDidUnload object: nil];
+            break;
+        case UnityEngineQuitLevel::AppQuit:
+            [GetAppController() downgradeEngineLoadState: kUnityEngineLoadStateNotStarted];
+            [NSNotificationCenter.defaultCenter postNotificationName: kUnityDidQuit object: nil];
+            _didResignActive = true;
+            if (GetAppController().quitHandler)
+                GetAppController().quitHandler();
+            else
+                exit(0);
+            break;
+    }
+}
+
+extern void SensorsCleanup();
+UNITY_EXPORT extern "C" void UnityCleanupTrampoline()
+{
+    // Prevent multiple cleanups
+    if (_UnityAppController == nil)
+        return;
+
+    // Unity view and viewController will not necessary be destroyed right after this function execution.
+    // We need to ensure that these objects will not receive any callbacks from system during that time.
+    _UnityAppController.window.rootViewController = nil;
+#if PLATFORM_IOS || PLATFORM_VISIONOS
+    // Stop GCMouse callbacks before detaching: the view can outlive cleanup in UaaL.
+    [_UnityAppController.unityView teardownIndirectMouseInput];
+#endif
+    [_UnityAppController.unityView removeFromSuperview];
+
+    [KeyboardDelegate Destroy];
+
+    SensorsCleanup();
+
+    Profiler_UninitProfiler();
+
+#if !PLATFORM_VISIONOS
+    [DisplayManager Destroy];
+#endif
+
+    // there are two ways we can end up here:
+    // 1. normal shutdown sequence: let's be fair, in this case ios will just (cleanly) kills everything so we don't care that much
+    // 2. unity unload (UaaL): in this case, run loop continues to exist.
+    //      Alas on some device/ios-versions, if we invalidate/destroy (metal) display link here, it gets a crash later on
+    //      referencing null pointer in displaylink dispatcher
+    // so we take the safest route: we just pause display link here. Note that we *never* run unity again after this point
+    _UnityAppController.unityDisplayLink.paused = YES;
+#if UNITY_USES_METAL_DISPLAY_LINK
+    if (@available(iOS 17.0, tvOS 17.0, *))
+        _UnityAppController.unityMetalDisplayLink.paused = YES;
+#endif
+
+    _UnityAppController = nil;
+}
+
+#if UNITY_SUPPORT_ROTATION
+
+- (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
+{
+    // No rootViewController is set because we are switching from one view controller to another, all orientations should be enabled
+    if ([window rootViewController] == nil)
+        return UIInterfaceOrientationMaskAll;
+
+    // During splash screen show phase no forced orientations should be allowed.
+    // This will prevent unwanted rotation while splash screen is on and application is not yet ready to present (Ex. Fogbugz cases: 1190428, 1269547).
+    if (self.engineLoadState < kUnityEngineLoadStateAppReady)
+        return [_rootController supportedInterfaceOrientations];
+
+    // Some presentation controllers (e.g. UIImagePickerController) require portrait orientation and will throw exception if it is not supported.
+    // At the same time enabling all orientations by returning UIInterfaceOrientationMaskAll might cause unwanted orientation change
+    // (e.g. when using UIActivityViewController to "share to" another application, iOS will use supportedInterfaceOrientations to possibly reorient).
+    // So to avoid exception we are returning combination of constraints for root view controller and orientation requested by iOS.
+    // _forceInterfaceOrientationMask is updated in willChangeStatusBarOrientation, which is called if some presentation controller insists on orientation change.
+    return [[window rootViewController] supportedInterfaceOrientations] | _forceInterfaceOrientationMask;
+}
+
+- (void)application:(UIApplication*)application willChangeStatusBarOrientation:(UIInterfaceOrientation)newStatusBarOrientation duration:(NSTimeInterval)duration
+{
+    // Setting orientation mask which is requested by iOS: see supportedInterfaceOrientationsForWindow above for details
+    _forceInterfaceOrientationMask = 1 << newStatusBarOrientation;
+}
+
+#endif
+
+#if UNITY_USES_REMOTE_NOTIFICATIONS
+
+- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
+{
+    AppController_SendNotificationWithArg(kUnityDidRegisterForRemoteNotificationsWithDeviceToken, deviceToken);
+}
+
+#if !PLATFORM_TVOS
+- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
+{
+    AppController_SendNotificationWithArg(kUnityDidReceiveRemoteNotification, userInfo);
+
+    if (handler)
+    {
+        handler(UIBackgroundFetchResultNoData);
+    }
+}
+
+#endif
+
+- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
+{
+    AppController_SendNotificationWithArg(kUnityDidFailToRegisterForRemoteNotificationsWithError, error);
+
+    // alas people do not check remote notification error through api (which is clunky, i agree) so log here to have at least some visibility
+    ::printf("\nFailed to register for remote notifications:\n%s\n\n", [[error localizedDescription] UTF8String]);
+}
+
+#endif
+
+// UIApplicationOpenURLOptionsKey was added only in ios10 sdk, while we still support ios9 sdk
+- (BOOL)application:(UIApplication*)app openURL:(NSURL*)url options:(NSDictionary<NSString*, id>*)options
+{
+    id sourceApplication = options[UIApplicationOpenURLOptionsSourceApplicationKey], annotation = options[UIApplicationOpenURLOptionsAnnotationKey];
+
+    NSMutableDictionary<NSString*, id>* notifData = [NSMutableDictionary dictionaryWithCapacity: 3];
+    if (url)
+    {
+        notifData[@"url"] = url;
+        UnitySetAbsoluteURL(url.absoluteString.UTF8String);
+    }
+    if (sourceApplication) notifData[@"sourceApplication"] = sourceApplication;
+    if (annotation) notifData[@"annotation"] = annotation;
+
+    AppController_SendNotificationWithArg(kUnityOnOpenURL, notifData);
+    return YES;
+}
+
+- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring> > * _Nullable restorableObjects))restorationHandler
+{
+    NSURL* url = userActivity.webpageURL;
+    if (url)
+        UnitySetAbsoluteURL(url.absoluteString.UTF8String);
+    return YES;
+}
+
+- (BOOL)application:(UIApplication*)application willFinishLaunchingWithOptions:(NSDictionary*)launchOptions
+{
+    AppController_SendNotificationWithArg(kUnityWillFinishLaunchingWithOptions, launchOptions);
+    NSURL* url = [self extractURLFromLaunchOptions: launchOptions];
+    if (url != nil)
+    {
+        [self initUnityApplicationNoGraphics];
+        UnitySetAbsoluteURL(url.absoluteString.UTF8String);
+    }
+    return YES;
+}
+
+// Helper method to extract URL from launch options
+- (NSURL*)extractURLFromLaunchOptions:(NSDictionary*)launchOptions
+{
+    // Check for the direct launch URL
+    NSURL* url = launchOptions[UIApplicationLaunchOptionsURLKey];
+    if (url != nil)
+    {
+        return url;
+    }
+
+    // Check for the user activity dictionary and URL from user activity
+    NSUserActivity* userActivity = launchOptions[UIApplicationLaunchOptionsUserActivityDictionaryKey][@"UIApplicationLaunchOptionsUserActivityKey"];
+    if (userActivity != nil && [userActivity.activityType isEqualToString: NSUserActivityTypeBrowsingWeb])
+    {
+        url = userActivity.webpageURL;
+        if (url != nil)
+        {
+            return url;
+        }
+    }
+
+    return nil;
+}
+
+- (UIWindowScene*)pickStartupWindowScene:(NSSet<UIScene*>*)scenes
+{
+    // if we have scene with UISceneActivationStateForegroundActive - pick it
+    // otherwise UISceneActivationStateForegroundInactive will work
+    //   it will be the scene going into active state
+    // if there were no active/inactive scenes (only background) we should allow background scene
+    //   this might happen in some cases with native plugins doing "things"
+    UIWindowScene *foregroundScene = nil, *backgroundScene = nil;
+    for (UIScene* scene in scenes)
+    {
+        if (![scene isKindOfClass: [UIWindowScene class]])
+            continue;
+        UIWindowScene* windowScene = (UIWindowScene*)scene;
+
+        if (scene.activationState == UISceneActivationStateForegroundActive)
+            return windowScene;
+        if (scene.activationState == UISceneActivationStateForegroundInactive)
+            foregroundScene = windowScene;
+        else if (scene.activationState == UISceneActivationStateBackground)
+            backgroundScene = windowScene;
+    }
+
+    return foregroundScene ? foregroundScene : backgroundScene;
+}
+
+- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
+{
+    ::printf("-> applicationDidFinishLaunching()\n");
+
+    // make sure orientation notifications are sent
+#if !PLATFORM_TVOS && !PLATFORM_VISIONOS
+    if ([UIDevice currentDevice].generatesDeviceOrientationNotifications == NO)
+        [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
+#endif
+
+    return YES;
+}
+
+- (void)initUnityApplicationNoGraphics
+{
+    if ([self advanceEngineLoadState: kUnityEngineLoadStateMinimal])
+        UnityInitApplicationNoGraphics(UnityDataBundleDir());
+}
+
+- (void)initUnityWithScene:(UIWindowScene*)scene
+{
+    if (self.engineLoadState >= kUnityEngineLoadStateCoreInitialized)
+        return;
+    // basic unity init
+    [self initUnityApplicationNoGraphics];
+    // initUnityApplicationNoGraphics progresses the state & does initialization if necessary
+    // so the next state bump has to be after it to not skip the init part
+    [self advanceEngineLoadState: kUnityEngineLoadStateCoreInitialized];
+
+    // we want to initialize DisplayManager first, since unity view might need it on creation
+    [DisplayManager Initialize];
+
+    // init main window
+    if (scene == nil)
+        _window = [[UIWindow alloc] init];
+    else
+        _window = [[UIWindow alloc] initWithWindowScene: scene];
+
+    // init unity view
+    [self selectRenderingAPI];
+    [UnityRenderingView InitializeForAPI: self.renderingAPI];
+    _unityView = [self createUnityView];
+
+    // connect main display with window and unity view
+    _mainDisplay = [DisplayManager Instance].mainDisplay;
+    [_mainDisplay createWithWindow: _window andView: _unityView];
+
+    // create UI hierarchy, and proceed with unity graphics init
+    [self createUI];
+    [self preStartUnity];
+
+    // if you wont use keyboard you may comment it out at save some memory
+    [KeyboardDelegate Initialize];
+
+#if UNITY_DEVELOPER_BUILD && !PLATFORM_VISIONOS
+    // Causes a black screen after splash screen, but would deadlock if waiting for manged debugger otherwise
+    [self performSelector: @selector(startUnity) withObject: nil afterDelay: 0];
+#else
+    [self startUnity];
+#endif
+}
+
+- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context
+{
+    if ([keyPath isEqual: @"outputVolume"])
+    {
+        UnityUpdateMuteState([[AVAudioSession sharedInstance] outputVolume] < 0.01f ? 1 : 0);
+    }
+}
+
+- (void)applicationDidEnterBackground:(UIApplication*)application
+{
+    ::printf("-> applicationDidEnterBackground()\n");
+
+    [self pauseDisplayLink];
+    UnityCancelTouches();
+
+#if PLATFORM_VISIONOS
+    if (UnityIsFocused())
+        UnitySetPlayerFocus(0);
+
+    if (!UnityShouldRunInBackground() && !UnityIsPaused())
+        UnityPause(1);
+#endif
+}
+
+- (void)applicationWillEnterForeground:(UIApplication*)application
+{
+    ::printf("-> applicationWillEnterForeground()\n");
+
+    [self unpauseDisplayLink];
+
+    // applicationWillEnterForeground: might sometimes arrive *before* actually initing unity (e.g. locking on startup)
+    if (self.engineLoadState >= kUnityEngineLoadStateAppReady)
+    {
+#if PLATFORM_VISIONOS
+        if (!UnityIsFocused())
+            UnitySetPlayerFocus(1);
+
+        if (UnityIsPaused() && _wasPausedExternal == false)
+            UnityPause(0);
+#endif
+
+        // if we were showing video before going to background - the view size may be changed while we are in background
+        [GetAppController().unityView recreateRenderingSurfaceIfNeeded];
+    }
+}
+
+- (void)applicationDidBecomeActive:(UIApplication*)application
+{
+    ::printf("-> applicationDidBecomeActive()\n");
+
+    [self removeSnapshotViewController];
+
+    if (self.engineLoadState >= kUnityEngineLoadStateAppReady)
+    {
+        // Pause/unpause is handled by repaint if CompositorLayer is in use
+        if (self.usingCompositorLayer == NO && UnityIsPaused() && _wasPausedExternal == false)
+        {
+            UnityWillResume();
+            UnityPause(0);
+        }
+        if (_wasPausedExternal)
+        {
+            if (UnityIsFullScreenPlaying())
+                TryResumeFullScreenVideo();
+        }
+        // need to do this with delay because FMOD restarts audio in AVAudioSessionInterruptionNotification handler
+        [self performSelector: @selector(updateUnityAudioOutput) withObject: nil afterDelay: 0.1];
+
+        // In case we got to applicationWillEnterForeground before Unity was initialized (or any other edge case)
+        if (!UnityIsFocused())
+            UnitySetPlayerFocus(1);
+    }
+    else
+    {
+        UIWindowScene *scene = [self pickStartupWindowScene:application.connectedScenes];
+        [self initUnityWithScene: scene];
+    }
+
+    _didResignActive = false;
+}
+
+- (void)updateUnityAudioOutput
+{
+    UnityUpdateMuteState([[AVAudioSession sharedInstance] outputVolume] < 0.01f ? 1 : 0);
+}
+
+- (void)addSnapshotViewController
+{
+    if (!_didResignActive || self->_snapshotViewController)
+    {
+        return;
+    }
+
+    UIView* snapshotView = [self createSnapshotView];
+
+    if (snapshotView != nil)
+    {
+        UIViewController* snapshotViewController = [AllocUnityViewController() init];
+        snapshotViewController.modalPresentationStyle = UIModalPresentationFullScreen;
+        snapshotViewController.view = snapshotView;
+
+        [self->_rootController presentViewController: snapshotViewController animated: false completion: nil];
+        self->_snapshotViewController = snapshotViewController;
+    }
+}
+
+- (void)removeSnapshotViewController
+{
+    // do this on the main queue async so that if we try to create one
+    // and remove in the same frame, this always happens after in the same queue
+    dispatch_async(dispatch_get_main_queue(), ^{
+        if (self->_snapshotViewController)
+        {
+            // we've got a view on top of the snapshot view (3rd party plugin/social media login etc).
+            if (self->_snapshotViewController.presentedViewController)
+            {
+                [self performSelector: @selector(removeSnapshotViewController) withObject: nil afterDelay: 0.05];
+                return;
+            }
+
+            [self->_snapshotViewController dismissViewControllerAnimated: NO completion: nil];
+            self->_snapshotViewController = nil;
+
+            // Make sure that the keyboard input field regains focus after the application becomes active.
+            [[KeyboardDelegate Instance] becomeFirstResponder];
+        }
+    });
+}
+
+- (void)applicationWillResignActive:(UIApplication*)application
+{
+    ::printf("-> applicationWillResignActive()\n");
+
+    if (self.engineLoadState >= kUnityEngineLoadStateAppReady)
+    {
+        // This should be covered by applicationDidEnterBackground but double-check just in case we missed it
+        if (UnityIsFocused())
+            UnitySetPlayerFocus(0);
+
+        // signal unity that the frame rendering have ended
+        // as we will not get the callback from the display link current frame
+        UnityDisplayLinkCallback(0);
+
+        _wasPausedExternal = UnityIsPaused();
+        // Pause/unpause is handled by repaint if CompositorLayer is in use
+        if (self.usingCompositorLayer == NO && _wasPausedExternal == false)
+        {
+            // Pause Unity only if we don't need special background processing
+            // otherwise batched player loop can be called to run user scripts.
+            if (!UnityGetUseCustomAppBackgroundBehavior())
+            {
+#if UNITY_SNAPSHOT_VIEW_ON_APPLICATION_PAUSE
+                // we cannot repaint without drawable given to us by CAMetalDisplayLink
+                // TODO: there should be a way to handle this somehow
+                if(!self.unityUsesMetalDisplayLink)
+                {
+                    // Force player to do one more frame, so scripts get a chance to render custom screen for minimized app in task manager.
+                    // NB: UnityWillPause will schedule OnApplicationPause message, which will be sent normally inside repaint (unity player loop)
+                    // NB: We will actually pause after the loop (when calling UnityPause).
+                    UnityWillPause();
+                    [self repaint];
+                    [self addSnapshotViewController];
+                }
+#endif
+
+#if PLATFORM_VISIONOS
+                if (!UnityShouldRunInBackground())
+                    UnityPause(1);
+#else
+                UnityPause(1);
+#endif
+            }
+        }
+    }
+
+    _didResignActive = true;
+}
+
+- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application
+{
+    UnityLowMemory();
+}
+
+- (void)applicationWillTerminate:(UIApplication*)application
+{
+    ::printf("-> applicationWillTerminate()\n");
+
+    // Only clean up if Unity has finished initializing, else the clean up process will crash,
+    // this happens if the app is force closed immediately after opening it.
+    if (self.engineLoadState >= kUnityEngineLoadStateAppReady)
+    {
+        // make sure that we are in a "unity cannot be touched" state
+        // if there was some complex UI shown when terminating, we can get extra UI calls from iOS after applicationWillTerminate:
+        // and we want to make sure we never do anything touching unity runtime at this point
+        _engineLoadState = kUnityEngineLoadStateMinimal;
+
+        // keep "old" way of tracking state synced
+        _unityAppReady = _renderingInited = _unityEngineInitialized = false;
+        _didResignActive = true;
+
+        UnityCleanup();
+        UnityCleanupTrampoline();
+    }
+}
+
+- (void)application:(UIApplication*)application handleEventsForBackgroundURLSession:(nonnull NSString *)identifier completionHandler:(nonnull void (^)())completionHandler
+{
+    NSDictionary* arg = @{identifier: completionHandler};
+    AppController_SendNotificationWithArg(kUnityHandleEventsForBackgroundURLSession, arg);
+}
+
+// advance the load state to newState, if it's not there or higher yet
+// returns YES if state was less than newState
+// returns NO if previous state was already the requested one or even higher than that
+- (BOOL)advanceEngineLoadState:(UnityEngineLoadState)newState
+{
+    if (_engineLoadState >= newState)
+        return NO;
+    _engineLoadState = newState;
+
+    // Old individual variables; fall-through because higher level also has to set all lower ones
+    switch (_engineLoadState)
+    {
+        case kUnityEngineLoadStateAppReady:
+            _unityAppReady = true;
+        case kUnityEngineLoadStateRenderingInitialized:
+            _renderingInited = true;
+        case kUnityEngineLoadStateCoreInitialized:
+            _unityEngineInitialized = true;
+        case kUnityEngineLoadStateMinimal:
+            _unityEngineLoaded = true;
+        case kUnityEngineLoadStateNotStarted:
+            break;
+    }
+
+    return YES;
+}
+
+// the opposite of advanceEngineLoadState:
+- (BOOL)downgradeEngineLoadState:(UnityEngineLoadState)newState
+{
+    if (newState >= _engineLoadState)
+        return NO;
+    _engineLoadState = newState;
+
+    switch (_engineLoadState)
+    {
+        case kUnityEngineLoadStateNotStarted:
+            _unityEngineLoaded = false;
+        case kUnityEngineLoadStateMinimal:
+            _unityEngineInitialized = false;
+        case kUnityEngineLoadStateCoreInitialized:
+            _renderingInited = false;
+        case kUnityEngineLoadStateRenderingInitialized:
+            _unityAppReady = false;
+        case kUnityEngineLoadStateAppReady:
+            break;
+    }
+
+    return YES;
+}
+
+@end
+
+
+void AppController_SendNotification(NSString* name)
+{
+    [[NSNotificationCenter defaultCenter] postNotificationName: name object: GetAppController()];
+}
+
+void AppController_SendNotificationWithArg(NSString* name, id arg)
+{
+    [[NSNotificationCenter defaultCenter] postNotificationName: name object: GetAppController() userInfo: arg];
+}
+
+void AppController_SendUnityViewControllerNotification(NSString* name)
+{
+    [[NSNotificationCenter defaultCenter] postNotificationName: name object: UnityGetGLViewController()];
+}
+
+UNITY_EXPORT extern "C" UIWindow*            UnityGetMainWindow()        { return GetAppController().mainDisplay.window; }
+UNITY_EXPORT extern "C" UIViewController*    UnityGetGLViewController()  { return GetAppController().rootViewController; }
+UNITY_EXPORT extern "C" UnityView*           UnityGetUnityView()         { return GetAppController().unityView; }
+UNITY_EXPORT extern "C" UIView*              UnityGetGLView()            { return UnityGetUnityView(); }
+
+
+UNITY_EXPORT extern "C" ScreenOrientation    UnityCurrentOrientation()   { return GetAppController().unityView.contentOrientation; }
+
+
+bool LogToNSLogHandler(LogType logType, const char* log, va_list list)
+{
+    NSString *formatString = [NSString stringWithUTF8String:log];
+    NSString *formatted = [[NSString alloc] initWithFormat:formatString arguments:list];
+
+    os_log_with_type(OS_LOG_DEFAULT, OS_LOG_TYPE_DEFAULT, "%{public}@", formatted);
+    return true;
+}
+
+static void AddNewAPIImplIfNeeded();
+
+// From https://stackoverflow.com/questions/4744826/detecting-if-ios-app-is-run-in-debugger
+static bool isDebuggerAttachedToConsole(void)
+// Returns true if the current process is being debugged (either
+// running under the debugger or has a debugger attached post facto).
+{
+    int                 junk;
+    int                 mib[4];
+    struct kinfo_proc   info;
+    size_t              size;
+
+    // Initialize the flags so that, if sysctl fails for some bizarre
+    // reason, we get a predictable result.
+
+    info.kp_proc.p_flag = 0;
+
+    // Initialize mib, which tells sysctl the info we want, in this case
+    // we're looking for information about a specific process ID.
+
+    mib[0] = CTL_KERN;
+    mib[1] = KERN_PROC;
+    mib[2] = KERN_PROC_PID;
+    mib[3] = getpid();
+
+    // Call sysctl.
+
+    size = sizeof(info);
+    junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
+    assert(junk == 0);
+
+    // We're being debugged if the P_TRACED flag is set.
+    // But if we are starting app on device (and make debugger wait and attach after start)
+    //   it will NOT connect stout (only stderr, used by nslog)
+    // Hence we also check that stoud is rerouted
+    return ((info.kp_proc.p_flag & P_TRACED) != 0) && isatty(STDOUT_FILENO);
+}
+
+void UnityInitTrampoline()
+{
+    InitCrashHandling();
+
+    NSString* version = [[UIDevice currentDevice] systemVersion];
+    const char* versionStr = version.UTF8String;
+    char* dot = NULL;
+    UInt32 major = (UInt32)std::strtoul(versionStr, &dot, 10);
+    UInt32 minor = 0;
+    if (major > 0 && *dot == '.')
+        minor = (UInt32)std::strtoul(++dot, NULL, 10);
+    _iosMajorVersion = major;
+    _iosMinorVersion = minor;
+
+#define CHECK_VER(s) [version compare: s options: NSNumericSearch] != NSOrderedAscending
+    _ios140orNewer = CHECK_VER(@"14.0"); _ios150orNewer = CHECK_VER(@"15.0");
+    _ios160orNewer = CHECK_VER(@"16.0");
+#undef CHECK_VER
+
+    AddNewAPIImplIfNeeded();
+
+#if !TARGET_OS_SIMULATOR
+    // Use NSLog logging if a debugger is not attached, otherwise we write to stdout.
+    if (!isDebuggerAttachedToConsole())
+        UnitySetLogEntryHandler(LogToNSLogHandler);
+#endif
+}
+
+extern "C" bool UnityiOS81orNewer() { return _ios81orNewer; }
+extern "C" bool UnityiOS82orNewer() { return _ios82orNewer; }
+extern "C" bool UnityiOS90orNewer() { return _ios90orNewer; }
+extern "C" bool UnityiOS91orNewer() { return _ios91orNewer; }
+extern "C" bool UnityiOS100orNewer() { return _ios100orNewer; }
+extern "C" bool UnityiOS101orNewer() { return _ios101orNewer; }
+extern "C" bool UnityiOS102orNewer() { return _ios102orNewer; }
+extern "C" bool UnityiOS103orNewer() { return _ios103orNewer; }
+extern "C" bool UnityiOS110orNewer() { return _ios110orNewer; }
+extern "C" bool UnityiOS111orNewer() { return _ios111orNewer; }
+extern "C" bool UnityiOS112orNewer() { return _ios112orNewer; }
+extern "C" bool UnityiOS130orNewer() { return _ios130orNewer; }
+extern "C" bool UnityiOS140orNewer() { return _ios140orNewer; }
+extern "C" bool UnityiOS150orNewer() { return _ios150orNewer; }
+extern "C" bool UnityiOS160orNewer() { return _ios160orNewer; }
+UNITY_EXPORT extern "C" bool UnityiOSVersionIsAtLeast(uint32_t major, uint32_t minor)
+{
+    if (major < _iosMajorVersion)
+        return true;
+    if (major > _iosMajorVersion)
+        return false;
+    return minor <= _iosMinorVersion;
+}
+
+// sometimes apple adds new api with obvious fallback on older ios.
+// in that case we simply add these functions ourselves to simplify code
+static void AddNewAPIImplIfNeeded()
+{
+#if !PLATFORM_VISIONOS
+    if (![[UIScreen class] instancesRespondToSelector: @selector(maximumFramesPerSecond)])
+    {
+        IMP UIScreen_MaximumFramesPerSecond_IMP = imp_implementationWithBlock(^NSInteger(id _self) {
+            return 60;
+        });
+        class_replaceMethod([UIScreen class], @selector(maximumFramesPerSecond), UIScreen_MaximumFramesPerSecond_IMP, UIScreen_maximumFramesPerSecond_Enc);
+    }
+
+    if (![[UIView class] instancesRespondToSelector: @selector(safeAreaInsets)])
+    {
+        IMP UIView_SafeAreaInsets_IMP = imp_implementationWithBlock(^UIEdgeInsets(id _self) {
+            return UIEdgeInsetsZero;
+        });
+        class_replaceMethod([UIView class], @selector(safeAreaInsets), UIView_SafeAreaInsets_IMP, UIView_safeAreaInsets_Enc);
+    }
+#endif
+}

+ 53 - 0
unity_ios/Classes/UnityTrampolineConfigure.h

@@ -0,0 +1,53 @@
+#pragma once
+
+// use this macro to encode unity version into an integer
+// numbers generated this way can be compared numerically to check which version is newer/older
+#define MAKE_UNITY_VERSION(ver, maj, min) ((ver)*10000 + (maj)*100 + (min))
+
+#if !defined(UNITY_VERSION_VER) || !defined(UNITY_VERSION_MAJ) || !defined(UNITY_VERSION_MIN)
+    #error "UNITY_VERSION_VER, UNITY_VERSION_MAJ, UNITY_VERSION_MIN must be set in xcode project, something went wrong"
+#endif
+
+#define UNITY_VERSION MAKE_UNITY_VERSION(UNITY_VERSION_VER, UNITY_VERSION_MAJ, UNITY_VERSION_MIN)
+
+
+//  * Before, we were having UNITY_X_Y_Z defines (we keep old ones present to not break old projects)
+//  * Alas it had several issues:
+//  *   we were using one digit for major/minor version, meaning that
+//  *     UNITY_2019_3_13 = 2019313 was larger than UNITY_2020_2_0 = 202020
+//  *   we were never forward porting minor version changes, so UNITY_2019_3_13 was not present in 2020
+//  *     what is worse: UNITY_2019_3_13 would be absent in 2019.3.14
+//  *
+//  * We keep old defines around for backwards compatibility but we are forced to break direct numerical comparison
+
+#define UNITY_4_2_0     MAKE_UNITY_VERSION(4,2,0)
+#define UNITY_4_2_1     MAKE_UNITY_VERSION(4,2,1)
+#define UNITY_4_2_2     MAKE_UNITY_VERSION(4,2,2)
+#define UNITY_4_3_0     MAKE_UNITY_VERSION(4,3,0)
+#define UNITY_4_3_1     MAKE_UNITY_VERSION(4,3,1)
+#define UNITY_4_3_2     MAKE_UNITY_VERSION(4,3,2)
+#define UNITY_4_3_3     MAKE_UNITY_VERSION(4,3,3)
+#define UNITY_4_3_4     MAKE_UNITY_VERSION(4,3,4)
+#define UNITY_4_5_0     MAKE_UNITY_VERSION(4,5,0)
+#define UNITY_4_5_1     MAKE_UNITY_VERSION(4,5,1)
+#define UNITY_4_5_2     MAKE_UNITY_VERSION(4,5,2)
+#define UNITY_4_5_3     MAKE_UNITY_VERSION(4,5,3)
+#define UNITY_4_6_0     MAKE_UNITY_VERSION(4,6,0)
+#define UNITY_5_0_0     MAKE_UNITY_VERSION(5,0,0)
+#define UNITY_5_1_0     MAKE_UNITY_VERSION(5,1,0)
+#define UNITY_5_2_0     MAKE_UNITY_VERSION(5,2,0)
+#define UNITY_5_3_0     MAKE_UNITY_VERSION(5,3,0)
+#define UNITY_5_4_0     MAKE_UNITY_VERSION(5,4,0)
+#define UNITY_5_5_0     MAKE_UNITY_VERSION(5,5,0)
+#define UNITY_5_6_0     MAKE_UNITY_VERSION(5,6,0)
+#define UNITY_2017_1_0  MAKE_UNITY_VERSION(2017,1,0)
+#define UNITY_2017_2_0  MAKE_UNITY_VERSION(2017,2,0)
+#define UNITY_2017_3_0  MAKE_UNITY_VERSION(2017,3,0)
+#define UNITY_2018_1_0  MAKE_UNITY_VERSION(2018,1,0)
+#define UNITY_2018_2_0  MAKE_UNITY_VERSION(2018,2,0)
+#define UNITY_2018_3_0  MAKE_UNITY_VERSION(2018,3,0)
+#define UNITY_2019_1_0  MAKE_UNITY_VERSION(2019,1,0)
+#define UNITY_2019_2_0  MAKE_UNITY_VERSION(2019,2,0)
+#define UNITY_2019_3_0  MAKE_UNITY_VERSION(2019,3,0)
+#define UNITY_2020_1_0  MAKE_UNITY_VERSION(2020,1,0)
+#define UNITY_2020_2_0  MAKE_UNITY_VERSION(2020,2,0)

+ 40 - 0
unity_ios/Classes/Vector3.h

@@ -0,0 +1,40 @@
+#pragma once
+
+struct Vector3f
+{
+    float x, y, z;
+};
+
+inline float VecDotProduct(const Vector3f& v1, const Vector3f& v2)
+{
+    return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
+}
+
+inline float VecMagnitude(const Vector3f& v)
+{
+    return sqrtf(VecDotProduct(v, v));
+}
+
+inline Vector3f VecMake(float x, float y, float z)
+{
+    Vector3f v = {x, y, z};
+    return v;
+}
+
+inline Vector3f VecCrossProduct(const Vector3f& v1, const Vector3f& v2)
+{
+    return VecMake(
+        v1.y * v2.z - v1.z * v2.y,
+        v1.z * v2.x - v1.x * v2.z,
+        v1.x * v2.y - v1.y * v2.x);
+}
+
+inline Vector3f VecScale(float s, const Vector3f& v)
+{
+    return VecMake(s * v.x, s * v.y, s * v.z);
+}
+
+inline Vector3f VecNormalize(const Vector3f& v)
+{
+    return VecScale(1.0f / VecMagnitude(v), v);
+}

+ 34 - 0
unity_ios/Classes/iPhone_Sensors.h

@@ -0,0 +1,34 @@
+#pragma once
+
+enum LocationServiceStatus
+{
+    kLocationServiceStopped,
+    kLocationServiceInitializing,
+    kLocationServiceRunning,
+    kLocationServiceFailed
+};
+
+class LocationService
+{
+public:
+    static void SetDesiredAccuracy(float val);
+    static float GetDesiredAccuracy();
+    static void SetDistanceFilter(float val);
+    static float GetDistanceFilter();
+    static bool IsServiceEnabledByUser();
+    static void StartUpdatingLocation();
+    static void StopUpdatingLocation();
+    static void SetHeadingUpdatesEnabled(bool enabled);
+    static bool IsHeadingUpdatesEnabled();
+    static LocationServiceStatus GetLocationStatus();
+    static LocationServiceStatus GetHeadingStatus();
+    static bool IsHeadingAvailable();
+};
+
+#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
+void ReportSimulatedRemoteButtonPress(UIPressType type);
+void ReportSimulatedRemoteButtonRelease(UIPressType type);
+void ReportSimulatedRemoteTouchesBegan(UIView* view, NSSet* touches);
+void ReportSimulatedRemoteTouchesMoved(UIView* view, NSSet* touches);
+void ReportSimulatedRemoteTouchesEnded(UIView* view, NSSet* touches);
+#endif

+ 1168 - 0
unity_ios/Classes/iPhone_Sensors.mm

@@ -0,0 +1,1168 @@
+#define SIMULATE_ATTITUDE_FROM_GRAVITY 1
+
+#import "iPhone_Sensors.h"
+
+#if UNITY_USES_LOCATION
+#import <CoreLocation/CoreLocation.h>
+#endif
+
+#if !PLATFORM_TVOS
+#import <CoreMotion/CoreMotion.h>
+#endif
+#import <GameController/GameController.h>
+
+#include "OrientationSupport.h"
+#include "Unity/UnityInterface.h"
+
+#include "Vector3.h"
+#include "Quaternion4.h"
+
+extern "C" void il2cpp_init(void);
+__attribute__((retain)) void keepCallAgainstIL2CPP() {
+    // todo move to more propper location
+    // here just to ensures LD will 'see' il2cpp.a and export il2cpp symbols from UnityFramework binary
+    // keepCallAgainstIL2CPP wont be called
+    il2cpp_init();
+}
+typedef void (^ControllerPausedHandler)(GCController *controller);
+static NSArray* QueryControllerCollection();
+
+#if PLATFORM_TVOS
+static bool gTVRemoteTouchesEnabled = true;
+static bool gTVRemoteAllowRotationInitialValue = false;
+static bool gTVRemoteReportsAbsoluteDpadValuesInitialValue = false;
+static int gTVControllerUserInteractionEnabled = 0;
+#endif
+
+static bool gCompensateSensors = true;
+bool gEnableGyroscope = false;
+extern "C" void UnityEnableGyroscope(bool value) { gEnableGyroscope = value; }
+
+static bool gJoysticksInited = false;
+#define MAX_JOYSTICKS 4
+static bool gPausedJoysticks[MAX_JOYSTICKS] = {false, false, false, false};
+static id gGameControllerClass = nil;
+// This defines the number of maximum acceleration events Unity will queue internally for scripts to access.
+UNITY_EXPORT extern "C" int UnityMaxQueuedAccelerationEvents() { return 2 * 60; } // 120 events or 2 seconds at 60Hz reporting.
+
+static ControllerPausedHandler gControllerHandler = ^(GCController *controller)
+{
+    NSArray* list = QueryControllerCollection();
+    if (list != nil)
+    {
+        NSUInteger idx = [list indexOfObject: controller];
+        if (idx < MAX_JOYSTICKS)
+        {
+            gPausedJoysticks[idx] = !gPausedJoysticks[idx];
+        }
+    }
+};
+
+UNITY_EXPORT extern "C" bool IsCompensatingSensors() { return gCompensateSensors; }
+UNITY_EXPORT extern "C" void SetCompensatingSensors(bool val) { gCompensateSensors = val; }
+
+inline float UnityReorientHeading(float heading)
+{
+    if (IsCompensatingSensors())
+    {
+        float rotateBy = 0.f;
+        switch (UnityCurrentOrientation())
+        {
+            case portraitUpsideDown:
+                rotateBy = -180.f;
+                break;
+            case landscapeLeft:
+                rotateBy = -270.f;
+                break;
+            case landscapeRight:
+                rotateBy = -90.f;
+                break;
+            default:
+                break;
+        }
+
+        return fmodf((360.f + heading + rotateBy), 360.f);
+    }
+    else
+    {
+        return heading;
+    }
+}
+
+inline Vector3f UnityReorientVector3(float x, float y, float z)
+{
+    if (IsCompensatingSensors())
+    {
+        Vector3f res;
+        switch (UnityCurrentOrientation())
+        {
+            case portraitUpsideDown:
+            { res = (Vector3f) {-x, -y, z}; }
+            break;
+            case landscapeLeft:
+            { res = (Vector3f) {-y, x, z}; }
+            break;
+            case landscapeRight:
+            { res = (Vector3f) {y, -x, z}; }
+            break;
+            default:
+            { res = (Vector3f) {x, y, z}; }
+        }
+        return res;
+    }
+    else
+    {
+        return (Vector3f) {x, y, z};
+    }
+}
+
+inline Quaternion4f UnityReorientQuaternion(float x, float y, float z, float w)
+{
+    if (IsCompensatingSensors())
+    {
+        Quaternion4f res, inp = {x, y, z, w};
+        switch (UnityCurrentOrientation())
+        {
+            case landscapeLeft:
+                QuatMultiply(res, inp, gQuatRot[1]);
+                break;
+            case portraitUpsideDown:
+                QuatMultiply(res, inp, gQuatRot[2]);
+                break;
+            case landscapeRight:
+                QuatMultiply(res, inp, gQuatRot[3]);
+                break;
+            default:
+                res = inp;
+        }
+        return res;
+    }
+    else
+    {
+        return (Quaternion4f) {x, y, z, w};
+    }
+}
+
+#if PLATFORM_TVOS
+static bool sGCMotionForwardingEnabled = false;
+static bool sGCMotionForwardedForCurrentFrame = false;
+#else
+static CMMotionManager*     sMotionManager  = nil;
+static NSOperationQueue*    sMotionQueue    = nil;
+#endif
+
+// Current update interval or 0.0f if not initialized. This is returned
+// to the user as current update interval and this value is set to 0.0f when
+// gyroscope is disabled.
+static float sUpdateInterval = 0.0f;
+
+// Update interval set by the user. Core motion will be set-up to use
+// this update interval after disabling and re-enabling gyroscope
+// so users can set update interval, disable gyroscope, enable gyroscope and
+// after that gyroscope will be updated at this previously set interval.
+#if !PLATFORM_TVOS
+static float sUserUpdateInterval = 1.0f / 30.0f;
+#endif
+
+void SensorsCleanup()
+{
+#if !PLATFORM_TVOS
+    if (sMotionManager != nil)
+    {
+        [sMotionManager stopGyroUpdates];
+        [sMotionManager stopDeviceMotionUpdates];
+        [sMotionManager stopAccelerometerUpdates];
+        sMotionManager = nil;
+    }
+
+    sMotionQueue = nil;
+#endif
+}
+
+UNITY_EXPORT extern "C" void UnityCoreMotionStart()
+{
+#if PLATFORM_TVOS
+    sGCMotionForwardingEnabled = true;
+#else
+    if (sMotionQueue == nil)
+        sMotionQueue = [[NSOperationQueue alloc] init];
+
+    bool initMotionManager = (sMotionManager == nil);
+    if (initMotionManager)
+        sMotionManager = [[CMMotionManager alloc] init];
+
+    // iOS might get confused if we repeatedly enable gyroscope/motions
+    // so we take into account the current state
+
+    if (gEnableGyroscope && !sMotionManager.gyroActive && sMotionManager.gyroAvailable)
+    {
+        [sMotionManager startGyroUpdates];
+        [sMotionManager setGyroUpdateInterval: sUpdateInterval];
+    }
+
+    if (gEnableGyroscope && !sMotionManager.deviceMotionActive && sMotionManager.deviceMotionAvailable)
+    {
+        [sMotionManager startDeviceMotionUpdates];
+        [sMotionManager setDeviceMotionUpdateInterval: sUpdateInterval];
+    }
+
+    // we (ab)use UnityCoreMotionStart to both init sensors and restart gyro
+    // make sure we touch accelerometer only on init
+    if (initMotionManager && sMotionManager.accelerometerAvailable)
+    {
+        const int frequency = UnityGetAccelerometerFrequency();
+        if (frequency > 0)
+        {
+            sMotionManager.accelerometerUpdateInterval = 1.0f / frequency;
+            [sMotionManager startAccelerometerUpdates];
+        }
+    }
+#endif
+}
+
+UNITY_EXPORT extern "C" void UnityCoreMotionStop()
+{
+#if PLATFORM_TVOS
+    sGCMotionForwardingEnabled = false;
+#else
+    if (sMotionManager != nil)
+    {
+        [sMotionManager stopGyroUpdates];
+        [sMotionManager stopDeviceMotionUpdates];
+    }
+#endif
+}
+
+UNITY_EXPORT extern "C" void UnityUpdateAccelerometerData()
+{
+#if !PLATFORM_TVOS
+    if (sMotionManager)
+    {
+        CMAccelerometerData* data = sMotionManager.accelerometerData;
+        if (data != nil)
+        {
+            Vector3f res = UnityReorientVector3(data.acceleration.x, data.acceleration.y, data.acceleration.z);
+            UnityDidAccelerate(res.x, res.y, res.z, data.timestamp);
+        }
+    }
+#endif
+}
+
+UNITY_EXPORT extern "C" void UnitySetGyroUpdateInterval(int idx, float interval)
+{
+#if !PLATFORM_TVOS
+    static const float _MinUpdateInterval = 1.0f / 60.0f;
+    static const float _MaxUpdateInterval = 1.0f;
+
+    if (interval < _MinUpdateInterval)
+        interval = _MinUpdateInterval;
+    else if (interval > _MaxUpdateInterval)
+        interval = _MaxUpdateInterval;
+
+    sUserUpdateInterval = interval;
+
+    if (sMotionManager)
+    {
+        sUpdateInterval = interval;
+
+        [sMotionManager setGyroUpdateInterval: interval];
+        [sMotionManager setDeviceMotionUpdateInterval: interval];
+    }
+#endif
+}
+
+UNITY_EXPORT extern "C" float UnityGetGyroUpdateInterval(int idx)
+{
+    return sUpdateInterval;
+}
+
+UNITY_EXPORT extern "C" void UnityUpdateGyroData()
+{
+#if !PLATFORM_TVOS
+    CMRotationRate rotationRate = { 0.0, 0.0, 0.0 };
+    CMRotationRate rotationRateUnbiased = { 0.0, 0.0, 0.0 };
+    CMAcceleration userAcceleration = { 0.0, 0.0, 0.0 };
+    CMAcceleration gravity = { 0.0, 0.0, 0.0 };
+    CMQuaternion attitude = { 0.0, 0.0, 0.0, 1.0 };
+
+    if (sMotionManager != nil)
+    {
+        CMGyroData *gyroData = sMotionManager.gyroData;
+        CMDeviceMotion *motionData = sMotionManager.deviceMotion;
+
+        if (gyroData != nil)
+        {
+            rotationRate = gyroData.rotationRate;
+        }
+
+        if (motionData != nil)
+        {
+            CMAttitude *att = motionData.attitude;
+
+            attitude = att.quaternion;
+            rotationRateUnbiased = motionData.rotationRate;
+            userAcceleration = motionData.userAcceleration;
+            gravity = motionData.gravity;
+        }
+    }
+
+    Vector3f reorientedRotRate = UnityReorientVector3(rotationRate.x, rotationRate.y, rotationRate.z);
+    UnitySensorsSetGyroRotationRate(0, reorientedRotRate.x, reorientedRotRate.y, reorientedRotRate.z);
+
+    Vector3f reorientedRotRateUnbiased = UnityReorientVector3(rotationRateUnbiased.x, rotationRateUnbiased.y, rotationRateUnbiased.z);
+    UnitySensorsSetGyroRotationRateUnbiased(0, reorientedRotRateUnbiased.x, reorientedRotRateUnbiased.y, reorientedRotRateUnbiased.z);
+
+    Vector3f reorientedUserAcc = UnityReorientVector3(userAcceleration.x, userAcceleration.y, userAcceleration.z);
+    UnitySensorsSetUserAcceleration(0, reorientedUserAcc.x, reorientedUserAcc.y, reorientedUserAcc.z);
+
+    Vector3f reorientedG = UnityReorientVector3(gravity.x, gravity.y, gravity.z);
+    UnitySensorsSetGravity(0, reorientedG.x, reorientedG.y, reorientedG.z);
+
+    Quaternion4f reorientedAtt = UnityReorientQuaternion(attitude.x, attitude.y, attitude.z, attitude.w);
+    UnitySensorsSetAttitude(0, reorientedAtt.x, reorientedAtt.y, reorientedAtt.z, reorientedAtt.w);
+#endif
+}
+
+UNITY_EXPORT extern "C" int UnityIsGyroEnabled(int idx)
+{
+#if PLATFORM_TVOS
+    return sGCMotionForwardingEnabled;
+#else
+    if (sMotionManager == nil)
+        return 0;
+
+    return sMotionManager.gyroAvailable && sMotionManager.gyroActive;
+#endif
+}
+
+UNITY_EXPORT extern "C" int UnityIsGyroAvailable()
+{
+#if PLATFORM_TVOS
+    return true;
+#else
+    if (sMotionManager != nil)
+        return sMotionManager.gyroAvailable;
+#endif
+
+    return 0;
+}
+
+// -- Joystick stuff --
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wobjc-method-access"
+enum JoystickButtonNumbers
+{
+    BTN_PAUSE = 0,
+    BTN_DPAD_UP = 4,
+    BTN_DPAD_RIGHT = 5,
+    BTN_DPAD_DOWN = 6,
+    BTN_DPAD_LEFT = 7,
+    BTN_Y = 12,
+    BTN_B = 13,
+    BTN_A = 14,
+    BTN_X = 15,
+    BTN_L1 = 8,
+    BTN_L2 = 10,
+    BTN_R1 = 9,
+    BTN_R2 = 11,
+    BTN_MENU = 16,
+    BTN_L3 = 17,
+    BTN_R3 = 18,
+    BTN_COUNT
+};
+
+struct JoystickButtonState
+{
+    int buttonCode;
+    bool state;
+    bool lastRecordedState;
+
+    bool StateChanged() { return state ^ lastRecordedState; }
+    void ClearRecordedState() { lastRecordedState = false; }
+};
+
+JoystickButtonState gAggregatedJoystickState[BTN_COUNT];
+
+
+static float GetAxisValue(GCControllerAxisInput* axis)
+{
+    return axis.value;
+}
+
+static float GetButtonValue(GCControllerButtonInput* button)
+{
+    return button.value;
+}
+
+static BOOL GetButtonPressed(GCControllerButtonInput* button)
+{
+    return button.pressed;
+}
+
+UNITY_EXPORT extern "C" void UnityInitJoysticks()
+{
+    if (!gJoysticksInited)
+    {
+        NSBundle* bundle = [NSBundle bundleWithPath: @"/System/Library/Frameworks/GameController.framework"];
+        if (bundle)
+        {
+            [bundle load];
+            gGameControllerClass = NSClassFromString(@"GCController");
+
+            //Apply settings that could have been set by user scripts before controller initialization
+        #if PLATFORM_TVOS
+            UnitySetAppleTVRemoteAllowRotation(gTVRemoteAllowRotationInitialValue);
+            UnitySetAppleTVRemoteReportAbsoluteDpadValues(gTVRemoteReportsAbsoluteDpadValuesInitialValue);
+        #endif
+        }
+
+        for (int i = 0; i < BTN_COUNT; i++)
+        {
+            const int bufSize = 128;
+            char buf[bufSize];
+            snprintf(buf, bufSize, "joystick button %d", i);
+
+            gAggregatedJoystickState[i].buttonCode = UnityStringToKey(buf);
+            gAggregatedJoystickState[i].state = false;
+            gAggregatedJoystickState[i].lastRecordedState = false;
+        }
+
+        gJoysticksInited = true;
+    }
+}
+
+static NSArray* QueryControllerCollection()
+{
+    return gGameControllerClass != nil ? (NSArray*)[gGameControllerClass performSelector: @selector(controllers)] : nil;
+}
+
+static void HandleAggregatedJoystickState()
+{
+    for (int i = 0; i < BTN_COUNT; i++)
+    {
+        // Mirror button state to the aggregate controller 0.
+        if (gAggregatedJoystickState[i].StateChanged())
+        {
+            UnitySetKeyState(gAggregatedJoystickState[i].buttonCode, gAggregatedJoystickState[i].lastRecordedState);
+            gAggregatedJoystickState[i].state = gAggregatedJoystickState[i].lastRecordedState;
+        }
+
+        gAggregatedJoystickState[i].ClearRecordedState();
+    }
+}
+
+static void SetJoystickButtonState(int joyNum, int buttonNum, int state)
+{
+    const int bufSize = 128;
+    char buf[bufSize];
+    snprintf(buf, bufSize, "joystick %d button %d", joyNum, buttonNum);
+    UnitySetKeyState(UnityStringToKey(buf), state);
+    if (state && buttonNum < BTN_COUNT)
+    {
+        gAggregatedJoystickState[buttonNum].lastRecordedState = true;
+    }
+}
+
+static void ReportJoystickButton(int idx, JoystickButtonNumbers num, GCControllerButtonInput* button)
+{
+    SetJoystickButtonState(idx + 1, num, GetButtonPressed(button));
+    UnitySetJoystickPosition(idx + 1, num, GetButtonValue(button));
+}
+
+template<class ClassXYZ>
+static void ReportJoystickXYZAxes(int idx, int xaxis, int yaxis, int zaxis, const ClassXYZ& xyz)
+{
+    UnitySetJoystickPosition(idx + 1, xaxis, xyz.x);
+    UnitySetJoystickPosition(idx + 1, yaxis, xyz.y);
+    UnitySetJoystickPosition(idx + 1, zaxis, xyz.z);
+}
+
+template<class ClassXYZW>
+static void ReportJoystickXYZWAxes(int idx, int xaxis, int yaxis, int zaxis, int waxis,
+    const ClassXYZW& xyzw)
+{
+    UnitySetJoystickPosition(idx + 1, xaxis, xyzw.x);
+    UnitySetJoystickPosition(idx + 1, yaxis, xyzw.y);
+    UnitySetJoystickPosition(idx + 1, zaxis, xyzw.z);
+    UnitySetJoystickPosition(idx + 1, waxis, xyzw.w);
+}
+
+static GCControllerDirectionPad* GetCardinalDPad(GCMicroGamepad* gamepad)
+{
+    if (![gamepad respondsToSelector: @selector(dpadsbling)])
+        return nil;
+
+    NSDictionary<NSString *, GCDeviceDirectionPad *> *dpads = [gamepad performSelector: @selector(dpadsbling)];
+    return [dpads valueForKey: @"Cardinal Direction Pad"];
+}
+
+static GCControllerButtonInput* SelectPreferedButton(GCControllerButtonInput* prefered, GCControllerButtonInput* alternative)
+{
+    if (prefered.isPressed)
+        return prefered;
+
+    return alternative;
+}
+
+static void ReportJoystickMicro(int idx, GCMicroGamepad* gamepad)
+{
+    GCControllerDirectionPad* dpad = [gamepad dpad];
+    GCControllerDirectionPad* cardinalDpad;
+
+#if PLATFORM_TVOS
+    cardinalDpad = [[gamepad dpads] valueForKey: GCInputDirectionalCardinalDpad];
+#endif
+
+    UnitySetJoystickPosition(idx + 1, 0, GetAxisValue([dpad xAxis]));
+    UnitySetJoystickPosition(idx + 1, 1, -GetAxisValue([dpad yAxis]));
+
+    ReportJoystickButton(idx, BTN_DPAD_UP, SelectPreferedButton([dpad up], [cardinalDpad up]));
+    ReportJoystickButton(idx, BTN_DPAD_RIGHT, SelectPreferedButton([dpad right], [cardinalDpad right]));
+    ReportJoystickButton(idx, BTN_DPAD_DOWN, SelectPreferedButton([dpad down], [cardinalDpad down]));
+    ReportJoystickButton(idx, BTN_DPAD_LEFT, SelectPreferedButton([dpad left], [cardinalDpad left]));
+
+    bool isDirectionalButtonPressed = false;
+#if PLATFORM_TVOS
+    if (cardinalDpad)
+    {
+        ReportJoystickButton(idx, BTN_A, [[gamepad buttons] valueForKey: GCInputDirectionalCenterButton]);
+        isDirectionalButtonPressed = true;
+    }
+#endif
+
+    if (!isDirectionalButtonPressed)
+        ReportJoystickButton(idx, BTN_A, [gamepad buttonA]);
+    ReportJoystickButton(idx, BTN_X, [gamepad buttonX]);
+}
+
+static void ReportJoystickExtended(int idx, GCExtendedGamepad* gamepad)
+{
+    GCControllerDirectionPad* dpad = [gamepad dpad];
+    ReportJoystickButton(idx, BTN_DPAD_UP, [dpad up]);
+    ReportJoystickButton(idx, BTN_DPAD_RIGHT, [dpad right]);
+    ReportJoystickButton(idx, BTN_DPAD_DOWN, [dpad down]);
+    ReportJoystickButton(idx, BTN_DPAD_LEFT, [dpad left]);
+
+    ReportJoystickButton(idx, BTN_A, [gamepad buttonA]);
+    ReportJoystickButton(idx, BTN_B, [gamepad buttonB]);
+    ReportJoystickButton(idx, BTN_Y, [gamepad buttonY]);
+    ReportJoystickButton(idx, BTN_X, [gamepad buttonX]);
+
+    ReportJoystickButton(idx, BTN_L1, [gamepad leftShoulder]);
+    ReportJoystickButton(idx, BTN_R1, [gamepad rightShoulder]);
+    ReportJoystickButton(idx, BTN_L2, [gamepad leftTrigger]);
+    ReportJoystickButton(idx, BTN_R2, [gamepad rightTrigger]);
+
+    ReportJoystickButton(idx, BTN_L3, [gamepad valueForKey: @"leftThumbstickButton"]);
+    ReportJoystickButton(idx, BTN_R3, [gamepad valueForKey: @"rightThumbstickButton"]);
+    ReportJoystickButton(idx, BTN_MENU, [gamepad valueForKey: @"buttonMenu"]);
+    ReportJoystickButton(idx, BTN_PAUSE, [gamepad valueForKey: @"buttonOptions"]);
+
+    // To avoid overwriting axis input with button input when axis index
+    // overlaps with button enum value, handle directional input after buttons.
+    GCControllerDirectionPad* leftStick = [gamepad leftThumbstick];
+    GCControllerDirectionPad* rightStick = [gamepad rightThumbstick];
+
+    UnitySetJoystickPosition(idx + 1, 0, GetAxisValue([leftStick xAxis]));
+    UnitySetJoystickPosition(idx + 1, 1, -GetAxisValue([leftStick yAxis]));
+
+    UnitySetJoystickPosition(idx + 1, 2, GetAxisValue([rightStick xAxis]));
+    UnitySetJoystickPosition(idx + 1, 3, -GetAxisValue([rightStick yAxis]));
+}
+
+static void SimulateAttitudeViaGravityVector(const Vector3f& gravity, Quaternion4f& currentAttitude, Vector3f& rotationRate)
+{
+    static Quaternion4f lastAttitude = QuatIdentity();
+    static double lastTime = 0.0;
+    double currentTime = [NSDate timeIntervalSinceReferenceDate];
+    double deltaTime = lastTime - currentTime;
+    currentAttitude = QuatRotationFromTo(gravity, VecMake(0.0f, 0.0f, -1.0f));
+    rotationRate = VecScale(1.0f / deltaTime, QuatToEuler(QuatDifference(currentAttitude, lastAttitude)));
+    lastAttitude = currentAttitude;
+    lastTime = currentTime;
+}
+
+// Note that joystick axis numbers in documentation are shifted
+// by one. 1st axis is referred to by index 0, 16th by 15, etc.
+static void ReportJoystickMotion(int idx, GCMotion* motion)
+{
+    Vector3f rotationRate = VecMake(0.0f, 0.0f, 0.0f);
+    Quaternion4f attitude = QuatMake(0.0f, 0.0f, 0.0f, 1.0f);
+
+    bool gotRotationData = false;
+    if (motion.hasAttitudeAndRotationRate)
+    {
+        rotationRate = {(float)motion.rotationRate.x, (float)motion.rotationRate.y, (float)motion.rotationRate.z};
+        attitude = {(float)motion.attitude.x, (float)motion.attitude.y, (float)motion.attitude.z, (float)motion.attitude.w};
+        gotRotationData = true;
+    }
+
+#if SIMULATE_ATTITUDE_FROM_GRAVITY
+    if (!gotRotationData)
+        SimulateAttitudeViaGravityVector(VecMake((float)motion.gravity.x, (float)motion.gravity.y, (float)motion.gravity.z), attitude, rotationRate);
+#endif
+
+    // From docs:
+    // gravity (x,y,z) : 16, 17, 18
+    // user acceleration: 19, 20, 21
+    // rotation rate: 22, 23, 24
+    // attitude quaternion (x,y,z,w): 25, 26, 27, 28
+    ReportJoystickXYZAxes(idx, 15, 16, 17, motion.gravity);
+    ReportJoystickXYZAxes(idx, 18, 19, 20, motion.userAcceleration);
+    ReportJoystickXYZAxes(idx, 21, 22, 23, rotationRate);
+    ReportJoystickXYZWAxes(idx, 24, 25, 26, 27, attitude);
+
+#if PLATFORM_TVOS
+    if (sGCMotionForwardingEnabled && !sGCMotionForwardedForCurrentFrame)
+    {
+        UnitySensorsSetGravity(0, motion.gravity.x, motion.gravity.y, motion.gravity.z);
+        UnitySensorsSetUserAcceleration(0, motion.userAcceleration.x, motion.userAcceleration.y, motion.userAcceleration.z);
+        UnitySensorsSetGyroRotationRate(0, rotationRate.y, rotationRate.x, rotationRate.z);
+        UnitySensorsSetAttitude(0, attitude.x, attitude.y, attitude.z, attitude.w);
+        UnityDidAccelerate(motion.userAcceleration.x + motion.gravity.x, motion.userAcceleration.y + motion.gravity.y, motion.userAcceleration.z + motion.gravity.z, [[NSDate date] timeIntervalSince1970]);
+        sGCMotionForwardedForCurrentFrame = true;
+    }
+#endif
+}
+
+static void ReportJoystick(GCController* controller, int idx)
+{
+    if (controller.controllerPausedHandler == nil)
+        controller.controllerPausedHandler = gControllerHandler;
+
+    if ([controller extendedGamepad] != nil)
+        ReportJoystickExtended(idx, [controller extendedGamepad]);
+    else if ([controller microGamepad] != nil)
+        ReportJoystickMicro(idx, [controller microGamepad]);
+    else
+    {
+        // TODO: do something with not supported gamepad profiles
+    }
+
+    if (controller.motion != nil)
+        ReportJoystickMotion(idx, controller.motion);
+
+    // Map pause button
+    SetJoystickButtonState(idx + 1, BTN_PAUSE, gPausedJoysticks[idx]);
+
+    // Reset pause button
+    gPausedJoysticks[idx] = false;
+}
+
+// On tvOS simulator we implement a fake remote as tvOS simulator
+// does not support controllers (yet)
+#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
+struct FakeRemoteState
+{
+    bool pressedX, pressedA;
+    bool pressedUp, pressedDown, pressedLeft, pressedRight;
+    float xAxis, yAxis;
+
+    FakeRemoteState() :
+        pressedX(false),
+        pressedA(false),
+        pressedUp(false),
+        pressedDown(false),
+        pressedLeft(false),
+        pressedRight(false),
+        xAxis(0),
+        yAxis(0)
+    {}
+};
+
+static FakeRemoteState gFakeRemoteState;
+
+static void ReportFakeRemoteButton(int idx, JoystickButtonNumbers num, bool pressed)
+{
+    SetJoystickButtonState(idx + 1, num, pressed);
+    UnitySetJoystickPosition(idx + 1, num, pressed);
+}
+
+void ReportFakeRemote(int idx)
+{
+    UnitySetJoystickPosition(idx + 1, 0, gFakeRemoteState.xAxis);
+    UnitySetJoystickPosition(idx + 1, 1, -gFakeRemoteState.yAxis);
+
+    ReportFakeRemoteButton(idx, BTN_DPAD_UP, gFakeRemoteState.pressedUp);
+    ReportFakeRemoteButton(idx, BTN_DPAD_RIGHT, gFakeRemoteState.pressedRight);
+    ReportFakeRemoteButton(idx, BTN_DPAD_DOWN, gFakeRemoteState.pressedDown);
+    ReportFakeRemoteButton(idx, BTN_DPAD_LEFT, gFakeRemoteState.pressedLeft);
+
+    ReportFakeRemoteButton(idx, BTN_A, gFakeRemoteState.pressedA);
+    ReportFakeRemoteButton(idx, BTN_X, gFakeRemoteState.pressedX);
+}
+
+#endif
+
+UNITY_EXPORT extern "C" void UnityUpdateJoystickData()
+{
+    UnityInitJoysticks();
+
+    NSArray* list = QueryControllerCollection();
+#if PLATFORM_TVOS
+    sGCMotionForwardedForCurrentFrame = false;
+#endif
+
+    if (list != nil)
+    {
+        for (int i = 0; i < [list count]; i++)
+        {
+            id controller = [list objectAtIndex: i];
+            ReportJoystick(controller, i);
+        }
+    }
+
+#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
+    int remoteIndex = list != nil ? (int)[list count] : 0;
+    ReportFakeRemote(remoteIndex);
+#endif
+
+    // Report all aggregated joystick buttons in bulk
+    HandleAggregatedJoystickState();
+}
+
+static NSString* FormatJoystickIdentifier(int idx, const char* typeString, const char* attachment, const char* vendorName)
+{
+    return [NSString stringWithFormat: @"[%s,%s] joystick %d by %s", typeString, attachment, idx + 1, vendorName];
+}
+
+NSString* GetJoystickName(GCController* controller, int idx)
+{
+    if (controller != nil)
+    {
+        // iOS 8 has bug, which is encountered when controller is being attached
+        // while app is still running. It creates two instances of controller object:
+        // one original and one "Forwarded", accesing later properties are causing crashes
+        const char* attached = "unknown";
+
+        // Controller is good one
+        if ([[controller vendorName] rangeOfString: @"Forwarded"].location == NSNotFound)
+            attached = (controller.attachedToDevice ? "wired" : "wireless");
+
+        const char* typeString = [controller extendedGamepad] != nil ? "extended" : "basic";
+        return FormatJoystickIdentifier(idx, typeString, attached, [[controller vendorName] UTF8String]);
+    }
+    
+    return @"unknown";
+}
+
+UNITY_EXPORT extern "C" NSArray* UnityGetJoystickNames()
+{
+    NSArray* joysticks = QueryControllerCollection();
+    int count = joysticks != nil ? (int)[joysticks count] : 0;
+
+    NSMutableArray * joystickNames = [NSMutableArray arrayWithCapacity: count];
+
+    for (int i = 0; i < count; i++)
+    {
+        [joystickNames addObject: GetJoystickName(joysticks[i], i)];
+    }
+    
+#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
+    [joystickNames addObject: FormatJoystickIdentifier(count, "basic", "wireless", "Unity")];
+#endif
+    
+    return joystickNames;
+}
+
+UNITY_EXPORT extern "C" void UnityGetJoystickAxisName(int idx, int axis, char* buffer, int maxLen)
+{
+}
+
+UNITY_EXPORT extern "C" void UnityGetNiceKeyname(int key, char* buffer, int maxLen)
+{
+}
+
+#pragma clang diagnostic pop
+
+#if UNITY_USES_LOCATION
+@interface LocationServiceDelegate : NSObject<CLLocationManagerDelegate>
+@end
+#endif
+
+extern "C" void
+UnitySetLastLocation(double timestamp,
+    float latitude,
+    float longitude,
+    float altitude,
+    float horizontalAccuracy,
+    float verticalAccuracy);
+
+extern "C" void
+UnitySetLastHeading(float magneticHeading, float trueHeading, float headingAccuracy,
+    float rawX, float rawY, float rawZ, double timestamp);
+
+#if UNITY_USES_LOCATION
+struct LocationServiceInfo
+{
+private:
+    LocationServiceDelegate* delegate;
+    CLLocationManager* locationManager;
+public:
+    LocationServiceStatus locationStatus;
+    LocationServiceStatus headingStatus;
+
+    float desiredAccuracy;
+    float distanceFilter;
+
+    LocationServiceInfo();
+    CLLocationManager* GetLocationManager();
+};
+
+LocationServiceInfo::LocationServiceInfo()
+{
+    locationStatus = kLocationServiceStopped;
+    desiredAccuracy = kCLLocationAccuracyKilometer;
+    distanceFilter = 500;
+
+    headingStatus = kLocationServiceStopped;
+}
+
+static LocationServiceInfo gLocationServiceStatus;
+
+CLLocationManager* LocationServiceInfo::GetLocationManager()
+{
+    if (locationManager == nil)
+    {
+        locationManager = [[CLLocationManager alloc] init];
+        delegate = [LocationServiceDelegate alloc];
+
+        locationManager.delegate = delegate;
+    }
+
+    return locationManager;
+}
+
+#endif
+
+UNITY_EXPORT bool LocationService::IsServiceEnabledByUser()
+{
+#if UNITY_USES_LOCATION
+    return [CLLocationManager locationServicesEnabled];
+#else
+    return false;
+#endif
+}
+
+UNITY_EXPORT void LocationService::SetDesiredAccuracy(float val)
+{
+#if UNITY_USES_LOCATION
+    gLocationServiceStatus.desiredAccuracy = val;
+#endif
+}
+
+UNITY_EXPORT float LocationService::GetDesiredAccuracy()
+{
+#if UNITY_USES_LOCATION
+    return gLocationServiceStatus.desiredAccuracy;
+#else
+    return NAN;
+#endif
+}
+
+UNITY_EXPORT void LocationService::SetDistanceFilter(float val)
+{
+#if UNITY_USES_LOCATION
+    gLocationServiceStatus.distanceFilter = val;
+#endif
+}
+
+UNITY_EXPORT float LocationService::GetDistanceFilter()
+{
+#if UNITY_USES_LOCATION
+    return gLocationServiceStatus.distanceFilter;
+#else
+    return NAN;
+#endif
+}
+
+UNITY_EXPORT void LocationService::StartUpdatingLocation()
+{
+#if UNITY_USES_LOCATION
+    if (gLocationServiceStatus.locationStatus != kLocationServiceRunning)
+    {
+        CLLocationManager* locationManager = gLocationServiceStatus.GetLocationManager();
+        [locationManager requestWhenInUseAuthorization];
+
+        locationManager.desiredAccuracy = gLocationServiceStatus.desiredAccuracy;
+        // Set a movement threshold for new events
+        locationManager.distanceFilter = gLocationServiceStatus.distanceFilter;
+
+#if PLATFORM_IOS
+        [locationManager startUpdatingLocation];
+#else
+        [locationManager requestLocation];
+#endif
+
+        gLocationServiceStatus.locationStatus = kLocationServiceInitializing;
+    }
+#endif
+}
+
+UNITY_EXPORT void LocationService::StopUpdatingLocation()
+{
+#if UNITY_USES_LOCATION
+    if (gLocationServiceStatus.locationStatus != kLocationServiceStopped)
+    {
+        [gLocationServiceStatus.GetLocationManager() stopUpdatingLocation];
+        gLocationServiceStatus.locationStatus = kLocationServiceStopped;
+    }
+#endif
+}
+
+UNITY_EXPORT void LocationService::SetHeadingUpdatesEnabled(bool enabled)
+{
+#if PLATFORM_IOS && UNITY_USES_LOCATION
+    if (enabled)
+    {
+        if (gLocationServiceStatus.headingStatus != kLocationServiceRunning &&
+            IsHeadingAvailable())
+        {
+            CLLocationManager* locationManager = gLocationServiceStatus.GetLocationManager();
+
+            [locationManager startUpdatingHeading];
+            gLocationServiceStatus.headingStatus = kLocationServiceInitializing;
+        }
+    }
+    else
+    {
+        if (gLocationServiceStatus.headingStatus != kLocationServiceStopped)
+        {
+            [gLocationServiceStatus.GetLocationManager() stopUpdatingHeading];
+            gLocationServiceStatus.headingStatus = kLocationServiceStopped;
+        }
+    }
+#endif
+}
+
+UNITY_EXPORT bool LocationService::IsHeadingUpdatesEnabled()
+{
+#if UNITY_USES_LOCATION
+    return (gLocationServiceStatus.headingStatus == kLocationServiceRunning);
+#else
+    return false;
+#endif
+}
+
+UNITY_EXPORT LocationServiceStatus LocationService::GetLocationStatus()
+{
+#if UNITY_USES_LOCATION
+    return (LocationServiceStatus)gLocationServiceStatus.locationStatus;
+#else
+    return kLocationServiceFailed;
+#endif
+}
+
+UNITY_EXPORT LocationServiceStatus LocationService::GetHeadingStatus()
+{
+#if UNITY_USES_LOCATION
+    return (LocationServiceStatus)gLocationServiceStatus.headingStatus;
+#else
+    return kLocationServiceFailed;
+#endif
+}
+
+UNITY_EXPORT bool LocationService::IsHeadingAvailable()
+{
+#if PLATFORM_IOS && UNITY_USES_LOCATION
+    return [CLLocationManager headingAvailable];
+#else
+    return false;
+#endif
+}
+
+#if UNITY_USES_LOCATION
+@implementation LocationServiceDelegate
+
+- (void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations
+{
+    CLLocation* lastLocation = locations.lastObject;
+
+    gLocationServiceStatus.locationStatus = kLocationServiceRunning;
+
+    UnitySetLastLocation([lastLocation.timestamp timeIntervalSince1970],
+        lastLocation.coordinate.latitude, lastLocation.coordinate.longitude, lastLocation.altitude,
+        lastLocation.horizontalAccuracy, lastLocation.verticalAccuracy
+    );
+}
+
+#if PLATFORM_IOS
+- (void)locationManager:(CLLocationManager*)manager didUpdateHeading:(CLHeading*)newHeading
+{
+    gLocationServiceStatus.headingStatus = kLocationServiceRunning;
+
+    Vector3f reorientedRawHeading = UnityReorientVector3(newHeading.x, newHeading.y, newHeading.z);
+
+    UnitySetLastHeading(UnityReorientHeading(newHeading.magneticHeading),
+        UnityReorientHeading(newHeading.trueHeading),
+        newHeading.headingAccuracy,
+        reorientedRawHeading.x, reorientedRawHeading.y, reorientedRawHeading.z,
+        [newHeading.timestamp timeIntervalSince1970]);
+}
+
+#endif
+
+- (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager*)manager
+{
+    return NO;
+}
+
+- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error;
+{
+    gLocationServiceStatus.locationStatus = kLocationServiceFailed;
+    gLocationServiceStatus.headingStatus = kLocationServiceFailed;
+}
+
+@end
+#endif
+
+#if PLATFORM_TVOS
+
+GCMicroGamepad* QueryMicroController()
+{
+    NSArray* list = QueryControllerCollection();
+    for (GCController* controller in list)
+    {
+        if (controller.microGamepad != nil)
+            return controller.microGamepad;
+    }
+
+    return nil;
+}
+
+UNITY_EXPORT extern "C" int UnityGetAppleTVRemoteTouchesEnabled()
+{
+    return gTVRemoteTouchesEnabled;
+}
+
+UNITY_EXPORT extern "C" void UnitySetAppleTVRemoteTouchesEnabled(int val)
+{
+    gTVRemoteTouchesEnabled = val;
+}
+
+/*
+    TVRemoteAllowExitToMenu.
+    Lowest bit caches the value of .controllerUserInteractionEnabled.
+    Second lowest bit is set if .controllerUserInteractionEnabled is temporarily changed for internal purposes.
+*/
+UNITY_EXPORT extern "C" int UnityGetAppleTVRemoteAllowExitToMenu()
+{
+    if (gTVControllerUserInteractionEnabled & 2)
+        return gTVControllerUserInteractionEnabled & 1;
+    return ((GCEventViewController*)UnityGetGLViewController()).controllerUserInteractionEnabled;
+}
+
+/*
+    Same as getter above, except that second lowest bit here indicates fake setting,
+    meaning we set the value on controller, but cache the true value so getter report no changes.
+*/
+UNITY_EXPORT extern "C" void UnitySetAppleTVRemoteAllowExitToMenu(int val)
+{
+    bool newVal = val & 1;
+    if (val & 2)
+    {
+        if (gTVControllerUserInteractionEnabled == val)
+            return;
+        if (0 == (gTVControllerUserInteractionEnabled & 2))
+        {
+            int cacheVal = ((GCEventViewController*)UnityGetGLViewController()).controllerUserInteractionEnabled;
+            gTVControllerUserInteractionEnabled = 2 | cacheVal;
+        }
+    }
+    ((GCEventViewController*)UnityGetGLViewController()).controllerUserInteractionEnabled = newVal;
+}
+
+UNITY_EXPORT extern "C" int UnityGetAppleTVRemoteAllowRotation()
+{
+    GCMicroGamepad* controller = QueryMicroController();
+    if (controller != nil)
+        return controller.allowsRotation;
+    else
+        return false;
+}
+
+UNITY_EXPORT extern "C" void UnitySetAppleTVRemoteAllowRotation(int val)
+{
+    GCMicroGamepad* controller = QueryMicroController();
+    if (controller != nil)
+        controller.allowsRotation = val;
+    else
+        gTVRemoteAllowRotationInitialValue = val;
+}
+
+UNITY_EXPORT extern "C" int UnityGetAppleTVRemoteReportAbsoluteDpadValues()
+{
+    GCMicroGamepad* controller = QueryMicroController();
+    if (controller != nil)
+        return controller.reportsAbsoluteDpadValues;
+    else
+        return false;
+}
+
+UNITY_EXPORT extern "C" void UnitySetAppleTVRemoteReportAbsoluteDpadValues(int val)
+{
+    NSArray* list = QueryControllerCollection();
+    for (GCController* controller in list)
+    {
+        if (controller.microGamepad != nil)
+            controller.microGamepad.reportsAbsoluteDpadValues = val;
+        else
+            gTVRemoteReportsAbsoluteDpadValuesInitialValue = val;
+    }
+}
+
+#endif
+
+#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
+static void FakeRemoteStateSetButton(UIPressType type, bool state)
+{
+    switch (type)
+    {
+        case UIPressTypeUpArrow: gFakeRemoteState.pressedUp = state; return;
+        case UIPressTypeDownArrow: gFakeRemoteState.pressedDown = state; return;
+        case UIPressTypeLeftArrow: gFakeRemoteState.pressedLeft = state; return;
+        case UIPressTypeRightArrow: gFakeRemoteState.pressedRight = state; return;
+        case UIPressTypeSelect: gFakeRemoteState.pressedA = state; return;
+        case UIPressTypePlayPause: gFakeRemoteState.pressedX = state; return;
+    }
+}
+
+void ReportSimulatedRemoteButtonPress(UIPressType type)
+{
+    FakeRemoteStateSetButton(type, true);
+}
+
+void ReportSimulatedRemoteButtonRelease(UIPressType type)
+{
+    FakeRemoteStateSetButton(type, false);
+}
+
+static float FakeRemoteMapTouchToAxis(float pos, float bounds)
+{
+    float halfRange = bounds / 2;
+    return (pos - halfRange) / halfRange;
+}
+
+void ReportSimulatedRemoteTouchesBegan(UIView* view, NSSet* touches)
+{
+    ReportSimulatedRemoteTouchesMoved(view, touches);
+}
+
+void ReportSimulatedRemoteTouchesMoved(UIView* view, NSSet* touches)
+{
+    for (UITouch* touch in touches)
+    {
+        gFakeRemoteState.xAxis = FakeRemoteMapTouchToAxis([touch locationInView: view].x, view.bounds.size.width);
+        gFakeRemoteState.yAxis = FakeRemoteMapTouchToAxis([touch locationInView: view].y, view.bounds.size.height);
+        // We assume that at most single touch is received.
+        break;
+    }
+}
+
+void ReportSimulatedRemoteTouchesEnded(UIView* view, NSSet* touches)
+{
+    gFakeRemoteState.xAxis = 0;
+    gFakeRemoteState.yAxis = 0;
+}
+
+#endif

+ 175 - 0
unity_ios/Classes/main.mm

@@ -0,0 +1,175 @@
+#include "RegisterFeatures.h"
+#include <csignal>
+#include "UnityInterface.h"
+#import <UnityFramework/UnityFramework.h>
+#include "UI/Keyboard.h"
+
+void UnityInitTrampoline();
+
+// WARNING: this MUST be c decl (NSString ctor will be called after +load, so we cant really change its value)
+const char* AppControllerClassName = "UnityAppController";
+
+extern "C" void UnitySetExecuteMachHeader(const MachHeader* header);
+
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityDidUnload;
+extern "C" __attribute__((visibility("default"))) NSString* const kUnityDidQuit;
+
+@implementation UnityFramework
+{
+    int runCount;
+}
+
+UnityFramework* _gUnityFramework = nil;
++ (UnityFramework*)getInstance
+{
+    if (_gUnityFramework == nil)
+    {
+        _gUnityFramework = [[UnityFramework alloc] init];
+    }
+    return _gUnityFramework;
+}
+
+- (UnityAppController*)appController
+{
+    return GetAppController();
+}
+
+- (UITextField*)keyboardTextField
+{
+    return KeyboardDelegate.Instance.getTextField;
+}
+
+- (void)setExecuteHeader:(const MachHeader*)header
+{
+    UnitySetExecuteMachHeader(header);
+}
+
+- (void)sendMessageToGOWithName:(const char*)goName functionName:(const char*)name message:(const char*)msg
+{
+    UnitySendMessage(goName, name, msg);
+}
+
+- (void)registerFrameworkListener:(id<UnityFrameworkListener>)obj
+{
+#define REGISTER_SELECTOR(sel, notif_name)                  \
+if([obj respondsToSelector:sel])                        \
+[[NSNotificationCenter defaultCenter]   addObserver:obj selector:sel name:notif_name object:nil];
+
+    REGISTER_SELECTOR(@selector(unityDidUnload:), kUnityDidUnload);
+    REGISTER_SELECTOR(@selector(unityDidQuit:), kUnityDidQuit);
+
+#undef REGISTER_SELECTOR
+}
+
+- (void)unregisterFrameworkListener:(id<UnityFrameworkListener>)obj
+{
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityDidUnload object: nil];
+    [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityDidQuit object: nil];
+}
+
+- (void)frameworkWarmup:(int)argc argv:(char*[])argv
+{
+    UnityInitTrampoline();
+    UnityInitRuntime(argc, argv);
+
+    RegisterFeatures();
+
+    // iOS terminates open sockets when an application enters background mode.
+    // The next write to any of such socket causes SIGPIPE signal being raised,
+    // even if the request has been done from scripting side. This disables the
+    // signal and allows Mono to throw a proper C# exception.
+    std::signal(SIGPIPE, SIG_IGN);
+}
+
+- (void)setDataBundleId:(const char*)bundleId
+{
+    UnitySetDataBundleDirWithBundleId(bundleId);
+}
+
+- (void)runUIApplicationMainWithArgc:(int)argc argv:(char*[])argv
+{
+    self->runCount += 1;
+    [self frameworkWarmup: argc argv: argv];
+    UIApplicationMain(argc, argv, nil, [NSString stringWithUTF8String: AppControllerClassName]);
+}
+
+- (void)runEmbeddedWithArgc:(int)argc argv:(char*[])argv appLaunchOpts:(NSDictionary*)appLaunchOpts
+{
+    if (self->runCount)
+    {
+        // initialize from partial unload ( sceneLessMode & onPause )
+        UnityLoadApplicationFromSceneLessState();
+        UnitySuppressPauseMessage();
+        [self pause: false];
+        [self showUnityWindow];
+
+        // Send Unity start event
+        UnitySendEmbeddedLaunchEvent(0);
+    }
+    else
+    {
+        // full initialization from ground up
+        [self frameworkWarmup: argc argv: argv];
+
+        id app = [UIApplication sharedApplication];
+
+        id appCtrl = [[NSClassFromString([NSString stringWithUTF8String: AppControllerClassName]) alloc] init];
+        [appCtrl application: app didFinishLaunchingWithOptions: appLaunchOpts];
+
+        [appCtrl applicationWillEnterForeground: app];
+        [appCtrl applicationDidBecomeActive: app];
+
+        // Send Unity start (first time) event
+        UnitySendEmbeddedLaunchEvent(1);
+    }
+
+    self->runCount += 1;
+}
+
+- (void)unloadApplication
+{
+    UnityUnloadApplication();
+}
+
+- (void)quitApplication:(int)exitCode
+{
+    UnityQuitApplication(exitCode);
+}
+
+- (void)showUnityWindow
+{
+    [[[self appController] window] makeKeyAndVisible];
+}
+
+- (void)pause:(bool)pause
+{
+    UnityPause(pause);
+}
+
+- (void)setAbsoluteURL:(const char *)url
+{
+    UnitySetAbsoluteURL(url);
+}
+
+- (int)shouldRunInBackground
+{
+    return UnityShouldRunInBackground();
+}
+
+@end
+
+
+#if TARGET_OS_SIMULATOR
+#include <pthread.h>
+
+extern "C" int pthread_cond_init$UNIX2003(pthread_cond_t *cond, const pthread_condattr_t *attr)
+{ return pthread_cond_init(cond, attr); }
+extern "C" int pthread_cond_destroy$UNIX2003(pthread_cond_t *cond)
+{ return pthread_cond_destroy(cond); }
+extern "C" int pthread_cond_wait$UNIX2003(pthread_cond_t *cond, pthread_mutex_t *mutex)
+{ return pthread_cond_wait(cond, mutex); }
+extern "C" int pthread_cond_timedwait$UNIX2003(pthread_cond_t *cond, pthread_mutex_t *mutex,
+    const struct timespec *abstime)
+{ return pthread_cond_timedwait(cond, mutex, abstime); }
+
+#endif // TARGET_OS_SIMULATOR

BIN
unity_ios/Data/Managed/Metadata/global-metadata.dat


BIN
unity_ios/Data/Managed/Resources/mscorlib.dll-resources.dat


+ 307 - 0
unity_ios/Data/Managed/mono/4.0/machine.config

@@ -0,0 +1,307 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<configuration>
+
+	<configSections>
+		<section name="configProtectedData" type="System.Configuration.ProtectedConfigurationSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+		<section name="appSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+		<section name="connectionStrings" type="System.Configuration.ConnectionStringsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+		<section name="mscorlib" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowLocation="false"/>
+		<section name="runtime" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowLocation="false"/>
+		<section name="assemblyBinding"  type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowLocation="false" />
+		<section name="satelliteassemblies" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowLocation="false" />
+		<section name="startup" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowLocation="false"/>
+		<section name="system.codedom" type="System.CodeDom.Compiler.CodeDomConfigurationHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+		<section name="system.data" type="System.Data.Common.DbProviderFactoriesConfigurationHandler, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+		<section name="system.diagnostics" type="System.Diagnostics.DiagnosticsConfigurationHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+		<section name="system.runtime.remoting" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowLocation="false"/>
+		<section name="system.windows.forms" type="System.Windows.Forms.WindowsFormsSection, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+		<section name="windows" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowLocation="false" />
+		<section name="strongNames" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowLocation="false"/>
+		<sectionGroup name="system.web" type="System.Web.Configuration.SystemWebSectionGroup, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
+			<section name="anonymousIdentification" type="System.Web.Configuration.AnonymousIdentificationSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+			<section name="authentication" type="System.Web.Configuration.AuthenticationSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+			<section name="authorization" type="System.Web.Configuration.AuthorizationSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="browserCaps" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="clientTarget" type="System.Web.Configuration.ClientTargetSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="compilation" type="System.Web.Configuration.CompilationSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="customErrors" type="System.Web.Configuration.CustomErrorsSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="deployment" type="System.Web.Configuration.DeploymentSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineOnly" />
+			<section name="globalization" type="System.Web.Configuration.GlobalizationSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="healthMonitoring" type="System.Web.Configuration.HealthMonitoringSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+			<section name="hostingEnvironment" type="System.Web.Configuration.HostingEnvironmentSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication" />
+			<section name="httpCookies" type="System.Web.Configuration.HttpCookiesSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="httpHandlers" type="System.Web.Configuration.HttpHandlersSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="httpModules" type="System.Web.Configuration.HttpModulesSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="httpRuntime" type="System.Web.Configuration.HttpRuntimeSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="identity" type="System.Web.Configuration.IdentitySection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="machineKey" type="System.Web.Configuration.MachineKeySection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="membership" type="System.Web.Configuration.MembershipSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="mobileControls" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+                        <section name="deviceFilters" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="pages" type="System.Web.Configuration.PagesSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="processModel" type="System.Web.Configuration.ProcessModelSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineOnly" allowLocation="false" />
+			<section name="profile" type="System.Web.Configuration.ProfileSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+			<section name="roleManager" type="System.Web.Configuration.RoleManagerSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+			<section name="securityPolicy" type="System.Web.Configuration.SecurityPolicySection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication" />
+			<section name="sessionPageState" type="System.Web.Configuration.SessionPageStateSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="sessionState" type="System.Web.Configuration.SessionStateSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+			<section name="siteMap" type="System.Web.Configuration.SiteMapSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+			<section name="trace" type="System.Web.Configuration.TraceSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="trust" type="System.Web.Configuration.TrustSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication" />
+			<section name="urlMappings" type="System.Web.Configuration.UrlMappingsSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+			<section name="webControls" type="System.Web.Configuration.WebControlsSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="webParts" type="System.Web.Configuration.WebPartsSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="webServices" type="System.Web.Services.Configuration.WebServicesSection, System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<section name="xhtmlConformance" type="System.Web.Configuration.XhtmlConformanceSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+			<sectionGroup name="caching" type="System.Web.Configuration.SystemWebCachingSectionGroup, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
+				<section name="cache" type="System.Web.Configuration.CacheSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+				<section name="outputCache" type="System.Web.Configuration.OutputCacheSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+				<section name="outputCacheSettings" type="System.Web.Configuration.OutputCacheSettingsSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+				<section name="sqlCacheDependency" type="System.Web.Configuration.OutputCacheSettingsSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+			</sectionGroup>
+			<section name="monoSettings" type="System.Web.Configuration.MonoSettingsSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+		</sectionGroup>
+		<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
+			<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
+				<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
+				<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
+					<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
+					<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
+					<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
+					<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
+				</sectionGroup>
+			</sectionGroup>
+		</sectionGroup>
+		<sectionGroup name="system.net" type="System.Net.Configuration.NetSectionGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+			<section name="authenticationModules" type="System.Net.Configuration.AuthenticationModulesSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="connectionManagement" type="System.Net.Configuration.ConnectionManagementSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="defaultProxy" type="System.Net.Configuration.DefaultProxySection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<sectionGroup name="mailSettings" type="System.Net.Configuration.MailSettingsSectionGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+				<section name="smtp" type="System.Net.Configuration.SmtpSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			</sectionGroup>
+			<section name="requestCaching" type="System.Net.Configuration.RequestCachingSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="settings" type="System.Net.Configuration.SettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="webRequestModules" type="System.Net.Configuration.WebRequestModulesSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+		</sectionGroup>
+		<section name="system.drawing" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+		<sectionGroup name="system.serviceModel" type="System.ServiceModel.Configuration.ServiceModelSectionGroup, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+			<section name="behaviors" type="System.ServiceModel.Configuration.BehaviorsSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="bindings" type="System.ServiceModel.Configuration.BindingsSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="client" type="System.ServiceModel.Configuration.ClientSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="commonBehaviors" type="System.ServiceModel.Configuration.CommonBehaviorsSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="diagnostics" type="System.ServiceModel.Configuration.DiagnosticSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="extensions" type="System.ServiceModel.Configuration.ExtensionsSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="serviceHostingEnvironment" type="System.ServiceModel.Configuration.ServiceHostingEnvironmentSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="services" type="System.ServiceModel.Configuration.ServicesSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<section name="standardEndpoints" type="System.ServiceModel.Configuration.StandardEndpointsSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
+			<section name="routing" type="System.ServiceModel.Routing.Configuration.RoutingSection, System.ServiceModel.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+			<section name="protocolMapping" type="System.ServiceModel.Configuration.ProtocolMappingSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
+		</sectionGroup>
+		<sectionGroup name="system.transactions" type="System.Transactions.Configuration.TransactionsSectionGroup, System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null">
+			<section name="defaultSettings" type="System.Transactions.Configuration.DefaultSettingsSection, System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null"/>
+			<section name="machineSettings" type="System.Transactions.Configuration.MachineSettingsSection, System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null" allowDefinition="MachineOnly" allowExeDefinition="MachineOnly"/>
+		</sectionGroup>
+		<section name="system.webServer" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+		<section name="uri" type="System.Configuration.UriSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+		<sectionGroup name="system.runtime.caching" type="System.Runtime.Caching.Configuration.CachingSectionGroup, System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
+		  <section name="memoryCache" type="System.Runtime.Caching.Configuration.MemoryCacheSection, System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+                </sectionGroup>
+	</configSections>
+
+	<connectionStrings>
+		<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
+		<add name="LocalSqliteServer" connectionString="Data Source=|DataDirectory|/aspnetdb.sqlite;version=3" providerName="Mono.Data.Sqlite"/>
+	</connectionStrings>
+	
+	<configProtectedData defaultProvider="RsaProtectedConfigurationProvider">
+		<providers>
+			<add name="RsaProtectedConfigurationProvider" type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
+                             description="" keyContainerName="MonoFrameworkConfigurationKey" cspProviderName="" useMachineContainer="true" useOAEP="false" />
+			<add name="DataProtectionConfigurationProvider" type="System.Configuration.DpapiProtectedConfigurationProvider, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
+                             description="" useMachineProtection="true" keyEntropy="" />
+		</providers>
+	</configProtectedData>
+
+	<system.net>
+		<authenticationModules>
+			<add type="System.Net.BasicClient, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<add type="System.Net.DigestClient, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<add type="System.Net.NtlmClient, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+		</authenticationModules>
+		<webRequestModules>
+			<add prefix="http" type="System.Net.HttpRequestCreator, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<add prefix="https" type="System.Net.HttpRequestCreator, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<add prefix="file" type="System.Net.FileWebRequestCreator, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<add prefix="ftp" type="System.Net.FtpWebRequestCreator, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+		</webRequestModules>
+	</system.net>
+	
+	<system.runtime.remoting>
+		<application>
+			<channels>
+				<channel ref="http client" displayName="http client (delay loaded)" delayLoadAsClientChannel="true" />
+				<channel ref="tcp client" displayName="tcp client (delay loaded)" delayLoadAsClientChannel="true" />
+				<channel ref="ipc client" displayName="ipc client (delay loaded)" delayLoadAsClientChannel="true" />
+			</channels>
+		</application>
+		<channels>
+			<channel id="http" type="System.Runtime.Remoting.Channels.Http.HttpChannel, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<channel id="http client" type="System.Runtime.Remoting.Channels.Http.HttpClientChannel, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<channel id="http server" type="System.Runtime.Remoting.Channels.Http.HttpServerChannel, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<channel id="tcp" type="System.Runtime.Remoting.Channels.Tcp.TcpChannel, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<channel id="tcp client" type="System.Runtime.Remoting.Channels.Tcp.TcpClientChannel, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<channel id="tcp server" type="System.Runtime.Remoting.Channels.Tcp.TcpServerChannel, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<channel id="ipc" type="System.Runtime.Remoting.Channels.Ipc.IpcChannel, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<channel id="ipc client" type="System.Runtime.Remoting.Channels.Ipc.IpcClientChannel, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+			<channel id="ipc server" type="System.Runtime.Remoting.Channels.Ipc.IpcServerChannel, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+		</channels>
+			<channelSinkProviders>
+				<clientProviders>
+					<formatter id="soap" type="System.Runtime.Remoting.Channels.SoapClientFormatterSinkProvider, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+					<formatter id="binary" type="System.Runtime.Remoting.Channels.BinaryClientFormatterSinkProvider, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+				</clientProviders>
+				<serverProviders>
+					<formatter id="soap" type="System.Runtime.Remoting.Channels.SoapServerFormatterSinkProvider, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+					<formatter id="binary" type="System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+					<provider id="wsdl" type="System.Runtime.Remoting.MetadataServices.SdlChannelSinkProvider, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+				</serverProviders>
+			</channelSinkProviders>
+	</system.runtime.remoting>
+	
+	<appSettings>
+	<!--<add key="yourkey" value="your value" /> -->
+	<!--<remove key="a key defined higher in the hierarchy" /> -->
+	<!--<clear/> Removes all defined settings -->
+	</appSettings>
+	<system.diagnostics>
+		<trace autoflush="false" indentsize="4" />
+	</system.diagnostics>
+        <system.drawing>
+        </system.drawing>
+
+	<system.data>
+	  <DbProviderFactories>
+	    <add name="Mono Sqlite Data Provider"  invariant="Mono.Data.SqliteClient" 
+		 description="Mono Framework Data Provider for SQLite (old version)" 
+		 type="Mono.Data.SqliteClient.SqliteFactory, Mono.Data.SqliteClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"/>
+	    <add name="Mono Sqlite Provider"  invariant="Mono.Data.Sqlite" 
+		 description="Mono Framework Data Provider for SQLite (new version)"
+		 type="Mono.Data.Sqlite.SqliteFactory, Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"/>
+	    <add name="Odbc Data Provider"         invariant="System.Data.Odbc"         
+		 description=".Net Framework Data Provider for Odbc"      
+		 type="System.Data.Odbc.OdbcFactory, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
+            <add name="OleDb Data Provider"        invariant="System.Data.OleDb"        
+		 description=".Net Framework Data Provider for OleDb"     
+		 type="System.Data.OleDb.OleDbFactory, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
+            <add name="OracleClient Data Provider" invariant="System.Data.OracleClient" 
+		 description=".Net Framework Data Provider for Oracle"    
+		 type="System.Data.OracleClient.OracleClientFactory, System.Data.OracleClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
+            <add name="SqlClient Data Provider"    invariant="System.Data.SqlClient"    
+		 description=".Net Framework Data Provider for SqlServer" 
+		 type="System.Data.SqlClient.SqlClientFactory, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
+            <add name="Sybase Data Provider"    invariant="Mono.Data.SybaseClient"    
+		 description=".Net Framework Data Provider for Sybase" 
+		 type="Mono.Data.SybaseClient.SybaseClientFactory, Mono.Data.SybaseClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"/>
+	  </DbProviderFactories>
+	</system.data>
+
+	<mscorlib>
+		<cryptographySettings>
+			<cryptoNameMapping>
+				<cryptoClasses>
+					<cryptoClass monoMD2="Mono.Security.Cryptography.MD2Managed, Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756" />
+					<cryptoClass monoMD4="Mono.Security.Cryptography.MD4Managed, Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756" />
+				</cryptoClasses>
+				<nameEntry name="MD2" class="monoMD2" />
+				<nameEntry name="MD4" class="monoMD4" />
+			</cryptoNameMapping>
+			<oidMap>
+				<oidEntry OID="1.2.840.113549.2.2" name="MD2" />
+				<oidEntry OID="1.2.840.113549.2.2" name="Mono.Security.Cryptography.MD2Managed" />
+				<oidEntry OID="1.2.840.113549.2.4" name="MD4" />
+				<oidEntry OID="1.2.840.113549.2.4" name="Mono.Security.Cryptography.MD4Managed" />
+			</oidMap>
+		</cryptographySettings>
+	</mscorlib>
+
+	<strongNames>
+		<pubTokenMapping>
+			<!-- ECMA key -->
+			<map Token="b77a5c561934e089" PublicKey="002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df" />
+			<!-- Microsoft (final) key -->
+			<map Token="b03f5f7f11d50a3a" PublicKey="002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df" />
+			<!-- Microsoft (Web Service Enhancement) key -->
+			<map Token="31bf3856ad364e35" PublicKey="002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df" />
+			<!-- IBM (DB2 Data Provider) key -->
+			<map Token="7c307b91aa13d208" PublicKey="002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df" />
+			<!-- Silverlight 2.0 key -->
+			<map Token="7cec85d7bea7798e" PublicKey="002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df" />
+			<!-- XNA Framework key -->                                                            
+			<map Token="6d5c3888ef60e27d" PublicKey="0024000004800000940000000602000000240000525341310004000001000100f9a2641bac9847900d92a33d652ccc4e8b529360f908e7af53e57008b2a9a1938c32a160d47f795a23590557608d2c8d0c0e8846a052d070f9298281b8185343dbe5b479bd52de256f73c2a943e1a8a42065b5c918622dc14b1c0151dbd94d9a4543e7cd03e536b1b1d2d6d99af535d227ab9bdac76af9312a21d457bdf817e6" />
+		</pubTokenMapping>
+	</strongNames>
+
+	<system.web>
+		<webServices>
+			<protocols>
+				<add name="HttpSoap"/>
+				<add name="HttpSoap12"/>
+				<add name="HttpPost"/>
+				<add name="HttpGet"/>
+				<add name="Documentation"/>
+			</protocols>
+			<conformanceWarnings>
+				<add name="BasicProfile1_1"/>
+			</conformanceWarnings>
+			<wsdlHelpGenerator href="DefaultWsdlHelpGenerator.aspx" />
+		</webServices>
+
+		<membership>
+			<providers>
+				<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="LocalSqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>
+				<!-- <add name="AspNetSqlMembershipProvider" type="Mainsoft.Web.Security.GenericMembershipProvider, Mainsoft.Web.Security" applicationName="/" connectionStringName="LocalSqlServer" /> -->
+			</providers>
+		</membership>
+
+		<roleManager>
+			<providers>
+				<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" applicationName="/" connectionStringName="LocalSqlServer" />
+				<!-- <add name="AspNetSqlRoleProvider" type="Mainsoft.Web.Security.GenericRoleProvider, Mainsoft.Web.Security" applicationName="/" connectionStringName="LocalSqlServer" /> -->
+			</providers>
+		</roleManager>
+
+		<profile>
+        		<providers>
+            		    <add name="AspNetSqlProfileProvider" connectionStringName="LocalSqlServer" applicationName="/" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+		        </providers>
+    		</profile>
+	</system.web>
+
+
+	<system.serviceModel>
+		<extensions>
+			<behaviorExtensions>
+				<add name="enableWebScript" type="System.ServiceModel.Configuration.WebScriptEnablingElement, System.ServiceModel.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+				<add name="webHttp" type="System.ServiceModel.Configuration.WebHttpElement, System.ServiceModel.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+			</behaviorExtensions>
+			<bindingElementExtensions>
+				<add name="webMessageEncoding" type="System.ServiceModel.Configuration.WebMessageEncodingElement, System.ServiceModel.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+			</bindingElementExtensions>
+			<bindingExtensions>
+				<add name="webHttpBinding" type="System.ServiceModel.Configuration.WebHttpBindingCollectionElement, System.ServiceModel.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+			</bindingExtensions>
+			<endpointExtensions>
+				<add name="dynamicEndpoint" type="System.ServiceModel.Discovery.Configuration.DynamicEndpointCollectionElement, System.ServiceModel.Discovery, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+				<add name="discoveryEndpoint" type="System.ServiceModel.Discovery.Configuration.DiscoveryEndpointCollectionElement, System.ServiceModel.Discovery, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+				<add name="udpDiscoveryEndpoint" type="System.ServiceModel.Discovery.Configuration.UdpDiscoveryEndpointCollectionElement, System.ServiceModel.Discovery, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+				<add name="announcementEndpoint" type="System.ServiceModel.Discovery.Configuration.AnnouncementEndpointCollectionElement, System.ServiceModel.Discovery, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+				<add name="udpAnnouncementEndpoint" type="System.ServiceModel.Discovery.Configuration.UdpAnnouncementEndpointCollectionElement, System.ServiceModel.Discovery, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+				<add name="webHttpEndpoint" type="System.ServiceModel.Configuration.WebHttpEndpointCollectionElement, System.ServiceModel.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+				<add name="webScriptEndpoint" type="System.ServiceModel.Configuration.WebScriptEndpointCollectionElement, System.ServiceModel.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+			</endpointExtensions>
+		</extensions>
+	</system.serviceModel>
+</configuration>
+
+

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor