001/* License: GPL. For details, see LICENSE file. */
002package org.openstreetmap.josm.data.osm.visitor.paint;
003
004import java.awt.BasicStroke;
005import java.awt.Color;
006import java.awt.Graphics2D;
007import java.awt.Point;
008import java.awt.Polygon;
009import java.awt.Rectangle;
010import java.awt.RenderingHints;
011import java.awt.Stroke;
012import java.awt.geom.GeneralPath;
013import java.util.ArrayList;
014import java.util.Iterator;
015import java.util.List;
016
017import org.openstreetmap.josm.Main;
018import org.openstreetmap.josm.data.Bounds;
019import org.openstreetmap.josm.data.osm.BBox;
020import org.openstreetmap.josm.data.osm.Changeset;
021import org.openstreetmap.josm.data.osm.DataSet;
022import org.openstreetmap.josm.data.osm.Node;
023import org.openstreetmap.josm.data.osm.OsmPrimitive;
024import org.openstreetmap.josm.data.osm.Relation;
025import org.openstreetmap.josm.data.osm.RelationMember;
026import org.openstreetmap.josm.data.osm.Way;
027import org.openstreetmap.josm.data.osm.WaySegment;
028import org.openstreetmap.josm.data.osm.visitor.Visitor;
029import org.openstreetmap.josm.gui.NavigatableComponent;
030
031/**
032 * A map renderer that paints a simple scheme of every primitive it visits to a
033 * previous set graphic environment.
034 * @since 23
035 */
036public class WireframeMapRenderer extends AbstractMapRenderer implements Visitor {
037
038    /** Color Preference for ways not matching any other group */
039    protected Color dfltWayColor;
040    /** Color Preference for relations */
041    protected Color relationColor;
042    /** Color Preference for untagged ways */
043    protected Color untaggedWayColor;
044    /** Color Preference for tagged nodes */
045    protected Color taggedColor;
046    /** Color Preference for multiply connected nodes */
047    protected Color connectionColor;
048    /** Color Preference for tagged and multiply connected nodes */
049    protected Color taggedConnectionColor;
050    /** Preference: should directional arrows be displayed */
051    protected boolean showDirectionArrow;
052    /** Preference: should arrows for oneways be displayed */
053    protected boolean showOnewayArrow;
054    /** Preference: should only the last arrow of a way be displayed */
055    protected boolean showHeadArrowOnly;
056    /** Preference: should the segement numbers of ways be displayed */
057    protected boolean showOrderNumber;
058    /** Preference: should selected nodes be filled */
059    protected boolean fillSelectedNode;
060    /** Preference: should unselected nodes be filled */
061    protected boolean fillUnselectedNode;
062    /** Preference: should tagged nodes be filled */
063    protected boolean fillTaggedNode;
064    /** Preference: should multiply connected nodes be filled */
065    protected boolean fillConnectionNode;
066    /** Preference: size of selected nodes */
067    protected int selectedNodeSize;
068    /** Preference: size of unselected nodes */
069    protected int unselectedNodeSize;
070    /** Preference: size of multiply connected nodes */
071    protected int connectionNodeSize;
072    /** Preference: size of tagged nodes */
073    protected int taggedNodeSize;
074
075    /** Color cache to draw subsequent segments of same color as one <code>Path</code>. */
076    protected Color currentColor = null;
077    /** Path store to draw subsequent segments of same color as one <code>Path</code>. */
078    protected GeneralPath currentPath = new GeneralPath();
079    /**
080      * <code>DataSet</code> passed to the @{link render} function to overcome the argument
081      * limitations of @{link Visitor} interface. Only valid until end of rendering call.
082      */
083    private DataSet ds;
084
085    /** Helper variable for {@link #drawSegment} */
086    private static final double PHI = Math.toRadians(20);
087    /** Helper variable for {@link #drawSegment} */
088    private static final double cosPHI = Math.cos(PHI);
089    /** Helper variable for {@link #drawSegment} */
090    private static final double sinPHI = Math.sin(PHI);
091
092    /** Helper variable for {@link #visit(Relation)} */
093    private Stroke relatedWayStroke = new BasicStroke(
094            4, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL);
095
096    /**
097     * Creates an wireframe render
098     *
099     * @param g the graphics context. Must not be null.
100     * @param nc the map viewport. Must not be null.
101     * @param isInactiveMode if true, the paint visitor shall render OSM objects such that they
102     * look inactive. Example: rendering of data in an inactive layer using light gray as color only.
103     * @throws IllegalArgumentException thrown if {@code g} is null
104     * @throws IllegalArgumentException thrown if {@code nc} is null
105     */
106    public WireframeMapRenderer(Graphics2D g, NavigatableComponent nc, boolean isInactiveMode) {
107        super(g, nc, isInactiveMode);
108    }
109
110    @Override
111    public void getColors() {
112        super.getColors();
113        dfltWayColor = PaintColors.DEFAULT_WAY.get();
114        relationColor = PaintColors.RELATION.get();
115        untaggedWayColor = PaintColors.UNTAGGED_WAY.get();
116        highlightColor = PaintColors.HIGHLIGHT_WIREFRAME.get();
117        taggedColor = PaintColors.TAGGED.get();
118        connectionColor = PaintColors.CONNECTION.get();
119
120        if (taggedColor != nodeColor) {
121            taggedConnectionColor = taggedColor;
122        } else {
123            taggedConnectionColor = connectionColor;
124        }
125    }
126
127    @Override
128    protected void getSettings(boolean virtual) {
129        super.getSettings(virtual);
130        MapPaintSettings settings = MapPaintSettings.INSTANCE;
131        showDirectionArrow = settings.isShowDirectionArrow();
132        showOnewayArrow = settings.isShowOnewayArrow();
133        showHeadArrowOnly = settings.isShowHeadArrowOnly();
134        showOrderNumber = settings.isShowOrderNumber();
135        selectedNodeSize = settings.getSelectedNodeSize();
136        unselectedNodeSize = settings.getUnselectedNodeSize();
137        connectionNodeSize = settings.getConnectionNodeSize();
138        taggedNodeSize = settings.getTaggedNodeSize();
139        fillSelectedNode = settings.isFillSelectedNode();
140        fillUnselectedNode = settings.isFillUnselectedNode();
141        fillConnectionNode = settings.isFillConnectionNode();
142        fillTaggedNode = settings.isFillTaggedNode();
143
144        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
145                Main.pref.getBoolean("mappaint.wireframe.use-antialiasing", false) ?
146                        RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
147    }
148
149    /**
150     * Renders the dataset for display.
151     *
152     * @param data <code>DataSet</code> to display
153     * @param virtual <code>true</code> if virtual nodes are used
154     * @param bounds display boundaries
155     */
156    @Override
157    public void render(DataSet data, boolean virtual, Bounds bounds) {
158        BBox bbox = bounds.toBBox();
159        this.ds = data;
160        getSettings(virtual);
161
162        for (final Relation rel : data.searchRelations(bbox)) {
163            if (rel.isDrawable() && !ds.isSelected(rel) && !rel.isDisabledAndHidden()) {
164                rel.accept(this);
165            }
166        }
167
168        // draw tagged ways first, then untagged ways, then highlighted ways
169        List<Way> highlightedWays = new ArrayList<>();
170        List<Way> untaggedWays = new ArrayList<>();
171
172        for (final Way way : data.searchWays(bbox)){
173            if (way.isDrawable() && !ds.isSelected(way) && !way.isDisabledAndHidden()) {
174                if (way.isHighlighted()) {
175                    highlightedWays.add(way);
176                } else if (!way.isTagged()) {
177                    untaggedWays.add(way);
178                } else {
179                    way.accept(this);
180                }
181            }
182        }
183        displaySegments();
184
185        // Display highlighted ways after the other ones (fix #8276)
186        List<Way> specialWays = new ArrayList<>(untaggedWays);
187        specialWays.addAll(highlightedWays);
188        for (final Way way : specialWays){
189            way.accept(this);
190        }
191        specialWays.clear();
192        displaySegments();
193
194        for (final OsmPrimitive osm : data.getSelected()) {
195            if (osm.isDrawable()) {
196                osm.accept(this);
197            }
198        }
199        displaySegments();
200
201        for (final OsmPrimitive osm: data.searchNodes(bbox)) {
202            if (osm.isDrawable() && !ds.isSelected(osm) && !osm.isDisabledAndHidden())
203            {
204                osm.accept(this);
205            }
206        }
207        drawVirtualNodes(data, bbox);
208
209        // draw highlighted way segments over the already drawn ways. Otherwise each
210        // way would have to be checked if it contains a way segment to highlight when
211        // in most of the cases there won't be more than one segment. Since the wireframe
212        // renderer does not feature any transparency there should be no visual difference.
213        for (final WaySegment wseg : data.getHighlightedWaySegments()) {
214            drawSegment(nc.getPoint(wseg.getFirstNode()), nc.getPoint(wseg.getSecondNode()), highlightColor, false);
215        }
216        displaySegments();
217    }
218
219    /**
220     * Helper function to calculate maximum of 4 values.
221     *
222     * @param a First value
223     * @param b Second value
224     * @param c Third value
225     * @param d Fourth value
226     */
227    private static final int max(int a, int b, int c, int d) {
228        return Math.max(Math.max(a, b), Math.max(c, d));
229    }
230
231    /**
232     * Draw a small rectangle.
233     * White if selected (as always) or red otherwise.
234     *
235     * @param n The node to draw.
236     */
237    @Override
238    public void visit(Node n) {
239        if (n.isIncomplete()) return;
240
241        if (n.isHighlighted()) {
242            drawNode(n, highlightColor, selectedNodeSize, fillSelectedNode);
243        } else {
244            Color color;
245
246            if (isInactiveMode || n.isDisabled()) {
247                color = inactiveColor;
248            } else if (n.isSelected()) {
249                color = selectedColor;
250            } else if (n.isMemberOfSelected()) {
251                color = relationSelectedColor;
252            } else if (n.isConnectionNode()) {
253                if (isNodeTagged(n)) {
254                    color = taggedConnectionColor;
255                } else {
256                    color = connectionColor;
257                }
258            } else {
259                if (isNodeTagged(n)) {
260                    color = taggedColor;
261                } else {
262                    color = nodeColor;
263                }
264            }
265
266            final int size = max((ds.isSelected(n) ? selectedNodeSize : 0),
267                    (isNodeTagged(n) ? taggedNodeSize : 0),
268                    (n.isConnectionNode() ? connectionNodeSize : 0),
269                    unselectedNodeSize);
270
271            final boolean fill = (ds.isSelected(n) && fillSelectedNode) ||
272            (isNodeTagged(n) && fillTaggedNode) ||
273            (n.isConnectionNode() && fillConnectionNode) ||
274            fillUnselectedNode;
275
276            drawNode(n, color, size, fill);
277        }
278    }
279
280    private boolean isNodeTagged(Node n) {
281        return n.isTagged() || n.isAnnotated();
282    }
283
284    /**
285     * Draw a line for all way segments.
286     * @param w The way to draw.
287     */
288    @Override
289    public void visit(Way w) {
290        if (w.isIncomplete() || w.getNodesCount() < 2)
291            return;
292
293        /* show direction arrows, if draw.segment.relevant_directions_only is not set, the way is tagged with a direction key
294           (even if the tag is negated as in oneway=false) or the way is selected */
295
296        boolean showThisDirectionArrow = ds.isSelected(w) || showDirectionArrow;
297        /* head only takes over control if the option is true,
298           the direction should be shown at all and not only because it's selected */
299        boolean showOnlyHeadArrowOnly = showThisDirectionArrow && !ds.isSelected(w) && showHeadArrowOnly;
300        Color wayColor;
301
302        if (isInactiveMode || w.isDisabled()) {
303            wayColor = inactiveColor;
304        } else if (w.isHighlighted()) {
305            wayColor = highlightColor;
306        } else if (w.isSelected()) {
307            wayColor = selectedColor;
308        } else if (w.isMemberOfSelected()) {
309            wayColor = relationSelectedColor;
310        } else if (!w.isTagged()) {
311            wayColor = untaggedWayColor;
312        } else {
313            wayColor = dfltWayColor;
314        }
315
316        Iterator<Node> it = w.getNodes().iterator();
317        if (it.hasNext()) {
318            Point lastP = nc.getPoint(it.next());
319            for (int orderNumber = 1; it.hasNext(); orderNumber++) {
320                Point p = nc.getPoint(it.next());
321                drawSegment(lastP, p, wayColor,
322                        showOnlyHeadArrowOnly ? !it.hasNext() : showThisDirectionArrow);
323                if (showOrderNumber && !isInactiveMode) {
324                    drawOrderNumber(lastP, p, orderNumber, g.getColor());
325                }
326                lastP = p;
327            }
328        }
329    }
330
331    /**
332     * Draw objects used in relations.
333     * @param r The relation to draw.
334     */
335    @Override
336    public void visit(Relation r) {
337        if (r.isIncomplete()) return;
338
339        Color col;
340        if (isInactiveMode || r.isDisabled()) {
341            col = inactiveColor;
342        } else if (r.isSelected()) {
343            col = selectedColor;
344        } else if (r.isMultipolygon() && r.isMemberOfSelected()) {
345            col = relationSelectedColor;
346        } else {
347            col = relationColor;
348        }
349        g.setColor(col);
350
351        for (RelationMember m : r.getMembers()) {
352            if (m.getMember().isIncomplete() || !m.getMember().isDrawable()) {
353                continue;
354            }
355
356            if (m.isNode()) {
357                Point p = nc.getPoint(m.getNode());
358                if (p.x < 0 || p.y < 0
359                        || p.x > nc.getWidth() || p.y > nc.getHeight()) {
360                    continue;
361                }
362
363                g.drawOval(p.x-4, p.y-4, 9, 9);
364            } else if (m.isWay()) {
365                GeneralPath path = new GeneralPath();
366
367                boolean first = true;
368                for (Node n : m.getWay().getNodes()) {
369                    if (!n.isDrawable()) {
370                        continue;
371                    }
372                    Point p = nc.getPoint(n);
373                    if (first) {
374                        path.moveTo(p.x, p.y);
375                        first = false;
376                    } else {
377                        path.lineTo(p.x, p.y);
378                    }
379                }
380
381                g.draw(relatedWayStroke.createStrokedShape(path));
382            }
383        }
384    }
385
386    /**
387     * Visitor for changesets not used in this class
388     * @param cs The changeset for inspection.
389     */
390    @Override
391    public void visit(Changeset cs) {/* ignore */}
392
393    @Override
394    public void drawNode(Node n, Color color, int size, boolean fill) {
395        if (size > 1) {
396            int radius = size / 2;
397            Point p = nc.getPoint(n);
398            if ((p.x < 0) || (p.y < 0) || (p.x > nc.getWidth())
399                    || (p.y > nc.getHeight()))
400                return;
401            g.setColor(color);
402            if (fill) {
403                g.fillRect(p.x - radius, p.y - radius, size, size);
404                g.drawRect(p.x - radius, p.y - radius, size, size);
405            } else {
406                g.drawRect(p.x - radius, p.y - radius, size, size);
407            }
408        }
409    }
410
411    /**
412     * Draw a line with the given color.
413     *
414     * @param path The path to append this segment.
415     * @param p1 First point of the way segment.
416     * @param p2 Second point of the way segment.
417     * @param showDirection <code>true</code> if segment direction should be indicated
418     */
419    protected void drawSegment(GeneralPath path, Point p1, Point p2, boolean showDirection) {
420        Rectangle bounds = g.getClipBounds();
421        bounds.grow(100, 100);                  // avoid arrow heads at the border
422        LineClip clip = new LineClip(p1, p2, bounds);
423        if (clip.execute()) {
424            p1 = clip.getP1();
425            p2 = clip.getP2();
426            path.moveTo(p1.x, p1.y);
427            path.lineTo(p2.x, p2.y);
428
429            if (showDirection) {
430                final double l =  10. / p1.distance(p2);
431
432                final double sx = l * (p1.x - p2.x);
433                final double sy = l * (p1.y - p2.y);
434
435                path.lineTo (p2.x + (int) Math.round(cosPHI * sx - sinPHI * sy), p2.y + (int) Math.round(sinPHI * sx + cosPHI * sy));
436                path.moveTo (p2.x + (int) Math.round(cosPHI * sx + sinPHI * sy), p2.y + (int) Math.round(- sinPHI * sx + cosPHI * sy));
437                path.lineTo(p2.x, p2.y);
438            }
439        }
440    }
441
442    /**
443     * Draw a line with the given color.
444     *
445     * @param p1 First point of the way segment.
446     * @param p2 Second point of the way segment.
447     * @param col The color to use for drawing line.
448     * @param showDirection <code>true</code> if segment direction should be indicated.
449     */
450    protected void drawSegment(Point p1, Point p2, Color col, boolean showDirection) {
451        if (col != currentColor) {
452            displaySegments(col);
453        }
454        drawSegment(currentPath, p1, p2, showDirection);
455    }
456
457    /**
458     * Checks if a polygon is visible in display.
459     *
460     * @param polygon The polygon to check.
461     * @return <code>true</code> if polygon is visible.
462     */
463    protected boolean isPolygonVisible(Polygon polygon) {
464        Rectangle bounds = polygon.getBounds();
465        if (bounds.width == 0 && bounds.height == 0) return false;
466        if (bounds.x > nc.getWidth()) return false;
467        if (bounds.y > nc.getHeight()) return false;
468        if (bounds.x + bounds.width < 0) return false;
469        if (bounds.y + bounds.height < 0) return false;
470        return true;
471    }
472
473    /**
474     * Finally display all segments in currect path.
475     */
476    protected void displaySegments() {
477        displaySegments(null);
478    }
479
480    /**
481     * Finally display all segments in currect path.
482     *
483     * @param newColor This color is set after the path is drawn.
484     */
485    protected void displaySegments(Color newColor) {
486        if (currentPath != null) {
487            g.setColor(currentColor);
488            g.draw(currentPath);
489            currentPath = new GeneralPath();
490            currentColor = newColor;
491        }
492    }
493}