space_2d_sw.cpp 48 KB

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