001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.projection;
003
004import java.io.BufferedReader;
005import java.io.IOException;
006import java.util.ArrayList;
007import java.util.Collection;
008import java.util.Collections;
009import java.util.HashMap;
010import java.util.HashSet;
011import java.util.LinkedHashMap;
012import java.util.List;
013import java.util.Locale;
014import java.util.Map;
015import java.util.Set;
016import java.util.concurrent.ConcurrentHashMap;
017import java.util.function.Supplier;
018import java.util.regex.Matcher;
019import java.util.regex.Pattern;
020import java.util.stream.Collectors;
021
022import org.openstreetmap.josm.data.projection.datum.Datum;
023import org.openstreetmap.josm.data.projection.datum.GRS80Datum;
024import org.openstreetmap.josm.data.projection.datum.NTV2GridShiftFileWrapper;
025import org.openstreetmap.josm.data.projection.datum.SevenParameterDatum;
026import org.openstreetmap.josm.data.projection.datum.ThreeParameterDatum;
027import org.openstreetmap.josm.data.projection.datum.WGS84Datum;
028import org.openstreetmap.josm.data.projection.proj.AlbersEqualArea;
029import org.openstreetmap.josm.data.projection.proj.AzimuthalEquidistant;
030import org.openstreetmap.josm.data.projection.proj.CassiniSoldner;
031import org.openstreetmap.josm.data.projection.proj.ClassProjFactory;
032import org.openstreetmap.josm.data.projection.proj.DoubleStereographic;
033import org.openstreetmap.josm.data.projection.proj.EquidistantCylindrical;
034import org.openstreetmap.josm.data.projection.proj.LambertAzimuthalEqualArea;
035import org.openstreetmap.josm.data.projection.proj.LambertConformalConic;
036import org.openstreetmap.josm.data.projection.proj.LonLat;
037import org.openstreetmap.josm.data.projection.proj.Mercator;
038import org.openstreetmap.josm.data.projection.proj.ObliqueMercator;
039import org.openstreetmap.josm.data.projection.proj.PolarStereographic;
040import org.openstreetmap.josm.data.projection.proj.Proj;
041import org.openstreetmap.josm.data.projection.proj.ProjFactory;
042import org.openstreetmap.josm.data.projection.proj.Sinusoidal;
043import org.openstreetmap.josm.data.projection.proj.SwissObliqueMercator;
044import org.openstreetmap.josm.data.projection.proj.TransverseMercator;
045import org.openstreetmap.josm.io.CachedFile;
046import org.openstreetmap.josm.tools.JosmRuntimeException;
047import org.openstreetmap.josm.tools.Logging;
048
049/**
050 * Class to manage projections.
051 *
052 * Use this class to query available projection or register new projections from a plugin.
053 */
054public final class Projections {
055
056    /**
057     * Class to hold information about one projection.
058     */
059    public static class ProjectionDefinition {
060        /**
061         * EPSG code
062         */
063        public final String code;
064        /**
065         * Projection name
066         */
067        public final String name;
068        /**
069         * projection definition (EPSG format)
070         */
071        public final String definition;
072
073        /**
074         * Constructs a new {@code ProjectionDefinition}.
075         * @param code EPSG code
076         * @param name projection name
077         * @param definition projection definition (EPSG format)
078         */
079        public ProjectionDefinition(String code, String name, String definition) {
080            this.code = code.intern();
081            this.name = name.intern();
082            this.definition = definition.intern();
083        }
084    }
085
086    private static final Set<String> allCodes = new HashSet<>();
087    private static final Map<String, Supplier<Projection>> projectionSuppliersByCode = new HashMap<>();
088    private static final Map<String, Projection> projectionsByCodeCache = new ConcurrentHashMap<>();
089
090    /*********************************
091     * Registry for custom projection
092     *
093     * should be compatible to PROJ.4
094     */
095    private static final Map<String, ProjFactory> projs = new HashMap<>();
096    private static final Map<String, Ellipsoid> ellipsoids = new HashMap<>();
097    private static final Map<String, Datum> datums = new HashMap<>();
098    private static final Map<String, NTV2GridShiftFileWrapper> nadgrids = new HashMap<>();
099    private static final Map<String, ProjectionDefinition> inits;
100
101    static {
102        registerBaseProjection("aea", AlbersEqualArea.class, "core");
103        registerBaseProjection("aeqd", AzimuthalEquidistant.class, "core");
104        registerBaseProjection("cass", CassiniSoldner.class, "core");
105        registerBaseProjection("eqc", EquidistantCylindrical.class, "core");
106        registerBaseProjection("laea", LambertAzimuthalEqualArea.class, "core");
107        registerBaseProjection("lcc", LambertConformalConic.class, "core");
108        registerBaseProjection("lonlat", LonLat.class, "core");
109        registerBaseProjection("merc", Mercator.class, "core");
110        registerBaseProjection("omerc", ObliqueMercator.class, "core");
111        registerBaseProjection("somerc", SwissObliqueMercator.class, "core");
112        registerBaseProjection("sinu", Sinusoidal.class, "core");
113        registerBaseProjection("stere", PolarStereographic.class, "core");
114        registerBaseProjection("sterea", DoubleStereographic.class, "core");
115        registerBaseProjection("tmerc", TransverseMercator.class, "core");
116
117        ellipsoids.put("airy", Ellipsoid.Airy);
118        ellipsoids.put("mod_airy", Ellipsoid.AiryMod);
119        ellipsoids.put("aust_SA", Ellipsoid.AustSA);
120        ellipsoids.put("bessel", Ellipsoid.Bessel1841);
121        ellipsoids.put("bess_nam", Ellipsoid.BesselNamibia);
122        ellipsoids.put("clrk66", Ellipsoid.Clarke1866);
123        ellipsoids.put("clrk80", Ellipsoid.Clarke1880);
124        ellipsoids.put("clrk80ign", Ellipsoid.ClarkeIGN);
125        ellipsoids.put("evrst30", Ellipsoid.Everest);
126        ellipsoids.put("evrst48", Ellipsoid.Everest1948);
127        ellipsoids.put("evrst56", Ellipsoid.Everest1956);
128        ellipsoids.put("evrst69", Ellipsoid.Everest1969);
129        ellipsoids.put("evrstSS", Ellipsoid.EverestSabahSarawak);
130        ellipsoids.put("fschr60", Ellipsoid.Fischer);
131        ellipsoids.put("fschr60m", Ellipsoid.FischerMod);
132        ellipsoids.put("fschr68", Ellipsoid.Fischer1968);
133        ellipsoids.put("intl", Ellipsoid.Hayford);
134        ellipsoids.put("helmert", Ellipsoid.Helmert);
135        ellipsoids.put("hough", Ellipsoid.Hough);
136        ellipsoids.put("krass", Ellipsoid.Krassowsky);
137        ellipsoids.put("sphere", Ellipsoid.Sphere);
138        ellipsoids.put("walbeck", Ellipsoid.Walbeck);
139        ellipsoids.put("GRS67", Ellipsoid.GRS67);
140        ellipsoids.put("GRS80", Ellipsoid.GRS80);
141        ellipsoids.put("WGS66", Ellipsoid.WGS66);
142        ellipsoids.put("WGS72", Ellipsoid.WGS72);
143        ellipsoids.put("WGS84", Ellipsoid.WGS84);
144
145        datums.put("WGS84", WGS84Datum.INSTANCE);
146        datums.put("NAD83", GRS80Datum.INSTANCE);
147        datums.put("carthage", new ThreeParameterDatum(
148                "Carthage 1934 Tunisia", "carthage",
149                Ellipsoid.ClarkeIGN, -263.0, 6.0, 431.0));
150        datums.put("GGRS87", new ThreeParameterDatum(
151                "Greek Geodetic Reference System 1987", "GGRS87",
152                Ellipsoid.GRS80, -199.87, 74.79, 246.62));
153        datums.put("hermannskogel", new SevenParameterDatum(
154                "Hermannskogel", "hermannskogel",
155                Ellipsoid.Bessel1841, 577.326, 90.129, 463.919, 5.137, 1.474, 5.297, 2.4232));
156        datums.put("ire65", new SevenParameterDatum(
157                "Ireland 1965", "ire65",
158                Ellipsoid.AiryMod, 482.530, -130.596, 564.557, -1.042, -0.214, -0.631, 8.15));
159        datums.put("nzgd49", new SevenParameterDatum(
160                "New Zealand Geodetic Datum 1949", "nzgd49",
161                Ellipsoid.Hayford, 59.47, -5.04, 187.44, 0.47, -0.1, 1.024, -4.5993));
162        datums.put("OSGB36", new SevenParameterDatum(
163                "Airy 1830", "OSGB36",
164                Ellipsoid.Airy, 446.448, -125.157, 542.060, 0.1502, 0.2470, 0.8421, -20.4894));
165        datums.put("potsdam", new SevenParameterDatum(
166                "Potsdam Rauenberg 1950 DHDN", "potsdam",
167                Ellipsoid.Bessel1841, 598.1, 73.7, 418.2, 0.202, 0.045, -2.455, 6.7));
168
169        try {
170            inits = new LinkedHashMap<>();
171            for (ProjectionDefinition pd : loadProjectionDefinitions("resource://data/projection/custom-epsg")) {
172                inits.put(pd.code, pd);
173                loadNadgrids(pd.definition);
174            }
175        } catch (IOException ex) {
176            throw new JosmRuntimeException(ex);
177        }
178        allCodes.addAll(inits.keySet());
179    }
180
181    private Projections() {
182        // Hide default constructor for utils classes
183    }
184
185    private static void loadNadgrids(String definition) {
186        final String key = CustomProjection.Param.nadgrids.key;
187        if (definition.contains(key)) {
188            try {
189                String nadgridsId = CustomProjection.parseParameterList(definition, true).get(key);
190                if (nadgridsId.startsWith("@")) {
191                    nadgridsId = nadgridsId.substring(1);
192                }
193                if (!"null".equals(nadgridsId) && !nadgrids.containsKey(nadgridsId)) {
194                    nadgrids.put(nadgridsId, new NTV2GridShiftFileWrapper(nadgridsId));
195                }
196            } catch (ProjectionConfigurationException e) {
197                Logging.trace(e);
198            }
199        }
200    }
201
202    /**
203     * Plugins can register additional base projections.
204     *
205     * @param id The "official" PROJ.4 id. In case the projection is not supported
206     * by PROJ.4, use some prefix, e.g. josm:myproj or gdal:otherproj.
207     * @param fac The base projection factory.
208     * @param origin Multiple plugins may implement the same base projection.
209     * Provide plugin name or similar string, so it be differentiated.
210     */
211    public static void registerBaseProjection(String id, ProjFactory fac, String origin) {
212        projs.put(id, fac);
213    }
214
215    /**
216     * Plugins can register additional base projections.
217     *
218     * @param id The "official" PROJ.4 id. In case the projection is not supported
219     * by PROJ.4, use some prefix, e.g. josm:myproj or gdal:otherproj.
220     * @param projClass The base projection class.
221     * @param origin Multiple plugins may implement the same base projection.
222     * Provide plugin name or similar string, so it be differentiated.
223     */
224    public static void registerBaseProjection(String id, Class<? extends Proj> projClass, String origin) {
225        registerBaseProjection(id, new ClassProjFactory(projClass), origin);
226    }
227
228    /**
229     * Register a projection supplier, that is, a factory class for projections.
230     * @param code the code of the projection that will be returned
231     * @param supplier a supplier to return a projection with given code
232     * @since 12786
233     */
234    public static void registerProjectionSupplier(String code, Supplier<Projection> supplier) {
235        projectionSuppliersByCode.put(code, supplier);
236        allCodes.add(code);
237    }
238
239    /**
240     * Get a base projection by id.
241     *
242     * @param id the id, for example "lonlat" or "tmerc"
243     * @return the corresponding base projection if the id is known, null otherwise
244     */
245    public static Proj getBaseProjection(String id) {
246        ProjFactory fac = projs.get(id);
247        if (fac == null) return null;
248        return fac.createInstance();
249    }
250
251    /**
252     * Get an ellipsoid by id.
253     *
254     * @param id the id, for example "bessel" or "WGS84"
255     * @return the corresponding ellipsoid if the id is known, null otherwise
256     */
257    public static Ellipsoid getEllipsoid(String id) {
258        return ellipsoids.get(id);
259    }
260
261    /**
262     * Get a geodetic datum by id.
263     *
264     * @param id the id, for example "potsdam" or "WGS84"
265     * @return the corresponding datum if the id is known, null otherwise
266     */
267    public static Datum getDatum(String id) {
268        return datums.get(id);
269    }
270
271    /**
272     * Get a NTV2 grid database by id.
273     * @param id the id
274     * @return the corresponding NTV2 grid if the id is known, null otherwise
275     */
276    public static NTV2GridShiftFileWrapper getNTV2Grid(String id) {
277        return nadgrids.get(id);
278    }
279
280    /**
281     * Get the projection definition string for the given code.
282     * @param code the code
283     * @return the string that can be processed by {@link CustomProjection}.
284     * Null, if the code isn't supported.
285     */
286    public static String getInit(String code) {
287        ProjectionDefinition pd = inits.get(code.toUpperCase(Locale.ENGLISH));
288        if (pd == null) return null;
289        return pd.definition;
290    }
291
292    /**
293     * Load projection definitions from file.
294     *
295     * @param path the path
296     * @return projection definitions
297     * @throws IOException in case of I/O error
298     */
299    public static List<ProjectionDefinition> loadProjectionDefinitions(String path) throws IOException {
300        try (
301            CachedFile cf = new CachedFile(path);
302            BufferedReader r = cf.getContentReader()
303        ) {
304            return loadProjectionDefinitions(r);
305        }
306    }
307
308    /**
309     * Load projection definitions from file.
310     *
311     * @param r the reader
312     * @return projection definitions
313     * @throws IOException in case of I/O error
314     */
315    public static List<ProjectionDefinition> loadProjectionDefinitions(BufferedReader r) throws IOException {
316        List<ProjectionDefinition> result = new ArrayList<>();
317        Pattern epsgPattern = Pattern.compile("<(\\d+)>(.*)<>");
318        String coor = "(-?\\d+\\.\\d+)";
319        Pattern areaPattern = Pattern.compile("# area: \\(lat: "+coor+", "+coor+"\\) - \\(lon: "+coor+", "+coor+"\\).*");
320        StringBuilder sb = new StringBuilder();
321        String bounds = null;
322        String line;
323        while ((line = r.readLine()) != null) {
324            line = line.trim();
325            if (!line.isEmpty() && !line.startsWith("##")) {
326                if (!line.startsWith("#")) {
327                    Matcher m = epsgPattern.matcher(line);
328                    if (m.matches()) {
329                        String code = "EPSG:" + m.group(1);
330                        String definition = m.group(2).trim();
331                        if (!definition.contains("+bounds=") && bounds != null) {
332                            definition += bounds;
333                        }
334                        result.add(new ProjectionDefinition(code, sb.toString(), definition));
335                    } else {
336                        Logging.warn("Failed to parse line from the EPSG projection definition: "+line);
337                    }
338                    sb.setLength(0);
339                    bounds = null;
340                } else if (line.startsWith("# area: ")) {
341                    Matcher m = areaPattern.matcher(line);
342                    if (m.matches()) {
343                        bounds = " +bounds=" + String.join(",", m.group(3), m.group(1), m.group(4), m.group(2));
344                    }
345                } else {
346                    String s = line.substring(1).trim();
347                    if (sb.length() == 0) {
348                        sb.append(s);
349                    } else {
350                        sb.append('(').append(s).append(')');
351                    }
352                }
353            }
354        }
355        return result;
356    }
357
358    /**
359     * Get a projection by code.
360     * @param code the code, e.g. "EPSG:2026"
361     * @return the corresponding projection, if the code is known, null otherwise
362     */
363    public static Projection getProjectionByCode(String code) {
364        return code != null ? projectionsByCodeCache.computeIfAbsent(code, Projections::computeProjectionByCode) : null;
365    }
366
367    private static Projection computeProjectionByCode(String code) {
368        Projection proj = null;
369        ProjectionDefinition pd = inits.get(code);
370        if (pd != null) {
371            CustomProjection cproj = new CustomProjection(pd.name, code, null);
372            try {
373                cproj.update(pd.definition);
374            } catch (ProjectionConfigurationException ex) {
375                throw new JosmRuntimeException("Error loading " + code, ex);
376            }
377            proj = cproj;
378        }
379        if (proj == null) {
380            Supplier<Projection> ps = projectionSuppliersByCode.get(code);
381            if (ps != null) {
382                proj = ps.get();
383            }
384        }
385        return proj;
386    }
387
388    /**
389     * Get a list of all supported projection codes.
390     *
391     * @return all supported projection codes
392     * @see #getProjectionByCode(java.lang.String)
393     */
394    public static Collection<String> getAllProjectionCodes() {
395        return Collections.unmodifiableCollection(allCodes);
396    }
397
398    /**
399     * Get a list of ids of all registered base projections.
400     *
401     * @return all registered base projection ids
402     * @see #getBaseProjection(java.lang.String)
403     */
404    public static Collection<String> getAllBaseProjectionIds() {
405        return projs.keySet();
406    }
407
408    private static String listKeys(Map<String, ?> map) {
409        return map.keySet().stream()
410                .sorted()
411                .collect(Collectors.joining(", "));
412    }
413
414    /**
415     * Replies the list of projections as string (comma separated).
416     * @return the list of projections as string (comma separated)
417     * @since 8533
418     */
419    public static String listProjs() {
420        return listKeys(projs);
421    }
422
423    /**
424     * Replies the list of ellipsoids as string (comma separated).
425     * @return the list of ellipsoids as string (comma separated)
426     * @since 8533
427     */
428    public static String listEllipsoids() {
429        return listKeys(ellipsoids);
430    }
431
432    /**
433     * Replies the list of datums as string (comma separated).
434     * @return the list of datums as string (comma separated)
435     * @since 8533
436     */
437    public static String listDatums() {
438        return listKeys(datums);
439    }
440
441    /**
442     * Replies the list of nadgrids as string (comma separated).
443     * @return the list of nadgrids as string (comma separated)
444     * @since 8533
445     */
446    public static String listNadgrids() {
447        return listKeys(nadgrids);
448    }
449}