godot_view.mm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /**************************************************************************/
  2. /* godot_view.mm */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #import "godot_view.h"
  31. #import "display_layer.h"
  32. #import "display_server_ios.h"
  33. #import "godot_view_renderer.h"
  34. #include "core/config/project_settings.h"
  35. #include "core/os/keyboard.h"
  36. #include "core/string/ustring.h"
  37. #import <CoreMotion/CoreMotion.h>
  38. static const int max_touches = 32;
  39. static const float earth_gravity = 9.80665;
  40. @interface GodotView () {
  41. UITouch *godot_touches[max_touches];
  42. }
  43. @property(assign, nonatomic) BOOL isActive;
  44. // CADisplayLink available on 3.1+ synchronizes the animation timer & drawing with the refresh rate of the display, only supports animation intervals of 1/60 1/30 & 1/15
  45. @property(strong, nonatomic) CADisplayLink *displayLink;
  46. // An animation timer that, when animation is started, will periodically call -drawView at the given rate.
  47. // Only used if CADisplayLink is not
  48. @property(strong, nonatomic) NSTimer *animationTimer;
  49. @property(strong, nonatomic) CALayer<DisplayLayer> *renderingLayer;
  50. @property(strong, nonatomic) CMMotionManager *motionManager;
  51. @end
  52. @implementation GodotView
  53. - (CALayer<DisplayLayer> *)initializeRenderingForDriver:(NSString *)driverName {
  54. if (self.renderingLayer) {
  55. return self.renderingLayer;
  56. }
  57. CALayer<DisplayLayer> *layer;
  58. if ([driverName isEqualToString:@"vulkan"] || [driverName isEqualToString:@"metal"]) {
  59. #if defined(TARGET_OS_SIMULATOR) && TARGET_OS_SIMULATOR
  60. if (@available(iOS 13, *)) {
  61. layer = [GodotMetalLayer layer];
  62. } else {
  63. return nil;
  64. }
  65. #else
  66. layer = [GodotMetalLayer layer];
  67. #endif
  68. } else if ([driverName isEqualToString:@"opengl3"]) {
  69. #pragma clang diagnostic push
  70. #pragma clang diagnostic ignored "-Wdeprecated-declarations" // OpenGL is deprecated in iOS 12.0
  71. layer = [GodotOpenGLLayer layer];
  72. #pragma clang diagnostic pop
  73. } else {
  74. return nil;
  75. }
  76. layer.frame = self.bounds;
  77. layer.contentsScale = self.contentScaleFactor;
  78. [self.layer addSublayer:layer];
  79. self.renderingLayer = layer;
  80. [layer initializeDisplayLayer];
  81. return self.renderingLayer;
  82. }
  83. - (instancetype)initWithCoder:(NSCoder *)coder {
  84. self = [super initWithCoder:coder];
  85. if (self) {
  86. [self godot_commonInit];
  87. }
  88. return self;
  89. }
  90. - (instancetype)initWithFrame:(CGRect)frame {
  91. self = [super initWithFrame:frame];
  92. if (self) {
  93. [self godot_commonInit];
  94. }
  95. return self;
  96. }
  97. - (void)dealloc {
  98. [self stopRendering];
  99. self.renderer = nil;
  100. self.delegate = nil;
  101. if (self.renderingLayer) {
  102. [self.renderingLayer removeFromSuperlayer];
  103. self.renderingLayer = nil;
  104. }
  105. if (self.motionManager) {
  106. [self.motionManager stopDeviceMotionUpdates];
  107. self.motionManager = nil;
  108. }
  109. if (self.displayLink) {
  110. [self.displayLink invalidate];
  111. self.displayLink = nil;
  112. }
  113. if (self.animationTimer) {
  114. [self.animationTimer invalidate];
  115. self.animationTimer = nil;
  116. }
  117. }
  118. - (void)godot_commonInit {
  119. self.contentScaleFactor = [UIScreen mainScreen].scale;
  120. [self initTouches];
  121. self.multipleTouchEnabled = YES;
  122. // Configure and start accelerometer
  123. if (!self.motionManager) {
  124. self.motionManager = [[CMMotionManager alloc] init];
  125. if (self.motionManager.deviceMotionAvailable) {
  126. self.motionManager.deviceMotionUpdateInterval = 1.0 / 70.0;
  127. [self.motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical];
  128. } else {
  129. self.motionManager = nil;
  130. }
  131. }
  132. }
  133. - (void)system_theme_changed {
  134. DisplayServerIOS *ds = (DisplayServerIOS *)DisplayServer::get_singleton();
  135. if (ds) {
  136. ds->emit_system_theme_changed();
  137. }
  138. }
  139. - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
  140. if (@available(iOS 13.0, *)) {
  141. [super traitCollectionDidChange:previousTraitCollection];
  142. if ([UITraitCollection currentTraitCollection].userInterfaceStyle != previousTraitCollection.userInterfaceStyle) {
  143. [self system_theme_changed];
  144. }
  145. }
  146. }
  147. - (void)stopRendering {
  148. if (!self.isActive) {
  149. return;
  150. }
  151. self.isActive = NO;
  152. print_verbose("Stop animation!");
  153. if (self.useCADisplayLink) {
  154. [self.displayLink invalidate];
  155. self.displayLink = nil;
  156. } else {
  157. [self.animationTimer invalidate];
  158. self.animationTimer = nil;
  159. }
  160. [self clearTouches];
  161. }
  162. - (void)startRendering {
  163. if (self.isActive) {
  164. return;
  165. }
  166. self.isActive = YES;
  167. print_verbose("Start animation!");
  168. if (self.useCADisplayLink) {
  169. self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawView)];
  170. if (GLOBAL_GET("display/window/ios/allow_high_refresh_rate")) {
  171. self.displayLink.preferredFramesPerSecond = 120;
  172. } else {
  173. self.displayLink.preferredFramesPerSecond = 60;
  174. }
  175. // Setup DisplayLink in main thread
  176. [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  177. } else {
  178. self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:(1.0 / 60) target:self selector:@selector(drawView) userInfo:nil repeats:YES];
  179. }
  180. }
  181. - (void)drawView {
  182. if (!self.isActive) {
  183. print_verbose("Draw view not active!");
  184. return;
  185. }
  186. if (self.useCADisplayLink) {
  187. // Pause the CADisplayLink to avoid recursion
  188. [self.displayLink setPaused:YES];
  189. // Process all input events
  190. while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0, TRUE) == kCFRunLoopRunHandledSource) {
  191. // Continue.
  192. }
  193. // We are good to go, resume the CADisplayLink
  194. [self.displayLink setPaused:NO];
  195. }
  196. [self.renderingLayer startRenderDisplayLayer];
  197. if (!self.renderer) {
  198. return;
  199. }
  200. if ([self.renderer setupView:self]) {
  201. return;
  202. }
  203. if (self.delegate) {
  204. BOOL delegateFinishedSetup = [self.delegate godotViewFinishedSetup:self];
  205. if (!delegateFinishedSetup) {
  206. return;
  207. }
  208. }
  209. [self handleMotion];
  210. [self.renderer renderOnView:self];
  211. [self.renderingLayer stopRenderDisplayLayer];
  212. }
  213. - (BOOL)canRender {
  214. if (self.useCADisplayLink) {
  215. return self.displayLink != nil;
  216. } else {
  217. return self.animationTimer != nil;
  218. }
  219. }
  220. - (void)setRenderingInterval:(NSTimeInterval)renderingInterval {
  221. _renderingInterval = renderingInterval;
  222. if (self.canRender) {
  223. [self stopRendering];
  224. [self startRendering];
  225. }
  226. }
  227. - (void)layoutSubviews {
  228. if (self.renderingLayer) {
  229. self.renderingLayer.frame = self.bounds;
  230. [self.renderingLayer layoutDisplayLayer];
  231. if (DisplayServerIOS::get_singleton()) {
  232. DisplayServerIOS::get_singleton()->resize_window(self.bounds.size);
  233. }
  234. }
  235. [super layoutSubviews];
  236. }
  237. // MARK: - Input
  238. // MARK: Touches
  239. - (void)initTouches {
  240. for (int i = 0; i < max_touches; i++) {
  241. godot_touches[i] = nullptr;
  242. }
  243. }
  244. - (int)getTouchIDForTouch:(UITouch *)p_touch {
  245. int first = -1;
  246. for (int i = 0; i < max_touches; i++) {
  247. if (first == -1 && godot_touches[i] == nullptr) {
  248. first = i;
  249. continue;
  250. }
  251. if (godot_touches[i] == p_touch) {
  252. return i;
  253. }
  254. }
  255. if (first != -1) {
  256. godot_touches[first] = p_touch;
  257. return first;
  258. }
  259. return -1;
  260. }
  261. - (int)removeTouch:(UITouch *)p_touch {
  262. int remaining = 0;
  263. for (int i = 0; i < max_touches; i++) {
  264. if (godot_touches[i] == nullptr) {
  265. continue;
  266. }
  267. if (godot_touches[i] == p_touch) {
  268. godot_touches[i] = nullptr;
  269. } else {
  270. ++remaining;
  271. }
  272. }
  273. return remaining;
  274. }
  275. - (void)clearTouches {
  276. for (int i = 0; i < max_touches; i++) {
  277. godot_touches[i] = nullptr;
  278. }
  279. }
  280. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  281. for (UITouch *touch in touches) {
  282. int tid = [self getTouchIDForTouch:touch];
  283. ERR_FAIL_COND(tid == -1);
  284. CGPoint touchPoint = [touch locationInView:self];
  285. DisplayServerIOS::get_singleton()->touch_press(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, true, touch.tapCount > 1);
  286. }
  287. }
  288. - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  289. for (UITouch *touch in touches) {
  290. int tid = [self getTouchIDForTouch:touch];
  291. ERR_FAIL_COND(tid == -1);
  292. CGPoint touchPoint = [touch locationInView:self];
  293. CGPoint prev_point = [touch previousLocationInView:self];
  294. CGFloat alt = [touch altitudeAngle];
  295. CGVector azim = [touch azimuthUnitVectorInView:self];
  296. DisplayServerIOS::get_singleton()->touch_drag(tid, prev_point.x * self.contentScaleFactor, prev_point.y * self.contentScaleFactor, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, [touch force] / [touch maximumPossibleForce], Vector2(azim.dx, azim.dy) * Math::cos(alt));
  297. }
  298. }
  299. - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  300. for (UITouch *touch in touches) {
  301. int tid = [self getTouchIDForTouch:touch];
  302. ERR_FAIL_COND(tid == -1);
  303. [self removeTouch:touch];
  304. CGPoint touchPoint = [touch locationInView:self];
  305. DisplayServerIOS::get_singleton()->touch_press(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, false, false);
  306. }
  307. }
  308. - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
  309. for (UITouch *touch in touches) {
  310. int tid = [self getTouchIDForTouch:touch];
  311. ERR_FAIL_COND(tid == -1);
  312. DisplayServerIOS::get_singleton()->touches_canceled(tid);
  313. }
  314. [self clearTouches];
  315. }
  316. // MARK: Motion
  317. - (void)handleMotion {
  318. if (!self.motionManager) {
  319. return;
  320. }
  321. // Just using polling approach for now, we can set this up so it sends
  322. // data to us in intervals, might be better. See Apple reference pages
  323. // for more details:
  324. // https://developer.apple.com/reference/coremotion/cmmotionmanager?language=objc
  325. // Apple splits our accelerometer date into a gravity and user movement
  326. // component. We add them back together.
  327. CMAcceleration gravity = self.motionManager.deviceMotion.gravity;
  328. CMAcceleration acceleration = self.motionManager.deviceMotion.userAcceleration;
  329. // To be consistent with Android we convert the unit of measurement from g (Earth's gravity)
  330. // to m/s^2.
  331. gravity.x *= earth_gravity;
  332. gravity.y *= earth_gravity;
  333. gravity.z *= earth_gravity;
  334. acceleration.x *= earth_gravity;
  335. acceleration.y *= earth_gravity;
  336. acceleration.z *= earth_gravity;
  337. ///@TODO We don't seem to be getting data here, is my device broken or
  338. /// is this code incorrect?
  339. CMMagneticField magnetic = self.motionManager.deviceMotion.magneticField.field;
  340. ///@TODO we can access rotationRate as a CMRotationRate variable
  341. ///(processed date) or CMGyroData (raw data), have to see what works
  342. /// best
  343. CMRotationRate rotation = self.motionManager.deviceMotion.rotationRate;
  344. // Adjust for screen orientation.
  345. // [[UIDevice currentDevice] orientation] changes even if we've fixed
  346. // our orientation which is not a good thing when you're trying to get
  347. // your user to move the screen in all directions and want consistent
  348. // output
  349. ///@TODO Using [[UIApplication sharedApplication] statusBarOrientation]
  350. /// is a bit of a hack. Godot obviously knows the orientation so maybe
  351. /// we
  352. // can use that instead? (note that left and right seem swapped)
  353. UIInterfaceOrientation interfaceOrientation = UIInterfaceOrientationUnknown;
  354. #if __IPHONE_OS_VERSION_MAX_ALLOWED < 140000
  355. interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  356. #else
  357. if (@available(iOS 13, *)) {
  358. interfaceOrientation = [UIApplication sharedApplication].delegate.window.windowScene.interfaceOrientation;
  359. #if !defined(TARGET_OS_SIMULATOR) || !TARGET_OS_SIMULATOR
  360. } else {
  361. interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  362. #endif
  363. }
  364. #endif
  365. switch (interfaceOrientation) {
  366. case UIInterfaceOrientationLandscapeLeft: {
  367. DisplayServerIOS::get_singleton()->update_gravity(Vector3(gravity.x, gravity.y, gravity.z).rotated(Vector3(0, 0, 1), -Math_PI * 0.5));
  368. DisplayServerIOS::get_singleton()->update_accelerometer(Vector3(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z).rotated(Vector3(0, 0, 1), -Math_PI * 0.5));
  369. DisplayServerIOS::get_singleton()->update_magnetometer(Vector3(magnetic.x, magnetic.y, magnetic.z).rotated(Vector3(0, 0, 1), -Math_PI * 0.5));
  370. DisplayServerIOS::get_singleton()->update_gyroscope(Vector3(rotation.x, rotation.y, rotation.z).rotated(Vector3(0, 0, 1), -Math_PI * 0.5));
  371. } break;
  372. case UIInterfaceOrientationLandscapeRight: {
  373. DisplayServerIOS::get_singleton()->update_gravity(Vector3(gravity.x, gravity.y, gravity.z).rotated(Vector3(0, 0, 1), Math_PI * 0.5));
  374. DisplayServerIOS::get_singleton()->update_accelerometer(Vector3(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z).rotated(Vector3(0, 0, 1), Math_PI * 0.5));
  375. DisplayServerIOS::get_singleton()->update_magnetometer(Vector3(magnetic.x, magnetic.y, magnetic.z).rotated(Vector3(0, 0, 1), Math_PI * 0.5));
  376. DisplayServerIOS::get_singleton()->update_gyroscope(Vector3(rotation.x, rotation.y, rotation.z).rotated(Vector3(0, 0, 1), Math_PI * 0.5));
  377. } break;
  378. case UIInterfaceOrientationPortraitUpsideDown: {
  379. DisplayServerIOS::get_singleton()->update_gravity(Vector3(gravity.x, gravity.y, gravity.z).rotated(Vector3(0, 0, 1), Math_PI));
  380. DisplayServerIOS::get_singleton()->update_accelerometer(Vector3(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z).rotated(Vector3(0, 0, 1), Math_PI));
  381. DisplayServerIOS::get_singleton()->update_magnetometer(Vector3(magnetic.x, magnetic.y, magnetic.z).rotated(Vector3(0, 0, 1), Math_PI));
  382. DisplayServerIOS::get_singleton()->update_gyroscope(Vector3(rotation.x, rotation.y, rotation.z).rotated(Vector3(0, 0, 1), Math_PI));
  383. } break;
  384. default: { // assume portrait
  385. DisplayServerIOS::get_singleton()->update_gravity(Vector3(gravity.x, gravity.y, gravity.z));
  386. DisplayServerIOS::get_singleton()->update_accelerometer(Vector3(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z));
  387. DisplayServerIOS::get_singleton()->update_magnetometer(Vector3(magnetic.x, magnetic.y, magnetic.z));
  388. DisplayServerIOS::get_singleton()->update_gyroscope(Vector3(rotation.x, rotation.y, rotation.z));
  389. } break;
  390. }
  391. }
  392. @end