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

Last change on this file since 16119 was 16119, checked in by Don-vip, 4 years ago

fix #18928 - fix various crashes with empty ways

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