1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import java.awt.Rectangle;
|
---|
5 | import java.awt.geom.Area;
|
---|
6 | import java.awt.geom.Line2D;
|
---|
7 | import java.awt.geom.Path2D;
|
---|
8 | import java.math.BigDecimal;
|
---|
9 | import java.math.MathContext;
|
---|
10 | import java.util.ArrayList;
|
---|
11 | import java.util.Collections;
|
---|
12 | import java.util.Comparator;
|
---|
13 | import java.util.EnumSet;
|
---|
14 | import java.util.HashSet;
|
---|
15 | import java.util.LinkedHashSet;
|
---|
16 | import java.util.List;
|
---|
17 | import java.util.Set;
|
---|
18 |
|
---|
19 | import org.openstreetmap.josm.Main;
|
---|
20 | import org.openstreetmap.josm.command.AddCommand;
|
---|
21 | import org.openstreetmap.josm.command.ChangeCommand;
|
---|
22 | import org.openstreetmap.josm.command.Command;
|
---|
23 | import org.openstreetmap.josm.data.coor.EastNorth;
|
---|
24 | import org.openstreetmap.josm.data.coor.LatLon;
|
---|
25 | import org.openstreetmap.josm.data.osm.BBox;
|
---|
26 | import org.openstreetmap.josm.data.osm.Node;
|
---|
27 | import org.openstreetmap.josm.data.osm.NodePositionComparator;
|
---|
28 | import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
|
---|
29 | import org.openstreetmap.josm.data.osm.Relation;
|
---|
30 | import org.openstreetmap.josm.data.osm.RelationMember;
|
---|
31 | import org.openstreetmap.josm.data.osm.Way;
|
---|
32 |
|
---|
33 | /**
|
---|
34 | * Some tools for geometry related tasks.
|
---|
35 | *
|
---|
36 | * @author viesturs
|
---|
37 | */
|
---|
38 | public final class Geometry {
|
---|
39 |
|
---|
40 | private Geometry() {
|
---|
41 | // Hide default constructor for utils classes
|
---|
42 | }
|
---|
43 |
|
---|
44 | public enum PolygonIntersection {FIRST_INSIDE_SECOND, SECOND_INSIDE_FIRST, OUTSIDE, CROSSING}
|
---|
45 |
|
---|
46 | /**
|
---|
47 | * Will find all intersection and add nodes there for list of given ways.
|
---|
48 | * Handles self-intersections too.
|
---|
49 | * And makes commands to add the intersection points to ways.
|
---|
50 | *
|
---|
51 | * Prerequisite: no two nodes have the same coordinates.
|
---|
52 | *
|
---|
53 | * @param ways a list of ways to test
|
---|
54 | * @param test if false, do not build list of Commands, just return nodes
|
---|
55 | * @param cmds list of commands, typically empty when handed to this method.
|
---|
56 | * Will be filled with commands that add intersection nodes to
|
---|
57 | * the ways.
|
---|
58 | * @return list of new nodes
|
---|
59 | */
|
---|
60 | public static Set<Node> addIntersections(List<Way> ways, boolean test, List<Command> cmds) {
|
---|
61 |
|
---|
62 | int n = ways.size();
|
---|
63 | @SuppressWarnings("unchecked")
|
---|
64 | List<Node>[] newNodes = new ArrayList[n];
|
---|
65 | BBox[] wayBounds = new BBox[n];
|
---|
66 | boolean[] changedWays = new boolean[n];
|
---|
67 |
|
---|
68 | Set<Node> intersectionNodes = new LinkedHashSet<Node>();
|
---|
69 |
|
---|
70 | //copy node arrays for local usage.
|
---|
71 | for (int pos = 0; pos < n; pos ++) {
|
---|
72 | newNodes[pos] = new ArrayList<Node>(ways.get(pos).getNodes());
|
---|
73 | wayBounds[pos] = getNodesBounds(newNodes[pos]);
|
---|
74 | changedWays[pos] = false;
|
---|
75 | }
|
---|
76 |
|
---|
77 | //iterate over all way pairs and introduce the intersections
|
---|
78 | Comparator<Node> coordsComparator = new NodePositionComparator();
|
---|
79 | for (int seg1Way = 0; seg1Way < n; seg1Way ++) {
|
---|
80 | for (int seg2Way = seg1Way; seg2Way < n; seg2Way ++) {
|
---|
81 |
|
---|
82 | //do not waste time on bounds that do not intersect
|
---|
83 | if (!wayBounds[seg1Way].intersects(wayBounds[seg2Way])) {
|
---|
84 | continue;
|
---|
85 | }
|
---|
86 |
|
---|
87 | List<Node> way1Nodes = newNodes[seg1Way];
|
---|
88 | List<Node> way2Nodes = newNodes[seg2Way];
|
---|
89 |
|
---|
90 | //iterate over primary segmemt
|
---|
91 | for (int seg1Pos = 0; seg1Pos + 1 < way1Nodes.size(); seg1Pos ++) {
|
---|
92 |
|
---|
93 | //iterate over secondary segment
|
---|
94 | int seg2Start = seg1Way != seg2Way ? 0: seg1Pos + 2;//skip the adjacent segment
|
---|
95 |
|
---|
96 | for (int seg2Pos = seg2Start; seg2Pos + 1< way2Nodes.size(); seg2Pos ++) {
|
---|
97 |
|
---|
98 | //need to get them again every time, because other segments may be changed
|
---|
99 | Node seg1Node1 = way1Nodes.get(seg1Pos);
|
---|
100 | Node seg1Node2 = way1Nodes.get(seg1Pos + 1);
|
---|
101 | Node seg2Node1 = way2Nodes.get(seg2Pos);
|
---|
102 | Node seg2Node2 = way2Nodes.get(seg2Pos + 1);
|
---|
103 |
|
---|
104 | int commonCount = 0;
|
---|
105 | //test if we have common nodes to add.
|
---|
106 | if (seg1Node1 == seg2Node1 || seg1Node1 == seg2Node2) {
|
---|
107 | commonCount ++;
|
---|
108 |
|
---|
109 | if (seg1Way == seg2Way &&
|
---|
110 | seg1Pos == 0 &&
|
---|
111 | seg2Pos == way2Nodes.size() -2) {
|
---|
112 | //do not add - this is first and last segment of the same way.
|
---|
113 | } else {
|
---|
114 | intersectionNodes.add(seg1Node1);
|
---|
115 | }
|
---|
116 | }
|
---|
117 |
|
---|
118 | if (seg1Node2 == seg2Node1 || seg1Node2 == seg2Node2) {
|
---|
119 | commonCount ++;
|
---|
120 |
|
---|
121 | intersectionNodes.add(seg1Node2);
|
---|
122 | }
|
---|
123 |
|
---|
124 | //no common nodes - find intersection
|
---|
125 | if (commonCount == 0) {
|
---|
126 | EastNorth intersection = getSegmentSegmentIntersection(
|
---|
127 | seg1Node1.getEastNorth(), seg1Node2.getEastNorth(),
|
---|
128 | seg2Node1.getEastNorth(), seg2Node2.getEastNorth());
|
---|
129 |
|
---|
130 | if (intersection != null) {
|
---|
131 | if (test) {
|
---|
132 | intersectionNodes.add(seg2Node1);
|
---|
133 | return intersectionNodes;
|
---|
134 | }
|
---|
135 |
|
---|
136 | Node newNode = new Node(Main.getProjection().eastNorth2latlon(intersection));
|
---|
137 | Node intNode = newNode;
|
---|
138 | boolean insertInSeg1 = false;
|
---|
139 | boolean insertInSeg2 = false;
|
---|
140 | //find if the intersection point is at end point of one of the segments, if so use that point
|
---|
141 |
|
---|
142 | //segment 1
|
---|
143 | if (coordsComparator.compare(newNode, seg1Node1) == 0) {
|
---|
144 | intNode = seg1Node1;
|
---|
145 | } else if (coordsComparator.compare(newNode, seg1Node2) == 0) {
|
---|
146 | intNode = seg1Node2;
|
---|
147 | } else {
|
---|
148 | insertInSeg1 = true;
|
---|
149 | }
|
---|
150 |
|
---|
151 | //segment 2
|
---|
152 | if (coordsComparator.compare(newNode, seg2Node1) == 0) {
|
---|
153 | intNode = seg2Node1;
|
---|
154 | } else if (coordsComparator.compare(newNode, seg2Node2) == 0) {
|
---|
155 | intNode = seg2Node2;
|
---|
156 | } else {
|
---|
157 | insertInSeg2 = true;
|
---|
158 | }
|
---|
159 |
|
---|
160 | if (insertInSeg1) {
|
---|
161 | way1Nodes.add(seg1Pos +1, intNode);
|
---|
162 | changedWays[seg1Way] = true;
|
---|
163 |
|
---|
164 | //fix seg2 position, as indexes have changed, seg2Pos is always bigger than seg1Pos on the same segment.
|
---|
165 | if (seg2Way == seg1Way) {
|
---|
166 | seg2Pos ++;
|
---|
167 | }
|
---|
168 | }
|
---|
169 |
|
---|
170 | if (insertInSeg2) {
|
---|
171 | way2Nodes.add(seg2Pos +1, intNode);
|
---|
172 | changedWays[seg2Way] = true;
|
---|
173 |
|
---|
174 | //Do not need to compare again to already split segment
|
---|
175 | seg2Pos ++;
|
---|
176 | }
|
---|
177 |
|
---|
178 | intersectionNodes.add(intNode);
|
---|
179 |
|
---|
180 | if (intNode == newNode) {
|
---|
181 | cmds.add(new AddCommand(intNode));
|
---|
182 | }
|
---|
183 | }
|
---|
184 | }
|
---|
185 | else if (test && !intersectionNodes.isEmpty())
|
---|
186 | return intersectionNodes;
|
---|
187 | }
|
---|
188 | }
|
---|
189 | }
|
---|
190 | }
|
---|
191 |
|
---|
192 |
|
---|
193 | for (int pos = 0; pos < ways.size(); pos ++) {
|
---|
194 | if (!changedWays[pos]) {
|
---|
195 | continue;
|
---|
196 | }
|
---|
197 |
|
---|
198 | Way way = ways.get(pos);
|
---|
199 | Way newWay = new Way(way);
|
---|
200 | newWay.setNodes(newNodes[pos]);
|
---|
201 |
|
---|
202 | cmds.add(new ChangeCommand(way, newWay));
|
---|
203 | }
|
---|
204 |
|
---|
205 | return intersectionNodes;
|
---|
206 | }
|
---|
207 |
|
---|
208 | private static BBox getNodesBounds(List<Node> nodes) {
|
---|
209 |
|
---|
210 | BBox bounds = new BBox(nodes.get(0));
|
---|
211 | for (Node n: nodes) {
|
---|
212 | bounds.add(n.getCoor());
|
---|
213 | }
|
---|
214 | return bounds;
|
---|
215 | }
|
---|
216 |
|
---|
217 | /**
|
---|
218 | * Tests if given point is to the right side of path consisting of 3 points.
|
---|
219 | *
|
---|
220 | * (Imagine the path is continued beyond the endpoints, so you get two rays
|
---|
221 | * starting from lineP2 and going through lineP1 and lineP3 respectively
|
---|
222 | * which divide the plane into two parts. The test returns true, if testPoint
|
---|
223 | * lies in the part that is to the right when traveling in the direction
|
---|
224 | * lineP1, lineP2, lineP3.)
|
---|
225 | *
|
---|
226 | * @param lineP1 first point in path
|
---|
227 | * @param lineP2 second point in path
|
---|
228 | * @param lineP3 third point in path
|
---|
229 | * @param testPoint
|
---|
230 | * @return true if to the right side, false otherwise
|
---|
231 | */
|
---|
232 | public static boolean isToTheRightSideOfLine(Node lineP1, Node lineP2, Node lineP3, Node testPoint) {
|
---|
233 | boolean pathBendToRight = angleIsClockwise(lineP1, lineP2, lineP3);
|
---|
234 | boolean rightOfSeg1 = angleIsClockwise(lineP1, lineP2, testPoint);
|
---|
235 | boolean rightOfSeg2 = angleIsClockwise(lineP2, lineP3, testPoint);
|
---|
236 |
|
---|
237 | if (pathBendToRight)
|
---|
238 | return rightOfSeg1 && rightOfSeg2;
|
---|
239 | else
|
---|
240 | return !(!rightOfSeg1 && !rightOfSeg2);
|
---|
241 | }
|
---|
242 |
|
---|
243 | /**
|
---|
244 | * This method tests if secondNode is clockwise to first node.
|
---|
245 | * @param commonNode starting point for both vectors
|
---|
246 | * @param firstNode first vector end node
|
---|
247 | * @param secondNode second vector end node
|
---|
248 | * @return true if first vector is clockwise before second vector.
|
---|
249 | */
|
---|
250 | public static boolean angleIsClockwise(Node commonNode, Node firstNode, Node secondNode) {
|
---|
251 | return angleIsClockwise(commonNode.getEastNorth(), firstNode.getEastNorth(), secondNode.getEastNorth());
|
---|
252 | }
|
---|
253 |
|
---|
254 | /**
|
---|
255 | * Finds the intersection of two line segments
|
---|
256 | * @return EastNorth null if no intersection was found, the EastNorth coordinates of the intersection otherwise
|
---|
257 | */
|
---|
258 | public static EastNorth getSegmentSegmentIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
|
---|
259 |
|
---|
260 | CheckParameterUtil.ensureValidCoordinates(p1, "p1");
|
---|
261 | CheckParameterUtil.ensureValidCoordinates(p2, "p2");
|
---|
262 | CheckParameterUtil.ensureValidCoordinates(p3, "p3");
|
---|
263 | CheckParameterUtil.ensureValidCoordinates(p4, "p4");
|
---|
264 |
|
---|
265 | double x1 = p1.getX();
|
---|
266 | double y1 = p1.getY();
|
---|
267 | double x2 = p2.getX();
|
---|
268 | double y2 = p2.getY();
|
---|
269 | double x3 = p3.getX();
|
---|
270 | double y3 = p3.getY();
|
---|
271 | double x4 = p4.getX();
|
---|
272 | double y4 = p4.getY();
|
---|
273 |
|
---|
274 | //TODO: do this locally.
|
---|
275 | //TODO: remove this check after careful testing
|
---|
276 | if (!Line2D.linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return null;
|
---|
277 |
|
---|
278 | // solve line-line intersection in parametric form:
|
---|
279 | // (x1,y1) + (x2-x1,y2-y1)* u = (x3,y3) + (x4-x3,y4-y3)* v
|
---|
280 | // (x2-x1,y2-y1)*u - (x4-x3,y4-y3)*v = (x3-x1,y3-y1)
|
---|
281 | // if 0<= u,v <=1, intersection exists at ( x1+ (x2-x1)*u, y1 + (y2-y1)*u )
|
---|
282 |
|
---|
283 | double a1 = x2 - x1;
|
---|
284 | double b1 = x3 - x4;
|
---|
285 | double c1 = x3 - x1;
|
---|
286 |
|
---|
287 | double a2 = y2 - y1;
|
---|
288 | double b2 = y3 - y4;
|
---|
289 | double c2 = y3 - y1;
|
---|
290 |
|
---|
291 | // Solve the equations
|
---|
292 | double det = a1*b2 - a2*b1;
|
---|
293 |
|
---|
294 | double uu = b2*c1 - b1*c2 ;
|
---|
295 | double vv = a1*c2 - a2*c1;
|
---|
296 | double mag = Math.abs(uu)+Math.abs(vv);
|
---|
297 |
|
---|
298 | if (Math.abs(det) > 1e-12 * mag) {
|
---|
299 | double u = uu/det, v = vv/det;
|
---|
300 | if (u>-1e-8 && u < 1+1e-8 && v>-1e-8 && v < 1+1e-8 ) {
|
---|
301 | if (u<0) u=0;
|
---|
302 | if (u>1) u=1.0;
|
---|
303 | return new EastNorth(x1+a1*u, y1+a2*u);
|
---|
304 | } else {
|
---|
305 | return null;
|
---|
306 | }
|
---|
307 | } else {
|
---|
308 | // parallel lines
|
---|
309 | return null;
|
---|
310 | }
|
---|
311 | }
|
---|
312 |
|
---|
313 | /**
|
---|
314 | * Finds the intersection of two lines of infinite length.
|
---|
315 | * @return EastNorth null if no intersection was found, the coordinates of the intersection otherwise
|
---|
316 | * @throws IllegalArgumentException if a parameter is null or without valid coordinates
|
---|
317 | */
|
---|
318 | public static EastNorth getLineLineIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
|
---|
319 |
|
---|
320 | CheckParameterUtil.ensureValidCoordinates(p1, "p1");
|
---|
321 | CheckParameterUtil.ensureValidCoordinates(p2, "p2");
|
---|
322 | CheckParameterUtil.ensureValidCoordinates(p3, "p3");
|
---|
323 | CheckParameterUtil.ensureValidCoordinates(p4, "p4");
|
---|
324 |
|
---|
325 | if (!p1.isValid()) throw new IllegalArgumentException();
|
---|
326 |
|
---|
327 | // Convert line from (point, point) form to ax+by=c
|
---|
328 | double a1 = p2.getY() - p1.getY();
|
---|
329 | double b1 = p1.getX() - p2.getX();
|
---|
330 | double c1 = p2.getX() * p1.getY() - p1.getX() * p2.getY();
|
---|
331 |
|
---|
332 | double a2 = p4.getY() - p3.getY();
|
---|
333 | double b2 = p3.getX() - p4.getX();
|
---|
334 | double c2 = p4.getX() * p3.getY() - p3.getX() * p4.getY();
|
---|
335 |
|
---|
336 | // Solve the equations
|
---|
337 | double det = a1 * b2 - a2 * b1;
|
---|
338 | if (det == 0)
|
---|
339 | return null; // Lines are parallel
|
---|
340 |
|
---|
341 | return new EastNorth((b1 * c2 - b2 * c1) / det, (a2 * c1 - a1 * c2) / det);
|
---|
342 | }
|
---|
343 |
|
---|
344 | public static boolean segmentsParallel(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
|
---|
345 |
|
---|
346 | CheckParameterUtil.ensureValidCoordinates(p1, "p1");
|
---|
347 | CheckParameterUtil.ensureValidCoordinates(p2, "p2");
|
---|
348 | CheckParameterUtil.ensureValidCoordinates(p3, "p3");
|
---|
349 | CheckParameterUtil.ensureValidCoordinates(p4, "p4");
|
---|
350 |
|
---|
351 | // Convert line from (point, point) form to ax+by=c
|
---|
352 | double a1 = p2.getY() - p1.getY();
|
---|
353 | double b1 = p1.getX() - p2.getX();
|
---|
354 |
|
---|
355 | double a2 = p4.getY() - p3.getY();
|
---|
356 | double b2 = p3.getX() - p4.getX();
|
---|
357 |
|
---|
358 | // Solve the equations
|
---|
359 | double det = a1 * b2 - a2 * b1;
|
---|
360 | // remove influence of of scaling factor
|
---|
361 | det /= Math.sqrt(a1*a1 + b1*b1) * Math.sqrt(a2*a2 + b2*b2);
|
---|
362 | return Math.abs(det) < 1e-3;
|
---|
363 | }
|
---|
364 |
|
---|
365 | private static EastNorth closestPointTo(EastNorth p1, EastNorth p2, EastNorth point, boolean segmentOnly) {
|
---|
366 | CheckParameterUtil.ensureParameterNotNull(p1, "p1");
|
---|
367 | CheckParameterUtil.ensureParameterNotNull(p2, "p2");
|
---|
368 | CheckParameterUtil.ensureParameterNotNull(point, "point");
|
---|
369 |
|
---|
370 | double ldx = p2.getX() - p1.getX();
|
---|
371 | double ldy = p2.getY() - p1.getY();
|
---|
372 |
|
---|
373 | if (ldx == 0 && ldy == 0) //segment zero length
|
---|
374 | return p1;
|
---|
375 |
|
---|
376 | double pdx = point.getX() - p1.getX();
|
---|
377 | double pdy = point.getY() - p1.getY();
|
---|
378 |
|
---|
379 | double offset = (pdx * ldx + pdy * ldy) / (ldx * ldx + ldy * ldy);
|
---|
380 |
|
---|
381 | if (segmentOnly && offset <= 0)
|
---|
382 | return p1;
|
---|
383 | else if (segmentOnly && offset >= 1)
|
---|
384 | return p2;
|
---|
385 | else
|
---|
386 | return new EastNorth(p1.getX() + ldx * offset, p1.getY() + ldy * offset);
|
---|
387 | }
|
---|
388 |
|
---|
389 | /**
|
---|
390 | * Calculates closest point to a line segment.
|
---|
391 | * @param segmentP1 First point determining line segment
|
---|
392 | * @param segmentP2 Second point determining line segment
|
---|
393 | * @param point Point for which a closest point is searched on line segment [P1,P2]
|
---|
394 | * @return segmentP1 if it is the closest point, segmentP2 if it is the closest point,
|
---|
395 | * a new point if closest point is between segmentP1 and segmentP2.
|
---|
396 | * @since 3650
|
---|
397 | * @see #closestPointToLine
|
---|
398 | */
|
---|
399 | public static EastNorth closestPointToSegment(EastNorth segmentP1, EastNorth segmentP2, EastNorth point) {
|
---|
400 | return closestPointTo(segmentP1, segmentP2, point, true);
|
---|
401 | }
|
---|
402 |
|
---|
403 | /**
|
---|
404 | * Calculates closest point to a line.
|
---|
405 | * @param lineP1 First point determining line
|
---|
406 | * @param lineP2 Second point determining line
|
---|
407 | * @param point Point for which a closest point is searched on line (P1,P2)
|
---|
408 | * @return The closest point found on line. It may be outside the segment [P1,P2].
|
---|
409 | * @since 4134
|
---|
410 | * @see #closestPointToSegment
|
---|
411 | */
|
---|
412 | public static EastNorth closestPointToLine(EastNorth lineP1, EastNorth lineP2, EastNorth point) {
|
---|
413 | return closestPointTo(lineP1, lineP2, point, false);
|
---|
414 | }
|
---|
415 |
|
---|
416 | /**
|
---|
417 | * This method tests if secondNode is clockwise to first node.
|
---|
418 | *
|
---|
419 | * The line through the two points commonNode and firstNode divides the
|
---|
420 | * plane into two parts. The test returns true, if secondNode lies in
|
---|
421 | * the part that is to the right when traveling in the direction from
|
---|
422 | * commonNode to firstNode.
|
---|
423 | *
|
---|
424 | * @param commonNode starting point for both vectors
|
---|
425 | * @param firstNode first vector end node
|
---|
426 | * @param secondNode second vector end node
|
---|
427 | * @return true if first vector is clockwise before second vector.
|
---|
428 | */
|
---|
429 | public static boolean angleIsClockwise(EastNorth commonNode, EastNorth firstNode, EastNorth secondNode) {
|
---|
430 |
|
---|
431 | CheckParameterUtil.ensureValidCoordinates(commonNode, "commonNode");
|
---|
432 | CheckParameterUtil.ensureValidCoordinates(firstNode, "firstNode");
|
---|
433 | CheckParameterUtil.ensureValidCoordinates(secondNode, "secondNode");
|
---|
434 |
|
---|
435 | double dy1 = (firstNode.getY() - commonNode.getY());
|
---|
436 | double dy2 = (secondNode.getY() - commonNode.getY());
|
---|
437 | double dx1 = (firstNode.getX() - commonNode.getX());
|
---|
438 | double dx2 = (secondNode.getX() - commonNode.getX());
|
---|
439 |
|
---|
440 | return dy1 * dx2 - dx1 * dy2 > 0;
|
---|
441 | }
|
---|
442 |
|
---|
443 | private static Area getArea(List<Node> polygon) {
|
---|
444 | Path2D path = new Path2D.Double();
|
---|
445 |
|
---|
446 | boolean begin = true;
|
---|
447 | for (Node n : polygon) {
|
---|
448 | if (begin) {
|
---|
449 | path.moveTo(n.getEastNorth().getX(), n.getEastNorth().getY());
|
---|
450 | begin = false;
|
---|
451 | } else {
|
---|
452 | path.lineTo(n.getEastNorth().getX(), n.getEastNorth().getY());
|
---|
453 | }
|
---|
454 | }
|
---|
455 | if (!begin) {
|
---|
456 | path.closePath();
|
---|
457 | }
|
---|
458 |
|
---|
459 | return new Area(path);
|
---|
460 | }
|
---|
461 |
|
---|
462 | /**
|
---|
463 | * Tests if two polygons intersect.
|
---|
464 | * @param first
|
---|
465 | * @param second
|
---|
466 | * @return intersection kind
|
---|
467 | */
|
---|
468 | public static PolygonIntersection polygonIntersection(List<Node> first, List<Node> second) {
|
---|
469 |
|
---|
470 | Area a1 = getArea(first);
|
---|
471 | Area a2 = getArea(second);
|
---|
472 |
|
---|
473 | Area inter = new Area(a1);
|
---|
474 | inter.intersect(a2);
|
---|
475 |
|
---|
476 | Rectangle bounds = inter.getBounds();
|
---|
477 |
|
---|
478 | if (inter.isEmpty() || bounds.getHeight()*bounds.getWidth() <= 1.0) {
|
---|
479 | return PolygonIntersection.OUTSIDE;
|
---|
480 | } else if (inter.equals(a1)) {
|
---|
481 | return PolygonIntersection.FIRST_INSIDE_SECOND;
|
---|
482 | } else if (inter.equals(a2)) {
|
---|
483 | return PolygonIntersection.SECOND_INSIDE_FIRST;
|
---|
484 | } else {
|
---|
485 | return PolygonIntersection.CROSSING;
|
---|
486 | }
|
---|
487 | }
|
---|
488 |
|
---|
489 | /**
|
---|
490 | * Tests if point is inside a polygon. The polygon can be self-intersecting. In such case the contains function works in xor-like manner.
|
---|
491 | * @param polygonNodes list of nodes from polygon path.
|
---|
492 | * @param point the point to test
|
---|
493 | * @return true if the point is inside polygon.
|
---|
494 | */
|
---|
495 | public static boolean nodeInsidePolygon(Node point, List<Node> polygonNodes) {
|
---|
496 | if (polygonNodes.size() < 2)
|
---|
497 | return false;
|
---|
498 |
|
---|
499 | boolean inside = false;
|
---|
500 | Node p1, p2;
|
---|
501 |
|
---|
502 | //iterate each side of the polygon, start with the last segment
|
---|
503 | Node oldPoint = polygonNodes.get(polygonNodes.size() - 1);
|
---|
504 |
|
---|
505 | for (Node newPoint : polygonNodes) {
|
---|
506 | //skip duplicate points
|
---|
507 | if (newPoint.equals(oldPoint)) {
|
---|
508 | continue;
|
---|
509 | }
|
---|
510 |
|
---|
511 | //order points so p1.lat <= p2.lat
|
---|
512 | if (newPoint.getEastNorth().getY() > oldPoint.getEastNorth().getY()) {
|
---|
513 | p1 = oldPoint;
|
---|
514 | p2 = newPoint;
|
---|
515 | } else {
|
---|
516 | p1 = newPoint;
|
---|
517 | p2 = oldPoint;
|
---|
518 | }
|
---|
519 |
|
---|
520 | //test if the line is crossed and if so invert the inside flag.
|
---|
521 | if ((newPoint.getEastNorth().getY() < point.getEastNorth().getY()) == (point.getEastNorth().getY() <= oldPoint.getEastNorth().getY())
|
---|
522 | && (point.getEastNorth().getX() - p1.getEastNorth().getX()) * (p2.getEastNorth().getY() - p1.getEastNorth().getY())
|
---|
523 | < (p2.getEastNorth().getX() - p1.getEastNorth().getX()) * (point.getEastNorth().getY() - p1.getEastNorth().getY()))
|
---|
524 | {
|
---|
525 | inside = !inside;
|
---|
526 | }
|
---|
527 |
|
---|
528 | oldPoint = newPoint;
|
---|
529 | }
|
---|
530 |
|
---|
531 | return inside;
|
---|
532 | }
|
---|
533 |
|
---|
534 | /**
|
---|
535 | * Returns area of a closed way in square meters.
|
---|
536 | * (approximate(?), but should be OK for small areas)
|
---|
537 | *
|
---|
538 | * Relies on the current projection: Works correctly, when
|
---|
539 | * one unit in projected coordinates corresponds to one meter.
|
---|
540 | * This is true for most projections, but not for WGS84 and
|
---|
541 | * Mercator (EPSG:3857).
|
---|
542 | *
|
---|
543 | * @param way Way to measure, should be closed (first node is the same as last node)
|
---|
544 | * @return area of the closed way.
|
---|
545 | */
|
---|
546 | public static double closedWayArea(Way way) {
|
---|
547 |
|
---|
548 | //http://local.wasp.uwa.edu.au/~pbourke/geometry/polyarea/
|
---|
549 | double area = 0;
|
---|
550 | Node lastN = null;
|
---|
551 | for (Node n : way.getNodes()) {
|
---|
552 | if (lastN != null) {
|
---|
553 | n.getEastNorth().getX();
|
---|
554 |
|
---|
555 | area += (calcX(n) * calcY(lastN)) - (calcY(n) * calcX(lastN));
|
---|
556 | }
|
---|
557 | lastN = n;
|
---|
558 | }
|
---|
559 | return Math.abs(area/2);
|
---|
560 | }
|
---|
561 |
|
---|
562 | protected static double calcX(Node p1){
|
---|
563 | double lat1, lon1, lat2, lon2;
|
---|
564 | double dlon, dlat;
|
---|
565 |
|
---|
566 | lat1 = p1.getCoor().lat() * Math.PI / 180.0;
|
---|
567 | lon1 = p1.getCoor().lon() * Math.PI / 180.0;
|
---|
568 | lat2 = lat1;
|
---|
569 | lon2 = 0;
|
---|
570 |
|
---|
571 | dlon = lon2 - lon1;
|
---|
572 | dlat = lat2 - lat1;
|
---|
573 |
|
---|
574 | double a = (Math.pow(Math.sin(dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2), 2));
|
---|
575 | double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
|
---|
576 | return 6367000 * c;
|
---|
577 | }
|
---|
578 |
|
---|
579 | protected static double calcY(Node p1){
|
---|
580 | double lat1, lon1, lat2, lon2;
|
---|
581 | double dlon, dlat;
|
---|
582 |
|
---|
583 | lat1 = p1.getCoor().lat() * Math.PI / 180.0;
|
---|
584 | lon1 = p1.getCoor().lon() * Math.PI / 180.0;
|
---|
585 | lat2 = 0;
|
---|
586 | lon2 = lon1;
|
---|
587 |
|
---|
588 | dlon = lon2 - lon1;
|
---|
589 | dlat = lat2 - lat1;
|
---|
590 |
|
---|
591 | double a = (Math.pow(Math.sin(dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2), 2));
|
---|
592 | double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
|
---|
593 | return 6367000 * c;
|
---|
594 | }
|
---|
595 |
|
---|
596 | /**
|
---|
597 | * Determines whether a way is oriented clockwise.
|
---|
598 | *
|
---|
599 | * Internals: Assuming a closed non-looping way, compute twice the area
|
---|
600 | * of the polygon using the formula {@code 2 * area = sum (X[n] * Y[n+1] - X[n+1] * Y[n])}.
|
---|
601 | * If the area is negative the way is ordered in a clockwise direction.
|
---|
602 | *
|
---|
603 | * See http://paulbourke.net/geometry/polyarea/
|
---|
604 | *
|
---|
605 | * @param w the way to be checked.
|
---|
606 | * @return true if and only if way is oriented clockwise.
|
---|
607 | * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}).
|
---|
608 | */
|
---|
609 | public static boolean isClockwise(Way w) {
|
---|
610 | if (!w.isClosed()) {
|
---|
611 | throw new IllegalArgumentException("Way must be closed to check orientation.");
|
---|
612 | }
|
---|
613 |
|
---|
614 | double area2 = 0.;
|
---|
615 | int nodesCount = w.getNodesCount();
|
---|
616 |
|
---|
617 | for (int node = 1; node <= /*sic! consider last-first as well*/ nodesCount; node++) {
|
---|
618 | LatLon coorPrev = w.getNode(node - 1).getCoor();
|
---|
619 | LatLon coorCurr = w.getNode(node % nodesCount).getCoor();
|
---|
620 | area2 += coorPrev.lon() * coorCurr.lat();
|
---|
621 | area2 -= coorCurr.lon() * coorPrev.lat();
|
---|
622 | }
|
---|
623 | return area2 < 0;
|
---|
624 | }
|
---|
625 |
|
---|
626 | /**
|
---|
627 | * Returns angle of a segment defined with 2 point coordinates.
|
---|
628 | *
|
---|
629 | * @param p1
|
---|
630 | * @param p2
|
---|
631 | * @return Angle in radians (-pi, pi]
|
---|
632 | */
|
---|
633 | public static double getSegmentAngle(EastNorth p1, EastNorth p2) {
|
---|
634 |
|
---|
635 | CheckParameterUtil.ensureValidCoordinates(p1, "p1");
|
---|
636 | CheckParameterUtil.ensureValidCoordinates(p2, "p2");
|
---|
637 |
|
---|
638 | return Math.atan2(p2.north() - p1.north(), p2.east() - p1.east());
|
---|
639 | }
|
---|
640 |
|
---|
641 | /**
|
---|
642 | * Returns angle of a corner defined with 3 point coordinates.
|
---|
643 | *
|
---|
644 | * @param p1
|
---|
645 | * @param p2 Common endpoint
|
---|
646 | * @param p3
|
---|
647 | * @return Angle in radians (-pi, pi]
|
---|
648 | */
|
---|
649 | public static double getCornerAngle(EastNorth p1, EastNorth p2, EastNorth p3) {
|
---|
650 |
|
---|
651 | CheckParameterUtil.ensureValidCoordinates(p1, "p1");
|
---|
652 | CheckParameterUtil.ensureValidCoordinates(p2, "p2");
|
---|
653 | CheckParameterUtil.ensureValidCoordinates(p3, "p3");
|
---|
654 |
|
---|
655 | Double result = getSegmentAngle(p2, p1) - getSegmentAngle(p2, p3);
|
---|
656 | if (result <= -Math.PI) {
|
---|
657 | result += 2 * Math.PI;
|
---|
658 | }
|
---|
659 |
|
---|
660 | if (result > Math.PI) {
|
---|
661 | result -= 2 * Math.PI;
|
---|
662 | }
|
---|
663 |
|
---|
664 | return result;
|
---|
665 | }
|
---|
666 |
|
---|
667 | /**
|
---|
668 | * Compute the centroid/barycenter of nodes
|
---|
669 | * @param nodes Nodes for which the centroid is wanted
|
---|
670 | * @return the centroid of nodes
|
---|
671 | */
|
---|
672 | public static EastNorth getCentroid(List<Node> nodes) {
|
---|
673 |
|
---|
674 | BigDecimal area = BigDecimal.ZERO;
|
---|
675 | BigDecimal north = BigDecimal.ZERO;
|
---|
676 | BigDecimal east = BigDecimal.ZERO;
|
---|
677 |
|
---|
678 | // See http://en.wikipedia.org/w/index.php?title=Centroid&oldid=294224857#Centroid_of_polygon for the equation used here
|
---|
679 | for (int i = 0; i < nodes.size(); i++) {
|
---|
680 | EastNorth n0 = nodes.get(i).getEastNorth();
|
---|
681 | EastNorth n1 = nodes.get((i+1) % nodes.size()).getEastNorth();
|
---|
682 |
|
---|
683 | if (n0.isValid() && n1.isValid()) {
|
---|
684 | BigDecimal x0 = new BigDecimal(n0.east());
|
---|
685 | BigDecimal y0 = new BigDecimal(n0.north());
|
---|
686 | BigDecimal x1 = new BigDecimal(n1.east());
|
---|
687 | BigDecimal y1 = new BigDecimal(n1.north());
|
---|
688 |
|
---|
689 | BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128));
|
---|
690 |
|
---|
691 | area = area.add(k, MathContext.DECIMAL128);
|
---|
692 | east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128));
|
---|
693 | north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128));
|
---|
694 | }
|
---|
695 | }
|
---|
696 |
|
---|
697 | BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3
|
---|
698 | area = area.multiply(d, MathContext.DECIMAL128);
|
---|
699 | if (area.compareTo(BigDecimal.ZERO) != 0) {
|
---|
700 | north = north.divide(area, MathContext.DECIMAL128);
|
---|
701 | east = east.divide(area, MathContext.DECIMAL128);
|
---|
702 | }
|
---|
703 |
|
---|
704 | return new EastNorth(east.doubleValue(), north.doubleValue());
|
---|
705 | }
|
---|
706 |
|
---|
707 | /**
|
---|
708 | * Returns the coordinate of intersection of segment sp1-sp2 and an altitude
|
---|
709 | * to it starting at point ap. If the line defined with sp1-sp2 intersects
|
---|
710 | * its altitude out of sp1-sp2, null is returned.
|
---|
711 | *
|
---|
712 | * @param sp1
|
---|
713 | * @param sp2
|
---|
714 | * @param ap
|
---|
715 | * @return Intersection coordinate or null
|
---|
716 | */
|
---|
717 | public static EastNorth getSegmentAltituteIntersection(EastNorth sp1, EastNorth sp2, EastNorth ap) {
|
---|
718 |
|
---|
719 | CheckParameterUtil.ensureValidCoordinates(sp1, "sp1");
|
---|
720 | CheckParameterUtil.ensureValidCoordinates(sp2, "sp2");
|
---|
721 | CheckParameterUtil.ensureValidCoordinates(ap, "ap");
|
---|
722 |
|
---|
723 | Double segmentLenght = sp1.distance(sp2);
|
---|
724 | Double altitudeAngle = getSegmentAngle(sp1, sp2) + Math.PI / 2;
|
---|
725 |
|
---|
726 | // Taking a random point on the altitude line (angle is known).
|
---|
727 | EastNorth ap2 = new EastNorth(ap.east() + 1000
|
---|
728 | * Math.cos(altitudeAngle), ap.north() + 1000
|
---|
729 | * Math.sin(altitudeAngle));
|
---|
730 |
|
---|
731 | // Finding the intersection of two lines
|
---|
732 | EastNorth resultCandidate = Geometry.getLineLineIntersection(sp1, sp2,
|
---|
733 | ap, ap2);
|
---|
734 |
|
---|
735 | // Filtering result
|
---|
736 | if (resultCandidate != null
|
---|
737 | && resultCandidate.distance(sp1) * .999 < segmentLenght
|
---|
738 | && resultCandidate.distance(sp2) * .999 < segmentLenght) {
|
---|
739 | return resultCandidate;
|
---|
740 | } else {
|
---|
741 | return null;
|
---|
742 | }
|
---|
743 | }
|
---|
744 |
|
---|
745 | public static class MultiPolygonMembers {
|
---|
746 | public final Set<Way> outers = new HashSet<Way>();
|
---|
747 | public final Set<Way> inners = new HashSet<Way>();
|
---|
748 |
|
---|
749 | public MultiPolygonMembers(Relation multiPolygon) {
|
---|
750 | for (RelationMember m : multiPolygon.getMembers()) {
|
---|
751 | if (m.getType().equals(OsmPrimitiveType.WAY)) {
|
---|
752 | if (m.getRole().equals("outer")) {
|
---|
753 | outers.add(m.getWay());
|
---|
754 | } else if (m.getRole().equals("inner")) {
|
---|
755 | inners.add(m.getWay());
|
---|
756 | }
|
---|
757 | }
|
---|
758 | }
|
---|
759 | }
|
---|
760 | }
|
---|
761 |
|
---|
762 | /**
|
---|
763 | * Tests if the {@code node} is inside the multipolygon {@code multiPolygon}. The nullable argument
|
---|
764 | * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
|
---|
765 | */
|
---|
766 | public static boolean isNodeInsideMultiPolygon(Node node, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
|
---|
767 | return isPolygonInsideMultiPolygon(Collections.singletonList(node), multiPolygon, isOuterWayAMatch);
|
---|
768 | }
|
---|
769 |
|
---|
770 | /**
|
---|
771 | * Tests if the polygon formed by {@code nodes} is inside the multipolygon {@code multiPolygon}. The nullable argument
|
---|
772 | * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
|
---|
773 | * <p/>
|
---|
774 | * If {@code nodes} contains exactly one element, then it is checked whether that one node is inside the multipolygon.
|
---|
775 | */
|
---|
776 | public static boolean isPolygonInsideMultiPolygon(List<Node> nodes, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
|
---|
777 | // Extract outer/inner members from multipolygon
|
---|
778 | MultiPolygonMembers mpm = new MultiPolygonMembers(multiPolygon);
|
---|
779 | // Test if object is inside an outer member
|
---|
780 | for (Way out : mpm.outers) {
|
---|
781 | if (nodes.size() == 1
|
---|
782 | ? nodeInsidePolygon(nodes.get(0), out.getNodes())
|
---|
783 | : EnumSet.of(PolygonIntersection.FIRST_INSIDE_SECOND, PolygonIntersection.CROSSING).contains(polygonIntersection(nodes, out.getNodes()))) {
|
---|
784 | boolean insideInner = false;
|
---|
785 | // If inside an outer, check it is not inside an inner
|
---|
786 | for (Way in : mpm.inners) {
|
---|
787 | if (polygonIntersection(in.getNodes(), out.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND
|
---|
788 | && (nodes.size() == 1
|
---|
789 | ? nodeInsidePolygon(nodes.get(0), in.getNodes())
|
---|
790 | : polygonIntersection(nodes, in.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND)) {
|
---|
791 | insideInner = true;
|
---|
792 | break;
|
---|
793 | }
|
---|
794 | }
|
---|
795 | // Inside outer but not inside inner -> the polygon appears to be inside a the multipolygon
|
---|
796 | if (!insideInner) {
|
---|
797 | // Final check using predicate
|
---|
798 | if (isOuterWayAMatch == null || isOuterWayAMatch.evaluate(out)) {
|
---|
799 | return true;
|
---|
800 | }
|
---|
801 | }
|
---|
802 | }
|
---|
803 | }
|
---|
804 | return false;
|
---|
805 | }
|
---|
806 | }
|
---|