summaryrefslogtreecommitdiff
path: root/indra/llmath/lloctree.h
blob: 88ba006269690677521e868e6157f98dae2b8f7a (plain)
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
/**
 * @file lloctree.h
 * @brief Octree declaration.
 *
 * $LicenseInfo:firstyear=2005&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#ifndef LL_LLOCTREE_H
#define LL_LLOCTREE_H

#include "lltreenode.h"
#include "v3math.h"
#include "llvector4a.h"
#include <vector>

#define OCT_ERRS LL_WARNS("OctreeErrors")

#define OCTREE_DEBUG_COLOR_REMOVE   0x0000FF // r
#define OCTREE_DEBUG_COLOR_INSERT   0x00FF00 // g
#define OCTREE_DEBUG_COLOR_BALANCE  0xFF0000 // b

extern U32 gOctreeMaxCapacity;
extern float gOctreeMinSize;

/*#define LL_OCTREE_PARANOIA_CHECK 0
#if LL_DARWIN
#define LL_OCTREE_MAX_CAPACITY 32
#else
#define LL_OCTREE_MAX_CAPACITY 128
#endif*/

// T is the type of the element referenced by the octree node.
// T_PTR determines how pointers to elements are stored internally.
// LLOctreeNode<T, LLPointer<T>> assumes ownership of inserted elements and
// deletes elements removed from the tree.
// LLOctreeNode<T, T*> doesn't take ownership of inserted elements, so the API
// user is responsible for managing the storage lifecycle of elements added to
// the tree.
template <class T, typename T_PTR> class LLOctreeNode;

template <class T, typename T_PTR>
class LLOctreeListener: public LLTreeListener<T>
{
public:
    typedef LLTreeListener<T> BaseType;
    typedef LLOctreeNode<T, T_PTR> oct_node;

    virtual void handleChildAddition(const oct_node* parent, oct_node* child) = 0;
    virtual void handleChildRemoval(const oct_node* parent, const oct_node* child) = 0;
};

template <class T, typename T_PTR>
class LLOctreeTraveler
{
public:
    virtual void traverse(const LLOctreeNode<T, T_PTR>* node);
    virtual void visit(const LLOctreeNode<T, T_PTR>* branch) = 0;
};

template <class T, typename T_PTR>
class LLOctreeTravelerDepthFirst : public LLOctreeTraveler<T, T_PTR>
{
public:
    virtual void traverse(const LLOctreeNode<T, T_PTR>* node) override;
};

template <class T, typename T_PTR>
class alignas(16) LLOctreeNode : public LLTreeNode<T>
{
    LL_ALIGN_NEW
public:

    typedef LLOctreeTraveler<T, T_PTR>                          oct_traveler;
    typedef LLTreeTraveler<T>                                   tree_traveler;
    typedef std::vector<T_PTR>                                  element_list;
    typedef typename element_list::iterator                     element_iter;
    typedef typename element_list::const_iterator               const_element_iter;
    typedef typename std::vector<LLTreeListener<T>*>::iterator  tree_listener_iter;
    typedef LLOctreeNode<T, T_PTR>**                            child_list;
    typedef LLOctreeNode<T, T_PTR>**                            child_iter;

    typedef LLTreeNode<T>               BaseType;
    typedef LLOctreeNode<T, T_PTR>      oct_node;
    typedef LLOctreeListener<T, T_PTR>  oct_listener;

    enum
    {
        NO_CHILD_NODES = 255 // Note: This is an U8 to match the max value in mChildMap[]
    };

    LLOctreeNode(   const LLVector4a& center,
                    const LLVector4a& size,
                    BaseType* parent,
                    U8 octant = NO_CHILD_NODES)
    :   mParent((oct_node*)parent),
        mOctant(octant)
    {
        llassert(size[0] >= gOctreeMinSize*0.5f);

        mCenter = center;
        mSize = size;

        updateMinMax();
        if ((mOctant == NO_CHILD_NODES) && mParent)
        {
            mOctant = ((oct_node*) mParent)->getOctant(mCenter);
        }

        clearChildren();
    }

