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

Last change on this file since 12966 was 12966, checked in by bastiK, 7 years ago

use RenderingHelper in MapCSSRendererTest; move getBackgroundColor() from PaintColors to ElemStyles (no longer global) (see #15273)

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