001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.data.projection; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.util.ArrayList; 007import java.util.Arrays; 008import java.util.EnumMap; 009import java.util.HashMap; 010import java.util.List; 011import java.util.Map; 012import java.util.Optional; 013import java.util.concurrent.ConcurrentHashMap; 014import java.util.regex.Matcher; 015import java.util.regex.Pattern; 016import java.util.stream.IntStream; 017 018import org.openstreetmap.josm.data.Bounds; 019import org.openstreetmap.josm.data.ProjectionBounds; 020import org.openstreetmap.josm.data.coor.EastNorth; 021import org.openstreetmap.josm.data.coor.ILatLon; 022import org.openstreetmap.josm.data.coor.LatLon; 023import org.openstreetmap.josm.data.coor.conversion.LatLonParser; 024import org.openstreetmap.josm.data.projection.datum.CentricDatum; 025import org.openstreetmap.josm.data.projection.datum.Datum; 026import org.openstreetmap.josm.data.projection.datum.NTV2Datum; 027import org.openstreetmap.josm.data.projection.datum.NullDatum; 028import org.openstreetmap.josm.data.projection.datum.SevenParameterDatum; 029import org.openstreetmap.josm.data.projection.datum.ThreeParameterDatum; 030import org.openstreetmap.josm.data.projection.datum.WGS84Datum; 031import org.openstreetmap.josm.data.projection.proj.ICentralMeridianProvider; 032import org.openstreetmap.josm.data.projection.proj.IScaleFactorProvider; 033import org.openstreetmap.josm.data.projection.proj.Mercator; 034import org.openstreetmap.josm.data.projection.proj.Proj; 035import org.openstreetmap.josm.data.projection.proj.ProjParameters; 036import org.openstreetmap.josm.tools.JosmRuntimeException; 037import org.openstreetmap.josm.tools.Logging; 038import org.openstreetmap.josm.tools.Utils; 039import org.openstreetmap.josm.tools.bugreport.BugReport; 040import org.openstreetmap.josm.tools.bugreport.ReportedException; 041 042/** 043 * Custom projection. 044 * <p> 045 * Inspired by PROJ.4 and Proj4J. 046 * @since 5072 047 */ 048public class CustomProjection extends AbstractProjection { 049 050 /* 051 * Equation for METER_PER_UNIT_DEGREE taken from: 052 * https://github.com/openlayers/ol3/blob/master/src/ol/proj/epsg4326projection.js#L58 053 * Value for Radius taken form: 054 * https://github.com/openlayers/ol3/blob/master/src/ol/sphere/wgs84sphere.js#L11 055 */ 056 private static final double METER_PER_UNIT_DEGREE = 2 * Math.PI * 6378137.0 / 360; 057 private static final Map<String, Double> UNITS_TO_METERS = getUnitsToMeters(); 058 private static final Map<String, Double> PRIME_MERIDANS = getPrimeMeridians(); 059 060 /** 061 * pref String that defines the projection 062 * <p> 063 * null means fall back mode (Mercator) 064 */ 065 protected String pref; 066 protected String name; 067 protected String code; 068 protected Bounds bounds; 069 private double metersPerUnitWMTS; 070 /** 071 * Starting in PROJ 4.8.0, the {@code +axis} argument can be used to control the axis orientation of the coordinate system. 072 * The default orientation is "easting, northing, up" but directions can be flipped, or axes flipped using 073 * combinations of the axes in the {@code +axis} switch. The values are: {@code e} (Easting), {@code w} (Westing), 074 * {@code n} (Northing), {@code s} (Southing), {@code u} (Up), {@code d} (Down); 075 * Examples: {@code +axis=enu} (the default easting, northing, elevation), {@code +axis=neu} (northing, easting, up; 076 * useful for "lat/long" geographic coordinates, or south orientated transverse mercator), {@code +axis=wnu} 077 * (westing, northing, up - some planetary coordinate systems have "west positive" coordinate systems)<p> 078 * See <a href="https://proj4.org/usage/projections.html#axis-orientation">proj4.org</a> 079 */ 080 private String axis = "enu"; // default axis orientation is East, North, Up 081 082 private static final List<String> LON_LAT_VALUES = Arrays.asList("longlat", "latlon", "latlong"); 083 084 /** 085 * Proj4-like projection parameters. See <a href="https://trac.osgeo.org/proj/wiki/GenParms">reference</a>. 086 * @since 7370 (public) 087 */ 088 public enum Param { 089 090 /** False easting */ 091 x_0("x_0", true), 092 /** False northing */ 093 y_0("y_0", true), 094 /** Central meridian */ 095 lon_0("lon_0", true), 096 /** Prime meridian */ 097 pm("pm", true), 098 /** Scaling factor */ 099 k_0("k_0", true), 100 /** Ellipsoid name (see {@code proj -le}) */ 101 ellps("ellps", true), 102 /** Semimajor radius of the ellipsoid axis */ 103 a("a", true), 104 /** Eccentricity of the ellipsoid squared */ 105 es("es", true), 106 /** Reciprocal of the ellipsoid flattening term (e.g. 298) */ 107 rf("rf", true), 108 /** Flattening of the ellipsoid = 1-sqrt(1-e^2) */ 109 f("f", true), 110 /** Semiminor radius of the ellipsoid axis */ 111 b("b", true), 112 /** Datum name (see {@code proj -ld}) */ 113 datum("datum", true), 114 /** 3 or 7 term datum transform parameters */ 115 towgs84("towgs84", true), 116 /** Filename of NTv2 grid file to use for datum transforms */ 117 nadgrids("nadgrids", true), 118 /** Projection name (see {@code proj -l}) */ 119 proj("proj", true), 120 /** Latitude of origin */ 121 lat_0("lat_0", true), 122 /** Latitude of first standard parallel */ 123 lat_1("lat_1", true), 124 /** Latitude of second standard parallel */ 125 lat_2("lat_2", true), 126 /** Latitude of true scale (Polar Stereographic) */ 127 lat_ts("lat_ts", true), 128 /** longitude of the center of the projection (Oblique Mercator) */ 129 lonc("lonc", true), 130 /** azimuth (true) of the center line passing through the center of the 131 * projection (Oblique Mercator) */ 132 alpha("alpha", true), 133 /** rectified bearing of the center line (Oblique Mercator) */ 134 gamma("gamma", true), 135 /** select "Hotine" variant of Oblique Mercator */ 136 no_off("no_off", false), 137 /** legacy alias for no_off */ 138 no_uoff("no_uoff", false), 139 /** longitude of first point (Oblique Mercator) */ 140 lon_1("lon_1", true), 141 /** longitude of second point (Oblique Mercator) */ 142 lon_2("lon_2", true), 143 /** the exact proj.4 string will be preserved in the WKT representation */ 144 wktext("wktext", false), // ignored 145 /** meters, US survey feet, etc. */ 146 units("units", true), 147 /** Don't use the /usr/share/proj/proj_def.dat defaults file */ 148 no_defs("no_defs", false), 149 init("init", true), 150 /** crs units to meter multiplier */ 151 to_meter("to_meter", true), 152 /** definition of axis for projection */ 153 axis("axis", true), 154 /** UTM zone */ 155 zone("zone", true), 156 /** indicate southern hemisphere for UTM */ 157 south("south", false), 158 /** vertical units - ignore, as we don't use height information */ 159 vunits("vunits", true), 160 // JOSM extensions, not present in PROJ.4 161 wmssrs("wmssrs", true), 162 bounds("bounds", true); 163 164 /** Parameter key */ 165 public final String key; 166 /** {@code true} if the parameter has a value */ 167 public final boolean hasValue; 168 169 /** Map of all parameters by key */ 170 static final Map<String, Param> paramsByKey = new ConcurrentHashMap<>(); 171 static { 172 for (Param p : Param.values()) { 173 paramsByKey.put(p.key, p); 174 } 175 // alias 176 paramsByKey.put("k", Param.k_0); 177 } 178 179 Param(String key, boolean hasValue) { 180 this.key = key; 181 this.hasValue = hasValue; 182 } 183 } 184 185 enum Polarity { 186 NORTH(LatLon.NORTH_POLE), 187 SOUTH(LatLon.SOUTH_POLE); 188 189 @SuppressWarnings("ImmutableEnumChecker") 190 private final LatLon latlon; 191 192 Polarity(LatLon latlon) { 193 this.latlon = latlon; 194 } 195 196 LatLon getLatLon() { 197 return latlon; 198 } 199 } 200 201 private EnumMap<Polarity, EastNorth> polesEN; 202 203 /** 204 * Constructs a new empty {@code CustomProjection}. 205 */ 206 public CustomProjection() { 207 // contents can be set later with update() 208 } 209 210 /** 211 * Constructs a new {@code CustomProjection} with given parameters. 212 * @param pref String containing projection parameters 213 * (ex: "+proj=tmerc +lon_0=-3 +k_0=0.9996 +x_0=500000 +ellps=WGS84 +datum=WGS84 +bounds=-8,-5,2,85") 214 */ 215 public CustomProjection(String pref) { 216 this(null, null, pref); 217 } 218 219 /** 220 * Constructs a new {@code CustomProjection} with given name, code and parameters. 221 * 222 * @param name describe projection in one or two words 223 * @param code unique code for this projection - may be null 224 * @param pref the string that defines the custom projection 225 */ 226 public CustomProjection(String name, String code, String pref) { 227 this.name = name; 228 this.code = code; 229 this.pref = pref; 230 try { 231 update(pref); 232 } catch (ProjectionConfigurationException ex) { 233 Logging.trace(ex); 234 try { 235 update(null); 236 } catch (ProjectionConfigurationException ex1) { 237 ReportedException reportedException = BugReport.intercept(ex1).put("name", name).put("code", code).put("pref", pref); 238 reportedException.addSuppressed(ex); 239 throw reportedException; 240 } 241 } 242 } 243 244 /** 245 * Updates this {@code CustomProjection} with given parameters. 246 * @param pref String containing projection parameters (ex: "+proj=lonlat +ellps=WGS84 +datum=WGS84 +bounds=-180,-90,180,90") 247 * @throws ProjectionConfigurationException if {@code pref} cannot be parsed properly 248 */ 249 public final void update(String pref) throws ProjectionConfigurationException { 250 this.pref = pref; 251 if (pref == null) { 252 ellps = Ellipsoid.WGS84; 253 datum = WGS84Datum.INSTANCE; 254 proj = new Mercator(); 255 bounds = new Bounds( 256 -85.05112877980659, -180.0, 257 85.05112877980659, 180.0, true); 258 } else { 259 Map<String, String> parameters = parseParameterList(pref, false); 260 parameters = resolveInits(parameters, false); 261 ellps = parseEllipsoid(parameters); 262 datum = parseDatum(parameters, ellps); 263 if (ellps == null) { 264 ellps = datum.getEllipsoid(); 265 } 266 proj = parseProjection(parameters, ellps); 267 // "utm" is a shortcut for a set of parameters 268 if ("utm".equals(parameters.get(Param.proj.key))) { 269 Integer zone; 270 try { 271 zone = Integer.valueOf(Optional.ofNullable(parameters.get(Param.zone.key)).orElseThrow( 272 () -> new ProjectionConfigurationException(tr("UTM projection (''+proj=utm'') requires ''+zone=...'' parameter.")))); 273 } catch (NumberFormatException e) { 274 zone = null; 275 } 276 if (zone == null || zone < 1 || zone > 60) 277 throw new ProjectionConfigurationException(tr("Expected integer value in range 1-60 for ''+zone=...'' parameter.")); 278 this.lon0 = 6d * zone - 183d; 279 this.k0 = 0.9996; 280 this.x0 = 500_000; 281 this.y0 = parameters.containsKey(Param.south.key) ? 10_000_000 : 0; 282 } 283 String s = parameters.get(Param.x_0.key); 284 if (s != null) { 285 this.x0 = parseDouble(s, Param.x_0.key); 286 } 287 s = parameters.get(Param.y_0.key); 288 if (s != null) { 289 this.y0 = parseDouble(s, Param.y_0.key); 290 } 291 s = parameters.get(Param.lon_0.key); 292 if (s != null) { 293 this.lon0 = parseAngle(s, Param.lon_0.key); 294 } 295 if (proj instanceof ICentralMeridianProvider) { 296 this.lon0 = ((ICentralMeridianProvider) proj).getCentralMeridian(); 297 } 298 s = parameters.get(Param.pm.key); 299 if (s != null) { 300 if (PRIME_MERIDANS.containsKey(s)) { 301 this.pm = PRIME_MERIDANS.get(s); 302 } else { 303 this.pm = parseAngle(s, Param.pm.key); 304 } 305 } 306 s = parameters.get(Param.k_0.key); 307 if (s != null) { 308 this.k0 = parseDouble(s, Param.k_0.key); 309 } 310 if (proj instanceof IScaleFactorProvider) { 311 this.k0 *= ((IScaleFactorProvider) proj).getScaleFactor(); 312 } 313 s = parameters.get(Param.bounds.key); 314 this.bounds = s != null ? parseBounds(s) : null; 315 s = parameters.get(Param.wmssrs.key); 316 if (s != null) { 317 this.code = s; 318 } 319 boolean defaultUnits = true; 320 s = parameters.get(Param.units.key); 321 if (s != null) { 322 s = Utils.strip(s, "\""); 323 if (UNITS_TO_METERS.containsKey(s)) { 324 this.toMeter = UNITS_TO_METERS.get(s); 325 this.metersPerUnitWMTS = this.toMeter; 326 defaultUnits = false; 327 } else { 328 throw new ProjectionConfigurationException(tr("No unit found for: {0}", s)); 329 } 330 } 331 s = parameters.get(Param.to_meter.key); 332 if (s != null) { 333 this.toMeter = parseDouble(s, Param.to_meter.key); 334 this.metersPerUnitWMTS = this.toMeter; 335 defaultUnits = false; 336 } 337 if (defaultUnits) { 338 this.toMeter = 1; 339 this.metersPerUnitWMTS = proj.isGeographic() ? METER_PER_UNIT_DEGREE : 1; 340 } 341 s = parameters.get(Param.axis.key); 342 if (s != null) { 343 this.axis = s; 344 } 345 } 346 } 347 348 /** 349 * Parse a parameter list to key=value pairs. 350 * 351 * @param pref the parameter list 352 * @param ignoreUnknownParameter true, if unknown parameter should not raise exception 353 * @return parameters map 354 * @throws ProjectionConfigurationException in case of invalid parameter 355 */ 356 public static Map<String, String> parseParameterList(String pref, boolean ignoreUnknownParameter) throws ProjectionConfigurationException { 357 Map<String, String> parameters = new HashMap<>(); 358 String trimmedPref = pref.trim(); 359 if (trimmedPref.isEmpty()) { 360 return parameters; 361 } 362 363 Pattern keyPattern = Pattern.compile("\\+(?<key>[a-zA-Z0-9_]+)(=(?<value>.*))?"); 364 String[] parts = Utils.WHITE_SPACES_PATTERN.split(trimmedPref, -1); 365 for (String part : parts) { 366 Matcher m = keyPattern.matcher(part); 367 if (m.matches()) { 368 String key = m.group("key"); 369 String value = m.group("value"); 370 // some aliases 371 if (key.equals(Param.proj.key) && LON_LAT_VALUES.contains(value)) { 372 value = "lonlat"; 373 } 374 Param param = Param.paramsByKey.get(key); 375 if (param == null) { 376 if (!ignoreUnknownParameter) 377 throw new ProjectionConfigurationException(tr("Unknown parameter: ''{0}''.", key)); 378 } else { 379 if (param.hasValue && value == null) 380 throw new ProjectionConfigurationException(tr("Value expected for parameter ''{0}''.", key)); 381 if (!param.hasValue && value != null) 382 throw new ProjectionConfigurationException(tr("No value expected for parameter ''{0}''.", key)); 383 key = param.key; // To be really sure, we might have an alias. 384 } 385 parameters.put(key, value); 386 } else if (!part.startsWith("+")) { 387 throw new ProjectionConfigurationException(tr("Parameter must begin with a ''+'' character (found ''{0}'')", part)); 388 } else { 389 throw new ProjectionConfigurationException(tr("Unexpected parameter format (''{0}'')", part)); 390 } 391 } 392 return parameters; 393 } 394 395 /** 396 * Recursive resolution of +init includes. 397 * 398 * @param parameters parameters map 399 * @param ignoreUnknownParameter true, if unknown parameter should not raise exception 400 * @return parameters map with +init includes resolved 401 * @throws ProjectionConfigurationException in case of invalid parameter 402 */ 403 public static Map<String, String> resolveInits(Map<String, String> parameters, boolean ignoreUnknownParameter) 404 throws ProjectionConfigurationException { 405 // recursive resolution of +init includes 406 String initKey = parameters.get(Param.init.key); 407 if (initKey != null) { 408 Map<String, String> initp; 409 try { 410 initp = parseParameterList(Optional.ofNullable(Projections.getInit(initKey)).orElseThrow( 411 () -> new ProjectionConfigurationException(tr("Value ''{0}'' for option +init not supported.", initKey))), 412 ignoreUnknownParameter); 413 initp = resolveInits(initp, ignoreUnknownParameter); 414 } catch (ProjectionConfigurationException ex) { 415 throw new ProjectionConfigurationException(initKey+": "+ex.getMessage(), ex); 416 } 417 initp.putAll(parameters); 418 return initp; 419 } 420 return parameters; 421 } 422 423 /** 424 * Gets the ellipsoid 425 * @param parameters The parameters to get the value from 426 * @return The Ellipsoid as specified with the parameters 427 * @throws ProjectionConfigurationException in case of invalid parameters 428 */ 429 public Ellipsoid parseEllipsoid(Map<String, String> parameters) throws ProjectionConfigurationException { 430 String code = parameters.get(Param.ellps.key); 431 if (code != null) { 432 return Optional.ofNullable(Projections.getEllipsoid(code)).orElseThrow( 433 () -> new ProjectionConfigurationException(tr("Ellipsoid ''{0}'' not supported.", code))); 434 } 435 String s = parameters.get(Param.a.key); 436 if (s != null) { 437 double a = parseDouble(s, Param.a.key); 438 if (parameters.get(Param.es.key) != null) { 439 double es = parseDouble(parameters, Param.es.key); 440 return Ellipsoid.createAes(a, es); 441 } 442 if (parameters.get(Param.rf.key) != null) { 443 double rf = parseDouble(parameters, Param.rf.key); 444 return Ellipsoid.createArf(a, rf); 445 } 446 if (parameters.get(Param.f.key) != null) { 447 double f = parseDouble(parameters, Param.f.key); 448 return Ellipsoid.createAf(a, f); 449 } 450 if (parameters.get(Param.b.key) != null) { 451 double b = parseDouble(parameters, Param.b.key); 452 return Ellipsoid.createAb(a, b); 453 } 454 } 455 if (parameters.containsKey(Param.a.key) || 456 parameters.containsKey(Param.es.key) || 457 parameters.containsKey(Param.rf.key) || 458 parameters.containsKey(Param.f.key) || 459 parameters.containsKey(Param.b.key)) 460 throw new ProjectionConfigurationException(tr("Combination of ellipsoid parameters is not supported.")); 461 return null; 462 } 463 464 /** 465 * Gets the datum 466 * @param parameters The parameters to get the value from 467 * @param ellps The ellisoid that was previously computed 468 * @return The Datum as specified with the parameters 469 * @throws ProjectionConfigurationException in case of invalid parameters 470 */ 471 public Datum parseDatum(Map<String, String> parameters, Ellipsoid ellps) throws ProjectionConfigurationException { 472 Datum result = null; 473 String datumId = parameters.get(Param.datum.key); 474 if (datumId != null) { 475 result = Optional.ofNullable(Projections.getDatum(datumId)).orElseThrow( 476 () -> new ProjectionConfigurationException(tr("Unknown datum identifier: ''{0}''", datumId))); 477 } 478 if (ellps == null) { 479 if (result == null && parameters.containsKey(Param.no_defs.key)) 480 throw new ProjectionConfigurationException(tr("Ellipsoid required (+ellps=* or +a=*, +b=*)")); 481 // nothing specified, use WGS84 as default 482 ellps = result != null ? result.getEllipsoid() : Ellipsoid.WGS84; 483 } 484 485 String nadgridsId = parameters.get(Param.nadgrids.key); 486 if (nadgridsId != null) { 487 if (nadgridsId.startsWith("@")) { 488 nadgridsId = nadgridsId.substring(1); 489 } 490 if ("null".equals(nadgridsId)) 491 return new NullDatum(null, ellps); 492 final String fNadgridsId = nadgridsId; 493 return new NTV2Datum(fNadgridsId, null, ellps, Optional.ofNullable(Projections.getNTV2Grid(fNadgridsId)).orElseThrow( 494 () -> new ProjectionConfigurationException(tr("Grid shift file ''{0}'' for option +nadgrids not supported.", fNadgridsId)))); 495 } 496 497 String towgs84 = parameters.get(Param.towgs84.key); 498 if (towgs84 != null) { 499 Datum towgs84Datum = parseToWGS84(towgs84, ellps); 500 if (result == null || towgs84Datum instanceof ThreeParameterDatum || towgs84Datum instanceof SevenParameterDatum) { 501 // +datum has priority over +towgs84=0,0,0[,0,0,0,0] 502 return towgs84Datum; 503 } 504 } 505 506 return result != null ? result : new NullDatum(null, ellps); 507 } 508 509 /** 510 * Parse {@code towgs84} parameter. 511 * @param paramList List of parameter arguments (expected: 3 or 7) 512 * @param ellps ellipsoid 513 * @return parsed datum ({@link ThreeParameterDatum} or {@link SevenParameterDatum}) 514 * @throws ProjectionConfigurationException if the arguments cannot be parsed 515 */ 516 public Datum parseToWGS84(String paramList, Ellipsoid ellps) throws ProjectionConfigurationException { 517 String[] numStr = paramList.split(",", -1); 518 519 if (numStr.length != 3 && numStr.length != 7) 520 throw new ProjectionConfigurationException(tr("Unexpected number of arguments for parameter ''towgs84'' (must be 3 or 7)")); 521 List<Double> towgs84Param = new ArrayList<>(); 522 for (String str : numStr) { 523 try { 524 towgs84Param.add(Double.valueOf(str)); 525 } catch (NumberFormatException e) { 526 throw new ProjectionConfigurationException(tr("Unable to parse value of parameter ''towgs84'' (''{0}'')", str), e); 527 } 528 } 529 boolean isCentric = towgs84Param.stream().noneMatch(param -> param != 0); 530 if (isCentric) 531 return Ellipsoid.WGS84.equals(ellps) ? WGS84Datum.INSTANCE : new CentricDatum(null, null, ellps); 532 boolean is3Param = IntStream.range(3, towgs84Param.size()).noneMatch(i -> towgs84Param.get(i) != 0); 533 if (is3Param) 534 return new ThreeParameterDatum(null, null, ellps, 535 towgs84Param.get(0), 536 towgs84Param.get(1), 537 towgs84Param.get(2)); 538 else 539 return new SevenParameterDatum(null, null, ellps, 540 towgs84Param.get(0), 541 towgs84Param.get(1), 542 towgs84Param.get(2), 543 towgs84Param.get(3), 544 towgs84Param.get(4), 545 towgs84Param.get(5), 546 towgs84Param.get(6)); 547 } 548 549 /** 550 * Gets a projection using the given ellipsoid 551 * @param parameters Additional parameters 552 * @param ellps The {@link Ellipsoid} 553 * @return The projection 554 * @throws ProjectionConfigurationException in case of invalid parameters 555 */ 556 public Proj parseProjection(Map<String, String> parameters, Ellipsoid ellps) throws ProjectionConfigurationException { 557 String id = parameters.get(Param.proj.key); 558 if (id == null) throw new ProjectionConfigurationException(tr("Projection required (+proj=*)")); 559 560 // "utm" is not a real projection, but a shortcut for a set of parameters 561 if ("utm".equals(id)) { 562 id = "tmerc"; 563 } 564 Proj proj = Projections.getBaseProjection(id); 565 if (proj == null) throw new ProjectionConfigurationException(tr("Unknown projection identifier: ''{0}''", id)); 566 567 ProjParameters projParams = new ProjParameters(); 568 569 projParams.ellps = ellps; 570 571 String s; 572 s = parameters.get(Param.lat_0.key); 573 if (s != null) { 574 projParams.lat0 = parseAngle(s, Param.lat_0.key); 575 } 576 s = parameters.get(Param.lat_1.key); 577 if (s != null) { 578 projParams.lat1 = parseAngle(s, Param.lat_1.key); 579 } 580 s = parameters.get(Param.lat_2.key); 581 if (s != null) { 582 projParams.lat2 = parseAngle(s, Param.lat_2.key); 583 } 584 s = parameters.get(Param.lat_ts.key); 585 if (s != null) { 586 projParams.lat_ts = parseAngle(s, Param.lat_ts.key); 587 } 588 s = parameters.get(Param.lonc.key); 589 if (s != null) { 590 projParams.lonc = parseAngle(s, Param.lonc.key); 591 } 592 s = parameters.get(Param.alpha.key); 593 if (s != null) { 594 projParams.alpha = parseAngle(s, Param.alpha.key); 595 } 596 s = parameters.get(Param.gamma.key); 597 if (s != null) { 598 projParams.gamma = parseAngle(s, Param.gamma.key); 599 } 600 s = parameters.get(Param.lon_0.key); 601 if (s != null) { 602 projParams.lon0 = parseAngle(s, Param.lon_0.key); 603 } 604 s = parameters.get(Param.lon_1.key); 605 if (s != null) { 606 projParams.lon1 = parseAngle(s, Param.lon_1.key); 607 } 608 s = parameters.get(Param.lon_2.key); 609 if (s != null) { 610 projParams.lon2 = parseAngle(s, Param.lon_2.key); 611 } 612 if (parameters.containsKey(Param.no_off.key) || parameters.containsKey(Param.no_uoff.key)) { 613 projParams.no_off = Boolean.TRUE; 614 } 615 proj.initialize(projParams); 616 return proj; 617 } 618 619 /** 620 * Converts a string to a bounds object 621 * @param boundsStr The string as comma separated list of angles. 622 * @return The bounds. 623 * @throws ProjectionConfigurationException in case of invalid parameter 624 * @see CustomProjection#parseAngle(String, String) 625 */ 626 public static Bounds parseBounds(String boundsStr) throws ProjectionConfigurationException { 627 String[] numStr = boundsStr.split(",", -1); 628 if (numStr.length != 4) 629 throw new ProjectionConfigurationException(tr("Unexpected number of arguments for parameter ''+bounds'' (must be 4)")); 630 return new Bounds(parseAngle(numStr[1], "minlat (+bounds)"), 631 parseAngle(numStr[0], "minlon (+bounds)"), 632 parseAngle(numStr[3], "maxlat (+bounds)"), 633 parseAngle(numStr[2], "maxlon (+bounds)"), false); 634 } 635 636 public static double parseDouble(Map<String, String> parameters, String parameterName) throws ProjectionConfigurationException { 637 if (!parameters.containsKey(parameterName)) 638 throw new ProjectionConfigurationException(tr("Unknown parameter: ''{0}''.", parameterName)); 639 return parseDouble(Optional.ofNullable(parameters.get(parameterName)).orElseThrow( 640 () -> new ProjectionConfigurationException(tr("Expected number argument for parameter ''{0}''", parameterName))), 641 parameterName); 642 } 643 644 public static double parseDouble(String doubleStr, String parameterName) throws ProjectionConfigurationException { 645 try { 646 return Double.parseDouble(doubleStr); 647 } catch (NumberFormatException e) { 648 throw new ProjectionConfigurationException( 649 tr("Unable to parse value ''{1}'' of parameter ''{0}'' as number.", parameterName, doubleStr), e); 650 } 651 } 652 653 /** 654 * Convert an angle string to a double value 655 * @param angleStr The string. e.g. -1.1 or 50d10'3" 656 * @param parameterName Only for error message. 657 * @return The angle value, in degrees. 658 * @throws ProjectionConfigurationException in case of invalid parameter 659 */ 660 public static double parseAngle(String angleStr, String parameterName) throws ProjectionConfigurationException { 661 try { 662 return LatLonParser.parseCoordinate(angleStr); 663 } catch (IllegalArgumentException e) { 664 throw new ProjectionConfigurationException( 665 tr("Unable to parse value ''{1}'' of parameter ''{0}'' as coordinate value.", parameterName, angleStr), e); 666 } 667 } 668 669 @Override 670 public Integer getEpsgCode() { 671 if (code != null && code.startsWith("EPSG:")) { 672 try { 673 return Integer.valueOf(code.substring(5)); 674 } catch (NumberFormatException e) { 675 Logging.warn(e); 676 } 677 } 678 return null; 679 } 680 681 @Override 682 public String toCode() { 683 if (code != null) { 684 return code; 685 } else if (pref != null) { 686 return "proj:" + pref; 687 } else { 688 return "proj:ERROR"; 689 } 690 } 691 692 @Override 693 public Bounds getWorldBoundsLatLon() { 694 if (bounds == null) { 695 Bounds ab = proj.getAlgorithmBounds(); 696 if (ab != null) { 697 double minlon = Math.max(ab.getMinLon() + lon0 + pm, -180); 698 double maxlon = Math.min(ab.getMaxLon() + lon0 + pm, 180); 699 bounds = new Bounds(ab.getMinLat(), minlon, ab.getMaxLat(), maxlon, false); 700 } else { 701 bounds = new Bounds( 702 new LatLon(-90.0, -180.0), 703 new LatLon(90.0, 180.0)); 704 } 705 } 706 return bounds; 707 } 708 709 @Override 710 public String toString() { 711 return name != null ? name : tr("Custom Projection"); 712 } 713 714 /** 715 * Factor to convert units of east/north coordinates to meters. 716 * 717 * When east/north coordinates are in degrees (geographic CRS), the scale 718 * at the equator is taken, i.e. 360 degrees corresponds to the length of 719 * the equator in meters. 720 * 721 * @return factor to convert units to meter 722 */ 723 @Override 724 public double getMetersPerUnit() { 725 return metersPerUnitWMTS; 726 } 727 728 @Override 729 public boolean switchXY() { 730 // TODO: support for other axis orientation such as West South, and Up Down 731 // +axis=neu 732 return this.axis.startsWith("ne"); 733 } 734 735 private static Map<String, Double> getUnitsToMeters() { 736 Map<String, Double> ret = new ConcurrentHashMap<>(); 737 ret.put("km", 1000d); 738 ret.put("m", 1d); 739 ret.put("dm", 1d/10); 740 ret.put("cm", 1d/100); 741 ret.put("mm", 1d/1000); 742 ret.put("kmi", 1852.0); 743 ret.put("in", 0.0254); 744 ret.put("ft", 0.3048); 745 ret.put("yd", 0.9144); 746 ret.put("mi", 1609.344); 747 ret.put("fathom", 1.8288); 748 ret.put("chain", 20.1168); 749 ret.put("link", 0.201168); 750 ret.put("us-in", 1d/39.37); 751 ret.put("us-ft", 0.304800609601219); 752 ret.put("us-yd", 0.914401828803658); 753 ret.put("us-ch", 20.11684023368047); 754 ret.put("us-mi", 1609.347218694437); 755 ret.put("ind-yd", 0.91439523); 756 ret.put("ind-ft", 0.30479841); 757 ret.put("ind-ch", 20.11669506); 758 ret.put("degree", METER_PER_UNIT_DEGREE); 759 return ret; 760 } 761 762 private static Map<String, Double> getPrimeMeridians() { 763 Map<String, Double> ret = new ConcurrentHashMap<>(); 764 try { 765 ret.put("greenwich", 0.0); 766 ret.put("lisbon", parseAngle("9d07'54.862\"W", null)); 767 ret.put("paris", parseAngle("2d20'14.025\"E", null)); 768 ret.put("bogota", parseAngle("74d04'51.3\"W", null)); 769 ret.put("madrid", parseAngle("3d41'16.58\"W", null)); 770 ret.put("rome", parseAngle("12d27'8.4\"E", null)); 771 ret.put("bern", parseAngle("7d26'22.5\"E", null)); 772 ret.put("jakarta", parseAngle("106d48'27.79\"E", null)); 773 ret.put("ferro", parseAngle("17d40'W", null)); 774 ret.put("brussels", parseAngle("4d22'4.71\"E", null)); 775 ret.put("stockholm", parseAngle("18d3'29.8\"E", null)); 776 ret.put("athens", parseAngle("23d42'58.815\"E", null)); 777 ret.put("oslo", parseAngle("10d43'22.5\"E", null)); 778 } catch (ProjectionConfigurationException ex) { 779 throw new IllegalStateException(ex); 780 } 781 return ret; 782 } 783 784 private static EastNorth getPointAlong(int i, int n, ProjectionBounds r) { 785 double dEast = (r.maxEast - r.minEast) / n; 786 double dNorth = (r.maxNorth - r.minNorth) / n; 787 if (i < n) { 788 return new EastNorth(r.minEast + i * dEast, r.minNorth); 789 } else if (i < 2*n) { 790 i -= n; 791 return new EastNorth(r.maxEast, r.minNorth + i * dNorth); 792 } else if (i < 3*n) { 793 i -= 2*n; 794 return new EastNorth(r.maxEast - i * dEast, r.maxNorth); 795 } else if (i < 4*n) { 796 i -= 3*n; 797 return new EastNorth(r.minEast, r.maxNorth - i * dNorth); 798 } else { 799 throw new AssertionError(); 800 } 801 } 802 803 private EastNorth getPole(Polarity whichPole) { 804 if (polesEN == null) { 805 polesEN = new EnumMap<>(Polarity.class); 806 for (Polarity p : Polarity.values()) { 807 polesEN.put(p, null); 808 LatLon ll = p.getLatLon(); 809 try { 810 EastNorth enPole = latlon2eastNorth(ll); 811 if (enPole.isValid()) { 812 // project back and check if the result is somewhat reasonable 813 LatLon llBack = eastNorth2latlon(enPole); 814 if (llBack.isValid() && ll.greatCircleDistance((ILatLon) llBack) < 1000) { 815 polesEN.put(p, enPole); 816 } 817 } 818 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) { 819 Logging.error(e); 820 } 821 } 822 } 823 return polesEN.get(whichPole); 824 } 825 826 @Override 827 public Bounds getLatLonBoundsBox(ProjectionBounds r) { 828 final int n = 10; 829 Bounds result = new Bounds(eastNorth2latlon(r.getMin())); 830 result.extend(eastNorth2latlon(r.getMax())); 831 LatLon llPrev = null; 832 for (int i = 0; i < 4*n; i++) { 833 LatLon llNow = eastNorth2latlon(getPointAlong(i, n, r)); 834 result.extend(llNow); 835 // check if segment crosses 180th meridian and if so, make sure 836 // to extend bounds to +/-180 degrees longitude 837 if (llPrev != null) { 838 double lon1 = llPrev.lon(); 839 double lon2 = llNow.lon(); 840 if (90 < lon1 && lon1 < 180 && -180 < lon2 && lon2 < -90) { 841 result.extend(new LatLon(llPrev.lat(), 180)); 842 result.extend(new LatLon(llNow.lat(), -180)); 843 } 844 if (90 < lon2 && lon2 < 180 && -180 < lon1 && lon1 < -90) { 845 result.extend(new LatLon(llNow.lat(), 180)); 846 result.extend(new LatLon(llPrev.lat(), -180)); 847 } 848 } 849 llPrev = llNow; 850 } 851 // if the box contains one of the poles, the above method did not get 852 // correct min/max latitude value 853 for (Polarity p : Polarity.values()) { 854 EastNorth pole = getPole(p); 855 if (pole != null && r.contains(pole)) { 856 result.extend(p.getLatLon()); 857 } 858 } 859 return result; 860 } 861 862 @Override 863 public ProjectionBounds getEastNorthBoundsBox(ProjectionBounds box, Projection boxProjection) { 864 final int n = 8; 865 ProjectionBounds result = null; 866 for (int i = 0; i < 4*n; i++) { 867 EastNorth en = latlon2eastNorth(boxProjection.eastNorth2latlon(getPointAlong(i, n, box))); 868 if (result == null) { 869 result = new ProjectionBounds(en); 870 } else { 871 result.extend(en); 872 } 873 } 874 return result; 875 } 876 877 /** 878 * Return true, if a geographic coordinate reference system is represented. 879 * <p> 880 * I.e. if it returns latitude/longitude values rather than Cartesian 881 * east/north coordinates on a flat surface. 882 * @return true, if it is geographic 883 * @since 12792 884 */ 885 public boolean isGeographic() { 886 return proj.isGeographic(); 887 } 888 889}