space_bullet.cpp 58 KB

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