Debian Codegraph @

src/uk/me/parabola/imgfmt/app/Coord.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 Steve Ratcliffe
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 *
14 * Author: Steve Ratcliffe
15 * Create date: 11-Dec-2006
16 */
17 package uk.me.parabola.imgfmt.app;
18
19 import java.util.ArrayList;
20 import java.util.List;
21 import java.util.Locale;
22
23 import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
24 import uk.me.parabola.imgfmt.Utils;
25 import uk.me.parabola.mkgmap.filters.ShapeMergeFilter;
26
27 /**
28 * A point coordinate in unshifted map-units.
29 * A map unit is 360/2^24 degrees. In some places <i>shifted</i> coordinates
30 * are used, which means that they are divided by some power of two to save
31 * space in the file.
32 *
33 * You can create one of these with lat/long by calling the constructor with
34 * double args.
35 *
36 * See also http://www.movable-type.co.uk/scripts/latlong.html
37 *
38 * @author Steve Ratcliffe
39 */
40 public class Coord implements Comparable<Coord> {
41 private static final short ON_BOUNDARY_MASK = 0x0001; // bit in flags is true if point lies on a boundary
42 private static final short PRESERVED_MASK = 0x0002; // bit in flags is true if point should not be filtered out
43 private static final short REPLACED_MASK = 0x0004; // bit in flags is true if point was replaced
44 private static final short ADDED_BY_CLIPPER_MASK = 0x0008; // bit in flags is true if point was added by clipper
45 private static final short SKIP_DEAD_END_CHECK_NODE_MASK = 0x0010; // bit in flags is true if a node with this coords has a tag listed in --dead-ends
46 private static final short REMOVE_MASK = 0x0020; // bit in flags is true if this point should be removed
47 private static final short VIA_NODE_MASK = 0x0040; // bit in flags is true if a node with this coords is the via node of a RestrictionRelation
48
49 private static final short PART_OF_BAD_ANGLE = 0x0080; // bit in flags is true if point should be treated as a node
50 private static final short PART_OF_SHAPE2 = 0x0100; // use only in ShapeMerger
51 private static final short END_OF_WAY = 0x0200; // use only in WrongAngleFixer
52 private static final short HOUSENUMBER_NODE = 0x0400; // start/end of house number interval
53 private static final short ADDED_HOUSENUMBER_NODE = 0x0800; // node was added for house numbers
54 private static final short ON_COUNTRY_BORDER = 0x1000; // node is on a country border
55
56 private static final int HIGH_PREC_BITS = 30;
57 public static final int DELTA_SHIFT = HIGH_PREC_BITS - 24;
58 private static final int MAX_DELTA = 1 << (DELTA_SHIFT - 2); // max delta abs value that is considered okay
59 private static final long FACTOR_HP = 1L << HIGH_PREC_BITS;
60 private static final int HIGH_PREC_UNUSED_BITS = Integer.SIZE - HIGH_PREC_BITS;
61
62 public static final double R = 6378137.0; // Radius of earth at equator as defined by WGS84
63 public static final double U = R * 2 * Math.PI; // circumference of earth at equator (WGS84)
64 public static final double MEAN_EARTH_RADIUS = 6371000; // earth is a flattened sphere
65
66 private final int latitude;
67 private final int longitude;
68 private byte highwayCount; // number of highways that use this point
69 private short flags; // further attributes
70 private final byte latDelta; // delta to high precision latitude value
71 private final byte lonDelta; // delta to high precision longitude value
72 private short approxDistanceToDisplayedCoord = -1;
73
74 /**
75 * Construct from co-ordinates that are already in map-units.
76 * @param latitude The latitude in map units.
77 * @param longitude The longitude in map units.
78 */
79 public Coord(int latitude, int longitude) {
80 this.latitude = latitude;
81 this.longitude = longitude;
82 latDelta = lonDelta = 0;
83 }
84
85 /**
86 * Construct from regular latitude and longitude.
87 * @param latitude The latitude in degrees.
88 * @param longitude The longitude in degrees.
89 */
90 public Coord(double latitude, double longitude) {
91 this.latitude = Utils.toMapUnit(latitude);
92 this.longitude = Utils.toMapUnit(longitude);
93 int latHighPrec = toHighPrec(latitude);
94 int lonHighPrec = toHighPrec(longitude);
95 this.latDelta = (byte) ((this.latitude << DELTA_SHIFT) - latHighPrec);
96 this.lonDelta = (byte) ((this.longitude << DELTA_SHIFT) - lonHighPrec);
97
98 // verify math
99 assert (this.latitude << DELTA_SHIFT) - (int) latDelta == latHighPrec;
100 assert (this.longitude << DELTA_SHIFT) - (int) lonDelta == lonHighPrec;
101 }
102
103 private Coord (int lat, int lon, byte latDelta, byte lonDelta){
104 this.latitude = lat;
105 this.longitude = lon;
106 this.latDelta = latDelta;
107 this.lonDelta = lonDelta;
108 }
109
110 /**
111 * Constructor for high precision values.
112 * @param latHighPrec latitude in high precision
113 * @param lonHighPrec longitude in high precision
114 * @return Coord instance
115 */
116 public static Coord makeHighPrecCoord(int latHighPrec, int lonHighPrec){
117 int lat24 = (latHighPrec + (1 << (DELTA_SHIFT - 1))) >> DELTA_SHIFT;
118 int lon24 = (lonHighPrec + (1 << (DELTA_SHIFT - 1))) >> DELTA_SHIFT;
119 byte dLat = (byte) ((lat24 << DELTA_SHIFT) - latHighPrec);
120 byte dLon = (byte) ((lon24 << DELTA_SHIFT) - lonHighPrec);
121 return new Coord(lat24, lon24, dLat, dLon);
122 }
123
124 public static Coord makeHighPrecCoord(int latHp, int lonHp, Long2ObjectOpenHashMap<Coord> coordPool) {
125 if (coordPool == null)
126 return makeHighPrecCoord(latHp, lonHp);
127 long key = (latHp & 0xffffffffL) << 32 | (lonHp & 0xffffffffL);
128 Coord p = coordPool.get(key);
129 if (p == null) {
130 p = makeHighPrecCoord(latHp, lonHp);
131 coordPool.put(key, p);
132 }
133 return p;
134 }
135
136 /**
137 * Construct from other coord instance, copies
138 * the lat/lon values in high precision
139 * @param other
140 */
141 public Coord(Coord other) {
142 this.latitude = other.latitude;
143 this.longitude = other.longitude;
144 this.latDelta = other.latDelta;
145 this.lonDelta = other.lonDelta;
146 this.approxDistanceToDisplayedCoord = other.approxDistanceToDisplayedCoord;
147 }
148
149 public int getLatitude() {
150 return latitude;
151 }
152
153 public int getLongitude() {
154 return longitude;
155 }
156
157 /**
158 * @return the route node id
159 */
160 public int getId() {
161 return 0;
162 }
163
164 public int getHighwayCount() {
165 return highwayCount;
166 }
167
168 /**
169 * Increase the counter how many highways use this coord.
170 */
171 public void incHighwayCount() {
172 // don't let it wrap
173 if(highwayCount < Byte.MAX_VALUE)
174 ++highwayCount;
175 }
176
177 /**
178 * Decrease the counter how many highways use this coord.
179 */
180 public void decHighwayCount() {
181 // don't let it wrap
182 if(highwayCount > 0)
183 --highwayCount;
184 }
185
186 /**
187 * Resets the highway counter to 0.
188 */
189 public void resetHighwayCount() {
190 highwayCount = 0;
191 }
192
193 public boolean getOnBoundary() {
194 return (flags & ON_BOUNDARY_MASK) != 0;
195 }
196
197 public void setOnBoundary(boolean onBoundary) {
198 if (onBoundary)
199 this.flags |= ON_BOUNDARY_MASK;
200 else
201 this.flags &= ~ON_BOUNDARY_MASK;
202 }
203
204 public boolean preserved() {
205 return (flags & PRESERVED_MASK) != 0;
206 }
207
208 public void preserved(boolean preserved) {
209 if (preserved)
210 this.flags |= PRESERVED_MASK;
211 else
212 this.flags &= ~PRESERVED_MASK;
213 }
214
215 /**
216 * Returns if this coord was marked to be replaced in short arc removal.
217 * @return True means the replacement has to be looked up.
218 */
219 public boolean isReplaced() {
220 return (flags & REPLACED_MASK) != 0;
221 }
222
223 /**
224 * Mark a point as replaced in short arc removal process.
225 * @param replaced true or false
226 */
227 public void setReplaced(boolean replaced) {
228 if (replaced)
229 this.flags |= REPLACED_MASK;
230 else
231 this.flags &= ~REPLACED_MASK;
232 }
233
234 /**
235 * @return true if this coord was added by a clipper
236 */
237 public boolean isAddedByClipper() {
238 return (flags & ADDED_BY_CLIPPER_MASK) != 0;
239 }
240
241 /**
242 * Mark the Coord as added by clipper
243 * @param b true or false
244 */
245 public void setAddedByClipper(boolean b) {
246 if (b)
247 this.flags |= ADDED_BY_CLIPPER_MASK;
248 else
249 this.flags &= ~ADDED_BY_CLIPPER_MASK;
250 }
251
252 /**
253 * Does this coordinate belong to a node with a tag specified in --dead-ends?
254 * Note that the value is set after evaluating the points style.
255 * @return true if the flag is set, else false
256 */
257 public boolean isSkipDeadEndCheck() {
258 return (flags & SKIP_DEAD_END_CHECK_NODE_MASK) != 0;
259 }
260
261 public void setSkipDeadEndCheck(boolean b) {
262 if (b)
263 this.flags |= SKIP_DEAD_END_CHECK_NODE_MASK;
264 else
265 this.flags &= ~SKIP_DEAD_END_CHECK_NODE_MASK;
266 }
267
268 public boolean isToRemove() {
269 return (flags & REMOVE_MASK) != 0;
270 }
271
272 public void setRemove(boolean b) {
273 if (b)
274 this.flags |= REMOVE_MASK;
275 else
276 this.flags &= ~REMOVE_MASK;
277 }
278
279 /**
280 * @return true if this coordinate belong to a via node of a restriction relation
281 */
282 public boolean isViaNodeOfRestriction() {
283 return (flags & VIA_NODE_MASK) != 0;
284 }
285
286 /**
287 * @param b true: Mark the coordinate as via node of a restriction relation
288 */
289 public void setViaNodeOfRestriction(boolean b) {
290 if (b)
291 this.flags |= VIA_NODE_MASK;
292 else
293 this.flags &= ~VIA_NODE_MASK;
294 }
295
296 /**
297 * Should this Coord be treated by the removeWrongAngle method=
298 * The value has no meaning outside of StyledConverter.
299 * @return true if this coord is part of a line that has a big bearing error.
300 */
301 public boolean isPartOfBadAngle() {
302 return (flags & PART_OF_BAD_ANGLE) != 0;
303 }
304
305 /**
306 * Mark the Coord to be part of a line which has a big bearing
307 * error because of the rounding to map units.
308 * @param b true or false
309 */
310 public void setPartOfBadAngle(boolean b) {
311 if (b)
312 this.flags |= PART_OF_BAD_ANGLE;
313 else
314 this.flags &= ~PART_OF_BAD_ANGLE;
315 }
316
317 /**
318 * Get flag for {@link ShapeMergeFilter}
319 * The value has no meaning outside of {@link ShapeMergeFilter}
320 * @return flag value
321 */
322 public boolean isPartOfShape2() {
323 return (flags & PART_OF_SHAPE2) != 0;
324 }
325
326 /**
327 * Set or unset flag for {@link ShapeMergeFilter}
328 * @param b true or false
329 */
330 public void setPartOfShape2(boolean b) {
331 if (b)
332 this.flags |= PART_OF_SHAPE2;
333 else
334 this.flags &= ~PART_OF_SHAPE2;
335 }
336
337 /**
338 * Get flag for {@link WrongAngleFixer}
339 * The value has no meaning outside of {@link WrongAngleFixer}
340 * @return flag value
341 */
342 public boolean isEndOfWay() {
343 return (flags & END_OF_WAY) != 0;
344 }
345
346 /**
347 * Set or unset flag for {@link WrongAngleFixer}
348 * @param b true or false
349 */
350 public void setEndOfWay(boolean b) {
351 if (b)
352 this.flags |= END_OF_WAY;
353 else
354 this.flags &= ~END_OF_WAY;
355 }
356
357 /**
358 * @return true if this is the beginning/end of a house number interval
359 */
360 public boolean isNumberNode(){
361 return (flags & HOUSENUMBER_NODE) != 0;
362 }
363
364 /**
365 * @param b true or false
366 */
367 public void setNumberNode(boolean b) {
368 if (b)
369 this.flags |= HOUSENUMBER_NODE;
370 else
371 this.flags &= ~HOUSENUMBER_NODE;
372 }
373
374 /**
375 * @return true if this was added by the housenumber processing
376 */
377 public boolean isAddedNumberNode(){
378 return (flags & ADDED_HOUSENUMBER_NODE) != 0;
379 }
380
381 /**
382 * @param b true or false
383 */
384 public void setAddedNumberNode(boolean b) {
385 if (b)
386 this.flags |= ADDED_HOUSENUMBER_NODE;
387 else
388 this.flags &= ~ADDED_HOUSENUMBER_NODE;
389 }
390
391 /**
392 * @return true if this was marked as place on country border.
393 */
394 public boolean getOnCountryBorder() {
395 return (flags & ON_COUNTRY_BORDER) != 0;
396 }
397
398 /**
399 * Mark as place on a country border
400 * @param onCountryBorder
401 */
402 public void setOnCountryBorder(boolean onCountryBorder) {
403 if (onCountryBorder)
404 this.flags |= ON_COUNTRY_BORDER;
405 else
406 this.flags &= ~ON_COUNTRY_BORDER;
407 }
408
409 public int hashCode() {
410 // Use a factor for latitude to span over the whole integer range:
411 // max lat: 4194304
412 // max lon: 8388608
413 // max hashCode: 2118123520 < 2147483647 (Integer.MAX_VALUE)
414 return 503 * latitude + longitude;
415 }
416
417 /**
418 * Compares the coordinates that are displayed in the map
419 */
420 public boolean equals(Object obj) {
421 if (!(obj instanceof Coord))
422 return false;
423 Coord other = (Coord) obj;
424 return latitude == other.latitude && longitude == other.longitude;
425 }
426
427 /**
428 * Compares the coordinates using the delta values.
429 * XXX: Note that
430 * p1.highPrecEquals(p2) is not always equal to p1.equals(p2)
431 * @param other
432 * @return
433 */
434 public boolean highPrecEquals(Coord other) {
435 if (other == null)
436 return false;
437 if (this == other)
438 return true;
439 return getHighPrecLat() == other.getHighPrecLat() && getHighPrecLon() == other.getHighPrecLon();
440 }
441
442 /**
443 * Distance to other point in metres, using
444 * "flat earth approximation" or rhumb-line algo
445 */
446 public double distance(Coord other) {
447 double d1 = U / 360 * Math.sqrt(distanceInDegreesSquared(other));
448 if (d1 < 10000)
449 return d1; // error is below 0.01 m
450 // for long distances, use more complex algorithm
451 return distanceOnRhumbLine(other);
452 }
453
454 /**
455 * Square of distance to other point in metres, using
456 * "flat earth approximation"
457 */
458 public double distanceInDegreesSquared(Coord other) {
459 if (this == other || highPrecEquals(other))
460 return 0;
461
462 double lat1 = getLatDegrees();
463 double lat2 = other.getLatDegrees();
464 double long1 = getLonDegrees();
465 double long2 = other.getLonDegrees();
466
467 double latDiff;
468 if (lat1 < lat2)
469 latDiff = lat2 - lat1;
470 else
471 latDiff = lat1 - lat2;
472 if (latDiff > 90)
473 latDiff -= 180;
474
475 double longDiff;
476 if (long1 < long2)
477 longDiff = long2 - long1;
478 else
479 longDiff = long1 - long2;
480 if (longDiff > 180)
481 longDiff -= 360;
482
483 // scale longDiff by cosine of average latitude
484 longDiff *= Math.cos(Math.PI / 180 * Math.abs((lat1 + lat2) / 2));
485
486 return (latDiff * latDiff) + (longDiff * longDiff);
487 }
488
489 /**
490 * Distance to other point in metres following a great circle path, without
491 * flat earth approximation, slower but better with large
492 * distances and big deltas in lat AND lon.
493 * Similar to code in JOSM
494 */
495 public double distanceHaversine (Coord point){
496 double lat1 = hpToRadians(getHighPrecLat());
497 double lat2 = hpToRadians(point.getHighPrecLat());
498 double lon1 = hpToRadians(getHighPrecLon());
499 double lon2 = hpToRadians(point.getHighPrecLon());
500 double sinMidLat = Math.sin((lat1-lat2)/2);
501 double sinMidLon = Math.sin((lon1-lon2)/2);
502 double dRad = 2*Math.asin(Math.sqrt(sinMidLat*sinMidLat + Math.cos(lat1)*Math.cos(lat2)*sinMidLon*sinMidLon));
503 return dRad * R; // the distance
504 }
505
506 /**
507 * Distance to other point in metres following the shortest rhumb line.
508 */
509 public double distanceOnRhumbLine(Coord point){
510 double lat1 = hpToRadians(getHighPrecLat());
511 double lat2 = hpToRadians(point.getHighPrecLat());
512 double lon1 = hpToRadians(getHighPrecLon());
513 double lon2 = hpToRadians(point.getHighPrecLon());
514
515 // see http://williams.best.vwh.net/avform.htm#Rhumb
516
517 double dLat = lat2 - lat1;
518 double dLon = Math.abs(lon2 - lon1);
519 // if dLon over 180° take shorter rhumb line across the anti-meridian:
520 if (Math.abs(dLon) > Math.PI) dLon = dLon>0 ? -(2*Math.PI-dLon) : (2*Math.PI+dLon);
521
522 // on Mercator projection, longitude distances shrink by latitude; q is the 'stretch factor'
523 // q becomes ill-conditioned along E-W line (0/0); use empirical tolerance to avoid it
524 double deltaPhi = Math.log(Math.tan(lat2/2+Math.PI/4)/Math.tan(lat1/2+Math.PI/4));
525 double q = Math.abs(deltaPhi) > 10e-12 ? dLat/deltaPhi : Math.cos(lat1);
526
527 // distance is pythagoras on 'stretched' Mercator projection
528 double distRad = Math.sqrt(dLat*dLat + q*q*dLon*dLon); // angular distance in radians
529 return distRad * R; // the distance
530 }
531
532 /**
533 * Distance to other point in high precision squared units
534 */
535 public long distanceInHighPrecSquared(Coord other) {
536 int dLatHp = other.getHighPrecLat() - getHighPrecLat();
537 int dLonHp = other.getHighPrecLon() - getHighPrecLon();
538 dLonHp = (dLonHp << HIGH_PREC_UNUSED_BITS) >> HIGH_PREC_UNUSED_BITS; // fix wrap-around earth
539 return (long)dLatHp * dLatHp + (long)dLonHp * dLonHp;
540 }
541
542 /**
543 * Calculate point on the line this->other. If d is the distance between this and other,
544 * the point is {@code fraction * d} metres from this.
545 * For small distances between this and other we use a flat earth approximation,
546 * for large distances this could result in errors of many metres, so we use
547 * the rhumb line calculations.
548 */
549 public Coord makeBetweenPoint(Coord other, double fraction) {
550 int dlatHp = other.getHighPrecLat() - getHighPrecLat();
551 int dlonHp = other.getHighPrecLon() - getHighPrecLon();
552 if (dlonHp == 0 || Math.abs(dlatHp) < 1000000 && Math.abs(dlonHp) < 1000000) {
553 // distances are rather small, we can use flat earth approximation
554 int latHighPrec = (int)Math.round(getHighPrecLat() + dlatHp * fraction);
555 int lonHighPrec = (int)Math.round(getHighPrecLon() + dlonHp * fraction);
556 return makeHighPrecCoord(latHighPrec, lonHighPrec);
557 }
558 double brng = this.bearingToOnRhumbLine(other, true);
559 double dist = this.distance(other) * fraction;
560 return this.destOnRhumbLine(dist, brng);
561 }
562
563
564 /**
565 * returns bearing (in degrees) from current point to another point
566 * following a rhumb line
567 */
568 public double bearingTo(Coord point) {
569 return bearingToOnRhumbLine(point, false);
570 }
571
572 /**
573 * returns bearing (in degrees) from current point to another point
574 * following a great circle path
575 * @param point the other point
576 * @param needHighPrec set to true if you need a very high precision
577 */
578 public double bearingToOnGreatCircle(Coord point, boolean needHighPrec) {
579 // use high precision values for this
580 double lat1 = hpToRadians(getHighPrecLat());
581 double lat2 = hpToRadians(point.getHighPrecLat());
582 double lon1 = hpToRadians(getHighPrecLon());
583 double lon2 = hpToRadians(point.getHighPrecLon());
584
585 double dlon = lon2 - lon1;
586
587 double y = Math.sin(dlon) * Math.cos(lat2);
588 double x = Math.cos(lat1)*Math.sin(lat2) -
589 Math.sin(lat1)*Math.cos(lat2)*Math.cos(dlon);
590 double brngRad = needHighPrec ? Math.atan2(y, x) : Utils.atan2_approximation(y, x);
591 return brngRad * 180 / Math.PI;
592 }
593
594 /**
595 * returns bearing (in degrees) from current point to another point
596 * following shortest rhumb line
597 * @param point the other point
598 * @param needHighPrec set to true if you need a very high precision
599 */
600 public double bearingToOnRhumbLine(Coord point, boolean needHighPrec){
601 double lat1 = hpToRadians(this.getHighPrecLat());
602 double lat2 = hpToRadians(point.getHighPrecLat());
603 double lon1 = hpToRadians(this.getHighPrecLon());
604 double lon2 = hpToRadians(point.getHighPrecLon());
605
606 double dLon = lon2-lon1;
607 // if dLon over 180° take shorter rhumb line across the anti-meridian:
608 if (Math.abs(dLon) > Math.PI) dLon = dLon>0 ? -(2*Math.PI-dLon) : (2*Math.PI+dLon);
609
610 double deltaPhi = Math.log(Math.tan(lat2/2+Math.PI/4)/Math.tan(lat1/2+Math.PI/4));
611
612 double brngRad = needHighPrec ? Math.atan2(dLon, deltaPhi) : Utils.atan2_approximation(dLon, deltaPhi);
613 return brngRad * 180 / Math.PI;
614 }
615
616
617 /**
618 * Sort lexicographically by longitude, then latitude.
619 *
620 * This ordering is used for sorting entries in NOD3.
621 */
622 public int compareTo(Coord other) {
623 if (longitude == other.getLongitude()) {
624 if (latitude == other.getLatitude())
625 return 0;
626 return latitude > other.getLatitude() ? 1 : -1;
627 }
628 return longitude > other.getLongitude() ? 1 : -1;
629 }
630
631 /**
632 * Returns a string representation of the object in degrees.
633 *
634 * @return a string representation of the object in degrees
635 */
636 public String toString() {
637 return String.format(Locale.ENGLISH, "%.6f,%.6f",
638 getLatDegrees(),
639 getLonDegrees());
640 }
641
642 /**
643 * Returns a string representation of the object showing Garmin units
644 *
645 * @return a string representation of the object showing Garmin units
646 */
647 public String toGarminString() {
648 return (latitude) + "/" + (longitude);
649 }
650
651 protected String toOSMURL(int zoom) {
652 return ("http://www.openstreetmap.org/?mlat=" +
653 String.format(Locale.ENGLISH, "%.6f", getLatDegrees()) +
654 "&mlon=" +
655 String.format(Locale.ENGLISH, "%.6f", getLonDegrees()) +
656 "&zoom=" +
657 zoom);
658 }
659
660 public String toOSMURL() {
661 return toOSMURL(17);
662 }
663
664 /**
665 * Convert latitude or longitude to HIGH_PREC_BITS bits value.
666 * This allows higher precision than the 24 bits
667 * used in map units.
668 * @param degrees The latitude or longitude as decimal degrees.
669 * @return An integer value with {@code HIGH_PREC_BITS} bit precision.
670 */
671 private static int toHighPrec(double degrees) {
672 // this is a bit like Utils.toMapUnit() except needs to be offset to give range -31..+32
673 // in each MapUnit in Coord() calc above; this is accomplished by not rounding
674 final double DELTA = 360.0D;
675 final double RESCALE = (1 << HIGH_PREC_BITS) / 360.0D;
676 final int UNDO360 = 1 << HIGH_PREC_BITS;
677 return (int)((degrees + DELTA) * RESCALE) - UNDO360;
678 }
679
680 /* Factor for conversion to radians using HIGH_PREC_BITS bits
681 * (Math.PI / 180) * (360.0 / (1 << HIGH_PREC_BITS))
682 */
683 static final double HIGH_PREC_RAD_FACTOR = 2 * Math.PI / FACTOR_HP;
684
685 /**
686 * Convert to radians using high precision
687 * @param valHighPrec a longitude/latitude value with HIGH_PREC_BITS bit precision
688 * @return an angle in radians.
689 */
690 public static double hpToRadians(int valHighPrec){
691 return HIGH_PREC_RAD_FACTOR * valHighPrec;
692 }
693
694 /**
695 * @return Latitude as signed HIGH_PREC_BITS bit integer
696 */
697 public int getHighPrecLat() {
698 return (latitude << DELTA_SHIFT) - (int) latDelta;
699 }
700
701 /**
702 * @return Longitude as signed HIGH_PREC_BITS bit integer
703 */
704 public int getHighPrecLon() {
705 return (longitude << DELTA_SHIFT) - (int) lonDelta;
706 }
707
708 /**
709 * @return latitude in degrees with highest avail. precision
710 */
711 public double getLatDegrees(){
712 return (360.0D / FACTOR_HP) * getHighPrecLat();
713 }
714
715 /**
716 * @return longitude in degrees with highest avail. precision
717 */
718 public double getLonDegrees(){
719 return (360.0D / FACTOR_HP) * getHighPrecLon();
720 }
721
722 public Coord getDisplayedCoord(){
723 return new Coord(latitude,longitude);
724 }
725
726 /**
727 * Check if the rounding to 24 bit resolution caused large error. If so, the point may be placed
728 * at an alternative position.
729 * @return true if rounding error is large.
730 */
731 public boolean hasAlternativePos(){
732 if (getOnBoundary() || getOnCountryBorder())
733 return false;
734 return (Math.abs(latDelta) > MAX_DELTA || Math.abs(lonDelta) > MAX_DELTA);
735 }
736 /**
737 * Calculate up to three points with equal
738 * high precision coordinate, but
739 * different map unit coordinates.
740 * @return a list of Coord instances, is empty if alternative positions are too far
741 */
742 public List<Coord> getAlternativePositions(){
743 ArrayList<Coord> list = new ArrayList<>();
744 if (getOnBoundary() || getOnCountryBorder())
745 return list;
746 int modLatDelta = 0;
747 int modLonDelta = 0;
748
749 int modLat = latitude;
750 int modLon = longitude;
751 if (latDelta > MAX_DELTA)
752 modLat--;
753 else if (latDelta < -MAX_DELTA)
754 modLat++;
755 if (lonDelta > MAX_DELTA)
756 modLon--;
757 else if (lonDelta < -MAX_DELTA)
758 modLon++;
759 int latHighPrec = getHighPrecLat();
760 int lonHighPrec = getHighPrecLon();
761 modLatDelta = (modLat << DELTA_SHIFT) - latHighPrec;
762 modLonDelta = (modLon << DELTA_SHIFT) - lonHighPrec;
763 assert modLatDelta >= Byte.MIN_VALUE && modLatDelta <= Byte.MAX_VALUE;
764 assert modLonDelta >= Byte.MIN_VALUE && modLonDelta <= Byte.MAX_VALUE;
765 if (modLat != latitude){
766 if (modLon != longitude)
767 list.add(new Coord(modLat, modLon, (byte)modLatDelta, (byte)modLonDelta));
768 list.add(new Coord(modLat, longitude, (byte)modLatDelta, lonDelta));
769 }
770 if (modLon != longitude)
771 list.add(new Coord(latitude, modLon, latDelta, (byte)modLonDelta));
772 /* verify math
773 for(Coord co:list){
774 double d = distance(new Coord (co.getLatitude(),co.getLongitude()));
775 assert d < 3.0;
776 }
777 */
778 return list;
779 }
780
781 /**
782 * @return approximate distance in cm
783 */
784 public short getDistToDisplayedPoint() {
785 if (approxDistanceToDisplayedCoord < 0) {
786 approxDistanceToDisplayedCoord = (short) Math.round(getDisplayedCoord().distance(this) * 100);
787 }
788 return approxDistanceToDisplayedCoord;
789 }
790
791 /**
792 * Get the coord that is {@code dist} metre away travelling with course
793 * {@code brng} on a rhumb-line.
794 * @param dist distance in m
795 * @param brng bearing in degrees
796 * @return a new Coord instance
797 */
798 public Coord destOnRhumbLine(double dist, double brng){
799 double distRad = dist / R; // angular distance in radians
800 double lat1 = hpToRadians(this.getHighPrecLat());
801 double lon1 = hpToRadians(this.getHighPrecLon());
802
803 double brngRad = Math.toRadians(brng);
804
805 double deltaLat = distRad * Math.cos(brngRad);
806
807 double lat2 = lat1 + deltaLat;
808 // check for some daft bugger going past the pole, normalise latitude if so
809 if (Math.abs(lat2) > Math.PI/2) lat2 = lat2>0 ? Math.PI-lat2 : -Math.PI-lat2;
810 double lon2;
811 // catch special case: normalised value would be -8388608
812 if (this.getLongitude() == 8388608 && brng == 0)
813 lon2 = lon1;
814 else {
815 double deltaPhi = Math.log(Math.tan(lat2/2+Math.PI/4)/Math.tan(lat1/2+Math.PI/4));
816 double q = Math.abs(deltaPhi) > 10e-12 ? deltaLat / deltaPhi : Math.cos(lat1); // E-W course becomes ill-conditioned with 0/0
817
818 double deltaLon = distRad*Math.sin(brngRad)/q;
819
820 lon2 = lon1 + deltaLon;
821
822 lon2 = (lon2 + 3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180º
823 }
824
825 return new Coord(Math.toDegrees(lat2), Math.toDegrees(lon2));
826 }
827
828 /**
829 * Calculate the distance in metres to the rhumb line
830 * defined by coords a and b.
831 * @param a start point
832 * @param b end point
833 * @return perpendicular distance in m.
834 */
835 public double distToLineSegment(Coord a, Coord b){
836 double ab = a.distance(b);
837 double ap = a.distance(this);
838 if (ab == 0) {
839 return ap;
840 }
841 double bp = b.distance(this);
842 if (ap == 0 || bp == 0)
843 return 0;
844 double abpa = (ab+ap+bp)/2;
845 double dx = abpa-ab;
846 double dist;
847 if (dx < 0){
848 // simple calculation using Herons formula will fail
849 // calculate x, the point on line a-b which is as far away from a as this point
850 double b_ab = a.bearingToOnRhumbLine(b, true);
851 Coord x = a.destOnRhumbLine(ap, b_ab);
852 // this dist between these two points is not exactly
853 // the perpendicular distance, but close enough
854 dist = x.distance(this);
855 }
856 else
857 dist = 2 * Math.sqrt(abpa * (abpa-ab) * (abpa-ap) * (abpa-bp)) / ab;
858 return dist;
859 }
860
861 /**
862 * Calculate distance to rhumb line segment a-b.
863 * @param a point a
864 * @param b point b
865 * @return distance in m
866 */
867 public double shortestDistToLineSegment(Coord a, Coord b){
868 int aLon = a.getHighPrecLon();
869 int bLon = b.getHighPrecLon();
870 int aLat = a.getHighPrecLat();
871 int bLat = b.getHighPrecLat();
872
873 double deltaLon = (bLon - aLon);
874 double deltaLat = (bLat - aLat);
875
876 double frac;
877 if (deltaLon == 0 && deltaLat == 0){
878 frac = 0;
879 }
880 else {
881 int pLon = this.getHighPrecLon();
882 int pLat = this.getHighPrecLat();
883 // scale for longitude deltas by cosine of average latitude
884 double scale = Math.cos(Coord.hpToRadians((aLat + bLat + pLat) / 3) );
885 deltaLon = scale * deltaLon;
886 if (deltaLon == 0 && deltaLat == 0)
887 frac = 0;
888 else {
889 double deltaLonAP = scale * (pLon - aLon);
890 frac = (deltaLonAP * deltaLon + (pLat - aLat) * deltaLat) / (deltaLon * deltaLon + deltaLat * deltaLat);
891 }
892 }
893
894 double distance;
895 if (frac <= 0) {
896 distance = a.distance(this);
897 } else if (frac >= 1) {
898 distance = b.distance(this);
899 } else {
900 distance = this.distToLineSegment(a, b);
901 }
902 return distance;
903 }
904
905 /**
906 * @return a new coordinate at the specified distance (metres) away along the specified bearing (degrees)
907 * uses "Destination point given distance and bearing from start point" formula from
908 * http://www.movable-type.co.uk/scripts/latlong.html
909 */
910 public Coord offset(double bearingInDegrees, double distanceInMetres) {
911 double bearing = Math.toRadians(bearingInDegrees);
912 double angularDistance = distanceInMetres / MEAN_EARTH_RADIUS;
913 double lat = Math.toRadians(getLatDegrees());
914 double lon = Math.toRadians(getLonDegrees());
915 double newLat = Math.asin(Math.sin(lat) * Math.cos(angularDistance) + Math.cos(lat) * Math.sin(angularDistance) * Math.cos(bearing));
916 double newLon = lon + Math.atan2(Math.sin(bearing) * Math.sin(angularDistance) * Math.cos(lat), Math.cos(angularDistance) - Math.sin(lat) * Math.sin(newLat));
917 return new Coord(Math.toDegrees(newLat), Math.toDegrees(newLon));
918 }
919
920 /**
921 * Calculate if this point lies on the left or right of the line through the given points.
922 * @param p0 first point
923 * @param p2 second point
924 * @return positive value if on left, negative value if on the right, 0 if on the line
925 */
926 public long isLeft(final Coord p1, final Coord p2) {
927 long p1Lat = p1.getHighPrecLat();
928 long p1Lon = p1.getHighPrecLon();
929 return ((long) p2.getHighPrecLon() - p1Lon) * ((long) this.getHighPrecLat() - p1Lat)
930 - ((long) p2.getHighPrecLat() - p1Lat) * ((long) this.getHighPrecLon() - p1Lon);
931 }
932 }