entry_android.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. /*
  2. * Copyright 2011-2018 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "entry_p.h"
  6. #if ENTRY_CONFIG_USE_NATIVE && BX_PLATFORM_ANDROID
  7. #include <bgfx/platform.h>
  8. #include <bx/thread.h>
  9. #include <bx/file.h>
  10. #include <android/input.h>
  11. #include <android/log.h>
  12. #include <android/looper.h>
  13. #include <android/window.h>
  14. #include <android_native_app_glue.h>
  15. #include <android/native_window.h>
  16. extern "C"
  17. {
  18. #pragma GCC diagnostic push
  19. #pragma GCC diagnostic ignored "-Wunused-parameter"
  20. #include <android_native_app_glue.c>
  21. #pragma GCC diagnostic pop
  22. } // extern "C"
  23. namespace entry
  24. {
  25. ///
  26. inline void androidSetWindow(::ANativeWindow* _window)
  27. {
  28. bgfx::PlatformData pd;
  29. pd.ndt = NULL;
  30. pd.nwh = _window;
  31. pd.context = NULL;
  32. pd.backBuffer = NULL;
  33. pd.backBufferDS = NULL;
  34. bgfx::setPlatformData(pd);
  35. }
  36. struct GamepadRemap
  37. {
  38. uint16_t m_keyCode;
  39. Key::Enum m_key;
  40. };
  41. static GamepadRemap s_gamepadRemap[] =
  42. {
  43. { AKEYCODE_DPAD_UP, Key::GamepadUp },
  44. { AKEYCODE_DPAD_DOWN, Key::GamepadDown },
  45. { AKEYCODE_DPAD_LEFT, Key::GamepadLeft },
  46. { AKEYCODE_DPAD_RIGHT, Key::GamepadRight },
  47. { AKEYCODE_BUTTON_START, Key::GamepadStart },
  48. { AKEYCODE_BACK, Key::GamepadBack },
  49. { AKEYCODE_BUTTON_THUMBL, Key::GamepadThumbL },
  50. { AKEYCODE_BUTTON_THUMBR, Key::GamepadThumbR },
  51. { AKEYCODE_BUTTON_L1, Key::GamepadShoulderL },
  52. { AKEYCODE_BUTTON_R1, Key::GamepadShoulderR },
  53. { AKEYCODE_GUIDE, Key::GamepadGuide },
  54. { AKEYCODE_BUTTON_A, Key::GamepadA },
  55. { AKEYCODE_BUTTON_B, Key::GamepadB },
  56. { AKEYCODE_BUTTON_X, Key::GamepadX },
  57. { AKEYCODE_BUTTON_Y, Key::GamepadY },
  58. };
  59. struct GamepadAxisRemap
  60. {
  61. int32_t m_event;
  62. GamepadAxis::Enum m_axis;
  63. bool m_convert;
  64. };
  65. static GamepadAxisRemap s_translateAxis[] =
  66. {
  67. { AMOTION_EVENT_AXIS_X, GamepadAxis::LeftX, false },
  68. { AMOTION_EVENT_AXIS_Y, GamepadAxis::LeftY, false },
  69. { AMOTION_EVENT_AXIS_LTRIGGER, GamepadAxis::LeftZ, false },
  70. { AMOTION_EVENT_AXIS_Z, GamepadAxis::RightX, true },
  71. { AMOTION_EVENT_AXIS_RZ, GamepadAxis::RightY, false },
  72. { AMOTION_EVENT_AXIS_RTRIGGER, GamepadAxis::RightZ, false },
  73. };
  74. struct MainThreadEntry
  75. {
  76. int m_argc;
  77. const char* const* m_argv;
  78. static int32_t threadFunc(bx::Thread* _thread, void* _userData);
  79. };
  80. class FileReaderAndroid : public bx::FileReaderI
  81. {
  82. public:
  83. FileReaderAndroid(AAssetManager* _assetManager, AAsset* _file)
  84. : m_assetManager(_assetManager)
  85. , m_file(_file)
  86. , m_open(false)
  87. {
  88. }
  89. virtual ~FileReaderAndroid()
  90. {
  91. close();
  92. }
  93. virtual bool open(const bx::FilePath& _filePath, bx::Error* _err) override
  94. {
  95. BX_CHECK(NULL != _err, "Reader/Writer interface calling functions must handle errors.");
  96. if (NULL != m_file)
  97. {
  98. BX_ERROR_SET(_err, BX_ERROR_READERWRITER_ALREADY_OPEN, "FileReader: File is already open.");
  99. return false;
  100. }
  101. m_file = AAssetManager_open(m_assetManager, _filePath.get(), AASSET_MODE_RANDOM);
  102. if (NULL == m_file)
  103. {
  104. BX_ERROR_SET(_err, BX_ERROR_READERWRITER_OPEN, "FileReader: Failed to open file.");
  105. return false;
  106. }
  107. m_open = true;
  108. return true;
  109. }
  110. virtual void close() override
  111. {
  112. if (m_open
  113. && NULL != m_file)
  114. {
  115. AAsset_close(m_file);
  116. m_file = NULL;
  117. }
  118. }
  119. virtual int64_t seek(int64_t _offset, bx::Whence::Enum _whence) override
  120. {
  121. BX_CHECK(NULL != m_file, "Reader/Writer file is not open.");
  122. return AAsset_seek64(m_file, _offset, _whence);
  123. }
  124. virtual int32_t read(void* _data, int32_t _size, bx::Error* _err) override
  125. {
  126. BX_CHECK(NULL != m_file, "Reader/Writer file is not open.");
  127. BX_CHECK(NULL != _err, "Reader/Writer interface calling functions must handle errors.");
  128. int32_t size = (int32_t)AAsset_read(m_file, _data, _size);
  129. if (size != _size)
  130. {
  131. if (0 == AAsset_getRemainingLength(m_file) )
  132. {
  133. BX_ERROR_SET(_err, BX_ERROR_READERWRITER_EOF, "FileReader: EOF.");
  134. }
  135. return size >= 0 ? size : 0;
  136. }
  137. return size;
  138. }
  139. private:
  140. AAssetManager* m_assetManager;
  141. AAsset* m_file;
  142. bool m_open;
  143. };
  144. struct Context
  145. {
  146. Context()
  147. : m_window(NULL)
  148. {
  149. bx::memSet(m_value, 0, sizeof(m_value) );
  150. // Deadzone values from xinput.h
  151. m_deadzone[GamepadAxis::LeftX ] =
  152. m_deadzone[GamepadAxis::LeftY ] = 7849;
  153. m_deadzone[GamepadAxis::RightX] =
  154. m_deadzone[GamepadAxis::RightY] = 8689;
  155. m_deadzone[GamepadAxis::LeftZ ] =
  156. m_deadzone[GamepadAxis::RightZ] = 30;
  157. }
  158. void run(android_app* _app)
  159. {
  160. m_app = _app;
  161. m_app->userData = (void*)this;
  162. m_app->onAppCmd = onAppCmdCB;
  163. m_app->onInputEvent = onInputEventCB;
  164. ANativeActivity_setWindowFlags(m_app->activity, 0
  165. | AWINDOW_FLAG_FULLSCREEN
  166. | AWINDOW_FLAG_KEEP_SCREEN_ON
  167. , 0
  168. );
  169. const char* const argv[1] = { "android.so" };
  170. m_mte.m_argc = 1;
  171. m_mte.m_argv = argv;
  172. while (0 == m_app->destroyRequested)
  173. {
  174. int32_t num;
  175. android_poll_source* source;
  176. /*int32_t id =*/ ALooper_pollAll(-1, NULL, &num, (void**)&source);
  177. if (NULL != source)
  178. {
  179. source->process(m_app, source);
  180. }
  181. }
  182. m_thread.shutdown();
  183. }
  184. void onAppCmd(int32_t _cmd)
  185. {
  186. switch (_cmd)
  187. {
  188. case APP_CMD_INPUT_CHANGED:
  189. // Command from main thread: the AInputQueue has changed. Upon processing
  190. // this command, android_app->inputQueue will be updated to the new queue
  191. // (or NULL).
  192. break;
  193. case APP_CMD_INIT_WINDOW:
  194. // Command from main thread: a new ANativeWindow is ready for use. Upon
  195. // receiving this command, android_app->window will contain the new window
  196. // surface.
  197. if (m_window != m_app->window)
  198. {
  199. m_window = m_app->window;
  200. androidSetWindow(m_window);
  201. int32_t width = ANativeWindow_getWidth(m_window);
  202. int32_t height = ANativeWindow_getHeight(m_window);
  203. DBG("ANativeWindow width %d, height %d", width, height);
  204. WindowHandle defaultWindow = { 0 };
  205. m_eventQueue.postSizeEvent(defaultWindow, width, height);
  206. if (!m_thread.isRunning() )
  207. {
  208. m_thread.init(MainThreadEntry::threadFunc, &m_mte);
  209. }
  210. }
  211. break;
  212. case APP_CMD_TERM_WINDOW:
  213. // Command from main thread: the existing ANativeWindow needs to be
  214. // terminated. Upon receiving this command, android_app->window still
  215. // contains the existing window; after calling android_app_exec_cmd
  216. // it will be set to NULL.
  217. break;
  218. case APP_CMD_WINDOW_RESIZED:
  219. // Command from main thread: the current ANativeWindow has been resized.
  220. // Please redraw with its new size.
  221. break;
  222. case APP_CMD_WINDOW_REDRAW_NEEDED:
  223. // Command from main thread: the system needs that the current ANativeWindow
  224. // be redrawn. You should redraw the window before handing this to
  225. // android_app_exec_cmd() in order to avoid transient drawing glitches.
  226. break;
  227. case APP_CMD_CONTENT_RECT_CHANGED:
  228. // Command from main thread: the content area of the window has changed,
  229. // such as from the soft input window being shown or hidden. You can
  230. // find the new content rect in android_app::contentRect.
  231. break;
  232. case APP_CMD_GAINED_FOCUS:
  233. {
  234. // Command from main thread: the app's activity window has gained
  235. // input focus.
  236. WindowHandle defaultWindow = { 0 };
  237. m_eventQueue.postSuspendEvent(defaultWindow, Suspend::WillResume);
  238. break;
  239. }
  240. case APP_CMD_LOST_FOCUS:
  241. {
  242. // Command from main thread: the app's activity window has lost
  243. // input focus.
  244. WindowHandle defaultWindow = { 0 };
  245. m_eventQueue.postSuspendEvent(defaultWindow, Suspend::WillSuspend);
  246. break;
  247. }
  248. case APP_CMD_CONFIG_CHANGED:
  249. // Command from main thread: the current device configuration has changed.
  250. break;
  251. case APP_CMD_LOW_MEMORY:
  252. // Command from main thread: the system is running low on memory.
  253. // Try to reduce your memory use.
  254. break;
  255. case APP_CMD_START:
  256. // Command from main thread: the app's activity has been started.
  257. break;
  258. case APP_CMD_RESUME:
  259. {
  260. // Command from main thread: the app's activity has been resumed.
  261. WindowHandle defaultWindow = { 0 };
  262. m_eventQueue.postSuspendEvent(defaultWindow, Suspend::DidResume);
  263. break;
  264. }
  265. case APP_CMD_SAVE_STATE:
  266. // Command from main thread: the app should generate a new saved state
  267. // for itself, to restore from later if needed. If you have saved state,
  268. // allocate it with malloc and place it in android_app.savedState with
  269. // the size in android_app.savedStateSize. The will be freed for you
  270. // later.
  271. break;
  272. case APP_CMD_PAUSE:
  273. {
  274. // Command from main thread: the app's activity has been paused.
  275. WindowHandle defaultWindow = { 0 };
  276. m_eventQueue.postSuspendEvent(defaultWindow, Suspend::DidSuspend);
  277. break;
  278. }
  279. case APP_CMD_STOP:
  280. // Command from main thread: the app's activity has been stopped.
  281. break;
  282. case APP_CMD_DESTROY:
  283. // Command from main thread: the app's activity is being destroyed,
  284. // and waiting for the app thread to clean up and exit before proceeding.
  285. m_eventQueue.postExitEvent();
  286. break;
  287. }
  288. }
  289. bool filter(GamepadAxis::Enum _axis, int32_t* _value)
  290. {
  291. const int32_t old = m_value[_axis];
  292. const int32_t deadzone = m_deadzone[_axis];
  293. int32_t value = *_value;
  294. value = value > deadzone || value < -deadzone ? value : 0;
  295. m_value[_axis] = value;
  296. *_value = value;
  297. return old != value;
  298. }
  299. int32_t onInputEvent(AInputEvent* _event)
  300. {
  301. WindowHandle defaultWindow = { 0 };
  302. GamepadHandle handle = { 0 };
  303. const int32_t type = AInputEvent_getType(_event);
  304. const int32_t source = AInputEvent_getSource(_event);
  305. const int32_t actionBits = AMotionEvent_getAction(_event);
  306. switch (type)
  307. {
  308. case AINPUT_EVENT_TYPE_MOTION:
  309. {
  310. if (0 != (source & (AINPUT_SOURCE_GAMEPAD|AINPUT_SOURCE_JOYSTICK) ) )
  311. {
  312. for (uint32_t ii = 0; ii < BX_COUNTOF(s_translateAxis); ++ii)
  313. {
  314. const float fval = AMotionEvent_getAxisValue(_event, s_translateAxis[ii].m_event, 0);
  315. int32_t value = int32_t( (s_translateAxis[ii].m_convert ? fval * 2.0f + 1.0f : fval) * INT16_MAX);
  316. GamepadAxis::Enum axis = s_translateAxis[ii].m_axis;
  317. if (filter(axis, &value) )
  318. {
  319. m_eventQueue.postAxisEvent(defaultWindow, handle, axis, value);
  320. }
  321. }
  322. return 1;
  323. }
  324. else
  325. {
  326. float mx = AMotionEvent_getX(_event, 0);
  327. float my = AMotionEvent_getY(_event, 0);
  328. int32_t count = AMotionEvent_getPointerCount(_event);
  329. int32_t action = (actionBits & AMOTION_EVENT_ACTION_MASK);
  330. int32_t index = (actionBits & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
  331. // Simulate left mouse click with 1st touch and right mouse click with 2nd touch. ignore other touchs
  332. if (count < 2)
  333. {
  334. switch (action)
  335. {
  336. case AMOTION_EVENT_ACTION_DOWN:
  337. case AMOTION_EVENT_ACTION_POINTER_DOWN:
  338. m_eventQueue.postMouseEvent(defaultWindow
  339. , (int32_t)mx
  340. , (int32_t)my
  341. , 0
  342. , action == AMOTION_EVENT_ACTION_DOWN ? MouseButton::Left : MouseButton::Right
  343. , true
  344. );
  345. break;
  346. case AMOTION_EVENT_ACTION_UP:
  347. case AMOTION_EVENT_ACTION_POINTER_UP:
  348. m_eventQueue.postMouseEvent(defaultWindow
  349. , (int32_t)mx
  350. , (int32_t)my
  351. , 0
  352. , action == AMOTION_EVENT_ACTION_UP ? MouseButton::Left : MouseButton::Right
  353. , false
  354. );
  355. break;
  356. default:
  357. break;
  358. }
  359. }
  360. switch (action)
  361. {
  362. case AMOTION_EVENT_ACTION_MOVE:
  363. if (0 == index)
  364. {
  365. m_eventQueue.postMouseEvent(defaultWindow
  366. , (int32_t)mx
  367. , (int32_t)my
  368. , 0
  369. );
  370. }
  371. break;
  372. default:
  373. break;
  374. }
  375. }
  376. }
  377. break;
  378. case AINPUT_EVENT_TYPE_KEY:
  379. {
  380. int32_t keyCode = AKeyEvent_getKeyCode(_event);
  381. if (0 != (source & (AINPUT_SOURCE_GAMEPAD|AINPUT_SOURCE_JOYSTICK) ) )
  382. {
  383. for (uint32_t jj = 0; jj < BX_COUNTOF(s_gamepadRemap); ++jj)
  384. {
  385. if (keyCode == s_gamepadRemap[jj].m_keyCode)
  386. {
  387. m_eventQueue.postKeyEvent(defaultWindow, s_gamepadRemap[jj].m_key, 0, actionBits == AKEY_EVENT_ACTION_DOWN);
  388. break;
  389. }
  390. }
  391. }
  392. return 1;
  393. }
  394. break;
  395. default:
  396. DBG("type %d", type);
  397. break;
  398. }
  399. return 0;
  400. }
  401. static void onAppCmdCB(struct android_app* _app, int32_t _cmd)
  402. {
  403. Context* self = (Context*)_app->userData;
  404. self->onAppCmd(_cmd);
  405. }
  406. static int32_t onInputEventCB(struct android_app* _app, AInputEvent* _event)
  407. {
  408. Context* self = (Context*)_app->userData;
  409. return self->onInputEvent(_event);
  410. }
  411. MainThreadEntry m_mte;
  412. bx::Thread m_thread;
  413. EventQueue m_eventQueue;
  414. ANativeWindow* m_window;
  415. android_app* m_app;
  416. int32_t m_value[GamepadAxis::Count];
  417. int32_t m_deadzone[GamepadAxis::Count];
  418. };
  419. static Context s_ctx;
  420. const Event* poll()
  421. {
  422. return s_ctx.m_eventQueue.poll();
  423. }
  424. const Event* poll(WindowHandle _handle)
  425. {
  426. return s_ctx.m_eventQueue.poll(_handle);
  427. }
  428. void release(const Event* _event)
  429. {
  430. s_ctx.m_eventQueue.release(_event);
  431. }
  432. WindowHandle createWindow(int32_t _x, int32_t _y, uint32_t _width, uint32_t _height, uint32_t _flags, const char* _title)
  433. {
  434. BX_UNUSED(_x, _y, _width, _height, _flags, _title);
  435. WindowHandle handle = { UINT16_MAX };
  436. return handle;
  437. }
  438. void destroyWindow(WindowHandle _handle)
  439. {
  440. BX_UNUSED(_handle);
  441. }
  442. void setWindowPos(WindowHandle _handle, int32_t _x, int32_t _y)
  443. {
  444. BX_UNUSED(_handle, _x, _y);
  445. }
  446. void setWindowSize(WindowHandle _handle, uint32_t _width, uint32_t _height)
  447. {
  448. BX_UNUSED(_handle, _width, _height);
  449. }
  450. void setWindowTitle(WindowHandle _handle, const char* _title)
  451. {
  452. BX_UNUSED(_handle, _title);
  453. }
  454. void setWindowFlags(WindowHandle _handle, uint32_t _flags, bool _enabled)
  455. {
  456. BX_UNUSED(_handle, _flags, _enabled);
  457. }
  458. void toggleFullscreen(WindowHandle _handle)
  459. {
  460. BX_UNUSED(_handle);
  461. }
  462. void setMouseLock(WindowHandle _handle, bool _lock)
  463. {
  464. BX_UNUSED(_handle, _lock);
  465. }
  466. int32_t MainThreadEntry::threadFunc(bx::Thread* _thread, void* _userData)
  467. {
  468. BX_UNUSED(_thread);
  469. int32_t result = chdir("/sdcard/bgfx/examples/runtime");
  470. BX_CHECK(0 == result, "Failed to chdir to dir. android.permission.WRITE_EXTERNAL_STORAGE?", errno);
  471. MainThreadEntry* self = (MainThreadEntry*)_userData;
  472. result = main(self->m_argc, self->m_argv);
  473. // PostMessage(s_ctx.m_hwnd, WM_QUIT, 0, 0);
  474. return result;
  475. }
  476. } // namespace entry
  477. extern "C" void android_main(android_app* _app)
  478. {
  479. using namespace entry;
  480. s_ctx.run(_app);
  481. }
  482. #endif // ENTRY_CONFIG_USE_NATIVE && BX_PLATFORM_ANDROID