source: josm/trunk/src/org/openstreetmap/josm/tools/Geometry.java@ 12718

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

see #13036 - see #15229 - see #15182 - make Commands depends only on a DataSet, not a Layer. This removes a lot of GUI dependencies

  • Property svn:eol-style set to native
File size: 40.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import java.awt.Rectangle;
5import java.awt.geom.Area;
6import java.awt.geom.Line2D;
7import java.awt.geom.Path2D;
8import java.math.BigDecimal;
9import java.math.MathContext;
10import java.util.ArrayList;
11import java.util.Collections;
12import java.util.Comparator;
13import java.util.EnumSet;
14import java.util.LinkedHashSet;
15import java.util.List;
16import java.util.Set;
17import java.util.function.Predicate;
18
19import org.openstreetmap.josm.Main;
20import org.openstreetmap.josm.command.AddCommand;
21import org.openstreetmap.josm.command.ChangeCommand;
22import org.openstreetmap.josm.command.Command;
23import org.openstreetmap.josm.data.coor.EastNorth;
24import org.openstreetmap.josm.data.osm.BBox;
25import org.openstreetmap.josm.data.osm.DataSet;
26import org.openstreetmap.josm.data.osm.MultipolygonBuilder;
27import org.openstreetmap.josm.data.osm.MultipolygonBuilder.JoinedPolygon;
28import org.openstreetmap.josm.data.osm.Node;
29import org.openstreetmap.josm.data.osm.NodePositionComparator;
30import org.openstreetmap.josm.data.osm.OsmPrimitive;
31import org.openstreetmap.josm.data.osm.Relation;
32import org.openstreetmap.josm.data.osm.Way;
33import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon;
34import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
35import org.openstreetmap.josm.data.projection.Projection;
36import org.openstreetmap.josm.data.projection.Projections;
37import org.openstreetmap.josm.gui.MainApplication;
38import org.openstreetmap.josm.gui.MapFrame;
39
40/**
41 * Some tools for geometry related tasks.
42 *
43 * @author viesturs
44 */
45public final class Geometry {
46
47 private Geometry() {
48 // Hide default constructor for utils classes
49 }
50
51 /**
52 * The result types for a {@link Geometry#polygonIntersection(Area, Area)} test
53 */
54 public enum PolygonIntersection {
55 /**
56 * The first polygon is inside the second one
57 */
58 FIRST_INSIDE_SECOND,
59 /**
60 * The second one is inside the first
61 */
62 SECOND_INSIDE_FIRST,
63 /**
64 * The polygons do not overlap
65 */
66 OUTSIDE,
67 /**
68 * The polygon borders cross each other
69 */
70 CROSSING
71 }
72
73 /**
74 * Will find all intersection and add nodes there for list of given ways.
75 * Handles self-intersections too.
76 * And makes commands to add the intersection points to ways.
77 *
78 * Prerequisite: no two nodes have the same coordinates.
79 *
80 * @param ways a list of ways to test
81 * @param test if false, do not build list of Commands, just return nodes
82 * @param cmds list of commands, typically empty when handed to this method.
83 * Will be filled with commands that add intersection nodes to
84 * the ways.
85 * @return list of new nodes
86 */
87 public static Set<Node> addIntersections(List<Way> ways, boolean test, List<Command> cmds) {
88
89 int n = ways.size();
90 @SuppressWarnings("unchecked")
91 List<Node>[] newNodes = new ArrayList[n];
92 BBox[] wayBounds = new BBox[n];
93 boolean[] changedWays = new boolean[n];
94
95 Set<Node> intersectionNodes = new LinkedHashSet<>();
96
97 //copy node arrays for local usage.
98 for (int pos = 0; pos < n; pos++) {
99 newNodes[pos] = new ArrayList<>(ways.get(pos).getNodes());
100 wayBounds[pos] = getNodesBounds(newNodes[pos]);
101 changedWays[pos] = false;
102 }
103
104 DataSet dataset = ways.get(0).getDataSet();
105
106 //iterate over all way pairs and introduce the intersections
107 Comparator<Node> coordsComparator = new NodePositionComparator();
108 for (int seg1Way = 0; seg1Way < n; seg1Way++) {
109 for (int seg2Way = seg1Way; seg2Way < n; seg2Way++) {
110
111 //do not waste time on bounds that do not intersect
112 if (!wayBounds[seg1Way].intersects(wayBounds[seg2Way])) {
113 continue;
114 }
115
116 List<Node> way1Nodes = newNodes[seg1Way];
117 List<Node> way2Nodes = newNodes[seg2Way];
118
119 //iterate over primary segmemt
120 for (int seg1Pos = 0; seg1Pos + 1 < way1Nodes.size(); seg1Pos++) {
121
122 //iterate over secondary segment
123 int seg2Start = seg1Way != seg2Way ? 0 : seg1Pos + 2; //skip the adjacent segment
124
125 for (int seg2Pos = seg2Start; seg2Pos + 1 < way2Nodes.size(); seg2Pos++) {
126
127 //need to get them again every time, because other segments may be changed
128 Node seg1Node1 = way1Nodes.get(seg1Pos);
129 Node seg1Node2 = way1Nodes.get(seg1Pos + 1);
130 Node seg2Node1 = way2Nodes.get(seg2Pos);
131 Node seg2Node2 = way2Nodes.get(seg2Pos + 1);
132
133 int commonCount = 0;
134 //test if we have common nodes to add.
135 if (seg1Node1 == seg2Node1 || seg1Node1 == seg2Node2) {
136 commonCount++;
137
138 if (seg1Way == seg2Way &&
139 seg1Pos == 0 &&
140 seg2Pos == way2Nodes.size() -2) {
141 //do not add - this is first and last segment of the same way.
142 } else {
143 intersectionNodes.add(seg1Node1);
144 }
145 }
146
147 if (seg1Node2 == seg2Node1 || seg1Node2 == seg2Node2) {
148 commonCount++;
149
150 intersectionNodes.add(seg1Node2);
151 }
152
153 //no common nodes - find intersection
154 if (commonCount == 0) {
155 EastNorth intersection = getSegmentSegmentIntersection(
156 seg1Node1.getEastNorth(), seg1Node2.getEastNorth(),
157 seg2Node1.getEastNorth(), seg2Node2.getEastNorth());
158
159 if (intersection != null) {
160 if (test) {
161 intersectionNodes.add(seg2Node1);
162 return intersectionNodes;
163 }
164
165 Node newNode = new Node(Main.getProjection().eastNorth2latlon(intersection));
166 Node intNode = newNode;
167 boolean insertInSeg1 = false;
168 boolean insertInSeg2 = false;
169 //find if the intersection point is at end point of one of the segments, if so use that point
170
171 //segment 1
172 if (coordsComparator.compare(newNode, seg1Node1) == 0) {
173 intNode = seg1Node1;
174 } else if (coordsComparator.compare(newNode, seg1Node2) == 0) {
175 intNode = seg1Node2;
176 } else {
177 insertInSeg1 = true;
178 }
179
180 //segment 2
181 if (coordsComparator.compare(newNode, seg2Node1) == 0) {
182 intNode = seg2Node1;
183 } else if (coordsComparator.compare(newNode, seg2Node2) == 0) {
184 intNode = seg2Node2;
185 } else {
186 insertInSeg2 = true;
187 }
188
189 if (insertInSeg1) {
190 way1Nodes.add(seg1Pos +1, intNode);
191 changedWays[seg1Way] = true;
192
193 //fix seg2 position, as indexes have changed, seg2Pos is always bigger than seg1Pos on the same segment.
194 if (seg2Way == seg1Way) {
195 seg2Pos++;
196 }
197 }
198
199 if (insertInSeg2) {
200 way2Nodes.add(seg2Pos +1, intNode);
201 changedWays[seg2Way] = true;
202
203 //Do not need to compare again to already split segment
204 seg2Pos++;
205 }
206
207 intersectionNodes.add(intNode);
208
209 if (intNode == newNode) {
210 cmds.add(new AddCommand(dataset, intNode));
211 }
212 }
213 } else if (test && !intersectionNodes.isEmpty())
214 return intersectionNodes;
215 }
216 }
217 }
218 }
219
220
221 for (int pos = 0; pos < ways.size(); pos++) {
222 if (!changedWays[pos]) {
223 continue;
224 }
225
226 Way way = ways.get(pos);
227 Way newWay = new Way(way);
228 newWay.setNodes(newNodes[pos]);
229
230 cmds.add(new ChangeCommand(way, newWay));
231 }
232
233 return intersectionNodes;
234 }
235
236 private static BBox getNodesBounds(List<Node> nodes) {
237
238 BBox bounds = new BBox(nodes.get(0));
239 for (Node n: nodes) {
240 bounds.add(n);
241 }
242 return bounds;
243 }
244
245 /**
246 * Tests if given point is to the right side of path consisting of 3 points.
247 *
248 * (Imagine the path is continued beyond the endpoints, so you get two rays
249 * starting from lineP2 and going through lineP1 and lineP3 respectively
250 * which divide the plane into two parts. The test returns true, if testPoint
251 * lies in the part that is to the right when traveling in the direction
252 * lineP1, lineP2, lineP3.)
253 *
254 * @param lineP1 first point in path
255 * @param lineP2 second point in path
256 * @param lineP3 third point in path
257 * @param testPoint point to test
258 * @return true if to the right side, false otherwise
259 */
260 public static boolean isToTheRightSideOfLine(Node lineP1, Node lineP2, Node lineP3, Node testPoint) {
261 boolean pathBendToRight = angleIsClockwise(lineP1, lineP2, lineP3);
262 boolean rightOfSeg1 = angleIsClockwise(lineP1, lineP2, testPoint);
263 boolean rightOfSeg2 = angleIsClockwise(lineP2, lineP3, testPoint);
264
265 if (pathBendToRight)
266 return rightOfSeg1 && rightOfSeg2;
267 else
268 return !(!rightOfSeg1 && !rightOfSeg2);
269 }
270
271 /**
272 * This method tests if secondNode is clockwise to first node.
273 * @param commonNode starting point for both vectors
274 * @param firstNode first vector end node
275 * @param secondNode second vector end node
276 * @return true if first vector is clockwise before second vector.
277 */
278 public static boolean angleIsClockwise(Node commonNode, Node firstNode, Node secondNode) {
279 return angleIsClockwise(commonNode.getEastNorth(), firstNode.getEastNorth(), secondNode.getEastNorth());
280 }
281
282 /**
283 * Finds the intersection of two line segments.
284 * @param p1 the coordinates of the start point of the first specified line segment
285 * @param p2 the coordinates of the end point of the first specified line segment
286 * @param p3 the coordinates of the start point of the second specified line segment
287 * @param p4 the coordinates of the end point of the second specified line segment
288 * @return EastNorth null if no intersection was found, the EastNorth coordinates of the intersection otherwise
289 */
290 public static EastNorth getSegmentSegmentIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
291
292 CheckParameterUtil.ensure(p1, "p1", EastNorth::isValid);
293 CheckParameterUtil.ensure(p2, "p2", EastNorth::isValid);
294 CheckParameterUtil.ensure(p3, "p3", EastNorth::isValid);
295 CheckParameterUtil.ensure(p4, "p4", EastNorth::isValid);
296
297 double x1 = p1.getX();
298 double y1 = p1.getY();
299 double x2 = p2.getX();
300 double y2 = p2.getY();
301 double x3 = p3.getX();
302 double y3 = p3.getY();
303 double x4 = p4.getX();
304 double y4 = p4.getY();
305
306 //TODO: do this locally.
307 //TODO: remove this check after careful testing
308 if (!Line2D.linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return null;
309
310 // solve line-line intersection in parametric form:
311 // (x1,y1) + (x2-x1,y2-y1)* u = (x3,y3) + (x4-x3,y4-y3)* v
312 // (x2-x1,y2-y1)*u - (x4-x3,y4-y3)*v = (x3-x1,y3-y1)
313 // if 0<= u,v <=1, intersection exists at ( x1+ (x2-x1)*u, y1 + (y2-y1)*u )
314
315 double a1 = x2 - x1;
316 double b1 = x3 - x4;
317 double c1 = x3 - x1;
318
319 double a2 = y2 - y1;
320 double b2 = y3 - y4;
321 double c2 = y3 - y1;
322
323 // Solve the equations
324 double det = a1*b2 - a2*b1;
325
326 double uu = b2*c1 - b1*c2;
327 double vv = a1*c2 - a2*c1;
328 double mag = Math.abs(uu)+Math.abs(vv);
329
330 if (Math.abs(det) > 1e-12 * mag) {
331 double u = uu/det, v = vv/det;
332 if (u > -1e-8 && u < 1+1e-8 && v > -1e-8 && v < 1+1e-8) {
333 if (u < 0) u = 0;
334 if (u > 1) u = 1.0;
335 return new EastNorth(x1+a1*u, y1+a2*u);
336 } else {
337 return null;
338 }
339 } else {
340 // parallel lines
341 return null;
342 }
343 }
344
345 /**
346 * Finds the intersection of two lines of infinite length.
347 *
348 * @param p1 first point on first line
349 * @param p2 second point on first line
350 * @param p3 first point on second line
351 * @param p4 second point on second line
352 * @return EastNorth null if no intersection was found, the coordinates of the intersection otherwise
353 * @throws IllegalArgumentException if a parameter is null or without valid coordinates
354 */
355 public static EastNorth getLineLineIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
356
357 CheckParameterUtil.ensure(p1, "p1", EastNorth::isValid);
358 CheckParameterUtil.ensure(p2, "p2", EastNorth::isValid);
359 CheckParameterUtil.ensure(p3, "p3", EastNorth::isValid);
360 CheckParameterUtil.ensure(p4, "p4", EastNorth::isValid);
361
362 // Basically, the formula from wikipedia is used:
363 // https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
364 // However, large numbers lead to rounding errors (see #10286).
365 // To avoid this, p1 is first substracted from each of the points:
366 // p1' = 0
367 // p2' = p2 - p1
368 // p3' = p3 - p1
369 // p4' = p4 - p1
370 // In the end, p1 is added to the intersection point of segment p1'/p2'
371 // and segment p3'/p4'.
372
373 // Convert line from (point, point) form to ax+by=c
374 double a1 = p2.getY() - p1.getY();
375 double b1 = p1.getX() - p2.getX();
376
377 double a2 = p4.getY() - p3.getY();
378 double b2 = p3.getX() - p4.getX();
379
380 // Solve the equations
381 double det = a1 * b2 - a2 * b1;
382 if (det == 0)
383 return null; // Lines are parallel
384
385 double c2 = (p4.getX() - p1.getX()) * (p3.getY() - p1.getY()) - (p3.getX() - p1.getX()) * (p4.getY() - p1.getY());
386
387 return new EastNorth(b1 * c2 / det + p1.getX(), -a1 * c2 / det + p1.getY());
388 }
389
390 /**
391 * Check if the segment p1 - p2 is parallel to p3 - p4
392 * @param p1 First point for first segment
393 * @param p2 Second point for first segment
394 * @param p3 First point for second segment
395 * @param p4 Second point for second segment
396 * @return <code>true</code> if they are parallel or close to parallel
397 */
398 public static boolean segmentsParallel(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
399
400 CheckParameterUtil.ensure(p1, "p1", EastNorth::isValid);
401 CheckParameterUtil.ensure(p2, "p2", EastNorth::isValid);
402 CheckParameterUtil.ensure(p3, "p3", EastNorth::isValid);
403 CheckParameterUtil.ensure(p4, "p4", EastNorth::isValid);
404
405 // Convert line from (point, point) form to ax+by=c
406 double a1 = p2.getY() - p1.getY();
407 double b1 = p1.getX() - p2.getX();
408
409 double a2 = p4.getY() - p3.getY();
410 double b2 = p3.getX() - p4.getX();
411
412 // Solve the equations
413 double det = a1 * b2 - a2 * b1;
414 // remove influence of of scaling factor
415 det /= Math.sqrt(a1*a1 + b1*b1) * Math.sqrt(a2*a2 + b2*b2);
416 return Math.abs(det) < 1e-3;
417 }
418
419 private static EastNorth closestPointTo(EastNorth p1, EastNorth p2, EastNorth point, boolean segmentOnly) {
420 CheckParameterUtil.ensureParameterNotNull(p1, "p1");
421 CheckParameterUtil.ensureParameterNotNull(p2, "p2");
422 CheckParameterUtil.ensureParameterNotNull(point, "point");
423
424 double ldx = p2.getX() - p1.getX();
425 double ldy = p2.getY() - p1.getY();
426
427 //segment zero length
428 if (ldx == 0 && ldy == 0)
429 return p1;
430
431 double pdx = point.getX() - p1.getX();
432 double pdy = point.getY() - p1.getY();
433
434 double offset = (pdx * ldx + pdy * ldy) / (ldx * ldx + ldy * ldy);
435
436 if (segmentOnly && offset <= 0)
437 return p1;
438 else if (segmentOnly && offset >= 1)
439 return p2;
440 else
441 return p1.interpolate(p2, offset);
442 }
443
444 /**
445 * Calculates closest point to a line segment.
446 * @param segmentP1 First point determining line segment
447 * @param segmentP2 Second point determining line segment
448 * @param point Point for which a closest point is searched on line segment [P1,P2]
449 * @return segmentP1 if it is the closest point, segmentP2 if it is the closest point,
450 * a new point if closest point is between segmentP1 and segmentP2.
451 * @see #closestPointToLine
452 * @since 3650
453 */
454 public static EastNorth closestPointToSegment(EastNorth segmentP1, EastNorth segmentP2, EastNorth point) {
455 return closestPointTo(segmentP1, segmentP2, point, true);
456 }
457
458 /**
459 * Calculates closest point to a line.
460 * @param lineP1 First point determining line
461 * @param lineP2 Second point determining line
462 * @param point Point for which a closest point is searched on line (P1,P2)
463 * @return The closest point found on line. It may be outside the segment [P1,P2].
464 * @see #closestPointToSegment
465 * @since 4134
466 */
467 public static EastNorth closestPointToLine(EastNorth lineP1, EastNorth lineP2, EastNorth point) {
468 return closestPointTo(lineP1, lineP2, point, false);
469 }
470
471 /**
472 * This method tests if secondNode is clockwise to first node.
473 *
474 * The line through the two points commonNode and firstNode divides the
475 * plane into two parts. The test returns true, if secondNode lies in
476 * the part that is to the right when traveling in the direction from
477 * commonNode to firstNode.
478 *
479 * @param commonNode starting point for both vectors
480 * @param firstNode first vector end node
481 * @param secondNode second vector end node
482 * @return true if first vector is clockwise before second vector.
483 */
484 public static boolean angleIsClockwise(EastNorth commonNode, EastNorth firstNode, EastNorth secondNode) {
485
486 CheckParameterUtil.ensure(commonNode, "commonNode", EastNorth::isValid);
487 CheckParameterUtil.ensure(firstNode, "firstNode", EastNorth::isValid);
488 CheckParameterUtil.ensure(secondNode, "secondNode", EastNorth::isValid);
489
490 double dy1 = firstNode.getY() - commonNode.getY();
491 double dy2 = secondNode.getY() - commonNode.getY();
492 double dx1 = firstNode.getX() - commonNode.getX();
493 double dx2 = secondNode.getX() - commonNode.getX();
494
495 return dy1 * dx2 - dx1 * dy2 > 0;
496 }
497
498 /**
499 * Returns the Area of a polygon, from its list of nodes.
500 * @param polygon List of nodes forming polygon
501 * @return Area for the given list of nodes (EastNorth coordinates)
502 * @since 6841
503 */
504 public static Area getArea(List<Node> polygon) {
505 Path2D path = new Path2D.Double();
506
507 boolean begin = true;
508 for (Node n : polygon) {
509 EastNorth en = n.getEastNorth();
510 if (en != null) {
511 if (begin) {
512 path.moveTo(en.getX(), en.getY());
513 begin = false;
514 } else {
515 path.lineTo(en.getX(), en.getY());
516 }
517 }
518 }
519 if (!begin) {
520 path.closePath();
521 }
522
523 return new Area(path);
524 }
525
526 /**
527 * Builds a path from a list of nodes
528 * @param polygon Nodes, forming a closed polygon
529 * @param path2d path to add to; can be null, then a new path is created
530 * @return the path (LatLon coordinates)
531 */
532 public static Path2D buildPath2DLatLon(List<Node> polygon, Path2D path2d) {
533 Path2D path = path2d != null ? path2d : new Path2D.Double();
534 boolean begin = true;
535 for (Node n : polygon) {
536 if (begin) {
537 path.moveTo(n.lon(), n.lat());
538 begin = false;
539 } else {
540 path.lineTo(n.lon(), n.lat());
541 }
542 }
543 if (!begin) {
544 path.closePath();
545 }
546 return path;
547 }
548
549 /**
550 * Returns the Area of a polygon, from the multipolygon relation.
551 * @param multipolygon the multipolygon relation
552 * @return Area for the multipolygon (LatLon coordinates)
553 */
554 public static Area getAreaLatLon(Relation multipolygon) {
555 MapFrame map = MainApplication.getMap();
556 final Multipolygon mp = map == null || map.mapView == null
557 ? new Multipolygon(multipolygon)
558 : MultipolygonCache.getInstance().get(multipolygon);
559 Path2D path = new Path2D.Double();
560 path.setWindingRule(Path2D.WIND_EVEN_ODD);
561 for (Multipolygon.PolyData pd : mp.getCombinedPolygons()) {
562 buildPath2DLatLon(pd.getNodes(), path);
563 for (Multipolygon.PolyData pdInner : pd.getInners()) {
564 buildPath2DLatLon(pdInner.getNodes(), path);
565 }
566 }
567 return new Area(path);
568 }
569
570 /**
571 * Tests if two polygons intersect.
572 * @param first List of nodes forming first polygon
573 * @param second List of nodes forming second polygon
574 * @return intersection kind
575 */
576 public static PolygonIntersection polygonIntersection(List<Node> first, List<Node> second) {
577 Area a1 = getArea(first);
578 Area a2 = getArea(second);
579 return polygonIntersection(a1, a2);
580 }
581
582 /**
583 * Tests if two polygons intersect.
584 * @param a1 Area of first polygon
585 * @param a2 Area of second polygon
586 * @return intersection kind
587 * @since 6841
588 */
589 public static PolygonIntersection polygonIntersection(Area a1, Area a2) {
590 return polygonIntersection(a1, a2, 1.0);
591 }
592
593 /**
594 * Tests if two polygons intersect.
595 * @param a1 Area of first polygon
596 * @param a2 Area of second polygon
597 * @param eps an area threshold, everything below is considered an empty intersection
598 * @return intersection kind
599 */
600 public static PolygonIntersection polygonIntersection(Area a1, Area a2, double eps) {
601
602 Area inter = new Area(a1);
603 inter.intersect(a2);
604
605 Rectangle bounds = inter.getBounds();
606
607 if (inter.isEmpty() || bounds.getHeight()*bounds.getWidth() <= eps) {
608 return PolygonIntersection.OUTSIDE;
609 } else if (a2.getBounds2D().contains(a1.getBounds2D()) && inter.equals(a1)) {
610 return PolygonIntersection.FIRST_INSIDE_SECOND;
611 } else if (a1.getBounds2D().contains(a2.getBounds2D()) && inter.equals(a2)) {
612 return PolygonIntersection.SECOND_INSIDE_FIRST;
613 } else {
614 return PolygonIntersection.CROSSING;
615 }
616 }
617
618 /**
619 * Tests if point is inside a polygon. The polygon can be self-intersecting. In such case the contains function works in xor-like manner.
620 * @param polygonNodes list of nodes from polygon path.
621 * @param point the point to test
622 * @return true if the point is inside polygon.
623 */
624 public static boolean nodeInsidePolygon(Node point, List<Node> polygonNodes) {
625 if (polygonNodes.size() < 2)
626 return false;
627
628 //iterate each side of the polygon, start with the last segment
629 Node oldPoint = polygonNodes.get(polygonNodes.size() - 1);
630
631 if (!oldPoint.isLatLonKnown()) {
632 return false;
633 }
634
635 boolean inside = false;
636 Node p1, p2;
637
638 for (Node newPoint : polygonNodes) {
639 //skip duplicate points
640 if (newPoint.equals(oldPoint)) {
641 continue;
642 }
643
644 if (!newPoint.isLatLonKnown()) {
645 return false;
646 }
647
648 //order points so p1.lat <= p2.lat
649 if (newPoint.getEastNorth().getY() > oldPoint.getEastNorth().getY()) {
650 p1 = oldPoint;
651 p2 = newPoint;
652 } else {
653 p1 = newPoint;
654 p2 = oldPoint;
655 }
656
657 EastNorth pEN = point.getEastNorth();
658 EastNorth opEN = oldPoint.getEastNorth();
659 EastNorth npEN = newPoint.getEastNorth();
660 EastNorth p1EN = p1.getEastNorth();
661 EastNorth p2EN = p2.getEastNorth();
662
663 if (pEN != null && opEN != null && npEN != null && p1EN != null && p2EN != null) {
664 //test if the line is crossed and if so invert the inside flag.
665 if ((npEN.getY() < pEN.getY()) == (pEN.getY() <= opEN.getY())
666 && (pEN.getX() - p1EN.getX()) * (p2EN.getY() - p1EN.getY())
667 < (p2EN.getX() - p1EN.getX()) * (pEN.getY() - p1EN.getY())) {
668 inside = !inside;
669 }
670 }
671
672 oldPoint = newPoint;
673 }
674
675 return inside;
676 }
677
678 /**
679 * Returns area of a closed way in square meters.
680 *
681 * @param way Way to measure, should be closed (first node is the same as last node)
682 * @return area of the closed way.
683 */
684 public static double closedWayArea(Way way) {
685 return getAreaAndPerimeter(way.getNodes(), Projections.getProjectionByCode("EPSG:54008")).getArea();
686 }
687
688 /**
689 * Returns area of a multipolygon in square meters.
690 *
691 * @param multipolygon the multipolygon to measure
692 * @return area of the multipolygon.
693 */
694 public static double multipolygonArea(Relation multipolygon) {
695 double area = 0.0;
696 MapFrame map = MainApplication.getMap();
697 final Multipolygon mp = map == null || map.mapView == null
698 ? new Multipolygon(multipolygon)
699 : MultipolygonCache.getInstance().get(multipolygon);
700 for (Multipolygon.PolyData pd : mp.getCombinedPolygons()) {
701 area += pd.getAreaAndPerimeter(Projections.getProjectionByCode("EPSG:54008")).getArea();
702 }
703 return area;
704 }
705
706 /**
707 * Computes the area of a closed way and multipolygon in square meters, or {@code null} for other primitives
708 *
709 * @param osm the primitive to measure
710 * @return area of the primitive, or {@code null}
711 */
712 public static Double computeArea(OsmPrimitive osm) {
713 if (osm instanceof Way && ((Way) osm).isClosed()) {
714 return closedWayArea((Way) osm);
715 } else if (osm instanceof Relation && ((Relation) osm).isMultipolygon() && !((Relation) osm).hasIncompleteMembers()) {
716 return multipolygonArea((Relation) osm);
717 } else {
718 return null;
719 }
720 }
721
722 /**
723 * Determines whether a way is oriented clockwise.
724 *
725 * Internals: Assuming a closed non-looping way, compute twice the area
726 * of the polygon using the formula {@code 2 * area = sum (X[n] * Y[n+1] - X[n+1] * Y[n])}.
727 * If the area is negative the way is ordered in a clockwise direction.
728 *
729 * See http://paulbourke.net/geometry/polyarea/
730 *
731 * @param w the way to be checked.
732 * @return true if and only if way is oriented clockwise.
733 * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}).
734 */
735 public static boolean isClockwise(Way w) {
736 return isClockwise(w.getNodes());
737 }
738
739 /**
740 * Determines whether path from nodes list is oriented clockwise.
741 * @param nodes Nodes list to be checked.
742 * @return true if and only if way is oriented clockwise.
743 * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}).
744 * @see #isClockwise(Way)
745 */
746 public static boolean isClockwise(List<Node> nodes) {
747 int nodesCount = nodes.size();
748 if (nodesCount < 3 || nodes.get(0) != nodes.get(nodesCount - 1)) {
749 throw new IllegalArgumentException("Way must be closed to check orientation.");
750 }
751 double area2 = 0.;
752
753 for (int node = 1; node <= /*sic! consider last-first as well*/ nodesCount; node++) {
754 Node coorPrev = nodes.get(node - 1);
755 Node coorCurr = nodes.get(node % nodesCount);
756 area2 += coorPrev.lon() * coorCurr.lat();
757 area2 -= coorCurr.lon() * coorPrev.lat();
758 }
759 return area2 < 0;
760 }
761
762 /**
763 * Returns angle of a segment defined with 2 point coordinates.
764 *
765 * @param p1 first point
766 * @param p2 second point
767 * @return Angle in radians (-pi, pi]
768 */
769 public static double getSegmentAngle(EastNorth p1, EastNorth p2) {
770
771 CheckParameterUtil.ensure(p1, "p1", EastNorth::isValid);
772 CheckParameterUtil.ensure(p2, "p2", EastNorth::isValid);
773
774 return Math.atan2(p2.north() - p1.north(), p2.east() - p1.east());
775 }
776
777 /**
778 * Returns angle of a corner defined with 3 point coordinates.
779 *
780 * @param p1 first point
781 * @param p2 Common endpoint
782 * @param p3 third point
783 * @return Angle in radians (-pi, pi]
784 */
785 public static double getCornerAngle(EastNorth p1, EastNorth p2, EastNorth p3) {
786
787 CheckParameterUtil.ensure(p1, "p1", EastNorth::isValid);
788 CheckParameterUtil.ensure(p2, "p2", EastNorth::isValid);
789 CheckParameterUtil.ensure(p3, "p3", EastNorth::isValid);
790
791 Double result = getSegmentAngle(p2, p1) - getSegmentAngle(p2, p3);
792 if (result <= -Math.PI) {
793 result += 2 * Math.PI;
794 }
795
796 if (result > Math.PI) {
797 result -= 2 * Math.PI;
798 }
799
800 return result;
801 }
802
803 /**
804 * Compute the centroid/barycenter of nodes
805 * @param nodes Nodes for which the centroid is wanted
806 * @return the centroid of nodes
807 * @see Geometry#getCenter
808 */
809 public static EastNorth getCentroid(List<Node> nodes) {
810
811 BigDecimal area = BigDecimal.ZERO;
812 BigDecimal north = BigDecimal.ZERO;
813 BigDecimal east = BigDecimal.ZERO;
814
815 // See https://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon for the equation used here
816 for (int i = 0; i < nodes.size(); i++) {
817 EastNorth n0 = nodes.get(i).getEastNorth();
818 EastNorth n1 = nodes.get((i+1) % nodes.size()).getEastNorth();
819
820 if (n0 != null && n1 != null && n0.isValid() && n1.isValid()) {
821 BigDecimal x0 = BigDecimal.valueOf(n0.east());
822 BigDecimal y0 = BigDecimal.valueOf(n0.north());
823 BigDecimal x1 = BigDecimal.valueOf(n1.east());
824 BigDecimal y1 = BigDecimal.valueOf(n1.north());
825
826 BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128));
827
828 area = area.add(k, MathContext.DECIMAL128);
829 east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128));
830 north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128));
831 }
832 }
833
834 BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3
835 area = area.multiply(d, MathContext.DECIMAL128);
836 if (area.compareTo(BigDecimal.ZERO) != 0) {
837 north = north.divide(area, MathContext.DECIMAL128);
838 east = east.divide(area, MathContext.DECIMAL128);
839 }
840
841 return new EastNorth(east.doubleValue(), north.doubleValue());
842 }
843
844 /**
845 * Compute center of the circle closest to different nodes.
846 *
847 * Ensure exact center computation in case nodes are already aligned in circle.
848 * This is done by least square method.
849 * Let be a_i x + b_i y + c_i = 0 equations of bisectors of each edges.
850 * Center must be intersection of all bisectors.
851 * <pre>
852 * [ a1 b1 ] [ -c1 ]
853 * With A = [ ... ... ] and Y = [ ... ]
854 * [ an bn ] [ -cn ]
855 * </pre>
856 * An approximation of center of circle is (At.A)^-1.At.Y
857 * @param nodes Nodes parts of the circle (at least 3)
858 * @return An approximation of the center, of null if there is no solution.
859 * @see Geometry#getCentroid
860 * @since 6934
861 */
862 public static EastNorth getCenter(List<Node> nodes) {
863 int nc = nodes.size();
864 if (nc < 3) return null;
865 /**
866 * Equation of each bisector ax + by + c = 0
867 */
868 double[] a = new double[nc];
869 double[] b = new double[nc];
870 double[] c = new double[nc];
871 // Compute equation of bisector
872 for (int i = 0; i < nc; i++) {
873 EastNorth pt1 = nodes.get(i).getEastNorth();
874 EastNorth pt2 = nodes.get((i+1) % nc).getEastNorth();
875 a[i] = pt1.east() - pt2.east();
876 b[i] = pt1.north() - pt2.north();
877 double d = Math.sqrt(a[i]*a[i] + b[i]*b[i]);
878 if (d == 0) return null;
879 a[i] /= d;
880 b[i] /= d;
881 double xC = (pt1.east() + pt2.east()) / 2;
882 double yC = (pt1.north() + pt2.north()) / 2;
883 c[i] = -(a[i]*xC + b[i]*yC);
884 }
885 // At.A = [aij]
886 double a11 = 0, a12 = 0, a22 = 0;
887 // At.Y = [bi]
888 double b1 = 0, b2 = 0;
889 for (int i = 0; i < nc; i++) {
890 a11 += a[i]*a[i];
891 a12 += a[i]*b[i];
892 a22 += b[i]*b[i];
893 b1 -= a[i]*c[i];
894 b2 -= b[i]*c[i];
895 }
896 // (At.A)^-1 = [invij]
897 double det = a11*a22 - a12*a12;
898 if (Math.abs(det) < 1e-5) return null;
899 double inv11 = a22/det;
900 double inv12 = -a12/det;
901 double inv22 = a11/det;
902 // center (xC, yC) = (At.A)^-1.At.y
903 double xC = inv11*b1 + inv12*b2;
904 double yC = inv12*b1 + inv22*b2;
905 return new EastNorth(xC, yC);
906 }
907
908 /**
909 * Tests if the {@code node} is inside the multipolygon {@code multiPolygon}. The nullable argument
910 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
911 * @param node node
912 * @param multiPolygon multipolygon
913 * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match
914 * @return {@code true} if the node is inside the multipolygon
915 */
916 public static boolean isNodeInsideMultiPolygon(Node node, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
917 return isPolygonInsideMultiPolygon(Collections.singletonList(node), multiPolygon, isOuterWayAMatch);
918 }
919
920 /**
921 * Tests if the polygon formed by {@code nodes} is inside the multipolygon {@code multiPolygon}. The nullable argument
922 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
923 * <p>
924 * If {@code nodes} contains exactly one element, then it is checked whether that one node is inside the multipolygon.
925 * @param nodes nodes forming the polygon
926 * @param multiPolygon multipolygon
927 * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match
928 * @return {@code true} if the polygon formed by nodes is inside the multipolygon
929 */
930 public static boolean isPolygonInsideMultiPolygon(List<Node> nodes, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
931 // Extract outer/inner members from multipolygon
932 final Pair<List<JoinedPolygon>, List<JoinedPolygon>> outerInner;
933 try {
934 outerInner = MultipolygonBuilder.joinWays(multiPolygon);
935 } catch (MultipolygonBuilder.JoinedPolygonCreationException ex) {
936 Logging.trace(ex);
937 Logging.debug("Invalid multipolygon " + multiPolygon);
938 return false;
939 }
940 // Test if object is inside an outer member
941 for (JoinedPolygon out : outerInner.a) {
942 if (nodes.size() == 1
943 ? nodeInsidePolygon(nodes.get(0), out.getNodes())
944 : EnumSet.of(PolygonIntersection.FIRST_INSIDE_SECOND, PolygonIntersection.CROSSING).contains(
945 polygonIntersection(nodes, out.getNodes()))) {
946 boolean insideInner = false;
947 // If inside an outer, check it is not inside an inner
948 for (JoinedPolygon in : outerInner.b) {
949 if (polygonIntersection(in.getNodes(), out.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND
950 && (nodes.size() == 1
951 ? nodeInsidePolygon(nodes.get(0), in.getNodes())
952 : polygonIntersection(nodes, in.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND)) {
953 insideInner = true;
954 break;
955 }
956 }
957 // Inside outer but not inside inner -> the polygon appears to be inside a the multipolygon
958 if (!insideInner) {
959 // Final check using predicate
960 if (isOuterWayAMatch == null || isOuterWayAMatch.test(out.ways.get(0)
961 /* TODO give a better representation of the outer ring to the predicate */)) {
962 return true;
963 }
964 }
965 }
966 }
967 return false;
968 }
969
970 /**
971 * Data class to hold two double values (area and perimeter of a polygon).
972 */
973 public static class AreaAndPerimeter {
974 private final double area;
975 private final double perimeter;
976
977 /**
978 * Create a new {@link AreaAndPerimeter}
979 * @param area The area
980 * @param perimeter The perimeter
981 */
982 public AreaAndPerimeter(double area, double perimeter) {
983 this.area = area;
984 this.perimeter = perimeter;
985 }
986
987 /**
988 * Gets the area
989 * @return The area size
990 */
991 public double getArea() {
992 return area;
993 }
994
995 /**
996 * Gets the perimeter
997 * @return The perimeter length
998 */
999 public double getPerimeter() {
1000 return perimeter;
1001 }
1002 }
1003
1004 /**
1005 * Calculate area and perimeter length of a polygon.
1006 *
1007 * Uses current projection; units are that of the projected coordinates.
1008 *
1009 * @param nodes the list of nodes representing the polygon
1010 * @return area and perimeter
1011 */
1012 public static AreaAndPerimeter getAreaAndPerimeter(List<Node> nodes) {
1013 return getAreaAndPerimeter(nodes, null);
1014 }
1015
1016 /**
1017 * Calculate area and perimeter length of a polygon in the given projection.
1018 *
1019 * @param nodes the list of nodes representing the polygon
1020 * @param projection the projection to use for the calculation, {@code null} defaults to {@link Main#getProjection()}
1021 * @return area and perimeter
1022 */
1023 public static AreaAndPerimeter getAreaAndPerimeter(List<Node> nodes, Projection projection) {
1024 CheckParameterUtil.ensureParameterNotNull(nodes, "nodes");
1025 double area = 0;
1026 double perimeter = 0;
1027 Projection useProjection = projection == null ? Main.getProjection() : projection;
1028
1029 if (!nodes.isEmpty()) {
1030 boolean closed = nodes.get(0) == nodes.get(nodes.size() - 1);
1031 int numSegments = closed ? nodes.size() - 1 : nodes.size();
1032 EastNorth p1 = nodes.get(0).getEastNorth(useProjection);
1033 for (int i = 1; i <= numSegments; i++) {
1034 final Node node = nodes.get(i == numSegments ? 0 : i);
1035 final EastNorth p2 = node.getEastNorth(useProjection);
1036 if (p1 != null && p2 != null) {
1037 area += p1.east() * p2.north() - p2.east() * p1.north();
1038 perimeter += p1.distance(p2);
1039 }
1040 p1 = p2;
1041 }
1042 }
1043 return new AreaAndPerimeter(Math.abs(area) / 2, perimeter);
1044 }
1045}
Note: See TracBrowser for help on using the repository browser.