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