001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import java.io.File;
005import java.io.IOException;
006import java.io.InputStream;
007import java.io.OutputStreamWriter;
008import java.io.PrintWriter;
009import java.io.Writer;
010import java.nio.charset.StandardCharsets;
011import java.nio.file.Files;
012import java.nio.file.InvalidPathException;
013import java.nio.file.Paths;
014import java.util.ArrayList;
015import java.util.Collection;
016import java.util.Collections;
017import java.util.List;
018import java.util.Set;
019
020import org.openstreetmap.josm.actions.JoinAreasAction;
021import org.openstreetmap.josm.actions.JoinAreasAction.JoinAreasResult;
022import org.openstreetmap.josm.actions.JoinAreasAction.Multipolygon;
023import org.openstreetmap.josm.command.PurgeCommand;
024import org.openstreetmap.josm.data.coor.LatLon;
025import org.openstreetmap.josm.data.osm.DataSet;
026import org.openstreetmap.josm.data.osm.DownloadPolicy;
027import org.openstreetmap.josm.data.osm.OsmPrimitive;
028import org.openstreetmap.josm.data.osm.Relation;
029import org.openstreetmap.josm.data.osm.RelationMember;
030import org.openstreetmap.josm.data.osm.UploadPolicy;
031import org.openstreetmap.josm.data.osm.Way;
032import org.openstreetmap.josm.io.IllegalDataException;
033import org.openstreetmap.josm.io.OsmReader;
034import org.openstreetmap.josm.io.OsmWriter;
035import org.openstreetmap.josm.io.OsmWriterFactory;
036import org.openstreetmap.josm.spi.preferences.Config;
037
038/**
039 * Look up, if there is right- or left-hand traffic at a certain place.
040 */
041public final class RightAndLefthandTraffic {
042
043    private static final String DRIVING_SIDE = "driving_side";
044    private static final String LEFT = "left";
045    private static final String RIGHT = "right";
046
047    private static volatile GeoPropertyIndex<Boolean> rlCache;
048
049    private RightAndLefthandTraffic() {
050        // Hide implicit public constructor for utility classes
051    }
052
053    /**
054     * Check if there is right-hand traffic at a certain location.
055     *
056     * @param ll the coordinates of the point
057     * @return true if there is right-hand traffic, false if there is left-hand traffic
058     */
059    public static synchronized boolean isRightHandTraffic(LatLon ll) {
060        return !rlCache.get(ll);
061    }
062
063    /**
064     * Initializes Right and lefthand traffic data.
065     * TODO: Synchronization can be refined inside the {@link GeoPropertyIndex} as most look-ups are read-only.
066     */
067    public static synchronized void initialize() {
068        Collection<Way> optimizedWays = loadOptimizedBoundaries();
069        if (optimizedWays.isEmpty()) {
070            optimizedWays = computeOptimizedBoundaries();
071            try {
072                saveOptimizedBoundaries(optimizedWays);
073            } catch (IOException | SecurityException e) {
074                Logging.log(Logging.LEVEL_ERROR, "Unable to save optimized boundaries", e);
075            }
076        }
077        rlCache = new GeoPropertyIndex<>(new DefaultGeoProperty(optimizedWays), 24);
078    }
079
080    private static Collection<Way> computeOptimizedBoundaries() {
081        Collection<Way> ways = new ArrayList<>();
082        Collection<OsmPrimitive> toPurge = new ArrayList<>();
083        // Find all outer ways of left-driving countries. Many of them are adjacent (African and Asian states)
084        DataSet data = Territories.getDataSet();
085        Collection<Relation> allRelations = data.getRelations();
086        Collection<Way> allWays = data.getWays();
087        for (Way w : allWays) {
088            if (LEFT.equals(w.get(DRIVING_SIDE))) {
089                addWayIfNotInner(ways, w);
090            }
091        }
092        for (Relation r : allRelations) {
093            if (r.isMultipolygon() && LEFT.equals(r.get(DRIVING_SIDE))) {
094                for (RelationMember rm : r.getMembers()) {
095                    if (rm.isWay() && "outer".equals(rm.getRole()) && !RIGHT.equals(rm.getMember().get(DRIVING_SIDE))) {
096                        addWayIfNotInner(ways, (Way) rm.getMember());
097                    }
098                }
099            }
100        }
101        toPurge.addAll(allRelations);
102        toPurge.addAll(allWays);
103        toPurge.removeAll(ways);
104        // Remove ways from parent relations for following optimizations
105        for (Relation r : OsmPrimitive.getParentRelations(ways)) {
106            r.setMembers(null);
107        }
108        // Remove all tags to avoid any conflict
109        for (Way w : ways) {
110            w.removeAll();
111        }
112        // Purge all other ways and relations so dataset only contains lefthand traffic data
113        PurgeCommand.build(toPurge, null).executeCommand();
114        // Combine adjacent countries into a single polygon
115        Collection<Way> optimizedWays = new ArrayList<>();
116        List<Multipolygon> areas = JoinAreasAction.collectMultipolygons(ways);
117        if (areas != null) {
118            try {
119                JoinAreasResult result = new JoinAreasAction(false).joinAreas(areas);
120                if (result.hasChanges()) {
121                    for (Multipolygon mp : result.getPolygons()) {
122                        optimizedWays.add(mp.getOuterWay());
123                    }
124                }
125            } catch (UserCancelException ex) {
126                Logging.warn(ex);
127            } catch (JosmRuntimeException ex) {
128                // Workaround to #10511 / #14185. To remove when #10511 is solved
129                Logging.error(ex);
130            }
131        }
132        if (optimizedWays.isEmpty()) {
133            // Problem: don't optimize
134            Logging.warn("Unable to join left-driving countries polygons");
135            optimizedWays.addAll(ways);
136        }
137        return optimizedWays;
138    }
139
140    /**
141     * Adds w to ways, except if it is an inner way of another lefthand driving multipolygon,
142     * as Lesotho in South Africa and Cyprus village in British Cyprus base.
143     * @param ways ways
144     * @param w way
145     */
146    private static void addWayIfNotInner(Collection<Way> ways, Way w) {
147        Set<Way> s = Collections.singleton(w);
148        for (Relation r : OsmPrimitive.getParentRelations(s)) {
149            if (r.isMultipolygon() && LEFT.equals(r.get(DRIVING_SIDE)) &&
150                "inner".equals(r.getMembersFor(s).iterator().next().getRole())) {
151                if (Logging.isDebugEnabled()) {
152                    Logging.debug("Skipping {0} because inner part of {1}", w.get("name:en"), r.get("name:en"));
153                }
154                return;
155            }
156        }
157        ways.add(w);
158    }
159
160    private static void saveOptimizedBoundaries(Collection<Way> optimizedWays) throws IOException {
161        DataSet ds = optimizedWays.iterator().next().getDataSet();
162        File file = new File(Config.getDirs().getCacheDirectory(true), "left-right-hand-traffic.osm");
163        try (Writer writer = new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8);
164             OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, ds.getVersion())
165            ) {
166            w.header(DownloadPolicy.NORMAL, UploadPolicy.DISCOURAGED);
167            w.writeContent(ds);
168            w.footer();
169        }
170    }
171
172    private static Collection<Way> loadOptimizedBoundaries() {
173        try (InputStream is = Files.newInputStream(Paths.get(
174                Config.getDirs().getCacheDirectory(false).getPath(), "left-right-hand-traffic.osm"))) {
175           return OsmReader.parseDataSet(is, null).getWays();
176        } catch (IllegalDataException | IOException | InvalidPathException | SecurityException ex) {
177            Logging.trace(ex);
178            return Collections.emptyList();
179        }
180    }
181}