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