001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.mappaint.styleelement;
003
004import java.awt.BasicStroke;
005import java.awt.Color;
006import java.awt.Rectangle;
007import java.awt.Stroke;
008import java.util.Objects;
009import java.util.Optional;
010
011import org.openstreetmap.josm.data.osm.INode;
012import org.openstreetmap.josm.data.osm.IPrimitive;
013import org.openstreetmap.josm.data.osm.IRelation;
014import org.openstreetmap.josm.data.osm.visitor.paint.MapPaintSettings;
015import org.openstreetmap.josm.data.osm.visitor.paint.StyledMapRenderer;
016import org.openstreetmap.josm.gui.draw.SymbolShape;
017import org.openstreetmap.josm.gui.mappaint.Cascade;
018import org.openstreetmap.josm.gui.mappaint.Environment;
019import org.openstreetmap.josm.gui.mappaint.Keyword;
020import org.openstreetmap.josm.gui.mappaint.MapPaintStyles.IconReference;
021import org.openstreetmap.josm.gui.mappaint.styleelement.BoxTextElement.BoxProvider;
022import org.openstreetmap.josm.gui.mappaint.styleelement.BoxTextElement.SimpleBoxProvider;
023import org.openstreetmap.josm.spi.preferences.Config;
024import org.openstreetmap.josm.tools.CheckParameterUtil;
025import org.openstreetmap.josm.tools.ColorHelper;
026import org.openstreetmap.josm.tools.Logging;
027import org.openstreetmap.josm.tools.RotationAngle;
028import org.openstreetmap.josm.tools.Utils;
029
030/**
031 * applies for Nodes and turn restriction relations
032 */
033public class NodeElement extends StyleElement {
034    /**
035     * The image that is used to display this node. May be <code>null</code>
036     */
037    public final MapImage mapImage;
038    /**
039     * The angle that is used to rotate {@link #mapImage}. May be <code>null</code> to indicate no rotation.
040     */
041    public final RotationAngle mapImageAngle;
042    /**
043     * The symbol that should be used for drawing this node.
044     */
045    public final Symbol symbol;
046
047    private static final String[] ICON_KEYS = {ICON_IMAGE, ICON_WIDTH, ICON_HEIGHT, ICON_OPACITY, ICON_OFFSET_X, ICON_OFFSET_Y};
048
049    protected NodeElement(Cascade c, MapImage mapImage, Symbol symbol, float defaultMajorZindex, RotationAngle rotationAngle) {
050        super(c, defaultMajorZindex);
051        this.mapImage = mapImage;
052        this.symbol = symbol;
053        this.mapImageAngle = Objects.requireNonNull(rotationAngle, "rotationAngle");
054    }
055
056    /**
057     * Creates a new node element for the given Environment
058     * @param env The environment
059     * @return The node element style or <code>null</code> if the node should not be painted.
060     */
061    public static NodeElement create(Environment env) {
062        return create(env, 4f, false);
063    }
064
065    static NodeElement create(Environment env, float defaultMajorZindex, boolean allowDefault) {
066        MapImage mapImage = createIcon(env);
067        Symbol symbol = null;
068        if (mapImage == null) {
069            symbol = createSymbol(env);
070        }
071
072        // optimization: if we neither have a symbol, nor a mapImage
073        // we don't have to check for the remaining style properties and we don't
074        // have to allocate a node element style.
075        if (!allowDefault && symbol == null && mapImage == null) return null;
076
077        Cascade c = env.getCascade();
078        RotationAngle rotationAngle = createRotationAngle(env);
079        return new NodeElement(c, mapImage, symbol, defaultMajorZindex, rotationAngle);
080    }
081
082    /**
083     * Reads the icon-rotation property and creates a rotation angle from it.
084     * @param env The environment
085     * @return The angle
086     * @since 11670
087     */
088    public static RotationAngle createRotationAngle(Environment env) {
089        return createRotationAngle(env, ICON_ROTATION);
090    }
091
092    /**
093     * Reads the text-rotation property and creates a rotation angle from it.
094     * @param env The environment
095     * @return The angle
096     * @since 16253
097     */
098    public static RotationAngle createTextRotationAngle(Environment env) {
099        return createRotationAngle(env, TEXT_ROTATION);
100    }
101
102    private static RotationAngle createRotationAngle(Environment env, String key) {
103        Cascade c = env.getCascade();
104
105        RotationAngle rotationAngle = RotationAngle.NO_ROTATION;
106        final Float angle = c.get(key, null, Float.class, true);
107        if (angle != null) {
108            rotationAngle = RotationAngle.buildStaticRotation(angle);
109        } else {
110            final Keyword rotationKW = c.get(key, null, Keyword.class);
111            if (rotationKW != null) {
112                if ("way".equals(rotationKW.val)) {
113                    rotationAngle = RotationAngle.buildWayDirectionRotation();
114                } else {
115                    try {
116                        rotationAngle = RotationAngle.buildStaticRotation(rotationKW.val);
117                    } catch (IllegalArgumentException ignore) {
118                        Logging.trace(ignore);
119                    }
120                }
121            }
122        }
123        return rotationAngle;
124    }
125
126    /**
127     * Create a map icon for the environment using the default keys.
128     * @param env The environment to read the icon form
129     * @return The icon or <code>null</code> if no icon is defined
130     * @since 11670
131     */
132    public static MapImage createIcon(final Environment env) {
133        return createIcon(env, ICON_KEYS);
134    }
135
136    /**
137     * Create a map icon for the environment.
138     * @param env The environment to read the icon form
139     * @param keys The keys, indexed by the ICON_..._IDX constants.
140     * @return The icon or <code>null</code> if no icon is defined
141     */
142    public static MapImage createIcon(final Environment env, final String... keys) {
143        CheckParameterUtil.ensureParameterNotNull(env, "env");
144        CheckParameterUtil.ensureParameterNotNull(keys, "keys");
145
146        Cascade c = env.getCascade();
147
148        final IconReference iconRef = c.get(keys[ICON_IMAGE_IDX], null, IconReference.class, true);
149        if (iconRef == null)
150            return null;
151
152        Cascade cDef = env.getCascade("default");
153
154        Float widthOnDefault = cDef.get(keys[ICON_WIDTH_IDX], null, Float.class);
155        if (widthOnDefault != null && widthOnDefault <= 0) {
156            widthOnDefault = null;
157        }
158        Float widthF = getWidth(c, keys[ICON_WIDTH_IDX], widthOnDefault);
159
160        Float heightOnDefault = cDef.get(keys[ICON_HEIGHT_IDX], null, Float.class);
161        if (heightOnDefault != null && heightOnDefault <= 0) {
162            heightOnDefault = null;
163        }
164        Float heightF = getWidth(c, keys[ICON_HEIGHT_IDX], heightOnDefault);
165
166        int width = widthF == null ? -1 : Math.round(widthF);
167        int height = heightF == null ? -1 : Math.round(heightF);
168
169        float offsetXF = 0f;
170        float offsetYF = 0f;
171        if (keys[ICON_OFFSET_X_IDX] != null) {
172            offsetXF = c.get(keys[ICON_OFFSET_X_IDX], 0f, Float.class);
173            offsetYF = c.get(keys[ICON_OFFSET_Y_IDX], 0f, Float.class);
174        }
175
176        final MapImage mapImage = new MapImage(iconRef.iconName, iconRef.source);
177
178        mapImage.width = width;
179        mapImage.height = height;
180        mapImage.offsetX = Math.round(offsetXF);
181        mapImage.offsetY = Math.round(offsetYF);
182
183        mapImage.alpha = Utils.clamp(Config.getPref().getInt("mappaint.icon-image-alpha", 255), 0, 255);
184        Integer pAlpha = ColorHelper.float2int(c.get(keys[ICON_OPACITY_IDX], null, float.class));
185        if (pAlpha != null) {
186            mapImage.alpha = pAlpha;
187        }
188        return mapImage;
189    }
190
191    /**
192     * Create a symbol for the environment
193     * @param env The environment to read the icon form
194     * @return The symbol.
195     */
196    private static Symbol createSymbol(Environment env) {
197        Cascade c = env.getCascade();
198
199        Keyword shapeKW = c.get("symbol-shape", null, Keyword.class);
200        if (shapeKW == null)
201            return null;
202        Optional<SymbolShape> shape = SymbolShape.forName(shapeKW.val);
203        if (!shape.isPresent()) {
204            return null;
205        }
206
207        Cascade cDef = env.getCascade("default");
208        Float sizeOnDefault = cDef.get("symbol-size", null, Float.class);
209        if (sizeOnDefault != null && sizeOnDefault <= 0) {
210            sizeOnDefault = null;
211        }
212        Float size = Optional.ofNullable(getWidth(c, "symbol-size", sizeOnDefault)).orElse(10f);
213        if (size <= 0)
214            return null;
215
216        Float strokeWidthOnDefault = getWidth(cDef, "symbol-stroke-width", null);
217        Float strokeWidth = getWidth(c, "symbol-stroke-width", strokeWidthOnDefault);
218
219        Color strokeColor = c.get("symbol-stroke-color", null, Color.class);
220
221        if (strokeWidth == null && strokeColor != null) {
222            strokeWidth = 1f;
223        } else if (strokeWidth != null && strokeColor == null) {
224            strokeColor = Color.ORANGE;
225        }
226
227        Stroke stroke = null;
228        if (strokeColor != null && strokeWidth != null) {
229            Integer strokeAlpha = ColorHelper.float2int(c.get("symbol-stroke-opacity", null, Float.class));
230            if (strokeAlpha != null) {
231                strokeColor = new Color(strokeColor.getRed(), strokeColor.getGreen(),
232                        strokeColor.getBlue(), strokeAlpha);
233            }
234            stroke = new BasicStroke(strokeWidth);
235        }
236
237        Color fillColor = c.get("symbol-fill-color", null, Color.class);
238        if (stroke == null && fillColor == null) {
239            fillColor = Color.BLUE;
240        }
241
242        if (fillColor != null) {
243            Integer fillAlpha = ColorHelper.float2int(c.get("symbol-fill-opacity", null, Float.class));
244            if (fillAlpha != null) {
245                fillColor = new Color(fillColor.getRed(), fillColor.getGreen(),
246                        fillColor.getBlue(), fillAlpha);
247            }
248        }
249
250        return new Symbol(shape.get(), Math.round(size), stroke, strokeColor, fillColor);
251    }
252
253    @Override
254    public void paintPrimitive(IPrimitive primitive, MapPaintSettings settings, StyledMapRenderer painter,
255            boolean selected, boolean outermember, boolean member) {
256        if (primitive instanceof INode) {
257            INode n = (INode) primitive;
258            if (mapImage != null && painter.isShowIcons()) {
259                painter.drawNodeIcon(n, mapImage, painter.isInactiveMode() || n.isDisabled(), selected, member,
260                        mapImageAngle == null ? 0.0 : mapImageAngle.getRotationAngle(primitive));
261            } else if (symbol != null) {
262                paintWithSymbol(settings, painter, selected, member, n);
263            } else {
264                Color color;
265                boolean isConnection = n.isConnectionNode();
266
267                if (painter.isInactiveMode() || n.isDisabled()) {
268                    color = settings.getInactiveColor();
269                } else if (selected) {
270                    color = settings.getSelectedColor();
271                } else if (member) {
272                    color = settings.getRelationSelectedColor();
273                } else if (isConnection) {
274                    if (n.isTagged()) {
275                        color = settings.getTaggedConnectionColor();
276                    } else {
277                        color = settings.getConnectionColor();
278                    }
279                } else {
280                    if (n.isTagged()) {
281                        color = settings.getTaggedColor();
282                    } else {
283                        color = settings.getNodeColor();
284                    }
285                }
286
287                final int size = max(
288                        selected ? settings.getSelectedNodeSize() : 0,
289                        n.isTagged() ? settings.getTaggedNodeSize() : 0,
290                        isConnection ? settings.getConnectionNodeSize() : 0,
291                        settings.getUnselectedNodeSize());
292
293                final boolean fill = (selected && settings.isFillSelectedNode()) ||
294                (n.isTagged() && settings.isFillTaggedNode()) ||
295                (isConnection && settings.isFillConnectionNode()) ||
296                settings.isFillUnselectedNode();
297
298                painter.drawNode(n, color, size, fill);
299
300            }
301        } else if (primitive instanceof IRelation && mapImage != null) {
302            painter.drawRestriction((IRelation<?>) primitive, mapImage, painter.isInactiveMode() || primitive.isDisabled());
303        }
304    }
305
306    private void paintWithSymbol(MapPaintSettings settings, StyledMapRenderer painter, boolean selected, boolean member,
307            INode n) {
308        Color fillColor = symbol.fillColor;
309        if (fillColor != null) {
310            if (painter.isInactiveMode() || n.isDisabled()) {
311                fillColor = settings.getInactiveColor();
312            } else if (defaultSelectedHandling && selected) {
313                fillColor = settings.getSelectedColor(fillColor.getAlpha());
314            } else if (member) {
315                fillColor = settings.getRelationSelectedColor(fillColor.getAlpha());
316            }
317        }
318        Color strokeColor = symbol.strokeColor;
319        if (strokeColor != null) {
320            if (painter.isInactiveMode() || n.isDisabled()) {
321                strokeColor = settings.getInactiveColor();
322            } else if (defaultSelectedHandling && selected) {
323                strokeColor = settings.getSelectedColor(strokeColor.getAlpha());
324            } else if (member) {
325                strokeColor = settings.getRelationSelectedColor(strokeColor.getAlpha());
326            }
327        }
328        painter.drawNodeSymbol(n, symbol, fillColor, strokeColor);
329    }
330
331    /**
332     * Gets the selection box for this element.
333     * @return The selection box as {@link BoxProvider} object.
334     */
335    public BoxProvider getBoxProvider() {
336        if (mapImage != null)
337            return mapImage.getBoxProvider();
338        else if (symbol != null)
339            return new SimpleBoxProvider(new Rectangle(-symbol.size/2, -symbol.size/2, symbol.size, symbol.size));
340        else {
341            // This is only executed once, so no performance concerns.
342            // However, it would be better, if the settings could be changed at runtime.
343            int size = max(Config.getPref().getInt("mappaint.node.selected-size", 5),
344                    Config.getPref().getInt("mappaint.node.unselected-size", 3),
345                    Config.getPref().getInt("mappaint.node.connection-size", 5),
346                    Config.getPref().getInt("mappaint.node.tagged-size", 3)
347            );
348            return new SimpleBoxProvider(new Rectangle(-size/2, -size/2, size, size));
349        }
350    }
351
352    private static int max(int a, int b, int c, int d) {
353        // Profile before switching to a stream/int[] array
354        // This was 66% give or take for painting nodes in terms of memory allocations
355        // and was ~17% of the CPU allocations. By not using a vararg method call, we avoid
356        // the creation of an array. By avoiding both streams and arrays, the cost for this method is negligible.
357        // This means that this saves about 7% of the CPU cycles during map paint, and about 20%
358        // of the memory allocations during map paint.
359        return Math.max(a, Math.max(b, Math.max(c, d)));
360    }
361
362    @Override
363    public int hashCode() {
364        return Objects.hash(super.hashCode(), mapImage, mapImageAngle, symbol);
365    }
366
367    @Override
368    public boolean equals(Object obj) {
369        if (this == obj) return true;
370        if (obj == null || getClass() != obj.getClass()) return false;
371        if (!super.equals(obj)) return false;
372        NodeElement that = (NodeElement) obj;
373        return Objects.equals(mapImage, that.mapImage) &&
374               Objects.equals(mapImageAngle, that.mapImageAngle) &&
375               Objects.equals(symbol, that.symbol);
376    }
377
378    @Override
379    public String toString() {
380        StringBuilder s = new StringBuilder(64).append("NodeElement{").append(super.toString());
381        if (mapImage != null) {
382            s.append(" icon=[").append(mapImage).append(']');
383        }
384        if (mapImage != null && mapImageAngle != null) {
385            s.append(" mapImageAngle=[").append(mapImageAngle).append(']');
386        }
387        if (symbol != null) {
388            s.append(" symbol=[").append(symbol).append(']');
389        }
390        s.append('}');
391        return s.toString();
392    }
393}