vehicle_body.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  1. /*************************************************************************/
  2. /* vehicle_body.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "vehicle_body.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;
  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 VehicleWheel::_notification(int p_what) {
  74. if (p_what == NOTIFICATION_ENTER_TREE) {
  75. VehicleBody *cb = Object::cast_to<VehicleBody>(get_parent());
  76. if (!cb)
  77. return;
  78. body = cb;
  79. local_xform = get_transform();
  80. cb->wheels.push_back(this);
  81. m_chassisConnectionPointCS = get_transform().origin;
  82. m_wheelDirectionCS = -get_transform().basis.get_axis(Vector3::AXIS_Y).normalized();
  83. m_wheelAxleCS = get_transform().basis.get_axis(Vector3::AXIS_X).normalized();
  84. }
  85. if (p_what == NOTIFICATION_EXIT_TREE) {
  86. VehicleBody *cb = Object::cast_to<VehicleBody>(get_parent());
  87. if (!cb)
  88. return;
  89. cb->wheels.erase(this);
  90. body = NULL;
  91. }
  92. }
  93. String VehicleWheel::get_configuration_warning() const {
  94. if (!Object::cast_to<VehicleBody>(get_parent())) {
  95. return TTR("VehicleWheel serves to provide a wheel system to a VehicleBody. Please use it as a child of a VehicleBody.");
  96. }
  97. return String();
  98. }
  99. void VehicleWheel::_update(PhysicsDirectBodyState *s) {
  100. if (m_raycastInfo.m_isInContact)
  101. {
  102. real_t project = m_raycastInfo.m_contactNormalWS.dot(m_raycastInfo.m_wheelDirectionWS);
  103. Vector3 chassis_velocity_at_contactPoint;
  104. Vector3 relpos = m_raycastInfo.m_contactPointWS - s->get_transform().origin;
  105. chassis_velocity_at_contactPoint = s->get_linear_velocity() +
  106. (s->get_angular_velocity()).cross(relpos); // * mPos);
  107. real_t projVel = m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint);
  108. if (project >= real_t(-0.1)) {
  109. m_suspensionRelativeVelocity = real_t(0.0);
  110. m_clippedInvContactDotSuspension = real_t(1.0) / real_t(0.1);
  111. } else {
  112. real_t inv = real_t(-1.) / project;
  113. m_suspensionRelativeVelocity = projVel * inv;
  114. m_clippedInvContactDotSuspension = inv;
  115. }
  116. }
  117. else // Not in contact : position wheel in a nice (rest length) position
  118. {
  119. m_raycastInfo.m_suspensionLength = m_suspensionRestLength;
  120. m_suspensionRelativeVelocity = real_t(0.0);
  121. m_raycastInfo.m_contactNormalWS = -m_raycastInfo.m_wheelDirectionWS;
  122. m_clippedInvContactDotSuspension = real_t(1.0);
  123. }
  124. }
  125. void VehicleWheel::set_radius(float p_radius) {
  126. m_wheelRadius = p_radius;
  127. update_gizmo();
  128. }
  129. float VehicleWheel::get_radius() const {
  130. return m_wheelRadius;
  131. }
  132. void VehicleWheel::set_suspension_rest_length(float p_length) {
  133. m_suspensionRestLength = p_length;
  134. update_gizmo();
  135. }
  136. float VehicleWheel::get_suspension_rest_length() const {
  137. return m_suspensionRestLength;
  138. }
  139. void VehicleWheel::set_suspension_travel(float p_length) {
  140. m_maxSuspensionTravelCm = p_length / 0.01;
  141. }
  142. float VehicleWheel::get_suspension_travel() const {
  143. return m_maxSuspensionTravelCm * 0.01;
  144. }
  145. void VehicleWheel::set_suspension_stiffness(float p_value) {
  146. m_suspensionStiffness = p_value;
  147. }
  148. float VehicleWheel::get_suspension_stiffness() const {
  149. return m_suspensionStiffness;
  150. }
  151. void VehicleWheel::set_suspension_max_force(float p_value) {
  152. m_maxSuspensionForce = p_value;
  153. }
  154. float VehicleWheel::get_suspension_max_force() const {
  155. return m_maxSuspensionForce;
  156. }
  157. void VehicleWheel::set_damping_compression(float p_value) {
  158. m_wheelsDampingCompression = p_value;
  159. }
  160. float VehicleWheel::get_damping_compression() const {
  161. return m_wheelsDampingCompression;
  162. }
  163. void VehicleWheel::set_damping_relaxation(float p_value) {
  164. m_wheelsDampingRelaxation = p_value;
  165. }
  166. float VehicleWheel::get_damping_relaxation() const {
  167. return m_wheelsDampingRelaxation;
  168. }
  169. void VehicleWheel::set_friction_slip(float p_value) {
  170. m_frictionSlip = p_value;
  171. }
  172. float VehicleWheel::get_friction_slip() const {
  173. return m_frictionSlip;
  174. }
  175. void VehicleWheel::set_roll_influence(float p_value) {
  176. m_rollInfluence = p_value;
  177. }
  178. float VehicleWheel::get_roll_influence() const {
  179. return m_rollInfluence;
  180. }
  181. bool VehicleWheel::is_in_contact() const {
  182. return m_raycastInfo.m_isInContact;
  183. }
  184. void VehicleWheel::_bind_methods() {
  185. ClassDB::bind_method(D_METHOD("set_radius", "length"), &VehicleWheel::set_radius);
  186. ClassDB::bind_method(D_METHOD("get_radius"), &VehicleWheel::get_radius);
  187. ClassDB::bind_method(D_METHOD("set_suspension_rest_length", "length"), &VehicleWheel::set_suspension_rest_length);
  188. ClassDB::bind_method(D_METHOD("get_suspension_rest_length"), &VehicleWheel::get_suspension_rest_length);
  189. ClassDB::bind_method(D_METHOD("set_suspension_travel", "length"), &VehicleWheel::set_suspension_travel);
  190. ClassDB::bind_method(D_METHOD("get_suspension_travel"), &VehicleWheel::get_suspension_travel);
  191. ClassDB::bind_method(D_METHOD("set_suspension_stiffness", "length"), &VehicleWheel::set_suspension_stiffness);
  192. ClassDB::bind_method(D_METHOD("get_suspension_stiffness"), &VehicleWheel::get_suspension_stiffness);
  193. ClassDB::bind_method(D_METHOD("set_suspension_max_force", "length"), &VehicleWheel::set_suspension_max_force);
  194. ClassDB::bind_method(D_METHOD("get_suspension_max_force"), &VehicleWheel::get_suspension_max_force);
  195. ClassDB::bind_method(D_METHOD("set_damping_compression", "length"), &VehicleWheel::set_damping_compression);
  196. ClassDB::bind_method(D_METHOD("get_damping_compression"), &VehicleWheel::get_damping_compression);
  197. ClassDB::bind_method(D_METHOD("set_damping_relaxation", "length"), &VehicleWheel::set_damping_relaxation);
  198. ClassDB::bind_method(D_METHOD("get_damping_relaxation"), &VehicleWheel::get_damping_relaxation);
  199. ClassDB::bind_method(D_METHOD("set_use_as_traction", "enable"), &VehicleWheel::set_use_as_traction);
  200. ClassDB::bind_method(D_METHOD("is_used_as_traction"), &VehicleWheel::is_used_as_traction);
  201. ClassDB::bind_method(D_METHOD("set_use_as_steering", "enable"), &VehicleWheel::set_use_as_steering);
  202. ClassDB::bind_method(D_METHOD("is_used_as_steering"), &VehicleWheel::is_used_as_steering);
  203. ClassDB::bind_method(D_METHOD("set_friction_slip", "length"), &VehicleWheel::set_friction_slip);
  204. ClassDB::bind_method(D_METHOD("get_friction_slip"), &VehicleWheel::get_friction_slip);
  205. ClassDB::bind_method(D_METHOD("is_in_contact"), &VehicleWheel::is_in_contact);
  206. ClassDB::bind_method(D_METHOD("set_roll_influence", "roll_influence"), &VehicleWheel::set_roll_influence);
  207. ClassDB::bind_method(D_METHOD("get_roll_influence"), &VehicleWheel::get_roll_influence);
  208. ClassDB::bind_method(D_METHOD("get_skidinfo"), &VehicleWheel::get_skidinfo);
  209. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_as_traction"), "set_use_as_traction", "is_used_as_traction");
  210. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_as_steering"), "set_use_as_steering", "is_used_as_steering");
  211. ADD_GROUP("Wheel", "wheel_");
  212. ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_roll_influence"), "set_roll_influence", "get_roll_influence");
  213. ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_radius"), "set_radius", "get_radius");
  214. ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_rest_length"), "set_suspension_rest_length", "get_suspension_rest_length");
  215. ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_friction_slip"), "set_friction_slip", "get_friction_slip");
  216. ADD_GROUP("Suspension", "suspension_");
  217. ADD_PROPERTY(PropertyInfo(Variant::REAL, "suspension_travel"), "set_suspension_travel", "get_suspension_travel");
  218. ADD_PROPERTY(PropertyInfo(Variant::REAL, "suspension_stiffness"), "set_suspension_stiffness", "get_suspension_stiffness");
  219. ADD_PROPERTY(PropertyInfo(Variant::REAL, "suspension_max_force"), "set_suspension_max_force", "get_suspension_max_force");
  220. ADD_GROUP("Damping", "damping_");
  221. ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping_compression"), "set_damping_compression", "get_damping_compression");
  222. ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping_relaxation"), "set_damping_relaxation", "get_damping_relaxation");
  223. }
  224. void VehicleWheel::set_use_as_traction(bool p_enable) {
  225. engine_traction = p_enable;
  226. }
  227. bool VehicleWheel::is_used_as_traction() const {
  228. return engine_traction;
  229. }
  230. void VehicleWheel::set_use_as_steering(bool p_enabled) {
  231. steers = p_enabled;
  232. }
  233. bool VehicleWheel::is_used_as_steering() const {
  234. return steers;
  235. }
  236. float VehicleWheel::get_skidinfo() const {
  237. return m_skidInfo;
  238. }
  239. VehicleWheel::VehicleWheel() {
  240. steers = false;
  241. engine_traction = false;
  242. m_steering = real_t(0.);
  243. //m_engineForce = real_t(0.);
  244. m_rotation = real_t(0.);
  245. m_deltaRotation = real_t(0.);
  246. m_brake = real_t(0.);
  247. m_rollInfluence = real_t(0.1);
  248. m_suspensionRestLength = 0.15;
  249. m_wheelRadius = 0.5; //0.28;
  250. m_suspensionStiffness = 5.88;
  251. m_wheelsDampingCompression = 0.83;
  252. m_wheelsDampingRelaxation = 0.88;
  253. m_frictionSlip = 10.5;
  254. m_bIsFrontWheel = false;
  255. m_maxSuspensionTravelCm = 500;
  256. m_maxSuspensionForce = 6000;
  257. m_suspensionRelativeVelocity = 0;
  258. m_clippedInvContactDotSuspension = 1.0;
  259. m_raycastInfo.m_isInContact = false;
  260. body = NULL;
  261. }
  262. void VehicleBody::_update_wheel_transform(VehicleWheel &wheel, PhysicsDirectBodyState *s) {
  263. wheel.m_raycastInfo.m_isInContact = false;
  264. Transform chassisTrans = s->get_transform();
  265. /*
  266. if (interpolatedTransform && (getRigidBody()->getMotionState())) {
  267. getRigidBody()->getMotionState()->getWorldTransform(chassisTrans);
  268. }
  269. */
  270. wheel.m_raycastInfo.m_hardPointWS = chassisTrans.xform(wheel.m_chassisConnectionPointCS);
  271. //wheel.m_raycastInfo.m_hardPointWS+=s->get_linear_velocity()*s->get_step();
  272. wheel.m_raycastInfo.m_wheelDirectionWS = chassisTrans.get_basis().xform(wheel.m_wheelDirectionCS).normalized();
  273. wheel.m_raycastInfo.m_wheelAxleWS = chassisTrans.get_basis().xform(wheel.m_wheelAxleCS).normalized();
  274. }
  275. void VehicleBody::_update_wheel(int p_idx, PhysicsDirectBodyState *s) {
  276. VehicleWheel &wheel = *wheels[p_idx];
  277. _update_wheel_transform(wheel, s);
  278. Vector3 up = -wheel.m_raycastInfo.m_wheelDirectionWS;
  279. const Vector3 &right = wheel.m_raycastInfo.m_wheelAxleWS;
  280. Vector3 fwd = up.cross(right);
  281. fwd = fwd.normalized();
  282. //rotate around steering over de wheelAxleWS
  283. real_t steering = wheel.steers ? m_steeringValue : 0.0;
  284. Basis steeringMat(up, steering);
  285. Basis rotatingMat(right, wheel.m_rotation);
  286. Basis basis2(
  287. right[0], up[0], fwd[0],
  288. right[1], up[1], fwd[1],
  289. right[2], up[2], fwd[2]);
  290. wheel.m_worldTransform.set_basis(steeringMat * rotatingMat * basis2);
  291. //wheel.m_worldTransform.set_basis(basis2 * (steeringMat * rotatingMat));
  292. wheel.m_worldTransform.set_origin(
  293. wheel.m_raycastInfo.m_hardPointWS + wheel.m_raycastInfo.m_wheelDirectionWS * wheel.m_raycastInfo.m_suspensionLength);
  294. }
  295. real_t VehicleBody::_ray_cast(int p_idx, PhysicsDirectBodyState *s) {
  296. VehicleWheel &wheel = *wheels[p_idx];
  297. _update_wheel_transform(wheel, s);
  298. real_t depth = -1;
  299. real_t raylen = wheel.m_suspensionRestLength + wheel.m_wheelRadius;
  300. Vector3 rayvector = wheel.m_raycastInfo.m_wheelDirectionWS * (raylen);
  301. Vector3 source = wheel.m_raycastInfo.m_hardPointWS;
  302. wheel.m_raycastInfo.m_contactPointWS = source + rayvector;
  303. const Vector3 &target = wheel.m_raycastInfo.m_contactPointWS;
  304. source -= wheel.m_wheelRadius * wheel.m_raycastInfo.m_wheelDirectionWS;
  305. real_t param = real_t(0.);
  306. PhysicsDirectSpaceState::RayResult rr;
  307. PhysicsDirectSpaceState *ss = s->get_space_state();
  308. bool col = ss->intersect_ray(source, target, rr, exclude);
  309. wheel.m_raycastInfo.m_groundObject = 0;
  310. if (col) {
  311. param = source.distance_to(rr.position) / source.distance_to(target);
  312. depth = raylen * param;
  313. wheel.m_raycastInfo.m_contactNormalWS = rr.normal;
  314. wheel.m_raycastInfo.m_isInContact = true;
  315. if (rr.collider)
  316. wheel.m_raycastInfo.m_groundObject = Object::cast_to<PhysicsBody>(rr.collider);
  317. real_t hitDistance = param * raylen;
  318. wheel.m_raycastInfo.m_suspensionLength = hitDistance - wheel.m_wheelRadius;
  319. //clamp on max suspension travel
  320. real_t minSuspensionLength = wheel.m_suspensionRestLength - wheel.m_maxSuspensionTravelCm * real_t(0.01);
  321. real_t maxSuspensionLength = wheel.m_suspensionRestLength + wheel.m_maxSuspensionTravelCm * real_t(0.01);
  322. if (wheel.m_raycastInfo.m_suspensionLength < minSuspensionLength) {
  323. wheel.m_raycastInfo.m_suspensionLength = minSuspensionLength;
  324. }
  325. if (wheel.m_raycastInfo.m_suspensionLength > maxSuspensionLength) {
  326. wheel.m_raycastInfo.m_suspensionLength = maxSuspensionLength;
  327. }
  328. wheel.m_raycastInfo.m_contactPointWS = rr.position;
  329. real_t denominator = wheel.m_raycastInfo.m_contactNormalWS.dot(wheel.m_raycastInfo.m_wheelDirectionWS);
  330. Vector3 chassis_velocity_at_contactPoint;
  331. //Vector3 relpos = wheel.m_raycastInfo.m_contactPointWS-getRigidBody()->getCenterOfMassPosition();
  332. //chassis_velocity_at_contactPoint = getRigidBody()->getVelocityInLocalPoint(relpos);
  333. chassis_velocity_at_contactPoint = s->get_linear_velocity() +
  334. (s->get_angular_velocity()).cross(wheel.m_raycastInfo.m_contactPointWS - s->get_transform().origin); // * mPos);
  335. real_t projVel = wheel.m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint);
  336. if (denominator >= real_t(-0.1)) {
  337. wheel.m_suspensionRelativeVelocity = real_t(0.0);
  338. wheel.m_clippedInvContactDotSuspension = real_t(1.0) / real_t(0.1);
  339. } else {
  340. real_t inv = real_t(-1.) / denominator;
  341. wheel.m_suspensionRelativeVelocity = projVel * inv;
  342. wheel.m_clippedInvContactDotSuspension = inv;
  343. }
  344. } else {
  345. wheel.m_raycastInfo.m_isInContact = false;
  346. //put wheel info as in rest position
  347. wheel.m_raycastInfo.m_suspensionLength = wheel.m_suspensionRestLength;
  348. wheel.m_suspensionRelativeVelocity = real_t(0.0);
  349. wheel.m_raycastInfo.m_contactNormalWS = -wheel.m_raycastInfo.m_wheelDirectionWS;
  350. wheel.m_clippedInvContactDotSuspension = real_t(1.0);
  351. }
  352. return depth;
  353. }
  354. void VehicleBody::_update_suspension(PhysicsDirectBodyState *s) {
  355. real_t chassisMass = mass;
  356. for (int w_it = 0; w_it < wheels.size(); w_it++) {
  357. VehicleWheel &wheel_info = *wheels[w_it];
  358. if (wheel_info.m_raycastInfo.m_isInContact) {
  359. real_t force;
  360. //Spring
  361. {
  362. real_t susp_length = wheel_info.m_suspensionRestLength;
  363. real_t current_length = wheel_info.m_raycastInfo.m_suspensionLength;
  364. real_t length_diff = (susp_length - current_length);
  365. force = wheel_info.m_suspensionStiffness * length_diff * wheel_info.m_clippedInvContactDotSuspension;
  366. }
  367. // Damper
  368. {
  369. real_t projected_rel_vel = wheel_info.m_suspensionRelativeVelocity;
  370. {
  371. real_t susp_damping;
  372. if (projected_rel_vel < real_t(0.0)) {
  373. susp_damping = wheel_info.m_wheelsDampingCompression;
  374. } else {
  375. susp_damping = wheel_info.m_wheelsDampingRelaxation;
  376. }
  377. force -= susp_damping * projected_rel_vel;
  378. }
  379. }
  380. // RESULT
  381. wheel_info.m_wheelsSuspensionForce = force * chassisMass;
  382. if (wheel_info.m_wheelsSuspensionForce < real_t(0.)) {
  383. wheel_info.m_wheelsSuspensionForce = real_t(0.);
  384. }
  385. } else {
  386. wheel_info.m_wheelsSuspensionForce = real_t(0.0);
  387. }
  388. }
  389. }
  390. //bilateral constraint between two dynamic objects
  391. void VehicleBody::_resolve_single_bilateral(PhysicsDirectBodyState *s, const Vector3 &pos1,
  392. PhysicsBody *body2, const Vector3 &pos2, const Vector3 &normal, real_t &impulse, const real_t p_rollInfluence) {
  393. real_t normalLenSqr = normal.length_squared();
  394. //ERR_FAIL_COND( normalLenSqr < real_t(1.1));
  395. if (normalLenSqr > real_t(1.1)) {
  396. impulse = real_t(0.);
  397. return;
  398. }
  399. Vector3 rel_pos1 = pos1 - s->get_transform().origin;
  400. Vector3 rel_pos2;
  401. if (body2)
  402. rel_pos2 = pos2 - body2->get_global_transform().origin;
  403. //this jacobian entry could be re-used for all iterations
  404. Vector3 vel1 = s->get_linear_velocity() + (s->get_angular_velocity()).cross(rel_pos1); // * mPos);
  405. Vector3 vel2;
  406. if (body2)
  407. vel2 = body2->get_linear_velocity() + body2->get_angular_velocity().cross(rel_pos2);
  408. Vector3 vel = vel1 - vel2;
  409. Basis b2trans;
  410. float b2invmass = 0;
  411. Vector3 b2lv;
  412. Vector3 b2av;
  413. Vector3 b2invinertia; //todo
  414. if (body2) {
  415. b2trans = body2->get_global_transform().basis.transposed();
  416. b2invmass = body2->get_inverse_mass();
  417. b2lv = body2->get_linear_velocity();
  418. b2av = body2->get_angular_velocity();
  419. }
  420. btVehicleJacobianEntry jac(s->get_transform().basis.transposed(),
  421. b2trans,
  422. rel_pos1,
  423. rel_pos2,
  424. normal,
  425. s->get_inverse_inertia_tensor().get_main_diagonal(),
  426. 1.0 / mass,
  427. b2invinertia,
  428. b2invmass);
  429. // FIXME: rel_vel assignment here is overwritten by the following assignment.
  430. // What seems to be intended in the next next assignment is: rel_vel = normal.dot(rel_vel);
  431. // Investigate why.
  432. real_t rel_vel = jac.getRelativeVelocity(
  433. s->get_linear_velocity(),
  434. s->get_transform().basis.transposed().xform(s->get_angular_velocity()),
  435. b2lv,
  436. b2trans.xform(b2av));
  437. rel_vel = normal.dot(vel);
  438. // !BAS! We had this set to 0.4, in bullet its 0.2
  439. real_t contactDamping = real_t(0.2);
  440. if (p_rollInfluence > 0.0) {
  441. // !BAS! But seeing we apply this frame by frame, makes more sense to me to make this time based
  442. // keeping in mind our anti roll factor if it is set
  443. contactDamping = s->get_step() / p_rollInfluence;
  444. }
  445. #define ONLY_USE_LINEAR_MASS
  446. #ifdef ONLY_USE_LINEAR_MASS
  447. real_t massTerm = real_t(1.) / ((1.0 / mass) + b2invmass);
  448. impulse = -contactDamping * rel_vel * massTerm;
  449. #else
  450. real_t velocityImpulse = -contactDamping * rel_vel * jacDiagABInv;
  451. impulse = velocityImpulse;
  452. #endif
  453. }
  454. VehicleBody::btVehicleWheelContactPoint::btVehicleWheelContactPoint(PhysicsDirectBodyState *s, PhysicsBody *body1, const Vector3 &frictionPosWorld, const Vector3 &frictionDirectionWorld, real_t maxImpulse) :
  455. m_s(s),
  456. m_body1(body1),
  457. m_frictionPositionWorld(frictionPosWorld),
  458. m_frictionDirectionWorld(frictionDirectionWorld),
  459. m_maxImpulse(maxImpulse) {
  460. float denom0 = 0;
  461. float denom1 = 0;
  462. {
  463. Vector3 r0 = frictionPosWorld - s->get_transform().origin;
  464. Vector3 c0 = (r0).cross(frictionDirectionWorld);
  465. Vector3 vec = s->get_inverse_inertia_tensor().xform_inv(c0).cross(r0);
  466. denom0 = s->get_inverse_mass() + frictionDirectionWorld.dot(vec);
  467. }
  468. /* TODO: Why is this code unused?
  469. if (body1) {
  470. Vector3 r0 = frictionPosWorld - body1->get_global_transform().origin;
  471. Vector3 c0 = (r0).cross(frictionDirectionWorld);
  472. Vector3 vec = s->get_inverse_inertia_tensor().xform_inv(c0).cross(r0);
  473. //denom1= body1->get_inverse_mass() + frictionDirectionWorld.dot(vec);
  474. }
  475. */
  476. real_t relaxation = 1.f;
  477. m_jacDiagABInv = relaxation / (denom0 + denom1);
  478. }
  479. real_t VehicleBody::_calc_rolling_friction(btVehicleWheelContactPoint &contactPoint) {
  480. real_t j1 = 0.f;
  481. const Vector3 &contactPosWorld = contactPoint.m_frictionPositionWorld;
  482. Vector3 rel_pos1 = contactPosWorld - contactPoint.m_s->get_transform().origin;
  483. Vector3 rel_pos2;
  484. if (contactPoint.m_body1)
  485. rel_pos2 = contactPosWorld - contactPoint.m_body1->get_global_transform().origin;
  486. real_t maxImpulse = contactPoint.m_maxImpulse;
  487. Vector3 vel1 = contactPoint.m_s->get_linear_velocity() + (contactPoint.m_s->get_angular_velocity()).cross(rel_pos1); // * mPos);
  488. Vector3 vel2;
  489. if (contactPoint.m_body1) {
  490. vel2 = contactPoint.m_body1->get_linear_velocity() + contactPoint.m_body1->get_angular_velocity().cross(rel_pos2);
  491. }
  492. Vector3 vel = vel1 - vel2;
  493. real_t vrel = contactPoint.m_frictionDirectionWorld.dot(vel);
  494. // calculate j that moves us to zero relative velocity
  495. j1 = -vrel * contactPoint.m_jacDiagABInv;
  496. return CLAMP(j1, -maxImpulse, maxImpulse);
  497. }
  498. static const real_t sideFrictionStiffness2 = real_t(1.0);
  499. void VehicleBody::_update_friction(PhysicsDirectBodyState *s) {
  500. //calculate the impulse, so that the wheels don't move sidewards
  501. int numWheel = wheels.size();
  502. if (!numWheel)
  503. return;
  504. m_forwardWS.resize(numWheel);
  505. m_axle.resize(numWheel);
  506. m_forwardImpulse.resize(numWheel);
  507. m_sideImpulse.resize(numWheel);
  508. //collapse all those loops into one!
  509. for (int i = 0; i < wheels.size(); i++) {
  510. m_sideImpulse.write[i] = real_t(0.);
  511. m_forwardImpulse.write[i] = real_t(0.);
  512. }
  513. {
  514. for (int i = 0; i < wheels.size(); i++) {
  515. VehicleWheel &wheelInfo = *wheels[i];
  516. if (wheelInfo.m_raycastInfo.m_isInContact) {
  517. //const btTransform& wheelTrans = getWheelTransformWS( i );
  518. Basis wheelBasis0 = wheelInfo.m_worldTransform.basis; //get_global_transform().basis;
  519. m_axle.write[i] = wheelBasis0.get_axis(Vector3::AXIS_X);
  520. //m_axle[i] = wheelInfo.m_raycastInfo.m_wheelAxleWS;
  521. const Vector3 &surfNormalWS = wheelInfo.m_raycastInfo.m_contactNormalWS;
  522. real_t proj = m_axle[i].dot(surfNormalWS);
  523. m_axle.write[i] -= surfNormalWS * proj;
  524. m_axle.write[i] = m_axle[i].normalized();
  525. m_forwardWS.write[i] = surfNormalWS.cross(m_axle[i]);
  526. m_forwardWS.write[i].normalize();
  527. _resolve_single_bilateral(s, wheelInfo.m_raycastInfo.m_contactPointWS,
  528. wheelInfo.m_raycastInfo.m_groundObject, wheelInfo.m_raycastInfo.m_contactPointWS,
  529. m_axle[i], m_sideImpulse.write[i], wheelInfo.m_rollInfluence);
  530. m_sideImpulse.write[i] *= sideFrictionStiffness2;
  531. }
  532. }
  533. }
  534. real_t sideFactor = real_t(1.);
  535. real_t fwdFactor = 0.5;
  536. bool sliding = false;
  537. {
  538. for (int wheel = 0; wheel < wheels.size(); wheel++) {
  539. VehicleWheel &wheelInfo = *wheels[wheel];
  540. //class btRigidBody* groundObject = (class btRigidBody*) wheelInfo.m_raycastInfo.m_groundObject;
  541. real_t rollingFriction = 0.f;
  542. if (wheelInfo.m_raycastInfo.m_isInContact) {
  543. if (engine_force != 0.f) {
  544. rollingFriction = -engine_force * s->get_step();
  545. } else {
  546. real_t defaultRollingFrictionImpulse = 0.f;
  547. float cbrake = MAX(wheelInfo.m_brake, brake);
  548. real_t maxImpulse = cbrake ? cbrake : defaultRollingFrictionImpulse;
  549. btVehicleWheelContactPoint contactPt(s, wheelInfo.m_raycastInfo.m_groundObject, wheelInfo.m_raycastInfo.m_contactPointWS, m_forwardWS[wheel], maxImpulse);
  550. rollingFriction = _calc_rolling_friction(contactPt);
  551. }
  552. }
  553. //switch between active rolling (throttle), braking and non-active rolling friction (no throttle/break)
  554. m_forwardImpulse.write[wheel] = real_t(0.);
  555. wheelInfo.m_skidInfo = real_t(1.);
  556. if (wheelInfo.m_raycastInfo.m_isInContact) {
  557. wheelInfo.m_skidInfo = real_t(1.);
  558. real_t maximp = wheelInfo.m_wheelsSuspensionForce * s->get_step() * wheelInfo.m_frictionSlip;
  559. real_t maximpSide = maximp;
  560. real_t maximpSquared = maximp * maximpSide;
  561. m_forwardImpulse.write[wheel] = rollingFriction; //wheelInfo.m_engineForce* timeStep;
  562. real_t x = (m_forwardImpulse[wheel]) * fwdFactor;
  563. real_t y = (m_sideImpulse[wheel]) * sideFactor;
  564. real_t impulseSquared = (x * x + y * y);
  565. if (impulseSquared > maximpSquared) {
  566. sliding = true;
  567. real_t factor = maximp / Math::sqrt(impulseSquared);
  568. wheelInfo.m_skidInfo *= factor;
  569. }
  570. }
  571. }
  572. }
  573. if (sliding) {
  574. for (int wheel = 0; wheel < wheels.size(); wheel++) {
  575. if (m_sideImpulse[wheel] != real_t(0.)) {
  576. if (wheels[wheel]->m_skidInfo < real_t(1.)) {
  577. m_forwardImpulse.write[wheel] *= wheels[wheel]->m_skidInfo;
  578. m_sideImpulse.write[wheel] *= wheels[wheel]->m_skidInfo;
  579. }
  580. }
  581. }
  582. }
  583. // apply the impulses
  584. {
  585. for (int wheel = 0; wheel < wheels.size(); wheel++) {
  586. VehicleWheel &wheelInfo = *wheels[wheel];
  587. Vector3 rel_pos = wheelInfo.m_raycastInfo.m_contactPointWS -
  588. s->get_transform().origin;
  589. if (m_forwardImpulse[wheel] != real_t(0.)) {
  590. s->apply_impulse(rel_pos, m_forwardWS[wheel] * (m_forwardImpulse[wheel]));
  591. }
  592. if (m_sideImpulse[wheel] != real_t(0.)) {
  593. PhysicsBody *groundObject = wheelInfo.m_raycastInfo.m_groundObject;
  594. Vector3 rel_pos2;
  595. if (groundObject) {
  596. rel_pos2 = wheelInfo.m_raycastInfo.m_contactPointWS - groundObject->get_global_transform().origin;
  597. }
  598. Vector3 sideImp = m_axle[wheel] * m_sideImpulse[wheel];
  599. #if defined ROLLING_INFLUENCE_FIX // fix. It only worked if car's up was along Y - VT.
  600. Vector3 vChassisWorldUp = s->get_transform().basis.transposed()[1]; //getRigidBody()->getCenterOfMassTransform().getBasis().getColumn(m_indexUpAxis);
  601. rel_pos -= vChassisWorldUp * (vChassisWorldUp.dot(rel_pos) * (1.f - wheelInfo.m_rollInfluence));
  602. #else
  603. rel_pos[1] *= wheelInfo.m_rollInfluence; //?
  604. #endif
  605. s->apply_impulse(rel_pos, sideImp);
  606. //apply friction impulse on the ground
  607. //todo
  608. //groundObject->applyImpulse(-sideImp,rel_pos2);
  609. }
  610. }
  611. }
  612. }
  613. void VehicleBody::_direct_state_changed(Object *p_state) {
  614. RigidBody::_direct_state_changed(p_state);
  615. state = Object::cast_to<PhysicsDirectBodyState>(p_state);
  616. float step = state->get_step();
  617. for (int i = 0; i < wheels.size(); i++) {
  618. _update_wheel(i, state);
  619. }
  620. for (int i = 0; i < wheels.size(); i++) {
  621. _ray_cast(i, state);
  622. wheels[i]->set_transform(state->get_transform().inverse() * wheels[i]->m_worldTransform);
  623. }
  624. _update_suspension(state);
  625. for (int i = 0; i < wheels.size(); i++) {
  626. //apply suspension force
  627. VehicleWheel &wheel = *wheels[i];
  628. real_t suspensionForce = wheel.m_wheelsSuspensionForce;
  629. if (suspensionForce > wheel.m_maxSuspensionForce) {
  630. suspensionForce = wheel.m_maxSuspensionForce;
  631. }
  632. Vector3 impulse = wheel.m_raycastInfo.m_contactNormalWS * suspensionForce * step;
  633. Vector3 relpos = wheel.m_raycastInfo.m_contactPointWS - state->get_transform().origin;
  634. state->apply_impulse(relpos, impulse);
  635. //getRigidBody()->applyImpulse(impulse, relpos);
  636. }
  637. _update_friction(state);
  638. for (int i = 0; i < wheels.size(); i++) {
  639. VehicleWheel &wheel = *wheels[i];
  640. Vector3 relpos = wheel.m_raycastInfo.m_hardPointWS - state->get_transform().origin;
  641. Vector3 vel = state->get_linear_velocity() + (state->get_angular_velocity()).cross(relpos); // * mPos);
  642. if (wheel.m_raycastInfo.m_isInContact) {
  643. const Transform &chassisWorldTransform = state->get_transform();
  644. Vector3 fwd(
  645. chassisWorldTransform.basis[0][Vector3::AXIS_Z],
  646. chassisWorldTransform.basis[1][Vector3::AXIS_Z],
  647. chassisWorldTransform.basis[2][Vector3::AXIS_Z]);
  648. real_t proj = fwd.dot(wheel.m_raycastInfo.m_contactNormalWS);
  649. fwd -= wheel.m_raycastInfo.m_contactNormalWS * proj;
  650. real_t proj2 = fwd.dot(vel);
  651. wheel.m_deltaRotation = (proj2 * step) / (wheel.m_wheelRadius);
  652. wheel.m_rotation += wheel.m_deltaRotation;
  653. } else {
  654. wheel.m_rotation += wheel.m_deltaRotation;
  655. }
  656. wheel.m_deltaRotation *= real_t(0.99); //damping of rotation when not in contact
  657. }
  658. state = NULL;
  659. }
  660. void VehicleBody::set_engine_force(float p_engine_force) {
  661. engine_force = p_engine_force;
  662. }
  663. float VehicleBody::get_engine_force() const {
  664. return engine_force;
  665. }
  666. void VehicleBody::set_brake(float p_brake) {
  667. brake = p_brake;
  668. }
  669. float VehicleBody::get_brake() const {
  670. return brake;
  671. }
  672. void VehicleBody::set_steering(float p_steering) {
  673. m_steeringValue = p_steering;
  674. }
  675. float VehicleBody::get_steering() const {
  676. return m_steeringValue;
  677. }
  678. void VehicleBody::_bind_methods() {
  679. ClassDB::bind_method(D_METHOD("set_engine_force", "engine_force"), &VehicleBody::set_engine_force);
  680. ClassDB::bind_method(D_METHOD("get_engine_force"), &VehicleBody::get_engine_force);
  681. ClassDB::bind_method(D_METHOD("set_brake", "brake"), &VehicleBody::set_brake);
  682. ClassDB::bind_method(D_METHOD("get_brake"), &VehicleBody::get_brake);
  683. ClassDB::bind_method(D_METHOD("set_steering", "steering"), &VehicleBody::set_steering);
  684. ClassDB::bind_method(D_METHOD("get_steering"), &VehicleBody::get_steering);
  685. ADD_GROUP("Motion", "");
  686. ADD_PROPERTY(PropertyInfo(Variant::REAL, "engine_force", PROPERTY_HINT_RANGE, "0.00,1024.0,0.01,or_greater"), "set_engine_force", "get_engine_force");
  687. ADD_PROPERTY(PropertyInfo(Variant::REAL, "brake", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), "set_brake", "get_brake");
  688. ADD_PROPERTY(PropertyInfo(Variant::REAL, "steering", PROPERTY_HINT_RANGE, "-180,180.0,0.01"), "set_steering", "get_steering");
  689. }
  690. VehicleBody::VehicleBody() :
  691. RigidBody() {
  692. m_pitchControl = 0;
  693. m_currentVehicleSpeedKmHour = real_t(0.);
  694. m_steeringValue = real_t(0.);
  695. engine_force = 0;
  696. brake = 0;
  697. state = NULL;
  698. ccd = false;
  699. exclude.insert(get_rid());
  700. //PhysicsServer::get_singleton()->body_set_force_integration_callback(get_rid(), this, "_direct_state_changed");
  701. set_mass(40);
  702. }