4#ifndef GREM_CORE_DATA_LINEAR_BOUNDING_VOLUME_HIERARCHY_HPP
5#define GREM_CORE_DATA_LINEAR_BOUNDING_VOLUME_HIERARCHY_HPP
37template <
size_t N,
typename Scalar,
typename T>
40 static_assert(N == 2 || N == 3);
63 dirty = dirty || !elements.empty();
75 return std::launder(
reinterpret_cast<pointer>(elements.data()));
86 return std::launder(
reinterpret_cast<const_pointer>(elements.data()));
108 return begin() + elements.size();
119 return begin() + elements.size();
139 return elements.size();
147 [[nodiscard]]
bool empty() const noexcept {
169 template <
typename... Args>
171 if (elements.size() >=
static_cast<size_t>(INVALID_ELEMENT)) {
172 throw std::length_error{
"Maximum element count exceeded."};
174 value_type& element = elements.emplace_back(std::piecewise_construct, std::forward_as_tuple(elementBoundingBox), std::forward_as_tuple(std::forward<Args>(args)...));
176 return std::launder(
reinterpret_cast<pointer>(&element));
198 return emplace(elementBoundingBox, value);
220 return emplace(elementBoundingBox, std::move(value));
232 elements.erase(elements.begin() + (pos -
cbegin()));
281 template <
typename Callback,
typename Predicate>
283 return traverseNodesImplementation(
284 [
this, callback = std::forward<Callback>(callback)](
const Node& node)
mutable {
285 const T*
const element = (node.elementIndex == INVALID_ELEMENT) ?
nullptr : &elements[node.elementIndex].second;
286 constexpr bool CALLBACK_RETURNS_BOOL = std::is_convertible_v<
decltype(callback(node.boundingBox, element)),
bool>;
287 if constexpr (CALLBACK_RETURNS_BOOL) {
288 return callback(node.boundingBox, element);
290 callback(node.boundingBox, element);
293 std::forward<Predicate>(predicate));
333 template <
typename Callback>
379 template <
typename Callback,
typename Predicate>
381 return traverseNodesImplementation(
382 [
this, callback = std::forward<Callback>(callback)](
const Node& node)
mutable {
383 constexpr bool CALLBACK_RETURNS_BOOL = std::is_convertible_v<
decltype(callback(elements[node.elementIndex].second)),
bool>;
384 if (node.elementIndex != INVALID_ELEMENT) {
385 if constexpr (CALLBACK_RETURNS_BOOL) {
386 if (callback(elements[node.elementIndex].second)) {
390 callback(elements[node.elementIndex].second);
393 if constexpr (CALLBACK_RETURNS_BOOL) {
397 std::forward<Predicate>(predicate));
432 template <
typename Callback>
471 template <
typename Callback>
496 return traverseElements([](
const T&) ->
bool {
return true; }, [&point](
const Box<N, Scalar>& boundingBox) ->
bool {
return boundingBox.contains(point); });
533 template <
typename Callback>
563 using NodeIndex = uint32_t;
564 using ElementIndex = uint32_t;
570 NodeIndex firstChildIndex = INVALID_NODE;
571 NodeIndex secondChildIndex = INVALID_NODE;
572 ElementIndex elementIndex = INVALID_ELEMENT;
576 [[nodiscard]]
static uint32_t separateMortonCodeBits(uint32_t x)
noexcept {
577 if constexpr (
N == 2) {
578 x = (x ^ (x << 8)) & 0b00000000111111110000000011111111;
579 x = (x ^ (x << 4)) & 0b00001111000011110000111100001111;
580 x = (x ^ (x << 2)) & 0b00110011001100110011001100110011;
581 x = (x ^ (x << 1)) & 0b01010101010101010101010101010101;
582 }
else if constexpr (
N == 3) {
583 x = (x ^ (x << 16)) & 0b11111111000000000000000011111111;
584 x = (x ^ (x << 8)) & 0b00001111000000001111000000001111;
585 x = (x ^ (x << 4)) & 0b11000011000011000011000011000011;
586 x = (x ^ (x << 2)) & 0b01001001001001001001001001001001;
591 [[nodiscard]]
static uint32_t getMortonCode(
const Point<N, Scalar>& normalizedPosition)
noexcept {
592 if constexpr (
N == 2) {
593 constexpr Scalar MAX_EXTENT = 0b1111111111111111;
594 const uint32_t x = separateMortonCodeBits(
static_cast<uint32_t
>(
clamp(normalizedPosition.x * MAX_EXTENT, Scalar{0}, MAX_EXTENT)));
595 const uint32_t y = separateMortonCodeBits(
static_cast<uint32_t
>(
clamp(normalizedPosition.y * MAX_EXTENT, Scalar{0}, MAX_EXTENT)));
597 }
else if constexpr (
N == 3) {
598 constexpr Scalar MAX_EXTENT = 0b1111111111;
599 const uint32_t x = separateMortonCodeBits(
static_cast<uint32_t
>(
clamp(normalizedPosition.x * MAX_EXTENT, Scalar{0}, MAX_EXTENT)));
600 const uint32_t y = separateMortonCodeBits(
static_cast<uint32_t
>(
clamp(normalizedPosition.y * MAX_EXTENT, Scalar{0}, MAX_EXTENT)));
601 const uint32_t z = separateMortonCodeBits(
static_cast<uint32_t
>(
clamp(normalizedPosition.z * MAX_EXTENT, Scalar{0}, MAX_EXTENT)));
602 return x | (y << 1) | (z << 2);
606 [[nodiscard]] NodeIndex flushSubTree(
Span<
const Pair<uint32_t, ElementIndex>> elementIndices)
const {
607 if (elementIndices.empty()) {
611 if (tree.size() >=
static_cast<size_t>(INVALID_NODE)) {
612 throw std::length_error{
"Maximum node count exceeded."};
614 const NodeIndex nodeIndex =
static_cast<NodeIndex
>(tree.size());
616 if (elementIndices.size() == 1) {
617 Node& node = tree[nodeIndex];
618 node.firstChildIndex = INVALID_NODE;
619 node.secondChildIndex = INVALID_NODE;
620 node.elementIndex = elementIndices.front().second;
621 node.boundingBox = elements[elementIndices.front().second].first;
623 const size_t halfSize = elementIndices.size() / 2;
624 const NodeIndex firstChildIndex = flushSubTree(elementIndices.first(halfSize));
625 const NodeIndex secondChildIndex = flushSubTree(elementIndices.subspan(halfSize));
628 Node& node = tree[nodeIndex];
629 const Node& firstChild = tree[firstChildIndex];
630 const Node& secondChild = tree[secondChildIndex];
631 node.firstChildIndex = firstChildIndex;
632 node.secondChildIndex = secondChildIndex;
633 node.elementIndex = INVALID_ELEMENT;
635 .min =
min(firstChild.boundingBox.min, secondChild.boundingBox.min),
636 .max =
max(firstChild.boundingBox.max, secondChild.boundingBox.max),
649 worldBoundingBox.min =
min(worldBoundingBox.min, element.first.min);
650 worldBoundingBox.max =
max(worldBoundingBox.max, element.first.max);
653 const Point<N, Scalar> worldCenter = (worldBoundingBox.min + worldBoundingBox.max) * Scalar{0.5};
655 const vec<N, Scalar> inverseWorldExtents =
Scalar{1} / worldExtents;
657 elementIndicesOrderedByMortonCode.clear();
658 for (
size_t elementIndex = 0; elementIndex < elements.size(); ++elementIndex) {
659 const Box<N, Scalar>& boundingBox = elements[elementIndex].first;
660 const Point<N, Scalar> center = (boundingBox.min + boundingBox.max) * Scalar{0.5};
661 elementIndicesOrderedByMortonCode.push_back({getMortonCode((center + worldCenter) * inverseWorldExtents),
static_cast<ElementIndex
>(elementIndex)});
664 std::sort(elementIndicesOrderedByMortonCode.begin(), elementIndicesOrderedByMortonCode.end(),
665 [](
const Pair<uint32_t, ElementIndex>& a,
const Pair<uint32_t, ElementIndex>& b) ->
bool { return a.first < b.first; });
668 [[maybe_unused]]
const NodeIndex nodeIndex = flushSubTree(elementIndicesOrderedByMortonCode);
669 GREM_ASSERT((nodeIndex == 0 && !tree.empty()) || (nodeIndex == INVALID_NODE && tree.empty()));
674 template <
typename Callback,
typename Predicate>
675 auto traverseNodesImplementation(Callback&& callback, Predicate&& predicate)
const {
676 constexpr bool CALLBACK_RETURNS_BOOL = std::is_convertible_v<decltype(callback(std::declval<const Node&>())),
bool>;
677 using CallbackResult = std::conditional_t<CALLBACK_RETURNS_BOOL, bool, void>;
681 const auto traverseSubTree = [&](
const auto& self, NodeIndex nodeIndex) -> CallbackResult {
682 const Node& node = tree[nodeIndex];
683 if (predicate(node.boundingBox)) {
684 if constexpr (CALLBACK_RETURNS_BOOL) {
685 if (callback(node)) {
692 if (node.firstChildIndex != INVALID_NODE) {
693 if constexpr (CALLBACK_RETURNS_BOOL) {
694 if (self(self, node.firstChildIndex)) {
698 self(self, node.firstChildIndex);
701 if (node.secondChildIndex != INVALID_NODE) {
702 if constexpr (CALLBACK_RETURNS_BOOL) {
703 if (self(self, node.secondChildIndex)) {
707 self(self, node.secondChildIndex);
711 if constexpr (CALLBACK_RETURNS_BOOL) {
717 return traverseSubTree(traverseSubTree, 0);
719 if constexpr (CALLBACK_RETURNS_BOOL) {
724 ArrayList<value_type> elements{};
725 mutable ArrayList<Node> tree{};
726 mutable Buffer<Pair<uint32_t, ElementIndex>> elementIndicesOrderedByMortonCode{};
727 mutable bool dirty =
false;
737template <
typename Scalar,
typename T>
747template <
typename Scalar,
typename T>
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
Binary tree-based space subdivision container, Z-ordered using morton codes, optimized for intersecti...
Definition LinearBoundingVolumeHierarchy.hpp:38
iterator emplace(const Box< N, Scalar > &elementBoundingBox, Args &&... args)
Construct a new element in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:170
void clear() noexcept
Definition LinearBoundingVolumeHierarchy.hpp:62
const_pointer const_iterator
Const iterator type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:50
LinearBoundingVolumeHierarchy() noexcept=default
Construct an empty tree.
auto traverseElements(Callback &&callback) const
Execute a callback function for each element in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:433
pointer iterator
Iterator type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:49
const Pair< const Box< N, Scalar >, T > & const_reference
Const reference type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:44
const_iterator end() const noexcept
Get the end iterator of the elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:118
auto traverseElements(Callback &&callback, Predicate &&predicate) const
Execute a callback function for each element in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:380
const_iterator cbegin() const noexcept
Get the begin iterator of the elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:96
iterator begin() noexcept
Get the begin iterator of the elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:74
size_type size() const noexcept
Get the number of elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:138
auto traverseNodes(Callback &&callback, Predicate &&predicate) const
Execute a callback function for each active node of the tree, including empty internal nodes without ...
Definition LinearBoundingVolumeHierarchy.hpp:282
const_iterator cend() const noexcept
Get the end iterator of the elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:129
size_t size_type
Size type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:47
Pair< Box< N, Scalar >, T > value_type
Value type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:42
iterator insert(const Box< N, Scalar > &elementBoundingBox, T &&value)
Move an element into the tree.
Definition LinearBoundingVolumeHierarchy.hpp:219
bool test(Point< N, Scalar > point) const noexcept
Check if it is possible that some element in the tree contains a given point.
Definition LinearBoundingVolumeHierarchy.hpp:495
iterator end() noexcept
Get the end iterator of the elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:107
bool empty() const noexcept
Check whether the tree is empty or not.
Definition LinearBoundingVolumeHierarchy.hpp:147
const_iterator begin() const noexcept
Get the begin iterator of the elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:85
ptrdiff_t difference_type
Difference type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:48
void erase(const_iterator pos)
Remove an element from the tree.
Definition LinearBoundingVolumeHierarchy.hpp:230
auto test(Point< N, Scalar > point, Callback &&callback) const
Execute a callback function for each element in the tree that might contain a given point.
Definition LinearBoundingVolumeHierarchy.hpp:472
auto traverseNodes(Callback &&callback) const
Execute a callback function for each active node of the tree, including empty internal nodes without ...
Definition LinearBoundingVolumeHierarchy.hpp:334
auto test(const Box< N, Scalar > &box, Callback &&callback) const
Execute a callback function for each element in the tree that might be intersecting with a given axis...
Definition LinearBoundingVolumeHierarchy.hpp:534
const Pair< const Box< N, Scalar >, T > * const_pointer
Const pointer type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:46
iterator insert(const Box< N, Scalar > &elementBoundingBox, const T &value)
Copy an element into the tree.
Definition LinearBoundingVolumeHierarchy.hpp:197
bool test(const Box< N, Scalar > &box) const noexcept
Check if it is possible that some element in the tree is intersecting with a given axis-aligned box.
Definition LinearBoundingVolumeHierarchy.hpp:558
Pair< const Box< N, Scalar >, T > & reference
Reference type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:43
Definition concepts.hpp:106
@ N
'n'
Definition keyboard.hpp:84
float Scalar
Underlying scalar type of physics quantity components.
Definition quantities.hpp:1480
GREM_ALWAYS_INLINE constexpr decltype(auto) clamp(T &&value, Low &&minValue, High &&maxValue)
Clamp a value to a specific interval.
Definition fundamentals.hpp:630
vec< N, T > Length
Generic length in N-dimensional space.
Definition geometry.hpp:38
constexpr bool intersects(const spherical_shape auto &a, const spherical_shape auto &b) noexcept
Check if two spherical shapes intersect.
Definition geometry.hpp:1662
LinearBoundingVolumeHierarchy< 3, Scalar, T > BoundingVolumeHierarchy3D
Binary tree-based space subdivision container, optimized for intersection queries between 3D axis-ali...
Definition LinearBoundingVolumeHierarchy.hpp:748
Span(R &&range) -> Span< std::remove_reference_t< decltype(*std::data(range))> >
vec< N, T > Point
Generic point in N-dimensional space.
Definition geometry.hpp:29
GREM_ALWAYS_INLINE constexpr decltype(auto) max(A &&a, B &&b)
Get the greater of two values, or the first value if they are equivalent.
Definition fundamentals.hpp:598
LinearBoundingVolumeHierarchy< 2, Scalar, T > BoundingVolumeHierarchy2D
Binary tree-based space subdivision container, optimized for intersection queries between 2D axis-ali...
Definition LinearBoundingVolumeHierarchy.hpp:738
GREM_ALWAYS_INLINE constexpr decltype(auto) min(A &&a, B &&b)
Get the smaller of two values, or the first value if they are equivalent.
Definition fundamentals.hpp:585
Generic axis-aligned box shape with minimum and maximum extents in N-dimensional space.
Definition geometry.hpp:149
constexpr bool contains(const Point< N, T > &point) const noexcept
Check if a given point is contained within the extents of this box.
Definition geometry.hpp:182
Point< N, T > max
Position with the maximum coordinates of the box extents on each coordinate axis.
Definition geometry.hpp:154
static constexpr T MAX
Definition fundamentals.hpp:29
static constexpr T MIN
Definition fundamentals.hpp:28