rigid_body_bullet.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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_j) {
  106. body->apply_central_impulse(p_j);
  107. }
  108. void BulletPhysicsDirectBodyState::apply_impulse(const Vector3 &p_pos, const Vector3 &p_j) {
  109. body->apply_impulse(p_pos, p_j);
  110. }
  111. void BulletPhysicsDirectBodyState::apply_torque_impulse(const Vector3 &p_j) {
  112. body->apply_torque_impulse(p_j);
  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. // Remove all eventual constraints
  274. assert_no_constraints();
  275. // Remove this object form the physics world
  276. space->remove_rigid_body(this);
  277. }
  278. space = p_space;
  279. if (space) {
  280. space->add_rigid_body(this);
  281. }
  282. }
  283. void RigidBodyBullet::dispatch_callbacks() {
  284. /// The check isFirstTransformChanged is necessary in order to call integrated forces only when the first transform is sent
  285. if ((btBody->isKinematicObject() || btBody->isActive() || previousActiveState != btBody->isActive()) && force_integration_callback && can_integrate_forces) {
  286. if (omit_forces_integration)
  287. btBody->clearForces();
  288. BulletPhysicsDirectBodyState *bodyDirect = BulletPhysicsDirectBodyState::get_singleton(this);
  289. Variant variantBodyDirect = bodyDirect;
  290. Object *obj = ObjectDB::get_instance(force_integration_callback->id);
  291. if (!obj) {
  292. // Remove integration callback
  293. set_force_integration_callback(0, StringName());
  294. } else {
  295. const Variant *vp[2] = { &variantBodyDirect, &force_integration_callback->udata };
  296. Variant::CallError responseCallError;
  297. int argc = (force_integration_callback->udata.get_type() == Variant::NIL) ? 1 : 2;
  298. obj->call(force_integration_callback->method, vp, argc, responseCallError);
  299. }
  300. }
  301. if (isScratchedSpaceOverrideModificator || 0 < countGravityPointSpaces) {
  302. isScratchedSpaceOverrideModificator = false;
  303. reload_space_override_modificator();
  304. }
  305. /// Lock axis
  306. btBody->setLinearVelocity(btBody->getLinearVelocity() * btBody->getLinearFactor());
  307. btBody->setAngularVelocity(btBody->getAngularVelocity() * btBody->getAngularFactor());
  308. previousActiveState = btBody->isActive();
  309. }
  310. void RigidBodyBullet::set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata) {
  311. if (force_integration_callback) {
  312. memdelete(force_integration_callback);
  313. force_integration_callback = NULL;
  314. }
  315. if (p_id != 0) {
  316. force_integration_callback = memnew(ForceIntegrationCallback);
  317. force_integration_callback->id = p_id;
  318. force_integration_callback->method = p_method;
  319. force_integration_callback->udata = p_udata;
  320. }
  321. }
  322. void RigidBodyBullet::scratch_space_override_modificator() {
  323. isScratchedSpaceOverrideModificator = true;
  324. }
  325. void RigidBodyBullet::on_collision_filters_change() {
  326. if (space) {
  327. space->reload_collision_filters(this);
  328. }
  329. }
  330. void RigidBodyBullet::on_collision_checker_start() {
  331. prev_collision_count = collisionsCount;
  332. collisionsCount = 0;
  333. // Swap array
  334. Vector<RigidBodyBullet *> *s = prev_collision_traces;
  335. prev_collision_traces = curr_collision_traces;
  336. curr_collision_traces = s;
  337. }
  338. void RigidBodyBullet::on_collision_checker_end() {
  339. // Always true if active and not a static or kinematic body
  340. isTransformChanged = btBody->isActive() && !btBody->isStaticOrKinematicObject();
  341. }
  342. 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) {
  343. if (collisionsCount >= maxCollisionsDetection) {
  344. return false;
  345. }
  346. CollisionData &cd = collisions.write[collisionsCount];
  347. cd.hitLocalLocation = p_hitLocalLocation;
  348. cd.otherObject = p_otherObject;
  349. cd.hitWorldLocation = p_hitWorldLocation;
  350. cd.hitNormal = p_hitNormal;
  351. cd.appliedImpulse = p_appliedImpulse;
  352. cd.other_object_shape = p_other_shape_index;
  353. cd.local_shape = p_local_shape_index;
  354. curr_collision_traces->write[collisionsCount] = p_otherObject;
  355. ++collisionsCount;
  356. return true;
  357. }
  358. bool RigidBodyBullet::was_colliding(RigidBodyBullet *p_other_object) {
  359. for (int i = prev_collision_count - 1; 0 <= i; --i) {
  360. if ((*prev_collision_traces)[i] == p_other_object)
  361. return true;
  362. }
  363. return false;
  364. }
  365. void RigidBodyBullet::assert_no_constraints() {
  366. if (btBody->getNumConstraintRefs()) {
  367. WARN_PRINT("A body with a joints is destroyed. Please check the implementation in order to destroy the joint before the body.");
  368. }
  369. /*for(int i = btBody->getNumConstraintRefs()-1; 0<=i; --i){
  370. btTypedConstraint* btConst = btBody->getConstraintRef(i);
  371. JointBullet* joint = static_cast<JointBullet*>( btConst->getUserConstraintPtr() );
  372. space->removeConstraint(joint);
  373. }*/
  374. }
  375. void RigidBodyBullet::set_activation_state(bool p_active) {
  376. if (p_active) {
  377. btBody->setActivationState(ACTIVE_TAG);
  378. } else {
  379. btBody->setActivationState(WANTS_DEACTIVATION);
  380. }
  381. }
  382. bool RigidBodyBullet::is_active() const {
  383. return btBody->isActive();
  384. }
  385. void RigidBodyBullet::set_omit_forces_integration(bool p_omit) {
  386. omit_forces_integration = p_omit;
  387. }
  388. void RigidBodyBullet::set_param(PhysicsServer::BodyParameter p_param, real_t p_value) {
  389. switch (p_param) {
  390. case PhysicsServer::BODY_PARAM_BOUNCE:
  391. btBody->setRestitution(p_value);
  392. break;
  393. case PhysicsServer::BODY_PARAM_FRICTION:
  394. btBody->setFriction(p_value);
  395. break;
  396. case PhysicsServer::BODY_PARAM_MASS: {
  397. ERR_FAIL_COND(p_value < 0);
  398. mass = p_value;
  399. _internal_set_mass(p_value);
  400. break;
  401. }
  402. case PhysicsServer::BODY_PARAM_LINEAR_DAMP:
  403. linearDamp = p_value;
  404. btBody->setDamping(linearDamp, angularDamp);
  405. break;
  406. case PhysicsServer::BODY_PARAM_ANGULAR_DAMP:
  407. angularDamp = p_value;
  408. btBody->setDamping(linearDamp, angularDamp);
  409. break;
  410. case PhysicsServer::BODY_PARAM_GRAVITY_SCALE:
  411. gravity_scale = p_value;
  412. /// The Bullet gravity will be is set by reload_space_override_modificator
  413. scratch_space_override_modificator();
  414. break;
  415. default:
  416. WARN_PRINTS("Parameter " + itos(p_param) + " not supported by bullet. Value: " + itos(p_value));
  417. }
  418. }
  419. real_t RigidBodyBullet::get_param(PhysicsServer::BodyParameter p_param) const {
  420. switch (p_param) {
  421. case PhysicsServer::BODY_PARAM_BOUNCE:
  422. return btBody->getRestitution();
  423. case PhysicsServer::BODY_PARAM_FRICTION:
  424. return btBody->getFriction();
  425. case PhysicsServer::BODY_PARAM_MASS: {
  426. const btScalar invMass = btBody->getInvMass();
  427. return 0 == invMass ? 0 : 1 / invMass;
  428. }
  429. case PhysicsServer::BODY_PARAM_LINEAR_DAMP:
  430. return linearDamp;
  431. case PhysicsServer::BODY_PARAM_ANGULAR_DAMP:
  432. return angularDamp;
  433. case PhysicsServer::BODY_PARAM_GRAVITY_SCALE:
  434. return gravity_scale;
  435. default:
  436. WARN_PRINTS("Parameter " + itos(p_param) + " not supported by bullet");
  437. return 0;
  438. }
  439. }
  440. void RigidBodyBullet::set_mode(PhysicsServer::BodyMode p_mode) {
  441. // This is necessary to block force_integration untile next move
  442. can_integrate_forces = false;
  443. destroy_kinematic_utilities();
  444. // The mode change is relevant to its mass
  445. switch (p_mode) {
  446. case PhysicsServer::BODY_MODE_KINEMATIC:
  447. mode = PhysicsServer::BODY_MODE_KINEMATIC;
  448. reload_axis_lock();
  449. _internal_set_mass(0);
  450. init_kinematic_utilities();
  451. break;
  452. case PhysicsServer::BODY_MODE_STATIC:
  453. mode = PhysicsServer::BODY_MODE_STATIC;
  454. reload_axis_lock();
  455. _internal_set_mass(0);
  456. break;
  457. case PhysicsServer::BODY_MODE_RIGID:
  458. mode = PhysicsServer::BODY_MODE_RIGID;
  459. reload_axis_lock();
  460. _internal_set_mass(0 == mass ? 1 : mass);
  461. scratch_space_override_modificator();
  462. break;
  463. case PhysicsServer::BODY_MODE_CHARACTER:
  464. mode = PhysicsServer::BODY_MODE_CHARACTER;
  465. reload_axis_lock();
  466. _internal_set_mass(0 == mass ? 1 : mass);
  467. scratch_space_override_modificator();
  468. break;
  469. }
  470. btBody->setAngularVelocity(btVector3(0, 0, 0));
  471. btBody->setLinearVelocity(btVector3(0, 0, 0));
  472. }
  473. PhysicsServer::BodyMode RigidBodyBullet::get_mode() const {
  474. return mode;
  475. }
  476. void RigidBodyBullet::set_state(PhysicsServer::BodyState p_state, const Variant &p_variant) {
  477. switch (p_state) {
  478. case PhysicsServer::BODY_STATE_TRANSFORM:
  479. set_transform(p_variant);
  480. break;
  481. case PhysicsServer::BODY_STATE_LINEAR_VELOCITY:
  482. set_linear_velocity(p_variant);
  483. break;
  484. case PhysicsServer::BODY_STATE_ANGULAR_VELOCITY:
  485. set_angular_velocity(p_variant);
  486. break;
  487. case PhysicsServer::BODY_STATE_SLEEPING:
  488. set_activation_state(!bool(p_variant));
  489. break;
  490. case PhysicsServer::BODY_STATE_CAN_SLEEP:
  491. can_sleep = bool(p_variant);
  492. if (!can_sleep) {
  493. // Can't sleep
  494. btBody->forceActivationState(DISABLE_DEACTIVATION);
  495. }
  496. break;
  497. }
  498. }
  499. Variant RigidBodyBullet::get_state(PhysicsServer::BodyState p_state) const {
  500. switch (p_state) {
  501. case PhysicsServer::BODY_STATE_TRANSFORM:
  502. return get_transform();
  503. case PhysicsServer::BODY_STATE_LINEAR_VELOCITY:
  504. return get_linear_velocity();
  505. case PhysicsServer::BODY_STATE_ANGULAR_VELOCITY:
  506. return get_angular_velocity();
  507. case PhysicsServer::BODY_STATE_SLEEPING:
  508. return !is_active();
  509. case PhysicsServer::BODY_STATE_CAN_SLEEP:
  510. return can_sleep;
  511. default:
  512. WARN_PRINTS("This state " + itos(p_state) + " is not supported by Bullet");
  513. return Variant();
  514. }
  515. }
  516. void RigidBodyBullet::apply_central_impulse(const Vector3 &p_impulse) {
  517. btVector3 btImpu;
  518. G_TO_B(p_impulse, btImpu);
  519. if (Vector3() != p_impulse)
  520. btBody->activate();
  521. btBody->applyCentralImpulse(btImpu);
  522. }
  523. void RigidBodyBullet::apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse) {
  524. btVector3 btImpu;
  525. btVector3 btPos;
  526. G_TO_B(p_impulse, btImpu);
  527. G_TO_B(p_pos, btPos);
  528. if (Vector3() != p_impulse)
  529. btBody->activate();
  530. btBody->applyImpulse(btImpu, btPos);
  531. }
  532. void RigidBodyBullet::apply_torque_impulse(const Vector3 &p_impulse) {
  533. btVector3 btImp;
  534. G_TO_B(p_impulse, btImp);
  535. if (Vector3() != p_impulse)
  536. btBody->activate();
  537. btBody->applyTorqueImpulse(btImp);
  538. }
  539. void RigidBodyBullet::apply_force(const Vector3 &p_force, const Vector3 &p_pos) {
  540. btVector3 btForce;
  541. btVector3 btPos;
  542. G_TO_B(p_force, btForce);
  543. G_TO_B(p_pos, btPos);
  544. if (Vector3() != p_force)
  545. btBody->activate();
  546. btBody->applyForce(btForce, btPos);
  547. }
  548. void RigidBodyBullet::apply_central_force(const Vector3 &p_force) {
  549. btVector3 btForce;
  550. G_TO_B(p_force, btForce);
  551. if (Vector3() != p_force)
  552. btBody->activate();
  553. btBody->applyCentralForce(btForce);
  554. }
  555. void RigidBodyBullet::apply_torque(const Vector3 &p_torque) {
  556. btVector3 btTorq;
  557. G_TO_B(p_torque, btTorq);
  558. if (Vector3() != p_torque)
  559. btBody->activate();
  560. btBody->applyTorque(btTorq);
  561. }
  562. void RigidBodyBullet::set_applied_force(const Vector3 &p_force) {
  563. btVector3 btVec = btBody->getTotalTorque();
  564. if (Vector3() != p_force)
  565. btBody->activate();
  566. btBody->clearForces();
  567. btBody->applyTorque(btVec);
  568. G_TO_B(p_force, btVec);
  569. btBody->applyCentralForce(btVec);
  570. }
  571. Vector3 RigidBodyBullet::get_applied_force() const {
  572. Vector3 gTotForc;
  573. B_TO_G(btBody->getTotalForce(), gTotForc);
  574. return gTotForc;
  575. }
  576. void RigidBodyBullet::set_applied_torque(const Vector3 &p_torque) {
  577. btVector3 btVec = btBody->getTotalForce();
  578. if (Vector3() != p_torque)
  579. btBody->activate();
  580. btBody->clearForces();
  581. btBody->applyCentralForce(btVec);
  582. G_TO_B(p_torque, btVec);
  583. btBody->applyTorque(btVec);
  584. }
  585. Vector3 RigidBodyBullet::get_applied_torque() const {
  586. Vector3 gTotTorq;
  587. B_TO_G(btBody->getTotalTorque(), gTotTorq);
  588. return gTotTorq;
  589. }
  590. void RigidBodyBullet::set_axis_lock(PhysicsServer::BodyAxis p_axis, bool lock) {
  591. if (lock) {
  592. locked_axis |= p_axis;
  593. } else {
  594. locked_axis &= ~p_axis;
  595. }
  596. reload_axis_lock();
  597. }
  598. bool RigidBodyBullet::is_axis_locked(PhysicsServer::BodyAxis p_axis) const {
  599. return locked_axis & p_axis;
  600. }
  601. void RigidBodyBullet::reload_axis_lock() {
  602. btBody->setLinearFactor(btVector3(!is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_X), !is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_Y), !is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_Z)));
  603. if (PhysicsServer::BODY_MODE_CHARACTER == mode) {
  604. /// When character angular is always locked
  605. btBody->setAngularFactor(btVector3(0., 0., 0.));
  606. } else {
  607. btBody->setAngularFactor(btVector3(!is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_X), !is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_Y), !is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_Z)));
  608. }
  609. }
  610. void RigidBodyBullet::set_continuous_collision_detection(bool p_enable) {
  611. if (p_enable) {
  612. // This threshold enable CCD if the object moves more than
  613. // 1 meter in one simulation frame
  614. btBody->setCcdMotionThreshold(0.1);
  615. /// Calculate using the rule writte below the CCD swept sphere radius
  616. /// CCD works on an embedded sphere of radius, make sure this radius
  617. /// is embedded inside the convex objects, preferably smaller:
  618. /// for an object of dimensions 1 meter, try 0.2
  619. btScalar radius;
  620. if (btBody->getCollisionShape()) {
  621. btVector3 center;
  622. btBody->getCollisionShape()->getBoundingSphere(center, radius);
  623. } else {
  624. radius = 0;
  625. }
  626. btBody->setCcdSweptSphereRadius(radius * 0.2);
  627. } else {
  628. btBody->setCcdMotionThreshold(0.);
  629. btBody->setCcdSweptSphereRadius(0.);
  630. }
  631. }
  632. bool RigidBodyBullet::is_continuous_collision_detection_enabled() const {
  633. return 0. < btBody->getCcdMotionThreshold();
  634. }
  635. void RigidBodyBullet::set_linear_velocity(const Vector3 &p_velocity) {
  636. btVector3 btVec;
  637. G_TO_B(p_velocity, btVec);
  638. if (Vector3() != p_velocity)
  639. btBody->activate();
  640. btBody->setLinearVelocity(btVec);
  641. }
  642. Vector3 RigidBodyBullet::get_linear_velocity() const {
  643. Vector3 gVec;
  644. B_TO_G(btBody->getLinearVelocity(), gVec);
  645. return gVec;
  646. }
  647. void RigidBodyBullet::set_angular_velocity(const Vector3 &p_velocity) {
  648. btVector3 btVec;
  649. G_TO_B(p_velocity, btVec);
  650. if (Vector3() != p_velocity)
  651. btBody->activate();
  652. btBody->setAngularVelocity(btVec);
  653. }
  654. Vector3 RigidBodyBullet::get_angular_velocity() const {
  655. Vector3 gVec;
  656. B_TO_G(btBody->getAngularVelocity(), gVec);
  657. return gVec;
  658. }
  659. void RigidBodyBullet::set_transform__bullet(const btTransform &p_global_transform) {
  660. if (mode == PhysicsServer::BODY_MODE_KINEMATIC) {
  661. if (space)
  662. btBody->setLinearVelocity((p_global_transform.getOrigin() - btBody->getWorldTransform().getOrigin()) / space->get_delta_time());
  663. // The kinematic use MotionState class
  664. godotMotionState->moveBody(p_global_transform);
  665. }
  666. CollisionObjectBullet::set_transform__bullet(p_global_transform);
  667. }
  668. const btTransform &RigidBodyBullet::get_transform__bullet() const {
  669. if (is_static()) {
  670. return RigidCollisionObjectBullet::get_transform__bullet();
  671. } else {
  672. return godotMotionState->getCurrentWorldTransform();
  673. }
  674. }
  675. void RigidBodyBullet::reload_shapes() {
  676. RigidCollisionObjectBullet::reload_shapes();
  677. const btScalar invMass = btBody->getInvMass();
  678. const btScalar mass = invMass == 0 ? 0 : 1 / invMass;
  679. if (mainShape) {
  680. // inertia initialised zero here because some of bullet's collision
  681. // shapes incorrectly do not set the vector in calculateLocalIntertia.
  682. // Arbitrary zero is preferable to undefined behaviour.
  683. btVector3 inertia(0, 0, 0);
  684. mainShape->calculateLocalInertia(mass, inertia);
  685. btBody->setMassProps(mass, inertia);
  686. }
  687. btBody->updateInertiaTensor();
  688. reload_kinematic_shapes();
  689. reload_body();
  690. }
  691. void RigidBodyBullet::on_enter_area(AreaBullet *p_area) {
  692. /// Add this area to the array in an ordered way
  693. ++areaWhereIamCount;
  694. if (areaWhereIamCount >= maxAreasWhereIam) {
  695. --areaWhereIamCount;
  696. return;
  697. }
  698. for (int i = 0; i < areaWhereIamCount; ++i) {
  699. if (NULL == areasWhereIam[i]) {
  700. // This area has the highest priority
  701. areasWhereIam.write[i] = p_area;
  702. break;
  703. } else {
  704. if (areasWhereIam[i]->get_spOv_priority() > p_area->get_spOv_priority()) {
  705. // The position was found, just shift all elements
  706. for (int j = i; j < areaWhereIamCount; ++j) {
  707. areasWhereIam.write[j + 1] = areasWhereIam[j];
  708. }
  709. areasWhereIam.write[i] = p_area;
  710. break;
  711. }
  712. }
  713. }
  714. if (PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED != p_area->get_spOv_mode()) {
  715. scratch_space_override_modificator();
  716. }
  717. if (p_area->is_spOv_gravityPoint()) {
  718. ++countGravityPointSpaces;
  719. assert(0 < countGravityPointSpaces);
  720. }
  721. }
  722. void RigidBodyBullet::on_exit_area(AreaBullet *p_area) {
  723. RigidCollisionObjectBullet::on_exit_area(p_area);
  724. /// Remove this area and keep the order
  725. /// N.B. Since I don't want resize the array I can't use the "erase" function
  726. bool wasTheAreaFound = false;
  727. for (int i = 0; i < areaWhereIamCount; ++i) {
  728. if (p_area == areasWhereIam[i]) {
  729. // The area was found, just shift down all elements
  730. for (int j = i; j < areaWhereIamCount; ++j) {
  731. areasWhereIam.write[j] = areasWhereIam[j + 1];
  732. }
  733. wasTheAreaFound = true;
  734. break;
  735. }
  736. }
  737. if (wasTheAreaFound) {
  738. if (p_area->is_spOv_gravityPoint()) {
  739. --countGravityPointSpaces;
  740. assert(0 <= countGravityPointSpaces);
  741. }
  742. --areaWhereIamCount;
  743. areasWhereIam.write[areaWhereIamCount] = NULL; // Even if this is not required, I clear the last element to be safe
  744. if (PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED != p_area->get_spOv_mode()) {
  745. scratch_space_override_modificator();
  746. }
  747. }
  748. }
  749. void RigidBodyBullet::reload_space_override_modificator() {
  750. // Make sure that kinematic bodies have their total gravity calculated
  751. if (!is_active() && PhysicsServer::BODY_MODE_KINEMATIC != mode)
  752. return;
  753. Vector3 newGravity(space->get_gravity_direction() * space->get_gravity_magnitude());
  754. real_t newLinearDamp(linearDamp);
  755. real_t newAngularDamp(angularDamp);
  756. AreaBullet *currentArea;
  757. // Variable used to calculate new gravity for gravity point areas, it is pointed by currentGravity pointer
  758. Vector3 support_gravity(0, 0, 0);
  759. int countCombined(0);
  760. for (int i = areaWhereIamCount - 1; 0 <= i; --i) {
  761. currentArea = areasWhereIam[i];
  762. if (PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED == currentArea->get_spOv_mode()) {
  763. continue;
  764. }
  765. /// Here is calculated the gravity
  766. if (currentArea->is_spOv_gravityPoint()) {
  767. /// It calculates the direction of new gravity
  768. support_gravity = currentArea->get_transform().xform(currentArea->get_spOv_gravityVec()) - get_transform().get_origin();
  769. real_t distanceMag = support_gravity.length();
  770. // Normalized in this way to avoid the double call of function "length()"
  771. if (distanceMag == 0) {
  772. support_gravity.x = 0;
  773. support_gravity.y = 0;
  774. support_gravity.z = 0;
  775. } else {
  776. support_gravity.x /= distanceMag;
  777. support_gravity.y /= distanceMag;
  778. support_gravity.z /= distanceMag;
  779. }
  780. /// Here is calculated the final gravity
  781. if (currentArea->get_spOv_gravityPointDistanceScale() > 0) {
  782. // Scaled gravity by distance
  783. support_gravity *= currentArea->get_spOv_gravityMag() / Math::pow(distanceMag * currentArea->get_spOv_gravityPointDistanceScale() + 1, 2);
  784. } else {
  785. // Unscaled gravity
  786. support_gravity *= currentArea->get_spOv_gravityMag();
  787. }
  788. } else {
  789. support_gravity = currentArea->get_spOv_gravityVec() * currentArea->get_spOv_gravityMag();
  790. }
  791. switch (currentArea->get_spOv_mode()) {
  792. case PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED:
  793. /// This area does not affect gravity/damp. These are generally areas
  794. /// that exist only to detect collisions, and objects entering or exiting them.
  795. break;
  796. case PhysicsServer::AREA_SPACE_OVERRIDE_COMBINE:
  797. /// This area adds its gravity/damp values to whatever has been
  798. /// calculated so far. This way, many overlapping areas can combine
  799. /// their physics to make interesting
  800. newGravity += support_gravity;
  801. newLinearDamp += currentArea->get_spOv_linearDamp();
  802. newAngularDamp += currentArea->get_spOv_angularDamp();
  803. ++countCombined;
  804. break;
  805. case PhysicsServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE:
  806. /// This area adds its gravity/damp values to whatever has been calculated
  807. /// so far. Then stops taking into account the rest of the areas, even the
  808. /// default one.
  809. newGravity += support_gravity;
  810. newLinearDamp += currentArea->get_spOv_linearDamp();
  811. newAngularDamp += currentArea->get_spOv_angularDamp();
  812. ++countCombined;
  813. goto endAreasCycle;
  814. case PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE:
  815. /// This area replaces any gravity/damp, even the default one, and
  816. /// stops taking into account the rest of the areas.
  817. newGravity = support_gravity;
  818. newLinearDamp = currentArea->get_spOv_linearDamp();
  819. newAngularDamp = currentArea->get_spOv_angularDamp();
  820. countCombined = 1;
  821. goto endAreasCycle;
  822. case PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE_COMBINE:
  823. /// This area replaces any gravity/damp calculated so far, but keeps
  824. /// calculating the rest of the areas, down to the default one.
  825. newGravity = support_gravity;
  826. newLinearDamp = currentArea->get_spOv_linearDamp();
  827. newAngularDamp = currentArea->get_spOv_angularDamp();
  828. countCombined = 1;
  829. break;
  830. }
  831. }
  832. endAreasCycle:
  833. if (1 < countCombined) {
  834. newGravity /= countCombined;
  835. newLinearDamp /= countCombined;
  836. newAngularDamp /= countCombined;
  837. }
  838. btVector3 newBtGravity;
  839. G_TO_B(newGravity * gravity_scale, newBtGravity);
  840. btBody->setGravity(newBtGravity);
  841. btBody->setDamping(newLinearDamp, newAngularDamp);
  842. }
  843. void RigidBodyBullet::reload_kinematic_shapes() {
  844. if (!kinematic_utilities) {
  845. return;
  846. }
  847. kinematic_utilities->copyAllOwnerShapes();
  848. }
  849. void RigidBodyBullet::notify_transform_changed() {
  850. RigidCollisionObjectBullet::notify_transform_changed();
  851. can_integrate_forces = true;
  852. }
  853. void RigidBodyBullet::_internal_set_mass(real_t p_mass) {
  854. btVector3 localInertia(0, 0, 0);
  855. int clearedCurrentFlags = btBody->getCollisionFlags();
  856. clearedCurrentFlags &= ~(btCollisionObject::CF_KINEMATIC_OBJECT | btCollisionObject::CF_STATIC_OBJECT | btCollisionObject::CF_CHARACTER_OBJECT);
  857. // Rigidbody is dynamic if and only if mass is non Zero, otherwise static
  858. const bool isDynamic = p_mass != 0.f;
  859. if (isDynamic) {
  860. if (PhysicsServer::BODY_MODE_RIGID != mode && PhysicsServer::BODY_MODE_CHARACTER != mode)
  861. return;
  862. m_isStatic = false;
  863. if (mainShape)
  864. mainShape->calculateLocalInertia(p_mass, localInertia);
  865. if (PhysicsServer::BODY_MODE_RIGID == mode) {
  866. btBody->setCollisionFlags(clearedCurrentFlags); // Just set the flags without Kin and Static
  867. } else {
  868. btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_CHARACTER_OBJECT);
  869. }
  870. if (can_sleep) {
  871. btBody->forceActivationState(ACTIVE_TAG); // ACTIVE_TAG 1
  872. } else {
  873. btBody->forceActivationState(DISABLE_DEACTIVATION); // DISABLE_DEACTIVATION 4
  874. }
  875. } else {
  876. if (PhysicsServer::BODY_MODE_STATIC != mode && PhysicsServer::BODY_MODE_KINEMATIC != mode)
  877. return;
  878. m_isStatic = true;
  879. if (PhysicsServer::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. }