    virtual ~LLOctreeNode()
    {
        BaseType::destroyListeners();

        const U32 element_count = getElementCount();
        for (U32 i = 0; i < element_count; ++i)
        {
            mData[i]->setBinIndex(-1);
            mData[i] = NULL;
        }

        mData.clear();

        for (U32 i = 0; i < getChildCount(); i++)
        {
            delete getChild(i);
        }
    }

    inline const BaseType* getParent()  const           { return mParent; }
    inline void setParent(BaseType* parent)             { mParent = (oct_node*) parent; }
    inline const LLVector4a& getCenter() const          { return mCenter; }
    inline const LLVector4a& getSize() const            { return mSize; }
    inline void setCenter(const LLVector4a& center)     { mCenter = center; }
    inline void setSize(const LLVector4a& size)         { mSize = size; }
    inline oct_node* getNodeAt(T* data)                 { return getNodeAt(data->getPositionGroup(), data->getBinRadius()); }
    inline U8 getOctant() const                         { return mOctant; }
    inline const oct_node*  getOctParent() const        { return (const oct_node*) getParent(); }
    inline oct_node* getOctParent()                     { return (oct_node*) getParent(); }

    U8 getOctant(const LLVector4a& pos) const           //get the octant pos is in
    {
        return (U8) (pos.greaterThan(mCenter).getGatheredBits() & 0x7);
    }

    inline bool isInside(const LLVector4a& pos, const F32& rad) const
    {
        return rad <= mSize[0]*2.f && isInside(pos);
    }

    inline bool isInside(T* data) const
    {
        return isInside(data->getPositionGroup(), data->getBinRadius());
    }

    bool isInside(const LLVector4a& pos) const
    {
        S32 gt = pos.greaterThan(mMax).getGatheredBits() & 0x7;
        if (gt)
        {
            return false;
        }

        S32 lt = pos.lessEqual(mMin).getGatheredBits() & 0x7;
        if (lt)
        {
            return false;
        }

        return true;
    }

    void updateMinMax()
    {
        mMax.setAdd(mCenter, mSize);
        mMin.setSub(mCenter, mSize);
    }

    inline oct_listener* getOctListener(U32 index)
    {
        return (oct_listener*) BaseType::getListener(index);
    }

    inline bool contains(T* xform)
    {
        return contains(xform->getBinRadius());
    }

    bool contains(F32 radius)
    {
        if (mParent == NULL)
        {   //root node contains nothing
            return false;
        }

        F32 size = mSize[0];
        F32 p_size = size * 2.f;

        return (radius <= gOctreeMinSize && size <= gOctreeMinSize) ||
                (radius <= p_size && radius > size);
    }

    static void pushCenter(LLVector4a &center, const LLVector4a &size, const T* data)
    {
        const LLVector4a& pos = data->getPositionGroup();

        LLVector4Logical gt = pos.greaterThan(center);

        LLVector4a up;
        up = _mm_and_ps(size, gt);

        LLVector4a down;
        down = _mm_andnot_ps(gt, size);

        center.add(up);
        center.sub(down);
    }

    void accept(oct_traveler* visitor)              { visitor->visit(this); }
    virtual bool isLeaf() const                     { return mChildCount == 0; }

    U32 getElementCount() const                     { return (U32)mData.size(); }
    bool isEmpty() const                            { return mData.empty(); }
    element_iter getDataBegin()                     { return mData.begin(); }
    element_iter getDataEnd()                       { return mData.end(); }
    const_element_iter getDataBegin() const         { return mData.cbegin(); }
    const_element_iter getDataEnd() const           { return mData.cend(); }

    U32 getChildCount() const                       { return mChildCount; }
    oct_node* getChild(U32 index)                   { return mChild[index]; }
    const oct_node* getChild(U32 index) const       { return mChild[index]; }
    child_list& getChildren()                       { return mChild; }
    const child_list& getChildren() const           { return mChild; }

