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

Last change on this file since 11761 was 11761, checked in by michael2402, 7 years ago

See #10176: Allow icons in multipolygons, use even/odd winding rule for icon placement position in multipolygons

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