001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import org.openstreetmap.josm.data.coor.LatLon;
005import org.openstreetmap.josm.data.osm.BBox;
006
007/**
008 * Fast index to look up properties of the earth surface.
009 *
010 * It is expected that there is a relatively slow method to look up the property
011 * for a certain coordinate and that there are larger areas with a uniform
012 * property.
013 *
014 * This index tries to find rectangles with uniform property and caches them.
015 * Rectangles are subdivided, if there are different properties within.
016 * (Up to a maximum level, when the slow method is used again.)
017 *
018 * @param <T> the property (like land/water or nation)
019 */
020public class GeoPropertyIndex<T> {
021
022    private final int maxLevel;
023    private final GeoProperty<T> geoProp;
024    private final GPLevel<T> root;
025    private GPLevel<T> lastLevelUsed;
026
027    private static final boolean DEBUG = false;
028
029    /**
030     * Create new GeoPropertyIndex.
031     * @param geoProp the input property that should be made faster by this index
032     * @param maxLevel max level
033     */
034    public GeoPropertyIndex(GeoProperty<T> geoProp, int maxLevel) {
035        this.geoProp = geoProp;
036        this.maxLevel = maxLevel;
037        this.root = new GPLevel<>(0, new BBox(-180, -90, 180, 90), null, this);
038        this.lastLevelUsed = root;
039    }
040
041    /**
042     * Look up the property for a certain point.
043     * This gives the same result as {@link GeoProperty#get(LatLon)}, but
044     * should be faster.
045     * @param ll the point coordinates
046     * @return property value at that point
047     */
048    public T get(LatLon ll) {
049        return lastLevelUsed.get(ll);
050    }
051
052    public static int index(LatLon ll, int level) {
053        long noParts = 1L << level;
054        long x = ((long) ((ll.lon() + 180.0) * noParts / 360.0)) & 1;
055        long y = ((long) ((ll.lat() + 90.0) * noParts / 180.0)) & 1;
056        return (int) (2 * x + y);
057    }
058
059    protected static class GPLevel<T> {
060        private final T val;
061        private final int level;
062        private final BBox bbox;
063        private final GPLevel<T> parent;
064        private final GeoPropertyIndex<T> owner;
065
066        // child order by index is sw, nw, se, ne
067        private GPLevel<T>[] children;
068
069        public GPLevel(int level, BBox bbox, GPLevel<T> parent, GeoPropertyIndex<T> owner) {
070            this.level = level;
071            this.bbox = bbox;
072            this.parent = parent;
073            this.owner = owner;
074            this.val = owner.geoProp.get(bbox);
075        }
076
077        public T get(LatLon ll) {
078            if (isInside(ll))
079                return getBounded(ll);
080            if (DEBUG) System.err.print("up["+level+"]");
081            return parent.get(ll);
082        }
083
084        private T getBounded(LatLon ll) {
085            if (DEBUG) System.err.print("GPLevel["+level+"]"+bbox+" ");
086            if (!isInside(ll)) {
087                throw new AssertionError("Point "+ll+" should be inside "+bbox);
088            }
089            if (val != null) {
090                if (DEBUG) System.err.println(" hit! "+val);
091                owner.lastLevelUsed = this;
092                return val;
093            }
094            if (level >= owner.maxLevel) {
095                if (DEBUG) System.err.println(" max level reached !");
096                return owner.geoProp.get(ll);
097            }
098
099            if (children == null) {
100                @SuppressWarnings("unchecked")
101                GPLevel<T>[] tmp = new GPLevel[4];
102                this.children = tmp;
103            }
104
105            int idx = index(ll, level+1);
106            if (children[idx] == null) {
107            double lon1, lat1;
108                switch (idx) {
109                    case 0:
110                        lon1 = bbox.getTopLeftLon();
111                        lat1 = bbox.getBottomRightLat();
112                        break;
113                    case 1:
114                        lon1 = bbox.getTopLeftLon();
115                        lat1 = bbox.getTopLeftLat();
116                        break;
117                    case 2:
118                        lon1 = bbox.getBottomRightLon();
119                        lat1 = bbox.getBottomRightLat();
120                        break;
121                    case 3:
122                        lon1 = bbox.getBottomRightLon();
123                        lat1 = bbox.getTopLeftLat();
124                        break;
125                    default:
126                        throw new AssertionError();
127                }
128                if (DEBUG) System.err.println(" - new with idx "+idx);
129                LatLon center = bbox.getCenter();
130                BBox b = new BBox(lon1, lat1, center.lon(), center.lat());
131                children[idx] = new GPLevel<>(level + 1, b, this, owner);
132            }
133            return children[idx].getBounded(ll);
134        }
135
136        /**
137         * Checks, if a point is inside this tile.
138         * Makes sure, that neighboring tiles do not overlap, i.e. a point exactly
139         * on the border of two tiles must be inside exactly one of the tiles.
140         * @param ll the coordinates of the point
141         * @return true, if it is inside of the box
142         */
143        boolean isInside(LatLon ll) {
144            return bbox.getTopLeftLon() <= ll.lon() &&
145                    (ll.lon() < bbox.getBottomRightLon() || (ll.lon() == 180.0 && bbox.getBottomRightLon() == 180.0)) &&
146                    bbox.getBottomRightLat() <= ll.lat() &&
147                    (ll.lat() < bbox.getTopLeftLat() || (ll.lat() == 90.0 && bbox.getTopLeftLat() == 90.0));
148        }
149
150        @Override
151        public String toString() {
152            return "GPLevel [val=" + val + ", level=" + level + ", bbox=" + bbox + ']';
153        }
154    }
155
156    @Override
157    public String toString() {
158        return "GeoPropertyIndex [maxLevel=" + maxLevel + ", geoProp=" + geoProp + ", root=" + root + ", lastLevelUsed="
159                + lastLevelUsed + ']';
160    }
161}