octree.h 35 KB

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