Home | History | Annotate | Download | only in core
      1 
      2 /*
      3  * Copyright 2012 Google Inc.
      4  *
      5  * Use of this source code is governed by a BSD-style license that can be
      6  * found in the LICENSE file.
      7  */
      8 
      9 #ifndef SkRTree_DEFINED
     10 #define SkRTree_DEFINED
     11 
     12 #include "SkRect.h"
     13 #include "SkTDArray.h"
     14 #include "SkChunkAlloc.h"
     15 #include "SkBBoxHierarchy.h"
     16 
     17 /**
     18  * An R-Tree implementation. In short, it is a balanced n-ary tree containing a hierarchy of
     19  * bounding rectangles.
     20  *
     21  * Much like a B-Tree it maintains balance by enforcing minimum and maximum child counts, and
     22  * splitting nodes when they become overfull. Unlike B-trees, however, we're using spatial data; so
     23  * there isn't a canonical ordering to use when choosing insertion locations and splitting
     24  * distributions. A variety of heuristics have been proposed for these problems; here, we're using
     25  * something resembling an R*-tree, which attempts to minimize area and overlap during insertion,
     26  * and aims to minimize a combination of margin, overlap, and area when splitting.
     27  *
     28  * One detail that is thus far unimplemented that may improve tree quality is attempting to remove
     29  * and reinsert nodes when they become full, instead of immediately splitting (nodes that may have
     30  * been placed well early on may hurt the tree later when more nodes have been added; removing
     31  * and reinserting nodes generally helps reduce overlap and make a better tree). Deletion of nodes
     32  * is also unimplemented.
     33  *
     34  * For more details see:
     35  *
     36  *  Beckmann, N.; Kriegel, H. P.; Schneider, R.; Seeger, B. (1990). "The R*-tree:
     37  *      an efficient and robust access method for points and rectangles"
     38  *
     39  * It also supports bulk-loading from a batch of bounds and values; if you don't require the tree
     40  * to be usable in its intermediate states while it is being constructed, this is significantly
     41  * quicker than individual insertions and produces more consistent trees.
     42  */
     43 class SkRTree : public SkBBoxHierarchy {
     44 public:
     45     SK_DECLARE_INST_COUNT(SkRTree)
     46 
     47     /**
     48      * Create a new R-Tree with specified min/max child counts.
     49      * The child counts are valid iff:
     50      * - (max + 1) / 2 >= min (splitting an overfull node must be enough to populate 2 nodes)
     51      * - min < max
     52      * - min > 0
     53      * - max < SK_MaxU16
     54      * If you have some prior information about the distribution of bounds you're expecting, you
     55      * can provide an optional aspect ratio parameter. This allows the bulk-load algorithm to create
     56      * better proportioned tiles of rectangles.
     57      */
     58     static SkRTree* Create(int minChildren, int maxChildren, SkScalar aspectRatio = 1);
     59     virtual ~SkRTree();
     60 
     61     /**
     62      * Insert a node, consisting of bounds and a data value into the tree, if we don't immediately
     63      * need to use the tree; we may allow the insert to be deferred (this can allow us to bulk-load
     64      * a large batch of nodes at once, which tends to be faster and produce a better tree).
     65      *  @param data The data value
     66      *  @param bounds The corresponding bounding box
     67      *  @param defer Can this insert be deferred? (this may be ignored)
     68      */
     69     virtual void insert(void* data, const SkIRect& bounds, bool defer = false);
     70 
     71     /**
     72      * If any inserts have been deferred, this will add them into the tree
     73      */
     74     virtual void flushDeferredInserts();
     75 
     76     /**
     77      * Given a query rectangle, populates the passed-in array with the elements it intersects
     78      */
     79     virtual void search(const SkIRect& query, SkTDArray<void*>* results);
     80 
     81     virtual void clear();
     82     bool isEmpty() const { return 0 == fCount; }
     83     int getDepth() const { return this->isEmpty() ? 0 : fRoot.fChild.subtree->fLevel + 1; }
     84 
     85     /**
     86      * This gets the insertion count (rather than the node count)
     87      */
     88     virtual int getCount() const { return fCount; }
     89 
     90     virtual void rewindInserts() SK_OVERRIDE;
     91 
     92 private:
     93 
     94     struct Node;
     95 
     96     /**
     97      * A branch of the tree, this may contain a pointer to another interior node, or a data value
     98      */
     99     struct Branch {
    100         union {
    101             Node* subtree;
    102             void* data;
    103         } fChild;
    104         SkIRect fBounds;
    105     };
    106 
    107     /**
    108      * A node in the tree, has between fMinChildren and fMaxChildren (the root is a special case)
    109      */
    110     struct Node {
    111         uint16_t fNumChildren;
    112         uint16_t fLevel;
    113         bool isLeaf() { return 0 == fLevel; }
    114         // Since we want to be able to pick min/max child counts at runtime, we assume the creator
    115         // has allocated sufficient space directly after us in memory, and index into that space
    116         Branch* child(size_t index) {
    117             return reinterpret_cast<Branch*>(this + 1) + index;
    118         }
    119     };
    120 
    121     typedef int32_t SkIRect::*SortSide;
    122 
    123     // Helper for sorting our children arrays by sides of their rects
    124     struct RectLessThan {
    125         RectLessThan(SkRTree::SortSide side) : fSide(side) { }
    126         bool operator()(const SkRTree::Branch lhs, const SkRTree::Branch rhs) const {
    127             return lhs.fBounds.*fSide < rhs.fBounds.*fSide;
    128         }
    129     private:
    130         const SkRTree::SortSide fSide;
    131     };
    132 
    133     struct RectLessX {
    134         bool operator()(const SkRTree::Branch lhs, const SkRTree::Branch rhs) {
    135             return ((lhs.fBounds.fRight - lhs.fBounds.fLeft) >> 1) <
    136                    ((rhs.fBounds.fRight - lhs.fBounds.fLeft) >> 1);
    137         }
    138     };
    139 
    140     struct RectLessY {
    141         bool operator()(const SkRTree::Branch lhs, const SkRTree::Branch rhs) {
    142             return ((lhs.fBounds.fBottom - lhs.fBounds.fTop) >> 1) <
    143                    ((rhs.fBounds.fBottom - lhs.fBounds.fTop) >> 1);
    144         }
    145     };
    146 
    147     SkRTree(int minChildren, int maxChildren, SkScalar aspectRatio);
    148 
    149     /**
    150      * Recursively descend the tree to find an insertion position for 'branch', updates
    151      * bounding boxes on the way up.
    152      */
    153     Branch* insert(Node* root, Branch* branch, uint16_t level = 0);
    154 
    155     int chooseSubtree(Node* root, Branch* branch);
    156     SkIRect computeBounds(Node* n);
    157     int distributeChildren(Branch* children);
    158     void search(Node* root, const SkIRect query, SkTDArray<void*>* results) const;
    159 
    160     /**
    161      * This performs a bottom-up bulk load using the STR (sort-tile-recursive) algorithm, this
    162      * seems to generally produce better, more consistent trees at significantly lower cost than
    163      * repeated insertions.
    164      *
    165      * This consumes the input array.
    166      *
    167      * TODO: Experiment with other bulk-load algorithms (in particular the Hilbert pack variant,
    168      * which groups rects by position on the Hilbert curve, is probably worth a look). There also
    169      * exist top-down bulk load variants (VAMSplit, TopDownGreedy, etc).
    170      */
    171     Branch bulkLoad(SkTDArray<Branch>* branches, int level = 0);
    172 
    173     void validate();
    174     int validateSubtree(Node* root, SkIRect bounds, bool isRoot = false);
    175 
    176     const int fMinChildren;
    177     const int fMaxChildren;
    178     const size_t fNodeSize;
    179 
    180     // This is the count of data elements (rather than total nodes in the tree)
    181     size_t fCount;
    182 
    183     Branch fRoot;
    184     SkChunkAlloc fNodes;
    185     SkTDArray<Branch> fDeferredInserts;
    186     SkScalar fAspectRatio;
    187 
    188     Node* allocateNode(uint16_t level);
    189 
    190     typedef SkBBoxHierarchy INHERITED;
    191 };
    192 
    193 #endif
    194