001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.layer;
003
004import static org.openstreetmap.josm.tools.I18n.marktr;
005
006import java.awt.BasicStroke;
007import java.awt.Color;
008import java.awt.Graphics2D;
009import java.awt.RenderingHints;
010import java.awt.geom.Line2D;
011import java.awt.geom.Path2D;
012import java.awt.geom.Point2D;
013import java.util.ArrayList;
014import java.util.List;
015import java.util.concurrent.atomic.AtomicReference;
016
017import org.openstreetmap.josm.data.Bounds;
018import org.openstreetmap.josm.data.ProjectionBounds;
019import org.openstreetmap.josm.data.coor.EastNorth;
020import org.openstreetmap.josm.data.coor.LatLon;
021import org.openstreetmap.josm.data.preferences.BooleanProperty;
022import org.openstreetmap.josm.data.preferences.DoubleProperty;
023import org.openstreetmap.josm.data.preferences.EnumProperty;
024import org.openstreetmap.josm.data.preferences.NamedColorProperty;
025import org.openstreetmap.josm.data.projection.Projection;
026import org.openstreetmap.josm.gui.MapView;
027import org.openstreetmap.josm.gui.draw.BlendComposite;
028import org.openstreetmap.josm.spi.preferences.Config;
029import org.openstreetmap.josm.spi.preferences.PreferenceChangeEvent;
030import org.openstreetmap.josm.spi.preferences.PreferenceChangedListener;
031import org.openstreetmap.josm.tools.Destroyable;
032import org.openstreetmap.josm.tools.Logging;
033
034/**
035 * A grid drawn over the whole map view, on top of all layers.
036 * <p>
037 * The grid is a pure visual aid (there is no snapping to it). It is either aligned to latitude/longitude, with a
038 * spacing in degrees, or to the projected coordinates, with a spacing in metres (true distance, measured at the
039 * grid origin), an optional rotation and an origin offset. When the grid cells would become
040 * smaller than a minimal size on screen, the spacing is multiplied by 10 until the cells are large enough, so the
041 * grid stays readable at every zoom level while remaining aligned to the configured one.
042 * <p>
043 * All settings are preferences (prefix {@code draw.grid.}), see {@link org.openstreetmap.josm.gui.preferences.display.GridPreference}.
044 * <p>
045 * An instance registers itself as a preference listener, so {@link #destroy()} must be called when it is no
046 * longer used ({@link org.openstreetmap.josm.gui.MapFrame} does this), otherwise the listener is leaked.
047 * @since 19640
048 */
049public class MapGridPaintable extends AbstractMapViewPaintable implements PreferenceChangedListener, Destroyable {
050
051    /**
052     * The kind of coordinates a grid is aligned to.
053     */
054    public enum GridType {
055        /** lines of constant latitude and longitude, spacing in degrees */
056        LATLON,
057        /** lines of constant projected east/north coordinate (optionally rotated), spacing in metres */
058        PROJECTED
059    }
060
061    private static final String PREFIX = "draw.grid.";
062
063    /** Whether the grid is shown */
064    public static final BooleanProperty ENABLED = new BooleanProperty(PREFIX + "enabled", false);
065    /** The kind of grid */
066    public static final EnumProperty<GridType> TYPE = new EnumProperty<>(PREFIX + "type", GridType.class, GridType.PROJECTED);
067    /** Spacing of the vertical lines (longitude resp. east), in degrees resp. metres (true distance at the origin) */
068    public static final DoubleProperty SPACING_X = new DoubleProperty(PREFIX + "spacing-x", 1000);
069    /** Spacing of the horizontal lines (latitude resp. north), in degrees resp. metres (true distance at the origin) */
070    public static final DoubleProperty SPACING_Y = new DoubleProperty(PREFIX + "spacing-y", 1000);
071    /** Rotation of a projected grid, in degrees counter clockwise */
072    public static final DoubleProperty ROTATION = new DoubleProperty(PREFIX + "rotation", 0);
073    /** Origin of the grid: a grid line passes through this coordinate (longitude resp. east) */
074    public static final DoubleProperty ORIGIN_X = new DoubleProperty(PREFIX + "origin-x", 0);
075    /** Origin of the grid: a grid line passes through this coordinate (latitude resp. north) */
076    public static final DoubleProperty ORIGIN_Y = new DoubleProperty(PREFIX + "origin-y", 0);
077    /** Below this distance between lines (in pixels) the spacing is multiplied by 10 */
078    public static final DoubleProperty MIN_PIXEL_SPACING = new DoubleProperty(PREFIX + "min-pixel-spacing", 25);
079    /** The blend mode used to draw the lines */
080    public static final EnumProperty<BlendComposite.Mode> BLEND_MODE
081            = new EnumProperty<>(PREFIX + "blend-mode", BlendComposite.Mode.class, BlendComposite.Mode.HARD_LIGHT);
082    /** Width of the lines in pixels */
083    public static final DoubleProperty LINE_WIDTH = new DoubleProperty(PREFIX + "line-width", 2);
084    /** Color of the lines of constant east coordinate resp. longitude (the lines running north-south) */
085    public static final NamedColorProperty COLOR_EAST = new NamedColorProperty(marktr("grid east lines"), Color.YELLOW);
086    /** Color of the lines of constant north coordinate resp. latitude (the lines running east-west) */
087    public static final NamedColorProperty COLOR_NORTH = new NamedColorProperty(marktr("grid north lines"), Color.YELLOW);
088
089    /**
090     * A straight line of a projected grid.
091     * @since 19640
092     */
093    public static final class ProjectedGridLine {
094        /** start point */
095        public final EastNorth start;
096        /** end point */
097        public final EastNorth end;
098        /** {@code true} for a line of constant (rotated) east coordinate, {@code false} for constant north */
099        public final boolean constantEast;
100
101        ProjectedGridLine(EastNorth start, EastNorth end, boolean constantEast) {
102            this.start = start;
103            this.end = end;
104            this.constantEast = constantEast;
105        }
106
107        @Override
108        public String toString() {
109            return (constantEast ? "east " : "north ") + start + " -> " + end;
110        }
111    }
112
113    /**
114     * A (curved) line of a latitude/longitude grid.
115     * @since 19640
116     */
117    public static final class LatLonGridLine {
118        /** the points of the polyline */
119        public final List<LatLon> points;
120        /** {@code true} for a meridian (constant longitude), {@code false} for a parallel (constant latitude) */
121        public final boolean meridian;
122
123        LatLonGridLine(List<LatLon> points, boolean meridian) {
124            this.points = points;
125            this.meridian = meridian;
126        }
127
128        @Override
129        public String toString() {
130            return (meridian ? "meridian " : "parallel ") + points;
131        }
132    }
133
134    /** number of segments used to draw a curved (lat/lon) grid line across the view */
135    private static final int CURVE_SEGMENTS = 32;
136    /** hard limit for the number of lines in one direction, whatever the settings are */
137    private static final int MAX_LINES = 500;
138
139    /** written by {@link #paint} and read by {@link #preferenceChanged}, which may run on another thread */
140    private final AtomicReference<MapView> mapView = new AtomicReference<>();
141
142    /**
143     * Constructs a new {@code MapGridPaintable}.
144     */
145    public MapGridPaintable() {
146        Config.getPref().addPreferenceChangeListener(this);
147    }
148
149    @Override
150    public void paint(Graphics2D g, MapView mv, Bounds bbox) {
151        mapView.set(mv);
152        if (!Boolean.TRUE.equals(ENABLED.get()) || mv.getWidth() <= 0 || mv.getHeight() <= 0) {
153            return;
154        }
155        Graphics2D g2 = (Graphics2D) g.create();
156        try {
157            g2.setStroke(new BasicStroke((float) Math.max(0.1, LINE_WIDTH.get())));
158            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
159                    Config.getPref().getBoolean("mappaint.use-antialiasing", true)
160                    ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
161            BlendComposite.Mode mode = BLEND_MODE.get();
162            if (mode != null && mode != BlendComposite.Mode.NORMAL) {
163                g2.setComposite(BlendComposite.getInstance(mode));
164            }
165            if (TYPE.get() == GridType.PROJECTED) {
166                paintProjectedGrid(g2, mv);
167            } else {
168                paintLatLonGrid(g2, mv);
169            }
170        } finally {
171            g2.dispose();
172        }
173    }
174
175    private static void paintProjectedGrid(Graphics2D g, MapView mv) {
176        double sx = SPACING_X.get();
177        double sy = SPACING_Y.get();
178        if (sx <= 0 || sy <= 0) {
179            return;
180        }
181        // the spacing is a true distance in metres, measured at the grid origin
182        EastNorth origin = new EastNorth(ORIGIN_X.get(), ORIGIN_Y.get());
183        double unitsPerMetre = projectionUnitsPerMetre(mv.getProjection(), origin);
184        sx *= unitsPerMetre;
185        sy *= unitsPerMetre;
186        // thin out the grid until the cells are large enough on screen
187        double factor = thinningFactor(Math.min(sx, sy) / mv.getScale());
188        List<ProjectedGridLine> lines = getProjectedGridLines(mv.getProjectionBounds(), sx * factor, sy * factor,
189                ROTATION.get(), origin.east(), origin.north());
190        for (ProjectedGridLine line : lines) {
191            g.setColor(line.constantEast ? COLOR_EAST.get() : COLOR_NORTH.get());
192            g.draw(new Line2D.Double(mv.getPoint2D(line.start), mv.getPoint2D(line.end)));
193        }
194    }
195
196    private static void paintLatLonGrid(Graphics2D g, MapView mv) {
197        double sx = SPACING_X.get();
198        double sy = SPACING_Y.get();
199        if (sx <= 0 || sy <= 0) {
200            return;
201        }
202        Bounds view = getVisibleLatLonBounds(mv);
203        if (view == null) {
204            return;
205        }
206        // pixel size of one cell at the center of the view
207        LatLon center = view.getCenter();
208        Point2D c = mv.getPoint2D(center);
209        double factor = thinningFactor(Math.min(probePixels(mv, c, center, sx, true), probePixels(mv, c, center, sy, false)));
210        List<LatLonGridLine> lines = getLatLonGridLines(view, mv.getProjection().getWorldBoundsLatLon(),
211                sx * factor, sy * factor, ORIGIN_X.get(), ORIGIN_Y.get(), CURVE_SEGMENTS);
212        for (LatLonGridLine line : lines) {
213            g.setColor(line.meridian ? COLOR_EAST.get() : COLOR_NORTH.get());
214            Path2D.Double path = new Path2D.Double();
215            boolean first = true;
216            for (LatLon ll : line.points) {
217                Point2D p = mv.getPoint2D(ll);
218                if (first) {
219                    path.moveTo(p.getX(), p.getY());
220                    first = false;
221                } else {
222                    path.lineTo(p.getX(), p.getY());
223                }
224            }
225            g.draw(path);
226        }
227    }
228
229    /**
230     * Computes the latitude/longitude bounds of the part of the world which is visible in the given view.
231     * <p>
232     * Contrary to {@link org.openstreetmap.josm.gui.NavigatableComponent#getRealBounds()} this does not simply
233     * convert the corners of the view: as soon as the view is larger than the world, those lie outside the world
234     * and their longitude wraps around, which yields a range much narrower than what is really visible (and one
235     * which jumps around while zooming or panning). The view is therefore first clipped to the world in
236     * projected coordinates.
237     * <p>
238     * The clipped area is kept a hair inside the world, because a point exactly on the antimeridian converts to
239     * an ambiguous longitude: {@link Projection#eastNorth2latlon} normalizes it to -180, which would turn the
240     * visible range of a view showing e.g. 60° E to 180° into 180° W to 60° E, i.e. the other half of the world.
241     * @param mv the map view
242     * @return the visible bounds, or {@code null} if no part of the world is visible
243     */
244    static Bounds getVisibleLatLonBounds(MapView mv) {
245        Projection projection = mv.getProjection();
246        ProjectionBounds view = mv.getProjectionBounds();
247        ProjectionBounds world = projection.getWorldBoundsBoxEastNorth();
248        double minEast = Math.max(view.minEast, world.minEast);
249        double maxEast = Math.min(view.maxEast, world.maxEast);
250        double minNorth = Math.max(view.minNorth, world.minNorth);
251        double maxNorth = Math.min(view.maxNorth, world.maxNorth);
252        if (minEast >= maxEast || minNorth >= maxNorth) {
253            return null;
254        }
255        // stay inside the world, but never collapse the area (the inset is a fraction of a millimetre on the ground)
256        double insetEast = Math.min((maxEast - minEast) / 4, (world.maxEast - world.minEast) * 1e-9);
257        double insetNorth = Math.min((maxNorth - minNorth) / 4, (world.maxNorth - world.minNorth) * 1e-9);
258        minEast += insetEast;
259        maxEast -= insetEast;
260        minNorth += insetNorth;
261        maxNorth -= insetNorth;
262        Bounds bounds = null;
263        for (double east : new double[] {minEast, maxEast}) {
264            for (double north : new double[] {minNorth, maxNorth}) {
265                LatLon ll = projection.eastNorth2latlon(new EastNorth(east, north));
266                if (ll.isValid()) {
267                    if (bounds == null) {
268                        bounds = new Bounds(ll, false);
269                    } else {
270                        bounds.extend(ll);
271                    }
272                }
273            }
274        }
275        return bounds != null ? bounds : mv.getRealBounds();
276    }
277
278    /**
279     * Measures the distance on screen which corresponds to one grid spacing at the center of the view. The probe
280     * is placed on whichever side of the center stays inside the valid coordinate range, and it is shortened if
281     * the spacing itself does not fit, so that the result is a usable length at every zoom level.
282     * @param mv the map view
283     * @param center the center of the view, on screen
284     * @param at the center of the view
285     * @param spacing the grid spacing, in degrees
286     * @param lon {@code true} to probe along the longitude, {@code false} along the latitude
287     * @return the distance in pixels; 0 if it cannot be measured
288     */
289    private static double probePixels(MapView mv, Point2D center, LatLon at, double spacing, boolean lon) {
290        double max = lon ? 180 : 89;
291        double delta = Math.min(spacing, max);
292        double value = lon ? at.lon() : at.lat();
293        // probe towards the pole resp. the antimeridian, or backwards if that would leave the valid range
294        double probe = value + delta <= max ? value + delta : value - delta;
295        if (probe < -max || probe > max) {
296            return 0;
297        }
298        Point2D p = mv.getPoint2D(lon ? new LatLon(at.lat(), probe) : new LatLon(probe, at.lon()));
299        return center.distance(p) * spacing / delta;
300    }
301
302    /**
303     * Computes how many projection units correspond to one metre on the ground at the given position. For
304     * conformal projections (e.g. Mercator) this is the local scale factor, for a Mercator grid at 60° latitude
305     * one metre is two projection units.
306     * @param projection the projection
307     * @param at the position (projected coordinates)
308     * @return projection units per metre; 1 if it cannot be determined (position outside the world)
309     */
310    public static double projectionUnitsPerMetre(Projection projection, EastNorth at) {
311        try {
312            if (!projection.getWorldBoundsBoxEastNorth().contains(at)) {
313                return 1;
314            }
315            double step = 100;
316            LatLon a = projection.eastNorth2latlon(at);
317            LatLon b = projection.eastNorth2latlon(new EastNorth(at.east() + step, at.north()));
318            if (!a.isValid() || !b.isValid()) {
319                return 1;
320            }
321            double metres = a.greatCircleDistance(b);
322            return metres > 0 && Double.isFinite(metres) ? step / metres : 1;
323        } catch (IllegalArgumentException e) {
324            Logging.trace(e);
325            return 1;
326        }
327    }
328
329    /**
330     * Computes the factor (a power of 10) by which the spacing must be multiplied so that the lines are at least
331     * {@link #MIN_PIXEL_SPACING} apart.
332     * @param pixelSpacing the distance between two lines on screen, in pixels
333     * @return the factor (at least 1)
334     */
335    static double thinningFactor(double pixelSpacing) {
336        double min = Math.max(1, MIN_PIXEL_SPACING.get());
337        double factor = 1;
338        if (pixelSpacing <= 0 || Double.isNaN(pixelSpacing)) {
339            return factor;
340        }
341        while (pixelSpacing * factor < min && factor < 1e15) {
342            factor *= 10;
343        }
344        return factor;
345    }
346
347    /**
348     * Computes the lines of a (possibly rotated) grid in projected coordinates which cross the given area.
349     * @param area the area to cover
350     * @param spacingX distance between the lines running in the "north" direction of the grid (before rotation)
351     * @param spacingY distance between the lines running in the "east" direction of the grid (before rotation)
352     * @param rotationDegrees rotation of the grid, counter clockwise
353     * @param originX east coordinate of the grid origin
354     * @param originY north coordinate of the grid origin
355     * @return the lines; empty if the spacing is invalid or there would be too many lines
356     */
357    public static List<ProjectedGridLine> getProjectedGridLines(ProjectionBounds area, double spacingX, double spacingY,
358            double rotationDegrees, double originX, double originY) {
359        List<ProjectedGridLine> lines = new ArrayList<>();
360        if (!isPositive(spacingX) || !isPositive(spacingY)) {
361            return lines;
362        }
363        double angle = Math.toRadians(rotationDegrees);
364        double c = Math.cos(angle);
365        double s = Math.sin(angle);
366        // grid coordinates (u along the rotated east axis, v along the rotated north axis) of the area corners
367        double[] xs = {area.minEast, area.maxEast, area.maxEast, area.minEast};
368        double[] ys = {area.minNorth, area.minNorth, area.maxNorth, area.maxNorth};
369        double uMin = Double.POSITIVE_INFINITY;
370        double uMax = Double.NEGATIVE_INFINITY;
371        double vMin = Double.POSITIVE_INFINITY;
372        double vMax = Double.NEGATIVE_INFINITY;
373        for (int i = 0; i < 4; i++) {
374            double dx = xs[i] - originX;
375            double dy = ys[i] - originY;
376            double u = c * dx + s * dy;
377            double v = -s * dx + c * dy;
378            uMin = Math.min(uMin, u);
379            uMax = Math.max(uMax, u);
380            vMin = Math.min(vMin, v);
381            vMax = Math.max(vMax, v);
382        }
383        long kuMin = (long) Math.ceil(uMin / spacingX);
384        long kuMax = (long) Math.floor(uMax / spacingX);
385        long kvMin = (long) Math.ceil(vMin / spacingY);
386        long kvMax = (long) Math.floor(vMax / spacingY);
387        if (kuMax - kuMin > MAX_LINES || kvMax - kvMin > MAX_LINES) {
388            return lines;
389        }
390        // lines of constant u run along the v axis
391        for (long k = kuMin; k <= kuMax; k++) {
392            double u = k * spacingX;
393            lines.add(new ProjectedGridLine(gridToEastNorth(u, vMin, c, s, originX, originY),
394                    gridToEastNorth(u, vMax, c, s, originX, originY), true));
395        }
396        for (long k = kvMin; k <= kvMax; k++) {
397            double v = k * spacingY;
398            lines.add(new ProjectedGridLine(gridToEastNorth(uMin, v, c, s, originX, originY),
399                    gridToEastNorth(uMax, v, c, s, originX, originY), false));
400        }
401        return lines;
402    }
403
404    private static EastNorth gridToEastNorth(double u, double v, double c, double s, double originX, double originY) {
405        return new EastNorth(originX + c * u - s * v, originY + s * u + c * v);
406    }
407
408    /**
409     * Computes the lines of a latitude/longitude grid which cross the given area. Since these lines are curves in
410     * most projections, each line is returned as a polyline.
411     * @param area the area to cover
412     * @param world the bounds of the world in the current projection, the lines are clamped to it
413     * @param spacingLon distance between the meridians, in degrees
414     * @param spacingLat distance between the parallels, in degrees
415     * @param originLon longitude of a meridian of the grid
416     * @param originLat latitude of a parallel of the grid
417     * @param segments number of segments of each polyline
418     * @return the lines; empty if the spacing is invalid or there would be too many lines
419     */
420    public static List<LatLonGridLine> getLatLonGridLines(Bounds area, Bounds world, double spacingLon, double spacingLat,
421            double originLon, double originLat, int segments) {
422        List<LatLonGridLine> lines = new ArrayList<>();
423        if (!isPositive(spacingLon) || !isPositive(spacingLat) || segments < 1) {
424            return lines;
425        }
426        double minLat = Math.max(area.getMinLat(), world.getMinLat());
427        double maxLat = Math.min(area.getMaxLat(), world.getMaxLat());
428        double minLon = area.getMinLon();
429        double maxLon = area.getMaxLon();
430        if (maxLon < minLon) {
431            maxLon += 360; // the view crosses the antimeridian
432        }
433        if (minLat >= maxLat || minLon >= maxLon) {
434            return lines;
435        }
436        long kLonMin = (long) Math.ceil((minLon - originLon) / spacingLon);
437        long kLonMax = (long) Math.floor((maxLon - originLon) / spacingLon);
438        long kLatMin = (long) Math.ceil((minLat - originLat) / spacingLat);
439        long kLatMax = (long) Math.floor((maxLat - originLat) / spacingLat);
440        if (kLonMax - kLonMin > MAX_LINES || kLatMax - kLatMin > MAX_LINES) {
441            return lines;
442        }
443        // for a projection which does not span the whole globe, meridians outside its longitude range are
444        // skipped like the parallels below; a full range must not be checked since longitudes wrap around
445        boolean limitedLon = world.getMinLon() > -180 || world.getMaxLon() < 180;
446        for (long k = kLonMin; k <= kLonMax; k++) {
447            double lon = LatLon.toIntervalLon(originLon + k * spacingLon);
448            if (!limitedLon || (lon >= world.getMinLon() && lon <= world.getMaxLon())) {
449                addMeridian(lines, lon, minLat, maxLat, segments);
450            }
451        }
452        for (long k = kLatMin; k <= kLatMax; k++) {
453            double lat = originLat + k * spacingLat;
454            if (lat < world.getMinLat() || lat > world.getMaxLat()) {
455                continue;
456            }
457            addParallel(lines, lat, minLon, maxLon, segments);
458        }
459        return lines;
460    }
461
462    /**
463     * Adds a meridian running from one latitude to another.
464     * @param lines the list to add to
465     * @param lon the longitude of the meridian
466     * @param minLat the latitude to start at
467     * @param maxLat the latitude to end at
468     * @param segments number of segments of the polyline
469     */
470    private static void addMeridian(List<LatLonGridLine> lines, double lon, double minLat, double maxLat, int segments) {
471        List<LatLon> line = new ArrayList<>(segments + 1);
472        for (int i = 0; i <= segments; i++) {
473            line.add(new LatLon(minLat + (maxLat - minLat) * i / segments, lon));
474        }
475        lines.add(new LatLonGridLine(line, true));
476    }
477
478    /**
479     * Adds a parallel running from one longitude to another. A parallel which crosses the antimeridian is added
480     * as two lines, one on each side of it: wrapping the longitudes of a single polyline would instead make it
481     * jump right across the view.
482     * @param lines the list to add to
483     * @param lat the latitude of the parallel
484     * @param minLon the longitude to start at, in [-180, 180]
485     * @param maxLon the longitude to end at, may be larger than 180 if the area crosses the antimeridian
486     * @param segments number of segments of each polyline
487     */
488    private static void addParallel(List<LatLonGridLine> lines, double lat, double minLon, double maxLon, int segments) {
489        if (maxLon > 180) {
490            addParallel(lines, lat, minLon, 180, segments);
491            addParallel(lines, lat, -180, maxLon - 360, segments);
492            return;
493        }
494        if (maxLon <= minLon) {
495            return;
496        }
497        List<LatLon> line = new ArrayList<>(segments + 1);
498        for (int i = 0; i <= segments; i++) {
499            line.add(new LatLon(lat, minLon + (maxLon - minLon) * i / segments));
500        }
501        lines.add(new LatLonGridLine(line, false));
502    }
503
504    /**
505     * Determines if a value is strictly positive. Unlike {@code value <= 0}, this rejects NaN.
506     * @param value the value
507     * @return {@code true} if the value is greater than 0
508     */
509    private static boolean isPositive(double value) {
510        return value > 0;
511    }
512
513    @Override
514    public void preferenceChanged(PreferenceChangeEvent e) {
515        if (e.getKey().startsWith(PREFIX) || e.getKey().equals(COLOR_EAST.getKey()) || e.getKey().equals(COLOR_NORTH.getKey())) {
516            invalidate();
517            MapView mv = mapView.get();
518            if (mv != null) {
519                mv.repaint();
520            }
521        }
522    }
523
524    @Override
525    public void destroy() {
526        Config.getPref().removePreferenceChangeListener(this);
527        mapView.set(null);
528    }
529}