source: josm/trunk/src/org/openstreetmap/josm/data/projection/CustomProjection.java@ 11746

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

PMD - Strict Exceptions

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