PlatformiOS.mm 46 KB

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