source: josm/trunk/src/org/openstreetmap/josm/actions/JoinAreasAction.java@ 6993

Last change on this file since 6993 was 6987, checked in by Don-vip, 10 years ago

sonar - fix some more issues

  • Property svn:eol-style set to native
File size: 50.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
8import java.awt.event.ActionEvent;
9import java.awt.event.KeyEvent;
10import java.util.ArrayList;
11import java.util.Collection;
12import java.util.Collections;
13import java.util.HashMap;
14import java.util.HashSet;
15import java.util.LinkedHashSet;
16import java.util.LinkedList;
17import java.util.List;
18import java.util.Map;
19import java.util.Set;
20import java.util.TreeMap;
21
22import javax.swing.JOptionPane;
23
24import org.openstreetmap.josm.Main;
25import org.openstreetmap.josm.actions.ReverseWayAction.ReverseWayResult;
26import org.openstreetmap.josm.actions.SplitWayAction.SplitWayResult;
27import org.openstreetmap.josm.command.AddCommand;
28import org.openstreetmap.josm.command.ChangeCommand;
29import org.openstreetmap.josm.command.Command;
30import org.openstreetmap.josm.command.DeleteCommand;
31import org.openstreetmap.josm.command.SequenceCommand;
32import org.openstreetmap.josm.corrector.UserCancelException;
33import org.openstreetmap.josm.data.UndoRedoHandler;
34import org.openstreetmap.josm.data.coor.EastNorth;
35import org.openstreetmap.josm.data.osm.DataSet;
36import org.openstreetmap.josm.data.osm.Node;
37import org.openstreetmap.josm.data.osm.NodePositionComparator;
38import org.openstreetmap.josm.data.osm.OsmPrimitive;
39import org.openstreetmap.josm.data.osm.Relation;
40import org.openstreetmap.josm.data.osm.RelationMember;
41import org.openstreetmap.josm.data.osm.TagCollection;
42import org.openstreetmap.josm.data.osm.Way;
43import org.openstreetmap.josm.gui.Notification;
44import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog;
45import org.openstreetmap.josm.tools.Geometry;
46import org.openstreetmap.josm.tools.Pair;
47import org.openstreetmap.josm.tools.Shortcut;
48
49/**
50 * Join Areas (i.e. closed ways and multipolygons)
51 */
52public class JoinAreasAction extends JosmAction {
53 // This will be used to commit commands and unite them into one large command sequence at the end
54 private final LinkedList<Command> cmds = new LinkedList<Command>();
55 private int cmdsCount = 0;
56 private final List<Relation> addedRelations = new LinkedList<Relation>();
57
58 /**
59 * This helper class describes join ares action result.
60 * @author viesturs
61 *
62 */
63 public static class JoinAreasResult {
64
65 public boolean hasChanges;
66
67 public List<Multipolygon> polygons;
68 }
69
70 public static class Multipolygon {
71 public Way outerWay;
72 public List<Way> innerWays;
73
74 public Multipolygon(Way way) {
75 outerWay = way;
76 innerWays = new ArrayList<Way>();
77 }
78 }
79
80 // HelperClass
81 // Saves a relation and a role an OsmPrimitve was part of until it was stripped from all relations
82 private static class RelationRole {
83 public final Relation rel;
84 public final String role;
85 public RelationRole(Relation rel, String role) {
86 this.rel = rel;
87 this.role = role;
88 }
89
90 @Override
91 public int hashCode() {
92 return rel.hashCode();
93 }
94
95 @Override
96 public boolean equals(Object other) {
97 if (!(other instanceof RelationRole)) return false;
98 RelationRole otherMember = (RelationRole) other;
99 return otherMember.role.equals(role) && otherMember.rel.equals(rel);
100 }
101 }
102
103
104 /**
105 * HelperClass - saves a way and the "inside" side.
106 *
107 * insideToTheLeft: if true left side is "in", false -right side is "in".
108 * Left and right are determined along the orientation of way.
109 */
110 public static class WayInPolygon {
111 public final Way way;
112 public boolean insideToTheRight;
113
114 public WayInPolygon(Way way, boolean insideRight) {
115 this.way = way;
116 this.insideToTheRight = insideRight;
117 }
118
119 @Override
120 public int hashCode() {
121 return way.hashCode();
122 }
123
124 @Override
125 public boolean equals(Object other) {
126 if (!(other instanceof WayInPolygon)) return false;
127 WayInPolygon otherMember = (WayInPolygon) other;
128 return otherMember.way.equals(this.way) && otherMember.insideToTheRight == this.insideToTheRight;
129 }
130 }
131
132 /**
133 * This helper class describes a polygon, assembled from several ways.
134 * @author viesturs
135 *
136 */
137 public static class AssembledPolygon {
138 public List<WayInPolygon> ways;
139
140 public AssembledPolygon(List<WayInPolygon> boundary) {
141 this.ways = boundary;
142 }
143
144 public List<Node> getNodes() {
145 List<Node> nodes = new ArrayList<Node>();
146 for (WayInPolygon way : this.ways) {
147 //do not add the last node as it will be repeated in the next way
148 if (way.insideToTheRight) {
149 for (int pos = 0; pos < way.way.getNodesCount() - 1; pos++) {
150 nodes.add(way.way.getNode(pos));
151 }
152 }
153 else {
154 for (int pos = way.way.getNodesCount() - 1; pos > 0; pos--) {
155 nodes.add(way.way.getNode(pos));
156 }
157 }
158 }
159
160 return nodes;
161 }
162
163 /**
164 * Inverse inside and outside
165 */
166 public void reverse() {
167 for(WayInPolygon way: ways)
168 way.insideToTheRight = !way.insideToTheRight;
169 Collections.reverse(ways);
170 }
171 }
172
173 public static class AssembledMultipolygon {
174 public AssembledPolygon outerWay;
175 public List<AssembledPolygon> innerWays;
176
177 public AssembledMultipolygon(AssembledPolygon way) {
178 outerWay = way;
179 innerWays = new ArrayList<AssembledPolygon>();
180 }
181 }
182
183 /**
184 * This hepler class implements algorithm traversing trough connected ways.
185 * Assumes you are going in clockwise orientation.
186 * @author viesturs
187 *
188 */
189 private static class WayTraverser {
190
191 private Set<WayInPolygon> availableWays;
192 private WayInPolygon lastWay;
193 private boolean lastWayReverse;
194
195 public WayTraverser(Collection<WayInPolygon> ways) {
196
197 availableWays = new HashSet<WayInPolygon>(ways);
198 lastWay = null;
199 }
200
201 public void removeWays(Collection<WayInPolygon> ways) {
202 availableWays.removeAll(ways);
203 }
204
205 public void removeWay(WayInPolygon way) {
206 availableWays.remove(way);
207 }
208
209 public void setStartWay(WayInPolygon way) {
210 lastWay = way;
211 lastWayReverse = !way.insideToTheRight;
212 }
213
214 public WayInPolygon startNewWay() {
215 if (availableWays.isEmpty()) {
216 lastWay = null;
217 } else {
218 lastWay = availableWays.iterator().next();
219 lastWayReverse = !lastWay.insideToTheRight;
220 }
221
222 return lastWay;
223 }
224
225 /**
226 * Get the next way creating a clockwise path, ensure it is the most right way. #7959
227 * @return The next way.
228 */
229 public WayInPolygon walk() {
230 Node headNode = !lastWayReverse ? lastWay.way.lastNode() : lastWay.way.firstNode();
231 Node prevNode = !lastWayReverse ? lastWay.way.getNode(lastWay.way.getNodesCount() - 2) : lastWay.way.getNode(1);
232
233 double headAngle = Math.atan2(headNode.getEastNorth().east() - prevNode.getEastNorth().east(),
234 headNode.getEastNorth().north() - prevNode.getEastNorth().north());
235 double bestAngle = 0;
236
237 //find best next way
238 WayInPolygon bestWay = null;
239 boolean bestWayReverse = false;
240
241 for (WayInPolygon way : availableWays) {
242 Node nextNode;
243
244 // Check for a connected way
245 if (way.way.firstNode().equals(headNode) && way.insideToTheRight) {
246 nextNode = way.way.getNode(1);
247 } else if (way.way.lastNode().equals(headNode) && !way.insideToTheRight) {
248 nextNode = way.way.getNode(way.way.getNodesCount() - 2);
249 } else {
250 continue;
251 }
252
253 if(nextNode == prevNode) {
254 // go back
255 lastWay = way;
256 lastWayReverse = !way.insideToTheRight;
257 return lastWay;
258 }
259
260 double angle = Math.atan2(nextNode.getEastNorth().east() - headNode.getEastNorth().east(),
261 nextNode.getEastNorth().north() - headNode.getEastNorth().north()) - headAngle;
262 if(angle > Math.PI)
263 angle -= 2*Math.PI;
264 if(angle <= -Math.PI)
265 angle += 2*Math.PI;
266
267 // Now we have a valid candidate way, is it better than the previous one ?
268 if (bestWay == null || angle > bestAngle) {
269 //the new way is better
270 bestWay = way;
271 bestWayReverse = !way.insideToTheRight;
272 bestAngle = angle;
273 }
274 }
275
276 lastWay = bestWay;
277 lastWayReverse = bestWayReverse;
278
279 return lastWay;
280 }
281 }
282
283 /**
284 * Helper storage class for finding findOuterWays
285 * @author viesturs
286 */
287 static class PolygonLevel {
288 public final int level;
289 public final AssembledMultipolygon pol;
290
291 public PolygonLevel(AssembledMultipolygon pol, int level) {
292 this.pol = pol;
293 this.level = level;
294 }
295 }
296
297 /**
298 * Constructs a new {@code JoinAreasAction}.
299 */
300 public JoinAreasAction() {
301 super(tr("Join overlapping Areas"), "joinareas", tr("Joins areas that overlap each other"),
302 Shortcut.registerShortcut("tools:joinareas", tr("Tool: {0}", tr("Join overlapping Areas")),
303 KeyEvent.VK_J, Shortcut.SHIFT), true);
304 }
305
306 /**
307 * Gets called whenever the shortcut is pressed or the menu entry is selected
308 * Checks whether the selected objects are suitable to join and joins them if so
309 */
310 @Override
311 public void actionPerformed(ActionEvent e) {
312 LinkedList<Way> ways = new LinkedList<Way>(Main.main.getCurrentDataSet().getSelectedWays());
313 addedRelations.clear();
314
315 if (ways.isEmpty()) {
316 new Notification(
317 tr("Please select at least one closed way that should be joined."))
318 .setIcon(JOptionPane.INFORMATION_MESSAGE)
319 .show();
320 return;
321 }
322
323 List<Node> allNodes = new ArrayList<Node>();
324 for (Way way : ways) {
325 if (!way.isClosed()) {
326 new Notification(
327 tr("One of the selected ways is not closed and therefore cannot be joined."))
328 .setIcon(JOptionPane.INFORMATION_MESSAGE)
329 .show();
330 return;
331 }
332
333 allNodes.addAll(way.getNodes());
334 }
335
336 // TODO: Only display this warning when nodes outside dataSourceArea are deleted
337 boolean ok = Command.checkAndConfirmOutlyingOperation("joinarea", tr("Join area confirmation"),
338 trn("The selected way has nodes outside of the downloaded data region.",
339 "The selected ways have nodes outside of the downloaded data region.",
340 ways.size()) + "<br/>"
341 + tr("This can lead to nodes being deleted accidentally.") + "<br/>"
342 + tr("Are you really sure to continue?")
343 + tr("Please abort if you are not sure"),
344 tr("The selected area is incomplete. Continue?"),
345 allNodes, null);
346 if(!ok) return;
347
348 //analyze multipolygon relations and collect all areas
349 List<Multipolygon> areas = collectMultipolygons(ways);
350
351 if (areas == null)
352 //too complex multipolygon relations found
353 return;
354
355 if (!testJoin(areas)) {
356 new Notification(
357 tr("No intersection found. Nothing was changed."))
358 .setIcon(JOptionPane.INFORMATION_MESSAGE)
359 .show();
360 return;
361 }
362
363 if (!resolveTagConflicts(areas))
364 return;
365 //user canceled, do nothing.
366
367 try {
368 JoinAreasResult result = joinAreas(areas);
369
370 if (result.hasChanges) {
371 // move tags from ways to newly created relations
372 // TODO: do we need to also move tags for the modified relations?
373 for (Relation r: addedRelations) {
374 cmds.addAll(CreateMultipolygonAction.removeTagsFromWaysIfNeeded(r));
375 }
376 commitCommands(tr("Move tags from ways to relations"));
377
378 List<Way> allWays = new ArrayList<Way>();
379 for (Multipolygon pol : result.polygons) {
380 allWays.add(pol.outerWay);
381 allWays.addAll(pol.innerWays);
382 }
383 DataSet ds = Main.main.getCurrentDataSet();
384 ds.setSelected(allWays);
385 Main.map.mapView.repaint();
386 } else {
387 new Notification(
388 tr("No intersection found. Nothing was changed."))
389 .setIcon(JOptionPane.INFORMATION_MESSAGE)
390 .show();
391 }
392 }
393 catch (UserCancelException exception) {
394 //revert changes
395 //FIXME: this is dirty hack
396 makeCommitsOneAction(tr("Reverting changes"));
397 Main.main.undoRedo.undo();
398 Main.main.undoRedo.redoCommands.clear();
399 }
400 }
401
402 /**
403 * Tests if the areas have some intersections to join.
404 * @param areas Areas to test
405 * @return {@code true} if areas are joinable
406 */
407 private boolean testJoin(List<Multipolygon> areas) {
408 List<Way> allStartingWays = new ArrayList<Way>();
409
410 for (Multipolygon area : areas) {
411 allStartingWays.add(area.outerWay);
412 allStartingWays.addAll(area.innerWays);
413 }
414
415 //find intersection points
416 Set<Node> nodes = Geometry.addIntersections(allStartingWays, true, cmds);
417 return !nodes.isEmpty();
418 }
419
420 /**
421 * Will join two or more overlapping areas
422 * @param areas list of areas to join
423 * @return new area formed.
424 */
425 private JoinAreasResult joinAreas(List<Multipolygon> areas) throws UserCancelException {
426
427 JoinAreasResult result = new JoinAreasResult();
428 result.hasChanges = false;
429
430 List<Way> allStartingWays = new ArrayList<Way>();
431 List<Way> innerStartingWays = new ArrayList<Way>();
432 List<Way> outerStartingWays = new ArrayList<Way>();
433
434 for (Multipolygon area : areas) {
435 outerStartingWays.add(area.outerWay);
436 innerStartingWays.addAll(area.innerWays);
437 }
438
439 allStartingWays.addAll(innerStartingWays);
440 allStartingWays.addAll(outerStartingWays);
441
442 //first remove nodes in the same coordinate
443 boolean removedDuplicates = false;
444 removedDuplicates |= removeDuplicateNodes(allStartingWays);
445
446 if (removedDuplicates) {
447 result.hasChanges = true;
448 commitCommands(marktr("Removed duplicate nodes"));
449 }
450
451 //find intersection points
452 Set<Node> nodes = Geometry.addIntersections(allStartingWays, false, cmds);
453
454 //no intersections, return.
455 if (nodes.isEmpty())
456 return result;
457 commitCommands(marktr("Added node on all intersections"));
458
459 List<RelationRole> relations = new ArrayList<RelationRole>();
460
461 // Remove ways from all relations so ways can be combined/split quietly
462 for (Way way : allStartingWays) {
463 relations.addAll(removeFromAllRelations(way));
464 }
465
466 // Don't warn now, because it will really look corrupted
467 boolean warnAboutRelations = !relations.isEmpty() && allStartingWays.size() > 1;
468
469 List<WayInPolygon> preparedWays = new ArrayList<WayInPolygon>();
470
471 for (Way way : outerStartingWays) {
472 List<Way> splitWays = splitWayOnNodes(way, nodes);
473 preparedWays.addAll(markWayInsideSide(splitWays, false));
474 }
475
476 for (Way way : innerStartingWays) {
477 List<Way> splitWays = splitWayOnNodes(way, nodes);
478 preparedWays.addAll(markWayInsideSide(splitWays, true));
479 }
480
481 // Find boundary ways
482 List<Way> discardedWays = new ArrayList<Way>();
483 List<AssembledPolygon> bounadries = findBoundaryPolygons(preparedWays, discardedWays);
484
485 //find polygons
486 List<AssembledMultipolygon> preparedPolygons = findPolygons(bounadries);
487
488
489 //assemble final polygons
490 List<Multipolygon> polygons = new ArrayList<Multipolygon>();
491 Set<Relation> relationsToDelete = new LinkedHashSet<Relation>();
492
493 for (AssembledMultipolygon pol : preparedPolygons) {
494
495 //create the new ways
496 Multipolygon resultPol = joinPolygon(pol);
497
498 //create multipolygon relation, if necessary.
499 RelationRole ownMultipolygonRelation = addOwnMultigonRelation(resultPol.innerWays, resultPol.outerWay);
500
501 //add back the original relations, merged with our new multipolygon relation
502 fixRelations(relations, resultPol.outerWay, ownMultipolygonRelation, relationsToDelete);
503
504 //strip tags from inner ways
505 //TODO: preserve tags on existing inner ways
506 stripTags(resultPol.innerWays);
507
508 polygons.add(resultPol);
509 }
510
511 commitCommands(marktr("Assemble new polygons"));
512
513 for(Relation rel: relationsToDelete) {
514 cmds.add(new DeleteCommand(rel));
515 }
516
517 commitCommands(marktr("Delete relations"));
518
519 // Delete the discarded inner ways
520 if (!discardedWays.isEmpty()) {
521 Command deleteCmd = DeleteCommand.delete(Main.main.getEditLayer(), discardedWays, true);
522 if (deleteCmd != null) {
523 cmds.add(deleteCmd);
524 commitCommands(marktr("Delete Ways that are not part of an inner multipolygon"));
525 }
526 }
527
528 makeCommitsOneAction(marktr("Joined overlapping areas"));
529
530 if (warnAboutRelations) {
531 new Notification(
532 tr("Some of the ways were part of relations that have been modified.<br>Please verify no errors have been introduced."))
533 .setIcon(JOptionPane.INFORMATION_MESSAGE)
534 .setDuration(Notification.TIME_LONG)
535 .show();
536 }
537
538 result.hasChanges = true;
539 result.polygons = polygons;
540 return result;
541 }
542
543 /**
544 * Checks if tags of two given ways differ, and presents the user a dialog to solve conflicts
545 * @param polygons ways to check
546 * @return {@code true} if all conflicts are resolved, {@code false} if conflicts remain.
547 */
548 private boolean resolveTagConflicts(List<Multipolygon> polygons) {
549
550 List<Way> ways = new ArrayList<Way>();
551
552 for (Multipolygon pol : polygons) {
553 ways.add(pol.outerWay);
554 ways.addAll(pol.innerWays);
555 }
556
557 if (ways.size() < 2) {
558 return true;
559 }
560
561 TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
562 try {
563 cmds.addAll(CombinePrimitiveResolverDialog.launchIfNecessary(wayTags, ways, ways));
564 commitCommands(marktr("Fix tag conflicts"));
565 return true;
566 } catch (UserCancelException ex) {
567 return false;
568 }
569 }
570
571 /**
572 * This method removes duplicate points (if any) from the input way.
573 * @param ways the ways to process
574 * @return {@code true} if any changes where made
575 */
576 private boolean removeDuplicateNodes(List<Way> ways) {
577 //TODO: maybe join nodes with JoinNodesAction, rather than reconnect the ways.
578
579 Map<Node, Node> nodeMap = new TreeMap<Node, Node>(new NodePositionComparator());
580 int totalNodesRemoved = 0;
581
582 for (Way way : ways) {
583 if (way.getNodes().size() < 2) {
584 continue;
585 }
586
587 int nodesRemoved = 0;
588 List<Node> newNodes = new ArrayList<Node>();
589 Node prevNode = null;
590
591 for (Node node : way.getNodes()) {
592 if (!nodeMap.containsKey(node)) {
593 //new node
594 nodeMap.put(node, node);
595
596 //avoid duplicate nodes
597 if (prevNode != node) {
598 newNodes.add(node);
599 } else {
600 nodesRemoved ++;
601 }
602 } else {
603 //node with same coordinates already exists, substitute with existing node
604 Node representator = nodeMap.get(node);
605
606 if (representator != node) {
607 nodesRemoved ++;
608 }
609
610 //avoid duplicate node
611 if (prevNode != representator) {
612 newNodes.add(representator);
613 }
614 }
615 prevNode = node;
616 }
617
618 if (nodesRemoved > 0) {
619
620 if (newNodes.size() == 1) { //all nodes in the same coordinate - add one more node, to have closed way.
621 newNodes.add(newNodes.get(0));
622 }
623
624 Way newWay=new Way(way);
625 newWay.setNodes(newNodes);
626 cmds.add(new ChangeCommand(way, newWay));
627 totalNodesRemoved += nodesRemoved;
628 }
629 }
630
631 return totalNodesRemoved > 0;
632 }
633
634 /**
635 * Commits the command list with a description
636 * @param description The description of what the commands do
637 */
638 private void commitCommands(String description) {
639 switch(cmds.size()) {
640 case 0:
641 return;
642 case 1:
643 Main.main.undoRedo.add(cmds.getFirst());
644 break;
645 default:
646 Command c = new SequenceCommand(tr(description), cmds);
647 Main.main.undoRedo.add(c);
648 break;
649 }
650
651 cmds.clear();
652 cmdsCount++;
653 }
654
655 /**
656 * This method analyzes the way and assigns each part what direction polygon "inside" is.
657 * @param parts the split parts of the way
658 * @param isInner - if true, reverts the direction (for multipolygon islands)
659 * @return list of parts, marked with the inside orientation.
660 */
661 private List<WayInPolygon> markWayInsideSide(List<Way> parts, boolean isInner) {
662
663 List<WayInPolygon> result = new ArrayList<WayInPolygon>();
664
665 //prepare prev and next maps
666 Map<Way, Way> nextWayMap = new HashMap<Way, Way>();
667 Map<Way, Way> prevWayMap = new HashMap<Way, Way>();
668
669 for (int pos = 0; pos < parts.size(); pos ++) {
670
671 if (!parts.get(pos).lastNode().equals(parts.get((pos + 1) % parts.size()).firstNode()))
672 throw new RuntimeException("Way not circular");
673
674 nextWayMap.put(parts.get(pos), parts.get((pos + 1) % parts.size()));
675 prevWayMap.put(parts.get(pos), parts.get((pos + parts.size() - 1) % parts.size()));
676 }
677
678 //find the node with minimum y - it's guaranteed to be outer. (What about the south pole?)
679 Way topWay = null;
680 Node topNode = null;
681 int topIndex = 0;
682 double minY = Double.POSITIVE_INFINITY;
683
684 for (Way way : parts) {
685 for (int pos = 0; pos < way.getNodesCount(); pos ++) {
686 Node node = way.getNode(pos);
687
688 if (node.getEastNorth().getY() < minY) {
689 minY = node.getEastNorth().getY();
690 topWay = way;
691 topNode = node;
692 topIndex = pos;
693 }
694 }
695 }
696
697 //get the upper way and it's orientation.
698
699 boolean wayClockwise; // orientation of the top way.
700
701 if (topNode.equals(topWay.firstNode()) || topNode.equals(topWay.lastNode())) {
702 Node headNode = null; // the node at junction
703 Node prevNode = null; // last node from previous path
704 wayClockwise = false;
705
706 //node is in split point - find the outermost way from this point
707
708 headNode = topNode;
709 //make a fake node that is downwards from head node (smaller Y). It will be a division point between paths.
710 prevNode = new Node(new EastNorth(headNode.getEastNorth().getX(), headNode.getEastNorth().getY() - 1e5));
711
712 topWay = null;
713 wayClockwise = false;
714 Node bestWayNextNode = null;
715
716 for (Way way : parts) {
717 if (way.firstNode().equals(headNode)) {
718 Node nextNode = way.getNode(1);
719
720 if (topWay == null || !Geometry.isToTheRightSideOfLine(prevNode, headNode, bestWayNextNode, nextNode)) {
721 //the new way is better
722 topWay = way;
723 wayClockwise = true;
724 bestWayNextNode = nextNode;
725 }
726 }
727
728 if (way.lastNode().equals(headNode)) {
729 //end adjacent to headNode
730 Node nextNode = way.getNode(way.getNodesCount() - 2);
731
732 if (topWay == null || !Geometry.isToTheRightSideOfLine(prevNode, headNode, bestWayNextNode, nextNode)) {
733 //the new way is better
734 topWay = way;
735 wayClockwise = false;
736 bestWayNextNode = nextNode;
737 }
738 }
739 }
740 } else {
741 //node is inside way - pick the clockwise going end.
742 Node prev = topWay.getNode(topIndex - 1);
743 Node next = topWay.getNode(topIndex + 1);
744
745 //there will be no parallel segments in the middle of way, so all fine.
746 wayClockwise = Geometry.angleIsClockwise(prev, topNode, next);
747 }
748
749 Way curWay = topWay;
750 boolean curWayInsideToTheRight = wayClockwise ^ isInner;
751
752 //iterate till full circle is reached
753 while (true) {
754
755 //add cur way
756 WayInPolygon resultWay = new WayInPolygon(curWay, curWayInsideToTheRight);
757 result.add(resultWay);
758
759 //process next way
760 Way nextWay = nextWayMap.get(curWay);
761 Node prevNode = curWay.getNode(curWay.getNodesCount() - 2);
762 Node headNode = curWay.lastNode();
763 Node nextNode = nextWay.getNode(1);
764
765 if (nextWay == topWay) {
766 //full loop traversed - all done.
767 break;
768 }
769
770 //find intersecting segments
771 // the intersections will look like this:
772 //
773 // ^
774 // |
775 // X wayBNode
776 // |
777 // wayB |
778 // |
779 // curWay | nextWay
780 //----X----------------->X----------------------X---->
781 // prevNode ^headNode nextNode
782 // |
783 // |
784 // wayA |
785 // |
786 // X wayANode
787 // |
788
789 int intersectionCount = 0;
790
791 for (Way wayA : parts) {
792
793 if (wayA == curWay) {
794 continue;
795 }
796
797 if (wayA.lastNode().equals(headNode)) {
798
799 Way wayB = nextWayMap.get(wayA);
800
801 //test if wayA is opposite wayB relative to curWay and nextWay
802
803 Node wayANode = wayA.getNode(wayA.getNodesCount() - 2);
804 Node wayBNode = wayB.getNode(1);
805
806 boolean wayAToTheRight = Geometry.isToTheRightSideOfLine(prevNode, headNode, nextNode, wayANode);
807 boolean wayBToTheRight = Geometry.isToTheRightSideOfLine(prevNode, headNode, nextNode, wayBNode);
808
809 if (wayAToTheRight != wayBToTheRight) {
810 intersectionCount ++;
811 }
812 }
813 }
814
815 //if odd number of crossings, invert orientation
816 if (intersectionCount % 2 != 0) {
817 curWayInsideToTheRight = !curWayInsideToTheRight;
818 }
819
820 curWay = nextWay;
821 }
822
823 return result;
824 }
825
826 /**
827 * This is a method splits way into smaller parts, using the prepared nodes list as split points.
828 * Uses SplitWayAction.splitWay for the heavy lifting.
829 * @return list of split ways (or original ways if no splitting is done).
830 */
831 private List<Way> splitWayOnNodes(Way way, Set<Node> nodes) {
832
833 List<Way> result = new ArrayList<Way>();
834 List<List<Node>> chunks = buildNodeChunks(way, nodes);
835
836 if (chunks.size() > 1) {
837 SplitWayResult split = SplitWayAction.splitWay(Main.main.getEditLayer(), way, chunks, Collections.<OsmPrimitive>emptyList());
838
839 //execute the command, we need the results
840 cmds.add(split.getCommand());
841 commitCommands(marktr("Split ways into fragments"));
842
843 result.add(split.getOriginalWay());
844 result.addAll(split.getNewWays());
845 } else {
846 //nothing to split
847 result.add(way);
848 }
849
850 return result;
851 }
852
853 /**
854 * Simple chunking version. Does not care about circular ways and result being
855 * proper, we will glue it all back together later on.
856 * @param way the way to chunk
857 * @param splitNodes the places where to cut.
858 * @return list of node paths to produce.
859 */
860 private List<List<Node>> buildNodeChunks(Way way, Collection<Node> splitNodes) {
861 List<List<Node>> result = new ArrayList<List<Node>>();
862 List<Node> curList = new ArrayList<Node>();
863
864 for (Node node : way.getNodes()) {
865 curList.add(node);
866 if (curList.size() > 1 && splitNodes.contains(node)) {
867 result.add(curList);
868 curList = new ArrayList<Node>();
869 curList.add(node);
870 }
871 }
872
873 if (curList.size() > 1) {
874 result.add(curList);
875 }
876
877 return result;
878 }
879
880
881 /**
882 * This method finds which ways are outer and which are inner.
883 * @param boundaries list of joined boundaries to search in
884 * @return outer ways
885 */
886 private List<AssembledMultipolygon> findPolygons(Collection<AssembledPolygon> boundaries) {
887
888 List<PolygonLevel> list = findOuterWaysImpl(0, boundaries);
889 List<AssembledMultipolygon> result = new ArrayList<AssembledMultipolygon>();
890
891 //take every other level
892 for (PolygonLevel pol : list) {
893 if (pol.level % 2 == 0) {
894 result.add(pol.pol);
895 }
896 }
897
898 return result;
899 }
900
901 /**
902 * Collects outer way and corresponding inner ways from all boundaries.
903 * @param level depth level
904 * @param boundaryWays
905 * @return the outermostWay.
906 */
907 private List<PolygonLevel> findOuterWaysImpl(int level, Collection<AssembledPolygon> boundaryWays) {
908
909 //TODO: bad performance for deep nestings...
910 List<PolygonLevel> result = new ArrayList<PolygonLevel>();
911
912 for (AssembledPolygon outerWay : boundaryWays) {
913
914 boolean outerGood = true;
915 List<AssembledPolygon> innerCandidates = new ArrayList<AssembledPolygon>();
916
917 for (AssembledPolygon innerWay : boundaryWays) {
918 if (innerWay == outerWay) {
919 continue;
920 }
921
922 if (wayInsideWay(outerWay, innerWay)) {
923 outerGood = false;
924 break;
925 } else if (wayInsideWay(innerWay, outerWay)) {
926 innerCandidates.add(innerWay);
927 }
928 }
929
930 if (!outerGood) {
931 continue;
932 }
933
934 //add new outer polygon
935 AssembledMultipolygon pol = new AssembledMultipolygon(outerWay);
936 PolygonLevel polLev = new PolygonLevel(pol, level);
937
938 //process inner ways
939 if (!innerCandidates.isEmpty()) {
940 List<PolygonLevel> innerList = findOuterWaysImpl(level + 1, innerCandidates);
941 result.addAll(innerList);
942
943 for (PolygonLevel pl : innerList) {
944 if (pl.level == level + 1) {
945 pol.innerWays.add(pl.pol.outerWay);
946 }
947 }
948 }
949
950 result.add(polLev);
951 }
952
953 return result;
954 }
955
956 /**
957 * Finds all ways that form inner or outer boundaries.
958 * @param multigonWays A list of (splitted) ways that form a multigon and share common end nodes on intersections.
959 * @param discardedResult this list is filled with ways that are to be discarded
960 * @return A list of ways that form the outer and inner boundaries of the multigon.
961 */
962 public static List<AssembledPolygon> findBoundaryPolygons(Collection<WayInPolygon> multigonWays, List<Way> discardedResult) {
963 //first find all discardable ways, by getting outer shells.
964 //this will produce incorrect boundaries in some cases, but second pass will fix it.
965 List<WayInPolygon> discardedWays = new ArrayList<WayInPolygon>();
966
967 // In multigonWays collection, some way are just a point (i.e. way like nodeA-nodeA)
968 // This seems to appear when is apply over invalid way like #9911 test-case
969 // Remove all of these way to make the next work.
970 ArrayList<WayInPolygon> cleanMultigonWays = new ArrayList<WayInPolygon>();
971 for(WayInPolygon way: multigonWays)
972 if(way.way.getNodesCount() == 2 && way.way.firstNode() == way.way.lastNode())
973 discardedWays.add(way);
974 else
975 cleanMultigonWays.add(way);
976
977 WayTraverser traverser = new WayTraverser(cleanMultigonWays);
978 List<AssembledPolygon> result = new ArrayList<AssembledPolygon>();
979
980 WayInPolygon startWay;
981 while((startWay = traverser.startNewWay()) != null) {
982 ArrayList<WayInPolygon> path = new ArrayList<WayInPolygon>();
983 path.add(startWay);
984 while(true) {
985 WayInPolygon nextWay = traverser.walk();
986 if(nextWay == null)
987 throw new RuntimeException("Join areas internal error.");
988 if(path.get(0) == nextWay) {
989 AssembledPolygon ring = new AssembledPolygon(path);
990 if(ring.getNodes().size() <= 2) {
991 // Invalid ring (2 nodes) -> remove
992 traverser.removeWays(path);
993 for(WayInPolygon way: path)
994 discardedResult.add(way.way);
995 } else {
996 // Close ring -> add
997 result.add(ring);
998 traverser.removeWays(path);
999 }
1000 break;
1001 }
1002 if(path.contains(nextWay)) {
1003 // Inner loop -> remove
1004 int index = path.indexOf(nextWay);
1005 while(path.size() > index) {
1006 WayInPolygon currentWay = path.get(index);
1007 discardedResult.add(currentWay.way);
1008 traverser.removeWay(currentWay);
1009 path.remove(index);
1010 }
1011 traverser.setStartWay(path.get(index-1));
1012 } else {
1013 path.add(nextWay);
1014 }
1015 }
1016 }
1017
1018 return fixTouchingPolygons(result);
1019 }
1020
1021 /**
1022 * This method checks if polygons have several touching parts and splits them in several polygons.
1023 * @param polygons the polygons to process.
1024 */
1025 public static List<AssembledPolygon> fixTouchingPolygons(List<AssembledPolygon> polygons) {
1026 List<AssembledPolygon> newPolygons = new ArrayList<AssembledPolygon>();
1027
1028 for (AssembledPolygon ring : polygons) {
1029 ring.reverse();
1030 WayTraverser traverser = new WayTraverser(ring.ways);
1031 WayInPolygon startWay;
1032
1033 while((startWay = traverser.startNewWay()) != null) {
1034 List<WayInPolygon> simpleRingWays = new ArrayList<WayInPolygon>();
1035 simpleRingWays.add(startWay);
1036 WayInPolygon nextWay;
1037 while((nextWay = traverser.walk()) != startWay) {
1038 if(nextWay == null)
1039 throw new RuntimeException("Join areas internal error.");
1040 simpleRingWays.add(nextWay);
1041 }
1042 traverser.removeWays(simpleRingWays);
1043 AssembledPolygon simpleRing = new AssembledPolygon(simpleRingWays);
1044 simpleRing.reverse();
1045 newPolygons.add(simpleRing);
1046 }
1047 }
1048
1049 return newPolygons;
1050 }
1051
1052 /**
1053 * Tests if way is inside other way
1054 * @param outside outer polygon description
1055 * @param inside inner polygon description
1056 * @return {@code true} if inner is inside outer
1057 */
1058 public static boolean wayInsideWay(AssembledPolygon inside, AssembledPolygon outside) {
1059 Set<Node> outsideNodes = new HashSet<Node>(outside.getNodes());
1060 List<Node> insideNodes = inside.getNodes();
1061
1062 for (Node insideNode : insideNodes) {
1063
1064 if (!outsideNodes.contains(insideNode))
1065 //simply test the one node
1066 return Geometry.nodeInsidePolygon(insideNode, outside.getNodes());
1067 }
1068
1069 //all nodes shared.
1070 return false;
1071 }
1072
1073 /**
1074 * Joins the lists of ways.
1075 * @param polygon The list of outer ways that belong to that multigon.
1076 * @return The newly created outer way
1077 */
1078 private Multipolygon joinPolygon(AssembledMultipolygon polygon) throws UserCancelException {
1079 Multipolygon result = new Multipolygon(joinWays(polygon.outerWay.ways));
1080
1081 for (AssembledPolygon pol : polygon.innerWays) {
1082 result.innerWays.add(joinWays(pol.ways));
1083 }
1084
1085 return result;
1086 }
1087
1088 /**
1089 * Joins the outer ways and deletes all short ways that can't be part of a multipolygon anyway.
1090 * @param ways The list of outer ways that belong to that multigon.
1091 * @return The newly created outer way
1092 */
1093 private Way joinWays(List<WayInPolygon> ways) throws UserCancelException {
1094
1095 //leave original orientation, if all paths are reverse.
1096 boolean allReverse = true;
1097 for (WayInPolygon way : ways) {
1098 allReverse &= !way.insideToTheRight;
1099 }
1100
1101 if (allReverse) {
1102 for (WayInPolygon way : ways) {
1103 way.insideToTheRight = !way.insideToTheRight;
1104 }
1105 }
1106
1107 Way joinedWay = joinOrientedWays(ways);
1108
1109 //should not happen
1110 if (joinedWay == null || !joinedWay.isClosed())
1111 throw new RuntimeException("Join areas internal error.");
1112
1113 return joinedWay;
1114 }
1115
1116 /**
1117 * Joins a list of ways (using CombineWayAction and ReverseWayAction as specified in WayInPath)
1118 * @param ways The list of ways to join and reverse
1119 * @return The newly created way
1120 */
1121 private Way joinOrientedWays(List<WayInPolygon> ways) throws UserCancelException{
1122 if (ways.size() < 2)
1123 return ways.get(0).way;
1124
1125 // This will turn ways so all of them point in the same direction and CombineAction won't bug
1126 // the user about this.
1127
1128 //TODO: ReverseWay and Combine way are really slow and we use them a lot here. This slows down large joins.
1129 List<Way> actionWays = new ArrayList<Way>(ways.size());
1130
1131 for (WayInPolygon way : ways) {
1132 actionWays.add(way.way);
1133
1134 if (!way.insideToTheRight) {
1135 ReverseWayResult res = ReverseWayAction.reverseWay(way.way);
1136 Main.main.undoRedo.add(res.getReverseCommand());
1137 cmdsCount++;
1138 }
1139 }
1140
1141 Pair<Way, Command> result = CombineWayAction.combineWaysWorker(actionWays);
1142
1143 Main.main.undoRedo.add(result.b);
1144 cmdsCount ++;
1145
1146 return result.a;
1147 }
1148
1149 /**
1150 * This method analyzes multipolygon relationships of given ways and collects addition inner ways to consider.
1151 * @param selectedWays the selected ways
1152 * @return list of polygons, or null if too complex relation encountered.
1153 */
1154 private List<Multipolygon> collectMultipolygons(List<Way> selectedWays) {
1155
1156 List<Multipolygon> result = new ArrayList<Multipolygon>();
1157
1158 //prepare the lists, to minimize memory allocation.
1159 List<Way> outerWays = new ArrayList<Way>();
1160 List<Way> innerWays = new ArrayList<Way>();
1161
1162 Set<Way> processedOuterWays = new LinkedHashSet<Way>();
1163 Set<Way> processedInnerWays = new LinkedHashSet<Way>();
1164
1165 for (Relation r : OsmPrimitive.getParentRelations(selectedWays)) {
1166 if (r.isDeleted() || !r.isMultipolygon()) {
1167 continue;
1168 }
1169
1170 boolean hasKnownOuter = false;
1171 outerWays.clear();
1172 innerWays.clear();
1173
1174 for (RelationMember rm : r.getMembers()) {
1175 if (rm.getRole().equalsIgnoreCase("outer")) {
1176 outerWays.add(rm.getWay());
1177 hasKnownOuter |= selectedWays.contains(rm.getWay());
1178 }
1179 else if (rm.getRole().equalsIgnoreCase("inner")) {
1180 innerWays.add(rm.getWay());
1181 }
1182 }
1183
1184 if (!hasKnownOuter) {
1185 continue;
1186 }
1187
1188 if (outerWays.size() > 1) {
1189 new Notification(
1190 tr("Sorry. Cannot handle multipolygon relations with multiple outer ways."))
1191 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1192 .show();
1193 return null;
1194 }
1195
1196 Way outerWay = outerWays.get(0);
1197
1198 //retain only selected inner ways
1199 innerWays.retainAll(selectedWays);
1200
1201 if (processedOuterWays.contains(outerWay)) {
1202 new Notification(
1203 tr("Sorry. Cannot handle way that is outer in multiple multipolygon relations."))
1204 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1205 .show();
1206 return null;
1207 }
1208
1209 if (processedInnerWays.contains(outerWay)) {
1210 new Notification(
1211 tr("Sorry. Cannot handle way that is both inner and outer in multipolygon relations."))
1212 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1213 .show();
1214 return null;
1215 }
1216
1217 for (Way way :innerWays)
1218 {
1219 if (processedOuterWays.contains(way)) {
1220 new Notification(
1221 tr("Sorry. Cannot handle way that is both inner and outer in multipolygon relations."))
1222 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1223 .show();
1224 return null;
1225 }
1226
1227 if (processedInnerWays.contains(way)) {
1228 new Notification(
1229 tr("Sorry. Cannot handle way that is inner in multiple multipolygon relations."))
1230 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1231 .show();
1232 return null;
1233 }
1234 }
1235
1236 processedOuterWays.add(outerWay);
1237 processedInnerWays.addAll(innerWays);
1238
1239 Multipolygon pol = new Multipolygon(outerWay);
1240 pol.innerWays.addAll(innerWays);
1241
1242 result.add(pol);
1243 }
1244
1245 //add remaining ways, not in relations
1246 for (Way way : selectedWays) {
1247 if (processedOuterWays.contains(way) || processedInnerWays.contains(way)) {
1248 continue;
1249 }
1250
1251 result.add(new Multipolygon(way));
1252 }
1253
1254 return result;
1255 }
1256
1257 /**
1258 * Will add own multipolygon relation to the "previously existing" relations. Fixup is done by fixRelations
1259 * @param inner List of already closed inner ways
1260 * @param outer The outer way
1261 * @return The list of relation with roles to add own relation to
1262 */
1263 private RelationRole addOwnMultigonRelation(Collection<Way> inner, Way outer) {
1264 if (inner.isEmpty()) return null;
1265 // Create new multipolygon relation and add all inner ways to it
1266 Relation newRel = new Relation();
1267 newRel.put("type", "multipolygon");
1268 for (Way w : inner) {
1269 newRel.addMember(new RelationMember("inner", w));
1270 }
1271 cmds.add(new AddCommand(newRel));
1272 addedRelations.add(newRel);
1273
1274 // We don't add outer to the relation because it will be handed to fixRelations()
1275 // which will then do the remaining work.
1276 return new RelationRole(newRel, "outer");
1277 }
1278
1279 /**
1280 * Removes a given OsmPrimitive from all relations
1281 * @param osm Element to remove from all relations
1282 * @return List of relations with roles the primitives was part of
1283 */
1284 private List<RelationRole> removeFromAllRelations(OsmPrimitive osm) {
1285 List<RelationRole> result = new ArrayList<RelationRole>();
1286
1287 for (Relation r : Main.main.getCurrentDataSet().getRelations()) {
1288 if (r.isDeleted()) {
1289 continue;
1290 }
1291 for (RelationMember rm : r.getMembers()) {
1292 if (rm.getMember() != osm) {
1293 continue;
1294 }
1295
1296 Relation newRel = new Relation(r);
1297 List<RelationMember> members = newRel.getMembers();
1298 members.remove(rm);
1299 newRel.setMembers(members);
1300
1301 cmds.add(new ChangeCommand(r, newRel));
1302 RelationRole saverel = new RelationRole(r, rm.getRole());
1303 if (!result.contains(saverel)) {
1304 result.add(saverel);
1305 }
1306 break;
1307 }
1308 }
1309
1310 commitCommands(marktr("Removed Element from Relations"));
1311 return result;
1312 }
1313
1314 /**
1315 * Adds the previously removed relations again to the outer way. If there are multiple multipolygon
1316 * relations where the joined areas were in "outer" role a new relation is created instead with all
1317 * members of both. This function depends on multigon relations to be valid already, it won't fix them.
1318 * @param rels List of relations with roles the (original) ways were part of
1319 * @param outer The newly created outer area/way
1320 * @param ownMultipol elements to directly add as outer
1321 * @param relationsToDelete set of relations to delete.
1322 */
1323 private void fixRelations(List<RelationRole> rels, Way outer, RelationRole ownMultipol, Set<Relation> relationsToDelete) {
1324 List<RelationRole> multiouters = new ArrayList<RelationRole>();
1325
1326 if (ownMultipol != null) {
1327 multiouters.add(ownMultipol);
1328 }
1329
1330 for (RelationRole r : rels) {
1331 if (r.rel.isMultipolygon() && r.role.equalsIgnoreCase("outer")) {
1332 multiouters.add(r);
1333 continue;
1334 }
1335 // Add it back!
1336 Relation newRel = new Relation(r.rel);
1337 newRel.addMember(new RelationMember(r.role, outer));
1338 cmds.add(new ChangeCommand(r.rel, newRel));
1339 }
1340
1341 Relation newRel;
1342 switch (multiouters.size()) {
1343 case 0:
1344 return;
1345 case 1:
1346 // Found only one to be part of a multipolygon relation, so just add it back as well
1347 newRel = new Relation(multiouters.get(0).rel);
1348 newRel.addMember(new RelationMember(multiouters.get(0).role, outer));
1349 cmds.add(new ChangeCommand(multiouters.get(0).rel, newRel));
1350 return;
1351 default:
1352 // Create a new relation with all previous members and (Way)outer as outer.
1353 newRel = new Relation();
1354 for (RelationRole r : multiouters) {
1355 // Add members
1356 for (RelationMember rm : r.rel.getMembers())
1357 if (!newRel.getMembers().contains(rm)) {
1358 newRel.addMember(rm);
1359 }
1360 // Add tags
1361 for (String key : r.rel.keySet()) {
1362 newRel.put(key, r.rel.get(key));
1363 }
1364 // Delete old relation
1365 relationsToDelete.add(r.rel);
1366 }
1367 newRel.addMember(new RelationMember("outer", outer));
1368 cmds.add(new AddCommand(newRel));
1369 }
1370 }
1371
1372 /**
1373 * Remove all tags from the all the way
1374 * @param ways The List of Ways to remove all tags from
1375 */
1376 private void stripTags(Collection<Way> ways) {
1377 for (Way w : ways) {
1378 stripTags(w);
1379 }
1380 /* I18N: current action printed in status display */
1381 commitCommands(marktr("Remove tags from inner ways"));
1382 }
1383
1384 /**
1385 * Remove all tags from the way
1386 * @param x The Way to remove all tags from
1387 */
1388 private void stripTags(Way x) {
1389 Way y = new Way(x);
1390 for (String key : x.keySet()) {
1391 y.remove(key);
1392 }
1393 cmds.add(new ChangeCommand(x, y));
1394 }
1395
1396 /**
1397 * Takes the last cmdsCount actions back and combines them into a single action
1398 * (for when the user wants to undo the join action)
1399 * @param message The commit message to display
1400 */
1401 private void makeCommitsOneAction(String message) {
1402 UndoRedoHandler ur = Main.main.undoRedo;
1403 cmds.clear();
1404 int i = Math.max(ur.commands.size() - cmdsCount, 0);
1405 for (; i < ur.commands.size(); i++) {
1406 cmds.add(ur.commands.get(i));
1407 }
1408
1409 for (i = 0; i < cmds.size(); i++) {
1410 ur.undo();
1411 }
1412
1413 commitCommands(message == null ? marktr("Join Areas Function") : message);
1414 cmdsCount = 0;
1415 }
1416
1417 @Override
1418 protected void updateEnabledState() {
1419 if (getCurrentDataSet() == null) {
1420 setEnabled(false);
1421 } else {
1422 updateEnabledState(getCurrentDataSet().getSelected());
1423 }
1424 }
1425
1426 @Override
1427 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
1428 setEnabled(selection != null && !selection.isEmpty());
1429 }
1430}
Note: See TracBrowser for help on using the repository browser.