rigid_body_bullet.cpp 34 KB

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