    void accept(tree_traveler* visitor) const       { visitor->visit(this); }
    void accept(oct_traveler* visitor) const        { visitor->visit(this); }

    void validateChildMap()
    {
        for (U32 i = 0; i < 8; i++)
        {
            U8 idx = mChildMap[i];
            if (idx != NO_CHILD_NODES)
            {
                oct_node* child = mChild[idx];

                if (child->getOctant() != i)
                {
                    LL_ERRS() << "Invalid child map, bad octant data." << LL_ENDL;
                }

                if (getOctant(child->getCenter()) != child->getOctant())
                {
                    LL_ERRS() << "Invalid child octant compared to position data." << LL_ENDL;
                }
            }
        }
    }


    oct_node* getNodeAt(const LLVector4a& pos, const F32& rad)
    {
        oct_node* node = this;

        if (node->isInside(pos, rad))
        {
            //do a quick search by octant
            U8 octant = node->getOctant(pos);

            //traverse the tree until we find a node that has no node
            //at the appropriate octant or is smaller than the object.
            //by definition, that node is the smallest node that contains
            // the data
            U8 next_node = node->mChildMap[octant];

            while (next_node != NO_CHILD_NODES && node->getSize()[0] >= rad)
            {
                node = node->getChild(next_node);
                octant = node->getOctant(pos);
                next_node = node->mChildMap[octant];
            }
        }
        else if (!node->contains(rad) && node->getParent())
        { //if we got here, data does not exist in this node
            return ((oct_node*) node->getParent())->getNodeAt(pos, rad);
        }

        return node;
    }

    virtual bool insert(T* data)
    {
        //LL_PROFILE_ZONE_NAMED_COLOR("Octree::insert()",OCTREE_DEBUG_COLOR_INSERT);

        if (data == NULL || data->getBinIndex() != -1)
        {
            OCT_ERRS << "!!! INVALID ELEMENT ADDED TO OCTREE BRANCH !!!" << LL_ENDL;
            return false;
        }
        oct_node* parent = getOctParent();

        //is it here?
        if (isInside(data->getPositionGroup()))
        {
            if ((((getElementCount() < gOctreeMaxCapacity || getSize()[0] <= gOctreeMinSize) && contains(data->getBinRadius())) ||
                (data->getBinRadius() > getSize()[0] && parent && parent->getElementCount() >= gOctreeMaxCapacity)))
            { //it belongs here
                mData.push_back(data);
                data->setBinIndex(getElementCount() - 1);
                BaseType::insert(data);
                return true;
            }
            else
            {
                //find a child to give it to
                oct_node* child = NULL;
                for (U32 i = 0; i < getChildCount(); i++)
                {
                    child = getChild(i);
                    if (child->isInside(data->getPositionGroup()))
                    {
                        child->insert(data);
                        return false;
                    }
                }

                //it's here, but no kids are in the right place, make a new kid
                LLVector4a center = getCenter();
                LLVector4a size = getSize();
                size.mul(0.5f);

                //push center in direction of data
                oct_node::pushCenter(center, size, data);

                // handle case where floating point number gets too small
                LLVector4a val;
                val.setSub(center, getCenter());
                val.setAbs(val);
                LLVector4a min_diff(gOctreeMinSize);

                S32 lt = val.lessThan(min_diff).getGatheredBits() & 0x7;

                if( lt == 0x7 )
                {
                    mData.push_back(data);
                    data->setBinIndex(getElementCount() - 1);
                    BaseType::insert(data);
                    return true;
                }

#if LL_OCTREE_PARANOIA_CHECK
                if (getChildCount() == 8)
                {
                    //this really isn't possible, something bad has happened
                    OCT_ERRS << "Octree detected floating point error and gave up." << LL_ENDL;
                    return false;
                }

                //make sure no existing node matches this position
                for (U32 i = 0; i < getChildCount(); i++)
                {
                    if (mChild[i]->getCenter().equals3(center))
                    {
                        OCT_ERRS << "Octree detected duplicate child center and gave up." << LL_ENDL;
                        return false;
                    }
                }
#endif

                llassert(size[0] >= gOctreeMinSize*0.5f);
                //make the new kid
                child = new oct_node(center, size, this);
                addChild(child);

                child->insert(data);
            }
        }
        else if (parent)
        {
            //it's not in here, give it to the root
            OCT_ERRS << "Octree insertion failed, starting over from root!" << LL_ENDL;

            oct_node* node = this;

            while (parent)
            {
                node = parent;
                parent = node->getOctParent();
            }

            node->insert(data);
        }
        else
        {
            // It's not in here, and we are root.
            // LLOctreeRoot::insert() should have expanded
            // root by now, something is wrong
            OCT_ERRS << "Octree insertion failed! Root expansion failed." << LL_ENDL;
        }

        return false;
    }

