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

Last change on this file was 19549, checked in by stoecker, 5 weeks ago

fix #24678 - Possibility to specify custom MapPaintSettings for MapCSS rendering - patch by zkir

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