source: josm/trunk/src/org/openstreetmap/josm/actions/OrthogonalizeAction.java@ 6049

Last change on this file since 6049 was 5736, checked in by Don-vip, 11 years ago

fix #4276 - Allow to disable warning messages of orthogonalize action

  • Property svn:eol-style set to native
File size: 25.3 KB
Line 
1// License: GPL. See LICENSE file for details.
2//
3package org.openstreetmap.josm.actions;
4
5import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
6import static org.openstreetmap.josm.tools.I18n.tr;
7
8import java.awt.event.ActionEvent;
9import java.awt.event.KeyEvent;
10import java.util.ArrayList;
11import java.util.Arrays;
12import java.util.Collection;
13import java.util.Collections;
14import java.util.HashMap;
15import java.util.HashSet;
16import java.util.Iterator;
17import java.util.LinkedList;
18import java.util.List;
19import java.util.Set;
20
21import javax.swing.JOptionPane;
22
23import org.openstreetmap.josm.Main;
24import org.openstreetmap.josm.command.Command;
25import org.openstreetmap.josm.command.MoveCommand;
26import org.openstreetmap.josm.command.SequenceCommand;
27import org.openstreetmap.josm.data.coor.EastNorth;
28import org.openstreetmap.josm.data.osm.Node;
29import org.openstreetmap.josm.data.osm.OsmPrimitive;
30import org.openstreetmap.josm.data.osm.Way;
31import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
32import org.openstreetmap.josm.tools.Shortcut;
33
34/**
35 * Tools / Orthogonalize
36 *
37 * Align edges of a way so all angles are angles of 90 or 180 degrees.
38 * See USAGE String below.
39 */
40public final class OrthogonalizeAction extends JosmAction {
41 private String USAGE = tr(
42 "<h3>When one or more ways are selected, the shape is adjusted such, that all angles are 90 or 180 degrees.</h3>"+
43 "You can add two nodes to the selection. Then, the direction is fixed by these two reference nodes. "+
44 "(Afterwards, you can undo the movement for certain nodes:<br>"+
45 "Select them and press the shortcut for Orthogonalize / Undo. The default is Shift-Q.)");
46
47 /**
48 * Constructor
49 */
50 public OrthogonalizeAction() {
51 super(tr("Orthogonalize Shape"),
52 "ortho",
53 tr("Move nodes so all angles are 90 or 180 degrees"),
54 Shortcut.registerShortcut("tools:orthogonalize", tr("Tool: {0}", tr("Orthogonalize Shape")),
55 KeyEvent.VK_Q,
56 Shortcut.DIRECT), true);
57 putValue("help", ht("/Action/OrthogonalizeShape"));
58 }
59
60 /**
61 * excepted deviation from an angle of 0, 90, 180, 360 degrees
62 * maximum value: 45 degrees
63 *
64 * Current policy is to except just everything, no matter how strange the result would be.
65 */
66 private static final double TOLERANCE1 = Math.toRadians(45.); // within a way
67 private static final double TOLERANCE2 = Math.toRadians(45.); // ways relative to each other
68
69 /**
70 * Remember movements, so the user can later undo it for certain nodes
71 */
72 private static final HashMap<Node, EastNorth> rememberMovements = new HashMap<Node, EastNorth>();
73
74 /**
75 * Undo the previous orthogonalization for certain nodes.
76 *
77 * This is useful, if the way shares nodes that you don't like to change, e.g. imports or
78 * work of another user.
79 *
80 * This action can be triggered by shortcut only.
81 */
82 public static class Undo extends JosmAction {
83 /**
84 * Constructor
85 */
86 public Undo() {
87 super(tr("Orthogonalize Shape / Undo"), "ortho",
88 tr("Undo orthogonalization for certain nodes"),
89 Shortcut.registerShortcut("tools:orthogonalizeUndo", tr("Tool: {0}", tr("Orthogonalize Shape / Undo")),
90 KeyEvent.VK_Q,
91 Shortcut.SHIFT),
92 true, "action/orthogonalize/undo", true);
93 }
94 public void actionPerformed(ActionEvent e) {
95 if (!isEnabled())
96 return;
97 final Collection<Command> commands = new LinkedList<Command>();
98 final Collection<OsmPrimitive> sel = getCurrentDataSet().getSelected();
99 try {
100 for (OsmPrimitive p : sel) {
101 if (! (p instanceof Node)) throw new InvalidUserInputException();
102 Node n = (Node) p;
103 if (rememberMovements.containsKey(n)) {
104 EastNorth tmp = rememberMovements.get(n);
105 commands.add(new MoveCommand(n, - tmp.east(), - tmp.north()));
106 rememberMovements.remove(n);
107 }
108 }
109 if (commands.size() > 0) {
110 Main.main.undoRedo.add(new SequenceCommand(tr("Orthogonalize / Undo"), commands));
111 Main.map.repaint();
112 } else throw new InvalidUserInputException();
113 }
114 catch (InvalidUserInputException ex) {
115 JOptionPane.showMessageDialog(
116 Main.parent,
117 tr("Orthogonalize Shape / Undo\n"+
118 "Please select nodes that were moved by the previous Orthogonalize Shape action!"),
119 tr("Undo Orthogonalize Shape"),
120 JOptionPane.INFORMATION_MESSAGE);
121 }
122 }
123 }
124
125 public void actionPerformed(ActionEvent e) {
126 if (!isEnabled())
127 return;
128 if ("EPSG:4326".equals(Main.getProjection().toString())) {
129 String msg = tr("<html>You are using the EPSG:4326 projection which might lead<br>" +
130 "to undesirable results when doing rectangular alignments.<br>" +
131 "Change your projection to get rid of this warning.<br>" +
132 "Do you want to continue?</html>");
133 if (!ConditionalOptionPaneUtil.showConfirmationDialog(
134 "align_rectangular_4326",
135 Main.parent,
136 msg,
137 tr("Warning"),
138 JOptionPane.YES_NO_OPTION,
139 JOptionPane.QUESTION_MESSAGE,
140 JOptionPane.YES_OPTION))
141 return;
142 }
143
144 final ArrayList<Node> nodeList = new ArrayList<Node>();
145 final ArrayList<WayData> wayDataList = new ArrayList<WayData>();
146 final Collection<OsmPrimitive> sel = getCurrentDataSet().getSelected();
147
148 try {
149 // collect nodes and ways from the selection
150 for (OsmPrimitive p : sel) {
151 if (p instanceof Node) {
152 nodeList.add((Node) p);
153 }
154 else if (p instanceof Way) {
155 wayDataList.add(new WayData((Way) p));
156 } else
157 throw new InvalidUserInputException(tr("Selection must consist only of ways and nodes."));
158 }
159 if (wayDataList.isEmpty())
160 throw new InvalidUserInputException("usage");
161 else {
162 if (nodeList.size() == 2 || nodeList.isEmpty()) {
163 OrthogonalizeAction.rememberMovements.clear();
164 final Collection<Command> commands = new LinkedList<Command>();
165
166 if (nodeList.size() == 2) { // fixed direction
167 commands.addAll(orthogonalize(wayDataList, nodeList));
168 }
169 else if (nodeList.isEmpty()) {
170 List<ArrayList<WayData>> groups = buildGroups(wayDataList);
171 for (ArrayList<WayData> g: groups) {
172 commands.addAll(orthogonalize(g, nodeList));
173 }
174 } else
175 throw new IllegalStateException();
176
177 Main.main.undoRedo.add(new SequenceCommand(tr("Orthogonalize"), commands));
178 Main.map.repaint();
179
180 } else
181 throw new InvalidUserInputException("usage");
182 }
183 } catch (InvalidUserInputException ex) {
184 if (ex.getMessage().equals("usage")) {
185 ConditionalOptionPaneUtil.showMessageDialog("orthogonalize_usage",
186 Main.parent,
187 "<html><h2>" + tr("Usage") + "</h2>" + USAGE + "</html>",
188 tr("Orthogonalize Shape"),
189 JOptionPane.INFORMATION_MESSAGE);
190 }
191 else {
192 ConditionalOptionPaneUtil.showMessageDialog("orthogonalize_error",
193 Main.parent,
194 "<html>" + ex.getMessage() + "<br><hr><h2>" + tr("Usage") + "</h2>" + USAGE + "</html>",
195 tr("Selected Elements cannot be orthogonalized"),
196 JOptionPane.INFORMATION_MESSAGE);
197 }
198 }
199 }
200
201 /**
202 * Collect groups of ways with common nodes in order to orthogonalize each group separately.
203 */
204 private static List<ArrayList<WayData>> buildGroups(ArrayList<WayData> wayDataList) {
205 List<ArrayList<WayData>> groups = new ArrayList<ArrayList<WayData>>();
206 Set<WayData> remaining = new HashSet<WayData>(wayDataList);
207 while (!remaining.isEmpty()) {
208 ArrayList<WayData> group = new ArrayList<WayData>();
209 groups.add(group);
210 Iterator<WayData> it = remaining.iterator();
211 WayData next = it.next();
212 it.remove();
213 extendGroupRec(group, next, new ArrayList<WayData>(remaining));
214 remaining.removeAll(group);
215 }
216 return groups;
217 }
218
219 private static void extendGroupRec(List<WayData> group, WayData newGroupMember, List<WayData> remaining) {
220 group.add(newGroupMember);
221 for (int i = 0; i < remaining.size(); ++i) {
222 WayData candidate = remaining.get(i);
223 if (candidate == null) continue;
224 if (!Collections.disjoint(candidate.way.getNodes(), newGroupMember.way.getNodes())) {
225 remaining.set(i, null);
226 extendGroupRec(group, candidate, remaining);
227 }
228 }
229 }
230
231 /**
232 *
233 * Outline:
234 * 1. Find direction of all segments
235 * - direction = 0..3 (right,up,left,down)
236 * - right is not really right, you may have to turn your screen
237 * 2. Find average heading of all segments
238 * - heading = angle of a vector in polar coordinates
239 * - sum up horizontal segments (those with direction 0 or 2)
240 * - sum up vertical segments
241 * - turn the vertical sum by 90 degrees and add it to the horizontal sum
242 * - get the average heading from this total sum
243 * 3. Rotate all nodes by the average heading so that right is really right
244 * and all segments are approximately NS or EW.
245 * 4. If nodes are connected by a horizontal segment: Replace their y-Coordinate by
246 * the mean value of their y-Coordinates.
247 * - The same for vertical segments.
248 * 5. Rotate back.
249 *
250 **/
251 private static Collection<Command> orthogonalize(ArrayList<WayData> wayDataList, ArrayList<Node> headingNodes)
252 throws InvalidUserInputException
253 {
254 // find average heading
255 double headingAll;
256 try {
257 if (headingNodes.isEmpty()) {
258 // find directions of the segments and make them consistent between different ways
259 wayDataList.get(0).calcDirections(Direction.RIGHT);
260 double refHeading = wayDataList.get(0).heading;
261 for (WayData w : wayDataList) {
262 w.calcDirections(Direction.RIGHT);
263 int directionOffset = angleToDirectionChange(w.heading - refHeading, TOLERANCE2);
264 w.calcDirections(Direction.RIGHT.changeBy(directionOffset));
265 if (angleToDirectionChange(refHeading - w.heading, TOLERANCE2) != 0) throw new RuntimeException();
266 }
267 EastNorth totSum = new EastNorth(0., 0.);
268 for (WayData w : wayDataList) {
269 totSum = EN.sum(totSum, w.segSum);
270 }
271 headingAll = EN.polar(new EastNorth(0., 0.), totSum);
272 }
273 else {
274 headingAll = EN.polar(headingNodes.get(0).getEastNorth(), headingNodes.get(1).getEastNorth());
275 for (WayData w : wayDataList) {
276 w.calcDirections(Direction.RIGHT);
277 int directionOffset = angleToDirectionChange(w.heading - headingAll, TOLERANCE2);
278 w.calcDirections(Direction.RIGHT.changeBy(directionOffset));
279 }
280 }
281 } catch (RejectedAngleException ex) {
282 throw new InvalidUserInputException(
283 tr("<html>Please make sure all selected ways head in a similar direction<br>"+
284 "or orthogonalize them one by one.</html>"));
285 }
286
287 // put the nodes of all ways in a set
288 final HashSet<Node> allNodes = new HashSet<Node>();
289 for (WayData w : wayDataList) {
290 for (Node n : w.way.getNodes()) {
291 allNodes.add(n);
292 }
293 }
294
295 // the new x and y value for each node
296 final HashMap<Node, Double> nX = new HashMap<Node, Double>();
297 final HashMap<Node, Double> nY = new HashMap<Node, Double>();
298
299 // calculate the centroid of all nodes
300 // it is used as rotation center
301 EastNorth pivot = new EastNorth(0., 0.);
302 for (Node n : allNodes) {
303 pivot = EN.sum(pivot, n.getEastNorth());
304 }
305 pivot = new EastNorth(pivot.east() / allNodes.size(), pivot.north() / allNodes.size());
306
307 // rotate
308 for (Node n: allNodes) {
309 EastNorth tmp = EN.rotate_cc(pivot, n.getEastNorth(), - headingAll);
310 nX.put(n, tmp.east());
311 nY.put(n, tmp.north());
312 }
313
314 // orthogonalize
315 final Direction[] HORIZONTAL = {Direction.RIGHT, Direction.LEFT};
316 final Direction[] VERTICAL = {Direction.UP, Direction.DOWN};
317 final Direction[][] ORIENTATIONS = {HORIZONTAL, VERTICAL};
318 for (Direction[] orientation : ORIENTATIONS){
319 final HashSet<Node> s = new HashSet<Node>(allNodes);
320 int s_size = s.size();
321 for (int dummy = 0; dummy < s_size; ++dummy) {
322 if (s.isEmpty()) {
323 break;
324 }
325 final Node dummy_n = s.iterator().next(); // pick arbitrary element of s
326
327 final HashSet<Node> cs = new HashSet<Node>(); // will contain each node that can be reached from dummy_n
328 cs.add(dummy_n); // walking only on horizontal / vertical segments
329
330 boolean somethingHappened = true;
331 while (somethingHappened) {
332 somethingHappened = false;
333 for (WayData w : wayDataList) {
334 for (int i=0; i < w.nSeg; ++i) {
335 Node n1 = w.way.getNodes().get(i);
336 Node n2 = w.way.getNodes().get(i+1);
337 if (Arrays.asList(orientation).contains(w.segDirections[i])) {
338 if (cs.contains(n1) && ! cs.contains(n2)) {
339 cs.add(n2);
340 somethingHappened = true;
341 }
342 if (cs.contains(n2) && ! cs.contains(n1)) {
343 cs.add(n1);
344 somethingHappened = true;
345 }
346 }
347 }
348 }
349 }
350 for (Node n : cs) {
351 s.remove(n);
352 }
353
354 final HashMap<Node, Double> nC = (orientation == HORIZONTAL) ? nY : nX;
355
356 double average = 0;
357 for (Node n : cs) {
358 average += nC.get(n).doubleValue();
359 }
360 average = average / cs.size();
361
362 // if one of the nodes is a heading node, forget about the average and use its value
363 for (Node fn : headingNodes) {
364 if (cs.contains(fn)) {
365 average = nC.get(fn);
366 }
367 }
368
369 // At this point, the two heading nodes (if any) are horizontally aligned, i.e. they
370 // have the same y coordinate. So in general we shouldn't find them in a vertical string
371 // of segments. This can still happen in some pathological cases (see #7889). To avoid
372 // both heading nodes collapsing to one point, we simply skip this segment string and
373 // don't touch the node coordinates.
374 if (orientation == VERTICAL && headingNodes.size() == 2 && cs.containsAll(headingNodes)) {
375 continue;
376 }
377
378 for (Node n : cs) {
379 nC.put(n, average);
380 }
381 }
382 if (!s.isEmpty()) throw new RuntimeException();
383 }
384
385 // rotate back and log the change
386 final Collection<Command> commands = new LinkedList<Command>();
387 // OrthogonalizeAction.rememberMovements.clear();
388 for (Node n: allNodes) {
389 EastNorth tmp = new EastNorth(nX.get(n), nY.get(n));
390 tmp = EN.rotate_cc(pivot, tmp, headingAll);
391 final double dx = tmp.east() - n.getEastNorth().east();
392 final double dy = tmp.north() - n.getEastNorth().north();
393 if (headingNodes.contains(n)) { // The heading nodes should not have changed
394 final double EPSILON = 1E-6;
395 if (Math.abs(dx) > Math.abs(EPSILON * tmp.east()) ||
396 Math.abs(dy) > Math.abs(EPSILON * tmp.east()))
397 throw new AssertionError();
398 }
399 else {
400 OrthogonalizeAction.rememberMovements.put(n, new EastNorth(dx, dy));
401 commands.add(new MoveCommand(n, dx, dy));
402 }
403 }
404 return commands;
405 }
406
407 /**
408 * Class contains everything we need to know about a singe way.
409 */
410 private static class WayData {
411 final public Way way; // The assigned way
412 final public int nSeg; // Number of Segments of the Way
413 final public int nNode; // Number of Nodes of the Way
414 public Direction[] segDirections; // Direction of the segments
415 // segment i goes from node i to node (i+1)
416 public EastNorth segSum; // (Vector-)sum of all horizontal segments plus the sum of all vertical
417 // segments turned by 90 degrees
418 public double heading; // heading of segSum == approximate heading of the way
419 public WayData(Way pWay) {
420 way = pWay;
421 nNode = way.getNodes().size();
422 nSeg = nNode - 1;
423 }
424 /**
425 * Estimate the direction of the segments, given the first segment points in the
426 * direction <code>pInitialDirection</code>.
427 * Then sum up all horizontal / vertical segments to have a good guess for the
428 * heading of the entire way.
429 * @throws InvalidUserInputException
430 */
431 public void calcDirections(Direction pInitialDirection) throws InvalidUserInputException {
432 final EastNorth[] en = new EastNorth[nNode]; // alias: way.getNodes().get(i).getEastNorth() ---> en[i]
433 for (int i=0; i < nNode; i++) {
434 en[i] = new EastNorth(way.getNodes().get(i).getEastNorth().east(), way.getNodes().get(i).getEastNorth().north());
435 }
436 segDirections = new Direction[nSeg];
437 Direction direction = pInitialDirection;
438 segDirections[0] = direction;
439 for (int i=0; i < nSeg - 1; i++) {
440 double h1 = EN.polar(en[i],en[i+1]);
441 double h2 = EN.polar(en[i+1],en[i+2]);
442 try {
443 direction = direction.changeBy(angleToDirectionChange(h2 - h1, TOLERANCE1));
444 } catch (RejectedAngleException ex) {
445 throw new InvalidUserInputException(tr("Please select ways with angles of approximately 90 or 180 degrees."));
446 }
447 segDirections[i+1] = direction;
448 }
449
450 // sum up segments
451 EastNorth h = new EastNorth(0.,0.);
452 //double lh = EN.abs(h);
453 EastNorth v = new EastNorth(0.,0.);
454 //double lv = EN.abs(v);
455 for (int i = 0; i < nSeg; ++i) {
456 EastNorth segment = EN.diff(en[i+1], en[i]);
457 if (segDirections[i] == Direction.RIGHT) {
458 h = EN.sum(h,segment);
459 } else if (segDirections[i] == Direction.UP) {
460 v = EN.sum(v,segment);
461 } else if (segDirections[i] == Direction.LEFT) {
462 h = EN.diff(h,segment);
463 } else if (segDirections[i] == Direction.DOWN) {
464 v = EN.diff(v,segment);
465 } else throw new IllegalStateException();
466 /**
467 * When summing up the length of the sum vector should increase.
468 * However, it is possible to construct ways, such that this assertion fails.
469 * So only uncomment this for testing
470 **/
471 // if (segDirections[i].ordinal() % 2 == 0) {
472 // if (EN.abs(h) < lh) throw new AssertionError();
473 // lh = EN.abs(h);
474 // } else {
475 // if (EN.abs(v) < lv) throw new AssertionError();
476 // lv = EN.abs(v);
477 // }
478 }
479 // rotate the vertical vector by 90 degrees (clockwise) and add it to the horizontal vector
480 segSum = EN.sum(h, new EastNorth(v.north(), - v.east()));
481 // if (EN.abs(segSum) < lh) throw new AssertionError();
482 this.heading = EN.polar(new EastNorth(0.,0.), segSum);
483 }
484 }
485
486 private enum Direction {
487 RIGHT, UP, LEFT, DOWN;
488 public Direction changeBy(int directionChange) {
489 int tmp = (this.ordinal() + directionChange) % 4;
490 if (tmp < 0) {
491 tmp += 4; // the % operator can return negative value
492 }
493 return Direction.values()[tmp];
494 }
495 }
496
497 /**
498 * Make sure angle (up to 2*Pi) is in interval [ 0, 2*Pi ).
499 */
500 private static double standard_angle_0_to_2PI(double a) {
501 while (a >= 2 * Math.PI) {
502 a -= 2 * Math.PI;
503 }
504 while (a < 0) {
505 a += 2 * Math.PI;
506 }
507 return a;
508 }
509
510 /**
511 * Make sure angle (up to 2*Pi) is in interval ( -Pi, Pi ].
512 */
513 private static double standard_angle_mPI_to_PI(double a) {
514 while (a > Math.PI) {
515 a -= 2 * Math.PI;
516 }
517 while (a <= - Math.PI) {
518 a += 2 * Math.PI;
519 }
520 return a;
521 }
522
523 /**
524 * Class contains some auxiliary functions
525 */
526 private static class EN {
527 // rotate counter-clock-wise
528 public static EastNorth rotate_cc(EastNorth pivot, EastNorth en, double angle) {
529 double cosPhi = Math.cos(angle);
530 double sinPhi = Math.sin(angle);
531 double x = en.east() - pivot.east();
532 double y = en.north() - pivot.north();
533 double nx = cosPhi * x - sinPhi * y + pivot.east();
534 double ny = sinPhi * x + cosPhi * y + pivot.north();
535 return new EastNorth(nx, ny);
536 }
537 public static EastNorth sum(EastNorth en1, EastNorth en2) {
538 return new EastNorth(en1.east() + en2.east(), en1.north() + en2.north());
539 }
540 public static EastNorth diff(EastNorth en1, EastNorth en2) {
541 return new EastNorth(en1.east() - en2.east(), en1.north() - en2.north());
542 }
543 public static double polar(EastNorth en1, EastNorth en2) {
544 return Math.atan2(en2.north() - en1.north(), en2.east() - en1.east());
545 }
546 }
547
548 /**
549 * Recognize angle to be approximately 0, 90, 180 or 270 degrees.
550 * returns an integral value, corresponding to a counter clockwise turn:
551 */
552 private static int angleToDirectionChange(double a, double deltaMax) throws RejectedAngleException {
553 a = standard_angle_mPI_to_PI(a);
554 double d0 = Math.abs(a);
555 double d90 = Math.abs(a - Math.PI / 2);
556 double d_m90 = Math.abs(a + Math.PI / 2);
557 int dirChange;
558 if (d0 < deltaMax) {
559 dirChange = 0;
560 } else if (d90 < deltaMax) {
561 dirChange = 1;
562 } else if (d_m90 < deltaMax) {
563 dirChange = -1;
564 } else {
565 a = standard_angle_0_to_2PI(a);
566 double d180 = Math.abs(a - Math.PI);
567 if (d180 < deltaMax) {
568 dirChange = 2;
569 } else
570 throw new RejectedAngleException();
571 }
572 return dirChange;
573 }
574
575 /**
576 * Exception: unsuited user input
577 */
578 private static class InvalidUserInputException extends Exception {
579 InvalidUserInputException(String message) {
580 super(message);
581 }
582 InvalidUserInputException() {
583 super();
584 }
585 }
586 /**
587 * Exception: angle cannot be recognized as 0, 90, 180 or 270 degrees
588 */
589 private static class RejectedAngleException extends Exception {
590 RejectedAngleException() {
591 super();
592 }
593 }
594
595 /**
596 * Don't check, if the current selection is suited for orthogonalization.
597 * Instead, show a usage dialog, that explains, why it cannot be done.
598 */
599 @Override
600 protected void updateEnabledState() {
601 setEnabled(getCurrentDataSet() != null);
602 }
603}
Note: See TracBrowser for help on using the repository browser.