2
0

jolt_physics_direct_space_state_3d.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. /**************************************************************************/
  2. /* jolt_physics_direct_space_state_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_physics_direct_space_state_3d.h"
  31. #include "../jolt_physics_server_3d.h"
  32. #include "../jolt_project_settings.h"
  33. #include "../misc/jolt_type_conversions.h"
  34. #include "../objects/jolt_area_3d.h"
  35. #include "../objects/jolt_body_3d.h"
  36. #include "../objects/jolt_object_3d.h"
  37. #include "../shapes/jolt_custom_motion_shape.h"
  38. #include "../shapes/jolt_shape_3d.h"
  39. #include "jolt_motion_filter_3d.h"
  40. #include "jolt_query_collectors.h"
  41. #include "jolt_query_filter_3d.h"
  42. #include "jolt_space_3d.h"
  43. #include "Jolt/Geometry/GJKClosestPoint.h"
  44. #include "Jolt/Physics/Body/Body.h"
  45. #include "Jolt/Physics/Body/BodyFilter.h"
  46. #include "Jolt/Physics/Collision/BroadPhase/BroadPhaseQuery.h"
  47. #include "Jolt/Physics/Collision/CastResult.h"
  48. #include "Jolt/Physics/Collision/CollidePointResult.h"
  49. #include "Jolt/Physics/Collision/NarrowPhaseQuery.h"
  50. #include "Jolt/Physics/Collision/RayCast.h"
  51. #include "Jolt/Physics/Collision/Shape/MeshShape.h"
  52. #include "Jolt/Physics/PhysicsSystem.h"
  53. bool JoltPhysicsDirectSpaceState3D::_cast_motion_impl(const JPH::Shape &p_jolt_shape, const Transform3D &p_transform_com, const Vector3 &p_scale, const Vector3 &p_motion, bool p_use_edge_removal, bool p_ignore_overlaps, const JPH::CollideShapeSettings &p_settings, const JPH::BroadPhaseLayerFilter &p_broad_phase_layer_filter, const JPH::ObjectLayerFilter &p_object_layer_filter, const JPH::BodyFilter &p_body_filter, const JPH::ShapeFilter &p_shape_filter, real_t &r_closest_safe, real_t &r_closest_unsafe) const {
  54. r_closest_safe = 1.0f;
  55. r_closest_unsafe = 1.0f;
  56. ERR_FAIL_COND_V_MSG(p_jolt_shape.GetType() != JPH::EShapeType::Convex, false, "Shape-casting with non-convex shapes is not supported.");
  57. const float motion_length = (float)p_motion.length();
  58. if (p_ignore_overlaps && motion_length == 0.0f) {
  59. return false;
  60. }
  61. const JPH::RMat44 transform_com = to_jolt_r(p_transform_com);
  62. const JPH::Vec3 scale = to_jolt(p_scale);
  63. const JPH::Vec3 motion = to_jolt(p_motion);
  64. const JPH::Vec3 motion_local = transform_com.Multiply3x3Transposed(motion);
  65. JPH::AABox aabb = p_jolt_shape.GetWorldSpaceBounds(transform_com, scale);
  66. JPH::AABox aabb_translated = aabb;
  67. aabb_translated.Translate(motion);
  68. aabb.Encapsulate(aabb_translated);
  69. JoltQueryCollectorAnyMulti<JPH::CollideShapeBodyCollector, 1024> aabb_collector;
  70. space->get_broad_phase_query().CollideAABox(aabb, aabb_collector, p_broad_phase_layer_filter, p_object_layer_filter);
  71. if (!aabb_collector.had_hit()) {
  72. return false;
  73. }
  74. const JPH::RVec3 base_offset = transform_com.GetTranslation();
  75. JoltCustomMotionShape motion_shape(static_cast<const JPH::ConvexShape &>(p_jolt_shape));
  76. auto collides = [&](const JPH::Body &p_other_body, float p_fraction) {
  77. motion_shape.set_motion(motion_local * p_fraction);
  78. const JPH::TransformedShape other_shape = p_other_body.GetTransformedShape();
  79. JoltQueryCollectorAny<JPH::CollideShapeCollector> collector;
  80. if (p_use_edge_removal) {
  81. JPH::CollideShapeSettings eier_settings = p_settings;
  82. eier_settings.mActiveEdgeMode = JPH::EActiveEdgeMode::CollideWithAll;
  83. eier_settings.mCollectFacesMode = JPH::ECollectFacesMode::CollectFaces;
  84. JPH::InternalEdgeRemovingCollector eier_collector(collector);
  85. other_shape.CollideShape(&motion_shape, scale, transform_com, eier_settings, base_offset, eier_collector, p_shape_filter);
  86. eier_collector.Flush();
  87. } else {
  88. other_shape.CollideShape(&motion_shape, scale, transform_com, p_settings, base_offset, collector, p_shape_filter);
  89. }
  90. return collector.had_hit();
  91. };
  92. // Figure out the number of steps we need in our binary search in order to achieve millimeter precision, within reason.
  93. const int step_count = CLAMP(int(logf(1000.0f * motion_length) / (float)Math_LN2), 4, 16);
  94. bool collided = false;
  95. for (int i = 0; i < aabb_collector.get_hit_count(); ++i) {
  96. const JPH::BodyID other_jolt_id = aabb_collector.get_hit(i);
  97. if (!p_body_filter.ShouldCollide(other_jolt_id)) {
  98. continue;
  99. }
  100. const JoltReadableBody3D other_jolt_body = space->read_body(other_jolt_id);
  101. if (!p_body_filter.ShouldCollideLocked(*other_jolt_body)) {
  102. continue;
  103. }
  104. if (!collides(*other_jolt_body, 1.0f)) {
  105. continue;
  106. }
  107. if (p_ignore_overlaps && collides(*other_jolt_body, 0.0f)) {
  108. continue;
  109. }
  110. float lo = 0.0f;
  111. float hi = 1.0f;
  112. float coeff = 0.5f;
  113. for (int j = 0; j < step_count; ++j) {
  114. const float fraction = lo + (hi - lo) * coeff;
  115. if (collides(*other_jolt_body, fraction)) {
  116. collided = true;
  117. hi = fraction;
  118. if (j == 0 || lo > 0.0f) {
  119. coeff = 0.5f;
  120. } else {
  121. coeff = 0.25f;
  122. }
  123. } else {
  124. lo = fraction;
  125. if (j == 0 || hi < 1.0f) {
  126. coeff = 0.5f;
  127. } else {
  128. coeff = 0.75f;
  129. }
  130. }
  131. }
  132. if (lo < r_closest_safe) {
  133. r_closest_safe = lo;
  134. r_closest_unsafe = hi;
  135. }
  136. }
  137. return collided;
  138. }
  139. bool JoltPhysicsDirectSpaceState3D::_body_motion_recover(const JoltBody3D &p_body, const Transform3D &p_transform, float p_margin, const HashSet<RID> &p_excluded_bodies, const HashSet<ObjectID> &p_excluded_objects, Vector3 &r_recovery) const {
  140. const int recovery_iterations = JoltProjectSettings::get_motion_query_recovery_iterations();
  141. const float recovery_amount = JoltProjectSettings::get_motion_query_recovery_amount();
  142. const JPH::Shape *jolt_shape = p_body.get_jolt_shape();
  143. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  144. Transform3D transform_com = p_transform.translated_local(com_scaled);
  145. JPH::CollideShapeSettings settings;
  146. settings.mMaxSeparationDistance = p_margin;
  147. const Vector3 &base_offset = transform_com.origin;
  148. const JoltMotionFilter3D motion_filter(p_body, p_excluded_bodies, p_excluded_objects);
  149. JoltQueryCollectorAnyMulti<JPH::CollideShapeCollector, 32> collector;
  150. bool recovered = false;
  151. for (int i = 0; i < recovery_iterations; ++i) {
  152. collector.reset();
  153. _collide_shape_kinematics(jolt_shape, JPH::Vec3::sReplicate(1.0f), to_jolt_r(transform_com), settings, to_jolt_r(base_offset), collector, motion_filter, motion_filter, motion_filter, motion_filter);
  154. if (!collector.had_hit()) {
  155. break;
  156. }
  157. const int hit_count = collector.get_hit_count();
  158. float combined_priority = 0.0;
  159. for (int j = 0; j < hit_count; j++) {
  160. const JPH::CollideShapeResult &hit = collector.get_hit(j);
  161. const JoltReadableBody3D other_jolt_body = space->read_body(hit.mBodyID2);
  162. const JoltBody3D *other_body = other_jolt_body.as_body();
  163. ERR_CONTINUE(other_body == nullptr);
  164. combined_priority += other_body->get_collision_priority();
  165. }
  166. const float average_priority = MAX(combined_priority / (float)hit_count, (float)CMP_EPSILON);
  167. recovered = true;
  168. Vector3 recovery;
  169. for (int j = 0; j < hit_count; ++j) {
  170. const JPH::CollideShapeResult &hit = collector.get_hit(j);
  171. const Vector3 penetration_axis = to_godot(hit.mPenetrationAxis.Normalized());
  172. const Vector3 margin_offset = penetration_axis * p_margin;
  173. const Vector3 point_on_1 = base_offset + to_godot(hit.mContactPointOn1) + margin_offset;
  174. const Vector3 point_on_2 = base_offset + to_godot(hit.mContactPointOn2);
  175. const real_t distance_to_1 = penetration_axis.dot(point_on_1 + recovery);
  176. const real_t distance_to_2 = penetration_axis.dot(point_on_2);
  177. const float penetration_depth = float(distance_to_1 - distance_to_2);
  178. if (penetration_depth <= 0.0f) {
  179. continue;
  180. }
  181. const JoltReadableBody3D other_jolt_body = space->read_body(hit.mBodyID2);
  182. const JoltBody3D *other_body = other_jolt_body.as_body();
  183. ERR_CONTINUE(other_body == nullptr);
  184. const float recovery_distance = penetration_depth * recovery_amount;
  185. const float other_priority = other_body->get_collision_priority();
  186. const float other_priority_normalized = other_priority / average_priority;
  187. const float scaled_recovery_distance = recovery_distance * other_priority_normalized;
  188. recovery -= penetration_axis * scaled_recovery_distance;
  189. }
  190. if (recovery == Vector3()) {
  191. break;
  192. }
  193. r_recovery += recovery;
  194. transform_com.origin += recovery;
  195. }
  196. return recovered;
  197. }
  198. bool JoltPhysicsDirectSpaceState3D::_body_motion_cast(const JoltBody3D &p_body, const Transform3D &p_transform, const Vector3 &p_scale, const Vector3 &p_motion, bool p_collide_separation_ray, const HashSet<RID> &p_excluded_bodies, const HashSet<ObjectID> &p_excluded_objects, real_t &r_safe_fraction, real_t &r_unsafe_fraction) const {
  199. const Transform3D body_transform = p_transform.scaled_local(p_scale);
  200. const JPH::CollideShapeSettings settings;
  201. const JoltMotionFilter3D motion_filter(p_body, p_excluded_bodies, p_excluded_objects, p_collide_separation_ray);
  202. bool collided = false;
  203. for (int i = 0; i < p_body.get_shape_count(); ++i) {
  204. if (p_body.is_shape_disabled(i)) {
  205. continue;
  206. }
  207. JoltShape3D *shape = p_body.get_shape(i);
  208. if (!shape->is_convex()) {
  209. continue;
  210. }
  211. const JPH::ShapeRefC jolt_shape = shape->try_build();
  212. if (unlikely(jolt_shape == nullptr)) {
  213. return false;
  214. }
  215. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  216. const Transform3D transform_local = p_body.get_shape_transform_scaled(i);
  217. const Transform3D transform_com_local = transform_local.translated_local(com_scaled);
  218. Transform3D transform_com = body_transform * transform_com_local;
  219. Vector3 scale = transform_com.basis.get_scale();
  220. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "body_test_motion was passed an invalid transform along with body '%s'. This results in invalid scaling for shape at index %d.");
  221. transform_com.basis.orthonormalize();
  222. real_t shape_safe_fraction = 1.0;
  223. real_t shape_unsafe_fraction = 1.0;
  224. collided |= _cast_motion_impl(*jolt_shape, transform_com, scale, p_motion, JoltProjectSettings::use_enhanced_internal_edge_removal_for_motion_queries(), false, settings, motion_filter, motion_filter, motion_filter, motion_filter, shape_safe_fraction, shape_unsafe_fraction);
  225. r_safe_fraction = MIN(r_safe_fraction, shape_safe_fraction);
  226. r_unsafe_fraction = MIN(r_unsafe_fraction, shape_unsafe_fraction);
  227. }
  228. return collided;
  229. }
  230. bool JoltPhysicsDirectSpaceState3D::_body_motion_collide(const JoltBody3D &p_body, const Transform3D &p_transform, const Vector3 &p_motion, float p_margin, int p_max_collisions, const HashSet<RID> &p_excluded_bodies, const HashSet<ObjectID> &p_excluded_objects, PhysicsServer3D::MotionResult *p_result) const {
  231. if (p_max_collisions == 0) {
  232. return false;
  233. }
  234. const JPH::Shape *jolt_shape = p_body.get_jolt_shape();
  235. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  236. const Transform3D transform_com = p_transform.translated_local(com_scaled);
  237. JPH::CollideShapeSettings settings;
  238. settings.mCollectFacesMode = JPH::ECollectFacesMode::CollectFaces;
  239. settings.mMaxSeparationDistance = p_margin;
  240. const Vector3 &base_offset = transform_com.origin;
  241. const JoltMotionFilter3D motion_filter(p_body, p_excluded_bodies, p_excluded_objects);
  242. JoltQueryCollectorClosestMulti<JPH::CollideShapeCollector, 32> collector(p_max_collisions);
  243. _collide_shape_kinematics(jolt_shape, JPH::Vec3::sReplicate(1.0f), to_jolt_r(transform_com), settings, to_jolt_r(base_offset), collector, motion_filter, motion_filter, motion_filter, motion_filter);
  244. if (!collector.had_hit() || p_result == nullptr) {
  245. return collector.had_hit();
  246. }
  247. int count = 0;
  248. for (int i = 0; i < collector.get_hit_count(); ++i) {
  249. const JPH::CollideShapeResult &hit = collector.get_hit(i);
  250. const float penetration_depth = hit.mPenetrationDepth + p_margin;
  251. if (penetration_depth <= 0.0f) {
  252. continue;
  253. }
  254. const Vector3 normal = to_godot(-hit.mPenetrationAxis.Normalized());
  255. if (p_motion.length_squared() > 0) {
  256. const Vector3 direction = p_motion.normalized();
  257. if (direction.dot(normal) >= -CMP_EPSILON) {
  258. continue;
  259. }
  260. }
  261. JPH::ContactPoints contact_points1;
  262. JPH::ContactPoints contact_points2;
  263. if (p_max_collisions > 1) {
  264. _generate_manifold(hit, contact_points1, contact_points2 JPH_IF_DEBUG_RENDERER(, to_jolt_r(base_offset)));
  265. } else {
  266. contact_points2.push_back(hit.mContactPointOn2);
  267. }
  268. const JoltReadableBody3D collider_jolt_body = space->read_body(hit.mBodyID2);
  269. const JoltShapedObject3D *collider = collider_jolt_body.as_shaped();
  270. ERR_FAIL_NULL_V(collider, false);
  271. const int local_shape = p_body.find_shape_index(hit.mSubShapeID1);
  272. ERR_FAIL_COND_V(local_shape == -1, false);
  273. const int collider_shape = collider->find_shape_index(hit.mSubShapeID2);
  274. ERR_FAIL_COND_V(collider_shape == -1, false);
  275. for (JPH::Vec3 contact_point : contact_points2) {
  276. const Vector3 position = base_offset + to_godot(contact_point);
  277. PhysicsServer3D::MotionCollision &collision = p_result->collisions[count++];
  278. collision.position = position;
  279. collision.normal = normal;
  280. collision.collider_velocity = collider->get_velocity_at_position(position);
  281. collision.collider_angular_velocity = collider->get_angular_velocity();
  282. collision.depth = penetration_depth;
  283. collision.local_shape = local_shape;
  284. collision.collider_id = collider->get_instance_id();
  285. collision.collider = collider->get_rid();
  286. collision.collider_shape = collider_shape;
  287. if (count == p_max_collisions) {
  288. break;
  289. }
  290. }
  291. if (count == p_max_collisions) {
  292. break;
  293. }
  294. }
  295. p_result->collision_count = count;
  296. return count > 0;
  297. }
  298. int JoltPhysicsDirectSpaceState3D::_try_get_face_index(const JPH::Body &p_body, const JPH::SubShapeID &p_sub_shape_id) {
  299. if (!JoltProjectSettings::enable_ray_cast_face_index()) {
  300. return -1;
  301. }
  302. const JPH::Shape *root_shape = p_body.GetShape();
  303. JPH::SubShapeID sub_shape_id_remainder;
  304. const JPH::Shape *leaf_shape = root_shape->GetLeafShape(p_sub_shape_id, sub_shape_id_remainder);
  305. if (leaf_shape->GetType() != JPH::EShapeType::Mesh) {
  306. return -1;
  307. }
  308. const JPH::MeshShape *mesh_shape = static_cast<const JPH::MeshShape *>(leaf_shape);
  309. return (int)mesh_shape->GetTriangleUserData(sub_shape_id_remainder);
  310. }
  311. void JoltPhysicsDirectSpaceState3D::_generate_manifold(const JPH::CollideShapeResult &p_hit, JPH::ContactPoints &r_contact_points1, JPH::ContactPoints &r_contact_points2 JPH_IF_DEBUG_RENDERER(, JPH::RVec3Arg p_center_of_mass)) const {
  312. const JPH::PhysicsSystem &physics_system = space->get_physics_system();
  313. const JPH::PhysicsSettings &physics_settings = physics_system.GetPhysicsSettings();
  314. const JPH::Vec3 penetration_axis = p_hit.mPenetrationAxis.Normalized();
  315. JPH::ManifoldBetweenTwoFaces(p_hit.mContactPointOn1, p_hit.mContactPointOn2, penetration_axis, physics_settings.mManifoldToleranceSq, p_hit.mShape1Face, p_hit.mShape2Face, r_contact_points1, r_contact_points2 JPH_IF_DEBUG_RENDERER(, p_center_of_mass));
  316. if (r_contact_points1.size() > 4) {
  317. JPH::PruneContactPoints(penetration_axis, r_contact_points1, r_contact_points2 JPH_IF_DEBUG_RENDERER(, p_center_of_mass));
  318. }
  319. }
  320. void JoltPhysicsDirectSpaceState3D::_collide_shape_queries(
  321. const JPH::Shape *p_shape,
  322. JPH::Vec3Arg p_scale,
  323. JPH::RMat44Arg p_transform_com,
  324. const JPH::CollideShapeSettings &p_settings,
  325. JPH::RVec3Arg p_base_offset,
  326. JPH::CollideShapeCollector &p_collector,
  327. const JPH::BroadPhaseLayerFilter &p_broad_phase_layer_filter,
  328. const JPH::ObjectLayerFilter &p_object_layer_filter,
  329. const JPH::BodyFilter &p_body_filter,
  330. const JPH::ShapeFilter &p_shape_filter) const {
  331. if (JoltProjectSettings::use_enhanced_internal_edge_removal_for_queries()) {
  332. space->get_narrow_phase_query().CollideShapeWithInternalEdgeRemoval(p_shape, p_scale, p_transform_com, p_settings, p_base_offset, p_collector, p_broad_phase_layer_filter, p_object_layer_filter, p_body_filter, p_shape_filter);
  333. } else {
  334. space->get_narrow_phase_query().CollideShape(p_shape, p_scale, p_transform_com, p_settings, p_base_offset, p_collector, p_broad_phase_layer_filter, p_object_layer_filter, p_body_filter, p_shape_filter);
  335. }
  336. }
  337. void JoltPhysicsDirectSpaceState3D::_collide_shape_kinematics(
  338. const JPH::Shape *p_shape,
  339. JPH::Vec3Arg p_scale,
  340. JPH::RMat44Arg p_transform_com,
  341. const JPH::CollideShapeSettings &p_settings,
  342. JPH::RVec3Arg p_base_offset,
  343. JPH::CollideShapeCollector &p_collector,
  344. const JPH::BroadPhaseLayerFilter &p_broad_phase_layer_filter,
  345. const JPH::ObjectLayerFilter &p_object_layer_filter,
  346. const JPH::BodyFilter &p_body_filter,
  347. const JPH::ShapeFilter &p_shape_filter) const {
  348. if (JoltProjectSettings::use_enhanced_internal_edge_removal_for_motion_queries()) {
  349. space->get_narrow_phase_query().CollideShapeWithInternalEdgeRemoval(p_shape, p_scale, p_transform_com, p_settings, p_base_offset, p_collector, p_broad_phase_layer_filter, p_object_layer_filter, p_body_filter, p_shape_filter);
  350. } else {
  351. space->get_narrow_phase_query().CollideShape(p_shape, p_scale, p_transform_com, p_settings, p_base_offset, p_collector, p_broad_phase_layer_filter, p_object_layer_filter, p_body_filter, p_shape_filter);
  352. }
  353. }
  354. JoltPhysicsDirectSpaceState3D::JoltPhysicsDirectSpaceState3D(JoltSpace3D *p_space) :
  355. space(p_space) {
  356. }
  357. bool JoltPhysicsDirectSpaceState3D::intersect_ray(const RayParameters &p_parameters, RayResult &r_result) {
  358. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "intersect_ray must not be called while the physics space is being stepped.");
  359. space->try_optimize();
  360. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude, p_parameters.pick_ray);
  361. const JPH::RVec3 from = to_jolt_r(p_parameters.from);
  362. const JPH::RVec3 to = to_jolt_r(p_parameters.to);
  363. const JPH::Vec3 vector = JPH::Vec3(to - from);
  364. const JPH::RRayCast ray(from, vector);
  365. const JPH::EBackFaceMode back_face_mode = p_parameters.hit_back_faces ? JPH::EBackFaceMode::CollideWithBackFaces : JPH::EBackFaceMode::IgnoreBackFaces;
  366. JPH::RayCastSettings settings;
  367. settings.mTreatConvexAsSolid = p_parameters.hit_from_inside;
  368. settings.mBackFaceModeTriangles = back_face_mode;
  369. JoltQueryCollectorClosest<JPH::CastRayCollector> collector;
  370. space->get_narrow_phase_query().CastRay(ray, settings, collector, query_filter, query_filter, query_filter);
  371. if (!collector.had_hit()) {
  372. return false;
  373. }
  374. const JPH::RayCastResult &hit = collector.get_hit();
  375. const JPH::BodyID &body_id = hit.mBodyID;
  376. const JPH::SubShapeID &sub_shape_id = hit.mSubShapeID2;
  377. const JoltReadableBody3D body = space->read_body(body_id);
  378. const JoltObject3D *object = body.as_object();
  379. ERR_FAIL_NULL_V(object, false);
  380. const JPH::RVec3 position = ray.GetPointOnRay(hit.mFraction);
  381. JPH::Vec3 normal = JPH::Vec3::sZero();
  382. if (!p_parameters.hit_from_inside || hit.mFraction > 0.0f) {
  383. normal = body->GetWorldSpaceSurfaceNormal(sub_shape_id, position);
  384. // If we got a back-face normal we need to flip it.
  385. if (normal.Dot(vector) > 0) {
  386. normal = -normal;
  387. }
  388. }
  389. r_result.position = to_godot(position);
  390. r_result.normal = to_godot(normal);
  391. r_result.rid = object->get_rid();
  392. r_result.collider_id = object->get_instance_id();
  393. r_result.collider = object->get_instance();
  394. r_result.shape = 0;
  395. if (const JoltShapedObject3D *shaped_object = object->as_shaped()) {
  396. const int shape_index = shaped_object->find_shape_index(sub_shape_id);
  397. ERR_FAIL_COND_V(shape_index == -1, false);
  398. r_result.shape = shape_index;
  399. r_result.face_index = _try_get_face_index(*body, sub_shape_id);
  400. }
  401. return true;
  402. }
  403. int JoltPhysicsDirectSpaceState3D::intersect_point(const PointParameters &p_parameters, ShapeResult *r_results, int p_result_max) {
  404. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "intersect_point must not be called while the physics space is being stepped.");
  405. if (p_result_max == 0) {
  406. return 0;
  407. }
  408. space->try_optimize();
  409. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  410. JoltQueryCollectorAnyMulti<JPH::CollidePointCollector, 32> collector(p_result_max);
  411. space->get_narrow_phase_query().CollidePoint(to_jolt_r(p_parameters.position), collector, query_filter, query_filter, query_filter);
  412. const int hit_count = collector.get_hit_count();
  413. for (int i = 0; i < hit_count; ++i) {
  414. const JPH::CollidePointResult &hit = collector.get_hit(i);
  415. const JoltReadableBody3D body = space->read_body(hit.mBodyID);
  416. const JoltObject3D *object = body.as_object();
  417. ERR_FAIL_NULL_V(object, 0);
  418. ShapeResult &result = *r_results++;
  419. result.shape = 0;
  420. if (const JoltShapedObject3D *shaped_object = object->as_shaped()) {
  421. const int shape_index = shaped_object->find_shape_index(hit.mSubShapeID2);
  422. ERR_FAIL_COND_V(shape_index == -1, 0);
  423. result.shape = shape_index;
  424. }
  425. result.rid = object->get_rid();
  426. result.collider_id = object->get_instance_id();
  427. result.collider = object->get_instance();
  428. }
  429. return hit_count;
  430. }
  431. int JoltPhysicsDirectSpaceState3D::intersect_shape(const ShapeParameters &p_parameters, ShapeResult *r_results, int p_result_max) {
  432. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "intersect_shape must not be called while the physics space is being stepped.");
  433. if (p_result_max == 0) {
  434. return 0;
  435. }
  436. space->try_optimize();
  437. JoltShape3D *shape = JoltPhysicsServer3D::get_singleton()->get_shape(p_parameters.shape_rid);
  438. ERR_FAIL_NULL_V(shape, 0);
  439. const JPH::ShapeRefC jolt_shape = shape->try_build();
  440. ERR_FAIL_NULL_V(jolt_shape, 0);
  441. Transform3D transform = p_parameters.transform;
  442. JOLT_ENSURE_SCALE_NOT_ZERO(transform, "intersect_shape was passed an invalid transform.");
  443. Vector3 scale = transform.basis.get_scale();
  444. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "intersect_shape was passed an invalid transform.");
  445. transform.basis.orthonormalize();
  446. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  447. const Transform3D transform_com = transform.translated_local(com_scaled);
  448. JPH::CollideShapeSettings settings;
  449. settings.mMaxSeparationDistance = (float)p_parameters.margin;
  450. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  451. JoltQueryCollectorAnyMulti<JPH::CollideShapeCollector, 32> collector(p_result_max);
  452. _collide_shape_queries(jolt_shape, to_jolt(scale), to_jolt_r(transform_com), settings, to_jolt_r(transform_com.origin), collector, query_filter, query_filter, query_filter);
  453. const int hit_count = collector.get_hit_count();
  454. for (int i = 0; i < hit_count; ++i) {
  455. const JPH::CollideShapeResult &hit = collector.get_hit(i);
  456. const JoltReadableBody3D body = space->read_body(hit.mBodyID2);
  457. const JoltObject3D *object = body.as_object();
  458. ERR_FAIL_NULL_V(object, 0);
  459. ShapeResult &result = *r_results++;
  460. result.shape = 0;
  461. if (const JoltShapedObject3D *shaped_object = object->as_shaped()) {
  462. const int shape_index = shaped_object->find_shape_index(hit.mSubShapeID2);
  463. ERR_FAIL_COND_V(shape_index == -1, 0);
  464. result.shape = shape_index;
  465. }
  466. result.rid = object->get_rid();
  467. result.collider_id = object->get_instance_id();
  468. result.collider = object->get_instance();
  469. }
  470. return hit_count;
  471. }
  472. bool JoltPhysicsDirectSpaceState3D::cast_motion(const ShapeParameters &p_parameters, real_t &r_closest_safe, real_t &r_closest_unsafe, ShapeRestInfo *r_info) {
  473. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "cast_motion must not be called while the physics space is being stepped.");
  474. ERR_FAIL_COND_V_MSG(r_info != nullptr, false, "Providing rest info as part of cast_motion is not supported when using Jolt Physics.");
  475. space->try_optimize();
  476. JoltShape3D *shape = JoltPhysicsServer3D::get_singleton()->get_shape(p_parameters.shape_rid);
  477. ERR_FAIL_NULL_V(shape, false);
  478. const JPH::ShapeRefC jolt_shape = shape->try_build();
  479. ERR_FAIL_NULL_V(jolt_shape, false);
  480. Transform3D transform = p_parameters.transform;
  481. JOLT_ENSURE_SCALE_NOT_ZERO(transform, "cast_motion (maybe from ShapeCast3D?) was passed an invalid transform.");
  482. Vector3 scale = transform.basis.get_scale();
  483. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "cast_motion (maybe from ShapeCast3D?) was passed an invalid transform.");
  484. transform.basis.orthonormalize();
  485. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  486. Transform3D transform_com = transform.translated_local(com_scaled);
  487. JPH::CollideShapeSettings settings;
  488. settings.mMaxSeparationDistance = (float)p_parameters.margin;
  489. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  490. _cast_motion_impl(*jolt_shape, transform_com, scale, p_parameters.motion, JoltProjectSettings::use_enhanced_internal_edge_removal_for_queries(), true, settings, query_filter, query_filter, query_filter, JPH::ShapeFilter(), r_closest_safe, r_closest_unsafe);
  491. return true;
  492. }
  493. bool JoltPhysicsDirectSpaceState3D::collide_shape(const ShapeParameters &p_parameters, Vector3 *r_results, int p_result_max, int &r_result_count) {
  494. r_result_count = 0;
  495. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "collide_shape must not be called while the physics space is being stepped.");
  496. if (p_result_max == 0) {
  497. return false;
  498. }
  499. space->try_optimize();
  500. JoltShape3D *shape = JoltPhysicsServer3D::get_singleton()->get_shape(p_parameters.shape_rid);
  501. ERR_FAIL_NULL_V(shape, false);
  502. const JPH::ShapeRefC jolt_shape = shape->try_build();
  503. ERR_FAIL_NULL_V(jolt_shape, false);
  504. Transform3D transform = p_parameters.transform;
  505. JOLT_ENSURE_SCALE_NOT_ZERO(transform, "collide_shape was passed an invalid transform.");
  506. Vector3 scale = transform.basis.get_scale();
  507. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "collide_shape was passed an invalid transform.");
  508. transform.basis.orthonormalize();
  509. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  510. const Transform3D transform_com = transform.translated_local(com_scaled);
  511. JPH::CollideShapeSettings settings;
  512. settings.mCollectFacesMode = JPH::ECollectFacesMode::CollectFaces;
  513. settings.mMaxSeparationDistance = (float)p_parameters.margin;
  514. const Vector3 &base_offset = transform_com.origin;
  515. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  516. JoltQueryCollectorAnyMulti<JPH::CollideShapeCollector, 32> collector(p_result_max);
  517. _collide_shape_queries(jolt_shape, to_jolt(scale), to_jolt_r(transform_com), settings, to_jolt_r(base_offset), collector, query_filter, query_filter, query_filter);
  518. if (!collector.had_hit()) {
  519. return false;
  520. }
  521. const int max_points = p_result_max * 2;
  522. int point_count = 0;
  523. for (int i = 0; i < collector.get_hit_count(); ++i) {
  524. const JPH::CollideShapeResult &hit = collector.get_hit(i);
  525. const Vector3 penetration_axis = to_godot(hit.mPenetrationAxis.Normalized());
  526. const Vector3 margin_offset = penetration_axis * (float)p_parameters.margin;
  527. JPH::ContactPoints contact_points1;
  528. JPH::ContactPoints contact_points2;
  529. _generate_manifold(hit, contact_points1, contact_points2 JPH_IF_DEBUG_RENDERER(, to_jolt_r(base_offset)));
  530. for (JPH::uint j = 0; j < contact_points1.size(); ++j) {
  531. r_results[point_count++] = base_offset + to_godot(contact_points1[j]) + margin_offset;
  532. r_results[point_count++] = base_offset + to_godot(contact_points2[j]);
  533. if (point_count >= max_points) {
  534. break;
  535. }
  536. }
  537. if (point_count >= max_points) {
  538. break;
  539. }
  540. }
  541. r_result_count = point_count / 2;
  542. return true;
  543. }
  544. bool JoltPhysicsDirectSpaceState3D::rest_info(const ShapeParameters &p_parameters, ShapeRestInfo *r_info) {
  545. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "get_rest_info must not be called while the physics space is being stepped.");
  546. space->try_optimize();
  547. JoltShape3D *shape = JoltPhysicsServer3D::get_singleton()->get_shape(p_parameters.shape_rid);
  548. ERR_FAIL_NULL_V(shape, false);
  549. const JPH::ShapeRefC jolt_shape = shape->try_build();
  550. ERR_FAIL_NULL_V(jolt_shape, false);
  551. Transform3D transform = p_parameters.transform;
  552. JOLT_ENSURE_SCALE_NOT_ZERO(transform, "get_rest_info (maybe from ShapeCast3D?) was passed an invalid transform.");
  553. Vector3 scale = transform.basis.get_scale();
  554. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "get_rest_info (maybe from ShapeCast3D?) was passed an invalid transform.");
  555. transform.basis.orthonormalize();
  556. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  557. const Transform3D transform_com = transform.translated_local(com_scaled);
  558. JPH::CollideShapeSettings settings;
  559. settings.mMaxSeparationDistance = (float)p_parameters.margin;
  560. const Vector3 &base_offset = transform_com.origin;
  561. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  562. JoltQueryCollectorClosest<JPH::CollideShapeCollector> collector;
  563. _collide_shape_queries(jolt_shape, to_jolt(scale), to_jolt_r(transform_com), settings, to_jolt_r(base_offset), collector, query_filter, query_filter, query_filter);
  564. if (!collector.had_hit()) {
  565. return false;
  566. }
  567. const JPH::CollideShapeResult &hit = collector.get_hit();
  568. const JoltReadableBody3D body = space->read_body(hit.mBodyID2);
  569. const JoltObject3D *object = body.as_object();
  570. ERR_FAIL_NULL_V(object, false);
  571. r_info->shape = 0;
  572. if (const JoltShapedObject3D *shaped_object = object->as_shaped()) {
  573. const int shape_index = shaped_object->find_shape_index(hit.mSubShapeID2);
  574. ERR_FAIL_COND_V(shape_index == -1, false);
  575. r_info->shape = shape_index;
  576. }
  577. const Vector3 hit_point = base_offset + to_godot(hit.mContactPointOn2);
  578. r_info->point = hit_point;
  579. r_info->normal = to_godot(-hit.mPenetrationAxis.Normalized());
  580. r_info->rid = object->get_rid();
  581. r_info->collider_id = object->get_instance_id();
  582. r_info->shape = 0;
  583. r_info->linear_velocity = object->get_velocity_at_position(hit_point);
  584. return true;
  585. }
  586. Vector3 JoltPhysicsDirectSpaceState3D::get_closest_point_to_object_volume(RID p_object, Vector3 p_point) const {
  587. ERR_FAIL_COND_V_MSG(space->is_stepping(), Vector3(), "get_closest_point_to_object_volume must not be called while the physics space is being stepped.");
  588. space->try_optimize();
  589. JoltPhysicsServer3D *physics_server = JoltPhysicsServer3D::get_singleton();
  590. JoltObject3D *object = physics_server->get_area(p_object);
  591. if (object == nullptr) {
  592. object = physics_server->get_body(p_object);
  593. }
  594. ERR_FAIL_NULL_V(object, Vector3());
  595. ERR_FAIL_COND_V(object->get_space() != space, Vector3());
  596. const JoltReadableBody3D body = space->read_body(*object);
  597. const JPH::TransformedShape root_shape = body->GetTransformedShape();
  598. JoltQueryCollectorAll<JPH::TransformedShapeCollector, 32> collector;
  599. root_shape.CollectTransformedShapes(body->GetWorldSpaceBounds(), collector);
  600. const JPH::RVec3 point = to_jolt_r(p_point);
  601. float closest_distance_sq = FLT_MAX;
  602. JPH::RVec3 closest_point = JPH::RVec3::sZero();
  603. bool found_point = false;
  604. for (int i = 0; i < collector.get_hit_count(); ++i) {
  605. const JPH::TransformedShape &shape_transformed = collector.get_hit(i);
  606. const JPH::Shape &shape = *shape_transformed.mShape;
  607. if (shape.GetType() != JPH::EShapeType::Convex) {
  608. continue;
  609. }
  610. const JPH::ConvexShape &shape_convex = static_cast<const JPH::ConvexShape &>(shape);
  611. JPH::GJKClosestPoint gjk;
  612. JPH::ConvexShape::SupportBuffer shape_support_buffer;
  613. const JPH::ConvexShape::Support *shape_support = shape_convex.GetSupportFunction(JPH::ConvexShape::ESupportMode::IncludeConvexRadius, shape_support_buffer, shape_transformed.GetShapeScale());
  614. const JPH::Quat &shape_rotation = shape_transformed.mShapeRotation;
  615. const JPH::RVec3 &shape_pos_com = shape_transformed.mShapePositionCOM;
  616. const JPH::RMat44 shape_3x3 = JPH::RMat44::sRotation(shape_rotation);
  617. const JPH::Vec3 shape_com_local = shape.GetCenterOfMass();
  618. const JPH::Vec3 shape_com = shape_3x3.Multiply3x3(shape_com_local);
  619. const JPH::RVec3 shape_pos = shape_pos_com - JPH::RVec3(shape_com);
  620. const JPH::RMat44 shape_4x4 = shape_3x3.PostTranslated(shape_pos);
  621. const JPH::RMat44 shape_4x4_inv = shape_4x4.InversedRotationTranslation();
  622. JPH::PointConvexSupport point_support;
  623. point_support.mPoint = JPH::Vec3(shape_4x4_inv * point);
  624. JPH::Vec3 separating_axis = JPH::Vec3::sAxisX();
  625. JPH::Vec3 point_on_a = JPH::Vec3::sZero();
  626. JPH::Vec3 point_on_b = JPH::Vec3::sZero();
  627. const float distance_sq = gjk.GetClosestPoints(*shape_support, point_support, JPH::cDefaultCollisionTolerance, FLT_MAX, separating_axis, point_on_a, point_on_b);
  628. if (distance_sq == 0.0f) {
  629. closest_point = point;
  630. found_point = true;
  631. break;
  632. }
  633. if (distance_sq < closest_distance_sq) {
  634. closest_distance_sq = distance_sq;
  635. closest_point = shape_4x4 * point_on_a;
  636. found_point = true;
  637. }
  638. }
  639. if (found_point) {
  640. return to_godot(closest_point);
  641. } else {
  642. return to_godot(body->GetPosition());
  643. }
  644. }
  645. bool JoltPhysicsDirectSpaceState3D::body_test_motion(const JoltBody3D &p_body, const PhysicsServer3D::MotionParameters &p_parameters, PhysicsServer3D::MotionResult *r_result) const {
  646. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "body_test_motion (maybe from move_and_slide?) must not be called while the physics space is being stepped.");
  647. const float margin = MAX((float)p_parameters.margin, 0.0001f);
  648. const int max_collisions = MIN(p_parameters.max_collisions, 32);
  649. Transform3D transform = p_parameters.from;
  650. JOLT_ENSURE_SCALE_NOT_ZERO(transform, vformat("body_test_motion (maybe from move_and_slide?) was passed an invalid transform along with body '%s'.", p_body.to_string()));
  651. Vector3 scale = transform.basis.get_scale();
  652. transform.basis.orthonormalize();
  653. space->try_optimize();
  654. Vector3 recovery;
  655. const bool recovered = _body_motion_recover(p_body, transform, margin, p_parameters.exclude_bodies, p_parameters.exclude_objects, recovery);
  656. transform.origin += recovery;
  657. real_t safe_fraction = 1.0;
  658. real_t unsafe_fraction = 1.0;
  659. const bool hit = _body_motion_cast(p_body, transform, scale, p_parameters.motion, p_parameters.collide_separation_ray, p_parameters.exclude_bodies, p_parameters.exclude_objects, safe_fraction, unsafe_fraction);
  660. bool collided = false;
  661. if (hit || (recovered && p_parameters.recovery_as_collision)) {
  662. collided = _body_motion_collide(p_body, transform.translated(p_parameters.motion * unsafe_fraction), p_parameters.motion, margin, max_collisions, p_parameters.exclude_bodies, p_parameters.exclude_objects, r_result);
  663. }
  664. if (r_result == nullptr) {
  665. return collided;
  666. }
  667. if (collided) {
  668. const PhysicsServer3D::MotionCollision &deepest = r_result->collisions[0];
  669. r_result->travel = recovery + p_parameters.motion * safe_fraction;
  670. r_result->remainder = p_parameters.motion - p_parameters.motion * safe_fraction;
  671. r_result->collision_depth = deepest.depth;
  672. r_result->collision_safe_fraction = safe_fraction;
  673. r_result->collision_unsafe_fraction = unsafe_fraction;
  674. } else {
  675. r_result->travel = recovery + p_parameters.motion;
  676. r_result->remainder = Vector3();
  677. r_result->collision_depth = 0.0f;
  678. r_result->collision_safe_fraction = 1.0f;
  679. r_result->collision_unsafe_fraction = 1.0f;
  680. r_result->collision_count = 0;
  681. }
  682. return collided;
  683. }