    void _remove(T* data, S32 i)
    { //precondition -- getElementCount() > 0, idx is in range [0, getElementCount())

        data->setBinIndex(-1);

        const U32 new_element_count = getElementCount() - 1;
        if (new_element_count > 0)
        {
            if (new_element_count != i)
            {
                mData[i] = mData[new_element_count]; //might unref data, do not access data after this point
                mData[i]->setBinIndex(i);
            }

            mData[new_element_count] = NULL;
            mData.pop_back();
        }
        else
        {
            mData.clear();
        }

        this->notifyRemoval(data);
        checkAlive();
    }

    bool remove(T* data)
    {
        //LL_PROFILE_ZONE_NAMED_COLOR("Octree::remove()", OCTREE_DEBUG_COLOR_REMOVE);

        S32 i = data->getBinIndex();

        if (i >= 0 && i < getElementCount())
        {
            if (mData[i] == data)
            { //found it
                _remove(data, i);
                llassert(data->getBinIndex() == -1);
                return true;
            }
        }

        if (isInside(data))
        {
            oct_node* dest = getNodeAt(data);

            if (dest != this)
            {
                bool ret = dest->remove(data);
                llassert(data->getBinIndex() == -1);
                return ret;
            }
        }

        //SHE'S GONE MISSING...
        //none of the children have it, let's just brute force this bastard out
        //starting with the root node (UGLY CODE COMETH!)
        oct_node* parent = getOctParent();
        oct_node* node = this;

        while (parent != NULL)
        {
            node = parent;
            parent = node->getOctParent();
        }

        //node is now root
        LL_WARNS() << "!!! OCTREE REMOVING ELEMENT BY ADDRESS, SEVERE PERFORMANCE PENALTY |||" << LL_ENDL;
        node->removeByAddress(data);
        llassert(data->getBinIndex() == -1);
        return true;
    }

    void removeByAddress(T* data)
    {
        const U32 element_count = getElementCount();
        for (U32 i = 0; i < element_count; ++i)
        {
            if (mData[i] == data)
            { //we have data
                _remove(data, i);
                LL_WARNS() << "FOUND!" << LL_ENDL;
                return;
            }
        }

        for (U32 i = 0; i < getChildCount(); i++)
        {   //we don't contain data, so pass this guy down
            oct_node* child = (oct_node*) getChild(i);
            child->removeByAddress(data);
        }
    }

    void clearChildren()
    {
        mChildCount = 0;
        memset(mChildMap, NO_CHILD_NODES, sizeof(mChildMap));
    }

    void validate()
    {
#if LL_OCTREE_PARANOIA_CHECK
        for (U32 i = 0; i < getChildCount(); i++)
        {
            mChild[i]->validate();
            if (mChild[i]->getParent() != this)
            {
                LL_ERRS() << "Octree child has invalid parent." << LL_ENDL;
            }
        }
#endif
    }

    virtual bool balance()
    {
        return false;
    }

    void destroy()
    {
        for (U32 i = 0; i < getChildCount(); i++)
        {
            mChild[i]->destroy();
            delete mChild[i];
        }
    }

