SVGMap.java 13.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
 * Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
 *
 * This file is part of PeerfactSim.KOM.
 * 
 * PeerfactSim.KOM is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 * 
 * PeerfactSim.KOM is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with PeerfactSim.KOM.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package de.tud.kom.p2psim.impl.util.geo.maps.svg;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.PathIterator;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.JComponent;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.batik.ext.awt.geom.ExtendedGeneralPath;
import org.apache.batik.parser.AWTPathProducer;
import org.apache.batik.parser.PathParser;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
Julian Zobel's avatar
Julian Zobel committed
46
47
import org.locationtech.jts.algorithm.LineIntersector;
import org.locationtech.jts.algorithm.RobustLineIntersector;
48
49
50

import de.tud.kom.p2psim.api.scenario.ConfigurationException;
import de.tud.kom.p2psim.impl.topology.obstacles.PolygonObstacle;
51
import de.tud.kom.p2psim.impl.topology.util.PositionVector;
52
import de.tud.kom.p2psim.impl.topology.views.VisualizationTopologyView.VisualizationInjector;
Julian Zobel's avatar
Julian Zobel committed
53
import de.tud.kom.p2psim.impl.topology.waypoints.graph.PathEdge;
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import de.tud.kom.p2psim.impl.topology.waypoints.graph.Waypoint;
import de.tud.kom.p2psim.impl.topology.waypoints.graph.WeakWaypoint;
import de.tud.kom.p2psim.impl.util.geo.maps.AbstractMap;

/**
 * This map generates waypoints and obstacles based on a given SVG file.
 * 
 * The SVG file must adhere to the following conventions: - Everything must be
 * contained in a rect element named "map" (id) - Obstacles are implemented
 * using rect or path elements. - Their id must start with "obstacle" - Ways for
 * the movement of nodes are implemented using path elements. - Their id must
 * start with "way"
 * 
 * The size of the map element will be used to determine the map size and to
 * scale the map to the configured dimensions. All elements besides rect and
 * path elements with the previously named ids are ignored.
 * 
 * Note: The SVGMap will not verify if the obstacles or ways are inside of the
 * map rect. All rects or paths with the correct ids will be loaded regardless
 * of their positioning.
 * 
 * @author Fabio Zöllner
 * @version 1.0, 22.10.2012
 */
public class SVGMap extends AbstractMap {

	private Map<PositionVector, Waypoint> waypointCache = Maps.newHashMap();

