PlatformiOS.mm 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. #ifdef __APPLE__
  2. #include "Base.h"
  3. #include "Platform.h"
  4. #include "FileSystem.h"
  5. #include "Game.h"
  6. #include "Form.h"
  7. #include "ScriptController.h"
  8. #include <unistd.h>
  9. #include <sys/time.h>
  10. #import <UIKit/UIKit.h>
  11. #import <GameKit/GameKit.h>
  12. #import <QuartzCore/QuartzCore.h>
  13. #import <CoreMotion/CoreMotion.h>
  14. #import <OpenGLES/EAGL.h>
  15. #import <OpenGLES/EAGLDrawable.h>
  16. #import <OpenGLES/ES2/gl.h>
  17. #import <OpenGLES/ES2/glext.h>
  18. #import <mach/mach_time.h>
  19. #define UIInterfaceOrientationEnum(x) ([x isEqualToString:@"UIInterfaceOrientationPortrait"]?UIInterfaceOrientationPortrait: \
  20. ([x isEqualToString:@"UIInterfaceOrientationPortraitUpsideDown"]?UIInterfaceOrientationPortraitUpsideDown: \
  21. ([x isEqualToString:@"UIInterfaceOrientationLandscapeLeft"]?UIInterfaceOrientationLandscapeLeft: \
  22. UIInterfaceOrientationLandscapeRight)))
  23. #define DeviceOrientedSize(o) ((o == UIInterfaceOrientationPortrait || o == UIInterfaceOrientationPortraitUpsideDown)? \
  24. CGSizeMake([[UIScreen mainScreen] bounds].size.width * [[UIScreen mainScreen] scale], [[UIScreen mainScreen] bounds].size.height * [[UIScreen mainScreen] scale]): \
  25. CGSizeMake([[UIScreen mainScreen] bounds].size.height * [[UIScreen mainScreen] scale], [[UIScreen mainScreen] bounds].size.width * [[UIScreen mainScreen] scale]))
  26. using namespace std;
  27. using namespace gameplay;
  28. // UIScreen bounds are provided as if device was in portrait mode Gameplay defaults to landscape
  29. extern const int WINDOW_WIDTH = [[UIScreen mainScreen] bounds].size.height * [[UIScreen mainScreen] scale];
  30. extern const int WINDOW_HEIGHT = [[UIScreen mainScreen] bounds].size.width * [[UIScreen mainScreen] scale];
  31. extern const int WINDOW_SCALE = [[UIScreen mainScreen] scale];
  32. int __argc = 0;
  33. char** __argv = 0;
  34. @class AppDelegate;
  35. @class View;
  36. static AppDelegate *__appDelegate = NULL;
  37. static View* __view = NULL;
  38. class TouchPoint
  39. {
  40. public:
  41. unsigned int hashId;
  42. int x;
  43. int y;
  44. bool down;
  45. TouchPoint()
  46. {
  47. hashId = 0;
  48. x = 0;
  49. y = 0;
  50. down = false;
  51. }
  52. };
  53. // gestures
  54. #define GESTURE_LONG_PRESS_DURATION_MIN 0.2
  55. #define GESTURE_LONG_PRESS_DISTANCE_MIN 10
  56. static CGPoint __gestureLongPressStartPosition;
  57. static long __gestureLongTapStartTimestamp = 0;
  58. static bool __gestureDraging = false;
  59. // more than we'd ever need, to be safe
  60. #define TOUCH_POINTS_MAX (10)
  61. static TouchPoint __touchPoints[TOUCH_POINTS_MAX];
  62. static double __timeStart;
  63. static double __timeAbsolute;
  64. static bool __vsync = WINDOW_VSYNC;
  65. static float __pitch;
  66. static float __roll;
  67. double getMachTimeInMilliseconds();
  68. int getKey(unichar keyCode);
  69. int getUnicode(int key);
  70. @interface View : UIView <UIKeyInput>
  71. {
  72. EAGLContext* context;
  73. CADisplayLink* displayLink;
  74. BOOL updateFramebuffer;
  75. GLuint defaultFramebuffer;
  76. GLuint colorRenderbuffer;
  77. GLuint depthRenderbuffer;
  78. GLint framebufferWidth;
  79. GLint framebufferHeight;
  80. GLuint multisampleFramebuffer;
  81. GLuint multisampleRenderbuffer;
  82. GLuint multisampleDepthbuffer;
  83. NSInteger swapInterval;
  84. BOOL updating;
  85. Game* game;
  86. BOOL oglDiscardSupported;
  87. UITapGestureRecognizer *_tapRecognizer;
  88. UIPinchGestureRecognizer *_pinchRecognizer;
  89. UISwipeGestureRecognizer *_swipeRecognizer;
  90. UILongPressGestureRecognizer *_longPressRecognizer;
  91. UILongPressGestureRecognizer *_longTapRecognizer;
  92. UILongPressGestureRecognizer *_dragAndDropRecognizer;
  93. }
  94. @property (readonly, nonatomic, getter=isUpdating) BOOL updating;
  95. @property (readonly, nonatomic, getter=getContext) EAGLContext* context;
  96. - (void)startGame;
  97. - (void)startUpdating;
  98. - (void)stopUpdating;
  99. - (void)update:(id)sender;
  100. - (void)setSwapInterval:(NSInteger)interval;
  101. - (int)swapInterval;
  102. - (void)swapBuffers;
  103. - (BOOL)showKeyboard;
  104. - (BOOL)dismissKeyboard;
  105. @end
  106. @interface View (Private)
  107. - (BOOL)createFramebuffer;
  108. - (void)deleteFramebuffer;
  109. @end
  110. @implementation View
  111. @synthesize updating;
  112. @synthesize context;
  113. + (Class) layerClass
  114. {
  115. return [CAEAGLLayer class];
  116. }
  117. - (id) initWithFrame:(CGRect)frame
  118. {
  119. if ((self = [super initWithFrame:frame]))
  120. {
  121. // A system version of 3.1 or greater is required to use CADisplayLink.
  122. NSString *reqSysVer = @"3.1";
  123. NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
  124. if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
  125. {
  126. // Log the system version
  127. NSLog(@"System Version: %@", currSysVer);
  128. }
  129. else
  130. {
  131. GP_ERROR("Invalid OS Version: %s\n", (currSysVer == NULL?"NULL":[currSysVer cStringUsingEncoding:NSASCIIStringEncoding]));
  132. [self release];
  133. return nil;
  134. }
  135. // Check for OS 4.0+ features
  136. if ([currSysVer compare:@"4.0" options:NSNumericSearch] != NSOrderedAscending)
  137. {
  138. oglDiscardSupported = YES;
  139. }
  140. else
  141. {
  142. oglDiscardSupported = NO;
  143. }
  144. // Configure the CAEAGLLayer and setup out the rendering context
  145. CGFloat scale = [[UIScreen mainScreen] scale];
  146. CAEAGLLayer* layer = (CAEAGLLayer *)self.layer;
  147. layer.opaque = TRUE;
  148. layer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
  149. [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking,
  150. kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
  151. self.contentScaleFactor = scale;
  152. layer.contentsScale = scale;
  153. context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
  154. if (!context || ![EAGLContext setCurrentContext:context])
  155. {
  156. GP_ERROR("Failed to make context current.");
  157. [self release];
  158. return nil;
  159. }
  160. // Initialize Internal Defaults
  161. displayLink = nil;
  162. updateFramebuffer = YES;
  163. defaultFramebuffer = 0;
  164. colorRenderbuffer = 0;
  165. depthRenderbuffer = 0;
  166. framebufferWidth = 0;
  167. framebufferHeight = 0;
  168. multisampleFramebuffer = 0;
  169. multisampleRenderbuffer = 0;
  170. multisampleDepthbuffer = 0;
  171. swapInterval = 1;
  172. updating = FALSE;
  173. game = nil;
  174. // Set the resource path and initalize the game
  175. NSString* bundlePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/"];
  176. FileSystem::setResourcePath([bundlePath fileSystemRepresentation]);
  177. }
  178. return self;
  179. }
  180. - (void) dealloc
  181. {
  182. if (game)
  183. game->exit();
  184. [self deleteFramebuffer];
  185. if ([EAGLContext currentContext] == context)
  186. {
  187. [EAGLContext setCurrentContext:nil];
  188. }
  189. [context release];
  190. [super dealloc];
  191. }
  192. - (BOOL)canBecomeFirstResponder
  193. {
  194. // Override so we can control the keyboard
  195. return YES;
  196. }
  197. - (void) layoutSubviews
  198. {
  199. // Called on 'resize'.
  200. // Mark that framebuffer needs to be updated.
  201. // NOTE: Current disabled since we need to have a way to reset the default frame buffer handle
  202. // in FrameBuffer.cpp (for FrameBuffer:bindDefault). This means that changing orientation at
  203. // runtime is currently not supported until we fix this.
  204. //updateFramebuffer = YES;
  205. }
  206. - (BOOL)createFramebuffer
  207. {
  208. // iOS Requires all content go to a rendering buffer then it is swapped into the windows rendering surface
  209. assert(defaultFramebuffer == 0);
  210. // Create the default frame buffer
  211. GL_ASSERT( glGenFramebuffers(1, &defaultFramebuffer) );
  212. GL_ASSERT( glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer) );
  213. // Create a color buffer to attach to the frame buffer
  214. GL_ASSERT( glGenRenderbuffers(1, &colorRenderbuffer) );
  215. GL_ASSERT( glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer) );
  216. // Associate render buffer storage with CAEAGLLauyer so that the rendered content is display on our UI layer.
  217. [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer *)self.layer];
  218. // Attach the color buffer to our frame buffer
  219. GL_ASSERT( glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderbuffer) );
  220. // Retrieve framebuffer size
  221. GL_ASSERT( glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &framebufferWidth) );
  222. GL_ASSERT( glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &framebufferHeight) );
  223. NSLog(@"width: %d, height: %d", framebufferWidth, framebufferHeight);
  224. // If multisampling is enabled in config, create and setup a multisample buffer
  225. Properties* config = Game::getInstance()->getConfig()->getNamespace("window", true);
  226. int samples = config ? config->getInt("samples") : 0;
  227. if (samples < 0)
  228. samples = 0;
  229. if (samples)
  230. {
  231. // Create multisample framebuffer
  232. GL_ASSERT( glGenFramebuffers(1, &multisampleFramebuffer) );
  233. GL_ASSERT( glBindFramebuffer(GL_FRAMEBUFFER, multisampleFramebuffer) );
  234. // Create multisample render and depth buffers
  235. GL_ASSERT( glGenRenderbuffers(1, &multisampleRenderbuffer) );
  236. GL_ASSERT( glGenRenderbuffers(1, &multisampleDepthbuffer) );
  237. // Try to find a supported multisample configuration starting with the defined sample count
  238. while (samples)
  239. {
  240. GL_ASSERT( glBindRenderbuffer(GL_RENDERBUFFER, multisampleRenderbuffer) );
  241. GL_ASSERT( glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, samples, GL_RGBA8_OES, framebufferWidth, framebufferHeight) );
  242. GL_ASSERT( glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, multisampleRenderbuffer) );
  243. GL_ASSERT( glBindRenderbuffer(GL_RENDERBUFFER, multisampleDepthbuffer) );
  244. GL_ASSERT( glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, samples, GL_DEPTH_COMPONENT24_OES, framebufferWidth, framebufferHeight) );
  245. GL_ASSERT( glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, multisampleDepthbuffer) );
  246. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
  247. break; // success!
  248. NSLog(@"Creation of multisample buffer with samples=%d failed. Attempting to use configuration with samples=%d instead: %x", samples, samples / 2, glCheckFramebufferStatus(GL_FRAMEBUFFER));
  249. samples /= 2;
  250. }
  251. //todo: __multiSampling = samples > 0;
  252. // Re-bind the default framebuffer
  253. GL_ASSERT( glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer) );
  254. if (samples == 0)
  255. {
  256. // Unable to find a valid/supported multisample configuratoin - fallback to no multisampling
  257. GL_ASSERT( glDeleteRenderbuffers(1, &multisampleRenderbuffer) );
  258. GL_ASSERT( glDeleteRenderbuffers(1, &multisampleDepthbuffer) );
  259. GL_ASSERT( glDeleteFramebuffers(1, &multisampleFramebuffer) );
  260. multisampleFramebuffer = multisampleRenderbuffer = multisampleDepthbuffer = 0;
  261. }
  262. }
  263. // Create default depth buffer and attach to the frame buffer.
  264. // Note: If we are using multisample buffers, we can skip depth buffer creation here since we only
  265. // need the color buffer to resolve to.
  266. if (multisampleFramebuffer == 0)
  267. {
  268. GL_ASSERT( glGenRenderbuffers(1, &depthRenderbuffer) );
  269. GL_ASSERT( glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer) );
  270. GL_ASSERT( glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24_OES, framebufferWidth, framebufferHeight) );
  271. GL_ASSERT( glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer) );
  272. }
  273. // Sanity check, ensure that the framebuffer is valid
  274. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  275. {
  276. NSLog(@"ERROR: Failed to make complete framebuffer object %x", glCheckFramebufferStatus(GL_FRAMEBUFFER));
  277. [self deleteFramebuffer];
  278. return NO;
  279. }
  280. // If multisampling is enabled, set the currently bound framebuffer to the multisample buffer
  281. // since that is the buffer code should be drawing into (and FrameBuffr::initialize will detect
  282. // and set this bound buffer as the default one during initialization.
  283. if (multisampleFramebuffer)
  284. GL_ASSERT( glBindFramebuffer(GL_FRAMEBUFFER, multisampleFramebuffer) );
  285. return YES;
  286. }
  287. - (void)deleteFramebuffer
  288. {
  289. if (context)
  290. {
  291. [EAGLContext setCurrentContext:context];
  292. if (defaultFramebuffer)
  293. {
  294. GL_ASSERT( glDeleteFramebuffers(1, &defaultFramebuffer) );
  295. defaultFramebuffer = 0;
  296. }
  297. if (colorRenderbuffer)
  298. {
  299. GL_ASSERT( glDeleteRenderbuffers(1, &colorRenderbuffer) );
  300. colorRenderbuffer = 0;
  301. }
  302. if (depthRenderbuffer)
  303. {
  304. GL_ASSERT( glDeleteRenderbuffers(1, &depthRenderbuffer) );
  305. depthRenderbuffer = 0;
  306. }
  307. if (multisampleFramebuffer)
  308. {
  309. GL_ASSERT( glDeleteFramebuffers(1, &multisampleFramebuffer) );
  310. multisampleFramebuffer = 0;
  311. }
  312. if (multisampleRenderbuffer)
  313. {
  314. GL_ASSERT( glDeleteRenderbuffers(1, &multisampleRenderbuffer) );
  315. multisampleRenderbuffer = 0;
  316. }
  317. if (multisampleDepthbuffer)
  318. {
  319. GL_ASSERT( glDeleteRenderbuffers(1, &multisampleDepthbuffer) );
  320. multisampleDepthbuffer = 0;
  321. }
  322. }
  323. }
  324. - (void)setSwapInterval:(NSInteger)interval
  325. {
  326. if (interval >= 1)
  327. {
  328. swapInterval = interval;
  329. if (updating)
  330. {
  331. [self stopUpdating];
  332. [self startUpdating];
  333. }
  334. }
  335. }
  336. - (int)swapInterval
  337. {
  338. return swapInterval;
  339. }
  340. - (void)swapBuffers
  341. {
  342. if (context)
  343. {
  344. if (multisampleFramebuffer)
  345. {
  346. // Multisampling is enabled: resolve the multisample buffer into the default framebuffer
  347. GL_ASSERT( glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, defaultFramebuffer) );
  348. GL_ASSERT( glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, multisampleFramebuffer) );
  349. GL_ASSERT( glResolveMultisampleFramebufferAPPLE() );
  350. if (oglDiscardSupported)
  351. {
  352. // Performance hint that the GL driver can discard the contents of the multisample buffers
  353. // since they have now been resolved into the default framebuffer
  354. const GLenum discards[] = { GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT };
  355. GL_ASSERT( glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 2, discards) );
  356. }
  357. }
  358. else
  359. {
  360. if (oglDiscardSupported)
  361. {
  362. // Performance hint to the GL driver that the depth buffer is no longer required.
  363. const GLenum discards[] = { GL_DEPTH_ATTACHMENT };
  364. GL_ASSERT( glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer) );
  365. GL_ASSERT( glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, discards) );
  366. }
  367. }
  368. // Present the color buffer
  369. GL_ASSERT( glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer) );
  370. [context presentRenderbuffer:GL_RENDERBUFFER];
  371. }
  372. }
  373. - (void)startGame
  374. {
  375. if (game == nil)
  376. {
  377. game = Game::getInstance();
  378. __timeStart = getMachTimeInMilliseconds();
  379. game->run();
  380. }
  381. }
  382. - (void)startUpdating
  383. {
  384. if (!updating)
  385. {
  386. displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update:)];
  387. [displayLink setFrameInterval:swapInterval];
  388. [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  389. if (game)
  390. game->resume();
  391. updating = TRUE;
  392. }
  393. }
  394. - (void)stopUpdating
  395. {
  396. if (updating)
  397. {
  398. if (game)
  399. game->pause();
  400. [displayLink invalidate];
  401. displayLink = nil;
  402. updating = FALSE;
  403. }
  404. }
  405. - (void)update:(id)sender
  406. {
  407. if (context != nil)
  408. {
  409. // Ensure our context is current
  410. [EAGLContext setCurrentContext:context];
  411. // If the framebuffer needs (re)creating, do so
  412. if (updateFramebuffer)
  413. {
  414. updateFramebuffer = NO;
  415. [self deleteFramebuffer];
  416. [self createFramebuffer];
  417. // Start the game after our framebuffer is created for the first time.
  418. if (game == nil)
  419. {
  420. [self startGame];
  421. // HACK: Skip the first display update after creating buffers and initializing the game.
  422. // If we don't do this, the first frame (which includes any drawing during initialization)
  423. // does not make it to the display for some reason.
  424. return;
  425. }
  426. }
  427. // Bind our framebuffer for rendering.
  428. // If multisampling is enabled, bind the multisample buffer - otherwise bind the default buffer
  429. GL_ASSERT( glBindFramebuffer(GL_FRAMEBUFFER, multisampleFramebuffer ? multisampleFramebuffer : defaultFramebuffer) );
  430. GL_ASSERT( glViewport(0, 0, framebufferWidth, framebufferHeight) );
  431. // Execute a single game frame
  432. if (game)
  433. game->frame();
  434. // Present the contents of the color buffer
  435. [self swapBuffers];
  436. }
  437. }
  438. - (BOOL)showKeyboard
  439. {
  440. return [self becomeFirstResponder];
  441. }
  442. - (BOOL)dismissKeyboard
  443. {
  444. return [self resignFirstResponder];
  445. }
  446. - (void)insertText:(NSString*)text
  447. {
  448. if([text length] == 0) return;
  449. assert([text length] == 1);
  450. unichar c = [text characterAtIndex:0];
  451. int key = getKey(c);
  452. Platform::keyEventInternal(Keyboard::KEY_PRESS, key);
  453. int character = getUnicode(key);
  454. if (character)
  455. {
  456. Platform::keyEventInternal(Keyboard::KEY_CHAR, /*character*/c);
  457. }
  458. Platform::keyEventInternal(Keyboard::KEY_RELEASE, key);
  459. }
  460. - (void)deleteBackward
  461. {
  462. Platform::keyEventInternal(Keyboard::KEY_PRESS, Keyboard::KEY_BACKSPACE);
  463. Platform::keyEventInternal(Keyboard::KEY_CHAR, getUnicode(Keyboard::KEY_BACKSPACE));
  464. Platform::keyEventInternal(Keyboard::KEY_RELEASE, Keyboard::KEY_BACKSPACE);
  465. }
  466. - (BOOL)hasText
  467. {
  468. return YES;
  469. }
  470. - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
  471. {
  472. unsigned int touchID = 0;
  473. for(UITouch* touch in touches)
  474. {
  475. CGPoint touchPoint = [touch locationInView:self];
  476. if(self.multipleTouchEnabled == YES)
  477. {
  478. touchID = [touch hash];
  479. }
  480. // Nested loop efficiency shouldn't be a concern since both loop sizes are small (<= 10)
  481. int i = 0;
  482. while (i < TOUCH_POINTS_MAX && __touchPoints[i].down)
  483. {
  484. i++;
  485. }
  486. if (i < TOUCH_POINTS_MAX)
  487. {
  488. __touchPoints[i].hashId = touchID;
  489. __touchPoints[i].x = touchPoint.x * WINDOW_SCALE;
  490. __touchPoints[i].y = touchPoint.y * WINDOW_SCALE;
  491. __touchPoints[i].down = true;
  492. Platform::touchEventInternal(Touch::TOUCH_PRESS, __touchPoints[i].x, __touchPoints[i].y, i);
  493. }
  494. else
  495. {
  496. print("touchesBegan: unable to find free element in __touchPoints");
  497. }
  498. }
  499. }
  500. - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
  501. {
  502. unsigned int touchID = 0;
  503. for(UITouch* touch in touches)
  504. {
  505. CGPoint touchPoint = [touch locationInView:self];
  506. if(self.multipleTouchEnabled == YES)
  507. touchID = [touch hash];
  508. // Nested loop efficiency shouldn't be a concern since both loop sizes are small (<= 10)
  509. bool found = false;
  510. for (int i = 0; !found && i < TOUCH_POINTS_MAX; i++)
  511. {
  512. if (__touchPoints[i].down && __touchPoints[i].hashId == touchID)
  513. {
  514. __touchPoints[i].down = false;
  515. Platform::touchEventInternal(Touch::TOUCH_RELEASE, touchPoint.x * WINDOW_SCALE, touchPoint.y * WINDOW_SCALE, i);
  516. found = true;
  517. }
  518. }
  519. if (!found)
  520. {
  521. // It seems possible to receive an ID not in the array.
  522. // The best we can do is clear the whole array.
  523. for (int i = 0; i < TOUCH_POINTS_MAX; i++)
  524. {
  525. if (__touchPoints[i].down)
  526. {
  527. __touchPoints[i].down = false;
  528. Platform::touchEventInternal(Touch::TOUCH_RELEASE, __touchPoints[i].x, __touchPoints[i].y, i);
  529. }
  530. }
  531. }
  532. }
  533. }
  534. - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event
  535. {
  536. // No equivalent for this in GamePlay -- treat as touch end
  537. [self touchesEnded:touches withEvent:event];
  538. }
  539. - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
  540. {
  541. unsigned int touchID = 0;
  542. for(UITouch* touch in touches)
  543. {
  544. CGPoint touchPoint = [touch locationInView:self];
  545. if(self.multipleTouchEnabled == YES)
  546. touchID = [touch hash];
  547. // Nested loop efficiency shouldn't be a concern since both loop sizes are small (<= 10)
  548. for (int i = 0; i < TOUCH_POINTS_MAX; i++)
  549. {
  550. if (__touchPoints[i].down && __touchPoints[i].hashId == touchID)
  551. {
  552. __touchPoints[i].x = touchPoint.x * WINDOW_SCALE;
  553. __touchPoints[i].y = touchPoint.y * WINDOW_SCALE;
  554. Platform::touchEventInternal(Touch::TOUCH_MOVE, __touchPoints[i].x, __touchPoints[i].y, i);
  555. break;
  556. }
  557. }
  558. }
  559. }
  560. // Gesture support for Mac OS X Trackpads
  561. - (bool)isGestureRegistered: (Gesture::GestureEvent) evt
  562. {
  563. switch(evt) {
  564. case Gesture::GESTURE_SWIPE:
  565. return (_swipeRecognizer != NULL);
  566. case Gesture::GESTURE_PINCH:
  567. return (_pinchRecognizer != NULL);
  568. case Gesture::GESTURE_TAP:
  569. return (_tapRecognizer != NULL);
  570. case Gesture::GESTURE_LONG_TAP:
  571. return (_longTapRecognizer != NULL);
  572. case Gesture::GESTURE_DRAG:
  573. case Gesture::GESTURE_DROP:
  574. return (_dragAndDropRecognizer != NULL);
  575. default:
  576. break;
  577. }
  578. return false;
  579. }
  580. - (void)registerGesture: (Gesture::GestureEvent) evt
  581. {
  582. if((evt & Gesture::GESTURE_SWIPE) == Gesture::GESTURE_SWIPE && _swipeRecognizer == NULL)
  583. {
  584. // right swipe (default)
  585. _swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
  586. [self addGestureRecognizer:_swipeRecognizer];
  587. // left swipe
  588. UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
  589. swipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
  590. [self addGestureRecognizer:swipeGesture];
  591. [swipeGesture release];
  592. // up swipe
  593. UISwipeGestureRecognizer *swipeGesture2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
  594. swipeGesture2.direction = UISwipeGestureRecognizerDirectionUp;
  595. [self addGestureRecognizer:swipeGesture2];
  596. [swipeGesture2 release];
  597. // down swipe
  598. UISwipeGestureRecognizer *swipeGesture3 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
  599. swipeGesture3.direction = UISwipeGestureRecognizerDirectionDown;
  600. [self addGestureRecognizer:swipeGesture3];
  601. [swipeGesture3 release];
  602. }
  603. if((evt & Gesture::GESTURE_PINCH) == Gesture::GESTURE_PINCH && _pinchRecognizer == NULL)
  604. {
  605. _pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
  606. [self addGestureRecognizer:_pinchRecognizer];
  607. }
  608. if((evt & Gesture::GESTURE_TAP) == Gesture::GESTURE_TAP && _tapRecognizer == NULL)
  609. {
  610. _tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
  611. [self addGestureRecognizer:_tapRecognizer];
  612. }
  613. if ((evt & Gesture::GESTURE_LONG_TAP) == Gesture::GESTURE_LONG_TAP && _longTapRecognizer == NULL)
  614. {
  615. if (_longPressRecognizer == NULL)
  616. {
  617. _longPressRecognizer =[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGestures:)];
  618. _longPressRecognizer.minimumPressDuration = GESTURE_LONG_PRESS_DURATION_MIN;
  619. _longPressRecognizer.allowableMovement = CGFLOAT_MAX;
  620. [self addGestureRecognizer:_longPressRecognizer];
  621. }
  622. _longTapRecognizer = _longPressRecognizer;
  623. }
  624. if (((evt & Gesture::GESTURE_DRAG) == Gesture::GESTURE_DRAG || (evt & Gesture::GESTURE_DROP) == Gesture::GESTURE_DROP) && _dragAndDropRecognizer == NULL)
  625. {
  626. if (_longPressRecognizer == NULL)
  627. {
  628. _longPressRecognizer =[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGestures:)];
  629. _longPressRecognizer.minimumPressDuration = GESTURE_LONG_PRESS_DURATION_MIN;
  630. _longPressRecognizer.allowableMovement = CGFLOAT_MAX;
  631. [self addGestureRecognizer:_longPressRecognizer];
  632. }
  633. _dragAndDropRecognizer = _longPressRecognizer;
  634. }
  635. }
  636. - (void)unregisterGesture: (Gesture::GestureEvent) evt
  637. {
  638. if((evt & Gesture::GESTURE_SWIPE) == Gesture::GESTURE_SWIPE && _swipeRecognizer != NULL)
  639. {
  640. [self removeGestureRecognizer:_swipeRecognizer];
  641. [_swipeRecognizer release];
  642. _swipeRecognizer = NULL;
  643. }
  644. if((evt & Gesture::GESTURE_PINCH) == Gesture::GESTURE_PINCH && _pinchRecognizer != NULL)
  645. {
  646. [self removeGestureRecognizer:_pinchRecognizer];
  647. [_pinchRecognizer release];
  648. _pinchRecognizer = NULL;
  649. }
  650. if((evt & Gesture::GESTURE_TAP) == Gesture::GESTURE_TAP && _tapRecognizer != NULL)
  651. {
  652. [self removeGestureRecognizer:_tapRecognizer];
  653. [_tapRecognizer release];
  654. _tapRecognizer = NULL;
  655. }
  656. if((evt & Gesture::GESTURE_LONG_TAP) == Gesture::GESTURE_LONG_TAP && _longTapRecognizer != NULL)
  657. {
  658. if (_dragAndDropRecognizer == NULL)
  659. {
  660. [self removeGestureRecognizer:_longPressRecognizer];
  661. [_longPressRecognizer release];
  662. }
  663. _longTapRecognizer = NULL;
  664. }
  665. if (((evt & Gesture::GESTURE_DRAG) == Gesture::GESTURE_DRAG || (evt & Gesture::GESTURE_DROP) == Gesture::GESTURE_DROP) && _dragAndDropRecognizer != NULL)
  666. {
  667. if (_longTapRecognizer == NULL)
  668. {
  669. [self removeGestureRecognizer:_longPressRecognizer];
  670. [_longPressRecognizer release];
  671. }
  672. _dragAndDropRecognizer = NULL;
  673. }
  674. }
  675. - (void)handleTapGesture:(UITapGestureRecognizer*)sender
  676. {
  677. CGPoint location = [sender locationInView:self];
  678. gameplay::Platform::gestureTapEventInternal(location.x, location.y);
  679. }
  680. - (void)handleLongTapGesture:(UILongPressGestureRecognizer*)sender
  681. {
  682. if (sender.state == UIGestureRecognizerStateBegan)
  683. {
  684. struct timeval time;
  685. gettimeofday(&time, NULL);
  686. __gestureLongTapStartTimestamp = (time.tv_sec * 1000) + (time.tv_usec / 1000);
  687. }
  688. else if (sender.state == UIGestureRecognizerStateEnded)
  689. {
  690. CGPoint location = [sender locationInView:self];
  691. struct timeval time;
  692. long currentTimeStamp;
  693. gettimeofday(&time, NULL);
  694. currentTimeStamp = (time.tv_sec * 1000) + (time.tv_usec / 1000);
  695. gameplay::Platform::gestureLongTapEventInternal(location.x, location.y, currentTimeStamp - __gestureLongTapStartTimestamp);
  696. }
  697. }
  698. - (void)handlePinchGesture:(UIPinchGestureRecognizer*)sender
  699. {
  700. CGFloat factor = [sender scale];
  701. CGPoint location = [sender locationInView:self];
  702. gameplay::Platform::gesturePinchEventInternal(location.x, location.y, factor);
  703. }
  704. - (void)handleSwipeGesture:(UISwipeGestureRecognizer*)sender
  705. {
  706. UISwipeGestureRecognizerDirection direction = [sender direction];
  707. CGPoint location = [sender locationInView:self];
  708. int gameplayDirection = 0;
  709. switch(direction) {
  710. case UISwipeGestureRecognizerDirectionRight:
  711. gameplayDirection = Gesture::SWIPE_DIRECTION_RIGHT;
  712. break;
  713. case UISwipeGestureRecognizerDirectionLeft:
  714. gameplayDirection = Gesture::SWIPE_DIRECTION_LEFT;
  715. break;
  716. case UISwipeGestureRecognizerDirectionUp:
  717. gameplayDirection = Gesture::SWIPE_DIRECTION_UP;
  718. break;
  719. case UISwipeGestureRecognizerDirectionDown:
  720. gameplayDirection = Gesture::SWIPE_DIRECTION_DOWN;
  721. break;
  722. }
  723. gameplay::Platform::gestureSwipeEventInternal(location.x, location.y, gameplayDirection);
  724. }
  725. - (void)handleLongPressGestures:(UILongPressGestureRecognizer*)sender
  726. {
  727. CGPoint location = [sender locationInView:self];
  728. if (sender.state == UIGestureRecognizerStateBegan)
  729. {
  730. struct timeval time;
  731. gettimeofday(&time, NULL);
  732. __gestureLongTapStartTimestamp = (time.tv_sec * 1000) + (time.tv_usec / 1000);
  733. __gestureLongPressStartPosition = location;
  734. }
  735. if (sender.state == UIGestureRecognizerStateChanged)
  736. {
  737. if (__gestureDraging)
  738. gameplay::Platform::gestureDragEventInternal(location.x, location.y);
  739. else
  740. {
  741. float delta = sqrt(pow(__gestureLongPressStartPosition.x - location.x, 2) + pow(__gestureLongPressStartPosition.y - location.y, 2));
  742. if (delta >= GESTURE_LONG_PRESS_DISTANCE_MIN)
  743. {
  744. __gestureDraging = true;
  745. gameplay::Platform::gestureDragEventInternal(__gestureLongPressStartPosition.x, __gestureLongPressStartPosition.y);
  746. }
  747. }
  748. }
  749. if (sender.state == UIGestureRecognizerStateEnded)
  750. {
  751. if (__gestureDraging)
  752. {
  753. gameplay::Platform::gestureDropEventInternal(location.x, location.y);
  754. __gestureDraging = false;
  755. }
  756. else
  757. {
  758. struct timeval time;
  759. long currentTimeStamp;
  760. gettimeofday(&time, NULL);
  761. currentTimeStamp = (time.tv_sec * 1000) + (time.tv_usec / 1000);
  762. gameplay::Platform::gestureLongTapEventInternal(location.x, location.y, currentTimeStamp - __gestureLongTapStartTimestamp);
  763. }
  764. }
  765. if ((sender.state == UIGestureRecognizerStateCancelled || sender.state == UIGestureRecognizerStateFailed) && __gestureDraging)
  766. {
  767. gameplay::Platform::gestureDropEventInternal(location.x, location.y);
  768. __gestureDraging = false;
  769. }
  770. }
  771. @end
  772. @interface ViewController : UIViewController
  773. - (void)startUpdating;
  774. - (void)stopUpdating;
  775. - (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController;
  776. @end
  777. @implementation ViewController
  778. - (id)init
  779. {
  780. if((self = [super init]))
  781. {
  782. }
  783. return self;
  784. }
  785. - (void)dealloc
  786. {
  787. __view = nil;
  788. [super dealloc];
  789. }
  790. - (void)didReceiveMemoryWarning
  791. {
  792. [super didReceiveMemoryWarning];
  793. }
  794. #pragma mark - View lifecycle
  795. - (void)loadView
  796. {
  797. self.view = [[[View alloc] init] autorelease];
  798. if(__view == nil)
  799. {
  800. __view = (View*)self.view;
  801. }
  802. }
  803. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  804. {
  805. // Fetch the supported orientations array
  806. NSArray *supportedOrientations = NULL;
  807. if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
  808. {
  809. supportedOrientations = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations~ipad"];
  810. }
  811. else if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
  812. {
  813. supportedOrientations = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations~iphone"];
  814. }
  815. if(supportedOrientations == NULL)
  816. {
  817. supportedOrientations = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"];
  818. }
  819. // If no supported orientations default to v1.0 handling (landscape only)
  820. if(supportedOrientations == nil) {
  821. return UIInterfaceOrientationIsLandscape(interfaceOrientation);
  822. }
  823. for(NSString *s in supportedOrientations) {
  824. if(interfaceOrientation == UIInterfaceOrientationEnum(s)) return YES;
  825. }
  826. return NO;
  827. }
  828. - (void)startUpdating
  829. {
  830. [(View*)self.view startUpdating];
  831. }
  832. - (void)stopUpdating
  833. {
  834. [(View*)self.view stopUpdating];
  835. }
  836. - (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController
  837. {
  838. [self dismissViewControllerAnimated:YES completion:nil];
  839. }
  840. @end
  841. @interface AppDelegate : UIApplication <UIApplicationDelegate>
  842. {
  843. UIWindow* window;
  844. ViewController* viewController;
  845. CMMotionManager *motionManager;
  846. }
  847. @property (nonatomic, retain) ViewController *viewController;
  848. @end
  849. @implementation AppDelegate
  850. @synthesize viewController;
  851. - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  852. {
  853. __appDelegate = self;
  854. [UIApplication sharedApplication].statusBarHidden = YES;
  855. [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  856. motionManager = [[CMMotionManager alloc] init];
  857. if([motionManager isAccelerometerAvailable] == YES)
  858. {
  859. motionManager.accelerometerUpdateInterval = 1 / 40.0; // 40Hz
  860. [motionManager startAccelerometerUpdates];
  861. }
  862. if([motionManager isGyroAvailable] == YES)
  863. {
  864. motionManager.gyroUpdateInterval = 1 / 40.0; // 40Hz
  865. [motionManager startGyroUpdates];
  866. }
  867. window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  868. viewController = [[ViewController alloc] init];
  869. [window setRootViewController:viewController];
  870. [window makeKeyAndVisible];
  871. return YES;
  872. }
  873. - (BOOL)prefersStatusBarHidden
  874. {
  875. return YES;
  876. }
  877. - (void)getAccelerometerPitch:(float*)pitch roll:(float*)roll
  878. {
  879. float p = 0.0f;
  880. float r = 0.0f;
  881. CMAccelerometerData* accelerometerData = motionManager.accelerometerData;
  882. if(accelerometerData != nil)
  883. {
  884. float tx, ty, tz;
  885. switch ([[UIApplication sharedApplication] statusBarOrientation])
  886. {
  887. case UIInterfaceOrientationLandscapeRight:
  888. tx = -accelerometerData.acceleration.y;
  889. ty = accelerometerData.acceleration.x;
  890. break;
  891. case UIInterfaceOrientationLandscapeLeft:
  892. tx = accelerometerData.acceleration.y;
  893. ty = -accelerometerData.acceleration.x;
  894. break;
  895. case UIInterfaceOrientationPortraitUpsideDown:
  896. tx = -accelerometerData.acceleration.y;
  897. ty = -accelerometerData.acceleration.x;
  898. break;
  899. case UIInterfaceOrientationPortrait:
  900. tx = accelerometerData.acceleration.x;
  901. ty = accelerometerData.acceleration.y;
  902. break;
  903. }
  904. tz = accelerometerData.acceleration.z;
  905. p = atan(ty / sqrt(tx * tx + tz * tz)) * 180.0f * M_1_PI;
  906. r = atan(tx / sqrt(ty * ty + tz * tz)) * 180.0f * M_1_PI;
  907. }
  908. if(pitch != NULL)
  909. *pitch = p;
  910. if(roll != NULL)
  911. *roll = r;
  912. }
  913. - (void)getRawAccelX:(float*)x Y:(float*)y Z:(float*)z
  914. {
  915. CMAccelerometerData* accelerometerData = motionManager.accelerometerData;
  916. if(accelerometerData != nil)
  917. {
  918. *x = -9.81f * accelerometerData.acceleration.x;
  919. *y = -9.81f * accelerometerData.acceleration.y;
  920. *z = -9.81f * accelerometerData.acceleration.z;
  921. }
  922. }
  923. - (void)getRawGyroX:(float*)x Y:(float*)y Z:(float*)z
  924. {
  925. CMGyroData* gyroData = motionManager.gyroData;
  926. if(gyroData != nil)
  927. {
  928. *x = gyroData.rotationRate.x;
  929. *y = gyroData.rotationRate.y;
  930. *z = gyroData.rotationRate.z;
  931. }
  932. }
  933. - (void)applicationWillResignActive:(UIApplication*)application
  934. {
  935. [viewController stopUpdating];
  936. }
  937. - (void)applicationDidEnterBackground:(UIApplication*)application
  938. {
  939. [viewController stopUpdating];
  940. }
  941. - (void)applicationWillEnterForeground:(UIApplication*)application
  942. {
  943. [viewController startUpdating];
  944. }
  945. - (void)applicationDidBecomeActive:(UIApplication*)application
  946. {
  947. [viewController startUpdating];
  948. }
  949. - (void)applicationWillTerminate:(UIApplication*)application
  950. {
  951. [viewController stopUpdating];
  952. }
  953. - (void)dealloc
  954. {
  955. [window setRootViewController:nil];
  956. [viewController release];
  957. [window release];
  958. [motionManager release];
  959. [super dealloc];
  960. }
  961. @end
  962. double getMachTimeInMilliseconds()
  963. {
  964. static const double kOneMillion = 1000 * 1000;
  965. static mach_timebase_info_data_t s_timebase_info;
  966. if (s_timebase_info.denom == 0)
  967. (void) mach_timebase_info(&s_timebase_info);
  968. // mach_absolute_time() returns billionth of seconds, so divide by one million to get milliseconds
  969. GP_ASSERT(s_timebase_info.denom);
  970. return ((double)mach_absolute_time() * (double)s_timebase_info.numer) / (kOneMillion * (double)s_timebase_info.denom);
  971. }
  972. int getKey(unichar keyCode)
  973. {
  974. switch(keyCode)
  975. {
  976. case 0x0A:
  977. return Keyboard::KEY_RETURN;
  978. case 0x20:
  979. return Keyboard::KEY_SPACE;
  980. case 0x30:
  981. return Keyboard::KEY_ZERO;
  982. case 0x31:
  983. return Keyboard::KEY_ONE;
  984. case 0x32:
  985. return Keyboard::KEY_TWO;
  986. case 0x33:
  987. return Keyboard::KEY_THREE;
  988. case 0x34:
  989. return Keyboard::KEY_FOUR;
  990. case 0x35:
  991. return Keyboard::KEY_FIVE;
  992. case 0x36:
  993. return Keyboard::KEY_SIX;
  994. case 0x37:
  995. return Keyboard::KEY_SEVEN;
  996. case 0x38:
  997. return Keyboard::KEY_EIGHT;
  998. case 0x39:
  999. return Keyboard::KEY_NINE;
  1000. case 0x41:
  1001. return Keyboard::KEY_CAPITAL_A;
  1002. case 0x42:
  1003. return Keyboard::KEY_CAPITAL_B;
  1004. case 0x43:
  1005. return Keyboard::KEY_CAPITAL_C;
  1006. case 0x44:
  1007. return Keyboard::KEY_CAPITAL_D;
  1008. case 0x45:
  1009. return Keyboard::KEY_CAPITAL_E;
  1010. case 0x46:
  1011. return Keyboard::KEY_CAPITAL_F;
  1012. case 0x47:
  1013. return Keyboard::KEY_CAPITAL_G;
  1014. case 0x48:
  1015. return Keyboard::KEY_CAPITAL_H;
  1016. case 0x49:
  1017. return Keyboard::KEY_CAPITAL_I;
  1018. case 0x4A:
  1019. return Keyboard::KEY_CAPITAL_J;
  1020. case 0x4B:
  1021. return Keyboard::KEY_CAPITAL_K;
  1022. case 0x4C:
  1023. return Keyboard::KEY_CAPITAL_L;
  1024. case 0x4D:
  1025. return Keyboard::KEY_CAPITAL_M;
  1026. case 0x4E:
  1027. return Keyboard::KEY_CAPITAL_N;
  1028. case 0x4F:
  1029. return Keyboard::KEY_CAPITAL_O;
  1030. case 0x50:
  1031. return Keyboard::KEY_CAPITAL_P;
  1032. case 0x51:
  1033. return Keyboard::KEY_CAPITAL_Q;
  1034. case 0x52:
  1035. return Keyboard::KEY_CAPITAL_R;
  1036. case 0x53:
  1037. return Keyboard::KEY_CAPITAL_S;
  1038. case 0x54:
  1039. return Keyboard::KEY_CAPITAL_T;
  1040. case 0x55:
  1041. return Keyboard::KEY_CAPITAL_U;
  1042. case 0x56:
  1043. return Keyboard::KEY_CAPITAL_V;
  1044. case 0x57:
  1045. return Keyboard::KEY_CAPITAL_W;
  1046. case 0x58:
  1047. return Keyboard::KEY_CAPITAL_X;
  1048. case 0x59:
  1049. return Keyboard::KEY_CAPITAL_Y;
  1050. case 0x5A:
  1051. return Keyboard::KEY_CAPITAL_Z;
  1052. case 0x61:
  1053. return Keyboard::KEY_A;
  1054. case 0x62:
  1055. return Keyboard::KEY_B;
  1056. case 0x63:
  1057. return Keyboard::KEY_C;
  1058. case 0x64:
  1059. return Keyboard::KEY_D;
  1060. case 0x65:
  1061. return Keyboard::KEY_E;
  1062. case 0x66:
  1063. return Keyboard::KEY_F;
  1064. case 0x67:
  1065. return Keyboard::KEY_G;
  1066. case 0x68:
  1067. return Keyboard::KEY_H;
  1068. case 0x69:
  1069. return Keyboard::KEY_I;
  1070. case 0x6A:
  1071. return Keyboard::KEY_J;
  1072. case 0x6B:
  1073. return Keyboard::KEY_K;
  1074. case 0x6C:
  1075. return Keyboard::KEY_L;
  1076. case 0x6D:
  1077. return Keyboard::KEY_M;
  1078. case 0x6E:
  1079. return Keyboard::KEY_N;
  1080. case 0x6F:
  1081. return Keyboard::KEY_O;
  1082. case 0x70:
  1083. return Keyboard::KEY_P;
  1084. case 0x71:
  1085. return Keyboard::KEY_Q;
  1086. case 0x72:
  1087. return Keyboard::KEY_R;
  1088. case 0x73:
  1089. return Keyboard::KEY_S;
  1090. case 0x74:
  1091. return Keyboard::KEY_T;
  1092. case 0x75:
  1093. return Keyboard::KEY_U;
  1094. case 0x76:
  1095. return Keyboard::KEY_V;
  1096. case 0x77:
  1097. return Keyboard::KEY_W;
  1098. case 0x78:
  1099. return Keyboard::KEY_X;
  1100. case 0x79:
  1101. return Keyboard::KEY_Y;
  1102. case 0x7A:
  1103. return Keyboard::KEY_Z;
  1104. default:
  1105. break;
  1106. // Symbol Row 3
  1107. case 0x2E:
  1108. return Keyboard::KEY_PERIOD;
  1109. case 0x2C:
  1110. return Keyboard::KEY_COMMA;
  1111. case 0x3F:
  1112. return Keyboard::KEY_QUESTION;
  1113. case 0x21:
  1114. return Keyboard::KEY_EXCLAM;
  1115. case 0x27:
  1116. return Keyboard::KEY_APOSTROPHE;
  1117. // Symbols Row 2
  1118. case 0x2D:
  1119. return Keyboard::KEY_MINUS;
  1120. case 0x2F:
  1121. return Keyboard::KEY_SLASH;
  1122. case 0x3A:
  1123. return Keyboard::KEY_COLON;
  1124. case 0x3B:
  1125. return Keyboard::KEY_SEMICOLON;
  1126. case 0x28:
  1127. return Keyboard::KEY_LEFT_PARENTHESIS;
  1128. case 0x29:
  1129. return Keyboard::KEY_RIGHT_PARENTHESIS;
  1130. case 0x24:
  1131. return Keyboard::KEY_DOLLAR;
  1132. case 0x26:
  1133. return Keyboard::KEY_AMPERSAND;
  1134. case 0x40:
  1135. return Keyboard::KEY_AT;
  1136. case 0x22:
  1137. return Keyboard::KEY_QUOTE;
  1138. // Numeric Symbols Row 1
  1139. case 0x5B:
  1140. return Keyboard::KEY_LEFT_BRACKET;
  1141. case 0x5D:
  1142. return Keyboard::KEY_RIGHT_BRACKET;
  1143. case 0x7B:
  1144. return Keyboard::KEY_LEFT_BRACE;
  1145. case 0x7D:
  1146. return Keyboard::KEY_RIGHT_BRACE;
  1147. case 0x23:
  1148. return Keyboard::KEY_NUMBER;
  1149. case 0x25:
  1150. return Keyboard::KEY_PERCENT;
  1151. case 0x5E:
  1152. return Keyboard::KEY_CIRCUMFLEX;
  1153. case 0x2A:
  1154. return Keyboard::KEY_ASTERISK;
  1155. case 0x2B:
  1156. return Keyboard::KEY_PLUS;
  1157. case 0x3D:
  1158. return Keyboard::KEY_EQUAL;
  1159. // Numeric Symbols Row 2
  1160. case 0x5F:
  1161. return Keyboard::KEY_UNDERSCORE;
  1162. case 0x5C:
  1163. return Keyboard::KEY_BACK_SLASH;
  1164. case 0x7C:
  1165. return Keyboard::KEY_BAR;
  1166. case 0x7E:
  1167. return Keyboard::KEY_TILDE;
  1168. case 0x3C:
  1169. return Keyboard::KEY_LESS_THAN;
  1170. case 0x3E:
  1171. return Keyboard::KEY_GREATER_THAN;
  1172. case 0x80:
  1173. return Keyboard::KEY_EURO;
  1174. case 0xA3:
  1175. return Keyboard::KEY_POUND;
  1176. case 0xA5:
  1177. return Keyboard::KEY_YEN;
  1178. case 0xB7:
  1179. return Keyboard::KEY_MIDDLE_DOT;
  1180. }
  1181. return Keyboard::KEY_NONE;
  1182. }
  1183. /**
  1184. * Returns the unicode value for the given keycode or zero if the key is not a valid printable character.
  1185. */
  1186. int getUnicode(int key)
  1187. {
  1188. switch (key)
  1189. {
  1190. case Keyboard::KEY_BACKSPACE:
  1191. return 0x0008;
  1192. case Keyboard::KEY_TAB:
  1193. return 0x0009;
  1194. case Keyboard::KEY_RETURN:
  1195. case Keyboard::KEY_KP_ENTER:
  1196. return 0x000A;
  1197. case Keyboard::KEY_ESCAPE:
  1198. return 0x001B;
  1199. case Keyboard::KEY_SPACE:
  1200. case Keyboard::KEY_EXCLAM:
  1201. case Keyboard::KEY_QUOTE:
  1202. case Keyboard::KEY_NUMBER:
  1203. case Keyboard::KEY_DOLLAR:
  1204. case Keyboard::KEY_PERCENT:
  1205. case Keyboard::KEY_CIRCUMFLEX:
  1206. case Keyboard::KEY_AMPERSAND:
  1207. case Keyboard::KEY_APOSTROPHE:
  1208. case Keyboard::KEY_LEFT_PARENTHESIS:
  1209. case Keyboard::KEY_RIGHT_PARENTHESIS:
  1210. case Keyboard::KEY_ASTERISK:
  1211. case Keyboard::KEY_PLUS:
  1212. case Keyboard::KEY_COMMA:
  1213. case Keyboard::KEY_MINUS:
  1214. case Keyboard::KEY_PERIOD:
  1215. case Keyboard::KEY_SLASH:
  1216. case Keyboard::KEY_ZERO:
  1217. case Keyboard::KEY_ONE:
  1218. case Keyboard::KEY_TWO:
  1219. case Keyboard::KEY_THREE:
  1220. case Keyboard::KEY_FOUR:
  1221. case Keyboard::KEY_FIVE:
  1222. case Keyboard::KEY_SIX:
  1223. case Keyboard::KEY_SEVEN:
  1224. case Keyboard::KEY_EIGHT:
  1225. case Keyboard::KEY_NINE:
  1226. case Keyboard::KEY_COLON:
  1227. case Keyboard::KEY_SEMICOLON:
  1228. case Keyboard::KEY_LESS_THAN:
  1229. case Keyboard::KEY_EQUAL:
  1230. case Keyboard::KEY_GREATER_THAN:
  1231. case Keyboard::KEY_QUESTION:
  1232. case Keyboard::KEY_AT:
  1233. case Keyboard::KEY_CAPITAL_A:
  1234. case Keyboard::KEY_CAPITAL_B:
  1235. case Keyboard::KEY_CAPITAL_C:
  1236. case Keyboard::KEY_CAPITAL_D:
  1237. case Keyboard::KEY_CAPITAL_E:
  1238. case Keyboard::KEY_CAPITAL_F:
  1239. case Keyboard::KEY_CAPITAL_G:
  1240. case Keyboard::KEY_CAPITAL_H:
  1241. case Keyboard::KEY_CAPITAL_I:
  1242. case Keyboard::KEY_CAPITAL_J:
  1243. case Keyboard::KEY_CAPITAL_K:
  1244. case Keyboard::KEY_CAPITAL_L:
  1245. case Keyboard::KEY_CAPITAL_M:
  1246. case Keyboard::KEY_CAPITAL_N:
  1247. case Keyboard::KEY_CAPITAL_O:
  1248. case Keyboard::KEY_CAPITAL_P:
  1249. case Keyboard::KEY_CAPITAL_Q:
  1250. case Keyboard::KEY_CAPITAL_R:
  1251. case Keyboard::KEY_CAPITAL_S:
  1252. case Keyboard::KEY_CAPITAL_T:
  1253. case Keyboard::KEY_CAPITAL_U:
  1254. case Keyboard::KEY_CAPITAL_V:
  1255. case Keyboard::KEY_CAPITAL_W:
  1256. case Keyboard::KEY_CAPITAL_X:
  1257. case Keyboard::KEY_CAPITAL_Y:
  1258. case Keyboard::KEY_CAPITAL_Z:
  1259. case Keyboard::KEY_LEFT_BRACKET:
  1260. case Keyboard::KEY_BACK_SLASH:
  1261. case Keyboard::KEY_RIGHT_BRACKET:
  1262. case Keyboard::KEY_UNDERSCORE:
  1263. case Keyboard::KEY_GRAVE:
  1264. case Keyboard::KEY_A:
  1265. case Keyboard::KEY_B:
  1266. case Keyboard::KEY_C:
  1267. case Keyboard::KEY_D:
  1268. case Keyboard::KEY_E:
  1269. case Keyboard::KEY_F:
  1270. case Keyboard::KEY_G:
  1271. case Keyboard::KEY_H:
  1272. case Keyboard::KEY_I:
  1273. case Keyboard::KEY_J:
  1274. case Keyboard::KEY_K:
  1275. case Keyboard::KEY_L:
  1276. case Keyboard::KEY_M:
  1277. case Keyboard::KEY_N:
  1278. case Keyboard::KEY_O:
  1279. case Keyboard::KEY_P:
  1280. case Keyboard::KEY_Q:
  1281. case Keyboard::KEY_R:
  1282. case Keyboard::KEY_S:
  1283. case Keyboard::KEY_T:
  1284. case Keyboard::KEY_U:
  1285. case Keyboard::KEY_V:
  1286. case Keyboard::KEY_W:
  1287. case Keyboard::KEY_X:
  1288. case Keyboard::KEY_Y:
  1289. case Keyboard::KEY_Z:
  1290. case Keyboard::KEY_LEFT_BRACE:
  1291. case Keyboard::KEY_BAR:
  1292. case Keyboard::KEY_RIGHT_BRACE:
  1293. case Keyboard::KEY_TILDE:
  1294. return key;
  1295. default:
  1296. return 0;
  1297. }
  1298. }
  1299. namespace gameplay
  1300. {
  1301. extern void print(const char* format, ...)
  1302. {
  1303. GP_ASSERT(format);
  1304. va_list argptr;
  1305. va_start(argptr, format);
  1306. vfprintf(stderr, format, argptr);
  1307. va_end(argptr);
  1308. }
  1309. Platform::Platform(Game* game) : _game(game)
  1310. {
  1311. }
  1312. Platform::~Platform()
  1313. {
  1314. }
  1315. Platform* Platform::create(Game* game)
  1316. {
  1317. Platform* platform = new Platform(game);
  1318. return platform;
  1319. }
  1320. int Platform::enterMessagePump()
  1321. {
  1322. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  1323. [AppDelegate load];
  1324. UIApplicationMain(0, nil, NSStringFromClass([AppDelegate class]), NSStringFromClass([AppDelegate class]));
  1325. [pool release];
  1326. return EXIT_SUCCESS;
  1327. }
  1328. void Platform::signalShutdown()
  1329. {
  1330. // Cannot 'exit' an iOS Application
  1331. assert(false);
  1332. [__view stopUpdating];
  1333. exit(0);
  1334. }
  1335. bool Platform::canExit()
  1336. {
  1337. return false;
  1338. }
  1339. unsigned int Platform::getDisplayWidth()
  1340. {
  1341. CGSize size = DeviceOrientedSize([__appDelegate.viewController interfaceOrientation]);
  1342. return size.width;
  1343. }
  1344. unsigned int Platform::getDisplayHeight()
  1345. {
  1346. CGSize size = DeviceOrientedSize([__appDelegate.viewController interfaceOrientation]);
  1347. return size.height;
  1348. }
  1349. double Platform::getAbsoluteTime()
  1350. {
  1351. __timeAbsolute = getMachTimeInMilliseconds();
  1352. return __timeAbsolute;
  1353. }
  1354. void Platform::setAbsoluteTime(double time)
  1355. {
  1356. __timeAbsolute = time;
  1357. }
  1358. bool Platform::isVsync()
  1359. {
  1360. return __vsync;
  1361. }
  1362. void Platform::setVsync(bool enable)
  1363. {
  1364. __vsync = enable;
  1365. }
  1366. void Platform::swapBuffers()
  1367. {
  1368. if (__view)
  1369. [__view swapBuffers];
  1370. }
  1371. void Platform::sleep(long ms)
  1372. {
  1373. usleep(ms * 1000);
  1374. }
  1375. bool Platform::hasAccelerometer()
  1376. {
  1377. return true;
  1378. }
  1379. void Platform::getAccelerometerValues(float* pitch, float* roll)
  1380. {
  1381. [__appDelegate getAccelerometerPitch:pitch roll:roll];
  1382. }
  1383. void Platform::getSensorValues(float* accelX, float* accelY, float* accelZ, float* gyroX, float* gyroY, float* gyroZ)
  1384. {
  1385. float x, y, z;
  1386. [__appDelegate getRawAccelX:&x Y:&y Z:&z];
  1387. if (accelX)
  1388. {
  1389. *accelX = x;
  1390. }
  1391. if (accelY)
  1392. {
  1393. *accelY = y;
  1394. }
  1395. if (accelZ)
  1396. {
  1397. *accelZ = z;
  1398. }
  1399. [__appDelegate getRawGyroX:&x Y:&y Z:&z];
  1400. if (gyroX)
  1401. {
  1402. *gyroX = x;
  1403. }
  1404. if (gyroY)
  1405. {
  1406. *gyroY = y;
  1407. }
  1408. if (gyroZ)
  1409. {
  1410. *gyroZ = z;
  1411. }
  1412. }
  1413. void Platform::getArguments(int* argc, char*** argv)
  1414. {
  1415. if (argc)
  1416. *argc = __argc;
  1417. if (argv)
  1418. *argv = __argv;
  1419. }
  1420. bool Platform::hasMouse()
  1421. {
  1422. // not supported
  1423. return false;
  1424. }
  1425. void Platform::setMouseCaptured(bool captured)
  1426. {
  1427. // not supported
  1428. }
  1429. bool Platform::isMouseCaptured()
  1430. {
  1431. // not supported
  1432. return false;
  1433. }
  1434. void Platform::setCursorVisible(bool visible)
  1435. {
  1436. // not supported
  1437. }
  1438. bool Platform::isCursorVisible()
  1439. {
  1440. // not supported
  1441. return false;
  1442. }
  1443. void Platform::setMultiSampling(bool enabled)
  1444. {
  1445. //todo
  1446. }
  1447. bool Platform::isMultiSampling()
  1448. {
  1449. return false; //todo
  1450. }
  1451. void Platform::setMultiTouch(bool enabled)
  1452. {
  1453. __view.multipleTouchEnabled = enabled;
  1454. }
  1455. bool Platform::isMultiTouch()
  1456. {
  1457. return __view.multipleTouchEnabled;
  1458. }
  1459. void Platform::displayKeyboard(bool display)
  1460. {
  1461. if(__view)
  1462. {
  1463. if(display)
  1464. {
  1465. [__view showKeyboard];
  1466. }
  1467. else
  1468. {
  1469. [__view dismissKeyboard];
  1470. }
  1471. }
  1472. }
  1473. void Platform::shutdownInternal()
  1474. {
  1475. Game::getInstance()->shutdown();
  1476. }
  1477. bool Platform::isGestureSupported(Gesture::GestureEvent evt)
  1478. {
  1479. return true;
  1480. }
  1481. void Platform::registerGesture(Gesture::GestureEvent evt)
  1482. {
  1483. [__view registerGesture:evt];
  1484. }
  1485. void Platform::unregisterGesture(Gesture::GestureEvent evt)
  1486. {
  1487. [__view unregisterGesture:evt];
  1488. }
  1489. bool Platform::isGestureRegistered(Gesture::GestureEvent evt)
  1490. {
  1491. return [__view isGestureRegistered:evt];
  1492. }
  1493. void Platform::pollGamepadState(Gamepad* gamepad)
  1494. {
  1495. }
  1496. bool Platform::launchURL(const char *url)
  1497. {
  1498. if (url == NULL || *url == '\0')
  1499. return false;
  1500. return [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithUTF8String: url]]];
  1501. }
  1502. std::string Platform::displayFileDialog(size_t mode, const char* title, const char* filterDescription, const char* filterExtensions, const char* initialDirectory)
  1503. {
  1504. return "";
  1505. }
  1506. }
  1507. #endif