UnityAppController.mm 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. #import "UnityAppController.h"
  2. #import "UnityAppController+Thermal.h"
  3. #import "UnityAppController+ViewHandling.h"
  4. #import "UnityAppController+Rendering.h"
  5. #import "iPhone_Sensors.h"
  6. #import <CoreGraphics/CoreGraphics.h>
  7. #import <QuartzCore/QuartzCore.h>
  8. #import <QuartzCore/CADisplayLink.h>
  9. #import <Availability.h>
  10. #import <AVFoundation/AVFoundation.h>
  11. #import <GameController/GameController.h>
  12. #include <mach/mach_time.h>
  13. // MSAA_DEFAULT_SAMPLE_COUNT was removed
  14. // ENABLE_INTERNAL_PROFILER and related defines were moved to iPhone_Profiler.h
  15. // kFPS define for removed: you can use Application.targetFrameRate (30 fps by default)
  16. // DisplayLink is the only run loop mode now - all others were removed
  17. #include "CrashReporter.h"
  18. #include "UI/OrientationSupport.h"
  19. #include "UI/UnityView.h"
  20. #include "UI/Keyboard.h"
  21. #include "UI/UnityViewControllerBase.h"
  22. #include "Unity/InternalProfiler.h"
  23. #include "Unity/DisplayManager.h"
  24. #include "Unity/ObjCRuntime.h"
  25. #include "PluginBase/AppDelegateListener.h"
  26. #include <assert.h>
  27. #include <stdbool.h>
  28. #include <sys/types.h>
  29. #include <unistd.h>
  30. #include <sys/sysctl.h>
  31. #include <UndefinePlatforms.h>
  32. #include <os/log.h>
  33. #include <RedefinePlatforms.h>
  34. #if PLATFORM_IOS || PLATFORM_VISIONOS
  35. @interface UnityView (iOSScrollWheel)
  36. - (void)teardownIndirectMouseInput;
  37. @end
  38. #endif
  39. // we assume that app delegate is never changed and we can cache it, instead of re-query UIApplication every time
  40. UnityAppController* _UnityAppController = nil;
  41. UnityAppController* GetAppController()
  42. {
  43. return _UnityAppController;
  44. }
  45. // we keep old bools around to support "old" code that might have used them
  46. bool _ios81orNewer = true, _ios82orNewer = true, _ios83orNewer = true, _ios90orNewer = true, _ios91orNewer = true;
  47. bool _ios100orNewer = true, _ios101orNewer = true, _ios102orNewer = true, _ios103orNewer = true;
  48. bool _ios110orNewer = true, _ios111orNewer = true, _ios112orNewer = true;
  49. bool _ios130orNewer = true, _ios140orNewer = false, _ios150orNewer = false, _ios160orNewer = false;
  50. bool _unityEngineLoaded = false, _unityEngineInitialized = false, _renderingInited = false, _unityAppReady = false;
  51. static UInt32 _iosMajorVersion = 0;
  52. static UInt32 _iosMinorVersion = 0;
  53. // see if there's a need to do internal player pause/resume handling
  54. //
  55. // Typically the trampoline code should manage this internally, but
  56. // there are use cases, videoplayer, plugin code, etc where the player
  57. // is paused before the internal handling comes relevant. Avoid
  58. // overriding externally managed player pause/resume handling by
  59. // caching the state
  60. bool _wasPausedExternal = false;
  61. // was app "resigned active": some operations do not make sense while app is in background
  62. bool _didResignActive = false;
  63. #if UNITY_SUPPORT_ROTATION
  64. // Required to enable specific orientation for some presentation controllers: see supportedInterfaceOrientationsForWindow below for details
  65. NSInteger _forceInterfaceOrientationMask = 0;
  66. #endif
  67. @implementation UnityAppController
  68. {
  69. UnityEngineLoadState _engineLoadState;
  70. }
  71. @synthesize unityView = _unityView;
  72. @synthesize unityDisplayLink = _displayLink;
  73. @synthesize unityUsesMetalDisplayLink = _usesMetalDisplayLink;
  74. #if UNITY_USES_METAL_DISPLAY_LINK
  75. @synthesize unityMetalDisplayLink = _metalDisplayLink;
  76. #endif
  77. @synthesize rootView = _rootView;
  78. @synthesize rootViewController = _rootController;
  79. @synthesize mainDisplay = _mainDisplay;
  80. @synthesize engineLoadState = _engineLoadState;
  81. @synthesize renderDelegate = _renderDelegate;
  82. @synthesize quitHandler = _quitHandler;
  83. #if UNITY_SUPPORT_ROTATION
  84. @synthesize interfaceOrientation = _curOrientation;
  85. #endif
  86. - (id)init
  87. {
  88. if ((self = _UnityAppController = [super init]))
  89. {
  90. // due to clang issues with generating warning for overriding deprecated methods
  91. // we will simply assert if deprecated methods are present
  92. // NB: methods table is initied at load (before this call), so it is ok to check for override
  93. NSAssert(![self respondsToSelector: @selector(createUnityViewImpl)],
  94. @"createUnityViewImpl is deprecated and will not be called. Override createUnityView"
  95. );
  96. NSAssert(![self respondsToSelector: @selector(createViewHierarchyImpl)],
  97. @"createViewHierarchyImpl is deprecated and will not be called. Override willStartWithViewController"
  98. );
  99. NSAssert(![self respondsToSelector: @selector(createViewHierarchy)],
  100. @"createViewHierarchy is deprecated and will not be implemented. Use createUI"
  101. );
  102. }
  103. return self;
  104. }
  105. - (bool)didResignActive
  106. {
  107. return _didResignActive;
  108. }
  109. - (void)setWindow:(id)object {}
  110. - (UIWindow*)window { return _window; }
  111. - (void)shouldAttachRenderDelegate {}
  112. - (void)preStartUnity {}
  113. - (BOOL)shouldUseMetalDisplayLink
  114. {
  115. // if we start in batchmode (command line argument), we expect to never render to "backbuffer"
  116. // metal display link does not make sense in this case
  117. if (UnityIsBatchmode())
  118. return NO;
  119. // if we start in nographics mode, all rendering is ignored
  120. // metal display link does not make sense in this case
  121. if (![_unityView.layer isKindOfClass: [CAMetalLayer class]])
  122. return NO;
  123. // check if we want metal display link (player settings)
  124. if (!UnityShouldUseMetalDisplayLink())
  125. return NO;
  126. // currently not supported on visionOS
  127. #if PLATFORM_VISIONOS
  128. return NO;
  129. #endif
  130. return YES;
  131. }
  132. - (void)startUnity
  133. {
  134. NSAssert(self.engineLoadState < kUnityEngineLoadStateAppReady, @"[UnityAppController startUnity:] called after Unity has been initialized");
  135. UnityInitApplicationGraphics();
  136. #if !PLATFORM_VISIONOS
  137. // we make sure that first level gets correct display list and orientation
  138. [[DisplayManager Instance] prepareForFirstScene];
  139. #endif
  140. #if PLATFORM_VISIONOS && UNITY_HAS_VISIONOSSDK_2_0
  141. // https://developer.apple.com/documentation/visionos-release-notes/visionos-2-release-notes
  142. // Game controllers can be used to interact with system UI on visionOS.
  143. // Apps built with the visionOS 2 SDK that use the Game Controller
  144. // framework for input in one or more of their views must add an instance
  145. // of GCEventInteraction to those views (UIKit) or apply a
  146. // handlesGameControllerEvents(matching: .gamepad) modifier to those views (SwiftUI).
  147. GCEventInteraction* gamepadInteraction = [[GCEventInteraction alloc] init];
  148. gamepadInteraction.handledEventTypes = GCUIEventTypeGamepad;
  149. NSMutableArray* interactions = [NSMutableArray array];
  150. [interactions addObject:gamepadInteraction];
  151. [interactions addObjectsFromArray:_rootView.interactions];
  152. _rootView.interactions = interactions;
  153. #endif
  154. UnityLoadApplication();
  155. Profiler_InitProfiler();
  156. [self createDisplayLink];
  157. [self showGameUI];
  158. UnitySetPlayerFocus(1);
  159. AVAudioSession* audioSession = [AVAudioSession sharedInstance];
  160. // 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
  161. // to active so we can get outputVolume callbacks. If Unity audio is enabled, FMOD should have already handled all of this AVAudioSession init.
  162. if (!UnityIsAudioManagerAvailableAndEnabled())
  163. {
  164. [audioSession setCategory: AVAudioSessionCategoryAmbient error: nil];
  165. [audioSession setActive: YES error: nil];
  166. }
  167. [audioSession addObserver: self forKeyPath: @"outputVolume" options: 0 context: nil];
  168. UnityUpdateMuteState([audioSession outputVolume] < 0.01f ? 1 : 0);
  169. [self subscribeToThermalChanges];
  170. #if UNITY_REPLAY_KIT_AVAILABLE
  171. void InitUnityReplayKit(); // Classes/Unity/UnityReplayKit.mm
  172. InitUnityReplayKit();
  173. #endif
  174. }
  175. UNITY_EXPORT extern "C" void UnityDestroyDisplayLink()
  176. {
  177. [GetAppController() destroyDisplayLink];
  178. }
  179. UNITY_EXPORT extern "C" void UnityEngineDidQuit(unsigned level)
  180. {
  181. enum class UnityEngineQuitLevel : unsigned
  182. {
  183. Unload = 1,
  184. AppQuit = 2,
  185. };
  186. if (level > static_cast<unsigned>(UnityEngineQuitLevel::AppQuit))
  187. return;
  188. switch (static_cast<UnityEngineQuitLevel>(level))
  189. {
  190. case UnityEngineQuitLevel::Unload:
  191. [GetAppController() downgradeEngineLoadState: kUnityEngineLoadStateRenderingInitialized];
  192. [NSNotificationCenter.defaultCenter postNotificationName: kUnityDidUnload object: nil];
  193. break;
  194. case UnityEngineQuitLevel::AppQuit:
  195. [GetAppController() downgradeEngineLoadState: kUnityEngineLoadStateNotStarted];
  196. [NSNotificationCenter.defaultCenter postNotificationName: kUnityDidQuit object: nil];
  197. _didResignActive = true;
  198. if (GetAppController().quitHandler)
  199. GetAppController().quitHandler();
  200. else
  201. exit(0);
  202. break;
  203. }
  204. }
  205. extern void SensorsCleanup();
  206. UNITY_EXPORT extern "C" void UnityCleanupTrampoline()
  207. {
  208. // Prevent multiple cleanups
  209. if (_UnityAppController == nil)
  210. return;
  211. // Unity view and viewController will not necessary be destroyed right after this function execution.
  212. // We need to ensure that these objects will not receive any callbacks from system during that time.
  213. _UnityAppController.window.rootViewController = nil;
  214. #if PLATFORM_IOS || PLATFORM_VISIONOS
  215. // Stop GCMouse callbacks before detaching: the view can outlive cleanup in UaaL.
  216. [_UnityAppController.unityView teardownIndirectMouseInput];
  217. #endif
  218. [_UnityAppController.unityView removeFromSuperview];
  219. [KeyboardDelegate Destroy];
  220. SensorsCleanup();
  221. Profiler_UninitProfiler();
  222. #if !PLATFORM_VISIONOS
  223. [DisplayManager Destroy];
  224. #endif
  225. // there are two ways we can end up here:
  226. // 1. normal shutdown sequence: let's be fair, in this case ios will just (cleanly) kills everything so we don't care that much
  227. // 2. unity unload (UaaL): in this case, run loop continues to exist.
  228. // Alas on some device/ios-versions, if we invalidate/destroy (metal) display link here, it gets a crash later on
  229. // referencing null pointer in displaylink dispatcher
  230. // so we take the safest route: we just pause display link here. Note that we *never* run unity again after this point
  231. _UnityAppController.unityDisplayLink.paused = YES;
  232. #if UNITY_USES_METAL_DISPLAY_LINK
  233. if (@available(iOS 17.0, tvOS 17.0, *))
  234. _UnityAppController.unityMetalDisplayLink.paused = YES;
  235. #endif
  236. _UnityAppController = nil;
  237. }
  238. #if UNITY_SUPPORT_ROTATION
  239. - (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
  240. {
  241. // No rootViewController is set because we are switching from one view controller to another, all orientations should be enabled
  242. if ([window rootViewController] == nil)
  243. return UIInterfaceOrientationMaskAll;
  244. // During splash screen show phase no forced orientations should be allowed.
  245. // This will prevent unwanted rotation while splash screen is on and application is not yet ready to present (Ex. Fogbugz cases: 1190428, 1269547).
  246. if (self.engineLoadState < kUnityEngineLoadStateAppReady)
  247. return [_rootController supportedInterfaceOrientations];
  248. // Some presentation controllers (e.g. UIImagePickerController) require portrait orientation and will throw exception if it is not supported.
  249. // At the same time enabling all orientations by returning UIInterfaceOrientationMaskAll might cause unwanted orientation change
  250. // (e.g. when using UIActivityViewController to "share to" another application, iOS will use supportedInterfaceOrientations to possibly reorient).
  251. // So to avoid exception we are returning combination of constraints for root view controller and orientation requested by iOS.
  252. // _forceInterfaceOrientationMask is updated in willChangeStatusBarOrientation, which is called if some presentation controller insists on orientation change.
  253. return [[window rootViewController] supportedInterfaceOrientations] | _forceInterfaceOrientationMask;
  254. }
  255. - (void)application:(UIApplication*)application willChangeStatusBarOrientation:(UIInterfaceOrientation)newStatusBarOrientation duration:(NSTimeInterval)duration
  256. {
  257. // Setting orientation mask which is requested by iOS: see supportedInterfaceOrientationsForWindow above for details
  258. _forceInterfaceOrientationMask = 1 << newStatusBarOrientation;
  259. }
  260. #endif
  261. #if UNITY_USES_REMOTE_NOTIFICATIONS
  262. - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
  263. {
  264. AppController_SendNotificationWithArg(kUnityDidRegisterForRemoteNotificationsWithDeviceToken, deviceToken);
  265. }
  266. #if !PLATFORM_TVOS
  267. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
  268. {
  269. AppController_SendNotificationWithArg(kUnityDidReceiveRemoteNotification, userInfo);
  270. if (handler)
  271. {
  272. handler(UIBackgroundFetchResultNoData);
  273. }
  274. }
  275. #endif
  276. - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
  277. {
  278. AppController_SendNotificationWithArg(kUnityDidFailToRegisterForRemoteNotificationsWithError, error);
  279. // alas people do not check remote notification error through api (which is clunky, i agree) so log here to have at least some visibility
  280. ::printf("\nFailed to register for remote notifications:\n%s\n\n", [[error localizedDescription] UTF8String]);
  281. }
  282. #endif
  283. // UIApplicationOpenURLOptionsKey was added only in ios10 sdk, while we still support ios9 sdk
  284. - (BOOL)application:(UIApplication*)app openURL:(NSURL*)url options:(NSDictionary<NSString*, id>*)options
  285. {
  286. id sourceApplication = options[UIApplicationOpenURLOptionsSourceApplicationKey], annotation = options[UIApplicationOpenURLOptionsAnnotationKey];
  287. NSMutableDictionary<NSString*, id>* notifData = [NSMutableDictionary dictionaryWithCapacity: 3];
  288. if (url)
  289. {
  290. notifData[@"url"] = url;
  291. UnitySetAbsoluteURL(url.absoluteString.UTF8String);
  292. }
  293. if (sourceApplication) notifData[@"sourceApplication"] = sourceApplication;
  294. if (annotation) notifData[@"annotation"] = annotation;
  295. AppController_SendNotificationWithArg(kUnityOnOpenURL, notifData);
  296. return YES;
  297. }
  298. - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring> > * _Nullable restorableObjects))restorationHandler
  299. {
  300. NSURL* url = userActivity.webpageURL;
  301. if (url)
  302. UnitySetAbsoluteURL(url.absoluteString.UTF8String);
  303. return YES;
  304. }
  305. - (BOOL)application:(UIApplication*)application willFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  306. {
  307. AppController_SendNotificationWithArg(kUnityWillFinishLaunchingWithOptions, launchOptions);
  308. NSURL* url = [self extractURLFromLaunchOptions: launchOptions];
  309. if (url != nil)
  310. {
  311. [self initUnityApplicationNoGraphics];
  312. UnitySetAbsoluteURL(url.absoluteString.UTF8String);
  313. }
  314. return YES;
  315. }
  316. // Helper method to extract URL from launch options
  317. - (NSURL*)extractURLFromLaunchOptions:(NSDictionary*)launchOptions
  318. {
  319. // Check for the direct launch URL
  320. NSURL* url = launchOptions[UIApplicationLaunchOptionsURLKey];
  321. if (url != nil)
  322. {
  323. return url;
  324. }
  325. // Check for the user activity dictionary and URL from user activity
  326. NSUserActivity* userActivity = launchOptions[UIApplicationLaunchOptionsUserActivityDictionaryKey][@"UIApplicationLaunchOptionsUserActivityKey"];
  327. if (userActivity != nil && [userActivity.activityType isEqualToString: NSUserActivityTypeBrowsingWeb])
  328. {
  329. url = userActivity.webpageURL;
  330. if (url != nil)
  331. {
  332. return url;
  333. }
  334. }
  335. return nil;
  336. }
  337. - (UIWindowScene*)pickStartupWindowScene:(NSSet<UIScene*>*)scenes
  338. {
  339. // if we have scene with UISceneActivationStateForegroundActive - pick it
  340. // otherwise UISceneActivationStateForegroundInactive will work
  341. // it will be the scene going into active state
  342. // if there were no active/inactive scenes (only background) we should allow background scene
  343. // this might happen in some cases with native plugins doing "things"
  344. UIWindowScene *foregroundScene = nil, *backgroundScene = nil;
  345. for (UIScene* scene in scenes)
  346. {
  347. if (![scene isKindOfClass: [UIWindowScene class]])
  348. continue;
  349. UIWindowScene* windowScene = (UIWindowScene*)scene;
  350. if (scene.activationState == UISceneActivationStateForegroundActive)
  351. return windowScene;
  352. if (scene.activationState == UISceneActivationStateForegroundInactive)
  353. foregroundScene = windowScene;
  354. else if (scene.activationState == UISceneActivationStateBackground)
  355. backgroundScene = windowScene;
  356. }
  357. return foregroundScene ? foregroundScene : backgroundScene;
  358. }
  359. - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  360. {
  361. ::printf("-> applicationDidFinishLaunching()\n");
  362. // make sure orientation notifications are sent
  363. #if !PLATFORM_TVOS && !PLATFORM_VISIONOS
  364. if ([UIDevice currentDevice].generatesDeviceOrientationNotifications == NO)
  365. [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  366. #endif
  367. return YES;
  368. }
  369. - (void)initUnityApplicationNoGraphics
  370. {
  371. if ([self advanceEngineLoadState: kUnityEngineLoadStateMinimal])
  372. UnityInitApplicationNoGraphics(UnityDataBundleDir());
  373. }
  374. - (void)initUnityWithScene:(UIWindowScene*)scene
  375. {
  376. if (self.engineLoadState >= kUnityEngineLoadStateCoreInitialized)
  377. return;
  378. // basic unity init
  379. [self initUnityApplicationNoGraphics];
  380. // initUnityApplicationNoGraphics progresses the state & does initialization if necessary
  381. // so the next state bump has to be after it to not skip the init part
  382. [self advanceEngineLoadState: kUnityEngineLoadStateCoreInitialized];
  383. // we want to initialize DisplayManager first, since unity view might need it on creation
  384. [DisplayManager Initialize];
  385. // init main window
  386. if (scene == nil)
  387. _window = [[UIWindow alloc] init];
  388. else
  389. _window = [[UIWindow alloc] initWithWindowScene: scene];
  390. // init unity view
  391. [self selectRenderingAPI];
  392. [UnityRenderingView InitializeForAPI: self.renderingAPI];
  393. _unityView = [self createUnityView];
  394. // connect main display with window and unity view
  395. _mainDisplay = [DisplayManager Instance].mainDisplay;
  396. [_mainDisplay createWithWindow: _window andView: _unityView];
  397. // create UI hierarchy, and proceed with unity graphics init
  398. [self createUI];
  399. [self preStartUnity];
  400. // if you wont use keyboard you may comment it out at save some memory
  401. [KeyboardDelegate Initialize];
  402. #if UNITY_DEVELOPER_BUILD && !PLATFORM_VISIONOS
  403. // Causes a black screen after splash screen, but would deadlock if waiting for manged debugger otherwise
  404. [self performSelector: @selector(startUnity) withObject: nil afterDelay: 0];
  405. #else
  406. [self startUnity];
  407. #endif
  408. }
  409. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context
  410. {
  411. if ([keyPath isEqual: @"outputVolume"])
  412. {
  413. UnityUpdateMuteState([[AVAudioSession sharedInstance] outputVolume] < 0.01f ? 1 : 0);
  414. }
  415. }
  416. - (void)applicationDidEnterBackground:(UIApplication*)application
  417. {
  418. ::printf("-> applicationDidEnterBackground()\n");
  419. [self pauseDisplayLink];
  420. UnityCancelTouches();
  421. #if PLATFORM_VISIONOS
  422. if (UnityIsFocused())
  423. UnitySetPlayerFocus(0);
  424. if (!UnityShouldRunInBackground() && !UnityIsPaused())
  425. UnityPause(1);
  426. #endif
  427. }
  428. - (void)applicationWillEnterForeground:(UIApplication*)application
  429. {
  430. ::printf("-> applicationWillEnterForeground()\n");
  431. [self unpauseDisplayLink];
  432. // applicationWillEnterForeground: might sometimes arrive *before* actually initing unity (e.g. locking on startup)
  433. if (self.engineLoadState >= kUnityEngineLoadStateAppReady)
  434. {
  435. #if PLATFORM_VISIONOS
  436. if (!UnityIsFocused())
  437. UnitySetPlayerFocus(1);
  438. if (UnityIsPaused() && _wasPausedExternal == false)
  439. UnityPause(0);
  440. #endif
  441. // if we were showing video before going to background - the view size may be changed while we are in background
  442. [GetAppController().unityView recreateRenderingSurfaceIfNeeded];
  443. }
  444. }
  445. - (void)applicationDidBecomeActive:(UIApplication*)application
  446. {
  447. ::printf("-> applicationDidBecomeActive()\n");
  448. [self removeSnapshotViewController];
  449. if (self.engineLoadState >= kUnityEngineLoadStateAppReady)
  450. {
  451. // Pause/unpause is handled by repaint if CompositorLayer is in use
  452. if (self.usingCompositorLayer == NO && UnityIsPaused() && _wasPausedExternal == false)
  453. {
  454. UnityWillResume();
  455. UnityPause(0);
  456. }
  457. if (_wasPausedExternal)
  458. {
  459. if (UnityIsFullScreenPlaying())
  460. TryResumeFullScreenVideo();
  461. }
  462. // need to do this with delay because FMOD restarts audio in AVAudioSessionInterruptionNotification handler
  463. [self performSelector: @selector(updateUnityAudioOutput) withObject: nil afterDelay: 0.1];
  464. // In case we got to applicationWillEnterForeground before Unity was initialized (or any other edge case)
  465. if (!UnityIsFocused())
  466. UnitySetPlayerFocus(1);
  467. }
  468. else
  469. {
  470. UIWindowScene *scene = [self pickStartupWindowScene:application.connectedScenes];
  471. [self initUnityWithScene: scene];
  472. }
  473. _didResignActive = false;
  474. }
  475. - (void)updateUnityAudioOutput
  476. {
  477. UnityUpdateMuteState([[AVAudioSession sharedInstance] outputVolume] < 0.01f ? 1 : 0);
  478. }
  479. - (void)addSnapshotViewController
  480. {
  481. if (!_didResignActive || self->_snapshotViewController)
  482. {
  483. return;
  484. }
  485. UIView* snapshotView = [self createSnapshotView];
  486. if (snapshotView != nil)
  487. {
  488. UIViewController* snapshotViewController = [AllocUnityViewController() init];
  489. snapshotViewController.modalPresentationStyle = UIModalPresentationFullScreen;
  490. snapshotViewController.view = snapshotView;
  491. [self->_rootController presentViewController: snapshotViewController animated: false completion: nil];
  492. self->_snapshotViewController = snapshotViewController;
  493. }
  494. }
  495. - (void)removeSnapshotViewController
  496. {
  497. // do this on the main queue async so that if we try to create one
  498. // and remove in the same frame, this always happens after in the same queue
  499. dispatch_async(dispatch_get_main_queue(), ^{
  500. if (self->_snapshotViewController)
  501. {
  502. // we've got a view on top of the snapshot view (3rd party plugin/social media login etc).
  503. if (self->_snapshotViewController.presentedViewController)
  504. {
  505. [self performSelector: @selector(removeSnapshotViewController) withObject: nil afterDelay: 0.05];
  506. return;
  507. }
  508. [self->_snapshotViewController dismissViewControllerAnimated: NO completion: nil];
  509. self->_snapshotViewController = nil;
  510. // Make sure that the keyboard input field regains focus after the application becomes active.
  511. [[KeyboardDelegate Instance] becomeFirstResponder];
  512. }
  513. });
  514. }
  515. - (void)applicationWillResignActive:(UIApplication*)application
  516. {
  517. ::printf("-> applicationWillResignActive()\n");
  518. if (self.engineLoadState >= kUnityEngineLoadStateAppReady)
  519. {
  520. // This should be covered by applicationDidEnterBackground but double-check just in case we missed it
  521. if (UnityIsFocused())
  522. UnitySetPlayerFocus(0);
  523. // signal unity that the frame rendering have ended
  524. // as we will not get the callback from the display link current frame
  525. UnityDisplayLinkCallback(0);
  526. _wasPausedExternal = UnityIsPaused();
  527. // Pause/unpause is handled by repaint if CompositorLayer is in use
  528. if (self.usingCompositorLayer == NO && _wasPausedExternal == false)
  529. {
  530. // Pause Unity only if we don't need special background processing
  531. // otherwise batched player loop can be called to run user scripts.
  532. if (!UnityGetUseCustomAppBackgroundBehavior())
  533. {
  534. #if UNITY_SNAPSHOT_VIEW_ON_APPLICATION_PAUSE
  535. // we cannot repaint without drawable given to us by CAMetalDisplayLink
  536. // TODO: there should be a way to handle this somehow
  537. if(!self.unityUsesMetalDisplayLink)
  538. {
  539. // Force player to do one more frame, so scripts get a chance to render custom screen for minimized app in task manager.
  540. // NB: UnityWillPause will schedule OnApplicationPause message, which will be sent normally inside repaint (unity player loop)
  541. // NB: We will actually pause after the loop (when calling UnityPause).
  542. UnityWillPause();
  543. [self repaint];
  544. [self addSnapshotViewController];
  545. }
  546. #endif
  547. #if PLATFORM_VISIONOS
  548. if (!UnityShouldRunInBackground())
  549. UnityPause(1);
  550. #else
  551. UnityPause(1);
  552. #endif
  553. }
  554. }
  555. }
  556. _didResignActive = true;
  557. }
  558. - (void)applicationDidReceiveMemoryWarning:(UIApplication*)application
  559. {
  560. UnityLowMemory();
  561. }
  562. - (void)applicationWillTerminate:(UIApplication*)application
  563. {
  564. ::printf("-> applicationWillTerminate()\n");
  565. // Only clean up if Unity has finished initializing, else the clean up process will crash,
  566. // this happens if the app is force closed immediately after opening it.
  567. if (self.engineLoadState >= kUnityEngineLoadStateAppReady)
  568. {
  569. // make sure that we are in a "unity cannot be touched" state
  570. // if there was some complex UI shown when terminating, we can get extra UI calls from iOS after applicationWillTerminate:
  571. // and we want to make sure we never do anything touching unity runtime at this point
  572. _engineLoadState = kUnityEngineLoadStateMinimal;
  573. // keep "old" way of tracking state synced
  574. _unityAppReady = _renderingInited = _unityEngineInitialized = false;
  575. _didResignActive = true;
  576. UnityCleanup();
  577. UnityCleanupTrampoline();
  578. }
  579. }
  580. - (void)application:(UIApplication*)application handleEventsForBackgroundURLSession:(nonnull NSString *)identifier completionHandler:(nonnull void (^)())completionHandler
  581. {
  582. NSDictionary* arg = @{identifier: completionHandler};
  583. AppController_SendNotificationWithArg(kUnityHandleEventsForBackgroundURLSession, arg);
  584. }
  585. // advance the load state to newState, if it's not there or higher yet
  586. // returns YES if state was less than newState
  587. // returns NO if previous state was already the requested one or even higher than that
  588. - (BOOL)advanceEngineLoadState:(UnityEngineLoadState)newState
  589. {
  590. if (_engineLoadState >= newState)
  591. return NO;
  592. _engineLoadState = newState;
  593. // Old individual variables; fall-through because higher level also has to set all lower ones
  594. switch (_engineLoadState)
  595. {
  596. case kUnityEngineLoadStateAppReady:
  597. _unityAppReady = true;
  598. case kUnityEngineLoadStateRenderingInitialized:
  599. _renderingInited = true;
  600. case kUnityEngineLoadStateCoreInitialized:
  601. _unityEngineInitialized = true;
  602. case kUnityEngineLoadStateMinimal:
  603. _unityEngineLoaded = true;
  604. case kUnityEngineLoadStateNotStarted:
  605. break;
  606. }
  607. return YES;
  608. }
  609. // the opposite of advanceEngineLoadState:
  610. - (BOOL)downgradeEngineLoadState:(UnityEngineLoadState)newState
  611. {
  612. if (newState >= _engineLoadState)
  613. return NO;
  614. _engineLoadState = newState;
  615. switch (_engineLoadState)
  616. {
  617. case kUnityEngineLoadStateNotStarted:
  618. _unityEngineLoaded = false;
  619. case kUnityEngineLoadStateMinimal:
  620. _unityEngineInitialized = false;
  621. case kUnityEngineLoadStateCoreInitialized:
  622. _renderingInited = false;
  623. case kUnityEngineLoadStateRenderingInitialized:
  624. _unityAppReady = false;
  625. case kUnityEngineLoadStateAppReady:
  626. break;
  627. }
  628. return YES;
  629. }
  630. @end
  631. void AppController_SendNotification(NSString* name)
  632. {
  633. [[NSNotificationCenter defaultCenter] postNotificationName: name object: GetAppController()];
  634. }
  635. void AppController_SendNotificationWithArg(NSString* name, id arg)
  636. {
  637. [[NSNotificationCenter defaultCenter] postNotificationName: name object: GetAppController() userInfo: arg];
  638. }
  639. void AppController_SendUnityViewControllerNotification(NSString* name)
  640. {
  641. [[NSNotificationCenter defaultCenter] postNotificationName: name object: UnityGetGLViewController()];
  642. }
  643. UNITY_EXPORT extern "C" UIWindow* UnityGetMainWindow() { return GetAppController().mainDisplay.window; }
  644. UNITY_EXPORT extern "C" UIViewController* UnityGetGLViewController() { return GetAppController().rootViewController; }
  645. UNITY_EXPORT extern "C" UnityView* UnityGetUnityView() { return GetAppController().unityView; }
  646. UNITY_EXPORT extern "C" UIView* UnityGetGLView() { return UnityGetUnityView(); }
  647. UNITY_EXPORT extern "C" ScreenOrientation UnityCurrentOrientation() { return GetAppController().unityView.contentOrientation; }
  648. bool LogToNSLogHandler(LogType logType, const char* log, va_list list)
  649. {
  650. NSString *formatString = [NSString stringWithUTF8String:log];
  651. NSString *formatted = [[NSString alloc] initWithFormat:formatString arguments:list];
  652. os_log_with_type(OS_LOG_DEFAULT, OS_LOG_TYPE_DEFAULT, "%{public}@", formatted);
  653. return true;
  654. }
  655. static void AddNewAPIImplIfNeeded();
  656. // From https://stackoverflow.com/questions/4744826/detecting-if-ios-app-is-run-in-debugger
  657. static bool isDebuggerAttachedToConsole(void)
  658. // Returns true if the current process is being debugged (either
  659. // running under the debugger or has a debugger attached post facto).
  660. {
  661. int junk;
  662. int mib[4];
  663. struct kinfo_proc info;
  664. size_t size;
  665. // Initialize the flags so that, if sysctl fails for some bizarre
  666. // reason, we get a predictable result.
  667. info.kp_proc.p_flag = 0;
  668. // Initialize mib, which tells sysctl the info we want, in this case
  669. // we're looking for information about a specific process ID.
  670. mib[0] = CTL_KERN;
  671. mib[1] = KERN_PROC;
  672. mib[2] = KERN_PROC_PID;
  673. mib[3] = getpid();
  674. // Call sysctl.
  675. size = sizeof(info);
  676. junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
  677. assert(junk == 0);
  678. // We're being debugged if the P_TRACED flag is set.
  679. // But if we are starting app on device (and make debugger wait and attach after start)
  680. // it will NOT connect stout (only stderr, used by nslog)
  681. // Hence we also check that stoud is rerouted
  682. return ((info.kp_proc.p_flag & P_TRACED) != 0) && isatty(STDOUT_FILENO);
  683. }
  684. void UnityInitTrampoline()
  685. {
  686. InitCrashHandling();
  687. NSString* version = [[UIDevice currentDevice] systemVersion];
  688. const char* versionStr = version.UTF8String;
  689. char* dot = NULL;
  690. UInt32 major = (UInt32)std::strtoul(versionStr, &dot, 10);
  691. UInt32 minor = 0;
  692. if (major > 0 && *dot == '.')
  693. minor = (UInt32)std::strtoul(++dot, NULL, 10);
  694. _iosMajorVersion = major;
  695. _iosMinorVersion = minor;
  696. #define CHECK_VER(s) [version compare: s options: NSNumericSearch] != NSOrderedAscending
  697. _ios140orNewer = CHECK_VER(@"14.0"); _ios150orNewer = CHECK_VER(@"15.0");
  698. _ios160orNewer = CHECK_VER(@"16.0");
  699. #undef CHECK_VER
  700. AddNewAPIImplIfNeeded();
  701. #if !TARGET_OS_SIMULATOR
  702. // Use NSLog logging if a debugger is not attached, otherwise we write to stdout.
  703. if (!isDebuggerAttachedToConsole())
  704. UnitySetLogEntryHandler(LogToNSLogHandler);
  705. #endif
  706. }
  707. extern "C" bool UnityiOS81orNewer() { return _ios81orNewer; }
  708. extern "C" bool UnityiOS82orNewer() { return _ios82orNewer; }
  709. extern "C" bool UnityiOS90orNewer() { return _ios90orNewer; }
  710. extern "C" bool UnityiOS91orNewer() { return _ios91orNewer; }
  711. extern "C" bool UnityiOS100orNewer() { return _ios100orNewer; }
  712. extern "C" bool UnityiOS101orNewer() { return _ios101orNewer; }
  713. extern "C" bool UnityiOS102orNewer() { return _ios102orNewer; }
  714. extern "C" bool UnityiOS103orNewer() { return _ios103orNewer; }
  715. extern "C" bool UnityiOS110orNewer() { return _ios110orNewer; }
  716. extern "C" bool UnityiOS111orNewer() { return _ios111orNewer; }
  717. extern "C" bool UnityiOS112orNewer() { return _ios112orNewer; }
  718. extern "C" bool UnityiOS130orNewer() { return _ios130orNewer; }
  719. extern "C" bool UnityiOS140orNewer() { return _ios140orNewer; }
  720. extern "C" bool UnityiOS150orNewer() { return _ios150orNewer; }
  721. extern "C" bool UnityiOS160orNewer() { return _ios160orNewer; }
  722. UNITY_EXPORT extern "C" bool UnityiOSVersionIsAtLeast(uint32_t major, uint32_t minor)
  723. {
  724. if (major < _iosMajorVersion)
  725. return true;
  726. if (major > _iosMajorVersion)
  727. return false;
  728. return minor <= _iosMinorVersion;
  729. }
  730. // sometimes apple adds new api with obvious fallback on older ios.
  731. // in that case we simply add these functions ourselves to simplify code
  732. static void AddNewAPIImplIfNeeded()
  733. {
  734. #if !PLATFORM_VISIONOS
  735. if (![[UIScreen class] instancesRespondToSelector: @selector(maximumFramesPerSecond)])
  736. {
  737. IMP UIScreen_MaximumFramesPerSecond_IMP = imp_implementationWithBlock(^NSInteger(id _self) {
  738. return 60;
  739. });
  740. class_replaceMethod([UIScreen class], @selector(maximumFramesPerSecond), UIScreen_MaximumFramesPerSecond_IMP, UIScreen_maximumFramesPerSecond_Enc);
  741. }
  742. if (![[UIView class] instancesRespondToSelector: @selector(safeAreaInsets)])
  743. {
  744. IMP UIView_SafeAreaInsets_IMP = imp_implementationWithBlock(^UIEdgeInsets(id _self) {
  745. return UIEdgeInsetsZero;
  746. });
  747. class_replaceMethod([UIView class], @selector(safeAreaInsets), UIView_SafeAreaInsets_IMP, UIView_safeAreaInsets_Enc);
  748. }
  749. #endif
  750. }