2
0

rigid_body_bullet.cpp 34 KB

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