	@Override
	protected void doLoadMap() {
		File osmFile = new File(getFilename());

		if (!osmFile.exists())
			throw new ConfigurationException("Couldn't find SVG file: "
					+ getFilename());

		try {

			SAXParserFactory parserFactory = SAXParserFactory.newInstance();
			SAXParser parser;
			parser = parserFactory.newSAXParser();

			parser.parse(new File(filename), new SVGMapHandler());

			postProcessing();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void postProcessing() {
		waypointCache.clear();

		resolveIntersections();
	}

	private void resolveIntersections() {
		List<PositionVector> intersections = Lists.newLinkedList();

Julian Zobel's avatar
Julian Zobel committed
114
115
		List<PathEdge> worklist = Lists.newLinkedList(getPaths());
		Iterator<PathEdge> iter = concurrentIterator(worklist);
116
117

		while (iter.hasNext()) {
Julian Zobel's avatar
Julian Zobel committed
118
			PathEdge path = iter.next();
119

Julian Zobel's avatar
Julian Zobel committed
120
			Iterator<PathEdge> compareIter = concurrentIterator(worklist);
121
			while (compareIter.hasNext()) {
Julian Zobel's avatar
Julian Zobel committed
122
				PathEdge comparePath = compareIter.next();
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

				// Prevent intersection comparison for the same path and
				// connected paths
				if (path.equals(comparePath))
					continue;
				if (path.getSource().getPosition()
						.equals(comparePath.getSource().getPosition()))
					continue;
				if (path.getSource().getPosition()
						.equals(comparePath.getTarget().getPosition()))
					continue;
				if (path.getTarget().getPosition()
						.equals(comparePath.getSource().getPosition()))
					continue;
				if (path.getTarget().getPosition()
						.equals(comparePath.getTarget().getPosition()))
					continue;

				PositionVector intersection = intersects(path, comparePath);
				if (intersection != null) {
Julian Zobel's avatar
Julian Zobel committed
143
144
					PathEdge[] splitPath1 = splitPath(path, intersection);
					PathEdge[] splitPath2 = splitPath(comparePath, intersection);
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224

					// Prevent the creation of loops
					if (splitPath1[0].getSource().equals(
							splitPath1[0].getTarget()))
						continue;
					if (splitPath1[1].getSource().equals(
							splitPath1[1].getTarget()))
						continue;
					if (splitPath2[0].getSource().equals(
							splitPath2[0].getTarget()))
						continue;
					if (splitPath2[1].getSource().equals(
							splitPath2[1].getTarget()))
						continue;

					worklist.add(splitPath1[0]);
					worklist.add(splitPath1[1]);
					worklist.add(splitPath2[0]);
					worklist.add(splitPath2[1]);

					intersections.add(intersection);

					compareIter.remove();
					iter.remove();

					break;
				}
			}
		}

		getPaths().clear();
		getPaths().addAll(worklist);

		VisualizationInjector.injectComponent("New intersections", 1,
				new MarkPositions(intersections, this));
	}

	public <E> Iterator<E> concurrentIterator(final List<E> list) {
		return new Iterator<E>() {
			int index = -1;

			@Override
			public boolean hasNext() {
				System.err.println("Checking if index " + (index + 1)
						+ " is in bounds");
				return index + 1 < list.size();
			}

			@Override
			public E next() {
				index++;

				if (index < list.size()) {
					return list.get(index);
				} else {
					throw new IndexOutOfBoundsException(
							"List has "
									+ list.size()
									+ " entries at the moment. Couldn't retrieve entry at position "
									+ index);
				}
			}

			@Override
			public void remove() {
				if (index < list.size()) {
					list.remove(index);
					index--;
				} else {
					throw new IndexOutOfBoundsException(
							"List has "
									+ list.size()
									+ " entries at the moment. Couldn't retrieve entry at position "
									+ index);
				}
			}

		};
	}

Julian Zobel's avatar
Julian Zobel committed
225
226
	private PathEdge[] splitPath(PathEdge path, PositionVector intersectionPoint) {
		PathEdge[] paths = new PathEdge[2];
227
228
229
230
231

		Waypoint wp1 = path.getSource();
		Waypoint wp2 = path.getTarget();
		Waypoint iwp = getWaypoint(intersectionPoint);

Julian Zobel's avatar
Julian Zobel committed
232
233
		paths[0] = new PathEdge(wp1, iwp);
		paths[1] = new PathEdge(wp2, iwp);
234
235
236
237

		return paths;
	}

Julian Zobel's avatar
Julian Zobel committed
238
	private PositionVector intersects(PathEdge path1, PathEdge path2) {
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
		LineIntersector inter = new RobustLineIntersector();

		inter.computeIntersection(path1.getSource().getPosition()
				.asCoordinate(),
				path1.getTarget().getPosition().asCoordinate(), path2
						.getSource().getPosition().asCoordinate(), path2
						.getTarget().getPosition().asCoordinate());

		if (inter.getIntersectionNum() == 0) {
			return null;
		}

		return new PositionVector(inter.getIntersection(0).x,
				inter.getIntersection(0).y);
	}

	private class SVGMapHandler extends DefaultHandler {
		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if (checkId(attrs, "map")) {
				int x = (int) Double.parseDouble(attrs.getValue("x"));
				int y = (int) Double.parseDouble(attrs.getValue("y"));
				int width = (int) Double.parseDouble(attrs.getValue("width"));
				int height = (int) Double.parseDouble(attrs.getValue("height"));

				setMinPosition(new PositionVector(x, y));
				setMaxPosition(new PositionVector(x + width, y + height));

			} else if (checkId(attrs, "obstacle")) {
				if (qName.equals("rect")) {
					int x = (int) Double.parseDouble(attrs.getValue("x"));
					int y = (int) Double.parseDouble(attrs.getValue("y"));
					int width = (int) Double.parseDouble(attrs
							.getValue("width"));
					int height = (int) Double.parseDouble(attrs
							.getValue("height"));

					addObstacle(new PolygonObstacle(Lists.newArrayList(
							pos(x, y), pos(x + width, y),
							pos(x + width, y + height), pos(x, y + height))));
				} else if (qName.equals("path")) {
					List<PositionVector> positions = parseObstaclePositions(attrs
							.getValue("d"));
					addObstacle(new PolygonObstacle(positions));
				}
				// TODO: Add path
			} else if (checkId(attrs, "way")) {
				parseWay(attrs.getValue("d"));

			}
		}
	}

	private Waypoint getWaypoint(PositionVector pos) {
		Waypoint wp = waypointCache.get(pos);
		if (wp == null) {
			wp = new WeakWaypoint(pos);
			waypointCache.put(pos, wp);
		}
		return wp;
	}

	void parseWay(String d) {
		PathParser parser = new PathParser();

		AWTPathProducer producer = new AWTPathProducer();
		parser.setPathHandler(producer);

		parser.parse(d);

		ExtendedGeneralPath path = (ExtendedGeneralPath) producer.getShape();

		PathIterator iter = path.getPathIterator(null, 1.0);

		Waypoint lastWaypoint = null;
		Waypoint lastMoveTo = null;

		double[] coords = new double[6];
		while (!iter.isDone()) {
			int type = iter.currentSegment(coords);

			if (type == iter.SEG_MOVETO) {
				lastWaypoint = getWaypoint(new PositionVector((int) coords[0],
						(int) coords[1]));
				lastMoveTo = lastWaypoint;
				System.err.println("Moved to " + lastMoveTo);
			} else if (type == iter.SEG_LINETO) {
				Waypoint targetWaypoint = getWaypoint(new PositionVector(
						(int) coords[0], (int) coords[1]));
				createPath(lastWaypoint, targetWaypoint);
				lastWaypoint = targetWaypoint;
				System.err.println("Created a line to " + targetWaypoint);
			} else if (type == iter.SEG_CLOSE) {
				createPath(lastWaypoint, lastMoveTo);
				lastWaypoint = lastMoveTo;
				System.err.println("Closed a line to " + lastMoveTo);
			}

			iter.next();
		}
	}

	@Override
	public void createPath(Waypoint wp1, Waypoint wp2) {
		if (wp1.equals(wp2))
			return; // Prevent loops

		super.createPath(wp1, wp2);
	}

	List<PositionVector> parseObstaclePositions(String d) {
		PathParser parser = new PathParser();

		AWTPathProducer producer = new AWTPathProducer();
		parser.setPathHandler(producer);

		parser.parse(d);

		ExtendedGeneralPath path = (ExtendedGeneralPath) producer.getShape();

		PathIterator iter = path.getPathIterator(null, 1.0);

		PositionVector firstPosition = null;

		List<PositionVector> positions = Lists.newLinkedList();
		double[] coords = new double[6];
		while (!iter.isDone()) {
			int type = iter.currentSegment(coords);

			PositionVector newPosition = new PositionVector((int) coords[0],
					(int) coords[1]);

			if (firstPosition == null) {
				firstPosition = newPosition;
			}

			if (type == iter.SEG_MOVETO || type == iter.SEG_LINETO) {
				positions.add(newPosition);
			} else if (type == iter.SEG_CLOSE) {
				positions.add(firstPosition);
			} else {
				throw new ConfigurationException(
						"Cannot handle obstacles with a path more complex than a simple closed path. (e.g. using more than moveto, lineto or close commands)");
			}

			iter.next();
		}

		return positions;
	}

	boolean checkId(Attributes attrs, String value) {
		if (attrs.getValue("id") == null)
			return false;

		return attrs.getValue("id").startsWith(value);
	}

	private class MarkPositions extends JComponent {
		private List<PositionVector> positions;

		public MarkPositions(List<PositionVector> positions, SVGMap map) {
			super();

			this.positions = positions;

			setBounds(0, 0, VisualizationInjector.getWorldX(),
					VisualizationInjector.getWorldY());
			setOpaque(false);
			setVisible(true);
		}

		protected PositionVector toPixelCoords(PositionVector position,
				PositionVector pixelPerMeter) {
			PositionVector clonedPosition = position.clone();
			PositionVector relativePosition = clonedPosition
					.minus(getMinPosition());
			relativePosition.multiply(pixelPerMeter);

			return relativePosition;
		}

		@Override
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);

			Graphics2D g2 = (Graphics2D) g;

			g2.setFont(new Font("SansSerif", Font.PLAIN, 9));

			PositionVector lst = null;
			for (PositionVector p : positions) {
				PositionVector pos = p;

				if (ppm != null) {
					pos = toPixelCoords(p, ppm);
				}

				g2.setColor(Color.RED);
				g2.drawOval((int) pos.getX() - 10, (int) pos.getY() - 10, 20,
						20);

				g2.setColor(Color.BLACK);
				g2.drawLine((int) pos.getX() - 2, (int) pos.getY() - 2,
						(int) pos.getX() + 2, (int) pos.getY() + 2);
				g2.drawLine((int) pos.getX() - 2, (int) pos.getY() + 2,
						(int) pos.getX() + 2, (int) pos.getY() - 2);

				if (lst != null) {
					g2.setColor(Color.GREEN);
					g2.drawLine((int) lst.getX(), (int) lst.getY(),
							(int) pos.getX(), (int) pos.getY());
				}
				lst = pos;
			}
		}
	}
}