    void addChild(oct_node* child, BOOL silent = FALSE)
    {
#if LL_OCTREE_PARANOIA_CHECK

        if (child->getSize().equals3(getSize()))
        {
            OCT_ERRS << "Child size is same as parent size!" << LL_ENDL;
        }

        for (U32 i = 0; i < getChildCount(); i++)
        {
            if(!mChild[i]->getSize().equals3(child->getSize()))
            {
                OCT_ERRS <<"Invalid octree child size." << LL_ENDL;
            }
            if (mChild[i]->getCenter().equals3(child->getCenter()))
            {
                OCT_ERRS <<"Duplicate octree child position." << LL_ENDL;
            }
        }

        if (mChild.size() >= 8)
        {
            OCT_ERRS <<"Octree node has too many children... why?" << LL_ENDL;
        }
#endif

        mChildMap[child->getOctant()] = mChildCount;

        mChild[mChildCount] = child;
        ++mChildCount;
        child->setParent(this);

        if (!silent)
        {
            for (U32 i = 0; i < this->getListenerCount(); i++)
            {
                oct_listener* listener = getOctListener(i);
                listener->handleChildAddition(this, child);
            }
        }
    }

    void removeChild(S32 index, BOOL destroy = FALSE)
    {
        for (U32 i = 0; i < this->getListenerCount(); i++)
        {
            oct_listener* listener = getOctListener(i);
            listener->handleChildRemoval(this, getChild(index));
        }

        if (destroy)
        {
            mChild[index]->destroy();
            delete mChild[index];
        }

        --mChildCount;

        mChild[index] = mChild[mChildCount];

        //rebuild child map
        memset(mChildMap, NO_CHILD_NODES, sizeof(mChildMap));

        for (U32 i = 0; i < mChildCount; ++i)
        {
            mChildMap[mChild[i]->getOctant()] = i;
        }

        checkAlive();
    }

    void checkAlive()
    {
        if (getChildCount() == 0 && getElementCount() == 0)
        {
            oct_node* parent = getOctParent();
            if (parent)
            {
                parent->deleteChild(this);
            }
        }
    }

    void deleteChild(oct_node* node)
    {
        for (U32 i = 0; i < getChildCount(); i++)
        {
            if (getChild(i) == node)
            {
                removeChild(i, TRUE);
                return;
            }
        }

        OCT_ERRS << "Octree failed to delete requested child." << LL_ENDL;
    }

protected:
    typedef enum
    {
        CENTER = 0,
        SIZE = 1,
        MAX = 2,
        MIN = 3
    } eDName;

    LLVector4a mCenter;
    LLVector4a mSize;
    LLVector4a mMax;
    LLVector4a mMin;

    oct_node* mParent;
    U8 mOctant;

    oct_node* mChild[8];
    U8 mChildMap[8];
    U32 mChildCount;

    element_list mData;
};

//just like a regular node, except it might expand on insert and compress on balance
template <class T, typename T_PTR>
class LLOctreeRoot : public LLOctreeNode<T, T_PTR>
{
public:
    typedef LLOctreeNode<T, T_PTR> BaseType;
    typedef LLOctreeNode<T, T_PTR> oct_node;

    LLOctreeRoot(const LLVector4a& center,
                 const LLVector4a& size,
                 BaseType* parent)
    :   BaseType(center, size, parent)
    {
    }

    bool balance() override
    {
        //LL_PROFILE_ZONE_NAMED_COLOR("Octree::balance()",OCTREE_DEBUG_COLOR_BALANCE);

        if (this->getChildCount() == 1 &&
            !(this->mChild[0]->isLeaf()) &&
            this->mChild[0]->getElementCount() == 0)
        { //if we have only one child and that child is an empty branch, make that child the root
            oct_node* child = this->mChild[0];

            //make the root node look like the child
            this->setCenter(this->mChild[0]->getCenter());
            this->setSize(this->mChild[0]->getSize());
            this->updateMinMax();

            //reset root node child list
            this->clearChildren();

            //copy the child's children into the root node silently
            //(don't notify listeners of addition)
            for (U32 i = 0; i < child->getChildCount(); i++)
            {
                this->addChild(child->getChild(i), TRUE);
            }

            //destroy child
            child->clearChildren();
            delete child;

            return false;
        }

        return true;
    }

