UnityView.mm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. #include "UnityView.h"
  2. #include "UnityAppController.h"
  3. #include "UnityAppController+Rendering.h"
  4. #include "OrientationSupport.h"
  5. #include "Unity/DisplayManager.h"
  6. #include "Unity/ObjCRuntime.h"
  7. #include "UI/Keyboard.h"
  8. #import <Metal/Metal.h>
  9. #if PLATFORM_IOS || PLATFORM_VISIONOS
  10. @interface UnityView (iOSScrollWheel)
  11. - (void)setupIndirectMouseInput;
  12. - (void)teardownIndirectMouseInput;
  13. @end
  14. #endif
  15. @implementation UnityView
  16. {
  17. CGSize _surfaceSize;
  18. }
  19. @synthesize contentOrientation = _curOrientation;
  20. // we need to support both CADisplayLink and CAMetalDisplayLink
  21. // alas they have a bit of an "opposite" approach to backbuffer (drawable) management so we have several complications
  22. // - for CADisplayLink the callback is more or less just "oh it is time: you asked to be poked every N ms"
  23. // we will query drawable from the view's layer (we delay this as much as possible to not introduce sync point)
  24. // so we should NOT tweak drawable size at "random" times
  25. // our approach was:
  26. // whenever iOS is telling us that view should be resized, we poke unity native side
  27. // * this is a bit more complicated: we were doing so only in layoutSubviews and some corner cases with orientation change
  28. // and on the next displaylink callback we recreate the "connection" between native side and trampoline (using "new" drawable extents)
  29. //
  30. // - for CAMetalDisplayLink the callback gives us a ready CAMetalDrawable
  31. // that is all the syncing is handled by iOS (this is very good) and it now acts like a compositor of sorts
  32. // there are several caveats though (read above: we have a "unity approach" already in place)
  33. // 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)
  34. // second: we should update drawable size whenever iOS is telling us that the view bounds are tweaked
  35. // recall that we get ready-made drawable in the callback - at this point we can not tweak anything regarding drawable
  36. // and yet we should delay updating unity on "backbuffer" change, since it might have drawable of the old size currently
  37. //
  38. // So our plan is:
  39. // - override "change bounds" methods to track drawable size (with _surfaceSize)
  40. // note that we will update drawableSize immediately when using CAMetalDisplayLink, but not when using CADisplayLink
  41. // - on displaylink callback as before we will update connection to unity render surfaces
  42. // when using CADisplayLink we will also update drawableSize here before poking unity
  43. //
  44. // this will do update drawable size to agree with bounds
  45. // CAMetalDisplayLink: will be called from onUpdateDrawableSize, called in all "something view related changed" callbacks
  46. // CADisplayLink: we will call it from the display link callback, to not touch drawableSize while we are potentially rendering to drawable
  47. // using old extents
  48. - (void)updateLayerDrawableSizeFromBounds
  49. {
  50. if (![self.layer isKindOfClass: [CAMetalLayer class]])
  51. {
  52. // UnityView either has CAMetalLayer backing, when running on Metal, or CALayer, when running in 'nographics' mode
  53. return;
  54. }
  55. CAMetalLayer* metalLayer = (CAMetalLayer*)self.layer;
  56. @synchronized(metalLayer)
  57. {
  58. const CGSize size = self.bounds.size;
  59. const float scale = self.contentScaleFactor;
  60. const CGSize systemRenderSize = CGSizeMake(::roundf(size.width * scale), ::roundf(size.height * scale));
  61. if (systemRenderSize.width <= 0 || systemRenderSize.height <= 0)
  62. {
  63. _shouldRecreateView = NO;
  64. }
  65. else if (systemRenderSize.width == metalLayer.drawableSize.width && systemRenderSize.height == metalLayer.drawableSize.height)
  66. {
  67. _shouldRecreateView = NO;
  68. }
  69. else
  70. {
  71. metalLayer.drawableSize = systemRenderSize;
  72. _shouldRecreateView = YES;
  73. }
  74. }
  75. }
  76. - (void)onUpdateDrawableSize
  77. {
  78. // when using metal display link, update drawable size immediately so that we are getting callback with correct size
  79. // when using old display link we will do this on frame start along with updating proxy textures (so that they all agree)
  80. if(GetAppController().unityUsesMetalDisplayLink)
  81. [self updateLayerDrawableSizeFromBounds];
  82. }
  83. // this reports "backbuffer" update to unity: this should be done right before player loop
  84. - (void)updateUnityBackbufferSize
  85. {
  86. const CGSize size = self.bounds.size;
  87. // this is needed for CADisplayLink handling since in this case we do not track view extents changes
  88. if (size.width != _surfaceSize.width || size.height != _surfaceSize.height)
  89. _shouldRecreateView = YES;
  90. _surfaceSize = size;
  91. const float scale = self.contentScaleFactor;
  92. const CGSize systemRenderSize = CGSizeMake(::roundf(size.width * scale), ::roundf(size.height * scale));
  93. _curOrientation = (ScreenOrientation)UnityReportResizeView((unsigned)systemRenderSize.width, (unsigned)systemRenderSize.height, _curOrientation);
  94. ReportSafeAreaChangeForView(self);
  95. }
  96. // this was part of public interface, so keep it around just in case
  97. #pragma clang diagnostic push
  98. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  99. - (void)boundsUpdated
  100. {
  101. [self updateUnityBackbufferSize];
  102. }
  103. #pragma clang diagnostic pop
  104. - (void)initImpl:(CGRect)frame scaleFactor:(CGFloat)scale
  105. {
  106. #if !PLATFORM_TVOS
  107. self.multipleTouchEnabled = YES;
  108. self.exclusiveTouch = YES;
  109. #endif
  110. self.contentScaleFactor = scale;
  111. self.skipRendering = NO;
  112. #if PLATFORM_TVOS
  113. _curOrientation = UNITY_TVOS_ORIENTATION;
  114. #elif PLATFORM_VISIONOS
  115. _curOrientation = UNITY_VISIONOS_ORIENTATION;
  116. #endif
  117. [self updateUnityBackbufferSize];
  118. #if PLATFORM_IOS || PLATFORM_VISIONOS
  119. [self setupIndirectMouseInput];
  120. #endif
  121. }
  122. - (id)initWithFrame:(CGRect)frame scaleFactor:(CGFloat)scale;
  123. {
  124. if ((self = [super initWithFrame: frame]))
  125. [self initImpl: frame scaleFactor: scale];
  126. return self;
  127. }
  128. - (id)initWithFrame:(CGRect)frame
  129. {
  130. if ((self = [super initWithFrame: frame]))
  131. [self initImpl: frame scaleFactor: 1.0f];
  132. return self;
  133. }
  134. - (id)initFromMainScreen
  135. {
  136. #if !PLATFORM_VISIONOS
  137. CGRect frame = [UIScreen mainScreen].bounds;
  138. CGFloat scale = UnityScreenScaleFactor([UIScreen mainScreen]);
  139. #else
  140. CGRect frame = CGRectMake(0.0f, 0.0f, 1920.0f, 1080.0f);
  141. CGFloat scale = 1.0f;
  142. #endif
  143. if ((self = [super initWithFrame: frame]))
  144. [self initImpl: frame scaleFactor: scale];
  145. return self;
  146. }
  147. - (void)dealloc
  148. {
  149. #if PLATFORM_IOS || PLATFORM_VISIONOS
  150. [self teardownIndirectMouseInput];
  151. #endif
  152. }
  153. - (void)resumeRendering
  154. {
  155. self.skipRendering = NO;
  156. }
  157. - (void)recreateRenderingSurfaceIfNeeded
  158. {
  159. // when using metal display link, update drawable size immediately so that we are getting callback with correct size
  160. // when using old display link we will do this on frame start along with updating proxy textures (so that they all agree)
  161. if(!GetAppController().unityUsesMetalDisplayLink)
  162. [self updateLayerDrawableSizeFromBounds];
  163. [self updateUnityBackbufferSize];
  164. unsigned requestedW, requestedH; UnityGetRenderingResolution(&requestedW, &requestedH);
  165. int requestedMSAA = UnityGetDesiredMSAASampleCount(1);
  166. int requestedSRGB = UnityGetSRGBRequested();
  167. int requestedWideColor = UnityGetWideColorRequested();
  168. int requestedHDR = UnityGetHDRModeRequested();
  169. int requestedMemorylessDepth = UnityMetalMemorylessDepth();
  170. UnityDisplaySurfaceBase* surf = GetMainDisplaySurface();
  171. if (_shouldRecreateView == YES
  172. || surf->targetW != requestedW || surf->targetH != requestedH
  173. || surf->disableDepthAndStencil != UnityDisableDepthAndStencilBuffers()
  174. || surf->msaaSamples != requestedMSAA
  175. || surf->srgb != requestedSRGB
  176. || surf->wideColor != requestedWideColor
  177. || surf->hdr != requestedHDR
  178. || surf->memorylessDepth != requestedMemorylessDepth
  179. )
  180. {
  181. [self recreateRenderingSurface];
  182. }
  183. }
  184. - (void)recreateRenderingSurface
  185. {
  186. auto controller = GetAppController();
  187. if (controller.engineLoadState >= kUnityEngineLoadStateRenderingInitialized)
  188. {
  189. unsigned requestedW, requestedH;
  190. UnityGetRenderingResolution(&requestedW, &requestedH);
  191. RenderingSurfaceParams params =
  192. {
  193. .msaaSampleCount = UnityGetDesiredMSAASampleCount(1),
  194. .renderW = (int)requestedW,
  195. .renderH = (int)requestedH,
  196. .srgb = UnityGetSRGBRequested(),
  197. .wideColor = UnityGetWideColorRequested(),
  198. .hdr = UnityGetHDRModeRequested(),
  199. .metalFramebufferOnly = UnityMetalFramebufferOnly(),
  200. .metalMemorylessDepth = UnityMetalMemorylessDepth(),
  201. .disableDepthAndStencil = UnityDisableDepthAndStencilBuffers(),
  202. };
  203. APP_CONTROLLER_RENDER_PLUGIN_METHOD_ARG(onBeforeMainDisplaySurfaceRecreate, &params);
  204. [GetMainDisplay() recreateSurface: params];
  205. APP_CONTROLLER_RENDER_PLUGIN_METHOD(onAfterMainDisplaySurfaceRecreate);
  206. // TODO: it should be done better
  207. if ( controller.engineLoadState >= kUnityEngineLoadStateAppReady && !GetAppController().unityUsesMetalDisplayLink
  208. && (_viewIsRotating || UnityIsPaused()))
  209. {
  210. UnityDisplayLinkCallback(GetAppController().unityDisplayLink.timestamp);
  211. UnityRepaint();
  212. id<MTLCommandBuffer> cb = [UnityGetMetalCommandQueue() commandBuffer];
  213. cb.label = @"Present";
  214. [[DisplayManager Instance] presentWith:cb];
  215. [cb commit];
  216. }
  217. }
  218. _shouldRecreateView = NO;
  219. }
  220. - (void)safeAreaInsetsDidChange
  221. {
  222. ReportSafeAreaChangeForView(self);
  223. }
  224. - (void)layoutSubviews
  225. {
  226. [super layoutSubviews];
  227. [self onUpdateDrawableSize];
  228. [[KeyboardDelegate Instance] layoutSubviews];
  229. for (UIView* subView in self.subviews)
  230. {
  231. if ([subView respondsToSelector: @selector(onUnityUpdateViewLayout)])
  232. [subView performSelector: @selector(onUnityUpdateViewLayout)];
  233. }
  234. }
  235. - (void)setContentScaleFactor:(CGFloat)contentScaleFactor
  236. {
  237. [super setContentScaleFactor:contentScaleFactor];
  238. [self onUpdateDrawableSize];
  239. }
  240. - (void)setFrame:(CGRect)frame
  241. {
  242. [super setFrame:frame];
  243. [self onUpdateDrawableSize];
  244. }
  245. - (void)setBounds:(CGRect)bounds
  246. {
  247. [super setBounds:bounds];
  248. [self onUpdateDrawableSize];
  249. }
  250. @end
  251. @implementation UnityView (Deprecated)
  252. - (void)recreateGLESSurfaceIfNeeded { [self recreateRenderingSurfaceIfNeeded]; }
  253. - (void)recreateGLESSurface { [self recreateRenderingSurface]; }
  254. @end
  255. static Class UnityRenderingView_LayerClassMTL(id self_, SEL _cmd)
  256. {
  257. return NSClassFromString(@"CAMetalLayer");
  258. }
  259. static Class UnityRenderingView_LayerClassNULL(id self_, SEL _cmd)
  260. {
  261. return NSClassFromString(@"CALayer");
  262. }
  263. @implementation UnityRenderingView
  264. + (Class)layerClass
  265. {
  266. return nil;
  267. }
  268. + (void)InitializeForAPI:(UnityRenderingAPI)api
  269. {
  270. IMP layerClassImpl = api == apiMetal ? (IMP)UnityRenderingView_LayerClassMTL : (IMP)UnityRenderingView_LayerClassNULL;
  271. class_replaceMethod(object_getClass([UnityRenderingView class]), @selector(layerClass), layerClassImpl, UIView_LayerClass_Enc);
  272. }
  273. @end
  274. void ReportSafeAreaChangeForView(UIView* view)
  275. {
  276. CGRect safeArea = ComputeSafeArea(view);
  277. UnityReportSafeAreaChange(safeArea.origin.x, safeArea.origin.y,
  278. safeArea.size.width, safeArea.size.height);
  279. #if !PLATFORM_VISIONOS
  280. if (UnityDeviceHasCutout())
  281. {
  282. CGSize cutoutSizeRatio = GetCutoutToScreenRatio();
  283. if (!CGSizeEqualToSize(CGSizeZero, cutoutSizeRatio))
  284. {
  285. const float w = ([UIScreen mainScreen].nativeBounds.size.width * cutoutSizeRatio.width);
  286. const float h = ([UIScreen mainScreen].nativeBounds.size.height * cutoutSizeRatio.height);
  287. // Apple's cutouts are currently centred on the horizontal, and stuck to the top of the vertical, hence this positioning.
  288. const float x = (([UIScreen mainScreen].nativeBounds.size.width - w) / 2);
  289. const float y = ([UIScreen mainScreen].nativeBounds.size.height - h);
  290. UnityReportDisplayCutouts(&x, &y, &w, &h, 1);
  291. return;
  292. }
  293. }
  294. #endif
  295. UnityReportDisplayCutouts(nullptr, nullptr, nullptr, nullptr, 0);
  296. }
  297. CGRect ComputeSafeArea(UIView* view)
  298. {
  299. CGSize screenSize = view.bounds.size;
  300. CGRect screenRect = CGRectMake(0, 0, screenSize.width, screenSize.height);
  301. UIEdgeInsets insets = [view safeAreaInsets];
  302. float insetLeft = insets.left, insetBottom = insets.bottom, insetTop = insets.top;
  303. float insetHeight = insetBottom + insetTop;
  304. float insetWidth = insetLeft + insets.right;
  305. // Unity uses bottom left as the origin
  306. screenRect = CGRectOffset(screenRect, insetLeft, insetBottom);
  307. screenRect.size.width -= insetWidth;
  308. screenRect.size.height -= insetHeight;
  309. const float scale = view.contentScaleFactor;
  310. // Truncate safe area size because in some cases (for example when Display zoom is turned on)
  311. // it might become larger than Screen.width/height which are returned as ints.
  312. screenRect.origin.x = (unsigned)::roundf(screenRect.origin.x * scale);
  313. screenRect.origin.y = (unsigned)::roundf(screenRect.origin.y * scale);
  314. screenRect.size.width = (unsigned)::roundf(screenRect.size.width * scale);
  315. screenRect.size.height = (unsigned)::roundf(screenRect.size.height * scale);
  316. return screenRect;
  317. }
  318. // Apple does not provide the cutout width and height in points/pixels. They *do* however list the
  319. // 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.
  320. // This information can be found here - https://developer.apple.com/accessories/Accessory-Design-Guidelines.pdf
  321. CGSize GetCutoutToScreenRatio()
  322. {
  323. switch (UnityDeviceGeneration())
  324. {
  325. case deviceiPhone14:
  326. case deviceiPhone16e:
  327. case deviceiPhone17e:
  328. return CGSizeMake(0.415, 0.04);
  329. case deviceiPhone14Plus:
  330. return CGSizeMake(0.377, 0.036);
  331. case deviceiPhone14Pro:
  332. case deviceiPhone15:
  333. case deviceiPhone15Pro:
  334. case deviceiPhone16:
  335. case deviceiPhone16Pro:
  336. case deviceiPhone17:
  337. case deviceiPhone17Pro:
  338. return CGSizeMake(0.318, 0.057);
  339. case deviceiPhone14ProMax:
  340. case deviceiPhone15ProMax:
  341. case deviceiPhone15Plus:
  342. case deviceiPhone16Plus:
  343. case deviceiPhone16ProMax:
  344. case deviceiPhone17ProMax:
  345. return CGSizeMake(0.292, 0.052);
  346. case deviceiPhoneAir:
  347. return CGSizeMake(0.299, 0.062);
  348. case deviceiPhone13ProMax:
  349. return CGSizeMake(0.373, 0.036);
  350. case deviceiPhone13Pro:
  351. case deviceiPhone13:
  352. return CGSizeMake(0.4148, 0.0399);
  353. case deviceiPhone13Mini:
  354. return CGSizeMake(0.4644, 0.0462);
  355. case deviceiPhone12ProMax:
  356. return CGSizeMake(0.4897, 0.0346);
  357. case deviceiPhone12Pro:
  358. case deviceiPhone12:
  359. return CGSizeMake(0.5393, 0.0379);
  360. case deviceiPhone12Mini:
  361. return CGSizeMake(0.604, 0.0424);
  362. case deviceiPhone11ProMax:
  363. return CGSizeMake(0.5057, 0.0335);
  364. case deviceiPhone11Pro:
  365. return CGSizeMake(0.5583, 0.037);
  366. case deviceiPhone11:
  367. case deviceiPhoneXR:
  368. return CGSizeMake(0.5568, 0.0398);
  369. case deviceiPhoneXSMax:
  370. return CGSizeMake(0.4884, 0.0333);
  371. case deviceiPhoneX:
  372. case deviceiPhoneXS:
  373. return CGSizeMake(0.5391, 0.0368);
  374. default:
  375. NSCAssert(!UnityDeviceHasCutout(), @"Device has a cutout, but no ratio has been added for it.");
  376. return CGSizeZero;
  377. }
  378. }