space_sw.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  1. /*************************************************************************/
  2. /* space_sw.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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_sw.h"
  31. #include "collision_solver_sw.h"
  32. #include "physics_server_sw.h"
  33. #include "project_settings.h"
  34. _FORCE_INLINE_ static bool _can_collide_with(CollisionObjectSW *p_object, uint32_t p_collision_mask) {
  35. return p_object->get_collision_layer() & p_collision_mask;
  36. }
  37. int PhysicsDirectSpaceStateSW::intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask) {
  38. ERR_FAIL_COND_V(space->locked, false);
  39. int amount = space->broadphase->cull_point(p_point, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  40. int cc = 0;
  41. //Transform ai = p_xform.affine_inverse();
  42. for (int i = 0; i < amount; i++) {
  43. if (cc >= p_result_max)
  44. break;
  45. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask))
  46. continue;
  47. //area can't be picked by ray (default)
  48. if (p_exclude.has(space->intersection_query_results[i]->get_self()))
  49. continue;
  50. const CollisionObjectSW *col_obj = space->intersection_query_results[i];
  51. int shape_idx = space->intersection_query_subindex_results[i];
  52. Transform inv_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  53. inv_xform.affine_invert();
  54. if (!col_obj->get_shape(shape_idx)->intersect_point(inv_xform.xform(p_point)))
  55. continue;
  56. r_results[cc].collider_id = col_obj->get_instance_id();
  57. if (r_results[cc].collider_id != 0)
  58. r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
  59. else
  60. r_results[cc].collider = NULL;
  61. r_results[cc].rid = col_obj->get_self();
  62. r_results[cc].shape = shape_idx;
  63. cc++;
  64. }
  65. return cc;
  66. }
  67. bool PhysicsDirectSpaceStateSW::intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_pick_ray) {
  68. ERR_FAIL_COND_V(space->locked, false);
  69. Vector3 begin, end;
  70. Vector3 normal;
  71. begin = p_from;
  72. end = p_to;
  73. normal = (end - begin).normalized();
  74. int amount = space->broadphase->cull_segment(begin, end, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  75. //todo, create another array tha references results, compute AABBs and check closest point to ray origin, sort, and stop evaluating results when beyond first collision
  76. bool collided = false;
  77. Vector3 res_point, res_normal;
  78. int res_shape;
  79. const CollisionObjectSW *res_obj;
  80. real_t min_d = 1e10;
  81. for (int i = 0; i < amount; i++) {
  82. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask))
  83. continue;
  84. if (p_pick_ray && !(static_cast<CollisionObjectSW *>(space->intersection_query_results[i])->is_ray_pickable()))
  85. continue;
  86. if (p_exclude.has(space->intersection_query_results[i]->get_self()))
  87. continue;
  88. const CollisionObjectSW *col_obj = space->intersection_query_results[i];
  89. int shape_idx = space->intersection_query_subindex_results[i];
  90. Transform inv_xform = col_obj->get_shape_inv_transform(shape_idx) * col_obj->get_inv_transform();
  91. Vector3 local_from = inv_xform.xform(begin);
  92. Vector3 local_to = inv_xform.xform(end);
  93. const ShapeSW *shape = col_obj->get_shape(shape_idx);
  94. Vector3 shape_point, shape_normal;
  95. if (shape->intersect_segment(local_from, local_to, shape_point, shape_normal)) {
  96. Transform xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  97. shape_point = xform.xform(shape_point);
  98. real_t ld = normal.dot(shape_point);
  99. if (ld < min_d) {
  100. min_d = ld;
  101. res_point = shape_point;
  102. res_normal = inv_xform.basis.xform_inv(shape_normal).normalized();
  103. res_shape = shape_idx;
  104. res_obj = col_obj;
  105. collided = true;
  106. }
  107. }
  108. }
  109. if (!collided)
  110. return false;
  111. r_result.collider_id = res_obj->get_instance_id();
  112. if (r_result.collider_id != 0)
  113. r_result.collider = ObjectDB::get_instance(r_result.collider_id);
  114. else
  115. r_result.collider = NULL;
  116. r_result.normal = res_normal;
  117. r_result.position = res_point;
  118. r_result.rid = res_obj->get_self();
  119. r_result.shape = res_shape;
  120. return true;
  121. }
  122. int PhysicsDirectSpaceStateSW::intersect_shape(const RID &p_shape, const Transform &p_xform, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask) {
  123. if (p_result_max <= 0)
  124. return 0;
  125. ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
  126. ERR_FAIL_COND_V(!shape, 0);
  127. AABB aabb = p_xform.xform(shape->get_aabb());
  128. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  129. int cc = 0;
  130. //Transform ai = p_xform.affine_inverse();
  131. for (int i = 0; i < amount; i++) {
  132. if (cc >= p_result_max)
  133. break;
  134. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask))
  135. continue;
  136. //area can't be picked by ray (default)
  137. if (p_exclude.has(space->intersection_query_results[i]->get_self()))
  138. continue;
  139. const CollisionObjectSW *col_obj = space->intersection_query_results[i];
  140. int shape_idx = space->intersection_query_subindex_results[i];
  141. if (!CollisionSolverSW::solve_static(shape, p_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), NULL, NULL, NULL, p_margin, 0))
  142. continue;
  143. if (r_results) {
  144. r_results[cc].collider_id = col_obj->get_instance_id();
  145. if (r_results[cc].collider_id != 0)
  146. r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
  147. else
  148. r_results[cc].collider = NULL;
  149. r_results[cc].rid = col_obj->get_self();
  150. r_results[cc].shape = shape_idx;
  151. }
  152. cc++;
  153. }
  154. return cc;
  155. }
  156. bool PhysicsDirectSpaceStateSW::cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &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, ShapeRestInfo *r_info) {
  157. ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
  158. ERR_FAIL_COND_V(!shape, false);
  159. AABB aabb = p_xform.xform(shape->get_aabb());
  160. aabb = aabb.merge(AABB(aabb.position + p_motion, aabb.size)); //motion
  161. aabb = aabb.grow(p_margin);
  162. /*
  163. if (p_motion!=Vector3())
  164. print_line(p_motion);
  165. */
  166. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  167. real_t best_safe = 1;
  168. real_t best_unsafe = 1;
  169. Transform xform_inv = p_xform.affine_inverse();
  170. MotionShapeSW mshape;
  171. mshape.shape = shape;
  172. mshape.motion = xform_inv.basis.xform(p_motion);
  173. bool best_first = true;
  174. Vector3 closest_A, closest_B;
  175. for (int i = 0; i < amount; i++) {
  176. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask))
  177. continue;
  178. if (p_exclude.has(space->intersection_query_results[i]->get_self()))
  179. continue; //ignore excluded
  180. const CollisionObjectSW *col_obj = space->intersection_query_results[i];
  181. int shape_idx = space->intersection_query_subindex_results[i];
  182. Vector3 point_A, point_B;
  183. Vector3 sep_axis = p_motion.normalized();
  184. Transform col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  185. //test initial overlap, does it collide if going all the way?
  186. if (CollisionSolverSW::solve_distance(&mshape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, aabb, &sep_axis)) {
  187. //print_line("failed motion cast (no collision)");
  188. continue;
  189. }
  190. //test initial overlap
  191. sep_axis = p_motion.normalized();
  192. if (!CollisionSolverSW::solve_distance(shape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, aabb, &sep_axis)) {
  193. //print_line("failed motion cast (no collision)");
  194. return false;
  195. }
  196. //just do kinematic solving
  197. real_t low = 0;
  198. real_t hi = 1;
  199. Vector3 mnormal = p_motion.normalized();
  200. for (int i = 0; i < 8; i++) { //steps should be customizable..
  201. real_t ofs = (low + hi) * 0.5;
  202. Vector3 sep = mnormal; //important optimization for this to work fast enough
  203. mshape.motion = xform_inv.basis.xform(p_motion * ofs);
  204. Vector3 lA, lB;
  205. bool collided = !CollisionSolverSW::solve_distance(&mshape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, lA, lB, aabb, &sep);
  206. if (collided) {
  207. //print_line(itos(i)+": "+rtos(ofs));
  208. hi = ofs;
  209. } else {
  210. point_A = lA;
  211. point_B = lB;
  212. low = ofs;
  213. }
  214. }
  215. if (low < best_safe) {
  216. best_first = true; //force reset
  217. best_safe = low;
  218. best_unsafe = hi;
  219. }
  220. if (r_info && (best_first || (point_A.distance_squared_to(point_B) < closest_A.distance_squared_to(closest_B) && low <= best_safe))) {
  221. closest_A = point_A;
  222. closest_B = point_B;
  223. r_info->collider_id = col_obj->get_instance_id();
  224. r_info->rid = col_obj->get_self();
  225. r_info->shape = shape_idx;
  226. r_info->point = closest_B;
  227. r_info->normal = (closest_A - closest_B).normalized();
  228. best_first = false;
  229. if (col_obj->get_type() == CollisionObjectSW::TYPE_BODY) {
  230. const BodySW *body = static_cast<const BodySW *>(col_obj);
  231. r_info->linear_velocity = body->get_linear_velocity() + (body->get_angular_velocity()).cross(body->get_transform().origin - closest_B);
  232. }
  233. }
  234. }
  235. p_closest_safe = best_safe;
  236. p_closest_unsafe = best_unsafe;
  237. return true;
  238. }
  239. bool PhysicsDirectSpaceStateSW::collide_shape(RID p_shape, const Transform &p_shape_xform, real_t p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_collision_mask) {
  240. if (p_result_max <= 0)
  241. return 0;
  242. ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
  243. ERR_FAIL_COND_V(!shape, 0);
  244. AABB aabb = p_shape_xform.xform(shape->get_aabb());
  245. aabb = aabb.grow(p_margin);
  246. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  247. bool collided = false;
  248. r_result_count = 0;
  249. PhysicsServerSW::CollCbkData cbk;
  250. cbk.max = p_result_max;
  251. cbk.amount = 0;
  252. cbk.ptr = r_results;
  253. CollisionSolverSW::CallbackResult cbkres = NULL;
  254. PhysicsServerSW::CollCbkData *cbkptr = NULL;
  255. if (p_result_max > 0) {
  256. cbkptr = &cbk;
  257. cbkres = PhysicsServerSW::_shape_col_cbk;
  258. }
  259. for (int i = 0; i < amount; i++) {
  260. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask))
  261. continue;
  262. const CollisionObjectSW *col_obj = space->intersection_query_results[i];
  263. int shape_idx = space->intersection_query_subindex_results[i];
  264. if (p_exclude.has(col_obj->get_self())) {
  265. continue;
  266. }
  267. //print_line("AGAINST: "+itos(col_obj->get_self().get_id())+":"+itos(shape_idx));
  268. //print_line("THE ABBB: "+(col_obj->get_transform() * col_obj->get_shape_transform(shape_idx)).xform(col_obj->get_shape(shape_idx)->get_aabb()));
  269. if (CollisionSolverSW::solve_static(shape, p_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), cbkres, cbkptr, NULL, p_margin)) {
  270. collided = true;
  271. }
  272. }
  273. r_result_count = cbk.amount;
  274. return collided;
  275. }
  276. struct _RestCallbackData {
  277. const CollisionObjectSW *object;
  278. const CollisionObjectSW *best_object;
  279. int shape;
  280. int best_shape;
  281. Vector3 best_contact;
  282. Vector3 best_normal;
  283. real_t best_len;
  284. };
  285. static void _rest_cbk_result(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata) {
  286. _RestCallbackData *rd = (_RestCallbackData *)p_userdata;
  287. Vector3 contact_rel = p_point_B - p_point_A;
  288. real_t len = contact_rel.length();
  289. if (len <= rd->best_len)
  290. return;
  291. rd->best_len = len;
  292. rd->best_contact = p_point_B;
  293. rd->best_normal = contact_rel / len;
  294. rd->best_object = rd->object;
  295. rd->best_shape = rd->shape;
  296. }
  297. bool PhysicsDirectSpaceStateSW::rest_info(RID p_shape, const Transform &p_shape_xform, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_collision_mask) {
  298. ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
  299. ERR_FAIL_COND_V(!shape, 0);
  300. AABB aabb = p_shape_xform.xform(shape->get_aabb());
  301. aabb = aabb.grow(p_margin);
  302. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  303. _RestCallbackData rcd;
  304. rcd.best_len = 0;
  305. rcd.best_object = NULL;
  306. rcd.best_shape = 0;
  307. for (int i = 0; i < amount; i++) {
  308. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask))
  309. continue;
  310. const CollisionObjectSW *col_obj = space->intersection_query_results[i];
  311. int shape_idx = space->intersection_query_subindex_results[i];
  312. if (p_exclude.has(col_obj->get_self()))
  313. continue;
  314. rcd.object = col_obj;
  315. rcd.shape = shape_idx;
  316. bool sc = CollisionSolverSW::solve_static(shape, p_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), _rest_cbk_result, &rcd, NULL, p_margin);
  317. if (!sc)
  318. continue;
  319. }
  320. if (rcd.best_len == 0)
  321. return false;
  322. r_info->collider_id = rcd.best_object->get_instance_id();
  323. r_info->shape = rcd.best_shape;
  324. r_info->normal = rcd.best_normal;
  325. r_info->point = rcd.best_contact;
  326. r_info->rid = rcd.best_object->get_self();
  327. if (rcd.best_object->get_type() == CollisionObjectSW::TYPE_BODY) {
  328. const BodySW *body = static_cast<const BodySW *>(rcd.best_object);
  329. r_info->linear_velocity = body->get_linear_velocity() +
  330. (body->get_angular_velocity()).cross(body->get_transform().origin - rcd.best_contact); // * mPos);
  331. } else {
  332. r_info->linear_velocity = Vector3();
  333. }
  334. return true;
  335. }
  336. Vector3 PhysicsDirectSpaceStateSW::get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const {
  337. CollisionObjectSW *obj = PhysicsServerSW::singleton->area_owner.getornull(p_object);
  338. if (!obj) {
  339. obj = PhysicsServerSW::singleton->body_owner.getornull(p_object);
  340. }
  341. ERR_FAIL_COND_V(!obj, Vector3());
  342. ERR_FAIL_COND_V(obj->get_space() != space, Vector3());
  343. float min_distance = 1e20;
  344. Vector3 min_point;
  345. bool shapes_found = false;
  346. for (int i = 0; i < obj->get_shape_count(); i++) {
  347. if (obj->is_shape_set_as_disabled(i))
  348. continue;
  349. Transform shape_xform = obj->get_transform() * obj->get_shape_transform(i);
  350. ShapeSW *shape = obj->get_shape(i);
  351. Vector3 point = shape->get_closest_point_to(shape_xform.affine_inverse().xform(p_point));
  352. point = shape_xform.xform(point);
  353. float dist = point.distance_to(p_point);
  354. if (dist < min_distance) {
  355. min_distance = dist;
  356. min_point = point;
  357. }
  358. shapes_found = true;
  359. }
  360. if (!shapes_found) {
  361. return obj->get_transform().origin; //no shapes found, use distance to origin.
  362. } else {
  363. return min_point;
  364. }
  365. }
  366. PhysicsDirectSpaceStateSW::PhysicsDirectSpaceStateSW() {
  367. space = NULL;
  368. }
  369. ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  370. int SpaceSW::_cull_aabb_for_body(BodySW *p_body, const AABB &p_aabb) {
  371. int amount = broadphase->cull_aabb(p_aabb, intersection_query_results, INTERSECTION_QUERY_MAX, intersection_query_subindex_results);
  372. for (int i = 0; i < amount; i++) {
  373. bool keep = true;
  374. if (intersection_query_results[i] == p_body)
  375. keep = false;
  376. else if (intersection_query_results[i]->get_type() == CollisionObjectSW::TYPE_AREA)
  377. keep = false;
  378. else if ((static_cast<BodySW *>(intersection_query_results[i])->test_collision_mask(p_body)) == 0)
  379. keep = false;
  380. else if (static_cast<BodySW *>(intersection_query_results[i])->has_exception(p_body->get_self()) || p_body->has_exception(intersection_query_results[i]->get_self()))
  381. keep = false;
  382. else if (static_cast<BodySW *>(intersection_query_results[i])->is_shape_set_as_disabled(intersection_query_subindex_results[i]))
  383. keep = false;
  384. if (!keep) {
  385. if (i < amount - 1) {
  386. SWAP(intersection_query_results[i], intersection_query_results[amount - 1]);
  387. SWAP(intersection_query_subindex_results[i], intersection_query_subindex_results[amount - 1]);
  388. }
  389. amount--;
  390. i--;
  391. }
  392. }
  393. return amount;
  394. }
  395. bool SpaceSW::test_body_motion(BodySW *p_body, const Transform &p_from, const Vector3 &p_motion, real_t p_margin, PhysicsServer::MotionResult *r_result) {
  396. //give me back regular physics engine logic
  397. //this is madness
  398. //and most people using this function will think
  399. //what it does is simpler than using physics
  400. //this took about a week to get right..
  401. //but is it right? who knows at this point..
  402. if (r_result) {
  403. r_result->collider_id = 0;
  404. r_result->collider_shape = 0;
  405. }
  406. AABB body_aabb;
  407. for (int i = 0; i < p_body->get_shape_count(); i++) {
  408. if (i == 0)
  409. body_aabb = p_body->get_shape_aabb(i);
  410. else
  411. body_aabb = body_aabb.merge(p_body->get_shape_aabb(i));
  412. }
  413. // Undo the currently transform the physics server is aware of and apply the provided one
  414. body_aabb = p_from.xform(p_body->get_inv_transform().xform(body_aabb));
  415. body_aabb = body_aabb.grow(p_margin);
  416. Transform body_transform = p_from;
  417. {
  418. //STEP 1, FREE BODY IF STUCK
  419. const int max_results = 32;
  420. int recover_attempts = 4;
  421. Vector3 sr[max_results * 2];
  422. do {
  423. PhysicsServerSW::CollCbkData cbk;
  424. cbk.max = max_results;
  425. cbk.amount = 0;
  426. cbk.ptr = sr;
  427. PhysicsServerSW::CollCbkData *cbkptr = &cbk;
  428. CollisionSolverSW::CallbackResult cbkres = PhysicsServerSW::_shape_col_cbk;
  429. bool collided = false;
  430. int amount = _cull_aabb_for_body(p_body, body_aabb);
  431. for (int j = 0; j < p_body->get_shape_count(); j++) {
  432. if (p_body->is_shape_set_as_disabled(j))
  433. continue;
  434. Transform body_shape_xform = body_transform * p_body->get_shape_transform(j);
  435. ShapeSW *body_shape = p_body->get_shape(j);
  436. for (int i = 0; i < amount; i++) {
  437. const CollisionObjectSW *col_obj = intersection_query_results[i];
  438. int shape_idx = intersection_query_subindex_results[i];
  439. if (CollisionSolverSW::solve_static(body_shape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), cbkres, cbkptr, NULL, p_margin)) {
  440. collided = cbk.amount > 0;
  441. }
  442. }
  443. }
  444. if (!collided) {
  445. break;
  446. }
  447. Vector3 recover_motion;
  448. for (int i = 0; i < cbk.amount; i++) {
  449. Vector3 a = sr[i * 2 + 0];
  450. Vector3 b = sr[i * 2 + 1];
  451. recover_motion += (b - a) * 0.4;
  452. }
  453. if (recover_motion == Vector3()) {
  454. collided = false;
  455. break;
  456. }
  457. body_transform.origin += recover_motion;
  458. body_aabb.position += recover_motion;
  459. recover_attempts--;
  460. } while (recover_attempts);
  461. }
  462. real_t safe = 1.0;
  463. real_t unsafe = 1.0;
  464. int best_shape = -1;
  465. {
  466. // STEP 2 ATTEMPT MOTION
  467. AABB motion_aabb = body_aabb;
  468. motion_aabb.position += p_motion;
  469. motion_aabb = motion_aabb.merge(body_aabb);
  470. int amount = _cull_aabb_for_body(p_body, motion_aabb);
  471. for (int j = 0; j < p_body->get_shape_count(); j++) {
  472. if (p_body->is_shape_set_as_disabled(j))
  473. continue;
  474. Transform body_shape_xform = body_transform * p_body->get_shape_transform(j);
  475. ShapeSW *body_shape = p_body->get_shape(j);
  476. Transform body_shape_xform_inv = body_shape_xform.affine_inverse();
  477. MotionShapeSW mshape;
  478. mshape.shape = body_shape;
  479. mshape.motion = body_shape_xform_inv.basis.xform(p_motion);
  480. bool stuck = false;
  481. real_t best_safe = 1;
  482. real_t best_unsafe = 1;
  483. for (int i = 0; i < amount; i++) {
  484. const CollisionObjectSW *col_obj = intersection_query_results[i];
  485. int shape_idx = intersection_query_subindex_results[i];
  486. //test initial overlap, does it collide if going all the way?
  487. Vector3 point_A, point_B;
  488. Vector3 sep_axis = p_motion.normalized();
  489. Transform col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  490. //test initial overlap, does it collide if going all the way?
  491. if (CollisionSolverSW::solve_distance(&mshape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, motion_aabb, &sep_axis)) {
  492. //print_line("failed motion cast (no collision)");
  493. continue;
  494. }
  495. sep_axis = p_motion.normalized();
  496. if (!CollisionSolverSW::solve_distance(body_shape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, motion_aabb, &sep_axis)) {
  497. //print_line("failed motion cast (no collision)");
  498. stuck = true;
  499. break;
  500. }
  501. //just do kinematic solving
  502. real_t low = 0;
  503. real_t hi = 1;
  504. Vector3 mnormal = p_motion.normalized();
  505. for (int i = 0; i < 8; i++) { //steps should be customizable..
  506. real_t ofs = (low + hi) * 0.5;
  507. Vector3 sep = mnormal; //important optimization for this to work fast enough
  508. mshape.motion = body_shape_xform_inv.basis.xform(p_motion * ofs);
  509. Vector3 lA, lB;
  510. bool collided = !CollisionSolverSW::solve_distance(&mshape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj_xform, lA, lB, motion_aabb, &sep);
  511. if (collided) {
  512. //print_line(itos(i)+": "+rtos(ofs));
  513. hi = ofs;
  514. } else {
  515. point_A = lA;
  516. point_B = lB;
  517. low = ofs;
  518. }
  519. }
  520. if (low < best_safe) {
  521. best_safe = low;
  522. best_unsafe = hi;
  523. }
  524. }
  525. if (stuck) {
  526. safe = 0;
  527. unsafe = 0;
  528. best_shape = j; //sadly it's the best
  529. break;
  530. }
  531. if (best_safe == 1.0) {
  532. continue;
  533. }
  534. if (best_safe < safe) {
  535. safe = best_safe;
  536. unsafe = best_unsafe;
  537. best_shape = j;
  538. }
  539. }
  540. }
  541. bool collided = false;
  542. if (safe >= 1) {
  543. //not collided
  544. collided = false;
  545. if (r_result) {
  546. r_result->motion = p_motion;
  547. r_result->remainder = Vector3();
  548. r_result->motion += (body_transform.get_origin() - p_from.get_origin());
  549. }
  550. } else {
  551. //it collided, let's get the rest info in unsafe advance
  552. Transform ugt = body_transform;
  553. ugt.origin += p_motion * unsafe;
  554. _RestCallbackData rcd;
  555. rcd.best_len = 0;
  556. rcd.best_object = NULL;
  557. rcd.best_shape = 0;
  558. Transform body_shape_xform = ugt * p_body->get_shape_transform(best_shape);
  559. ShapeSW *body_shape = p_body->get_shape(best_shape);
  560. body_aabb.position += p_motion * unsafe;
  561. int amount = _cull_aabb_for_body(p_body, body_aabb);
  562. for (int i = 0; i < amount; i++) {
  563. const CollisionObjectSW *col_obj = intersection_query_results[i];
  564. int shape_idx = intersection_query_subindex_results[i];
  565. rcd.object = col_obj;
  566. rcd.shape = shape_idx;
  567. bool sc = CollisionSolverSW::solve_static(body_shape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), _rest_cbk_result, &rcd, NULL, p_margin);
  568. if (!sc)
  569. continue;
  570. }
  571. if (rcd.best_len != 0) {
  572. if (r_result) {
  573. r_result->collider = rcd.best_object->get_self();
  574. r_result->collider_id = rcd.best_object->get_instance_id();
  575. r_result->collider_shape = rcd.best_shape;
  576. r_result->collision_local_shape = best_shape;
  577. r_result->collision_normal = rcd.best_normal;
  578. r_result->collision_point = rcd.best_contact;
  579. //r_result->collider_metadata = rcd.best_object->get_shape_metadata(rcd.best_shape);
  580. const BodySW *body = static_cast<const BodySW *>(rcd.best_object);
  581. //Vector3 rel_vec = r_result->collision_point - body->get_transform().get_origin();
  582. // r_result->collider_velocity = Vector3(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity();
  583. r_result->collider_velocity = body->get_linear_velocity() + (body->get_angular_velocity()).cross(body->get_transform().origin - rcd.best_contact); // * mPos);
  584. r_result->motion = safe * p_motion;
  585. r_result->remainder = p_motion - safe * p_motion;
  586. r_result->motion += (body_transform.get_origin() - p_from.get_origin());
  587. }
  588. collided = true;
  589. } else {
  590. if (r_result) {
  591. r_result->motion = p_motion;
  592. r_result->remainder = Vector3();
  593. r_result->motion += (body_transform.get_origin() - p_from.get_origin());
  594. }
  595. collided = false;
  596. }
  597. }
  598. return collided;
  599. }
  600. void *SpaceSW::_broadphase_pair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_self) {
  601. CollisionObjectSW::Type type_A = A->get_type();
  602. CollisionObjectSW::Type type_B = B->get_type();
  603. if (type_A > type_B) {
  604. SWAP(A, B);
  605. SWAP(p_subindex_A, p_subindex_B);
  606. SWAP(type_A, type_B);
  607. }
  608. SpaceSW *self = (SpaceSW *)p_self;
  609. self->collision_pairs++;
  610. if (type_A == CollisionObjectSW::TYPE_AREA) {
  611. AreaSW *area = static_cast<AreaSW *>(A);
  612. if (type_B == CollisionObjectSW::TYPE_AREA) {
  613. AreaSW *area_b = static_cast<AreaSW *>(B);
  614. Area2PairSW *area2_pair = memnew(Area2PairSW(area_b, p_subindex_B, area, p_subindex_A));
  615. return area2_pair;
  616. } else {
  617. BodySW *body = static_cast<BodySW *>(B);
  618. AreaPairSW *area_pair = memnew(AreaPairSW(body, p_subindex_B, area, p_subindex_A));
  619. return area_pair;
  620. }
  621. } else {
  622. BodyPairSW *b = memnew(BodyPairSW((BodySW *)A, p_subindex_A, (BodySW *)B, p_subindex_B));
  623. return b;
  624. }
  625. return NULL;
  626. }
  627. void SpaceSW::_broadphase_unpair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_data, void *p_self) {
  628. SpaceSW *self = (SpaceSW *)p_self;
  629. self->collision_pairs--;
  630. ConstraintSW *c = (ConstraintSW *)p_data;
  631. memdelete(c);
  632. }
  633. const SelfList<BodySW>::List &SpaceSW::get_active_body_list() const {
  634. return active_list;
  635. }
  636. void SpaceSW::body_add_to_active_list(SelfList<BodySW> *p_body) {
  637. active_list.add(p_body);
  638. }
  639. void SpaceSW::body_remove_from_active_list(SelfList<BodySW> *p_body) {
  640. active_list.remove(p_body);
  641. }
  642. void SpaceSW::body_add_to_inertia_update_list(SelfList<BodySW> *p_body) {
  643. inertia_update_list.add(p_body);
  644. }
  645. void SpaceSW::body_remove_from_inertia_update_list(SelfList<BodySW> *p_body) {
  646. inertia_update_list.remove(p_body);
  647. }
  648. BroadPhaseSW *SpaceSW::get_broadphase() {
  649. return broadphase;
  650. }
  651. void SpaceSW::add_object(CollisionObjectSW *p_object) {
  652. ERR_FAIL_COND(objects.has(p_object));
  653. objects.insert(p_object);
  654. }
  655. void SpaceSW::remove_object(CollisionObjectSW *p_object) {
  656. ERR_FAIL_COND(!objects.has(p_object));
  657. objects.erase(p_object);
  658. }
  659. const Set<CollisionObjectSW *> &SpaceSW::get_objects() const {
  660. return objects;
  661. }
  662. void SpaceSW::body_add_to_state_query_list(SelfList<BodySW> *p_body) {
  663. state_query_list.add(p_body);
  664. }
  665. void SpaceSW::body_remove_from_state_query_list(SelfList<BodySW> *p_body) {
  666. state_query_list.remove(p_body);
  667. }
  668. void SpaceSW::area_add_to_monitor_query_list(SelfList<AreaSW> *p_area) {
  669. monitor_query_list.add(p_area);
  670. }
  671. void SpaceSW::area_remove_from_monitor_query_list(SelfList<AreaSW> *p_area) {
  672. monitor_query_list.remove(p_area);
  673. }
  674. void SpaceSW::area_add_to_moved_list(SelfList<AreaSW> *p_area) {
  675. area_moved_list.add(p_area);
  676. }
  677. void SpaceSW::area_remove_from_moved_list(SelfList<AreaSW> *p_area) {
  678. area_moved_list.remove(p_area);
  679. }
  680. const SelfList<AreaSW>::List &SpaceSW::get_moved_area_list() const {
  681. return area_moved_list;
  682. }
  683. void SpaceSW::call_queries() {
  684. while (state_query_list.first()) {
  685. BodySW *b = state_query_list.first()->self();
  686. state_query_list.remove(state_query_list.first());
  687. b->call_queries();
  688. }
  689. while (monitor_query_list.first()) {
  690. AreaSW *a = monitor_query_list.first()->self();
  691. monitor_query_list.remove(monitor_query_list.first());
  692. a->call_queries();
  693. }
  694. }
  695. void SpaceSW::setup() {
  696. contact_debug_count = 0;
  697. while (inertia_update_list.first()) {
  698. inertia_update_list.first()->self()->update_inertias();
  699. inertia_update_list.remove(inertia_update_list.first());
  700. }
  701. }
  702. void SpaceSW::update() {
  703. broadphase->update();
  704. }
  705. void SpaceSW::set_param(PhysicsServer::SpaceParameter p_param, real_t p_value) {
  706. switch (p_param) {
  707. case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: contact_recycle_radius = p_value; break;
  708. case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: contact_max_separation = p_value; break;
  709. case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: contact_max_allowed_penetration = p_value; break;
  710. case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD: body_linear_velocity_sleep_threshold = p_value; break;
  711. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD: body_angular_velocity_sleep_threshold = p_value; break;
  712. case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: body_time_to_sleep = p_value; break;
  713. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO: body_angular_velocity_damp_ratio = p_value; break;
  714. case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: constraint_bias = p_value; break;
  715. }
  716. }
  717. real_t SpaceSW::get_param(PhysicsServer::SpaceParameter p_param) const {
  718. switch (p_param) {
  719. case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: return contact_recycle_radius;
  720. case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: return contact_max_separation;
  721. case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: return contact_max_allowed_penetration;
  722. case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD: return body_linear_velocity_sleep_threshold;
  723. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD: return body_angular_velocity_sleep_threshold;
  724. case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: return body_time_to_sleep;
  725. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO: return body_angular_velocity_damp_ratio;
  726. case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: return constraint_bias;
  727. }
  728. return 0;
  729. }
  730. void SpaceSW::lock() {
  731. locked = true;
  732. }
  733. void SpaceSW::unlock() {
  734. locked = false;
  735. }
  736. bool SpaceSW::is_locked() const {
  737. return locked;
  738. }
  739. PhysicsDirectSpaceStateSW *SpaceSW::get_direct_state() {
  740. return direct_access;
  741. }
  742. SpaceSW::SpaceSW() {
  743. collision_pairs = 0;
  744. active_objects = 0;
  745. island_count = 0;
  746. contact_debug_count = 0;
  747. locked = false;
  748. contact_recycle_radius = 0.01;
  749. contact_max_separation = 0.05;
  750. contact_max_allowed_penetration = 0.01;
  751. constraint_bias = 0.01;
  752. body_linear_velocity_sleep_threshold = GLOBAL_DEF("physics/3d/sleep_threshold_linear", 0.1);
  753. body_angular_velocity_sleep_threshold = GLOBAL_DEF("physics/3d/sleep_threshold_angular", (8.0 / 180.0 * Math_PI));
  754. body_time_to_sleep = GLOBAL_DEF("physics/3d/time_before_sleep", 0.5);
  755. body_angular_velocity_damp_ratio = 10;
  756. broadphase = BroadPhaseSW::create_func();
  757. broadphase->set_pair_callback(_broadphase_pair, this);
  758. broadphase->set_unpair_callback(_broadphase_unpair, this);
  759. area = NULL;
  760. direct_access = memnew(PhysicsDirectSpaceStateSW);
  761. direct_access->space = this;
  762. for (int i = 0; i < ELAPSED_TIME_MAX; i++)
  763. elapsed_time[i] = 0;
  764. }
  765. SpaceSW::~SpaceSW() {
  766. memdelete(broadphase);
  767. memdelete(direct_access);
  768. }