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

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

support drawing INode in renderers

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