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

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

rendering of IPrimitives

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