source: josm/trunk/src/org/openstreetmap/josm/actions/AlignInCircleAction.java

Last change on this file was 18615, checked in by taylor.smock, 16 months ago

Fix #22504: Circularize multiple selected ways (patch by qeef, modified)

  • Property svn:eol-style set to native
File size: 16.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.event.ActionEvent;
8import java.awt.event.KeyEvent;
9import java.util.ArrayList;
10import java.util.Collection;
11import java.util.Collections;
12import java.util.HashSet;
13import java.util.LinkedList;
14import java.util.List;
15import java.util.Set;
16import java.util.SortedMap;
17import java.util.TreeMap;
18import java.util.stream.Collectors;
19
20import javax.swing.JOptionPane;
21
22import org.openstreetmap.josm.command.Command;
23import org.openstreetmap.josm.command.MoveCommand;
24import org.openstreetmap.josm.command.SequenceCommand;
25import org.openstreetmap.josm.data.UndoRedoHandler;
26import org.openstreetmap.josm.data.coor.EastNorth;
27import org.openstreetmap.josm.data.coor.PolarCoor;
28import org.openstreetmap.josm.data.osm.DataSet;
29import org.openstreetmap.josm.data.osm.Node;
30import org.openstreetmap.josm.data.osm.OsmPrimitive;
31import org.openstreetmap.josm.data.osm.Way;
32import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon;
33import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.JoinedWay;
34import org.openstreetmap.josm.data.validation.tests.CrossingWays;
35import org.openstreetmap.josm.data.validation.tests.SelfIntersectingWay;
36import org.openstreetmap.josm.gui.Notification;
37import org.openstreetmap.josm.tools.Geometry;
38import org.openstreetmap.josm.tools.Logging;
39import org.openstreetmap.josm.tools.Shortcut;
40
41/**
42 * Aligns all selected nodes within a circle. (Useful for roundabouts)
43 *
44 * @author Matthew Newton
45 * @author Petr Dlouhý
46 * @author Teemu Koskinen
47 * @author Alain Delplanque
48 * @author Gerd Petermann
49 *
50 * @since 146
51 */
52public final class AlignInCircleAction extends JosmAction {
53
54 /**
55 * Constructs a new {@code AlignInCircleAction}.
56 */
57 public AlignInCircleAction() {
58 super(tr("Align Nodes in Circle"), "aligncircle", tr("Move the selected nodes into a circle."),
59 Shortcut.registerShortcut("tools:aligncircle", tr("Tools: {0}", tr("Align Nodes in Circle")),
60 KeyEvent.VK_O, Shortcut.DIRECT), true);
61 setHelpId(ht("/Action/AlignInCircle"));
62 }
63
64 /**
65 * InvalidSelection exception has to be raised when action can't be performed
66 */
67 public static class InvalidSelection extends Exception {
68
69 /**
70 * Create an InvalidSelection exception with default message
71 */
72 InvalidSelection() {
73 super(tr("Selection could not be used to align in circle."));
74 }
75
76 /**
77 * Create an InvalidSelection exception with specific message
78 * @param msg Message that will be displayed to the user
79 */
80 InvalidSelection(String msg) {
81 super(msg);
82 }
83 }
84
85 /**
86 * Add a {@link MoveCommand} to move a node to a PolarCoor if there is a significant move.
87 * @param n Node to move
88 * @param coor polar coordinate where to move the node
89 * @param cmds list of commands
90 * @since 17386
91 */
92 public static void addMoveCommandIfNeeded(Node n, PolarCoor coor, List<Command> cmds) {
93 EastNorth en = coor.toEastNorth();
94 double deltaEast = en.east() - n.getEastNorth().east();
95 double deltaNorth = en.north() - n.getEastNorth().north();
96
97 if (Math.abs(deltaEast) > 5e-6 || Math.abs(deltaNorth) > 5e-6) {
98 cmds.add(new MoveCommand(n, deltaEast, deltaNorth));
99 }
100 }
101
102 /**
103 * Perform AlignInCircle action.
104 *
105 */
106 @Override
107 public void actionPerformed(ActionEvent e) {
108 if (!isEnabled())
109 return;
110
111 try {
112 Command cmd = buildCommand(getLayerManager().getEditDataSet());
113 if (cmd != null)
114 UndoRedoHandler.getInstance().add(cmd);
115 else {
116 new Notification(tr("Nothing changed"))
117 .setIcon(JOptionPane.INFORMATION_MESSAGE)
118 .setDuration(Notification.TIME_SHORT)
119 .show();
120
121 }
122 } catch (InvalidSelection except) {
123 Logging.debug(except);
124 new Notification(except.getMessage())
125 .setIcon(JOptionPane.INFORMATION_MESSAGE)
126 .setDuration(Notification.TIME_SHORT)
127 .show();
128 }
129 }
130
131 /**
132 * Builds "align in circle" command depending on the selected objects.
133 * A fixed node is a node for which it is forbidden to change the angle relative to center of the circle.
134 * All other nodes are uniformly distributed.
135 * <p>
136 * Case 1: One unclosed way.
137 * --&gt; allow action, and align selected way nodes
138 * If nodes contained by this way are selected, there are fix.
139 * If nodes outside from the way are selected there are ignored.
140 * <p>
141 * Case 2: One or more ways are selected and can be joined into a polygon
142 * --&gt; allow action, and align selected ways nodes
143 * If 1 node outside of way is selected, it became center
144 * If 1 node outside and 1 node inside are selected there define center and radius
145 * If no outside node and 2 inside nodes are selected those 2 nodes define diameter
146 * In all other cases outside nodes are ignored
147 * In all cases, selected nodes are fix, nodes with more than one referrers are fix
148 * (first referrer is the selected way)
149 * <p>
150 * Case 3: Only nodes are selected
151 * --&gt; Align these nodes, all are fix
152 * <p>
153 * Case 4: Circularize selected ways
154 * --&gt; Circularize each way of the selection.
155 * @param ds data set in which the command operates
156 * @return the resulting command to execute to perform action, or null if nothing was changed
157 * @throws InvalidSelection if selection cannot be used
158 * @since 17386
159 *
160 */
161 public static Command buildCommand(DataSet ds) throws InvalidSelection {
162 Collection<OsmPrimitive> sel = ds.getSelected();
163 List<Node> selectedNodes = new LinkedList<>();
164 // fixNodes: All nodes for which the angle relative to center should not be modified
165 Set<Node> fixNodes = new HashSet<>();
166 List<Way> ways = new LinkedList<>();
167 EastNorth center = null;
168 double radius = 0;
169
170 for (OsmPrimitive osm : sel) {
171 if (osm instanceof Node) {
172 selectedNodes.add((Node) osm);
173 } else if (osm instanceof Way) {
174 ways.add((Way) osm);
175 }
176 }
177
178 // nodes on selected ways
179 List<Node> onWay = new ArrayList<>();
180 if (!ways.isEmpty()) {
181 List<Node> potentialCenter = new ArrayList<>();
182 for (Node n : selectedNodes) {
183 if (ways.stream().anyMatch(w -> w.containsNode(n))) {
184 onWay.add(n);
185 } else {
186 potentialCenter.add(n);
187 }
188 }
189 if (potentialCenter.size() == 1) {
190 // center is given
191 center = potentialCenter.get(0).getEastNorth();
192 if (onWay.size() == 1) {
193 radius = center.distance(onWay.get(0).getEastNorth());
194 }
195 } else if (potentialCenter.size() > 1) {
196 throw new InvalidSelection(tr("Please select only one node as center."));
197 }
198
199 }
200
201 final List<Node> nodes;
202 if (ways.isEmpty()) {
203 nodes = sortByAngle(selectedNodes);
204 fixNodes.addAll(nodes);
205 } else if (ways.size() == 1 && !ways.get(0).isClosed()) {
206 // Case 1
207 Way w = ways.get(0);
208 fixNodes.add(w.firstNode());
209 fixNodes.add(w.lastNode());
210 fixNodes.addAll(onWay);
211 // Temporary closed way used to reorder nodes
212 Way closedWay = new Way(w);
213 try {
214 closedWay.addNode(w.firstNode());
215 nodes = collectNodesAnticlockwise(Collections.singletonList(closedWay));
216 } finally {
217 closedWay.setNodes(null); // see #19885
218 }
219 } else if (Multipolygon.joinWays(ways).size() == 1) {
220 // Case 2:
221 if (onWay.size() == 2) {
222 // 2 way nodes define diameter
223 EastNorth en0 = onWay.get(0).getEastNorth();
224 EastNorth en1 = onWay.get(1).getEastNorth();
225 radius = en0.distance(en1) / 2;
226 if (center == null) {
227 center = en0.getCenter(en1);
228 }
229 }
230 fixNodes.addAll(onWay);
231 nodes = collectNodesAnticlockwise(ways);
232 } else if (!ways.isEmpty() && selectedNodes.isEmpty()) {
233 List<Command> rcmds = new LinkedList<>();
234 for (Way w : ways) {
235 if (!w.isDeleted() && w.isArea()) {
236 List<Node> wnodes = w.getNodes();
237 wnodes.remove(wnodes.size() - 1);
238 if (validateGeometry(wnodes)) {
239 center = Geometry.getCenter(wnodes);
240 }
241 if (center == null) {
242 continue;
243 }
244 boolean skipThisWay = false;
245 radius = 0;
246 for (Node n : wnodes) {
247 if (!n.isLatLonKnown()) {
248 skipThisWay = true;
249 break;
250 } else {
251 radius += center.distance(n.getEastNorth());
252 }
253 }
254 if (skipThisWay) {
255 continue;
256 } else {
257 radius /= wnodes.size();
258 }
259 Command c = moveNodesCommand(wnodes, Collections.emptySet(), center, radius);
260 if (c != null) {
261 rcmds.add(c);
262 }
263 }
264 }
265 if (rcmds.isEmpty()) {
266 throw new InvalidSelection();
267 }
268 return new SequenceCommand(tr("Align each Way in Circle"), rcmds);
269 } else {
270 throw new InvalidSelection();
271 }
272 fixNodes.addAll(collectNodesWithExternReferrers(ways));
273
274 // Check if one or more nodes are outside of download area
275 if (nodes.stream().anyMatch(Node::isOutsideDownloadArea))
276 throw new InvalidSelection(tr("One or more nodes involved in this action is outside of the downloaded area."));
277
278
279 if (center == null) {
280 if (nodes.size() < 4) {
281 throw new InvalidSelection(tr("Not enough nodes to calculate center."));
282 }
283 if (validateGeometry(nodes)) {
284 // Compute the center of nodes
285 center = Geometry.getCenter(nodes);
286 }
287 if (center == null) {
288 throw new InvalidSelection(tr("Cannot determine center of circle for this geometry."));
289 }
290 }
291
292 // Now calculate the average distance to each node from the
293 // center. This method is ok as long as distances are short
294 // relative to the distance from the N or S poles.
295 if (radius == 0) {
296 for (Node n : nodes) {
297 radius += center.distance(n.getEastNorth());
298 }
299 radius = radius / nodes.size();
300 }
301 return moveNodesCommand(nodes, fixNodes, center, radius);
302 }
303
304 /**
305 * Move each node of the list of nodes to be arranged in a circle.
306 * @param nodes The list of nodes to be moved.
307 * @param fixNodes The list of nodes that must not be moved.
308 * @param center A center of the circle formed by the nodes.
309 * @param radius A radius of the circle formed by the nodes.
310 * @return the command that arranges the nodes in a circle.
311 * @since 18615
312 */
313 public static Command moveNodesCommand(
314 List<Node> nodes,
315 Set<Node> fixNodes,
316 EastNorth center,
317 double radius) {
318 List<Command> cmds = new LinkedList<>();
319
320 // Move each node to that distance from the center.
321 // Nodes that are not "fix" will be adjust making regular arcs.
322 int nodeCount = nodes.size();
323 // Search first fixed node
324 int startPosition;
325 for (startPosition = 0; startPosition < nodeCount; startPosition++) {
326 if (fixNodes.contains(nodes.get(startPosition % nodeCount)))
327 break;
328 }
329 int i = startPosition; // Start position for current arc
330 int j; // End position for current arc
331 while (i < startPosition + nodeCount) {
332 for (j = i + 1; j < startPosition + nodeCount; j++) {
333 if (fixNodes.contains(nodes.get(j % nodeCount)))
334 break;
335 }
336 Node first = nodes.get(i % nodeCount);
337 PolarCoor pcFirst = new PolarCoor(radius, PolarCoor.computeAngle(first.getEastNorth(), center), center);
338 addMoveCommandIfNeeded(first, pcFirst, cmds);
339 if (j > i + 1) {
340 double delta;
341 if (j == i + nodeCount) {
342 delta = 2 * Math.PI / nodeCount;
343 } else {
344 PolarCoor pcLast = new PolarCoor(nodes.get(j % nodeCount).getEastNorth(), center);
345 delta = pcLast.angle - pcFirst.angle;
346 if (delta < 0) // Assume each PolarCoor.angle is in range ]-pi; pi]
347 delta += 2*Math.PI;
348 delta /= j - i;
349 }
350 for (int k = i+1; k < j; k++) {
351 PolarCoor p = new PolarCoor(radius, pcFirst.angle + (k-i)*delta, center);
352 addMoveCommandIfNeeded(nodes.get(k % nodeCount), p, cmds);
353 }
354 }
355 i = j; // Update start point for next iteration
356 }
357 if (cmds.isEmpty())
358 return null;
359 return new SequenceCommand(tr("Align Nodes in Circle"), cmds);
360 }
361
362 private static List<Node> sortByAngle(final List<Node> nodes) {
363 EastNorth sum = new EastNorth(0, 0);
364 for (Node n : nodes) {
365 EastNorth en = n.getEastNorth();
366 sum = sum.add(en.east(), en.north());
367 }
368 final EastNorth simpleCenter = new EastNorth(sum.east()/nodes.size(), sum.north()/nodes.size());
369
370 SortedMap<Double, List<Node>> orderedMap = new TreeMap<>();
371 for (Node n : nodes) {
372 double angle = new PolarCoor(n.getEastNorth(), simpleCenter).angle;
373 orderedMap.computeIfAbsent(angle, k-> new ArrayList<>()).add(n);
374 }
375 return orderedMap.values().stream().flatMap(List<Node>::stream).collect(Collectors.toList());
376 }
377
378 private static boolean validateGeometry(List<Node> nodes) {
379 Way test = new Way();
380 test.setNodes(nodes);
381 if (!test.isClosed()) {
382 test.addNode(test.firstNode());
383 }
384
385 try {
386 if (CrossingWays.isSelfCrossing(test))
387 return false;
388 return !SelfIntersectingWay.isSelfIntersecting(test);
389 } finally {
390 test.setNodes(null); // see #19855
391 }
392 }
393
394 /**
395 * Collect all nodes with more than one referrer.
396 * @param ways Ways from witch nodes are selected
397 * @return List of nodes with more than one referrer
398 */
399 private static List<Node> collectNodesWithExternReferrers(List<Way> ways) {
400 return ways.stream().flatMap(w -> w.getNodes().stream()).filter(n -> n.getReferrers().size() > 1).collect(Collectors.toList());
401 }
402
403 /**
404 * Assuming all ways can be joined into polygon, create an ordered list of node.
405 * @param ways List of ways to be joined
406 * @return Nodes anticlockwise ordered
407 * @throws InvalidSelection if selection cannot be used
408 */
409 private static List<Node> collectNodesAnticlockwise(List<Way> ways) throws InvalidSelection {
410 Collection<JoinedWay> rings = Multipolygon.joinWays(ways);
411 if (rings.size() != 1)
412 throw new InvalidSelection(); // we should never get here
413 List<Node> nodes = new ArrayList<>(rings.iterator().next().getNodes());
414 if (nodes.get(0) != nodes.get(nodes.size() - 1))
415 throw new InvalidSelection();
416 if (Geometry.isClockwise(nodes))
417 Collections.reverse(nodes);
418 nodes.remove(nodes.size() - 1);
419 return nodes;
420 }
421
422 @Override
423 protected void updateEnabledState() {
424 DataSet ds = getLayerManager().getEditDataSet();
425 setEnabled(ds != null && !ds.selectionEmpty());
426 }
427
428 @Override
429 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
430 updateEnabledStateOnModifiableSelection(selection);
431 }
432}
Note: See TracBrowser for help on using the repository browser.