jolt_space_3d.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. /**************************************************************************/
  2. /* jolt_space_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_space_3d.h"
  31. #include "../joints/jolt_joint_3d.h"
  32. #include "../jolt_physics_server_3d.h"
  33. #include "../jolt_project_settings.h"
  34. #include "../misc/jolt_stream_wrappers.h"
  35. #include "../objects/jolt_area_3d.h"
  36. #include "../objects/jolt_body_3d.h"
  37. #include "../shapes/jolt_custom_shape_type.h"
  38. #include "../shapes/jolt_shape_3d.h"
  39. #include "jolt_contact_listener_3d.h"
  40. #include "jolt_layers.h"
  41. #include "jolt_physics_direct_space_state_3d.h"
  42. #include "jolt_temp_allocator.h"
  43. #include "core/io/file_access.h"
  44. #include "core/os/time.h"
  45. #include "core/string/print_string.h"
  46. #include "core/variant/variant_utility.h"
  47. #include "Jolt/Physics/Collision/CollideShapeVsShapePerLeaf.h"
  48. #include "Jolt/Physics/Collision/CollisionCollectorImpl.h"
  49. #include "Jolt/Physics/PhysicsScene.h"
  50. namespace {
  51. constexpr double SPACE_DEFAULT_CONTACT_RECYCLE_RADIUS = 0.01;
  52. constexpr double SPACE_DEFAULT_CONTACT_MAX_SEPARATION = 0.05;
  53. constexpr double SPACE_DEFAULT_CONTACT_MAX_ALLOWED_PENETRATION = 0.01;
  54. constexpr double SPACE_DEFAULT_CONTACT_DEFAULT_BIAS = 0.8;
  55. constexpr double SPACE_DEFAULT_SLEEP_THRESHOLD_LINEAR = 0.1;
  56. constexpr double SPACE_DEFAULT_SLEEP_THRESHOLD_ANGULAR = 8.0 * Math::PI / 180;
  57. constexpr double SPACE_DEFAULT_SOLVER_ITERATIONS = 8;
  58. } // namespace
  59. void JoltSpace3D::_pre_step(float p_step) {
  60. flush_pending_objects();
  61. while (needs_optimization_list.first()) {
  62. JoltShapedObject3D *object = needs_optimization_list.first()->self();
  63. needs_optimization_list.remove(needs_optimization_list.first());
  64. object->commit_shapes(true);
  65. }
  66. contact_listener->pre_step();
  67. const JPH::BodyLockInterface &lock_iface = get_lock_iface();
  68. const JPH::BodyID *active_rigid_bodies = physics_system->GetActiveBodiesUnsafe(JPH::EBodyType::RigidBody);
  69. const JPH::uint32 active_rigid_body_count = physics_system->GetNumActiveBodies(JPH::EBodyType::RigidBody);
  70. for (JPH::uint32 i = 0; i < active_rigid_body_count; i++) {
  71. JPH::Body *jolt_body = lock_iface.TryGetBody(active_rigid_bodies[i]);
  72. JoltObject3D *object = reinterpret_cast<JoltObject3D *>(jolt_body->GetUserData());
  73. object->pre_step(p_step, *jolt_body);
  74. }
  75. }
  76. void JoltSpace3D::_post_step(float p_step) {
  77. contact_listener->post_step();
  78. while (shapes_changed_list.first()) {
  79. JoltShapedObject3D *object = shapes_changed_list.first()->self();
  80. shapes_changed_list.remove(shapes_changed_list.first());
  81. object->clear_previous_shape();
  82. }
  83. }
  84. JoltSpace3D::JoltSpace3D(JPH::JobSystem *p_job_system) :
  85. job_system(p_job_system),
  86. temp_allocator(new JoltTempAllocator()),
  87. layers(new JoltLayers()),
  88. contact_listener(new JoltContactListener3D(this)),
  89. physics_system(new JPH::PhysicsSystem()) {
  90. physics_system->Init((JPH::uint)JoltProjectSettings::max_bodies, 0, (JPH::uint)JoltProjectSettings::max_body_pairs, (JPH::uint)JoltProjectSettings::max_contact_constraints, *layers, *layers, *layers);
  91. JPH::PhysicsSettings settings;
  92. settings.mBaumgarte = JoltProjectSettings::baumgarte_stabilization_factor;
  93. settings.mSpeculativeContactDistance = JoltProjectSettings::speculative_contact_distance;
  94. settings.mPenetrationSlop = JoltProjectSettings::penetration_slop;
  95. settings.mLinearCastThreshold = JoltProjectSettings::ccd_movement_threshold;
  96. settings.mLinearCastMaxPenetration = JoltProjectSettings::ccd_max_penetration;
  97. settings.mBodyPairCacheMaxDeltaPositionSq = JoltProjectSettings::body_pair_cache_distance_sq;
  98. settings.mBodyPairCacheCosMaxDeltaRotationDiv2 = JoltProjectSettings::body_pair_cache_angle_cos_div2;
  99. settings.mNumVelocitySteps = (JPH::uint)JoltProjectSettings::simulation_velocity_steps;
  100. settings.mNumPositionSteps = (JPH::uint)JoltProjectSettings::simulation_position_steps;
  101. settings.mMinVelocityForRestitution = JoltProjectSettings::bounce_velocity_threshold;
  102. settings.mTimeBeforeSleep = JoltProjectSettings::sleep_time_threshold;
  103. settings.mPointVelocitySleepThreshold = JoltProjectSettings::sleep_velocity_threshold;
  104. settings.mUseBodyPairContactCache = JoltProjectSettings::body_pair_contact_cache_enabled;
  105. settings.mAllowSleeping = JoltProjectSettings::sleep_allowed;
  106. physics_system->SetPhysicsSettings(settings);
  107. physics_system->SetGravity(JPH::Vec3::sZero());
  108. physics_system->SetContactListener(contact_listener);
  109. physics_system->SetSoftBodyContactListener(contact_listener);
  110. physics_system->SetSimCollideBodyVsBody([](const JPH::Body &p_body1, const JPH::Body &p_body2, JPH::Mat44Arg p_transform_com1, JPH::Mat44Arg p_transform_com2, JPH::CollideShapeSettings &p_collide_shape_settings, JPH::CollideShapeCollector &p_collector, const JPH::ShapeFilter &p_shape_filter) {
  111. if (p_body1.IsSensor() || p_body2.IsSensor()) {
  112. JPH::CollideShapeSettings new_collide_shape_settings = p_collide_shape_settings;
  113. // Since we're breaking the sensor down into leaf shapes we'll end up stripping away our `JoltCustomDoubleSidedShape` decorator shape and thus any back-face collision, so we simply force-enable it like this rather than going through the trouble of reapplying the decorator.
  114. new_collide_shape_settings.mBackFaceMode = JPH::EBackFaceMode::CollideWithBackFaces;
  115. JPH::SubShapeIDCreator part1, part2;
  116. JPH::CollideShapeVsShapePerLeaf<JPH::AnyHitCollisionCollector<JPH::CollideShapeCollector>>(p_body1.GetShape(), p_body2.GetShape(), JPH::Vec3::sOne(), JPH::Vec3::sOne(), p_transform_com1, p_transform_com2, part1, part2, new_collide_shape_settings, p_collector, p_shape_filter);
  117. } else {
  118. JPH::PhysicsSystem::sDefaultSimCollideBodyVsBody(p_body1, p_body2, p_transform_com1, p_transform_com2, p_collide_shape_settings, p_collector, p_shape_filter);
  119. }
  120. });
  121. physics_system->SetCombineFriction([](const JPH::Body &p_body1, const JPH::SubShapeID &p_sub_shape_id1, const JPH::Body &p_body2, const JPH::SubShapeID &p_sub_shape_id2) {
  122. return Math::abs(MIN(p_body1.GetFriction(), p_body2.GetFriction()));
  123. });
  124. physics_system->SetCombineRestitution([](const JPH::Body &p_body1, const JPH::SubShapeID &p_sub_shape_id1, const JPH::Body &p_body2, const JPH::SubShapeID &p_sub_shape_id2) {
  125. return CLAMP(p_body1.GetRestitution() + p_body2.GetRestitution(), 0.0f, 1.0f);
  126. });
  127. }
  128. JoltSpace3D::~JoltSpace3D() {
  129. if (direct_state != nullptr) {
  130. memdelete(direct_state);
  131. direct_state = nullptr;
  132. }
  133. if (physics_system != nullptr) {
  134. delete physics_system;
  135. physics_system = nullptr;
  136. }
  137. if (contact_listener != nullptr) {
  138. delete contact_listener;
  139. contact_listener = nullptr;
  140. }
  141. if (layers != nullptr) {
  142. delete layers;
  143. layers = nullptr;
  144. }
  145. if (temp_allocator != nullptr) {
  146. delete temp_allocator;
  147. temp_allocator = nullptr;
  148. }
  149. }
  150. void JoltSpace3D::step(float p_step) {
  151. stepping = true;
  152. last_step = p_step;
  153. _pre_step(p_step);
  154. const JPH::EPhysicsUpdateError update_error = physics_system->Update(p_step, 1, temp_allocator, job_system);
  155. if ((update_error & JPH::EPhysicsUpdateError::ManifoldCacheFull) != JPH::EPhysicsUpdateError::None) {
  156. WARN_PRINT_ONCE(vformat("Jolt Physics manifold cache exceeded capacity and contacts were ignored. "
  157. "Consider increasing maximum number of contact constraints in project settings. "
  158. "Maximum number of contact constraints is currently set to %d.",
  159. JoltProjectSettings::max_contact_constraints));
  160. }
  161. if ((update_error & JPH::EPhysicsUpdateError::BodyPairCacheFull) != JPH::EPhysicsUpdateError::None) {
  162. WARN_PRINT_ONCE(vformat("Jolt Physics body pair cache exceeded capacity and contacts were ignored. "
  163. "Consider increasing maximum number of body pairs in project settings. "
  164. "Maximum number of body pairs is currently set to %d.",
  165. JoltProjectSettings::max_body_pairs));
  166. }
  167. if ((update_error & JPH::EPhysicsUpdateError::ContactConstraintsFull) != JPH::EPhysicsUpdateError::None) {
  168. WARN_PRINT_ONCE(vformat("Jolt Physics contact constraint buffer exceeded capacity and contacts were ignored. "
  169. "Consider increasing maximum number of contact constraints in project settings. "
  170. "Maximum number of contact constraints is currently set to %d.",
  171. JoltProjectSettings::max_contact_constraints));
  172. }
  173. _post_step(p_step);
  174. stepping = false;
  175. }
  176. void JoltSpace3D::call_queries() {
  177. while (body_call_queries_list.first()) {
  178. JoltBody3D *body = body_call_queries_list.first()->self();
  179. body_call_queries_list.remove(body_call_queries_list.first());
  180. body->call_queries();
  181. }
  182. while (area_call_queries_list.first()) {
  183. JoltArea3D *body = area_call_queries_list.first()->self();
  184. area_call_queries_list.remove(area_call_queries_list.first());
  185. body->call_queries();
  186. }
  187. }
  188. double JoltSpace3D::get_param(PhysicsServer3D::SpaceParameter p_param) const {
  189. switch (p_param) {
  190. case PhysicsServer3D::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: {
  191. return SPACE_DEFAULT_CONTACT_RECYCLE_RADIUS;
  192. }
  193. case PhysicsServer3D::SPACE_PARAM_CONTACT_MAX_SEPARATION: {
  194. return SPACE_DEFAULT_CONTACT_MAX_SEPARATION;
  195. }
  196. case PhysicsServer3D::SPACE_PARAM_CONTACT_MAX_ALLOWED_PENETRATION: {
  197. return SPACE_DEFAULT_CONTACT_MAX_ALLOWED_PENETRATION;
  198. }
  199. case PhysicsServer3D::SPACE_PARAM_CONTACT_DEFAULT_BIAS: {
  200. return SPACE_DEFAULT_CONTACT_DEFAULT_BIAS;
  201. }
  202. case PhysicsServer3D::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD: {
  203. return SPACE_DEFAULT_SLEEP_THRESHOLD_LINEAR;
  204. }
  205. case PhysicsServer3D::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD: {
  206. return SPACE_DEFAULT_SLEEP_THRESHOLD_ANGULAR;
  207. }
  208. case PhysicsServer3D::SPACE_PARAM_BODY_TIME_TO_SLEEP: {
  209. return JoltProjectSettings::sleep_time_threshold;
  210. }
  211. case PhysicsServer3D::SPACE_PARAM_SOLVER_ITERATIONS: {
  212. return SPACE_DEFAULT_SOLVER_ITERATIONS;
  213. }
  214. default: {
  215. ERR_FAIL_V_MSG(0.0, vformat("Unhandled space parameter: '%d'. This should not happen. Please report this.", p_param));
  216. }
  217. }
  218. }
  219. void JoltSpace3D::set_param(PhysicsServer3D::SpaceParameter p_param, double p_value) {
  220. switch (p_param) {
  221. case PhysicsServer3D::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: {
  222. WARN_PRINT("Space-specific contact recycle radius is not supported when using Jolt Physics. Any such value will be ignored.");
  223. } break;
  224. case PhysicsServer3D::SPACE_PARAM_CONTACT_MAX_SEPARATION: {
  225. WARN_PRINT("Space-specific contact max separation is not supported when using Jolt Physics. Any such value will be ignored.");
  226. } break;
  227. case PhysicsServer3D::SPACE_PARAM_CONTACT_MAX_ALLOWED_PENETRATION: {
  228. WARN_PRINT("Space-specific contact max allowed penetration is not supported when using Jolt Physics. Any such value will be ignored.");
  229. } break;
  230. case PhysicsServer3D::SPACE_PARAM_CONTACT_DEFAULT_BIAS: {
  231. WARN_PRINT("Space-specific contact default bias is not supported when using Jolt Physics. Any such value will be ignored.");
  232. } break;
  233. case PhysicsServer3D::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD: {
  234. WARN_PRINT("Space-specific linear velocity sleep threshold is not supported when using Jolt Physics. Any such value will be ignored.");
  235. } break;
  236. case PhysicsServer3D::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD: {
  237. WARN_PRINT("Space-specific angular velocity sleep threshold is not supported when using Jolt Physics. Any such value will be ignored.");
  238. } break;
  239. case PhysicsServer3D::SPACE_PARAM_BODY_TIME_TO_SLEEP: {
  240. WARN_PRINT("Space-specific body sleep time is not supported when using Jolt Physics. Any such value will be ignored.");
  241. } break;
  242. case PhysicsServer3D::SPACE_PARAM_SOLVER_ITERATIONS: {
  243. WARN_PRINT("Space-specific solver iterations is not supported when using Jolt Physics. Any such value will be ignored.");
  244. } break;
  245. default: {
  246. ERR_FAIL_MSG(vformat("Unhandled space parameter: '%d'. This should not happen. Please report this.", p_param));
  247. } break;
  248. }
  249. }
  250. JPH::BodyInterface &JoltSpace3D::get_body_iface() {
  251. return physics_system->GetBodyInterfaceNoLock();
  252. }
  253. const JPH::BodyInterface &JoltSpace3D::get_body_iface() const {
  254. return physics_system->GetBodyInterfaceNoLock();
  255. }
  256. const JPH::BodyLockInterface &JoltSpace3D::get_lock_iface() const {
  257. return physics_system->GetBodyLockInterfaceNoLock();
  258. }
  259. const JPH::BroadPhaseQuery &JoltSpace3D::get_broad_phase_query() const {
  260. return physics_system->GetBroadPhaseQuery();
  261. }
  262. const JPH::NarrowPhaseQuery &JoltSpace3D::get_narrow_phase_query() const {
  263. return physics_system->GetNarrowPhaseQueryNoLock();
  264. }
  265. JPH::ObjectLayer JoltSpace3D::map_to_object_layer(JPH::BroadPhaseLayer p_broad_phase_layer, uint32_t p_collision_layer, uint32_t p_collision_mask) {
  266. return layers->to_object_layer(p_broad_phase_layer, p_collision_layer, p_collision_mask);
  267. }
  268. void JoltSpace3D::map_from_object_layer(JPH::ObjectLayer p_object_layer, JPH::BroadPhaseLayer &r_broad_phase_layer, uint32_t &r_collision_layer, uint32_t &r_collision_mask) const {
  269. layers->from_object_layer(p_object_layer, r_broad_phase_layer, r_collision_layer, r_collision_mask);
  270. }
  271. JPH::Body *JoltSpace3D::try_get_jolt_body(const JPH::BodyID &p_body_id) const {
  272. return get_lock_iface().TryGetBody(p_body_id);
  273. }
  274. JoltObject3D *JoltSpace3D::try_get_object(const JPH::BodyID &p_body_id) const {
  275. const JPH::Body *jolt_body = try_get_jolt_body(p_body_id);
  276. if (unlikely(jolt_body == nullptr)) {
  277. return nullptr;
  278. }
  279. return reinterpret_cast<JoltObject3D *>(jolt_body->GetUserData());
  280. }
  281. JoltShapedObject3D *JoltSpace3D::try_get_shaped(const JPH::BodyID &p_body_id) const {
  282. JoltObject3D *object = try_get_object(p_body_id);
  283. if (unlikely(object == nullptr)) {
  284. return nullptr;
  285. }
  286. return object->as_shaped();
  287. }
  288. JoltBody3D *JoltSpace3D::try_get_body(const JPH::BodyID &p_body_id) const {
  289. JoltObject3D *object = try_get_object(p_body_id);
  290. if (unlikely(object == nullptr)) {
  291. return nullptr;
  292. }
  293. return object->as_body();
  294. }
  295. JoltArea3D *JoltSpace3D::try_get_area(const JPH::BodyID &p_body_id) const {
  296. JoltObject3D *object = try_get_object(p_body_id);
  297. if (unlikely(object == nullptr)) {
  298. return nullptr;
  299. }
  300. return object->as_area();
  301. }
  302. JoltSoftBody3D *JoltSpace3D::try_get_soft_body(const JPH::BodyID &p_body_id) const {
  303. JoltObject3D *object = try_get_object(p_body_id);
  304. if (unlikely(object == nullptr)) {
  305. return nullptr;
  306. }
  307. return object->as_soft_body();
  308. }
  309. JoltPhysicsDirectSpaceState3D *JoltSpace3D::get_direct_state() {
  310. if (direct_state == nullptr) {
  311. direct_state = memnew(JoltPhysicsDirectSpaceState3D(this));
  312. }
  313. return direct_state;
  314. }
  315. void JoltSpace3D::set_default_area(JoltArea3D *p_area) {
  316. if (default_area == p_area) {
  317. return;
  318. }
  319. if (default_area != nullptr) {
  320. default_area->set_default_area(false);
  321. }
  322. default_area = p_area;
  323. if (default_area != nullptr) {
  324. default_area->set_default_area(true);
  325. }
  326. }
  327. JPH::Body *JoltSpace3D::add_object(const JoltObject3D &p_object, const JPH::BodyCreationSettings &p_settings, bool p_sleeping) {
  328. JPH::BodyInterface &body_iface = get_body_iface();
  329. JPH::Body *jolt_body = body_iface.CreateBody(p_settings);
  330. if (unlikely(jolt_body == nullptr)) {
  331. ERR_PRINT_ONCE(vformat("Failed to create underlying Jolt Physics body for '%s'. "
  332. "Consider increasing maximum number of bodies in project settings. "
  333. "Maximum number of bodies is currently set to %d.",
  334. p_object.to_string(), JoltProjectSettings::max_bodies));
  335. return nullptr;
  336. }
  337. if (p_sleeping) {
  338. pending_objects_sleeping.push_back(jolt_body->GetID());
  339. } else {
  340. pending_objects_awake.push_back(jolt_body->GetID());
  341. }
  342. return jolt_body;
  343. }
  344. JPH::Body *JoltSpace3D::add_object(const JoltObject3D &p_object, const JPH::SoftBodyCreationSettings &p_settings, bool p_sleeping) {
  345. JPH::BodyInterface &body_iface = get_body_iface();
  346. JPH::Body *jolt_body = body_iface.CreateSoftBody(p_settings);
  347. if (unlikely(jolt_body == nullptr)) {
  348. ERR_PRINT_ONCE(vformat("Failed to create underlying Jolt Physics body for '%s'. "
  349. "Consider increasing maximum number of bodies in project settings. "
  350. "Maximum number of bodies is currently set to %d.",
  351. p_object.to_string(), JoltProjectSettings::max_bodies));
  352. return nullptr;
  353. }
  354. if (p_sleeping) {
  355. pending_objects_sleeping.push_back(jolt_body->GetID());
  356. } else {
  357. pending_objects_awake.push_back(jolt_body->GetID());
  358. }
  359. return jolt_body;
  360. }
  361. void JoltSpace3D::remove_object(const JPH::BodyID &p_jolt_id) {
  362. JPH::BodyInterface &body_iface = get_body_iface();
  363. if (!pending_objects_sleeping.erase_unordered(p_jolt_id) && !pending_objects_awake.erase_unordered(p_jolt_id)) {
  364. body_iface.RemoveBody(p_jolt_id);
  365. }
  366. body_iface.DestroyBody(p_jolt_id);
  367. // If we're never going to step this space, like in the editor viewport, we need to manually clean up Jolt's broad phase instead, otherwise performance can degrade when doing things like switching scenes.
  368. // We'll never actually have zero bodies in any space though, since we always have the default area, so we check if there's one or fewer left instead.
  369. if (!JoltPhysicsServer3D::get_singleton()->is_active() && physics_system->GetNumBodies() <= 1) {
  370. physics_system->OptimizeBroadPhase();
  371. }
  372. }
  373. void JoltSpace3D::flush_pending_objects() {
  374. if (pending_objects_sleeping.is_empty() && pending_objects_awake.is_empty()) {
  375. return;
  376. }
  377. // We only care about locking within this method, because it's called when performing queries, which aren't covered by `PhysicsServer3DWrapMT`.
  378. MutexLock pending_objects_lock(pending_objects_mutex);
  379. JPH::BodyInterface &body_iface = get_body_iface();
  380. if (!pending_objects_sleeping.is_empty()) {
  381. JPH::BodyInterface::AddState add_state = body_iface.AddBodiesPrepare(pending_objects_sleeping.ptr(), pending_objects_sleeping.size());
  382. body_iface.AddBodiesFinalize(pending_objects_sleeping.ptr(), pending_objects_sleeping.size(), add_state, JPH::EActivation::DontActivate);
  383. pending_objects_sleeping.reset();
  384. }
  385. if (!pending_objects_awake.is_empty()) {
  386. JPH::BodyInterface::AddState add_state = body_iface.AddBodiesPrepare(pending_objects_awake.ptr(), pending_objects_awake.size());
  387. body_iface.AddBodiesFinalize(pending_objects_awake.ptr(), pending_objects_awake.size(), add_state, JPH::EActivation::Activate);
  388. pending_objects_awake.reset();
  389. }
  390. }
  391. void JoltSpace3D::set_is_object_sleeping(const JPH::BodyID &p_jolt_id, bool p_enable) {
  392. if (p_enable) {
  393. if (pending_objects_awake.erase_unordered(p_jolt_id)) {
  394. pending_objects_sleeping.push_back(p_jolt_id);
  395. } else if (pending_objects_sleeping.has(p_jolt_id)) {
  396. // Do nothing.
  397. } else {
  398. get_body_iface().DeactivateBody(p_jolt_id);
  399. }
  400. } else {
  401. if (pending_objects_sleeping.erase_unordered(p_jolt_id)) {
  402. pending_objects_awake.push_back(p_jolt_id);
  403. } else if (pending_objects_awake.has(p_jolt_id)) {
  404. // Do nothing.
  405. } else {
  406. get_body_iface().ActivateBody(p_jolt_id);
  407. }
  408. }
  409. }
  410. void JoltSpace3D::enqueue_call_queries(SelfList<JoltBody3D> *p_body) {
  411. if (!p_body->in_list()) {
  412. body_call_queries_list.add(p_body);
  413. }
  414. }
  415. void JoltSpace3D::enqueue_call_queries(SelfList<JoltArea3D> *p_area) {
  416. if (!p_area->in_list()) {
  417. area_call_queries_list.add(p_area);
  418. }
  419. }
  420. void JoltSpace3D::dequeue_call_queries(SelfList<JoltBody3D> *p_body) {
  421. if (p_body->in_list()) {
  422. body_call_queries_list.remove(p_body);
  423. }
  424. }
  425. void JoltSpace3D::dequeue_call_queries(SelfList<JoltArea3D> *p_area) {
  426. if (p_area->in_list()) {
  427. area_call_queries_list.remove(p_area);
  428. }
  429. }
  430. void JoltSpace3D::enqueue_shapes_changed(SelfList<JoltShapedObject3D> *p_object) {
  431. if (!p_object->in_list()) {
  432. shapes_changed_list.add(p_object);
  433. }
  434. }
  435. void JoltSpace3D::dequeue_shapes_changed(SelfList<JoltShapedObject3D> *p_object) {
  436. if (p_object->in_list()) {
  437. shapes_changed_list.remove(p_object);
  438. }
  439. }
  440. void JoltSpace3D::enqueue_needs_optimization(SelfList<JoltShapedObject3D> *p_object) {
  441. if (!p_object->in_list()) {
  442. needs_optimization_list.add(p_object);
  443. }
  444. }
  445. void JoltSpace3D::dequeue_needs_optimization(SelfList<JoltShapedObject3D> *p_object) {
  446. if (p_object->in_list()) {
  447. needs_optimization_list.remove(p_object);
  448. }
  449. }
  450. void JoltSpace3D::add_joint(JPH::Constraint *p_jolt_ref) {
  451. physics_system->AddConstraint(p_jolt_ref);
  452. }
  453. void JoltSpace3D::add_joint(JoltJoint3D *p_joint) {
  454. add_joint(p_joint->get_jolt_ref());
  455. }
  456. void JoltSpace3D::remove_joint(JPH::Constraint *p_jolt_ref) {
  457. physics_system->RemoveConstraint(p_jolt_ref);
  458. }
  459. void JoltSpace3D::remove_joint(JoltJoint3D *p_joint) {
  460. remove_joint(p_joint->get_jolt_ref());
  461. }
  462. #ifdef DEBUG_ENABLED
  463. void JoltSpace3D::dump_debug_snapshot(const String &p_dir) {
  464. const Dictionary datetime = Time::get_singleton()->get_datetime_dict_from_system();
  465. const String datetime_str = vformat("%04d-%02d-%02d_%02d-%02d-%02d", datetime["year"], datetime["month"], datetime["day"], datetime["hour"], datetime["minute"], datetime["second"]);
  466. const String path = p_dir + vformat("/jolt_snapshot_%s_%d.bin", datetime_str, rid.get_id());
  467. Ref<FileAccess> file_access = FileAccess::open(path, FileAccess::ModeFlags::WRITE);
  468. ERR_FAIL_COND_MSG(file_access.is_null(), vformat("Failed to open '%s' for writing when saving snapshot of physics space with RID '%d'.", path, rid.get_id()));
  469. JPH::PhysicsScene physics_scene;
  470. physics_scene.FromPhysicsSystem(physics_system);
  471. for (JPH::BodyCreationSettings &settings : physics_scene.GetBodies()) {
  472. const JoltObject3D *object = reinterpret_cast<const JoltObject3D *>(settings.mUserData);
  473. if (const JoltBody3D *body = object->as_body()) {
  474. // Since we do our own integration of gravity and damping, while leaving Jolt's own values at zero, we need to transfer over the correct values.
  475. settings.mGravityFactor = body->get_gravity_scale();
  476. settings.mLinearDamping = body->get_total_linear_damp();
  477. settings.mAngularDamping = body->get_total_angular_damp();
  478. }
  479. settings.SetShape(JoltShape3D::without_custom_shapes(settings.GetShape()));
  480. }
  481. JoltStreamOutputWrapper output_stream(file_access);
  482. physics_scene.SaveBinaryState(output_stream, true, false);
  483. ERR_FAIL_COND_MSG(file_access->get_error() != OK, vformat("Writing snapshot of physics space with RID '%d' to '%s' failed with error '%s'.", rid.get_id(), path, VariantUtilityFunctions::error_string(file_access->get_error())));
  484. print_line(vformat("Snapshot of physics space with RID '%d' saved to '%s'.", rid.get_id(), path));
  485. }
  486. const PackedVector3Array &JoltSpace3D::get_debug_contacts() const {
  487. return contact_listener->get_debug_contacts();
  488. }
  489. int JoltSpace3D::get_debug_contact_count() const {
  490. return contact_listener->get_debug_contact_count();
  491. }
  492. int JoltSpace3D::get_max_debug_contacts() const {
  493. return contact_listener->get_max_debug_contacts();
  494. }
  495. void JoltSpace3D::set_max_debug_contacts(int p_count) {
  496. contact_listener->set_max_debug_contacts(p_count);
  497. }
  498. #endif