Gamedev Framework (gf)  0.14.0
A C++14 framework for 2D games
Spatial.h
1 /*
2  * Gamedev Framework (gf)
3  * Copyright (C) 2016-2019 Julien Bernard
4  *
5  * This software is provided 'as-is', without any express or implied
6  * warranty. In no event will the authors be held liable for any damages
7  * arising from the use of this software.
8  *
9  * Permission is granted to anyone to use this software for any purpose,
10  * including commercial applications, and to alter it and redistribute it
11  * freely, subject to the following restrictions:
12  *
13  * 1. The origin of this software must not be misrepresented; you must not
14  * claim that you wrote the original software. If you use this software
15  * in a product, an acknowledgment in the product documentation would be
16  * appreciated but is not required.
17  * 2. Altered source versions must be plainly marked as such, and must not be
18  * misrepresented as being the original software.
19  * 3. This notice may not be removed or altered from any source distribution.
20  */
21 #ifndef GF_SPATIAL_H
22 #define GF_SPATIAL_H
23 
24 #include <cassert>
25 #include <cmath>
26 #include <algorithm>
27 #include <functional>
28 #include <iterator>
29 #include <map>
30 #include <memory>
31 #include <numeric>
32 #include <vector>
33 
34 #include <boost/container/static_vector.hpp>
35 
36 #include "Box.h"
37 #include "Math.h"
38 #include "Unused.h"
39 
40 #include "Log.h"
41 
42 namespace gf {
43 #ifndef DOXYGEN_SHOULD_SKIP_THIS
44 inline namespace v1 {
45 #endif
46 
53  enum class SpatialStructureType {
54  Object,
55  Node,
56  };
57 
66  template<typename U, std::size_t N>
70  int level;
71  };
72 
77  enum class SpatialQuery {
78  Contain,
79  Intersect,
80  };
81 
86  template<typename T>
87  using SpatialQueryCallback = std::function<void(const T&)>;
88 
96  template<typename T, typename U = float, std::size_t Size = 16>
97  class QuadTree {
98  static_assert(Size > 0, "Size can not be 0");
99  public:
105  QuadTree(const Box<U, 2>& bounds)
106  : m_root(bounds)
107  {
108 
109  }
110 
118  bool insert(T value, const Box<U, 2>& bounds) {
119  Node *node = m_root.chooseNode(bounds);
120 
121  if (node == nullptr) {
122  return false;
123  }
124 
125  return node->insert(std::move(value), bounds);
126  }
127 
136  std::size_t query(const Box<U, 2>& bounds, SpatialQueryCallback<T> callback, SpatialQuery kind = SpatialQuery::Intersect) const {
137  return m_root.query(bounds, callback, kind);
138  }
139 
143  void clear() {
144  m_root.clear();
145  }
146 
147 
148  std::vector<SpatialStructure<U, 2>> getStructure() const {
149  std::vector<SpatialStructure<U, 2>> structures;
150  m_root.appendToStructure(structures, 0);
151  return structures;
152  }
153 
154  private:
155  struct Entry {
156  T value;
157  Box<U, 2> bounds;
158  };
159 
160  class Node {
161  public:
162  Node()
163  : m_children(nullptr)
164  {
165  m_entries.reserve(Size);
166  }
167 
168  Node(const Box<U, 2>& bounds)
169  : m_bounds(bounds)
170  , m_children(nullptr)
171  {
172  m_entries.reserve(Size);
173  }
174 
175  bool isLeaf() const {
176  return m_children == nullptr;
177  }
178 
179  Node *chooseNode(const Box<U, 2>& bounds) {
180  if (!m_bounds.contains(bounds)) {
181  return nullptr;
182  }
183 
184  if (isLeaf()) {
185  if (m_entries.size() < Size) {
186  return this;
187  }
188 
189  subdivide();
190 
191  // try again
192  if (m_entries.size() < Size) {
193  return this;
194  }
195  }
196 
197  for (std::size_t i = 0; i < 4; ++i) {
198  if (m_children[i].chooseNode(bounds) != nullptr) {
199  return &m_children[i];
200  }
201  }
202 
203  clearChildrenIfEmpty();
204 
205  return this;
206  }
207 
208  bool insert(T&& value, const Box<U, 2>& bounds) {
209  m_entries.push_back({ std::move(value), bounds });
210  return true;
211  }
212 
213  std::size_t query(const Box<U, 2>& bounds, SpatialQueryCallback<T>& callback, SpatialQuery kind) const {
214  if (!m_bounds.intersects(bounds)) {
215  return 0;
216  }
217 
218  std::size_t found = 0;
219 
220  for (auto& entry : m_entries) {
221  switch (kind) {
223  if (bounds.contains(entry.bounds)) {
224  callback(entry.value);
225  ++found;
226  }
227  break;
228 
230  if (bounds.intersects(entry.bounds)) {
231  callback(entry.value);
232  ++found;
233  }
234  break;
235  }
236  }
237 
238  if (!isLeaf()) {
239  for (std::size_t i = 0; i < 4; ++i) {
240  found += m_children[i].query(bounds, callback, kind);
241  }
242  }
243 
244  return found;
245  }
246 
247  void clear() {
248  m_entries.clear();
249 
250  // no need to explicitly clear children
251  m_children = nullptr;
252  }
253 
254  void appendToStructure(std::vector<SpatialStructure<U, 2>>& structures, int level) const {
255  structures.push_back({ m_bounds, SpatialStructureType::Node, level });
256 
257  for (auto& entry : m_entries) {
258  structures.push_back( { entry.bounds, SpatialStructureType::Object, level });
259  }
260 
261  if (m_children) {
262  for (std::size_t i = 0; i < 4; ++i) {
263  m_children[i].appendToStructure(structures, level + 1);
264  }
265  }
266  }
267 
268  private:
269  void subdivide() {
270  m_children = std::make_unique<Node[]>(4);
271 
272  m_children[0].m_bounds = computeBoxQuarter(m_bounds, Quarter::UpperLeft);
273  m_children[1].m_bounds = computeBoxQuarter(m_bounds, Quarter::UpperRight);
274  m_children[2].m_bounds = computeBoxQuarter(m_bounds, Quarter::LowerRight);
275  m_children[3].m_bounds = computeBoxQuarter(m_bounds, Quarter::LowerLeft);
276 
277  std::vector<Entry> entries;
278 
279  for (auto& entry : m_entries) {
280  bool inserted = false;
281 
282  for (std::size_t i = 0; i < 4; ++i) {
283  if (m_children[i].m_bounds.contains(entry.bounds)) {
284  m_children[i].m_entries.push_back(std::move(entry));
285  inserted = true;
286  break;
287  }
288  }
289 
290  if (!inserted) {
291  entries.push_back(std::move(entry));
292  }
293  }
294 
295  std::swap(m_entries, entries);
296  }
297 
298  void clearChildrenIfEmpty() {
299  assert(!isLeaf());
300 
301  for (std::size_t i = 0; i < 4; ++i) {
302  if (!m_children[i].m_entries.empty()) {
303  return;
304  }
305  }
306 
307  m_children = nullptr;
308  }
309 
310  private:
311  Box<U, 2> m_bounds;
312  std::vector<Entry> m_entries;
313  std::unique_ptr<Node[]> m_children;
314  };
315 
316  private:
317  Node m_root;
318  };
319 
329  template<typename T, typename U = float, std::size_t N = 2, std::size_t MaxSize = 16, std::size_t MinSize = 4>
330  class RStarTree {
331  static_assert(N > 0, "N can not be 0");
332  static_assert(2 <= MinSize, "MinSize must be at least 2");
333  static_assert(MinSize <= MaxSize / 2, "MinSize must be less than MaxSize/2");
334  public:
339  : m_root(new Leaf)
340  {
341 
342  }
343 
347  RStarTree(const RStarTree&) = delete;
348 
352  RStarTree& operator=(const RStarTree&) = delete;
353 
357  RStarTree(RStarTree&& other) noexcept
358  {
359  m_root = std::exchange(other.m_root, nullptr);
360  }
361 
365  RStarTree& operator=(RStarTree&& other) noexcept {
366  std::swap(m_root, other.m_root);
367  return *this;
368  }
369 
374  delete m_root;
375  }
376 
384  bool insert(T value, const Box<U, N>& bounds) {
385  Leaf *leaf = m_root->chooseSubtree(bounds);
386 
387  Node *splitted = leaf->tryInsert(std::move(value), bounds);
388  Node *current = leaf;
389 
390  while (splitted != nullptr) {
391  auto splittedBounds = splitted->computeBounds();
392  splitted->updateOriginalBounds(splittedBounds);
393 
394  auto currentBounds = current->computeBounds();
395  current->updateOriginalBounds(currentBounds);
396 
397  if (current == m_root) {
398  auto branch = new Branch;
399 
400  current->setParent(branch);
401  branch->tryInsert(current, currentBounds);
402 
403  splitted->setParent(branch);
404  branch->tryInsert(splitted, splittedBounds);
405 
406  branch->updateOriginalBounds(branch->computeBounds());
407 
408  m_root = branch;
409  current = m_root;
410  splitted = nullptr;
411  } else {
412  Branch *parent = current->getParent();
413  assert(parent != nullptr);
414 
415  parent->updateBoundsForChild(currentBounds, current);
416 
417  splitted->setParent(parent);
418  splitted = parent->tryInsert(splitted, splittedBounds);
419 
420  current = parent;
421  }
422  }
423 
424  while (current != m_root) {
425  auto currentBounds = current->computeBounds();
426 
427  Branch *parent = current->getParent();
428  assert(parent != nullptr);
429 
430  parent->updateBoundsForChild(currentBounds, current);
431 
432  current = parent;
433  }
434 
435  return true;
436  }
437 
446  std::size_t query(const Box<U, N>& bounds, SpatialQueryCallback<T> callback, SpatialQuery kind = SpatialQuery::Intersect) const {
447  return m_root->query(bounds, callback, kind);
448  }
449 
453  void clear() {
454  delete m_root;
455  m_root = new Leaf;
456  }
457 
458  std::vector<SpatialStructure<U, N>> getStructure() const {
459  std::vector<SpatialStructure<U, N>> structures;
460  m_root->appendToStructure(structures, 0);
461  return structures;
462  }
463 
464  private:
465  static constexpr std::size_t Size = MaxSize + 1;
466 
467  enum SplitOrder {
468  Min,
469  Max,
470  };
471 
472  struct SplitResult {
473  std::size_t index;
474  std::size_t axis;
475  SplitOrder order;
476  };
477 
478  class Leaf;
479  class Branch;
480 
481  /*
482  * Node
483  */
484 
485  struct Entry {
486  Box<U, N> bounds;
487  };
488 
489  class Node {
490  public:
491  Node()
492  : m_parent(nullptr)
493  {
494 
495  }
496 
497  Branch *getParent() noexcept {
498  return m_parent;
499  }
500 
501  void setParent(Branch *parent) {
502  m_parent = parent;
503  }
504 
505  bool hasOriginalBounds() const {
506  return !m_orig.isEmpty();
507  }
508 
509  U getOriginalCenterAxisValue(std::size_t axis) const {
510  return (m_orig.min[axis] + m_orig.max[axis]) / 2;
511  }
512 
513  void updateOriginalBounds(Box<U, N> orig) {
514  m_orig = orig;
515  }
516 
517  virtual ~Node() = default;
518  virtual std::size_t query(const Box<U, N>& bounds, SpatialQueryCallback<T>& callback, SpatialQuery kind) const = 0;
519  virtual Leaf *chooseSubtree(const Box<U, N>& bounds) = 0;
520 
521  virtual Box<U, N> computeBounds() const = 0;
522 
523  virtual void appendToStructure(std::vector<SpatialStructure<U, N>>& structures, int level) const = 0;
524 
525  private:
526  Branch *m_parent;
527  Box<U, N> m_orig;
528  };
529 
530  /*
531  * Leaf
532  */
533 
534  struct LeafEntry : Entry {
535  T value;
536  };
537 
538  class Leaf : public Node {
539  public:
540  virtual std::size_t query(const Box<U, N>& bounds, SpatialQueryCallback<T>& callback, SpatialQuery kind) const override {
541  std::size_t found = 0;
542 
543  switch (kind) {
545  for (auto& entry : m_entries) {
546  if (bounds.contains(entry.bounds)) {
547  callback(entry.value);
548  ++found;
549  }
550  }
551  break;
552 
554  for (auto& entry : m_entries) {
555  if (bounds.intersects(entry.bounds)) {
556  callback(entry.value);
557  ++found;
558  }
559  }
560  break;
561  }
562 
563  return found;
564  }
565 
566 
567  virtual Leaf *chooseSubtree(const Box<U, N>& bounds) override {
568  gf::unused(bounds);
569  return this;
570  }
571 
572  virtual Box<U,N> computeBounds() const override {
573  assert(!m_entries.empty());
574  Box<U,N> res(m_entries[0].bounds);
575 
576  for (auto& entry : m_entries) {
577  res.extend(entry.bounds);
578  }
579 
580  return res;
581  }
582 
583  virtual void appendToStructure(std::vector<SpatialStructure<U, N>>& structures, int level) const override {
584  for (auto& entry : m_entries) {
585  structures.push_back({ entry.bounds, SpatialStructureType::Object, level });
586  }
587  }
588 
589  Leaf *tryInsert(T&& value, const Box<U, N>& bounds) {
590  LeafEntry entry;
591  entry.bounds = bounds;
592  entry.value = std::move(value);
593  m_entries.push_back(std::move(entry));
594 
595  if (m_entries.size() < Size) {
596  return nullptr;
597  }
598 
599  std::vector<Box<U, N>> boxes;
600 
601  std::transform(m_entries.begin(), m_entries.end(), std::back_inserter(boxes), [](const Entry& entry) {
602  return entry.bounds;
603  });
604 
605  SplitResult split = computeSplit(boxes);
606 
607  switch (split.order) {
608  case SplitOrder::Min:
609  std::sort(m_entries.begin(), m_entries.end(), EntryMinAxisComparator<LeafEntry>(split.axis));
610  break;
611  case SplitOrder::Max:
612  std::sort(m_entries.begin(), m_entries.end(), EntryMaxAxisComparator<LeafEntry>(split.axis));
613  break;
614  }
615 
616  auto leaf = new Leaf;
617 
618  auto splitIteratorBegin = std::next(m_entries.begin(), split.index + 1);
619  auto splitIteratorEnd = m_entries.end();
620 
621  std::move(splitIteratorBegin, splitIteratorEnd, std::back_inserter(leaf->m_entries));
622  m_entries.erase(splitIteratorBegin, splitIteratorEnd);
623 
624  return leaf;
625  }
626 
627  private:
628  SplitResult computeSplit(std::vector<Box<U, N>>& boxes) {
629  SplitResult split;
630  std::tie(split.axis, split.order) = computeSplitAxis(boxes);
631 
632  switch (split.order) {
633  case SplitOrder::Min:
634  std::sort(boxes.begin(), boxes.end(), MinAxisComparator(split.axis));
635  break;
636  case SplitOrder::Max:
637  std::sort(boxes.begin(), boxes.end(), MaxAxisComparator(split.axis));
638  break;
639  }
640 
641  split.index = computeSplitIndex(boxes, split.axis);
642  return split;
643  }
644 
645  std::tuple<std::size_t, SplitOrder> computeSplitAxis(std::vector<Box<U, N>>& boxes) {
646  std::size_t currentAxis = 0;
647  U currentValue = std::numeric_limits<U>::max();
648  SplitOrder currentOrder = SplitOrder::Min;
649 
650  for (std::size_t axis = 0; axis < N; ++axis) {
651  std::sort(boxes.begin(), boxes.end(), MinAxisComparator(axis));
652 
653  U value = computeAxisValue(boxes);
654 
655  if (value < currentValue) {
656  currentAxis = axis;
657  currentValue = value;
658  currentOrder = SplitOrder::Min;
659  }
660 
661  std::sort(boxes.begin(), boxes.end(), MaxAxisComparator(axis));
662 
663  value = computeAxisValue(boxes);
664 
665  if (value < currentValue) {
666  currentAxis = axis;
667  currentValue = value;
668  currentOrder = SplitOrder::Max;
669  }
670  }
671 
672  return std::make_tuple(currentAxis, currentOrder);
673  }
674 
675  U computeAxisValue(const std::vector<Box<U, N>>& boxes) {
676  std::vector<Box<U, N>> firstBounds;
677 
678  std::partial_sum(boxes.begin(), boxes.end(), std::back_inserter(firstBounds), [](const Box<U, N>& lhs, const Box<U, N>& rhs) {
679  return lhs.getExtended(rhs);
680  });
681 
682  std::vector<Box<U, N>> secondBounds;
683 
684  std::partial_sum(boxes.rbegin(), boxes.rend(), std::back_inserter(secondBounds), [](const Box<U, N>& lhs, const Box<U, N>& rhs) {
685  return lhs.getExtended(rhs);
686  });
687 
688  U value = { };
689 
690  for (std::size_t j = MinSize; j <= MaxSize - MinSize + 1; ++j) {
691  value += firstBounds[j].getExtentLength() + secondBounds[Size - j].getExtentLength();
692  }
693 
694  return value;
695  }
696 
697  std::size_t computeSplitIndex(const std::vector<Box<U, N>>& boxes, std::size_t axis) {
698  std::vector<Box<U, N>> firstBounds;
699 
700  std::partial_sum(boxes.begin(), boxes.end(), std::back_inserter(firstBounds), [](const Box<U, N>& lhs, const Box<U, N>& rhs) {
701  return lhs.getExtended(rhs);
702  });
703 
704  std::vector<Box<U, N>> secondBounds;
705 
706  std::partial_sum(boxes.rbegin(), boxes.rend(), std::back_inserter(secondBounds), [](const Box<U, N>& lhs, const Box<U, N>& rhs) {
707  return lhs.getExtended(rhs);
708  });
709 
710 
711  // define wf
712 
713  const auto& bounds = firstBounds.back();
714  float asym = 0.0f;
715 
716  if (Node::hasOriginalBounds()) {
717  asym = 2.0f * ((bounds.max[axis] + bounds.min[axis]) / 2 - Node::getOriginalCenterAxisValue(axis)) / (bounds.max[axis] - bounds.min[axis]);
718  }
719 
720  assert(-1.0f <= asym && asym <= 1.0f);
721 
722  static constexpr float S = 0.5f;
723  const float mu = (1 - 2.0f * MinSize / (MaxSize + 1)) * asym;
724  const float rho = S * (1 + std::abs(mu));
725  const float y1 = std::exp(- 1 / (S * S));
726  const float ys = 1 / (1 - y1);
727 
728  auto wf = [mu,rho,y1,ys](std::size_t i) {
729  const float xi = 2.0f * i / (MaxSize + 1.0f) - 1.0f;
730  return ys * (std::exp(- gf::square((xi - mu) / rho) - y1));
731  };
732 
733  // compute weight
734 
735  std::size_t currentIndex = 0;
736  U currentValue = std::numeric_limits<U>::max();
737 
738  U (Box<U,N>::* overlapFn)(const Box<U, N>&) const noexcept = nullptr;
739 
740  if (firstBounds[MinSize].getVolume() == 0 || secondBounds[MinSize].getVolume() == 0) {
741  // perimeter based strategy
743  } else {
744  // volume based strategy
745  overlapFn = &Box<U,N>::getIntersectionVolume;
746  }
747 
748  bool overlapFree = false;
749 
750  U perimeterMax = 2 * bounds.getExtentLength() - bounds.getMinimumEdge();
751 
752  for (std::size_t index = MinSize; index <= MaxSize - MinSize + 1; ++index) {
753  auto weight = (firstBounds[index].*overlapFn)(secondBounds[Size - index - 1]);
754 
755  if (!overlapFree) {
756  if (weight == 0) {
757  overlapFree = true;
758  } else {
759  auto value = weight * wf(index);
760 
761  if (value < currentValue) {
762  currentValue = value;
763  currentIndex = index;
764  }
765  }
766  }
767 
768  if (overlapFree && weight == 0) {
769  weight = firstBounds[index].getExtentLength() + secondBounds[Size - index - 1].getExtentLength() - perimeterMax;
770  assert(weight <= 0);
771 
772  auto value = weight / wf(index);
773 
774  if (value < currentValue) {
775  currentValue = value;
776  currentIndex = index;
777  }
778  }
779  }
780 
781  return currentIndex;
782  }
783 
784  private:
785  boost::container::static_vector<LeafEntry, Size> m_entries;
786  };
787 
788  /*
789  * Branch
790  */
791 
792  struct BranchEntry : Entry {
793  Node *child;
794  };
795 
796  class Branch : public Node {
797  public:
798  virtual ~Branch() {
799  for (auto& entry : m_entries) {
800  delete entry.child;
801  }
802  }
803 
804  virtual std::size_t query(const Box<U, N>& bounds, SpatialQueryCallback<T>& callback, SpatialQuery kind) const override {
805  std::size_t found = 0;
806 
807  for (auto& entry : m_entries) {
808  if (bounds.intersects(entry.bounds)) {
809  found += entry.child->query(bounds, callback, kind);
810  }
811  }
812 
813  return found;
814  }
815 
816  virtual Leaf *chooseSubtree(const Box<U, N>& bounds) override {
817  return chooseNode(bounds)->chooseSubtree(bounds);
818  }
819 
820  Node *searchForCoveringNode(const Box<U, N>& bounds) {
821  Node *bestNodeForVolume = nullptr;
822  U bestVolume = std::numeric_limits<U>::max();
823 
824  Node *bestNodeForExtentLength = nullptr;
825  U bestExtentLength = std::numeric_limits<U>::max();
826 
827  for (auto& entry : m_entries) {
828  if (entry.bounds.getIntersection(bounds) == bounds) {
829  U volume = entry.bounds.getVolume();
830 
831  if (bestNodeForVolume == nullptr || volume < bestVolume) {
832  bestVolume = volume;
833  bestNodeForVolume = entry.child;
834  }
835 
836  U extentDistance = entry.bounds.getExtentLength();
837 
838  if (bestNodeForExtentLength == nullptr || extentDistance < bestExtentLength) {
839  bestExtentLength = extentDistance;
840  bestNodeForExtentLength = entry.child;
841  }
842  }
843  }
844 
845  if (bestNodeForVolume != nullptr) {
846  if (bestVolume > 0) {
847  return bestNodeForVolume;
848  }
849 
850  assert(bestNodeForExtentLength);
851  return bestNodeForExtentLength;
852  }
853 
854  return nullptr;
855  }
856 
857  Node *chooseNode(const Box<U, N>& bounds) {
858  Node *covering = searchForCoveringNode(bounds);
859 
860  if (covering != nullptr) {
861  return covering;
862  }
863 
864  std::sort(m_entries.begin(), m_entries.end(), ExtentLengthEnlargement(bounds));
865 
866  OverlapExtentLengthEnlargement extentDistanceEnlargement(bounds, m_entries.front());
867 
868  std::size_t p;
869 
870  for (p = m_entries.size() - 1; p > 0; --p) {
871  if (extentDistanceEnlargement(m_entries[p]) != 0) {
872  break;
873  }
874  }
875 
876  if (p == 0) {
877  return m_entries[0].child;
878  }
879 
880  std::vector<Candidate> candidates(p + 1, { 0, false, U() });
881  Node *node = nullptr;
882 
883  if (existsEmptyVolumeExtension(bounds)) {
884  node = findCandidates<OverlapExtentLengthEnlargement>(0, p, bounds, candidates);
885  } else {
886  node = findCandidates<OverlapVolumeEnlargement>(0, p, bounds, candidates);
887  }
888 
889  if (node != nullptr) {
890  return node;
891  }
892 
893  candidates.erase(std::remove_if(candidates.begin(), candidates.end(), [](const Candidate& candidate) {
894  return !candidate.isCandidate;
895  }), candidates.end());
896 
897  assert(!candidates.empty());
898 
899  auto it = std::min_element(candidates.begin(), candidates.end(), [](const Candidate& lhs, const Candidate& rhs) {
900  return lhs.overlap < rhs.overlap;
901  });
902 
903  return m_entries[it->index].child;
904  }
905 
906  virtual Box<U,N> computeBounds() const override {
907  assert(!m_entries.empty());
908  Box<U,N> res(m_entries[0].bounds);
909 
910  for (auto& entry : m_entries) {
911  res.extend(entry.bounds);
912  }
913 
914  return res;
915  }
916 
917  virtual void appendToStructure(std::vector<SpatialStructure<U, N>>& structures, int level) const override {
918  for (auto& entry : m_entries) {
919  structures.push_back({ entry.bounds, SpatialStructureType::Node, level });
920  entry.child->appendToStructure(structures, level + 1);
921  }
922  }
923 
924  void updateBoundsForChild(const Box<U, N>& bounds, Node *child) {
925  for (auto& entry : m_entries) {
926  if (entry.child == child) {
927  entry.bounds = bounds;
928  return;
929  }
930  }
931 
932  assert(false);
933  }
934 
935  Branch *tryInsert(Node * node, const Box<U, N>& bounds) {
936  BranchEntry entry;
937  entry.bounds = bounds;
938  entry.child = node;
939  m_entries.push_back(std::move(entry));
940 
941  if (m_entries.size() < Size) {
942  return nullptr;
943  }
944 
945  std::vector<Box<U, N>> boxes;
946 
947  std::transform(m_entries.begin(), m_entries.end(), std::back_inserter(boxes), [](const Entry& entry) {
948  return entry.bounds;
949  });
950 
951  SplitResult split = computeSplit(boxes);
952 
953  switch (split.order) {
954  case SplitOrder::Min:
955  std::sort(m_entries.begin(), m_entries.end(), EntryMinAxisComparator<BranchEntry>(split.axis));
956  break;
957  case SplitOrder::Max:
958  std::sort(m_entries.begin(), m_entries.end(), EntryMaxAxisComparator<BranchEntry>(split.axis));
959  break;
960  }
961 
962  auto branch = new Branch;
963 
964  auto splitIteratorBegin = std::next(m_entries.begin(), split.index + 1);
965  auto splitIteratorEnd = m_entries.end();
966 
967  std::move(splitIteratorBegin, splitIteratorEnd, std::back_inserter(branch->m_entries));
968  m_entries.erase(splitIteratorBegin, splitIteratorEnd);
969 
970  for (auto& entry : branch->m_entries) {
971  entry.child->setParent(branch);
972  }
973 
974  return branch;
975  }
976 
977  private:
978  struct Candidate {
979  std::size_t index;
980  bool isCandidate;
981  U overlap;
982  };
983 
984  bool existsEmptyVolumeExtension(const Box<U, N>& bounds) {
985  for (auto& entry : m_entries) {
986  if (entry.bounds.getExtended(bounds).getVolume() == 0) {
987  return true;
988  }
989  }
990 
991  return false;
992  }
993 
994  template<typename OverlapEnlargement>
995  Node *findCandidates(std::size_t t, std::size_t p, const Box<U, N>& bounds, std::vector<Candidate>& candidates) {
996  candidates[t].index = t;
997  candidates[t].isCandidate = true;
998 
999  OverlapEnlargement enlargement(bounds, m_entries[t]);
1000 
1001  U overlap = { };
1002 
1003  for (std::size_t i = 0; i <= p; ++i) {
1004  if (i == t) {
1005  continue;
1006  }
1007 
1008  U localOverlap = enlargement(m_entries[i]);
1009  overlap += localOverlap;
1010 
1011  if (localOverlap == 0 && !candidates[i].isCandidate) {
1012  Node *node = findCandidates<OverlapEnlargement>(i, p, bounds, candidates);
1013 
1014  if (node != nullptr) {
1015  return node;
1016  }
1017  }
1018  }
1019 
1020  if (overlap == 0) {
1021  return m_entries[t].child;
1022  }
1023 
1024  candidates[t].overlap = overlap;
1025  return nullptr;
1026  }
1027 
1028  struct SplitStatus {
1029  bool overlapFree = false;
1030  U currentValue = std::numeric_limits<U>::max();
1031  };
1032 
1033  SplitResult computeSplit(std::vector<Box<U, N>>& boxes) {
1034  SplitResult result;
1035  SplitStatus status;
1036 
1037  for (std::size_t axis = 0; axis < N; ++axis) {
1038  std::sort(boxes.begin(), boxes.end(), MinAxisComparator(axis));
1039  computeBestSplitValue(boxes, result, status, axis, SplitOrder::Min);
1040 
1041  std::sort(boxes.begin(), boxes.end(), MaxAxisComparator(axis));
1042  computeBestSplitValue(boxes, result, status, axis, SplitOrder::Max);
1043  }
1044 
1045  return result;
1046  }
1047 
1048  void computeBestSplitValue(std::vector<Box<U, N>>& boxes, SplitResult& result, SplitStatus& status, std::size_t axis, SplitOrder order) {
1049  std::vector<Box<U, N>> firstBounds;
1050 
1051  std::partial_sum(boxes.begin(), boxes.end(), std::back_inserter(firstBounds), [](const Box<U, N>& lhs, const Box<U, N>& rhs) {
1052  return lhs.getExtended(rhs);
1053  });
1054 
1055  std::vector<Box<U, N>> secondBounds;
1056 
1057  std::partial_sum(boxes.rbegin(), boxes.rend(), std::back_inserter(secondBounds), [](const Box<U, N>& lhs, const Box<U, N>& rhs) {
1058  return lhs.getExtended(rhs);
1059  });
1060 
1061  // define wf
1062 
1063  const auto& bounds = firstBounds.back();
1064  float asym = 0.0f;
1065 
1066  if (Node::hasOriginalBounds()) {
1067  asym = 2.0f * ((bounds.max[axis] + bounds.min[axis]) / 2 - Node::getOriginalCenterAxisValue(axis)) / (bounds.max[axis] - bounds.min[axis]);
1068  }
1069 
1070  assert(-1.0f <= asym && asym <= 1.0f);
1071 
1072  static constexpr float S = 0.5f;
1073  const float mu = (1 - 2.0f * MinSize / (MaxSize + 1)) * asym;
1074  const float rho = S * (1 + std::abs(mu));
1075  const float y1 = std::exp(- 1 / (S * S));
1076  const float ys = 1 / (1 - y1);
1077 
1078  auto wf = [mu,rho,y1,ys](std::size_t i) {
1079  const float xi = 2.0f * i / (MaxSize + 1.0f) - 1.0f;
1080  return ys * (std::exp(- gf::square((xi - mu) / rho) - y1));
1081  };
1082 
1083  // compute weight
1084 
1085  U (Box<U,N>::* overlapFn)(const Box<U, N>&) const noexcept = nullptr;
1086 
1087  if (firstBounds[MinSize].getVolume() == 0 || secondBounds[MinSize].getVolume() == 0) {
1088  // perimeter based strategy
1090  } else {
1091  // volume based strategy
1092  overlapFn = &Box<U,N>::getIntersectionVolume;
1093  }
1094 
1095  U perimeterMax = 2 * bounds.getExtentLength() - bounds.getMinimumEdge();
1096 
1097  for (std::size_t index = MinSize; index <= MaxSize - MinSize + 1; ++index) {
1098  auto weight = (firstBounds[index].*overlapFn)(secondBounds[Size - index - 1]);
1099 
1100  if (!status.overlapFree) {
1101  if (weight == 0) {
1102  status.overlapFree = true;
1103  } else {
1104  auto value = weight * wf(index);
1105 
1106  if (value < status.currentValue) {
1107  status.currentValue = value;
1108  result.index = index;
1109  result.axis = axis;
1110  result.order = order;
1111  }
1112  }
1113  }
1114 
1115  if (status.overlapFree && weight == 0) {
1116  weight = firstBounds[index].getExtentLength() + secondBounds[Size - index - 1].getExtentLength() - perimeterMax;
1117  assert(weight <= 0);
1118 
1119  auto value = weight / wf(index);
1120 
1121  if (value < status.currentValue) {
1122  status.currentValue = value;
1123  result.index = index;
1124  result.axis = axis;
1125  result.order = order;
1126  }
1127  }
1128  }
1129  }
1130 
1131  private:
1132  boost::container::static_vector<BranchEntry, Size> m_entries;
1133  };
1134 
1135  /*
1136  * Comparators and Functors
1137  */
1138 
1139  class ExtentLengthEnlargement {
1140  public:
1141  ExtentLengthEnlargement(const Box<U, N>& bounds)
1142  : m_bounds(bounds)
1143  {
1144 
1145  }
1146 
1147  bool operator()(const Entry& lhs, const Entry& rhs) const {
1148  return getExtentLengthEnlargement(lhs) < getExtentLengthEnlargement(rhs);
1149  }
1150 
1151  U getExtentLengthEnlargement(const Entry& entry) const {
1152  return entry.bounds.getExtended(m_bounds).getExtentLength() - entry.bounds.getExtentLength();
1153  }
1154 
1155  private:
1156  const Box<U, N>& m_bounds;
1157  };
1158 
1159  class OverlapExtentLengthEnlargement {
1160  public:
1161  OverlapExtentLengthEnlargement(const Box<U, N>& bounds, const Entry& reference)
1162  : m_bounds(bounds)
1163  , m_reference(reference)
1164  , m_extended(reference.bounds.getExtended(bounds))
1165  {
1166 
1167  }
1168 
1169  U operator()(const Entry& entry) const {
1170  return getOverlapExtentLengthEnlargement(entry);
1171  }
1172 
1173  U getOverlapExtentLengthEnlargement(const Entry& entry) const {
1174  return m_extended.getIntersectionExtentLength(entry.bounds) - m_reference.bounds.getIntersectionExtentLength(entry.bounds);
1175  }
1176 
1177  private:
1178  const Box<U, N>& m_bounds;
1179  const Entry& m_reference;
1180  Box<U, N> m_extended;
1181  };
1182 
1183 
1184  class OverlapVolumeEnlargement {
1185  public:
1186  OverlapVolumeEnlargement(const Box<U, N>& bounds, const Entry& reference)
1187  : m_bounds(bounds)
1188  , m_reference(reference)
1189  , m_extended(reference.bounds.getExtended(bounds))
1190  {
1191 
1192  }
1193 
1194  U operator()(const Entry& entry) const {
1195  return getOverlapVolumeEnlargement(entry);
1196  }
1197 
1198  U getOverlapVolumeEnlargement(const Entry& entry) const {
1199  return m_extended.getIntersectionVolume(entry.bounds) - m_reference.bounds.getIntersectionVolume(entry.bounds);
1200  }
1201 
1202  private:
1203  const Box<U, N>& m_bounds;
1204  const Entry& m_reference;
1205  Box<U, N> m_extended;
1206  };
1207 
1208  class MinAxisComparator {
1209  public:
1210  MinAxisComparator(std::size_t axis)
1211  : m_axis(axis)
1212  {
1213 
1214  }
1215 
1216  bool operator()(const Box<U, N>& lhs, const Box<U, N>& rhs) {
1217  return std::make_tuple(lhs.min[m_axis], lhs.max[m_axis]) < std::make_tuple(rhs.min[m_axis], rhs.max[m_axis]);
1218  }
1219 
1220  private:
1221  std::size_t m_axis;
1222  };
1223 
1224  template<typename Entry>
1225  class EntryMinAxisComparator {
1226  public:
1227  EntryMinAxisComparator(std::size_t axis)
1228  : m_axis(axis)
1229  {
1230 
1231  }
1232 
1233  bool operator()(const Entry& lhs, const Entry& rhs) {
1234  return std::make_tuple(lhs.bounds.min[m_axis], lhs.bounds.max[m_axis]) < std::make_tuple(rhs.bounds.min[m_axis], rhs.bounds.max[m_axis]);
1235  }
1236 
1237  private:
1238  std::size_t m_axis;
1239  };
1240 
1241  class MaxAxisComparator {
1242  public:
1243  MaxAxisComparator(std::size_t axis)
1244  : m_axis(axis)
1245  {
1246 
1247  }
1248 
1249  bool operator()(const Box<U, N>& lhs, const Box<U, N>& rhs) {
1250  return std::make_tuple(lhs.max[m_axis], lhs.min[m_axis]) < std::make_tuple(rhs.max[m_axis], rhs.min[m_axis]);
1251  }
1252 
1253  private:
1254  std::size_t m_axis;
1255  };
1256 
1257  template<typename Entry>
1258  class EntryMaxAxisComparator {
1259  public:
1260  EntryMaxAxisComparator(std::size_t axis)
1261  : m_axis(axis)
1262  {
1263 
1264  }
1265 
1266  bool operator()(const Entry& lhs, const Entry& rhs) {
1267  return std::make_tuple(lhs.bounds.max[m_axis], lhs.bounds.min[m_axis]) < std::make_tuple(rhs.bounds.max[m_axis], rhs.bounds.min[m_axis]);
1268  }
1269 
1270  private:
1271  std::size_t m_axis;
1272  };
1273 
1274  private:
1275  void updateBounds(Node *node) {
1276  while (node != nullptr) {
1277  Box<U, N> bounds = node->computeBounds();
1278 
1279  Branch *parent = node->getParent();
1280 
1281  if (parent != nullptr) {
1282  parent->updateBoundsForChild(bounds, node);
1283  }
1284 
1285  node = parent;
1286  }
1287  }
1288 
1289  private:
1290  Node *m_root;
1291  };
1292 
1293 
1294 #ifndef DOXYGEN_SHOULD_SKIP_THIS
1295 }
1296 #endif
1297 }
1298 
1299 #endif // GF_SPATIAL_H
constexpr Box< T, N > getExtended(const Box< T, N > &other) const noexcept
Get the box extended by another box.
Definition: Box.h:335
bool insert(T value, const Box< U, N > &bounds)
Insert an object in the tree.
Definition: Spatial.h:384
constexpr bool intersects(const Box< T, N > &other) const noexcept
Check if two boxes interset.
Definition: Box.h:203
Upper-right quarter.
Definition: Quarter.h:35
The structure represents an internal node.
void clear()
Remove all the objects from the tree.
Definition: Spatial.h:143
std::size_t query(const Box< U, N > &bounds, SpatialQueryCallback< T > callback, SpatialQuery kind=SpatialQuery::Intersect) const
Query objects in the tree.
Definition: Spatial.h:446
std::function< void(const T &)> SpatialQueryCallback
A callback for spatial query.
Definition: Spatial.h:87
std::vector< SpatialStructure< U, N > > getStructure() const
Definition: Spatial.h:458
constexpr Vector2f transform(const Matrix3f &mat, Vector2f point)
Apply an affine transformation to a 2D point.
Definition: Transform.h:323
SpatialStructureType type
The type of the structure.
Definition: Spatial.h:69
SpatialStructureType
A type of spatial structure.
Definition: Spatial.h:53
Box< U, N > bounds
The bounds of the structure.
Definition: Spatial.h:68
Vector< T, N > min
The minimum point of the box.
Definition: Box.h:53
Search for all objects that contain the given bounds.
constexpr Box< T, 2 > computeBoxQuarter(const Box< T, 2 > &box, Quarter quarter)
Divide a box in quarters.
Definition: Box.h:466
~RStarTree()
Destructor.
Definition: Spatial.h:373
Lower-right quarter.
Definition: Quarter.h:36
A spatial structure.
Definition: Spatial.h:67
Upper-left quarter.
Definition: Quarter.h:34
std::vector< SpatialStructure< U, 2 > > getStructure() const
Definition: Spatial.h:148
constexpr T square(T val)
Square function.
Definition: Math.h:289
std::size_t query(const Box< U, 2 > &bounds, SpatialQueryCallback< T > callback, SpatialQuery kind=SpatialQuery::Intersect) const
Query objects in the tree.
Definition: Spatial.h:136
Search for all objects that intersect the given bounds.
RStarTree & operator=(RStarTree &&other) noexcept
Move assignement.
Definition: Spatial.h:365
void clear()
Remove all the objects from the tree.
Definition: Spatial.h:453
The namespace for gf classes.
Definition: Action.h:35
QuadTree(const Box< U, 2 > &bounds)
Constructor.
Definition: Spatial.h:105
RStarTree()
Constructor.
Definition: Spatial.h:338
An implementation of quadtree.
Definition: Spatial.h:97
Lower-left quarter.
Definition: Quarter.h:37
The structure represents an actuel object.
Vector< T, N > max
The maximum point of the box.
Definition: Box.h:54
int level
The level of the structure.
Definition: Spatial.h:70
RStarTree(RStarTree &&other) noexcept
Move constructor.
Definition: Spatial.h:357
An implemntation of a R* tree.
Definition: Spatial.h:330
SpatialQuery
A kind of spatial query.
Definition: Spatial.h:77
bool insert(T value, const Box< U, 2 > &bounds)
Insert an object in the tree.
Definition: Spatial.h:118
constexpr bool contains(Vector< T, N > point) const noexcept
Check if a point is inside the box.
Definition: Box.h:171
constexpr void unused(Args &&...)
A simple way to avoid warnings about unused variables.
Definition: Unused.h:35