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

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

revert [12399], fixes #14980, reopens #14926

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