source: josm/trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/StyledMapRenderer.java@ 17012

Last change on this file since 17012 was 17012, checked in by simon04, 4 years ago

fix #19705 - StyledMapRenderer.drawIcon: bicubic interpolation

Reference: former ImageProvider.createRotatedImage

  • Property svn:eol-style set to native
File size: 69.1 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.osm.visitor.paint;
3
4import java.awt.AlphaComposite;
5import java.awt.BasicStroke;
6import java.awt.Color;
7import java.awt.Component;
8import java.awt.Composite;
9import java.awt.Font;
10import java.awt.FontMetrics;
11import java.awt.Graphics2D;
12import java.awt.Image;
13import java.awt.Point;
14import java.awt.Rectangle;
15import java.awt.RenderingHints;
16import java.awt.Shape;
17import java.awt.TexturePaint;
18import java.awt.font.FontRenderContext;
19import java.awt.font.GlyphVector;
20import java.awt.font.LineMetrics;
21import java.awt.font.TextLayout;
22import java.awt.geom.AffineTransform;
23import java.awt.geom.Path2D;
24import java.awt.geom.Point2D;
25import java.awt.geom.Rectangle2D;
26import java.awt.geom.RoundRectangle2D;
27import java.awt.image.BufferedImage;
28import java.util.ArrayList;
29import java.util.Arrays;
30import java.util.Collection;
31import java.util.HashMap;
32import java.util.Iterator;
33import java.util.List;
34import java.util.Map;
35import java.util.Objects;
36import java.util.Optional;
37import java.util.concurrent.ForkJoinPool;
38import java.util.concurrent.TimeUnit;
39import java.util.function.BiConsumer;
40import java.util.function.Consumer;
41import java.util.function.Supplier;
42
43import javax.swing.AbstractButton;
44import javax.swing.FocusManager;
45
46import org.openstreetmap.josm.data.Bounds;
47import org.openstreetmap.josm.data.coor.EastNorth;
48import org.openstreetmap.josm.data.osm.BBox;
49import org.openstreetmap.josm.data.osm.INode;
50import org.openstreetmap.josm.data.osm.IPrimitive;
51import org.openstreetmap.josm.data.osm.IRelation;
52import org.openstreetmap.josm.data.osm.IRelationMember;
53import org.openstreetmap.josm.data.osm.IWay;
54import org.openstreetmap.josm.data.osm.OsmData;
55import org.openstreetmap.josm.data.osm.OsmPrimitive;
56import org.openstreetmap.josm.data.osm.OsmUtils;
57import org.openstreetmap.josm.data.osm.Relation;
58import org.openstreetmap.josm.data.osm.WaySegment;
59import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon;
60import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.PolyData;
61import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
62import org.openstreetmap.josm.data.preferences.AbstractProperty;
63import org.openstreetmap.josm.data.preferences.BooleanProperty;
64import org.openstreetmap.josm.data.preferences.IntegerProperty;
65import org.openstreetmap.josm.data.preferences.StringProperty;
66import org.openstreetmap.josm.gui.MapViewState.MapViewPoint;
67import org.openstreetmap.josm.gui.NavigatableComponent;
68import org.openstreetmap.josm.gui.draw.MapViewPath;
69import org.openstreetmap.josm.gui.draw.MapViewPositionAndRotation;
70import org.openstreetmap.josm.gui.mappaint.ElemStyles;
71import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
72import org.openstreetmap.josm.gui.mappaint.styleelement.BoxTextElement;
73import org.openstreetmap.josm.gui.mappaint.styleelement.BoxTextElement.HorizontalTextAlignment;
74import org.openstreetmap.josm.gui.mappaint.styleelement.BoxTextElement.VerticalTextAlignment;
75import org.openstreetmap.josm.gui.mappaint.styleelement.DefaultStyles;
76import org.openstreetmap.josm.gui.mappaint.styleelement.MapImage;
77import org.openstreetmap.josm.gui.mappaint.styleelement.RepeatImageElement.LineImageAlignment;
78import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement;
79import org.openstreetmap.josm.gui.mappaint.styleelement.Symbol;
80import org.openstreetmap.josm.gui.mappaint.styleelement.TextLabel;
81import org.openstreetmap.josm.gui.mappaint.styleelement.placement.PositionForAreaStrategy;
82import org.openstreetmap.josm.spi.preferences.Config;
83import org.openstreetmap.josm.tools.CompositeList;
84import org.openstreetmap.josm.tools.Geometry;
85import org.openstreetmap.josm.tools.Geometry.AreaAndPerimeter;
86import org.openstreetmap.josm.tools.HiDPISupport;
87import org.openstreetmap.josm.tools.JosmRuntimeException;
88import org.openstreetmap.josm.tools.Logging;
89import org.openstreetmap.josm.tools.RotationAngle;
90import org.openstreetmap.josm.tools.ShapeClipper;
91import org.openstreetmap.josm.tools.Utils;
92import org.openstreetmap.josm.tools.bugreport.BugReport;
93
94/**
95 * A map renderer which renders a map according to style rules in a set of style sheets.
96 * @since 486
97 */
98public class StyledMapRenderer extends AbstractMapRenderer {
99
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 final 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 area 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 area, Color color,
440 MapImage fillImage, Float extent, MapViewPath pfClip, boolean disabled) {
441 if (!isOutlineOnly && color.getAlpha() != 0) {
442 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
443 if (fillImage == null) {
444 if (isInactiveMode) {
445 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.33f));
446 }
447 g.setColor(color);
448 computeFill(area, extent, pfClip, 4);
449 } else {
450 // TexturePaint requires BufferedImage -> get base image from possible multi-resolution image
451 Image img = HiDPISupport.getBaseImage(fillImage.getImage(disabled));
452 if (img != null) {
453 g.setPaint(new TexturePaint((BufferedImage) img,
454 new Rectangle(0, 0, fillImage.getWidth(), fillImage.getHeight())));
455 } else {
456 Logging.warn("Unable to get image from " + fillImage);
457 }
458 float alpha = fillImage.getAlphaFloat();
459 if (!Utils.equalsEpsilon(alpha, 1f)) {
460 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
461 }
462 computeFill(area, extent, pfClip, 10);
463 g.setPaintMode();
464 }
465 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialiasing);
466 }
467 }
468
469 /**
470 * Fill the given shape. If partial fill is used, computes the clipping.
471 * @param shape the given shape
472 * @param extent if not null, area will be filled partially; specifies, how
473 * far to fill from the boundary towards the center of the area;
474 * if null, area will be filled completely
475 * @param pfClip clipping area for partial fill (only needed for unclosed
476 * polygons)
477 * @param mitterLimit parameter for BasicStroke
478 *
479 */
480 private void computeFill(Shape shape, Float extent, MapViewPath pfClip, float mitterLimit) {
481 if (extent == null) {
482 g.fill(shape);
483 } else {
484 Shape oldClip = g.getClip();
485 Shape clip = shape;
486 if (pfClip != null) {
487 clip = pfClip;
488 }
489 g.clip(clip);
490 g.setStroke(new BasicStroke(2 * extent, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, mitterLimit));
491 g.draw(shape);
492 g.setClip(oldClip);
493 g.setStroke(new BasicStroke());
494 }
495 }
496
497 /**
498 * Draws a multipolygon area.
499 * @param r The multipolygon relation
500 * @param color The color to fill the area with.
501 * @param fillImage The image to fill the area with. Overrides color.
502 * @param extent if not null, area will be filled partially; specifies, how
503 * far to fill from the boundary towards the center of the area;
504 * if null, area will be filled completely
505 * @param extentThreshold if not null, determines if the partial filled should
506 * be replaced by plain fill, when it covers a certain fraction of the total area
507 * @param disabled If this should be drawn with a special disabled style.
508 * @since 12285
509 */
510 public void drawArea(Relation r, Color color, MapImage fillImage, Float extent, Float extentThreshold, boolean disabled) {
511 Multipolygon multipolygon = MultipolygonCache.getInstance().get(r);
512 if (!r.isDisabled() && !multipolygon.getOuterWays().isEmpty()) {
513 for (PolyData pd : multipolygon.getCombinedPolygons()) {
514 if (!isAreaVisible(pd.get())) {
515 continue;
516 }
517 MapViewPath p = shapeEastNorthToMapView(pd.get());
518 MapViewPath pfClip = null;
519 if (extent != null) {
520 if (!usePartialFill(pd.getAreaAndPerimeter(null), extent, extentThreshold)) {
521 extent = null;
522 } else if (!pd.isClosed()) {
523 pfClip = shapeEastNorthToMapView(getPFClip(pd, extent * scale));
524 }
525 }
526 drawArea(p,
527 pd.isSelected() ? paintSettings.getRelationSelectedColor(color.getAlpha()) : color,
528 fillImage, extent, pfClip, disabled);
529 }
530 }
531 }
532
533 /**
534 * Convert shape in EastNorth coordinates to MapViewPath and remove invisible parts.
535 * For complex shapes this improves performance drastically because the methods in Graphics2D.clip() and Graphics2D.draw() are rather slow.
536 * @param shape the shape to convert
537 * @return the converted shape
538 */
539 private MapViewPath shapeEastNorthToMapView(Path2D.Double shape) {
540 MapViewPath convertedShape = null;
541 if (shape != null) {
542 convertedShape = new MapViewPath(mapState);
543 convertedShape.appendFromEastNorth(shape);
544 convertedShape.setWindingRule(Path2D.WIND_EVEN_ODD);
545
546 Rectangle2D extViewBBox = mapState.getViewClipRectangle().getInView();
547 if (!extViewBBox.contains(convertedShape.getBounds2D())) {
548 // remove invisible parts of shape
549 Path2D.Double clipped = ShapeClipper.clipShape(convertedShape, extViewBBox);
550 if (clipped != null) {
551 convertedShape.reset();
552 convertedShape.append(clipped, false);
553 }
554 }
555 }
556 return convertedShape;
557 }
558
559 /**
560 * Draws an area defined by a way. They way does not need to be closed, but it should.
561 * @param w The way.
562 * @param color The color to fill the area with.
563 * @param fillImage The image to fill the area with. Overrides color.
564 * @param extent if not null, area will be filled partially; specifies, how
565 * far to fill from the boundary towards the center of the area;
566 * if null, area will be filled completely
567 * @param extentThreshold if not null, determines if the partial filled should
568 * be replaced by plain fill, when it covers a certain fraction of the total area
569 * @param disabled If this should be drawn with a special disabled style.
570 * @since 12285
571 */
572 public void drawArea(IWay<?> w, Color color, MapImage fillImage, Float extent, Float extentThreshold, boolean disabled) {
573 MapViewPath pfClip = null;
574 if (extent != null) {
575 if (!usePartialFill(Geometry.getAreaAndPerimeter(w.getNodes()), extent, extentThreshold)) {
576 extent = null;
577 } else if (!w.isClosed()) {
578 pfClip = shapeEastNorthToMapView(getPFClip(w, extent * scale));
579 }
580 }
581 drawArea(getPath(w), color, fillImage, extent, pfClip, disabled);
582 }
583
584 /**
585 * Determine, if partial fill should be turned off for this object, because
586 * only a small unfilled gap in the center of the area would be left.
587 *
588 * This is used to get a cleaner look for urban regions with many small
589 * areas like buildings, etc.
590 * @param ap the area and the perimeter of the object
591 * @param extent the "width" of partial fill
592 * @param threshold when the partial fill covers that much of the total
593 * area, the partial fill is turned off; can be greater than 100% as the
594 * covered area is estimated as <code>perimeter * extent</code>
595 * @return true, if the partial fill should be used, false otherwise
596 */
597 private boolean usePartialFill(AreaAndPerimeter ap, float extent, Float threshold) {
598 if (threshold == null) return true;
599 return ap.getPerimeter() * extent * scale < threshold * ap.getArea();
600 }
601
602 /**
603 * Draw a text onto a node
604 * @param n The node to draw the text on
605 * @param bs The text and it's alignment.
606 */
607 public void drawBoxText(INode n, BoxTextElement bs) {
608 if (!isShowNames() || bs == null)
609 return;
610
611 MapViewPoint p = mapState.getPointFor(n);
612 TextLabel text = bs.text;
613 String s = text.labelCompositionStrategy.compose(n);
614 if (s == null || s.isEmpty()) return;
615
616 Font defaultFont = g.getFont();
617 g.setFont(text.font);
618
619 FontRenderContext frc = g.getFontRenderContext();
620 Rectangle2D bounds = text.font.getStringBounds(s, frc);
621
622 double x = p.getInViewX() + bs.xOffset;
623 double y = p.getInViewY() + bs.yOffset;
624 /**
625 *
626 * left-above __center-above___ right-above
627 * left-top| |right-top
628 * | |
629 * left-center| center-center |right-center
630 * | |
631 * left-bottom|_________________|right-bottom
632 * left-below center-below right-below
633 *
634 */
635 Rectangle box = bs.getBox();
636 if (bs.hAlign == HorizontalTextAlignment.RIGHT) {
637 x += box.x + box.width + 2;
638 } else {
639 int textWidth = (int) bounds.getWidth();
640 if (bs.hAlign == HorizontalTextAlignment.CENTER) {
641 x -= textWidth / 2d;
642 } else if (bs.hAlign == HorizontalTextAlignment.LEFT) {
643 x -= -box.x + 4 + textWidth;
644 } else throw new AssertionError();
645 }
646
647 if (bs.vAlign == VerticalTextAlignment.BOTTOM) {
648 y += box.y + box.height;
649 } else {
650 LineMetrics metrics = text.font.getLineMetrics(s, frc);
651 if (bs.vAlign == VerticalTextAlignment.ABOVE) {
652 y -= -box.y + (int) metrics.getDescent();
653 } else if (bs.vAlign == VerticalTextAlignment.TOP) {
654 y -= -box.y - (int) metrics.getAscent();
655 } else if (bs.vAlign == VerticalTextAlignment.CENTER) {
656 y += (int) ((metrics.getAscent() - metrics.getDescent()) / 2);
657 } else if (bs.vAlign == VerticalTextAlignment.BELOW) {
658 y += box.y + box.height + (int) metrics.getAscent() + 2;
659 } else throw new AssertionError();
660 }
661
662 final MapViewPoint viewPoint = mapState.getForView(x, y);
663 final AffineTransform at = new AffineTransform();
664 at.setToTranslation(
665 Math.round(viewPoint.getInViewX()),
666 Math.round(viewPoint.getInViewY()));
667 if (!RotationAngle.NO_ROTATION.equals(text.rotationAngle)) {
668 at.rotate(text.rotationAngle.getRotationAngle(n));
669 }
670 displayText(n, text, s, at);
671 g.setFont(defaultFont);
672 }
673
674 /**
675 * Draw an image along a way repeatedly.
676 *
677 * @param way the way
678 * @param pattern the image
679 * @param disabled If this should be drawn with a special disabled style.
680 * @param offset offset from the way
681 * @param spacing spacing between two images
682 * @param phase initial spacing
683 * @param opacity the opacity
684 * @param align alignment of the image. The top, center or bottom edge can be aligned with the way.
685 */
686 public void drawRepeatImage(IWay<?> way, MapImage pattern, boolean disabled, double offset, double spacing, double phase,
687 float opacity, LineImageAlignment align) {
688 final int imgWidth = pattern.getWidth();
689 final double repeat = imgWidth + spacing;
690 final int imgHeight = pattern.getHeight();
691
692 int dy1 = (int) ((align.getAlignmentOffset() - .5) * imgHeight);
693 int dy2 = dy1 + imgHeight;
694
695 OffsetIterator it = new OffsetIterator(mapState, way.getNodes(), offset);
696 MapViewPath path = new MapViewPath(mapState);
697 if (it.hasNext()) {
698 path.moveTo(it.next());
699 }
700 while (it.hasNext()) {
701 path.lineTo(it.next());
702 }
703
704 double startOffset = computeStartOffset(phase, repeat);
705
706 Image image = pattern.getImage(disabled);
707
708 path.visitClippedLine(repeat, (inLineOffset, start, end, startIsOldEnd) -> {
709 final double segmentLength = start.distanceToInView(end);
710 if (segmentLength < 0.1) {
711 // avoid odd patterns when zoomed out.
712 return;
713 }
714 if (segmentLength > repeat * 500) {
715 // simply skip drawing so many images - something must be wrong.
716 return;
717 }
718 AffineTransform saveTransform = g.getTransform();
719 g.translate(start.getInViewX(), start.getInViewY());
720 double dx = end.getInViewX() - start.getInViewX();
721 double dy = end.getInViewY() - start.getInViewY();
722 g.rotate(Math.atan2(dy, dx));
723
724 // The start of the next image
725 // It is shifted by startOffset.
726 double imageStart = -((inLineOffset - startOffset + repeat) % repeat);
727
728 while (imageStart < segmentLength) {
729 int x = (int) imageStart;
730 int sx1 = Math.max(0, -x);
731 int sx2 = imgWidth - Math.max(0, x + imgWidth - (int) Math.ceil(segmentLength));
732 Composite saveComposite = g.getComposite();
733 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
734 g.drawImage(image, x + sx1, dy1, x + sx2, dy2, sx1, 0, sx2, imgHeight, null);
735 g.setComposite(saveComposite);
736 imageStart += repeat;
737 }
738
739 g.setTransform(saveTransform);
740 });
741 }
742
743 private static double computeStartOffset(double phase, final double repeat) {
744 double startOffset = phase % repeat;
745 if (startOffset < 0) {
746 startOffset += repeat;
747 }
748 return startOffset;
749 }
750
751 @Override
752 public void drawNode(INode n, Color color, int size, boolean fill) {
753 if (size <= 0 && !n.isHighlighted())
754 return;
755
756 MapViewPoint p = mapState.getPointFor(n);
757
758 if (n.isHighlighted()) {
759 drawPointHighlight(p.getInView(), size);
760 }
761
762 if (size > 1 && p.isInView()) {
763 int radius = size / 2;
764
765 if (isInactiveMode || n.isDisabled()) {
766 g.setColor(inactiveColor);
767 } else {
768 g.setColor(color);
769 }
770 Rectangle2D rect = new Rectangle2D.Double(p.getInViewX()-radius-1d, p.getInViewY()-radius-1d, size + 1d, size + 1d);
771 if (fill) {
772 g.fill(rect);
773 } else {
774 g.draw(rect);
775 }
776 }
777 }
778
779 /**
780 * Draw the icon for a given node.
781 * @param n The node
782 * @param img The icon to draw at the node position
783 * @param disabled {@code} true to render disabled version, {@code false} for the standard version
784 * @param selected {@code} true to render it as selected, {@code false} otherwise
785 * @param member {@code} true to render it as a relation member, {@code false} otherwise
786 * @param theta the angle of rotation in radians
787 */
788 public void drawNodeIcon(INode n, MapImage img, boolean disabled, boolean selected, boolean member, double theta) {
789 MapViewPoint p = mapState.getPointFor(n);
790
791 int w = img.getWidth();
792 int h = img.getHeight();
793 if (n.isHighlighted()) {
794 drawPointHighlight(p.getInView(), Math.max(w, h));
795 }
796
797 drawIcon(p.getInViewX(), p.getInViewY(), img, disabled, selected, member, theta, (g, r) -> {
798 Color color = getSelectionHintColor(disabled, selected);
799 g.setColor(color);
800 g.draw(r);
801 });
802 }
803
804 /**
805 * Draw the icon for a given area. Normally, the icon is drawn around the center of the area.
806 * @param osm The primitive to draw the icon for
807 * @param img The icon to draw
808 * @param disabled {@code} true to render disabled version, {@code false} for the standard version
809 * @param selected {@code} true to render it as selected, {@code false} otherwise
810 * @param member {@code} true to render it as a relation member, {@code false} otherwise
811 * @param theta the angle of rotation in radians
812 * @param iconPosition Where to place the icon.
813 * @since 11670
814 */
815 public void drawAreaIcon(IPrimitive osm, MapImage img, boolean disabled, boolean selected, boolean member, double theta,
816 PositionForAreaStrategy iconPosition) {
817 Rectangle2D.Double iconRect = new Rectangle2D.Double(-img.getWidth() / 2.0, -img.getHeight() / 2.0, img.getWidth(), img.getHeight());
818
819 forEachPolygon(osm, path -> {
820 MapViewPositionAndRotation placement = iconPosition.findLabelPlacement(path, iconRect);
821 if (placement == null) {
822 return;
823 }
824 MapViewPoint p = placement.getPoint();
825 drawIcon(p.getInViewX(), p.getInViewY(), img, disabled, selected, member, theta + placement.getRotation(), (g, r) -> {
826 if (useStrokes) {
827 g.setStroke(new BasicStroke(2));
828 }
829 // only draw a minor highlighting, so that users do not confuse this for a point.
830 Color color = getSelectionHintColor(disabled, selected);
831 color = new Color(color.getRed(), color.getGreen(), color.getBlue(), (int) (color.getAlpha() * .2));
832 g.setColor(color);
833 g.draw(r);
834 });
835 });
836 }
837
838 private void drawIcon(final double x, final double y, MapImage img, boolean disabled, boolean selected, boolean member, double theta,
839 BiConsumer<Graphics2D, Rectangle2D> selectionDrawer) {
840 float alpha = img.getAlphaFloat();
841
842 Graphics2D temporaryGraphics = (Graphics2D) g.create();
843 if (!Utils.equalsEpsilon(alpha, 1f)) {
844 temporaryGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
845 }
846
847 temporaryGraphics.translate(Math.round(x), Math.round(y));
848 temporaryGraphics.rotate(theta);
849 int drawX = -img.getWidth() / 2 + img.offsetX;
850 int drawY = -img.getHeight() / 2 + img.offsetY;
851 temporaryGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
852 temporaryGraphics.drawImage(img.getImage(disabled), drawX, drawY, nc);
853 if (selected || member) {
854 selectionDrawer.accept(temporaryGraphics, new Rectangle2D.Double(drawX - 2d, drawY - 2d, img.getWidth() + 4d, img.getHeight() + 4d));
855 }
856 }
857
858 private Color getSelectionHintColor(boolean disabled, boolean selected) {
859 Color color;
860 if (disabled) {
861 color = inactiveColor;
862 } else if (selected) {
863 color = selectedColor;
864 } else {
865 color = relationSelectedColor;
866 }
867 return color;
868 }
869
870 /**
871 * Draw the symbol and possibly a highlight marking on a given node.
872 * @param n The position to draw the symbol on
873 * @param s The symbol to draw
874 * @param fillColor The color to fill the symbol with
875 * @param strokeColor The color to use for the outer corner of the symbol
876 */
877 public void drawNodeSymbol(INode n, Symbol s, Color fillColor, Color strokeColor) {
878 MapViewPoint p = mapState.getPointFor(n);
879
880 if (n.isHighlighted()) {
881 drawPointHighlight(p.getInView(), s.size);
882 }
883
884 if (fillColor != null || strokeColor != null) {
885 Shape shape = s.buildShapeAround(p.getInViewX(), p.getInViewY());
886
887 if (fillColor != null) {
888 g.setColor(fillColor);
889 g.fill(shape);
890 }
891 if (s.stroke != null) {
892 g.setStroke(s.stroke);
893 g.setColor(strokeColor);
894 g.draw(shape);
895 g.setStroke(new BasicStroke());
896 }
897 }
898 }
899
900 /**
901 * Draw a number of the order of the two consecutive nodes within the
902 * parents way
903 *
904 * @param n1 First node of the way segment.
905 * @param n2 Second node of the way segment.
906 * @param orderNumber The number of the segment in the way.
907 * @param clr The color to use for drawing the text.
908 */
909 public void drawOrderNumber(INode n1, INode n2, int orderNumber, Color clr) {
910 MapViewPoint p1 = mapState.getPointFor(n1);
911 MapViewPoint p2 = mapState.getPointFor(n2);
912 drawOrderNumber(p1, p2, orderNumber, clr);
913 }
914
915 /**
916 * highlights a given GeneralPath using the settings from BasicStroke to match the line's
917 * style. Width of the highlight can be changed by user preferences
918 * @param path path to draw
919 * @param line line style
920 */
921 private void drawPathHighlight(MapViewPath path, BasicStroke line) {
922 if (path == null)
923 return;
924 g.setColor(highlightColorTransparent);
925 float w = line.getLineWidth() + HIGHLIGHT_LINE_WIDTH.get();
926 if (useWiderHighlight) {
927 w += WIDER_HIGHLIGHT.get();
928 }
929 int step = Math.max(HIGHLIGHT_STEP.get(), 1);
930 while (w >= line.getLineWidth()) {
931 g.setStroke(new BasicStroke(w, line.getEndCap(), line.getLineJoin(), line.getMiterLimit()));
932 g.draw(path);
933 w -= step;
934 }
935 }
936
937 /**
938 * highlights a given point by drawing a rounded rectangle around it. Give the
939 * size of the object you want to be highlighted, width is added automatically.
940 * @param p point
941 * @param size highlight size
942 */
943 private void drawPointHighlight(Point2D p, int size) {
944 g.setColor(highlightColorTransparent);
945 int s = size + HIGHLIGHT_POINT_RADIUS.get();
946 if (useWiderHighlight) {
947 s += WIDER_HIGHLIGHT.get();
948 }
949 int step = Math.max(HIGHLIGHT_STEP.get(), 1);
950 while (s >= size) {
951 int r = (int) Math.floor(s/2d);
952 g.fill(new RoundRectangle2D.Double(p.getX()-r, p.getY()-r, s, s, r, r));
953 s -= step;
954 }
955 }
956
957 /**
958 * Draw a turn restriction
959 * @param r The turn restriction relation
960 * @param icon The icon to draw at the turn point
961 * @param disabled draw using disabled style
962 */
963 public void drawRestriction(IRelation<?> r, MapImage icon, boolean disabled) {
964 IWay<?> fromWay = null;
965 IWay<?> toWay = null;
966 IPrimitive via = null;
967
968 /* find the "from", "via" and "to" elements */
969 for (IRelationMember<?> m : r.getMembers()) {
970 if (m.getMember().isIncomplete())
971 return;
972 else {
973 if (m.isWay()) {
974 IWay<?> w = (IWay<?>) m.getMember();
975 if (w.getNodesCount() < 2) {
976 continue;
977 }
978
979 switch(m.getRole()) {
980 case "from":
981 if (fromWay == null) {
982 fromWay = w;
983 }
984 break;
985 case "to":
986 if (toWay == null) {
987 toWay = w;
988 }
989 break;
990 case "via":
991 if (via == null) {
992 via = w;
993 }
994 break;
995 default: // Do nothing
996 }
997 } else if (m.isNode()) {
998 INode n = (INode) m.getMember();
999 if (via == null && "via".equals(m.getRole())) {
1000 via = n;
1001 }
1002 }
1003 }
1004 }
1005
1006 if (fromWay == null || toWay == null || via == null)
1007 return;
1008
1009 INode viaNode;
1010 if (via instanceof INode) {
1011 viaNode = (INode) via;
1012 if (!fromWay.isFirstLastNode(viaNode))
1013 return;
1014 } else {
1015 IWay<?> viaWay = (IWay<?>) via;
1016 INode firstNode = viaWay.firstNode();
1017 INode lastNode = viaWay.lastNode();
1018 Boolean onewayvia = Boolean.FALSE;
1019
1020 String onewayviastr = viaWay.get("oneway");
1021 if (onewayviastr != null) {
1022 if ("-1".equals(onewayviastr)) {
1023 onewayvia = Boolean.TRUE;
1024 INode tmp = firstNode;
1025 firstNode = lastNode;
1026 lastNode = tmp;
1027 } else {
1028 onewayvia = Optional.ofNullable(OsmUtils.getOsmBoolean(onewayviastr)).orElse(Boolean.FALSE);
1029 }
1030 }
1031
1032 if (fromWay.isFirstLastNode(firstNode)) {
1033 viaNode = firstNode;
1034 } else if (!onewayvia && fromWay.isFirstLastNode(lastNode)) {
1035 viaNode = lastNode;
1036 } else
1037 return;
1038 }
1039
1040 /* find the "direct" nodes before the via node */
1041 INode fromNode;
1042 if (fromWay.firstNode() == via) {
1043 fromNode = fromWay.getNode(1);
1044 } else {
1045 fromNode = fromWay.getNode(fromWay.getNodesCount()-2);
1046 }
1047
1048 Point pFrom = nc.getPoint(fromNode);
1049 Point pVia = nc.getPoint(viaNode);
1050
1051 /* starting from via, go back the "from" way a few pixels
1052 (calculate the vector vx/vy with the specified length and the direction
1053 away from the "via" node along the first segment of the "from" way)
1054 */
1055 double distanceFromVia = 14;
1056 double dx = pFrom.x >= pVia.x ? pFrom.x - pVia.x : pVia.x - pFrom.x;
1057 double dy = pFrom.y >= pVia.y ? pFrom.y - pVia.y : pVia.y - pFrom.y;
1058
1059 double fromAngle;
1060 if (dx == 0) {
1061 fromAngle = Math.PI/2;
1062 } else {
1063 fromAngle = Math.atan(dy / dx);
1064 }
1065 double fromAngleDeg = Utils.toDegrees(fromAngle);
1066
1067 double vx = distanceFromVia * Math.cos(fromAngle);
1068 double vy = distanceFromVia * Math.sin(fromAngle);
1069
1070 if (pFrom.x < pVia.x) {
1071 vx = -vx;
1072 }
1073 if (pFrom.y < pVia.y) {
1074 vy = -vy;
1075 }
1076
1077 /* go a few pixels away from the way (in a right angle)
1078 (calculate the vx2/vy2 vector with the specified length and the direction
1079 90degrees away from the first segment of the "from" way)
1080 */
1081 double distanceFromWay = 10;
1082 double vx2 = 0;
1083 double vy2 = 0;
1084 double iconAngle = 0;
1085
1086 if (pFrom.x >= pVia.x && pFrom.y >= pVia.y) {
1087 if (!leftHandTraffic) {
1088 vx2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg - 90));
1089 vy2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg - 90));
1090 } else {
1091 vx2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg + 90));
1092 vy2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg + 90));
1093 }
1094 iconAngle = 270+fromAngleDeg;
1095 }
1096 if (pFrom.x < pVia.x && pFrom.y >= pVia.y) {
1097 if (!leftHandTraffic) {
1098 vx2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg));
1099 vy2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg));
1100 } else {
1101 vx2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg + 180));
1102 vy2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg + 180));
1103 }
1104 iconAngle = 90-fromAngleDeg;
1105 }
1106 if (pFrom.x < pVia.x && pFrom.y < pVia.y) {
1107 if (!leftHandTraffic) {
1108 vx2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg + 90));
1109 vy2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg + 90));
1110 } else {
1111 vx2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg - 90));
1112 vy2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg - 90));
1113 }
1114 iconAngle = 90+fromAngleDeg;
1115 }
1116 if (pFrom.x >= pVia.x && pFrom.y < pVia.y) {
1117 if (!leftHandTraffic) {
1118 vx2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg + 180));
1119 vy2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg + 180));
1120 } else {
1121 vx2 = distanceFromWay * Math.sin(Utils.toRadians(fromAngleDeg));
1122 vy2 = distanceFromWay * Math.cos(Utils.toRadians(fromAngleDeg));
1123 }
1124 iconAngle = 270-fromAngleDeg;
1125 }
1126
1127 drawIcon(
1128 pVia.x + vx + vx2,
1129 pVia.y + vy + vy2,
1130 icon, disabled, false, false, Math.toRadians(iconAngle), (graphics2D, rectangle2D) -> {
1131 });
1132 }
1133
1134 /**
1135 * Draws a text for the given primitive
1136 * @param osm The primitive to draw the text for
1137 * @param text The text definition (font/position/.../text content) to draw
1138 * @param labelPositionStrategy The position of the text
1139 * @since 11722
1140 */
1141 public void drawText(IPrimitive osm, TextLabel text, PositionForAreaStrategy labelPositionStrategy) {
1142 if (!isShowNames()) {
1143 return;
1144 }
1145 String name = text.getString(osm);
1146 if (name == null || name.isEmpty()) {
1147 return;
1148 }
1149
1150 FontMetrics fontMetrics = g.getFontMetrics(text.font); // if slow, use cache
1151 Rectangle2D nb = fontMetrics.getStringBounds(name, g); // if slow, approximate by strlen()*maxcharbounds(font)
1152
1153 Font defaultFont = g.getFont();
1154 forEachPolygon(osm, path -> {
1155 //TODO: Ignore areas that are out of bounds.
1156 PositionForAreaStrategy position = labelPositionStrategy;
1157 MapViewPositionAndRotation center = position.findLabelPlacement(path, nb);
1158 if (center != null) {
1159 displayText(osm, text, name, nb, center);
1160 } else if (position.supportsGlyphVector()) {
1161 List<GlyphVector> gvs = Utils.getGlyphVectorsBidi(name, text.font, g.getFontRenderContext());
1162
1163 List<GlyphVector> translatedGvs = position.generateGlyphVectors(path, nb, gvs, isGlyphVectorDoubleTranslationBug(text.font));
1164 displayText(() -> translatedGvs.forEach(gv -> g.drawGlyphVector(gv, 0, 0)),
1165 () -> translatedGvs.stream().collect(
1166 Path2D.Double::new,
1167 (p, gv) -> p.append(gv.getOutline(0, 0), false),
1168 (p1, p2) -> p1.append(p2, false)),
1169 osm.isDisabled(), text);
1170 } else {
1171 Logging.trace("Couldn't find a correct label placement for {0} / {1}", osm, name);
1172 }
1173 });
1174 g.setFont(defaultFont);
1175 }
1176
1177 private void displayText(IPrimitive osm, TextLabel text, String name, Rectangle2D nb,
1178 MapViewPositionAndRotation center) {
1179 AffineTransform at = new AffineTransform();
1180 if (Math.abs(center.getRotation()) < .01) {
1181 // Explicitly no rotation: move to full pixels.
1182 at.setToTranslation(
1183 Math.round(center.getPoint().getInViewX() - nb.getCenterX()),
1184 Math.round(center.getPoint().getInViewY() - nb.getCenterY()));
1185 } else {
1186 at.setToTranslation(
1187 center.getPoint().getInViewX(),
1188 center.getPoint().getInViewY());
1189 at.rotate(center.getRotation());
1190 at.translate(-nb.getCenterX(), -nb.getCenterY());
1191 }
1192 displayText(osm, text, name, at);
1193 }
1194
1195 private void displayText(IPrimitive osm, TextLabel text, String name, AffineTransform at) {
1196 displayText(() -> {
1197 AffineTransform defaultTransform = g.getTransform();
1198 g.transform(at);
1199 g.setFont(text.font);
1200 g.drawString(name, 0, 0);
1201 g.setTransform(defaultTransform);
1202 }, () -> {
1203 FontRenderContext frc = g.getFontRenderContext();
1204 TextLayout tl = new TextLayout(name, text.font, frc);
1205 return tl.getOutline(at);
1206 }, osm.isDisabled(), text);
1207 }
1208
1209 /**
1210 * Displays text at specified position including its halo, if applicable.
1211 *
1212 * @param fill The function that fills the text
1213 * @param outline The function to draw the outline
1214 * @param disabled {@code true} if element is disabled (filtered out)
1215 * @param text text style to use
1216 */
1217 private void displayText(Runnable fill, Supplier<Shape> outline, boolean disabled, TextLabel text) {
1218 if (isInactiveMode || disabled) {
1219 g.setColor(inactiveColor);
1220 fill.run();
1221 } else if (text.haloRadius != null) {
1222 g.setStroke(new BasicStroke(2*text.haloRadius, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
1223 g.setColor(text.haloColor);
1224 Shape textOutline = outline.get();
1225 g.draw(textOutline);
1226 g.setStroke(new BasicStroke());
1227 g.setColor(text.color);
1228 g.fill(textOutline);
1229 } else {
1230 g.setColor(text.color);
1231 fill.run();
1232 }
1233 }
1234
1235 /**
1236 * Calls a consumer for each path of the area shape-
1237 * @param osm A way or a multipolygon
1238 * @param consumer The consumer to call.
1239 */
1240 private void forEachPolygon(IPrimitive osm, Consumer<MapViewPath> consumer) {
1241 if (osm instanceof IWay) {
1242 consumer.accept(getPath((IWay<?>) osm));
1243 } else if (osm instanceof Relation) {
1244 Multipolygon multipolygon = MultipolygonCache.getInstance().get((Relation) osm);
1245 if (!multipolygon.getOuterWays().isEmpty()) {
1246 for (PolyData pd : multipolygon.getCombinedPolygons()) {
1247 MapViewPath path = new MapViewPath(mapState);
1248 path.appendFromEastNorth(pd.get());
1249 path.setWindingRule(MapViewPath.WIND_EVEN_ODD);
1250 consumer.accept(path);
1251 }
1252 }
1253 }
1254 }
1255
1256 /**
1257 * draw way. This method allows for two draw styles (line using color, dashes using dashedColor) to be passed.
1258 * @param way The way to draw
1259 * @param color The base color to draw the way in
1260 * @param line The line style to use. This is drawn using color.
1261 * @param dashes The dash style to use. This is drawn using dashedColor. <code>null</code> if unused.
1262 * @param dashedColor The color of the dashes.
1263 * @param offset The offset
1264 * @param showOrientation show arrows that indicate the technical orientation of
1265 * the way (defined by order of nodes)
1266 * @param showHeadArrowOnly True if only the arrow at the end of the line but not those on the segments should be displayed.
1267 * @param showOneway show symbols that indicate the direction of the feature,
1268 * e.g. oneway street or waterway
1269 * @param onewayReversed for oneway=-1 and similar
1270 */
1271 public void drawWay(IWay<?> way, Color color, BasicStroke line, BasicStroke dashes, Color dashedColor, float offset,
1272 boolean showOrientation, boolean showHeadArrowOnly,
1273 boolean showOneway, boolean onewayReversed) {
1274
1275 MapViewPath path = new MapViewPath(mapState);
1276 MapViewPath orientationArrows = showOrientation ? new MapViewPath(mapState) : null;
1277 MapViewPath onewayArrows;
1278 MapViewPath onewayArrowsCasing;
1279 Rectangle bounds = g.getClipBounds();
1280 if (bounds != null) {
1281 // avoid arrow heads at the border
1282 bounds.grow(100, 100);
1283 }
1284
1285 List<? extends INode> wayNodes = way.getNodes();
1286 if (wayNodes.size() < 2) return;
1287
1288 // only highlight the segment if the way itself is not highlighted
1289 if (!way.isHighlighted() && highlightWaySegments != null) {
1290 MapViewPath highlightSegs = null;
1291 for (WaySegment ws : highlightWaySegments) {
1292 if (ws.way != way || ws.lowerIndex < offset) {
1293 continue;
1294 }
1295 if (highlightSegs == null) {
1296 highlightSegs = new MapViewPath(mapState);
1297 }
1298
1299 highlightSegs.moveTo(ws.getFirstNode());
1300 highlightSegs.lineTo(ws.getSecondNode());
1301 }
1302
1303 drawPathHighlight(highlightSegs, line);
1304 }
1305
1306 MapViewPoint lastPoint = null;
1307 Iterator<MapViewPoint> it = new OffsetIterator(mapState, wayNodes, offset);
1308 boolean initialMoveToNeeded = true;
1309 ArrowPaintHelper drawArrowHelper = null;
1310 double minSegmentLenSq = 0;
1311 if (showOrientation) {
1312 drawArrowHelper = new ArrowPaintHelper(PHI, 10 + line.getLineWidth());
1313 minSegmentLenSq = Math.pow(drawArrowHelper.getOnLineLength() * 1.3, 2);
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 final boolean drawArrow;
1330 if (way.isSelected()) {
1331 // always draw last arrow - no matter how short the segment is
1332 drawArrow = !it.hasNext() || p1.distanceToInViewSq(p2) > minSegmentLenSq;
1333 } else {
1334 // not selected: only draw arrow when it fits
1335 drawArrow = (!showHeadArrowOnly || !it.hasNext()) && p1.distanceToInViewSq(p2) > minSegmentLenSq;
1336 }
1337 if (drawArrow) {
1338 drawArrowHelper.paintArrowAt(orientationArrows, p2, p1);
1339 }
1340 }
1341 }
1342 lastPoint = p;
1343 }
1344 if (showOneway) {
1345 onewayArrows = new MapViewPath(mapState);
1346 onewayArrowsCasing = new MapViewPath(mapState);
1347 double interval = 60;
1348
1349 path.visitClippedLine(60, (inLineOffset, start, end, startIsOldEnd) -> {
1350 double segmentLength = start.distanceToInView(end);
1351 if (segmentLength > 0.001) {
1352 final double nx = (end.getInViewX() - start.getInViewX()) / segmentLength;
1353 final double ny = (end.getInViewY() - start.getInViewY()) / segmentLength;
1354
1355 // distance from p1
1356 double dist = interval - (inLineOffset % interval);
1357
1358 while (dist < segmentLength) {
1359 appendOnewayPath(onewayReversed, start, nx, ny, dist, 3d, onewayArrowsCasing);
1360 appendOnewayPath(onewayReversed, start, nx, ny, dist, 2d, onewayArrows);
1361 dist += interval;
1362 }
1363 }
1364 });
1365 } else {
1366 onewayArrows = null;
1367 onewayArrowsCasing = null;
1368 }
1369
1370 if (way.isHighlighted()) {
1371 drawPathHighlight(path, line);
1372 }
1373 displaySegments(path, orientationArrows, onewayArrows, onewayArrowsCasing, color, line, dashes, dashedColor);
1374 }
1375
1376 private static void appendOnewayPath(boolean onewayReversed, MapViewPoint p1, double nx, double ny, double dist,
1377 double onewaySize, Path2D onewayPath) {
1378 // scale such that border is 1 px
1379 final double fac = -(onewayReversed ? -1 : 1) * onewaySize * (1 + sinPHI) / (sinPHI * cosPHI);
1380 final double sx = nx * fac;
1381 final double sy = ny * fac;
1382
1383 // Attach the triangle at the incenter and not at the tip.
1384 // Makes the border even at all sides.
1385 final double x = p1.getInViewX() + nx * (dist + (onewayReversed ? -1 : 1) * (onewaySize / sinPHI));
1386 final double y = p1.getInViewY() + ny * (dist + (onewayReversed ? -1 : 1) * (onewaySize / sinPHI));
1387
1388 onewayPath.moveTo(x, y);
1389 onewayPath.lineTo(x + cosPHI * sx - sinPHI * sy, y + sinPHI * sx + cosPHI * sy);
1390 onewayPath.lineTo(x + cosPHI * sx + sinPHI * sy, y - sinPHI * sx + cosPHI * sy);
1391 onewayPath.lineTo(x, y);
1392 }
1393
1394 /**
1395 * Gets the "circum". This is the distance on the map in meters that 100 screen pixels represent.
1396 * @return The "circum"
1397 */
1398 public double getCircum() {
1399 return circum;
1400 }
1401
1402 @Override
1403 public void getColors() {
1404 super.getColors();
1405 this.highlightColorTransparent = new Color(highlightColor.getRed(), highlightColor.getGreen(), highlightColor.getBlue(), 100);
1406 this.backgroundColor = styles.getBackgroundColor();
1407 }
1408
1409 @Override
1410 public void getSettings(boolean virtual) {
1411 super.getSettings(virtual);
1412 paintSettings = MapPaintSettings.INSTANCE;
1413
1414 circum = nc.getDist100Pixel();
1415 scale = nc.getScale();
1416
1417 leftHandTraffic = PREFERENCE_LEFT_HAND_TRAFFIC.get();
1418
1419 useStrokes = paintSettings.getUseStrokesDistance() > circum;
1420 showNames = paintSettings.getShowNamesDistance() > circum;
1421 showIcons = paintSettings.getShowIconsDistance() > circum;
1422 isOutlineOnly = paintSettings.isOutlineOnly();
1423
1424 antialiasing = PREFERENCE_ANTIALIASING_USE.get() ?
1425 RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF;
1426 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialiasing);
1427
1428 Object textAntialiasing;
1429 switch (PREFERENCE_TEXT_ANTIALIASING.get()) {
1430 case "on":
1431 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
1432 break;
1433 case "off":
1434 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
1435 break;
1436 case "gasp":
1437 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_GASP;
1438 break;
1439 case "lcd-hrgb":
1440 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB;
1441 break;
1442 case "lcd-hbgr":
1443 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR;
1444 break;
1445 case "lcd-vrgb":
1446 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB;
1447 break;
1448 case "lcd-vbgr":
1449 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR;
1450 break;
1451 default:
1452 textAntialiasing = RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT;
1453 }
1454 g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textAntialiasing);
1455 }
1456
1457 private MapViewPath getPath(IWay<?> w) {
1458 MapViewPath path = new MapViewPath(mapState);
1459 if (w.isClosed()) {
1460 path.appendClosed(w.getNodes(), false);
1461 } else {
1462 path.append(w.getNodes(), false);
1463 }
1464 return path;
1465 }
1466
1467 private static Path2D.Double getPFClip(IWay<?> w, double extent) {
1468 Path2D.Double clip = new Path2D.Double();
1469 buildPFClip(clip, w.getNodes(), extent);
1470 return clip;
1471 }
1472
1473 private static Path2D.Double getPFClip(PolyData pd, double extent) {
1474 Path2D.Double clip = new Path2D.Double();
1475 clip.setWindingRule(Path2D.WIND_EVEN_ODD);
1476 buildPFClip(clip, pd.getNodes(), extent);
1477 for (PolyData pdInner : pd.getInners()) {
1478 buildPFClip(clip, pdInner.getNodes(), extent);
1479 }
1480 return clip;
1481 }
1482
1483 /**
1484 * Fix the clipping area of unclosed polygons for partial fill.
1485 *
1486 * The current algorithm for partial fill simply strokes the polygon with a
1487 * large stroke width after masking the outside with a clipping area.
1488 * This works, but for unclosed polygons, the mask can crop the corners at
1489 * both ends (see #12104).
1490 *
1491 * This method fixes the clipping area by sort of adding the corners to the
1492 * clip outline.
1493 *
1494 * @param clip the clipping area to modify (initially empty)
1495 * @param nodes nodes of the polygon
1496 * @param extent the extent
1497 */
1498 private static void buildPFClip(Path2D.Double clip, List<? extends INode> nodes, double extent) {
1499 boolean initial = true;
1500 for (INode n : nodes) {
1501 EastNorth p = n.getEastNorth();
1502 if (p != null) {
1503 if (initial) {
1504 clip.moveTo(p.getX(), p.getY());
1505 initial = false;
1506 } else {
1507 clip.lineTo(p.getX(), p.getY());
1508 }
1509 }
1510 }
1511 if (nodes.size() >= 3) {
1512 EastNorth fst = nodes.get(0).getEastNorth();
1513 EastNorth snd = nodes.get(1).getEastNorth();
1514 EastNorth lst = nodes.get(nodes.size() - 1).getEastNorth();
1515 EastNorth lbo = nodes.get(nodes.size() - 2).getEastNorth();
1516
1517 EastNorth cLst = getPFDisplacedEndPoint(lbo, lst, fst, extent);
1518 EastNorth cFst = getPFDisplacedEndPoint(snd, fst, cLst != null ? cLst : lst, extent);
1519 if (cLst == null && cFst != null) {
1520 cLst = getPFDisplacedEndPoint(lbo, lst, cFst, extent);
1521 }
1522 if (cLst != null) {
1523 clip.lineTo(cLst.getX(), cLst.getY());
1524 }
1525 if (cFst != null) {
1526 clip.lineTo(cFst.getX(), cFst.getY());
1527 }
1528 }
1529 }
1530
1531 /**
1532 * Get the point to add to the clipping area for partial fill of unclosed polygons.
1533 *
1534 * <code>(p1,p2)</code> is the first or last way segment and <code>p3</code> the
1535 * opposite endpoint.
1536 *
1537 * @param p1 1st point
1538 * @param p2 2nd point
1539 * @param p3 3rd point
1540 * @param extent the extent
1541 * @return a point q, such that p1,p2,q form a right angle
1542 * and the distance of q to p2 is <code>extent</code>. The point q lies on
1543 * the same side of the line p1,p2 as the point p3.
1544 * Returns null if p1,p2,p3 forms an angle greater 90 degrees. (In this case
1545 * the corner of the partial fill would not be cut off by the mask, so an
1546 * additional point is not necessary.)
1547 */
1548 private static EastNorth getPFDisplacedEndPoint(EastNorth p1, EastNorth p2, EastNorth p3, double extent) {
1549 double dx1 = p2.getX() - p1.getX();
1550 double dy1 = p2.getY() - p1.getY();
1551 double dx2 = p3.getX() - p2.getX();
1552 double dy2 = p3.getY() - p2.getY();
1553 if (dx1 * dx2 + dy1 * dy2 < 0) {
1554 double len = Math.sqrt(dx1 * dx1 + dy1 * dy1);
1555 if (len == 0) return null;
1556 double dxm = -dy1 * extent / len;
1557 double dym = dx1 * extent / len;
1558 if (dx1 * dy2 - dx2 * dy1 < 0) {
1559 dxm = -dxm;
1560 dym = -dym;
1561 }
1562 return new EastNorth(p2.getX() + dxm, p2.getY() + dym);
1563 }
1564 return null;
1565 }
1566
1567 /**
1568 * Test if the area is visible
1569 * @param area The area, interpreted in east/north space.
1570 * @return true if it is visible.
1571 */
1572 private boolean isAreaVisible(Path2D.Double area) {
1573 Rectangle2D bounds = area.getBounds2D();
1574 if (bounds.isEmpty()) return false;
1575 MapViewPoint p = mapState.getPointFor(new EastNorth(bounds.getX(), bounds.getY()));
1576 if (p.getInViewY() < 0 || p.getInViewX() > mapState.getViewWidth()) return false;
1577 p = mapState.getPointFor(new EastNorth(bounds.getX() + bounds.getWidth(), bounds.getY() + bounds.getHeight()));
1578 return p.getInViewX() >= 0 && p.getInViewY() <= mapState.getViewHeight();
1579 }
1580
1581 /**
1582 * Determines if the paint visitor shall render OSM objects such that they look inactive.
1583 * @return {@code true} if the paint visitor shall render OSM objects such that they look inactive
1584 */
1585 public boolean isInactiveMode() {
1586 return isInactiveMode;
1587 }
1588
1589 /**
1590 * Check if icons should be rendered
1591 * @return <code>true</code> to display icons
1592 */
1593 public boolean isShowIcons() {
1594 return showIcons;
1595 }
1596
1597 /**
1598 * Test if names should be rendered
1599 * @return <code>true</code> to display names
1600 */
1601 public boolean isShowNames() {
1602 return showNames && doSlowOperations;
1603 }
1604
1605 /**
1606 * Computes the flags for a given OSM primitive.
1607 * @param primitive The primititve to compute the flags for.
1608 * @param checkOuterMember <code>true</code> if we should also add {@link #FLAG_OUTERMEMBER_OF_SELECTED}
1609 * @return The flag.
1610 * @since 13676 (signature)
1611 */
1612 public static int computeFlags(IPrimitive primitive, boolean checkOuterMember) {
1613 if (primitive.isDisabled()) {
1614 return FLAG_DISABLED;
1615 } else if (primitive.isSelected()) {
1616 return FLAG_SELECTED;
1617 } else if (checkOuterMember && primitive.isOuterMemberOfSelected()) {
1618 return FLAG_OUTERMEMBER_OF_SELECTED;
1619 } else if (primitive.isMemberOfSelected()) {
1620 return FLAG_MEMBER_OF_SELECTED;
1621 } else {
1622 return FLAG_NORMAL;
1623 }
1624 }
1625
1626 /**
1627 * Sets the factory that creates the benchmark data receivers.
1628 * @param benchmarkFactory The factory.
1629 * @since 10697
1630 */
1631 public void setBenchmarkFactory(Supplier<RenderBenchmarkCollector> benchmarkFactory) {
1632 this.benchmarkFactory = benchmarkFactory;
1633 }
1634
1635 @Override
1636 public void render(final OsmData<?, ?, ?, ?> data, boolean renderVirtualNodes, Bounds bounds) {
1637 RenderBenchmarkCollector benchmark = benchmarkFactory.get();
1638 BBox bbox = bounds.toBBox();
1639 getSettings(renderVirtualNodes);
1640
1641 try {
1642 if (data.getReadLock().tryLock(1, TimeUnit.SECONDS)) {
1643 try {
1644 paintWithLock(data, renderVirtualNodes, benchmark, bbox);
1645 } finally {
1646 data.getReadLock().unlock();
1647 }
1648 } else {
1649 Logging.warn("Cannot paint layer {0}: It is locked.");
1650 }
1651 } catch (InterruptedException e) {
1652 Logging.warn("Cannot paint layer {0}: Interrupted");
1653 }
1654 }
1655
1656 private void paintWithLock(final OsmData<?, ?, ?, ?> data, boolean renderVirtualNodes, RenderBenchmarkCollector benchmark,
1657 BBox bbox) {
1658 try {
1659 highlightWaySegments = data.getHighlightedWaySegments();
1660
1661 benchmark.renderStart(circum);
1662
1663 List<? extends INode> nodes = data.searchNodes(bbox);
1664 List<? extends IWay<?>> ways = data.searchWays(bbox);
1665 List<? extends IRelation<?>> relations = data.searchRelations(bbox);
1666
1667 final List<StyleRecord> allStyleElems = new ArrayList<>(nodes.size()+ways.size()+relations.size());
1668
1669 // Need to process all relations first.
1670 // Reason: Make sure, ElemStyles.getStyleCacheWithRange is not called for the same primitive in parallel threads.
1671 // (Could be synchronized, but try to avoid this for performance reasons.)
1672 if (THREAD_POOL != null) {
1673 THREAD_POOL.invoke(new ComputeStyleListWorker(circum, nc, relations, allStyleElems,
1674 Math.max(20, relations.size() / THREAD_POOL.getParallelism() / 3), styles));
1675 THREAD_POOL.invoke(new ComputeStyleListWorker(circum, nc, new CompositeList<>(nodes, ways), allStyleElems,
1676 Math.max(100, (nodes.size() + ways.size()) / THREAD_POOL.getParallelism() / 3), styles));
1677 } else {
1678 new ComputeStyleListWorker(circum, nc, relations, allStyleElems, 0, styles).computeDirectly();
1679 new ComputeStyleListWorker(circum, nc, new CompositeList<>(nodes, ways), allStyleElems, 0, styles).computeDirectly();
1680 }
1681
1682 if (!benchmark.renderSort()) {
1683 return;
1684 }
1685
1686 // We use parallel sort here. This is only available for arrays.
1687 StyleRecord[] sorted = allStyleElems.toArray(new StyleRecord[0]);
1688 Arrays.parallelSort(sorted, null);
1689
1690 if (!benchmark.renderDraw(allStyleElems)) {
1691 return;
1692 }
1693
1694 for (StyleRecord record : sorted) {
1695 paintRecord(record);
1696 }
1697
1698 drawVirtualNodes(data, bbox);
1699
1700 benchmark.renderDone();
1701 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
1702 throw BugReport.intercept(e)
1703 .put("data", data)
1704 .put("circum", circum)
1705 .put("scale", scale)
1706 .put("paintSettings", paintSettings)
1707 .put("renderVirtualNodes", renderVirtualNodes);
1708 }
1709 }
1710
1711 private void paintRecord(StyleRecord record) {
1712 try {
1713 record.paintPrimitive(paintSettings, this);
1714 } catch (RuntimeException e) {
1715 throw BugReport.intercept(e).put("record", record);
1716 }
1717 }
1718}
Note: See TracBrowser for help on using the repository browser.