Debian Codegraph @

src/uk/me/parabola/util/Java2DConverter.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006, 2012.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 3 or
6 * version 2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 */
13 package uk.me.parabola.util;
14
15 import java.awt.Polygon;
16 import java.awt.Rectangle;
17 import java.awt.Shape;
18 import java.awt.geom.Area;
19 import java.awt.geom.Path2D;
20 import java.awt.geom.PathIterator;
21 import java.io.File;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.List;
25
26 import org.openstreetmap.osmosis.core.filter.common.PolygonFileReader;
27
28 import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
29 import uk.me.parabola.imgfmt.Utils;
30 import uk.me.parabola.imgfmt.app.Coord;
31 import uk.me.parabola.log.Logger;
32
33 /**
34 * This is a tool class that provides static methods to convert between mkgmap
35 * objects and Java2D objects. The Java2D objects provide some optimized polygon
36 * algorithms that are quite useful so that it makes sense to perform the
37 * conversion.
38 *
39 * @author WanMil
40 */
41 public class Java2DConverter {
42 private static final Logger log = Logger.getLogger(Java2DConverter.class);
43
44 /**
45 * Creates a Java2D {@link Area} object from the given mkgmap rectangular
46 * {@link uk.me.parabola.imgfmt.app.Area} object.
47 *
48 * @param bbox a rectangular bounding box
49 * @return the converted Java2D area
50 */
51 public static Area createBoundsArea(uk.me.parabola.imgfmt.app.Area bbox) {
52 return createArea(bbox.toCoords());
53 }
54
55 /**
56 * Converts the bounding box of a Java2D {@link Shape} object to an mkgmap
57 * {@link uk.me.parabola.imgfmt.app.Area} object.
58 *
59 * @param shape a Java2D Shape (Area, Path2D, ...)
60 * @return the bounding box
61 */
62 public static uk.me.parabola.imgfmt.app.Area createBbox(Shape shape) {
63 Rectangle areaBounds = shape.getBounds();
64 return new uk.me.parabola.imgfmt.app.Area(areaBounds.y,areaBounds.x,(int) areaBounds.getMaxY(),(int) areaBounds.getMaxX());
65 }
66
67
68 /**
69 * Creates a Java2D {@link Area} object from a polygon given as a list of
70 * {@link Coord} objects. This list should describe a closed polygon.
71 *
72 * @param polygonPoints a list of points that describe a closed polygon
73 * @return the converted Java2D area
74 */
75 public static Area createArea(List<Coord> polygonPoints) {
76 return new Area(createPath2D(polygonPoints));
77 }
78
79 /**
80 * Creates a Java2D {@link Path2D} object from a polygon given as a list of
81 * {@link Coord} objects. This list should describe a closed polygon.
82 *
83 * @param polygonPoints a list of points that describe a closed polygon
84 * @return the converted Java2D path
85 */
86 public static Path2D createPath2D (List<Coord> polygonPoints) {
87 int n = polygonPoints.size();
88 if (n < 3)
89 return new Path2D.Double();
90
91 Path2D path = new Path2D.Double(PathIterator.WIND_NON_ZERO, n);
92 if (polygonPoints.get(0).highPrecEquals(polygonPoints.get(n-1))){
93 // if first and last point are high-prec-equal, ignore last point
94 // because we use closePath() to signal that
95 --n;
96 }
97 int lastLat = Integer.MAX_VALUE,lastLon = Integer.MAX_VALUE;
98 for (int i = 0; i < n; i++){
99 Coord co = polygonPoints.get(i);
100 int latHp = co.getHighPrecLat();
101 int lonHp = co.getHighPrecLon();
102 double x = (double)lonHp / (1<<Coord.DELTA_SHIFT);
103 double y = (double)latHp / (1<<Coord.DELTA_SHIFT);
104 if (i == 0)
105 path.moveTo(x, y);
106 else {
107 if (lastLon != lonHp || lastLat != latHp)
108 path.lineTo(x, y);
109 }
110 lastLon = lonHp;
111 lastLat = latHp;
112 }
113 path.closePath();
114 return path;
115 }
116
117 public static Polygon createHighPrecPolygon(List<Coord> points) {
118 Polygon polygon = new Polygon();
119 for (Coord co : points) {
120 polygon.addPoint(co.getHighPrecLon(), co.getHighPrecLat());
121 }
122 return polygon;
123 }
124
125 public static List<Area> areaToSingularAreas(Area area) {
126 return areaToSingularAreas(0, area);
127 }
128 /**
129 * Convert an area that may contains multiple areas to a list of singular
130 * areas keeping the highest possible precision.
131 *
132 * @param area an area
133 * @return list of singular areas
134 */
135 private static List<Area> areaToSingularAreas(int depth, Area area) {
136 if (area.isEmpty()) {
137 return Collections.emptyList();
138 } else if (area.isSingular()) {
139 return Collections.singletonList(area);
140 } else {
141 List<Area> singularAreas = new ArrayList<>();
142
143 // all ways in the area MUST define outer areas
144 // it is not possible that one of the areas define an inner segment
145
146 double[] res = new double[6];
147 PathIterator pit = area.getPathIterator(null);
148 Path2D path = null;
149 while (!pit.isDone()) {
150 int type = pit.currentSegment(res);
151 double lat = res[1];
152 double lon = res[0];
153
154 switch (type) {
155 case PathIterator.SEG_LINETO:
156 path.lineTo(lon, lat);
157 break;
158 case PathIterator.SEG_CLOSE:
159 path.closePath();
160 Area a = new Area(path);
161 if (!a.isEmpty()) {
162 if (depth < 10 && !a.isSingular()){
163 // should not happen, but it does. Error in Area code?
164 singularAreas.addAll(areaToSingularAreas(depth+1,a));
165 }
166 else
167 singularAreas.add(a);
168 }
169 path = null;
170 break;
171 case PathIterator.SEG_MOVETO:
172 path = new Path2D.Double();
173 path.moveTo(lon, lat);
174 break;
175 default:
176 log.error("Unsupported path iterator type " + type
177 + ". This is an mkgmap error.");
178 }
179 pit.next();
180 }
181 return singularAreas;
182 }
183 }
184
185 /**
186 * Convert an area to an mkgmap way. The caller must ensure that the area is
187 * singular. Otherwise only the first non-empty part of the area is converted.
188 *
189 * @param area the area
190 * @return list of points
191 */
192 public static List<Coord> singularAreaToPoints(Area area) {
193 return singularAreaToPoints(area, null);
194 }
195
196 /**
197 * Convert an area to an mkgmap way. The caller must ensure that the area is
198 * singular. Otherwise only the first non-empty part of the area is converted.
199 *
200 * @param area the area
201 * @param coordPool the map for unique Coord instances, can be null
202 * @return list of points
203 */
204 public static List<Coord> singularAreaToPoints(Area area, Long2ObjectOpenHashMap<Coord> coordPool) {
205 if (area.isEmpty()) {
206 return null;
207 }
208
209 List<Coord> points = null;
210
211 double[] res = new double[6];
212 PathIterator pit = area.getPathIterator(null);
213 int prevLatHp = Integer.MIN_VALUE;
214 int prevLongHp = Integer.MIN_VALUE;
215
216 while (!pit.isDone()) {
217 int type = pit.currentSegment(res);
218
219 int latHp = (int)Math.round(res[1] * (1<<Coord.DELTA_SHIFT));
220 int lonHp = (int)Math.round(res[0] * (1<<Coord.DELTA_SHIFT));
221
222 switch (type) {
223 case PathIterator.SEG_MOVETO:
224 if (points != null)
225 log.error("area not singular");
226 points = new ArrayList<>();
227 points.add(Coord.makeHighPrecCoord(latHp, lonHp, coordPool));
228 break;
229 case PathIterator.SEG_LINETO:
230 assert points != null;
231 if (prevLatHp != latHp || prevLongHp != lonHp)
232 points.add(Coord.makeHighPrecCoord(latHp, lonHp, coordPool));
233 break;
234 case PathIterator.SEG_CLOSE:
235 assert points != null;
236 if (points.size() < 3)
237 points = null;
238 else {
239 if (points.get(0).highPrecEquals(points.get(points.size() - 1))) {
240 // replace equal last with closing point
241 points.set(points.size() - 1, points.get(0));
242 }
243 else
244 points.add(points.get(0)); // add closing point
245 if (points.size() < 4)
246 points = null;
247 else
248 return points;
249 }
250 break;
251 default:
252 log.error("Unsupported path iterator type " + type
253 + ". This is an mkgmap error.");
254 }
255
256 prevLatHp = latHp;
257 prevLongHp = lonHp;
258
259 pit.next();
260 }
261 return points;
262 }
263 /**
264 * Convert the area back into a list of polygons each represented by a list
265 * of coords. It is possible that the area contains multiple discontinuous
266 * polygons, so you may append more than one shape to the output list.<br/>
267 * <b>Attention:</b> The outline of the polygon is has clockwise order whereas
268 * holes in the polygon have counterclockwise order.
269 *
270 * @param area The area to be converted.
271 * @return a list of closed polygons
272 */
273 public static List<List<Coord>> areaToShapes(java.awt.geom.Area area) {
274 return areaToShapes(area, null);
275 }
276
277 /**
278 * Convert the area back into a list of polygons each represented by a list
279 * of coords. It is possible that the area contains multiple discontinuous
280 * polygons, so you may append more than one shape to the output list.<br/>
281 * <b>Attention:</b> The outline of the polygon is has clockwise order whereas
282 * holes in the polygon have counterclockwise order.
283 *
284 * @param area The area to be converted.
285 * @param coordPool map to produce unique Coord instances
286 * @return a list of closed polygons
287 */
288 public static List<List<Coord>> areaToShapes(java.awt.geom.Area area, Long2ObjectOpenHashMap<Coord> coordPool) {
289 List<List<Coord>> outputs = new ArrayList<>(4);
290
291 double[] res = new double[6];
292 PathIterator pit = area.getPathIterator(null);
293
294 List<Coord> coords = null;
295
296 int prevLatHp = Integer.MIN_VALUE;
297 int prevLongHp = Integer.MIN_VALUE;
298
299 while (!pit.isDone()) {
300 int type = pit.currentSegment(res);
301
302 int latHp = (int) Math.round(res[1] * (1<<Coord.DELTA_SHIFT));
303 int lonHp = (int) Math.round(res[0] * (1<<Coord.DELTA_SHIFT));
304
305 switch (type) {
306 case PathIterator.SEG_LINETO:
307 if (prevLatHp != latHp || prevLongHp != lonHp)
308 coords.add(Coord.makeHighPrecCoord(latHp, lonHp, coordPool));
309
310 prevLatHp = latHp;
311 prevLongHp = lonHp;
312 break;
313 case PathIterator.SEG_MOVETO:
314 case PathIterator.SEG_CLOSE:
315 if ((type == PathIterator.SEG_MOVETO && coords != null) || type == PathIterator.SEG_CLOSE) {
316 if (coords.size() > 2){
317 if (coords.get(0).highPrecEquals(coords.get(coords.size() - 1))){
318 // replace equal last with closing point
319 coords.set(coords.size() - 1, coords.get(0));
320 }
321 else
322 coords.add(coords.get(0)); // add closing point
323 }
324 if (coords.size() > 3){
325 outputs.add(coords);
326 }
327 }
328 if (type == PathIterator.SEG_MOVETO){
329 coords = new ArrayList<>();
330 coords.add(Coord.makeHighPrecCoord(latHp, lonHp, coordPool));
331 prevLatHp = latHp;
332 prevLongHp = lonHp;
333 } else {
334 coords = null;
335 prevLatHp = Integer.MIN_VALUE;
336 prevLongHp = Integer.MIN_VALUE;
337 }
338 break;
339 default:
340 log.error("Unsupported path iterator type " + type
341 + ". This is an mkgmap error.");
342 }
343
344 pit.next();
345 }
346
347 return outputs;
348 }
349
350 /**
351 * Convert area with coordinates in degrees to area in MapUnits
352 * @param area
353 * @return
354 */
355 public static java.awt.geom.Area AreaDegreesToMapUnit(java.awt.geom.Area area){
356 if (area == null)
357 return null;
358 double[] res = new double[6];
359 Path2D path = new Path2D.Double();
360 PathIterator pit = area.getPathIterator(null);
361 while (!pit.isDone()) {
362 int type = pit.currentSegment(res);
363
364 double fLat = res[1];
365 double fLon = res[0];
366 int lat = Utils.toMapUnit(fLat);
367 int lon = Utils.toMapUnit(fLon);
368
369 switch (type) {
370 case PathIterator.SEG_LINETO:
371 path.lineTo(lon, lat);
372 break;
373 case PathIterator.SEG_MOVETO:
374 path.moveTo(lon, lat);
375 break;
376 case PathIterator.SEG_CLOSE:
377 path.closePath();
378 break;
379 default:
380 System.out.println("Unsupported path iterator type " + type
381 + ". This is an internal splitter error.");
382 }
383
384 pit.next();
385 }
386 return new java.awt.geom.Area(path);
387 }
388
389 /**
390 * Read am osmosis *.poly file that describes a polygon with coordinates in degrees.
391 * @param polygonFile path to the poly file
392 * @return the polygon converted to map units or null in case of error.
393 */
394 public static java.awt.geom.Area readPolyFile(String polygonFile) {
395 File f = new File(polygonFile);
396 if (!f.exists()) {
397 throw new IllegalArgumentException("polygon file doesn't exist: " + polygonFile);
398 }
399 try {
400 PolygonFileReader pfr = new PolygonFileReader(f);
401 java.awt.geom.Area polygonInDegrees = pfr.loadPolygon();
402 return Java2DConverter.AreaDegreesToMapUnit(polygonInDegrees);
403 } catch (Exception e) {
404 log.error("cannot read polygon file", polygonFile);
405 log.error(e);
406 }
407 return null;
408 }
409
410
411 }