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

Last change on this file since 13649 was 13638, checked in by Don-vip, 6 years ago

use interfaces in Geometry

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