godot_space_2d.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. /*************************************************************************/
  2. /* godot_space_2d.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 "godot_space_2d.h"
  31. #include "godot_collision_solver_2d.h"
  32. #include "godot_physics_server_2d.h"
  33. #include "core/os/os.h"
  34. #include "core/templates/pair.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(GodotCollisionObject2D *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() == GodotCollisionObject2D::TYPE_AREA && !p_collide_with_areas) {
  42. return false;
  43. }
  44. if (p_object->get_type() == GodotCollisionObject2D::TYPE_BODY && !p_collide_with_bodies) {
  45. return false;
  46. }
  47. return true;
  48. }
  49. int GodotPhysicsDirectSpaceState2D::intersect_point(const PointParameters &p_parameters, ShapeResult *r_results, int p_result_max) {
  50. if (p_result_max <= 0) {
  51. return 0;
  52. }
  53. Rect2 aabb;
  54. aabb.position = p_parameters.position - 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, GodotSpace2D::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_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas)) {
  60. continue;
  61. }
  62. if (p_parameters.exclude.has(space->intersection_query_results[i]->get_self())) {
  63. continue;
  64. }
  65. const GodotCollisionObject2D *col_obj = space->intersection_query_results[i];
  66. if (p_parameters.pick_point && !col_obj->is_pickable()) {
  67. continue;
  68. }
  69. if (p_parameters.canvas_instance_id.is_valid() && col_obj->get_canvas_instance_id() != p_parameters.canvas_instance_id) {
  70. continue;
  71. }
  72. int shape_idx = space->intersection_query_subindex_results[i];
  73. GodotShape2D *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_parameters.position);
  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.is_valid()) {
  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. cc++;
  88. }
  89. return cc;
  90. }
  91. bool GodotPhysicsDirectSpaceState2D::intersect_ray(const RayParameters &p_parameters, RayResult &r_result) {
  92. ERR_FAIL_COND_V(space->locked, false);
  93. Vector2 begin, end;
  94. Vector2 normal;
  95. begin = p_parameters.from;
  96. end = p_parameters.to;
  97. normal = (end - begin).normalized();
  98. int amount = space->broadphase->cull_segment(begin, end, space->intersection_query_results, GodotSpace2D::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  99. //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
  100. bool collided = false;
  101. Vector2 res_point, res_normal;
  102. int res_shape;
  103. const GodotCollisionObject2D *res_obj;
  104. real_t min_d = 1e10;
  105. for (int i = 0; i < amount; i++) {
  106. if (!_can_collide_with(space->intersection_query_results[i], p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas)) {
  107. continue;
  108. }
  109. if (p_parameters.exclude.has(space->intersection_query_results[i]->get_self())) {
  110. continue;
  111. }
  112. const GodotCollisionObject2D *col_obj = space->intersection_query_results[i];
  113. int shape_idx = space->intersection_query_subindex_results[i];
  114. Transform2D inv_xform = col_obj->get_shape_inv_transform(shape_idx) * col_obj->get_inv_transform();
  115. Vector2 local_from = inv_xform.xform(begin);
  116. Vector2 local_to = inv_xform.xform(end);
  117. const GodotShape2D *shape = col_obj->get_shape(shape_idx);
  118. Vector2 shape_point, shape_normal;
  119. if (shape->contains_point(local_from)) {
  120. if (p_parameters.hit_from_inside) {
  121. // Hit shape at starting point.
  122. min_d = 0;
  123. res_point = begin;
  124. res_normal = Vector2();
  125. res_shape = shape_idx;
  126. res_obj = col_obj;
  127. collided = true;
  128. break;
  129. } else {
  130. // Ignore shape when starting inside.
  131. continue;
  132. }
  133. }
  134. if (shape->intersect_segment(local_from, local_to, shape_point, shape_normal)) {
  135. Transform2D xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  136. shape_point = xform.xform(shape_point);
  137. real_t ld = normal.dot(shape_point);
  138. if (ld < min_d) {
  139. min_d = ld;
  140. res_point = shape_point;
  141. res_normal = inv_xform.basis_xform_inv(shape_normal).normalized();
  142. res_shape = shape_idx;
  143. res_obj = col_obj;
  144. collided = true;
  145. }
  146. }
  147. }
  148. if (!collided) {
  149. return false;
  150. }
  151. r_result.collider_id = res_obj->get_instance_id();
  152. if (r_result.collider_id.is_valid()) {
  153. r_result.collider = ObjectDB::get_instance(r_result.collider_id);
  154. }
  155. r_result.normal = res_normal;
  156. r_result.position = res_point;
  157. r_result.rid = res_obj->get_self();
  158. r_result.shape = res_shape;
  159. return true;
  160. }
  161. int GodotPhysicsDirectSpaceState2D::intersect_shape(const ShapeParameters &p_parameters, ShapeResult *r_results, int p_result_max) {
  162. if (p_result_max <= 0) {
  163. return 0;
  164. }
  165. GodotShape2D *shape = GodotPhysicsServer2D::godot_singleton->shape_owner.get_or_null(p_parameters.shape_rid);
  166. ERR_FAIL_COND_V(!shape, 0);
  167. Rect2 aabb = p_parameters.transform.xform(shape->get_aabb());
  168. aabb = aabb.merge(Rect2(aabb.position + p_parameters.motion, aabb.size)); //motion
  169. aabb = aabb.grow(p_parameters.margin);
  170. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, GodotSpace2D::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  171. int cc = 0;
  172. for (int i = 0; i < amount; i++) {
  173. if (cc >= p_result_max) {
  174. break;
  175. }
  176. if (!_can_collide_with(space->intersection_query_results[i], p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas)) {
  177. continue;
  178. }
  179. if (p_parameters.exclude.has(space->intersection_query_results[i]->get_self())) {
  180. continue;
  181. }
  182. const GodotCollisionObject2D *col_obj = space->intersection_query_results[i];
  183. int shape_idx = space->intersection_query_subindex_results[i];
  184. if (!GodotCollisionSolver2D::solve(shape, p_parameters.transform, p_parameters.motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), nullptr, nullptr, nullptr, p_parameters.margin)) {
  185. continue;
  186. }
  187. r_results[cc].collider_id = col_obj->get_instance_id();
  188. if (r_results[cc].collider_id.is_valid()) {
  189. r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
  190. }
  191. r_results[cc].rid = col_obj->get_self();
  192. r_results[cc].shape = shape_idx;
  193. cc++;
  194. }
  195. return cc;
  196. }
  197. bool GodotPhysicsDirectSpaceState2D::cast_motion(const ShapeParameters &p_parameters, real_t &p_closest_safe, real_t &p_closest_unsafe) {
  198. GodotShape2D *shape = GodotPhysicsServer2D::godot_singleton->shape_owner.get_or_null(p_parameters.shape_rid);
  199. ERR_FAIL_COND_V(!shape, false);
  200. Rect2 aabb = p_parameters.transform.xform(shape->get_aabb());
  201. aabb = aabb.merge(Rect2(aabb.position + p_parameters.motion, aabb.size)); //motion
  202. aabb = aabb.grow(p_parameters.margin);
  203. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, GodotSpace2D::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  204. real_t best_safe = 1;
  205. real_t best_unsafe = 1;
  206. for (int i = 0; i < amount; i++) {
  207. if (!_can_collide_with(space->intersection_query_results[i], p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas)) {
  208. continue;
  209. }
  210. if (p_parameters.exclude.has(space->intersection_query_results[i]->get_self())) {
  211. continue; //ignore excluded
  212. }
  213. const GodotCollisionObject2D *col_obj = space->intersection_query_results[i];
  214. int shape_idx = space->intersection_query_subindex_results[i];
  215. Transform2D col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  216. //test initial overlap, does it collide if going all the way?
  217. if (!GodotCollisionSolver2D::solve(shape, p_parameters.transform, p_parameters.motion, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), nullptr, nullptr, nullptr, p_parameters.margin)) {
  218. continue;
  219. }
  220. //test initial overlap, ignore objects it's inside of.
  221. if (GodotCollisionSolver2D::solve(shape, p_parameters.transform, Vector2(), col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), nullptr, nullptr, nullptr, p_parameters.margin)) {
  222. continue;
  223. }
  224. Vector2 mnormal = p_parameters.motion.normalized();
  225. //just do kinematic solving
  226. real_t low = 0.0;
  227. real_t hi = 1.0;
  228. real_t fraction_coeff = 0.5;
  229. for (int j = 0; j < 8; j++) { //steps should be customizable..
  230. real_t fraction = low + (hi - low) * fraction_coeff;
  231. Vector2 sep = mnormal; //important optimization for this to work fast enough
  232. bool collided = GodotCollisionSolver2D::solve(shape, p_parameters.transform, p_parameters.motion * fraction, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), nullptr, nullptr, &sep, p_parameters.margin);
  233. if (collided) {
  234. hi = fraction;
  235. if ((j == 0) || (low > 0.0)) { // Did it not collide before?
  236. // When alternating or first iteration, use dichotomy.
  237. fraction_coeff = 0.5;
  238. } else {
  239. // When colliding again, converge faster towards low fraction
  240. // for more accurate results with long motions that collide near the start.
  241. fraction_coeff = 0.25;
  242. }
  243. } else {
  244. low = fraction;
  245. if ((j == 0) || (hi < 1.0)) { // Did it collide before?
  246. // When alternating or first iteration, use dichotomy.
  247. fraction_coeff = 0.5;
  248. } else {
  249. // When not colliding again, converge faster towards high fraction
  250. // for more accurate results with long motions that collide near the end.
  251. fraction_coeff = 0.75;
  252. }
  253. }
  254. }
  255. if (low < best_safe) {
  256. best_safe = low;
  257. best_unsafe = hi;
  258. }
  259. }
  260. p_closest_safe = best_safe;
  261. p_closest_unsafe = best_unsafe;
  262. return true;
  263. }
  264. bool GodotPhysicsDirectSpaceState2D::collide_shape(const ShapeParameters &p_parameters, Vector2 *r_results, int p_result_max, int &r_result_count) {
  265. if (p_result_max <= 0) {
  266. return false;
  267. }
  268. GodotShape2D *shape = GodotPhysicsServer2D::godot_singleton->shape_owner.get_or_null(p_parameters.shape_rid);
  269. ERR_FAIL_COND_V(!shape, 0);
  270. Rect2 aabb = p_parameters.transform.xform(shape->get_aabb());
  271. aabb = aabb.merge(Rect2(aabb.position + p_parameters.motion, aabb.size)); //motion
  272. aabb = aabb.grow(p_parameters.margin);
  273. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, GodotSpace2D::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  274. bool collided = false;
  275. r_result_count = 0;
  276. GodotPhysicsServer2D::CollCbkData cbk;
  277. cbk.max = p_result_max;
  278. cbk.amount = 0;
  279. cbk.passed = 0;
  280. cbk.ptr = r_results;
  281. GodotCollisionSolver2D::CallbackResult cbkres = GodotPhysicsServer2D::_shape_col_cbk;
  282. GodotPhysicsServer2D::CollCbkData *cbkptr = &cbk;
  283. for (int i = 0; i < amount; i++) {
  284. if (!_can_collide_with(space->intersection_query_results[i], p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas)) {
  285. continue;
  286. }
  287. const GodotCollisionObject2D *col_obj = space->intersection_query_results[i];
  288. if (p_parameters.exclude.has(col_obj->get_self())) {
  289. continue;
  290. }
  291. int shape_idx = space->intersection_query_subindex_results[i];
  292. cbk.valid_dir = Vector2();
  293. cbk.valid_depth = 0;
  294. if (GodotCollisionSolver2D::solve(shape, p_parameters.transform, p_parameters.motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), cbkres, cbkptr, nullptr, p_parameters.margin)) {
  295. collided = cbk.amount > 0;
  296. }
  297. }
  298. r_result_count = cbk.amount;
  299. return collided;
  300. }
  301. struct _RestCallbackData2D {
  302. const GodotCollisionObject2D *object = nullptr;
  303. const GodotCollisionObject2D *best_object = nullptr;
  304. int local_shape = 0;
  305. int best_local_shape = 0;
  306. int shape = 0;
  307. int best_shape = 0;
  308. Vector2 best_contact;
  309. Vector2 best_normal;
  310. real_t best_len = 0.0;
  311. Vector2 valid_dir;
  312. real_t valid_depth = 0.0;
  313. real_t min_allowed_depth = 0.0;
  314. };
  315. static void _rest_cbk_result(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata) {
  316. _RestCallbackData2D *rd = static_cast<_RestCallbackData2D *>(p_userdata);
  317. Vector2 contact_rel = p_point_B - p_point_A;
  318. real_t len = contact_rel.length();
  319. if (len < rd->min_allowed_depth) {
  320. return;
  321. }
  322. if (len <= rd->best_len) {
  323. return;
  324. }
  325. Vector2 normal = contact_rel / len;
  326. if (rd->valid_dir != Vector2()) {
  327. if (len > rd->valid_depth) {
  328. return;
  329. }
  330. if (rd->valid_dir.dot(normal) > -CMP_EPSILON) {
  331. return;
  332. }
  333. }
  334. rd->best_len = len;
  335. rd->best_contact = p_point_B;
  336. rd->best_normal = normal;
  337. rd->best_object = rd->object;
  338. rd->best_shape = rd->shape;
  339. rd->best_local_shape = rd->local_shape;
  340. }
  341. bool GodotPhysicsDirectSpaceState2D::rest_info(const ShapeParameters &p_parameters, ShapeRestInfo *r_info) {
  342. GodotShape2D *shape = GodotPhysicsServer2D::godot_singleton->shape_owner.get_or_null(p_parameters.shape_rid);
  343. ERR_FAIL_COND_V(!shape, 0);
  344. real_t margin = MAX(p_parameters.margin, TEST_MOTION_MARGIN_MIN_VALUE);
  345. Rect2 aabb = p_parameters.transform.xform(shape->get_aabb());
  346. aabb = aabb.merge(Rect2(aabb.position + p_parameters.motion, aabb.size)); //motion
  347. aabb = aabb.grow(margin);
  348. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, GodotSpace2D::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  349. _RestCallbackData2D rcd;
  350. // Allowed depth can't be lower than motion length, in order to handle contacts at low speed.
  351. real_t motion_length = p_parameters.motion.length();
  352. real_t min_contact_depth = margin * TEST_MOTION_MIN_CONTACT_DEPTH_FACTOR;
  353. rcd.min_allowed_depth = MIN(motion_length, min_contact_depth);
  354. for (int i = 0; i < amount; i++) {
  355. if (!_can_collide_with(space->intersection_query_results[i], p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas)) {
  356. continue;
  357. }
  358. const GodotCollisionObject2D *col_obj = space->intersection_query_results[i];
  359. if (p_parameters.exclude.has(col_obj->get_self())) {
  360. continue;
  361. }
  362. int shape_idx = space->intersection_query_subindex_results[i];
  363. rcd.valid_dir = Vector2();
  364. rcd.object = col_obj;
  365. rcd.shape = shape_idx;
  366. rcd.local_shape = 0;
  367. bool sc = GodotCollisionSolver2D::solve(shape, p_parameters.transform, p_parameters.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);
  368. if (!sc) {
  369. continue;
  370. }
  371. }
  372. if (rcd.best_len == 0 || !rcd.best_object) {
  373. return false;
  374. }
  375. r_info->collider_id = rcd.best_object->get_instance_id();
  376. r_info->shape = rcd.best_shape;
  377. r_info->normal = rcd.best_normal;
  378. r_info->point = rcd.best_contact;
  379. r_info->rid = rcd.best_object->get_self();
  380. if (rcd.best_object->get_type() == GodotCollisionObject2D::TYPE_BODY) {
  381. const GodotBody2D *body = static_cast<const GodotBody2D *>(rcd.best_object);
  382. Vector2 rel_vec = r_info->point - (body->get_transform().get_origin() + body->get_center_of_mass());
  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. ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  390. int GodotSpace2D::_cull_aabb_for_body(GodotBody2D *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() == GodotCollisionObject2D::TYPE_AREA) {
  397. keep = false;
  398. } else if (!p_body->collides_with(static_cast<GodotBody2D *>(intersection_query_results[i]))) {
  399. keep = false;
  400. } else if (static_cast<GodotBody2D *>(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. bool GodotSpace2D::test_body_motion(GodotBody2D *p_body, const PhysicsServer2D::MotionParameters &p_parameters, PhysicsServer2D::MotionResult *r_result) {
  415. //give me back regular physics engine logic
  416. //this is madness
  417. //and most people using this function will think
  418. //what it does is simpler than using physics
  419. //this took about a week to get right..
  420. //but is it right? who knows at this point..
  421. if (r_result) {
  422. r_result->collider_id = ObjectID();
  423. r_result->collider_shape = 0;
  424. }
  425. Rect2 body_aabb;
  426. bool shapes_found = false;
  427. for (int i = 0; i < p_body->get_shape_count(); i++) {
  428. if (p_body->is_shape_disabled(i)) {
  429. continue;
  430. }
  431. if (!shapes_found) {
  432. body_aabb = p_body->get_shape_aabb(i);
  433. shapes_found = true;
  434. } else {
  435. body_aabb = body_aabb.merge(p_body->get_shape_aabb(i));
  436. }
  437. }
  438. if (!shapes_found) {
  439. if (r_result) {
  440. *r_result = PhysicsServer2D::MotionResult();
  441. r_result->travel = p_parameters.motion;
  442. }
  443. return false;
  444. }
  445. real_t margin = MAX(p_parameters.margin, TEST_MOTION_MARGIN_MIN_VALUE);
  446. // Undo the currently transform the physics server is aware of and apply the provided one
  447. body_aabb = p_parameters.from.xform(p_body->get_inv_transform().xform(body_aabb));
  448. body_aabb = body_aabb.grow(margin);
  449. static const int max_excluded_shape_pairs = 32;
  450. ExcludedShapeSW excluded_shape_pairs[max_excluded_shape_pairs];
  451. int excluded_shape_pair_count = 0;
  452. real_t min_contact_depth = margin * TEST_MOTION_MIN_CONTACT_DEPTH_FACTOR;
  453. real_t motion_length = p_parameters.motion.length();
  454. Vector2 motion_normal = p_parameters.motion / motion_length;
  455. Transform2D body_transform = p_parameters.from;
  456. bool recovered = false;
  457. {
  458. //STEP 1, FREE BODY IF STUCK
  459. const int max_results = 32;
  460. int recover_attempts = 4;
  461. Vector2 sr[max_results * 2];
  462. real_t priorities[max_results];
  463. do {
  464. GodotPhysicsServer2D::CollCbkData cbk;
  465. cbk.max = max_results;
  466. cbk.amount = 0;
  467. cbk.passed = 0;
  468. cbk.ptr = sr;
  469. cbk.invalid_by_dir = 0;
  470. excluded_shape_pair_count = 0; //last step is the one valid
  471. GodotPhysicsServer2D::CollCbkData *cbkptr = &cbk;
  472. GodotCollisionSolver2D::CallbackResult cbkres = GodotPhysicsServer2D::_shape_col_cbk;
  473. int priority_amount = 0;
  474. bool collided = false;
  475. int amount = _cull_aabb_for_body(p_body, body_aabb);
  476. for (int j = 0; j < p_body->get_shape_count(); j++) {
  477. if (p_body->is_shape_disabled(j)) {
  478. continue;
  479. }
  480. GodotShape2D *body_shape = p_body->get_shape(j);
  481. Transform2D body_shape_xform = body_transform * p_body->get_shape_transform(j);
  482. for (int i = 0; i < amount; i++) {
  483. const GodotCollisionObject2D *col_obj = intersection_query_results[i];
  484. if (p_parameters.exclude_bodies.has(col_obj->get_self())) {
  485. continue;
  486. }
  487. if (p_parameters.exclude_objects.has(col_obj->get_instance_id())) {
  488. continue;
  489. }
  490. int shape_idx = intersection_query_subindex_results[i];
  491. Transform2D col_obj_shape_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  492. if (body_shape->allows_one_way_collision() && col_obj->is_shape_set_as_one_way_collision(shape_idx)) {
  493. cbk.valid_dir = col_obj_shape_xform.columns[1].normalized();
  494. real_t owc_margin = col_obj->get_shape_one_way_collision_margin(shape_idx);
  495. cbk.valid_depth = MAX(owc_margin, margin); //user specified, but never less than actual margin or it won't work
  496. cbk.invalid_by_dir = 0;
  497. if (col_obj->get_type() == GodotCollisionObject2D::TYPE_BODY) {
  498. const GodotBody2D *b = static_cast<const GodotBody2D *>(col_obj);
  499. if (b->get_mode() == PhysicsServer2D::BODY_MODE_KINEMATIC || b->get_mode() == PhysicsServer2D::BODY_MODE_RIGID) {
  500. //fix for moving platforms (kinematic and dynamic), margin is increased by how much it moved in the given direction
  501. Vector2 lv = b->get_linear_velocity();
  502. //compute displacement from linear velocity
  503. Vector2 motion = lv * last_step;
  504. real_t motion_len = motion.length();
  505. motion.normalize();
  506. cbk.valid_depth += motion_len * MAX(motion.dot(-cbk.valid_dir), 0.0);
  507. }
  508. }
  509. } else {
  510. cbk.valid_dir = Vector2();
  511. cbk.valid_depth = 0;
  512. cbk.invalid_by_dir = 0;
  513. }
  514. int current_passed = cbk.passed; //save how many points passed collision
  515. bool did_collide = false;
  516. GodotShape2D *against_shape = col_obj->get_shape(shape_idx);
  517. if (GodotCollisionSolver2D::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), cbkres, cbkptr, nullptr, margin)) {
  518. did_collide = cbk.passed > current_passed; //more passed, so collision actually existed
  519. }
  520. while (cbk.amount > priority_amount) {
  521. priorities[priority_amount] = col_obj->get_collision_priority();
  522. priority_amount++;
  523. }
  524. if (!did_collide && cbk.invalid_by_dir > 0) {
  525. //this shape must be excluded
  526. if (excluded_shape_pair_count < max_excluded_shape_pairs) {
  527. ExcludedShapeSW esp;
  528. esp.local_shape = body_shape;
  529. esp.against_object = col_obj;
  530. esp.against_shape_index = shape_idx;
  531. excluded_shape_pairs[excluded_shape_pair_count++] = esp;
  532. }
  533. }
  534. if (did_collide) {
  535. collided = true;
  536. }
  537. }
  538. }
  539. if (!collided) {
  540. break;
  541. }
  542. real_t inv_total_weight = 0.0;
  543. for (int i = 0; i < cbk.amount; i++) {
  544. inv_total_weight += priorities[i];
  545. }
  546. inv_total_weight = Math::is_zero_approx(inv_total_weight) ? 1.0 : (real_t)cbk.amount / inv_total_weight;
  547. recovered = true;
  548. Vector2 recover_motion;
  549. for (int i = 0; i < cbk.amount; i++) {
  550. Vector2 a = sr[i * 2 + 0];
  551. Vector2 b = sr[i * 2 + 1];
  552. // Compute plane on b towards a.
  553. Vector2 n = (a - b).normalized();
  554. real_t d = n.dot(b);
  555. // Compute depth on recovered motion.
  556. real_t depth = n.dot(a + recover_motion) - d;
  557. if (depth > min_contact_depth + CMP_EPSILON) {
  558. // Only recover if there is penetration.
  559. recover_motion -= n * (depth - min_contact_depth) * 0.4 * priorities[i] * inv_total_weight;
  560. }
  561. }
  562. if (recover_motion == Vector2()) {
  563. collided = false;
  564. break;
  565. }
  566. body_transform.columns[2] += recover_motion;
  567. body_aabb.position += recover_motion;
  568. recover_attempts--;
  569. } while (recover_attempts);
  570. }
  571. real_t safe = 1.0;
  572. real_t unsafe = 1.0;
  573. int best_shape = -1;
  574. {
  575. // STEP 2 ATTEMPT MOTION
  576. Rect2 motion_aabb = body_aabb;
  577. motion_aabb.position += p_parameters.motion;
  578. motion_aabb = motion_aabb.merge(body_aabb);
  579. int amount = _cull_aabb_for_body(p_body, motion_aabb);
  580. for (int body_shape_idx = 0; body_shape_idx < p_body->get_shape_count(); body_shape_idx++) {
  581. if (p_body->is_shape_disabled(body_shape_idx)) {
  582. continue;
  583. }
  584. GodotShape2D *body_shape = p_body->get_shape(body_shape_idx);
  585. // Colliding separation rays allows to properly snap to the ground,
  586. // otherwise it's not needed in regular motion.
  587. if (!p_parameters.collide_separation_ray && (body_shape->get_type() == PhysicsServer2D::SHAPE_SEPARATION_RAY)) {
  588. // When slide on slope is on, separation ray shape acts like a regular shape.
  589. if (!static_cast<GodotSeparationRayShape2D *>(body_shape)->get_slide_on_slope()) {
  590. continue;
  591. }
  592. }
  593. Transform2D body_shape_xform = body_transform * p_body->get_shape_transform(body_shape_idx);
  594. bool stuck = false;
  595. real_t best_safe = 1;
  596. real_t best_unsafe = 1;
  597. for (int i = 0; i < amount; i++) {
  598. const GodotCollisionObject2D *col_obj = intersection_query_results[i];
  599. if (p_parameters.exclude_bodies.has(col_obj->get_self())) {
  600. continue;
  601. }
  602. if (p_parameters.exclude_objects.has(col_obj->get_instance_id())) {
  603. continue;
  604. }
  605. int col_shape_idx = intersection_query_subindex_results[i];
  606. GodotShape2D *against_shape = col_obj->get_shape(col_shape_idx);
  607. bool excluded = false;
  608. for (int k = 0; k < excluded_shape_pair_count; k++) {
  609. 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) {
  610. excluded = true;
  611. break;
  612. }
  613. }
  614. if (excluded) {
  615. continue;
  616. }
  617. Transform2D col_obj_shape_xform = col_obj->get_transform() * col_obj->get_shape_transform(col_shape_idx);
  618. //test initial overlap, does it collide if going all the way?
  619. if (!GodotCollisionSolver2D::solve(body_shape, body_shape_xform, p_parameters.motion, against_shape, col_obj_shape_xform, Vector2(), nullptr, nullptr, nullptr, 0)) {
  620. continue;
  621. }
  622. //test initial overlap
  623. if (GodotCollisionSolver2D::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), nullptr, nullptr, nullptr, 0)) {
  624. if (body_shape->allows_one_way_collision() && col_obj->is_shape_set_as_one_way_collision(col_shape_idx)) {
  625. Vector2 direction = col_obj_shape_xform.columns[1].normalized();
  626. if (motion_normal.dot(direction) < 0) {
  627. continue;
  628. }
  629. }
  630. stuck = true;
  631. break;
  632. }
  633. //just do kinematic solving
  634. real_t low = 0.0;
  635. real_t hi = 1.0;
  636. real_t fraction_coeff = 0.5;
  637. for (int k = 0; k < 8; k++) { //steps should be customizable..
  638. real_t fraction = low + (hi - low) * fraction_coeff;
  639. Vector2 sep = motion_normal; //important optimization for this to work fast enough
  640. bool collided = GodotCollisionSolver2D::solve(body_shape, body_shape_xform, p_parameters.motion * fraction, against_shape, col_obj_shape_xform, Vector2(), nullptr, nullptr, &sep, 0);
  641. if (collided) {
  642. hi = fraction;
  643. if ((k == 0) || (low > 0.0)) { // Did it not collide before?
  644. // When alternating or first iteration, use dichotomy.
  645. fraction_coeff = 0.5;
  646. } else {
  647. // When colliding again, converge faster towards low fraction
  648. // for more accurate results with long motions that collide near the start.
  649. fraction_coeff = 0.25;
  650. }
  651. } else {
  652. low = fraction;
  653. if ((k == 0) || (hi < 1.0)) { // Did it collide before?
  654. // When alternating or first iteration, use dichotomy.
  655. fraction_coeff = 0.5;
  656. } else {
  657. // When not colliding again, converge faster towards high fraction
  658. // for more accurate results with long motions that collide near the end.
  659. fraction_coeff = 0.75;
  660. }
  661. }
  662. }
  663. if (body_shape->allows_one_way_collision() && col_obj->is_shape_set_as_one_way_collision(col_shape_idx)) {
  664. Vector2 cd[2];
  665. GodotPhysicsServer2D::CollCbkData cbk;
  666. cbk.max = 1;
  667. cbk.amount = 0;
  668. cbk.passed = 0;
  669. cbk.ptr = cd;
  670. cbk.valid_dir = col_obj_shape_xform.columns[1].normalized();
  671. cbk.valid_depth = 10e20;
  672. Vector2 sep = motion_normal; //important optimization for this to work fast enough
  673. bool collided = GodotCollisionSolver2D::solve(body_shape, body_shape_xform, p_parameters.motion * (hi + contact_max_allowed_penetration), col_obj->get_shape(col_shape_idx), col_obj_shape_xform, Vector2(), GodotPhysicsServer2D::_shape_col_cbk, &cbk, &sep, 0);
  674. if (!collided || cbk.amount == 0) {
  675. continue;
  676. }
  677. }
  678. if (low < best_safe) {
  679. best_safe = low;
  680. best_unsafe = hi;
  681. }
  682. }
  683. if (stuck) {
  684. safe = 0;
  685. unsafe = 0;
  686. best_shape = body_shape_idx; //sadly it's the best
  687. break;
  688. }
  689. if (best_safe == 1.0) {
  690. continue;
  691. }
  692. if (best_safe < safe) {
  693. safe = best_safe;
  694. unsafe = best_unsafe;
  695. best_shape = body_shape_idx;
  696. }
  697. }
  698. }
  699. bool collided = false;
  700. if ((p_parameters.recovery_as_collision && recovered) || (safe < 1)) {
  701. if (safe >= 1) {
  702. best_shape = -1; //no best shape with cast, reset to -1
  703. }
  704. //it collided, let's get the rest info in unsafe advance
  705. Transform2D ugt = body_transform;
  706. ugt.columns[2] += p_parameters.motion * unsafe;
  707. _RestCallbackData2D rcd;
  708. // Allowed depth can't be lower than motion length, in order to handle contacts at low speed.
  709. rcd.min_allowed_depth = MIN(motion_length, min_contact_depth);
  710. body_aabb.position += p_parameters.motion * unsafe;
  711. int amount = _cull_aabb_for_body(p_body, body_aabb);
  712. int from_shape = best_shape != -1 ? best_shape : 0;
  713. int to_shape = best_shape != -1 ? best_shape + 1 : p_body->get_shape_count();
  714. for (int j = from_shape; j < to_shape; j++) {
  715. if (p_body->is_shape_disabled(j)) {
  716. continue;
  717. }
  718. Transform2D body_shape_xform = ugt * p_body->get_shape_transform(j);
  719. GodotShape2D *body_shape = p_body->get_shape(j);
  720. for (int i = 0; i < amount; i++) {
  721. const GodotCollisionObject2D *col_obj = intersection_query_results[i];
  722. if (p_parameters.exclude_bodies.has(col_obj->get_self())) {
  723. continue;
  724. }
  725. if (p_parameters.exclude_objects.has(col_obj->get_instance_id())) {
  726. continue;
  727. }
  728. int shape_idx = intersection_query_subindex_results[i];
  729. GodotShape2D *against_shape = col_obj->get_shape(shape_idx);
  730. bool excluded = false;
  731. for (int k = 0; k < excluded_shape_pair_count; k++) {
  732. 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) {
  733. excluded = true;
  734. break;
  735. }
  736. }
  737. if (excluded) {
  738. continue;
  739. }
  740. Transform2D col_obj_shape_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  741. if (body_shape->allows_one_way_collision() && col_obj->is_shape_set_as_one_way_collision(shape_idx)) {
  742. rcd.valid_dir = col_obj_shape_xform.columns[1].normalized();
  743. real_t owc_margin = col_obj->get_shape_one_way_collision_margin(shape_idx);
  744. rcd.valid_depth = MAX(owc_margin, margin); //user specified, but never less than actual margin or it won't work
  745. if (col_obj->get_type() == GodotCollisionObject2D::TYPE_BODY) {
  746. const GodotBody2D *b = static_cast<const GodotBody2D *>(col_obj);
  747. if (b->get_mode() == PhysicsServer2D::BODY_MODE_KINEMATIC || b->get_mode() == PhysicsServer2D::BODY_MODE_RIGID) {
  748. //fix for moving platforms (kinematic and dynamic), margin is increased by how much it moved in the given direction
  749. Vector2 lv = b->get_linear_velocity();
  750. //compute displacement from linear velocity
  751. Vector2 motion = lv * last_step;
  752. real_t motion_len = motion.length();
  753. motion.normalize();
  754. rcd.valid_depth += motion_len * MAX(motion.dot(-rcd.valid_dir), 0.0);
  755. }
  756. }
  757. } else {
  758. rcd.valid_dir = Vector2();
  759. rcd.valid_depth = 0;
  760. }
  761. rcd.object = col_obj;
  762. rcd.shape = shape_idx;
  763. rcd.local_shape = j;
  764. bool sc = GodotCollisionSolver2D::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), _rest_cbk_result, &rcd, nullptr, margin);
  765. if (!sc) {
  766. continue;
  767. }
  768. }
  769. }
  770. if (rcd.best_len != 0) {
  771. if (r_result) {
  772. r_result->collider = rcd.best_object->get_self();
  773. r_result->collider_id = rcd.best_object->get_instance_id();
  774. r_result->collider_shape = rcd.best_shape;
  775. r_result->collision_local_shape = rcd.best_local_shape;
  776. r_result->collision_normal = rcd.best_normal;
  777. r_result->collision_point = rcd.best_contact;
  778. r_result->collision_depth = rcd.best_len;
  779. r_result->collision_safe_fraction = safe;
  780. r_result->collision_unsafe_fraction = unsafe;
  781. const GodotBody2D *body = static_cast<const GodotBody2D *>(rcd.best_object);
  782. Vector2 rel_vec = r_result->collision_point - (body->get_transform().get_origin() + body->get_center_of_mass());
  783. r_result->collider_velocity = Vector2(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity();
  784. r_result->travel = safe * p_parameters.motion;
  785. r_result->remainder = p_parameters.motion - safe * p_parameters.motion;
  786. r_result->travel += (body_transform.get_origin() - p_parameters.from.get_origin());
  787. }
  788. collided = true;
  789. }
  790. }
  791. if (!collided && r_result) {
  792. r_result->travel = p_parameters.motion;
  793. r_result->remainder = Vector2();
  794. r_result->travel += (body_transform.get_origin() - p_parameters.from.get_origin());
  795. }
  796. return collided;
  797. }
  798. // Assumes a valid collision pair, this should have been checked beforehand in the BVH or octree.
  799. void *GodotSpace2D::_broadphase_pair(GodotCollisionObject2D *A, int p_subindex_A, GodotCollisionObject2D *B, int p_subindex_B, void *p_self) {
  800. GodotCollisionObject2D::Type type_A = A->get_type();
  801. GodotCollisionObject2D::Type type_B = B->get_type();
  802. if (type_A > type_B) {
  803. SWAP(A, B);
  804. SWAP(p_subindex_A, p_subindex_B);
  805. SWAP(type_A, type_B);
  806. }
  807. GodotSpace2D *self = static_cast<GodotSpace2D *>(p_self);
  808. self->collision_pairs++;
  809. if (type_A == GodotCollisionObject2D::TYPE_AREA) {
  810. GodotArea2D *area = static_cast<GodotArea2D *>(A);
  811. if (type_B == GodotCollisionObject2D::TYPE_AREA) {
  812. GodotArea2D *area_b = static_cast<GodotArea2D *>(B);
  813. GodotArea2Pair2D *area2_pair = memnew(GodotArea2Pair2D(area_b, p_subindex_B, area, p_subindex_A));
  814. return area2_pair;
  815. } else {
  816. GodotBody2D *body = static_cast<GodotBody2D *>(B);
  817. GodotAreaPair2D *area_pair = memnew(GodotAreaPair2D(body, p_subindex_B, area, p_subindex_A));
  818. return area_pair;
  819. }
  820. } else {
  821. GodotBodyPair2D *b = memnew(GodotBodyPair2D(static_cast<GodotBody2D *>(A), p_subindex_A, static_cast<GodotBody2D *>(B), p_subindex_B));
  822. return b;
  823. }
  824. return nullptr;
  825. }
  826. void GodotSpace2D::_broadphase_unpair(GodotCollisionObject2D *A, int p_subindex_A, GodotCollisionObject2D *B, int p_subindex_B, void *p_data, void *p_self) {
  827. if (!p_data) {
  828. return;
  829. }
  830. GodotSpace2D *self = static_cast<GodotSpace2D *>(p_self);
  831. self->collision_pairs--;
  832. GodotConstraint2D *c = static_cast<GodotConstraint2D *>(p_data);
  833. memdelete(c);
  834. }
  835. const SelfList<GodotBody2D>::List &GodotSpace2D::get_active_body_list() const {
  836. return active_list;
  837. }
  838. void GodotSpace2D::body_add_to_active_list(SelfList<GodotBody2D> *p_body) {
  839. active_list.add(p_body);
  840. }
  841. void GodotSpace2D::body_remove_from_active_list(SelfList<GodotBody2D> *p_body) {
  842. active_list.remove(p_body);
  843. }
  844. void GodotSpace2D::body_add_to_mass_properties_update_list(SelfList<GodotBody2D> *p_body) {
  845. mass_properties_update_list.add(p_body);
  846. }
  847. void GodotSpace2D::body_remove_from_mass_properties_update_list(SelfList<GodotBody2D> *p_body) {
  848. mass_properties_update_list.remove(p_body);
  849. }
  850. GodotBroadPhase2D *GodotSpace2D::get_broadphase() {
  851. return broadphase;
  852. }
  853. void GodotSpace2D::add_object(GodotCollisionObject2D *p_object) {
  854. ERR_FAIL_COND(objects.has(p_object));
  855. objects.insert(p_object);
  856. }
  857. void GodotSpace2D::remove_object(GodotCollisionObject2D *p_object) {
  858. ERR_FAIL_COND(!objects.has(p_object));
  859. objects.erase(p_object);
  860. }
  861. const HashSet<GodotCollisionObject2D *> &GodotSpace2D::get_objects() const {
  862. return objects;
  863. }
  864. void GodotSpace2D::body_add_to_state_query_list(SelfList<GodotBody2D> *p_body) {
  865. state_query_list.add(p_body);
  866. }
  867. void GodotSpace2D::body_remove_from_state_query_list(SelfList<GodotBody2D> *p_body) {
  868. state_query_list.remove(p_body);
  869. }
  870. void GodotSpace2D::area_add_to_monitor_query_list(SelfList<GodotArea2D> *p_area) {
  871. monitor_query_list.add(p_area);
  872. }
  873. void GodotSpace2D::area_remove_from_monitor_query_list(SelfList<GodotArea2D> *p_area) {
  874. monitor_query_list.remove(p_area);
  875. }
  876. void GodotSpace2D::area_add_to_moved_list(SelfList<GodotArea2D> *p_area) {
  877. area_moved_list.add(p_area);
  878. }
  879. void GodotSpace2D::area_remove_from_moved_list(SelfList<GodotArea2D> *p_area) {
  880. area_moved_list.remove(p_area);
  881. }
  882. const SelfList<GodotArea2D>::List &GodotSpace2D::get_moved_area_list() const {
  883. return area_moved_list;
  884. }
  885. void GodotSpace2D::call_queries() {
  886. while (state_query_list.first()) {
  887. GodotBody2D *b = state_query_list.first()->self();
  888. state_query_list.remove(state_query_list.first());
  889. b->call_queries();
  890. }
  891. while (monitor_query_list.first()) {
  892. GodotArea2D *a = monitor_query_list.first()->self();
  893. monitor_query_list.remove(monitor_query_list.first());
  894. a->call_queries();
  895. }
  896. }
  897. void GodotSpace2D::setup() {
  898. contact_debug_count = 0;
  899. while (mass_properties_update_list.first()) {
  900. mass_properties_update_list.first()->self()->update_mass_properties();
  901. mass_properties_update_list.remove(mass_properties_update_list.first());
  902. }
  903. }
  904. void GodotSpace2D::update() {
  905. broadphase->update();
  906. }
  907. void GodotSpace2D::set_param(PhysicsServer2D::SpaceParameter p_param, real_t p_value) {
  908. switch (p_param) {
  909. case PhysicsServer2D::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  910. contact_recycle_radius = p_value;
  911. break;
  912. case PhysicsServer2D::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  913. contact_max_separation = p_value;
  914. break;
  915. case PhysicsServer2D::SPACE_PARAM_CONTACT_MAX_ALLOWED_PENETRATION:
  916. contact_max_allowed_penetration = p_value;
  917. break;
  918. case PhysicsServer2D::SPACE_PARAM_CONTACT_DEFAULT_BIAS:
  919. contact_bias = p_value;
  920. break;
  921. case PhysicsServer2D::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  922. body_linear_velocity_sleep_threshold = p_value;
  923. break;
  924. case PhysicsServer2D::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  925. body_angular_velocity_sleep_threshold = p_value;
  926. break;
  927. case PhysicsServer2D::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  928. body_time_to_sleep = p_value;
  929. break;
  930. case PhysicsServer2D::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  931. constraint_bias = p_value;
  932. break;
  933. case PhysicsServer2D::SPACE_PARAM_SOLVER_ITERATIONS:
  934. solver_iterations = p_value;
  935. break;
  936. }
  937. }
  938. real_t GodotSpace2D::get_param(PhysicsServer2D::SpaceParameter p_param) const {
  939. switch (p_param) {
  940. case PhysicsServer2D::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  941. return contact_recycle_radius;
  942. case PhysicsServer2D::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  943. return contact_max_separation;
  944. case PhysicsServer2D::SPACE_PARAM_CONTACT_MAX_ALLOWED_PENETRATION:
  945. return contact_max_allowed_penetration;
  946. case PhysicsServer2D::SPACE_PARAM_CONTACT_DEFAULT_BIAS:
  947. return contact_bias;
  948. case PhysicsServer2D::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  949. return body_linear_velocity_sleep_threshold;
  950. case PhysicsServer2D::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  951. return body_angular_velocity_sleep_threshold;
  952. case PhysicsServer2D::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  953. return body_time_to_sleep;
  954. case PhysicsServer2D::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  955. return constraint_bias;
  956. case PhysicsServer2D::SPACE_PARAM_SOLVER_ITERATIONS:
  957. return solver_iterations;
  958. }
  959. return 0;
  960. }
  961. void GodotSpace2D::lock() {
  962. locked = true;
  963. }
  964. void GodotSpace2D::unlock() {
  965. locked = false;
  966. }
  967. bool GodotSpace2D::is_locked() const {
  968. return locked;
  969. }
  970. GodotPhysicsDirectSpaceState2D *GodotSpace2D::get_direct_state() {
  971. return direct_access;
  972. }
  973. GodotSpace2D::GodotSpace2D() {
  974. body_linear_velocity_sleep_threshold = GLOBAL_DEF("physics/2d/sleep_threshold_linear", 2.0);
  975. body_angular_velocity_sleep_threshold = GLOBAL_DEF("physics/2d/sleep_threshold_angular", Math::deg_to_rad(8.0));
  976. body_time_to_sleep = GLOBAL_DEF("physics/2d/time_before_sleep", 0.5);
  977. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/time_before_sleep", PropertyInfo(Variant::FLOAT, "physics/2d/time_before_sleep", PROPERTY_HINT_RANGE, "0,5,0.01,or_greater"));
  978. solver_iterations = GLOBAL_DEF("physics/2d/solver/solver_iterations", 16);
  979. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/solver/solver_iterations", PropertyInfo(Variant::INT, "physics/2d/solver/solver_iterations", PROPERTY_HINT_RANGE, "1,32,1,or_greater"));
  980. contact_recycle_radius = GLOBAL_DEF("physics/2d/solver/contact_recycle_radius", 1.0);
  981. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/solver/contact_recycle_radius", PropertyInfo(Variant::FLOAT, "physics/2d/solver/contact_max_separation", PROPERTY_HINT_RANGE, "0,10,0.01,or_greater"));
  982. contact_max_separation = GLOBAL_DEF("physics/2d/solver/contact_max_separation", 1.5);
  983. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/solver/contact_max_separation", PropertyInfo(Variant::FLOAT, "physics/2d/solver/contact_max_separation", PROPERTY_HINT_RANGE, "0,10,0.01,or_greater"));
  984. contact_max_allowed_penetration = GLOBAL_DEF("physics/2d/solver/contact_max_allowed_penetration", 0.3);
  985. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/solver/contact_max_allowed_penetration", PropertyInfo(Variant::FLOAT, "physics/2d/solver/contact_max_allowed_penetration", PROPERTY_HINT_RANGE, "0,10,0.01,or_greater"));
  986. contact_bias = GLOBAL_DEF("physics/2d/solver/default_contact_bias", 0.8);
  987. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/solver/default_contact_bias", PropertyInfo(Variant::FLOAT, "physics/2d/solver/default_contact_bias", PROPERTY_HINT_RANGE, "0,1,0.01"));
  988. constraint_bias = GLOBAL_DEF("physics/2d/solver/default_constraint_bias", 0.2);
  989. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/solver/default_constraint_bias", PropertyInfo(Variant::FLOAT, "physics/2d/solver/default_constraint_bias", PROPERTY_HINT_RANGE, "0,1,0.01"));
  990. broadphase = GodotBroadPhase2D::create_func();
  991. broadphase->set_pair_callback(_broadphase_pair, this);
  992. broadphase->set_unpair_callback(_broadphase_unpair, this);
  993. direct_access = memnew(GodotPhysicsDirectSpaceState2D);
  994. direct_access->space = this;
  995. }
  996. GodotSpace2D::~GodotSpace2D() {
  997. memdelete(broadphase);
  998. memdelete(direct_access);
  999. }