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

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

fix some compilation warnings

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