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

Last change on this file since 13150 was 13150, checked in by Don-vip, 6 years ago

fix #14778 - stroke not reset after drawing of large areas produced graphics artifacts when painting world bounds and selection rectangles, bug seen when filtering ways only, as way rendering reset the stroke

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