source: osm/applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGBuilding.java@ 17528

Last change on this file since 17528 was 17528, checked in by guggis, 15 years ago

Updating to JOSM r2082

File size: 10.8 KB
Line 
1package cadastre_fr;
2
3import static org.openstreetmap.josm.tools.I18n.tr;
4
5import java.io.BufferedOutputStream;
6import java.io.BufferedReader;
7import java.io.File;
8import java.io.FileOutputStream;
9import java.io.IOException;
10import java.io.InputStream;
11import java.io.InputStreamReader;
12import java.net.HttpURLConnection;
13import java.net.MalformedURLException;
14import java.net.URL;
15import java.util.ArrayList;
16import java.util.Collection;
17import java.util.LinkedList;
18
19import javax.swing.JOptionPane;
20
21import org.openstreetmap.josm.Main;
22import org.openstreetmap.josm.command.AddCommand;
23import org.openstreetmap.josm.command.Command;
24import org.openstreetmap.josm.command.SequenceCommand;
25import org.openstreetmap.josm.data.coor.EastNorth;
26import org.openstreetmap.josm.data.osm.DataSet;
27import org.openstreetmap.josm.data.osm.Node;
28import org.openstreetmap.josm.data.osm.Way;
29import org.openstreetmap.josm.gui.MapView;
30import org.openstreetmap.josm.gui.PleaseWaitRunnable;
31import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
32import org.openstreetmap.josm.io.OsmTransferException;
33import org.openstreetmap.josm.io.ProgressInputStream;
34
35public class DownloadSVGBuilding extends PleaseWaitRunnable {
36
37 private WMSLayer wmsLayer;
38 private CadastreGrabber grabber = CadastrePlugin.cadastreGrabber;
39 private CadastreInterface wmsInterface;
40 private String svg = null;
41 private static EastNorthBound currentView = null;
42 private EastNorthBound viewBox = null;
43
44 public DownloadSVGBuilding(WMSLayer wmsLayer) {
45 super(tr("Downloading {0}", wmsLayer.getName()));
46
47 this.wmsLayer = wmsLayer;
48 this.wmsInterface = grabber.getWmsInterface();
49 }
50
51 @Override
52 public void realRun() throws IOException, OsmTransferException {
53 progressMonitor.indeterminateSubTask(tr("Contacting WMS Server..."));
54 try {
55 if (wmsInterface.retrieveInterface(wmsLayer)) {
56 svg = grabBoundary(currentView);
57 if (svg == null)
58 return;
59 getViewBox(svg);
60 if (viewBox == null)
61 return;
62 createBuildings(svg);
63 }
64 } catch (DuplicateLayerException e) {
65 System.err.println("removed a duplicated layer");
66 }
67 }
68
69 @Override
70 protected void cancel() {
71 grabber.getWmsInterface().cancel();
72 }
73
74 @Override
75 protected void finish() {
76 }
77
78 private boolean getViewBox(String svg) {
79 double[] box = new SVGParser().getViewBox(svg);
80 if (box != null) {
81 viewBox = new EastNorthBound(new EastNorth(box[0], box[1]),
82 new EastNorth(box[0]+box[2], box[1]+box[3]));
83 return true;
84 }
85 System.out.println("Unable to parse SVG data (viewBox)");
86 return false;
87 }
88
89 /**
90 * The svg contains more than one commune boundary defined by path elements. So detect
91 * which path element is the best fitting to the viewBox and convert it to OSM objects
92 */
93 private void createBuildings(String svg) {
94 String[] SVGpaths = new SVGParser().getClosedPaths(svg);
95 ArrayList<ArrayList<EastNorth>> eastNorths = new ArrayList<ArrayList<EastNorth>>();
96
97 // convert SVG nodes to eastNorth coordinates
98 for (int i=0; i< SVGpaths.length; i++) {
99 ArrayList<EastNorth> eastNorth = new ArrayList<EastNorth>();
100 createNodes(SVGpaths[i], eastNorth);
101 if (eastNorth.size() > 2)
102 eastNorths.add(eastNorth);
103 }
104
105 // create nodes and closed ways
106 DataSet svgDataSet = new DataSet();
107 for (ArrayList<EastNorth> path : eastNorths) {
108 Way wayToAdd = new Way();
109 for (EastNorth eastNorth : path) {
110 Node nodeToAdd = new Node(Main.proj.eastNorth2latlon(eastNorth));
111 // check if new node is not already created by another new path
112 Node nearestNewNode = checkNearestNode(nodeToAdd, svgDataSet.nodes);
113 if (nearestNewNode == nodeToAdd)
114 svgDataSet.addPrimitive(nearestNewNode);
115 wayToAdd.addNode(nearestNewNode); // either a new node or an existing one
116 }
117 wayToAdd.addNode(wayToAdd.getNode(0)); // close the way
118 svgDataSet.addPrimitive(wayToAdd);
119 }
120
121 // TODO remove small boxes (4 nodes with less than 1 meter distance)
122 /*
123 for (Way w : svgDataSet.ways)
124 if (w.nodes.size() == 5)
125 for (int i = 0; i < w.nodes.size()-2; i++) {
126 if (w.nodes.get(i).eastNorth.distance(w.nodes.get(i+1).eastNorth))
127 }*/
128
129 // simplify ways and check if we can reuse existing OSM nodes
130 for (Way wayToAdd : svgDataSet.ways)
131 new SimplifyWay().simplifyWay(wayToAdd, svgDataSet, 0.5);
132 // check if the new way or its nodes is already in OSM layer
133 for (Node n : svgDataSet.nodes) {
134 Node nearestNewNode = checkNearestNode(n, Main.main.getCurrentDataSet().nodes);
135 if (nearestNewNode != n) {
136 // replace the SVG node by the OSM node
137 for (Way w : svgDataSet.ways) {
138 int replaced = 0;
139 for (Node node : w.getNodes())
140 if (node == n) {
141 node = nearestNewNode;
142 replaced++;
143 }
144 if (w.getNodesCount() == replaced)
145 w.setDeleted(true);
146 }
147 n.setDeleted(true);
148 }
149
150 }
151
152 Collection<Command> cmds = new LinkedList<Command>();
153 for (Node node : svgDataSet.nodes)
154 if (!node.isDeleted())
155 cmds.add(new AddCommand(node));
156 for (Way way : svgDataSet.ways)
157 if (!way.isDeleted())
158 cmds.add(new AddCommand(way));
159 Main.main.undoRedo.add(new SequenceCommand(tr("Create buildings"), cmds));
160 Main.map.repaint();
161 }
162
163 private void createNodes(String SVGpath, ArrayList<EastNorth> eastNorth) {
164 // looks like "M981283.38 368690.15l143.81 72.46 155.86 ..."
165 String[] coor = SVGpath.split("[MlZ ]"); //coor[1] is x, coor[2] is y
166 double dx = Double.parseDouble(coor[1]);
167 double dy = Double.parseDouble(coor[2]);
168 for (int i=3; i<coor.length; i+=2){
169 if (coor[i].equals("")) {
170 eastNorth.clear(); // some paths are just artifacts
171 return;
172 }
173 double east = dx+=Double.parseDouble(coor[i]);
174 double north = dy+=Double.parseDouble(coor[i+1]);
175 eastNorth.add(new EastNorth(east,north));
176 }
177 // flip the image (svg using a reversed Y coordinate system)
178 double pivot = viewBox.min.getY() + (viewBox.max.getY() - viewBox.min.getY()) / 2;
179 for (EastNorth en : eastNorth) {
180 en.setLocation(en.east(), 2 * pivot - en.north());
181 }
182 return;
183 }
184
185 /**
186 * Check if node can be reused.
187 * @param nodeToAdd the candidate as new node
188 * @return the already existing node (if any), otherwise the new node candidate.
189 */
190 private Node checkNearestNode(Node nodeToAdd, Collection<Node> nodes) {
191 double epsilon = 0.05; // smallest distance considering duplicate node
192 for (Node n : nodes) {
193 if (!n.isDeleted() && !n.incomplete) {
194 double dist = n.getEastNorth().distance(nodeToAdd.getEastNorth());
195 if (dist < epsilon) {
196 return n;
197 }
198 }
199 }
200 return nodeToAdd;
201 }
202
203 private String grabBoundary(EastNorthBound bbox) throws IOException, OsmTransferException {
204 try {
205 URL url = null;
206 url = getURLsvg(bbox);
207 return grabSVG(url);
208 } catch (MalformedURLException e) {
209 throw (IOException) new IOException(tr("CadastreGrabber: Illegal url.")).initCause(e);
210 }
211 }
212
213 private URL getURLsvg(EastNorthBound bbox) throws MalformedURLException {
214 String str = new String(wmsInterface.baseURL+"/scpc/wms?version=1.1&request=GetMap");
215 str += "&layers=";
216 str += "CDIF:LS2";
217 str += "&format=image/svg";
218 str += "&bbox="+bbox.min.east()+",";
219 str += bbox.min.north() + ",";
220 str += bbox.max.east() + ",";
221 str += bbox.max.north();
222 str += "&width=800&height=600"; // maximum allowed by wms server
223 str += "&exception=application/vnd.ogc.se_inimage";
224 str += "&styles=";
225 str += "LS2_90";
226 System.out.println("URL="+str);
227 return new URL(str.replace(" ", "%20"));
228 }
229
230 private String grabSVG(URL url) throws IOException, OsmTransferException {
231 wmsInterface.urlConn = (HttpURLConnection)url.openConnection();
232 wmsInterface.urlConn.setRequestMethod("GET");
233 wmsInterface.setCookie();
234 InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE);
235 File file = new File(CadastrePlugin.cacheDir + "building.svg");
236 String svg = new String();
237 try {
238 if (file.exists())
239 file.delete();
240 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
241 InputStreamReader isr =new InputStreamReader(is);
242 BufferedReader br = new BufferedReader(isr);
243 String line="";
244 while ( null!=(line=br.readLine())){
245 line += "\n";
246 bos.write(line.getBytes());
247 svg += line;
248 }
249 bos.close();
250 } catch (IOException e) {
251 e.printStackTrace(System.out);
252 }
253 is.close();
254 return svg;
255 }
256
257 public static void download(WMSLayer wmsLayer) {
258 MapView mv = Main.map.mapView;
259 currentView = new EastNorthBound(mv.getEastNorth(0, mv.getHeight()),
260 mv.getEastNorth(mv.getWidth(), 0));
261 if ((currentView.max.east() - currentView.min.east()) > 1000 ||
262 (currentView.max.north() - currentView.min.north() > 1000)) {
263 JOptionPane.showMessageDialog(Main.parent,
264 tr("To avoid cadastre WMS overload,\nbuilding import size is limited to 1 km2 max."));
265 return;
266 }
267 if (CadastrePlugin.autoSourcing == false) {
268 JOptionPane.showMessageDialog(Main.parent,
269 tr("Please, enable auto-sourcing and check cadastre millesime."));
270 return;
271 }
272 Main.worker.execute(new DownloadSVGBuilding(wmsLayer));
273 }
274
275}
Note: See TracBrowser for help on using the repository browser.