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

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

see #7131 and #6987 - Let Multipolygon cache handle incomplete relations

  • Property svn:eol-style set to native
File size: 20.9 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 = new ArrayList<Node>(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 private boolean incomplete;
340
341 public Multipolygon(Relation r) {
342 load(r);
343 }
344
345 private void load(Relation r) {
346 MultipolygonRoleMatcher matcher = getMultipolygonRoleMatcher();
347
348 // Fill inner and outer list with valid ways
349 for (RelationMember m : r.getMembers()) {
350 if (m.getMember().isIncomplete()) {
351 this.incomplete = true;
352 } else if (m.getMember().isDrawable()) {
353 if (m.isWay()) {
354 Way w = m.getWay();
355
356 if (w.getNodesCount() < 2) {
357 continue;
358 }
359
360 if (matcher.isInnerRole(m.getRole())) {
361 innerWays.add(w);
362 } else if (matcher.isOuterRole(m.getRole())) {
363 outerWays.add(w);
364 } else if (!m.hasRole()) {
365 outerWays.add(w);
366 } // Remaining roles ignored
367 } // Non ways ignored
368 }
369 }
370
371 createPolygons(innerWays, innerPolygons);
372 createPolygons(outerWays, outerPolygons);
373 if (!outerPolygons.isEmpty()) {
374 addInnerToOuters();
375 }
376 }
377
378 public final boolean isIncomplete() {
379 return incomplete;
380 }
381
382 private void createPolygons(List<Way> ways, List<PolyData> result) {
383 List<Way> waysToJoin = new ArrayList<Way>();
384 for (Way way: ways) {
385 if (way.isClosed()) {
386 result.add(new PolyData(way));
387 } else {
388 waysToJoin.add(way);
389 }
390 }
391
392 for (JoinedWay jw: joinWays(waysToJoin)) {
393 result.add(new PolyData(jw));
394 }
395 }
396
397 public static Collection<JoinedWay> joinWays(Collection<Way> waysToJoin)
398 {
399 final Collection<JoinedWay> result = new ArrayList<JoinedWay>();
400 final Way[] joinArray = waysToJoin.toArray(new Way[waysToJoin.size()]);
401 int left = waysToJoin.size();
402 while (left > 0) {
403 Way w = null;
404 boolean selected = false;
405 List<Node> nodes = null;
406 Set<Long> wayIds = new HashSet<Long>();
407 boolean joined = true;
408 while (joined && left > 0) {
409 joined = false;
410 for (int i = 0; i < joinArray.length && left != 0; ++i) {
411 if (joinArray[i] != null) {
412 Way c = joinArray[i];
413 if (w == null) {
414 w = c;
415 selected = w.isSelected();
416 joinArray[i] = null;
417 --left;
418 } else {
419 int mode = 0;
420 int cl = c.getNodesCount()-1;
421 int nl;
422 if (nodes == null) {
423 nl = w.getNodesCount()-1;
424 if (w.getNode(nl) == c.getNode(0)) {
425 mode = 21;
426 } else if (w.getNode(nl) == c.getNode(cl)) {
427 mode = 22;
428 } else if (w.getNode(0) == c.getNode(0)) {
429 mode = 11;
430 } else if (w.getNode(0) == c.getNode(cl)) {
431 mode = 12;
432 }
433 } else {
434 nl = nodes.size()-1;
435 if (nodes.get(nl) == c.getNode(0)) {
436 mode = 21;
437 } else if (nodes.get(0) == c.getNode(cl)) {
438 mode = 12;
439 } else if (nodes.get(0) == c.getNode(0)) {
440 mode = 11;
441 } else if (nodes.get(nl) == c.getNode(cl)) {
442 mode = 22;
443 }
444 }
445 if (mode != 0) {
446 joinArray[i] = null;
447 joined = true;
448 if (c.isSelected()) {
449 selected = true;
450 }
451 --left;
452 if (nodes == null) {
453 nodes = w.getNodes();
454 wayIds.add(w.getUniqueId());
455 }
456 nodes.remove((mode == 21 || mode == 22) ? nl : 0);
457 if (mode == 21) {
458 nodes.addAll(c.getNodes());
459 } else if (mode == 12) {
460 nodes.addAll(0, c.getNodes());
461 } else if (mode == 22) {
462 for (Node node : c.getNodes()) {
463 nodes.add(nl, node);
464 }
465 } else /* mode == 11 */ {
466 for (Node node : c.getNodes()) {
467 nodes.add(0, node);
468 }
469 }
470 wayIds.add(c.getUniqueId());
471 }
472 }
473 }
474 } /* for(i = ... */
475 } /* while(joined) */
476
477 if (nodes == null) {
478 nodes = w.getNodes();
479 wayIds.add(w.getUniqueId());
480 }
481
482 result.add(new JoinedWay(nodes, wayIds, selected));
483 } /* while(left != 0) */
484
485 return result;
486 }
487
488 public PolyData findOuterPolygon(PolyData inner, List<PolyData> outerPolygons) {
489
490 // First try to test only bbox, use precise testing only if we don't get unique result
491 Rectangle2D innerBox = inner.getBounds();
492 PolyData insidePolygon = null;
493 PolyData intersectingPolygon = null;
494 int insideCount = 0;
495 int intersectingCount = 0;
496
497 for (PolyData outer: outerPolygons) {
498 if (outer.getBounds().contains(innerBox)) {
499 insidePolygon = outer;
500 insideCount++;
501 } else if (outer.getBounds().intersects(innerBox)) {
502 intersectingPolygon = outer;
503 intersectingCount++;
504 }
505 }
506
507 if (insideCount == 1)
508 return insidePolygon;
509 else if (intersectingCount == 1)
510 return intersectingPolygon;
511
512 PolyData result = null;
513 for (PolyData combined : outerPolygons) {
514 Intersection c = combined.contains(inner.poly);
515 if (c != Intersection.OUTSIDE)
516 {
517 if (result == null || result.contains(combined.poly) != Intersection.INSIDE) {
518 result = combined;
519 }
520 }
521 }
522 return result;
523 }
524
525 private void addInnerToOuters() {
526
527 if (innerPolygons.isEmpty()) {
528 combinedPolygons.addAll(outerPolygons);
529 } else if (outerPolygons.size() == 1) {
530 PolyData combinedOuter = new PolyData(outerPolygons.get(0));
531 for (PolyData inner: innerPolygons) {
532 combinedOuter.addInner(inner);
533 }
534 combinedPolygons.add(combinedOuter);
535 } else {
536 for (PolyData outer: outerPolygons) {
537 combinedPolygons.add(new PolyData(outer));
538 }
539
540 for (PolyData pdInner: innerPolygons) {
541 PolyData o = findOuterPolygon(pdInner, combinedPolygons);
542 if (o == null) {
543 o = outerPolygons.get(0);
544 }
545 o.addInner(pdInner);
546 }
547 }
548
549 // Clear inner and outer polygons to reduce memory footprint
550 innerPolygons.clear();
551 outerPolygons.clear();
552 }
553
554 public List<Way> getOuterWays() {
555 return outerWays;
556 }
557
558 public List<Way> getInnerWays() {
559 return innerWays;
560 }
561/*
562 public List<PolyData> getInnerPolygons() {
563 return innerPolygons;
564 }
565
566 public List<PolyData> getOuterPolygons() {
567 return outerPolygons;
568 }
569*/
570 public List<PolyData> getCombinedPolygons() {
571 return combinedPolygons;
572 }
573}
Note: See TracBrowser for help on using the repository browser.