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

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

code style - Close curly brace and the next "else", "catch" and "finally" keywords should be located on the same line

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