jolt_body_3d.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  1. /**************************************************************************/
  2. /* jolt_body_3d.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 "jolt_body_3d.h"
  31. #include "../joints/jolt_joint_3d.h"
  32. #include "../jolt_project_settings.h"
  33. #include "../misc/jolt_type_conversions.h"
  34. #include "../shapes/jolt_shape_3d.h"
  35. #include "../spaces/jolt_broad_phase_layer.h"
  36. #include "../spaces/jolt_space_3d.h"
  37. #include "jolt_area_3d.h"
  38. #include "jolt_group_filter.h"
  39. #include "jolt_physics_direct_body_state_3d.h"
  40. #include "jolt_soft_body_3d.h"
  41. namespace {
  42. template <typename TValue, typename TGetter>
  43. bool integrate(TValue &p_value, PhysicsServer3D::AreaSpaceOverrideMode p_mode, TGetter &&p_getter) {
  44. switch (p_mode) {
  45. case PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED: {
  46. return false;
  47. }
  48. case PhysicsServer3D::AREA_SPACE_OVERRIDE_COMBINE: {
  49. p_value += p_getter();
  50. return false;
  51. }
  52. case PhysicsServer3D::AREA_SPACE_OVERRIDE_COMBINE_REPLACE: {
  53. p_value += p_getter();
  54. return true;
  55. }
  56. case PhysicsServer3D::AREA_SPACE_OVERRIDE_REPLACE: {
  57. p_value = p_getter();
  58. return true;
  59. }
  60. case PhysicsServer3D::AREA_SPACE_OVERRIDE_REPLACE_COMBINE: {
  61. p_value = p_getter();
  62. return false;
  63. }
  64. default: {
  65. ERR_FAIL_V_MSG(false, vformat("Unhandled override mode: '%d'. This should not happen. Please report this.", p_mode));
  66. }
  67. }
  68. }
  69. } // namespace
  70. JPH::BroadPhaseLayer JoltBody3D::_get_broad_phase_layer() const {
  71. switch (mode) {
  72. case PhysicsServer3D::BODY_MODE_STATIC: {
  73. return _is_big() ? JoltBroadPhaseLayer::BODY_STATIC_BIG : JoltBroadPhaseLayer::BODY_STATIC;
  74. }
  75. case PhysicsServer3D::BODY_MODE_KINEMATIC:
  76. case PhysicsServer3D::BODY_MODE_RIGID:
  77. case PhysicsServer3D::BODY_MODE_RIGID_LINEAR: {
  78. return JoltBroadPhaseLayer::BODY_DYNAMIC;
  79. }
  80. default: {
  81. ERR_FAIL_V_MSG(JoltBroadPhaseLayer::BODY_STATIC, vformat("Unhandled body mode: '%d'. This should not happen. Please report this.", mode));
  82. }
  83. }
  84. }
  85. JPH::ObjectLayer JoltBody3D::_get_object_layer() const {
  86. ERR_FAIL_NULL_V(space, 0);
  87. return space->map_to_object_layer(_get_broad_phase_layer(), collision_layer, collision_mask);
  88. }
  89. JPH::EMotionType JoltBody3D::_get_motion_type() const {
  90. switch (mode) {
  91. case PhysicsServer3D::BODY_MODE_STATIC: {
  92. return JPH::EMotionType::Static;
  93. }
  94. case PhysicsServer3D::BODY_MODE_KINEMATIC: {
  95. return JPH::EMotionType::Kinematic;
  96. }
  97. case PhysicsServer3D::BODY_MODE_RIGID:
  98. case PhysicsServer3D::BODY_MODE_RIGID_LINEAR: {
  99. return JPH::EMotionType::Dynamic;
  100. }
  101. default: {
  102. ERR_FAIL_V_MSG(JPH::EMotionType::Static, vformat("Unhandled body mode: '%d'. This should not happen. Please report this.", mode));
  103. }
  104. }
  105. }
  106. void JoltBody3D::_add_to_space() {
  107. jolt_shape = build_shape();
  108. JPH::CollisionGroup::GroupID group_id = 0;
  109. JPH::CollisionGroup::SubGroupID sub_group_id = 0;
  110. JoltGroupFilter::encode_object(this, group_id, sub_group_id);
  111. jolt_settings->mUserData = reinterpret_cast<JPH::uint64>(this);
  112. jolt_settings->mObjectLayer = _get_object_layer();
  113. jolt_settings->mCollisionGroup = JPH::CollisionGroup(nullptr, group_id, sub_group_id);
  114. jolt_settings->mMotionType = _get_motion_type();
  115. jolt_settings->mAllowedDOFs = _calculate_allowed_dofs();
  116. jolt_settings->mAllowDynamicOrKinematic = true;
  117. jolt_settings->mCollideKinematicVsNonDynamic = reports_all_kinematic_contacts();
  118. jolt_settings->mUseManifoldReduction = !reports_contacts();
  119. jolt_settings->mLinearDamping = 0.0f;
  120. jolt_settings->mAngularDamping = 0.0f;
  121. jolt_settings->mMaxLinearVelocity = JoltProjectSettings::get_max_linear_velocity();
  122. jolt_settings->mMaxAngularVelocity = JoltProjectSettings::get_max_angular_velocity();
  123. if (JoltProjectSettings::use_enhanced_internal_edge_removal_for_bodies()) {
  124. jolt_settings->mEnhancedInternalEdgeRemoval = true;
  125. }
  126. jolt_settings->mOverrideMassProperties = JPH::EOverrideMassProperties::MassAndInertiaProvided;
  127. jolt_settings->mMassPropertiesOverride = _calculate_mass_properties();
  128. jolt_settings->SetShape(jolt_shape);
  129. const JPH::BodyID new_jolt_id = space->add_rigid_body(*this, *jolt_settings, sleep_initially);
  130. if (new_jolt_id.IsInvalid()) {
  131. return;
  132. }
  133. jolt_id = new_jolt_id;
  134. delete jolt_settings;
  135. jolt_settings = nullptr;
  136. }
  137. void JoltBody3D::_integrate_forces(float p_step, JPH::Body &p_jolt_body) {
  138. if (!p_jolt_body.IsActive()) {
  139. return;
  140. }
  141. _update_gravity(p_jolt_body);
  142. if (!custom_integrator) {
  143. JPH::MotionProperties &motion_properties = *p_jolt_body.GetMotionPropertiesUnchecked();
  144. JPH::Vec3 linear_velocity = motion_properties.GetLinearVelocity();
  145. JPH::Vec3 angular_velocity = motion_properties.GetAngularVelocity();
  146. // Jolt applies damping differently from Godot Physics, where Godot Physics applies damping before integrating
  147. // forces whereas Jolt does it after integrating forces. The way Godot Physics does it seems to yield more
  148. // consistent results across different update frequencies when using high (>1) damping values, so we apply the
  149. // damping ourselves instead, before any force integration happens.
  150. linear_velocity *= MAX(1.0f - total_linear_damp * p_step, 0.0f);
  151. angular_velocity *= MAX(1.0f - total_angular_damp * p_step, 0.0f);
  152. linear_velocity += to_jolt(gravity) * p_step;
  153. motion_properties.SetLinearVelocityClamped(linear_velocity);
  154. motion_properties.SetAngularVelocityClamped(angular_velocity);
  155. p_jolt_body.AddForce(to_jolt(constant_force));
  156. p_jolt_body.AddTorque(to_jolt(constant_torque));
  157. }
  158. sync_state = true;
  159. }
  160. void JoltBody3D::_move_kinematic(float p_step, JPH::Body &p_jolt_body) {
  161. p_jolt_body.SetLinearVelocity(JPH::Vec3::sZero());
  162. p_jolt_body.SetAngularVelocity(JPH::Vec3::sZero());
  163. const JPH::RVec3 current_position = p_jolt_body.GetPosition();
  164. const JPH::Quat current_rotation = p_jolt_body.GetRotation();
  165. const JPH::RVec3 new_position = to_jolt_r(kinematic_transform.origin);
  166. const JPH::Quat new_rotation = to_jolt(kinematic_transform.basis);
  167. if (new_position == current_position && new_rotation == current_rotation) {
  168. return;
  169. }
  170. p_jolt_body.MoveKinematic(new_position, new_rotation, p_step);
  171. sync_state = true;
  172. }
  173. void JoltBody3D::_pre_step_static(float p_step, JPH::Body &p_jolt_body) {
  174. // Nothing to do.
  175. }
  176. void JoltBody3D::_pre_step_rigid(float p_step, JPH::Body &p_jolt_body) {
  177. _integrate_forces(p_step, p_jolt_body);
  178. }
  179. void JoltBody3D::_pre_step_kinematic(float p_step, JPH::Body &p_jolt_body) {
  180. _update_gravity(p_jolt_body);
  181. _move_kinematic(p_step, p_jolt_body);
  182. if (reports_contacts()) {
  183. // This seems to emulate the behavior of Godot Physics, where kinematic bodies are set as active (and thereby
  184. // have their state synchronized on every step) only if its max reported contacts is non-zero.
  185. sync_state = true;
  186. }
  187. }
  188. JPH::EAllowedDOFs JoltBody3D::_calculate_allowed_dofs() const {
  189. if (is_static()) {
  190. return JPH::EAllowedDOFs::All;
  191. }
  192. JPH::EAllowedDOFs allowed_dofs = JPH::EAllowedDOFs::All;
  193. if (is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_X)) {
  194. allowed_dofs &= ~JPH::EAllowedDOFs::TranslationX;
  195. }
  196. if (is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_Y)) {
  197. allowed_dofs &= ~JPH::EAllowedDOFs::TranslationY;
  198. }
  199. if (is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_Z)) {
  200. allowed_dofs &= ~JPH::EAllowedDOFs::TranslationZ;
  201. }
  202. if (is_axis_locked(PhysicsServer3D::BODY_AXIS_ANGULAR_X) || is_rigid_linear()) {
  203. allowed_dofs &= ~JPH::EAllowedDOFs::RotationX;
  204. }
  205. if (is_axis_locked(PhysicsServer3D::BODY_AXIS_ANGULAR_Y) || is_rigid_linear()) {
  206. allowed_dofs &= ~JPH::EAllowedDOFs::RotationY;
  207. }
  208. if (is_axis_locked(PhysicsServer3D::BODY_AXIS_ANGULAR_Z) || is_rigid_linear()) {
  209. allowed_dofs &= ~JPH::EAllowedDOFs::RotationZ;
  210. }
  211. ERR_FAIL_COND_V_MSG(allowed_dofs == JPH::EAllowedDOFs::None, JPH::EAllowedDOFs::All, vformat("Invalid axis locks for '%s'. Locking all axes is not supported when using Jolt Physics. All axes will be unlocked. Considering freezing the body instead.", to_string()));
  212. return allowed_dofs;
  213. }
  214. JPH::MassProperties JoltBody3D::_calculate_mass_properties(const JPH::Shape &p_shape) const {
  215. const bool calculate_mass = mass <= 0;
  216. const bool calculate_inertia = inertia.x <= 0 || inertia.y <= 0 || inertia.z <= 0;
  217. JPH::MassProperties mass_properties = p_shape.GetMassProperties();
  218. if (calculate_mass && calculate_inertia) {
  219. // Use the mass properties calculated by the shape
  220. } else if (calculate_inertia) {
  221. mass_properties.ScaleToMass(mass);
  222. } else {
  223. mass_properties.mMass = mass;
  224. }
  225. if (inertia.x > 0) {
  226. mass_properties.mInertia(0, 0) = (float)inertia.x;
  227. mass_properties.mInertia(0, 1) = 0;
  228. mass_properties.mInertia(0, 2) = 0;
  229. mass_properties.mInertia(1, 0) = 0;
  230. mass_properties.mInertia(2, 0) = 0;
  231. }
  232. if (inertia.y > 0) {
  233. mass_properties.mInertia(1, 1) = (float)inertia.y;
  234. mass_properties.mInertia(1, 0) = 0;
  235. mass_properties.mInertia(1, 2) = 0;
  236. mass_properties.mInertia(0, 1) = 0;
  237. mass_properties.mInertia(2, 1) = 0;
  238. }
  239. if (inertia.z > 0) {
  240. mass_properties.mInertia(2, 2) = (float)inertia.z;
  241. mass_properties.mInertia(2, 0) = 0;
  242. mass_properties.mInertia(2, 1) = 0;
  243. mass_properties.mInertia(0, 2) = 0;
  244. mass_properties.mInertia(1, 2) = 0;
  245. }
  246. mass_properties.mInertia(3, 3) = 1.0f;
  247. return mass_properties;
  248. }
  249. JPH::MassProperties JoltBody3D::_calculate_mass_properties() const {
  250. return _calculate_mass_properties(*jolt_shape);
  251. }
  252. void JoltBody3D::_update_mass_properties() {
  253. if (!in_space()) {
  254. return;
  255. }
  256. const JoltWritableBody3D body = space->write_body(jolt_id);
  257. ERR_FAIL_COND(body.is_invalid());
  258. body->GetMotionPropertiesUnchecked()->SetMassProperties(_calculate_allowed_dofs(), _calculate_mass_properties());
  259. }
  260. void JoltBody3D::_update_gravity(JPH::Body &p_jolt_body) {
  261. gravity = Vector3();
  262. const Vector3 position = to_godot(p_jolt_body.GetPosition());
  263. bool gravity_done = false;
  264. for (const JoltArea3D *area : areas) {
  265. gravity_done = integrate(gravity, area->get_gravity_mode(), [&]() {
  266. return area->compute_gravity(position);
  267. });
  268. if (gravity_done) {
  269. break;
  270. }
  271. }
  272. if (!gravity_done) {
  273. gravity += space->get_default_area()->compute_gravity(position);
  274. }
  275. gravity *= gravity_scale;
  276. }
  277. void JoltBody3D::_update_damp() {
  278. if (!in_space()) {
  279. return;
  280. }
  281. total_linear_damp = 0.0;
  282. total_angular_damp = 0.0;
  283. bool linear_damp_done = linear_damp_mode == PhysicsServer3D::BODY_DAMP_MODE_REPLACE;
  284. bool angular_damp_done = angular_damp_mode == PhysicsServer3D::BODY_DAMP_MODE_REPLACE;
  285. for (const JoltArea3D *area : areas) {
  286. if (!linear_damp_done) {
  287. linear_damp_done = integrate(total_linear_damp, area->get_linear_damp_mode(), [&]() {
  288. return area->get_linear_damp();
  289. });
  290. }
  291. if (!angular_damp_done) {
  292. angular_damp_done = integrate(total_angular_damp, area->get_angular_damp_mode(), [&]() {
  293. return area->get_angular_damp();
  294. });
  295. }
  296. if (linear_damp_done && angular_damp_done) {
  297. break;
  298. }
  299. }
  300. const JoltArea3D *default_area = space->get_default_area();
  301. if (!linear_damp_done) {
  302. total_linear_damp += default_area->get_linear_damp();
  303. }
  304. if (!angular_damp_done) {
  305. total_angular_damp += default_area->get_angular_damp();
  306. }
  307. switch (linear_damp_mode) {
  308. case PhysicsServer3D::BODY_DAMP_MODE_COMBINE: {
  309. total_linear_damp += linear_damp;
  310. } break;
  311. case PhysicsServer3D::BODY_DAMP_MODE_REPLACE: {
  312. total_linear_damp = linear_damp;
  313. } break;
  314. }
  315. switch (angular_damp_mode) {
  316. case PhysicsServer3D::BODY_DAMP_MODE_COMBINE: {
  317. total_angular_damp += angular_damp;
  318. } break;
  319. case PhysicsServer3D::BODY_DAMP_MODE_REPLACE: {
  320. total_angular_damp = angular_damp;
  321. } break;
  322. }
  323. _motion_changed();
  324. }
  325. void JoltBody3D::_update_kinematic_transform() {
  326. if (is_kinematic()) {
  327. kinematic_transform = get_transform_unscaled();
  328. }
  329. }
  330. void JoltBody3D::_update_joint_constraints() {
  331. for (JoltJoint3D *joint : joints) {
  332. joint->rebuild();
  333. }
  334. }
  335. void JoltBody3D::_update_possible_kinematic_contacts() {
  336. const bool value = reports_all_kinematic_contacts();
  337. if (!in_space()) {
  338. jolt_settings->mCollideKinematicVsNonDynamic = value;
  339. } else {
  340. const JoltWritableBody3D body = space->write_body(jolt_id);
  341. ERR_FAIL_COND(body.is_invalid());
  342. body->SetCollideKinematicVsNonDynamic(value);
  343. }
  344. }
  345. void JoltBody3D::_destroy_joint_constraints() {
  346. for (JoltJoint3D *joint : joints) {
  347. joint->destroy();
  348. }
  349. }
  350. void JoltBody3D::_exit_all_areas() {
  351. for (JoltArea3D *area : areas) {
  352. area->body_exited(jolt_id, false);
  353. }
  354. areas.clear();
  355. }
  356. void JoltBody3D::_update_group_filter() {
  357. JPH::GroupFilter *group_filter = !exceptions.is_empty() ? JoltGroupFilter::instance : nullptr;
  358. if (!in_space()) {
  359. jolt_settings->mCollisionGroup.SetGroupFilter(group_filter);
  360. return;
  361. }
  362. const JoltWritableBody3D body = space->write_body(jolt_id);
  363. ERR_FAIL_COND(body.is_invalid());
  364. body->GetCollisionGroup().SetGroupFilter(group_filter);
  365. }
  366. void JoltBody3D::_mode_changed() {
  367. _update_object_layer();
  368. _update_kinematic_transform();
  369. _update_mass_properties();
  370. wake_up();
  371. }
  372. void JoltBody3D::_shapes_built() {
  373. JoltShapedObject3D::_shapes_built();
  374. _update_mass_properties();
  375. _update_joint_constraints();
  376. wake_up();
  377. }
  378. void JoltBody3D::_space_changing() {
  379. JoltShapedObject3D::_space_changing();
  380. sleep_initially = is_sleeping();
  381. _destroy_joint_constraints();
  382. _exit_all_areas();
  383. }
  384. void JoltBody3D::_space_changed() {
  385. JoltShapedObject3D::_space_changed();
  386. _update_kinematic_transform();
  387. _update_group_filter();
  388. _update_joint_constraints();
  389. _areas_changed();
  390. sync_state = false;
  391. }
  392. void JoltBody3D::_areas_changed() {
  393. _update_damp();
  394. wake_up();
  395. }
  396. void JoltBody3D::_joints_changed() {
  397. wake_up();
  398. }
  399. void JoltBody3D::_transform_changed() {
  400. wake_up();
  401. }
  402. void JoltBody3D::_motion_changed() {
  403. wake_up();
  404. }
  405. void JoltBody3D::_exceptions_changed() {
  406. _update_group_filter();
  407. }
  408. void JoltBody3D::_axis_lock_changed() {
  409. _update_mass_properties();
  410. wake_up();
  411. }
  412. void JoltBody3D::_contact_reporting_changed() {
  413. _update_possible_kinematic_contacts();
  414. wake_up();
  415. }
  416. JoltBody3D::JoltBody3D() :
  417. JoltShapedObject3D(OBJECT_TYPE_BODY) {
  418. }
  419. JoltBody3D::~JoltBody3D() {
  420. if (direct_state != nullptr) {
  421. memdelete(direct_state);
  422. direct_state = nullptr;
  423. }
  424. }
  425. void JoltBody3D::set_transform(Transform3D p_transform) {
  426. JOLT_ENSURE_SCALE_NOT_ZERO(p_transform, vformat("An invalid transform was passed to physics body '%s'.", to_string()));
  427. const Vector3 new_scale = p_transform.basis.get_scale();
  428. // Ideally we would do an exact comparison here, but due to floating-point precision this would be invalidated very often.
  429. if (!scale.is_equal_approx(new_scale)) {
  430. scale = new_scale;
  431. _shapes_changed();
  432. }
  433. p_transform.basis.orthonormalize();
  434. if (!in_space()) {
  435. jolt_settings->mPosition = to_jolt_r(p_transform.origin);
  436. jolt_settings->mRotation = to_jolt(p_transform.basis);
  437. } else if (is_kinematic()) {
  438. kinematic_transform = p_transform;
  439. } else {
  440. space->get_body_iface().SetPositionAndRotation(jolt_id, to_jolt_r(p_transform.origin), to_jolt(p_transform.basis), JPH::EActivation::DontActivate);
  441. }
  442. _transform_changed();
  443. }
  444. Variant JoltBody3D::get_state(PhysicsServer3D::BodyState p_state) const {
  445. switch (p_state) {
  446. case PhysicsServer3D::BODY_STATE_TRANSFORM: {
  447. return get_transform_scaled();
  448. }
  449. case PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY: {
  450. return get_linear_velocity();
  451. }
  452. case PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY: {
  453. return get_angular_velocity();
  454. }
  455. case PhysicsServer3D::BODY_STATE_SLEEPING: {
  456. return is_sleeping();
  457. }
  458. case PhysicsServer3D::BODY_STATE_CAN_SLEEP: {
  459. return can_sleep();
  460. }
  461. default: {
  462. ERR_FAIL_V_MSG(Variant(), vformat("Unhandled body state: '%d'. This should not happen. Please report this.", p_state));
  463. }
  464. }
  465. }
  466. void JoltBody3D::set_state(PhysicsServer3D::BodyState p_state, const Variant &p_value) {
  467. switch (p_state) {
  468. case PhysicsServer3D::BODY_STATE_TRANSFORM: {
  469. set_transform(p_value);
  470. } break;
  471. case PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY: {
  472. set_linear_velocity(p_value);
  473. } break;
  474. case PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY: {
  475. set_angular_velocity(p_value);
  476. } break;
  477. case PhysicsServer3D::BODY_STATE_SLEEPING: {
  478. set_is_sleeping(p_value);
  479. } break;
  480. case PhysicsServer3D::BODY_STATE_CAN_SLEEP: {
  481. set_can_sleep(p_value);
  482. } break;
  483. default: {
  484. ERR_FAIL_MSG(vformat("Unhandled body state: '%d'. This should not happen. Please report this.", p_state));
  485. } break;
  486. }
  487. }
  488. Variant JoltBody3D::get_param(PhysicsServer3D::BodyParameter p_param) const {
  489. switch (p_param) {
  490. case PhysicsServer3D::BODY_PARAM_BOUNCE: {
  491. return get_bounce();
  492. }
  493. case PhysicsServer3D::BODY_PARAM_FRICTION: {
  494. return get_friction();
  495. }
  496. case PhysicsServer3D::BODY_PARAM_MASS: {
  497. return get_mass();
  498. }
  499. case PhysicsServer3D::BODY_PARAM_INERTIA: {
  500. return get_inertia();
  501. }
  502. case PhysicsServer3D::BODY_PARAM_CENTER_OF_MASS: {
  503. return get_center_of_mass_custom();
  504. }
  505. case PhysicsServer3D::BODY_PARAM_GRAVITY_SCALE: {
  506. return get_gravity_scale();
  507. }
  508. case PhysicsServer3D::BODY_PARAM_LINEAR_DAMP_MODE: {
  509. return get_linear_damp_mode();
  510. }
  511. case PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP_MODE: {
  512. return get_angular_damp_mode();
  513. }
  514. case PhysicsServer3D::BODY_PARAM_LINEAR_DAMP: {
  515. return get_linear_damp();
  516. }
  517. case PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP: {
  518. return get_angular_damp();
  519. }
  520. default: {
  521. ERR_FAIL_V_MSG(Variant(), vformat("Unhandled body parameter: '%d'. This should not happen. Please report this.", p_param));
  522. }
  523. }
  524. }
  525. void JoltBody3D::set_param(PhysicsServer3D::BodyParameter p_param, const Variant &p_value) {
  526. switch (p_param) {
  527. case PhysicsServer3D::BODY_PARAM_BOUNCE: {
  528. set_bounce(p_value);
  529. } break;
  530. case PhysicsServer3D::BODY_PARAM_FRICTION: {
  531. set_friction(p_value);
  532. } break;
  533. case PhysicsServer3D::BODY_PARAM_MASS: {
  534. set_mass(p_value);
  535. } break;
  536. case PhysicsServer3D::BODY_PARAM_INERTIA: {
  537. set_inertia(p_value);
  538. } break;
  539. case PhysicsServer3D::BODY_PARAM_CENTER_OF_MASS: {
  540. set_center_of_mass_custom(p_value);
  541. } break;
  542. case PhysicsServer3D::BODY_PARAM_GRAVITY_SCALE: {
  543. set_gravity_scale(p_value);
  544. } break;
  545. case PhysicsServer3D::BODY_PARAM_LINEAR_DAMP_MODE: {
  546. set_linear_damp_mode((DampMode)(int)p_value);
  547. } break;
  548. case PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP_MODE: {
  549. set_angular_damp_mode((DampMode)(int)p_value);
  550. } break;
  551. case PhysicsServer3D::BODY_PARAM_LINEAR_DAMP: {
  552. set_linear_damp(p_value);
  553. } break;
  554. case PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP: {
  555. set_angular_damp(p_value);
  556. } break;
  557. default: {
  558. ERR_FAIL_MSG(vformat("Unhandled body parameter: '%d'. This should not happen. Please report this.", p_param));
  559. } break;
  560. }
  561. }
  562. void JoltBody3D::set_custom_integrator(bool p_enabled) {
  563. if (custom_integrator == p_enabled) {
  564. return;
  565. }
  566. custom_integrator = p_enabled;
  567. if (!in_space()) {
  568. _motion_changed();
  569. return;
  570. }
  571. const JoltWritableBody3D body = space->write_body(jolt_id);
  572. ERR_FAIL_COND(body.is_invalid());
  573. body->ResetForce();
  574. body->ResetTorque();
  575. _motion_changed();
  576. }
  577. bool JoltBody3D::is_sleeping() const {
  578. if (!in_space()) {
  579. return sleep_initially;
  580. }
  581. const JoltReadableBody3D body = space->read_body(jolt_id);
  582. ERR_FAIL_COND_V(body.is_invalid(), false);
  583. return !body->IsActive();
  584. }
  585. void JoltBody3D::set_is_sleeping(bool p_enabled) {
  586. if (!in_space()) {
  587. sleep_initially = p_enabled;
  588. return;
  589. }
  590. JPH::BodyInterface &body_iface = space->get_body_iface();
  591. if (p_enabled) {
  592. body_iface.DeactivateBody(jolt_id);
  593. } else {
  594. body_iface.ActivateBody(jolt_id);
  595. }
  596. }
  597. bool JoltBody3D::can_sleep() const {
  598. if (!in_space()) {
  599. return jolt_settings->mAllowSleeping;
  600. }
  601. const JoltReadableBody3D body = space->read_body(jolt_id);
  602. ERR_FAIL_COND_V(body.is_invalid(), false);
  603. return body->GetAllowSleeping();
  604. }
  605. void JoltBody3D::set_can_sleep(bool p_enabled) {
  606. if (!in_space()) {
  607. jolt_settings->mAllowSleeping = p_enabled;
  608. return;
  609. }
  610. const JoltWritableBody3D body = space->write_body(jolt_id);
  611. ERR_FAIL_COND(body.is_invalid());
  612. body->SetAllowSleeping(p_enabled);
  613. }
  614. Basis JoltBody3D::get_principal_inertia_axes() const {
  615. ERR_FAIL_NULL_V_MSG(space, Basis(), vformat("Failed to retrieve principal inertia axes of '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  616. if (unlikely(is_static() || is_kinematic())) {
  617. return Basis();
  618. }
  619. const JoltReadableBody3D body = space->read_body(jolt_id);
  620. ERR_FAIL_COND_V(body.is_invalid(), Basis());
  621. return to_godot(body->GetRotation() * body->GetMotionProperties()->GetInertiaRotation());
  622. }
  623. Vector3 JoltBody3D::get_inverse_inertia() const {
  624. ERR_FAIL_NULL_V_MSG(space, Vector3(), vformat("Failed to retrieve inverse inertia of '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  625. if (unlikely(is_static() || is_kinematic())) {
  626. return Vector3();
  627. }
  628. const JoltReadableBody3D body = space->read_body(jolt_id);
  629. ERR_FAIL_COND_V(body.is_invalid(), Vector3());
  630. const JPH::MotionProperties &motion_properties = *body->GetMotionPropertiesUnchecked();
  631. return to_godot(motion_properties.GetLocalSpaceInverseInertia().GetDiagonal3());
  632. }
  633. Basis JoltBody3D::get_inverse_inertia_tensor() const {
  634. ERR_FAIL_NULL_V_MSG(space, Basis(), vformat("Failed to retrieve inverse inertia tensor of '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  635. if (unlikely(is_static() || is_kinematic())) {
  636. return Basis();
  637. }
  638. const JoltReadableBody3D body = space->read_body(jolt_id);
  639. ERR_FAIL_COND_V(body.is_invalid(), Basis());
  640. return to_godot(body->GetInverseInertia()).basis;
  641. }
  642. void JoltBody3D::set_linear_velocity(const Vector3 &p_velocity) {
  643. if (is_static() || is_kinematic()) {
  644. linear_surface_velocity = p_velocity;
  645. _motion_changed();
  646. return;
  647. }
  648. if (!in_space()) {
  649. jolt_settings->mLinearVelocity = to_jolt(p_velocity);
  650. _motion_changed();
  651. return;
  652. }
  653. const JoltWritableBody3D body = space->write_body(jolt_id);
  654. ERR_FAIL_COND(body.is_invalid());
  655. body->GetMotionPropertiesUnchecked()->SetLinearVelocityClamped(to_jolt(p_velocity));
  656. _motion_changed();
  657. }
  658. void JoltBody3D::set_angular_velocity(const Vector3 &p_velocity) {
  659. if (is_static() || is_kinematic()) {
  660. angular_surface_velocity = p_velocity;
  661. _motion_changed();
  662. return;
  663. }
  664. if (!in_space()) {
  665. jolt_settings->mAngularVelocity = to_jolt(p_velocity);
  666. _motion_changed();
  667. return;
  668. }
  669. const JoltWritableBody3D body = space->write_body(jolt_id);
  670. ERR_FAIL_COND(body.is_invalid());
  671. body->GetMotionPropertiesUnchecked()->SetAngularVelocityClamped(to_jolt(p_velocity));
  672. _motion_changed();
  673. }
  674. void JoltBody3D::set_axis_velocity(const Vector3 &p_axis_velocity) {
  675. const Vector3 axis = p_axis_velocity.normalized();
  676. if (!in_space()) {
  677. Vector3 linear_velocity = to_godot(jolt_settings->mLinearVelocity);
  678. linear_velocity -= axis * axis.dot(linear_velocity);
  679. linear_velocity += p_axis_velocity;
  680. jolt_settings->mLinearVelocity = to_jolt(linear_velocity);
  681. } else {
  682. const JoltWritableBody3D body = space->write_body(jolt_id);
  683. ERR_FAIL_COND(body.is_invalid());
  684. Vector3 linear_velocity = get_linear_velocity();
  685. linear_velocity -= axis * axis.dot(linear_velocity);
  686. linear_velocity += p_axis_velocity;
  687. set_linear_velocity(linear_velocity);
  688. }
  689. _motion_changed();
  690. }
  691. Vector3 JoltBody3D::get_velocity_at_position(const Vector3 &p_position) const {
  692. if (unlikely(!in_space())) {
  693. return Vector3();
  694. }
  695. const JoltReadableBody3D body = space->read_body(jolt_id);
  696. ERR_FAIL_COND_V(body.is_invalid(), Vector3());
  697. const JPH::MotionProperties &motion_properties = *body->GetMotionPropertiesUnchecked();
  698. const Vector3 total_linear_velocity = to_godot(motion_properties.GetLinearVelocity()) + linear_surface_velocity;
  699. const Vector3 total_angular_velocity = to_godot(motion_properties.GetAngularVelocity()) + angular_surface_velocity;
  700. const Vector3 com_to_pos = p_position - to_godot(body->GetCenterOfMassPosition());
  701. return total_linear_velocity + total_angular_velocity.cross(com_to_pos);
  702. }
  703. void JoltBody3D::set_center_of_mass_custom(const Vector3 &p_center_of_mass) {
  704. if (custom_center_of_mass && p_center_of_mass == center_of_mass_custom) {
  705. return;
  706. }
  707. custom_center_of_mass = true;
  708. center_of_mass_custom = p_center_of_mass;
  709. _shapes_changed();
  710. }
  711. void JoltBody3D::set_max_contacts_reported(int p_count) {
  712. ERR_FAIL_COND(p_count < 0);
  713. if (unlikely((int)contacts.size() == p_count)) {
  714. return;
  715. }
  716. contacts.resize(p_count);
  717. contact_count = MIN(contact_count, p_count);
  718. const bool use_manifold_reduction = !reports_contacts();
  719. if (!in_space()) {
  720. jolt_settings->mUseManifoldReduction = use_manifold_reduction;
  721. _contact_reporting_changed();
  722. return;
  723. }
  724. JPH::BodyInterface &body_iface = space->get_body_iface();
  725. body_iface.SetUseManifoldReduction(jolt_id, use_manifold_reduction);
  726. _contact_reporting_changed();
  727. }
  728. bool JoltBody3D::reports_all_kinematic_contacts() const {
  729. return reports_contacts() && JoltProjectSettings::should_generate_all_kinematic_contacts();
  730. }
  731. void JoltBody3D::add_contact(const JoltBody3D *p_collider, float p_depth, int p_shape_index, int p_collider_shape_index, const Vector3 &p_normal, const Vector3 &p_position, const Vector3 &p_collider_position, const Vector3 &p_velocity, const Vector3 &p_collider_velocity, const Vector3 &p_impulse) {
  732. const int max_contacts = get_max_contacts_reported();
  733. if (max_contacts == 0) {
  734. return;
  735. }
  736. Contact *contact = nullptr;
  737. if (contact_count < max_contacts) {
  738. contact = &contacts[contact_count++];
  739. } else {
  740. Contact *shallowest_contact = &contacts[0];
  741. for (int i = 1; i < (int)contacts.size(); i++) {
  742. Contact &other_contact = contacts[i];
  743. if (other_contact.depth < shallowest_contact->depth) {
  744. shallowest_contact = &other_contact;
  745. }
  746. }
  747. if (shallowest_contact->depth < p_depth) {
  748. contact = shallowest_contact;
  749. }
  750. }
  751. if (contact != nullptr) {
  752. contact->normal = p_normal;
  753. contact->position = p_position;
  754. contact->collider_position = p_collider_position;
  755. contact->velocity = p_velocity;
  756. contact->collider_velocity = p_collider_velocity;
  757. contact->impulse = p_impulse;
  758. contact->collider_id = p_collider->get_instance_id();
  759. contact->collider_rid = p_collider->get_rid();
  760. contact->shape_index = p_shape_index;
  761. contact->collider_shape_index = p_collider_shape_index;
  762. }
  763. }
  764. void JoltBody3D::reset_mass_properties() {
  765. if (custom_center_of_mass) {
  766. custom_center_of_mass = false;
  767. center_of_mass_custom.zero();
  768. _shapes_changed();
  769. }
  770. inertia.zero();
  771. _update_mass_properties();
  772. }
  773. void JoltBody3D::apply_force(const Vector3 &p_force, const Vector3 &p_position) {
  774. ERR_FAIL_NULL_MSG(space, vformat("Failed to apply force to '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  775. if (unlikely(!is_rigid())) {
  776. return;
  777. }
  778. if (custom_integrator || p_force == Vector3()) {
  779. return;
  780. }
  781. const JoltWritableBody3D body = space->write_body(jolt_id);
  782. ERR_FAIL_COND(body.is_invalid());
  783. body->AddForce(to_jolt(p_force), body->GetPosition() + to_jolt(p_position));
  784. _motion_changed();
  785. }
  786. void JoltBody3D::apply_central_force(const Vector3 &p_force) {
  787. ERR_FAIL_NULL_MSG(space, vformat("Failed to apply central force to '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  788. if (unlikely(!is_rigid())) {
  789. return;
  790. }
  791. if (custom_integrator || p_force == Vector3()) {
  792. return;
  793. }
  794. const JoltWritableBody3D body = space->write_body(jolt_id);
  795. ERR_FAIL_COND(body.is_invalid());
  796. body->AddForce(to_jolt(p_force));
  797. _motion_changed();
  798. }
  799. void JoltBody3D::apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position) {
  800. ERR_FAIL_NULL_MSG(space, vformat("Failed to apply impulse to '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  801. if (unlikely(!is_rigid())) {
  802. return;
  803. }
  804. if (p_impulse == Vector3()) {
  805. return;
  806. }
  807. const JoltWritableBody3D body = space->write_body(jolt_id);
  808. ERR_FAIL_COND(body.is_invalid());
  809. body->AddImpulse(to_jolt(p_impulse), body->GetPosition() + to_jolt(p_position));
  810. _motion_changed();
  811. }
  812. void JoltBody3D::apply_central_impulse(const Vector3 &p_impulse) {
  813. ERR_FAIL_NULL_MSG(space, vformat("Failed to apply central impulse to '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  814. if (unlikely(!is_rigid())) {
  815. return;
  816. }
  817. if (p_impulse == Vector3()) {
  818. return;
  819. }
  820. const JoltWritableBody3D body = space->write_body(jolt_id);
  821. ERR_FAIL_COND(body.is_invalid());
  822. body->AddImpulse(to_jolt(p_impulse));
  823. _motion_changed();
  824. }
  825. void JoltBody3D::apply_torque(const Vector3 &p_torque) {
  826. ERR_FAIL_NULL_MSG(space, vformat("Failed to apply torque to '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  827. if (unlikely(!is_rigid())) {
  828. return;
  829. }
  830. if (custom_integrator || p_torque == Vector3()) {
  831. return;
  832. }
  833. const JoltWritableBody3D body = space->write_body(jolt_id);
  834. ERR_FAIL_COND(body.is_invalid());
  835. body->AddTorque(to_jolt(p_torque));
  836. _motion_changed();
  837. }
  838. void JoltBody3D::apply_torque_impulse(const Vector3 &p_impulse) {
  839. ERR_FAIL_NULL_MSG(space, vformat("Failed to apply torque impulse to '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  840. if (unlikely(!is_rigid())) {
  841. return;
  842. }
  843. if (p_impulse == Vector3()) {
  844. return;
  845. }
  846. const JoltWritableBody3D body = space->write_body(jolt_id);
  847. ERR_FAIL_COND(body.is_invalid());
  848. body->AddAngularImpulse(to_jolt(p_impulse));
  849. _motion_changed();
  850. }
  851. void JoltBody3D::add_constant_central_force(const Vector3 &p_force) {
  852. if (p_force == Vector3()) {
  853. return;
  854. }
  855. constant_force += p_force;
  856. _motion_changed();
  857. }
  858. void JoltBody3D::add_constant_force(const Vector3 &p_force, const Vector3 &p_position) {
  859. if (p_force == Vector3()) {
  860. return;
  861. }
  862. const JoltWritableBody3D body = space->write_body(jolt_id);
  863. ERR_FAIL_COND(body.is_invalid());
  864. constant_force += p_force;
  865. constant_torque += (p_position - get_center_of_mass_relative()).cross(p_force);
  866. _motion_changed();
  867. }
  868. void JoltBody3D::add_constant_torque(const Vector3 &p_torque) {
  869. if (p_torque == Vector3()) {
  870. return;
  871. }
  872. constant_torque += p_torque;
  873. _motion_changed();
  874. }
  875. Vector3 JoltBody3D::get_constant_force() const {
  876. return constant_force;
  877. }
  878. void JoltBody3D::set_constant_force(const Vector3 &p_force) {
  879. if (constant_force == p_force) {
  880. return;
  881. }
  882. constant_force = p_force;
  883. _motion_changed();
  884. }
  885. Vector3 JoltBody3D::get_constant_torque() const {
  886. return constant_torque;
  887. }
  888. void JoltBody3D::set_constant_torque(const Vector3 &p_torque) {
  889. if (constant_torque == p_torque) {
  890. return;
  891. }
  892. constant_torque = p_torque;
  893. _motion_changed();
  894. }
  895. void JoltBody3D::add_collision_exception(const RID &p_excepted_body) {
  896. exceptions.push_back(p_excepted_body);
  897. _exceptions_changed();
  898. }
  899. void JoltBody3D::remove_collision_exception(const RID &p_excepted_body) {
  900. exceptions.erase(p_excepted_body);
  901. _exceptions_changed();
  902. }
  903. bool JoltBody3D::has_collision_exception(const RID &p_excepted_body) const {
  904. return exceptions.find(p_excepted_body) >= 0;
  905. }
  906. void JoltBody3D::add_area(JoltArea3D *p_area) {
  907. int i = 0;
  908. for (; i < (int)areas.size(); i++) {
  909. if (p_area->get_priority() > areas[i]->get_priority()) {
  910. break;
  911. }
  912. }
  913. areas.insert(i, p_area);
  914. _areas_changed();
  915. }
  916. void JoltBody3D::remove_area(JoltArea3D *p_area) {
  917. areas.erase(p_area);
  918. _areas_changed();
  919. }
  920. void JoltBody3D::add_joint(JoltJoint3D *p_joint) {
  921. joints.push_back(p_joint);
  922. _joints_changed();
  923. }
  924. void JoltBody3D::remove_joint(JoltJoint3D *p_joint) {
  925. joints.erase(p_joint);
  926. _joints_changed();
  927. }
  928. void JoltBody3D::call_queries(JPH::Body &p_jolt_body) {
  929. if (!sync_state) {
  930. return;
  931. }
  932. if (custom_integration_callback.is_valid()) {
  933. const Variant direct_state_variant = get_direct_state();
  934. const Variant *args[2] = { &direct_state_variant, &custom_integration_userdata };
  935. const int argc = custom_integration_userdata.get_type() != Variant::NIL ? 2 : 1;
  936. Callable::CallError ce;
  937. Variant ret;
  938. custom_integration_callback.callp(args, argc, ret, ce);
  939. if (unlikely(ce.error != Callable::CallError::CALL_OK)) {
  940. ERR_PRINT_ONCE(vformat("Failed to call force integration callback for '%s'. It returned the following error: '%s'.", to_string(), Variant::get_callable_error_text(custom_integration_callback, args, argc, ce)));
  941. }
  942. }
  943. if (state_sync_callback.is_valid()) {
  944. const Variant direct_state_variant = get_direct_state();
  945. const Variant *args[1] = { &direct_state_variant };
  946. Callable::CallError ce;
  947. Variant ret;
  948. state_sync_callback.callp(args, 1, ret, ce);
  949. if (unlikely(ce.error != Callable::CallError::CALL_OK)) {
  950. ERR_PRINT_ONCE(vformat("Failed to call state synchronization callback for '%s'. It returned the following error: '%s'.", to_string(), Variant::get_callable_error_text(state_sync_callback, args, 1, ce)));
  951. }
  952. }
  953. sync_state = false;
  954. }
  955. void JoltBody3D::pre_step(float p_step, JPH::Body &p_jolt_body) {
  956. JoltObject3D::pre_step(p_step, p_jolt_body);
  957. switch (mode) {
  958. case PhysicsServer3D::BODY_MODE_STATIC: {
  959. _pre_step_static(p_step, p_jolt_body);
  960. } break;
  961. case PhysicsServer3D::BODY_MODE_RIGID:
  962. case PhysicsServer3D::BODY_MODE_RIGID_LINEAR: {
  963. _pre_step_rigid(p_step, p_jolt_body);
  964. } break;
  965. case PhysicsServer3D::BODY_MODE_KINEMATIC: {
  966. _pre_step_kinematic(p_step, p_jolt_body);
  967. } break;
  968. }
  969. contact_count = 0;
  970. }
  971. JoltPhysicsDirectBodyState3D *JoltBody3D::get_direct_state() {
  972. if (direct_state == nullptr) {
  973. direct_state = memnew(JoltPhysicsDirectBodyState3D(this));
  974. }
  975. return direct_state;
  976. }
  977. void JoltBody3D::set_mode(PhysicsServer3D::BodyMode p_mode) {
  978. if (p_mode == mode) {
  979. return;
  980. }
  981. mode = p_mode;
  982. if (!in_space()) {
  983. _mode_changed();
  984. return;
  985. }
  986. const JPH::EMotionType motion_type = _get_motion_type();
  987. const JoltWritableBody3D body = space->write_body(jolt_id);
  988. ERR_FAIL_COND(body.is_invalid());
  989. if (motion_type == JPH::EMotionType::Static) {
  990. put_to_sleep();
  991. }
  992. body->SetMotionType(motion_type);
  993. if (motion_type != JPH::EMotionType::Static) {
  994. wake_up();
  995. }
  996. if (motion_type == JPH::EMotionType::Kinematic) {
  997. body->SetLinearVelocity(JPH::Vec3::sZero());
  998. body->SetAngularVelocity(JPH::Vec3::sZero());
  999. }
  1000. linear_surface_velocity = Vector3();
  1001. angular_surface_velocity = Vector3();
  1002. _mode_changed();
  1003. }
  1004. bool JoltBody3D::is_ccd_enabled() const {
  1005. if (!in_space()) {
  1006. return jolt_settings->mMotionQuality == JPH::EMotionQuality::LinearCast;
  1007. }
  1008. const JPH::BodyInterface &body_iface = space->get_body_iface();
  1009. return body_iface.GetMotionQuality(jolt_id) == JPH::EMotionQuality::LinearCast;
  1010. }
  1011. void JoltBody3D::set_ccd_enabled(bool p_enabled) {
  1012. const JPH::EMotionQuality motion_quality = p_enabled ? JPH::EMotionQuality::LinearCast : JPH::EMotionQuality::Discrete;
  1013. if (!in_space()) {
  1014. jolt_settings->mMotionQuality = motion_quality;
  1015. return;
  1016. }
  1017. JPH::BodyInterface &body_iface = space->get_body_iface();
  1018. body_iface.SetMotionQuality(jolt_id, motion_quality);
  1019. }
  1020. void JoltBody3D::set_mass(float p_mass) {
  1021. if (p_mass != mass) {
  1022. mass = p_mass;
  1023. _update_mass_properties();
  1024. }
  1025. }
  1026. void JoltBody3D::set_inertia(const Vector3 &p_inertia) {
  1027. if (p_inertia != inertia) {
  1028. inertia = p_inertia;
  1029. _update_mass_properties();
  1030. }
  1031. }
  1032. float JoltBody3D::get_bounce() const {
  1033. if (!in_space()) {
  1034. return jolt_settings->mRestitution;
  1035. }
  1036. const JoltReadableBody3D body = space->read_body(jolt_id);
  1037. ERR_FAIL_COND_V(body.is_invalid(), 0.0f);
  1038. return body->GetRestitution();
  1039. }
  1040. void JoltBody3D::set_bounce(float p_bounce) {
  1041. if (!in_space()) {
  1042. jolt_settings->mRestitution = p_bounce;
  1043. return;
  1044. }
  1045. const JoltWritableBody3D body = space->write_body(jolt_id);
  1046. ERR_FAIL_COND(body.is_invalid());
  1047. body->SetRestitution(p_bounce);
  1048. }
  1049. float JoltBody3D::get_friction() const {
  1050. if (!in_space()) {
  1051. return jolt_settings->mFriction;
  1052. }
  1053. const JoltReadableBody3D body = space->read_body(jolt_id);
  1054. ERR_FAIL_COND_V(body.is_invalid(), 0.0f);
  1055. return body->GetFriction();
  1056. }
  1057. void JoltBody3D::set_friction(float p_friction) {
  1058. if (!in_space()) {
  1059. jolt_settings->mFriction = p_friction;
  1060. return;
  1061. }
  1062. const JoltWritableBody3D body = space->write_body(jolt_id);
  1063. ERR_FAIL_COND(body.is_invalid());
  1064. body->SetFriction(p_friction);
  1065. }
  1066. void JoltBody3D::set_gravity_scale(float p_scale) {
  1067. if (gravity_scale == p_scale) {
  1068. return;
  1069. }
  1070. gravity_scale = p_scale;
  1071. _motion_changed();
  1072. }
  1073. void JoltBody3D::set_linear_damp(float p_damp) {
  1074. p_damp = MAX(0.0f, p_damp);
  1075. if (p_damp == linear_damp) {
  1076. return;
  1077. }
  1078. linear_damp = p_damp;
  1079. _update_damp();
  1080. }
  1081. void JoltBody3D::set_angular_damp(float p_damp) {
  1082. p_damp = MAX(0.0f, p_damp);
  1083. if (p_damp == angular_damp) {
  1084. return;
  1085. }
  1086. angular_damp = p_damp;
  1087. _update_damp();
  1088. }
  1089. bool JoltBody3D::is_axis_locked(PhysicsServer3D::BodyAxis p_axis) const {
  1090. return (locked_axes & (uint32_t)p_axis) != 0;
  1091. }
  1092. void JoltBody3D::set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool p_enabled) {
  1093. const uint32_t previous_locked_axes = locked_axes;
  1094. if (p_enabled) {
  1095. locked_axes |= (uint32_t)p_axis;
  1096. } else {
  1097. locked_axes &= ~(uint32_t)p_axis;
  1098. }
  1099. if (previous_locked_axes != locked_axes) {
  1100. _axis_lock_changed();
  1101. }
  1102. }
  1103. bool JoltBody3D::can_interact_with(const JoltBody3D &p_other) const {
  1104. return (can_collide_with(p_other) || p_other.can_collide_with(*this)) && !has_collision_exception(p_other.get_rid()) && !p_other.has_collision_exception(rid);
  1105. }
  1106. bool JoltBody3D::can_interact_with(const JoltSoftBody3D &p_other) const {
  1107. return p_other.can_interact_with(*this);
  1108. }
  1109. bool JoltBody3D::can_interact_with(const JoltArea3D &p_other) const {
  1110. return p_other.can_interact_with(*this);
  1111. }