space_bullet.cpp 57 KB

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