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

Last change on this file since 16253 was 16253, checked in by simon04, 4 years ago

fix #18468 - MapCSS: add support for text-rotation

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