rigid_body_bullet.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. /*************************************************************************/
  2. /* rigid_body_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 "rigid_body_bullet.h"
  31. #include "btRayShape.h"
  32. #include "bullet_physics_server.h"
  33. #include "bullet_types_converter.h"
  34. #include "bullet_utilities.h"
  35. #include "godot_motion_state.h"
  36. #include "joint_bullet.h"
  37. #include <BulletCollision/CollisionDispatch/btGhostObject.h>
  38. #include <BulletCollision/CollisionShapes/btConvexPointCloudShape.h>
  39. #include <BulletDynamics/Dynamics/btRigidBody.h>
  40. #include <btBulletCollisionCommon.h>
  41. #include <assert.h>
  42. /**
  43. @author AndreaCatania
  44. */
  45. BulletPhysicsDirectBodyState3D *BulletPhysicsDirectBodyState3D::singleton = nullptr;
  46. Vector3 BulletPhysicsDirectBodyState3D::get_total_gravity() const {
  47. Vector3 gVec;
  48. B_TO_G(body->btBody->getGravity(), gVec);
  49. return gVec;
  50. }
  51. real_t BulletPhysicsDirectBodyState3D::get_total_angular_damp() const {
  52. return body->btBody->getAngularDamping();
  53. }
  54. real_t BulletPhysicsDirectBodyState3D::get_total_linear_damp() const {
  55. return body->btBody->getLinearDamping();
  56. }
  57. Vector3 BulletPhysicsDirectBodyState3D::get_center_of_mass() const {
  58. Vector3 gVec;
  59. B_TO_G(body->btBody->getCenterOfMassPosition(), gVec);
  60. return gVec;
  61. }
  62. Basis BulletPhysicsDirectBodyState3D::get_principal_inertia_axes() const {
  63. return Basis();
  64. }
  65. real_t BulletPhysicsDirectBodyState3D::get_inverse_mass() const {
  66. return body->btBody->getInvMass();
  67. }
  68. Vector3 BulletPhysicsDirectBodyState3D::get_inverse_inertia() const {
  69. Vector3 gVec;
  70. B_TO_G(body->btBody->getInvInertiaDiagLocal(), gVec);
  71. return gVec;
  72. }
  73. Basis BulletPhysicsDirectBodyState3D::get_inverse_inertia_tensor() const {
  74. Basis gInertia;
  75. B_TO_G(body->btBody->getInvInertiaTensorWorld(), gInertia);
  76. return gInertia;
  77. }
  78. void BulletPhysicsDirectBodyState3D::set_linear_velocity(const Vector3 &p_velocity) {
  79. body->set_linear_velocity(p_velocity);
  80. }
  81. Vector3 BulletPhysicsDirectBodyState3D::get_linear_velocity() const {
  82. return body->get_linear_velocity();
  83. }
  84. void BulletPhysicsDirectBodyState3D::set_angular_velocity(const Vector3 &p_velocity) {
  85. body->set_angular_velocity(p_velocity);
  86. }
  87. Vector3 BulletPhysicsDirectBodyState3D::get_angular_velocity() const {
  88. return body->get_angular_velocity();
  89. }
  90. void BulletPhysicsDirectBodyState3D::set_transform(const Transform &p_transform) {
  91. body->set_transform(p_transform);
  92. }
  93. Transform BulletPhysicsDirectBodyState3D::get_transform() const {
  94. return body->get_transform();
  95. }
  96. void BulletPhysicsDirectBodyState3D::add_central_force(const Vector3 &p_force) {
  97. body->apply_central_force(p_force);
  98. }
  99. void BulletPhysicsDirectBodyState3D::add_force(const Vector3 &p_force, const Vector3 &p_position) {
  100. body->apply_force(p_force, p_position);
  101. }
  102. void BulletPhysicsDirectBodyState3D::add_torque(const Vector3 &p_torque) {
  103. body->apply_torque(p_torque);
  104. }
  105. void BulletPhysicsDirectBodyState3D::apply_central_impulse(const Vector3 &p_impulse) {
  106. body->apply_central_impulse(p_impulse);
  107. }
  108. void BulletPhysicsDirectBodyState3D::apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position) {
  109. body->apply_impulse(p_impulse, p_position);
  110. }
  111. void BulletPhysicsDirectBodyState3D::apply_torque_impulse(const Vector3 &p_impulse) {
  112. body->apply_torque_impulse(p_impulse);
  113. }
  114. void BulletPhysicsDirectBodyState3D::set_sleep_state(bool p_sleep) {
  115. body->set_activation_state(!p_sleep);
  116. }
  117. bool BulletPhysicsDirectBodyState3D::is_sleeping() const {
  118. return !body->is_active();
  119. }
  120. int BulletPhysicsDirectBodyState3D::get_contact_count() const {
  121. return body->collisionsCount;
  122. }
  123. Vector3 BulletPhysicsDirectBodyState3D::get_contact_local_position(int p_contact_idx) const {
  124. return body->collisions[p_contact_idx].hitLocalLocation;
  125. }
  126. Vector3 BulletPhysicsDirectBodyState3D::get_contact_local_normal(int p_contact_idx) const {
  127. return body->collisions[p_contact_idx].hitNormal;
  128. }
  129. real_t BulletPhysicsDirectBodyState3D::get_contact_impulse(int p_contact_idx) const {
  130. return body->collisions[p_contact_idx].appliedImpulse;
  131. }
  132. int BulletPhysicsDirectBodyState3D::get_contact_local_shape(int p_contact_idx) const {
  133. return body->collisions[p_contact_idx].local_shape;
  134. }
  135. RID BulletPhysicsDirectBodyState3D::get_contact_collider(int p_contact_idx) const {
  136. return body->collisions[p_contact_idx].otherObject->get_self();
  137. }
  138. Vector3 BulletPhysicsDirectBodyState3D::get_contact_collider_position(int p_contact_idx) const {
  139. return body->collisions[p_contact_idx].hitWorldLocation;
  140. }
  141. ObjectID BulletPhysicsDirectBodyState3D::get_contact_collider_id(int p_contact_idx) const {
  142. return body->collisions[p_contact_idx].otherObject->get_instance_id();
  143. }
  144. int BulletPhysicsDirectBodyState3D::get_contact_collider_shape(int p_contact_idx) const {
  145. return body->collisions[p_contact_idx].other_object_shape;
  146. }
  147. Vector3 BulletPhysicsDirectBodyState3D::get_contact_collider_velocity_at_position(int p_contact_idx) const {
  148. RigidBodyBullet::CollisionData &colDat = body->collisions.write[p_contact_idx];
  149. btVector3 hitLocation;
  150. G_TO_B(colDat.hitLocalLocation, hitLocation);
  151. Vector3 velocityAtPoint;
  152. B_TO_G(colDat.otherObject->get_bt_rigid_body()->getVelocityInLocalPoint(hitLocation), velocityAtPoint);
  153. return velocityAtPoint;
  154. }
  155. PhysicsDirectSpaceState3D *BulletPhysicsDirectBodyState3D::get_space_state() {
  156. return body->get_space()->get_direct_state();
  157. }
  158. RigidBodyBullet::KinematicUtilities::KinematicUtilities(RigidBodyBullet *p_owner) :
  159. owner(p_owner),
  160. safe_margin(0.001) {
  161. }
  162. RigidBodyBullet::KinematicUtilities::~KinematicUtilities() {
  163. just_delete_shapes(shapes.size()); // don't need to resize
  164. }
  165. void RigidBodyBullet::KinematicUtilities::setSafeMargin(btScalar p_margin) {
  166. safe_margin = p_margin;
  167. copyAllOwnerShapes();
  168. }
  169. void RigidBodyBullet::KinematicUtilities::copyAllOwnerShapes() {
  170. const Vector<CollisionObjectBullet::ShapeWrapper> &shapes_wrappers(owner->get_shapes_wrappers());
  171. const int shapes_count = shapes_wrappers.size();
  172. just_delete_shapes(shapes_count);
  173. const CollisionObjectBullet::ShapeWrapper *shape_wrapper;
  174. btVector3 owner_scale(owner->get_bt_body_scale());
  175. for (int i = shapes_count - 1; 0 <= i; --i) {
  176. shape_wrapper = &shapes_wrappers[i];
  177. if (!shape_wrapper->active) {
  178. continue;
  179. }
  180. shapes.write[i].transform = shape_wrapper->transform;
  181. shapes.write[i].transform.getOrigin() *= owner_scale;
  182. switch (shape_wrapper->shape->get_type()) {
  183. case PhysicsServer3D::SHAPE_SPHERE:
  184. case PhysicsServer3D::SHAPE_BOX:
  185. case PhysicsServer3D::SHAPE_CAPSULE:
  186. case PhysicsServer3D::SHAPE_CYLINDER:
  187. case PhysicsServer3D::SHAPE_CONVEX_POLYGON:
  188. case PhysicsServer3D::SHAPE_RAY: {
  189. shapes.write[i].shape = static_cast<btConvexShape *>(shape_wrapper->shape->create_bt_shape(owner_scale * shape_wrapper->scale, safe_margin));
  190. } break;
  191. default:
  192. WARN_PRINT("This shape is not supported for kinematic collision.");
  193. shapes.write[i].shape = nullptr;
  194. }
  195. }
  196. }
  197. void RigidBodyBullet::KinematicUtilities::just_delete_shapes(int new_size) {
  198. for (int i = shapes.size() - 1; 0 <= i; --i) {
  199. if (shapes[i].shape) {
  200. bulletdelete(shapes.write[i].shape);
  201. }
  202. }
  203. shapes.resize(new_size);
  204. }
  205. RigidBodyBullet::RigidBodyBullet() :
  206. RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_RIGID_BODY) {
  207. godotMotionState = bulletnew(GodotMotionState(this));
  208. // Initial properties
  209. const btVector3 localInertia(0, 0, 0);
  210. btRigidBody::btRigidBodyConstructionInfo cInfo(mass, godotMotionState, nullptr, localInertia);
  211. btBody = bulletnew(btRigidBody(cInfo));
  212. btBody->setFriction(1.0);
  213. reload_shapes();
  214. setupBulletCollisionObject(btBody);
  215. set_mode(PhysicsServer3D::BODY_MODE_RIGID);
  216. reload_axis_lock();
  217. areasWhereIam.resize(maxAreasWhereIam);
  218. for (int i = areasWhereIam.size() - 1; 0 <= i; --i) {
  219. areasWhereIam.write[i] = nullptr;
  220. }
  221. btBody->setSleepingThresholds(0.2, 0.2);
  222. prev_collision_traces = &collision_traces_1;
  223. curr_collision_traces = &collision_traces_2;
  224. }
  225. RigidBodyBullet::~RigidBodyBullet() {
  226. bulletdelete(godotMotionState);
  227. if (force_integration_callback) {
  228. memdelete(force_integration_callback);
  229. }
  230. destroy_kinematic_utilities();
  231. }
  232. void RigidBodyBullet::init_kinematic_utilities() {
  233. kinematic_utilities = memnew(KinematicUtilities(this));
  234. }
  235. void RigidBodyBullet::destroy_kinematic_utilities() {
  236. if (kinematic_utilities) {
  237. memdelete(kinematic_utilities);
  238. kinematic_utilities = nullptr;
  239. }
  240. }
  241. void RigidBodyBullet::main_shape_changed() {
  242. CRASH_COND(!get_main_shape());
  243. btBody->setCollisionShape(get_main_shape());
  244. set_continuous_collision_detection(is_continuous_collision_detection_enabled()); // Reset
  245. }
  246. void RigidBodyBullet::reload_body() {
  247. if (space) {
  248. space->remove_rigid_body(this);
  249. if (get_main_shape()) {
  250. space->add_rigid_body(this);
  251. }
  252. }
  253. }
  254. void RigidBodyBullet::set_space(SpaceBullet *p_space) {
  255. // Clear the old space if there is one
  256. if (space) {
  257. can_integrate_forces = false;
  258. isScratchedSpaceOverrideModificator = false;
  259. // Remove any constraints
  260. space->remove_rigid_body_constraints(this);
  261. // Remove this object form the physics world
  262. space->remove_rigid_body(this);
  263. }
  264. space = p_space;
  265. if (space) {
  266. space->add_rigid_body(this);
  267. }
  268. }
  269. void RigidBodyBullet::dispatch_callbacks() {
  270. /// The check isFirstTransformChanged is necessary in order to call integrated forces only when the first transform is sent
  271. if ((btBody->isKinematicObject() || btBody->isActive() || previousActiveState != btBody->isActive()) && force_integration_callback && can_integrate_forces) {
  272. if (omit_forces_integration) {
  273. btBody->clearForces();
  274. }
  275. BulletPhysicsDirectBodyState3D *bodyDirect = BulletPhysicsDirectBodyState3D::get_singleton(this);
  276. Variant variantBodyDirect = bodyDirect;
  277. Object *obj = ObjectDB::get_instance(force_integration_callback->id);
  278. if (!obj) {
  279. // Remove integration callback
  280. set_force_integration_callback(ObjectID(), StringName());
  281. } else {
  282. const Variant *vp[2] = { &variantBodyDirect, &force_integration_callback->udata };
  283. Callable::CallError responseCallError;
  284. int argc = (force_integration_callback->udata.get_type() == Variant::NIL) ? 1 : 2;
  285. obj->call(force_integration_callback->method, vp, argc, responseCallError);
  286. }
  287. }
  288. if (isScratchedSpaceOverrideModificator || 0 < countGravityPointSpaces) {
  289. isScratchedSpaceOverrideModificator = false;
  290. reload_space_override_modificator();
  291. }
  292. /// Lock axis
  293. btBody->setLinearVelocity(btBody->getLinearVelocity() * btBody->getLinearFactor());
  294. btBody->setAngularVelocity(btBody->getAngularVelocity() * btBody->getAngularFactor());
  295. previousActiveState = btBody->isActive();
  296. }
  297. void RigidBodyBullet::set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata) {
  298. if (force_integration_callback) {
  299. memdelete(force_integration_callback);
  300. force_integration_callback = nullptr;
  301. }
  302. if (p_id.is_valid()) {
  303. force_integration_callback = memnew(ForceIntegrationCallback);
  304. force_integration_callback->id = p_id;
  305. force_integration_callback->method = p_method;
  306. force_integration_callback->udata = p_udata;
  307. }
  308. }
  309. void RigidBodyBullet::scratch_space_override_modificator() {
  310. isScratchedSpaceOverrideModificator = true;
  311. }
  312. void RigidBodyBullet::on_collision_filters_change() {
  313. if (space) {
  314. space->reload_collision_filters(this);
  315. }
  316. set_activation_state(true);
  317. }
  318. void RigidBodyBullet::on_collision_checker_start() {
  319. prev_collision_count = collisionsCount;
  320. collisionsCount = 0;
  321. // Swap array
  322. Vector<RigidBodyBullet *> *s = prev_collision_traces;
  323. prev_collision_traces = curr_collision_traces;
  324. curr_collision_traces = s;
  325. }
  326. void RigidBodyBullet::on_collision_checker_end() {
  327. // Always true if active and not a static or kinematic body
  328. isTransformChanged = btBody->isActive() && !btBody->isStaticOrKinematicObject();
  329. }
  330. bool RigidBodyBullet::add_collision_object(RigidBodyBullet *p_otherObject, const Vector3 &p_hitWorldLocation, const Vector3 &p_hitLocalLocation, const Vector3 &p_hitNormal, const real_t &p_appliedImpulse, int p_other_shape_index, int p_local_shape_index) {
  331. if (collisionsCount >= maxCollisionsDetection) {
  332. return false;
  333. }
  334. CollisionData &cd = collisions.write[collisionsCount];
  335. cd.hitLocalLocation = p_hitLocalLocation;
  336. cd.otherObject = p_otherObject;
  337. cd.hitWorldLocation = p_hitWorldLocation;
  338. cd.hitNormal = p_hitNormal;
  339. cd.appliedImpulse = p_appliedImpulse;
  340. cd.other_object_shape = p_other_shape_index;
  341. cd.local_shape = p_local_shape_index;
  342. curr_collision_traces->write[collisionsCount] = p_otherObject;
  343. ++collisionsCount;
  344. return true;
  345. }
  346. bool RigidBodyBullet::was_colliding(RigidBodyBullet *p_other_object) {
  347. for (int i = prev_collision_count - 1; 0 <= i; --i) {
  348. if ((*prev_collision_traces)[i] == p_other_object) {
  349. return true;
  350. }
  351. }
  352. return false;
  353. }
  354. void RigidBodyBullet::set_activation_state(bool p_active) {
  355. if (p_active) {
  356. btBody->activate();
  357. } else {
  358. btBody->setActivationState(WANTS_DEACTIVATION);
  359. }
  360. }
  361. bool RigidBodyBullet::is_active() const {
  362. return btBody->isActive();
  363. }
  364. void RigidBodyBullet::set_omit_forces_integration(bool p_omit) {
  365. omit_forces_integration = p_omit;
  366. }
  367. void RigidBodyBullet::set_param(PhysicsServer3D::BodyParameter p_param, real_t p_value) {
  368. switch (p_param) {
  369. case PhysicsServer3D::BODY_PARAM_BOUNCE:
  370. btBody->setRestitution(p_value);
  371. break;
  372. case PhysicsServer3D::BODY_PARAM_FRICTION:
  373. btBody->setFriction(p_value);
  374. break;
  375. case PhysicsServer3D::BODY_PARAM_MASS: {
  376. ERR_FAIL_COND(p_value < 0);
  377. mass = p_value;
  378. _internal_set_mass(p_value);
  379. break;
  380. }
  381. case PhysicsServer3D::BODY_PARAM_LINEAR_DAMP:
  382. linearDamp = p_value;
  383. // Mark for updating total linear damping.
  384. scratch_space_override_modificator();
  385. break;
  386. case PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP:
  387. angularDamp = p_value;
  388. // Mark for updating total angular damping.
  389. scratch_space_override_modificator();
  390. break;
  391. case PhysicsServer3D::BODY_PARAM_GRAVITY_SCALE:
  392. gravity_scale = p_value;
  393. // The Bullet gravity will be is set by reload_space_override_modificator.
  394. // Mark for updating total gravity scale.
  395. scratch_space_override_modificator();
  396. break;
  397. default:
  398. WARN_PRINT("Parameter " + itos(p_param) + " not supported by bullet. Value: " + itos(p_value));
  399. }
  400. }
  401. real_t RigidBodyBullet::get_param(PhysicsServer3D::BodyParameter p_param) const {
  402. switch (p_param) {
  403. case PhysicsServer3D::BODY_PARAM_BOUNCE:
  404. return btBody->getRestitution();
  405. case PhysicsServer3D::BODY_PARAM_FRICTION:
  406. return btBody->getFriction();
  407. case PhysicsServer3D::BODY_PARAM_MASS: {
  408. const btScalar invMass = btBody->getInvMass();
  409. return 0 == invMass ? 0 : 1 / invMass;
  410. }
  411. case PhysicsServer3D::BODY_PARAM_LINEAR_DAMP:
  412. return linearDamp;
  413. case PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP:
  414. return angularDamp;
  415. case PhysicsServer3D::BODY_PARAM_GRAVITY_SCALE:
  416. return gravity_scale;
  417. default:
  418. WARN_PRINT("Parameter " + itos(p_param) + " not supported by bullet");
  419. return 0;
  420. }
  421. }
  422. void RigidBodyBullet::set_mode(PhysicsServer3D::BodyMode p_mode) {
  423. // This is necessary to block force_integration until next move
  424. can_integrate_forces = false;
  425. destroy_kinematic_utilities();
  426. // The mode change is relevant to its mass
  427. switch (p_mode) {
  428. case PhysicsServer3D::BODY_MODE_KINEMATIC:
  429. mode = PhysicsServer3D::BODY_MODE_KINEMATIC;
  430. reload_axis_lock();
  431. _internal_set_mass(0);
  432. init_kinematic_utilities();
  433. break;
  434. case PhysicsServer3D::BODY_MODE_STATIC:
  435. mode = PhysicsServer3D::BODY_MODE_STATIC;
  436. reload_axis_lock();
  437. _internal_set_mass(0);
  438. break;
  439. case PhysicsServer3D::BODY_MODE_RIGID:
  440. mode = PhysicsServer3D::BODY_MODE_RIGID;
  441. reload_axis_lock();
  442. _internal_set_mass(0 == mass ? 1 : mass);
  443. scratch_space_override_modificator();
  444. break;
  445. case PhysicsServer3D::BODY_MODE_CHARACTER:
  446. mode = PhysicsServer3D::BODY_MODE_CHARACTER;
  447. reload_axis_lock();
  448. _internal_set_mass(0 == mass ? 1 : mass);
  449. scratch_space_override_modificator();
  450. break;
  451. }
  452. btBody->setAngularVelocity(btVector3(0, 0, 0));
  453. btBody->setLinearVelocity(btVector3(0, 0, 0));
  454. }
  455. PhysicsServer3D::BodyMode RigidBodyBullet::get_mode() const {
  456. return mode;
  457. }
  458. void RigidBodyBullet::set_state(PhysicsServer3D::BodyState p_state, const Variant &p_variant) {
  459. switch (p_state) {
  460. case PhysicsServer3D::BODY_STATE_TRANSFORM:
  461. set_transform(p_variant);
  462. break;
  463. case PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY:
  464. set_linear_velocity(p_variant);
  465. break;
  466. case PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY:
  467. set_angular_velocity(p_variant);
  468. break;
  469. case PhysicsServer3D::BODY_STATE_SLEEPING:
  470. set_activation_state(!bool(p_variant));
  471. break;
  472. case PhysicsServer3D::BODY_STATE_CAN_SLEEP:
  473. can_sleep = bool(p_variant);
  474. if (!can_sleep) {
  475. // Can't sleep
  476. btBody->forceActivationState(DISABLE_DEACTIVATION);
  477. } else {
  478. btBody->forceActivationState(ACTIVE_TAG);
  479. }
  480. break;
  481. }
  482. }
  483. Variant RigidBodyBullet::get_state(PhysicsServer3D::BodyState p_state) const {
  484. switch (p_state) {
  485. case PhysicsServer3D::BODY_STATE_TRANSFORM:
  486. return get_transform();
  487. case PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY:
  488. return get_linear_velocity();
  489. case PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY:
  490. return get_angular_velocity();
  491. case PhysicsServer3D::BODY_STATE_SLEEPING:
  492. return !is_active();
  493. case PhysicsServer3D::BODY_STATE_CAN_SLEEP:
  494. return can_sleep;
  495. default:
  496. WARN_PRINT("This state " + itos(p_state) + " is not supported by Bullet");
  497. return Variant();
  498. }
  499. }
  500. void RigidBodyBullet::apply_central_impulse(const Vector3 &p_impulse) {
  501. btVector3 btImpulse;
  502. G_TO_B(p_impulse, btImpulse);
  503. if (Vector3() != p_impulse) {
  504. btBody->activate();
  505. }
  506. btBody->applyCentralImpulse(btImpulse);
  507. }
  508. void RigidBodyBullet::apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position) {
  509. btVector3 btImpulse;
  510. btVector3 btPosition;
  511. G_TO_B(p_impulse, btImpulse);
  512. G_TO_B(p_position, btPosition);
  513. if (Vector3() != p_impulse) {
  514. btBody->activate();
  515. }
  516. btBody->applyImpulse(btImpulse, btPosition);
  517. }
  518. void RigidBodyBullet::apply_torque_impulse(const Vector3 &p_impulse) {
  519. btVector3 btImp;
  520. G_TO_B(p_impulse, btImp);
  521. if (Vector3() != p_impulse) {
  522. btBody->activate();
  523. }
  524. btBody->applyTorqueImpulse(btImp);
  525. }
  526. void RigidBodyBullet::apply_force(const Vector3 &p_force, const Vector3 &p_position) {
  527. btVector3 btForce;
  528. btVector3 btPosition;
  529. G_TO_B(p_force, btForce);
  530. G_TO_B(p_position, btPosition);
  531. if (Vector3() != p_force) {
  532. btBody->activate();
  533. }
  534. btBody->applyForce(btForce, btPosition);
  535. }
  536. void RigidBodyBullet::apply_central_force(const Vector3 &p_force) {
  537. btVector3 btForce;
  538. G_TO_B(p_force, btForce);
  539. if (Vector3() != p_force) {
  540. btBody->activate();
  541. }
  542. btBody->applyCentralForce(btForce);
  543. }
  544. void RigidBodyBullet::apply_torque(const Vector3 &p_torque) {
  545. btVector3 btTorq;
  546. G_TO_B(p_torque, btTorq);
  547. if (Vector3() != p_torque) {
  548. btBody->activate();
  549. }
  550. btBody->applyTorque(btTorq);
  551. }
  552. void RigidBodyBullet::set_applied_force(const Vector3 &p_force) {
  553. btVector3 btVec = btBody->getTotalTorque();
  554. if (Vector3() != p_force) {
  555. btBody->activate();
  556. }
  557. btBody->clearForces();
  558. btBody->applyTorque(btVec);
  559. G_TO_B(p_force, btVec);
  560. btBody->applyCentralForce(btVec);
  561. }
  562. Vector3 RigidBodyBullet::get_applied_force() const {
  563. Vector3 gTotForc;
  564. B_TO_G(btBody->getTotalForce(), gTotForc);
  565. return gTotForc;
  566. }
  567. void RigidBodyBullet::set_applied_torque(const Vector3 &p_torque) {
  568. btVector3 btVec = btBody->getTotalForce();
  569. if (Vector3() != p_torque) {
  570. btBody->activate();
  571. }
  572. btBody->clearForces();
  573. btBody->applyCentralForce(btVec);
  574. G_TO_B(p_torque, btVec);
  575. btBody->applyTorque(btVec);
  576. }
  577. Vector3 RigidBodyBullet::get_applied_torque() const {
  578. Vector3 gTotTorq;
  579. B_TO_G(btBody->getTotalTorque(), gTotTorq);
  580. return gTotTorq;
  581. }
  582. void RigidBodyBullet::set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool lock) {
  583. if (lock) {
  584. locked_axis |= p_axis;
  585. } else {
  586. locked_axis &= ~p_axis;
  587. }
  588. reload_axis_lock();
  589. }
  590. bool RigidBodyBullet::is_axis_locked(PhysicsServer3D::BodyAxis p_axis) const {
  591. return locked_axis & p_axis;
  592. }
  593. void RigidBodyBullet::reload_axis_lock() {
  594. btBody->setLinearFactor(btVector3(btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_X)), btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_Y)), btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_Z))));
  595. if (PhysicsServer3D::BODY_MODE_CHARACTER == mode) {
  596. /// When character angular is always locked
  597. btBody->setAngularFactor(btVector3(0., 0., 0.));
  598. } else {
  599. btBody->setAngularFactor(btVector3(btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_ANGULAR_X)), btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_ANGULAR_Y)), btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_ANGULAR_Z))));
  600. }
  601. }
  602. void RigidBodyBullet::set_continuous_collision_detection(bool p_enable) {
  603. if (p_enable) {
  604. // This threshold enable CCD if the object moves more than
  605. // 1 meter in one simulation frame
  606. btBody->setCcdMotionThreshold(1e-7);
  607. /// Calculate using the rule write below the CCD swept sphere radius
  608. /// CCD works on an embedded sphere of radius, make sure this radius
  609. /// is embedded inside the convex objects, preferably smaller:
  610. /// for an object of dimensions 1 meter, try 0.2
  611. btScalar radius(1.0);
  612. if (btBody->getCollisionShape()) {
  613. btVector3 center;
  614. btBody->getCollisionShape()->getBoundingSphere(center, radius);
  615. }
  616. btBody->setCcdSweptSphereRadius(radius * 0.2);
  617. } else {
  618. btBody->setCcdMotionThreshold(0.);
  619. btBody->setCcdSweptSphereRadius(0.);
  620. }
  621. }
  622. bool RigidBodyBullet::is_continuous_collision_detection_enabled() const {
  623. return 0. < btBody->getCcdMotionThreshold();
  624. }
  625. void RigidBodyBullet::set_linear_velocity(const Vector3 &p_velocity) {
  626. btVector3 btVec;
  627. G_TO_B(p_velocity, btVec);
  628. if (Vector3() != p_velocity) {
  629. btBody->activate();
  630. }
  631. btBody->setLinearVelocity(btVec);
  632. }
  633. Vector3 RigidBodyBullet::get_linear_velocity() const {
  634. Vector3 gVec;
  635. B_TO_G(btBody->getLinearVelocity(), gVec);
  636. return gVec;
  637. }
  638. void RigidBodyBullet::set_angular_velocity(const Vector3 &p_velocity) {
  639. btVector3 btVec;
  640. G_TO_B(p_velocity, btVec);
  641. if (Vector3() != p_velocity) {
  642. btBody->activate();
  643. }
  644. btBody->setAngularVelocity(btVec);
  645. }
  646. Vector3 RigidBodyBullet::get_angular_velocity() const {
  647. Vector3 gVec;
  648. B_TO_G(btBody->getAngularVelocity(), gVec);
  649. return gVec;
  650. }
  651. void RigidBodyBullet::set_transform__bullet(const btTransform &p_global_transform) {
  652. if (mode == PhysicsServer3D::BODY_MODE_KINEMATIC) {
  653. if (space && space->get_delta_time() != 0) {
  654. btBody->setLinearVelocity((p_global_transform.getOrigin() - btBody->getWorldTransform().getOrigin()) / space->get_delta_time());
  655. }
  656. // The kinematic use MotionState class
  657. godotMotionState->moveBody(p_global_transform);
  658. } else {
  659. // Is necessary to avoid wrong location on the rendering side on the next frame
  660. godotMotionState->setWorldTransform(p_global_transform);
  661. }
  662. CollisionObjectBullet::set_transform__bullet(p_global_transform);
  663. }
  664. const btTransform &RigidBodyBullet::get_transform__bullet() const {
  665. if (is_static()) {
  666. return RigidCollisionObjectBullet::get_transform__bullet();
  667. } else {
  668. return godotMotionState->getCurrentWorldTransform();
  669. }
  670. }
  671. void RigidBodyBullet::reload_shapes() {
  672. RigidCollisionObjectBullet::reload_shapes();
  673. const btScalar invMass = btBody->getInvMass();
  674. const btScalar mass = invMass == 0 ? 0 : 1 / invMass;
  675. if (mainShape) {
  676. // inertia initialised zero here because some of bullet's collision
  677. // shapes incorrectly do not set the vector in calculateLocalIntertia.
  678. // Arbitrary zero is preferable to undefined behaviour.
  679. btVector3 inertia(0, 0, 0);
  680. if (EMPTY_SHAPE_PROXYTYPE != mainShape->getShapeType()) { // Necessary to avoid assertion of the empty shape
  681. mainShape->calculateLocalInertia(mass, inertia);
  682. }
  683. btBody->setMassProps(mass, inertia);
  684. }
  685. btBody->updateInertiaTensor();
  686. reload_kinematic_shapes();
  687. set_continuous_collision_detection(is_continuous_collision_detection_enabled());
  688. reload_body();
  689. }
  690. void RigidBodyBullet::on_enter_area(AreaBullet *p_area) {
  691. /// Add this area to the array in an ordered way
  692. ++areaWhereIamCount;
  693. if (areaWhereIamCount >= maxAreasWhereIam) {
  694. --areaWhereIamCount;
  695. return;
  696. }
  697. for (int i = 0; i < areaWhereIamCount; ++i) {
  698. if (nullptr == areasWhereIam[i]) {
  699. // This area has the highest priority
  700. areasWhereIam.write[i] = p_area;
  701. break;
  702. } else {
  703. if (areasWhereIam[i]->get_spOv_priority() > p_area->get_spOv_priority()) {
  704. // The position was found, just shift all elements
  705. for (int j = areaWhereIamCount; j > i; j--) {
  706. areasWhereIam.write[j] = areasWhereIam[j - 1];
  707. }
  708. areasWhereIam.write[i] = p_area;
  709. break;
  710. }
  711. }
  712. }
  713. if (PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED != p_area->get_spOv_mode()) {
  714. scratch_space_override_modificator();
  715. }
  716. if (p_area->is_spOv_gravityPoint()) {
  717. ++countGravityPointSpaces;
  718. ERR_FAIL_COND(countGravityPointSpaces <= 0);
  719. }
  720. }
  721. void RigidBodyBullet::on_exit_area(AreaBullet *p_area) {
  722. RigidCollisionObjectBullet::on_exit_area(p_area);
  723. /// Remove this area and keep the order
  724. /// N.B. Since I don't want resize the array I can't use the "erase" function
  725. bool wasTheAreaFound = false;
  726. for (int i = 0; i < areaWhereIamCount; ++i) {
  727. if (p_area == areasWhereIam[i]) {
  728. // The area was found, just shift down all elements
  729. for (int j = i; j < areaWhereIamCount; ++j) {
  730. areasWhereIam.write[j] = areasWhereIam[j + 1];
  731. }
  732. wasTheAreaFound = true;
  733. break;
  734. }
  735. }
  736. if (wasTheAreaFound) {
  737. if (p_area->is_spOv_gravityPoint()) {
  738. --countGravityPointSpaces;
  739. ERR_FAIL_COND(countGravityPointSpaces < 0);
  740. }
  741. --areaWhereIamCount;
  742. areasWhereIam.write[areaWhereIamCount] = nullptr; // Even if this is not required, I clear the last element to be safe
  743. if (PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED != p_area->get_spOv_mode()) {
  744. scratch_space_override_modificator();
  745. }
  746. }
  747. }
  748. void RigidBodyBullet::reload_space_override_modificator() {
  749. if (mode == PhysicsServer3D::BODY_MODE_STATIC) {
  750. return;
  751. }
  752. Vector3 newGravity(0.0, 0.0, 0.0);
  753. real_t newLinearDamp = MAX(0.0, linearDamp);
  754. real_t newAngularDamp = MAX(0.0, angularDamp);
  755. AreaBullet *currentArea;
  756. // Variable used to calculate new gravity for gravity point areas, it is pointed by currentGravity pointer
  757. Vector3 support_gravity(0, 0, 0);
  758. bool stopped = false;
  759. for (int i = areaWhereIamCount - 1; (0 <= i) && !stopped; --i) {
  760. currentArea = areasWhereIam[i];
  761. if (!currentArea || PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED == currentArea->get_spOv_mode()) {
  762. continue;
  763. }
  764. /// Here is calculated the gravity
  765. if (currentArea->is_spOv_gravityPoint()) {
  766. /// It calculates the direction of new gravity
  767. support_gravity = currentArea->get_transform().xform(currentArea->get_spOv_gravityVec()) - get_transform().get_origin();
  768. real_t distanceMag = support_gravity.length();
  769. // Normalized in this way to avoid the double call of function "length()"
  770. if (distanceMag == 0) {
  771. support_gravity.x = 0;
  772. support_gravity.y = 0;
  773. support_gravity.z = 0;
  774. } else {
  775. support_gravity.x /= distanceMag;
  776. support_gravity.y /= distanceMag;
  777. support_gravity.z /= distanceMag;
  778. }
  779. /// Here is calculated the final gravity
  780. if (currentArea->get_spOv_gravityPointDistanceScale() > 0) {
  781. // Scaled gravity by distance
  782. support_gravity *= currentArea->get_spOv_gravityMag() / Math::pow(distanceMag * currentArea->get_spOv_gravityPointDistanceScale() + 1, 2);
  783. } else {
  784. // Unscaled gravity
  785. support_gravity *= currentArea->get_spOv_gravityMag();
  786. }
  787. } else {
  788. support_gravity = currentArea->get_spOv_gravityVec() * currentArea->get_spOv_gravityMag();
  789. }
  790. switch (currentArea->get_spOv_mode()) {
  791. case PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED:
  792. /// This area does not affect gravity/damp. These are generally areas
  793. /// that exist only to detect collisions, and objects entering or exiting them.
  794. break;
  795. case PhysicsServer3D::AREA_SPACE_OVERRIDE_COMBINE:
  796. /// This area adds its gravity/damp values to whatever has been
  797. /// calculated so far. This way, many overlapping areas can combine
  798. /// their physics to make interesting
  799. newGravity += support_gravity;
  800. newLinearDamp += currentArea->get_spOv_linearDamp();
  801. newAngularDamp += currentArea->get_spOv_angularDamp();
  802. break;
  803. case PhysicsServer3D::AREA_SPACE_OVERRIDE_COMBINE_REPLACE:
  804. /// This area adds its gravity/damp values to whatever has been calculated
  805. /// so far. Then stops taking into account the rest of the areas, even the
  806. /// default one.
  807. newGravity += support_gravity;
  808. newLinearDamp += currentArea->get_spOv_linearDamp();
  809. newAngularDamp += currentArea->get_spOv_angularDamp();
  810. stopped = true;
  811. break;
  812. case PhysicsServer3D::AREA_SPACE_OVERRIDE_REPLACE:
  813. /// This area replaces any gravity/damp, even the default one, and
  814. /// stops taking into account the rest of the areas.
  815. newGravity = support_gravity;
  816. newLinearDamp = currentArea->get_spOv_linearDamp();
  817. newAngularDamp = currentArea->get_spOv_angularDamp();
  818. stopped = true;
  819. break;
  820. case PhysicsServer3D::AREA_SPACE_OVERRIDE_REPLACE_COMBINE:
  821. /// This area replaces any gravity/damp calculated so far, but keeps
  822. /// calculating the rest of the areas, down to the default one.
  823. newGravity = support_gravity;
  824. newLinearDamp = currentArea->get_spOv_linearDamp();
  825. newAngularDamp = currentArea->get_spOv_angularDamp();
  826. break;
  827. }
  828. }
  829. // Add default gravity and damping from space.
  830. if (!stopped) {
  831. newGravity += space->get_gravity_direction() * space->get_gravity_magnitude();
  832. newLinearDamp += space->get_linear_damp();
  833. newAngularDamp += space->get_angular_damp();
  834. }
  835. btVector3 newBtGravity;
  836. G_TO_B(newGravity * gravity_scale, newBtGravity);
  837. btBody->setGravity(newBtGravity);
  838. btBody->setDamping(newLinearDamp, newAngularDamp);
  839. }
  840. void RigidBodyBullet::reload_kinematic_shapes() {
  841. if (!kinematic_utilities) {
  842. return;
  843. }
  844. kinematic_utilities->copyAllOwnerShapes();
  845. }
  846. void RigidBodyBullet::notify_transform_changed() {
  847. RigidCollisionObjectBullet::notify_transform_changed();
  848. can_integrate_forces = true;
  849. }
  850. void RigidBodyBullet::_internal_set_mass(real_t p_mass) {
  851. btVector3 localInertia(0, 0, 0);
  852. int clearedCurrentFlags = btBody->getCollisionFlags();
  853. clearedCurrentFlags &= ~(btCollisionObject::CF_KINEMATIC_OBJECT | btCollisionObject::CF_STATIC_OBJECT | btCollisionObject::CF_CHARACTER_OBJECT);
  854. // Rigidbody is dynamic if and only if mass is non Zero, otherwise static
  855. const bool isDynamic = p_mass != 0.f;
  856. if (isDynamic) {
  857. if (PhysicsServer3D::BODY_MODE_RIGID != mode && PhysicsServer3D::BODY_MODE_CHARACTER != mode) {
  858. return;
  859. }
  860. m_isStatic = false;
  861. if (mainShape) {
  862. mainShape->calculateLocalInertia(p_mass, localInertia);
  863. }
  864. if (PhysicsServer3D::BODY_MODE_RIGID == mode) {
  865. btBody->setCollisionFlags(clearedCurrentFlags); // Just set the flags without Kin and Static
  866. } else {
  867. btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_CHARACTER_OBJECT);
  868. }
  869. if (can_sleep) {
  870. btBody->forceActivationState(ACTIVE_TAG); // ACTIVE_TAG 1
  871. } else {
  872. btBody->forceActivationState(DISABLE_DEACTIVATION); // DISABLE_DEACTIVATION 4
  873. }
  874. } else {
  875. if (PhysicsServer3D::BODY_MODE_STATIC != mode && PhysicsServer3D::BODY_MODE_KINEMATIC != mode) {
  876. return;
  877. }
  878. m_isStatic = true;
  879. if (PhysicsServer3D::BODY_MODE_STATIC == mode) {
  880. btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_STATIC_OBJECT);
  881. } else {
  882. btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_KINEMATIC_OBJECT);
  883. set_transform__bullet(btBody->getWorldTransform()); // Set current Transform using kinematic method
  884. }
  885. btBody->forceActivationState(DISABLE_SIMULATION); // DISABLE_SIMULATION 5
  886. }
  887. btBody->setMassProps(p_mass, localInertia);
  888. btBody->updateInertiaTensor();
  889. reload_body();
  890. }