PlatformAndroid.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. #ifdef __ANDROID__
  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 <android/sensor.h>
  10. #include <android_native_app_glue.h>
  11. #include <android/log.h>
  12. // Externally referenced global variables.
  13. struct android_app* __state;
  14. AAssetManager* __assetManager;
  15. static bool __initialized;
  16. static bool __suspended;
  17. static EGLDisplay __eglDisplay = EGL_NO_DISPLAY;
  18. static EGLContext __eglContext = EGL_NO_CONTEXT;
  19. static EGLSurface __eglSurface = EGL_NO_SURFACE;
  20. static EGLConfig __eglConfig = 0;
  21. static int __width;
  22. static int __height;
  23. static struct timespec __timespec;
  24. static double __timeStart;
  25. static double __timeAbsolute;
  26. static bool __vsync = WINDOW_VSYNC;
  27. static ASensorManager* __sensorManager;
  28. static ASensorEventQueue* __sensorEventQueue;
  29. static ASensorEvent __sensorEvent;
  30. static const ASensor* __accelerometerSensor;
  31. static int __orientationAngle = 90;
  32. static bool __multiSampling = false;
  33. static bool __multiTouch = false;
  34. static int __primaryTouchId = -1;
  35. static bool __displayKeyboard = false;
  36. // OpenGL VAO functions.
  37. static const char* __glExtensions;
  38. PFNGLBINDVERTEXARRAYOESPROC glBindVertexArray = NULL;
  39. PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArrays = NULL;
  40. PFNGLGENVERTEXARRAYSOESPROC glGenVertexArrays = NULL;
  41. PFNGLISVERTEXARRAYOESPROC glIsVertexArray = NULL;
  42. #define GESTURE_TAP_DURATION_MAX 200
  43. #define GESTURE_SWIPE_DURATION_MAX 400
  44. #define GESTURE_SWIPE_DISTANCE_MIN 50
  45. static std::bitset<3> __gestureEventsProcessed;
  46. struct TouchPointerData
  47. {
  48. size_t pointerId;
  49. bool pressed;
  50. double time;
  51. int x;
  52. int y;
  53. };
  54. TouchPointerData __pointer0;
  55. TouchPointerData __pointer1;
  56. namespace gameplay
  57. {
  58. static double timespec2millis(struct timespec *a)
  59. {
  60. GP_ASSERT(a);
  61. return (1000.0 * a->tv_sec) + (0.000001 * a->tv_nsec);
  62. }
  63. extern void print(const char* format, ...)
  64. {
  65. GP_ASSERT(format);
  66. va_list argptr;
  67. va_start(argptr, format);
  68. __android_log_vprint(ANDROID_LOG_INFO, "gameplay-native-activity", format, argptr);
  69. va_end(argptr);
  70. }
  71. static EGLenum checkErrorEGL(const char* msg)
  72. {
  73. GP_ASSERT(msg);
  74. static const char* errmsg[] =
  75. {
  76. "EGL function succeeded",
  77. "EGL is not initialized, or could not be initialized, for the specified display",
  78. "EGL cannot access a requested resource",
  79. "EGL failed to allocate resources for the requested operation",
  80. "EGL fail to access an unrecognized attribute or attribute value was passed in an attribute list",
  81. "EGLConfig argument does not name a valid EGLConfig",
  82. "EGLContext argument does not name a valid EGLContext",
  83. "EGL current surface of the calling thread is no longer valid",
  84. "EGLDisplay argument does not name a valid EGLDisplay",
  85. "EGL arguments are inconsistent",
  86. "EGLNativePixmapType argument does not refer to a valid native pixmap",
  87. "EGLNativeWindowType argument does not refer to a valid native window",
  88. "EGL one or more argument values are invalid",
  89. "EGLSurface argument does not name a valid surface configured for rendering",
  90. "EGL power management event has occurred",
  91. };
  92. EGLenum error = eglGetError();
  93. print("%s: %s.", msg, errmsg[error - EGL_SUCCESS]);
  94. return error;
  95. }
  96. static int getRotation()
  97. {
  98. jint rotation;
  99. // Get the android application's activity.
  100. ANativeActivity* activity = __state->activity;
  101. JavaVM* jvm = __state->activity->vm;
  102. JNIEnv* env = NULL;
  103. jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
  104. jint res = jvm->AttachCurrentThread(&env, NULL);
  105. if (res == JNI_ERR)
  106. {
  107. GP_ERROR("Failed to retrieve JVM environment when entering message pump.");
  108. return -1;
  109. }
  110. GP_ASSERT(env);
  111. jclass clsContext = env->FindClass("android/content/Context");
  112. GP_ASSERT(clsContext != NULL);
  113. jmethodID getSystemService = env->GetMethodID(clsContext, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
  114. GP_ASSERT(getSystemService != NULL);
  115. jfieldID WINDOW_SERVICE_ID = env->GetStaticFieldID(clsContext, "WINDOW_SERVICE", "Ljava/lang/String;");
  116. GP_ASSERT(WINDOW_SERVICE_ID != NULL);
  117. jstring WINDOW_SERVICE = (jstring) env->GetStaticObjectField(clsContext, WINDOW_SERVICE_ID);
  118. GP_ASSERT(WINDOW_SERVICE != NULL);
  119. jobject windowManager = env->CallObjectMethod(activity->clazz, getSystemService, WINDOW_SERVICE);
  120. GP_ASSERT(windowManager != NULL);
  121. jclass clsWindowManager = env->FindClass("android/view/WindowManager");
  122. GP_ASSERT(clsWindowManager != NULL);
  123. jmethodID getDefaultDisplay = env->GetMethodID(clsWindowManager, "getDefaultDisplay", "()Landroid/view/Display;");
  124. GP_ASSERT(getDefaultDisplay != NULL);
  125. jobject defaultDisplay = env->CallObjectMethod(windowManager, getDefaultDisplay);
  126. GP_ASSERT(defaultDisplay != NULL);
  127. jclass clsDisplay = env->FindClass("android/view/Display");
  128. GP_ASSERT(clsDisplay != NULL);
  129. jmethodID getRotation = env->GetMethodID(clsDisplay, "getRotation", "()I");
  130. GP_ASSERT(getRotation != NULL)
  131. rotation = env->CallIntMethod(defaultDisplay, getRotation);
  132. return rotation;
  133. }
  134. // Initialized EGL resources.
  135. static bool initEGL()
  136. {
  137. int samples = 0;
  138. Properties* config = Game::getInstance()->getConfig()->getNamespace("window", true);
  139. if (config)
  140. {
  141. samples = std::max(config->getInt("samples"), 0);
  142. }
  143. // Hard-coded to 32-bit/OpenGL ES 2.0.
  144. // NOTE: EGL_SAMPLE_BUFFERS, EGL_SAMPLES and EGL_DEPTH_SIZE MUST remain at the beginning of the attribute list
  145. // since they are expected to be at indices 0-5 in config fallback code later.
  146. // EGL_DEPTH_SIZE is also expected to
  147. EGLint eglConfigAttrs[] =
  148. {
  149. EGL_SAMPLE_BUFFERS, samples > 0 ? 1 : 0,
  150. EGL_SAMPLES, samples,
  151. EGL_DEPTH_SIZE, 24,
  152. EGL_RED_SIZE, 8,
  153. EGL_GREEN_SIZE, 8,
  154. EGL_BLUE_SIZE, 8,
  155. EGL_ALPHA_SIZE, 8,
  156. EGL_STENCIL_SIZE, 8,
  157. EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
  158. EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
  159. EGL_NONE
  160. };
  161. __multiSampling = samples > 0;
  162. EGLint eglConfigCount;
  163. const EGLint eglContextAttrs[] =
  164. {
  165. EGL_CONTEXT_CLIENT_VERSION, 2,
  166. EGL_NONE
  167. };
  168. const EGLint eglSurfaceAttrs[] =
  169. {
  170. EGL_RENDER_BUFFER, EGL_BACK_BUFFER,
  171. EGL_NONE
  172. };
  173. if (__eglDisplay == EGL_NO_DISPLAY && __eglContext == EGL_NO_CONTEXT)
  174. {
  175. // Get the EGL display and initialize.
  176. __eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
  177. if (__eglDisplay == EGL_NO_DISPLAY)
  178. {
  179. checkErrorEGL("eglGetDisplay");
  180. goto error;
  181. }
  182. if (eglInitialize(__eglDisplay, NULL, NULL) != EGL_TRUE)
  183. {
  184. checkErrorEGL("eglInitialize");
  185. goto error;
  186. }
  187. // Try both 24 and 16-bit depth sizes since some hardware (i.e. Tegra) does not support 24-bit depth
  188. bool validConfig = false;
  189. EGLint depthSizes[] = { 24, 16 };
  190. for (unsigned int i = 0; i < 2; ++i)
  191. {
  192. eglConfigAttrs[1] = samples > 0 ? 1 : 0;
  193. eglConfigAttrs[3] = samples;
  194. eglConfigAttrs[5] = depthSizes[i];
  195. if (eglChooseConfig(__eglDisplay, eglConfigAttrs, &__eglConfig, 1, &eglConfigCount) == EGL_TRUE && eglConfigCount > 0)
  196. {
  197. validConfig = true;
  198. break;
  199. }
  200. if (samples)
  201. {
  202. // Try lowering the MSAA sample size until we find a supported config
  203. int sampleCount = samples;
  204. while (sampleCount)
  205. {
  206. GP_WARN("No EGL config found for depth_size=%d and samples=%d. Trying samples=%d instead.", depthSizes[i], sampleCount, sampleCount / 2);
  207. sampleCount /= 2;
  208. eglConfigAttrs[1] = sampleCount > 0 ? 1 : 0;
  209. eglConfigAttrs[3] = sampleCount;
  210. if (eglChooseConfig(__eglDisplay, eglConfigAttrs, &__eglConfig, 1, &eglConfigCount) == EGL_TRUE && eglConfigCount > 0)
  211. {
  212. validConfig = true;
  213. break;
  214. }
  215. }
  216. __multiSampling = sampleCount > 0;
  217. if (validConfig)
  218. break;
  219. }
  220. else
  221. {
  222. GP_WARN("No EGL config found for depth_size=%d.", depthSizes[i]);
  223. }
  224. }
  225. if (!validConfig)
  226. {
  227. checkErrorEGL("eglChooseConfig");
  228. goto error;
  229. }
  230. __eglContext = eglCreateContext(__eglDisplay, __eglConfig, EGL_NO_CONTEXT, eglContextAttrs);
  231. if (__eglContext == EGL_NO_CONTEXT)
  232. {
  233. checkErrorEGL("eglCreateContext");
  234. goto error;
  235. }
  236. }
  237. // EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
  238. // guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
  239. // As soon as we picked a EGLConfig, we can safely reconfigure the
  240. // ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID.
  241. EGLint format;
  242. eglGetConfigAttrib(__eglDisplay, __eglConfig, EGL_NATIVE_VISUAL_ID, &format);
  243. ANativeWindow_setBuffersGeometry(__state->window, 0, 0, format);
  244. __eglSurface = eglCreateWindowSurface(__eglDisplay, __eglConfig, __state->window, eglSurfaceAttrs);
  245. if (__eglSurface == EGL_NO_SURFACE)
  246. {
  247. checkErrorEGL("eglCreateWindowSurface");
  248. goto error;
  249. }
  250. if (eglMakeCurrent(__eglDisplay, __eglSurface, __eglSurface, __eglContext) != EGL_TRUE)
  251. {
  252. checkErrorEGL("eglMakeCurrent");
  253. goto error;
  254. }
  255. eglQuerySurface(__eglDisplay, __eglSurface, EGL_WIDTH, &__width);
  256. eglQuerySurface(__eglDisplay, __eglSurface, EGL_HEIGHT, &__height);
  257. __orientationAngle = getRotation() * 90;
  258. // Set vsync.
  259. eglSwapInterval(__eglDisplay, WINDOW_VSYNC ? 1 : 0);
  260. // Initialize OpenGL ES extensions.
  261. __glExtensions = (const char*)glGetString(GL_EXTENSIONS);
  262. if (strstr(__glExtensions, "GL_OES_vertex_array_object") || strstr(__glExtensions, "GL_ARB_vertex_array_object"))
  263. {
  264. // Disable VAO extension for now.
  265. glBindVertexArray = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress("glBindVertexArrayOES");
  266. glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress("glDeleteVertexArrays");
  267. glGenVertexArrays = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress("glGenVertexArraysOES");
  268. glIsVertexArray = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress("glIsVertexArrayOES");
  269. }
  270. return true;
  271. error:
  272. return false;
  273. }
  274. static void destroyEGLSurface()
  275. {
  276. if (__eglDisplay != EGL_NO_DISPLAY)
  277. {
  278. eglMakeCurrent(__eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  279. }
  280. if (__eglSurface != EGL_NO_SURFACE)
  281. {
  282. eglDestroySurface(__eglDisplay, __eglSurface);
  283. __eglSurface = EGL_NO_SURFACE;
  284. }
  285. }
  286. static void destroyEGLMain()
  287. {
  288. destroyEGLSurface();
  289. if (__eglContext != EGL_NO_CONTEXT)
  290. {
  291. eglDestroyContext(__eglDisplay, __eglContext);
  292. __eglContext = EGL_NO_CONTEXT;
  293. }
  294. if (__eglDisplay != EGL_NO_DISPLAY)
  295. {
  296. eglTerminate(__eglDisplay);
  297. __eglDisplay = EGL_NO_DISPLAY;
  298. }
  299. }
  300. // Display the android virtual keyboard.
  301. static void displayKeyboard(android_app* state, bool show)
  302. {
  303. // The following functions is supposed to show / hide functins from a native activity.. but currently do not work.
  304. // ANativeActivity_showSoftInput(state->activity, ANATIVEACTIVITY_SHOW_SOFT_INPUT_IMPLICIT);
  305. // ANativeActivity_hideSoftInput(state->activity, ANATIVEACTIVITY_HIDE_SOFT_INPUT_IMPLICIT_ONLY);
  306. GP_ASSERT(state && state->activity && state->activity->vm);
  307. // Show or hide the keyboard by calling the appropriate Java method through JNI instead.
  308. jint flags = 0;
  309. JavaVM* jvm = state->activity->vm;
  310. JNIEnv* env = NULL;
  311. jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
  312. jint result = jvm->AttachCurrentThread(&env, NULL);
  313. if (result == JNI_ERR)
  314. {
  315. GP_ERROR("Failed to retrieve JVM environment to display keyboard.");
  316. return;
  317. }
  318. GP_ASSERT(env);
  319. // Retrieves NativeActivity.
  320. jobject lNativeActivity = state->activity->clazz;
  321. jclass ClassNativeActivity = env->GetObjectClass(lNativeActivity);
  322. // Retrieves Context.INPUT_METHOD_SERVICE.
  323. jclass ClassContext = env->FindClass("android/content/Context");
  324. jfieldID FieldINPUT_METHOD_SERVICE = env->GetStaticFieldID(ClassContext, "INPUT_METHOD_SERVICE", "Ljava/lang/String;");
  325. jobject INPUT_METHOD_SERVICE = env->GetStaticObjectField(ClassContext, FieldINPUT_METHOD_SERVICE);
  326. // Runs getSystemService(Context.INPUT_METHOD_SERVICE).
  327. jclass ClassInputMethodManager = env->FindClass("android/view/inputmethod/InputMethodManager");
  328. jmethodID MethodGetSystemService = env->GetMethodID(ClassNativeActivity, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
  329. jobject lInputMethodManager = env->CallObjectMethod(lNativeActivity, MethodGetSystemService, INPUT_METHOD_SERVICE);
  330. // Runs getWindow().getDecorView().
  331. jmethodID MethodGetWindow = env->GetMethodID(ClassNativeActivity, "getWindow", "()Landroid/view/Window;");
  332. jobject lWindow = env->CallObjectMethod(lNativeActivity, MethodGetWindow);
  333. jclass ClassWindow = env->FindClass("android/view/Window");
  334. jmethodID MethodGetDecorView = env->GetMethodID(ClassWindow, "getDecorView", "()Landroid/view/View;");
  335. jobject lDecorView = env->CallObjectMethod(lWindow, MethodGetDecorView);
  336. if (show)
  337. {
  338. // Runs lInputMethodManager.showSoftInput(...).
  339. jmethodID MethodShowSoftInput = env->GetMethodID( ClassInputMethodManager, "showSoftInput", "(Landroid/view/View;I)Z");
  340. jboolean result = env->CallBooleanMethod(lInputMethodManager, MethodShowSoftInput, lDecorView, flags);
  341. }
  342. else
  343. {
  344. // Runs lWindow.getViewToken()
  345. jclass ClassView = env->FindClass("android/view/View");
  346. jmethodID MethodGetWindowToken = env->GetMethodID(ClassView, "getWindowToken", "()Landroid/os/IBinder;");
  347. jobject lBinder = env->CallObjectMethod(lDecorView, MethodGetWindowToken);
  348. // lInputMethodManager.hideSoftInput(...).
  349. jmethodID MethodHideSoftInput = env->GetMethodID(ClassInputMethodManager, "hideSoftInputFromWindow", "(Landroid/os/IBinder;I)Z");
  350. jboolean lRes = env->CallBooleanMethod( lInputMethodManager, MethodHideSoftInput, lBinder, flags);
  351. }
  352. // Finished with the JVM.
  353. jvm->DetachCurrentThread();
  354. }
  355. // Gets the Keyboard::Key enumeration constant that corresponds to the given Android key code.
  356. static Keyboard::Key getKey(int keycode, int metastate)
  357. {
  358. bool shiftOn = (metastate == AMETA_SHIFT_ON);
  359. switch(keycode)
  360. {
  361. case AKEYCODE_HOME:
  362. return Keyboard::KEY_HOME;
  363. case AKEYCODE_0:
  364. return Keyboard::KEY_ZERO;
  365. case AKEYCODE_1:
  366. return Keyboard::KEY_ONE;
  367. case AKEYCODE_2:
  368. return Keyboard::KEY_TWO;
  369. case AKEYCODE_3:
  370. return Keyboard::KEY_THREE;
  371. case AKEYCODE_4:
  372. return Keyboard::KEY_FOUR;
  373. case AKEYCODE_5:
  374. return Keyboard::KEY_FIVE;
  375. case AKEYCODE_6:
  376. return Keyboard::KEY_SIX;
  377. case AKEYCODE_7:
  378. return Keyboard::KEY_SEVEN;
  379. case AKEYCODE_8:
  380. return Keyboard::KEY_EIGHT;
  381. case AKEYCODE_9:
  382. return Keyboard::KEY_NINE;
  383. case AKEYCODE_STAR:
  384. return Keyboard::KEY_ASTERISK;
  385. case AKEYCODE_POUND:
  386. return Keyboard::KEY_NUMBER;
  387. case AKEYCODE_DPAD_UP:
  388. return Keyboard::KEY_UP_ARROW;
  389. case AKEYCODE_DPAD_DOWN:
  390. return Keyboard::KEY_DOWN_ARROW;
  391. case AKEYCODE_DPAD_LEFT:
  392. return Keyboard::KEY_LEFT_ARROW;
  393. case AKEYCODE_DPAD_RIGHT:
  394. return Keyboard::KEY_RIGHT_ARROW;
  395. case AKEYCODE_A:
  396. return (shiftOn) ? Keyboard::KEY_CAPITAL_A : Keyboard::KEY_A;
  397. case AKEYCODE_B:
  398. return (shiftOn) ? Keyboard::KEY_CAPITAL_B : Keyboard::KEY_B;
  399. case AKEYCODE_C:
  400. return (shiftOn) ? Keyboard::KEY_CAPITAL_C : Keyboard::KEY_C;
  401. case AKEYCODE_D:
  402. return (shiftOn) ? Keyboard::KEY_CAPITAL_D : Keyboard::KEY_D;
  403. case AKEYCODE_E:
  404. return (shiftOn) ? Keyboard::KEY_CAPITAL_E : Keyboard::KEY_E;
  405. case AKEYCODE_F:
  406. return (shiftOn) ? Keyboard::KEY_CAPITAL_F : Keyboard::KEY_F;
  407. case AKEYCODE_G:
  408. return (shiftOn) ? Keyboard::KEY_CAPITAL_G : Keyboard::KEY_G;
  409. case AKEYCODE_H:
  410. return (shiftOn) ? Keyboard::KEY_CAPITAL_H : Keyboard::KEY_H;
  411. case AKEYCODE_I:
  412. return (shiftOn) ? Keyboard::KEY_CAPITAL_I : Keyboard::KEY_I;
  413. case AKEYCODE_J:
  414. return (shiftOn) ? Keyboard::KEY_CAPITAL_J : Keyboard::KEY_J;
  415. case AKEYCODE_K:
  416. return (shiftOn) ? Keyboard::KEY_CAPITAL_K : Keyboard::KEY_K;
  417. case AKEYCODE_L:
  418. return (shiftOn) ? Keyboard::KEY_CAPITAL_L : Keyboard::KEY_L;
  419. case AKEYCODE_M:
  420. return (shiftOn) ? Keyboard::KEY_CAPITAL_M : Keyboard::KEY_M;
  421. case AKEYCODE_N:
  422. return (shiftOn) ? Keyboard::KEY_CAPITAL_N : Keyboard::KEY_N;
  423. case AKEYCODE_O:
  424. return (shiftOn) ? Keyboard::KEY_CAPITAL_O : Keyboard::KEY_O;
  425. case AKEYCODE_P:
  426. return (shiftOn) ? Keyboard::KEY_CAPITAL_P : Keyboard::KEY_P;
  427. case AKEYCODE_Q:
  428. return (shiftOn) ? Keyboard::KEY_CAPITAL_Q : Keyboard::KEY_Q;
  429. case AKEYCODE_R:
  430. return (shiftOn) ? Keyboard::KEY_CAPITAL_R : Keyboard::KEY_R;
  431. case AKEYCODE_S:
  432. return (shiftOn) ? Keyboard::KEY_CAPITAL_S : Keyboard::KEY_S;
  433. case AKEYCODE_T:
  434. return (shiftOn) ? Keyboard::KEY_CAPITAL_T : Keyboard::KEY_T;
  435. case AKEYCODE_U:
  436. return (shiftOn) ? Keyboard::KEY_CAPITAL_U : Keyboard::KEY_U;
  437. case AKEYCODE_V:
  438. return (shiftOn) ? Keyboard::KEY_CAPITAL_V : Keyboard::KEY_V;
  439. case AKEYCODE_W:
  440. return (shiftOn) ? Keyboard::KEY_CAPITAL_W : Keyboard::KEY_W;
  441. case AKEYCODE_X:
  442. return (shiftOn) ? Keyboard::KEY_CAPITAL_X : Keyboard::KEY_X;
  443. case AKEYCODE_Y:
  444. return (shiftOn) ? Keyboard::KEY_CAPITAL_Y : Keyboard::KEY_Y;
  445. case AKEYCODE_Z:
  446. return (shiftOn) ? Keyboard::KEY_CAPITAL_Y : Keyboard::KEY_Y;
  447. case AKEYCODE_COMMA:
  448. return Keyboard::KEY_COMMA;
  449. case AKEYCODE_PERIOD:
  450. return Keyboard::KEY_PERIOD;
  451. case AKEYCODE_ALT_LEFT:
  452. case AKEYCODE_ALT_RIGHT:
  453. return Keyboard::KEY_ALT;
  454. case AKEYCODE_SHIFT_LEFT:
  455. case AKEYCODE_SHIFT_RIGHT:
  456. return Keyboard::KEY_SHIFT;
  457. case AKEYCODE_TAB:
  458. return Keyboard::KEY_TAB;
  459. case AKEYCODE_SPACE:
  460. return Keyboard::KEY_SPACE;
  461. case AKEYCODE_ENTER:
  462. return Keyboard::KEY_RETURN;
  463. case AKEYCODE_DEL:
  464. return Keyboard::KEY_DELETE;
  465. case AKEYCODE_GRAVE:
  466. return Keyboard::KEY_GRAVE;
  467. case AKEYCODE_MINUS:
  468. return Keyboard::KEY_MINUS;
  469. case AKEYCODE_EQUALS:
  470. return Keyboard::KEY_EQUAL;
  471. case AKEYCODE_LEFT_BRACKET:
  472. return Keyboard::KEY_LEFT_BRACKET;
  473. case AKEYCODE_RIGHT_BRACKET:
  474. return Keyboard::KEY_RIGHT_BRACKET;
  475. case AKEYCODE_BACKSLASH:
  476. return Keyboard::KEY_BACK_SLASH;
  477. case AKEYCODE_SEMICOLON:
  478. return Keyboard::KEY_SEMICOLON;
  479. case AKEYCODE_APOSTROPHE:
  480. return Keyboard::KEY_APOSTROPHE;
  481. case AKEYCODE_SLASH:
  482. return Keyboard::KEY_SLASH;
  483. case AKEYCODE_AT:
  484. return Keyboard::KEY_AT;
  485. case AKEYCODE_PLUS:
  486. return Keyboard::KEY_PLUS;
  487. case AKEYCODE_PAGE_UP:
  488. return Keyboard::KEY_PG_UP;
  489. case AKEYCODE_PAGE_DOWN:
  490. return Keyboard::KEY_PG_DOWN;
  491. case AKEYCODE_MENU:
  492. return Keyboard::KEY_MENU;
  493. case AKEYCODE_SEARCH:
  494. return Keyboard::KEY_SEARCH;
  495. default:
  496. return Keyboard::KEY_NONE;
  497. }
  498. }
  499. /**
  500. * Returns the unicode value for the given keycode or zero if the key is not a valid printable character.
  501. */
  502. static int getUnicode(int keycode, int metastate)
  503. {
  504. if (keycode == AKEYCODE_DEL)
  505. return 0x0008;
  506. // TODO: Doesn't support unicode currently.
  507. Keyboard::Key key = getKey(keycode, metastate);
  508. switch (key)
  509. {
  510. case Keyboard::KEY_BACKSPACE:
  511. return 0x0008;
  512. case Keyboard::KEY_TAB:
  513. return 0x0009;
  514. case Keyboard::KEY_RETURN:
  515. case Keyboard::KEY_KP_ENTER:
  516. return 0x000A;
  517. case Keyboard::KEY_ESCAPE:
  518. return 0x001B;
  519. case Keyboard::KEY_SPACE:
  520. case Keyboard::KEY_EXCLAM:
  521. case Keyboard::KEY_QUOTE:
  522. case Keyboard::KEY_NUMBER:
  523. case Keyboard::KEY_DOLLAR:
  524. case Keyboard::KEY_PERCENT:
  525. case Keyboard::KEY_CIRCUMFLEX:
  526. case Keyboard::KEY_AMPERSAND:
  527. case Keyboard::KEY_APOSTROPHE:
  528. case Keyboard::KEY_LEFT_PARENTHESIS:
  529. case Keyboard::KEY_RIGHT_PARENTHESIS:
  530. case Keyboard::KEY_ASTERISK:
  531. case Keyboard::KEY_PLUS:
  532. case Keyboard::KEY_COMMA:
  533. case Keyboard::KEY_MINUS:
  534. case Keyboard::KEY_PERIOD:
  535. case Keyboard::KEY_SLASH:
  536. case Keyboard::KEY_ZERO:
  537. case Keyboard::KEY_ONE:
  538. case Keyboard::KEY_TWO:
  539. case Keyboard::KEY_THREE:
  540. case Keyboard::KEY_FOUR:
  541. case Keyboard::KEY_FIVE:
  542. case Keyboard::KEY_SIX:
  543. case Keyboard::KEY_SEVEN:
  544. case Keyboard::KEY_EIGHT:
  545. case Keyboard::KEY_NINE:
  546. case Keyboard::KEY_COLON:
  547. case Keyboard::KEY_SEMICOLON:
  548. case Keyboard::KEY_LESS_THAN:
  549. case Keyboard::KEY_EQUAL:
  550. case Keyboard::KEY_GREATER_THAN:
  551. case Keyboard::KEY_QUESTION:
  552. case Keyboard::KEY_AT:
  553. case Keyboard::KEY_CAPITAL_A:
  554. case Keyboard::KEY_CAPITAL_B:
  555. case Keyboard::KEY_CAPITAL_C:
  556. case Keyboard::KEY_CAPITAL_D:
  557. case Keyboard::KEY_CAPITAL_E:
  558. case Keyboard::KEY_CAPITAL_F:
  559. case Keyboard::KEY_CAPITAL_G:
  560. case Keyboard::KEY_CAPITAL_H:
  561. case Keyboard::KEY_CAPITAL_I:
  562. case Keyboard::KEY_CAPITAL_J:
  563. case Keyboard::KEY_CAPITAL_K:
  564. case Keyboard::KEY_CAPITAL_L:
  565. case Keyboard::KEY_CAPITAL_M:
  566. case Keyboard::KEY_CAPITAL_N:
  567. case Keyboard::KEY_CAPITAL_O:
  568. case Keyboard::KEY_CAPITAL_P:
  569. case Keyboard::KEY_CAPITAL_Q:
  570. case Keyboard::KEY_CAPITAL_R:
  571. case Keyboard::KEY_CAPITAL_S:
  572. case Keyboard::KEY_CAPITAL_T:
  573. case Keyboard::KEY_CAPITAL_U:
  574. case Keyboard::KEY_CAPITAL_V:
  575. case Keyboard::KEY_CAPITAL_W:
  576. case Keyboard::KEY_CAPITAL_X:
  577. case Keyboard::KEY_CAPITAL_Y:
  578. case Keyboard::KEY_CAPITAL_Z:
  579. case Keyboard::KEY_LEFT_BRACKET:
  580. case Keyboard::KEY_BACK_SLASH:
  581. case Keyboard::KEY_RIGHT_BRACKET:
  582. case Keyboard::KEY_UNDERSCORE:
  583. case Keyboard::KEY_GRAVE:
  584. case Keyboard::KEY_A:
  585. case Keyboard::KEY_B:
  586. case Keyboard::KEY_C:
  587. case Keyboard::KEY_D:
  588. case Keyboard::KEY_E:
  589. case Keyboard::KEY_F:
  590. case Keyboard::KEY_G:
  591. case Keyboard::KEY_H:
  592. case Keyboard::KEY_I:
  593. case Keyboard::KEY_J:
  594. case Keyboard::KEY_K:
  595. case Keyboard::KEY_L:
  596. case Keyboard::KEY_M:
  597. case Keyboard::KEY_N:
  598. case Keyboard::KEY_O:
  599. case Keyboard::KEY_P:
  600. case Keyboard::KEY_Q:
  601. case Keyboard::KEY_R:
  602. case Keyboard::KEY_S:
  603. case Keyboard::KEY_T:
  604. case Keyboard::KEY_U:
  605. case Keyboard::KEY_V:
  606. case Keyboard::KEY_W:
  607. case Keyboard::KEY_X:
  608. case Keyboard::KEY_Y:
  609. case Keyboard::KEY_Z:
  610. case Keyboard::KEY_LEFT_BRACE:
  611. case Keyboard::KEY_BAR:
  612. case Keyboard::KEY_RIGHT_BRACE:
  613. case Keyboard::KEY_TILDE:
  614. return key;
  615. default:
  616. return 0;
  617. }
  618. }
  619. // Process the next input event.
  620. static int32_t engine_handle_input(struct android_app* app, AInputEvent* event)
  621. {
  622. if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION)
  623. {
  624. int32_t action = AMotionEvent_getAction(event);
  625. size_t pointerIndex;
  626. size_t pointerId;
  627. size_t pointerCount;
  628. int x;
  629. int y;
  630. switch (action & AMOTION_EVENT_ACTION_MASK)
  631. {
  632. case AMOTION_EVENT_ACTION_DOWN:
  633. {
  634. pointerId = AMotionEvent_getPointerId(event, 0);
  635. x = AMotionEvent_getX(event, 0);
  636. y = AMotionEvent_getY(event, 0);
  637. // Gesture handling
  638. if ( __gestureEventsProcessed.test(Gesture::GESTURE_TAP) ||
  639. __gestureEventsProcessed.test(Gesture::GESTURE_SWIPE) )
  640. {
  641. __pointer0.pressed = true;
  642. __pointer0.time = Game::getInstance()->getAbsoluteTime();
  643. __pointer0.pointerId = pointerId;
  644. __pointer0.x = x;
  645. __pointer0.y = y;
  646. }
  647. // Primary pointer down.
  648. gameplay::Platform::touchEventInternal(Touch::TOUCH_PRESS, x, y, pointerId);
  649. __primaryTouchId = pointerId;
  650. }
  651. break;
  652. case AMOTION_EVENT_ACTION_UP:
  653. {
  654. pointerId = AMotionEvent_getPointerId(event, 0);
  655. x = AMotionEvent_getX(event, 0);
  656. y = AMotionEvent_getY(event, 0);
  657. // Gestures
  658. bool gestureDetected = false;
  659. if ( __pointer0.pressed && __pointer0.pointerId == pointerId)
  660. {
  661. int deltaX = x - __pointer0.x;
  662. int deltaY = y - __pointer0.y;
  663. // Test for swipe
  664. if (__gestureEventsProcessed.test(Gesture::GESTURE_SWIPE) &&
  665. gameplay::Game::getInstance()->getAbsoluteTime() - __pointer0.time < GESTURE_SWIPE_DURATION_MAX &&
  666. (abs(deltaX) > GESTURE_SWIPE_DISTANCE_MIN || abs(deltaY) > GESTURE_SWIPE_DISTANCE_MIN) )
  667. {
  668. int direction = 0;
  669. if ( abs(deltaX) > abs(deltaY) )
  670. {
  671. if (deltaX > 0)
  672. direction = gameplay::Gesture::SWIPE_DIRECTION_RIGHT;
  673. else if (deltaX < 0)
  674. direction = gameplay::Gesture::SWIPE_DIRECTION_LEFT;
  675. }
  676. else
  677. {
  678. if (deltaY > 0)
  679. direction = gameplay::Gesture::SWIPE_DIRECTION_DOWN;
  680. else if (deltaY < 0)
  681. direction = gameplay::Gesture::SWIPE_DIRECTION_UP;
  682. }
  683. gameplay::Game::getInstance()->gestureSwipeEvent(x, y, direction);
  684. __pointer0.pressed = false;
  685. gestureDetected = true;
  686. }
  687. else if(__gestureEventsProcessed.test(Gesture::GESTURE_TAP) &&
  688. gameplay::Game::getInstance()->getAbsoluteTime() - __pointer0.time < GESTURE_TAP_DURATION_MAX)
  689. {
  690. gameplay::Game::getInstance()->gestureTapEvent(x, y);
  691. __pointer0.pressed = false;
  692. gestureDetected = true;
  693. }
  694. }
  695. if (!gestureDetected && (__multiTouch || __primaryTouchId == pointerId) )
  696. {
  697. gameplay::Platform::touchEventInternal(Touch::TOUCH_RELEASE, x, y, pointerId);
  698. }
  699. __primaryTouchId = -1;
  700. }
  701. break;
  702. case AMOTION_EVENT_ACTION_POINTER_DOWN:
  703. {
  704. pointerId = AMotionEvent_getPointerId(event, 0);
  705. x = AMotionEvent_getX(event, 0);
  706. y = AMotionEvent_getY(event, 0);
  707. // Gesture handling
  708. if ( __gestureEventsProcessed.test(Gesture::GESTURE_TAP) ||
  709. __gestureEventsProcessed.test(Gesture::GESTURE_SWIPE) )
  710. {
  711. __pointer1.pressed = true;
  712. __pointer1.time = Game::getInstance()->getAbsoluteTime();
  713. __pointer1.pointerId = pointerId;
  714. __pointer1.x = x;
  715. __pointer1.y = y;
  716. }
  717. // Non-primary pointer down.
  718. if (__multiTouch)
  719. {
  720. pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
  721. pointerId = AMotionEvent_getPointerId(event, pointerIndex);
  722. gameplay::Platform::touchEventInternal(Touch::TOUCH_PRESS, AMotionEvent_getX(event, pointerIndex), AMotionEvent_getY(event, pointerIndex), pointerId);
  723. }
  724. }
  725. break;
  726. case AMOTION_EVENT_ACTION_POINTER_UP:
  727. {
  728. pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
  729. pointerId = AMotionEvent_getPointerId(event, pointerIndex);
  730. x = AMotionEvent_getX(event, 0);
  731. y = AMotionEvent_getY(event, 0);
  732. bool gestureDetected = false;
  733. if ( __pointer1.pressed && __pointer1.pointerId == pointerId)
  734. {
  735. int deltaX = x - __pointer1.x;
  736. int deltaY = y - __pointer1.y;
  737. // Test for swipe
  738. if (__gestureEventsProcessed.test(Gesture::GESTURE_SWIPE) &&
  739. gameplay::Game::getInstance()->getAbsoluteTime() - __pointer1.time < GESTURE_SWIPE_DURATION_MAX &&
  740. (abs(deltaX) > GESTURE_SWIPE_DISTANCE_MIN || abs(deltaY) > GESTURE_SWIPE_DISTANCE_MIN) )
  741. {
  742. int direction;
  743. if (deltaX > 0)
  744. direction |= gameplay::Gesture::SWIPE_DIRECTION_RIGHT;
  745. else if (deltaX < 0)
  746. direction |= gameplay::Gesture::SWIPE_DIRECTION_LEFT;
  747. if (deltaY > 0)
  748. direction |= gameplay::Gesture::SWIPE_DIRECTION_DOWN;
  749. else if (deltaY < 0)
  750. direction |= gameplay::Gesture::SWIPE_DIRECTION_UP;
  751. gameplay::Game::getInstance()->gestureSwipeEvent(x, y, direction);
  752. __pointer1.pressed = false;
  753. gestureDetected = true;
  754. }
  755. else if(__gestureEventsProcessed.test(Gesture::GESTURE_TAP) &&
  756. gameplay::Game::getInstance()->getAbsoluteTime() - __pointer1.time < GESTURE_TAP_DURATION_MAX)
  757. {
  758. gameplay::Game::getInstance()->gestureTapEvent(x, y);
  759. __pointer1.pressed = false;
  760. gestureDetected = true;
  761. }
  762. }
  763. if (!gestureDetected && (__multiTouch || __primaryTouchId == pointerId) )
  764. {
  765. gameplay::Platform::touchEventInternal(Touch::TOUCH_RELEASE, AMotionEvent_getX(event, pointerIndex), AMotionEvent_getY(event, pointerIndex), pointerId);
  766. }
  767. if (__primaryTouchId == pointerId)
  768. __primaryTouchId = -1;
  769. }
  770. break;
  771. case AMOTION_EVENT_ACTION_MOVE:
  772. {
  773. // ACTION_MOVE events are batched, unlike the other events.
  774. pointerCount = AMotionEvent_getPointerCount(event);
  775. for (size_t i = 0; i < pointerCount; ++i)
  776. {
  777. pointerId = AMotionEvent_getPointerId(event, i);
  778. if (__multiTouch || __primaryTouchId == pointerId)
  779. {
  780. gameplay::Platform::touchEventInternal(Touch::TOUCH_MOVE, AMotionEvent_getX(event, i), AMotionEvent_getY(event, i), pointerId);
  781. }
  782. }
  783. }
  784. break;
  785. }
  786. return 1;
  787. }
  788. else if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY)
  789. {
  790. int32_t action = AKeyEvent_getAction(event);
  791. int32_t keycode = AKeyEvent_getKeyCode(event);
  792. int32_t metastate = AKeyEvent_getMetaState(event);
  793. switch(action)
  794. {
  795. case AKEY_EVENT_ACTION_DOWN:
  796. Game::getInstance()->keyEvent(Keyboard::KEY_PRESS, getKey(keycode, metastate));
  797. if (int character = getUnicode(keycode, metastate))
  798. gameplay::Platform::keyEventInternal(Keyboard::KEY_CHAR, character);
  799. break;
  800. case AKEY_EVENT_ACTION_UP:
  801. gameplay::Platform::keyEventInternal(Keyboard::KEY_RELEASE, getKey(keycode, metastate));
  802. break;
  803. }
  804. }
  805. return 0;
  806. }
  807. // Process the next main command.
  808. static void engine_handle_cmd(struct android_app* app, int32_t cmd)
  809. {
  810. switch (cmd)
  811. {
  812. case APP_CMD_INIT_WINDOW:
  813. // The window is being shown, get it ready.
  814. if (app->window != NULL)
  815. {
  816. initEGL();
  817. __initialized = true;
  818. }
  819. break;
  820. case APP_CMD_TERM_WINDOW:
  821. destroyEGLSurface();
  822. __initialized = false;
  823. break;
  824. case APP_CMD_DESTROY:
  825. Game::getInstance()->exit();
  826. destroyEGLMain();
  827. __initialized = false;
  828. break;
  829. case APP_CMD_GAINED_FOCUS:
  830. // When our app gains focus, we start monitoring the accelerometer.
  831. if (__accelerometerSensor != NULL)
  832. {
  833. ASensorEventQueue_enableSensor(__sensorEventQueue, __accelerometerSensor);
  834. // We'd like to get 60 events per second (in microseconds).
  835. ASensorEventQueue_setEventRate(__sensorEventQueue, __accelerometerSensor, (1000L/60)*1000);
  836. }
  837. if (Game::getInstance()->getState() == Game::UNINITIALIZED)
  838. {
  839. Game::getInstance()->run();
  840. }
  841. else
  842. {
  843. Game::getInstance()->resume();
  844. }
  845. break;
  846. case APP_CMD_RESUME:
  847. if (__initialized)
  848. {
  849. Game::getInstance()->resume();
  850. }
  851. __suspended = false;
  852. break;
  853. case APP_CMD_PAUSE:
  854. Game::getInstance()->pause();
  855. __suspended = true;
  856. break;
  857. case APP_CMD_LOST_FOCUS:
  858. // When our app loses focus, we stop monitoring the accelerometer.
  859. // This is to avoid consuming battery while not being used.
  860. if (__accelerometerSensor != NULL)
  861. {
  862. ASensorEventQueue_disableSensor(__sensorEventQueue, __accelerometerSensor);
  863. }
  864. break;
  865. }
  866. }
  867. Platform::Platform(Game* game)
  868. : _game(game)
  869. {
  870. }
  871. Platform::~Platform()
  872. {
  873. }
  874. Platform* Platform::create(Game* game, void* attachToWindow)
  875. {
  876. Platform* platform = new Platform(game);
  877. return platform;
  878. }
  879. int Platform::enterMessagePump()
  880. {
  881. GP_ASSERT(__state && __state->activity && __state->activity->vm);
  882. __initialized = false;
  883. __suspended = false;
  884. // Get the android application's activity.
  885. ANativeActivity* activity = __state->activity;
  886. JavaVM* jvm = __state->activity->vm;
  887. JNIEnv* env = NULL;
  888. jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
  889. jint res = jvm->AttachCurrentThread(&env, NULL);
  890. if (res == JNI_ERR)
  891. {
  892. GP_ERROR("Failed to retrieve JVM environment when entering message pump.");
  893. return -1;
  894. }
  895. GP_ASSERT(env);
  896. /* Get external files directory on Android; this will result in a directory where all app files
  897. * should be stored, like /mnt/sdcard/android/<package-name>/files/
  898. */
  899. jboolean isCopy;
  900. jclass clazz = env->GetObjectClass(activity->clazz);
  901. jmethodID methodGetExternalStorage = env->GetMethodID(clazz, "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;");
  902. jclass clazzFile = env->FindClass("java/io/File");
  903. jmethodID methodGetPath = env->GetMethodID(clazzFile, "getPath", "()Ljava/lang/String;");
  904. // Now has java.io.File object pointing to directory
  905. jobject objectFile = env->CallObjectMethod(activity->clazz, methodGetExternalStorage, NULL);
  906. // Now has String object containing path to directory
  907. jstring stringExternalPath = static_cast<jstring>(env->CallObjectMethod(objectFile, methodGetPath));
  908. const char* externalPath = env->GetStringUTFChars(stringExternalPath, &isCopy);
  909. // Set the default path to store the resources.
  910. std::string assetsPath(externalPath);
  911. if (externalPath[strlen(externalPath)-1] != '/')
  912. assetsPath += "/";
  913. FileSystem::setResourcePath(assetsPath.c_str());
  914. // Release string data
  915. env->ReleaseStringUTFChars(stringExternalPath, externalPath);
  916. jvm->DetachCurrentThread();
  917. // Get the asset manager to get the resources from the .apk file.
  918. __assetManager = activity->assetManager;
  919. // Set the event call back functions.
  920. __state->onAppCmd = engine_handle_cmd;
  921. __state->onInputEvent = engine_handle_input;
  922. // Prepare to monitor accelerometer.
  923. __sensorManager = ASensorManager_getInstance();
  924. __accelerometerSensor = ASensorManager_getDefaultSensor(__sensorManager, ASENSOR_TYPE_ACCELEROMETER);
  925. __sensorEventQueue = ASensorManager_createEventQueue(__sensorManager, __state->looper, LOOPER_ID_USER, NULL, NULL);
  926. // Get the initial time.
  927. clock_gettime(CLOCK_REALTIME, &__timespec);
  928. __timeStart = timespec2millis(&__timespec);
  929. __timeAbsolute = 0L;
  930. while (true)
  931. {
  932. // Read all pending events.
  933. int ident;
  934. int events;
  935. struct android_poll_source* source;
  936. while ((ident=ALooper_pollAll(!__suspended ? 0 : -1, NULL, &events, (void**)&source)) >= 0)
  937. {
  938. // Process this event.
  939. if (source != NULL)
  940. source->process(__state, source);
  941. // If a sensor has data, process it now.
  942. if (ident == LOOPER_ID_USER && __accelerometerSensor != NULL)
  943. ASensorEventQueue_getEvents(__sensorEventQueue, &__sensorEvent, 1);
  944. if (__state->destroyRequested != 0)
  945. {
  946. return 0;
  947. }
  948. }
  949. // Idle time (no events left to process) is spent rendering.
  950. // We skip rendering when the app is paused.
  951. if (__initialized && !__suspended)
  952. {
  953. _game->frame();
  954. // Post the new frame to the display.
  955. // Note that there are a couple cases where eglSwapBuffers could fail
  956. // with an error code that requires a certain level of re-initialization:
  957. //
  958. // 1) EGL_BAD_NATIVE_WINDOW - Called when the surface we're currently using
  959. // is invalidated. This would require us to destroy our EGL surface,
  960. // close our OpenKODE window, and start again.
  961. //
  962. // 2) EGL_CONTEXT_LOST - Power management event that led to our EGL context
  963. // being lost. Requires us to re-create and re-initalize our EGL context
  964. // and all OpenGL ES state.
  965. //
  966. // For now, if we get these, we'll simply exit.
  967. int rc = eglSwapBuffers(__eglDisplay, __eglSurface);
  968. if (rc != EGL_TRUE)
  969. {
  970. EGLint error = eglGetError();
  971. if (error == EGL_BAD_NATIVE_WINDOW)
  972. {
  973. if (__state->window != NULL)
  974. {
  975. destroyEGLSurface();
  976. initEGL();
  977. }
  978. __initialized = true;
  979. }
  980. else
  981. {
  982. perror("eglSwapBuffers");
  983. break;
  984. }
  985. }
  986. }
  987. // Display the keyboard.
  988. gameplay::displayKeyboard(__state, __displayKeyboard);
  989. }
  990. }
  991. void Platform::signalShutdown()
  992. {
  993. // nothing to do
  994. }
  995. bool Platform::canExit()
  996. {
  997. return true;
  998. }
  999. unsigned int Platform::getDisplayWidth()
  1000. {
  1001. return __width;
  1002. }
  1003. unsigned int Platform::getDisplayHeight()
  1004. {
  1005. return __height;
  1006. }
  1007. double Platform::getAbsoluteTime()
  1008. {
  1009. clock_gettime(CLOCK_REALTIME, &__timespec);
  1010. double now = timespec2millis(&__timespec);
  1011. __timeAbsolute = now - __timeStart;
  1012. return __timeAbsolute;
  1013. }
  1014. void Platform::setAbsoluteTime(double time)
  1015. {
  1016. __timeAbsolute = time;
  1017. }
  1018. bool Platform::isVsync()
  1019. {
  1020. return __vsync;
  1021. }
  1022. void Platform::setVsync(bool enable)
  1023. {
  1024. eglSwapInterval(__eglDisplay, enable ? 1 : 0);
  1025. __vsync = enable;
  1026. }
  1027. void Platform::swapBuffers()
  1028. {
  1029. if (__eglDisplay && __eglSurface)
  1030. eglSwapBuffers(__eglDisplay, __eglSurface);
  1031. }
  1032. void Platform::sleep(long ms)
  1033. {
  1034. usleep(ms * 1000);
  1035. }
  1036. void Platform::setMultiSampling(bool enabled)
  1037. {
  1038. if (enabled == __multiSampling)
  1039. {
  1040. return;
  1041. }
  1042. //todo
  1043. __multiSampling = enabled;
  1044. }
  1045. bool Platform::isMultiSampling()
  1046. {
  1047. return __multiSampling;
  1048. }
  1049. void Platform::setMultiTouch(bool enabled)
  1050. {
  1051. __multiTouch = enabled;
  1052. }
  1053. bool Platform::isMultiTouch()
  1054. {
  1055. return __multiTouch;
  1056. }
  1057. void Platform::getAccelerometerValues(float* pitch, float* roll)
  1058. {
  1059. double tx, ty, tz;
  1060. ASensorEvent event;
  1061. // By default, android accelerometer values are oriented to the portrait mode.
  1062. // flipping the x and y to get the desired landscape mode values.
  1063. switch (__orientationAngle)
  1064. {
  1065. case 90:
  1066. tx = -__sensorEvent.acceleration.y;
  1067. ty = __sensorEvent.acceleration.x;
  1068. break;
  1069. case 180:
  1070. tx = -__sensorEvent.acceleration.x;
  1071. ty = -__sensorEvent.acceleration.y;
  1072. break;
  1073. case 270:
  1074. tx = __sensorEvent.acceleration.y;
  1075. ty = -__sensorEvent.acceleration.x;
  1076. break;
  1077. default:
  1078. tx = __sensorEvent.acceleration.x;
  1079. ty = __sensorEvent.acceleration.y;
  1080. break;
  1081. }
  1082. tz = __sensorEvent.acceleration.z;
  1083. if (pitch != NULL)
  1084. {
  1085. GP_ASSERT(tx * tx + tz * tz);
  1086. *pitch = -atan(ty / sqrt(tx * tx + tz * tz)) * 180.0f * M_1_PI;
  1087. }
  1088. if (roll != NULL)
  1089. {
  1090. GP_ASSERT(ty * ty + tz * tz);
  1091. *roll = -atan(tx / sqrt(ty * ty + tz * tz)) * 180.0f * M_1_PI;
  1092. }
  1093. }
  1094. bool Platform::hasMouse()
  1095. {
  1096. // not supported
  1097. return false;
  1098. }
  1099. void Platform::setMouseCaptured(bool captured)
  1100. {
  1101. // not supported
  1102. }
  1103. bool Platform::isMouseCaptured()
  1104. {
  1105. // not supported
  1106. return false;
  1107. }
  1108. void Platform::setCursorVisible(bool visible)
  1109. {
  1110. // not supported
  1111. }
  1112. bool Platform::isCursorVisible()
  1113. {
  1114. // not supported
  1115. return false;
  1116. }
  1117. void Platform::displayKeyboard(bool display)
  1118. {
  1119. if (display)
  1120. __displayKeyboard = true;
  1121. else
  1122. __displayKeyboard = false;
  1123. }
  1124. void Platform::touchEventInternal(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
  1125. {
  1126. if (!Form::touchEventInternal(evt, x, y, contactIndex))
  1127. {
  1128. Game::getInstance()->touchEvent(evt, x, y, contactIndex);
  1129. Game::getInstance()->getScriptController()->touchEvent(evt, x, y, contactIndex);
  1130. }
  1131. }
  1132. void Platform::keyEventInternal(Keyboard::KeyEvent evt, int key)
  1133. {
  1134. if (!Form::keyEventInternal(evt, key))
  1135. {
  1136. Game::getInstance()->keyEvent(evt, key);
  1137. Game::getInstance()->getScriptController()->keyEvent(evt, key);
  1138. }
  1139. }
  1140. bool Platform::mouseEventInternal(Mouse::MouseEvent evt, int x, int y, int wheelDelta)
  1141. {
  1142. if (Form::mouseEventInternal(evt, x, y, wheelDelta))
  1143. {
  1144. return true;
  1145. }
  1146. else if (Game::getInstance()->mouseEvent(evt, x, y, wheelDelta))
  1147. {
  1148. return true;
  1149. }
  1150. else
  1151. {
  1152. return Game::getInstance()->getScriptController()->mouseEvent(evt, x, y, wheelDelta);
  1153. }
  1154. }
  1155. void Platform::gamepadEventConnectedInternal(GamepadHandle handle, unsigned int buttonCount, unsigned int joystickCount, unsigned int triggerCount,
  1156. unsigned int vendorId, unsigned int productId, const char* vendorString, const char* productString)
  1157. {
  1158. Gamepad::add(handle, buttonCount, joystickCount, triggerCount, vendorId, productId, vendorString, productString);
  1159. }
  1160. void Platform::gamepadEventDisconnectedInternal(GamepadHandle handle)
  1161. {
  1162. Gamepad::remove(handle);
  1163. }
  1164. void Platform::shutdownInternal()
  1165. {
  1166. Game::getInstance()->shutdown();
  1167. }
  1168. bool Platform::isGestureSupported(Gesture::GestureEvent evt)
  1169. {
  1170. // Pinch currently not implemented
  1171. return evt == gameplay::Gesture::GESTURE_SWIPE || evt == gameplay::Gesture::GESTURE_TAP;
  1172. }
  1173. void Platform::registerGesture(Gesture::GestureEvent evt)
  1174. {
  1175. switch(evt)
  1176. {
  1177. case Gesture::GESTURE_ANY_SUPPORTED:
  1178. __gestureEventsProcessed.set();
  1179. break;
  1180. case Gesture::GESTURE_TAP:
  1181. case Gesture::GESTURE_SWIPE:
  1182. __gestureEventsProcessed.set(evt);
  1183. break;
  1184. default:
  1185. break;
  1186. }
  1187. }
  1188. void Platform::unregisterGesture(Gesture::GestureEvent evt)
  1189. {
  1190. switch(evt)
  1191. {
  1192. case Gesture::GESTURE_ANY_SUPPORTED:
  1193. __gestureEventsProcessed.reset();
  1194. break;
  1195. case Gesture::GESTURE_TAP:
  1196. case Gesture::GESTURE_SWIPE:
  1197. __gestureEventsProcessed.set(evt, 0);
  1198. break;
  1199. default:
  1200. break;
  1201. }
  1202. }
  1203. bool Platform::isGestureRegistered(Gesture::GestureEvent evt)
  1204. {
  1205. return __gestureEventsProcessed.test(evt);
  1206. }
  1207. void Platform::pollGamepadState(Gamepad* gamepad)
  1208. {
  1209. }
  1210. bool Platform::launchURL(const char *url)
  1211. {
  1212. if (url == NULL || *url == '\0')
  1213. return false;
  1214. bool result = true;
  1215. android_app* state = __state;
  1216. GP_ASSERT(state && state->activity && state->activity->vm);
  1217. JavaVM* jvm = state->activity->vm;
  1218. JNIEnv* env = NULL;
  1219. jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
  1220. jint r = jvm->AttachCurrentThread(&env, NULL);
  1221. if (r == JNI_ERR)
  1222. {
  1223. GP_ERROR("Failed to retrieve JVM environment to display keyboard.");
  1224. return false;
  1225. }
  1226. GP_ASSERT(env);
  1227. jclass classActivity = env->FindClass("android/app/NativeActivity");
  1228. jclass classIntent = env->FindClass("android/content/Intent");
  1229. jclass classUri = env->FindClass("android/net/Uri");
  1230. GP_ASSERT(classActivity && classIntent && classUri);
  1231. // Get static field ID Intent.ACTION_VIEW
  1232. jfieldID fieldActionView = env->GetStaticFieldID(classIntent, "ACTION_VIEW", "Ljava/lang/String;");
  1233. GP_ASSERT(fieldActionView);
  1234. // Get string value of Intent.ACTION_VIEW, we'll need that to pass to Intent's constructor later on
  1235. jstring paramActionView = (jstring)env->GetStaticObjectField(classIntent, fieldActionView);
  1236. GP_ASSERT(paramActionView);
  1237. // Get method ID Uri.parse, will be needed to parse the url given into Uri object
  1238. jmethodID methodUriParse = env->GetStaticMethodID(classUri, "parse","(Ljava/lang/String;)Landroid/net/Uri;");
  1239. GP_ASSERT(methodUriParse);
  1240. // Get method ID Activity.startActivity, so we can start the appropriate activity for the View action of our Uri
  1241. jmethodID methodActivityStartActivity = env->GetMethodID(classActivity, "startActivity","(Landroid/content/Intent;)V");
  1242. GP_ASSERT(methodActivityStartActivity);
  1243. // Get method ID Intent constructor, the one that takes action and uri (String;Uri)
  1244. jmethodID methodIntentInit = env->GetMethodID(classIntent, "<init>","(Ljava/lang/String;Landroid/net/Uri;)V");
  1245. GP_ASSERT(methodIntentInit);
  1246. // Convert our url to Java's string and parse it to Uri
  1247. jstring paramUrlString = env->NewStringUTF(url);
  1248. jobject paramUri = env->CallStaticObjectMethod(classUri, methodUriParse, paramUrlString);
  1249. GP_ASSERT(paramUri);
  1250. // Create Intent with Intent.ACTION_VIEW and parsed Uri arguments
  1251. jobject paramIntent = env->NewObject(classIntent, methodIntentInit, paramActionView, paramUri);
  1252. GP_ASSERT(paramIntent);
  1253. // Launch NativeActivity.startActivity with our intent to view the url! state->activity->clazz holds
  1254. // our NativeActivity object
  1255. env->CallVoidMethod(state->activity->clazz, methodActivityStartActivity, paramIntent);
  1256. /* startActivity may throw a ActivitNotFoundException if, well, activity is not found.
  1257. Example: http://<url> is passed to the intent but there is no browser installed in the system
  1258. we need to handle it. */
  1259. jobject exception = env->ExceptionOccurred();
  1260. // We're not lucky here
  1261. if (exception)
  1262. {
  1263. // Print out the exception data to logcat
  1264. env->ExceptionDescribe();
  1265. // Exception needs to be cleared
  1266. env->ExceptionClear();
  1267. // Launching the url failed
  1268. result = false;
  1269. }
  1270. // See you Space Cowboy
  1271. jvm->DetachCurrentThread();
  1272. return result;
  1273. }
  1274. }
  1275. #endif