bvh.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. /*************************************************************************/
  2. /* bvh.h */
  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. #ifndef BVH_H
  31. #define BVH_H
  32. // BVH
  33. // This class provides a wrapper around BVH tree, which contains most of the functionality
  34. // for a dynamic BVH with templated leaf size.
  35. // However BVH also adds facilities for pairing, to maintain compatibility with Godot 3.2.
  36. // Pairing is a collision pairing system, on top of the basic BVH.
  37. // Some notes on the use of BVH / Octree from Godot 3.2.
  38. // This is not well explained elsewhere.
  39. // The rendering tree mask and types that are sent to the BVH are NOT layer masks.
  40. // They are INSTANCE_TYPES (defined in visual_server.h), e.g. MESH, MULTIMESH, PARTICLES etc.
  41. // Thus the lights do no cull by layer mask in the BVH.
  42. // Layer masks are implemented in the renderers as a later step, and light_cull_mask appears to be
  43. // implemented in GLES3 but not GLES2. Layer masks are not yet implemented for directional lights.
  44. // In the physics, the pairable_type is based on 1 << p_object->get_type() where:
  45. // TYPE_AREA,
  46. // TYPE_BODY
  47. // and pairable_mask is either 0 if static, or set to all if non static
  48. #include "bvh_tree.h"
  49. #include "core/os/mutex.h"
  50. #define BVHTREE_CLASS BVH_Tree<T, NUM_TREES, 2, MAX_ITEMS, USER_PAIR_TEST_FUNCTION, USER_CULL_TEST_FUNCTION, USE_PAIRS, BOUNDS, POINT>
  51. #define BVH_LOCKED_FUNCTION BVHLockedFunction(&_mutex, BVH_THREAD_SAFE &&_thread_safe);
  52. template <class T, int NUM_TREES = 1, bool USE_PAIRS = false, int MAX_ITEMS = 32, class USER_PAIR_TEST_FUNCTION = BVH_DummyPairTestFunction<T>, class USER_CULL_TEST_FUNCTION = BVH_DummyCullTestFunction<T>, class BOUNDS = AABB, class POINT = Vector3, bool BVH_THREAD_SAFE = true>
  53. class BVH_Manager {
  54. public:
  55. // note we are using uint32_t instead of BVHHandle, losing type safety, but this
  56. // is for compatibility with octree
  57. typedef void *(*PairCallback)(void *, uint32_t, T *, int, uint32_t, T *, int);
  58. typedef void (*UnpairCallback)(void *, uint32_t, T *, int, uint32_t, T *, int, void *);
  59. typedef void *(*CheckPairCallback)(void *, uint32_t, T *, int, uint32_t, T *, int, void *);
  60. // allow locally toggling thread safety if the template has been compiled with BVH_THREAD_SAFE
  61. void params_set_thread_safe(bool p_enable) {
  62. _thread_safe = p_enable;
  63. }
  64. // these 2 are crucial for fine tuning, and can be applied manually
  65. // see the variable declarations for more info.
  66. void params_set_node_expansion(real_t p_value) {
  67. BVH_LOCKED_FUNCTION
  68. if (p_value >= 0.0) {
  69. tree._node_expansion = p_value;
  70. tree._auto_node_expansion = false;
  71. } else {
  72. tree._auto_node_expansion = true;
  73. }
  74. }
  75. void params_set_pairing_expansion(real_t p_value) {
  76. BVH_LOCKED_FUNCTION
  77. tree.params_set_pairing_expansion(p_value);
  78. }
  79. void set_pair_callback(PairCallback p_callback, void *p_userdata) {
  80. BVH_LOCKED_FUNCTION
  81. pair_callback = p_callback;
  82. pair_callback_userdata = p_userdata;
  83. }
  84. void set_unpair_callback(UnpairCallback p_callback, void *p_userdata) {
  85. BVH_LOCKED_FUNCTION
  86. unpair_callback = p_callback;
  87. unpair_callback_userdata = p_userdata;
  88. }
  89. void set_check_pair_callback(CheckPairCallback p_callback, void *p_userdata) {
  90. BVH_LOCKED_FUNCTION
  91. check_pair_callback = p_callback;
  92. check_pair_callback_userdata = p_userdata;
  93. }
  94. BVHHandle create(T *p_userdata, bool p_active = true, uint32_t p_tree_id = 0, uint32_t p_tree_collision_mask = 1, const BOUNDS &p_aabb = BOUNDS(), int p_subindex = 0) {
  95. BVH_LOCKED_FUNCTION
  96. // not sure if absolutely necessary to flush collisions here. It will cost performance to, instead
  97. // of waiting for update, so only uncomment this if there are bugs.
  98. if (USE_PAIRS) {
  99. //_check_for_collisions();
  100. }
  101. BVHHandle h = tree.item_add(p_userdata, p_active, p_aabb, p_subindex, p_tree_id, p_tree_collision_mask);
  102. if (USE_PAIRS) {
  103. // for safety initialize the expanded AABB
  104. BOUNDS &expanded_aabb = tree._pairs[h.id()].expanded_aabb;
  105. expanded_aabb = p_aabb;
  106. expanded_aabb.grow_by(tree._pairing_expansion);
  107. // force a collision check no matter the AABB
  108. if (p_active) {
  109. _add_changed_item(h, p_aabb, false);
  110. _check_for_collisions(true);
  111. }
  112. }
  113. return h;
  114. }
  115. ////////////////////////////////////////////////////
  116. // wrapper versions that use uint32_t instead of handle
  117. // for backward compatibility. Less type safe
  118. void move(uint32_t p_handle, const BOUNDS &p_aabb) {
  119. BVHHandle h;
  120. h.set(p_handle);
  121. move(h, p_aabb);
  122. }
  123. void recheck_pairs(uint32_t p_handle) {
  124. BVHHandle h;
  125. h.set(p_handle);
  126. recheck_pairs(h);
  127. }
  128. void erase(uint32_t p_handle) {
  129. BVHHandle h;
  130. h.set(p_handle);
  131. erase(h);
  132. }
  133. void force_collision_check(uint32_t p_handle) {
  134. BVHHandle h;
  135. h.set(p_handle);
  136. force_collision_check(h);
  137. }
  138. bool activate(uint32_t p_handle, const BOUNDS &p_aabb, bool p_delay_collision_check = false) {
  139. BVHHandle h;
  140. h.set(p_handle);
  141. return activate(h, p_aabb, p_delay_collision_check);
  142. }
  143. bool deactivate(uint32_t p_handle) {
  144. BVHHandle h;
  145. h.set(p_handle);
  146. return deactivate(h);
  147. }
  148. void set_tree(uint32_t p_handle, uint32_t p_tree_id, uint32_t p_tree_collision_mask, bool p_force_collision_check = true) {
  149. BVHHandle h;
  150. h.set(p_handle);
  151. set_tree(h, p_tree_id, p_tree_collision_mask, p_force_collision_check);
  152. }
  153. uint32_t get_tree_id(uint32_t p_handle) const {
  154. BVHHandle h;
  155. h.set(p_handle);
  156. return item_get_tree_id(h);
  157. }
  158. int get_subindex(uint32_t p_handle) const {
  159. BVHHandle h;
  160. h.set(p_handle);
  161. return item_get_subindex(h);
  162. }
  163. T *get(uint32_t p_handle) const {
  164. BVHHandle h;
  165. h.set(p_handle);
  166. return item_get_userdata(h);
  167. }
  168. ////////////////////////////////////////////////////
  169. void move(BVHHandle p_handle, const BOUNDS &p_aabb) {
  170. DEV_ASSERT(!p_handle.is_invalid());
  171. BVH_LOCKED_FUNCTION
  172. if (tree.item_move(p_handle, p_aabb)) {
  173. if (USE_PAIRS) {
  174. _add_changed_item(p_handle, p_aabb);
  175. }
  176. }
  177. }
  178. void recheck_pairs(BVHHandle p_handle) {
  179. DEV_ASSERT(!p_handle.is_invalid());
  180. force_collision_check(p_handle);
  181. }
  182. void erase(BVHHandle p_handle) {
  183. DEV_ASSERT(!p_handle.is_invalid());
  184. BVH_LOCKED_FUNCTION
  185. // call unpair and remove all references to the item
  186. // before deleting from the tree
  187. if (USE_PAIRS) {
  188. _remove_changed_item(p_handle);
  189. }
  190. tree.item_remove(p_handle);
  191. _check_for_collisions(true);
  192. }
  193. // use in conjunction with activate if you have deferred the collision check, and
  194. // set pairable has never been called.
  195. // (deferred collision checks are a workaround for visual server for historical reasons)
  196. void force_collision_check(BVHHandle p_handle) {
  197. DEV_ASSERT(!p_handle.is_invalid());
  198. BVH_LOCKED_FUNCTION
  199. if (USE_PAIRS) {
  200. // the aabb should already be up to date in the BVH
  201. BOUNDS aabb;
  202. item_get_AABB(p_handle, aabb);
  203. // add it as changed even if aabb not different
  204. _add_changed_item(p_handle, aabb, false);
  205. // force an immediate full collision check, much like calls to set_pairable
  206. _check_for_collisions(true);
  207. }
  208. }
  209. // these should be read as set_visible for render trees,
  210. // but generically this makes items add or remove from the
  211. // tree internally, to speed things up by ignoring inactive items
  212. bool activate(BVHHandle p_handle, const BOUNDS &p_aabb, bool p_delay_collision_check = false) {
  213. DEV_ASSERT(!p_handle.is_invalid());
  214. BVH_LOCKED_FUNCTION
  215. // sending the aabb here prevents the need for the BVH to maintain
  216. // a redundant copy of the aabb.
  217. // returns success
  218. if (tree.item_activate(p_handle, p_aabb)) {
  219. if (USE_PAIRS) {
  220. // in the special case of the render tree, when setting visibility we are using the combination of
  221. // activate then set_pairable. This would case 2 sets of collision checks. For efficiency here we allow
  222. // deferring to have a single collision check at the set_pairable call.
  223. // Watch for bugs! This may cause bugs if set_pairable is not called.
  224. if (!p_delay_collision_check) {
  225. _add_changed_item(p_handle, p_aabb, false);
  226. // force an immediate collision check, much like calls to set_pairable
  227. _check_for_collisions(true);
  228. }
  229. }
  230. return true;
  231. }
  232. return false;
  233. }
  234. bool deactivate(BVHHandle p_handle) {
  235. DEV_ASSERT(!p_handle.is_invalid());
  236. BVH_LOCKED_FUNCTION
  237. // returns success
  238. if (tree.item_deactivate(p_handle)) {
  239. // call unpair and remove all references to the item
  240. // before deleting from the tree
  241. if (USE_PAIRS) {
  242. _remove_changed_item(p_handle);
  243. // force check for collisions, much like an erase was called
  244. _check_for_collisions(true);
  245. }
  246. return true;
  247. }
  248. return false;
  249. }
  250. bool get_active(BVHHandle p_handle) {
  251. DEV_ASSERT(!p_handle.is_invalid());
  252. BVH_LOCKED_FUNCTION
  253. return tree.item_get_active(p_handle);
  254. }
  255. // call e.g. once per frame (this does a trickle optimize)
  256. void update() {
  257. BVH_LOCKED_FUNCTION
  258. tree.update();
  259. _check_for_collisions();
  260. #ifdef BVH_INTEGRITY_CHECKS
  261. tree.integrity_check_all();
  262. #endif
  263. }
  264. // this can be called more frequently than per frame if necessary
  265. void update_collisions() {
  266. BVH_LOCKED_FUNCTION
  267. _check_for_collisions();
  268. }
  269. // prefer calling this directly as type safe
  270. void set_tree(const BVHHandle &p_handle, uint32_t p_tree_id, uint32_t p_tree_collision_mask, bool p_force_collision_check = true) {
  271. DEV_ASSERT(!p_handle.is_invalid());
  272. BVH_LOCKED_FUNCTION
  273. // Returns true if the pairing state has changed.
  274. bool state_changed = tree.item_set_tree(p_handle, p_tree_id, p_tree_collision_mask);
  275. if (USE_PAIRS) {
  276. // not sure if absolutely necessary to flush collisions here. It will cost performance to, instead
  277. // of waiting for update, so only uncomment this if there are bugs.
  278. //_check_for_collisions();
  279. if ((p_force_collision_check || state_changed) && tree.item_get_active(p_handle)) {
  280. // when the pairable state changes, we need to force a collision check because newly pairable
  281. // items may be in collision, and unpairable items might move out of collision.
  282. // We cannot depend on waiting for the next update, because that may come much later.
  283. BOUNDS aabb;
  284. item_get_AABB(p_handle, aabb);
  285. // passing false disables the optimization which prevents collision checks if
  286. // the aabb hasn't changed
  287. _add_changed_item(p_handle, aabb, false);
  288. // force an immediate collision check (probably just for this one item)
  289. // but it must be a FULL collision check, also checking pairable state and masks.
  290. // This is because AABB intersecting objects may have changed pairable state / mask
  291. // such that they should no longer be paired. E.g. lights.
  292. _check_for_collisions(true);
  293. } // only if active
  294. }
  295. }
  296. // cull tests
  297. int cull_aabb(const BOUNDS &p_aabb, T **p_result_array, int p_result_max, const T *p_tester, uint32_t p_tree_collision_mask = 0xFFFFFFFF, int *p_subindex_array = nullptr) {
  298. BVH_LOCKED_FUNCTION
  299. typename BVHTREE_CLASS::CullParams params;
  300. params.result_count_overall = 0;
  301. params.result_max = p_result_max;
  302. params.result_array = p_result_array;
  303. params.subindex_array = p_subindex_array;
  304. params.tree_collision_mask = p_tree_collision_mask;
  305. params.abb.from(p_aabb);
  306. params.tester = p_tester;
  307. tree.cull_aabb(params);
  308. return params.result_count_overall;
  309. }
  310. int cull_segment(const POINT &p_from, const POINT &p_to, T **p_result_array, int p_result_max, const T *p_tester, uint32_t p_tree_collision_mask = 0xFFFFFFFF, int *p_subindex_array = nullptr) {
  311. BVH_LOCKED_FUNCTION
  312. typename BVHTREE_CLASS::CullParams params;
  313. params.result_count_overall = 0;
  314. params.result_max = p_result_max;
  315. params.result_array = p_result_array;
  316. params.subindex_array = p_subindex_array;
  317. params.tester = p_tester;
  318. params.tree_collision_mask = p_tree_collision_mask;
  319. params.segment.from = p_from;
  320. params.segment.to = p_to;
  321. tree.cull_segment(params);
  322. return params.result_count_overall;
  323. }
  324. int cull_point(const POINT &p_point, T **p_result_array, int p_result_max, const T *p_tester, uint32_t p_tree_collision_mask = 0xFFFFFFFF, int *p_subindex_array = nullptr) {
  325. BVH_LOCKED_FUNCTION
  326. typename BVHTREE_CLASS::CullParams params;
  327. params.result_count_overall = 0;
  328. params.result_max = p_result_max;
  329. params.result_array = p_result_array;
  330. params.subindex_array = p_subindex_array;
  331. params.tester = p_tester;
  332. params.tree_collision_mask = p_tree_collision_mask;
  333. params.point = p_point;
  334. tree.cull_point(params);
  335. return params.result_count_overall;
  336. }
  337. int cull_convex(const Vector<Plane> &p_convex, T **p_result_array, int p_result_max, const T *p_tester, uint32_t p_tree_collision_mask = 0xFFFFFFFF) {
  338. BVH_LOCKED_FUNCTION
  339. if (!p_convex.size()) {
  340. return 0;
  341. }
  342. Vector<Vector3> convex_points = Geometry3D::compute_convex_mesh_points(&p_convex[0], p_convex.size());
  343. if (convex_points.size() == 0) {
  344. return 0;
  345. }
  346. typename BVHTREE_CLASS::CullParams params;
  347. params.result_count_overall = 0;
  348. params.result_max = p_result_max;
  349. params.result_array = p_result_array;
  350. params.subindex_array = nullptr;
  351. params.tester = p_tester;
  352. params.tree_collision_mask = p_tree_collision_mask;
  353. params.hull.planes = &p_convex[0];
  354. params.hull.num_planes = p_convex.size();
  355. params.hull.points = &convex_points[0];
  356. params.hull.num_points = convex_points.size();
  357. tree.cull_convex(params);
  358. return params.result_count_overall;
  359. }
  360. private:
  361. // do this after moving etc.
  362. void _check_for_collisions(bool p_full_check = false) {
  363. if (!changed_items.size()) {
  364. // noop
  365. return;
  366. }
  367. BOUNDS bb;
  368. typename BVHTREE_CLASS::CullParams params;
  369. params.result_count_overall = 0;
  370. params.result_max = INT_MAX;
  371. params.result_array = nullptr;
  372. params.subindex_array = nullptr;
  373. for (unsigned int n = 0; n < changed_items.size(); n++) {
  374. const BVHHandle &h = changed_items[n];
  375. // use the expanded aabb for pairing
  376. const BOUNDS &expanded_aabb = tree._pairs[h.id()].expanded_aabb;
  377. BVHABB_CLASS abb;
  378. abb.from(expanded_aabb);
  379. tree.item_fill_cullparams(h, params);
  380. // find all the existing paired aabbs that are no longer
  381. // paired, and send callbacks
  382. _find_leavers(h, abb, p_full_check);
  383. uint32_t changed_item_ref_id = h.id();
  384. params.abb = abb;
  385. params.result_count_overall = 0; // might not be needed
  386. tree.cull_aabb(params, false);
  387. for (unsigned int i = 0; i < tree._cull_hits.size(); i++) {
  388. uint32_t ref_id = tree._cull_hits[i];
  389. // don't collide against ourself
  390. if (ref_id == changed_item_ref_id) {
  391. continue;
  392. }
  393. // checkmasks is already done in the cull routine.
  394. BVHHandle h_collidee;
  395. h_collidee.set_id(ref_id);
  396. // find NEW enterers, and send callbacks for them only
  397. _collide(h, h_collidee);
  398. }
  399. }
  400. _reset();
  401. }
  402. public:
  403. void item_get_AABB(BVHHandle p_handle, BOUNDS &r_aabb) {
  404. DEV_ASSERT(!p_handle.is_invalid());
  405. BVHABB_CLASS abb;
  406. tree.item_get_ABB(p_handle, abb);
  407. abb.to(r_aabb);
  408. }
  409. private:
  410. // supplemental funcs
  411. uint32_t item_get_tree_id(BVHHandle p_handle) const { return _get_extra(p_handle).tree_id; }
  412. T *item_get_userdata(BVHHandle p_handle) const { return _get_extra(p_handle).userdata; }
  413. int item_get_subindex(BVHHandle p_handle) const { return _get_extra(p_handle).subindex; }
  414. void _unpair(BVHHandle p_from, BVHHandle p_to) {
  415. tree._handle_sort(p_from, p_to);
  416. typename BVHTREE_CLASS::ItemExtra &exa = tree._extra[p_from.id()];
  417. typename BVHTREE_CLASS::ItemExtra &exb = tree._extra[p_to.id()];
  418. // if the userdata is the same, no collisions should occur
  419. if ((exa.userdata == exb.userdata) && exa.userdata) {
  420. return;
  421. }
  422. typename BVHTREE_CLASS::ItemPairs &pairs_from = tree._pairs[p_from.id()];
  423. typename BVHTREE_CLASS::ItemPairs &pairs_to = tree._pairs[p_to.id()];
  424. void *ud_from = pairs_from.remove_pair_to(p_to);
  425. pairs_to.remove_pair_to(p_from);
  426. #ifdef BVH_VERBOSE_PAIRING
  427. print_line("_unpair " + itos(p_from.id()) + " from " + itos(p_to.id()));
  428. #endif
  429. // callback
  430. if (unpair_callback) {
  431. unpair_callback(pair_callback_userdata, p_from, exa.userdata, exa.subindex, p_to, exb.userdata, exb.subindex, ud_from);
  432. }
  433. }
  434. void *_recheck_pair(BVHHandle p_from, BVHHandle p_to, void *p_pair_data) {
  435. tree._handle_sort(p_from, p_to);
  436. typename BVHTREE_CLASS::ItemExtra &exa = tree._extra[p_from.id()];
  437. typename BVHTREE_CLASS::ItemExtra &exb = tree._extra[p_to.id()];
  438. // if the userdata is the same, no collisions should occur
  439. if ((exa.userdata == exb.userdata) && exa.userdata) {
  440. return p_pair_data;
  441. }
  442. // callback
  443. if (check_pair_callback) {
  444. return check_pair_callback(check_pair_callback_userdata, p_from, exa.userdata, exa.subindex, p_to, exb.userdata, exb.subindex, p_pair_data);
  445. }
  446. return p_pair_data;
  447. }
  448. // returns true if unpair
  449. bool _find_leavers_process_pair(typename BVHTREE_CLASS::ItemPairs &p_pairs_from, const BVHABB_CLASS &p_abb_from, BVHHandle p_from, BVHHandle p_to, bool p_full_check) {
  450. BVHABB_CLASS abb_to;
  451. tree.item_get_ABB(p_to, abb_to);
  452. // do they overlap?
  453. if (p_abb_from.intersects(abb_to)) {
  454. // the full check for pairable / non pairable (i.e. tree_id and tree_masks) and mask changes is extra expense
  455. // this need not be done in most cases (for speed) except in the case where set_tree is called
  456. // where the masks etc of the objects in question may have changed
  457. if (!p_full_check) {
  458. return false;
  459. }
  460. const typename BVHTREE_CLASS::ItemExtra &exa = _get_extra(p_from);
  461. const typename BVHTREE_CLASS::ItemExtra &exb = _get_extra(p_to);
  462. // Checking tree_ids and tree_collision_masks
  463. if (exa.are_item_trees_compatible(exb)) {
  464. bool pair_allowed = USER_PAIR_TEST_FUNCTION::user_pair_check(exa.userdata, exb.userdata);
  465. // the masks must still be compatible to pair
  466. // i.e. if there is a hit between the two and they intersect, then they should stay paired
  467. if (pair_allowed) {
  468. return false;
  469. }
  470. }
  471. }
  472. _unpair(p_from, p_to);
  473. return true;
  474. }
  475. // find all the existing paired aabbs that are no longer
  476. // paired, and send callbacks
  477. void _find_leavers(BVHHandle p_handle, const BVHABB_CLASS &expanded_abb_from, bool p_full_check) {
  478. typename BVHTREE_CLASS::ItemPairs &p_from = tree._pairs[p_handle.id()];
  479. BVHABB_CLASS abb_from = expanded_abb_from;
  480. // remove from pairing list for every partner
  481. for (unsigned int n = 0; n < p_from.extended_pairs.size(); n++) {
  482. BVHHandle h_to = p_from.extended_pairs[n].handle;
  483. if (_find_leavers_process_pair(p_from, abb_from, p_handle, h_to, p_full_check)) {
  484. // we need to keep the counter n up to date if we deleted a pair
  485. // as the number of items in p_from.extended_pairs will have decreased by 1
  486. // and we don't want to miss an item
  487. n--;
  488. }
  489. }
  490. }
  491. // find NEW enterers, and send callbacks for them only
  492. // handle a and b
  493. void _collide(BVHHandle p_ha, BVHHandle p_hb) {
  494. // only have to do this oneway, lower ID then higher ID
  495. tree._handle_sort(p_ha, p_hb);
  496. const typename BVHTREE_CLASS::ItemExtra &exa = _get_extra(p_ha);
  497. const typename BVHTREE_CLASS::ItemExtra &exb = _get_extra(p_hb);
  498. // user collision callback
  499. if (!USER_PAIR_TEST_FUNCTION::user_pair_check(exa.userdata, exb.userdata)) {
  500. return;
  501. }
  502. // if the userdata is the same, no collisions should occur
  503. if ((exa.userdata == exb.userdata) && exa.userdata) {
  504. return;
  505. }
  506. typename BVHTREE_CLASS::ItemPairs &p_from = tree._pairs[p_ha.id()];
  507. typename BVHTREE_CLASS::ItemPairs &p_to = tree._pairs[p_hb.id()];
  508. // does this pair exist already?
  509. // or only check the one with lower number of pairs for greater speed
  510. if (p_from.num_pairs <= p_to.num_pairs) {
  511. if (p_from.contains_pair_to(p_hb)) {
  512. return;
  513. }
  514. } else {
  515. if (p_to.contains_pair_to(p_ha)) {
  516. return;
  517. }
  518. }
  519. // callback
  520. void *callback_userdata = nullptr;
  521. #ifdef BVH_VERBOSE_PAIRING
  522. print_line("_pair " + itos(p_ha.id()) + " to " + itos(p_hb.id()));
  523. #endif
  524. if (pair_callback) {
  525. callback_userdata = pair_callback(pair_callback_userdata, p_ha, exa.userdata, exa.subindex, p_hb, exb.userdata, exb.subindex);
  526. }
  527. // new pair! .. only really need to store the userdata on the lower handle, but both have storage so...
  528. p_from.add_pair_to(p_hb, callback_userdata);
  529. p_to.add_pair_to(p_ha, callback_userdata);
  530. }
  531. // if we remove an item, we need to immediately remove the pairs, to prevent reading the pair after deletion
  532. void _remove_pairs_containing(BVHHandle p_handle) {
  533. typename BVHTREE_CLASS::ItemPairs &p_from = tree._pairs[p_handle.id()];
  534. // remove from pairing list for every partner.
  535. // can't easily use a for loop here, because removing changes the size of the list
  536. while (p_from.extended_pairs.size()) {
  537. BVHHandle h_to = p_from.extended_pairs[0].handle;
  538. _unpair(p_handle, h_to);
  539. }
  540. }
  541. // Send pair callbacks again for all existing pairs for the given handle.
  542. void _recheck_pairs(BVHHandle p_handle) {
  543. typename BVHTREE_CLASS::ItemPairs &from = tree._pairs[p_handle.id()];
  544. // checking pair for every partner.
  545. for (unsigned int n = 0; n < from.extended_pairs.size(); n++) {
  546. typename BVHTREE_CLASS::ItemPairs::Link &pair = from.extended_pairs[n];
  547. BVHHandle h_to = pair.handle;
  548. void *new_pair_data = _recheck_pair(p_handle, h_to, pair.userdata);
  549. if (new_pair_data != pair.userdata) {
  550. pair.userdata = new_pair_data;
  551. // Update pair data for the second item.
  552. typename BVHTREE_CLASS::ItemPairs &to = tree._pairs[h_to.id()];
  553. for (unsigned int to_index = 0; to_index < to.extended_pairs.size(); to_index++) {
  554. typename BVHTREE_CLASS::ItemPairs::Link &to_pair = to.extended_pairs[to_index];
  555. if (to_pair.handle == p_handle) {
  556. to_pair.userdata = new_pair_data;
  557. break;
  558. }
  559. }
  560. }
  561. }
  562. }
  563. private:
  564. const typename BVHTREE_CLASS::ItemExtra &_get_extra(BVHHandle p_handle) const {
  565. return tree._extra[p_handle.id()];
  566. }
  567. const typename BVHTREE_CLASS::ItemRef &_get_ref(BVHHandle p_handle) const {
  568. return tree._refs[p_handle.id()];
  569. }
  570. void _reset() {
  571. changed_items.clear();
  572. _tick++;
  573. }
  574. void _add_changed_item(BVHHandle p_handle, const BOUNDS &aabb, bool p_check_aabb = true) {
  575. // Note that non pairable items can pair with pairable,
  576. // so all types must be added to the list
  577. #ifdef BVH_EXPAND_LEAF_AABBS
  578. // if using expanded AABB in the leaf, the redundancy check will already have been made
  579. BOUNDS &expanded_aabb = tree._pairs[p_handle.id()].expanded_aabb;
  580. item_get_AABB(p_handle, expanded_aabb);
  581. #else
  582. // aabb check with expanded aabb. This greatly decreases processing
  583. // at the cost of slightly less accurate pairing checks
  584. // Note this pairing AABB is separate from the AABB in the actual tree
  585. BOUNDS &expanded_aabb = tree._pairs[p_handle.id()].expanded_aabb;
  586. // passing p_check_aabb false disables the optimization which prevents collision checks if
  587. // the aabb hasn't changed. This is needed where set_pairable has been called, but the position
  588. // has not changed.
  589. if (p_check_aabb && tree.expanded_aabb_encloses_not_shrink(expanded_aabb, aabb)) {
  590. return;
  591. }
  592. // ALWAYS update the new expanded aabb, even if already changed once
  593. // this tick, because it is vital that the AABB is kept up to date
  594. expanded_aabb = aabb;
  595. expanded_aabb.grow_by(tree._pairing_expansion);
  596. #endif
  597. // this code is to ensure that changed items only appear once on the updated list
  598. // collision checking them multiple times is not needed, and repeats the same thing
  599. uint32_t &last_updated_tick = tree._extra[p_handle.id()].last_updated_tick;
  600. if (last_updated_tick == _tick) {
  601. return; // already on changed list
  602. }
  603. // mark as on list
  604. last_updated_tick = _tick;
  605. // add to the list
  606. changed_items.push_back(p_handle);
  607. }
  608. void _remove_changed_item(BVHHandle p_handle) {
  609. // Care has to be taken here for items that are deleted. The ref ID
  610. // could be reused on the same tick for new items. This is probably
  611. // rare but should be taken into consideration
  612. // callbacks
  613. _remove_pairs_containing(p_handle);
  614. // remove from changed items (not very efficient yet)
  615. for (int n = 0; n < (int)changed_items.size(); n++) {
  616. if (changed_items[n] == p_handle) {
  617. changed_items.remove_at_unordered(n);
  618. // because we are using an unordered remove,
  619. // the last changed item will now be at spot 'n',
  620. // and we need to redo it, so we prevent moving on to
  621. // the next n at the next for iteration.
  622. n--;
  623. }
  624. }
  625. // reset the last updated tick (may not be necessary but just in case)
  626. tree._extra[p_handle.id()].last_updated_tick = 0;
  627. }
  628. PairCallback pair_callback = nullptr;
  629. UnpairCallback unpair_callback = nullptr;
  630. CheckPairCallback check_pair_callback = nullptr;
  631. void *pair_callback_userdata = nullptr;
  632. void *unpair_callback_userdata = nullptr;
  633. void *check_pair_callback_userdata = nullptr;
  634. BVHTREE_CLASS tree;
  635. // for collision pairing,
  636. // maintain a list of all items moved etc on each frame / tick
  637. LocalVector<BVHHandle, uint32_t, true> changed_items;
  638. uint32_t _tick = 1; // Start from 1 so items with 0 indicate never updated.
  639. class BVHLockedFunction {
  640. public:
  641. BVHLockedFunction(Mutex *p_mutex, bool p_thread_safe) {
  642. // will be compiled out if not set in template
  643. if (p_thread_safe) {
  644. _mutex = p_mutex;
  645. if (_mutex->try_lock() != OK) {
  646. WARN_PRINT("Info : multithread BVH access detected (benign)");
  647. _mutex->lock();
  648. }
  649. } else {
  650. _mutex = nullptr;
  651. }
  652. }
  653. ~BVHLockedFunction() {
  654. // will be compiled out if not set in template
  655. if (_mutex) {
  656. _mutex->unlock();
  657. }
  658. }
  659. private:
  660. Mutex *_mutex = nullptr;
  661. };
  662. Mutex _mutex;
  663. // local toggle for turning on and off thread safety in project settings
  664. bool _thread_safe = BVH_THREAD_SAFE;
  665. public:
  666. BVH_Manager() {}
  667. };
  668. #undef BVHTREE_CLASS
  669. #endif // BVH_H