body_pair_2d_sw.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*************************************************************************/
  2. /* body_pair_2d_sw.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 "body_pair_2d_sw.h"
  31. #include "collision_solver_2d_sw.h"
  32. #include "space_2d_sw.h"
  33. #define POSITION_CORRECTION
  34. #define ACCUMULATE_IMPULSES
  35. void BodyPair2DSW::_add_contact(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_self) {
  36. BodyPair2DSW *self = (BodyPair2DSW *)p_self;
  37. self->_contact_added_callback(p_point_A, p_point_B);
  38. }
  39. void BodyPair2DSW::_contact_added_callback(const Vector2 &p_point_A, const Vector2 &p_point_B) {
  40. // check if we already have the contact
  41. Vector2 local_A = A->get_inv_transform().basis_xform(p_point_A);
  42. Vector2 local_B = B->get_inv_transform().basis_xform(p_point_B - offset_B);
  43. int new_index = contact_count;
  44. ERR_FAIL_COND(new_index >= (MAX_CONTACTS + 1));
  45. Contact contact;
  46. contact.acc_normal_impulse = 0;
  47. contact.acc_bias_impulse = 0;
  48. contact.acc_tangent_impulse = 0;
  49. contact.local_A = local_A;
  50. contact.local_B = local_B;
  51. contact.reused = true;
  52. contact.normal = (p_point_A - p_point_B).normalized();
  53. contact.mass_normal = 0; // will be computed in setup()
  54. // attempt to determine if the contact will be reused
  55. real_t recycle_radius_2 = space->get_contact_recycle_radius() * space->get_contact_recycle_radius();
  56. for (int i = 0; i < contact_count; i++) {
  57. Contact &c = contacts[i];
  58. if (
  59. c.local_A.distance_squared_to(local_A) < (recycle_radius_2) &&
  60. c.local_B.distance_squared_to(local_B) < (recycle_radius_2)) {
  61. contact.acc_normal_impulse = c.acc_normal_impulse;
  62. contact.acc_tangent_impulse = c.acc_tangent_impulse;
  63. contact.acc_bias_impulse = c.acc_bias_impulse;
  64. new_index = i;
  65. break;
  66. }
  67. }
  68. // figure out if the contact amount must be reduced to fit the new contact
  69. if (new_index == MAX_CONTACTS) {
  70. // remove the contact with the minimum depth
  71. int least_deep = -1;
  72. real_t min_depth = 1e10;
  73. for (int i = 0; i <= contact_count; i++) {
  74. Contact &c = (i == contact_count) ? contact : contacts[i];
  75. Vector2 global_A = A->get_transform().basis_xform(c.local_A);
  76. Vector2 global_B = B->get_transform().basis_xform(c.local_B) + offset_B;
  77. Vector2 axis = global_A - global_B;
  78. real_t depth = axis.dot(c.normal);
  79. if (depth < min_depth) {
  80. min_depth = depth;
  81. least_deep = i;
  82. }
  83. }
  84. ERR_FAIL_COND(least_deep == -1);
  85. if (least_deep < contact_count) { //replace the last deep contact by the new one
  86. contacts[least_deep] = contact;
  87. }
  88. return;
  89. }
  90. contacts[new_index] = contact;
  91. if (new_index == contact_count) {
  92. contact_count++;
  93. }
  94. }
  95. void BodyPair2DSW::_validate_contacts() {
  96. //make sure to erase contacts that are no longer valid
  97. real_t max_separation = space->get_contact_max_separation();
  98. real_t max_separation2 = max_separation * max_separation;
  99. for (int i = 0; i < contact_count; i++) {
  100. Contact &c = contacts[i];
  101. bool erase = false;
  102. if (!c.reused) {
  103. //was left behind in previous frame
  104. erase = true;
  105. } else {
  106. c.reused = false;
  107. Vector2 global_A = A->get_transform().basis_xform(c.local_A);
  108. Vector2 global_B = B->get_transform().basis_xform(c.local_B) + offset_B;
  109. Vector2 axis = global_A - global_B;
  110. real_t depth = axis.dot(c.normal);
  111. if (depth < -max_separation || (global_B + c.normal * depth - global_A).length_squared() > max_separation2) {
  112. erase = true;
  113. }
  114. }
  115. if (erase) {
  116. // contact no longer needed, remove
  117. if ((i + 1) < contact_count) {
  118. // swap with the last one
  119. SWAP(contacts[i], contacts[contact_count - 1]);
  120. }
  121. i--;
  122. contact_count--;
  123. }
  124. }
  125. }
  126. bool BodyPair2DSW::_test_ccd(real_t p_step, Body2DSW *p_A, int p_shape_A, const Transform2D &p_xform_A, Body2DSW *p_B, int p_shape_B, const Transform2D &p_xform_B, bool p_swap_result) {
  127. Vector2 motion = p_A->get_linear_velocity() * p_step;
  128. real_t mlen = motion.length();
  129. if (mlen < CMP_EPSILON)
  130. return false;
  131. Vector2 mnormal = motion / mlen;
  132. real_t min, max;
  133. p_A->get_shape(p_shape_A)->project_rangev(mnormal, p_xform_A, min, max);
  134. bool fast_object = mlen > (max - min) * 0.3; //going too fast in that direction
  135. if (!fast_object) { //did it move enough in this direction to even attempt raycast? let's say it should move more than 1/3 the size of the object in that axis
  136. return false;
  137. }
  138. //cast a segment from support in motion normal, in the same direction of motion by motion length
  139. //support is the worst case collision point, so real collision happened before
  140. int a;
  141. Vector2 s[2];
  142. p_A->get_shape(p_shape_A)->get_supports(p_xform_A.basis_xform(mnormal).normalized(), s, a);
  143. Vector2 from = p_xform_A.xform(s[0]);
  144. Vector2 to = from + motion;
  145. Transform2D from_inv = p_xform_B.affine_inverse();
  146. Vector2 local_from = from_inv.xform(from - mnormal * mlen * 0.1); //start from a little inside the bounding box
  147. Vector2 local_to = from_inv.xform(to);
  148. Vector2 rpos, rnorm;
  149. if (!p_B->get_shape(p_shape_B)->intersect_segment(local_from, local_to, rpos, rnorm))
  150. return false;
  151. //ray hit something
  152. Vector2 hitpos = p_xform_B.xform(rpos);
  153. Vector2 contact_A = to;
  154. Vector2 contact_B = hitpos;
  155. //create a contact
  156. if (p_swap_result)
  157. _contact_added_callback(contact_B, contact_A);
  158. else
  159. _contact_added_callback(contact_A, contact_B);
  160. return true;
  161. }
  162. real_t combine_bounce(Body2DSW *A, Body2DSW *B) {
  163. return CLAMP(A->get_bounce() + B->get_bounce(), 0, 1);
  164. }
  165. real_t combine_friction(Body2DSW *A, Body2DSW *B) {
  166. return ABS(MIN(A->get_friction(), B->get_friction()));
  167. }
  168. bool BodyPair2DSW::setup(real_t p_step) {
  169. //cannot collide
  170. if (!A->test_collision_mask(B) || A->has_exception(B->get_self()) || B->has_exception(A->get_self()) || (A->get_mode() <= Physics2DServer::BODY_MODE_KINEMATIC && B->get_mode() <= Physics2DServer::BODY_MODE_KINEMATIC && A->get_max_contacts_reported() == 0 && B->get_max_contacts_reported() == 0)) {
  171. collided = false;
  172. return false;
  173. }
  174. if (A->is_shape_set_as_disabled(shape_A) || B->is_shape_set_as_disabled(shape_B)) {
  175. collided = false;
  176. return false;
  177. }
  178. //use local A coordinates to avoid numerical issues on collision detection
  179. offset_B = B->get_transform().get_origin() - A->get_transform().get_origin();
  180. _validate_contacts();
  181. Vector2 offset_A = A->get_transform().get_origin();
  182. Transform2D xform_Au = A->get_transform().untranslated();
  183. Transform2D xform_A = xform_Au * A->get_shape_transform(shape_A);
  184. Transform2D xform_Bu = B->get_transform();
  185. xform_Bu.elements[2] -= A->get_transform().get_origin();
  186. Transform2D xform_B = xform_Bu * B->get_shape_transform(shape_B);
  187. Shape2DSW *shape_A_ptr = A->get_shape(shape_A);
  188. Shape2DSW *shape_B_ptr = B->get_shape(shape_B);
  189. Vector2 motion_A, motion_B;
  190. if (A->get_continuous_collision_detection_mode() == Physics2DServer::CCD_MODE_CAST_SHAPE) {
  191. motion_A = A->get_motion();
  192. }
  193. if (B->get_continuous_collision_detection_mode() == Physics2DServer::CCD_MODE_CAST_SHAPE) {
  194. motion_B = B->get_motion();
  195. }
  196. bool prev_collided = collided;
  197. collided = CollisionSolver2DSW::solve(shape_A_ptr, xform_A, motion_A, shape_B_ptr, xform_B, motion_B, _add_contact, this, &sep_axis);
  198. if (!collided) {
  199. //test ccd (currently just a raycast)
  200. if (A->get_continuous_collision_detection_mode() == Physics2DServer::CCD_MODE_CAST_RAY && A->get_mode() > Physics2DServer::BODY_MODE_KINEMATIC) {
  201. if (_test_ccd(p_step, A, shape_A, xform_A, B, shape_B, xform_B))
  202. collided = true;
  203. }
  204. if (B->get_continuous_collision_detection_mode() == Physics2DServer::CCD_MODE_CAST_RAY && B->get_mode() > Physics2DServer::BODY_MODE_KINEMATIC) {
  205. if (_test_ccd(p_step, B, shape_B, xform_B, A, shape_A, xform_A, true))
  206. collided = true;
  207. }
  208. if (!collided) {
  209. oneway_disabled = false;
  210. return false;
  211. }
  212. }
  213. if (oneway_disabled)
  214. return false;
  215. if (!prev_collided) {
  216. if (A->is_shape_set_as_one_way_collision(shape_A)) {
  217. Vector2 direction = xform_A.get_axis(1).normalized();
  218. bool valid = false;
  219. if (B->get_linear_velocity().dot(direction) >= 0) {
  220. for (int i = 0; i < contact_count; i++) {
  221. Contact &c = contacts[i];
  222. if (!c.reused)
  223. continue;
  224. if (c.normal.dot(direction) > 0) //greater (normal inverted)
  225. continue;
  226. valid = true;
  227. break;
  228. }
  229. }
  230. if (!valid) {
  231. collided = false;
  232. oneway_disabled = true;
  233. return false;
  234. }
  235. }
  236. if (B->is_shape_set_as_one_way_collision(shape_B)) {
  237. Vector2 direction = xform_B.get_axis(1).normalized();
  238. bool valid = false;
  239. if (A->get_linear_velocity().dot(direction) >= 0) {
  240. for (int i = 0; i < contact_count; i++) {
  241. Contact &c = contacts[i];
  242. if (!c.reused)
  243. continue;
  244. if (c.normal.dot(direction) < 0) //less (normal ok)
  245. continue;
  246. valid = true;
  247. break;
  248. }
  249. }
  250. if (!valid) {
  251. collided = false;
  252. oneway_disabled = true;
  253. return false;
  254. }
  255. }
  256. }
  257. real_t max_penetration = space->get_contact_max_allowed_penetration();
  258. real_t bias = 0.3;
  259. if (shape_A_ptr->get_custom_bias() || shape_B_ptr->get_custom_bias()) {
  260. if (shape_A_ptr->get_custom_bias() == 0)
  261. bias = shape_B_ptr->get_custom_bias();
  262. else if (shape_B_ptr->get_custom_bias() == 0)
  263. bias = shape_A_ptr->get_custom_bias();
  264. else
  265. bias = (shape_B_ptr->get_custom_bias() + shape_A_ptr->get_custom_bias()) * 0.5;
  266. }
  267. cc = 0;
  268. real_t inv_dt = 1.0 / p_step;
  269. bool do_process = false;
  270. for (int i = 0; i < contact_count; i++) {
  271. Contact &c = contacts[i];
  272. Vector2 global_A = xform_Au.xform(c.local_A);
  273. Vector2 global_B = xform_Bu.xform(c.local_B);
  274. real_t depth = c.normal.dot(global_A - global_B);
  275. if (depth <= 0 || !c.reused) {
  276. c.active = false;
  277. continue;
  278. }
  279. c.active = true;
  280. #ifdef DEBUG_ENABLED
  281. if (space->is_debugging_contacts()) {
  282. space->add_debug_contact(global_A + offset_A);
  283. space->add_debug_contact(global_B + offset_A);
  284. }
  285. #endif
  286. int gather_A = A->can_report_contacts();
  287. int gather_B = B->can_report_contacts();
  288. c.rA = global_A;
  289. c.rB = global_B - offset_B;
  290. if (gather_A | gather_B) {
  291. //Vector2 crB( -B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x );
  292. global_A += offset_A;
  293. global_B += offset_A;
  294. if (gather_A) {
  295. Vector2 crB(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x);
  296. A->add_contact(global_A, -c.normal, depth, shape_A, global_B, shape_B, B->get_instance_id(), B->get_self(), crB + B->get_linear_velocity());
  297. }
  298. if (gather_B) {
  299. Vector2 crA(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x);
  300. B->add_contact(global_B, c.normal, depth, shape_B, global_A, shape_A, A->get_instance_id(), A->get_self(), crA + A->get_linear_velocity());
  301. }
  302. }
  303. if ((A->get_mode() <= Physics2DServer::BODY_MODE_KINEMATIC && B->get_mode() <= Physics2DServer::BODY_MODE_KINEMATIC)) {
  304. c.active = false;
  305. collided = false;
  306. continue;
  307. }
  308. // Precompute normal mass, tangent mass, and bias.
  309. real_t rnA = c.rA.dot(c.normal);
  310. real_t rnB = c.rB.dot(c.normal);
  311. real_t kNormal = A->get_inv_mass() + B->get_inv_mass();
  312. kNormal += A->get_inv_inertia() * (c.rA.dot(c.rA) - rnA * rnA) + B->get_inv_inertia() * (c.rB.dot(c.rB) - rnB * rnB);
  313. c.mass_normal = 1.0f / kNormal;
  314. Vector2 tangent = c.normal.tangent();
  315. real_t rtA = c.rA.dot(tangent);
  316. real_t rtB = c.rB.dot(tangent);
  317. real_t kTangent = A->get_inv_mass() + B->get_inv_mass();
  318. kTangent += A->get_inv_inertia() * (c.rA.dot(c.rA) - rtA * rtA) + B->get_inv_inertia() * (c.rB.dot(c.rB) - rtB * rtB);
  319. c.mass_tangent = 1.0f / kTangent;
  320. c.bias = -bias * inv_dt * MIN(0.0f, -depth + max_penetration);
  321. c.depth = depth;
  322. //c.acc_bias_impulse=0;
  323. #ifdef ACCUMULATE_IMPULSES
  324. {
  325. // Apply normal + friction impulse
  326. Vector2 P = c.acc_normal_impulse * c.normal + c.acc_tangent_impulse * tangent;
  327. A->apply_impulse(c.rA, -P);
  328. B->apply_impulse(c.rB, P);
  329. }
  330. #endif
  331. c.bounce = combine_bounce(A, B);
  332. if (c.bounce) {
  333. Vector2 crA(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x);
  334. Vector2 crB(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x);
  335. Vector2 dv = B->get_linear_velocity() + crB - A->get_linear_velocity() - crA;
  336. c.bounce = c.bounce * dv.dot(c.normal);
  337. }
  338. do_process = true;
  339. }
  340. return do_process;
  341. }
  342. void BodyPair2DSW::solve(real_t p_step) {
  343. if (!collided)
  344. return;
  345. for (int i = 0; i < contact_count; ++i) {
  346. Contact &c = contacts[i];
  347. cc++;
  348. if (!c.active)
  349. continue;
  350. // Relative velocity at contact
  351. Vector2 crA(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x);
  352. Vector2 crB(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x);
  353. Vector2 dv = B->get_linear_velocity() + crB - A->get_linear_velocity() - crA;
  354. Vector2 crbA(-A->get_biased_angular_velocity() * c.rA.y, A->get_biased_angular_velocity() * c.rA.x);
  355. Vector2 crbB(-B->get_biased_angular_velocity() * c.rB.y, B->get_biased_angular_velocity() * c.rB.x);
  356. Vector2 dbv = B->get_biased_linear_velocity() + crbB - A->get_biased_linear_velocity() - crbA;
  357. real_t vn = dv.dot(c.normal);
  358. real_t vbn = dbv.dot(c.normal);
  359. Vector2 tangent = c.normal.tangent();
  360. real_t vt = dv.dot(tangent);
  361. real_t jbn = (c.bias - vbn) * c.mass_normal;
  362. real_t jbnOld = c.acc_bias_impulse;
  363. c.acc_bias_impulse = MAX(jbnOld + jbn, 0.0f);
  364. Vector2 jb = c.normal * (c.acc_bias_impulse - jbnOld);
  365. A->apply_bias_impulse(c.rA, -jb);
  366. B->apply_bias_impulse(c.rB, jb);
  367. real_t jn = -(c.bounce + vn) * c.mass_normal;
  368. real_t jnOld = c.acc_normal_impulse;
  369. c.acc_normal_impulse = MAX(jnOld + jn, 0.0f);
  370. real_t friction = combine_friction(A, B);
  371. real_t jtMax = friction * c.acc_normal_impulse;
  372. real_t jt = -vt * c.mass_tangent;
  373. real_t jtOld = c.acc_tangent_impulse;
  374. c.acc_tangent_impulse = CLAMP(jtOld + jt, -jtMax, jtMax);
  375. Vector2 j = c.normal * (c.acc_normal_impulse - jnOld) + tangent * (c.acc_tangent_impulse - jtOld);
  376. A->apply_impulse(c.rA, -j);
  377. B->apply_impulse(c.rB, j);
  378. }
  379. }
  380. BodyPair2DSW::BodyPair2DSW(Body2DSW *p_A, int p_shape_A, Body2DSW *p_B, int p_shape_B) :
  381. Constraint2DSW(_arr, 2) {
  382. A = p_A;
  383. B = p_B;
  384. shape_A = p_shape_A;
  385. shape_B = p_shape_B;
  386. space = A->get_space();
  387. A->add_constraint(this, 0);
  388. B->add_constraint(this, 1);
  389. contact_count = 0;
  390. collided = false;
  391. oneway_disabled = false;
  392. }
  393. BodyPair2DSW::~BodyPair2DSW() {
  394. A->remove_constraint(this);
  395. B->remove_constraint(this);
  396. }