rigid_body_bullet.cpp 34 KB

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