-
Notifications
You must be signed in to change notification settings - Fork 3
/
abby.hpp
1584 lines (1362 loc) · 42.3 KB
/
abby.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* MIT License
*
* Copyright (c) 2019-2020 Albin Johansson: adapted and improved source code
* from the AABBCC library.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* This codebase was mainly based on the AABBCC library, written by Lester
* Hedges, which uses the Zlib license: https://github.com/lohedges/aabbcc.
* Furthermore, the AABB tree implementation in the Simple Voxel Engine project
* also influenced this library, which uses the MIT license:
* https://github.com/JamesRandall/SimpleVoxelEngine.
*/
#pragma once
#include <algorithm> // min, max, clamp
#include <array> // array
#include <cassert> // assert
#include <cmath> // abs
#include <cstddef> // byte
#include <deque> // deque
#include <limits> // numeric_limits
#include <memory_resource> // monotonic_buffer_resource
#include <optional> // optional
#include <ostream> // ostream
#include <stack> // stack
#include <stdexcept> // invalid_argument
#include <string> // string
#include <unordered_map> // unordered_map
#include <vector> // vector
namespace abby {
using maybe_index = std::optional<std::size_t>;
/**
* \struct vector2
*
* \brief A simple two-dimensional vector.
*
* \tparam T the representation type.
*
* \since 0.1.0
*
* \headerfile abby.hpp
*/
template <typename T>
struct vector2 final
{
T x{}; ///< The x-coordinate.
T y{}; ///< The y-coordinate.
[[deprecated]] auto operator[](std::size_t index) -> T&
{
if (index == 0) {
return x;
} else if (index == 1) {
return y;
} else {
throw std::invalid_argument{"vector2: bad subscript index!"};
}
}
[[deprecated]] auto operator[](std::size_t index) const -> const T&
{
if (index == 0) {
return x;
} else if (index == 1) {
return y;
} else {
throw std::invalid_argument{"vector2: bad subscript index!"};
}
}
};
// clang-format off
template <typename T> vector2(T, T) -> vector2<T>;
// clang-format on
/**
* \brief Adds two vectors and returns the result.
*
* \tparam T the representation type used by the vectors.
*
* \param lhs the left-hand side vector.
* \param rhs the right-hand side vector.
*
* \return a vector that is the result of adding the components of the two
* vectors.
*
* \since 0.1.0
*/
template <typename T>
[[nodiscard]] constexpr auto operator+(const vector2<T>& lhs,
const vector2<T>& rhs) noexcept
-> vector2<T>
{
return {lhs.x + rhs.x, lhs.y + rhs.y};
}
/**
* \brief Subtracts two vectors and returns the result.
*
* \tparam T the representation type used by the vectors.
*
* \param lhs the left-hand side vector.
* \param rhs the right-hand side vector.
*
* \return a vector that is the result of subtracting the components of the two
* vectors.
*
* \since 0.1.0
*/
template <typename T>
[[nodiscard]] constexpr auto operator-(const vector2<T>& lhs,
const vector2<T>& rhs) noexcept
-> vector2<T>
{
return {lhs.x - rhs.x, lhs.y - rhs.y};
}
/**
* \brief Indicates whether or not two vectors are equal.
*
* \tparam T the representation type used by the vectors.
*
* \param lhs the left-hand side vector.
* \param rhs the right-hand side vector.
*
* \return `true` if the two vectors are equal; `false` otherwise.
*
* \since 0.1.0
*/
template <typename T>
[[nodiscard]] constexpr auto operator==(const vector2<T>& lhs,
const vector2<T>& rhs) noexcept -> bool
{
return (lhs.x == rhs.x) && (lhs.y == rhs.y);
}
/**
* \brief Indicates whether or not two vectors aren't equal.
*
* \tparam T the representation type used by the vectors.
*
* \param lhs the left-hand side vector.
* \param rhs the right-hand side vector.
*
* \return `true` if the two vectors aren't equal; `false` otherwise.
*
* \since 0.1.0
*/
template <typename T>
[[nodiscard]] constexpr auto operator!=(const vector2<T>& lhs,
const vector2<T>& rhs) noexcept -> bool
{
return !(lhs == rhs);
}
/**
* \class aabb
*
* \brief Represents an AABB (Axis-Aligned Bounding Box).
*
* \note This is really just a glorified rectangle.
*
* \tparam T the representation type used by the aabb, e.g. `float` or `double`.
*
* \since 0.1.0
*/
template <typename T>
class aabb final
{
public:
using value_type = T;
using vector_type = vector2<value_type>;
[[deprecated]] constexpr aabb() noexcept = default;
/**
* \brief Creates an AABB.
*
* \param min the lower bounds of the AABB.
* \param max the upper bounds of the AABB.
*
* \throws invalid_argument if `min` is greater than `max`.
*
* \since 0.1.0
*/
constexpr aabb(const vector_type& min, const vector_type& max)
: m_min{min},
m_max{max},
m_area{compute_area()}
{
if ((m_min.x > m_max.x) || (m_min.y > m_max.y)) {
throw std::invalid_argument("AABB: min > max");
}
}
/**
* \brief Updates the stored area.
*
* \since 0.2.0
*/
constexpr void update_area() noexcept
{
m_area = compute_area();
}
/**
* \brief Fattens the AABB by increasing its size.
*
* \note This function has no effect if the supplied value is `std::nullopt`.
*
* \param factor the fattening factor to use.
*
* \since 0.2.0
*/
constexpr void fatten(const std::optional<double> factor)
{
if (!factor) {
return;
}
const auto size = m_max - m_min;
const auto dx = *factor * size.x;
const auto dy = *factor * size.y;
m_min.x -= dx;
m_min.y -= dy;
m_max.x += dx;
m_max.y += dy;
m_area = compute_area();
// vector_type size; // AABB size in each dimension.
//
// // Compute the AABB limits.
// for (auto i = 0; i < 2; ++i) {
// // Validate the bound.
// if (m_min[i] > m_max[i]) {
// throw std::invalid_argument("aabb: lower bound > upper bound!");
// }
//
// node.aabb.m_min[i] = lowerBound[i];
// node.aabb.m_max[i] = upperBound[i];
// size[i] = upperBound[i] - lowerBound[i];
// }
//
// // Fatten the AABB.
// for (auto i = 0; i < 2; ++i) {
// node.aabb.m_min[i] -= (m_skinThickness * size[i]);
// node.aabb.m_max[i] += (m_skinThickness * size[i]);
// }
}
/**
* \brief Returns an AABB that is the union of the supplied pair of AABBs.
*
* \param fst the first AABB.
* \param snd the second AABB.
*
* \return an AABB that is the union of the two supplied AABBs.
*
* \since 0.1.0
*/
[[nodiscard]] static auto merge(const aabb& fst, const aabb& snd) -> aabb
{
vector_type lower;
vector_type upper;
for (auto i = 0; i < 2; ++i) {
lower[i] = std::min(fst.m_min[i], snd.m_min[i]);
upper[i] = std::max(fst.m_max[i], snd.m_max[i]);
}
return aabb{lower, upper};
}
/**
* \brief Indicates whether or not the supplied AABB is contained within the
* invoked AABB.
*
* \note The supplied AABB is still considered to be contained within the
* invoked AABB if the borders of the inner AABB are overlapping the borders
* of the outer AABB.
*
* \param other the AABB to check.
*
* \return `true` if the supplied AABB is contained in the AABB; `false`
* otherwise.
*
* \since 0.1.0
*/
[[nodiscard]] constexpr auto contains(const aabb& other) const noexcept
-> bool
{
for (auto i = 0; i < 2; ++i) {
if (other.m_min[i] < m_min[i]) {
return false;
}
if (other.m_max[i] > m_max[i]) {
return false;
}
}
return true;
}
/**
* \brief Indicates whether or not two AABBs are overlapping each other.
*
* \param other the other AABB to compare with.
* \param touchIsOverlap `true` if the AABBs are considered to be overlapping
* if they touch; `false` otherwise.
*
* \return `true` if the two AABBs are overlapping each other; `false`
* otherwise.
*
* \since 0.1.0
*/
[[nodiscard]] constexpr auto overlaps(const aabb& other,
bool touchIsOverlap) const noexcept
-> bool
{
if (touchIsOverlap) {
for (auto i = 0; i < 2; ++i) {
if (other.m_max[i] < m_min[i] || other.m_min[i] > m_max[i]) {
return false;
}
}
} else {
for (auto i = 0; i < 2; ++i) {
if (other.m_max[i] <= m_min[i] || other.m_min[i] >= m_max[i]) {
return false;
}
}
}
return true;
}
/**
* \brief Computes and returns the area of the AABB.
*
* \return the computed area of the AABB.
*
* \since 0.2.0
*/
[[nodiscard]] constexpr auto compute_area() const noexcept -> double
{
// Sum of "area" of all the sides.
auto sum = 0.0;
// hold one dimension constant and multiply by all the other ones.
for (auto d1 = 0; d1 < 2; ++d1) {
auto product = 1.0; // "Area" of current side.
for (auto d2 = 0; d2 < 2; ++d2) {
if (d1 != d2) {
const auto dx = m_max[d2] - m_min[d2];
product *= dx;
}
}
sum += product;
}
return 2.0 * sum;
}
/**
* \brief Returns the stored area of the AABB.
*
* \return the stored area of the AABB.
*
* \since 0.2.0
*/
[[nodiscard]] constexpr auto area() const noexcept -> double
{
return m_area;
}
/**
* \brief Returns the size of the AABB.
*
* \return the size of the AABB (width and height).
*
* \since 0.2.0
*/
[[nodiscard]] constexpr auto size() const noexcept -> vector_type
{
return m_max - m_min;
}
[[nodiscard]] constexpr auto min() const noexcept -> const vector_type&
{
return m_min;
}
[[nodiscard]] constexpr auto max() const noexcept -> const vector_type&
{
return m_max;
}
private:
vector_type m_min;
vector_type m_max;
double m_area{};
};
// clang-format off
template <typename T> aabb(vector2<T>, vector2<T>) -> aabb<T>;
// clang-format on
/**
* \brief Indicates whether or not two AABBs are equal.
*
* \tparam T the representation type used by the AABBs.
*
* \param lhs the left-hand side AABB.
* \param rhs the right-hand side AABB.
*
* \return `true` if the two AABBs are equal; `false` otherwise.
*
* \since 0.1.0
*/
template <typename T>
[[nodiscard]] constexpr auto operator==(const aabb<T>& lhs,
const aabb<T>& rhs) noexcept -> bool
{
return (lhs.min() == rhs.min()) && (lhs.max() == rhs.max());
}
/**
* \brief Indicates whether or not two AABBs aren't equal.
*
* \tparam T the representation type used by the AABBs.
*
* \param lhs the left-hand side AABB.
* \param rhs the right-hand side AABB.
*
* \return `true` if the two AABBs aren't equal; `false` otherwise.
*
* \since 0.1.0
*/
template <typename T>
[[nodiscard]] constexpr auto operator!=(const aabb<T>& lhs,
const aabb<T>& rhs) noexcept -> bool
{
return !(lhs == rhs);
}
/**
* \struct node
*
* \brief Represents a node in an AABB tree.
*
* \details Contains an AABB and the entity associated with the AABB, along
* with tree information.
*
* \tparam Key the type of the keys associated with each node.
* \tparam T the representation type used by the AABBs.
*
* \since 0.1.0
*
* \headerfile abby.hpp
*/
template <typename Key, typename T>
struct node final
{
using key_type = Key;
using aabb_type = aabb<T>;
std::optional<key_type> id;
aabb_type aabb;
maybe_index parent;
maybe_index left;
maybe_index right;
maybe_index next;
int height{-1};
[[nodiscard]] auto is_leaf() const noexcept -> bool
{
return left == std::nullopt;
}
};
/**
* \class tree
*
* \brief Represents a tree of AABBs used for efficient collision detection.
*
* \tparam Key the type of the keys associated with each node. Must be
* comparable and preferably small and cheap to copy type, e.g. `int`.
* \tparam T the representation type used by the AABBs, should be a
* floating-point type for best precision.
*
* \since 0.1.0
*
* \headerfile abby.hpp
*/
template <typename Key, typename T = double>
class tree final
{
template <typename U>
using pmr_stack = std::stack<U, std::pmr::deque<U>>;
public:
using value_type = T;
using key_type = Key;
using vector_type = vector2<value_type>;
using aabb_type = aabb<value_type>;
using node_type = node<key_type, value_type>;
using size_type = std::size_t;
using index_type = size_type;
/**
* \brief Creates an AABB tree.
*
* \param capacity the initial node capacity of the tree.
*
* \since 0.1.0
*/
explicit tree(const size_type capacity = 16) : m_nodeCapacity{capacity}
{
assert(m_root == std::nullopt);
assert(m_nodeCount == 0);
assert(m_nodeCapacity == capacity);
resize_to_match_node_capacity(0);
assert(m_nextFreeIndex == 0);
}
/**
* \brief Inserts an AABB in the tree.
*
* \pre `key` cannot be in use at the time of invoking this function.
*
* \param key the ID that will be associated with the box.
* \param lowerBound the lower-bound position of the AABB (i.e. the position).
* \param upperBound the upper-bound position of the AABB.
*
* \since 0.1.0
*/
void insert(const key_type& key,
const vector_type& lowerBound,
const vector_type& upperBound)
{
// Make sure the particle doesn't already exist
assert(!m_indexMap.count(key));
// Allocate a new node for the particle
const auto nodeIndex = allocate_node();
auto& node = m_nodes.at(nodeIndex);
node.id = key;
node.aabb = {lowerBound, upperBound};
node.aabb.fatten(m_skinThickness);
node.height = 0;
// node.aabb.m_area = node.aabb.compute_area();
// m_nodes[node].aabb.m_centre = m_nodes[node].aabb.computeCentre();
insert_leaf(nodeIndex);
m_indexMap.emplace(key, nodeIndex);
#ifndef NDEBUG
validate();
#endif
}
/**
* \brief Removes the AABB associated with the specified ID.
*
* \note This function has no effect if there is no AABB associated with the
* specified ID.
*
* \param key the ID associated with the AABB that will be removed.
*
* \since 0.1.0
*/
void erase(const key_type& key)
{
if (const auto it = m_indexMap.find(key); it != m_indexMap.end()) {
const auto node = it->second; // Extract the node index.
m_indexMap.erase(it);
assert(node < m_nodeCapacity);
assert(m_nodes.at(node).is_leaf());
remove_leaf(node);
free_node(node);
#ifndef NDEBUG
validate();
#endif
}
}
/**
* \brief Clears the tree of all entries.
*
* \since 0.2.0
*/
void clear()
{
// Iterator pointing to the start of the particle map.
auto it = m_indexMap.begin();
// Iterate over the map.
while (it != m_indexMap.end()) {
// Extract the node index.
const auto nodeIndex = it->second;
assert(nodeIndex < m_nodeCapacity);
assert(m_nodes.at(nodeIndex).is_leaf());
remove_leaf(nodeIndex);
free_node(nodeIndex);
++it;
}
// Clear the particle map.
m_indexMap.clear();
#ifndef NDEBUG
validate();
#endif
}
/**
* \brief Prints a textual representation of the tree.
*
* \param stream the stream used to print the tree, e.g. `std::cout`,
* `std::clog` or `std::cerr`.
*
* \since 0.2.0
*/
void print(std::ostream& stream) const
{
stream << "abby::tree\n";
print(stream, "", m_root, false);
}
/**
* \brief Updates the AABB associated with the specified ID.
*
* \note This function has no effect if there is no AABB associated with the
* specified ID.
*
* \param key the ID associated with the AABB that will be replaced.
* \param box the new AABB that will be associated with the specified ID.
* \param forceReinsert indicates whether or not the AABB is always
* reinserted, which wont happen if this is set to `true` and the new AABB is
* within the old AABB.
*
* \return `true` if an AABB was updated; `false` otherwise.
*
* \since 0.1.0
*/
auto update(const key_type& key, aabb_type aabb, bool forceReinsert = false)
-> bool
{
if (const auto it = m_indexMap.find(key); it != m_indexMap.end()) {
const auto nodeIndex = it->second; // Extract the node index.
assert(nodeIndex < m_nodeCapacity);
assert(m_nodes.at(nodeIndex).is_leaf());
// No need to update if the particle is still within its fattened AABB.
if (!forceReinsert && m_nodes.at(nodeIndex).aabb.contains(aabb)) {
return false;
}
// Remove the current leaf.
remove_leaf(nodeIndex);
aabb.fatten(m_skinThickness);
auto& node = m_nodes.at(nodeIndex);
node.aabb = aabb;
node.aabb.update_area();
// node.aabb.m_area = aabb.compute_area();
// m_nodes[node].aabb.m_centre = m_nodes[node].aabb.computeCentre();
insert_leaf(nodeIndex);
#ifndef NDEBUG
validate();
#endif
return true;
} else {
return false;
}
}
auto update(const key_type& key,
const vector_type& lowerBound,
const vector_type& upperBound,
bool forceReinsert = false) -> bool
{
return update(key, {lowerBound, upperBound}, forceReinsert);
}
/**
* \brief Updates the position of the AABB associated with the specified ID.
*
* \note This function has no effect if there is no AABB associated with the
* specified ID.
*
* \param key the ID associated with the AABB that will be moved.
* \param position the new position of the AABB associated with the specified
* ID.
* \param forceReinsert `true` if the associated AABB is forced to be
* reinserted into the tree.
*
* \return `true` if an AABB was updated; `false` otherwise.
*
* \since 0.1.0
*/
auto relocate(const key_type& key,
const vector_type& position,
bool forceReinsert = false) -> bool
{
if (const auto it = m_indexMap.find(key); it != m_indexMap.end()) {
const auto& aabb = m_nodes.at(it->second).aabb;
return update(key, {position, position + aabb.size()}, forceReinsert);
} else {
return false;
}
}
/// Rebuild an optimal tree.
void rebuild()
{
std::vector<index_type> nodeIndices(m_nodeCount);
int count{0};
for (auto index = 0; index < m_nodeCapacity; ++index) {
if (m_nodes.at(index).height < 0) { // Free node.
continue;
}
if (m_nodes.at(index).is_leaf()) {
m_nodes.at(index).parent = std::nullopt;
nodeIndices.at(count) = index;
++count;
} else {
free_node(index);
}
}
while (count > 1) {
auto minCost = std::numeric_limits<double>::max();
int iMin{-1};
int jMin{-1};
for (auto i = 0; i < count; ++i) {
const auto fstAabb = m_nodes.at(nodeIndices.at(i)).aabb;
for (auto j = (i + 1); j < count; ++j) {
const auto sndAabb = m_nodes.at(nodeIndices.at(j)).aabb;
const auto cost = aabb_type::merge(fstAabb, sndAabb).area();
if (cost < minCost) {
iMin = i;
jMin = j;
minCost = cost;
}
}
}
const auto index1 = nodeIndices.at(iMin);
const auto index2 = nodeIndices.at(jMin);
const auto parentIndex = allocate_node();
auto& parentNode = m_nodes.at(parentIndex);
auto& index1Node = m_nodes.at(index1);
auto& index2Node = m_nodes.at(index2);
parentNode.left = index1;
parentNode.right = index2;
parentNode.height = 1 + std::max(index1Node.height, index2Node.height);
parentNode.aabb = aabb_type::merge(index1Node.aabb, index2Node.aabb);
parentNode.parent = std::nullopt;
index1Node.parent = parentIndex;
index2Node.parent = parentIndex;
nodeIndices.at(jMin) = nodeIndices.at(count - 1);
nodeIndices.at(iMin) = parentIndex;
--count;
}
m_root = nodeIndices.at(0);
#ifndef NDEBUG
validate();
#endif
}
void set_thickness_factor(std::optional<double> thicknessFactor)
{
if (thicknessFactor) {
m_skinThickness = std::clamp(*thicknessFactor, 0.0, *thicknessFactor);
} else {
m_skinThickness = std::nullopt;
}
}
/**
* \brief Obtains collision candidates for the AABB associated with the
* specified ID.
*
* \details In order to avoid unnecessary dynamic allocations, this function
* returns the resulting collision candidates through an output iterator. This
* means that it is possible to write collision candidates to both a stack
* buffer and something like a `std::vector`.
*
* \details The output iterator can for instance be obtained using
* `std::back_inserter`, if you're writing to a standard container.
*
* \note This function has no effect if the supplied key is unknown.
*
* \tparam bufferSize the size of the initial stack buffer.
* \tparam OutputIterator the type of the output iterator.
*
* \param key the ID associated with the AABB to obtain collision candidates
* for.
* \param[out] iterator the output iterator used to write the collision
* candidate IDs.
*
* \since 0.1.0
*/
template <size_type bufferSize = 256, typename OutputIterator>
void query(const key_type& key, OutputIterator iterator) const
{
if (const auto it = m_indexMap.find(key); it != m_indexMap.end()) {
const auto& sourceNode = m_nodes.at(it->second);
std::array<std::byte, sizeof(maybe_index) * bufferSize> buffer;
std::pmr::monotonic_buffer_resource resource{buffer.data(),
sizeof buffer};
pmr_stack<maybe_index> stack{&resource};
stack.push(m_root);
while (!stack.empty()) {
const auto nodeIndex = stack.top();
stack.pop();
if (!nodeIndex) {
continue;
}
const auto& node = m_nodes.at(*nodeIndex);
// Test for overlap between the AABBs
if (sourceNode.aabb.overlaps(node.aabb, m_touchIsOverlap)) {
if (node.is_leaf() && node.id) {
if (node.id != key) { // Can't interact with itself
*iterator = *node.id;
++iterator;
}
} else {
stack.push(node.left);
stack.push(node.right);
}
}
}
}
}
[[nodiscard]] auto compute_maximum_balance() const -> size_type
{
size_type maxBalance{0};
for (auto i = 0; i < m_nodeCapacity; ++i) {
// if (node.height <= 1) {
// continue;
// }
const auto& node = m_nodes.at(i);
if (node.height > 2) {
assert(!node.is_leaf());
assert(node.left != std::nullopt);
assert(node.right != std::nullopt);
const auto balance = std::abs(m_nodes.at(*node.left).height -
m_nodes.at(*node.right).height);
maxBalance = std::max(maxBalance, balance);
}
}
return maxBalance;
}
[[nodiscard]] auto compute_surface_area_ratio() const -> double
{
if (m_root == std::nullopt) {
return 0;
}
const auto rootArea = m_nodes.at(*m_root).aabb.compute_area();
double totalArea{};
for (auto i = 0; i < m_nodeCapacity; ++i) {
const auto& node = m_nodes.at(i);
if (node.height < 0) {
continue;
}
totalArea += node.aabb.compute_area();
}
return totalArea / rootArea;
}
/**
* \brief Returns the AABB associated with the specified ID.
*
* \param key the ID associated with the desired AABB.
*
* \return the AABB associated with the specified ID.
*
* \throws if there is no AABB associated with the supplied ID.
*
* \since 0.1.0
*/
[[nodiscard]] auto get_aabb(const key_type& key) const -> const aabb_type&
{
return m_nodes.at(m_indexMap.at(key)).aabb;
}
/**
* \brief Returns the current height of the tree.
*
* \return the height of the tree.
*
* \since 0.2.0
*/
[[nodiscard]] auto height() const -> int
{
if (m_root == std::nullopt) {
return 0;
} else {
return m_nodes.at(*m_root).height;
}
}
/**
* \brief Returns the number of nodes in the tree.
*
* \return the amount of nodes in the tree.
*
* \since 0.2.0
*/
[[nodiscard]] auto node_count() const noexcept -> size_type
{
return m_nodeCount;
}
/**
* \brief Returns the amount of AABBs stored in the tree.
*
* \note The returned value is not necessarily the amount of _nodes_ in the
* tree.
*
* \return the current amount of AABBs stored in the tree.
*
* \since 0.1.0
*/
[[nodiscard]] auto size() const noexcept -> size_type
{
return m_indexMap.size();
}
/**
* \brief Indicates whether or not the tree is empty.
*
* \return `true` if there are no AABBs stored in the tree; `false` otherwise.
*
* \since 0.1.0
*/