mobile_vr_interface.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /**************************************************************************/
  2. /* mobile_vr_interface.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 "mobile_vr_interface.h"
  31. #include "core/input/input.h"
  32. #include "core/os/os.h"
  33. #include "servers/display_server.h"
  34. #include "servers/rendering/rendering_server_globals.h"
  35. StringName MobileVRInterface::get_name() const {
  36. return "Native mobile";
  37. };
  38. uint32_t MobileVRInterface::get_capabilities() const {
  39. return XRInterface::XR_STEREO;
  40. };
  41. Vector3 MobileVRInterface::scale_magneto(const Vector3 &p_magnetometer) {
  42. // Our magnetometer doesn't give us nice clean data.
  43. // Well it may on macOS because we're getting a calibrated value in the current implementation but Android we're getting raw data.
  44. // This is a fairly simple adjustment we can do to correct for the magnetometer data being elliptical
  45. Vector3 mag_raw = p_magnetometer;
  46. Vector3 mag_scaled = p_magnetometer;
  47. // update our variables every x frames
  48. if (mag_count > 20) {
  49. mag_current_min = mag_next_min;
  50. mag_current_max = mag_next_max;
  51. mag_count = 0;
  52. } else {
  53. mag_count++;
  54. };
  55. // adjust our min and max
  56. if (mag_raw.x > mag_next_max.x) {
  57. mag_next_max.x = mag_raw.x;
  58. }
  59. if (mag_raw.y > mag_next_max.y) {
  60. mag_next_max.y = mag_raw.y;
  61. }
  62. if (mag_raw.z > mag_next_max.z) {
  63. mag_next_max.z = mag_raw.z;
  64. }
  65. if (mag_raw.x < mag_next_min.x) {
  66. mag_next_min.x = mag_raw.x;
  67. }
  68. if (mag_raw.y < mag_next_min.y) {
  69. mag_next_min.y = mag_raw.y;
  70. }
  71. if (mag_raw.z < mag_next_min.z) {
  72. mag_next_min.z = mag_raw.z;
  73. }
  74. // scale our x, y and z
  75. if (!(mag_current_max.x - mag_current_min.x)) {
  76. mag_raw.x -= (mag_current_min.x + mag_current_max.x) / 2.0;
  77. mag_scaled.x = (mag_raw.x - mag_current_min.x) / ((mag_current_max.x - mag_current_min.x) * 2.0 - 1.0);
  78. };
  79. if (!(mag_current_max.y - mag_current_min.y)) {
  80. mag_raw.y -= (mag_current_min.y + mag_current_max.y) / 2.0;
  81. mag_scaled.y = (mag_raw.y - mag_current_min.y) / ((mag_current_max.y - mag_current_min.y) * 2.0 - 1.0);
  82. };
  83. if (!(mag_current_max.z - mag_current_min.z)) {
  84. mag_raw.z -= (mag_current_min.z + mag_current_max.z) / 2.0;
  85. mag_scaled.z = (mag_raw.z - mag_current_min.z) / ((mag_current_max.z - mag_current_min.z) * 2.0 - 1.0);
  86. };
  87. return mag_scaled;
  88. };
  89. Basis MobileVRInterface::combine_acc_mag(const Vector3 &p_grav, const Vector3 &p_magneto) {
  90. // yup, stock standard cross product solution...
  91. Vector3 up = -p_grav.normalized();
  92. Vector3 magneto_east = up.cross(p_magneto.normalized()); // or is this west?, but should be horizon aligned now
  93. magneto_east.normalize();
  94. Vector3 magneto = up.cross(magneto_east); // and now we have a horizon aligned north
  95. magneto.normalize();
  96. // We use our gravity and magnetometer vectors to construct our matrix
  97. Basis acc_mag_m3;
  98. acc_mag_m3.rows[0] = -magneto_east;
  99. acc_mag_m3.rows[1] = up;
  100. acc_mag_m3.rows[2] = magneto;
  101. return acc_mag_m3;
  102. };
  103. void MobileVRInterface::set_position_from_sensors() {
  104. _THREAD_SAFE_METHOD_
  105. // this is a helper function that attempts to adjust our transform using our 9dof sensors
  106. // 9dof is a misleading marketing term coming from 3 accelerometer axis + 3 gyro axis + 3 magnetometer axis = 9 axis
  107. // but in reality this only offers 3 dof (yaw, pitch, roll) orientation
  108. Basis orientation;
  109. uint64_t ticks = OS::get_singleton()->get_ticks_usec();
  110. uint64_t ticks_elapsed = ticks - last_ticks;
  111. float delta_time = (double)ticks_elapsed / 1000000.0;
  112. // few things we need
  113. Input *input = Input::get_singleton();
  114. Vector3 down(0.0, -1.0, 0.0); // Down is Y negative
  115. Vector3 north(0.0, 0.0, 1.0); // North is Z positive
  116. // make copies of our inputs
  117. bool has_grav = false;
  118. Vector3 acc = input->get_accelerometer();
  119. Vector3 gyro = input->get_gyroscope();
  120. Vector3 grav = input->get_gravity();
  121. Vector3 magneto = scale_magneto(input->get_magnetometer()); // this may be overkill on iOS because we're already getting a calibrated magnetometer reading
  122. if (sensor_first) {
  123. sensor_first = false;
  124. } else {
  125. acc = scrub(acc, last_accerometer_data, 2, 0.2);
  126. magneto = scrub(magneto, last_magnetometer_data, 3, 0.3);
  127. };
  128. last_accerometer_data = acc;
  129. last_magnetometer_data = magneto;
  130. if (grav.length() < 0.1) {
  131. // not ideal but use our accelerometer, this will contain shaky user behavior
  132. // maybe look into some math but I'm guessing that if this isn't available, it's because we lack the gyro sensor to actually work out
  133. // what a stable gravity vector is
  134. grav = acc;
  135. if (grav.length() > 0.1) {
  136. has_grav = true;
  137. };
  138. } else {
  139. has_grav = true;
  140. };
  141. bool has_magneto = magneto.length() > 0.1;
  142. if (gyro.length() > 0.1) {
  143. /* this can return to 0.0 if the user doesn't move the phone, so once on, it's on */
  144. has_gyro = true;
  145. };
  146. if (has_gyro) {
  147. // start with applying our gyro (do NOT smooth our gyro!)
  148. Basis rotate;
  149. rotate.rotate(orientation.get_column(0), gyro.x * delta_time);
  150. rotate.rotate(orientation.get_column(1), gyro.y * delta_time);
  151. rotate.rotate(orientation.get_column(2), gyro.z * delta_time);
  152. orientation = rotate * orientation;
  153. tracking_state = XRInterface::XR_NORMAL_TRACKING;
  154. tracking_confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
  155. };
  156. ///@TODO improve this, the magnetometer is very fidgety sometimes flipping the axis for no apparent reason (probably a bug on my part)
  157. // if you have a gyro + accelerometer that combo tends to be better than combining all three but without a gyro you need the magnetometer..
  158. if (has_magneto && has_grav && !has_gyro) {
  159. // convert to quaternions, easier to smooth those out
  160. Quaternion transform_quat(orientation);
  161. Quaternion acc_mag_quat(combine_acc_mag(grav, magneto));
  162. transform_quat = transform_quat.slerp(acc_mag_quat, 0.1);
  163. orientation = Basis(transform_quat);
  164. tracking_state = XRInterface::XR_NORMAL_TRACKING;
  165. tracking_confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
  166. } else if (has_grav) {
  167. // use gravity vector to make sure down is down...
  168. // transform gravity into our world space
  169. grav.normalize();
  170. Vector3 grav_adj = orientation.xform(grav);
  171. float dot = grav_adj.dot(down);
  172. if ((dot > -1.0) && (dot < 1.0)) {
  173. // axis around which we have this rotation
  174. Vector3 axis = grav_adj.cross(down);
  175. axis.normalize();
  176. Basis drift_compensation(axis, acos(dot) * delta_time * 10);
  177. orientation = drift_compensation * orientation;
  178. };
  179. };
  180. // and copy to our head transform
  181. head_transform.basis = orientation.orthonormalized();
  182. last_ticks = ticks;
  183. };
  184. void MobileVRInterface::_bind_methods() {
  185. ClassDB::bind_method(D_METHOD("set_eye_height", "eye_height"), &MobileVRInterface::set_eye_height);
  186. ClassDB::bind_method(D_METHOD("get_eye_height"), &MobileVRInterface::get_eye_height);
  187. ClassDB::bind_method(D_METHOD("set_iod", "iod"), &MobileVRInterface::set_iod);
  188. ClassDB::bind_method(D_METHOD("get_iod"), &MobileVRInterface::get_iod);
  189. ClassDB::bind_method(D_METHOD("set_display_width", "display_width"), &MobileVRInterface::set_display_width);
  190. ClassDB::bind_method(D_METHOD("get_display_width"), &MobileVRInterface::get_display_width);
  191. ClassDB::bind_method(D_METHOD("set_display_to_lens", "display_to_lens"), &MobileVRInterface::set_display_to_lens);
  192. ClassDB::bind_method(D_METHOD("get_display_to_lens"), &MobileVRInterface::get_display_to_lens);
  193. ClassDB::bind_method(D_METHOD("set_oversample", "oversample"), &MobileVRInterface::set_oversample);
  194. ClassDB::bind_method(D_METHOD("get_oversample"), &MobileVRInterface::get_oversample);
  195. ClassDB::bind_method(D_METHOD("set_k1", "k"), &MobileVRInterface::set_k1);
  196. ClassDB::bind_method(D_METHOD("get_k1"), &MobileVRInterface::get_k1);
  197. ClassDB::bind_method(D_METHOD("set_k2", "k"), &MobileVRInterface::set_k2);
  198. ClassDB::bind_method(D_METHOD("get_k2"), &MobileVRInterface::get_k2);
  199. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "eye_height", PROPERTY_HINT_RANGE, "0.0,3.0,0.1"), "set_eye_height", "get_eye_height");
  200. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "iod", PROPERTY_HINT_RANGE, "4.0,10.0,0.1"), "set_iod", "get_iod");
  201. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "display_width", PROPERTY_HINT_RANGE, "5.0,25.0,0.1"), "set_display_width", "get_display_width");
  202. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "display_to_lens", PROPERTY_HINT_RANGE, "5.0,25.0,0.1"), "set_display_to_lens", "get_display_to_lens");
  203. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "oversample", PROPERTY_HINT_RANGE, "1.0,2.0,0.1"), "set_oversample", "get_oversample");
  204. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "k1", PROPERTY_HINT_RANGE, "0.1,10.0,0.0001"), "set_k1", "get_k1");
  205. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "k2", PROPERTY_HINT_RANGE, "0.1,10.0,0.0001"), "set_k2", "get_k2");
  206. }
  207. void MobileVRInterface::set_eye_height(const double p_eye_height) {
  208. eye_height = p_eye_height;
  209. }
  210. double MobileVRInterface::get_eye_height() const {
  211. return eye_height;
  212. }
  213. void MobileVRInterface::set_iod(const double p_iod) {
  214. intraocular_dist = p_iod;
  215. };
  216. double MobileVRInterface::get_iod() const {
  217. return intraocular_dist;
  218. };
  219. void MobileVRInterface::set_display_width(const double p_display_width) {
  220. display_width = p_display_width;
  221. };
  222. double MobileVRInterface::get_display_width() const {
  223. return display_width;
  224. };
  225. void MobileVRInterface::set_display_to_lens(const double p_display_to_lens) {
  226. display_to_lens = p_display_to_lens;
  227. };
  228. double MobileVRInterface::get_display_to_lens() const {
  229. return display_to_lens;
  230. };
  231. void MobileVRInterface::set_oversample(const double p_oversample) {
  232. oversample = p_oversample;
  233. };
  234. double MobileVRInterface::get_oversample() const {
  235. return oversample;
  236. };
  237. void MobileVRInterface::set_k1(const double p_k1) {
  238. k1 = p_k1;
  239. };
  240. double MobileVRInterface::get_k1() const {
  241. return k1;
  242. };
  243. void MobileVRInterface::set_k2(const double p_k2) {
  244. k2 = p_k2;
  245. };
  246. double MobileVRInterface::get_k2() const {
  247. return k2;
  248. };
  249. uint32_t MobileVRInterface::get_view_count() {
  250. // needs stereo...
  251. return 2;
  252. };
  253. XRInterface::TrackingStatus MobileVRInterface::get_tracking_status() const {
  254. return tracking_state;
  255. }
  256. bool MobileVRInterface::is_initialized() const {
  257. return (initialized);
  258. };
  259. bool MobileVRInterface::initialize() {
  260. XRServer *xr_server = XRServer::get_singleton();
  261. ERR_FAIL_NULL_V(xr_server, false);
  262. if (!initialized) {
  263. // reset our sensor data
  264. mag_count = 0;
  265. has_gyro = false;
  266. sensor_first = true;
  267. mag_next_min = Vector3(10000, 10000, 10000);
  268. mag_next_max = Vector3(-10000, -10000, -10000);
  269. mag_current_min = Vector3(0, 0, 0);
  270. mag_current_max = Vector3(0, 0, 0);
  271. head_transform.basis = Basis();
  272. head_transform.origin = Vector3(0.0, eye_height, 0.0);
  273. // we must create a tracker for our head
  274. head.instantiate();
  275. head->set_tracker_type(XRServer::TRACKER_HEAD);
  276. head->set_tracker_name("head");
  277. head->set_tracker_desc("Players head");
  278. xr_server->add_tracker(head);
  279. // make this our primary interface
  280. xr_server->set_primary_interface(this);
  281. last_ticks = OS::get_singleton()->get_ticks_usec();
  282. initialized = true;
  283. };
  284. return true;
  285. };
  286. void MobileVRInterface::uninitialize() {
  287. if (initialized) {
  288. // do any cleanup here...
  289. XRServer *xr_server = XRServer::get_singleton();
  290. if (xr_server != nullptr) {
  291. if (head.is_valid()) {
  292. xr_server->remove_tracker(head);
  293. head.unref();
  294. }
  295. if (xr_server->get_primary_interface() == this) {
  296. // no longer our primary interface
  297. xr_server->set_primary_interface(nullptr);
  298. }
  299. }
  300. initialized = false;
  301. };
  302. };
  303. bool MobileVRInterface::supports_play_area_mode(XRInterface::PlayAreaMode p_mode) {
  304. // This interface has no positional tracking so fix this to 3DOF
  305. return p_mode == XR_PLAY_AREA_3DOF;
  306. }
  307. XRInterface::PlayAreaMode MobileVRInterface::get_play_area_mode() const {
  308. return XR_PLAY_AREA_3DOF;
  309. }
  310. bool MobileVRInterface::set_play_area_mode(XRInterface::PlayAreaMode p_mode) {
  311. return p_mode == XR_PLAY_AREA_3DOF;
  312. }
  313. Size2 MobileVRInterface::get_render_target_size() {
  314. _THREAD_SAFE_METHOD_
  315. // we use half our window size
  316. Size2 target_size = DisplayServer::get_singleton()->window_get_size();
  317. target_size.x *= 0.5 * oversample;
  318. target_size.y *= oversample;
  319. return target_size;
  320. };
  321. Transform3D MobileVRInterface::get_camera_transform() {
  322. _THREAD_SAFE_METHOD_
  323. Transform3D transform_for_eye;
  324. XRServer *xr_server = XRServer::get_singleton();
  325. ERR_FAIL_NULL_V(xr_server, transform_for_eye);
  326. if (initialized) {
  327. float world_scale = xr_server->get_world_scale();
  328. // just scale our origin point of our transform
  329. Transform3D _head_transform = head_transform;
  330. _head_transform.origin *= world_scale;
  331. transform_for_eye = (xr_server->get_reference_frame()) * _head_transform;
  332. }
  333. return transform_for_eye;
  334. };
  335. Transform3D MobileVRInterface::get_transform_for_view(uint32_t p_view, const Transform3D &p_cam_transform) {
  336. _THREAD_SAFE_METHOD_
  337. Transform3D transform_for_eye;
  338. XRServer *xr_server = XRServer::get_singleton();
  339. ERR_FAIL_NULL_V(xr_server, transform_for_eye);
  340. if (initialized) {
  341. float world_scale = xr_server->get_world_scale();
  342. // we don't need to check for the existence of our HMD, doesn't affect our values...
  343. // note * 0.01 to convert cm to m and * 0.5 as we're moving half in each direction...
  344. if (p_view == 0) {
  345. transform_for_eye.origin.x = -(intraocular_dist * 0.01 * 0.5 * world_scale);
  346. } else if (p_view == 1) {
  347. transform_for_eye.origin.x = intraocular_dist * 0.01 * 0.5 * world_scale;
  348. } else {
  349. // should not have any other values..
  350. };
  351. // just scale our origin point of our transform
  352. Transform3D _head_transform = head_transform;
  353. _head_transform.origin *= world_scale;
  354. transform_for_eye = p_cam_transform * (xr_server->get_reference_frame()) * _head_transform * transform_for_eye;
  355. } else {
  356. // huh? well just return what we got....
  357. transform_for_eye = p_cam_transform;
  358. };
  359. return transform_for_eye;
  360. };
  361. Projection MobileVRInterface::get_projection_for_view(uint32_t p_view, double p_aspect, double p_z_near, double p_z_far) {
  362. _THREAD_SAFE_METHOD_
  363. Projection eye;
  364. aspect = p_aspect;
  365. eye.set_for_hmd(p_view + 1, p_aspect, intraocular_dist, display_width, display_to_lens, oversample, p_z_near, p_z_far);
  366. return eye;
  367. };
  368. Vector<BlitToScreen> MobileVRInterface::post_draw_viewport(RID p_render_target, const Rect2 &p_screen_rect) {
  369. _THREAD_SAFE_METHOD_
  370. Vector<BlitToScreen> blit_to_screen;
  371. // We must have a valid render target
  372. ERR_FAIL_COND_V(!p_render_target.is_valid(), blit_to_screen);
  373. // Because we are rendering to our device we must use our main viewport!
  374. ERR_FAIL_COND_V(p_screen_rect == Rect2(), blit_to_screen);
  375. // and add our blits
  376. BlitToScreen blit;
  377. blit.render_target = p_render_target;
  378. blit.multi_view.use_layer = true;
  379. blit.lens_distortion.apply = true;
  380. blit.lens_distortion.k1 = k1;
  381. blit.lens_distortion.k2 = k2;
  382. blit.lens_distortion.upscale = oversample;
  383. blit.lens_distortion.aspect_ratio = aspect;
  384. // left eye
  385. blit.dst_rect = p_screen_rect;
  386. blit.dst_rect.size.width *= 0.5;
  387. blit.multi_view.layer = 0;
  388. blit.lens_distortion.eye_center.x = ((-intraocular_dist / 2.0) + (display_width / 4.0)) / (display_width / 2.0);
  389. blit_to_screen.push_back(blit);
  390. // right eye
  391. blit.dst_rect = p_screen_rect;
  392. blit.dst_rect.size.width *= 0.5;
  393. blit.dst_rect.position.x = blit.dst_rect.size.width;
  394. blit.multi_view.layer = 1;
  395. blit.lens_distortion.eye_center.x = ((intraocular_dist / 2.0) - (display_width / 4.0)) / (display_width / 2.0);
  396. blit_to_screen.push_back(blit);
  397. return blit_to_screen;
  398. }
  399. void MobileVRInterface::process() {
  400. _THREAD_SAFE_METHOD_
  401. if (initialized) {
  402. // update our head transform orientation
  403. set_position_from_sensors();
  404. // update our head transform position (should be constant)
  405. head_transform.origin = Vector3(0.0, eye_height, 0.0);
  406. if (head.is_valid()) {
  407. // Set our head position, note in real space, reference frame and world scale is applied later
  408. head->set_pose("default", head_transform, Vector3(), Vector3(), tracking_confidence);
  409. }
  410. };
  411. };
  412. MobileVRInterface::MobileVRInterface() {}
  413. MobileVRInterface::~MobileVRInterface() {
  414. // and make sure we cleanup if we haven't already
  415. if (is_initialized()) {
  416. uninitialize();
  417. };
  418. };