tile38/index/rtree/rtree.go

73 lines
1.7 KiB
Go
Raw Normal View History

2016-03-05 02:08:16 +03:00
package rtree
// Item is an rtree item
type Item interface {
Rect() (minX, minY, maxX, maxY float64)
}
// Rect is a rectangle
type Rect struct {
MinX, MinY, MaxX, MaxY float64
}
// Rect returns the rectangle
func (item *Rect) Rect() (minX, minY, maxX, maxY float64) {
return item.MinX, item.MinY, item.MaxX, item.MaxY
}
// RTree is an implementation of an rtree
type RTree struct {
2016-10-03 03:28:23 +03:00
tr *d2RTree
2016-03-05 02:08:16 +03:00
}
// New creates a new RTree
func New() *RTree {
2016-10-03 03:28:23 +03:00
return &RTree{
tr: d2New(),
}
2016-03-05 02:08:16 +03:00
}
// Insert inserts item into rtree
func (tr *RTree) Insert(item Item) {
2016-10-03 03:28:23 +03:00
minX, minY, maxX, maxY := item.Rect()
tr.tr.Insert([2]float64{minX, minY}, [2]float64{maxX, maxY}, item)
2016-03-05 02:08:16 +03:00
}
// Remove removes item from rtree
func (tr *RTree) Remove(item Item) {
2016-10-03 03:28:23 +03:00
minX, minY, maxX, maxY := item.Rect()
tr.tr.Remove([2]float64{minX, minY}, [2]float64{maxX, maxY}, item)
2016-03-05 02:08:16 +03:00
}
// Search finds all items in bounding box.
func (tr *RTree) Search(minX, minY, maxX, maxY float64, iterator func(item Item) bool) {
2016-10-03 03:28:23 +03:00
tr.tr.Search([2]float64{minX, minY}, [2]float64{maxX, maxY}, func(data interface{}) bool {
return iterator(data.(Item))
})
2016-03-05 02:08:16 +03:00
}
// Count return the number of items in rtree.
func (tr *RTree) Count() int {
2016-10-03 03:28:23 +03:00
return tr.tr.Count()
2016-03-05 02:08:16 +03:00
}
// RemoveAll removes all items from rtree.
func (tr *RTree) RemoveAll() {
2016-10-03 03:28:23 +03:00
tr.tr.RemoveAll()
2016-03-05 02:08:16 +03:00
}
2016-08-19 18:04:18 +03:00
func (tr *RTree) Bounds() (minX, minY, maxX, maxY float64) {
2016-10-03 03:28:23 +03:00
var rect d2rectT
if tr.tr.root != nil {
if tr.tr.root.count > 0 {
rect = tr.tr.root.branch[0].rect
for i := 1; i < tr.tr.root.count; i++ {
rect2 := tr.tr.root.branch[i].rect
rect = d2combineRect(&rect, &rect2)
2016-08-19 18:04:18 +03:00
}
}
}
minX, minY, maxX, maxY = rect.min[0], rect.min[1], rect.max[0], rect.max[1]
return
}