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

Last change on this file since 6203 was 6130, checked in by bastiK, 11 years ago

see #6963 - converted popups to notifications for all actions in the Tools menu (TODO: Simplify Way)

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