space_bullet.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. /*************************************************************************/
  2. /* space_bullet.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  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 "space_bullet.h"
  31. #include "bullet_physics_server.h"
  32. #include "bullet_types_converter.h"
  33. #include "bullet_utilities.h"
  34. #include "constraint_bullet.h"
  35. #include "core/config/project_settings.h"
  36. #include "core/string/ustring.h"
  37. #include "godot_collision_configuration.h"
  38. #include "godot_collision_dispatcher.h"
  39. #include "rigid_body_bullet.h"
  40. #include "servers/physics_server_3d.h"
  41. #include "soft_body_bullet.h"
  42. #include <BulletCollision/BroadphaseCollision/btBroadphaseProxy.h>
  43. #include <BulletCollision/CollisionDispatch/btCollisionObject.h>
  44. #include <BulletCollision/CollisionDispatch/btGhostObject.h>
  45. #include <BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h>
  46. #include <BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h>
  47. #include <BulletCollision/NarrowPhaseCollision/btPointCollector.h>
  48. #include <BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h>
  49. #include <BulletSoftBody/btSoftRigidDynamicsWorld.h>
  50. #include <btBulletDynamicsCommon.h>
  51. #include <assert.h>
  52. /**
  53. @author AndreaCatania
  54. */
  55. BulletPhysicsDirectSpaceState::BulletPhysicsDirectSpaceState(SpaceBullet *p_space) :
  56. PhysicsDirectSpaceState3D(),
  57. space(p_space) {}
  58. int BulletPhysicsDirectSpaceState::intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  59. if (p_result_max <= 0) {
  60. return 0;
  61. }
  62. btVector3 bt_point;
  63. G_TO_B(p_point, bt_point);
  64. btSphereShape sphere_point(0.001f);
  65. btCollisionObject collision_object_point;
  66. collision_object_point.setCollisionShape(&sphere_point);
  67. collision_object_point.setWorldTransform(btTransform(btQuaternion::getIdentity(), bt_point));
  68. // Setup query
  69. GodotAllContactResultCallback btResult(&collision_object_point, r_results, p_result_max, &p_exclude, p_collide_with_bodies, p_collide_with_areas);
  70. btResult.m_collisionFilterGroup = 0;
  71. btResult.m_collisionFilterMask = p_collision_mask;
  72. space->dynamicsWorld->contactTest(&collision_object_point, btResult);
  73. // The results is already populated by GodotAllConvexResultCallback
  74. return btResult.m_count;
  75. }
  76. bool BulletPhysicsDirectSpaceState::intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, bool p_pick_ray) {
  77. btVector3 btVec_from;
  78. btVector3 btVec_to;
  79. G_TO_B(p_from, btVec_from);
  80. G_TO_B(p_to, btVec_to);
  81. // setup query
  82. GodotClosestRayResultCallback btResult(btVec_from, btVec_to, &p_exclude, p_collide_with_bodies, p_collide_with_areas);
  83. btResult.m_collisionFilterGroup = 0;
  84. btResult.m_collisionFilterMask = p_collision_mask;
  85. btResult.m_pickRay = p_pick_ray;
  86. space->dynamicsWorld->rayTest(btVec_from, btVec_to, btResult);
  87. if (btResult.hasHit()) {
  88. B_TO_G(btResult.m_hitPointWorld, r_result.position);
  89. B_TO_G(btResult.m_hitNormalWorld.normalize(), r_result.normal);
  90. CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btResult.m_collisionObject->getUserPointer());
  91. if (gObj) {
  92. r_result.shape = btResult.m_shapeId;
  93. r_result.rid = gObj->get_self();
  94. r_result.collider_id = gObj->get_instance_id();
  95. r_result.collider = r_result.collider_id.is_null() ? nullptr : ObjectDB::get_instance(r_result.collider_id);
  96. } else {
  97. WARN_PRINT("The raycast performed has hit a collision object that is not part of Godot scene, please check it.");
  98. }
  99. return true;
  100. } else {
  101. return false;
  102. }
  103. }
  104. int BulletPhysicsDirectSpaceState::intersect_shape(const RID &p_shape, const Transform &p_xform, float p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  105. if (p_result_max <= 0) {
  106. return 0;
  107. }
  108. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->getornull(p_shape);
  109. ERR_FAIL_COND_V(!shape, 0);
  110. btCollisionShape *btShape = shape->create_bt_shape(p_xform.basis.get_scale_abs(), p_margin);
  111. if (!btShape->isConvex()) {
  112. bulletdelete(btShape);
  113. ERR_PRINT("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  114. return 0;
  115. }
  116. btConvexShape *btConvex = static_cast<btConvexShape *>(btShape);
  117. btTransform bt_xform;
  118. G_TO_B(p_xform, bt_xform);
  119. UNSCALE_BT_BASIS(bt_xform);
  120. btCollisionObject collision_object;
  121. collision_object.setCollisionShape(btConvex);
  122. collision_object.setWorldTransform(bt_xform);
  123. GodotAllContactResultCallback btQuery(&collision_object, r_results, p_result_max, &p_exclude, p_collide_with_bodies, p_collide_with_areas);
  124. btQuery.m_collisionFilterGroup = 0;
  125. btQuery.m_collisionFilterMask = p_collision_mask;
  126. btQuery.m_closestDistanceThreshold = 0;
  127. space->dynamicsWorld->contactTest(&collision_object, btQuery);
  128. bulletdelete(btConvex);
  129. return btQuery.m_count;
  130. }
  131. bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, float p_margin, float &r_closest_safe, float &r_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, ShapeRestInfo *r_info) {
  132. r_closest_safe = 0.0f;
  133. r_closest_unsafe = 0.0f;
  134. btVector3 bt_motion;
  135. G_TO_B(p_motion, bt_motion);
  136. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->getornull(p_shape);
  137. ERR_FAIL_COND_V(!shape, false);
  138. btCollisionShape *btShape = shape->create_bt_shape(p_xform.basis.get_scale(), p_margin);
  139. if (!btShape->isConvex()) {
  140. bulletdelete(btShape);
  141. ERR_PRINT("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  142. return false;
  143. }
  144. btConvexShape *bt_convex_shape = static_cast<btConvexShape *>(btShape);
  145. btTransform bt_xform_from;
  146. G_TO_B(p_xform, bt_xform_from);
  147. UNSCALE_BT_BASIS(bt_xform_from);
  148. btTransform bt_xform_to(bt_xform_from);
  149. bt_xform_to.getOrigin() += bt_motion;
  150. if ((bt_xform_to.getOrigin() - bt_xform_from.getOrigin()).fuzzyZero()) {
  151. bulletdelete(btShape);
  152. return false;
  153. }
  154. GodotClosestConvexResultCallback btResult(bt_xform_from.getOrigin(), bt_xform_to.getOrigin(), &p_exclude, p_collide_with_bodies, p_collide_with_areas);
  155. btResult.m_collisionFilterGroup = 0;
  156. btResult.m_collisionFilterMask = p_collision_mask;
  157. space->dynamicsWorld->convexSweepTest(bt_convex_shape, bt_xform_from, bt_xform_to, btResult, space->dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration);
  158. if (btResult.hasHit()) {
  159. const btScalar l = bt_motion.length();
  160. r_closest_unsafe = btResult.m_closestHitFraction;
  161. r_closest_safe = MAX(r_closest_unsafe - (1 - ((l - 0.01) / l)), 0);
  162. if (r_info) {
  163. if (btCollisionObject::CO_RIGID_BODY == btResult.m_hitCollisionObject->getInternalType()) {
  164. B_TO_G(static_cast<const btRigidBody *>(btResult.m_hitCollisionObject)->getVelocityInLocalPoint(btResult.m_hitPointWorld), r_info->linear_velocity);
  165. }
  166. CollisionObjectBullet *collision_object = static_cast<CollisionObjectBullet *>(btResult.m_hitCollisionObject->getUserPointer());
  167. B_TO_G(btResult.m_hitPointWorld, r_info->point);
  168. B_TO_G(btResult.m_hitNormalWorld, r_info->normal);
  169. r_info->rid = collision_object->get_self();
  170. r_info->collider_id = collision_object->get_instance_id();
  171. r_info->shape = btResult.m_shapeId;
  172. }
  173. } else {
  174. r_closest_safe = 1.0f;
  175. r_closest_unsafe = 1.0f;
  176. }
  177. bulletdelete(bt_convex_shape);
  178. return true; // Mean success
  179. }
  180. /// Returns the list of contacts pairs in this order: Local contact, other body contact
  181. bool BulletPhysicsDirectSpaceState::collide_shape(RID p_shape, const Transform &p_shape_xform, float p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  182. if (p_result_max <= 0) {
  183. return false;
  184. }
  185. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->getornull(p_shape);
  186. ERR_FAIL_COND_V(!shape, false);
  187. btCollisionShape *btShape = shape->create_bt_shape(p_shape_xform.basis.get_scale_abs(), p_margin);
  188. if (!btShape->isConvex()) {
  189. bulletdelete(btShape);
  190. ERR_PRINT("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  191. return false;
  192. }
  193. btConvexShape *btConvex = static_cast<btConvexShape *>(btShape);
  194. btTransform bt_xform;
  195. G_TO_B(p_shape_xform, bt_xform);
  196. UNSCALE_BT_BASIS(bt_xform);
  197. btCollisionObject collision_object;
  198. collision_object.setCollisionShape(btConvex);
  199. collision_object.setWorldTransform(bt_xform);
  200. GodotContactPairContactResultCallback btQuery(&collision_object, r_results, p_result_max, &p_exclude, p_collide_with_bodies, p_collide_with_areas);
  201. btQuery.m_collisionFilterGroup = 0;
  202. btQuery.m_collisionFilterMask = p_collision_mask;
  203. btQuery.m_closestDistanceThreshold = 0;
  204. space->dynamicsWorld->contactTest(&collision_object, btQuery);
  205. r_result_count = btQuery.m_count;
  206. bulletdelete(btConvex);
  207. return btQuery.m_count;
  208. }
  209. bool BulletPhysicsDirectSpaceState::rest_info(RID p_shape, const Transform &p_shape_xform, float p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  210. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->getornull(p_shape);
  211. ERR_FAIL_COND_V(!shape, false);
  212. btCollisionShape *btShape = shape->create_bt_shape(p_shape_xform.basis.get_scale_abs(), p_margin);
  213. if (!btShape->isConvex()) {
  214. bulletdelete(btShape);
  215. ERR_PRINT("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  216. return false;
  217. }
  218. btConvexShape *btConvex = static_cast<btConvexShape *>(btShape);
  219. btTransform bt_xform;
  220. G_TO_B(p_shape_xform, bt_xform);
  221. UNSCALE_BT_BASIS(bt_xform);
  222. btCollisionObject collision_object;
  223. collision_object.setCollisionShape(btConvex);
  224. collision_object.setWorldTransform(bt_xform);
  225. GodotRestInfoContactResultCallback btQuery(&collision_object, r_info, &p_exclude, p_collide_with_bodies, p_collide_with_areas);
  226. btQuery.m_collisionFilterGroup = 0;
  227. btQuery.m_collisionFilterMask = p_collision_mask;
  228. btQuery.m_closestDistanceThreshold = 0;
  229. space->dynamicsWorld->contactTest(&collision_object, btQuery);
  230. bulletdelete(btConvex);
  231. if (btQuery.m_collided) {
  232. if (btCollisionObject::CO_RIGID_BODY == btQuery.m_rest_info_collision_object->getInternalType()) {
  233. B_TO_G(static_cast<const btRigidBody *>(btQuery.m_rest_info_collision_object)->getVelocityInLocalPoint(btQuery.m_rest_info_bt_point), r_info->linear_velocity);
  234. }
  235. B_TO_G(btQuery.m_rest_info_bt_point, r_info->point);
  236. }
  237. return btQuery.m_collided;
  238. }
  239. Vector3 BulletPhysicsDirectSpaceState::get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const {
  240. RigidCollisionObjectBullet *rigid_object = space->get_physics_server()->get_rigid_collision_object(p_object);
  241. ERR_FAIL_COND_V(!rigid_object, Vector3());
  242. btVector3 out_closest_point(0, 0, 0);
  243. btScalar out_distance = 1e20;
  244. btVector3 bt_point;
  245. G_TO_B(p_point, bt_point);
  246. btSphereShape point_shape(0.);
  247. btCollisionShape *shape;
  248. btConvexShape *convex_shape;
  249. btTransform child_transform;
  250. btTransform body_transform(rigid_object->get_bt_collision_object()->getWorldTransform());
  251. btGjkPairDetector::ClosestPointInput input;
  252. input.m_transformA.getBasis().setIdentity();
  253. input.m_transformA.setOrigin(bt_point);
  254. bool shapes_found = false;
  255. for (int i = rigid_object->get_shape_count() - 1; 0 <= i; --i) {
  256. shape = rigid_object->get_bt_shape(i);
  257. if (shape->isConvex()) {
  258. child_transform = rigid_object->get_bt_shape_transform(i);
  259. convex_shape = static_cast<btConvexShape *>(shape);
  260. input.m_transformB = body_transform * child_transform;
  261. btPointCollector result;
  262. btGjkPairDetector gjk_pair_detector(&point_shape, convex_shape, space->gjk_simplex_solver, space->gjk_epa_pen_solver);
  263. gjk_pair_detector.getClosestPoints(input, result, nullptr);
  264. if (out_distance > result.m_distance) {
  265. out_distance = result.m_distance;
  266. out_closest_point = result.m_pointInWorld;
  267. }
  268. }
  269. shapes_found = true;
  270. }
  271. if (shapes_found) {
  272. Vector3 out;
  273. B_TO_G(out_closest_point, out);
  274. return out;
  275. } else {
  276. // no shapes found, use distance to origin.
  277. return rigid_object->get_transform().get_origin();
  278. }
  279. }
  280. SpaceBullet::SpaceBullet() {
  281. create_empty_world(GLOBAL_DEF("physics/3d/active_soft_world", true));
  282. direct_access = memnew(BulletPhysicsDirectSpaceState(this));
  283. }
  284. SpaceBullet::~SpaceBullet() {
  285. memdelete(direct_access);
  286. destroy_world();
  287. }
  288. void SpaceBullet::flush_queries() {
  289. const btCollisionObjectArray &colObjArray = dynamicsWorld->getCollisionObjectArray();
  290. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  291. static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->dispatch_callbacks();
  292. }
  293. }
  294. void SpaceBullet::step(real_t p_delta_time) {
  295. delta_time = p_delta_time;
  296. dynamicsWorld->stepSimulation(p_delta_time, 0, 0);
  297. }
  298. void SpaceBullet::set_param(PhysicsServer3D::AreaParameter p_param, const Variant &p_value) {
  299. assert(dynamicsWorld);
  300. switch (p_param) {
  301. case PhysicsServer3D::AREA_PARAM_GRAVITY:
  302. gravityMagnitude = p_value;
  303. update_gravity();
  304. break;
  305. case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR:
  306. gravityDirection = p_value;
  307. update_gravity();
  308. break;
  309. case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP:
  310. linear_damp = p_value;
  311. break;
  312. case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP:
  313. angular_damp = p_value;
  314. break;
  315. case PhysicsServer3D::AREA_PARAM_PRIORITY:
  316. // Priority is always 0, the lower
  317. break;
  318. case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT:
  319. case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
  320. case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
  321. break;
  322. default:
  323. WARN_PRINT("This set parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  324. break;
  325. }
  326. }
  327. Variant SpaceBullet::get_param(PhysicsServer3D::AreaParameter p_param) {
  328. switch (p_param) {
  329. case PhysicsServer3D::AREA_PARAM_GRAVITY:
  330. return gravityMagnitude;
  331. case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR:
  332. return gravityDirection;
  333. case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP:
  334. return linear_damp;
  335. case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP:
  336. return angular_damp;
  337. case PhysicsServer3D::AREA_PARAM_PRIORITY:
  338. return 0; // Priority is always 0, the lower
  339. case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT:
  340. return false;
  341. case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
  342. return 0;
  343. case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
  344. return 0;
  345. default:
  346. WARN_PRINT("This get parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  347. return Variant();
  348. }
  349. }
  350. void SpaceBullet::set_param(PhysicsServer3D::SpaceParameter p_param, real_t p_value) {
  351. switch (p_param) {
  352. case PhysicsServer3D::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  353. case PhysicsServer3D::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  354. case PhysicsServer3D::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION:
  355. case PhysicsServer3D::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  356. case PhysicsServer3D::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  357. case PhysicsServer3D::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  358. case PhysicsServer3D::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO:
  359. case PhysicsServer3D::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  360. default:
  361. WARN_PRINT("This set parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  362. break;
  363. }
  364. }
  365. real_t SpaceBullet::get_param(PhysicsServer3D::SpaceParameter p_param) {
  366. switch (p_param) {
  367. case PhysicsServer3D::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  368. case PhysicsServer3D::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  369. case PhysicsServer3D::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION:
  370. case PhysicsServer3D::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  371. case PhysicsServer3D::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  372. case PhysicsServer3D::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  373. case PhysicsServer3D::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO:
  374. case PhysicsServer3D::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  375. default:
  376. WARN_PRINT("The SpaceBullet doesn't support this get parameter (" + itos(p_param) + "), 0 is returned.");
  377. return 0.f;
  378. }
  379. }
  380. void SpaceBullet::add_area(AreaBullet *p_area) {
  381. areas.push_back(p_area);
  382. dynamicsWorld->addCollisionObject(p_area->get_bt_ghost(), p_area->get_collision_layer(), p_area->get_collision_mask());
  383. }
  384. void SpaceBullet::remove_area(AreaBullet *p_area) {
  385. areas.erase(p_area);
  386. dynamicsWorld->removeCollisionObject(p_area->get_bt_ghost());
  387. }
  388. void SpaceBullet::reload_collision_filters(AreaBullet *p_area) {
  389. btGhostObject *ghost_object = p_area->get_bt_ghost();
  390. btBroadphaseProxy *ghost_proxy = ghost_object->getBroadphaseHandle();
  391. ghost_proxy->m_collisionFilterGroup = p_area->get_collision_layer();
  392. ghost_proxy->m_collisionFilterMask = p_area->get_collision_mask();
  393. dynamicsWorld->refreshBroadphaseProxy(ghost_object);
  394. }
  395. void SpaceBullet::add_rigid_body(RigidBodyBullet *p_body) {
  396. if (p_body->is_static()) {
  397. dynamicsWorld->addCollisionObject(p_body->get_bt_rigid_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  398. } else {
  399. dynamicsWorld->addRigidBody(p_body->get_bt_rigid_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  400. p_body->scratch_space_override_modificator();
  401. }
  402. }
  403. void SpaceBullet::remove_rigid_body(RigidBodyBullet *p_body) {
  404. btRigidBody *btBody = p_body->get_bt_rigid_body();
  405. int constraints = btBody->getNumConstraintRefs();
  406. if (constraints > 0) {
  407. ERR_PRINT("A body connected to joints was removed.");
  408. for (int i = 0; i < constraints; i++) {
  409. dynamicsWorld->removeConstraint(btBody->getConstraintRef(i));
  410. }
  411. }
  412. if (p_body->is_static()) {
  413. dynamicsWorld->removeCollisionObject(btBody);
  414. } else {
  415. dynamicsWorld->removeRigidBody(btBody);
  416. }
  417. }
  418. void SpaceBullet::reload_collision_filters(RigidBodyBullet *p_body) {
  419. btRigidBody *rigid_body = p_body->get_bt_rigid_body();
  420. btBroadphaseProxy *body_proxy = rigid_body->getBroadphaseProxy();
  421. body_proxy->m_collisionFilterGroup = p_body->get_collision_layer();
  422. body_proxy->m_collisionFilterMask = p_body->get_collision_mask();
  423. dynamicsWorld->refreshBroadphaseProxy(rigid_body);
  424. }
  425. void SpaceBullet::add_soft_body(SoftBodyBullet *p_body) {
  426. if (is_using_soft_world()) {
  427. if (p_body->get_bt_soft_body()) {
  428. p_body->get_bt_soft_body()->m_worldInfo = get_soft_body_world_info();
  429. static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->addSoftBody(p_body->get_bt_soft_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  430. }
  431. } else {
  432. ERR_PRINT("This soft body can't be added to non soft world");
  433. }
  434. }
  435. void SpaceBullet::remove_soft_body(SoftBodyBullet *p_body) {
  436. if (is_using_soft_world()) {
  437. if (p_body->get_bt_soft_body()) {
  438. static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->removeSoftBody(p_body->get_bt_soft_body());
  439. p_body->get_bt_soft_body()->m_worldInfo = nullptr;
  440. }
  441. }
  442. }
  443. void SpaceBullet::reload_collision_filters(SoftBodyBullet *p_body) {
  444. // This is necessary to change collision filter
  445. remove_soft_body(p_body);
  446. add_soft_body(p_body);
  447. }
  448. void SpaceBullet::add_constraint(ConstraintBullet *p_constraint, bool disableCollisionsBetweenLinkedBodies) {
  449. p_constraint->set_space(this);
  450. dynamicsWorld->addConstraint(p_constraint->get_bt_constraint(), disableCollisionsBetweenLinkedBodies);
  451. }
  452. void SpaceBullet::remove_constraint(ConstraintBullet *p_constraint) {
  453. dynamicsWorld->removeConstraint(p_constraint->get_bt_constraint());
  454. }
  455. int SpaceBullet::get_num_collision_objects() const {
  456. return dynamicsWorld->getNumCollisionObjects();
  457. }
  458. void SpaceBullet::remove_all_collision_objects() {
  459. for (int i = dynamicsWorld->getNumCollisionObjects() - 1; 0 <= i; --i) {
  460. btCollisionObject *btObj = dynamicsWorld->getCollisionObjectArray()[i];
  461. CollisionObjectBullet *colObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer());
  462. colObj->set_space(nullptr);
  463. }
  464. }
  465. void onBulletTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) {
  466. const btCollisionObjectArray &colObjArray = p_dynamicsWorld->getCollisionObjectArray();
  467. // Notify all Collision objects the collision checker is started
  468. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  469. static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->on_collision_checker_start();
  470. }
  471. SpaceBullet *sb = static_cast<SpaceBullet *>(p_dynamicsWorld->getWorldUserInfo());
  472. sb->check_ghost_overlaps();
  473. sb->check_body_collision();
  474. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  475. static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->on_collision_checker_end();
  476. }
  477. }
  478. BulletPhysicsDirectSpaceState *SpaceBullet::get_direct_state() {
  479. return direct_access;
  480. }
  481. btScalar calculateGodotCombinedRestitution(const btCollisionObject *body0, const btCollisionObject *body1) {
  482. return CLAMP(body0->getRestitution() + body1->getRestitution(), 0, 1);
  483. }
  484. btScalar calculateGodotCombinedFriction(const btCollisionObject *body0, const btCollisionObject *body1) {
  485. return ABS(MIN(body0->getFriction(), body1->getFriction()));
  486. }
  487. void SpaceBullet::create_empty_world(bool p_create_soft_world) {
  488. gjk_epa_pen_solver = bulletnew(btGjkEpaPenetrationDepthSolver);
  489. gjk_simplex_solver = bulletnew(btVoronoiSimplexSolver);
  490. void *world_mem;
  491. if (p_create_soft_world) {
  492. world_mem = malloc(sizeof(btSoftRigidDynamicsWorld));
  493. } else {
  494. world_mem = malloc(sizeof(btDiscreteDynamicsWorld));
  495. }
  496. ERR_FAIL_COND_MSG(!world_mem, "Out of memory.");
  497. if (p_create_soft_world) {
  498. collisionConfiguration = bulletnew(GodotSoftCollisionConfiguration(static_cast<btDiscreteDynamicsWorld *>(world_mem)));
  499. } else {
  500. collisionConfiguration = bulletnew(GodotCollisionConfiguration(static_cast<btDiscreteDynamicsWorld *>(world_mem)));
  501. }
  502. dispatcher = bulletnew(GodotCollisionDispatcher(collisionConfiguration));
  503. broadphase = bulletnew(btDbvtBroadphase);
  504. solver = bulletnew(btSequentialImpulseConstraintSolver);
  505. if (p_create_soft_world) {
  506. dynamicsWorld = new (world_mem) btSoftRigidDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  507. soft_body_world_info = bulletnew(btSoftBodyWorldInfo);
  508. } else {
  509. dynamicsWorld = new (world_mem) btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  510. }
  511. ghostPairCallback = bulletnew(btGhostPairCallback);
  512. godotFilterCallback = bulletnew(GodotFilterCallback);
  513. gCalculateCombinedRestitutionCallback = &calculateGodotCombinedRestitution;
  514. gCalculateCombinedFrictionCallback = &calculateGodotCombinedFriction;
  515. gContactAddedCallback = &godotContactAddedCallback;
  516. dynamicsWorld->setWorldUserInfo(this);
  517. dynamicsWorld->setInternalTickCallback(onBulletTickCallback, this, false);
  518. dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(ghostPairCallback); // Setup ghost check
  519. dynamicsWorld->getPairCache()->setOverlapFilterCallback(godotFilterCallback);
  520. if (soft_body_world_info) {
  521. soft_body_world_info->m_broadphase = broadphase;
  522. soft_body_world_info->m_dispatcher = dispatcher;
  523. soft_body_world_info->m_sparsesdf.Initialize();
  524. }
  525. update_gravity();
  526. }
  527. void SpaceBullet::destroy_world() {
  528. /// The world elements (like: Collision Objects, Constraints, Shapes) are managed by godot
  529. dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(nullptr);
  530. dynamicsWorld->getPairCache()->setOverlapFilterCallback(nullptr);
  531. bulletdelete(ghostPairCallback);
  532. bulletdelete(godotFilterCallback);
  533. // Deallocate world
  534. dynamicsWorld->~btDiscreteDynamicsWorld();
  535. free(dynamicsWorld);
  536. dynamicsWorld = nullptr;
  537. bulletdelete(solver);
  538. bulletdelete(broadphase);
  539. bulletdelete(dispatcher);
  540. bulletdelete(collisionConfiguration);
  541. bulletdelete(soft_body_world_info);
  542. bulletdelete(gjk_simplex_solver);
  543. bulletdelete(gjk_epa_pen_solver);
  544. }
  545. void SpaceBullet::check_ghost_overlaps() {
  546. /// Algorithm support variables
  547. btCollisionShape *other_body_shape;
  548. btConvexShape *area_shape;
  549. btGjkPairDetector::ClosestPointInput gjk_input;
  550. AreaBullet *area;
  551. int x(-1), i(-1), y(-1), z(-1), indexOverlap(-1);
  552. /// For each areas
  553. for (x = areas.size() - 1; 0 <= x; --x) {
  554. area = areas[x];
  555. btVector3 area_scale(area->get_bt_body_scale());
  556. if (!area->is_monitoring()) {
  557. continue;
  558. }
  559. /// 1. Reset all states
  560. for (i = area->overlappingObjects.size() - 1; 0 <= i; --i) {
  561. AreaBullet::OverlappingObjectData &otherObj = area->overlappingObjects.write[i];
  562. // This check prevent the overwrite of ENTER state
  563. // if this function is called more times before dispatchCallbacks
  564. if (otherObj.state != AreaBullet::OVERLAP_STATE_ENTER) {
  565. otherObj.state = AreaBullet::OVERLAP_STATE_DIRTY;
  566. }
  567. }
  568. /// 2. Check all overlapping objects using GJK
  569. const btAlignedObjectArray<btCollisionObject *> ghostOverlaps = area->get_bt_ghost()->getOverlappingPairs();
  570. // For each overlapping
  571. for (i = ghostOverlaps.size() - 1; 0 <= i; --i) {
  572. bool hasOverlap = false;
  573. btCollisionObject *overlapped_bt_co = ghostOverlaps[i];
  574. RigidCollisionObjectBullet *otherObject = static_cast<RigidCollisionObjectBullet *>(overlapped_bt_co->getUserPointer());
  575. btVector3 other_body_scale(otherObject->get_bt_body_scale());
  576. if (!area->is_transform_changed() && !otherObject->is_transform_changed()) {
  577. hasOverlap = -1 != area->find_overlapping_object(otherObject);
  578. goto collision_found;
  579. }
  580. if (overlapped_bt_co->getUserIndex() == CollisionObjectBullet::TYPE_AREA) {
  581. if (!static_cast<AreaBullet *>(overlapped_bt_co->getUserPointer())->is_monitorable()) {
  582. continue;
  583. }
  584. } else if (overlapped_bt_co->getUserIndex() != CollisionObjectBullet::TYPE_RIGID_BODY) {
  585. continue;
  586. }
  587. // For each area shape
  588. for (y = area->get_shape_count() - 1; 0 <= y; --y) {
  589. if (!area->get_bt_shape(y)->isConvex()) {
  590. continue;
  591. }
  592. btTransform area_shape_treansform(area->get_bt_shape_transform(y));
  593. area_shape_treansform.getOrigin() *= area_scale;
  594. gjk_input.m_transformA =
  595. area->get_transform__bullet() *
  596. area_shape_treansform;
  597. area_shape = static_cast<btConvexShape *>(area->get_bt_shape(y));
  598. // For each other object shape
  599. for (z = otherObject->get_shape_count() - 1; 0 <= z; --z) {
  600. other_body_shape = static_cast<btCollisionShape *>(otherObject->get_bt_shape(z));
  601. btTransform other_shape_transform(otherObject->get_bt_shape_transform(z));
  602. other_shape_transform.getOrigin() *= other_body_scale;
  603. gjk_input.m_transformB =
  604. otherObject->get_transform__bullet() *
  605. other_shape_transform;
  606. if (other_body_shape->isConvex()) {
  607. btPointCollector result;
  608. btGjkPairDetector gjk_pair_detector(
  609. area_shape,
  610. static_cast<btConvexShape *>(other_body_shape),
  611. gjk_simplex_solver,
  612. gjk_epa_pen_solver);
  613. gjk_pair_detector.getClosestPoints(gjk_input, result, nullptr);
  614. if (0 >= result.m_distance) {
  615. hasOverlap = true;
  616. goto collision_found;
  617. }
  618. } else {
  619. btCollisionObjectWrapper obA(nullptr, area_shape, area->get_bt_ghost(), gjk_input.m_transformA, -1, y);
  620. btCollisionObjectWrapper obB(nullptr, other_body_shape, otherObject->get_bt_collision_object(), gjk_input.m_transformB, -1, z);
  621. btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, nullptr, BT_CONTACT_POINT_ALGORITHMS);
  622. if (!algorithm) {
  623. continue;
  624. }
  625. GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB);
  626. algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult);
  627. algorithm->~btCollisionAlgorithm();
  628. dispatcher->freeCollisionAlgorithm(algorithm);
  629. if (contactPointResult.hasHit()) {
  630. hasOverlap = true;
  631. goto collision_found;
  632. }
  633. }
  634. } // ~For each other object shape
  635. } // ~For each area shape
  636. collision_found:
  637. if (!hasOverlap) {
  638. continue;
  639. }
  640. indexOverlap = area->find_overlapping_object(otherObject);
  641. if (-1 == indexOverlap) {
  642. // Not found
  643. area->add_overlap(otherObject);
  644. } else {
  645. // Found
  646. area->put_overlap_as_inside(indexOverlap);
  647. }
  648. }
  649. /// 3. Remove not overlapping
  650. for (i = area->overlappingObjects.size() - 1; 0 <= i; --i) {
  651. // If the overlap has DIRTY state it means that it's no more overlapping
  652. if (area->overlappingObjects[i].state == AreaBullet::OVERLAP_STATE_DIRTY) {
  653. area->put_overlap_as_exit(i);
  654. }
  655. }
  656. }
  657. }
  658. void SpaceBullet::check_body_collision() {
  659. #ifdef DEBUG_ENABLED
  660. reset_debug_contact_count();
  661. #endif
  662. const int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
  663. for (int i = 0; i < numManifolds; ++i) {
  664. btPersistentManifold *contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
  665. // I know this static cast is a bit risky. But I'm checking its type just after it.
  666. // This allow me to avoid a lot of other cast and checks
  667. RigidBodyBullet *bodyA = static_cast<RigidBodyBullet *>(contactManifold->getBody0()->getUserPointer());
  668. RigidBodyBullet *bodyB = static_cast<RigidBodyBullet *>(contactManifold->getBody1()->getUserPointer());
  669. if (CollisionObjectBullet::TYPE_RIGID_BODY == bodyA->getType() && CollisionObjectBullet::TYPE_RIGID_BODY == bodyB->getType()) {
  670. if (!bodyA->can_add_collision() && !bodyB->can_add_collision()) {
  671. continue;
  672. }
  673. const int numContacts = contactManifold->getNumContacts();
  674. /// Since I don't need report all contacts for these objects,
  675. /// So report only the first
  676. #define REPORT_ALL_CONTACTS 0
  677. #if REPORT_ALL_CONTACTS
  678. for (int j = 0; j < numContacts; j++) {
  679. btManifoldPoint &pt = contactManifold->getContactPoint(j);
  680. #else
  681. if (numContacts) {
  682. btManifoldPoint &pt = contactManifold->getContactPoint(0);
  683. #endif
  684. if (
  685. pt.getDistance() <= 0.0 ||
  686. bodyA->was_colliding(bodyB) ||
  687. bodyB->was_colliding(bodyA)) {
  688. Vector3 collisionWorldPosition;
  689. Vector3 collisionLocalPosition;
  690. Vector3 normalOnB;
  691. float appliedImpulse = pt.m_appliedImpulse;
  692. B_TO_G(pt.m_normalWorldOnB, normalOnB);
  693. // The pt.m_index only contains the shape index when more than one collision shape is used
  694. // and only if the collision shape is not a concave collision shape.
  695. // A value of -1 in pt.m_partId indicates the pt.m_index is a shape index.
  696. int shape_index_a = 0;
  697. if (bodyA->get_shape_count() > 1 && pt.m_partId0 == -1) {
  698. shape_index_a = pt.m_index0;
  699. }
  700. int shape_index_b = 0;
  701. if (bodyB->get_shape_count() > 1 && pt.m_partId1 == -1) {
  702. shape_index_b = pt.m_index1;
  703. }
  704. if (bodyA->can_add_collision()) {
  705. B_TO_G(pt.getPositionWorldOnB(), collisionWorldPosition);
  706. /// pt.m_localPointB Doesn't report the exact point in local space
  707. B_TO_G(pt.getPositionWorldOnB() - contactManifold->getBody1()->getWorldTransform().getOrigin(), collisionLocalPosition);
  708. bodyA->add_collision_object(bodyB, collisionWorldPosition, collisionLocalPosition, normalOnB, appliedImpulse, shape_index_b, shape_index_a);
  709. }
  710. if (bodyB->can_add_collision()) {
  711. B_TO_G(pt.getPositionWorldOnA(), collisionWorldPosition);
  712. /// pt.m_localPointA Doesn't report the exact point in local space
  713. B_TO_G(pt.getPositionWorldOnA() - contactManifold->getBody0()->getWorldTransform().getOrigin(), collisionLocalPosition);
  714. bodyB->add_collision_object(bodyA, collisionWorldPosition, collisionLocalPosition, normalOnB * -1, appliedImpulse * -1, shape_index_a, shape_index_b);
  715. }
  716. #ifdef DEBUG_ENABLED
  717. if (is_debugging_contacts()) {
  718. add_debug_contact(collisionWorldPosition);
  719. }
  720. #endif
  721. }
  722. }
  723. }
  724. }
  725. }
  726. void SpaceBullet::update_gravity() {
  727. btVector3 btGravity;
  728. G_TO_B(gravityDirection * gravityMagnitude, btGravity);
  729. //dynamicsWorld->setGravity(btGravity);
  730. dynamicsWorld->setGravity(btVector3(0, 0, 0));
  731. if (soft_body_world_info) {
  732. soft_body_world_info->m_gravity = btGravity;
  733. }
  734. }
  735. /// IMPORTANT: Please don't turn it ON this is not managed correctly!!
  736. /// I'm leaving this here just for future tests.
  737. /// Debug motion and normal vector drawing
  738. #define debug_test_motion 0
  739. #define RECOVERING_MOVEMENT_SCALE 0.4
  740. #define RECOVERING_MOVEMENT_CYCLES 4
  741. #if debug_test_motion
  742. #include "scene/3d/immediate_geometry.h"
  743. static ImmediateGeometry3D *motionVec(nullptr);
  744. static ImmediateGeometry3D *normalLine(nullptr);
  745. static Ref<StandardMaterial3D> red_mat;
  746. static Ref<StandardMaterial3D> blue_mat;
  747. #endif
  748. bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, PhysicsServer3D::MotionResult *r_result, bool p_exclude_raycast_shapes) {
  749. #if debug_test_motion
  750. /// Yes I know this is not good, but I've used it as fast debugging hack.
  751. /// I'm leaving it here just for speedup the other eventual debugs
  752. if (!normalLine) {
  753. motionVec = memnew(ImmediateGeometry3D);
  754. normalLine = memnew(ImmediateGeometry3D);
  755. SceneTree::get_singleton()->get_current_scene()->add_child(motionVec);
  756. SceneTree::get_singleton()->get_current_scene()->add_child(normalLine);
  757. motionVec->set_as_top_level(true);
  758. normalLine->set_as_top_level(true);
  759. red_mat = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
  760. red_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  761. red_mat->set_line_width(20.0);
  762. red_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  763. red_mat->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  764. red_mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  765. red_mat->set_albedo(Color(1, 0, 0, 1));
  766. motionVec->set_material_override(red_mat);
  767. blue_mat = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
  768. blue_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  769. blue_mat->set_line_width(20.0);
  770. blue_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  771. blue_mat->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  772. blue_mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  773. blue_mat->set_albedo(Color(0, 0, 1, 1));
  774. normalLine->set_material_override(blue_mat);
  775. }
  776. #endif
  777. btTransform body_transform;
  778. G_TO_B(p_from, body_transform);
  779. UNSCALE_BT_BASIS(body_transform);
  780. btVector3 initial_recover_motion(0, 0, 0);
  781. { /// Phase one - multi shapes depenetration using margin
  782. for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) {
  783. if (!recover_from_penetration(p_body, body_transform, RECOVERING_MOVEMENT_SCALE, p_infinite_inertia, initial_recover_motion)) {
  784. break;
  785. }
  786. }
  787. // Add recover movement in order to make it safe
  788. body_transform.getOrigin() += initial_recover_motion;
  789. }
  790. btVector3 motion;
  791. G_TO_B(p_motion, motion);
  792. {
  793. // Phase two - sweep test, from a secure position without margin
  794. const int shape_count(p_body->get_shape_count());
  795. #if debug_test_motion
  796. Vector3 sup_line;
  797. B_TO_G(body_safe_position.getOrigin(), sup_line);
  798. motionVec->clear();
  799. motionVec->begin(Mesh::PRIMITIVE_LINES, nullptr);
  800. motionVec->add_vertex(sup_line);
  801. motionVec->add_vertex(sup_line + p_motion * 10);
  802. motionVec->end();
  803. #endif
  804. for (int shIndex = 0; shIndex < shape_count; ++shIndex) {
  805. if (p_body->is_shape_disabled(shIndex)) {
  806. continue;
  807. }
  808. if (!p_body->get_bt_shape(shIndex)->isConvex()) {
  809. // Skip no convex shape
  810. continue;
  811. }
  812. if (p_exclude_raycast_shapes && p_body->get_bt_shape(shIndex)->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) {
  813. // Skip rayshape in order to implement custom separation process
  814. continue;
  815. }
  816. btConvexShape *convex_shape_test(static_cast<btConvexShape *>(p_body->get_bt_shape(shIndex)));
  817. btTransform shape_world_from = body_transform * p_body->get_kinematic_utilities()->shapes[shIndex].transform;
  818. btTransform shape_world_to(shape_world_from);
  819. shape_world_to.getOrigin() += motion;
  820. if ((shape_world_to.getOrigin() - shape_world_from.getOrigin()).fuzzyZero()) {
  821. motion = btVector3(0, 0, 0);
  822. break;
  823. }
  824. GodotKinClosestConvexResultCallback btResult(shape_world_from.getOrigin(), shape_world_to.getOrigin(), p_body, p_infinite_inertia);
  825. btResult.m_collisionFilterGroup = p_body->get_collision_layer();
  826. btResult.m_collisionFilterMask = p_body->get_collision_mask();
  827. dynamicsWorld->convexSweepTest(convex_shape_test, shape_world_from, shape_world_to, btResult, dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration);
  828. if (btResult.hasHit()) {
  829. /// Since for each sweep test I fix the motion of new shapes in base the recover result,
  830. /// if another shape will hit something it means that has a deepest penetration respect the previous shape
  831. motion *= btResult.m_closestHitFraction;
  832. }
  833. }
  834. body_transform.getOrigin() += motion;
  835. }
  836. bool has_penetration = false;
  837. { /// Phase three - contact test with margin
  838. btVector3 __rec(0, 0, 0);
  839. RecoverResult r_recover_result;
  840. has_penetration = recover_from_penetration(p_body, body_transform, 1, p_infinite_inertia, __rec, &r_recover_result);
  841. // Parse results
  842. if (r_result) {
  843. B_TO_G(motion + initial_recover_motion + __rec, r_result->motion);
  844. if (has_penetration) {
  845. const btRigidBody *btRigid = static_cast<const btRigidBody *>(r_recover_result.other_collision_object);
  846. CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(btRigid->getUserPointer());
  847. B_TO_G(motion, r_result->remainder); // is the remaining movements
  848. r_result->remainder = p_motion - r_result->remainder;
  849. B_TO_G(r_recover_result.pointWorld, r_result->collision_point);
  850. B_TO_G(r_recover_result.normal, r_result->collision_normal);
  851. B_TO_G(btRigid->getVelocityInLocalPoint(r_recover_result.pointWorld - btRigid->getWorldTransform().getOrigin()), r_result->collider_velocity); // It calculates velocity at point and assign it using special function Bullet_to_Godot
  852. r_result->collider = collisionObject->get_self();
  853. r_result->collider_id = collisionObject->get_instance_id();
  854. r_result->collider_shape = r_recover_result.other_compound_shape_index;
  855. r_result->collision_local_shape = r_recover_result.local_shape_most_recovered;
  856. #if debug_test_motion
  857. Vector3 sup_line2;
  858. B_TO_G(motion, sup_line2);
  859. normalLine->clear();
  860. normalLine->begin(Mesh::PRIMITIVE_LINES, nullptr);
  861. normalLine->add_vertex(r_result->collision_point);
  862. normalLine->add_vertex(r_result->collision_point + r_result->collision_normal * 10);
  863. normalLine->end();
  864. #endif
  865. } else {
  866. r_result->remainder = Vector3();
  867. }
  868. }
  869. }
  870. return has_penetration;
  871. }
  872. int SpaceBullet::test_ray_separation(RigidBodyBullet *p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, PhysicsServer3D::SeparationResult *r_results, int p_result_max, float p_margin) {
  873. btTransform body_transform;
  874. G_TO_B(p_transform, body_transform);
  875. UNSCALE_BT_BASIS(body_transform);
  876. btVector3 recover_motion(0, 0, 0);
  877. int rays_found = 0;
  878. int rays_found_this_round = 0;
  879. for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) {
  880. PhysicsServer3D::SeparationResult *next_results = &r_results[rays_found];
  881. rays_found_this_round = recover_from_penetration_ray(p_body, body_transform, RECOVERING_MOVEMENT_SCALE, p_infinite_inertia, p_result_max - rays_found, recover_motion, next_results);
  882. rays_found += rays_found_this_round;
  883. if (rays_found_this_round == 0) {
  884. body_transform.getOrigin() += recover_motion;
  885. break;
  886. }
  887. }
  888. B_TO_G(recover_motion, r_recover_motion);
  889. return rays_found;
  890. }
  891. struct RecoverPenetrationBroadPhaseCallback : public btBroadphaseAabbCallback {
  892. private:
  893. btDbvtVolume bounds;
  894. const btCollisionObject *self_collision_object;
  895. uint32_t collision_layer;
  896. uint32_t collision_mask;
  897. struct CompoundLeafCallback : btDbvt::ICollide {
  898. private:
  899. RecoverPenetrationBroadPhaseCallback *parent_callback;
  900. btCollisionObject *collision_object;
  901. public:
  902. CompoundLeafCallback(RecoverPenetrationBroadPhaseCallback *p_parent_callback, btCollisionObject *p_collision_object) :
  903. parent_callback(p_parent_callback),
  904. collision_object(p_collision_object) {
  905. }
  906. void Process(const btDbvtNode *leaf) {
  907. BroadphaseResult result;
  908. result.collision_object = collision_object;
  909. result.compound_child_index = leaf->dataAsInt;
  910. parent_callback->results.push_back(result);
  911. }
  912. };
  913. public:
  914. struct BroadphaseResult {
  915. btCollisionObject *collision_object;
  916. int compound_child_index;
  917. };
  918. Vector<BroadphaseResult> results;
  919. public:
  920. RecoverPenetrationBroadPhaseCallback(const btCollisionObject *p_self_collision_object, uint32_t p_collision_layer, uint32_t p_collision_mask, btVector3 p_aabb_min, btVector3 p_aabb_max) :
  921. self_collision_object(p_self_collision_object),
  922. collision_layer(p_collision_layer),
  923. collision_mask(p_collision_mask) {
  924. bounds = btDbvtVolume::FromMM(p_aabb_min, p_aabb_max);
  925. }
  926. virtual ~RecoverPenetrationBroadPhaseCallback() {}
  927. virtual bool process(const btBroadphaseProxy *proxy) {
  928. btCollisionObject *co = static_cast<btCollisionObject *>(proxy->m_clientObject);
  929. if (co->getInternalType() <= btCollisionObject::CO_RIGID_BODY) {
  930. if (self_collision_object != proxy->m_clientObject && GodotFilterCallback::test_collision_filters(collision_layer, collision_mask, proxy->m_collisionFilterGroup, proxy->m_collisionFilterMask)) {
  931. if (co->getCollisionShape()->isCompound()) {
  932. const btCompoundShape *cs = static_cast<btCompoundShape *>(co->getCollisionShape());
  933. if (cs->getNumChildShapes() > 1) {
  934. const btDbvt *tree = cs->getDynamicAabbTree();
  935. ERR_FAIL_COND_V(tree == nullptr, true);
  936. // Transform bounds into compound shape local space
  937. const btTransform other_in_compound_space = co->getWorldTransform().inverse();
  938. const btMatrix3x3 abs_b = other_in_compound_space.getBasis().absolute();
  939. const btVector3 local_center = other_in_compound_space(bounds.Center());
  940. const btVector3 local_extent = bounds.Extents().dot3(abs_b[0], abs_b[1], abs_b[2]);
  941. const btVector3 local_aabb_min = local_center - local_extent;
  942. const btVector3 local_aabb_max = local_center + local_extent;
  943. const btDbvtVolume local_bounds = btDbvtVolume::FromMM(local_aabb_min, local_aabb_max);
  944. // Test collision against compound child shapes using its AABB tree
  945. CompoundLeafCallback compound_leaf_callback(this, co);
  946. tree->collideTV(tree->m_root, local_bounds, compound_leaf_callback);
  947. } else {
  948. // If there's only a single child shape then there's no need to search any more, we know which child overlaps
  949. BroadphaseResult result;
  950. result.collision_object = co;
  951. result.compound_child_index = 0;
  952. results.push_back(result);
  953. }
  954. } else {
  955. BroadphaseResult result;
  956. result.collision_object = co;
  957. result.compound_child_index = -1;
  958. results.push_back(result);
  959. }
  960. return true;
  961. }
  962. }
  963. return false;
  964. }
  965. };
  966. bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) {
  967. // Calculate the cumulative AABB of all shapes of the kinematic body
  968. btVector3 aabb_min, aabb_max;
  969. bool shapes_found = false;
  970. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  971. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  972. if (!kin_shape.is_active()) {
  973. continue;
  974. }
  975. if (kin_shape.shape->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) {
  976. // Skip rayshape in order to implement custom separation process
  977. continue;
  978. }
  979. btTransform shape_transform = p_body_position * kin_shape.transform;
  980. shape_transform.getOrigin() += r_delta_recover_movement;
  981. btVector3 shape_aabb_min, shape_aabb_max;
  982. kin_shape.shape->getAabb(shape_transform, shape_aabb_min, shape_aabb_max);
  983. if (!shapes_found) {
  984. aabb_min = shape_aabb_min;
  985. aabb_max = shape_aabb_max;
  986. shapes_found = true;
  987. } else {
  988. aabb_min.setX((aabb_min.x() < shape_aabb_min.x()) ? aabb_min.x() : shape_aabb_min.x());
  989. aabb_min.setY((aabb_min.y() < shape_aabb_min.y()) ? aabb_min.y() : shape_aabb_min.y());
  990. aabb_min.setZ((aabb_min.z() < shape_aabb_min.z()) ? aabb_min.z() : shape_aabb_min.z());
  991. aabb_max.setX((aabb_max.x() > shape_aabb_max.x()) ? aabb_max.x() : shape_aabb_max.x());
  992. aabb_max.setY((aabb_max.y() > shape_aabb_max.y()) ? aabb_max.y() : shape_aabb_max.y());
  993. aabb_max.setZ((aabb_max.z() > shape_aabb_max.z()) ? aabb_max.z() : shape_aabb_max.z());
  994. }
  995. }
  996. // If there are no shapes then there is no penetration either
  997. if (!shapes_found) {
  998. return false;
  999. }
  1000. // Perform broadphase test
  1001. RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask(), aabb_min, aabb_max);
  1002. dynamicsWorld->getBroadphase()->aabbTest(aabb_min, aabb_max, recover_broad_result);
  1003. bool penetration = false;
  1004. // Perform narrowphase per shape
  1005. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  1006. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  1007. if (!kin_shape.is_active()) {
  1008. continue;
  1009. }
  1010. if (kin_shape.shape->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) {
  1011. // Skip rayshape in order to implement custom separation process
  1012. continue;
  1013. }
  1014. btTransform shape_transform = p_body_position * kin_shape.transform;
  1015. shape_transform.getOrigin() += r_delta_recover_movement;
  1016. for (int i = recover_broad_result.results.size() - 1; 0 <= i; --i) {
  1017. btCollisionObject *otherObject = recover_broad_result.results[i].collision_object;
  1018. if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) {
  1019. otherObject->activate(); // Force activation of hitten rigid, soft body
  1020. continue;
  1021. } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object())) {
  1022. continue;
  1023. }
  1024. if (otherObject->getCollisionShape()->isCompound()) {
  1025. const btCompoundShape *cs = static_cast<const btCompoundShape *>(otherObject->getCollisionShape());
  1026. int shape_idx = recover_broad_result.results[i].compound_child_index;
  1027. ERR_FAIL_COND_V(shape_idx < 0 || shape_idx >= cs->getNumChildShapes(), false);
  1028. if (cs->getChildShape(shape_idx)->isConvex()) {
  1029. if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(cs->getChildShape(shape_idx)), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
  1030. penetration = true;
  1031. }
  1032. } else {
  1033. if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(shape_idx), p_body->get_bt_collision_object(), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
  1034. penetration = true;
  1035. }
  1036. }
  1037. } else if (otherObject->getCollisionShape()->isConvex()) { /// Execute GJK test against object shape
  1038. if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(otherObject->getCollisionShape()), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
  1039. penetration = true;
  1040. }
  1041. } else {
  1042. if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
  1043. penetration = true;
  1044. }
  1045. }
  1046. }
  1047. }
  1048. return penetration;
  1049. }
  1050. bool SpaceBullet::RFP_convex_convex_test(const btConvexShape *p_shapeA, const btConvexShape *p_shapeB, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) {
  1051. // Initialize GJK input
  1052. btGjkPairDetector::ClosestPointInput gjk_input;
  1053. gjk_input.m_transformA = p_transformA;
  1054. gjk_input.m_transformB = p_transformB;
  1055. // Perform GJK test
  1056. btPointCollector result;
  1057. btGjkPairDetector gjk_pair_detector(p_shapeA, p_shapeB, gjk_simplex_solver, gjk_epa_pen_solver);
  1058. gjk_pair_detector.getClosestPoints(gjk_input, result, nullptr);
  1059. if (0 > result.m_distance) {
  1060. // Has penetration
  1061. r_delta_recover_movement += result.m_normalOnBInWorld * (result.m_distance * -1 * p_recover_movement_scale);
  1062. if (r_recover_result) {
  1063. if (result.m_distance < r_recover_result->penetration_distance) {
  1064. r_recover_result->hasPenetration = true;
  1065. r_recover_result->local_shape_most_recovered = p_shapeId_A;
  1066. r_recover_result->other_collision_object = p_objectB;
  1067. r_recover_result->other_compound_shape_index = p_shapeId_B;
  1068. r_recover_result->penetration_distance = result.m_distance;
  1069. r_recover_result->pointWorld = result.m_pointInWorld;
  1070. r_recover_result->normal = result.m_normalOnBInWorld;
  1071. }
  1072. }
  1073. return true;
  1074. }
  1075. return false;
  1076. }
  1077. bool SpaceBullet::RFP_convex_world_test(const btConvexShape *p_shapeA, const btCollisionShape *p_shapeB, btCollisionObject *p_objectA, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) {
  1078. /// Contact test
  1079. btTransform tA(p_transformA);
  1080. btCollisionObjectWrapper obA(nullptr, p_shapeA, p_objectA, tA, -1, p_shapeId_A);
  1081. btCollisionObjectWrapper obB(nullptr, p_shapeB, p_objectB, p_transformB, -1, p_shapeId_B);
  1082. btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, nullptr, BT_CONTACT_POINT_ALGORITHMS);
  1083. if (algorithm) {
  1084. GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB);
  1085. //discrete collision detection query
  1086. algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult);
  1087. algorithm->~btCollisionAlgorithm();
  1088. dispatcher->freeCollisionAlgorithm(algorithm);
  1089. if (contactPointResult.hasHit()) {
  1090. r_delta_recover_movement += contactPointResult.m_pointNormalWorld * (contactPointResult.m_penetration_distance * -1 * p_recover_movement_scale);
  1091. if (r_recover_result) {
  1092. if (contactPointResult.m_penetration_distance < r_recover_result->penetration_distance) {
  1093. r_recover_result->hasPenetration = true;
  1094. r_recover_result->local_shape_most_recovered = p_shapeId_A;
  1095. r_recover_result->other_collision_object = p_objectB;
  1096. r_recover_result->other_compound_shape_index = p_shapeId_B;
  1097. r_recover_result->penetration_distance = contactPointResult.m_penetration_distance;
  1098. r_recover_result->pointWorld = contactPointResult.m_pointWorld;
  1099. r_recover_result->normal = contactPointResult.m_pointNormalWorld;
  1100. }
  1101. }
  1102. return true;
  1103. }
  1104. }
  1105. return false;
  1106. }
  1107. int SpaceBullet::add_separation_result(PhysicsServer3D::SeparationResult *r_result, const SpaceBullet::RecoverResult &p_recover_result, int p_shape_id, const btCollisionObject *p_other_object) const {
  1108. // optimize results (ignore non-colliding)
  1109. if (p_recover_result.penetration_distance < 0.0) {
  1110. const btRigidBody *btRigid = static_cast<const btRigidBody *>(p_other_object);
  1111. CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(p_other_object->getUserPointer());
  1112. r_result->collision_depth = p_recover_result.penetration_distance;
  1113. B_TO_G(p_recover_result.pointWorld, r_result->collision_point);
  1114. B_TO_G(p_recover_result.normal, r_result->collision_normal);
  1115. B_TO_G(btRigid->getVelocityInLocalPoint(p_recover_result.pointWorld - btRigid->getWorldTransform().getOrigin()), r_result->collider_velocity);
  1116. r_result->collision_local_shape = p_shape_id;
  1117. r_result->collider_id = collisionObject->get_instance_id();
  1118. r_result->collider = collisionObject->get_self();
  1119. r_result->collider_shape = p_recover_result.other_compound_shape_index;
  1120. return 1;
  1121. } else {
  1122. return 0;
  1123. }
  1124. }
  1125. int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, int p_result_max, btVector3 &r_delta_recover_movement, PhysicsServer3D::SeparationResult *r_results) {
  1126. // Calculate the cumulative AABB of all shapes of the kinematic body
  1127. btVector3 aabb_min, aabb_max;
  1128. bool shapes_found = false;
  1129. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  1130. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  1131. if (!kin_shape.is_active()) {
  1132. continue;
  1133. }
  1134. if (kin_shape.shape->getShapeType() != CUSTOM_CONVEX_SHAPE_TYPE) {
  1135. continue;
  1136. }
  1137. btTransform shape_transform = p_body_position * kin_shape.transform;
  1138. shape_transform.getOrigin() += r_delta_recover_movement;
  1139. btVector3 shape_aabb_min, shape_aabb_max;
  1140. kin_shape.shape->getAabb(shape_transform, shape_aabb_min, shape_aabb_max);
  1141. if (!shapes_found) {
  1142. aabb_min = shape_aabb_min;
  1143. aabb_max = shape_aabb_max;
  1144. shapes_found = true;
  1145. } else {
  1146. aabb_min.setX((aabb_min.x() < shape_aabb_min.x()) ? aabb_min.x() : shape_aabb_min.x());
  1147. aabb_min.setY((aabb_min.y() < shape_aabb_min.y()) ? aabb_min.y() : shape_aabb_min.y());
  1148. aabb_min.setZ((aabb_min.z() < shape_aabb_min.z()) ? aabb_min.z() : shape_aabb_min.z());
  1149. aabb_max.setX((aabb_max.x() > shape_aabb_max.x()) ? aabb_max.x() : shape_aabb_max.x());
  1150. aabb_max.setY((aabb_max.y() > shape_aabb_max.y()) ? aabb_max.y() : shape_aabb_max.y());
  1151. aabb_max.setZ((aabb_max.z() > shape_aabb_max.z()) ? aabb_max.z() : shape_aabb_max.z());
  1152. }
  1153. }
  1154. // If there are no shapes then there is no penetration either
  1155. if (!shapes_found) {
  1156. return 0;
  1157. }
  1158. // Perform broadphase test
  1159. RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask(), aabb_min, aabb_max);
  1160. dynamicsWorld->getBroadphase()->aabbTest(aabb_min, aabb_max, recover_broad_result);
  1161. int ray_count = 0;
  1162. // Perform narrowphase per shape
  1163. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  1164. if (ray_count >= p_result_max) {
  1165. break;
  1166. }
  1167. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  1168. if (!kin_shape.is_active()) {
  1169. continue;
  1170. }
  1171. if (kin_shape.shape->getShapeType() != CUSTOM_CONVEX_SHAPE_TYPE) {
  1172. continue;
  1173. }
  1174. btTransform shape_transform = p_body_position * kin_shape.transform;
  1175. shape_transform.getOrigin() += r_delta_recover_movement;
  1176. for (int i = recover_broad_result.results.size() - 1; 0 <= i; --i) {
  1177. btCollisionObject *otherObject = recover_broad_result.results[i].collision_object;
  1178. if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) {
  1179. otherObject->activate(); // Force activation of hitten rigid, soft body
  1180. continue;
  1181. } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object())) {
  1182. continue;
  1183. }
  1184. if (otherObject->getCollisionShape()->isCompound()) {
  1185. const btCompoundShape *cs = static_cast<const btCompoundShape *>(otherObject->getCollisionShape());
  1186. int shape_idx = recover_broad_result.results[i].compound_child_index;
  1187. ERR_FAIL_COND_V(shape_idx < 0 || shape_idx >= cs->getNumChildShapes(), false);
  1188. RecoverResult recover_result;
  1189. if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(shape_idx), p_body->get_bt_collision_object(), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) {
  1190. ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject);
  1191. }
  1192. } else {
  1193. RecoverResult recover_result;
  1194. if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) {
  1195. ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject);
  1196. }
  1197. }
  1198. }
  1199. }
  1200. return ray_count;
  1201. }