    // LLOctreeRoot::insert
    bool insert(T* data) override
    {
        if (data == NULL)
        {
            OCT_ERRS << "!!! INVALID ELEMENT ADDED TO OCTREE ROOT !!!" << LL_ENDL;
            return false;
        }

        if (data->getBinRadius() > 4096.0)
        {
            OCT_ERRS << "!!! ELEMENT EXCEEDS MAXIMUM SIZE IN OCTREE ROOT !!!" << LL_ENDL;
            return false;
        }

        LLVector4a MAX_MAG;
        MAX_MAG.splat(1024.f*1024.f);

        const LLVector4a& v = data->getPositionGroup();

        LLVector4a val;
        val.setSub(v, BaseType::mCenter);
        val.setAbs(val);
        S32 lt = val.lessThan(MAX_MAG).getGatheredBits() & 0x7;

        if (lt != 0x7)
        {
            //OCT_ERRS << "!!! ELEMENT EXCEEDS RANGE OF SPATIAL PARTITION !!!" << LL_ENDL;
            return false;
        }

        if (this->getSize()[0] > data->getBinRadius() && this->isInside(data->getPositionGroup()))
        {
            //we got it, just act like a branch
            oct_node* node = this->getNodeAt(data);
            if (node == this)
            {
                oct_node::insert(data);
            }
            else if (node->isInside(data->getPositionGroup()))
            {
                node->insert(data);
            }
            else
            {
                // calling node->insert(data) will return us to root
                OCT_ERRS << "Failed to insert data at child node" << LL_ENDL;
            }
        }
        else if (this->getChildCount() == 0)
        {
            //first object being added, just wrap it up
            while (!(this->getSize()[0] > data->getBinRadius() && this->isInside(data->getPositionGroup())))
            {
                LLVector4a center, size;
                center = this->getCenter();
                size = this->getSize();
                oct_node::pushCenter(center, size, data);
                this->setCenter(center);
                size.mul(2.f);
                this->setSize(size);
                this->updateMinMax();
            }
            oct_node::insert(data);
        }
        else
        {
            while (!(this->getSize()[0] > data->getBinRadius() && this->isInside(data->getPositionGroup())))
            {
                //the data is outside the root node, we need to grow
                LLVector4a center(this->getCenter());
                LLVector4a size(this->getSize());

                //expand this node
                LLVector4a newcenter(center);
                oct_node::pushCenter(newcenter, size, data);
                this->setCenter(newcenter);
                LLVector4a size2 = size;
                size2.mul(2.f);
                this->setSize(size2);
                this->updateMinMax();

                llassert(size[0] >= gOctreeMinSize);

                //copy our children to a new branch
                oct_node* newnode = new oct_node(center, size, this);

                for (U32 i = 0; i < this->getChildCount(); i++)
                {
                    oct_node* child = this->getChild(i);
                    newnode->addChild(child);
                }

                //clear our children and add the root copy
                this->clearChildren();
                this->addChild(newnode);
            }

            //insert the data
            insert(data);
        }

        return false;
    }

    bool isLeaf() const override
    {
        // root can't be a leaf
        return false;
    }
};

//========================
//      LLOctreeTraveler
//========================
template <class T, typename T_PTR>
void LLOctreeTraveler<T, T_PTR>::traverse(const LLOctreeNode<T, T_PTR>* node)
{
    node->accept(this);
    for (U32 i = 0; i < node->getChildCount(); i++)
    {
        traverse(node->getChild(i));
    }
}

template <class T, typename T_PTR>
void LLOctreeTravelerDepthFirst<T, T_PTR>::traverse(const LLOctreeNode<T, T_PTR>* node)
{
    for (U32 i = 0; i < node->getChildCount(); i++)
    {
        traverse(node->getChild(i));
    }
    node->accept(this);
}

#endif