source: osm/applications/editors/josm/plugins/terracer/src/terracer/TerracerAction.java@ 30614

Last change on this file since 30614 was 30614, checked in by donvip, 10 years ago

[josm_terracer] likely fix #josm10293 - focus potential issue

File size: 32.4 KB
Line 
1/**
2 * Terracer: A JOSM Plugin for terraced houses.
3 *
4 * Copyright 2009 CloudMade Ltd.
5 *
6 * Released under the GPLv2, see LICENSE file for details.
7 */
8package terracer;
9
10import static org.openstreetmap.josm.tools.I18n.tr;
11import static org.openstreetmap.josm.tools.I18n.trn;
12
13import java.awt.event.ActionEvent;
14import java.awt.event.KeyEvent;
15import java.util.ArrayList;
16import java.util.Arrays;
17import java.util.Collection;
18import java.util.Collections;
19import java.util.Comparator;
20import java.util.HashSet;
21import java.util.Iterator;
22import java.util.LinkedList;
23import java.util.List;
24import java.util.Set;
25import java.util.regex.Matcher;
26import java.util.regex.Pattern;
27
28import javax.swing.JOptionPane;
29
30import org.openstreetmap.josm.Main;
31import org.openstreetmap.josm.actions.JosmAction;
32import org.openstreetmap.josm.command.AddCommand;
33import org.openstreetmap.josm.command.ChangeCommand;
34import org.openstreetmap.josm.command.ChangePropertyCommand;
35import org.openstreetmap.josm.command.Command;
36import org.openstreetmap.josm.command.DeleteCommand;
37import org.openstreetmap.josm.command.SequenceCommand;
38import org.openstreetmap.josm.corrector.UserCancelException;
39import org.openstreetmap.josm.data.osm.Node;
40import org.openstreetmap.josm.data.osm.OsmPrimitive;
41import org.openstreetmap.josm.data.osm.Relation;
42import org.openstreetmap.josm.data.osm.RelationMember;
43import org.openstreetmap.josm.data.osm.Tag;
44import org.openstreetmap.josm.data.osm.TagCollection;
45import org.openstreetmap.josm.data.osm.Way;
46import org.openstreetmap.josm.gui.ExtendedDialog;
47import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog;
48import org.openstreetmap.josm.tools.Pair;
49import org.openstreetmap.josm.tools.Shortcut;
50
51/**
52 * Terraces a quadrilateral, closed way into a series of quadrilateral,
53 * closed ways. If two ways are selected and one of them can be identified as
54 * a street (highway=*, name=*) then the given street will be added
55 * to the 'associatedStreet' relation.
56 *
57 *
58 * At present it only works on quadrilaterals, but there is no reason
59 * why it couldn't be extended to work with other shapes too. The
60 * algorithm employed is naive, but it works in the simple case.
61 *
62 * @author zere
63 */
64public final class TerracerAction extends JosmAction {
65
66 // smsms1 asked for the last value to be remembered to make it easier to do
67 // repeated terraces. this is the easiest, but not necessarily nicest, way.
68 // private static String lastSelectedValue = "";
69
70 Collection<Command> commands;
71
72 private Collection<OsmPrimitive> primitives;
73 private TagCollection tagsInConflict;
74
75 public TerracerAction() {
76 super(tr("Terrace a building"), "terrace",
77 tr("Creates individual buildings from a long building."),
78 Shortcut.registerShortcut("tools:Terracer", tr("Tool: {0}",
79 tr("Terrace a building")), KeyEvent.VK_T,
80 Shortcut.SHIFT), true);
81 }
82
83 protected static final Set<Relation> findAssociatedStreets(Collection<OsmPrimitive> objects) {
84 Set<Relation> result = new HashSet<Relation>();
85 if (objects != null) {
86 for (OsmPrimitive c : objects) {
87 if (c != null) {
88 for (OsmPrimitive p : c.getReferrers()) {
89 if (p instanceof Relation && "associatedStreet".equals(p.get("type"))) {
90 result.add((Relation) p);
91 }
92 }
93 }
94 }
95 }
96 return result;
97 }
98
99 private static final class InvalidUserInputException extends Exception {
100 InvalidUserInputException(String message) {
101 super(message);
102 }
103 }
104
105 /**
106 * Checks that the selection is OK. If not, displays error message. If so
107 * calls to terraceBuilding(), which does all the real work.
108 */
109 @Override
110 public void actionPerformed(ActionEvent e) {
111 Collection<OsmPrimitive> sel = getCurrentDataSet().getSelected();
112 Way outline = null;
113 Way street = null;
114 String streetname = null;
115 ArrayList<Node> housenumbers = new ArrayList<Node>();
116 Node init = null;
117
118 try {
119 if (sel.size() == 1) {
120 OsmPrimitive prim = sel.iterator().next();
121
122 if (!(prim instanceof Way))
123 throw new InvalidUserInputException(prim+" is not a way");
124
125 outline = (Way) prim;
126 } else if (sel.size() > 1) {
127 List<Way> ways = OsmPrimitive.getFilteredList(sel, Way.class);
128 Iterator<Way> wit = ways.iterator();
129 while (wit.hasNext()) {
130 Way way = wit.next();
131 if (way.hasKey("building")) {
132 if (outline != null)
133 // already have a building
134 throw new InvalidUserInputException("already have a building");
135 outline = way;
136 } else if (way.hasKey("highway")) {
137 if (street != null)
138 // already have a street
139 throw new InvalidUserInputException("already have a street");
140 street = way;
141 streetname = street.get("name");
142 if (streetname == null)
143 throw new InvalidUserInputException("street does not have any name");
144 } else
145 throw new InvalidUserInputException(way+" is neither a building nor a highway");
146 }
147
148 if (outline == null)
149 throw new InvalidUserInputException("no outline way found");
150
151 List<Node> nodes = OsmPrimitive.getFilteredList(sel, Node.class);
152 Iterator<Node> nit = nodes.iterator();
153 // Actually this should test if the selected address nodes lie
154 // within the selected outline. Any ideas how to do this?
155 while (nit.hasNext()) {
156 Node node = nit.next();
157 if (node.hasKey("addr:housenumber")) {
158 String nodesStreetName = node.get("addr:street");
159 // if a node has a street name if must be equal
160 // to the one of the other address nodes
161 if (nodesStreetName != null) {
162 if (streetname == null)
163 streetname = nodesStreetName;
164 else if (!nodesStreetName.equals(streetname))
165 throw new InvalidUserInputException("addr:street does not match street name");
166 }
167
168 housenumbers.add(node);
169 } else {
170 // A given node might not be an address node but then
171 // it has to be part of the building to help getting
172 // the number direction right.
173 if (!outline.containsNode(node) || init != null)
174 throw new InvalidUserInputException("node problem");
175 init = node;
176 }
177 }
178
179 Collections.sort(housenumbers, new HousenumberNodeComparator());
180 }
181
182 if (outline == null || !outline.isClosed() || outline.getNodesCount() < 5)
183 throw new InvalidUserInputException("wrong or missing outline");
184
185 } catch (InvalidUserInputException ex) {
186 Main.warn("Terracer: "+ex.getMessage());
187 new ExtendedDialog(Main.parent, tr("Invalid selection"), new String[] {"OK"})
188 .setButtonIcons(new String[] {"ok"}).setIcon(JOptionPane.INFORMATION_MESSAGE)
189 .setContent(tr("Select a single, closed way of at least four nodes. " +
190 "(Optionally you can also select a street for the addr:street tag " +
191 "and a node to mark the start of numbering.)"))
192 .showDialog();
193 return;
194 }
195
196 Relation associatedStreet = null;
197
198 // Try to find an associatedStreet relation that could be reused from housenumbers, outline and street.
199 Set<OsmPrimitive> candidates = new HashSet<OsmPrimitive>(housenumbers);
200 candidates.add(outline);
201 if (street != null) {
202 candidates.add(street);
203 }
204
205 Set<Relation> associatedStreets = findAssociatedStreets(candidates);
206
207 if (!associatedStreets.isEmpty()) {
208 associatedStreet = associatedStreets.iterator().next();
209 if (associatedStreets.size() > 1) {
210 // TODO: Deal with multiple associated Streets
211 Main.warn("Terracer: Found "+associatedStreets.size()+" associatedStreet relations. Considering the first one only.");
212 }
213 }
214
215 if (streetname == null && associatedStreet != null && associatedStreet.hasKey("name")) {
216 streetname = associatedStreet.get("name");
217 }
218
219 if (housenumbers.size() == 1) {
220 // Special case of one outline and one address node.
221 // Don't open the dialog
222 try {
223 terraceBuilding(outline, init, street, associatedStreet, 0, null, null, 0, housenumbers, streetname, associatedStreet != null, false, "yes");
224 } catch (UserCancelException ex) {
225 // Ignore
226 } finally {
227 this.commands.clear();
228 this.commands = null;
229 }
230 } else {
231 String title = trn("Change {0} object", "Change {0} objects", sel.size(), sel.size());
232 // show input dialog.
233 new HouseNumberInputHandler(this, outline, init, street, streetname, outline.get("building"),
234 associatedStreet, housenumbers, title).dialog.showDialog();
235 }
236 }
237
238 public Integer getNumber(String number) {
239 try {
240 return Integer.parseInt(number);
241 } catch (NumberFormatException ex) {
242 return null;
243 }
244 }
245
246 /**
247 * Sorts the house number nodes according their numbers only
248 *
249 * @param house
250 * number nodes
251 */
252 class HousenumberNodeComparator implements Comparator<Node> {
253 private final Pattern pat = Pattern.compile("^(\\d+)\\s*(.*)");
254
255 @Override
256 public int compare(Node node1, Node node2) {
257 // It's necessary to strip off trailing non-numbers so we can
258 // compare the numbers itself numerically since string comparison
259 // doesn't work for numbers with different number of digits,
260 // e.g. 9 is higher than 11
261 String node1String = node1.get("addr:housenumber");
262 String node2String = node2.get("addr:housenumber");
263 Matcher mat = pat.matcher(node1String);
264 if (mat.find()) {
265 Integer node1Int = Integer.valueOf(mat.group(1));
266 String node1Rest = mat.group(2);
267 mat = pat.matcher(node2String);
268 if (mat.find()) {
269 Integer node2Int = Integer.valueOf(mat.group(1));
270 // If the numbers are the same, the rest has to make the decision,
271 // e.g. when comparing 23, 23a and 23b.
272 if (node1Int.equals(node2Int))
273 {
274 String node2Rest = mat.group(2);
275 return node1Rest.compareTo(node2Rest);
276 }
277
278 return node1Int.compareTo(node2Int);
279 }
280 }
281
282 return node1String.compareTo(node2String);
283 }
284 }
285
286 /**
287 * Terraces a single, closed, quadrilateral way.
288 *
289 * Any node must be adjacent to both a short and long edge, we naively
290 * choose the longest edge and its opposite and interpolate along them
291 * linearly to produce new nodes. Those nodes are then assembled into
292 * closed, quadrilateral ways and left in the selection.
293 *
294 * @param outline The closed, quadrilateral way to terrace.
295 * @param init The node that hints at which side to start the numbering
296 * @param street The street, the buildings belong to (may be null)
297 * @param associatedStreet
298 * @param segments The number of segments to generate
299 * @param From Starting housenumber
300 * @param To Ending housenumber
301 * @param step The step width to use
302 * @param housenumbers List of housenumbers to use. From and To are ignored
303 * if this is set.
304 * @param streetName the name of the street, derived from the street line
305 * or the house numbers (may be null)
306 * @param handleRelations If the user likes to add a relation or extend an
307 * existing relation
308 * @param deleteOutline If the outline way should be deleted when done
309 * @param buildingValue The value for {@code building} key to add
310 * @throws UserCancelException
311 */
312 public void terraceBuilding(final Way outline,
313 Node init,
314 Way street,
315 Relation associatedStreet,
316 Integer segments,
317 String From,
318 String To,
319 int step,
320 ArrayList<Node> housenumbers,
321 String streetName,
322 boolean handleRelations,
323 boolean deleteOutline, String buildingValue) throws UserCancelException {
324 final int nb;
325 Integer to = null, from = null;
326 if (housenumbers == null || housenumbers.isEmpty()) {
327 to = getNumber(To);
328 from = getNumber(From);
329 if (to != null && from != null) {
330 nb = 1 + (to.intValue() - from.intValue()) / step;
331 } else if (segments != null) {
332 nb = segments.intValue();
333 } else {
334 // if we get here, there is is a bug in the input validation.
335 throw new TerracerRuntimeException(
336 "Could not determine segments from parameters, this is a bug. "
337 + "Parameters were: segments " + segments
338 + " from " + from + " to " + to + " step "
339 + step);
340 }
341 } else {
342 nb = housenumbers.size();
343 }
344
345 // now find which is the longest side connecting the first node
346 Pair<Way, Way> interp = findFrontAndBack(outline);
347
348 boolean swap = false;
349 if (init != null) {
350 if (interp.a.lastNode().equals(init) || interp.b.lastNode().equals(init)) {
351 swap = true;
352 }
353 }
354
355 final double frontLength = wayLength(interp.a);
356 final double backLength = wayLength(interp.b);
357
358 // new nodes array to hold all intermediate nodes
359 // This set will contain at least 4 existing nodes from the original outline (those, which coordinates match coordinates of outline nodes)
360 Node[][] new_nodes = new Node[2][nb + 1];
361 // This list will contain nodes of the outline that are used in new lines.
362 // These nodes will not be deleted with the outline (if deleting was prompted).
363 ArrayList<Node> reused_nodes = new ArrayList<Node>();
364
365 this.commands = new LinkedList<Command>();
366 Collection<Way> ways = new LinkedList<Way>();
367
368 if (nb > 1) {
369 for (int i = 0; i <= nb; ++i) {
370 int i_dir = swap ? nb - i : i;
371 new_nodes[0][i] = interpolateAlong(interp.a, frontLength * i_dir / nb);
372 new_nodes[1][i] = interpolateAlong(interp.b, backLength * i_dir / nb);
373 if (!outline.containsNode(new_nodes[0][i]))
374 this.commands.add(new AddCommand(new_nodes[0][i]));
375 else
376 reused_nodes.add(new_nodes[0][i]);
377 if (!outline.containsNode(new_nodes[1][i]))
378 this.commands.add(new AddCommand(new_nodes[1][i]));
379 else
380 reused_nodes.add(new_nodes[1][i]);
381 }
382
383 // assemble new quadrilateral, closed ways
384 for (int i = 0; i < nb; ++i) {
385 Way terr = new Way();
386 terr.addNode(new_nodes[0][i]);
387 terr.addNode(new_nodes[0][i + 1]);
388 terr.addNode(new_nodes[1][i + 1]);
389 terr.addNode(new_nodes[1][i]);
390 terr.addNode(new_nodes[0][i]);
391
392 // add the tags of the outline to each building (e.g. source=*)
393 TagCollection.from(outline).applyTo(terr);
394 ways.add(addressBuilding(terr, street, streetName, associatedStreet, housenumbers, i,
395 from != null ? Integer.toString(from + i * step) : null, buildingValue));
396
397 this.commands.add(new AddCommand(terr));
398 }
399
400 if (deleteOutline) {
401 // Delete outline nodes having no tags and referrers but the outline itself
402 List<Node> nodes = outline.getNodes();
403 ArrayList<Node> nodesToDelete = new ArrayList<Node>();
404 for (Node n : nodes)
405 if (!n.hasKeys() && n.getReferrers().size() == 1 && !reused_nodes.contains(n))
406 nodesToDelete.add(n);
407 if (nodesToDelete.size() > 0)
408 this.commands.add(DeleteCommand.delete(Main.main.getEditLayer(), nodesToDelete));
409 // Delete the way itself without nodes
410 this.commands.add(DeleteCommand.delete(Main.main.getEditLayer(), Collections.singleton(outline), false, true));
411
412 }
413 } else {
414 // Single building, just add the address details
415 ways.add(addressBuilding(outline, street, streetName, associatedStreet, housenumbers, 0, From, buildingValue));
416 }
417
418 // Remove the address nodes since their tags have been incorporated into
419 // the terraces.
420 // Or should removing them also be an option?
421 if (!housenumbers.isEmpty()) {
422 commands.add(DeleteCommand.delete(Main.main.getEditLayer(),
423 housenumbers, true, true));
424 }
425
426 if (handleRelations) { // create a new relation or merge with existing
427 if (associatedStreet == null) { // create a new relation
428 associatedStreet = new Relation();
429 associatedStreet.put("type", "associatedStreet");
430 if (street != null) { // a street was part of the selection
431 associatedStreet.put("name", street.get("name"));
432 associatedStreet.addMember(new RelationMember("street", street));
433 } else {
434 associatedStreet.put("name", streetName);
435 }
436 for (Way w : ways) {
437 associatedStreet.addMember(new RelationMember("house", w));
438 }
439 this.commands.add(new AddCommand(associatedStreet));
440 } else { // relation exists already - add new members
441 Relation newAssociatedStreet = new Relation(associatedStreet);
442 // remove housenumbers as they have been deleted
443 newAssociatedStreet.removeMembersFor(housenumbers);
444 for (Way w : ways) {
445 newAssociatedStreet.addMember(new RelationMember("house", w));
446 }
447 if (deleteOutline) {
448 newAssociatedStreet.removeMembersFor(outline);
449 }
450 this.commands.add(new ChangeCommand(associatedStreet, newAssociatedStreet));
451 }
452 }
453
454 Main.main.undoRedo.add(new SequenceCommand(tr("Terrace"), commands) {
455 @Override
456 public boolean executeCommand() {
457 boolean result = super.executeCommand();
458 if (result && tagsInConflict != null) {
459 try {
460 // Build conflicts commands only after all primitives have been added to dataset to fix #8942
461 List<Command> conflictCommands = CombinePrimitiveResolverDialog.launchIfNecessary(
462 tagsInConflict, primitives, Collections.singleton(outline));
463 if (!conflictCommands.isEmpty()) {
464 List<Command> newCommands = new ArrayList<Command>(commands);
465 newCommands.addAll(conflictCommands);
466 setSequence(newCommands.toArray(new Command[0]));
467 // Run conflicts commands
468 for (int i = 0; i < conflictCommands.size(); i++) {
469 result = conflictCommands.get(i).executeCommand();
470 if (!result && !continueOnError) {
471 setSequenceComplete(false);
472 undoCommands(commands.size()+i-1);
473 return false;
474 }
475 }
476 }
477 } catch (UserCancelException e) {
478 // Ignore
479 }
480 }
481 return result;
482 }
483 });
484 if (nb <= 1 && street != null) {
485 // Select the way (for quick selection of a new house (with the same way))
486 Main.main.getCurrentDataSet().setSelected(street);
487 } else {
488 // Select the new building outlines (for quick reversing)
489 Main.main.getCurrentDataSet().setSelected(ways);
490 }
491 }
492
493 /**
494 * Adds address details to a single building
495 *
496 * @param outline The closed, quadrilateral way to add the address to.
497 * @param street The street, the buildings belong to (may be null)
498 * @param streetName the name of a street (may be null). Used if not null and street is null.
499 * @param associatedStreet The associated street. Used to determine if addr:street should be set or not.
500 * @param buildingValue The value for {@code building} key to add
501 * @return {@code outline}
502 * @throws UserCancelException
503 */
504 private Way addressBuilding(Way outline, Way street, String streetName, Relation associatedStreet, ArrayList<Node> housenumbers, int i, String defaultNumber, String buildingValue) throws UserCancelException {
505 Node houseNum = (housenumbers != null && i >= 0 && i < housenumbers.size()) ? housenumbers.get(i) : null;
506 boolean buildingAdded = false;
507 boolean numberAdded = false;
508 if (houseNum != null) {
509 primitives = Arrays.asList(new OsmPrimitive[]{houseNum, outline});
510
511 TagCollection tagsToCopy = TagCollection.unionOfAllPrimitives(primitives).getTagsFor(houseNum.keySet());
512 tagsInConflict = tagsToCopy.getTagsFor(tagsToCopy.getKeysWithMultipleValues());
513 tagsToCopy = tagsToCopy.minus(tagsInConflict).minus(TagCollection.from(outline));
514
515 for (Tag tag : tagsToCopy) {
516 this.commands.add(new ChangePropertyCommand(outline, tag.getKey(), tag.getValue()));
517 }
518
519 buildingAdded = houseNum.hasKey("building");
520 numberAdded = houseNum.hasKey("addr:housenumber");
521 }
522 if (!buildingAdded && buildingValue != null && !buildingValue.isEmpty()) {
523 this.commands.add(new ChangePropertyCommand(outline, "building", buildingValue));
524 }
525 if (defaultNumber != null && !numberAdded) {
526 this.commands.add(new ChangePropertyCommand(outline, "addr:housenumber", defaultNumber));
527 }
528 // Only put addr:street if no relation exists or if it has no name
529 if (associatedStreet == null || !associatedStreet.hasKey("name")) {
530 if (street != null) {
531 this.commands.add(new ChangePropertyCommand(outline, "addr:street", street.get("name")));
532 } else if (streetName != null && !streetName.trim().isEmpty()) {
533 this.commands.add(new ChangePropertyCommand(outline, "addr:street", streetName.trim()));
534 }
535 }
536 return outline;
537 }
538
539 /**
540 * Creates a node at a certain distance along a way, as calculated by the
541 * great circle distance.
542 *
543 * Note that this really isn't an efficient way to do this and leads to
544 * O(N^2) running time for the main algorithm, but its simple and easy
545 * to understand, and probably won't matter for reasonable-sized ways.
546 *
547 * @param w The way to interpolate.
548 * @param l The length at which to place the node.
549 * @return A node at a distance l along w from the first point.
550 */
551 private Node interpolateAlong(Way w, double l) {
552 List<Pair<Node,Node>> pairs = w.getNodePairs(false);
553 for (int i = 0; i < pairs.size(); ++i) {
554 Pair<Node,Node> p = pairs.get(i);
555 final double seg_length = p.a.getCoor().greatCircleDistance(p.b.getCoor());
556 if (l <= seg_length || i == pairs.size() - 1) {
557 // be generous on the last segment (numerical roudoff can lead to a small overshoot)
558 return interpolateNode(p.a, p.b, l / seg_length);
559 } else {
560 l -= seg_length;
561 }
562 }
563 // we shouldn't get here
564 throw new IllegalStateException();
565 }
566
567 /**
568 * Calculates the great circle length of a way by summing the great circle
569 * distance of each pair of nodes.
570 *
571 * @param w The way to calculate length of.
572 * @return The length of the way.
573 */
574 private double wayLength(Way w) {
575 double length = 0.0;
576 for (Pair<Node, Node> p : w.getNodePairs(false)) {
577 length += p.a.getCoor().greatCircleDistance(p.b.getCoor());
578 }
579 return length;
580 }
581
582 /**
583 * Given a way, try and find a definite front and back by looking at the
584 * segments to find the "sides". Sides are assumed to be single segments
585 * which cannot be contiguous.
586 *
587 * @param w The way to analyse.
588 * @return A pair of ways (front, back) pointing in the same directions.
589 */
590 private Pair<Way, Way> findFrontAndBack(Way w) {
591 // calculate the "side-ness" score for each segment of the way
592 double[] sideness = calculateSideness(w);
593
594 // find the largest two sidenesses which are not contiguous
595 int[] indexes = sortedIndexes(sideness);
596 int side1 = indexes[0];
597 int side2 = indexes[1];
598 // if side2 is contiguous with side1 then look further down the
599 // list. we know there are at least 4 sides, as anything smaller
600 // than a quadrilateral would have been rejected at an earlier stage.
601 if (indexDistance(side1, side2, indexes.length) < 2) {
602 side2 = indexes[2];
603 }
604 if (indexDistance(side1, side2, indexes.length) < 2) {
605 side2 = indexes[3];
606 }
607
608 // if the second side has a shorter length and an approximately equal
609 // sideness then its better to choose the shorter, as with
610 // quadrilaterals
611 // created using the orthogonalise tool the sideness will be about the
612 // same for all sides.
613 if (sideLength(w, side1) > sideLength(w, side1 + 1)
614 && Math.abs(sideness[side1] - sideness[(side1 + 1) % (w.getNodesCount() - 1)]) < 0.001) {
615 side1 = (side1 + 1) % (w.getNodesCount() - 1);
616 side2 = (side2 + 1) % (w.getNodesCount() - 1);
617 }
618
619 // swap side1 and side2 into sorted order.
620 if (side1 > side2) {
621 int tmp = side2;
622 side2 = side1;
623 side1 = tmp;
624 }
625
626 Way front = new Way();
627 Way back = new Way();
628 for (int i = side2 + 1; i < w.getNodesCount() - 1; ++i) {
629 front.addNode(w.getNode(i));
630 }
631 for (int i = 0; i <= side1; ++i) {
632 front.addNode(w.getNode(i));
633 }
634 // add the back in reverse order so that the front and back ways point
635 // in the same direction.
636 for (int i = side2; i > side1; --i) {
637 back.addNode(w.getNode(i));
638 }
639
640 return new Pair<Way, Way>(front, back);
641 }
642
643 /**
644 * returns the distance of two segments of a closed polygon
645 */
646 private int indexDistance(int i1, int i2, int n) {
647 return Math.min(positiveModulus(i1 - i2, n), positiveModulus(i2 - i1, n));
648 }
649
650 /**
651 * return the modulus in the range [0, n)
652 */
653 private int positiveModulus(int a, int n) {
654 if (n <= 0)
655 throw new IllegalArgumentException();
656 int res = a % n;
657 if (res < 0) {
658 res += n;
659 }
660 return res;
661 }
662
663 /**
664 * Calculate the length of a side (from node i to i+1) in a way. This assumes that
665 * the way is closed, but I only ever call it for buildings.
666 */
667 private double sideLength(Way w, int i) {
668 Node a = w.getNode(i);
669 Node b = w.getNode((i + 1) % (w.getNodesCount() - 1));
670 return a.getCoor().greatCircleDistance(b.getCoor());
671 }
672
673 /**
674 * Given an array of doubles (but this could made generic very easily) sort
675 * into order and return the array of indexes such that, for a returned array
676 * x, a[x[i]] is sorted for ascending index i.
677 *
678 * This isn't efficient at all, but should be fine for the small arrays we're
679 * expecting. If this gets slow - replace it with some more efficient algorithm.
680 *
681 * @param a The array to sort.
682 * @return An array of indexes, the same size as the input, such that a[x[i]]
683 * is in sorted order.
684 */
685 private int[] sortedIndexes(final double[] a) {
686 class SortWithIndex implements Comparable<SortWithIndex> {
687 public double x;
688 public int i;
689
690 public SortWithIndex(double a, int b) {
691 x = a;
692 i = b;
693 }
694
695 @Override
696 public int compareTo(SortWithIndex o) {
697 return Double.compare(x, o.x);
698 }
699 }
700
701 final int length = a.length;
702 ArrayList<SortWithIndex> sortable = new ArrayList<SortWithIndex>(length);
703 for (int i = 0; i < length; ++i) {
704 sortable.add(new SortWithIndex(a[i], i));
705 }
706 Collections.sort(sortable);
707
708 int[] indexes = new int[length];
709 for (int i = 0; i < length; ++i) {
710 indexes[i] = sortable.get(i).i;
711 }
712
713 return indexes;
714 }
715
716 /**
717 * Calculate "sideness" metric for each segment in a way.
718 */
719 private double[] calculateSideness(Way w) {
720 final int length = w.getNodesCount() - 1;
721 double[] sideness = new double[length];
722
723 sideness[0] = calculateSideness(w.getNode(length - 1), w.getNode(0), w
724 .getNode(1), w.getNode(2));
725 for (int i = 1; i < length - 1; ++i) {
726 sideness[i] = calculateSideness(w.getNode(i - 1), w.getNode(i), w
727 .getNode(i + 1), w.getNode(i + 2));
728 }
729 sideness[length - 1] = calculateSideness(w.getNode(length - 2), w
730 .getNode(length - 1), w.getNode(length), w.getNode(1));
731
732 return sideness;
733 }
734
735 /**
736 * Calculate sideness of a single segment given the nodes which make up that
737 * segment and its previous and next segments in order. Sideness is calculated
738 * for the segment b-c.
739 */
740 private double calculateSideness(Node a, Node b, Node c, Node d) {
741 final double ndx = b.getCoor().getX() - a.getCoor().getX();
742 final double pdx = d.getCoor().getX() - c.getCoor().getX();
743 final double ndy = b.getCoor().getY() - a.getCoor().getY();
744 final double pdy = d.getCoor().getY() - c.getCoor().getY();
745
746 return (ndx * pdx + ndy * pdy)
747 / Math.sqrt((ndx * ndx + ndy * ndy) * (pdx * pdx + pdy * pdy));
748 }
749
750 /**
751 * Creates a new node at the interpolated position between the argument
752 * nodes. Interpolates linearly in projected coordinates.
753 *
754 * If new node coordinate matches a or b coordinates, a or b is returned.
755 *
756 * @param a First node, at which f=0.
757 * @param b Last node, at which f=1.
758 * @param f Fractional position between first and last nodes.
759 * @return A new node at the interpolated position (or a or b in case if f ≈ 0 or f ≈ 1).
760 */
761 private Node interpolateNode(Node a, Node b, double f) {
762 Node n = new Node(a.getEastNorth().interpolate(b.getEastNorth(), f));
763 if (n.getCoor().equalsEpsilon(a.getCoor()))
764 return a;
765 if (n.getCoor().equalsEpsilon(b.getCoor()))
766 return b;
767 return n;
768 }
769
770 @Override
771 protected void updateEnabledState() {
772 setEnabled(getCurrentDataSet() != null);
773 }
774}
Note: See TracBrowser for help on using the repository browser.