space_2d_sw.cpp 44 KB

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