java_godot_lib_jni.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. /**************************************************************************/
  2. /* java_godot_lib_jni.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "java_godot_lib_jni.h"
  31. #include "android_input_handler.h"
  32. #include "api/java_class_wrapper.h"
  33. #include "api/jni_singleton.h"
  34. #include "dir_access_jandroid.h"
  35. #include "display_server_android.h"
  36. #include "file_access_android.h"
  37. #include "file_access_filesystem_jandroid.h"
  38. #include "java_godot_io_wrapper.h"
  39. #include "java_godot_wrapper.h"
  40. #include "jni_utils.h"
  41. #include "net_socket_android.h"
  42. #include "os_android.h"
  43. #include "string_android.h"
  44. #include "thread_jandroid.h"
  45. #include "tts_android.h"
  46. #include "core/config/engine.h"
  47. #include "core/config/project_settings.h"
  48. #include "core/input/input.h"
  49. #include "main/main.h"
  50. #ifdef TOOLS_ENABLED
  51. #include "editor/editor_settings.h"
  52. #endif
  53. #include <android/asset_manager_jni.h>
  54. #include <android/input.h>
  55. #include <android/native_window_jni.h>
  56. #include <unistd.h>
  57. static JavaClassWrapper *java_class_wrapper = nullptr;
  58. static OS_Android *os_android = nullptr;
  59. static AndroidInputHandler *input_handler = nullptr;
  60. static GodotJavaWrapper *godot_java = nullptr;
  61. static GodotIOJavaWrapper *godot_io_java = nullptr;
  62. static SafeNumeric<int> step; // Shared between UI and render threads
  63. static Size2 new_size;
  64. static Vector3 accelerometer;
  65. static Vector3 gravity;
  66. static Vector3 magnetometer;
  67. static Vector3 gyroscope;
  68. static void _terminate(JNIEnv *env, bool p_restart = false) {
  69. step.set(-1); // Ensure no further steps are attempted and no further events are sent
  70. // lets cleanup
  71. if (java_class_wrapper) {
  72. memdelete(java_class_wrapper);
  73. }
  74. if (input_handler) {
  75. delete input_handler;
  76. }
  77. // Whether restarting is handled by 'Main::cleanup()'
  78. bool restart_on_cleanup = false;
  79. if (os_android) {
  80. restart_on_cleanup = os_android->is_restart_on_exit_set();
  81. os_android->main_loop_end();
  82. Main::cleanup();
  83. delete os_android;
  84. }
  85. if (godot_io_java) {
  86. delete godot_io_java;
  87. }
  88. if (godot_java) {
  89. if (!restart_on_cleanup) {
  90. if (p_restart) {
  91. godot_java->restart(env);
  92. } else {
  93. godot_java->force_quit(env);
  94. }
  95. }
  96. delete godot_java;
  97. }
  98. }
  99. extern "C" {
  100. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_setVirtualKeyboardHeight(JNIEnv *env, jclass clazz, jint p_height) {
  101. if (godot_io_java) {
  102. godot_io_java->set_vk_height(p_height);
  103. }
  104. }
  105. JNIEXPORT jboolean JNICALL Java_org_godotengine_godot_GodotLib_initialize(JNIEnv *env, jclass clazz, jobject p_activity, jobject p_godot_instance, jobject p_asset_manager, jobject p_godot_io, jobject p_net_utils, jobject p_directory_access_handler, jobject p_file_access_handler, jboolean p_use_apk_expansion) {
  106. JavaVM *jvm;
  107. env->GetJavaVM(&jvm);
  108. // create our wrapper classes
  109. godot_java = new GodotJavaWrapper(env, p_activity, p_godot_instance);
  110. godot_io_java = new GodotIOJavaWrapper(env, p_godot_io);
  111. init_thread_jandroid(jvm, env);
  112. jobject amgr = env->NewGlobalRef(p_asset_manager);
  113. FileAccessAndroid::asset_manager = AAssetManager_fromJava(env, amgr);
  114. DirAccessJAndroid::setup(p_directory_access_handler);
  115. FileAccessFilesystemJAndroid::setup(p_file_access_handler);
  116. NetSocketAndroid::setup(p_net_utils);
  117. os_android = new OS_Android(godot_java, godot_io_java, p_use_apk_expansion);
  118. return godot_java->on_video_init(env);
  119. }
  120. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_ondestroy(JNIEnv *env, jclass clazz) {
  121. _terminate(env, false);
  122. }
  123. JNIEXPORT jboolean JNICALL Java_org_godotengine_godot_GodotLib_setup(JNIEnv *env, jclass clazz, jobjectArray p_cmdline, jobject p_godot_tts) {
  124. setup_android_thread();
  125. const char **cmdline = nullptr;
  126. jstring *j_cmdline = nullptr;
  127. int cmdlen = 0;
  128. if (p_cmdline) {
  129. cmdlen = env->GetArrayLength(p_cmdline);
  130. if (cmdlen) {
  131. cmdline = (const char **)memalloc((cmdlen + 1) * sizeof(const char *));
  132. ERR_FAIL_NULL_V_MSG(cmdline, false, "Out of memory.");
  133. cmdline[cmdlen] = nullptr;
  134. j_cmdline = (jstring *)memalloc(cmdlen * sizeof(jstring));
  135. ERR_FAIL_NULL_V_MSG(j_cmdline, false, "Out of memory.");
  136. for (int i = 0; i < cmdlen; i++) {
  137. jstring string = (jstring)env->GetObjectArrayElement(p_cmdline, i);
  138. const char *rawString = env->GetStringUTFChars(string, nullptr);
  139. cmdline[i] = rawString;
  140. j_cmdline[i] = string;
  141. }
  142. }
  143. }
  144. Error err = Main::setup(OS_Android::ANDROID_EXEC_PATH, cmdlen, (char **)cmdline, false);
  145. if (cmdline) {
  146. if (j_cmdline) {
  147. for (int i = 0; i < cmdlen; ++i) {
  148. env->ReleaseStringUTFChars(j_cmdline[i], cmdline[i]);
  149. }
  150. memfree(j_cmdline);
  151. }
  152. memfree(cmdline);
  153. }
  154. // Note: --help and --version return ERR_HELP, but this should be translated to 0 if exit codes are propagated.
  155. if (err != OK) {
  156. return false;
  157. }
  158. TTS_Android::setup(p_godot_tts);
  159. java_class_wrapper = memnew(JavaClassWrapper(godot_java->get_activity()));
  160. GDREGISTER_CLASS(JNISingleton);
  161. return true;
  162. }
  163. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv *env, jclass clazz, jobject p_surface, jint p_width, jint p_height) {
  164. if (os_android) {
  165. os_android->set_display_size(Size2i(p_width, p_height));
  166. // No need to reset the surface during startup
  167. if (step.get() > 0) {
  168. if (p_surface) {
  169. ANativeWindow *native_window = ANativeWindow_fromSurface(env, p_surface);
  170. os_android->set_native_window(native_window);
  171. }
  172. DisplayServerAndroid::get_singleton()->reset_window();
  173. DisplayServerAndroid::get_singleton()->notify_surface_changed(p_width, p_height);
  174. }
  175. }
  176. }
  177. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv *env, jclass clazz, jobject p_surface) {
  178. if (os_android) {
  179. if (step.get() == 0) {
  180. // During startup
  181. if (p_surface) {
  182. ANativeWindow *native_window = ANativeWindow_fromSurface(env, p_surface);
  183. os_android->set_native_window(native_window);
  184. }
  185. } else {
  186. // Rendering context recreated because it was lost; restart app to let it reload everything
  187. _terminate(env, true);
  188. }
  189. }
  190. }
  191. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_back(JNIEnv *env, jclass clazz) {
  192. if (step.get() == 0) {
  193. return;
  194. }
  195. if (DisplayServerAndroid *dsa = Object::cast_to<DisplayServerAndroid>(DisplayServer::get_singleton())) {
  196. dsa->send_window_event(DisplayServer::WINDOW_EVENT_GO_BACK_REQUEST);
  197. }
  198. }
  199. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_ttsCallback(JNIEnv *env, jclass clazz, jint event, jint id, jint pos) {
  200. TTS_Android::_java_utterance_callback(event, id, pos);
  201. }
  202. JNIEXPORT jboolean JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv *env, jclass clazz) {
  203. if (step.get() == -1) {
  204. return true;
  205. }
  206. if (step.get() == 0) {
  207. // Since Godot is initialized on the UI thread, main_thread_id was set to that thread's id,
  208. // but for Godot purposes, the main thread is the one running the game loop
  209. Main::setup2();
  210. input_handler = new AndroidInputHandler();
  211. step.increment();
  212. return true;
  213. }
  214. if (step.get() == 1) {
  215. if (!Main::start()) {
  216. return true; // should exit instead and print the error
  217. }
  218. godot_java->on_godot_setup_completed(env);
  219. os_android->main_loop_begin();
  220. godot_java->on_godot_main_loop_started(env);
  221. step.increment();
  222. }
  223. DisplayServerAndroid::get_singleton()->process_accelerometer(accelerometer);
  224. DisplayServerAndroid::get_singleton()->process_gravity(gravity);
  225. DisplayServerAndroid::get_singleton()->process_magnetometer(magnetometer);
  226. DisplayServerAndroid::get_singleton()->process_gyroscope(gyroscope);
  227. bool should_swap_buffers = false;
  228. if (os_android->main_loop_iterate(&should_swap_buffers)) {
  229. _terminate(env, false);
  230. }
  231. return should_swap_buffers;
  232. }
  233. // Called on the UI thread
  234. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_dispatchMouseEvent(JNIEnv *env, jclass clazz, jint p_event_type, jint p_button_mask, jfloat p_x, jfloat p_y, jfloat p_delta_x, jfloat p_delta_y, jboolean p_double_click, jboolean p_source_mouse_relative) {
  235. if (step.get() <= 0) {
  236. return;
  237. }
  238. input_handler->process_mouse_event(p_event_type, p_button_mask, Point2(p_x, p_y), Vector2(p_delta_x, p_delta_y), p_double_click, p_source_mouse_relative);
  239. }
  240. // Called on the UI thread
  241. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_dispatchTouchEvent(JNIEnv *env, jclass clazz, jint ev, jint pointer, jint pointer_count, jfloatArray position, jboolean p_double_tap) {
  242. if (step.get() <= 0) {
  243. return;
  244. }
  245. Vector<AndroidInputHandler::TouchPos> points;
  246. for (int i = 0; i < pointer_count; i++) {
  247. jfloat p[3];
  248. env->GetFloatArrayRegion(position, i * 3, 3, p);
  249. AndroidInputHandler::TouchPos tp;
  250. tp.pos = Point2(p[1], p[2]);
  251. tp.id = (int)p[0];
  252. points.push_back(tp);
  253. }
  254. input_handler->process_touch_event(ev, pointer, points, p_double_tap);
  255. }
  256. // Called on the UI thread
  257. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_magnify(JNIEnv *env, jclass clazz, jfloat p_x, jfloat p_y, jfloat p_factor) {
  258. if (step.get() <= 0) {
  259. return;
  260. }
  261. input_handler->process_magnify(Point2(p_x, p_y), p_factor);
  262. }
  263. // Called on the UI thread
  264. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_pan(JNIEnv *env, jclass clazz, jfloat p_x, jfloat p_y, jfloat p_delta_x, jfloat p_delta_y) {
  265. if (step.get() <= 0) {
  266. return;
  267. }
  268. input_handler->process_pan(Point2(p_x, p_y), Vector2(p_delta_x, p_delta_y));
  269. }
  270. // Called on the UI thread
  271. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joybutton(JNIEnv *env, jclass clazz, jint p_device, jint p_button, jboolean p_pressed) {
  272. if (step.get() <= 0) {
  273. return;
  274. }
  275. AndroidInputHandler::JoypadEvent jevent;
  276. jevent.device = p_device;
  277. jevent.type = AndroidInputHandler::JOY_EVENT_BUTTON;
  278. jevent.index = p_button;
  279. jevent.pressed = p_pressed;
  280. input_handler->process_joy_event(jevent);
  281. }
  282. // Called on the UI thread
  283. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyaxis(JNIEnv *env, jclass clazz, jint p_device, jint p_axis, jfloat p_value) {
  284. if (step.get() <= 0) {
  285. return;
  286. }
  287. AndroidInputHandler::JoypadEvent jevent;
  288. jevent.device = p_device;
  289. jevent.type = AndroidInputHandler::JOY_EVENT_AXIS;
  290. jevent.index = p_axis;
  291. jevent.value = p_value;
  292. input_handler->process_joy_event(jevent);
  293. }
  294. // Called on the UI thread
  295. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyhat(JNIEnv *env, jclass clazz, jint p_device, jint p_hat_x, jint p_hat_y) {
  296. if (step.get() <= 0) {
  297. return;
  298. }
  299. AndroidInputHandler::JoypadEvent jevent;
  300. jevent.device = p_device;
  301. jevent.type = AndroidInputHandler::JOY_EVENT_HAT;
  302. BitField<HatMask> hat;
  303. if (p_hat_x != 0) {
  304. if (p_hat_x < 0) {
  305. hat.set_flag(HatMask::LEFT);
  306. } else {
  307. hat.set_flag(HatMask::RIGHT);
  308. }
  309. }
  310. if (p_hat_y != 0) {
  311. if (p_hat_y < 0) {
  312. hat.set_flag(HatMask::UP);
  313. } else {
  314. hat.set_flag(HatMask::DOWN);
  315. }
  316. }
  317. jevent.hat = hat;
  318. input_handler->process_joy_event(jevent);
  319. }
  320. // Called on the UI thread
  321. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyconnectionchanged(JNIEnv *env, jclass clazz, jint p_device, jboolean p_connected, jstring p_name) {
  322. if (os_android) {
  323. String name = jstring_to_string(p_name, env);
  324. Input::get_singleton()->joy_connection_changed(p_device, p_connected, name);
  325. }
  326. }
  327. // Called on the UI thread
  328. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_key(JNIEnv *env, jclass clazz, jint p_physical_keycode, jint p_unicode, jint p_key_label, jboolean p_pressed, jboolean p_echo) {
  329. if (step.get() <= 0) {
  330. return;
  331. }
  332. input_handler->process_key_event(p_physical_keycode, p_unicode, p_key_label, p_pressed, p_echo);
  333. }
  334. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_accelerometer(JNIEnv *env, jclass clazz, jfloat x, jfloat y, jfloat z) {
  335. accelerometer = Vector3(x, y, z);
  336. }
  337. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_gravity(JNIEnv *env, jclass clazz, jfloat x, jfloat y, jfloat z) {
  338. gravity = Vector3(x, y, z);
  339. }
  340. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_magnetometer(JNIEnv *env, jclass clazz, jfloat x, jfloat y, jfloat z) {
  341. magnetometer = Vector3(x, y, z);
  342. }
  343. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_gyroscope(JNIEnv *env, jclass clazz, jfloat x, jfloat y, jfloat z) {
  344. gyroscope = Vector3(x, y, z);
  345. }
  346. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusin(JNIEnv *env, jclass clazz) {
  347. if (step.get() <= 0) {
  348. return;
  349. }
  350. os_android->main_loop_focusin();
  351. }
  352. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusout(JNIEnv *env, jclass clazz) {
  353. if (step.get() <= 0) {
  354. return;
  355. }
  356. os_android->main_loop_focusout();
  357. }
  358. JNIEXPORT jstring JNICALL Java_org_godotengine_godot_GodotLib_getGlobal(JNIEnv *env, jclass clazz, jstring path) {
  359. String js = jstring_to_string(path, env);
  360. return env->NewStringUTF(GLOBAL_GET(js).operator String().utf8().get_data());
  361. }
  362. JNIEXPORT jstring JNICALL Java_org_godotengine_godot_GodotLib_getEditorSetting(JNIEnv *env, jclass clazz, jstring p_setting_key) {
  363. String editor_setting = "";
  364. #ifdef TOOLS_ENABLED
  365. String godot_setting_key = jstring_to_string(p_setting_key, env);
  366. editor_setting = EDITOR_GET(godot_setting_key).operator String();
  367. #else
  368. WARN_PRINT("Access to the Editor Settings in only available on Editor builds");
  369. #endif
  370. return env->NewStringUTF(editor_setting.utf8().get_data());
  371. }
  372. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_callobject(JNIEnv *env, jclass clazz, jlong ID, jstring method, jobjectArray params) {
  373. Object *obj = ObjectDB::get_instance(ObjectID(ID));
  374. ERR_FAIL_NULL(obj);
  375. String str_method = jstring_to_string(method, env);
  376. int count = env->GetArrayLength(params);
  377. Variant *vlist = (Variant *)alloca(sizeof(Variant) * count);
  378. const Variant **vptr = (const Variant **)alloca(sizeof(Variant *) * count);
  379. for (int i = 0; i < count; i++) {
  380. jobject jobj = env->GetObjectArrayElement(params, i);
  381. ERR_FAIL_NULL(jobj);
  382. memnew_placement(&vlist[i], Variant(_jobject_to_variant(env, jobj)));
  383. vptr[i] = &vlist[i];
  384. env->DeleteLocalRef(jobj);
  385. }
  386. Callable::CallError err;
  387. obj->callp(str_method, vptr, count, err);
  388. }
  389. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_calldeferred(JNIEnv *env, jclass clazz, jlong ID, jstring method, jobjectArray params) {
  390. Object *obj = ObjectDB::get_instance(ObjectID(ID));
  391. ERR_FAIL_NULL(obj);
  392. String str_method = jstring_to_string(method, env);
  393. int count = env->GetArrayLength(params);
  394. Variant *args = (Variant *)alloca(sizeof(Variant) * count);
  395. const Variant **argptrs = (const Variant **)alloca(sizeof(Variant *) * count);
  396. for (int i = 0; i < count; i++) {
  397. jobject jobj = env->GetObjectArrayElement(params, i);
  398. ERR_FAIL_NULL(jobj);
  399. memnew_placement(&args[i], Variant(_jobject_to_variant(env, jobj)));
  400. argptrs[i] = &args[i];
  401. env->DeleteLocalRef(jobj);
  402. }
  403. MessageQueue::get_singleton()->push_callp(obj, str_method, argptrs, count);
  404. }
  405. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_requestPermissionResult(JNIEnv *env, jclass clazz, jstring p_permission, jboolean p_result) {
  406. String permission = jstring_to_string(p_permission, env);
  407. if (permission == "android.permission.RECORD_AUDIO" && p_result) {
  408. AudioDriver::get_singleton()->input_start();
  409. }
  410. if (os_android->get_main_loop()) {
  411. os_android->get_main_loop()->emit_signal(SNAME("on_request_permissions_result"), permission, p_result == JNI_TRUE);
  412. }
  413. }
  414. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_onRendererResumed(JNIEnv *env, jclass clazz) {
  415. if (step.get() <= 0) {
  416. return;
  417. }
  418. // We force redraw to ensure we render at least once when resuming the app.
  419. Main::force_redraw();
  420. if (os_android->get_main_loop()) {
  421. os_android->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_RESUMED);
  422. }
  423. }
  424. JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_onRendererPaused(JNIEnv *env, jclass clazz) {
  425. if (step.get() <= 0) {
  426. return;
  427. }
  428. if (os_android->get_main_loop()) {
  429. os_android->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_PAUSED);
  430. }
  431. }
  432. }