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    /**
053     * Returns the geo property.
054     * @return the geo property
055     * @since 14484
056     */
057    public final GeoProperty<T> getGeoProperty() {
058        return geoProp;
059    }
060
061    /**
062     * Gets the index of the given coordinate. Only used internally
063     * @param ll The lat/lon coordinate
064     * @param level The scale level
065     * @return The index for that position
066     */
067    public static int index(LatLon ll, int level) {
068        long noParts = 1L << level;
069        long x = ((long) ((ll.lon() + 180.0) * noParts / 360.0)) & 1;
070        long y = ((long) ((ll.lat() + 90.0) * noParts / 180.0)) & 1;
071        return (int) (2 * x + y);
072    }
073
074    protected static class GPLevel<T> {
075        private final T val;
076        private final int level;
077        private final BBox bbox;
078        private final GPLevel<T> parent;
079        private final GeoPropertyIndex<T> owner;
080
081        // child order by index is sw, nw, se, ne
082        private GPLevel<T>[] children;
083
084        public GPLevel(int level, BBox bbox, GPLevel<T> parent, GeoPropertyIndex<T> owner) {
085            this.level = level;
086            this.bbox = bbox;
087            this.parent = parent;
088            this.owner = owner;
089            this.val = owner.geoProp.get(bbox);
090        }
091
092        public T get(LatLon ll) {
093            if (isInside(ll))
094                return getBounded(ll);
095            if (DEBUG) System.err.print("up["+level+"]");
096            return parent != null ? parent.get(ll) : null;
097        }
098
099        private T getBounded(LatLon ll) {
100            if (DEBUG) System.err.print("GPLevel["+level+"]"+bbox+" ");
101            if (!isInside(ll)) {
102                throw new AssertionError("Point "+ll+" should be inside "+bbox);
103            }
104            if (val != null) {
105                if (DEBUG) System.err.println(" hit! "+val);
106                owner.lastLevelUsed = this;
107                return val;
108            }
109            if (level >= owner.maxLevel) {
110                if (DEBUG) System.err.println(" max level reached !");
111                return owner.geoProp.get(ll);
112            }
113
114            if (children == null) {
115                @SuppressWarnings("unchecked")
116                GPLevel<T>[] tmp = new GPLevel[4];
117                this.children = tmp;
118            }
119
120            int idx = index(ll, level+1);
121            if (children[idx] == null) {
122            double lon1, lat1;
123                switch (idx) {
124                    case 0:
125                        lon1 = bbox.getTopLeftLon();
126                        lat1 = bbox.getBottomRightLat();
127                        break;
128                    case 1:
129                        lon1 = bbox.getTopLeftLon();
130                        lat1 = bbox.getTopLeftLat();
131                        break;
132                    case 2:
133                        lon1 = bbox.getBottomRightLon();
134                        lat1 = bbox.getBottomRightLat();
135                        break;
136                    case 3:
137                        lon1 = bbox.getBottomRightLon();
138                        lat1 = bbox.getTopLeftLat();
139                        break;
140                    default:
141                        throw new AssertionError();
142                }
143                if (DEBUG) System.err.println(" - new with idx "+idx);
144                LatLon center = bbox.getCenter();
145                BBox b = new BBox(lon1, lat1, center.lon(), center.lat());
146                children[idx] = new GPLevel<>(level + 1, b, this, owner);
147            }
148            return children[idx].getBounded(ll);
149        }
150
151        /**
152         * Checks, if a point is inside this tile.
153         * Makes sure, that neighboring tiles do not overlap, i.e. a point exactly
154         * on the border of two tiles must be inside exactly one of the tiles.
155         * @param ll the coordinates of the point
156         * @return true, if it is inside of the box
157         */
158        boolean isInside(LatLon ll) {
159            return bbox.getTopLeftLon() <= ll.lon() &&
160                    (ll.lon() < bbox.getBottomRightLon() || (ll.lon() == 180.0 && bbox.getBottomRightLon() == 180.0)) &&
161                    bbox.getBottomRightLat() <= ll.lat() &&
162                    (ll.lat() < bbox.getTopLeftLat() || (ll.lat() == 90.0 && bbox.getTopLeftLat() == 90.0));
163        }
164
165        @Override
166        public String toString() {
167            return "GPLevel [val=" + val + ", level=" + level + ", bbox=" + bbox + ']';
168        }
169    }
170
171    @Override
172    public String toString() {
173        return "GeoPropertyIndex [maxLevel=" + maxLevel + ", geoProp=" + geoProp + ", root=" + root + ", lastLevelUsed="
174                + lastLevelUsed + ']';
175    }
176}