forked from nushoin/RTree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RTree.h
1696 lines (1391 loc) · 45.6 KB
/
RTree.h
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
#ifndef RTREE_H
#define RTREE_H
// NOTE This file compiles under MSVC 6 SP5 and MSVC .Net 2003 it may not work on other compilers without modification.
// NOTE These next few lines may be win32 specific, you may need to modify them to compile on other platform
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <stdlib.h>
#include <algorithm>
#include <functional>
#include <vector>
#define ASSERT assert // RTree uses ASSERT( condition )
#ifndef Min
#define Min std::min
#endif //Min
#ifndef Max
#define Max std::max
#endif //Max
//
// RTree.h
//
#define RTREE_TEMPLATE template<class DATATYPE, class ELEMTYPE, int NUMDIMS, class ELEMTYPEREAL, int TMAXNODES, int TMINNODES>
#define RTREE_QUAL RTree<DATATYPE, ELEMTYPE, NUMDIMS, ELEMTYPEREAL, TMAXNODES, TMINNODES>
#define RTREE_DONT_USE_MEMPOOLS // This version does not contain a fixed memory allocator, fill in lines with EXAMPLE to implement one.
#define RTREE_USE_SPHERICAL_VOLUME // Better split classification, may be slower on some systems
// Fwd decl
class RTFileStream; // File I/O helper class, look below for implementation and notes.
/// \class RTree
/// Implementation of RTree, a multidimensional bounding rectangle tree.
/// Example usage: For a 3-dimensional tree use RTree<Object*, float, 3> myTree;
///
/// This modified, templated C++ version by Greg Douglas at Auran (http://www.auran.com)
///
/// DATATYPE Referenced data, should be int, void*, obj* etc. no larger than sizeof<void*> and simple type
/// ELEMTYPE Type of element such as int or float
/// NUMDIMS Number of dimensions such as 2 or 3
/// ELEMTYPEREAL Type of element that allows fractional and large values such as float or double, for use in volume calcs
///
/// NOTES: Inserting and removing data requires the knowledge of its constant Minimal Bounding Rectangle.
/// This version uses new/delete for nodes, I recommend using a fixed size allocator for efficiency.
/// Instead of using a callback function for returned results, I recommend and efficient pre-sized, grow-only memory
/// array similar to MFC CArray or STL Vector for returning search query result.
///
template<class DATATYPE, class ELEMTYPE, int NUMDIMS,
class ELEMTYPEREAL = ELEMTYPE, int TMAXNODES = 8, int TMINNODES = TMAXNODES / 2>
class RTree
{
static_assert(std::numeric_limits<ELEMTYPEREAL>::is_iec559, "'ELEMTYPEREAL' accepts floating-point types only");
protected:
struct Node; // Fwd decl. Used by other internal structs and iterator
public:
// These constant must be declared after Branch and before Node struct
// Stuck up here for MSVC 6 compiler. NSVC .NET 2003 is much happier.
enum
{
MAXNODES = TMAXNODES, ///< Max elements in node
MINNODES = TMINNODES, ///< Min elements in node
};
public:
RTree();
RTree(const RTree& other);
virtual ~RTree();
/// Insert entry
/// \param a_min Min of bounding rect
/// \param a_max Max of bounding rect
/// \param a_dataId Positive Id of data. Maybe zero, but negative numbers not allowed.
void Insert(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMDIMS], const DATATYPE& a_dataId);
/// Remove entry
/// \param a_min Min of bounding rect
/// \param a_max Max of bounding rect
/// \param a_dataId Positive Id of data. Maybe zero, but negative numbers not allowed.
void Remove(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMDIMS], const DATATYPE& a_dataId);
/// Find all within search rectangle
/// \param a_min Min of search bounding rect
/// \param a_max Max of search bounding rect
/// \param a_searchResult Search result array. Caller should set grow size. Function will reset, not append to array.
/// \param a_resultCallback Callback function to return result. Callback should return 'true' to continue searching
/// \param a_context User context to pass as parameter to a_resultCallback
/// \return Returns the number of entries found
int Search(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMDIMS], std::function<bool (const DATATYPE&)> callback) const;
/// Remove all entries from tree
void RemoveAll();
/// Count the data elements in this container. This is slow as no internal counter is maintained.
int Count();
/// Load tree contents from file
bool Load(const char* a_fileName);
/// Load tree contents from stream
bool Load(RTFileStream& a_stream);
/// Save tree contents to file
bool Save(const char* a_fileName);
/// Save tree contents to stream
bool Save(RTFileStream& a_stream);
/// Iterator is not remove safe.
class Iterator
{
private:
enum { MAX_STACK = 32 }; // Max stack size. Allows almost n^32 where n is number of branches in node
struct StackElement
{
Node* m_node;
int m_branchIndex;
};
public:
Iterator() { Init(); }
~Iterator() { }
/// Is iterator invalid
bool IsNull() { return (m_tos <= 0); }
/// Is iterator pointing to valid data
bool IsNotNull() { return (m_tos > 0); }
/// Access the current data element. Caller must be sure iterator is not NULL first.
DATATYPE& operator*()
{
ASSERT(IsNotNull());
StackElement& curTos = m_stack[m_tos - 1];
return curTos.m_node->m_branch[curTos.m_branchIndex].m_data;
}
/// Access the current data element. Caller must be sure iterator is not NULL first.
const DATATYPE& operator*() const
{
ASSERT(IsNotNull());
StackElement& curTos = m_stack[m_tos - 1];
return curTos.m_node->m_branch[curTos.m_branchIndex].m_data;
}
/// Find the next data element
bool operator++() { return FindNextData(); }
/// Get the bounds for this node
void GetBounds(ELEMTYPE a_min[NUMDIMS], ELEMTYPE a_max[NUMDIMS])
{
ASSERT(IsNotNull());
StackElement& curTos = m_stack[m_tos - 1];
Branch& curBranch = curTos.m_node->m_branch[curTos.m_branchIndex];
for(int index = 0; index < NUMDIMS; ++index)
{
a_min[index] = curBranch.m_rect.m_min[index];
a_max[index] = curBranch.m_rect.m_max[index];
}
}
private:
/// Reset iterator
void Init() { m_tos = 0; }
/// Find the next data element in the tree (For internal use only)
bool FindNextData()
{
for(;;)
{
if(m_tos <= 0)
{
return false;
}
StackElement curTos = Pop(); // Copy stack top cause it may change as we use it
if(curTos.m_node->IsLeaf())
{
// Keep walking through data while we can
if(curTos.m_branchIndex+1 < curTos.m_node->m_count)
{
// There is more data, just point to the next one
Push(curTos.m_node, curTos.m_branchIndex + 1);
return true;
}
// No more data, so it will fall back to previous level
}
else
{
if(curTos.m_branchIndex+1 < curTos.m_node->m_count)
{
// Push sibling on for future tree walk
// This is the 'fall back' node when we finish with the current level
Push(curTos.m_node, curTos.m_branchIndex + 1);
}
// Since cur node is not a leaf, push first of next level to get deeper into the tree
Node* nextLevelnode = curTos.m_node->m_branch[curTos.m_branchIndex].m_child;
Push(nextLevelnode, 0);
// If we pushed on a new leaf, exit as the data is ready at TOS
if(nextLevelnode->IsLeaf())
{
return true;
}
}
}
}
/// Push node and branch onto iteration stack (For internal use only)
void Push(Node* a_node, int a_branchIndex)
{
m_stack[m_tos].m_node = a_node;
m_stack[m_tos].m_branchIndex = a_branchIndex;
++m_tos;
ASSERT(m_tos <= MAX_STACK);
}
/// Pop element off iteration stack (For internal use only)
StackElement& Pop()
{
ASSERT(m_tos > 0);
--m_tos;
return m_stack[m_tos];
}
StackElement m_stack[MAX_STACK]; ///< Stack as we are doing iteration instead of recursion
int m_tos; ///< Top Of Stack index
friend class RTree; // Allow hiding of non-public functions while allowing manipulation by logical owner
};
/// Get 'first' for iteration
void GetFirst(Iterator& a_it)
{
a_it.Init();
Node* first = m_root;
while(first)
{
if(first->IsInternalNode() && first->m_count > 1)
{
a_it.Push(first, 1); // Descend sibling branch later
}
else if(first->IsLeaf())
{
if(first->m_count)
{
a_it.Push(first, 0);
}
break;
}
first = first->m_branch[0].m_child;
}
}
/// Get Next for iteration
void GetNext(Iterator& a_it) { ++a_it; }
/// Is iterator NULL, or at end?
bool IsNull(Iterator& a_it) { return a_it.IsNull(); }
/// Get object at iterator position
DATATYPE& GetAt(Iterator& a_it) { return *a_it; }
protected:
/// Minimal bounding rectangle (n-dimensional)
struct Rect
{
ELEMTYPE m_min[NUMDIMS]; ///< Min dimensions of bounding box
ELEMTYPE m_max[NUMDIMS]; ///< Max dimensions of bounding box
};
/// May be data or may be another subtree
/// The parents level determines this.
/// If the parents level is 0, then this is data
struct Branch
{
Rect m_rect; ///< Bounds
Node* m_child; ///< Child node
DATATYPE m_data; ///< Data Id
};
/// Node for each branch level
struct Node
{
bool IsInternalNode() { return (m_level > 0); } // Not a leaf, but a internal node
bool IsLeaf() { return (m_level == 0); } // A leaf, contains data
int m_count; ///< Count
int m_level; ///< Leaf is zero, others positive
Branch m_branch[MAXNODES]; ///< Branch
};
/// A link list of nodes for reinsertion after a delete operation
struct ListNode
{
ListNode* m_next; ///< Next in list
Node* m_node; ///< Node
};
/// Variables for finding a split partition
struct PartitionVars
{
enum { NOT_TAKEN = -1 }; // indicates that position
int m_partition[MAXNODES+1];
int m_total;
int m_minFill;
int m_count[2];
Rect m_cover[2];
ELEMTYPEREAL m_area[2];
Branch m_branchBuf[MAXNODES+1];
int m_branchCount;
Rect m_coverSplit;
ELEMTYPEREAL m_coverSplitArea;
};
Node* AllocNode();
void FreeNode(Node* a_node);
void InitNode(Node* a_node);
void InitRect(Rect* a_rect);
bool InsertRectRec(const Branch& a_branch, Node* a_node, Node** a_newNode, int a_level);
bool InsertRect(const Branch& a_branch, Node** a_root, int a_level);
Rect NodeCover(Node* a_node);
bool AddBranch(const Branch* a_branch, Node* a_node, Node** a_newNode);
void DisconnectBranch(Node* a_node, int a_index);
int PickBranch(const Rect* a_rect, Node* a_node);
Rect CombineRect(const Rect* a_rectA, const Rect* a_rectB);
void SplitNode(Node* a_node, const Branch* a_branch, Node** a_newNode);
ELEMTYPEREAL RectSphericalVolume(Rect* a_rect);
ELEMTYPEREAL RectVolume(Rect* a_rect);
ELEMTYPEREAL CalcRectVolume(Rect* a_rect);
void GetBranches(Node* a_node, const Branch* a_branch, PartitionVars* a_parVars);
void ChoosePartition(PartitionVars* a_parVars, int a_minFill);
void LoadNodes(Node* a_nodeA, Node* a_nodeB, PartitionVars* a_parVars);
void InitParVars(PartitionVars* a_parVars, int a_maxRects, int a_minFill);
void PickSeeds(PartitionVars* a_parVars);
void Classify(int a_index, int a_group, PartitionVars* a_parVars);
bool RemoveRect(Rect* a_rect, const DATATYPE& a_id, Node** a_root);
bool RemoveRectRec(Rect* a_rect, const DATATYPE& a_id, Node* a_node, ListNode** a_listNode);
ListNode* AllocListNode();
void FreeListNode(ListNode* a_listNode);
bool Overlap(Rect* a_rectA, Rect* a_rectB) const;
void ReInsert(Node* a_node, ListNode** a_listNode);
bool Search(Node* a_node, Rect* a_rect, int& a_foundCount, std::function<bool (const DATATYPE&)> callback) const;
void RemoveAllRec(Node* a_node);
void Reset();
void CountRec(Node* a_node, int& a_count);
bool SaveRec(Node* a_node, RTFileStream& a_stream);
bool LoadRec(Node* a_node, RTFileStream& a_stream);
void CopyRec(Node* current, Node* other);
Node* m_root; ///< Root of tree
ELEMTYPEREAL m_unitSphereVolume; ///< Unit sphere constant for required number of dimensions
public:
// return all the AABBs that form the RTree
std::vector<Rect> ListTree() const;
};
// Because there is not stream support, this is a quick and dirty file I/O helper.
// Users will likely replace its usage with a Stream implementation from their favorite API.
class RTFileStream
{
FILE* m_file;
public:
RTFileStream()
{
m_file = NULL;
}
~RTFileStream()
{
Close();
}
bool Open(const char* a_fileName, const char* mode)
{
#if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__)
return fopen_s(&m_file, a_fileName, mode) == 0;
#else
m_file = fopen(a_fileName, mode);
return m_file != nullptr;
#endif
}
bool OpenRead(const char* a_fileName)
{
return this->Open(a_fileName, "rb");
}
bool OpenWrite(const char* a_fileName)
{
return this->Open(a_fileName, "wb");
}
void Close()
{
if(m_file)
{
fclose(m_file);
m_file = NULL;
}
}
template< typename TYPE >
size_t Write(const TYPE& a_value)
{
ASSERT(m_file);
return fwrite((void*)&a_value, sizeof(a_value), 1, m_file);
}
template< typename TYPE >
size_t WriteArray(const TYPE* a_array, int a_count)
{
ASSERT(m_file);
return fwrite((void*)a_array, sizeof(TYPE) * a_count, 1, m_file);
}
template< typename TYPE >
size_t Read(TYPE& a_value)
{
ASSERT(m_file);
return fread((void*)&a_value, sizeof(a_value), 1, m_file);
}
template< typename TYPE >
size_t ReadArray(TYPE* a_array, int a_count)
{
ASSERT(m_file);
return fread((void*)a_array, sizeof(TYPE) * a_count, 1, m_file);
}
};
RTREE_TEMPLATE
RTREE_QUAL::RTree()
{
ASSERT(MAXNODES > MINNODES);
ASSERT(MINNODES > 0);
// Precomputed volumes of the unit spheres for the first few dimensions
const float UNIT_SPHERE_VOLUMES[] = {
0.000000f, 2.000000f, 3.141593f, // Dimension 0,1,2
4.188790f, 4.934802f, 5.263789f, // Dimension 3,4,5
5.167713f, 4.724766f, 4.058712f, // Dimension 6,7,8
3.298509f, 2.550164f, 1.884104f, // Dimension 9,10,11
1.335263f, 0.910629f, 0.599265f, // Dimension 12,13,14
0.381443f, 0.235331f, 0.140981f, // Dimension 15,16,17
0.082146f, 0.046622f, 0.025807f, // Dimension 18,19,20
};
m_root = AllocNode();
m_root->m_level = 0;
m_unitSphereVolume = (ELEMTYPEREAL)UNIT_SPHERE_VOLUMES[NUMDIMS];
}
RTREE_TEMPLATE
RTREE_QUAL::RTree(const RTree& other) : RTree()
{
CopyRec(m_root, other.m_root);
}
RTREE_TEMPLATE
RTREE_QUAL::~RTree()
{
Reset(); // Free, or reset node memory
}
RTREE_TEMPLATE
void RTREE_QUAL::Insert(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMDIMS], const DATATYPE& a_dataId)
{
#ifdef _DEBUG
for(int index=0; index<NUMDIMS; ++index)
{
ASSERT(a_min[index] <= a_max[index]);
}
#endif //_DEBUG
Branch branch;
branch.m_data = a_dataId;
branch.m_child = NULL;
for(int axis=0; axis<NUMDIMS; ++axis)
{
branch.m_rect.m_min[axis] = a_min[axis];
branch.m_rect.m_max[axis] = a_max[axis];
}
InsertRect(branch, &m_root, 0);
}
RTREE_TEMPLATE
void RTREE_QUAL::Remove(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMDIMS], const DATATYPE& a_dataId)
{
#ifdef _DEBUG
for(int index=0; index<NUMDIMS; ++index)
{
ASSERT(a_min[index] <= a_max[index]);
}
#endif //_DEBUG
Rect rect;
for(int axis=0; axis<NUMDIMS; ++axis)
{
rect.m_min[axis] = a_min[axis];
rect.m_max[axis] = a_max[axis];
}
RemoveRect(&rect, a_dataId, &m_root);
}
RTREE_TEMPLATE
int RTREE_QUAL::Search(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMDIMS], std::function<bool (const DATATYPE&)> callback) const
{
#ifdef _DEBUG
for(int index=0; index<NUMDIMS; ++index)
{
ASSERT(a_min[index] <= a_max[index]);
}
#endif //_DEBUG
Rect rect;
for(int axis=0; axis<NUMDIMS; ++axis)
{
rect.m_min[axis] = a_min[axis];
rect.m_max[axis] = a_max[axis];
}
// NOTE: May want to return search result another way, perhaps returning the number of found elements here.
int foundCount = 0;
Search(m_root, &rect, foundCount, callback);
return foundCount;
}
RTREE_TEMPLATE
int RTREE_QUAL::Count()
{
int count = 0;
CountRec(m_root, count);
return count;
}
RTREE_TEMPLATE
void RTREE_QUAL::CountRec(Node* a_node, int& a_count)
{
if(a_node->IsInternalNode()) // not a leaf node
{
for(int index = 0; index < a_node->m_count; ++index)
{
CountRec(a_node->m_branch[index].m_child, a_count);
}
}
else // A leaf node
{
a_count += a_node->m_count;
}
}
RTREE_TEMPLATE
bool RTREE_QUAL::Load(const char* a_fileName)
{
RemoveAll(); // Clear existing tree
RTFileStream stream;
if(!stream.OpenRead(a_fileName))
{
return false;
}
bool result = Load(stream);
stream.Close();
return result;
}
RTREE_TEMPLATE
bool RTREE_QUAL::Load(RTFileStream& a_stream)
{
// Write some kind of header
int _dataFileId = ('R'<<0)|('T'<<8)|('R'<<16)|('E'<<24);
int _dataSize = sizeof(DATATYPE);
int _dataNumDims = NUMDIMS;
int _dataElemSize = sizeof(ELEMTYPE);
int _dataElemRealSize = sizeof(ELEMTYPEREAL);
int _dataMaxNodes = TMAXNODES;
int _dataMinNodes = TMINNODES;
int dataFileId = 0;
int dataSize = 0;
int dataNumDims = 0;
int dataElemSize = 0;
int dataElemRealSize = 0;
int dataMaxNodes = 0;
int dataMinNodes = 0;
a_stream.Read(dataFileId);
a_stream.Read(dataSize);
a_stream.Read(dataNumDims);
a_stream.Read(dataElemSize);
a_stream.Read(dataElemRealSize);
a_stream.Read(dataMaxNodes);
a_stream.Read(dataMinNodes);
bool result = false;
// Test if header was valid and compatible
if( (dataFileId == _dataFileId)
&& (dataSize == _dataSize)
&& (dataNumDims == _dataNumDims)
&& (dataElemSize == _dataElemSize)
&& (dataElemRealSize == _dataElemRealSize)
&& (dataMaxNodes == _dataMaxNodes)
&& (dataMinNodes == _dataMinNodes)
)
{
// Recursively load tree
result = LoadRec(m_root, a_stream);
}
return result;
}
RTREE_TEMPLATE
bool RTREE_QUAL::LoadRec(Node* a_node, RTFileStream& a_stream)
{
a_stream.Read(a_node->m_level);
a_stream.Read(a_node->m_count);
if(a_node->IsInternalNode()) // not a leaf node
{
for(int index = 0; index < a_node->m_count; ++index)
{
Branch* curBranch = &a_node->m_branch[index];
a_stream.ReadArray(curBranch->m_rect.m_min, NUMDIMS);
a_stream.ReadArray(curBranch->m_rect.m_max, NUMDIMS);
curBranch->m_child = AllocNode();
LoadRec(curBranch->m_child, a_stream);
}
}
else // A leaf node
{
for(int index = 0; index < a_node->m_count; ++index)
{
Branch* curBranch = &a_node->m_branch[index];
a_stream.ReadArray(curBranch->m_rect.m_min, NUMDIMS);
a_stream.ReadArray(curBranch->m_rect.m_max, NUMDIMS);
a_stream.Read(curBranch->m_data);
}
}
return true; // Should do more error checking on I/O operations
}
RTREE_TEMPLATE
void RTREE_QUAL::CopyRec(Node* current, Node* other)
{
current->m_level = other->m_level;
current->m_count = other->m_count;
if(current->IsInternalNode()) // not a leaf node
{
for(int index = 0; index < current->m_count; ++index)
{
Branch* currentBranch = ¤t->m_branch[index];
Branch* otherBranch = &other->m_branch[index];
std::copy(otherBranch->m_rect.m_min,
otherBranch->m_rect.m_min + NUMDIMS,
currentBranch->m_rect.m_min);
std::copy(otherBranch->m_rect.m_max,
otherBranch->m_rect.m_max + NUMDIMS,
currentBranch->m_rect.m_max);
currentBranch->m_child = AllocNode();
CopyRec(currentBranch->m_child, otherBranch->m_child);
}
}
else // A leaf node
{
for(int index = 0; index < current->m_count; ++index)
{
Branch* currentBranch = ¤t->m_branch[index];
Branch* otherBranch = &other->m_branch[index];
std::copy(otherBranch->m_rect.m_min,
otherBranch->m_rect.m_min + NUMDIMS,
currentBranch->m_rect.m_min);
std::copy(otherBranch->m_rect.m_max,
otherBranch->m_rect.m_max + NUMDIMS,
currentBranch->m_rect.m_max);
currentBranch->m_data = otherBranch->m_data;
}
}
}
RTREE_TEMPLATE
bool RTREE_QUAL::Save(const char* a_fileName)
{
RTFileStream stream;
if(!stream.OpenWrite(a_fileName))
{
return false;
}
bool result = Save(stream);
stream.Close();
return result;
}
RTREE_TEMPLATE
bool RTREE_QUAL::Save(RTFileStream& a_stream)
{
// Write some kind of header
int dataFileId = ('R'<<0)|('T'<<8)|('R'<<16)|('E'<<24);
int dataSize = sizeof(DATATYPE);
int dataNumDims = NUMDIMS;
int dataElemSize = sizeof(ELEMTYPE);
int dataElemRealSize = sizeof(ELEMTYPEREAL);
int dataMaxNodes = TMAXNODES;
int dataMinNodes = TMINNODES;
a_stream.Write(dataFileId);
a_stream.Write(dataSize);
a_stream.Write(dataNumDims);
a_stream.Write(dataElemSize);
a_stream.Write(dataElemRealSize);
a_stream.Write(dataMaxNodes);
a_stream.Write(dataMinNodes);
// Recursively save tree
bool result = SaveRec(m_root, a_stream);
return result;
}
RTREE_TEMPLATE
bool RTREE_QUAL::SaveRec(Node* a_node, RTFileStream& a_stream)
{
a_stream.Write(a_node->m_level);
a_stream.Write(a_node->m_count);
if(a_node->IsInternalNode()) // not a leaf node
{
for(int index = 0; index < a_node->m_count; ++index)
{
Branch* curBranch = &a_node->m_branch[index];
a_stream.WriteArray(curBranch->m_rect.m_min, NUMDIMS);
a_stream.WriteArray(curBranch->m_rect.m_max, NUMDIMS);
SaveRec(curBranch->m_child, a_stream);
}
}
else // A leaf node
{
for(int index = 0; index < a_node->m_count; ++index)
{
Branch* curBranch = &a_node->m_branch[index];
a_stream.WriteArray(curBranch->m_rect.m_min, NUMDIMS);
a_stream.WriteArray(curBranch->m_rect.m_max, NUMDIMS);
a_stream.Write(curBranch->m_data);
}
}
return true; // Should do more error checking on I/O operations
}
RTREE_TEMPLATE
void RTREE_QUAL::RemoveAll()
{
// Delete all existing nodes
Reset();
m_root = AllocNode();
m_root->m_level = 0;
}
RTREE_TEMPLATE
void RTREE_QUAL::Reset()
{
#ifdef RTREE_DONT_USE_MEMPOOLS
// Delete all existing nodes
RemoveAllRec(m_root);
#else // RTREE_DONT_USE_MEMPOOLS
// Just reset memory pools. We are not using complex types
// EXAMPLE
#endif // RTREE_DONT_USE_MEMPOOLS
}
RTREE_TEMPLATE
void RTREE_QUAL::RemoveAllRec(Node* a_node)
{
ASSERT(a_node);
ASSERT(a_node->m_level >= 0);
if(a_node->IsInternalNode()) // This is an internal node in the tree
{
for(int index=0; index < a_node->m_count; ++index)
{
RemoveAllRec(a_node->m_branch[index].m_child);
}
}
FreeNode(a_node);
}
RTREE_TEMPLATE
typename RTREE_QUAL::Node* RTREE_QUAL::AllocNode()
{
Node* newNode;
#ifdef RTREE_DONT_USE_MEMPOOLS
newNode = new Node;
#else // RTREE_DONT_USE_MEMPOOLS
// EXAMPLE
#endif // RTREE_DONT_USE_MEMPOOLS
InitNode(newNode);
return newNode;
}
RTREE_TEMPLATE
void RTREE_QUAL::FreeNode(Node* a_node)
{
ASSERT(a_node);
#ifdef RTREE_DONT_USE_MEMPOOLS
delete a_node;
#else // RTREE_DONT_USE_MEMPOOLS
// EXAMPLE
#endif // RTREE_DONT_USE_MEMPOOLS
}
// Allocate space for a node in the list used in DeletRect to
// store Nodes that are too empty.
RTREE_TEMPLATE
typename RTREE_QUAL::ListNode* RTREE_QUAL::AllocListNode()
{
#ifdef RTREE_DONT_USE_MEMPOOLS
return new ListNode;
#else // RTREE_DONT_USE_MEMPOOLS
// EXAMPLE
#endif // RTREE_DONT_USE_MEMPOOLS
}
RTREE_TEMPLATE
void RTREE_QUAL::FreeListNode(ListNode* a_listNode)
{
#ifdef RTREE_DONT_USE_MEMPOOLS
delete a_listNode;
#else // RTREE_DONT_USE_MEMPOOLS
// EXAMPLE
#endif // RTREE_DONT_USE_MEMPOOLS
}
RTREE_TEMPLATE
void RTREE_QUAL::InitNode(Node* a_node)
{
a_node->m_count = 0;
a_node->m_level = -1;
}
RTREE_TEMPLATE
void RTREE_QUAL::InitRect(Rect* a_rect)
{
for(int index = 0; index < NUMDIMS; ++index)
{
a_rect->m_min[index] = (ELEMTYPE)0;
a_rect->m_max[index] = (ELEMTYPE)0;
}
}
// Inserts a new data rectangle into the index structure.
// Recursively descends tree, propagates splits back up.
// Returns 0 if node was not split. Old node updated.
// If node was split, returns 1 and sets the pointer pointed to by
// new_node to point to the new node. Old node updated to become one of two.
// The level argument specifies the number of steps up from the leaf
// level to insert; e.g. a data rectangle goes in at level = 0.
RTREE_TEMPLATE
bool RTREE_QUAL::InsertRectRec(const Branch& a_branch, Node* a_node, Node** a_newNode, int a_level)
{
ASSERT(a_node && a_newNode);
ASSERT(a_level >= 0 && a_level <= a_node->m_level);
// recurse until we reach the correct level for the new record. data records
// will always be called with a_level == 0 (leaf)
if(a_node->m_level > a_level)
{
// Still above level for insertion, go down tree recursively
Node* otherNode;
// find the optimal branch for this record
int index = PickBranch(&a_branch.m_rect, a_node);
// recursively insert this record into the picked branch
bool childWasSplit = InsertRectRec(a_branch, a_node->m_branch[index].m_child, &otherNode, a_level);
if (!childWasSplit)
{
// Child was not split. Merge the bounding box of the new record with the
// existing bounding box
a_node->m_branch[index].m_rect = CombineRect(&a_branch.m_rect, &(a_node->m_branch[index].m_rect));
return false;
}
else
{
// Child was split. The old branches are now re-partitioned to two nodes
// so we have to re-calculate the bounding boxes of each node
a_node->m_branch[index].m_rect = NodeCover(a_node->m_branch[index].m_child);
Branch branch;
branch.m_child = otherNode;
branch.m_rect = NodeCover(otherNode);
// The old node is already a child of a_node. Now add the newly-created
// node to a_node as well. a_node might be split because of that.
return AddBranch(&branch, a_node, a_newNode);
}
}
else if(a_node->m_level == a_level)
{
// We have reached level for insertion. Add rect, split if necessary
return AddBranch(&a_branch, a_node, a_newNode);
}
else
{
// Should never occur
ASSERT(0);
return false;
}
}
// Insert a data rectangle into an index structure.
// InsertRect provides for splitting the root;
// returns 1 if root was split, 0 if it was not.
// The level argument specifies the number of steps up from the leaf
// level to insert; e.g. a data rectangle goes in at level = 0.