app_delegate.mm 26 KB

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