001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.osm.visitor.paint;
003
004import java.awt.AlphaComposite;
005import java.awt.BasicStroke;
006import java.awt.Color;
007import java.awt.Component;
008import java.awt.Dimension;
009import java.awt.Font;
010import java.awt.FontMetrics;
011import java.awt.Graphics2D;
012import java.awt.Image;
013import java.awt.Point;
014import java.awt.Rectangle;
015import java.awt.RenderingHints;
016import java.awt.Shape;
017import java.awt.TexturePaint;
018import java.awt.font.FontRenderContext;
019import java.awt.font.GlyphVector;
020import java.awt.font.LineMetrics;
021import java.awt.font.TextLayout;
022import java.awt.geom.AffineTransform;
023import java.awt.geom.Path2D;
024import java.awt.geom.Point2D;
025import java.awt.geom.Rectangle2D;
026import java.awt.geom.RoundRectangle2D;
027import java.awt.image.BufferedImage;
028import java.util.ArrayList;
029import java.util.Arrays;
030import java.util.Collection;
031import java.util.HashMap;
032import java.util.Iterator;
033import java.util.List;
034import java.util.Map;
035import java.util.Objects;
036import java.util.Optional;
037import java.util.concurrent.ForkJoinPool;
038import java.util.concurrent.TimeUnit;
039import java.util.function.BiConsumer;
040import java.util.function.Consumer;
041import java.util.function.Supplier;
042
043import javax.swing.AbstractButton;
044import javax.swing.FocusManager;
045
046import org.openstreetmap.josm.data.Bounds;
047import org.openstreetmap.josm.data.coor.EastNorth;
048import org.openstreetmap.josm.data.osm.BBox;
049import org.openstreetmap.josm.data.osm.INode;
050import org.openstreetmap.josm.data.osm.IPrimitive;
051import org.openstreetmap.josm.data.osm.IRelation;
052import org.openstreetmap.josm.data.osm.IRelationMember;
053import org.openstreetmap.josm.data.osm.IWay;
054import org.openstreetmap.josm.data.osm.OsmData;
055import org.openstreetmap.josm.data.osm.OsmPrimitive;
056import org.openstreetmap.josm.data.osm.OsmUtils;
057import org.openstreetmap.josm.data.osm.Relation;
058import org.openstreetmap.josm.data.osm.WaySegment;
059import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon;
060import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.PolyData;
061import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
062import org.openstreetmap.josm.data.preferences.AbstractProperty;
063import org.openstreetmap.josm.data.preferences.BooleanProperty;
064import org.openstreetmap.josm.data.preferences.IntegerProperty;
065import org.openstreetmap.josm.data.preferences.StringProperty;
066import org.openstreetmap.josm.gui.MapViewState.MapViewPoint;
067import org.openstreetmap.josm.gui.NavigatableComponent;
068import org.openstreetmap.josm.gui.draw.MapViewPath;
069import org.openstreetmap.josm.gui.draw.MapViewPositionAndRotation;
070import org.openstreetmap.josm.gui.mappaint.ElemStyles;
071import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
072import org.openstreetmap.josm.gui.mappaint.styleelement.BoxTextElement;
073import org.openstreetmap.josm.gui.mappaint.styleelement.BoxTextElement.HorizontalTextAlignment;
074import org.openstreetmap.josm.gui.mappaint.styleelement.BoxTextElement.VerticalTextAlignment;
075import org.openstreetmap.josm.gui.mappaint.styleelement.DefaultStyles;
076import org.openstreetmap.josm.gui.mappaint.styleelement.MapImage;
077import org.openstreetmap.josm.gui.mappaint.styleelement.RepeatImageElement.LineImageAlignment;
078import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement;
079import org.openstreetmap.josm.gui.mappaint.styleelement.Symbol;
080import org.openstreetmap.josm.gui.mappaint.styleelement.TextLabel;
081import org.openstreetmap.josm.gui.mappaint.styleelement.placement.PositionForAreaStrategy;
082import org.openstreetmap.josm.spi.preferences.Config;
083import org.openstreetmap.josm.tools.CompositeList;
084import org.openstreetmap.josm.tools.Geometry;
085import org.openstreetmap.josm.tools.Geometry.AreaAndPerimeter;
086import org.openstreetmap.josm.tools.HiDPISupport;
087import org.openstreetmap.josm.tools.ImageProvider;
088import org.openstreetmap.josm.tools.JosmRuntimeException;
089import org.openstreetmap.josm.tools.Logging;
090import org.openstreetmap.josm.tools.ShapeClipper;
091import org.openstreetmap.josm.tools.Utils;
092import org.openstreetmap.josm.tools.bugreport.BugReport;
093
094/**
095 * A map renderer which renders a map according to style rules in a set of style sheets.
096 * @since 486
097 */
098public class StyledMapRenderer extends AbstractMapRenderer {
099
100    private static final ForkJoinPool THREAD_POOL = newForkJoinPool();
101
102    private static ForkJoinPool newForkJoinPool() {
103        try {
104            return Utils.newForkJoinPool(
105                    "mappaint.StyledMapRenderer.style_creation.numberOfThreads", "styled-map-renderer-%d", Thread.NORM_PRIORITY);
106        } catch (SecurityException e) {
107            Logging.log(Logging.LEVEL_ERROR, "Unable to create new ForkJoinPool", e);
108            return null;
109        }
110    }
111
112    /**
113     * This stores a style and a primitive that should be painted with that style.
114     */
115    public static class StyleRecord implements Comparable<StyleRecord> {
116        private final StyleElement style;
117        private final IPrimitive osm;
118        private final int flags;
119        private final long order;
120
121        StyleRecord(StyleElement style, IPrimitive osm, int flags) {
122            this.style = style;
123            this.osm = osm;
124            this.flags = flags;
125
126            long order = 0;
127            if ((this.flags & FLAG_DISABLED) == 0) {
128                order |= 1;
129            }
130
131            order <<= 24;
132            order |= floatToFixed(this.style.majorZIndex, 24);
133
134            // selected on top of member of selected on top of unselected
135            // FLAG_DISABLED bit is the same at this point, but we simply ignore it
136            order <<= 4;
137            order |= this.flags & 0xf;
138
139            order <<= 24;
140            order |= floatToFixed(this.style.zIndex, 24);
141
142            order <<= 1;
143            // simple node on top of icons and shapes
144            if (DefaultStyles.SIMPLE_NODE_ELEMSTYLE.equals(this.style)) {
145                order |= 1;
146            }
147
148            this.order = order;
149        }
150
151        /**
152         * Converts a float to a fixed point decimal so that the order stays the same.
153         *
154         * @param number The float to convert
155         * @param totalBits
156         *            Total number of bits. 1 sign bit. There should be at least 15 bits.
157         * @return The float converted to an integer.
158         */
159        protected static long floatToFixed(float number, int totalBits) {
160            long value = Float.floatToIntBits(number) & 0xffffffffL;
161
162            boolean negative = (value & 0x80000000L) != 0;
163            // Invert the sign bit, so that negative numbers are lower
164            value ^= 0x80000000L;
165            // Now do the shift. Do it before accounting for negative numbers (symmetry)
166            if (totalBits < 32) {
167                value >>= (32 - totalBits);
168            }
169            // positive numbers are sorted now. Negative ones the wrong way.
170            if (negative) {
171                // Negative number: re-map it
172                value = (1L << (totalBits - 1)) - value;
173            }
174            return value;
175        }
176
177        @Override
178        public int compareTo(StyleRecord other) {
179            int d = Long.compare(order, other.order);
180            if (d != 0) {
181                return d;
182            }
183
184            // newer primitives to the front
185            long id = this.osm.getUniqueId() - other.osm.getUniqueId();
186            if (id > 0)
187                return 1;
188            if (id < 0)
189                return -1;
190
191            return Float.compare(this.style.objectZIndex, other.style.objectZIndex);
192        }
193
194        @Override
195        public int hashCode() {
196            return Objects.hash(order, osm, style, flags);
197        }
198
199        @Override
200        public boolean equals(Object obj) {
201            if (this == obj)
202                return true;
203            if (obj == null || getClass() != obj.getClass())
204                return false;
205            StyleRecord other = (StyleRecord) obj;
206            return flags == other.flags
207                && order == other.order
208                && Objects.equals(osm, other.osm)
209                && Objects.equals(style, other.style);
210        }
211
212        /**
213         * Get the style for this style element.
214         * @return The style
215         */
216        public StyleElement getStyle() {
217            return style;
218        }
219
220        /**
221         * Paints the primitive with the style.
222         * @param paintSettings The settings to use.
223         * @param painter The painter to paint the style.
224         */
225        public void paintPrimitive(MapPaintSettings paintSettings, StyledMapRenderer painter) {
226            style.paintPrimitive(
227                    osm,
228                    paintSettings,
229                    painter,
230                    (flags & FLAG_SELECTED) != 0,
231                    (flags & FLAG_OUTERMEMBER_OF_SELECTED) != 0,
232                    (flags & FLAG_MEMBER_OF_SELECTED) != 0
233            );
234        }
235
236        @Override
237        public String toString() {
238            return "StyleRecord [style=" + style + ", osm=" + osm + ", flags=" + flags + "]";
239        }
240    }
241
242    private static final Map<Font, Boolean> IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG = new HashMap<>();
243
244    /**
245     * Check, if this System has the GlyphVector double translation bug.
246     *
247     * With this bug, <code>gv.setGlyphTransform(i, trfm)</code> has a different
248     * effect than on most other systems, namely the translation components
249     * ("m02" &amp; "m12", {@link AffineTransform}) appear to be twice as large, as
250     * they actually are. The rotation is unaffected (scale &amp; shear not tested
251     * so far).
252     *
253     * This bug has only been observed on Mac OS X, see #7841.
254     *
255     * After switch to Java 7, this test is a false positive on Mac OS X (see #10446),
256     * i.e. it returns true, but the real rendering code does not require any special
257     * handling.
258     * It hasn't been further investigated why the test reports a wrong result in
259     * this case, but the method has been changed to simply return false by default.
260     * (This can be changed with a setting in the advanced preferences.)
261     *
262     * @param font The font to check.
263     * @return false by default, but depends on the value of the advanced
264     * preference glyph-bug=false|true|auto, where auto is the automatic detection
265     * method which apparently no longer gives a useful result for Java 7.
266     */
267    public static boolean isGlyphVectorDoubleTranslationBug(Font font) {
268        Boolean cached = IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG.get(font);
269        if (cached != null)
270            return cached;
271        String overridePref = Config.getPref().get("glyph-bug", "auto");
272        if ("auto".equals(overridePref)) {
273            FontRenderContext frc = new FontRenderContext(null, false, false);
274            GlyphVector gv = font.createGlyphVector(frc, "x");
275            gv.setGlyphTransform(0, AffineTransform.getTranslateInstance(1000, 1000));
276            Shape shape = gv.getGlyphOutline(0);
277            if (Logging.isTraceEnabled()) {
278                Logging.trace("#10446: shape: {0}", shape.getBounds());
279            }
280            // x is about 1000 on normal stystems and about 2000 when the bug occurs
281            int x = shape.getBounds().x;
282            boolean isBug = x > 1500;
283            IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG.put(font, isBug);
284            return isBug;
285        } else {
286            boolean override = Boolean.parseBoolean(overridePref);
287            IS_GLYPH_VECTOR_DOUBLE_TRANSLATION_BUG.put(font, override);
288            return override;
289        }
290    }
291
292    private double circum;
293    private double scale;
294
295    private MapPaintSettings paintSettings;
296    private ElemStyles styles;
297
298    private Color highlightColorTransparent;
299
300    /**
301     * Flags used to store the primitive state along with the style. This is the normal style.
302     * <p>
303     * Not used in any public interfaces.
304     */
305    static final int FLAG_NORMAL = 0;
306    /**
307     * A primitive with {@link OsmPrimitive#isDisabled()}
308     */
309    static final int FLAG_DISABLED = 1;
310    /**
311     * A primitive with {@link OsmPrimitive#isMemberOfSelected()}
312     */
313    static final int FLAG_MEMBER_OF_SELECTED = 2;
314    /**
315     * A primitive with {@link OsmPrimitive#isSelected()}
316     */
317    static final int FLAG_SELECTED = 4;
318    /**
319     * A primitive with {@link OsmPrimitive#isOuterMemberOfSelected()}
320     */
321    static final int FLAG_OUTERMEMBER_OF_SELECTED = 8;
322
323    private static final double PHI = Utils.toRadians(20);
324    private static final double cosPHI = Math.cos(PHI);
325    private static final double sinPHI = Math.sin(PHI);
326    /**
327     * If we should use left hand traffic.
328     */
329    private static final AbstractProperty<Boolean> PREFERENCE_LEFT_HAND_TRAFFIC
330            = new BooleanProperty("mappaint.lefthandtraffic", false).cached();
331    /**
332     * Indicates that the renderer should enable anti-aliasing
333     * @since 11758
334     */
335    public static final AbstractProperty<Boolean> PREFERENCE_ANTIALIASING_USE
336            = new BooleanProperty("mappaint.use-antialiasing", true).cached();
337    /**
338     * The mode that is used for anti-aliasing
339     * @since 11758
340     */
341    public static final AbstractProperty<String> PREFERENCE_TEXT_ANTIALIASING
342            = new StringProperty("mappaint.text-antialiasing", "default").cached();
343
344    /**
345     * The line with to use for highlighting
346     */
347    private static final AbstractProperty<Integer> HIGHLIGHT_LINE_WIDTH = new IntegerProperty("mappaint.highlight.width", 4).cached();
348    private static final AbstractProperty<Integer> HIGHLIGHT_POINT_RADIUS = new IntegerProperty("mappaint.highlight.radius", 7).cached();
349    private static final AbstractProperty<Integer> WIDER_HIGHLIGHT = new IntegerProperty("mappaint.highlight.bigger-increment", 5).cached();
350    private static final AbstractProperty<Integer> HIGHLIGHT_STEP = new IntegerProperty("mappaint.highlight.step", 4).cached();
351
352    private Collection<WaySegment> highlightWaySegments;
353
354    //flag that activate wider highlight mode
355    private boolean useWiderHighlight;
356
357    private boolean useStrokes;
358    private boolean showNames;
359    private boolean showIcons;
360    private boolean isOutlineOnly;
361
362    private boolean leftHandTraffic;
363    private Object antialiasing;
364
365    private Supplier<RenderBenchmarkCollector> benchmarkFactory = RenderBenchmarkCollector.defaultBenchmarkSupplier();
366
367    /**
368     * Constructs a new {@code StyledMapRenderer}.
369     *
370     * @param g the graphics context. Must not be null.
371     * @param nc the map viewport. Must not be null.
372     * @param isInactiveMode if true, the paint visitor shall render OSM objects such that they
373     * look inactive. Example: rendering of data in an inactive layer using light gray as color only.
374     * @throws IllegalArgumentException if {@code g} is null
375     * @throws IllegalArgumentException if {@code nc} is null
376     */
377    public StyledMapRenderer(Graphics2D g, NavigatableComponent nc, boolean isInactiveMode) {
378        super(g, nc, isInactiveMode);
379        Component focusOwner = FocusManager.getCurrentManager().getFocusOwner();
380        useWiderHighlight = !(focusOwner instanceof AbstractButton || focusOwner == nc);
381        this.styles = MapPaintStyles.getStyles();
382    }
383
384    /**
385     * Set the {@link ElemStyles} instance to use for this renderer.
386     * @param styles the {@code ElemStyles} instance to use
387     */
388    public void setStyles(ElemStyles styles) {
389        this.styles = styles;
390    }
391
392    private void displaySegments(MapViewPath path, Path2D orientationArrows, Path2D onewayArrows, Path2D onewayArrowsCasing,
393            Color color, BasicStroke line, BasicStroke dashes, Color dashedColor) {
394        g.setColor(isInactiveMode ? inactiveColor : color);
395        if (useStrokes) {
396            g.setStroke(line);
397        }
398        g.draw(path.computeClippedLine(g.getStroke()));
399
400        if (!isInactiveMode && useStrokes && dashes != null) {
401            g.setColor(dashedColor);
402            g.setStroke(dashes);
403            g.draw(path.computeClippedLine(dashes));
404        }
405
406        if (orientationArrows != null) {
407            g.setColor(isInactiveMode ? inactiveColor : color);
408            g.setStroke(new BasicStroke(line.getLineWidth(), line.getEndCap(), BasicStroke.JOIN_MITER, line.getMiterLimit()));
409            g.draw(orientationArrows);
410        }
411
412        if (onewayArrows != null) {
413            g.setStroke(new BasicStroke(1, line.getEndCap(), BasicStroke.JOIN_MITER, line.getMiterLimit()));
414            g.fill(onewayArrowsCasing);
415            g.setColor(isInactiveMode ? inactiveColor : backgroundColor);
416            g.fill(onewayArrows);
417        }
418
419        if (useStrokes) {
420            g.setStroke(new BasicStroke());
421        }
422    }
423
424    /**
425     * Worker function for drawing areas.
426     *
427     * @param path the path object for the area that should be drawn; in case
428     * of multipolygons, this can path can be a complex shape with one outer
429     * polygon and one or more inner polygons
430     * @param color The color to fill the area with.
431     * @param fillImage The image to fill the area with. Overrides color.
432     * @param extent if not null, area will be filled partially; specifies, how
433     * far to fill from the boundary towards the center of the area;
434     * if null, area will be filled completely
435     * @param pfClip clipping area for partial fill (only needed for unclosed
436     * polygons)
437     * @param disabled If this should be drawn with a special disabled style.
438     */
439    protected void drawArea(MapViewPath path, Color color,
440            MapImage fillImage, Float extent, MapViewPath pfClip, boolean disabled) {
441        if (!isOutlineOnly && color.getAlpha() != 0) {
442            Shape area = path;
443            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
444            if (fillImage == null) {
445                if (isInactiveMode) {
446                    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.33f));
447                }
448                g.setColor(color);
449                computeFill(area, extent, pfClip, 4);
450            } else {
451                // TexturePaint requires BufferedImage -> get base image from possible multi-resolution image
452                Image img = HiDPISupport.getBaseImage(fillImage.getImage(disabled));
453                if (img != null) {
454                    g.setPaint(new TexturePaint((BufferedImage) img,
455                            new Rectangle(0, 0, fillImage.getWidth(), fillImage.getHeight())));
456                } else {
457                    Logging.warn("Unable to get image from " + fillImage);
458                }
459                Float alpha = fillImage.getAlphaFloat();
460                if (!Utils.equalsEpsilon(alpha, 1f)) {
461                    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
462                }
463                computeFill(area, extent, pfClip, 10);
464                g.setPaintMode();
465            }
466            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialiasing);
467        }
468    }
469
470    /**
471     * Fill the given shape. If partial fill is used, computes the clipping.
472     * @param shape the given shape
473     * @param extent if not null, area will be filled partially; specifies, how
474     * far to fill from the boundary towards the center of the area;
475     * if null, area will be filled completely
476     * @param pfClip clipping area for partial fill (only needed for unclosed
477     * polygons)
478     * @param mitterLimit parameter for BasicStroke
479     *
480     */
481    private void computeFill(Shape shape, Float extent, MapViewPath pfClip, float mitterLimit) {
482        if (extent == null) {
483            g.fill(shape);
484        } else {
485            Shape oldClip = g.getClip();
486            Shape clip = shape;
487            if (pfClip != null) {
488                clip = pfClip;
489            }
490            g.clip(clip);
491            g.setStroke(new BasicStroke(2 * extent, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, mitterLimit));
492            g.draw(shape);
493            g.setClip(oldClip);
494            g.setStroke(new BasicStroke());
495        }
496    }
497
498    /**
499     * Draws a multipolygon area.
500     * @param r The multipolygon relation
501     * @param color The color to fill the area with.
502     * @param fillImage The image to fill the area with. Overrides color.
503     * @param extent if not null, area will be filled partially; specifies, how
504     * far to fill from the boundary towards the center of the area;
505     * if null, area will be filled completely
506     * @param extentThreshold if not null, determines if the partial filled should
507     * be replaced by plain fill, when it covers a certain fraction of the total area
508     * @param disabled If this should be drawn with a special disabled style.
509     * @since 12285
510     */
511    public void drawArea(Relation r, Color color, MapImage fillImage, Float extent, Float extentThreshold, boolean disabled) {
512        Multipolygon multipolygon = MultipolygonCache.getInstance().get(r);
513        if (!r.isDisabled() && !multipolygon.getOuterWays().isEmpty()) {
514            for (PolyData pd : multipolygon.getCombinedPolygons()) {
515                if (!isAreaVisible(pd.get())) {
516                    continue;
517                }
518                MapViewPath p = shapeEastNorthToMapView(pd.get());
519                MapViewPath pfClip = null;
520                if (extent != null) {
521                    if (!usePartialFill(pd.getAreaAndPerimeter(null), extent, extentThreshold)) {
522                        extent = null;
523                    } else if (!pd.isClosed()) {
524                        pfClip = shapeEastNorthToMapView(getPFClip(pd, extent * scale));
525                    }
526                }
527                drawArea(p,
528                        pd.isSelected() ? paintSettings.getRelationSelectedColor(color.getAlpha()) : color,
529                        fillImage, extent, pfClip, disabled);
530            }
531        }
532    }
533
534    /**
535     * Convert shape in EastNorth coordinates to MapViewPath and remove invisible parts.
536     * For complex shapes this improves performance drastically because the methods in Graphics2D.clip() and Graphics2D.draw() are rather slow.
537     * @param shape the shape to convert
538     * @return the converted shape
539     */
540    private MapViewPath shapeEastNorthToMapView(Path2D.Double shape) {
541        MapViewPath convertedShape = null;
542        if (shape != null) {
543            convertedShape = new MapViewPath(mapState);
544            convertedShape.appendFromEastNorth(shape);
545            convertedShape.setWindingRule(Path2D.WIND_EVEN_ODD);
546
547            Rectangle2D extViewBBox = mapState.getViewClipRectangle().getInView();
548            if (!extViewBBox.contains(convertedShape.getBounds2D())) {
549                // remove invisible parts of shape
550                Path2D.Double clipped = ShapeClipper.clipShape(convertedShape, extViewBBox);
551                if (clipped != null) {
552                    convertedShape.reset();
553                    convertedShape.append(clipped, false);
554                }
555            }
556        }
557        return convertedShape;
558    }
559
560    /**
561     * Draws an area defined by a way. They way does not need to be closed, but it should.
562     * @param w The way.
563     * @param color The color to fill the area with.
564     * @param fillImage The image to fill the area with. Overrides color.
565     * @param extent if not null, area will be filled partially; specifies, how
566     * far to fill from the boundary towards the center of the area;
567     * if null, area will be filled completely
568     * @param extentThreshold if not null, determines if the partial filled should
569     * be replaced by plain fill, when it covers a certain fraction of the total area
570     * @param disabled If this should be drawn with a special disabled style.
571     * @since 12285
572     */
573    public void drawArea(IWay<?> w, Color color, MapImage fillImage, Float extent, Float extentThreshold, boolean disabled) {
574        MapViewPath pfClip = null;
575        if (extent != null) {
576            if (!usePartialFill(Geometry.getAreaAndPerimeter(w.getNodes()), extent, extentThreshold)) {
577                extent = null;
578            } else if (!w.isClosed()) {
579                pfClip = shapeEastNorthToMapView(getPFClip(w, extent * scale));
580            }
581        }
582        drawArea(getPath(w), color, fillImage, extent, pfClip, disabled);
583    }
584
585    /**
586     * Determine, if partial fill should be turned off for this object, because
587     * only a small unfilled gap in the center of the area would be left.
588     *
589     * This is used to get a cleaner look for urban regions with many small
590     * areas like buildings, etc.
591     * @param ap the area and the perimeter of the object
592     * @param extent the "width" of partial fill
593     * @param threshold when the partial fill covers that much of the total
594     * area, the partial fill is turned off; can be greater than 100% as the
595     * covered area is estimated as <code>perimeter * extent</code>
596     * @return true, if the partial fill should be used, false otherwise
597     */
598    private boolean usePartialFill(AreaAndPerimeter ap, float extent, Float threshold) {
599        if (threshold == null) return true;
600        return ap.getPerimeter() * extent * scale < threshold * ap.getArea();
601    }
602
603    /**
604     * Draw a text onto a node
605     * @param n The node to draw the text on
606     * @param bs The text and it's alignment.
607     */
608    public void drawBoxText(INode n, BoxTextElement bs) {
609        if (!isShowNames() || bs == null)
610            return;
611
612        MapViewPoint p = mapState.getPointFor(n);
613        TextLabel text = bs.text;
614        String s = text.labelCompositionStrategy.compose(n);
615        if (s == null || s.isEmpty()) return;
616
617        Font defaultFont = g.getFont();
618        g.setFont(text.font);
619
620        FontRenderContext frc = g.getFontRenderContext();
621        Rectangle2D bounds = text.font.getStringBounds(s, frc);
622
623        double x = Math.round(p.getInViewX()) + bs.xOffset + bounds.getCenterX();
624        double y = Math.round(p.getInViewY()) + bs.yOffset + bounds.getCenterY();
625        /**
626         *
627         *       left-above __center-above___ right-above
628         *         left-top|                 |right-top
629         *                 |                 |
630         *      left-center|  center-center  |right-center
631         *                 |                 |
632         *      left-bottom|_________________|right-bottom
633         *       left-below   center-below    right-below
634         *
635         */
636        Rectangle box = bs.getBox();
637        if (bs.hAlign == HorizontalTextAlignment.RIGHT) {
638            x += box.x + box.width + 2;
639        } else {
640            int textWidth = (int) bounds.getWidth();
641            if (bs.hAlign == HorizontalTextAlignment.CENTER) {
642                x -= textWidth / 2d;
643            } else if (bs.hAlign == HorizontalTextAlignment.LEFT) {
644                x -= -box.x + 4 + textWidth;
645            } else throw new AssertionError();
646        }
647
648        if (bs.vAlign == VerticalTextAlignment.BOTTOM) {
649            y += box.y + box.height;
650        } else {
651            LineMetrics metrics = text.font.getLineMetrics(s, frc);
652            if (bs.vAlign == VerticalTextAlignment.ABOVE) {
653                y -= -box.y + (int) metrics.getDescent();
654            } else if (bs.vAlign == VerticalTextAlignment.TOP) {
655                y -= -box.y - (int) metrics.getAscent();
656            } else if (bs.vAlign == VerticalTextAlignment.CENTER) {
657                y += (int) ((metrics.getAscent() - metrics.getDescent()) / 2);
658            } else if (bs.vAlign == VerticalTextAlignment.BELOW) {
659                y += box.y + box.height + (int) metrics.getAscent() + 2;
660            } else throw new AssertionError();
661        }
662
663        displayText(n, text, s, bounds, new MapViewPositionAndRotation(mapState.getForView(x, y), 0));
664        g.setFont(defaultFont);
665    }
666
667    /**
668     * Draw an image along a way repeatedly.
669     *
670     * @param way the way
671     * @param pattern the image
672     * @param disabled If this should be drawn with a special disabled style.
673     * @param offset offset from the way
674     * @param spacing spacing between two images
675     * @param phase initial spacing
676     * @param align alignment of the image. The top, center or bottom edge can be aligned with the way.
677     */
678    public void drawRepeatImage(IWay<?> way, MapImage pattern, boolean disabled, double offset, double spacing, double phase,
679            LineImageAlignment align) {
680        final int imgWidth = pattern.getWidth();
681        final double repeat = imgWidth + spacing;
682        final int imgHeight = pattern.getHeight();
683
684        int dy1 = (int) ((align.getAlignmentOffset() - .5) * imgHeight);
685        int dy2 = dy1 + imgHeight;
686
687        OffsetIterator it = new OffsetIterator(mapState, way.getNodes(), offset);
688        MapViewPath path = new MapViewPath(mapState);
689        if (it.hasNext()) {
690            path.moveTo(it.next());
691        }
692        while (it.hasNext()) {
693            path.lineTo(it.next());
694        }
695
696        double startOffset = computeStartOffset(phase, repeat);
697
698        Image image = pattern.getImage(disabled);
699
700        path.visitClippedLine(repeat, (inLineOffset, start, end, startIsOldEnd) -> {
701            final double segmentLength = start.distanceToInView(end);
702            if (segmentLength < 0.1) {
703                // avoid odd patterns when zoomed out.
704                return;
705            }
706            if (segmentLength > repeat * 500) {
707                // simply skip drawing so many images - something must be wrong.
708                return;
709            }
710            AffineTransform saveTransform = g.getTransform();
711            g.translate(start.getInViewX(), start.getInViewY());
712            double dx = end.getInViewX() - start.getInViewX();
713            double dy = end.getInViewY() - start.getInViewY();
714            g.rotate(Math.atan2(dy, dx));
715
716            // The start of the next image
717            // It is shifted by startOffset.
718            double imageStart = -((inLineOffset - startOffset + repeat) % repeat);
719
720            while (imageStart < segmentLength) {
721                int x = (int) imageStart;
722                int sx1 = Math.max(0, -x);
723                int sx2 = imgWidth - Math.max(0, x + imgWidth - (int) Math.ceil(segmentLength));
724                g.drawImage(image, x + sx1, dy1, x + sx2, dy2, sx1, 0, sx2, imgHeight, null);
725                imageStart += repeat;
726            }
727
728            g.setTransform(saveTransform);
729        });
730    }
731
732    private static double computeStartOffset(double phase, final double repeat) {
733        double startOffset = phase % repeat;
734        if (startOffset < 0) {
735            startOffset += repeat;
736        }
737        return startOffset;
738    }
739
740    @Override
741    public void drawNode(INode n, Color color, int size, boolean fill) {
742        if (size <= 0 && !n.isHighlighted())
743            return;
744
745        MapViewPoint p = mapState.getPointFor(n);
746
747        if (n.isHighlighted()) {
748            drawPointHighlight(p.getInView(), size);
749        }
750
751        if (size > 1 && p.isInView()) {
752            int radius = size / 2;
753
754            if (isInactiveMode || n.isDisabled()) {
755                g.setColor(inactiveColor);
756            } else {
757                g.setColor(color);
758            }
759            Rectangle2D rect = new Rectangle2D.Double(p.getInViewX()-radius-1d, p.getInViewY()-radius-1d, size + 1d, size + 1d);
760            if (fill) {
761                g.fill(rect);
762            } else {
763                g.draw(rect);
764            }
765        }
766    }
767
768    /**
769     * Draw the icon for a given node.
770     * @param n The node
771     * @param img The icon to draw at the node position
772     * @param disabled {@code} true to render disabled version, {@code false} for the standard version
773     * @param selected {@code} true to render it as selected, {@code false} otherwise
774     * @param member {@code} true to render it as a relation member, {@code false} otherwise
775     * @param theta the angle of rotation in radians
776     */
777    public void drawNodeIcon(INode n, MapImage img, boolean disabled, boolean selected, boolean member, double theta) {
778        MapViewPoint p = mapState.getPointFor(n);
779
780        int w = img.getWidth();
781        int h = img.getHeight();
782        if (n.isHighlighted()) {
783            drawPointHighlight(p.getInView(), Math.max(w, h));
784        }
785
786        drawIcon(p, img, disabled, selected, member, theta, (g, r) -> {
787            Color color = getSelectionHintColor(disabled, selected);
788            g.setColor(color);
789            g.draw(r);
790        });
791    }
792
793    /**
794     * Draw the icon for a given area. Normally, the icon is drawn around the center of the area.
795     * @param osm The primitive to draw the icon for
796     * @param img The icon to draw
797     * @param disabled {@code} true to render disabled version, {@code false} for the standard version
798     * @param selected {@code} true to render it as selected, {@code false} otherwise
799     * @param member {@code} true to render it as a relation member, {@code false} otherwise
800     * @param theta the angle of rotation in radians
801     * @param iconPosition Where to place the icon.
802     * @since 11670
803     */
804    public void drawAreaIcon(IPrimitive osm, MapImage img, boolean disabled, boolean selected, boolean member, double theta,
805            PositionForAreaStrategy iconPosition) {
806        Rectangle2D.Double iconRect = new Rectangle2D.Double(-img.getWidth() / 2.0, -img.getHeight() / 2.0, img.getWidth(), img.getHeight());
807
808        forEachPolygon(osm, path -> {
809            MapViewPositionAndRotation placement = iconPosition.findLabelPlacement(path, iconRect);
810            if (placement == null) {
811                return;
812            }
813            MapViewPoint p = placement.getPoint();
814            drawIcon(p, img, disabled, selected, member, theta + placement.getRotation(), (g, r) -> {
815                if (useStrokes) {
816                    g.setStroke(new BasicStroke(2));
817                }
818                // only draw a minor highlighting, so that users do not confuse this for a point.
819                Color color = getSelectionHintColor(disabled, selected);
820                color = new Color(color.getRed(), color.getGreen(), color.getBlue(), (int) (color.getAlpha() * .2));
821                g.setColor(color);
822                g.draw(r);
823            });
824        });
825    }
826
827    private void drawIcon(MapViewPoint p, MapImage img, boolean disabled, boolean selected, boolean member, double theta,
828            BiConsumer<Graphics2D, Rectangle2D> selectionDrawer) {
829        float alpha = img.getAlphaFloat();
830
831        Graphics2D temporaryGraphics = (Graphics2D) g.create();
832        if (!Utils.equalsEpsilon(alpha, 1f)) {
833            temporaryGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
834        }
835
836        double x = Math.round(p.getInViewX());
837        double y = Math.round(p.getInViewY());
838        temporaryGraphics.translate(x, y);
839        temporaryGraphics.rotate(theta);
840        int drawX = -img.getWidth() / 2 + img.offsetX;
841        int drawY = -img.getHeight() / 2 + img.offsetY;
842        temporaryGraphics.drawImage(img.getImage(disabled), drawX, drawY, nc);
843        if (selected || member) {
844            selectionDrawer.accept(temporaryGraphics, new Rectangle2D.Double(drawX - 2d, drawY - 2d, img.getWidth() + 4d, img.getHeight() + 4d));
845        }
846    }
847
848    private Color getSelectionHintColor(boolean disabled, boolean selected) {
849        Color color;
850        if (disabled) {
851            color = inactiveColor;
852        } else if (selected) {
853            color = selectedColor;
854        } else {
855            color = relationSelectedColor;
856        }
857        return color;
858    }
859
860    /**
861     * Draw the symbol and possibly a highlight marking on a given node.
862     * @param n The position to draw the symbol on
863     * @param s The symbol to draw
864     * @param fillColor The color to fill the symbol with
865     * @param strokeColor The color to use for the outer corner of the symbol
866     */
867    public void drawNodeSymbol(INode n, Symbol s, Color fillColor, Color strokeColor) {
868        MapViewPoint p = mapState.getPointFor(n);
869
870        if (n.isHighlighted()) {
871            drawPointHighlight(p.getInView(), s.size);
872        }
873
874        if (fillColor != null || strokeColor != null) {
875            Shape shape = s.buildShapeAround(p.getInViewX(), p.getInViewY());
876
877            if (fillColor != null) {
878                g.setColor(fillColor);
879                g.fill(shape);
880            }
881            if (s.stroke != null) {
882                g.setStroke(s.stroke);
883                g.setColor(strokeColor);
884                g.draw(shape);
885                g.setStroke(new BasicStroke());
886            }
887        }
888    }
889
890    /**
891     * Draw a number of the order of the two consecutive nodes within the
892     * parents way
893     *
894     * @param n1 First node of the way segment.
895     * @param n2 Second node of the way segment.
896     * @param orderNumber The number of the segment in the way.
897     * @param clr The color to use for drawing the text.
898     */
899    public void drawOrderNumber(INode n1, INode n2, int orderNumber, Color clr) {
900        MapViewPoint p1 = mapState.getPointFor(n1);
901        MapViewPoint p2 = mapState.getPointFor(n2);
902        drawOrderNumber(p1, p2, orderNumber, clr);
903    }
904
905    /**
906     * highlights a given GeneralPath using the settings from BasicStroke to match the line's
907     * style. Width of the highlight can be changed by user preferences
908     * @param path path to draw
909     * @param line line style
910     */
911    private void drawPathHighlight(MapViewPath path, BasicStroke line) {
912        if (path == null)
913            return;
914        g.setColor(highlightColorTransparent);
915        float w = line.getLineWidth() + HIGHLIGHT_LINE_WIDTH.get();
916        if (useWiderHighlight) {
917            w += WIDER_HIGHLIGHT.get();
918        }
919        int step = Math.max(HIGHLIGHT_STEP.get(), 1);
920        while (w >= line.getLineWidth()) {
921            g.setStroke(new BasicStroke(w, line.getEndCap(), line.getLineJoin(), line.getMiterLimit()));
922            g.draw(path);
923            w -= step;
924        }
925    }
926
927    /**
928     * highlights a given point by drawing a rounded rectangle around it. Give the
929     * size of the object you want to be highlighted, width is added automatically.
930     * @param p point
931     * @param size highlight size
932     */
933    private void drawPointHighlight(Point2D p, int size) {
934        g.setColor(highlightColorTransparent);
935        int s = size + HIGHLIGHT_POINT_RADIUS.get();
936        if (useWiderHighlight) {
937            s += WIDER_HIGHLIGHT.get();
938        }
939        int step = Math.max(HIGHLIGHT_STEP.get(), 1);
940        while (s >= size) {
941            int r = (int) Math.floor(s/2d);
942            g.fill(new RoundRectangle2D.Double(p.getX()-r, p.getY()-r, s, s, r, r));
943            s -= step;
944        }
945    }
946
947    /**
948     * Draws a restriction.
949     * @param img symbol image
950     * @param pVia "via" node
951     * @param vx X offset
952     * @param vy Y offset
953     * @param angle the rotated angle, in degree, clockwise
954     * @param selected if true, draws a selection rectangle
955     * @since 13676
956     */
957    public void drawRestriction(Image img, Point pVia, double vx, double vy, double angle, boolean selected) {
958        // rotate image with direction last node in from to, and scale down image to 16*16 pixels
959        Image smallImg = ImageProvider.createRotatedImage(img, angle, new Dimension(16, 16));
960        int w = smallImg.getWidth(null), h = smallImg.getHeight(null);
961        g.drawImage(smallImg, (int) (pVia.x+vx)-w/2, (int) (pVia.y+vy)-h/2, nc);
962
963        if (selected) {
964            g.setColor(isInactiveMode ? inactiveColor : relationSelectedColor);
965            g.drawRect((int) (pVia.x+vx)-w/2-2, (int) (pVia.y+vy)-h/2-2, w+4, h+4);
966        }
967    }
968
969    /**
970     * Draw a turn restriction
971     * @param r The turn restriction relation
972     * @param icon The icon to draw at the turn point
973     * @param disabled draw using disabled style
974     */
975    public void drawRestriction(IRelation<?> r, MapImage icon, boolean disabled) {
976        IWay<?> fromWay = null;
977        IWay<?> toWay = null;
978        IPrimitive via = null;
979
980        /* find the "from", "via" and "to" elements */
981        for (IRelationMember<?> m : r.getMembers()) {
982            if (m.getMember().isIncomplete())
983                return;
984            else {
985                if (m.isWay()) {
986                    IWay<?> w = (IWay<?>) m.getMember();
987                    if (w.getNodesCount() < 2) {
988                        continue;
989                    }
990
991                    switch(m.getRole()) {
992                    case "from":
993                        if (fromWay == null) {
994                            fromWay = w;
995                        }
996                        break;
997                    case "to":
998                        if (toWay == null) {
999                            toWay = w;
1000                        }
1001                        break;
1002                    case "via":
1003                        if (via == null) {
1004                            via = w;
1005                        }
1006                        break;
1007                    default: // Do nothing
1008                    }
1009                } else if (m.isNode()) {
1010                    INode n = (INode) m.getMember();
1011                    if (via == null && "via".equals(m.getRole())) {
1012                        via = n;
1013                    }
1014                }
1015            }
1016        }
1017
1018        if (fromWay == null || toWay == null || via == null)
1019            return;
1020
1021        INode viaNode;
1022        if (via instanceof INode) {
1023            viaNode = (INode) via;
1024            if (!fromWay.isFirstLastNode(viaNode))
1025                return;
1026        } else {
1027            IWay<?> viaWay = (IWay<?>) via;
1028            INode firstNode = viaWay.firstNode();
1029            INode lastNode = viaWay.lastNode();
1030            Boolean onewayvia = Boolean.FALSE;
1031
1032            String onewayviastr = viaWay.get("oneway");
1033            if (onewayviastr != null) {
1034                if ("-1".equals(onewayviastr)) {
1035                    onewayvia = Boolean.TRUE;
1036                    INode tmp = firstNode;
1037                    firstNode = lastNode;
1038                    lastNode = tmp;
1039                } else {
1040                    onewayvia = Optional.ofNullable(OsmUtils.getOsmBoolean(onewayviastr)).orElse(Boolean.FALSE);
1041                }
1042            }
1043
1044            if (fromWay.isFirstLastNode(firstNode)) {
1045                viaNode = firstNode;
1046            } else if (!onewayvia && fromWay.isFirstLastNode(lastNode)) {
1047                viaNode = lastNode;
1048            } else
1049                return;
1050        }
1051
1052        /* find the "direct" nodes before the via node */
1053        INode fromNode;
1054        if (fromWay.firstNode() == via) {
1055            fromNode = fromWay.getNode(1);
1056        } else {
1057            fromNode = fromWay.getNode(fromWay.getNodesCount()-2);
1058        }
1059
1060        Point pFrom = nc.getPoint(fromNode);
1061        Point pVia = nc.getPoint(viaNode);
1062
1063        /* starting from via, go back the "from" way a few pixels
1064           (calculate the vector vx/vy with the specified length and the direction
1065           away from the "via" node along the first segment of the "from" way)
1066         */
1067        double distanceFromVia = 14;
1068        double dx = pFrom.x >= pVia.x ? pFrom.x - pVia.x : pVia.x - pFrom.x;
1069        double dy = pFrom.y >= pVia.y ? pFrom.y - pVia.y : pVia.y - pFrom.y;
1070
1071        double fromAngle;
1072        if (dx == 0) {
1073            fromAngle = Math.PI/2;
1074        } else {
1075            fromAngle = Math.atan(dy / dx);
1076        }
1077        double fromAngleDeg = Utils.toDegrees(fromAngle);
1078
1079        double vx = distanceFromVia * Math.cos(fromAngle);
1080        double vy = distanceFromVia * Math.sin(fromAngle);
1081
1082        if (pFrom.x < pVia.x) {
1083            vx = -vx;
1084        }
1085        if (pFrom.y < pVia.y) {
1086            vy = -vy;
1087        }
1088
1089        /* go a few pixels away from the way (in a right angle)
1090           (calculate the vx2/vy2 vector with the specified length and the direction
1091           90degrees away from the first segment of the "from" way)
1092         */
1093        double distanceFromWay = 10;
1094        double vx2 = 0;
1095        double vy2 = 0;
1096        double iconAngle = 0;
1097
1098        if (pFrom.x >= pVia.x && pFrom.y >= pVia.y) {
1099            if (!leftHandTraffic) {
1100                vx2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg - 90));
1101                vy2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg - 90));
1102            } else {
1103                vx2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg + 90));
1104                vy2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg + 90));
1105            }
1106            iconAngle = 270+fromAngleDeg;
1107        }
1108        if (pFrom.x < pVia.x && pFrom.y >= pVia.y) {
1109            if (!leftHandTraffic) {
1110                vx2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg));
1111                vy2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg));
1112            } else {
1113                vx2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg + 180));
1114                vy2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg + 180));
1115            }
1116            iconAngle = 90-fromAngleDeg;
1117        }
1118        if (pFrom.x < pVia.x && pFrom.y < pVia.y) {
1119            if (!leftHandTraffic) {
1120                vx2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg + 90));
1121                vy2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg + 90));
1122            } else {
1123                vx2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg - 90));
1124                vy2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg - 90));
1125            }
1126            iconAngle = 90+fromAngleDeg;
1127        }
1128        if (pFrom.x >= pVia.x && pFrom.y < pVia.y) {
1129            if (!leftHandTraffic) {
1130                vx2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg + 180));
1131                vy2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg + 180));
1132            } else {
1133                vx2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg));
1134                vy2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg));
1135            }
1136            iconAngle = 270-fromAngleDeg;
1137        }
1138
1139        drawRestriction(icon.getImage(disabled),
1140                pVia, vx+vx2, vy+vy2, iconAngle, r.isSelected());
1141    }
1142
1143    /**
1144     * Draws a text for the given primitive
1145     * @param osm The primitive to draw the text for
1146     * @param text The text definition (font/position/.../text content) to draw
1147     * @param labelPositionStrategy The position of the text
1148     * @since 11722
1149     */
1150    public void drawText(IPrimitive osm, TextLabel text, PositionForAreaStrategy labelPositionStrategy) {
1151        if (!isShowNames()) {
1152            return;
1153        }
1154        String name = text.getString(osm);
1155        if (name == null || name.isEmpty()) {
1156            return;
1157        }
1158
1159        FontMetrics fontMetrics = g.getFontMetrics(text.font); // if slow, use cache
1160        Rectangle2D nb = fontMetrics.getStringBounds(name, g); // if slow, approximate by strlen()*maxcharbounds(font)
1161
1162        Font defaultFont = g.getFont();
1163        forEachPolygon(osm, path -> {
1164            //TODO: Ignore areas that are out of bounds.
1165            PositionForAreaStrategy position = labelPositionStrategy;
1166            MapViewPositionAndRotation center = position.findLabelPlacement(path, nb);
1167            if (center != null) {
1168                displayText(osm, text, name, nb, center);
1169            } else if (position.supportsGlyphVector()) {
1170                List<GlyphVector> gvs = Utils.getGlyphVectorsBidi(name, text.font, g.getFontRenderContext());
1171
1172                List<GlyphVector> translatedGvs = position.generateGlyphVectors(path, nb, gvs, isGlyphVectorDoubleTranslationBug(text.font));
1173                displayText(() -> translatedGvs.forEach(gv -> g.drawGlyphVector(gv, 0, 0)),
1174                        () -> translatedGvs.stream().collect(
1175                                Path2D.Double::new,
1176                                (p, gv) -> p.append(gv.getOutline(0, 0), false),
1177                                (p1, p2) -> p1.append(p2, false)),
1178                        osm.isDisabled(), text);
1179            } else {
1180                Logging.trace("Couldn't find a correct label placement for {0} / {1}", osm, name);
1181            }
1182        });
1183        g.setFont(defaultFont);
1184    }
1185
1186    private void displayText(IPrimitive osm, TextLabel text, String name, Rectangle2D nb,
1187            MapViewPositionAndRotation center) {
1188        AffineTransform at = new AffineTransform();
1189        if (Math.abs(center.getRotation()) < .01) {
1190            // Explicitly no rotation: move to full pixels.
1191            at.setToTranslation(Math.round(center.getPoint().getInViewX() - nb.getCenterX()),
1192                    Math.round(center.getPoint().getInViewY() - nb.getCenterY()));
1193        } else {
1194            at.setToTranslation(center.getPoint().getInViewX(), center.getPoint().getInViewY());
1195            at.rotate(center.getRotation());
1196            at.translate(-nb.getCenterX(), -nb.getCenterY());
1197        }
1198        displayText(() -> {
1199            AffineTransform defaultTransform = g.getTransform();
1200            g.transform(at);
1201            g.setFont(text.font);
1202            g.drawString(name, 0, 0);
1203            g.setTransform(defaultTransform);
1204        }, () -> {
1205            FontRenderContext frc = g.getFontRenderContext();
1206            TextLayout tl = new TextLayout(name, text.font, frc);
1207            return tl.getOutline(at);
1208        }, osm.isDisabled(), text);
1209    }
1210
1211    /**
1212     * Displays text at specified position including its halo, if applicable.
1213     *
1214     * @param fill The function that fills the text
1215     * @param outline The function to draw the outline
1216     * @param disabled {@code true} if element is disabled (filtered out)
1217     * @param text text style to use
1218     */
1219    private void displayText(Runnable fill, Supplier<Shape> outline, boolean disabled, TextLabel text) {
1220        if (isInactiveMode || disabled) {
1221            g.setColor(inactiveColor);
1222            fill.run();
1223        } else if (text.haloRadius != null) {
1224            g.setStroke(new BasicStroke(2*text.haloRadius, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
1225            g.setColor(text.haloColor);
1226            Shape textOutline = outline.get();
1227            g.draw(textOutline);
1228            g.setStroke(new BasicStroke());
1229            g.setColor(text.color);
1230            g.fill(textOutline);
1231        } else {
1232            g.setColor(text.color);
1233            fill.run();
1234        }
1235    }
1236
1237    /**
1238     * Calls a consumer for each path of the area shape-
1239     * @param osm A way or a multipolygon
1240     * @param consumer The consumer to call.
1241     */
1242    private void forEachPolygon(IPrimitive osm, Consumer<MapViewPath> consumer) {
1243        if (osm instanceof IWay) {
1244            consumer.accept(getPath((IWay<?>) osm));
1245        } else if (osm instanceof Relation) {
1246            Multipolygon multipolygon = MultipolygonCache.getInstance().get((Relation) osm);
1247            if (!multipolygon.getOuterWays().isEmpty()) {
1248                for (PolyData pd : multipolygon.getCombinedPolygons()) {
1249                    MapViewPath path = new MapViewPath(mapState);
1250                    path.appendFromEastNorth(pd.get());
1251                    path.setWindingRule(MapViewPath.WIND_EVEN_ODD);
1252                    consumer.accept(path);
1253                }
1254            }
1255        }
1256    }
1257
1258    /**
1259     * draw way. This method allows for two draw styles (line using color, dashes using dashedColor) to be passed.
1260     * @param way The way to draw
1261     * @param color The base color to draw the way in
1262     * @param line The line style to use. This is drawn using color.
1263     * @param dashes The dash style to use. This is drawn using dashedColor. <code>null</code> if unused.
1264     * @param dashedColor The color of the dashes.
1265     * @param offset The offset
1266     * @param showOrientation show arrows that indicate the technical orientation of
1267     *              the way (defined by order of nodes)
1268     * @param showHeadArrowOnly True if only the arrow at the end of the line but not those on the segments should be displayed.
1269     * @param showOneway show symbols that indicate the direction of the feature,
1270     *              e.g. oneway street or waterway
1271     * @param onewayReversed for oneway=-1 and similar
1272     */
1273    public void drawWay(IWay<?> way, Color color, BasicStroke line, BasicStroke dashes, Color dashedColor, float offset,
1274            boolean showOrientation, boolean showHeadArrowOnly,
1275            boolean showOneway, boolean onewayReversed) {
1276
1277        MapViewPath path = new MapViewPath(mapState);
1278        MapViewPath orientationArrows = showOrientation ? new MapViewPath(mapState) : null;
1279        MapViewPath onewayArrows;
1280        MapViewPath onewayArrowsCasing;
1281        Rectangle bounds = g.getClipBounds();
1282        if (bounds != null) {
1283            // avoid arrow heads at the border
1284            bounds.grow(100, 100);
1285        }
1286
1287        List<? extends INode> wayNodes = way.getNodes();
1288        if (wayNodes.size() < 2) return;
1289
1290        // only highlight the segment if the way itself is not highlighted
1291        if (!way.isHighlighted() && highlightWaySegments != null) {
1292            MapViewPath highlightSegs = null;
1293            for (WaySegment ws : highlightWaySegments) {
1294                if (ws.way != way || ws.lowerIndex < offset) {
1295                    continue;
1296                }
1297                if (highlightSegs == null) {
1298                    highlightSegs = new MapViewPath(mapState);
1299                }
1300
1301                highlightSegs.moveTo(ws.getFirstNode());
1302                highlightSegs.lineTo(ws.getSecondNode());
1303            }
1304
1305            drawPathHighlight(highlightSegs, line);
1306        }
1307
1308        MapViewPoint lastPoint = null;
1309        Iterator<MapViewPoint> it = new OffsetIterator(mapState, wayNodes, offset);
1310        boolean initialMoveToNeeded = true;
1311        ArrowPaintHelper drawArrowHelper = null;
1312        if (showOrientation) {
1313            drawArrowHelper = new ArrowPaintHelper(PHI, 10 + line.getLineWidth());
1314        }
1315        while (it.hasNext()) {
1316            MapViewPoint p = it.next();
1317            if (lastPoint != null) {
1318                MapViewPoint p1 = lastPoint;
1319                MapViewPoint p2 = p;
1320
1321                if (initialMoveToNeeded) {
1322                    initialMoveToNeeded = false;
1323                    path.moveTo(p1);
1324                }
1325                path.lineTo(p2);
1326
1327                /* draw arrow */
1328                if (drawArrowHelper != null) {
1329                    boolean drawArrow;
1330                    // always draw last arrow - no matter how short the segment is
1331                    drawArrow = !it.hasNext();
1332                    if (!showHeadArrowOnly) {
1333                        // draw arrows in between only if there is enough space
1334                        drawArrow = drawArrow || p1.distanceToInView(p2) > drawArrowHelper.getOnLineLength() * 1.3;
1335                    }
1336                    if (drawArrow) {
1337                        drawArrowHelper.paintArrowAt(orientationArrows, p2, p1);
1338                    }
1339                }
1340            }
1341            lastPoint = p;
1342        }
1343        if (showOneway) {
1344            onewayArrows = new MapViewPath(mapState);
1345            onewayArrowsCasing = new MapViewPath(mapState);
1346            double interval = 60;
1347
1348            path.visitClippedLine(60, (inLineOffset, start, end, startIsOldEnd) -> {
1349                double segmentLength = start.distanceToInView(end);
1350                if (segmentLength > 0.001) {
1351                    final double nx = (end.getInViewX() - start.getInViewX()) / segmentLength;
1352                    final double ny = (end.getInViewY() - start.getInViewY()) / segmentLength;
1353
1354                    // distance from p1
1355                    double dist = interval - (inLineOffset % interval);
1356
1357                    while (dist < segmentLength) {
1358                        appendOnewayPath(onewayReversed, start, nx, ny, dist, 3d, onewayArrowsCasing);
1359                        appendOnewayPath(onewayReversed, start, nx, ny, dist, 2d, onewayArrows);
1360                        dist += interval;
1361                    }
1362                }
1363            });
1364        } else {
1365            onewayArrows = null;
1366            onewayArrowsCasing = null;
1367        }
1368
1369        if (way.isHighlighted()) {
1370            drawPathHighlight(path, line);
1371        }
1372        displaySegments(path, orientationArrows, onewayArrows, onewayArrowsCasing, color, line, dashes, dashedColor);
1373    }
1374
1375    private static void appendOnewayPath(boolean onewayReversed, MapViewPoint p1, double nx, double ny, double dist,
1376            double onewaySize, Path2D onewayPath) {
1377        // scale such that border is 1 px
1378        final double fac = -(onewayReversed ? -1 : 1) * onewaySize * (1 + sinPHI) / (sinPHI * cosPHI);
1379        final double sx = nx * fac;
1380        final double sy = ny * fac;
1381
1382        // Attach the triangle at the incenter and not at the tip.
1383        // Makes the border even at all sides.
1384        final double x = p1.getInViewX() + nx * (dist + (onewayReversed ? -1 : 1) * (onewaySize / sinPHI));
1385        final double y = p1.getInViewY() + ny * (dist + (onewayReversed ? -1 : 1) * (onewaySize / sinPHI));
1386
1387        onewayPath.moveTo(x, y);
1388        onewayPath.lineTo(x + cosPHI * sx - sinPHI * sy, y + sinPHI * sx + cosPHI * sy);
1389        onewayPath.lineTo(x + cosPHI * sx + sinPHI * sy, y - sinPHI * sx + cosPHI * sy);
1390        onewayPath.lineTo(x, y);
1391    }
1392
1393    /**
1394     * Gets the "circum". This is the distance on the map in meters that 100 screen pixels represent.
1395     * @return The "circum"
1396     */
1397    public double getCircum() {
1398        return circum;
1399    }
1400
1401    @Override
1402    public void getColors() {
1403        super.getColors();
1404        this.highlightColorTransparent = new Color(highlightColor.getRed(), highlightColor.getGreen(), highlightColor.getBlue(), 100);
1405        this.backgroundColor = styles.getBackgroundColor();
1406    }
1407
1408    @Override
1409    public void getSettings(boolean virtual) {
1410        super.getSettings(virtual);
1411        paintSettings = MapPaintSettings.INSTANCE;
1412
1413        circum = nc.getDist100Pixel();
1414        scale = nc.getScale();
1415
1416        leftHandTraffic = PREFERENCE_LEFT_HAND_TRAFFIC.get();
1417
1418        useStrokes = paintSettings.getUseStrokesDistance() > circum;
1419        showNames = paintSettings.getShowNamesDistance() > circum;
1420        showIcons = paintSettings.getShowIconsDistance() > circum;
1421        isOutlineOnly = paintSettings.isOutlineOnly();
1422
1423        antialiasing = PREFERENCE_ANTIALIASING_USE.get() ?
1424                        RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF;
1425        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialiasing);
1426
1427        Object textAntialiasing;
1428        switch (PREFERENCE_TEXT_ANTIALIASING.get()) {
1429            case "on":
1430                textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
1431                break;
1432            case "off":
1433                textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
1434                break;
1435            case "gasp":
1436                textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_GASP;
1437                break;
1438            case "lcd-hrgb":
1439                textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB;
1440                break;
1441            case "lcd-hbgr":
1442                textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR;
1443                break;
1444            case "lcd-vrgb":
1445                textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB;
1446                break;
1447            case "lcd-vbgr":
1448                textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR;
1449                break;
1450            default:
1451                textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT;
1452        }
1453        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textAntialiasing);
1454    }
1455
1456    private MapViewPath getPath(IWay<?> w) {
1457        MapViewPath path = new MapViewPath(mapState);
1458        if (w.isClosed()) {
1459            path.appendClosed(w.getNodes(), false);
1460        } else {
1461            path.append(w.getNodes(), false);
1462        }
1463        return path;
1464    }
1465
1466    private static Path2D.Double getPFClip(IWay<?> w, double extent) {
1467        Path2D.Double clip = new Path2D.Double();
1468        buildPFClip(clip, w.getNodes(), extent);
1469        return clip;
1470    }
1471
1472    private static Path2D.Double getPFClip(PolyData pd, double extent) {
1473        Path2D.Double clip = new Path2D.Double();
1474        clip.setWindingRule(Path2D.WIND_EVEN_ODD);
1475        buildPFClip(clip, pd.getNodes(), extent);
1476        for (PolyData pdInner : pd.getInners()) {
1477            buildPFClip(clip, pdInner.getNodes(), extent);
1478        }
1479        return clip;
1480    }
1481
1482    /**
1483     * Fix the clipping area of unclosed polygons for partial fill.
1484     *
1485     * The current algorithm for partial fill simply strokes the polygon with a
1486     * large stroke width after masking the outside with a clipping area.
1487     * This works, but for unclosed polygons, the mask can crop the corners at
1488     * both ends (see #12104).
1489     *
1490     * This method fixes the clipping area by sort of adding the corners to the
1491     * clip outline.
1492     *
1493     * @param clip the clipping area to modify (initially empty)
1494     * @param nodes nodes of the polygon
1495     * @param extent the extent
1496     */
1497    private static void buildPFClip(Path2D.Double clip, List<? extends INode> nodes, double extent) {
1498        boolean initial = true;
1499        for (INode n : nodes) {
1500            EastNorth p = n.getEastNorth();
1501            if (p != null) {
1502                if (initial) {
1503                    clip.moveTo(p.getX(), p.getY());
1504                    initial = false;
1505                } else {
1506                    clip.lineTo(p.getX(), p.getY());
1507                }
1508            }
1509        }
1510        if (nodes.size() >= 3) {
1511            EastNorth fst = nodes.get(0).getEastNorth();
1512            EastNorth snd = nodes.get(1).getEastNorth();
1513            EastNorth lst = nodes.get(nodes.size() - 1).getEastNorth();
1514            EastNorth lbo = nodes.get(nodes.size() - 2).getEastNorth();
1515
1516            EastNorth cLst = getPFDisplacedEndPoint(lbo, lst, fst, extent);
1517            EastNorth cFst = getPFDisplacedEndPoint(snd, fst, cLst != null ? cLst : lst, extent);
1518            if (cLst == null && cFst != null) {
1519                cLst = getPFDisplacedEndPoint(lbo, lst, cFst, extent);
1520            }
1521            if (cLst != null) {
1522                clip.lineTo(cLst.getX(), cLst.getY());
1523            }
1524            if (cFst != null) {
1525                clip.lineTo(cFst.getX(), cFst.getY());
1526            }
1527        }
1528    }
1529
1530    /**
1531     * Get the point to add to the clipping area for partial fill of unclosed polygons.
1532     *
1533     * <code>(p1,p2)</code> is the first or last way segment and <code>p3</code> the
1534     * opposite endpoint.
1535     *
1536     * @param p1 1st point
1537     * @param p2 2nd point
1538     * @param p3 3rd point
1539     * @param extent the extent
1540     * @return a point q, such that p1,p2,q form a right angle
1541     * and the distance of q to p2 is <code>extent</code>. The point q lies on
1542     * the same side of the line p1,p2 as the point p3.
1543     * Returns null if p1,p2,p3 forms an angle greater 90 degrees. (In this case
1544     * the corner of the partial fill would not be cut off by the mask, so an
1545     * additional point is not necessary.)
1546     */
1547    private static EastNorth getPFDisplacedEndPoint(EastNorth p1, EastNorth p2, EastNorth p3, double extent) {
1548        double dx1 = p2.getX() - p1.getX();
1549        double dy1 = p2.getY() - p1.getY();
1550        double dx2 = p3.getX() - p2.getX();
1551        double dy2 = p3.getY() - p2.getY();
1552        if (dx1 * dx2 + dy1 * dy2 < 0) {
1553            double len = Math.sqrt(dx1 * dx1 + dy1 * dy1);
1554            if (len == 0) return null;
1555            double dxm = -dy1 * extent / len;
1556            double dym = dx1 * extent / len;
1557            if (dx1 * dy2 - dx2 * dy1 < 0) {
1558                dxm = -dxm;
1559                dym = -dym;
1560            }
1561            return new EastNorth(p2.getX() + dxm, p2.getY() + dym);
1562        }
1563        return null;
1564    }
1565
1566    /**
1567     * Test if the area is visible
1568     * @param area The area, interpreted in east/north space.
1569     * @return true if it is visible.
1570     */
1571    private boolean isAreaVisible(Path2D.Double area) {
1572        Rectangle2D bounds = area.getBounds2D();
1573        if (bounds.isEmpty()) return false;
1574        MapViewPoint p = mapState.getPointFor(new EastNorth(bounds.getX(), bounds.getY()));
1575        if (p.getInViewY() < 0 || p.getInViewX() > mapState.getViewWidth()) return false;
1576        p = mapState.getPointFor(new EastNorth(bounds.getX() + bounds.getWidth(), bounds.getY() + bounds.getHeight()));
1577        return p.getInViewX() >= 0 && p.getInViewY() <= mapState.getViewHeight();
1578    }
1579
1580    /**
1581     * Determines if the paint visitor shall render OSM objects such that they look inactive.
1582     * @return {@code true} if the paint visitor shall render OSM objects such that they look inactive
1583     */
1584    public boolean isInactiveMode() {
1585        return isInactiveMode;
1586    }
1587
1588    /**
1589     * Check if icons should be rendered
1590     * @return <code>true</code> to display icons
1591     */
1592    public boolean isShowIcons() {
1593        return showIcons;
1594    }
1595
1596    /**
1597     * Test if names should be rendered
1598     * @return <code>true</code> to display names
1599     */
1600    public boolean isShowNames() {
1601        return showNames && doSlowOperations;
1602    }
1603
1604    /**
1605     * Computes the flags for a given OSM primitive.
1606     * @param primitive The primititve to compute the flags for.
1607     * @param checkOuterMember <code>true</code> if we should also add {@link #FLAG_OUTERMEMBER_OF_SELECTED}
1608     * @return The flag.
1609     * @since 13676 (signature)
1610     */
1611    public static int computeFlags(IPrimitive primitive, boolean checkOuterMember) {
1612        if (primitive.isDisabled()) {
1613            return FLAG_DISABLED;
1614        } else if (primitive.isSelected()) {
1615            return FLAG_SELECTED;
1616        } else if (checkOuterMember && primitive.isOuterMemberOfSelected()) {
1617            return FLAG_OUTERMEMBER_OF_SELECTED;
1618        } else if (primitive.isMemberOfSelected()) {
1619            return FLAG_MEMBER_OF_SELECTED;
1620        } else {
1621            return FLAG_NORMAL;
1622        }
1623    }
1624
1625    /**
1626     * Sets the factory that creates the benchmark data receivers.
1627     * @param benchmarkFactory The factory.
1628     * @since 10697
1629     */
1630    public void setBenchmarkFactory(Supplier<RenderBenchmarkCollector> benchmarkFactory) {
1631        this.benchmarkFactory = benchmarkFactory;
1632    }
1633
1634    @Override
1635    public void render(final OsmData<?, ?, ?, ?> data, boolean renderVirtualNodes, Bounds bounds) {
1636        RenderBenchmarkCollector benchmark = benchmarkFactory.get();
1637        BBox bbox = bounds.toBBox();
1638        getSettings(renderVirtualNodes);
1639
1640        try {
1641            if (data.getReadLock().tryLock(1, TimeUnit.SECONDS)) {
1642                try {
1643                    paintWithLock(data, renderVirtualNodes, benchmark, bbox);
1644                } finally {
1645                    data.getReadLock().unlock();
1646                }
1647            } else {
1648                Logging.warn("Cannot paint layer {0}: It is locked.");
1649            }
1650        } catch (InterruptedException e) {
1651            Logging.warn("Cannot paint layer {0}: Interrupted");
1652        }
1653    }
1654
1655    private void paintWithLock(final OsmData<?, ?, ?, ?> data, boolean renderVirtualNodes, RenderBenchmarkCollector benchmark,
1656            BBox bbox) {
1657        try {
1658            highlightWaySegments = data.getHighlightedWaySegments();
1659
1660            benchmark.renderStart(circum);
1661
1662            List<? extends INode> nodes = data.searchNodes(bbox);
1663            List<? extends IWay<?>> ways = data.searchWays(bbox);
1664            List<? extends IRelation<?>> relations = data.searchRelations(bbox);
1665
1666            final List<StyleRecord> allStyleElems = new ArrayList<>(nodes.size()+ways.size()+relations.size());
1667
1668            // Need to process all relations first.
1669            // Reason: Make sure, ElemStyles.getStyleCacheWithRange is not called for the same primitive in parallel threads.
1670            // (Could be synchronized, but try to avoid this for performance reasons.)
1671            if (THREAD_POOL != null) {
1672                THREAD_POOL.invoke(new ComputeStyleListWorker(circum, nc, relations, allStyleElems,
1673                        Math.max(20, relations.size() / THREAD_POOL.getParallelism() / 3), styles));
1674                THREAD_POOL.invoke(new ComputeStyleListWorker(circum, nc, new CompositeList<>(nodes, ways), allStyleElems,
1675                        Math.max(100, (nodes.size() + ways.size()) / THREAD_POOL.getParallelism() / 3), styles));
1676            } else {
1677                new ComputeStyleListWorker(circum, nc, relations, allStyleElems, 0, styles).computeDirectly();
1678                new ComputeStyleListWorker(circum, nc, new CompositeList<>(nodes, ways), allStyleElems, 0, styles).computeDirectly();
1679            }
1680
1681            if (!benchmark.renderSort()) {
1682                return;
1683            }
1684
1685            // We use parallel sort here. This is only available for arrays.
1686            StyleRecord[] sorted = allStyleElems.toArray(new StyleRecord[0]);
1687            Arrays.parallelSort(sorted, null);
1688
1689            if (!benchmark.renderDraw(allStyleElems)) {
1690                return;
1691            }
1692
1693            for (StyleRecord record : sorted) {
1694                paintRecord(record);
1695            }
1696
1697            drawVirtualNodes(data, bbox);
1698
1699            benchmark.renderDone();
1700        } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
1701            throw BugReport.intercept(e)
1702                    .put("data", data)
1703                    .put("circum", circum)
1704                    .put("scale", scale)
1705                    .put("paintSettings", paintSettings)
1706                    .put("renderVirtualNodes", renderVirtualNodes);
1707        }
1708    }
1709
1710    private void paintRecord(StyleRecord record) {
1711        try {
1712            record.paintPrimitive(paintSettings, this);
1713        } catch (RuntimeException e) {
1714            throw BugReport.intercept(e).put("record", record);
1715        }
1716    }
1717}