source: josm/trunk/src/org/openstreetmap/josm/actions/AlignInLineAction.java@ 8442

Last change on this file since 8442 was 8393, checked in by Don-vip, 9 years ago

see #11447 - partial revert of r8384

  • Property svn:eol-style set to native
File size: 15.8 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.HashMap;
12import java.util.HashSet;
13import java.util.List;
14import java.util.Map;
15import java.util.Set;
16
17import javax.swing.JOptionPane;
18
19import org.openstreetmap.josm.Main;
20import org.openstreetmap.josm.command.Command;
21import org.openstreetmap.josm.command.MoveCommand;
22import org.openstreetmap.josm.command.SequenceCommand;
23import org.openstreetmap.josm.data.coor.EastNorth;
24import org.openstreetmap.josm.data.osm.Node;
25import org.openstreetmap.josm.data.osm.OsmPrimitive;
26import org.openstreetmap.josm.data.osm.Way;
27import org.openstreetmap.josm.gui.Notification;
28import org.openstreetmap.josm.tools.Shortcut;
29
30/**
31 * Aligns all selected nodes into a straight line (useful for roads that should be straight, but have side roads and
32 * therefore need multiple nodes)
33 *
34 * <pre>
35 * Case 1: 1 or 2 ways selected and no nodes selected: align nodes of ways taking care of intersection.
36 * Case 2: Single node selected and no ways selected: align this node relative to all referrer ways (2 at most).
37 * Case 3: Single node and ways selected: align this node relative to selected ways.
38 * Case 4.1: Only nodes selected, part of a non-closed way: align these nodes on the line passing through the
39 * extremity nodes (most distant in the way sequence). See https://josm.openstreetmap.de/ticket/9605#comment:3
40 * Case 4.2: Only nodes selected, part of a closed way: align these nodes on the line passing through the most distant
41 * nodes.
42 * Case 4.3: Only nodes selected, part of multiple ways: align these nodes on the line passing through the most distant
43 * nodes.
44 * </pre>
45 *
46 * @author Matthew Newton
47 */
48public final class AlignInLineAction extends JosmAction {
49
50 /**
51 * Constructs a new {@code AlignInLineAction}.
52 */
53 public AlignInLineAction() {
54 super(tr("Align Nodes in Line"), "alignline", tr("Move the selected nodes in to a line."),
55 Shortcut.registerShortcut("tools:alignline", tr("Tool: {0}", tr("Align Nodes in Line")), KeyEvent.VK_L, Shortcut.DIRECT), true);
56 putValue("help", ht("/Action/AlignInLine"));
57 }
58
59 /**
60 * InvalidSelection exception has to be raised when action can't be perform
61 */
62 private static class InvalidSelection extends Exception {
63
64 /**
65 * Create an InvalidSelection exception with default message
66 */
67 public InvalidSelection() {
68 super(tr("Please select at least three nodes."));
69 }
70
71 /**
72 * Create an InvalidSelection exception with specific message
73 * @param msg Message that will be display to the user
74 */
75 public InvalidSelection(String msg) {
76 super(msg);
77 }
78 }
79
80 /**
81 * Return 2 nodes making up the line along which provided nodes must be aligned.
82 *
83 * @param nodes Nodes to be aligned.
84 * @return A array of two nodes.
85 */
86 private Node[] nodePairFurthestApart(List<Node> nodes) {
87 Node nodea = null;
88 Node nodeb = null;
89
90 // Detect if selected nodes are on the same way.
91
92 // Get ways passing though all selected nodes.
93 Set<Way> waysRef = null;
94 for(Node n: nodes) {
95 Collection<Way> ref = OsmPrimitive.getFilteredList(n.getReferrers(), Way.class);
96 if(waysRef == null)
97 waysRef = new HashSet<>(ref);
98 else
99 waysRef.retainAll(ref);
100 }
101
102 // Nodes belongs to multiple ways, return most distant nodes.
103 if (waysRef.size() != 1)
104 return nodeFurthestAppart(nodes);
105
106 // All nodes are part of the same way. See #9605.
107 Way way = waysRef.iterator().next();
108
109 if (way.isClosed()) {
110 // Align these nodes on the line passing through the most distant nodes.
111 return nodeFurthestAppart(nodes);
112 }
113
114 // The way is open, align nodes on the line passing through the extremity nodes (most distant in the way
115 // sequence). See #9605#comment:3.
116 Set<Node> remainNodes = new HashSet<>(nodes);
117 for (Node n : way.getNodes()) {
118 if (!remainNodes.contains(n))
119 continue;
120 if (nodea == null)
121 nodea = n;
122 if (remainNodes.size() == 1) {
123 nodeb = remainNodes.iterator().next();
124 break;
125 }
126 remainNodes.remove(n);
127 }
128
129 return new Node[] { nodea, nodeb };
130 }
131
132 /**
133 * Return the two nodes the most distant from the provided list.
134 *
135 * @param nodes List of nodes to analyze.
136 * @return An array containing the two most distant nodes.
137 */
138 private Node[] nodeFurthestAppart(List<Node> nodes) {
139 Node node1 = null, node2 = null;
140 double minSqDistance = 0;
141 int nb;
142
143 nb = nodes.size();
144 for (int i = 0; i < nb - 1; i++) {
145 Node n = nodes.get(i);
146 for (int j = i + 1; j < nb; j++) {
147 Node m = nodes.get(j);
148 double sqDist = n.getEastNorth().distanceSq(m.getEastNorth());
149 if (sqDist > minSqDistance) {
150 node1 = n;
151 node2 = m;
152 minSqDistance = sqDist;
153 }
154 }
155 }
156
157 return new Node[] { node1, node2 };
158 }
159
160 /**
161 * Operation depends on the selected objects:
162 */
163 @Override
164 public void actionPerformed(ActionEvent e) {
165 if (!isEnabled())
166 return;
167
168 List<Node> selectedNodes = new ArrayList<>(getCurrentDataSet().getSelectedNodes());
169 List<Way> selectedWays = new ArrayList<>(getCurrentDataSet().getSelectedWays());
170
171 try {
172 Command cmd = null;
173 // Decide what to align based on selection:
174
175 if(selectedNodes.isEmpty() && !selectedWays.isEmpty()) {
176 // Only ways selected -> For each way align their nodes taking care of intersection
177 cmd = alignMultiWay(selectedWays);
178 } else if(selectedNodes.size() == 1) {
179 // Only 1 node selected -> align this node relative to referers way
180 Node selectedNode = selectedNodes.get(0);
181 List<Way> involvedWays = null;
182 if(selectedWays.isEmpty())
183 // No selected way, all way containing this node are used
184 involvedWays = OsmPrimitive.getFilteredList(selectedNode.getReferrers(), Way.class);
185 else
186 // Selected way, use only these ways
187 involvedWays = selectedWays;
188 List<Line> lines = getInvolvedLines(selectedNode, involvedWays);
189 if(lines.size() > 2 || lines.isEmpty())
190 throw new InvalidSelection();
191 cmd = alignSingleNode(selectedNodes.get(0), lines);
192 } else if(selectedNodes.size() >= 3) {
193 // More than 3 nodes and way(s) selected -> align selected nodes. Don't care of way(s).
194 cmd = alignOnlyNodes(selectedNodes);
195 } else {
196 // All others cases are invalid
197 throw new InvalidSelection();
198 }
199
200 // Do it!
201 Main.main.undoRedo.add(cmd);
202 Main.map.repaint();
203
204 } catch (InvalidSelection except) {
205 new Notification(except.getMessage())
206 .setIcon(JOptionPane.INFORMATION_MESSAGE)
207 .show();
208 }
209 }
210
211 /**
212 * Align nodes in case 3 or more nodes are selected.
213 *
214 * @param nodes Nodes to be aligned.
215 * @return Command that perform action.
216 * @throws InvalidSelection If the nodes have same coordinates.
217 */
218 private Command alignOnlyNodes(List<Node> nodes) throws InvalidSelection {
219 // Choose nodes used as anchor points for projection.
220 Node[] anchors = nodePairFurthestApart(nodes);
221 Collection<Command> cmds = new ArrayList<>(nodes.size());
222 Line line = new Line(anchors[0], anchors[1]);
223 for(Node node: nodes)
224 if(node != anchors[0] && node != anchors[1])
225 cmds.add(line.projectionCommand(node));
226 return new SequenceCommand(tr("Align Nodes in Line"), cmds);
227 }
228
229 /**
230 * Align way in case of multiple way #6819
231 * @param ways Collection of way to align
232 * @return Command that perform action
233 * @throws InvalidSelection
234 */
235 private Command alignMultiWay(Collection<Way> ways) throws InvalidSelection {
236 // Collect all nodes and compute line equation
237 Set<Node> nodes = new HashSet<>();
238 Map<Way, Line> lines = new HashMap<>();
239 for(Way w: ways) {
240 if(w.firstNode() == w.lastNode())
241 throw new InvalidSelection(tr("Can not align a polygon. Abort."));
242 nodes.addAll(w.getNodes());
243 lines.put(w, new Line(w));
244 }
245 Collection<Command> cmds = new ArrayList<>(nodes.size());
246 List<Way> referers = new ArrayList<>(ways.size());
247 for(Node n: nodes) {
248 referers.clear();
249 for(OsmPrimitive o: n.getReferrers())
250 if(ways.contains(o))
251 referers.add((Way) o);
252 if(referers.size() == 1) {
253 Way way = referers.get(0);
254 if(n == way.firstNode() || n == way.lastNode()) continue;
255 cmds.add(lines.get(way).projectionCommand(n));
256 } else if(referers.size() == 2) {
257 Command cmd = lines.get(referers.get(0)).intersectionCommand(n, lines.get(referers.get(1)));
258 cmds.add(cmd);
259 } else
260 throw new InvalidSelection(tr("Intersection of three or more ways can not be solved. Abort."));
261 }
262 return new SequenceCommand(tr("Align Nodes in Line"), cmds);
263 }
264
265 /**
266 * Get lines useful to do alignment of a single node
267 * @param node Node to be aligned
268 * @param refWays Ways where useful lines will be searched
269 * @return List of useful lines
270 * @throws InvalidSelection
271 */
272 private List<Line> getInvolvedLines(Node node, List<Way> refWays) throws InvalidSelection {
273 List<Line> lines = new ArrayList<>();
274 List<Node> neighbors = new ArrayList<>();
275 for(Way way: refWays) {
276 List<Node> nodes = way.getNodes();
277 neighbors.clear();
278 for(int i = 1; i < nodes.size()-1; i++)
279 if(nodes.get(i) == node) {
280 neighbors.add(nodes.get(i-1));
281 neighbors.add(nodes.get(i+1));
282 }
283 if(neighbors.isEmpty())
284 continue;
285 else if(neighbors.size() == 2)
286 // Non self crossing
287 lines.add(new Line(neighbors.get(0), neighbors.get(1)));
288 else if(neighbors.size() == 4) {
289 // Self crossing, have to make 2 lines with 4 neighbors
290 // see #9081 comment 6
291 EastNorth c = node.getEastNorth();
292 double[] angle = new double[4];
293 for(int i = 0; i < 4; i++) {
294 EastNorth p = neighbors.get(i).getEastNorth();
295 angle[i] = Math.atan2(p.north() - c.north(), p.east() - c.east());
296 }
297 double[] deltaAngle = new double[3];
298 for(int i = 0; i < 3; i++) {
299 deltaAngle[i] = angle[i+1] - angle[0];
300 if(deltaAngle[i] < 0)
301 deltaAngle[i] += 2*Math.PI;
302 }
303 int nb = 0;
304 if(deltaAngle[1] < deltaAngle[0]) nb++;
305 if(deltaAngle[2] < deltaAngle[0]) nb++;
306 if(nb == 1) {
307 // Align along [neighbors[0], neighbors[1]] and [neighbors[0], neighbors[2]]
308 lines.add(new Line(neighbors.get(0), neighbors.get(1)));
309 lines.add(new Line(neighbors.get(2), neighbors.get(3)));
310 } else {
311 // Align along [neighbors[0], neighbors[2]] and [neighbors[1], neighbors[3]]
312 lines.add(new Line(neighbors.get(0), neighbors.get(2)));
313 lines.add(new Line(neighbors.get(1), neighbors.get(3)));
314 }
315 } else
316 throw new InvalidSelection();
317 }
318 return lines;
319 }
320
321 /**
322 * Align a single node relative to a set of lines #9081
323 * @param node Node to be aligned
324 * @param lines Lines to align node on
325 * @return Command that perform action
326 * @throws InvalidSelection
327 */
328 private Command alignSingleNode(Node node, List<Line> lines) throws InvalidSelection {
329 if(lines.size() == 1)
330 return lines.get(0).projectionCommand(node);
331 else if(lines.size() == 2)
332 return lines.get(0).intersectionCommand(node, lines.get(1));
333 throw new InvalidSelection();
334 }
335
336 /**
337 * Class that represent a line
338 */
339 private static class Line {
340
341 /**
342 * Line equation ax + by + c = 0
343 * Such as a^2 + b^2 = 1, ie (-b, a) is a unit vector of line
344 */
345 private double a, b, c;
346 /**
347 * (xM, yM) are coordinates of a point of the line
348 */
349 private double xM, yM;
350
351 /**
352 * Init a line by 2 nodes.
353 * @param first On point of the line
354 * @param last Other point of the line
355 * @throws InvalidSelection
356 */
357 public Line(Node first, Node last) throws InvalidSelection {
358 xM = first.getEastNorth().getX();
359 yM = first.getEastNorth().getY();
360 double xB = last.getEastNorth().getX();
361 double yB = last.getEastNorth().getY();
362 a = yB - yM;
363 b = xM - xB;
364 double norm = Math.sqrt(a*a + b*b);
365 if (norm == 0)
366 // Nodes have same coordinates !
367 throw new InvalidSelection();
368 a /= norm;
369 b /= norm;
370 c = -(a*xM + b*yM);
371 }
372
373 /**
374 * Init a line equation from a way.
375 * @param way Use extremity of this way to compute line equation
376 * @throws InvalidSelection
377 */
378 public Line(Way way) throws InvalidSelection {
379 this(way.firstNode(), way.lastNode());
380 }
381
382 /**
383 * Orthogonal projection of a node N along this line.
384 * @param n Node to be projected
385 * @return The command that do the projection of this node
386 */
387 public Command projectionCommand(Node n) {
388 double s = (xM - n.getEastNorth().getX()) * a + (yM - n.getEastNorth().getY()) * b;
389 return new MoveCommand(n, a*s, b*s);
390 }
391
392 /**
393 * Intersection of two line.
394 * @param n Node to move to the intersection
395 * @param other Second line for intersection
396 * @return The command that move the node
397 * @throws InvalidSelection
398 */
399 public Command intersectionCommand(Node n, Line other) throws InvalidSelection {
400 double d = this.a * other.b - other.a * this.b;
401 if(Math.abs(d) < 10e-6)
402 // parallels lines
403 throw new InvalidSelection(tr("Two parallels ways found. Abort."));
404 double x = (this.b * other.c - other.b * this.c) / d;
405 double y = (other.a * this.c - this.a * other.c) / d;
406 return new MoveCommand(n, x - n.getEastNorth().getX(), y - n.getEastNorth().getY());
407 }
408 }
409
410 @Override
411 protected void updateEnabledState() {
412 setEnabled(getCurrentDataSet() != null && !getCurrentDataSet().getSelected().isEmpty());
413 }
414
415 @Override
416 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
417 setEnabled(selection != null && !selection.isEmpty());
418 }
419}
Note: See TracBrowser for help on using the repository browser.