jolt_physics_direct_space_state_3d.cpp 36 KB

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