app_delegate.mm 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. /*************************************************************************/
  2. /* app_delegate.mm */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  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 "app_delegate.h"
  31. #include "core/project_settings.h"
  32. #include "drivers/coreaudio/audio_driver_coreaudio.h"
  33. #import "gl_view.h"
  34. #include "main/main.h"
  35. #include "os_iphone.h"
  36. #import "GameController/GameController.h"
  37. #import <AudioToolbox/AudioServices.h>
  38. #define kFilteringFactor 0.1
  39. #define kRenderingFrequency 60
  40. #define kAccelerometerFrequency 100.0 // Hz
  41. Error _shell_open(String);
  42. void _set_keep_screen_on(bool p_enabled);
  43. Error _shell_open(String p_uri) {
  44. NSString *url = [[NSString alloc] initWithUTF8String:p_uri.utf8().get_data()];
  45. if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]])
  46. return ERR_CANT_OPEN;
  47. printf("opening url %ls\n", p_uri.c_str());
  48. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
  49. [url release];
  50. return OK;
  51. };
  52. void _set_keep_screen_on(bool p_enabled) {
  53. [[UIApplication sharedApplication] setIdleTimerDisabled:(BOOL)p_enabled];
  54. };
  55. void _vibrate() {
  56. AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
  57. };
  58. @implementation AppDelegate
  59. @synthesize window;
  60. extern int gargc;
  61. extern char **gargv;
  62. extern int iphone_main(int, int, int, char **, String);
  63. extern void iphone_finish();
  64. CMMotionManager *motionManager;
  65. bool motionInitialised;
  66. static ViewController *mainViewController = nil;
  67. + (ViewController *)getViewController {
  68. return mainViewController;
  69. }
  70. NSMutableDictionary *ios_joysticks = nil;
  71. NSMutableArray *pending_ios_joysticks = nil;
  72. - (GCControllerPlayerIndex)getFreePlayerIndex {
  73. bool have_player_1 = false;
  74. bool have_player_2 = false;
  75. bool have_player_3 = false;
  76. bool have_player_4 = false;
  77. if (ios_joysticks == nil) {
  78. NSArray *keys = [ios_joysticks allKeys];
  79. for (NSNumber *key in keys) {
  80. GCController *controller = [ios_joysticks objectForKey:key];
  81. if (controller.playerIndex == GCControllerPlayerIndex1) {
  82. have_player_1 = true;
  83. } else if (controller.playerIndex == GCControllerPlayerIndex2) {
  84. have_player_2 = true;
  85. } else if (controller.playerIndex == GCControllerPlayerIndex3) {
  86. have_player_3 = true;
  87. } else if (controller.playerIndex == GCControllerPlayerIndex4) {
  88. have_player_4 = true;
  89. };
  90. };
  91. };
  92. if (!have_player_1) {
  93. return GCControllerPlayerIndex1;
  94. } else if (!have_player_2) {
  95. return GCControllerPlayerIndex2;
  96. } else if (!have_player_3) {
  97. return GCControllerPlayerIndex3;
  98. } else if (!have_player_4) {
  99. return GCControllerPlayerIndex4;
  100. } else {
  101. return GCControllerPlayerIndexUnset;
  102. };
  103. };
  104. void _ios_add_joystick(GCController *controller, AppDelegate *delegate) {
  105. // get a new id for our controller
  106. int joy_id = OSIPhone::get_singleton()->get_unused_joy_id();
  107. if (joy_id != -1) {
  108. // assign our player index
  109. if (controller.playerIndex == GCControllerPlayerIndexUnset) {
  110. controller.playerIndex = [delegate getFreePlayerIndex];
  111. };
  112. // tell Godot about our new controller
  113. OSIPhone::get_singleton()->joy_connection_changed(
  114. joy_id, true, [controller.vendorName UTF8String]);
  115. // add it to our dictionary, this will retain our controllers
  116. [ios_joysticks setObject:controller
  117. forKey:[NSNumber numberWithInt:joy_id]];
  118. // set our input handler
  119. [delegate setControllerInputHandler:controller];
  120. } else {
  121. printf("Couldn't retrieve new joy id\n");
  122. };
  123. }
  124. static void on_focus_out(ViewController *view_controller, bool *is_focus_out) {
  125. if (!*is_focus_out) {
  126. *is_focus_out = true;
  127. if (OS::get_singleton()->get_main_loop())
  128. OS::get_singleton()->get_main_loop()->notification(
  129. MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  130. [view_controller.view stopAnimation];
  131. if (OS::get_singleton()->native_video_is_playing()) {
  132. OSIPhone::get_singleton()->native_video_focus_out();
  133. }
  134. AudioDriverCoreAudio *audio = dynamic_cast<AudioDriverCoreAudio *>(AudioDriverCoreAudio::get_singleton());
  135. if (audio)
  136. audio->stop();
  137. }
  138. }
  139. static void on_focus_in(ViewController *view_controller, bool *is_focus_out) {
  140. if (*is_focus_out) {
  141. *is_focus_out = false;
  142. if (OS::get_singleton()->get_main_loop())
  143. OS::get_singleton()->get_main_loop()->notification(
  144. MainLoop::NOTIFICATION_WM_FOCUS_IN);
  145. [view_controller.view startAnimation];
  146. if (OSIPhone::get_singleton()->native_video_is_playing()) {
  147. OSIPhone::get_singleton()->native_video_unpause();
  148. }
  149. AudioDriverCoreAudio *audio = dynamic_cast<AudioDriverCoreAudio *>(AudioDriverCoreAudio::get_singleton());
  150. if (audio)
  151. audio->start();
  152. }
  153. }
  154. - (void)controllerWasConnected:(NSNotification *)notification {
  155. // create our dictionary if we don't have one yet
  156. if (ios_joysticks == nil) {
  157. ios_joysticks = [[NSMutableDictionary alloc] init];
  158. };
  159. // get our controller
  160. GCController *controller = (GCController *)notification.object;
  161. if (controller == nil) {
  162. printf("Couldn't retrieve new controller\n");
  163. } else if ([[ios_joysticks allKeysForObject:controller] count] != 0) {
  164. printf("Controller is already registered\n");
  165. } else if (frame_count > 1) {
  166. _ios_add_joystick(controller, self);
  167. } else {
  168. if (pending_ios_joysticks == nil)
  169. pending_ios_joysticks = [[NSMutableArray alloc] init];
  170. [pending_ios_joysticks addObject:controller];
  171. };
  172. };
  173. - (void)controllerWasDisconnected:(NSNotification *)notification {
  174. if (ios_joysticks != nil) {
  175. // find our joystick, there should be only one in our dictionary
  176. GCController *controller = (GCController *)notification.object;
  177. NSArray *keys = [ios_joysticks allKeysForObject:controller];
  178. for (NSNumber *key in keys) {
  179. // tell Godot this joystick is no longer there
  180. int joy_id = [key intValue];
  181. OSIPhone::get_singleton()->joy_connection_changed(joy_id, false, "");
  182. // and remove it from our dictionary
  183. [ios_joysticks removeObjectForKey:key];
  184. };
  185. };
  186. };
  187. - (int)getJoyIdForController:(GCController *)controller {
  188. if (ios_joysticks != nil) {
  189. // find our joystick, there should be only one in our dictionary
  190. NSArray *keys = [ios_joysticks allKeysForObject:controller];
  191. for (NSNumber *key in keys) {
  192. int joy_id = [key intValue];
  193. return joy_id;
  194. };
  195. };
  196. return -1;
  197. };
  198. - (void)setControllerInputHandler:(GCController *)controller {
  199. // Hook in the callback handler for the correct gamepad profile.
  200. // This is a bit of a weird design choice on Apples part.
  201. // You need to select the most capable gamepad profile for the
  202. // gamepad attached.
  203. if (controller.extendedGamepad != nil) {
  204. // The extended gamepad profile has all the input you could possibly find on
  205. // a gamepad but will only be active if your gamepad actually has all of
  206. // these...
  207. controller.extendedGamepad.valueChangedHandler = ^(
  208. GCExtendedGamepad *gamepad, GCControllerElement *element) {
  209. int joy_id = [self getJoyIdForController:controller];
  210. if (element == gamepad.buttonA) {
  211. OSIPhone::get_singleton()->joy_button(joy_id, JOY_BUTTON_0,
  212. gamepad.buttonA.isPressed);
  213. } else if (element == gamepad.buttonB) {
  214. OSIPhone::get_singleton()->joy_button(joy_id, JOY_BUTTON_1,
  215. gamepad.buttonB.isPressed);
  216. } else if (element == gamepad.buttonX) {
  217. OSIPhone::get_singleton()->joy_button(joy_id, JOY_BUTTON_2,
  218. gamepad.buttonX.isPressed);
  219. } else if (element == gamepad.buttonY) {
  220. OSIPhone::get_singleton()->joy_button(joy_id, JOY_BUTTON_3,
  221. gamepad.buttonY.isPressed);
  222. } else if (element == gamepad.leftShoulder) {
  223. OSIPhone::get_singleton()->joy_button(joy_id, JOY_L,
  224. gamepad.leftShoulder.isPressed);
  225. } else if (element == gamepad.rightShoulder) {
  226. OSIPhone::get_singleton()->joy_button(joy_id, JOY_R,
  227. gamepad.rightShoulder.isPressed);
  228. } else if (element == gamepad.leftTrigger) {
  229. OSIPhone::get_singleton()->joy_button(joy_id, JOY_L2,
  230. gamepad.leftTrigger.isPressed);
  231. } else if (element == gamepad.rightTrigger) {
  232. OSIPhone::get_singleton()->joy_button(joy_id, JOY_R2,
  233. gamepad.rightTrigger.isPressed);
  234. } else if (element == gamepad.dpad) {
  235. OSIPhone::get_singleton()->joy_button(joy_id, JOY_DPAD_UP,
  236. gamepad.dpad.up.isPressed);
  237. OSIPhone::get_singleton()->joy_button(joy_id, JOY_DPAD_DOWN,
  238. gamepad.dpad.down.isPressed);
  239. OSIPhone::get_singleton()->joy_button(joy_id, JOY_DPAD_LEFT,
  240. gamepad.dpad.left.isPressed);
  241. OSIPhone::get_singleton()->joy_button(joy_id, JOY_DPAD_RIGHT,
  242. gamepad.dpad.right.isPressed);
  243. };
  244. InputDefault::JoyAxis jx;
  245. jx.min = -1;
  246. if (element == gamepad.leftThumbstick) {
  247. jx.value = gamepad.leftThumbstick.xAxis.value;
  248. OSIPhone::get_singleton()->joy_axis(joy_id, JOY_ANALOG_LX, jx);
  249. jx.value = -gamepad.leftThumbstick.yAxis.value;
  250. OSIPhone::get_singleton()->joy_axis(joy_id, JOY_ANALOG_LY, jx);
  251. } else if (element == gamepad.rightThumbstick) {
  252. jx.value = gamepad.rightThumbstick.xAxis.value;
  253. OSIPhone::get_singleton()->joy_axis(joy_id, JOY_ANALOG_RX, jx);
  254. jx.value = -gamepad.rightThumbstick.yAxis.value;
  255. OSIPhone::get_singleton()->joy_axis(joy_id, JOY_ANALOG_RY, jx);
  256. } else if (element == gamepad.leftTrigger) {
  257. jx.value = gamepad.leftTrigger.value;
  258. OSIPhone::get_singleton()->joy_axis(joy_id, JOY_ANALOG_L2, jx);
  259. } else if (element == gamepad.rightTrigger) {
  260. jx.value = gamepad.rightTrigger.value;
  261. OSIPhone::get_singleton()->joy_axis(joy_id, JOY_ANALOG_R2, jx);
  262. };
  263. };
  264. } else if (controller.gamepad != nil) {
  265. // gamepad is the standard profile with 4 buttons, shoulder buttons and a
  266. // D-pad
  267. controller.gamepad.valueChangedHandler = ^(GCGamepad *gamepad,
  268. GCControllerElement *element) {
  269. int joy_id = [self getJoyIdForController:controller];
  270. if (element == gamepad.buttonA) {
  271. OSIPhone::get_singleton()->joy_button(joy_id, JOY_BUTTON_0,
  272. gamepad.buttonA.isPressed);
  273. } else if (element == gamepad.buttonB) {
  274. OSIPhone::get_singleton()->joy_button(joy_id, JOY_BUTTON_1,
  275. gamepad.buttonB.isPressed);
  276. } else if (element == gamepad.buttonX) {
  277. OSIPhone::get_singleton()->joy_button(joy_id, JOY_BUTTON_2,
  278. gamepad.buttonX.isPressed);
  279. } else if (element == gamepad.buttonY) {
  280. OSIPhone::get_singleton()->joy_button(joy_id, JOY_BUTTON_3,
  281. gamepad.buttonY.isPressed);
  282. } else if (element == gamepad.leftShoulder) {
  283. OSIPhone::get_singleton()->joy_button(joy_id, JOY_L,
  284. gamepad.leftShoulder.isPressed);
  285. } else if (element == gamepad.rightShoulder) {
  286. OSIPhone::get_singleton()->joy_button(joy_id, JOY_R,
  287. gamepad.rightShoulder.isPressed);
  288. } else if (element == gamepad.dpad) {
  289. OSIPhone::get_singleton()->joy_button(joy_id, JOY_DPAD_UP,
  290. gamepad.dpad.up.isPressed);
  291. OSIPhone::get_singleton()->joy_button(joy_id, JOY_DPAD_DOWN,
  292. gamepad.dpad.down.isPressed);
  293. OSIPhone::get_singleton()->joy_button(joy_id, JOY_DPAD_LEFT,
  294. gamepad.dpad.left.isPressed);
  295. OSIPhone::get_singleton()->joy_button(joy_id, JOY_DPAD_RIGHT,
  296. gamepad.dpad.right.isPressed);
  297. };
  298. };
  299. #ifdef ADD_MICRO_GAMEPAD // disabling this for now, only available on iOS 9+,
  300. // while we are setting that as the minimum, seems our
  301. // build environment doesn't like it
  302. } else if (controller.microGamepad != nil) {
  303. // micro gamepads were added in OS 9 and feature just 2 buttons and a d-pad
  304. controller.microGamepad.valueChangedHandler =
  305. ^(GCMicroGamepad *gamepad, GCControllerElement *element) {
  306. int joy_id = [self getJoyIdForController:controller];
  307. if (element == gamepad.buttonA) {
  308. OSIPhone::get_singleton()->joy_button(joy_id, JOY_BUTTON_0,
  309. gamepad.buttonA.isPressed);
  310. } else if (element == gamepad.buttonX) {
  311. OSIPhone::get_singleton()->joy_button(joy_id, JOY_BUTTON_2,
  312. gamepad.buttonX.isPressed);
  313. } else if (element == gamepad.dpad) {
  314. OSIPhone::get_singleton()->joy_button(joy_id, JOY_DPAD_UP,
  315. gamepad.dpad.up.isPressed);
  316. OSIPhone::get_singleton()->joy_button(joy_id, JOY_DPAD_DOWN,
  317. gamepad.dpad.down.isPressed);
  318. OSIPhone::get_singleton()->joy_button(joy_id, JOY_DPAD_LEFT,
  319. gamepad.dpad.left.isPressed);
  320. OSIPhone::get_singleton()->joy_button(joy_id, JOY_DPAD_RIGHT,
  321. gamepad.dpad.right.isPressed);
  322. };
  323. };
  324. #endif
  325. };
  326. ///@TODO need to add support for controller.motion which gives us access to
  327. /// the orientation of the device (if supported)
  328. ///@TODO need to add support for controllerPausedHandler which should be a
  329. /// toggle
  330. };
  331. - (void)initGameControllers {
  332. // get told when controllers connect, this will be called right away for
  333. // already connected controllers
  334. [[NSNotificationCenter defaultCenter]
  335. addObserver:self
  336. selector:@selector(controllerWasConnected:)
  337. name:GCControllerDidConnectNotification
  338. object:nil];
  339. // get told when controllers disconnect
  340. [[NSNotificationCenter defaultCenter]
  341. addObserver:self
  342. selector:@selector(controllerWasDisconnected:)
  343. name:GCControllerDidDisconnectNotification
  344. object:nil];
  345. };
  346. - (void)deinitGameControllers {
  347. [[NSNotificationCenter defaultCenter]
  348. removeObserver:self
  349. name:GCControllerDidConnectNotification
  350. object:nil];
  351. [[NSNotificationCenter defaultCenter]
  352. removeObserver:self
  353. name:GCControllerDidDisconnectNotification
  354. object:nil];
  355. if (ios_joysticks != nil) {
  356. [ios_joysticks dealloc];
  357. ios_joysticks = nil;
  358. };
  359. if (pending_ios_joysticks != nil) {
  360. [pending_ios_joysticks dealloc];
  361. pending_ios_joysticks = nil;
  362. };
  363. };
  364. OS::VideoMode _get_video_mode() {
  365. int backingWidth;
  366. int backingHeight;
  367. glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES,
  368. GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
  369. glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES,
  370. GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
  371. OS::VideoMode vm;
  372. vm.fullscreen = true;
  373. vm.width = backingWidth;
  374. vm.height = backingHeight;
  375. vm.resizable = false;
  376. return vm;
  377. };
  378. static int frame_count = 0;
  379. - (void)drawView:(GLView *)view;
  380. {
  381. switch (frame_count) {
  382. case 0: {
  383. OS::get_singleton()->set_video_mode(_get_video_mode());
  384. if (!OS::get_singleton()) {
  385. exit(0);
  386. };
  387. ++frame_count;
  388. NSString *locale_code = [[NSLocale currentLocale] localeIdentifier];
  389. OSIPhone::get_singleton()->set_locale(
  390. String::utf8([locale_code UTF8String]));
  391. NSString *uuid;
  392. if ([[UIDevice currentDevice]
  393. respondsToSelector:@selector(identifierForVendor)]) {
  394. uuid = [UIDevice currentDevice].identifierForVendor.UUIDString;
  395. } else {
  396. // before iOS 6, so just generate an identifier and store it
  397. uuid = [[NSUserDefaults standardUserDefaults]
  398. objectForKey:@"identiferForVendor"];
  399. if (!uuid) {
  400. CFUUIDRef cfuuid = CFUUIDCreate(NULL);
  401. uuid = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, cfuuid);
  402. CFRelease(cfuuid);
  403. [[NSUserDefaults standardUserDefaults]
  404. setObject:uuid
  405. forKey:@"identifierForVendor"];
  406. }
  407. }
  408. OSIPhone::get_singleton()->set_unique_id(String::utf8([uuid UTF8String]));
  409. }; break;
  410. case 1: {
  411. Main::setup2();
  412. ++frame_count;
  413. if (pending_ios_joysticks != nil) {
  414. for (GCController *controller in pending_ios_joysticks) {
  415. _ios_add_joystick(controller, self);
  416. }
  417. [pending_ios_joysticks dealloc];
  418. pending_ios_joysticks = nil;
  419. }
  420. // this might be necessary before here
  421. NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
  422. for (NSString *key in dict) {
  423. NSObject *value = [dict objectForKey:key];
  424. String ukey = String::utf8([key UTF8String]);
  425. // we need a NSObject to Variant conversor
  426. if ([value isKindOfClass:[NSString class]]) {
  427. NSString *str = (NSString *)value;
  428. String uval = String::utf8([str UTF8String]);
  429. ProjectSettings::get_singleton()->set("Info.plist/" + ukey, uval);
  430. } else if ([value isKindOfClass:[NSNumber class]]) {
  431. NSNumber *n = (NSNumber *)value;
  432. double dval = [n doubleValue];
  433. ProjectSettings::get_singleton()->set("Info.plist/" + ukey, dval);
  434. };
  435. // do stuff
  436. }
  437. }; break;
  438. case 2: {
  439. Main::start();
  440. ++frame_count;
  441. }; break; // no fallthrough
  442. default: {
  443. if (OSIPhone::get_singleton()) {
  444. // OSIPhone::get_singleton()->update_accelerometer(accel[0], accel[1],
  445. // accel[2]);
  446. if (motionInitialised) {
  447. // Just using polling approach for now, we can set this up so it sends
  448. // data to us in intervals, might be better. See Apple reference pages
  449. // for more details:
  450. // https://developer.apple.com/reference/coremotion/cmmotionmanager?language=objc
  451. // Apple splits our accelerometer date into a gravity and user movement
  452. // component. We add them back together
  453. CMAcceleration gravity = motionManager.deviceMotion.gravity;
  454. CMAcceleration acceleration =
  455. motionManager.deviceMotion.userAcceleration;
  456. ///@TODO We don't seem to be getting data here, is my device broken or
  457. /// is this code incorrect?
  458. CMMagneticField magnetic =
  459. motionManager.deviceMotion.magneticField.field;
  460. ///@TODO we can access rotationRate as a CMRotationRate variable
  461. ///(processed date) or CMGyroData (raw data), have to see what works
  462. /// best
  463. CMRotationRate rotation = motionManager.deviceMotion.rotationRate;
  464. // Adjust for screen orientation.
  465. // [[UIDevice currentDevice] orientation] changes even if we've fixed
  466. // our orientation which is not a good thing when you're trying to get
  467. // your user to move the screen in all directions and want consistent
  468. // output
  469. ///@TODO Using [[UIApplication sharedApplication] statusBarOrientation]
  470. /// is a bit of a hack. Godot obviously knows the orientation so maybe
  471. /// we
  472. // can use that instead? (note that left and right seem swapped)
  473. switch ([[UIApplication sharedApplication] statusBarOrientation]) {
  474. case UIDeviceOrientationLandscapeLeft: {
  475. OSIPhone::get_singleton()->update_gravity(-gravity.y, gravity.x,
  476. gravity.z);
  477. OSIPhone::get_singleton()->update_accelerometer(
  478. -(acceleration.y + gravity.y), (acceleration.x + gravity.x),
  479. acceleration.z + gravity.z);
  480. OSIPhone::get_singleton()->update_magnetometer(
  481. -magnetic.y, magnetic.x, magnetic.z);
  482. OSIPhone::get_singleton()->update_gyroscope(-rotation.y, rotation.x,
  483. rotation.z);
  484. }; break;
  485. case UIDeviceOrientationLandscapeRight: {
  486. OSIPhone::get_singleton()->update_gravity(gravity.y, -gravity.x,
  487. gravity.z);
  488. OSIPhone::get_singleton()->update_accelerometer(
  489. (acceleration.y + gravity.y), -(acceleration.x + gravity.x),
  490. acceleration.z + gravity.z);
  491. OSIPhone::get_singleton()->update_magnetometer(
  492. magnetic.y, -magnetic.x, magnetic.z);
  493. OSIPhone::get_singleton()->update_gyroscope(rotation.y, -rotation.x,
  494. rotation.z);
  495. }; break;
  496. case UIDeviceOrientationPortraitUpsideDown: {
  497. OSIPhone::get_singleton()->update_gravity(-gravity.x, gravity.y,
  498. gravity.z);
  499. OSIPhone::get_singleton()->update_accelerometer(
  500. -(acceleration.x + gravity.x), (acceleration.y + gravity.y),
  501. acceleration.z + gravity.z);
  502. OSIPhone::get_singleton()->update_magnetometer(
  503. -magnetic.x, magnetic.y, magnetic.z);
  504. OSIPhone::get_singleton()->update_gyroscope(-rotation.x, rotation.y,
  505. rotation.z);
  506. }; break;
  507. default: { // assume portrait
  508. OSIPhone::get_singleton()->update_gravity(gravity.x, gravity.y,
  509. gravity.z);
  510. OSIPhone::get_singleton()->update_accelerometer(
  511. acceleration.x + gravity.x, acceleration.y + gravity.y,
  512. acceleration.z + gravity.z);
  513. OSIPhone::get_singleton()->update_magnetometer(magnetic.x, magnetic.y,
  514. magnetic.z);
  515. OSIPhone::get_singleton()->update_gyroscope(rotation.x, rotation.y,
  516. rotation.z);
  517. }; break;
  518. };
  519. }
  520. bool quit_request = OSIPhone::get_singleton()->iterate();
  521. };
  522. }; break;
  523. };
  524. };
  525. - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
  526. if (OS::get_singleton()->get_main_loop()) {
  527. OS::get_singleton()->get_main_loop()->notification(
  528. MainLoop::NOTIFICATION_OS_MEMORY_WARNING);
  529. }
  530. };
  531. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  532. CGRect rect = [[UIScreen mainScreen] bounds];
  533. is_focus_out = false;
  534. [application setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
  535. // disable idle timer
  536. // application.idleTimerDisabled = YES;
  537. // Create a full-screen window
  538. window = [[UIWindow alloc] initWithFrame:rect];
  539. OS::VideoMode vm = _get_video_mode();
  540. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
  541. NSUserDomainMask, YES);
  542. NSString *documentsDirectory = [paths objectAtIndex:0];
  543. int err = iphone_main(vm.width, vm.height, gargc, gargv, String::utf8([documentsDirectory UTF8String]));
  544. if (err != 0) {
  545. // bail, things did not go very well for us, should probably output a message on screen with our error code...
  546. exit(0);
  547. return FALSE;
  548. };
  549. // WARNING: We must *always* create the GLView after we have constructed the
  550. // OS with iphone_main. This allows the GLView to access project settings so
  551. // it can properly initialize the OpenGL context
  552. GLView *glView = [[GLView alloc] initWithFrame:rect];
  553. glView.delegate = self;
  554. view_controller = [[ViewController alloc] init];
  555. view_controller.view = glView;
  556. window.rootViewController = view_controller;
  557. _set_keep_screen_on(bool(GLOBAL_DEF("display/window/energy_saving/keep_screen_on", true)) ? YES : NO);
  558. glView.useCADisplayLink =
  559. bool(GLOBAL_DEF("display.iOS/use_cadisplaylink", true)) ? YES : NO;
  560. printf("cadisaplylink: %d", glView.useCADisplayLink);
  561. glView.animationInterval = 1.0 / kRenderingFrequency;
  562. [glView startAnimation];
  563. // Show the window
  564. [window makeKeyAndVisible];
  565. // Configure and start accelerometer
  566. if (!motionInitialised) {
  567. motionManager = [[CMMotionManager alloc] init];
  568. if (motionManager.deviceMotionAvailable) {
  569. motionManager.deviceMotionUpdateInterval = 1.0 / 70.0;
  570. [motionManager startDeviceMotionUpdatesUsingReferenceFrame:
  571. CMAttitudeReferenceFrameXMagneticNorthZVertical];
  572. motionInitialised = YES;
  573. };
  574. };
  575. [self initGameControllers];
  576. [[NSNotificationCenter defaultCenter]
  577. addObserver:self
  578. selector:@selector(onAudioInterruption:)
  579. name:AVAudioSessionInterruptionNotification
  580. object:[AVAudioSession sharedInstance]];
  581. // OSIPhone::screen_width = rect.size.width - rect.origin.x;
  582. // OSIPhone::screen_height = rect.size.height - rect.origin.y;
  583. mainViewController = view_controller;
  584. // prevent to stop music in another background app
  585. [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
  586. return TRUE;
  587. };
  588. - (void)onAudioInterruption:(NSNotification *)notification {
  589. if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) {
  590. if ([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeBegan]]) {
  591. NSLog(@"Audio interruption began");
  592. on_focus_out(view_controller, &is_focus_out);
  593. } else if ([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeEnded]]) {
  594. NSLog(@"Audio interruption ended");
  595. on_focus_in(view_controller, &is_focus_out);
  596. }
  597. }
  598. };
  599. - (void)applicationWillTerminate:(UIApplication *)application {
  600. [self deinitGameControllers];
  601. if (motionInitialised) {
  602. ///@TODO is this the right place to clean this up?
  603. [motionManager stopDeviceMotionUpdates];
  604. [motionManager release];
  605. motionManager = nil;
  606. motionInitialised = NO;
  607. };
  608. iphone_finish();
  609. };
  610. // When application goes to background (e.g. user switches to another app or presses Home),
  611. // then applicationWillResignActive -> applicationDidEnterBackground are called.
  612. // When user opens the inactive app again,
  613. // applicationWillEnterForeground -> applicationDidBecomeActive are called.
  614. // There are cases when applicationWillResignActive -> applicationDidBecomeActive
  615. // sequence is called without the app going to background. For example, that happens
  616. // if you open the app list without switching to another app or open/close the
  617. // notification panel by swiping from the upper part of the screen.
  618. - (void)applicationWillResignActive:(UIApplication *)application {
  619. on_focus_out(view_controller, &is_focus_out);
  620. }
  621. - (void)applicationDidBecomeActive:(UIApplication *)application {
  622. on_focus_in(view_controller, &is_focus_out);
  623. }
  624. - (void)dealloc {
  625. [window release];
  626. [super dealloc];
  627. }
  628. @end