source: josm/trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/relations/Multipolygon.java@ 4631

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

see #7110 and #6987 - Use getUniqueId() to handle newly created primitive objects

  • Property svn:eol-style set to native
File size: 20.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.osm.visitor.paint.relations;
3
4import java.awt.geom.Path2D;
5import java.awt.geom.Path2D.Double;
6import java.awt.geom.PathIterator;
7import java.awt.geom.Point2D;
8import java.awt.geom.Rectangle2D;
9import java.util.ArrayList;
10import java.util.Collection;
11import java.util.Collections;
12import java.util.HashSet;
13import java.util.Iterator;
14import java.util.List;
15import java.util.Set;
16
17import org.openstreetmap.josm.Main;
18import org.openstreetmap.josm.data.Preferences.PreferenceChangeEvent;
19import org.openstreetmap.josm.data.Preferences.PreferenceChangedListener;
20import org.openstreetmap.josm.data.osm.DataSet;
21import org.openstreetmap.josm.data.osm.Node;
22import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
23import org.openstreetmap.josm.data.osm.Relation;
24import org.openstreetmap.josm.data.osm.RelationMember;
25import org.openstreetmap.josm.data.osm.Way;
26import org.openstreetmap.josm.data.osm.event.NodeMovedEvent;
27import org.openstreetmap.josm.data.osm.event.WayNodesChangedEvent;
28import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.PolyData.Intersection;
29
30public class Multipolygon {
31 /** preference key for a collection of roles which indicate that the respective member belongs to an
32 * <em>outer</em> polygon. Default is <tt>outer</tt>.
33 */
34 static public final String PREF_KEY_OUTER_ROLES = "mappaint.multipolygon.outer.roles";
35 /** preference key for collection of role prefixes which indicate that the respective
36 * member belongs to an <em>outer</em> polygon. Default is empty.
37 */
38 static public final String PREF_KEY_OUTER_ROLE_PREFIXES = "mappaint.multipolygon.outer.role-prefixes";
39 /** preference key for a collection of roles which indicate that the respective member belongs to an
40 * <em>inner</em> polygon. Default is <tt>inner</tt>.
41 */
42 static public final String PREF_KEY_INNER_ROLES = "mappaint.multipolygon.inner.roles";
43 /** preference key for collection of role prefixes which indicate that the respective
44 * member belongs to an <em>inner</em> polygon. Default is empty.
45 */
46 static public final String PREF_KEY_INNER_ROLE_PREFIXES = "mappaint.multipolygon.inner.role-prefixes";
47
48 /**
49 * <p>Kind of strategy object which is responsible for deciding whether a given
50 * member role indicates that the member belongs to an <em>outer</em> or an
51 * <em>inner</em> polygon.</p>
52 *
53 * <p>The decision is taken based on preference settings, see the four preference keys
54 * above.</p>
55 *
56 */
57 private static class MultipolygonRoleMatcher implements PreferenceChangedListener{
58 private final List<String> outerExactRoles = new ArrayList<String>();
59 private final List<String> outerRolePrefixes = new ArrayList<String>();
60 private final List<String> innerExactRoles = new ArrayList<String>();
61 private final List<String> innerRolePrefixes = new ArrayList<String>();
62
63 private void initDefaults() {
64 outerExactRoles.clear();
65 outerRolePrefixes.clear();
66 innerExactRoles.clear();
67 innerRolePrefixes.clear();
68 outerExactRoles.add("outer");
69 innerExactRoles.add("inner");
70 }
71
72 private void setNormalized(Collection<String> literals, List<String> target){
73 target.clear();
74 for(String l: literals) {
75 if (l == null) {
76 continue;
77 }
78 l = l.trim();
79 if (!target.contains(l)) {
80 target.add(l);
81 }
82 }
83 }
84
85 private void initFromPreferences() {
86 initDefaults();
87 if (Main.pref == null) return;
88 Collection<String> literals;
89 literals = Main.pref.getCollection(PREF_KEY_OUTER_ROLES);
90 if (literals != null && !literals.isEmpty()){
91 setNormalized(literals, outerExactRoles);
92 }
93 literals = Main.pref.getCollection(PREF_KEY_OUTER_ROLE_PREFIXES);
94 if (literals != null && !literals.isEmpty()){
95 setNormalized(literals, outerRolePrefixes);
96 }
97 literals = Main.pref.getCollection(PREF_KEY_INNER_ROLES);
98 if (literals != null && !literals.isEmpty()){
99 setNormalized(literals, innerExactRoles);
100 }
101 literals = Main.pref.getCollection(PREF_KEY_INNER_ROLE_PREFIXES);
102 if (literals != null && !literals.isEmpty()){
103 setNormalized(literals, innerRolePrefixes);
104 }
105 }
106
107 @Override
108 public void preferenceChanged(PreferenceChangeEvent evt) {
109 if (PREF_KEY_INNER_ROLE_PREFIXES.equals(evt.getKey()) ||
110 PREF_KEY_INNER_ROLES.equals(evt.getKey()) ||
111 PREF_KEY_OUTER_ROLE_PREFIXES.equals(evt.getKey()) ||
112 PREF_KEY_OUTER_ROLES.equals(evt.getKey())){
113 initFromPreferences();
114 }
115 }
116
117 public boolean isOuterRole(String role){
118 if (role == null) return false;
119 for (String candidate: outerExactRoles) {
120 if (role.equals(candidate)) return true;
121 }
122 for (String candidate: outerRolePrefixes) {
123 if (role.startsWith(candidate)) return true;
124 }
125 return false;
126 }
127
128 public boolean isInnerRole(String role){
129 if (role == null) return false;
130 for (String candidate: innerExactRoles) {
131 if (role.equals(candidate)) return true;
132 }
133 for (String candidate: innerRolePrefixes) {
134 if (role.startsWith(candidate)) return true;
135 }
136 return false;
137 }
138 }
139
140 /*
141 * Init a private global matcher object which will listen to preference
142 * changes.
143 */
144 private static MultipolygonRoleMatcher roleMatcher;
145 private static MultipolygonRoleMatcher getMultipolygonRoleMatcher() {
146 if (roleMatcher == null) {
147 roleMatcher = new MultipolygonRoleMatcher();
148 if (Main.pref != null){
149 roleMatcher.initFromPreferences();
150 Main.pref.addPreferenceChangeListener(roleMatcher);
151 }
152 }
153 return roleMatcher;
154 }
155
156 public static class JoinedWay {
157 private final List<Node> nodes;
158 private final Collection<Long> wayIds;
159 private final boolean selected;
160
161 public JoinedWay(List<Node> nodes, Collection<Long> wayIds, boolean selected) {
162 this.nodes = nodes;
163 this.wayIds = wayIds;
164 this.selected = selected;
165 }
166
167 public List<Node> getNodes() {
168 return nodes;
169 }
170
171 public Collection<Long> getWayIds() {
172 return wayIds;
173 }
174
175 public boolean isSelected() {
176 return selected;
177 }
178
179 public boolean isClosed() {
180 return nodes.isEmpty() || nodes.get(nodes.size() - 1).equals(nodes.get(0));
181 }
182 }
183
184 public static class PolyData {
185 public enum Intersection {INSIDE, OUTSIDE, CROSSING}
186
187 private final Path2D.Double poly;
188 public boolean selected;
189 private Rectangle2D bounds;
190 private final Collection<Long> wayIds;
191 private final List<Node> nodes;
192 private final List<PolyData> inners;
193
194 public PolyData(Way closedWay) {
195 this(closedWay.getNodes(), closedWay.isSelected(), Collections.singleton(closedWay.getUniqueId()));
196 }
197
198 public PolyData(JoinedWay joinedWay) {
199 this(joinedWay.getNodes(), joinedWay.isSelected(), joinedWay.getWayIds());
200 }
201
202 private PolyData(List<Node> nodes, boolean selected, Collection<Long> wayIds) {
203 this.wayIds = Collections.unmodifiableCollection(wayIds);
204 this.nodes = nodes;
205 this.selected = selected;
206 this.inners = new ArrayList<Multipolygon.PolyData>();
207 this.poly = new Path2D.Double();
208 this.poly.setWindingRule(Path2D.WIND_EVEN_ODD);
209 buildPoly();
210 }
211
212 private void buildPoly() {
213 boolean initial = true;
214 for (Node n : nodes) {
215 Point2D p = n.getEastNorth();
216 if (initial) {
217 poly.moveTo(p.getX(), p.getY());
218 initial = false;
219 } else {
220 poly.lineTo(p.getX(), p.getY());
221 }
222 }
223 poly.closePath();
224 for (PolyData inner : inners) {
225 appendInner(inner.poly);
226 }
227 }
228
229 public PolyData(PolyData copy) {
230 this.selected = copy.selected;
231 this.poly = (Double) copy.poly.clone();
232 this.wayIds = Collections.unmodifiableCollection(copy.wayIds);
233 this.nodes = new ArrayList<Node>(copy.nodes);
234 this.inners = new ArrayList<Multipolygon.PolyData>(copy.inners);
235 }
236
237 public Intersection contains(Path2D.Double p) {
238 int contains = 0;
239 int total = 0;
240 double[] coords = new double[6];
241 for (PathIterator it = p.getPathIterator(null); !it.isDone(); it.next()) {
242 switch (it.currentSegment(coords)) {
243 case PathIterator.SEG_MOVETO:
244 case PathIterator.SEG_LINETO:
245 if (poly.contains(coords[0], coords[1])) {
246 contains++;
247 }
248 total++;
249 }
250 }
251 if (contains == total) return Intersection.INSIDE;
252 if (contains == 0) return Intersection.OUTSIDE;
253 return Intersection.CROSSING;
254 }
255
256 public void addInner(PolyData inner) {
257 inners.add(inner);
258 appendInner(inner.poly);
259 }
260
261 private void appendInner(Path2D.Double inner) {
262 poly.append(inner.getPathIterator(null), false);
263 }
264
265 public Path2D.Double get() {
266 return poly;
267 }
268
269 public Rectangle2D getBounds() {
270 if (bounds == null) {
271 bounds = poly.getBounds2D();
272 }
273 return bounds;
274 }
275
276 public Collection<Long> getWayIds() {
277 return wayIds;
278 }
279
280 private void resetNodes() {
281 if (!nodes.isEmpty()) {
282 DataSet ds = nodes.get(0).getDataSet();
283 nodes.clear();
284 if (wayIds.size() == 1) {
285 Way w = (Way) ds.getPrimitiveById(wayIds.iterator().next(), OsmPrimitiveType.WAY);
286 nodes.addAll(w.getNodes());
287 } else {
288 List<Way> waysToJoin = new ArrayList<Way>();
289 for (Iterator<Long> it = wayIds.iterator(); it.hasNext(); ) {
290 waysToJoin.add((Way) ds.getPrimitiveById(it.next(), OsmPrimitiveType.WAY));
291 }
292 nodes.addAll(joinWays(waysToJoin).iterator().next().getNodes());
293 }
294 resetPoly();
295 }
296 }
297
298 private void resetPoly() {
299 poly.reset();
300 buildPoly();
301 bounds = null;
302 }
303
304 public void nodeMoved(NodeMovedEvent event) {
305 final Node n = event.getNode();
306 boolean innerChanged = false;
307 for (PolyData inner : inners) {
308 if (inner.nodes.contains(n)) {
309 inner.resetPoly();
310 innerChanged = true;
311 }
312 }
313 if (nodes.contains(n) || innerChanged) {
314 resetPoly();
315 }
316 }
317
318 public void wayNodesChanged(WayNodesChangedEvent event) {
319 final Long wayId = event.getChangedWay().getUniqueId();
320 boolean innerChanged = false;
321 for (PolyData inner : inners) {
322 if (inner.wayIds.contains(wayId)) {
323 inner.resetNodes();
324 innerChanged = true;
325 }
326 }
327 if (wayIds.contains(wayId) || innerChanged) {
328 resetNodes();
329 }
330 }
331 }
332
333 private final List<Way> innerWays = new ArrayList<Way>();
334 private final List<Way> outerWays = new ArrayList<Way>();
335 private final List<PolyData> innerPolygons = new ArrayList<PolyData>();
336 private final List<PolyData> outerPolygons = new ArrayList<PolyData>();
337 private final List<PolyData> combinedPolygons = new ArrayList<PolyData>();
338
339 public Multipolygon(Relation r) {
340 load(r);
341 }
342
343 private void load(Relation r) {
344 MultipolygonRoleMatcher matcher = getMultipolygonRoleMatcher();
345
346 // Fill inner and outer list with valid ways
347 for (RelationMember m : r.getMembers()) {
348 if (m.getMember().isDrawable()) {
349 if (m.isWay()) {
350 Way w = m.getWay();
351
352 if (w.getNodesCount() < 2) {
353 continue;
354 }
355
356 if (matcher.isInnerRole(m.getRole())) {
357 innerWays.add(w);
358 } else if (matcher.isOuterRole(m.getRole())) {
359 outerWays.add(w);
360 } else if (!m.hasRole()) {
361 outerWays.add(w);
362 } // Remaining roles ignored
363 } // Non ways ignored
364 }
365 }
366
367 createPolygons(innerWays, innerPolygons);
368 createPolygons(outerWays, outerPolygons);
369 if (!outerPolygons.isEmpty()) {
370 addInnerToOuters();
371 }
372 }
373
374 private void createPolygons(List<Way> ways, List<PolyData> result) {
375 List<Way> waysToJoin = new ArrayList<Way>();
376 for (Way way: ways) {
377 if (way.isClosed()) {
378 result.add(new PolyData(way));
379 } else {
380 waysToJoin.add(way);
381 }
382 }
383
384 for (JoinedWay jw: joinWays(waysToJoin)) {
385 result.add(new PolyData(jw));
386 }
387 }
388
389 public static Collection<JoinedWay> joinWays(Collection<Way> waysToJoin)
390 {
391 final Collection<JoinedWay> result = new ArrayList<JoinedWay>();
392 final Way[] joinArray = waysToJoin.toArray(new Way[waysToJoin.size()]);
393 int left = waysToJoin.size();
394 while (left > 0) {
395 Way w = null;
396 boolean selected = false;
397 List<Node> nodes = null;
398 Set<Long> wayIds = new HashSet<Long>();
399 boolean joined = true;
400 while (joined && left > 0) {
401 joined = false;
402 for (int i = 0; i < joinArray.length && left != 0; ++i) {
403 if (joinArray[i] != null) {
404 Way c = joinArray[i];
405 if (w == null) {
406 w = c;
407 selected = w.isSelected();
408 joinArray[i] = null;
409 --left;
410 } else {
411 int mode = 0;
412 int cl = c.getNodesCount()-1;
413 int nl;
414 if (nodes == null) {
415 nl = w.getNodesCount()-1;
416 if (w.getNode(nl) == c.getNode(0)) {
417 mode = 21;
418 } else if (w.getNode(nl) == c.getNode(cl)) {
419 mode = 22;
420 } else if (w.getNode(0) == c.getNode(0)) {
421 mode = 11;
422 } else if (w.getNode(0) == c.getNode(cl)) {
423 mode = 12;
424 }
425 } else {
426 nl = nodes.size()-1;
427 if (nodes.get(nl) == c.getNode(0)) {
428 mode = 21;
429 } else if (nodes.get(0) == c.getNode(cl)) {
430 mode = 12;
431 } else if (nodes.get(0) == c.getNode(0)) {
432 mode = 11;
433 } else if (nodes.get(nl) == c.getNode(cl)) {
434 mode = 22;
435 }
436 }
437 if (mode != 0) {
438 joinArray[i] = null;
439 joined = true;
440 if (c.isSelected()) {
441 selected = true;
442 }
443 --left;
444 if (nodes == null) {
445 nodes = w.getNodes();
446 wayIds.add(w.getUniqueId());
447 }
448 nodes.remove((mode == 21 || mode == 22) ? nl : 0);
449 if (mode == 21) {
450 nodes.addAll(c.getNodes());
451 } else if (mode == 12) {
452 nodes.addAll(0, c.getNodes());
453 } else if (mode == 22) {
454 for (Node node : c.getNodes()) {
455 nodes.add(nl, node);
456 }
457 } else /* mode == 11 */ {
458 for (Node node : c.getNodes()) {
459 nodes.add(0, node);
460 }
461 }
462 wayIds.add(c.getUniqueId());
463 }
464 }
465 }
466 } /* for(i = ... */
467 } /* while(joined) */
468
469 if (nodes == null) {
470 nodes = w.getNodes();
471 wayIds.add(w.getUniqueId());
472 }
473
474 result.add(new JoinedWay(nodes, wayIds, selected));
475 } /* while(left != 0) */
476
477 return result;
478 }
479
480 public PolyData findOuterPolygon(PolyData inner, List<PolyData> outerPolygons) {
481
482 // First try to test only bbox, use precise testing only if we don't get unique result
483 Rectangle2D innerBox = inner.getBounds();
484 PolyData insidePolygon = null;
485 PolyData intersectingPolygon = null;
486 int insideCount = 0;
487 int intersectingCount = 0;
488
489 for (PolyData outer: outerPolygons) {
490 if (outer.getBounds().contains(innerBox)) {
491 insidePolygon = outer;
492 insideCount++;
493 } else if (outer.getBounds().intersects(innerBox)) {
494 intersectingPolygon = outer;
495 intersectingCount++;
496 }
497 }
498
499 if (insideCount == 1)
500 return insidePolygon;
501 else if (intersectingCount == 1)
502 return intersectingPolygon;
503
504 PolyData result = null;
505 for (PolyData combined : outerPolygons) {
506 Intersection c = combined.contains(inner.poly);
507 if (c != Intersection.OUTSIDE)
508 {
509 if (result == null || result.contains(combined.poly) != Intersection.INSIDE) {
510 result = combined;
511 }
512 }
513 }
514 return result;
515 }
516
517 private void addInnerToOuters() {
518
519 if (innerPolygons.isEmpty()) {
520 combinedPolygons.addAll(outerPolygons);
521 } else if (outerPolygons.size() == 1) {
522 PolyData combinedOuter = new PolyData(outerPolygons.get(0));
523 for (PolyData inner: innerPolygons) {
524 combinedOuter.addInner(inner);
525 }
526 combinedPolygons.add(combinedOuter);
527 } else {
528 for (PolyData outer: outerPolygons) {
529 combinedPolygons.add(new PolyData(outer));
530 }
531
532 for (PolyData pdInner: innerPolygons) {
533 PolyData o = findOuterPolygon(pdInner, combinedPolygons);
534 if (o == null) {
535 o = outerPolygons.get(0);
536 }
537 o.addInner(pdInner);
538 }
539 }
540
541 // Clear inner and outer polygons to reduce memory footprint
542 innerPolygons.clear();
543 outerPolygons.clear();
544 }
545
546 public List<Way> getOuterWays() {
547 return outerWays;
548 }
549
550 public List<Way> getInnerWays() {
551 return innerWays;
552 }
553/*
554 public List<PolyData> getInnerPolygons() {
555 return innerPolygons;
556 }
557
558 public List<PolyData> getOuterPolygons() {
559 return outerPolygons;
560 }
561*/
562 public List<PolyData> getCombinedPolygons() {
563 return combinedPolygons;
564 }
565}
Note: See TracBrowser for help on using the repository browser.