entry_android.cpp 15 KB

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