octree.h 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  1. /*************************************************************************/
  2. /* octree.h */
  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. #ifndef OCTREE_H
  31. #define OCTREE_H
  32. #include "core/list.h"
  33. #include "core/map.h"
  34. #include "core/math/aabb.h"
  35. #include "core/math/vector3.h"
  36. #include "core/print_string.h"
  37. #include "core/variant.h"
  38. typedef uint32_t OctreeElementID;
  39. #define OCTREE_ELEMENT_INVALID_ID 0
  40. #define OCTREE_SIZE_LIMIT 1e15
  41. template <class T, bool use_pairs = false, class AL = DefaultAllocator>
  42. class Octree {
  43. public:
  44. typedef void *(*PairCallback)(void *, OctreeElementID, T *, int, OctreeElementID, T *, int);
  45. typedef void (*UnpairCallback)(void *, OctreeElementID, T *, int, OctreeElementID, T *, int, void *);
  46. private:
  47. enum {
  48. NEG = 0,
  49. POS = 1,
  50. };
  51. enum {
  52. OCTANT_NX_NY_NZ,
  53. OCTANT_PX_NY_NZ,
  54. OCTANT_NX_PY_NZ,
  55. OCTANT_PX_PY_NZ,
  56. OCTANT_NX_NY_PZ,
  57. OCTANT_PX_NY_PZ,
  58. OCTANT_NX_PY_PZ,
  59. OCTANT_PX_PY_PZ
  60. };
  61. struct PairKey {
  62. union {
  63. struct {
  64. OctreeElementID A;
  65. OctreeElementID B;
  66. };
  67. uint64_t key;
  68. };
  69. _FORCE_INLINE_ bool operator<(const PairKey &p_pair) const {
  70. return key < p_pair.key;
  71. }
  72. _FORCE_INLINE_ PairKey(OctreeElementID p_A, OctreeElementID p_B) {
  73. if (p_A < p_B) {
  74. A = p_A;
  75. B = p_B;
  76. } else {
  77. B = p_A;
  78. A = p_B;
  79. }
  80. }
  81. _FORCE_INLINE_ PairKey() {}
  82. };
  83. struct Element;
  84. struct Octant {
  85. // cached for FAST plane check
  86. AABB aabb;
  87. uint64_t last_pass;
  88. Octant *parent;
  89. Octant *children[8];
  90. int children_count; // cache for amount of childrens (fast check for removal)
  91. int parent_index; // cache for parent index (fast check for removal)
  92. List<Element *, AL> pairable_elements;
  93. List<Element *, AL> elements;
  94. Octant() {
  95. children_count = 0;
  96. parent_index = -1;
  97. last_pass = 0;
  98. parent = nullptr;
  99. for (int i = 0; i < 8; i++)
  100. children[i] = nullptr;
  101. }
  102. ~Octant() {
  103. /*
  104. for (int i=0;i<8;i++)
  105. memdelete_notnull(children[i]);
  106. */
  107. }
  108. };
  109. struct PairData;
  110. struct Element {
  111. Octree *octree;
  112. T *userdata;
  113. int subindex;
  114. bool pairable;
  115. uint32_t pairable_mask;
  116. uint32_t pairable_type;
  117. uint64_t last_pass;
  118. OctreeElementID _id;
  119. Octant *common_parent;
  120. AABB aabb;
  121. AABB container_aabb;
  122. List<PairData *, AL> pair_list;
  123. struct OctantOwner {
  124. Octant *octant;
  125. typename List<Element *, AL>::Element *E;
  126. }; // an element can be in max 8 octants
  127. List<OctantOwner, AL> octant_owners;
  128. Element() {
  129. last_pass = 0;
  130. _id = 0;
  131. pairable = false;
  132. subindex = 0;
  133. userdata = 0;
  134. octree = 0;
  135. pairable_mask = 0;
  136. pairable_type = 0;
  137. common_parent = nullptr;
  138. }
  139. };
  140. struct PairData {
  141. int refcount;
  142. bool intersect;
  143. Element *A, *B;
  144. void *ud;
  145. typename List<PairData *, AL>::Element *eA, *eB;
  146. };
  147. typedef Map<OctreeElementID, Element, Comparator<OctreeElementID>, AL> ElementMap;
  148. typedef Map<PairKey, PairData, Comparator<PairKey>, AL> PairMap;
  149. ElementMap element_map;
  150. PairMap pair_map;
  151. PairCallback pair_callback;
  152. UnpairCallback unpair_callback;
  153. void *pair_callback_userdata;
  154. void *unpair_callback_userdata;
  155. OctreeElementID last_element_id;
  156. uint64_t pass;
  157. real_t unit_size;
  158. Octant *root;
  159. int octant_count;
  160. int pair_count;
  161. _FORCE_INLINE_ void _pair_check(PairData *p_pair) {
  162. bool intersect = p_pair->A->aabb.intersects_inclusive(p_pair->B->aabb);
  163. if (intersect != p_pair->intersect) {
  164. if (intersect) {
  165. if (pair_callback) {
  166. p_pair->ud = pair_callback(pair_callback_userdata, p_pair->A->_id, p_pair->A->userdata, p_pair->A->subindex, p_pair->B->_id, p_pair->B->userdata, p_pair->B->subindex);
  167. }
  168. pair_count++;
  169. } else {
  170. if (unpair_callback) {
  171. unpair_callback(pair_callback_userdata, p_pair->A->_id, p_pair->A->userdata, p_pair->A->subindex, p_pair->B->_id, p_pair->B->userdata, p_pair->B->subindex, p_pair->ud);
  172. }
  173. pair_count--;
  174. }
  175. p_pair->intersect = intersect;
  176. }
  177. }
  178. _FORCE_INLINE_ void _pair_reference(Element *p_A, Element *p_B) {
  179. if (p_A == p_B || (p_A->userdata == p_B->userdata && p_A->userdata))
  180. return;
  181. if (!(p_A->pairable_type & p_B->pairable_mask) &&
  182. !(p_B->pairable_type & p_A->pairable_mask))
  183. return; // none can pair with none
  184. PairKey key(p_A->_id, p_B->_id);
  185. typename PairMap::Element *E = pair_map.find(key);
  186. if (!E) {
  187. PairData pdata;
  188. pdata.refcount = 1;
  189. pdata.A = p_A;
  190. pdata.B = p_B;
  191. pdata.intersect = false;
  192. E = pair_map.insert(key, pdata);
  193. E->get().eA = p_A->pair_list.push_back(&E->get());
  194. E->get().eB = p_B->pair_list.push_back(&E->get());
  195. /*
  196. if (pair_callback)
  197. pair_callback(pair_callback_userdata,p_A->userdata,p_B->userdata);
  198. */
  199. } else {
  200. E->get().refcount++;
  201. }
  202. }
  203. _FORCE_INLINE_ void _pair_unreference(Element *p_A, Element *p_B) {
  204. if (p_A == p_B)
  205. return;
  206. PairKey key(p_A->_id, p_B->_id);
  207. typename PairMap::Element *E = pair_map.find(key);
  208. if (!E) {
  209. return; // no pair
  210. }
  211. E->get().refcount--;
  212. if (E->get().refcount == 0) {
  213. // bye pair
  214. if (E->get().intersect) {
  215. if (unpair_callback) {
  216. unpair_callback(pair_callback_userdata, p_A->_id, p_A->userdata, p_A->subindex, p_B->_id, p_B->userdata, p_B->subindex, E->get().ud);
  217. }
  218. pair_count--;
  219. }
  220. if (p_A == E->get().B) {
  221. //may be reaching inverted
  222. SWAP(p_A, p_B);
  223. }
  224. p_A->pair_list.erase(E->get().eA);
  225. p_B->pair_list.erase(E->get().eB);
  226. pair_map.erase(E);
  227. }
  228. }
  229. _FORCE_INLINE_ void _element_check_pairs(Element *p_element) {
  230. typename List<PairData *, AL>::Element *E = p_element->pair_list.front();
  231. while (E) {
  232. _pair_check(E->get());
  233. E = E->next();
  234. }
  235. }
  236. _FORCE_INLINE_ void _optimize() {
  237. while (root && root->children_count < 2 && !root->elements.size() && !(use_pairs && root->pairable_elements.size())) {
  238. Octant *new_root = nullptr;
  239. if (root->children_count == 1) {
  240. for (int i = 0; i < 8; i++) {
  241. if (root->children[i]) {
  242. new_root = root->children[i];
  243. root->children[i] = nullptr;
  244. break;
  245. }
  246. }
  247. ERR_FAIL_COND(!new_root);
  248. new_root->parent = nullptr;
  249. new_root->parent_index = -1;
  250. }
  251. memdelete_allocator<Octant, AL>(root);
  252. octant_count--;
  253. root = new_root;
  254. }
  255. }
  256. void _insert_element(Element *p_element, Octant *p_octant);
  257. void _ensure_valid_root(const AABB &p_aabb);
  258. bool _remove_element_from_octant(Element *p_element, Octant *p_octant, Octant *p_limit = nullptr);
  259. void _remove_element(Element *p_element);
  260. void _pair_element(Element *p_element, Octant *p_octant);
  261. void _unpair_element(Element *p_element, Octant *p_octant);
  262. struct _CullConvexData {
  263. const Plane *planes;
  264. int plane_count;
  265. T **result_array;
  266. int *result_idx;
  267. int result_max;
  268. uint32_t mask;
  269. };
  270. void _cull_convex(Octant *p_octant, _CullConvexData *p_cull);
  271. void _cull_aabb(Octant *p_octant, const AABB &p_aabb, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask);
  272. void _cull_segment(Octant *p_octant, const Vector3 &p_from, const Vector3 &p_to, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask);
  273. void _cull_point(Octant *p_octant, const Vector3 &p_point, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask);
  274. void _remove_tree(Octant *p_octant) {
  275. if (!p_octant)
  276. return;
  277. for (int i = 0; i < 8; i++) {
  278. if (p_octant->children[i])
  279. _remove_tree(p_octant->children[i]);
  280. }
  281. memdelete_allocator<Octant, AL>(p_octant);
  282. }
  283. public:
  284. OctreeElementID create(T *p_userdata, const AABB &p_aabb = AABB(), int p_subindex = 0, bool p_pairable = false, uint32_t p_pairable_type = 0, uint32_t pairable_mask = 1);
  285. void move(OctreeElementID p_id, const AABB &p_aabb);
  286. void set_pairable(OctreeElementID p_id, bool p_pairable = false, uint32_t p_pairable_type = 0, uint32_t pairable_mask = 1);
  287. void erase(OctreeElementID p_id);
  288. bool is_pairable(OctreeElementID p_id) const;
  289. T *get(OctreeElementID p_id) const;
  290. int get_subindex(OctreeElementID p_id) const;
  291. int cull_convex(const Vector<Plane> &p_convex, T **p_result_array, int p_result_max, uint32_t p_mask = 0xFFFFFFFF);
  292. int cull_aabb(const AABB &p_aabb, T **p_result_array, int p_result_max, int *p_subindex_array = nullptr, uint32_t p_mask = 0xFFFFFFFF);
  293. int cull_segment(const Vector3 &p_from, const Vector3 &p_to, T **p_result_array, int p_result_max, int *p_subindex_array = nullptr, uint32_t p_mask = 0xFFFFFFFF);
  294. int cull_point(const Vector3 &p_point, T **p_result_array, int p_result_max, int *p_subindex_array = nullptr, uint32_t p_mask = 0xFFFFFFFF);
  295. void set_pair_callback(PairCallback p_callback, void *p_userdata);
  296. void set_unpair_callback(UnpairCallback p_callback, void *p_userdata);
  297. int get_octant_count() const { return octant_count; }
  298. int get_pair_count() const { return pair_count; }
  299. Octree(real_t p_unit_size = 1.0);
  300. ~Octree() { _remove_tree(root); }
  301. };
  302. /* PRIVATE FUNCTIONS */
  303. template <class T, bool use_pairs, class AL>
  304. T *Octree<T, use_pairs, AL>::get(OctreeElementID p_id) const {
  305. const typename ElementMap::Element *E = element_map.find(p_id);
  306. ERR_FAIL_COND_V(!E, nullptr);
  307. return E->get().userdata;
  308. }
  309. template <class T, bool use_pairs, class AL>
  310. bool Octree<T, use_pairs, AL>::is_pairable(OctreeElementID p_id) const {
  311. const typename ElementMap::Element *E = element_map.find(p_id);
  312. ERR_FAIL_COND_V(!E, false);
  313. return E->get().pairable;
  314. }
  315. template <class T, bool use_pairs, class AL>
  316. int Octree<T, use_pairs, AL>::get_subindex(OctreeElementID p_id) const {
  317. const typename ElementMap::Element *E = element_map.find(p_id);
  318. ERR_FAIL_COND_V(!E, -1);
  319. return E->get().subindex;
  320. }
  321. #define OCTREE_DIVISOR 4
  322. template <class T, bool use_pairs, class AL>
  323. void Octree<T, use_pairs, AL>::_insert_element(Element *p_element, Octant *p_octant) {
  324. real_t element_size = p_element->aabb.get_longest_axis_size() * 1.01; // avoid precision issues
  325. if (p_octant->aabb.size.x / OCTREE_DIVISOR < element_size) {
  326. //if (p_octant->aabb.size.x*0.5 < element_size) {
  327. /* at smallest possible size for the element */
  328. typename Element::OctantOwner owner;
  329. owner.octant = p_octant;
  330. if (use_pairs && p_element->pairable) {
  331. p_octant->pairable_elements.push_back(p_element);
  332. owner.E = p_octant->pairable_elements.back();
  333. } else {
  334. p_octant->elements.push_back(p_element);
  335. owner.E = p_octant->elements.back();
  336. }
  337. p_element->octant_owners.push_back(owner);
  338. if (p_element->common_parent == nullptr) {
  339. p_element->common_parent = p_octant;
  340. p_element->container_aabb = p_octant->aabb;
  341. } else {
  342. p_element->container_aabb.merge_with(p_octant->aabb);
  343. }
  344. if (use_pairs && p_octant->children_count > 0) {
  345. pass++; //elements below this only get ONE reference added
  346. for (int i = 0; i < 8; i++) {
  347. if (p_octant->children[i]) {
  348. _pair_element(p_element, p_octant->children[i]);
  349. }
  350. }
  351. }
  352. } else {
  353. /* not big enough, send it to subitems */
  354. int splits = 0;
  355. bool candidate = p_element->common_parent == nullptr;
  356. for (int i = 0; i < 8; i++) {
  357. if (p_octant->children[i]) {
  358. /* element exists, go straight to it */
  359. if (p_octant->children[i]->aabb.intersects_inclusive(p_element->aabb)) {
  360. _insert_element(p_element, p_octant->children[i]);
  361. splits++;
  362. }
  363. } else {
  364. /* check against AABB where child should be */
  365. AABB aabb = p_octant->aabb;
  366. aabb.size *= 0.5;
  367. if (i & 1)
  368. aabb.position.x += aabb.size.x;
  369. if (i & 2)
  370. aabb.position.y += aabb.size.y;
  371. if (i & 4)
  372. aabb.position.z += aabb.size.z;
  373. if (aabb.intersects_inclusive(p_element->aabb)) {
  374. /* if actually intersects, create the child */
  375. Octant *child = memnew_allocator(Octant, AL);
  376. p_octant->children[i] = child;
  377. child->parent = p_octant;
  378. child->parent_index = i;
  379. child->aabb = aabb;
  380. p_octant->children_count++;
  381. _insert_element(p_element, child);
  382. octant_count++;
  383. splits++;
  384. }
  385. }
  386. }
  387. if (candidate && splits > 1) {
  388. p_element->common_parent = p_octant;
  389. }
  390. }
  391. if (use_pairs) {
  392. typename List<Element *, AL>::Element *E = p_octant->pairable_elements.front();
  393. while (E) {
  394. _pair_reference(p_element, E->get());
  395. E = E->next();
  396. }
  397. if (p_element->pairable) {
  398. // and always test non-pairable if element is pairable
  399. E = p_octant->elements.front();
  400. while (E) {
  401. _pair_reference(p_element, E->get());
  402. E = E->next();
  403. }
  404. }
  405. }
  406. }
  407. template <class T, bool use_pairs, class AL>
  408. void Octree<T, use_pairs, AL>::_ensure_valid_root(const AABB &p_aabb) {
  409. if (!root) {
  410. // octre is empty
  411. AABB base(Vector3(), Vector3(1.0, 1.0, 1.0) * unit_size);
  412. while (!base.encloses(p_aabb)) {
  413. if (ABS(base.position.x + base.size.x) <= ABS(base.position.x)) {
  414. /* grow towards positive */
  415. base.size *= 2.0;
  416. } else {
  417. base.position -= base.size;
  418. base.size *= 2.0;
  419. }
  420. }
  421. root = memnew_allocator(Octant, AL);
  422. root->parent = nullptr;
  423. root->parent_index = -1;
  424. root->aabb = base;
  425. octant_count++;
  426. } else {
  427. AABB base = root->aabb;
  428. while (!base.encloses(p_aabb)) {
  429. ERR_FAIL_COND_MSG(base.size.x > OCTREE_SIZE_LIMIT, "Octree upper size limit reached, does the AABB supplied contain NAN?");
  430. Octant *gp = memnew_allocator(Octant, AL);
  431. octant_count++;
  432. root->parent = gp;
  433. if (ABS(base.position.x + base.size.x) <= ABS(base.position.x)) {
  434. /* grow towards positive */
  435. base.size *= 2.0;
  436. gp->aabb = base;
  437. gp->children[0] = root;
  438. root->parent_index = 0;
  439. } else {
  440. base.position -= base.size;
  441. base.size *= 2.0;
  442. gp->aabb = base;
  443. gp->children[(1 << 0) | (1 << 1) | (1 << 2)] = root; // add at all-positive
  444. root->parent_index = (1 << 0) | (1 << 1) | (1 << 2);
  445. }
  446. gp->children_count = 1;
  447. root = gp;
  448. }
  449. }
  450. }
  451. template <class T, bool use_pairs, class AL>
  452. bool Octree<T, use_pairs, AL>::_remove_element_from_octant(Element *p_element, Octant *p_octant, Octant *p_limit) {
  453. bool octant_removed = false;
  454. while (true) {
  455. // check all exit conditions
  456. if (p_octant == p_limit) // reached limit, nothing to erase, exit
  457. return octant_removed;
  458. bool unpaired = false;
  459. if (use_pairs && p_octant->last_pass != pass) {
  460. // check whether we should unpair stuff
  461. // always test pairable
  462. typename List<Element *, AL>::Element *E = p_octant->pairable_elements.front();
  463. while (E) {
  464. _pair_unreference(p_element, E->get());
  465. E = E->next();
  466. }
  467. if (p_element->pairable) {
  468. // and always test non-pairable if element is pairable
  469. E = p_octant->elements.front();
  470. while (E) {
  471. _pair_unreference(p_element, E->get());
  472. E = E->next();
  473. }
  474. }
  475. p_octant->last_pass = pass;
  476. unpaired = true;
  477. }
  478. bool removed = false;
  479. Octant *parent = p_octant->parent;
  480. if (p_octant->children_count == 0 && p_octant->elements.empty() && p_octant->pairable_elements.empty()) {
  481. // erase octant
  482. if (p_octant == root) { // won't have a parent, just erase
  483. root = nullptr;
  484. } else {
  485. ERR_FAIL_INDEX_V(p_octant->parent_index, 8, octant_removed);
  486. parent->children[p_octant->parent_index] = nullptr;
  487. parent->children_count--;
  488. }
  489. memdelete_allocator<Octant, AL>(p_octant);
  490. octant_count--;
  491. removed = true;
  492. octant_removed = true;
  493. }
  494. if (!removed && !unpaired)
  495. return octant_removed; // no reason to keep going up anymore! was already visited and was not removed
  496. p_octant = parent;
  497. }
  498. return octant_removed;
  499. }
  500. template <class T, bool use_pairs, class AL>
  501. void Octree<T, use_pairs, AL>::_unpair_element(Element *p_element, Octant *p_octant) {
  502. // always test pairable
  503. typename List<Element *, AL>::Element *E = p_octant->pairable_elements.front();
  504. while (E) {
  505. if (E->get()->last_pass != pass) { // only remove ONE reference
  506. _pair_unreference(p_element, E->get());
  507. E->get()->last_pass = pass;
  508. }
  509. E = E->next();
  510. }
  511. if (p_element->pairable) {
  512. // and always test non-pairable if element is pairable
  513. E = p_octant->elements.front();
  514. while (E) {
  515. if (E->get()->last_pass != pass) { // only remove ONE reference
  516. _pair_unreference(p_element, E->get());
  517. E->get()->last_pass = pass;
  518. }
  519. E = E->next();
  520. }
  521. }
  522. p_octant->last_pass = pass;
  523. if (p_octant->children_count == 0)
  524. return; // small optimization for leafs
  525. for (int i = 0; i < 8; i++) {
  526. if (p_octant->children[i])
  527. _unpair_element(p_element, p_octant->children[i]);
  528. }
  529. }
  530. template <class T, bool use_pairs, class AL>
  531. void Octree<T, use_pairs, AL>::_pair_element(Element *p_element, Octant *p_octant) {
  532. // always test pairable
  533. typename List<Element *, AL>::Element *E = p_octant->pairable_elements.front();
  534. while (E) {
  535. if (E->get()->last_pass != pass) { // only get ONE reference
  536. _pair_reference(p_element, E->get());
  537. E->get()->last_pass = pass;
  538. }
  539. E = E->next();
  540. }
  541. if (p_element->pairable) {
  542. // and always test non-pairable if element is pairable
  543. E = p_octant->elements.front();
  544. while (E) {
  545. if (E->get()->last_pass != pass) { // only get ONE reference
  546. _pair_reference(p_element, E->get());
  547. E->get()->last_pass = pass;
  548. }
  549. E = E->next();
  550. }
  551. }
  552. p_octant->last_pass = pass;
  553. if (p_octant->children_count == 0)
  554. return; // small optimization for leafs
  555. for (int i = 0; i < 8; i++) {
  556. if (p_octant->children[i])
  557. _pair_element(p_element, p_octant->children[i]);
  558. }
  559. }
  560. template <class T, bool use_pairs, class AL>
  561. void Octree<T, use_pairs, AL>::_remove_element(Element *p_element) {
  562. pass++; // will do a new pass for this
  563. typename List<typename Element::OctantOwner, AL>::Element *I = p_element->octant_owners.front();
  564. /* FIRST remove going up normally */
  565. for (; I; I = I->next()) {
  566. Octant *o = I->get().octant;
  567. if (!use_pairs) // small speedup
  568. o->elements.erase(I->get().E);
  569. _remove_element_from_octant(p_element, o);
  570. }
  571. /* THEN remove going down */
  572. I = p_element->octant_owners.front();
  573. if (use_pairs) {
  574. for (; I; I = I->next()) {
  575. Octant *o = I->get().octant;
  576. // erase children pairs, they are erased ONCE even if repeated
  577. pass++;
  578. for (int i = 0; i < 8; i++) {
  579. if (o->children[i])
  580. _unpair_element(p_element, o->children[i]);
  581. }
  582. if (p_element->pairable)
  583. o->pairable_elements.erase(I->get().E);
  584. else
  585. o->elements.erase(I->get().E);
  586. }
  587. }
  588. p_element->octant_owners.clear();
  589. if (use_pairs) {
  590. int remaining = p_element->pair_list.size();
  591. //p_element->pair_list.clear();
  592. ERR_FAIL_COND(remaining);
  593. }
  594. }
  595. template <class T, bool use_pairs, class AL>
  596. OctreeElementID Octree<T, use_pairs, AL>::create(T *p_userdata, const AABB &p_aabb, int p_subindex, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask) {
  597. // check for AABB validity
  598. #ifdef DEBUG_ENABLED
  599. ERR_FAIL_COND_V(p_aabb.position.x > 1e15 || p_aabb.position.x < -1e15, 0);
  600. ERR_FAIL_COND_V(p_aabb.position.y > 1e15 || p_aabb.position.y < -1e15, 0);
  601. ERR_FAIL_COND_V(p_aabb.position.z > 1e15 || p_aabb.position.z < -1e15, 0);
  602. ERR_FAIL_COND_V(p_aabb.size.x > 1e15 || p_aabb.size.x < 0.0, 0);
  603. ERR_FAIL_COND_V(p_aabb.size.y > 1e15 || p_aabb.size.y < 0.0, 0);
  604. ERR_FAIL_COND_V(p_aabb.size.z > 1e15 || p_aabb.size.z < 0.0, 0);
  605. ERR_FAIL_COND_V(Math::is_nan(p_aabb.size.x), 0);
  606. ERR_FAIL_COND_V(Math::is_nan(p_aabb.size.y), 0);
  607. ERR_FAIL_COND_V(Math::is_nan(p_aabb.size.z), 0);
  608. #endif
  609. typename ElementMap::Element *E = element_map.insert(last_element_id++,
  610. Element());
  611. Element &e = E->get();
  612. e.aabb = p_aabb;
  613. e.userdata = p_userdata;
  614. e.subindex = p_subindex;
  615. e.last_pass = 0;
  616. e.octree = this;
  617. e.pairable = p_pairable;
  618. e.pairable_type = p_pairable_type;
  619. e.pairable_mask = p_pairable_mask;
  620. e._id = last_element_id - 1;
  621. if (!e.aabb.has_no_surface()) {
  622. _ensure_valid_root(p_aabb);
  623. _insert_element(&e, root);
  624. if (use_pairs)
  625. _element_check_pairs(&e);
  626. }
  627. return last_element_id - 1;
  628. }
  629. template <class T, bool use_pairs, class AL>
  630. void Octree<T, use_pairs, AL>::move(OctreeElementID p_id, const AABB &p_aabb) {
  631. #ifdef DEBUG_ENABLED
  632. // check for AABB validity
  633. ERR_FAIL_COND(p_aabb.position.x > 1e15 || p_aabb.position.x < -1e15);
  634. ERR_FAIL_COND(p_aabb.position.y > 1e15 || p_aabb.position.y < -1e15);
  635. ERR_FAIL_COND(p_aabb.position.z > 1e15 || p_aabb.position.z < -1e15);
  636. ERR_FAIL_COND(p_aabb.size.x > 1e15 || p_aabb.size.x < 0.0);
  637. ERR_FAIL_COND(p_aabb.size.y > 1e15 || p_aabb.size.y < 0.0);
  638. ERR_FAIL_COND(p_aabb.size.z > 1e15 || p_aabb.size.z < 0.0);
  639. ERR_FAIL_COND(Math::is_nan(p_aabb.size.x));
  640. ERR_FAIL_COND(Math::is_nan(p_aabb.size.y));
  641. ERR_FAIL_COND(Math::is_nan(p_aabb.size.z));
  642. #endif
  643. typename ElementMap::Element *E = element_map.find(p_id);
  644. ERR_FAIL_COND(!E);
  645. Element &e = E->get();
  646. bool old_has_surf = !e.aabb.has_no_surface();
  647. bool new_has_surf = !p_aabb.has_no_surface();
  648. if (old_has_surf != new_has_surf) {
  649. if (old_has_surf) {
  650. _remove_element(&e); // removing
  651. e.common_parent = nullptr;
  652. e.aabb = AABB();
  653. _optimize();
  654. } else {
  655. _ensure_valid_root(p_aabb); // inserting
  656. e.common_parent = nullptr;
  657. e.aabb = p_aabb;
  658. _insert_element(&e, root);
  659. if (use_pairs)
  660. _element_check_pairs(&e);
  661. }
  662. return;
  663. }
  664. if (!old_has_surf) // doing nothing
  665. return;
  666. // it still is enclosed in the same AABB it was assigned to
  667. if (e.container_aabb.encloses(p_aabb)) {
  668. e.aabb = p_aabb;
  669. if (use_pairs)
  670. _element_check_pairs(&e); // must check pairs anyway
  671. return;
  672. }
  673. AABB combined = e.aabb;
  674. combined.merge_with(p_aabb);
  675. _ensure_valid_root(combined);
  676. ERR_FAIL_COND(e.octant_owners.front() == nullptr);
  677. /* FIND COMMON PARENT */
  678. List<typename Element::OctantOwner, AL> owners = e.octant_owners; // save the octant owners
  679. Octant *common_parent = e.common_parent;
  680. ERR_FAIL_COND(!common_parent);
  681. //src is now the place towards where insertion is going to happen
  682. pass++;
  683. while (common_parent && !common_parent->aabb.encloses(p_aabb))
  684. common_parent = common_parent->parent;
  685. ERR_FAIL_COND(!common_parent);
  686. //prepare for reinsert
  687. e.octant_owners.clear();
  688. e.common_parent = nullptr;
  689. e.aabb = p_aabb;
  690. _insert_element(&e, common_parent); // reinsert from this point
  691. pass++;
  692. for (typename List<typename Element::OctantOwner, AL>::Element *F = owners.front(); F;) {
  693. Octant *o = F->get().octant;
  694. typename List<typename Element::OctantOwner, AL>::Element *N = F->next();
  695. /*
  696. if (!use_pairs)
  697. o->elements.erase( F->get().E );
  698. */
  699. if (use_pairs && e.pairable)
  700. o->pairable_elements.erase(F->get().E);
  701. else
  702. o->elements.erase(F->get().E);
  703. if (_remove_element_from_octant(&e, o, common_parent->parent)) {
  704. owners.erase(F);
  705. }
  706. F = N;
  707. }
  708. if (use_pairs) {
  709. //unpair child elements in anything that survived
  710. for (typename List<typename Element::OctantOwner, AL>::Element *F = owners.front(); F; F = F->next()) {
  711. Octant *o = F->get().octant;
  712. // erase children pairs, unref ONCE
  713. pass++;
  714. for (int i = 0; i < 8; i++) {
  715. if (o->children[i])
  716. _unpair_element(&e, o->children[i]);
  717. }
  718. }
  719. _element_check_pairs(&e);
  720. }
  721. _optimize();
  722. }
  723. template <class T, bool use_pairs, class AL>
  724. void Octree<T, use_pairs, AL>::set_pairable(OctreeElementID p_id, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask) {
  725. typename ElementMap::Element *E = element_map.find(p_id);
  726. ERR_FAIL_COND(!E);
  727. Element &e = E->get();
  728. if (p_pairable == e.pairable && e.pairable_type == p_pairable_type && e.pairable_mask == p_pairable_mask)
  729. return; // no changes, return
  730. if (!e.aabb.has_no_surface()) {
  731. _remove_element(&e);
  732. }
  733. e.pairable = p_pairable;
  734. e.pairable_type = p_pairable_type;
  735. e.pairable_mask = p_pairable_mask;
  736. e.common_parent = nullptr;
  737. if (!e.aabb.has_no_surface()) {
  738. _ensure_valid_root(e.aabb);
  739. _insert_element(&e, root);
  740. if (use_pairs)
  741. _element_check_pairs(&e);
  742. }
  743. }
  744. template <class T, bool use_pairs, class AL>
  745. void Octree<T, use_pairs, AL>::erase(OctreeElementID p_id) {
  746. typename ElementMap::Element *E = element_map.find(p_id);
  747. ERR_FAIL_COND(!E);
  748. Element &e = E->get();
  749. if (!e.aabb.has_no_surface()) {
  750. _remove_element(&e);
  751. }
  752. element_map.erase(p_id);
  753. _optimize();
  754. }
  755. template <class T, bool use_pairs, class AL>
  756. void Octree<T, use_pairs, AL>::_cull_convex(Octant *p_octant, _CullConvexData *p_cull) {
  757. if (*p_cull->result_idx == p_cull->result_max)
  758. return; //pointless
  759. if (!p_octant->elements.empty()) {
  760. typename List<Element *, AL>::Element *I;
  761. I = p_octant->elements.front();
  762. for (; I; I = I->next()) {
  763. Element *e = I->get();
  764. if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_cull->mask)))
  765. continue;
  766. e->last_pass = pass;
  767. if (e->aabb.intersects_convex_shape(p_cull->planes, p_cull->plane_count)) {
  768. if (*p_cull->result_idx < p_cull->result_max) {
  769. p_cull->result_array[*p_cull->result_idx] = e->userdata;
  770. (*p_cull->result_idx)++;
  771. } else {
  772. return; // pointless to continue
  773. }
  774. }
  775. }
  776. }
  777. if (use_pairs && !p_octant->pairable_elements.empty()) {
  778. typename List<Element *, AL>::Element *I;
  779. I = p_octant->pairable_elements.front();
  780. for (; I; I = I->next()) {
  781. Element *e = I->get();
  782. if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_cull->mask)))
  783. continue;
  784. e->last_pass = pass;
  785. if (e->aabb.intersects_convex_shape(p_cull->planes, p_cull->plane_count)) {
  786. if (*p_cull->result_idx < p_cull->result_max) {
  787. p_cull->result_array[*p_cull->result_idx] = e->userdata;
  788. (*p_cull->result_idx)++;
  789. } else {
  790. return; // pointless to continue
  791. }
  792. }
  793. }
  794. }
  795. for (int i = 0; i < 8; i++) {
  796. if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_convex_shape(p_cull->planes, p_cull->plane_count)) {
  797. _cull_convex(p_octant->children[i], p_cull);
  798. }
  799. }
  800. }
  801. template <class T, bool use_pairs, class AL>
  802. void Octree<T, use_pairs, AL>::_cull_aabb(Octant *p_octant, const AABB &p_aabb, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
  803. if (*p_result_idx == p_result_max)
  804. return; //pointless
  805. if (!p_octant->elements.empty()) {
  806. typename List<Element *, AL>::Element *I;
  807. I = p_octant->elements.front();
  808. for (; I; I = I->next()) {
  809. Element *e = I->get();
  810. if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask)))
  811. continue;
  812. e->last_pass = pass;
  813. if (p_aabb.intersects_inclusive(e->aabb)) {
  814. if (*p_result_idx < p_result_max) {
  815. p_result_array[*p_result_idx] = e->userdata;
  816. if (p_subindex_array)
  817. p_subindex_array[*p_result_idx] = e->subindex;
  818. (*p_result_idx)++;
  819. } else {
  820. return; // pointless to continue
  821. }
  822. }
  823. }
  824. }
  825. if (use_pairs && !p_octant->pairable_elements.empty()) {
  826. typename List<Element *, AL>::Element *I;
  827. I = p_octant->pairable_elements.front();
  828. for (; I; I = I->next()) {
  829. Element *e = I->get();
  830. if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask)))
  831. continue;
  832. e->last_pass = pass;
  833. if (p_aabb.intersects_inclusive(e->aabb)) {
  834. if (*p_result_idx < p_result_max) {
  835. p_result_array[*p_result_idx] = e->userdata;
  836. if (p_subindex_array)
  837. p_subindex_array[*p_result_idx] = e->subindex;
  838. (*p_result_idx)++;
  839. } else {
  840. return; // pointless to continue
  841. }
  842. }
  843. }
  844. }
  845. for (int i = 0; i < 8; i++) {
  846. if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_inclusive(p_aabb)) {
  847. _cull_aabb(p_octant->children[i], p_aabb, p_result_array, p_result_idx, p_result_max, p_subindex_array, p_mask);
  848. }
  849. }
  850. }
  851. template <class T, bool use_pairs, class AL>
  852. void Octree<T, use_pairs, AL>::_cull_segment(Octant *p_octant, const Vector3 &p_from, const Vector3 &p_to, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
  853. if (*p_result_idx == p_result_max)
  854. return; //pointless
  855. if (!p_octant->elements.empty()) {
  856. typename List<Element *, AL>::Element *I;
  857. I = p_octant->elements.front();
  858. for (; I; I = I->next()) {
  859. Element *e = I->get();
  860. if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask)))
  861. continue;
  862. e->last_pass = pass;
  863. if (e->aabb.intersects_segment(p_from, p_to)) {
  864. if (*p_result_idx < p_result_max) {
  865. p_result_array[*p_result_idx] = e->userdata;
  866. if (p_subindex_array)
  867. p_subindex_array[*p_result_idx] = e->subindex;
  868. (*p_result_idx)++;
  869. } else {
  870. return; // pointless to continue
  871. }
  872. }
  873. }
  874. }
  875. if (use_pairs && !p_octant->pairable_elements.empty()) {
  876. typename List<Element *, AL>::Element *I;
  877. I = p_octant->pairable_elements.front();
  878. for (; I; I = I->next()) {
  879. Element *e = I->get();
  880. if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask)))
  881. continue;
  882. e->last_pass = pass;
  883. if (e->aabb.intersects_segment(p_from, p_to)) {
  884. if (*p_result_idx < p_result_max) {
  885. p_result_array[*p_result_idx] = e->userdata;
  886. if (p_subindex_array)
  887. p_subindex_array[*p_result_idx] = e->subindex;
  888. (*p_result_idx)++;
  889. } else {
  890. return; // pointless to continue
  891. }
  892. }
  893. }
  894. }
  895. for (int i = 0; i < 8; i++) {
  896. if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_segment(p_from, p_to)) {
  897. _cull_segment(p_octant->children[i], p_from, p_to, p_result_array, p_result_idx, p_result_max, p_subindex_array, p_mask);
  898. }
  899. }
  900. }
  901. template <class T, bool use_pairs, class AL>
  902. void Octree<T, use_pairs, AL>::_cull_point(Octant *p_octant, const Vector3 &p_point, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
  903. if (*p_result_idx == p_result_max)
  904. return; //pointless
  905. if (!p_octant->elements.empty()) {
  906. typename List<Element *, AL>::Element *I;
  907. I = p_octant->elements.front();
  908. for (; I; I = I->next()) {
  909. Element *e = I->get();
  910. if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask)))
  911. continue;
  912. e->last_pass = pass;
  913. if (e->aabb.has_point(p_point)) {
  914. if (*p_result_idx < p_result_max) {
  915. p_result_array[*p_result_idx] = e->userdata;
  916. if (p_subindex_array)
  917. p_subindex_array[*p_result_idx] = e->subindex;
  918. (*p_result_idx)++;
  919. } else {
  920. return; // pointless to continue
  921. }
  922. }
  923. }
  924. }
  925. if (use_pairs && !p_octant->pairable_elements.empty()) {
  926. typename List<Element *, AL>::Element *I;
  927. I = p_octant->pairable_elements.front();
  928. for (; I; I = I->next()) {
  929. Element *e = I->get();
  930. if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask)))
  931. continue;
  932. e->last_pass = pass;
  933. if (e->aabb.has_point(p_point)) {
  934. if (*p_result_idx < p_result_max) {
  935. p_result_array[*p_result_idx] = e->userdata;
  936. if (p_subindex_array)
  937. p_subindex_array[*p_result_idx] = e->subindex;
  938. (*p_result_idx)++;
  939. } else {
  940. return; // pointless to continue
  941. }
  942. }
  943. }
  944. }
  945. for (int i = 0; i < 8; i++) {
  946. //could be optimized..
  947. if (p_octant->children[i] && p_octant->children[i]->aabb.has_point(p_point)) {
  948. _cull_point(p_octant->children[i], p_point, p_result_array, p_result_idx, p_result_max, p_subindex_array, p_mask);
  949. }
  950. }
  951. }
  952. template <class T, bool use_pairs, class AL>
  953. int Octree<T, use_pairs, AL>::cull_convex(const Vector<Plane> &p_convex, T **p_result_array, int p_result_max, uint32_t p_mask) {
  954. if (!root)
  955. return 0;
  956. int result_count = 0;
  957. pass++;
  958. _CullConvexData cdata;
  959. cdata.planes = &p_convex[0];
  960. cdata.plane_count = p_convex.size();
  961. cdata.result_array = p_result_array;
  962. cdata.result_max = p_result_max;
  963. cdata.result_idx = &result_count;
  964. cdata.mask = p_mask;
  965. _cull_convex(root, &cdata);
  966. return result_count;
  967. }
  968. template <class T, bool use_pairs, class AL>
  969. int Octree<T, use_pairs, AL>::cull_aabb(const AABB &p_aabb, T **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
  970. if (!root)
  971. return 0;
  972. int result_count = 0;
  973. pass++;
  974. _cull_aabb(root, p_aabb, p_result_array, &result_count, p_result_max, p_subindex_array, p_mask);
  975. return result_count;
  976. }
  977. template <class T, bool use_pairs, class AL>
  978. int Octree<T, use_pairs, AL>::cull_segment(const Vector3 &p_from, const Vector3 &p_to, T **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
  979. if (!root)
  980. return 0;
  981. int result_count = 0;
  982. pass++;
  983. _cull_segment(root, p_from, p_to, p_result_array, &result_count, p_result_max, p_subindex_array, p_mask);
  984. return result_count;
  985. }
  986. template <class T, bool use_pairs, class AL>
  987. int Octree<T, use_pairs, AL>::cull_point(const Vector3 &p_point, T **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
  988. if (!root)
  989. return 0;
  990. int result_count = 0;
  991. pass++;
  992. _cull_point(root, p_point, p_result_array, &result_count, p_result_max, p_subindex_array, p_mask);
  993. return result_count;
  994. }
  995. template <class T, bool use_pairs, class AL>
  996. void Octree<T, use_pairs, AL>::set_pair_callback(PairCallback p_callback, void *p_userdata) {
  997. pair_callback = p_callback;
  998. pair_callback_userdata = p_userdata;
  999. }
  1000. template <class T, bool use_pairs, class AL>
  1001. void Octree<T, use_pairs, AL>::set_unpair_callback(UnpairCallback p_callback, void *p_userdata) {
  1002. unpair_callback = p_callback;
  1003. unpair_callback_userdata = p_userdata;
  1004. }
  1005. template <class T, bool use_pairs, class AL>
  1006. Octree<T, use_pairs, AL>::Octree(real_t p_unit_size) {
  1007. last_element_id = 1;
  1008. pass = 1;
  1009. unit_size = p_unit_size;
  1010. root = nullptr;
  1011. octant_count = 0;
  1012. pair_count = 0;
  1013. pair_callback = nullptr;
  1014. unpair_callback = nullptr;
  1015. pair_callback_userdata = nullptr;
  1016. unpair_callback_userdata = nullptr;
  1017. }
  1018. #endif // OCTREE_H