vehicle_body_3d.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. /**************************************************************************/
  2. /* vehicle_body_3d.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 "vehicle_body_3d.h"
  31. #define ROLLING_INFLUENCE_FIX
  32. class btVehicleJacobianEntry {
  33. public:
  34. Vector3 m_linearJointAxis;
  35. Vector3 m_aJ;
  36. Vector3 m_bJ;
  37. Vector3 m_0MinvJt;
  38. Vector3 m_1MinvJt;
  39. //Optimization: can be stored in the w/last component of one of the vectors
  40. real_t m_Adiag = 0.0;
  41. real_t getDiagonal() const { return m_Adiag; }
  42. btVehicleJacobianEntry() {}
  43. //constraint between two different rigidbodies
  44. btVehicleJacobianEntry(
  45. const Basis &world2A,
  46. const Basis &world2B,
  47. const Vector3 &rel_pos1,
  48. const Vector3 &rel_pos2,
  49. const Vector3 &jointAxis,
  50. const Vector3 &inertiaInvA,
  51. const real_t massInvA,
  52. const Vector3 &inertiaInvB,
  53. const real_t massInvB) :
  54. m_linearJointAxis(jointAxis) {
  55. m_aJ = world2A.xform(rel_pos1.cross(m_linearJointAxis));
  56. m_bJ = world2B.xform(rel_pos2.cross(-m_linearJointAxis));
  57. m_0MinvJt = inertiaInvA * m_aJ;
  58. m_1MinvJt = inertiaInvB * m_bJ;
  59. m_Adiag = massInvA + m_0MinvJt.dot(m_aJ) + massInvB + m_1MinvJt.dot(m_bJ);
  60. //btAssert(m_Adiag > real_t(0.0));
  61. }
  62. real_t getRelativeVelocity(const Vector3 &linvelA, const Vector3 &angvelA, const Vector3 &linvelB, const Vector3 &angvelB) {
  63. Vector3 linrel = linvelA - linvelB;
  64. Vector3 angvela = angvelA * m_aJ;
  65. Vector3 angvelb = angvelB * m_bJ;
  66. linrel *= m_linearJointAxis;
  67. angvela += angvelb;
  68. angvela += linrel;
  69. real_t rel_vel2 = angvela[0] + angvela[1] + angvela[2];
  70. return rel_vel2 + CMP_EPSILON;
  71. }
  72. };
  73. void VehicleWheel3D::_notification(int p_what) {
  74. switch (p_what) {
  75. case NOTIFICATION_ENTER_TREE: {
  76. VehicleBody3D *cb = Object::cast_to<VehicleBody3D>(get_parent());
  77. if (!cb) {
  78. return;
  79. }
  80. body = cb;
  81. local_xform = get_transform();
  82. cb->wheels.push_back(this);
  83. m_chassisConnectionPointCS = get_transform().origin;
  84. m_wheelDirectionCS = -get_transform().basis.get_column(Vector3::AXIS_Y).normalized();
  85. m_wheelAxleCS = get_transform().basis.get_column(Vector3::AXIS_X).normalized();
  86. } break;
  87. case NOTIFICATION_EXIT_TREE: {
  88. VehicleBody3D *cb = Object::cast_to<VehicleBody3D>(get_parent());
  89. if (!cb) {
  90. return;
  91. }
  92. cb->wheels.erase(this);
  93. body = nullptr;
  94. } break;
  95. }
  96. }
  97. PackedStringArray VehicleWheel3D::get_configuration_warnings() const {
  98. PackedStringArray warnings = Node::get_configuration_warnings();
  99. if (!Object::cast_to<VehicleBody3D>(get_parent())) {
  100. warnings.push_back(RTR("VehicleWheel3D serves to provide a wheel system to a VehicleBody3D. Please use it as a child of a VehicleBody3D."));
  101. }
  102. return warnings;
  103. }
  104. void VehicleWheel3D::_update(PhysicsDirectBodyState3D *s) {
  105. if (m_raycastInfo.m_isInContact) {
  106. real_t project = m_raycastInfo.m_contactNormalWS.dot(m_raycastInfo.m_wheelDirectionWS);
  107. Vector3 chassis_velocity_at_contactPoint;
  108. Vector3 relpos = m_raycastInfo.m_contactPointWS - s->get_transform().origin;
  109. chassis_velocity_at_contactPoint = s->get_linear_velocity() +
  110. (s->get_angular_velocity()).cross(relpos); // * mPos);
  111. real_t projVel = m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint);
  112. if (project >= real_t(-0.1)) {
  113. m_suspensionRelativeVelocity = real_t(0.0);
  114. m_clippedInvContactDotSuspension = real_t(1.0) / real_t(0.1);
  115. } else {
  116. real_t inv = real_t(-1.) / project;
  117. m_suspensionRelativeVelocity = projVel * inv;
  118. m_clippedInvContactDotSuspension = inv;
  119. }
  120. } else { // Not in contact : position wheel in a nice (rest length) position
  121. m_raycastInfo.m_suspensionLength = m_suspensionRestLength;
  122. m_suspensionRelativeVelocity = real_t(0.0);
  123. m_raycastInfo.m_contactNormalWS = -m_raycastInfo.m_wheelDirectionWS;
  124. m_clippedInvContactDotSuspension = real_t(1.0);
  125. }
  126. }
  127. void VehicleWheel3D::set_radius(real_t p_radius) {
  128. m_wheelRadius = p_radius;
  129. update_gizmos();
  130. }
  131. real_t VehicleWheel3D::get_radius() const {
  132. return m_wheelRadius;
  133. }
  134. void VehicleWheel3D::set_suspension_rest_length(real_t p_length) {
  135. m_suspensionRestLength = p_length;
  136. update_gizmos();
  137. }
  138. real_t VehicleWheel3D::get_suspension_rest_length() const {
  139. return m_suspensionRestLength;
  140. }
  141. void VehicleWheel3D::set_suspension_travel(real_t p_length) {
  142. m_maxSuspensionTravel = p_length;
  143. }
  144. real_t VehicleWheel3D::get_suspension_travel() const {
  145. return m_maxSuspensionTravel;
  146. }
  147. void VehicleWheel3D::set_suspension_stiffness(real_t p_value) {
  148. m_suspensionStiffness = p_value;
  149. }
  150. real_t VehicleWheel3D::get_suspension_stiffness() const {
  151. return m_suspensionStiffness;
  152. }
  153. void VehicleWheel3D::set_suspension_max_force(real_t p_value) {
  154. m_maxSuspensionForce = p_value;
  155. }
  156. real_t VehicleWheel3D::get_suspension_max_force() const {
  157. return m_maxSuspensionForce;
  158. }
  159. void VehicleWheel3D::set_damping_compression(real_t p_value) {
  160. m_wheelsDampingCompression = p_value;
  161. }
  162. real_t VehicleWheel3D::get_damping_compression() const {
  163. return m_wheelsDampingCompression;
  164. }
  165. void VehicleWheel3D::set_damping_relaxation(real_t p_value) {
  166. m_wheelsDampingRelaxation = p_value;
  167. }
  168. real_t VehicleWheel3D::get_damping_relaxation() const {
  169. return m_wheelsDampingRelaxation;
  170. }
  171. void VehicleWheel3D::set_friction_slip(real_t p_value) {
  172. m_frictionSlip = p_value;
  173. }
  174. real_t VehicleWheel3D::get_friction_slip() const {
  175. return m_frictionSlip;
  176. }
  177. void VehicleWheel3D::set_roll_influence(real_t p_value) {
  178. m_rollInfluence = p_value;
  179. }
  180. real_t VehicleWheel3D::get_roll_influence() const {
  181. return m_rollInfluence;
  182. }
  183. bool VehicleWheel3D::is_in_contact() const {
  184. return m_raycastInfo.m_isInContact;
  185. }
  186. Node3D *VehicleWheel3D::get_contact_body() const {
  187. return m_raycastInfo.m_groundObject;
  188. }
  189. void VehicleWheel3D::_bind_methods() {
  190. ClassDB::bind_method(D_METHOD("set_radius", "length"), &VehicleWheel3D::set_radius);
  191. ClassDB::bind_method(D_METHOD("get_radius"), &VehicleWheel3D::get_radius);
  192. ClassDB::bind_method(D_METHOD("set_suspension_rest_length", "length"), &VehicleWheel3D::set_suspension_rest_length);
  193. ClassDB::bind_method(D_METHOD("get_suspension_rest_length"), &VehicleWheel3D::get_suspension_rest_length);
  194. ClassDB::bind_method(D_METHOD("set_suspension_travel", "length"), &VehicleWheel3D::set_suspension_travel);
  195. ClassDB::bind_method(D_METHOD("get_suspension_travel"), &VehicleWheel3D::get_suspension_travel);
  196. ClassDB::bind_method(D_METHOD("set_suspension_stiffness", "length"), &VehicleWheel3D::set_suspension_stiffness);
  197. ClassDB::bind_method(D_METHOD("get_suspension_stiffness"), &VehicleWheel3D::get_suspension_stiffness);
  198. ClassDB::bind_method(D_METHOD("set_suspension_max_force", "length"), &VehicleWheel3D::set_suspension_max_force);
  199. ClassDB::bind_method(D_METHOD("get_suspension_max_force"), &VehicleWheel3D::get_suspension_max_force);
  200. ClassDB::bind_method(D_METHOD("set_damping_compression", "length"), &VehicleWheel3D::set_damping_compression);
  201. ClassDB::bind_method(D_METHOD("get_damping_compression"), &VehicleWheel3D::get_damping_compression);
  202. ClassDB::bind_method(D_METHOD("set_damping_relaxation", "length"), &VehicleWheel3D::set_damping_relaxation);
  203. ClassDB::bind_method(D_METHOD("get_damping_relaxation"), &VehicleWheel3D::get_damping_relaxation);
  204. ClassDB::bind_method(D_METHOD("set_use_as_traction", "enable"), &VehicleWheel3D::set_use_as_traction);
  205. ClassDB::bind_method(D_METHOD("is_used_as_traction"), &VehicleWheel3D::is_used_as_traction);
  206. ClassDB::bind_method(D_METHOD("set_use_as_steering", "enable"), &VehicleWheel3D::set_use_as_steering);
  207. ClassDB::bind_method(D_METHOD("is_used_as_steering"), &VehicleWheel3D::is_used_as_steering);
  208. ClassDB::bind_method(D_METHOD("set_friction_slip", "length"), &VehicleWheel3D::set_friction_slip);
  209. ClassDB::bind_method(D_METHOD("get_friction_slip"), &VehicleWheel3D::get_friction_slip);
  210. ClassDB::bind_method(D_METHOD("is_in_contact"), &VehicleWheel3D::is_in_contact);
  211. ClassDB::bind_method(D_METHOD("get_contact_body"), &VehicleWheel3D::get_contact_body);
  212. ClassDB::bind_method(D_METHOD("set_roll_influence", "roll_influence"), &VehicleWheel3D::set_roll_influence);
  213. ClassDB::bind_method(D_METHOD("get_roll_influence"), &VehicleWheel3D::get_roll_influence);
  214. ClassDB::bind_method(D_METHOD("get_skidinfo"), &VehicleWheel3D::get_skidinfo);
  215. ClassDB::bind_method(D_METHOD("get_rpm"), &VehicleWheel3D::get_rpm);
  216. ClassDB::bind_method(D_METHOD("set_engine_force", "engine_force"), &VehicleWheel3D::set_engine_force);
  217. ClassDB::bind_method(D_METHOD("get_engine_force"), &VehicleWheel3D::get_engine_force);
  218. ClassDB::bind_method(D_METHOD("set_brake", "brake"), &VehicleWheel3D::set_brake);
  219. ClassDB::bind_method(D_METHOD("get_brake"), &VehicleWheel3D::get_brake);
  220. ClassDB::bind_method(D_METHOD("set_steering", "steering"), &VehicleWheel3D::set_steering);
  221. ClassDB::bind_method(D_METHOD("get_steering"), &VehicleWheel3D::get_steering);
  222. ADD_GROUP("Per-Wheel Motion", "");
  223. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "engine_force", PROPERTY_HINT_RANGE, U"-1024,1024,0.01,or_less,or_greater,suffix:kg\u22C5m/s\u00B2 (N)"), "set_engine_force", "get_engine_force");
  224. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "brake", PROPERTY_HINT_RANGE, U"-128,128,0.01,or_less,or_greater,suffix:kg\u22C5m/s\u00B2 (N)"), "set_brake", "get_brake");
  225. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "steering", PROPERTY_HINT_RANGE, "-180,180,0.01,radians_as_degrees"), "set_steering", "get_steering");
  226. ADD_GROUP("VehicleBody3D Motion", "");
  227. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_as_traction"), "set_use_as_traction", "is_used_as_traction");
  228. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_as_steering"), "set_use_as_steering", "is_used_as_steering");
  229. ADD_GROUP("Wheel", "wheel_");
  230. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wheel_roll_influence"), "set_roll_influence", "get_roll_influence");
  231. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wheel_radius", PROPERTY_HINT_NONE, "suffix:m"), "set_radius", "get_radius");
  232. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wheel_rest_length", PROPERTY_HINT_NONE, "suffix:m"), "set_suspension_rest_length", "get_suspension_rest_length");
  233. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wheel_friction_slip"), "set_friction_slip", "get_friction_slip");
  234. ADD_GROUP("Suspension", "suspension_");
  235. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "suspension_travel", PROPERTY_HINT_NONE, "suffix:m"), "set_suspension_travel", "get_suspension_travel");
  236. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "suspension_stiffness"), "set_suspension_stiffness", "get_suspension_stiffness");
  237. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "suspension_max_force", PROPERTY_HINT_NONE, U"suffix:kg\u22C5m/s\u00B2 (N)"), "set_suspension_max_force", "get_suspension_max_force");
  238. ADD_GROUP("Damping", "damping_");
  239. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "damping_compression"), "set_damping_compression", "get_damping_compression");
  240. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "damping_relaxation"), "set_damping_relaxation", "get_damping_relaxation");
  241. }
  242. void VehicleWheel3D::set_engine_force(real_t p_engine_force) {
  243. m_engineForce = p_engine_force;
  244. }
  245. real_t VehicleWheel3D::get_engine_force() const {
  246. return m_engineForce;
  247. }
  248. void VehicleWheel3D::set_brake(real_t p_brake) {
  249. m_brake = p_brake;
  250. }
  251. real_t VehicleWheel3D::get_brake() const {
  252. return m_brake;
  253. }
  254. void VehicleWheel3D::set_steering(real_t p_steering) {
  255. m_steering = p_steering;
  256. }
  257. real_t VehicleWheel3D::get_steering() const {
  258. return m_steering;
  259. }
  260. void VehicleWheel3D::set_use_as_traction(bool p_enable) {
  261. engine_traction = p_enable;
  262. }
  263. bool VehicleWheel3D::is_used_as_traction() const {
  264. return engine_traction;
  265. }
  266. void VehicleWheel3D::set_use_as_steering(bool p_enabled) {
  267. steers = p_enabled;
  268. }
  269. bool VehicleWheel3D::is_used_as_steering() const {
  270. return steers;
  271. }
  272. real_t VehicleWheel3D::get_skidinfo() const {
  273. return m_skidInfo;
  274. }
  275. real_t VehicleWheel3D::get_rpm() const {
  276. return m_rpm;
  277. }
  278. VehicleWheel3D::VehicleWheel3D() {
  279. }
  280. void VehicleBody3D::_update_wheel_transform(VehicleWheel3D &wheel, PhysicsDirectBodyState3D *s) {
  281. wheel.m_raycastInfo.m_isInContact = false;
  282. Transform3D chassisTrans = s->get_transform();
  283. /*
  284. if (interpolatedTransform && (getRigidBody()->getMotionState())) {
  285. getRigidBody()->getMotionState()->getWorldTransform(chassisTrans);
  286. }
  287. */
  288. wheel.m_raycastInfo.m_hardPointWS = chassisTrans.xform(wheel.m_chassisConnectionPointCS);
  289. //wheel.m_raycastInfo.m_hardPointWS+=s->get_linear_velocity()*s->get_step();
  290. wheel.m_raycastInfo.m_wheelDirectionWS = chassisTrans.get_basis().xform(wheel.m_wheelDirectionCS).normalized();
  291. wheel.m_raycastInfo.m_wheelAxleWS = chassisTrans.get_basis().xform(wheel.m_wheelAxleCS).normalized();
  292. }
  293. void VehicleBody3D::_update_wheel(int p_idx, PhysicsDirectBodyState3D *s) {
  294. VehicleWheel3D &wheel = *wheels[p_idx];
  295. _update_wheel_transform(wheel, s);
  296. Vector3 up = -wheel.m_raycastInfo.m_wheelDirectionWS;
  297. const Vector3 &right = wheel.m_raycastInfo.m_wheelAxleWS;
  298. Vector3 fwd = up.cross(right);
  299. fwd = fwd.normalized();
  300. Basis steeringMat(up, wheel.m_steering);
  301. Basis rotatingMat(right, wheel.m_rotation);
  302. Basis basis2(
  303. right[0], up[0], fwd[0],
  304. right[1], up[1], fwd[1],
  305. right[2], up[2], fwd[2]);
  306. wheel.m_worldTransform.set_basis(steeringMat * rotatingMat * basis2);
  307. //wheel.m_worldTransform.set_basis(basis2 * (steeringMat * rotatingMat));
  308. wheel.m_worldTransform.set_origin(
  309. wheel.m_raycastInfo.m_hardPointWS + wheel.m_raycastInfo.m_wheelDirectionWS * wheel.m_raycastInfo.m_suspensionLength);
  310. }
  311. real_t VehicleBody3D::_ray_cast(int p_idx, PhysicsDirectBodyState3D *s) {
  312. VehicleWheel3D &wheel = *wheels[p_idx];
  313. _update_wheel_transform(wheel, s);
  314. real_t depth = -1;
  315. real_t raylen = wheel.m_suspensionRestLength + wheel.m_wheelRadius;
  316. Vector3 rayvector = wheel.m_raycastInfo.m_wheelDirectionWS * (raylen);
  317. Vector3 source = wheel.m_raycastInfo.m_hardPointWS;
  318. wheel.m_raycastInfo.m_contactPointWS = source + rayvector;
  319. const Vector3 &target = wheel.m_raycastInfo.m_contactPointWS;
  320. source -= wheel.m_wheelRadius * wheel.m_raycastInfo.m_wheelDirectionWS;
  321. real_t param = real_t(0.);
  322. PhysicsDirectSpaceState3D::RayResult rr;
  323. PhysicsDirectSpaceState3D *ss = s->get_space_state();
  324. PhysicsDirectSpaceState3D::RayParameters ray_params;
  325. ray_params.from = source;
  326. ray_params.to = target;
  327. ray_params.exclude = exclude;
  328. ray_params.collision_mask = get_collision_mask();
  329. wheel.m_raycastInfo.m_groundObject = nullptr;
  330. bool col = ss->intersect_ray(ray_params, rr);
  331. if (col) {
  332. param = source.distance_to(rr.position) / source.distance_to(target);
  333. depth = raylen * param;
  334. wheel.m_raycastInfo.m_contactNormalWS = rr.normal;
  335. wheel.m_raycastInfo.m_isInContact = true;
  336. if (rr.collider) {
  337. wheel.m_raycastInfo.m_groundObject = Object::cast_to<PhysicsBody3D>(rr.collider);
  338. }
  339. real_t hitDistance = param * raylen;
  340. wheel.m_raycastInfo.m_suspensionLength = hitDistance - wheel.m_wheelRadius;
  341. //clamp on max suspension travel
  342. real_t minSuspensionLength = wheel.m_suspensionRestLength - wheel.m_maxSuspensionTravel;
  343. real_t maxSuspensionLength = wheel.m_suspensionRestLength + wheel.m_maxSuspensionTravel;
  344. if (wheel.m_raycastInfo.m_suspensionLength < minSuspensionLength) {
  345. wheel.m_raycastInfo.m_suspensionLength = minSuspensionLength;
  346. }
  347. if (wheel.m_raycastInfo.m_suspensionLength > maxSuspensionLength) {
  348. wheel.m_raycastInfo.m_suspensionLength = maxSuspensionLength;
  349. }
  350. wheel.m_raycastInfo.m_contactPointWS = rr.position;
  351. real_t denominator = wheel.m_raycastInfo.m_contactNormalWS.dot(wheel.m_raycastInfo.m_wheelDirectionWS);
  352. Vector3 chassis_velocity_at_contactPoint;
  353. //Vector3 relpos = wheel.m_raycastInfo.m_contactPointWS-getRigidBody()->getCenterOfMassPosition();
  354. //chassis_velocity_at_contactPoint = getRigidBody()->getVelocityInLocalPoint(relpos);
  355. chassis_velocity_at_contactPoint = s->get_linear_velocity() +
  356. (s->get_angular_velocity()).cross(wheel.m_raycastInfo.m_contactPointWS - s->get_transform().origin); // * mPos);
  357. real_t projVel = wheel.m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint);
  358. if (denominator >= real_t(-0.1)) {
  359. wheel.m_suspensionRelativeVelocity = real_t(0.0);
  360. wheel.m_clippedInvContactDotSuspension = real_t(1.0) / real_t(0.1);
  361. } else {
  362. real_t inv = real_t(-1.) / denominator;
  363. wheel.m_suspensionRelativeVelocity = projVel * inv;
  364. wheel.m_clippedInvContactDotSuspension = inv;
  365. }
  366. } else {
  367. wheel.m_raycastInfo.m_isInContact = false;
  368. //put wheel info as in rest position
  369. wheel.m_raycastInfo.m_suspensionLength = wheel.m_suspensionRestLength;
  370. wheel.m_suspensionRelativeVelocity = real_t(0.0);
  371. wheel.m_raycastInfo.m_contactNormalWS = -wheel.m_raycastInfo.m_wheelDirectionWS;
  372. wheel.m_clippedInvContactDotSuspension = real_t(1.0);
  373. }
  374. return depth;
  375. }
  376. void VehicleBody3D::_update_suspension(PhysicsDirectBodyState3D *s) {
  377. real_t chassisMass = get_mass();
  378. for (int w_it = 0; w_it < wheels.size(); w_it++) {
  379. VehicleWheel3D &wheel_info = *wheels[w_it];
  380. if (wheel_info.m_raycastInfo.m_isInContact) {
  381. real_t force;
  382. //Spring
  383. {
  384. real_t susp_length = wheel_info.m_suspensionRestLength;
  385. real_t current_length = wheel_info.m_raycastInfo.m_suspensionLength;
  386. real_t length_diff = (susp_length - current_length);
  387. force = wheel_info.m_suspensionStiffness * length_diff * wheel_info.m_clippedInvContactDotSuspension;
  388. }
  389. // Damper
  390. {
  391. real_t projected_rel_vel = wheel_info.m_suspensionRelativeVelocity;
  392. {
  393. real_t susp_damping;
  394. if (projected_rel_vel < real_t(0.0)) {
  395. susp_damping = wheel_info.m_wheelsDampingCompression;
  396. } else {
  397. susp_damping = wheel_info.m_wheelsDampingRelaxation;
  398. }
  399. force -= susp_damping * projected_rel_vel;
  400. }
  401. }
  402. // RESULT
  403. wheel_info.m_wheelsSuspensionForce = force * chassisMass;
  404. if (wheel_info.m_wheelsSuspensionForce < real_t(0.)) {
  405. wheel_info.m_wheelsSuspensionForce = real_t(0.);
  406. }
  407. } else {
  408. wheel_info.m_wheelsSuspensionForce = real_t(0.0);
  409. }
  410. }
  411. }
  412. //bilateral constraint between two dynamic objects
  413. void VehicleBody3D::_resolve_single_bilateral(PhysicsDirectBodyState3D *s, const Vector3 &pos1,
  414. PhysicsBody3D *body2, const Vector3 &pos2, const Vector3 &normal, real_t &impulse, const real_t p_rollInfluence) {
  415. real_t normalLenSqr = normal.length_squared();
  416. //ERR_FAIL_COND( normalLenSqr < real_t(1.1));
  417. if (normalLenSqr > real_t(1.1)) {
  418. impulse = real_t(0.);
  419. return;
  420. }
  421. Vector3 rel_pos1 = pos1 - s->get_transform().origin;
  422. Vector3 rel_pos2;
  423. if (body2) {
  424. rel_pos2 = pos2 - body2->get_global_transform().origin;
  425. }
  426. //this jacobian entry could be re-used for all iterations
  427. Vector3 vel1 = s->get_linear_velocity() + (s->get_angular_velocity()).cross(rel_pos1); // * mPos);
  428. Vector3 vel2;
  429. if (body2) {
  430. vel2 = body2->get_linear_velocity() + body2->get_angular_velocity().cross(rel_pos2);
  431. }
  432. Vector3 vel = vel1 - vel2;
  433. Basis b2trans;
  434. real_t b2invmass = 0;
  435. Vector3 b2lv;
  436. Vector3 b2av;
  437. Vector3 b2invinertia; //todo
  438. if (body2) {
  439. b2trans = body2->get_global_transform().basis.transposed();
  440. b2invmass = body2->get_inverse_mass();
  441. b2lv = body2->get_linear_velocity();
  442. b2av = body2->get_angular_velocity();
  443. }
  444. btVehicleJacobianEntry jac(s->get_transform().basis.transposed(),
  445. b2trans,
  446. rel_pos1,
  447. rel_pos2,
  448. normal,
  449. s->get_inverse_inertia_tensor().get_main_diagonal(),
  450. 1.0 / get_mass(),
  451. b2invinertia,
  452. b2invmass);
  453. // FIXME: rel_vel assignment here is overwritten by the following assignment.
  454. // What seems to be intended in the next assignment is: rel_vel = normal.dot(rel_vel);
  455. // Investigate why.
  456. real_t rel_vel = jac.getRelativeVelocity(
  457. s->get_linear_velocity(),
  458. s->get_transform().basis.transposed().xform(s->get_angular_velocity()),
  459. b2lv,
  460. b2trans.xform(b2av));
  461. rel_vel = normal.dot(vel);
  462. // !BAS! We had this set to 0.4, in bullet its 0.2
  463. real_t contactDamping = real_t(0.2);
  464. if (p_rollInfluence > 0.0) {
  465. // !BAS! But seeing we apply this frame by frame, makes more sense to me to make this time based
  466. // keeping in mind our anti roll factor if it is set
  467. contactDamping = MIN(contactDamping, s->get_step() / p_rollInfluence);
  468. }
  469. #define ONLY_USE_LINEAR_MASS
  470. #ifdef ONLY_USE_LINEAR_MASS
  471. real_t massTerm = real_t(1.) / ((1.0 / get_mass()) + b2invmass);
  472. impulse = -contactDamping * rel_vel * massTerm;
  473. #else
  474. real_t velocityImpulse = -contactDamping * rel_vel * jacDiagABInv;
  475. impulse = velocityImpulse;
  476. #endif
  477. }
  478. VehicleBody3D::btVehicleWheelContactPoint::btVehicleWheelContactPoint(PhysicsDirectBodyState3D *s, PhysicsBody3D *body1, const Vector3 &frictionPosWorld, const Vector3 &frictionDirectionWorld, real_t maxImpulse) :
  479. m_s(s),
  480. m_body1(body1),
  481. m_frictionPositionWorld(frictionPosWorld),
  482. m_frictionDirectionWorld(frictionDirectionWorld),
  483. m_maxImpulse(maxImpulse) {
  484. real_t denom0 = 0;
  485. real_t denom1 = 0;
  486. {
  487. Vector3 r0 = frictionPosWorld - s->get_transform().origin;
  488. Vector3 c0 = (r0).cross(frictionDirectionWorld);
  489. Vector3 vec = s->get_inverse_inertia_tensor().xform_inv(c0).cross(r0);
  490. denom0 = s->get_inverse_mass() + frictionDirectionWorld.dot(vec);
  491. }
  492. /* TODO: Why is this code unused?
  493. if (body1) {
  494. Vector3 r0 = frictionPosWorld - body1->get_global_transform().origin;
  495. Vector3 c0 = (r0).cross(frictionDirectionWorld);
  496. Vector3 vec = s->get_inverse_inertia_tensor().xform_inv(c0).cross(r0);
  497. //denom1= body1->get_inverse_mass() + frictionDirectionWorld.dot(vec);
  498. }
  499. */
  500. real_t relaxation = 1.f;
  501. m_jacDiagABInv = relaxation / (denom0 + denom1);
  502. }
  503. real_t VehicleBody3D::_calc_rolling_friction(btVehicleWheelContactPoint &contactPoint) {
  504. real_t j1 = 0.f;
  505. const Vector3 &contactPosWorld = contactPoint.m_frictionPositionWorld;
  506. Vector3 rel_pos1 = contactPosWorld - contactPoint.m_s->get_transform().origin;
  507. Vector3 rel_pos2;
  508. if (contactPoint.m_body1) {
  509. rel_pos2 = contactPosWorld - contactPoint.m_body1->get_global_transform().origin;
  510. }
  511. real_t maxImpulse = contactPoint.m_maxImpulse;
  512. Vector3 vel1 = contactPoint.m_s->get_linear_velocity() + (contactPoint.m_s->get_angular_velocity()).cross(rel_pos1); // * mPos);
  513. Vector3 vel2;
  514. if (contactPoint.m_body1) {
  515. vel2 = contactPoint.m_body1->get_linear_velocity() + contactPoint.m_body1->get_angular_velocity().cross(rel_pos2);
  516. }
  517. Vector3 vel = vel1 - vel2;
  518. real_t vrel = contactPoint.m_frictionDirectionWorld.dot(vel);
  519. // calculate j that moves us to zero relative velocity
  520. j1 = -vrel * contactPoint.m_jacDiagABInv;
  521. return CLAMP(j1, -maxImpulse, maxImpulse);
  522. }
  523. static const real_t sideFrictionStiffness2 = real_t(1.0);
  524. void VehicleBody3D::_update_friction(PhysicsDirectBodyState3D *s) {
  525. //calculate the impulse, so that the wheels don't move sidewards
  526. int numWheel = wheels.size();
  527. if (!numWheel) {
  528. return;
  529. }
  530. m_forwardWS.resize(numWheel);
  531. m_axle.resize(numWheel);
  532. m_forwardImpulse.resize(numWheel);
  533. m_sideImpulse.resize(numWheel);
  534. //collapse all those loops into one!
  535. for (int i = 0; i < wheels.size(); i++) {
  536. m_sideImpulse.write[i] = real_t(0.);
  537. m_forwardImpulse.write[i] = real_t(0.);
  538. }
  539. {
  540. for (int i = 0; i < wheels.size(); i++) {
  541. VehicleWheel3D &wheelInfo = *wheels[i];
  542. if (wheelInfo.m_raycastInfo.m_isInContact) {
  543. //const btTransform& wheelTrans = getWheelTransformWS( i );
  544. Basis wheelBasis0 = wheelInfo.m_worldTransform.basis; //get_global_transform().basis;
  545. m_axle.write[i] = wheelBasis0.get_column(Vector3::AXIS_X);
  546. //m_axle[i] = wheelInfo.m_raycastInfo.m_wheelAxleWS;
  547. const Vector3 &surfNormalWS = wheelInfo.m_raycastInfo.m_contactNormalWS;
  548. real_t proj = m_axle[i].dot(surfNormalWS);
  549. m_axle.write[i] -= surfNormalWS * proj;
  550. m_axle.write[i] = m_axle[i].normalized();
  551. m_forwardWS.write[i] = surfNormalWS.cross(m_axle[i]);
  552. m_forwardWS.write[i].normalize();
  553. _resolve_single_bilateral(s, wheelInfo.m_raycastInfo.m_contactPointWS,
  554. wheelInfo.m_raycastInfo.m_groundObject, wheelInfo.m_raycastInfo.m_contactPointWS,
  555. m_axle[i], m_sideImpulse.write[i], wheelInfo.m_rollInfluence);
  556. m_sideImpulse.write[i] *= sideFrictionStiffness2;
  557. }
  558. }
  559. }
  560. real_t sideFactor = real_t(1.);
  561. real_t fwdFactor = 0.5;
  562. bool sliding = false;
  563. {
  564. for (int wheel = 0; wheel < wheels.size(); wheel++) {
  565. VehicleWheel3D &wheelInfo = *wheels[wheel];
  566. //class btRigidBody* groundObject = (class btRigidBody*) wheelInfo.m_raycastInfo.m_groundObject;
  567. real_t rollingFriction = 0.f;
  568. if (wheelInfo.m_raycastInfo.m_isInContact) {
  569. if (wheelInfo.m_engineForce != 0.f) {
  570. rollingFriction = -wheelInfo.m_engineForce * s->get_step();
  571. } else {
  572. real_t defaultRollingFrictionImpulse = 0.f;
  573. real_t maxImpulse = wheelInfo.m_brake ? wheelInfo.m_brake : defaultRollingFrictionImpulse;
  574. btVehicleWheelContactPoint contactPt(s, wheelInfo.m_raycastInfo.m_groundObject, wheelInfo.m_raycastInfo.m_contactPointWS, m_forwardWS[wheel], maxImpulse);
  575. rollingFriction = _calc_rolling_friction(contactPt);
  576. }
  577. }
  578. //switch between active rolling (throttle), braking and non-active rolling friction (no throttle/break)
  579. m_forwardImpulse.write[wheel] = real_t(0.);
  580. wheelInfo.m_skidInfo = real_t(1.);
  581. if (wheelInfo.m_raycastInfo.m_isInContact) {
  582. wheelInfo.m_skidInfo = real_t(1.);
  583. real_t maximp = wheelInfo.m_wheelsSuspensionForce * s->get_step() * wheelInfo.m_frictionSlip;
  584. real_t maximpSide = maximp;
  585. real_t maximpSquared = maximp * maximpSide;
  586. m_forwardImpulse.write[wheel] = rollingFriction; //wheelInfo.m_engineForce* timeStep;
  587. real_t x = (m_forwardImpulse[wheel]) * fwdFactor;
  588. real_t y = (m_sideImpulse[wheel]) * sideFactor;
  589. real_t impulseSquared = (x * x + y * y);
  590. if (impulseSquared > maximpSquared) {
  591. sliding = true;
  592. real_t factor = maximp / Math::sqrt(impulseSquared);
  593. wheelInfo.m_skidInfo *= factor;
  594. }
  595. }
  596. }
  597. }
  598. if (sliding) {
  599. for (int wheel = 0; wheel < wheels.size(); wheel++) {
  600. if (m_sideImpulse[wheel] != real_t(0.)) {
  601. if (wheels[wheel]->m_skidInfo < real_t(1.)) {
  602. m_forwardImpulse.write[wheel] *= wheels[wheel]->m_skidInfo;
  603. m_sideImpulse.write[wheel] *= wheels[wheel]->m_skidInfo;
  604. }
  605. }
  606. }
  607. }
  608. // apply the impulses
  609. {
  610. for (int wheel = 0; wheel < wheels.size(); wheel++) {
  611. VehicleWheel3D &wheelInfo = *wheels[wheel];
  612. Vector3 rel_pos = wheelInfo.m_raycastInfo.m_contactPointWS -
  613. s->get_transform().origin;
  614. if (m_forwardImpulse[wheel] != real_t(0.)) {
  615. s->apply_impulse(m_forwardWS[wheel] * (m_forwardImpulse[wheel]), rel_pos);
  616. }
  617. if (m_sideImpulse[wheel] != real_t(0.)) {
  618. PhysicsBody3D *groundObject = wheelInfo.m_raycastInfo.m_groundObject;
  619. Vector3 rel_pos2;
  620. if (groundObject) {
  621. rel_pos2 = wheelInfo.m_raycastInfo.m_contactPointWS - groundObject->get_global_transform().origin;
  622. }
  623. Vector3 sideImp = m_axle[wheel] * m_sideImpulse[wheel];
  624. #if defined ROLLING_INFLUENCE_FIX // fix. It only worked if car's up was along Y - VT.
  625. Vector3 vChassisWorldUp = s->get_transform().basis.transposed()[1]; //getRigidBody()->getCenterOfMassTransform3D().getBasis().getColumn(m_indexUpAxis);
  626. rel_pos -= vChassisWorldUp * (vChassisWorldUp.dot(rel_pos) * (1.f - wheelInfo.m_rollInfluence));
  627. #else
  628. rel_pos[1] *= wheelInfo.m_rollInfluence; //?
  629. #endif
  630. s->apply_impulse(sideImp, rel_pos);
  631. //apply friction impulse on the ground
  632. //todo
  633. //groundObject->applyImpulse(-sideImp,rel_pos2);
  634. }
  635. }
  636. }
  637. }
  638. void VehicleBody3D::_body_state_changed(PhysicsDirectBodyState3D *p_state) {
  639. RigidBody3D::_body_state_changed(p_state);
  640. real_t step = p_state->get_step();
  641. for (int i = 0; i < wheels.size(); i++) {
  642. _update_wheel(i, p_state);
  643. }
  644. for (int i = 0; i < wheels.size(); i++) {
  645. _ray_cast(i, p_state);
  646. wheels[i]->set_transform(p_state->get_transform().inverse() * wheels[i]->m_worldTransform);
  647. }
  648. _update_suspension(p_state);
  649. for (int i = 0; i < wheels.size(); i++) {
  650. //apply suspension force
  651. VehicleWheel3D &wheel = *wheels[i];
  652. real_t suspensionForce = wheel.m_wheelsSuspensionForce;
  653. if (suspensionForce > wheel.m_maxSuspensionForce) {
  654. suspensionForce = wheel.m_maxSuspensionForce;
  655. }
  656. Vector3 impulse = wheel.m_raycastInfo.m_contactNormalWS * suspensionForce * step;
  657. Vector3 relative_position = wheel.m_raycastInfo.m_contactPointWS - p_state->get_transform().origin;
  658. p_state->apply_impulse(impulse, relative_position);
  659. }
  660. _update_friction(p_state);
  661. for (int i = 0; i < wheels.size(); i++) {
  662. VehicleWheel3D &wheel = *wheels[i];
  663. Vector3 relpos = wheel.m_raycastInfo.m_hardPointWS - p_state->get_transform().origin;
  664. Vector3 vel = p_state->get_linear_velocity() + (p_state->get_angular_velocity()).cross(relpos); // * mPos);
  665. if (wheel.m_raycastInfo.m_isInContact) {
  666. const Transform3D &chassisWorldTransform = p_state->get_transform();
  667. Vector3 fwd(
  668. chassisWorldTransform.basis[0][Vector3::AXIS_Z],
  669. chassisWorldTransform.basis[1][Vector3::AXIS_Z],
  670. chassisWorldTransform.basis[2][Vector3::AXIS_Z]);
  671. real_t proj = fwd.dot(wheel.m_raycastInfo.m_contactNormalWS);
  672. fwd -= wheel.m_raycastInfo.m_contactNormalWS * proj;
  673. real_t proj2 = fwd.dot(vel);
  674. wheel.m_deltaRotation = (proj2 * step) / (wheel.m_wheelRadius);
  675. }
  676. wheel.m_rotation += wheel.m_deltaRotation;
  677. wheel.m_rpm = ((wheel.m_deltaRotation / step) * 60) / Math_TAU;
  678. wheel.m_deltaRotation *= real_t(0.99); //damping of rotation when not in contact
  679. }
  680. }
  681. void VehicleBody3D::set_engine_force(real_t p_engine_force) {
  682. engine_force = p_engine_force;
  683. for (int i = 0; i < wheels.size(); i++) {
  684. VehicleWheel3D &wheelInfo = *wheels[i];
  685. if (wheelInfo.engine_traction) {
  686. wheelInfo.m_engineForce = p_engine_force;
  687. }
  688. }
  689. }
  690. real_t VehicleBody3D::get_engine_force() const {
  691. return engine_force;
  692. }
  693. void VehicleBody3D::set_brake(real_t p_brake) {
  694. brake = p_brake;
  695. for (int i = 0; i < wheels.size(); i++) {
  696. VehicleWheel3D &wheelInfo = *wheels[i];
  697. wheelInfo.m_brake = p_brake;
  698. }
  699. }
  700. real_t VehicleBody3D::get_brake() const {
  701. return brake;
  702. }
  703. void VehicleBody3D::set_steering(real_t p_steering) {
  704. m_steeringValue = p_steering;
  705. for (int i = 0; i < wheels.size(); i++) {
  706. VehicleWheel3D &wheelInfo = *wheels[i];
  707. if (wheelInfo.steers) {
  708. wheelInfo.m_steering = p_steering;
  709. }
  710. }
  711. }
  712. real_t VehicleBody3D::get_steering() const {
  713. return m_steeringValue;
  714. }
  715. void VehicleBody3D::_bind_methods() {
  716. ClassDB::bind_method(D_METHOD("set_engine_force", "engine_force"), &VehicleBody3D::set_engine_force);
  717. ClassDB::bind_method(D_METHOD("get_engine_force"), &VehicleBody3D::get_engine_force);
  718. ClassDB::bind_method(D_METHOD("set_brake", "brake"), &VehicleBody3D::set_brake);
  719. ClassDB::bind_method(D_METHOD("get_brake"), &VehicleBody3D::get_brake);
  720. ClassDB::bind_method(D_METHOD("set_steering", "steering"), &VehicleBody3D::set_steering);
  721. ClassDB::bind_method(D_METHOD("get_steering"), &VehicleBody3D::get_steering);
  722. ADD_GROUP("Motion", "");
  723. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "engine_force", PROPERTY_HINT_RANGE, U"-1024,1024,0.01,or_less,or_greater,suffix:kg\u22C5m/s\u00B2 (N)"), "set_engine_force", "get_engine_force");
  724. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "brake", PROPERTY_HINT_RANGE, U"-128,128,0.01,or_less,or_greater,suffix:kg\u22C5m/s\u00B2 (N)"), "set_brake", "get_brake");
  725. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "steering", PROPERTY_HINT_RANGE, "-180,180,0.01,radians_as_degrees"), "set_steering", "get_steering");
  726. }
  727. VehicleBody3D::VehicleBody3D() {
  728. exclude.insert(get_rid());
  729. set_mass(40);
  730. }