space_2d_sw.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  1. /*************************************************************************/
  2. /* space_2d_sw.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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 "space_2d_sw.h"
  31. #include "collision_solver_2d_sw.h"
  32. #include "core/os/os.h"
  33. #include "core/pair.h"
  34. #include "physics_2d_server_sw.h"
  35. #define TEST_MOTION_MIN_CONTACT_DEPTH_FACTOR 0.05
  36. _FORCE_INLINE_ static bool _can_collide_with(CollisionObject2DSW *p_object, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  37. if (!(p_object->get_collision_layer() & p_collision_mask)) {
  38. return false;
  39. }
  40. if (p_object->get_type() == CollisionObject2DSW::TYPE_AREA && !p_collide_with_areas) {
  41. return false;
  42. }
  43. if (p_object->get_type() == CollisionObject2DSW::TYPE_BODY && !p_collide_with_bodies) {
  44. return false;
  45. }
  46. return true;
  47. }
  48. int Physics2DDirectSpaceStateSW::_intersect_point_impl(const Vector2 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, bool p_pick_point, bool p_filter_by_canvas, ObjectID p_canvas_instance_id) {
  49. if (p_result_max <= 0) {
  50. return 0;
  51. }
  52. Rect2 aabb;
  53. aabb.position = p_point - Vector2(0.00001, 0.00001);
  54. aabb.size = Vector2(0.00002, 0.00002);
  55. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  56. int cc = 0;
  57. for (int i = 0; i < amount; i++) {
  58. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask, p_collide_with_bodies, p_collide_with_areas)) {
  59. continue;
  60. }
  61. if (p_exclude.has(space->intersection_query_results[i]->get_self())) {
  62. continue;
  63. }
  64. const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
  65. if (p_pick_point && !col_obj->is_pickable()) {
  66. continue;
  67. }
  68. if (p_filter_by_canvas && col_obj->get_canvas_instance_id() != p_canvas_instance_id) {
  69. continue;
  70. }
  71. int shape_idx = space->intersection_query_subindex_results[i];
  72. Shape2DSW *shape = col_obj->get_shape(shape_idx);
  73. Vector2 local_point = (col_obj->get_transform() * col_obj->get_shape_transform(shape_idx)).affine_inverse().xform(p_point);
  74. if (!shape->contains_point(local_point)) {
  75. continue;
  76. }
  77. if (cc >= p_result_max) {
  78. continue;
  79. }
  80. r_results[cc].collider_id = col_obj->get_instance_id();
  81. if (r_results[cc].collider_id != 0) {
  82. r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
  83. }
  84. r_results[cc].rid = col_obj->get_self();
  85. r_results[cc].shape = shape_idx;
  86. r_results[cc].metadata = col_obj->get_shape_metadata(shape_idx);
  87. cc++;
  88. }
  89. return cc;
  90. }
  91. int Physics2DDirectSpaceStateSW::intersect_point(const Vector2 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, bool p_pick_point) {
  92. return _intersect_point_impl(p_point, r_results, p_result_max, p_exclude, p_collision_mask, p_collide_with_bodies, p_collide_with_areas, p_pick_point);
  93. }
  94. int Physics2DDirectSpaceStateSW::intersect_point_on_canvas(const Vector2 &p_point, ObjectID p_canvas_instance_id, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, bool p_pick_point) {
  95. return _intersect_point_impl(p_point, r_results, p_result_max, p_exclude, p_collision_mask, p_collide_with_bodies, p_collide_with_areas, p_pick_point, true, p_canvas_instance_id);
  96. }
  97. bool Physics2DDirectSpaceStateSW::intersect_ray(const Vector2 &p_from, const Vector2 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  98. ERR_FAIL_COND_V(space->locked, false);
  99. Vector2 begin, end;
  100. Vector2 normal;
  101. begin = p_from;
  102. end = p_to;
  103. normal = (end - begin).normalized();
  104. int amount = space->broadphase->cull_segment(begin, end, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  105. //todo, create another array that references results, compute AABBs and check closest point to ray origin, sort, and stop evaluating results when beyond first collision
  106. bool collided = false;
  107. Vector2 res_point, res_normal;
  108. int res_shape;
  109. const CollisionObject2DSW *res_obj;
  110. real_t min_d = 1e10;
  111. for (int i = 0; i < amount; i++) {
  112. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask, p_collide_with_bodies, p_collide_with_areas)) {
  113. continue;
  114. }
  115. if (p_exclude.has(space->intersection_query_results[i]->get_self())) {
  116. continue;
  117. }
  118. const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
  119. int shape_idx = space->intersection_query_subindex_results[i];
  120. Transform2D inv_xform = col_obj->get_shape_inv_transform(shape_idx) * col_obj->get_inv_transform();
  121. Vector2 local_from = inv_xform.xform(begin);
  122. Vector2 local_to = inv_xform.xform(end);
  123. /*local_from = col_obj->get_inv_transform().xform(begin);
  124. local_from = col_obj->get_shape_inv_transform(shape_idx).xform(local_from);
  125. local_to = col_obj->get_inv_transform().xform(end);
  126. local_to = col_obj->get_shape_inv_transform(shape_idx).xform(local_to);*/
  127. const Shape2DSW *shape = col_obj->get_shape(shape_idx);
  128. Vector2 shape_point, shape_normal;
  129. if (shape->intersect_segment(local_from, local_to, shape_point, shape_normal)) {
  130. Transform2D xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  131. shape_point = xform.xform(shape_point);
  132. real_t ld = normal.dot(shape_point);
  133. if (ld < min_d) {
  134. min_d = ld;
  135. res_point = shape_point;
  136. res_normal = inv_xform.basis_xform_inv(shape_normal).normalized();
  137. res_shape = shape_idx;
  138. res_obj = col_obj;
  139. collided = true;
  140. }
  141. }
  142. }
  143. if (!collided) {
  144. return false;
  145. }
  146. r_result.collider_id = res_obj->get_instance_id();
  147. if (r_result.collider_id != 0) {
  148. r_result.collider = ObjectDB::get_instance(r_result.collider_id);
  149. }
  150. r_result.normal = res_normal;
  151. r_result.metadata = res_obj->get_shape_metadata(res_shape);
  152. r_result.position = res_point;
  153. r_result.rid = res_obj->get_self();
  154. r_result.shape = res_shape;
  155. return true;
  156. }
  157. int Physics2DDirectSpaceStateSW::intersect_shape(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  158. if (p_result_max <= 0) {
  159. return 0;
  160. }
  161. Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape);
  162. ERR_FAIL_COND_V(!shape, 0);
  163. Rect2 aabb = p_xform.xform(shape->get_aabb());
  164. aabb = aabb.grow(p_margin);
  165. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  166. int cc = 0;
  167. for (int i = 0; i < amount; i++) {
  168. if (cc >= p_result_max) {
  169. break;
  170. }
  171. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask, p_collide_with_bodies, p_collide_with_areas)) {
  172. continue;
  173. }
  174. if (p_exclude.has(space->intersection_query_results[i]->get_self())) {
  175. continue;
  176. }
  177. const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
  178. int shape_idx = space->intersection_query_subindex_results[i];
  179. if (!CollisionSolver2DSW::solve(shape, p_xform, p_motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), nullptr, nullptr, nullptr, p_margin)) {
  180. continue;
  181. }
  182. r_results[cc].collider_id = col_obj->get_instance_id();
  183. if (r_results[cc].collider_id != 0) {
  184. r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
  185. }
  186. r_results[cc].rid = col_obj->get_self();
  187. r_results[cc].shape = shape_idx;
  188. r_results[cc].metadata = col_obj->get_shape_metadata(shape_idx);
  189. cc++;
  190. }
  191. return cc;
  192. }
  193. bool Physics2DDirectSpaceStateSW::cast_motion(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, real_t p_margin, real_t &p_closest_safe, real_t &p_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  194. Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape);
  195. ERR_FAIL_COND_V(!shape, false);
  196. Rect2 aabb = p_xform.xform(shape->get_aabb());
  197. aabb = aabb.merge(Rect2(aabb.position + p_motion, aabb.size)); //motion
  198. aabb = aabb.grow(p_margin);
  199. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  200. real_t best_safe = 1;
  201. real_t best_unsafe = 1;
  202. for (int i = 0; i < amount; i++) {
  203. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask, p_collide_with_bodies, p_collide_with_areas)) {
  204. continue;
  205. }
  206. if (p_exclude.has(space->intersection_query_results[i]->get_self())) {
  207. continue; //ignore excluded
  208. }
  209. const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
  210. int shape_idx = space->intersection_query_subindex_results[i];
  211. Transform2D col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  212. //test initial overlap, does it collide if going all the way?
  213. if (!CollisionSolver2DSW::solve(shape, p_xform, p_motion, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), nullptr, nullptr, nullptr, p_margin)) {
  214. continue;
  215. }
  216. //test initial overlap, ignore objects it's inside of.
  217. if (CollisionSolver2DSW::solve(shape, p_xform, Vector2(), col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), nullptr, nullptr, nullptr, p_margin)) {
  218. continue;
  219. }
  220. Vector2 mnormal = p_motion.normalized();
  221. //just do kinematic solving
  222. real_t low = 0.0;
  223. real_t hi = 1.0;
  224. real_t fraction_coeff = 0.5;
  225. for (int j = 0; j < 8; j++) { //steps should be customizable..
  226. real_t fraction = low + (hi - low) * fraction_coeff;
  227. Vector2 sep = mnormal; //important optimization for this to work fast enough
  228. bool collided = CollisionSolver2DSW::solve(shape, p_xform, p_motion * fraction, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), nullptr, nullptr, &sep, p_margin);
  229. if (collided) {
  230. hi = fraction;
  231. if ((j == 0) || (low > 0.0)) { // Did it not collide before?
  232. // When alternating or first iteration, use dichotomy.
  233. fraction_coeff = 0.5;
  234. } else {
  235. // When colliding again, converge faster towards low fraction
  236. // for more accurate results with long motions that collide near the start.
  237. fraction_coeff = 0.25;
  238. }
  239. } else {
  240. low = fraction;
  241. if ((j == 0) || (hi < 1.0)) { // Did it collide before?
  242. // When alternating or first iteration, use dichotomy.
  243. fraction_coeff = 0.5;
  244. } else {
  245. // When not colliding again, converge faster towards high fraction
  246. // for more accurate results with long motions that collide near the end.
  247. fraction_coeff = 0.75;
  248. }
  249. }
  250. }
  251. if (low < best_safe) {
  252. best_safe = low;
  253. best_unsafe = hi;
  254. }
  255. }
  256. p_closest_safe = best_safe;
  257. p_closest_unsafe = best_unsafe;
  258. return true;
  259. }
  260. bool Physics2DDirectSpaceStateSW::collide_shape(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, real_t p_margin, Vector2 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  261. if (p_result_max <= 0) {
  262. return false;
  263. }
  264. Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape);
  265. ERR_FAIL_COND_V(!shape, 0);
  266. Rect2 aabb = p_shape_xform.xform(shape->get_aabb());
  267. aabb = aabb.merge(Rect2(aabb.position + p_motion, aabb.size)); //motion
  268. aabb = aabb.grow(p_margin);
  269. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  270. bool collided = false;
  271. r_result_count = 0;
  272. Physics2DServerSW::CollCbkData cbk;
  273. cbk.max = p_result_max;
  274. cbk.amount = 0;
  275. cbk.passed = 0;
  276. cbk.ptr = r_results;
  277. CollisionSolver2DSW::CallbackResult cbkres = Physics2DServerSW::_shape_col_cbk;
  278. Physics2DServerSW::CollCbkData *cbkptr = &cbk;
  279. for (int i = 0; i < amount; i++) {
  280. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask, p_collide_with_bodies, p_collide_with_areas)) {
  281. continue;
  282. }
  283. const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
  284. int shape_idx = space->intersection_query_subindex_results[i];
  285. if (p_exclude.has(col_obj->get_self())) {
  286. continue;
  287. }
  288. cbk.valid_dir = Vector2();
  289. cbk.valid_depth = 0;
  290. if (CollisionSolver2DSW::solve(shape, p_shape_xform, p_motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), cbkres, cbkptr, nullptr, p_margin)) {
  291. collided = cbk.amount > 0;
  292. }
  293. }
  294. r_result_count = cbk.amount;
  295. return collided;
  296. }
  297. struct _RestCallbackData2D {
  298. const CollisionObject2DSW *object;
  299. const CollisionObject2DSW *best_object;
  300. int local_shape;
  301. int best_local_shape;
  302. int shape;
  303. int best_shape;
  304. Vector2 best_contact;
  305. Vector2 best_normal;
  306. real_t best_len;
  307. Vector2 valid_dir;
  308. real_t valid_depth;
  309. real_t min_allowed_depth;
  310. };
  311. static void _rest_cbk_result(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata) {
  312. _RestCallbackData2D *rd = (_RestCallbackData2D *)p_userdata;
  313. Vector2 contact_rel = p_point_B - p_point_A;
  314. real_t len = contact_rel.length();
  315. if (len < rd->min_allowed_depth) {
  316. return;
  317. }
  318. if (len <= rd->best_len) {
  319. return;
  320. }
  321. Vector2 normal = contact_rel / len;
  322. if (rd->valid_dir != Vector2()) {
  323. if (len > rd->valid_depth) {
  324. return;
  325. }
  326. if (rd->valid_dir.dot(normal) > -CMP_EPSILON) {
  327. return;
  328. }
  329. }
  330. rd->best_len = len;
  331. rd->best_contact = p_point_B;
  332. rd->best_normal = normal;
  333. rd->best_object = rd->object;
  334. rd->best_shape = rd->shape;
  335. rd->best_local_shape = rd->local_shape;
  336. }
  337. bool Physics2DDirectSpaceStateSW::rest_info(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  338. Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape);
  339. ERR_FAIL_COND_V(!shape, 0);
  340. real_t min_contact_depth = p_margin * TEST_MOTION_MIN_CONTACT_DEPTH_FACTOR;
  341. Rect2 aabb = p_shape_xform.xform(shape->get_aabb());
  342. aabb = aabb.merge(Rect2(aabb.position + p_motion, aabb.size)); //motion
  343. aabb = aabb.grow(p_margin);
  344. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  345. _RestCallbackData2D rcd;
  346. rcd.best_len = 0;
  347. rcd.best_object = nullptr;
  348. rcd.best_shape = 0;
  349. rcd.min_allowed_depth = min_contact_depth;
  350. for (int i = 0; i < amount; i++) {
  351. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask, p_collide_with_bodies, p_collide_with_areas)) {
  352. continue;
  353. }
  354. const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
  355. int shape_idx = space->intersection_query_subindex_results[i];
  356. if (p_exclude.has(col_obj->get_self())) {
  357. continue;
  358. }
  359. rcd.valid_dir = Vector2();
  360. rcd.object = col_obj;
  361. rcd.shape = shape_idx;
  362. rcd.local_shape = 0;
  363. bool sc = CollisionSolver2DSW::solve(shape, p_shape_xform, p_motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), _rest_cbk_result, &rcd, nullptr, p_margin);
  364. if (!sc) {
  365. continue;
  366. }
  367. }
  368. if (rcd.best_len == 0 || !rcd.best_object) {
  369. return false;
  370. }
  371. r_info->collider_id = rcd.best_object->get_instance_id();
  372. r_info->shape = rcd.best_shape;
  373. r_info->normal = rcd.best_normal;
  374. r_info->point = rcd.best_contact;
  375. r_info->rid = rcd.best_object->get_self();
  376. r_info->metadata = rcd.best_object->get_shape_metadata(rcd.best_shape);
  377. if (rcd.best_object->get_type() == CollisionObject2DSW::TYPE_BODY) {
  378. const Body2DSW *body = static_cast<const Body2DSW *>(rcd.best_object);
  379. Vector2 rel_vec = r_info->point - body->get_transform().get_origin();
  380. r_info->linear_velocity = Vector2(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity();
  381. } else {
  382. r_info->linear_velocity = Vector2();
  383. }
  384. return true;
  385. }
  386. Physics2DDirectSpaceStateSW::Physics2DDirectSpaceStateSW() {
  387. space = nullptr;
  388. }
  389. ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  390. int Space2DSW::_cull_aabb_for_body(Body2DSW *p_body, const Rect2 &p_aabb) {
  391. int amount = broadphase->cull_aabb(p_aabb, intersection_query_results, INTERSECTION_QUERY_MAX, intersection_query_subindex_results);
  392. for (int i = 0; i < amount; i++) {
  393. bool keep = true;
  394. if (intersection_query_results[i] == p_body) {
  395. keep = false;
  396. } else if (intersection_query_results[i]->get_type() == CollisionObject2DSW::TYPE_AREA) {
  397. keep = false;
  398. } else if ((static_cast<Body2DSW *>(intersection_query_results[i])->test_collision_mask(p_body)) == 0) {
  399. keep = false;
  400. } else if (static_cast<Body2DSW *>(intersection_query_results[i])->has_exception(p_body->get_self()) || p_body->has_exception(intersection_query_results[i]->get_self())) {
  401. keep = false;
  402. }
  403. if (!keep) {
  404. if (i < amount - 1) {
  405. SWAP(intersection_query_results[i], intersection_query_results[amount - 1]);
  406. SWAP(intersection_query_subindex_results[i], intersection_query_subindex_results[amount - 1]);
  407. }
  408. amount--;
  409. i--;
  410. }
  411. }
  412. return amount;
  413. }
  414. int Space2DSW::test_body_ray_separation(Body2DSW *p_body, const Transform2D &p_transform, bool p_infinite_inertia, Vector2 &r_recover_motion, Physics2DServer::SeparationResult *r_results, int p_result_max, real_t p_margin) {
  415. Rect2 body_aabb;
  416. bool shapes_found = false;
  417. for (int i = 0; i < p_body->get_shape_count(); i++) {
  418. if (p_body->is_shape_disabled(i)) {
  419. continue;
  420. }
  421. if (p_body->get_shape(i)->get_type() != Physics2DServer::SHAPE_RAY) {
  422. continue;
  423. }
  424. if (!shapes_found) {
  425. body_aabb = p_body->get_shape_aabb(i);
  426. shapes_found = true;
  427. } else {
  428. body_aabb = body_aabb.merge(p_body->get_shape_aabb(i));
  429. }
  430. }
  431. if (!shapes_found) {
  432. return 0;
  433. }
  434. // Undo the currently transform the physics server is aware of and apply the provided one
  435. body_aabb = p_transform.xform(p_body->get_inv_transform().xform(body_aabb));
  436. body_aabb = body_aabb.grow(p_margin);
  437. Transform2D body_transform = p_transform;
  438. for (int i = 0; i < p_result_max; i++) {
  439. //reset results
  440. r_results[i].collision_depth = -1.0;
  441. }
  442. int rays_found = 0;
  443. {
  444. // raycast AND separate
  445. const int max_results = 32;
  446. int recover_attempts = 4;
  447. Vector2 sr[max_results * 2];
  448. Physics2DServerSW::CollCbkData cbk;
  449. cbk.max = max_results;
  450. Physics2DServerSW::CollCbkData *cbkptr = &cbk;
  451. CollisionSolver2DSW::CallbackResult cbkres = Physics2DServerSW::_shape_col_cbk;
  452. do {
  453. Vector2 recover_motion;
  454. bool collided = false;
  455. int amount = _cull_aabb_for_body(p_body, body_aabb);
  456. for (int j = 0; j < p_body->get_shape_count(); j++) {
  457. if (p_body->is_shape_disabled(j)) {
  458. continue;
  459. }
  460. Shape2DSW *body_shape = p_body->get_shape(j);
  461. if (body_shape->get_type() != Physics2DServer::SHAPE_RAY) {
  462. continue;
  463. }
  464. Transform2D body_shape_xform = body_transform * p_body->get_shape_transform(j);
  465. for (int i = 0; i < amount; i++) {
  466. const CollisionObject2DSW *col_obj = intersection_query_results[i];
  467. int shape_idx = intersection_query_subindex_results[i];
  468. cbk.amount = 0;
  469. cbk.passed = 0;
  470. cbk.ptr = sr;
  471. cbk.invalid_by_dir = 0;
  472. if (CollisionObject2DSW::TYPE_BODY == col_obj->get_type()) {
  473. const Body2DSW *b = static_cast<const Body2DSW *>(col_obj);
  474. if (p_infinite_inertia && Physics2DServer::BODY_MODE_STATIC != b->get_mode() && Physics2DServer::BODY_MODE_KINEMATIC != b->get_mode()) {
  475. continue;
  476. }
  477. }
  478. Transform2D col_obj_shape_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  479. /*
  480. * There is no point in supporting one way collisions with ray shapes, as they will always collide in the desired
  481. * direction. Use a short ray shape if you want to achieve a similar effect.
  482. *
  483. if (col_obj->is_shape_set_as_one_way_collision(shape_idx)) {
  484. cbk.valid_dir = col_obj_shape_xform.get_axis(1).normalized();
  485. cbk.valid_depth = p_margin; //only valid depth is the collision margin
  486. cbk.invalid_by_dir = 0;
  487. } else {
  488. */
  489. cbk.valid_dir = Vector2();
  490. cbk.valid_depth = 0;
  491. cbk.invalid_by_dir = 0;
  492. /*
  493. }
  494. */
  495. Shape2DSW *against_shape = col_obj->get_shape(shape_idx);
  496. if (CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), cbkres, cbkptr, nullptr, p_margin)) {
  497. if (cbk.amount > 0) {
  498. collided = true;
  499. }
  500. int ray_index = -1; //reuse shape
  501. for (int k = 0; k < rays_found; k++) {
  502. if (r_results[ray_index].collision_local_shape == j) {
  503. ray_index = k;
  504. }
  505. }
  506. if (ray_index == -1 && rays_found < p_result_max) {
  507. ray_index = rays_found;
  508. rays_found++;
  509. }
  510. if (ray_index != -1) {
  511. Physics2DServer::SeparationResult &result = r_results[ray_index];
  512. for (int k = 0; k < cbk.amount; k++) {
  513. Vector2 a = sr[k * 2 + 0];
  514. Vector2 b = sr[k * 2 + 1];
  515. // Compute plane on b towards a.
  516. Vector2 n = (a - b).normalized();
  517. float d = n.dot(b);
  518. // Compute depth on recovered motion.
  519. float depth = n.dot(a + recover_motion) - d;
  520. // Apply recovery without margin.
  521. float separation_depth = depth - p_margin;
  522. if (separation_depth > 0.0) {
  523. // Only recover if there is penetration.
  524. recover_motion -= n * separation_depth;
  525. }
  526. if (depth > result.collision_depth) {
  527. result.collision_depth = depth;
  528. result.collision_point = b;
  529. result.collision_normal = -n;
  530. result.collision_local_shape = j;
  531. result.collider_shape = shape_idx;
  532. result.collider = col_obj->get_self();
  533. result.collider_id = col_obj->get_instance_id();
  534. result.collider_metadata = col_obj->get_shape_metadata(shape_idx);
  535. if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
  536. Body2DSW *body = (Body2DSW *)col_obj;
  537. Vector2 rel_vec = b - body->get_transform().get_origin();
  538. result.collider_velocity = Vector2(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity();
  539. }
  540. }
  541. }
  542. }
  543. }
  544. }
  545. }
  546. if (!collided || recover_motion == Vector2()) {
  547. break;
  548. }
  549. body_transform.elements[2] += recover_motion;
  550. body_aabb.position += recover_motion;
  551. recover_attempts--;
  552. } while (recover_attempts);
  553. }
  554. r_recover_motion = body_transform.elements[2] - p_transform.elements[2];
  555. return rays_found;
  556. }
  557. bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, const Vector2 &p_motion, bool p_infinite_inertia, real_t p_margin, Physics2DServer::MotionResult *r_result, bool p_exclude_raycast_shapes, const Set<RID> &p_exclude) {
  558. //give me back regular physics engine logic
  559. //this is madness
  560. //and most people using this function will think
  561. //what it does is simpler than using physics
  562. //this took about a week to get right..
  563. //but is it right? who knows at this point..
  564. if (r_result) {
  565. r_result->collider_id = 0;
  566. r_result->collider_shape = 0;
  567. }
  568. Rect2 body_aabb;
  569. bool shapes_found = false;
  570. for (int i = 0; i < p_body->get_shape_count(); i++) {
  571. if (p_body->is_shape_disabled(i)) {
  572. continue;
  573. }
  574. if (p_exclude_raycast_shapes && p_body->get_shape(i)->get_type() == Physics2DServer::SHAPE_RAY) {
  575. continue;
  576. }
  577. if (!shapes_found) {
  578. body_aabb = p_body->get_shape_aabb(i);
  579. shapes_found = true;
  580. } else {
  581. body_aabb = body_aabb.merge(p_body->get_shape_aabb(i));
  582. }
  583. }
  584. if (!shapes_found) {
  585. if (r_result) {
  586. *r_result = Physics2DServer::MotionResult();
  587. r_result->motion = p_motion;
  588. }
  589. return false;
  590. }
  591. // Undo the currently transform the physics server is aware of and apply the provided one
  592. body_aabb = p_from.xform(p_body->get_inv_transform().xform(body_aabb));
  593. body_aabb = body_aabb.grow(p_margin);
  594. static const int max_excluded_shape_pairs = 32;
  595. ExcludedShapeSW excluded_shape_pairs[max_excluded_shape_pairs];
  596. int excluded_shape_pair_count = 0;
  597. real_t min_contact_depth = p_margin * TEST_MOTION_MIN_CONTACT_DEPTH_FACTOR;
  598. float motion_length = p_motion.length();
  599. Vector2 motion_normal = p_motion / motion_length;
  600. Transform2D body_transform = p_from;
  601. bool recovered = false;
  602. {
  603. //STEP 1, FREE BODY IF STUCK
  604. const int max_results = 32;
  605. int recover_attempts = 4;
  606. Vector2 sr[max_results * 2];
  607. do {
  608. Physics2DServerSW::CollCbkData cbk;
  609. cbk.max = max_results;
  610. cbk.amount = 0;
  611. cbk.passed = 0;
  612. cbk.ptr = sr;
  613. cbk.invalid_by_dir = 0;
  614. excluded_shape_pair_count = 0; //last step is the one valid
  615. Physics2DServerSW::CollCbkData *cbkptr = &cbk;
  616. CollisionSolver2DSW::CallbackResult cbkres = Physics2DServerSW::_shape_col_cbk;
  617. bool collided = false;
  618. int amount = _cull_aabb_for_body(p_body, body_aabb);
  619. for (int j = 0; j < p_body->get_shape_count(); j++) {
  620. if (p_body->is_shape_disabled(j)) {
  621. continue;
  622. }
  623. Shape2DSW *body_shape = p_body->get_shape(j);
  624. if (p_exclude_raycast_shapes && body_shape->get_type() == Physics2DServer::SHAPE_RAY) {
  625. continue;
  626. }
  627. Transform2D body_shape_xform = body_transform * p_body->get_shape_transform(j);
  628. for (int i = 0; i < amount; i++) {
  629. const CollisionObject2DSW *col_obj = intersection_query_results[i];
  630. if (p_exclude.has(col_obj->get_self())) {
  631. continue;
  632. }
  633. int shape_idx = intersection_query_subindex_results[i];
  634. if (CollisionObject2DSW::TYPE_BODY == col_obj->get_type()) {
  635. const Body2DSW *b = static_cast<const Body2DSW *>(col_obj);
  636. if (p_infinite_inertia && Physics2DServer::BODY_MODE_STATIC != b->get_mode() && Physics2DServer::BODY_MODE_KINEMATIC != b->get_mode()) {
  637. continue;
  638. }
  639. }
  640. Transform2D col_obj_shape_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  641. if (col_obj->is_shape_set_as_one_way_collision(shape_idx)) {
  642. cbk.valid_dir = col_obj_shape_xform.get_axis(1).normalized();
  643. float owc_margin = col_obj->get_shape_one_way_collision_margin(shape_idx);
  644. cbk.valid_depth = MAX(owc_margin, p_margin); //user specified, but never less than actual margin or it won't work
  645. cbk.invalid_by_dir = 0;
  646. if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
  647. const Body2DSW *b = static_cast<const Body2DSW *>(col_obj);
  648. if (b->get_mode() == Physics2DServer::BODY_MODE_KINEMATIC || b->get_mode() == Physics2DServer::BODY_MODE_RIGID) {
  649. //fix for moving platforms (kinematic and dynamic), margin is increased by how much it moved in the given direction
  650. Vector2 lv = b->get_linear_velocity();
  651. //compute displacement from linear velocity
  652. Vector2 motion = lv * Physics2DDirectBodyStateSW::singleton->step;
  653. float motion_len = motion.length();
  654. motion.normalize();
  655. cbk.valid_depth += motion_len * MAX(motion.dot(-cbk.valid_dir), 0.0);
  656. }
  657. }
  658. } else {
  659. cbk.valid_dir = Vector2();
  660. cbk.valid_depth = 0;
  661. cbk.invalid_by_dir = 0;
  662. }
  663. int current_passed = cbk.passed; //save how many points passed collision
  664. bool did_collide = false;
  665. Shape2DSW *against_shape = col_obj->get_shape(shape_idx);
  666. if (CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), cbkres, cbkptr, nullptr, p_margin)) {
  667. did_collide = cbk.passed > current_passed; //more passed, so collision actually existed
  668. }
  669. if (!did_collide && cbk.invalid_by_dir > 0) {
  670. //this shape must be excluded
  671. if (excluded_shape_pair_count < max_excluded_shape_pairs) {
  672. ExcludedShapeSW esp;
  673. esp.local_shape = body_shape;
  674. esp.against_object = col_obj;
  675. esp.against_shape_index = shape_idx;
  676. excluded_shape_pairs[excluded_shape_pair_count++] = esp;
  677. }
  678. }
  679. if (did_collide) {
  680. collided = true;
  681. }
  682. }
  683. }
  684. if (!collided) {
  685. break;
  686. }
  687. recovered = true;
  688. Vector2 recover_motion;
  689. for (int i = 0; i < cbk.amount; i++) {
  690. Vector2 a = sr[i * 2 + 0];
  691. Vector2 b = sr[i * 2 + 1];
  692. // Compute plane on b towards a.
  693. Vector2 n = (a - b).normalized();
  694. float d = n.dot(b);
  695. // Compute depth on recovered motion.
  696. float depth = n.dot(a + recover_motion) - d;
  697. if (depth > min_contact_depth + CMP_EPSILON) {
  698. // Only recover if there is penetration.
  699. recover_motion -= n * (depth - min_contact_depth) * 0.4;
  700. }
  701. }
  702. if (recover_motion == Vector2()) {
  703. collided = false;
  704. break;
  705. }
  706. body_transform.elements[2] += recover_motion;
  707. body_aabb.position += recover_motion;
  708. recover_attempts--;
  709. } while (recover_attempts);
  710. }
  711. real_t safe = 1.0;
  712. real_t unsafe = 1.0;
  713. int best_shape = -1;
  714. {
  715. // STEP 2 ATTEMPT MOTION
  716. Rect2 motion_aabb = body_aabb;
  717. motion_aabb.position += p_motion;
  718. motion_aabb = motion_aabb.merge(body_aabb);
  719. int amount = _cull_aabb_for_body(p_body, motion_aabb);
  720. for (int body_shape_idx = 0; body_shape_idx < p_body->get_shape_count(); body_shape_idx++) {
  721. if (p_body->is_shape_disabled(body_shape_idx)) {
  722. continue;
  723. }
  724. Shape2DSW *body_shape = p_body->get_shape(body_shape_idx);
  725. if (p_exclude_raycast_shapes && body_shape->get_type() == Physics2DServer::SHAPE_RAY) {
  726. continue;
  727. }
  728. Transform2D body_shape_xform = body_transform * p_body->get_shape_transform(body_shape_idx);
  729. bool stuck = false;
  730. real_t best_safe = 1;
  731. real_t best_unsafe = 1;
  732. for (int i = 0; i < amount; i++) {
  733. const CollisionObject2DSW *col_obj = intersection_query_results[i];
  734. if (p_exclude.has(col_obj->get_self())) {
  735. continue;
  736. }
  737. int col_shape_idx = intersection_query_subindex_results[i];
  738. Shape2DSW *against_shape = col_obj->get_shape(col_shape_idx);
  739. if (CollisionObject2DSW::TYPE_BODY == col_obj->get_type()) {
  740. const Body2DSW *b = static_cast<const Body2DSW *>(col_obj);
  741. if (p_infinite_inertia && Physics2DServer::BODY_MODE_STATIC != b->get_mode() && Physics2DServer::BODY_MODE_KINEMATIC != b->get_mode()) {
  742. continue;
  743. }
  744. }
  745. bool excluded = false;
  746. for (int k = 0; k < excluded_shape_pair_count; k++) {
  747. if (excluded_shape_pairs[k].local_shape == body_shape && excluded_shape_pairs[k].against_object == col_obj && excluded_shape_pairs[k].against_shape_index == col_shape_idx) {
  748. excluded = true;
  749. break;
  750. }
  751. }
  752. if (excluded) {
  753. continue;
  754. }
  755. Transform2D col_obj_shape_xform = col_obj->get_transform() * col_obj->get_shape_transform(col_shape_idx);
  756. //test initial overlap, does it collide if going all the way?
  757. if (!CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion, against_shape, col_obj_shape_xform, Vector2(), nullptr, nullptr, nullptr, 0)) {
  758. continue;
  759. }
  760. //test initial overlap
  761. if (CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), nullptr, nullptr, nullptr, 0)) {
  762. if (col_obj->is_shape_set_as_one_way_collision(col_shape_idx)) {
  763. Vector2 direction = col_obj_shape_xform.get_axis(1).normalized();
  764. if (motion_normal.dot(direction) < 0) {
  765. continue;
  766. }
  767. }
  768. stuck = true;
  769. break;
  770. }
  771. //just do kinematic solving
  772. real_t low = 0.0;
  773. real_t hi = 1.0;
  774. real_t fraction_coeff = 0.5;
  775. for (int k = 0; k < 8; k++) { //steps should be customizable..
  776. real_t fraction = low + (hi - low) * fraction_coeff;
  777. Vector2 sep = motion_normal; //important optimization for this to work fast enough
  778. bool collided = CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion * fraction, against_shape, col_obj_shape_xform, Vector2(), nullptr, nullptr, &sep, 0);
  779. if (collided) {
  780. hi = fraction;
  781. if ((k == 0) || (low > 0.0)) { // Did it not collide before?
  782. // When alternating or first iteration, use dichotomy.
  783. fraction_coeff = 0.5;
  784. } else {
  785. // When colliding again, converge faster towards low fraction
  786. // for more accurate results with long motions that collide near the start.
  787. fraction_coeff = 0.25;
  788. }
  789. } else {
  790. low = fraction;
  791. if ((k == 0) || (hi < 1.0)) { // Did it collide before?
  792. // When alternating or first iteration, use dichotomy.
  793. fraction_coeff = 0.5;
  794. } else {
  795. // When not colliding again, converge faster towards high fraction
  796. // for more accurate results with long motions that collide near the end.
  797. fraction_coeff = 0.75;
  798. }
  799. }
  800. }
  801. if (col_obj->is_shape_set_as_one_way_collision(col_shape_idx)) {
  802. Vector2 cd[2];
  803. Physics2DServerSW::CollCbkData cbk;
  804. cbk.max = 1;
  805. cbk.amount = 0;
  806. cbk.passed = 0;
  807. cbk.ptr = cd;
  808. cbk.valid_dir = col_obj_shape_xform.get_axis(1).normalized();
  809. cbk.valid_depth = 10e20;
  810. Vector2 sep = motion_normal; //important optimization for this to work fast enough
  811. bool collided = CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion * (hi + contact_max_allowed_penetration), col_obj->get_shape(col_shape_idx), col_obj_shape_xform, Vector2(), Physics2DServerSW::_shape_col_cbk, &cbk, &sep, 0);
  812. if (!collided || cbk.amount == 0) {
  813. continue;
  814. }
  815. }
  816. if (low < best_safe) {
  817. best_safe = low;
  818. best_unsafe = hi;
  819. }
  820. }
  821. if (stuck) {
  822. safe = 0;
  823. unsafe = 0;
  824. best_shape = body_shape_idx; //sadly it's the best
  825. break;
  826. }
  827. if (best_safe == 1.0) {
  828. continue;
  829. }
  830. if (best_safe < safe) {
  831. safe = best_safe;
  832. unsafe = best_unsafe;
  833. best_shape = body_shape_idx;
  834. }
  835. }
  836. }
  837. bool collided = false;
  838. if (recovered || (safe < 1)) {
  839. if (safe >= 1) {
  840. best_shape = -1; //no best shape with cast, reset to -1
  841. }
  842. //it collided, let's get the rest info in unsafe advance
  843. Transform2D ugt = body_transform;
  844. ugt.elements[2] += p_motion * unsafe;
  845. _RestCallbackData2D rcd;
  846. rcd.best_len = 0;
  847. rcd.best_object = nullptr;
  848. rcd.best_shape = 0;
  849. // Allowed depth can't be lower than motion length, in order to handle contacts at low speed.
  850. rcd.min_allowed_depth = MIN(motion_length, min_contact_depth);
  851. body_aabb.position += p_motion * unsafe;
  852. int amount = _cull_aabb_for_body(p_body, body_aabb);
  853. int from_shape = best_shape != -1 ? best_shape : 0;
  854. int to_shape = best_shape != -1 ? best_shape + 1 : p_body->get_shape_count();
  855. for (int j = from_shape; j < to_shape; j++) {
  856. if (p_body->is_shape_disabled(j)) {
  857. continue;
  858. }
  859. Transform2D body_shape_xform = ugt * p_body->get_shape_transform(j);
  860. Shape2DSW *body_shape = p_body->get_shape(j);
  861. if (p_exclude_raycast_shapes && body_shape->get_type() == Physics2DServer::SHAPE_RAY) {
  862. continue;
  863. }
  864. for (int i = 0; i < amount; i++) {
  865. const CollisionObject2DSW *col_obj = intersection_query_results[i];
  866. if (p_exclude.has(col_obj->get_self())) {
  867. continue;
  868. }
  869. int shape_idx = intersection_query_subindex_results[i];
  870. if (CollisionObject2DSW::TYPE_BODY == col_obj->get_type()) {
  871. const Body2DSW *b = static_cast<const Body2DSW *>(col_obj);
  872. if (p_infinite_inertia && Physics2DServer::BODY_MODE_STATIC != b->get_mode() && Physics2DServer::BODY_MODE_KINEMATIC != b->get_mode()) {
  873. continue;
  874. }
  875. }
  876. Shape2DSW *against_shape = col_obj->get_shape(shape_idx);
  877. bool excluded = false;
  878. for (int k = 0; k < excluded_shape_pair_count; k++) {
  879. if (excluded_shape_pairs[k].local_shape == body_shape && excluded_shape_pairs[k].against_object == col_obj && excluded_shape_pairs[k].against_shape_index == shape_idx) {
  880. excluded = true;
  881. break;
  882. }
  883. }
  884. if (excluded) {
  885. continue;
  886. }
  887. Transform2D col_obj_shape_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  888. if (col_obj->is_shape_set_as_one_way_collision(shape_idx)) {
  889. rcd.valid_dir = col_obj_shape_xform.get_axis(1).normalized();
  890. float owc_margin = col_obj->get_shape_one_way_collision_margin(shape_idx);
  891. rcd.valid_depth = MAX(owc_margin, p_margin); //user specified, but never less than actual margin or it won't work
  892. if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
  893. const Body2DSW *b = static_cast<const Body2DSW *>(col_obj);
  894. if (b->get_mode() == Physics2DServer::BODY_MODE_KINEMATIC || b->get_mode() == Physics2DServer::BODY_MODE_RIGID) {
  895. //fix for moving platforms (kinematic and dynamic), margin is increased by how much it moved in the given direction
  896. Vector2 lv = b->get_linear_velocity();
  897. //compute displacement from linear velocity
  898. Vector2 motion = lv * Physics2DDirectBodyStateSW::singleton->step;
  899. float motion_len = motion.length();
  900. motion.normalize();
  901. rcd.valid_depth += motion_len * MAX(motion.dot(-rcd.valid_dir), 0.0);
  902. }
  903. }
  904. } else {
  905. rcd.valid_dir = Vector2();
  906. rcd.valid_depth = 0;
  907. }
  908. rcd.object = col_obj;
  909. rcd.shape = shape_idx;
  910. rcd.local_shape = j;
  911. bool sc = CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), _rest_cbk_result, &rcd, nullptr, p_margin);
  912. if (!sc) {
  913. continue;
  914. }
  915. }
  916. }
  917. if (rcd.best_len != 0) {
  918. if (r_result) {
  919. r_result->collider = rcd.best_object->get_self();
  920. r_result->collider_id = rcd.best_object->get_instance_id();
  921. r_result->collider_shape = rcd.best_shape;
  922. r_result->collision_local_shape = rcd.best_local_shape;
  923. r_result->collision_normal = rcd.best_normal;
  924. r_result->collision_point = rcd.best_contact;
  925. r_result->collision_depth = rcd.best_len;
  926. r_result->collision_safe_fraction = safe;
  927. r_result->collision_unsafe_fraction = unsafe;
  928. r_result->collider_metadata = rcd.best_object->get_shape_metadata(rcd.best_shape);
  929. const Body2DSW *body = static_cast<const Body2DSW *>(rcd.best_object);
  930. Vector2 rel_vec = r_result->collision_point - body->get_transform().get_origin();
  931. r_result->collider_velocity = Vector2(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity();
  932. r_result->motion = safe * p_motion;
  933. r_result->remainder = p_motion - safe * p_motion;
  934. r_result->motion += (body_transform.get_origin() - p_from.get_origin());
  935. }
  936. collided = true;
  937. }
  938. }
  939. if (!collided && r_result) {
  940. r_result->motion = p_motion;
  941. r_result->remainder = Vector2();
  942. r_result->motion += (body_transform.get_origin() - p_from.get_origin());
  943. }
  944. return collided;
  945. }
  946. void *Space2DSW::_broadphase_pair(CollisionObject2DSW *p_object_A, int p_subindex_A, CollisionObject2DSW *p_object_B, int p_subindex_B, void *p_pair_data, void *p_self) {
  947. bool valid_collision_pair = p_object_A->test_collision_mask(p_object_B);
  948. if (p_pair_data) {
  949. // Checking an existing pair.
  950. if (valid_collision_pair) {
  951. // Nothing to do, pair is still valid.
  952. return p_pair_data;
  953. } else {
  954. // Logical collision not valid anymore, unpair.
  955. _broadphase_unpair(p_object_A, p_subindex_A, p_object_B, p_subindex_B, p_pair_data, p_self);
  956. return nullptr;
  957. }
  958. }
  959. if (!valid_collision_pair) {
  960. return nullptr;
  961. }
  962. CollisionObject2DSW::Type type_A = p_object_A->get_type();
  963. CollisionObject2DSW::Type type_B = p_object_B->get_type();
  964. if (type_A > type_B) {
  965. SWAP(p_object_A, p_object_B);
  966. SWAP(p_subindex_A, p_subindex_B);
  967. SWAP(type_A, type_B);
  968. }
  969. Space2DSW *self = (Space2DSW *)p_self;
  970. self->collision_pairs++;
  971. if (type_A == CollisionObject2DSW::TYPE_AREA) {
  972. Area2DSW *area_a = static_cast<Area2DSW *>(p_object_A);
  973. if (type_B == CollisionObject2DSW::TYPE_AREA) {
  974. Area2DSW *area_b = static_cast<Area2DSW *>(p_object_B);
  975. Area2Pair2DSW *area2_pair = memnew(Area2Pair2DSW(area_b, p_subindex_B, area_a, p_subindex_A));
  976. return area2_pair;
  977. } else {
  978. Body2DSW *body_b = static_cast<Body2DSW *>(p_object_B);
  979. AreaPair2DSW *area_pair = memnew(AreaPair2DSW(body_b, p_subindex_B, area_a, p_subindex_A));
  980. return area_pair;
  981. }
  982. } else {
  983. Body2DSW *body_a = static_cast<Body2DSW *>(p_object_A);
  984. Body2DSW *body_b = static_cast<Body2DSW *>(p_object_B);
  985. BodyPair2DSW *body_pair = memnew(BodyPair2DSW(body_a, p_subindex_A, body_b, p_subindex_B));
  986. return body_pair;
  987. }
  988. return nullptr;
  989. }
  990. void Space2DSW::_broadphase_unpair(CollisionObject2DSW *p_object_A, int p_subindex_A, CollisionObject2DSW *p_object_B, int p_subindex_B, void *p_pair_data, void *p_self) {
  991. if (!p_pair_data) {
  992. return;
  993. }
  994. Space2DSW *self = (Space2DSW *)p_self;
  995. self->collision_pairs--;
  996. Constraint2DSW *c = (Constraint2DSW *)p_pair_data;
  997. memdelete(c);
  998. }
  999. const SelfList<Body2DSW>::List &Space2DSW::get_active_body_list() const {
  1000. return active_list;
  1001. }
  1002. void Space2DSW::body_add_to_active_list(SelfList<Body2DSW> *p_body) {
  1003. active_list.add(p_body);
  1004. }
  1005. void Space2DSW::body_remove_from_active_list(SelfList<Body2DSW> *p_body) {
  1006. active_list.remove(p_body);
  1007. }
  1008. void Space2DSW::body_add_to_inertia_update_list(SelfList<Body2DSW> *p_body) {
  1009. inertia_update_list.add(p_body);
  1010. }
  1011. void Space2DSW::body_remove_from_inertia_update_list(SelfList<Body2DSW> *p_body) {
  1012. inertia_update_list.remove(p_body);
  1013. }
  1014. BroadPhase2DSW *Space2DSW::get_broadphase() {
  1015. return broadphase;
  1016. }
  1017. void Space2DSW::add_object(CollisionObject2DSW *p_object) {
  1018. ERR_FAIL_COND(objects.has(p_object));
  1019. objects.insert(p_object);
  1020. }
  1021. void Space2DSW::remove_object(CollisionObject2DSW *p_object) {
  1022. ERR_FAIL_COND(!objects.has(p_object));
  1023. objects.erase(p_object);
  1024. }
  1025. const Set<CollisionObject2DSW *> &Space2DSW::get_objects() const {
  1026. return objects;
  1027. }
  1028. void Space2DSW::body_add_to_state_query_list(SelfList<Body2DSW> *p_body) {
  1029. state_query_list.add(p_body);
  1030. }
  1031. void Space2DSW::body_remove_from_state_query_list(SelfList<Body2DSW> *p_body) {
  1032. state_query_list.remove(p_body);
  1033. }
  1034. void Space2DSW::area_add_to_monitor_query_list(SelfList<Area2DSW> *p_area) {
  1035. monitor_query_list.add(p_area);
  1036. }
  1037. void Space2DSW::area_remove_from_monitor_query_list(SelfList<Area2DSW> *p_area) {
  1038. monitor_query_list.remove(p_area);
  1039. }
  1040. void Space2DSW::area_add_to_moved_list(SelfList<Area2DSW> *p_area) {
  1041. area_moved_list.add(p_area);
  1042. }
  1043. void Space2DSW::area_remove_from_moved_list(SelfList<Area2DSW> *p_area) {
  1044. area_moved_list.remove(p_area);
  1045. }
  1046. const SelfList<Area2DSW>::List &Space2DSW::get_moved_area_list() const {
  1047. return area_moved_list;
  1048. }
  1049. void Space2DSW::call_queries() {
  1050. while (state_query_list.first()) {
  1051. Body2DSW *b = state_query_list.first()->self();
  1052. state_query_list.remove(state_query_list.first());
  1053. b->call_queries();
  1054. }
  1055. while (monitor_query_list.first()) {
  1056. Area2DSW *a = monitor_query_list.first()->self();
  1057. monitor_query_list.remove(monitor_query_list.first());
  1058. a->call_queries();
  1059. }
  1060. }
  1061. void Space2DSW::setup() {
  1062. contact_debug_count = 0;
  1063. while (inertia_update_list.first()) {
  1064. inertia_update_list.first()->self()->update_inertias();
  1065. inertia_update_list.remove(inertia_update_list.first());
  1066. }
  1067. }
  1068. void Space2DSW::update() {
  1069. broadphase->update();
  1070. }
  1071. void Space2DSW::set_param(Physics2DServer::SpaceParameter p_param, real_t p_value) {
  1072. switch (p_param) {
  1073. case Physics2DServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  1074. contact_recycle_radius = p_value;
  1075. break;
  1076. case Physics2DServer::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  1077. contact_max_separation = p_value;
  1078. break;
  1079. case Physics2DServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION:
  1080. contact_max_allowed_penetration = p_value;
  1081. break;
  1082. case Physics2DServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  1083. body_linear_velocity_sleep_threshold = p_value;
  1084. break;
  1085. case Physics2DServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  1086. body_angular_velocity_sleep_threshold = p_value;
  1087. break;
  1088. case Physics2DServer::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  1089. body_time_to_sleep = p_value;
  1090. break;
  1091. case Physics2DServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  1092. constraint_bias = p_value;
  1093. break;
  1094. }
  1095. }
  1096. real_t Space2DSW::get_param(Physics2DServer::SpaceParameter p_param) const {
  1097. switch (p_param) {
  1098. case Physics2DServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  1099. return contact_recycle_radius;
  1100. case Physics2DServer::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  1101. return contact_max_separation;
  1102. case Physics2DServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION:
  1103. return contact_max_allowed_penetration;
  1104. case Physics2DServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  1105. return body_linear_velocity_sleep_threshold;
  1106. case Physics2DServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  1107. return body_angular_velocity_sleep_threshold;
  1108. case Physics2DServer::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  1109. return body_time_to_sleep;
  1110. case Physics2DServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  1111. return constraint_bias;
  1112. }
  1113. return 0;
  1114. }
  1115. void Space2DSW::lock() {
  1116. locked = true;
  1117. }
  1118. void Space2DSW::unlock() {
  1119. locked = false;
  1120. }
  1121. bool Space2DSW::is_locked() const {
  1122. return locked;
  1123. }
  1124. Physics2DDirectSpaceStateSW *Space2DSW::get_direct_state() {
  1125. return direct_access;
  1126. }
  1127. Space2DSW::Space2DSW() {
  1128. collision_pairs = 0;
  1129. active_objects = 0;
  1130. island_count = 0;
  1131. contact_debug_count = 0;
  1132. locked = false;
  1133. contact_recycle_radius = 1.0;
  1134. contact_max_separation = 1.5;
  1135. contact_max_allowed_penetration = 0.3;
  1136. constraint_bias = 0.2;
  1137. body_linear_velocity_sleep_threshold = GLOBAL_DEF("physics/2d/sleep_threshold_linear", 2.0);
  1138. body_angular_velocity_sleep_threshold = GLOBAL_DEF("physics/2d/sleep_threshold_angular", (8.0 / 180.0 * Math_PI));
  1139. body_time_to_sleep = GLOBAL_DEF("physics/2d/time_before_sleep", 0.5);
  1140. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/time_before_sleep", PropertyInfo(Variant::REAL, "physics/2d/time_before_sleep", PROPERTY_HINT_RANGE, "0,5,0.01,or_greater"));
  1141. broadphase = BroadPhase2DSW::create_func();
  1142. broadphase->set_pair_callback(_broadphase_pair, this);
  1143. broadphase->set_unpair_callback(_broadphase_unpair, this);
  1144. area = nullptr;
  1145. direct_access = memnew(Physics2DDirectSpaceStateSW);
  1146. direct_access->space = this;
  1147. for (int i = 0; i < ELAPSED_TIME_MAX; i++) {
  1148. elapsed_time[i] = 0;
  1149. }
  1150. }
  1151. Space2DSW::~Space2DSW() {
  1152. memdelete(broadphase);
  1153. memdelete(direct_access);
  1154. }