source: josm/trunk/src/org/openstreetmap/josm/gui/mappaint/RenderingCLI.java@ 12964

Last change on this file since 12964 was 12963, checked in by bastiK, 7 years ago

see #15273 - extract rendering code to new class

File size: 25.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.mappaint;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Dimension;
7import java.io.FileInputStream;
8import java.io.FileNotFoundException;
9import java.io.IOException;
10import java.util.ArrayList;
11import java.util.List;
12import java.util.Locale;
13import java.util.Optional;
14import java.util.function.Supplier;
15import java.util.logging.Level;
16
17import org.openstreetmap.gui.jmapviewer.OsmMercator;
18import org.openstreetmap.josm.CLIModule;
19import org.openstreetmap.josm.tools.I18n;
20import org.openstreetmap.josm.Main;
21import org.openstreetmap.josm.data.Bounds;
22import org.openstreetmap.josm.data.Preferences;
23import org.openstreetmap.josm.data.ProjectionBounds;
24import org.openstreetmap.josm.data.coor.EastNorth;
25import org.openstreetmap.josm.data.coor.LatLon;
26import org.openstreetmap.josm.data.coor.conversion.LatLonParser;
27import org.openstreetmap.josm.data.osm.DataSet;
28import org.openstreetmap.josm.data.projection.Projection;
29import org.openstreetmap.josm.data.projection.Projections;
30import org.openstreetmap.josm.gui.mappaint.RenderingHelper.StyleData;
31import org.openstreetmap.josm.io.IllegalDataException;
32import org.openstreetmap.josm.io.OsmReader;
33import org.openstreetmap.josm.spi.preferences.Config;
34import org.openstreetmap.josm.spi.preferences.MemoryPreferences;
35import org.openstreetmap.josm.tools.Logging;
36import org.openstreetmap.josm.tools.RightAndLefthandTraffic;
37
38import gnu.getopt.Getopt;
39import gnu.getopt.LongOpt;
40
41/**
42 * Command line interface for rendering osm data to an image file.
43 *
44 * @since 12906
45 */
46public class RenderingCLI implements CLIModule {
47
48 /**
49 * The singleton instance of this class.
50 */
51 public static final RenderingCLI INSTANCE = new RenderingCLI();
52
53 private static final double PIXEL_PER_METER = 96 / 2.54 * 100; // standard value of 96 dpi display resolution
54 private static final int DEFAULT_MAX_IMAGE_SIZE = 20000;
55
56 private boolean argDebug;
57 private boolean argTrace;
58 private String argInput;
59 private String argOutput;
60 private List<StyleData> argStyles;
61 private Integer argZoom;
62 private Double argScale;
63 private Bounds argBounds;
64 private LatLon argAnchor;
65 private Double argWidthM;
66 private Double argHeightM;
67 private Integer argWidthPx;
68 private Integer argHeightPx;
69 private String argProjection;
70 private Integer argMaxImageSize;
71
72 private enum Option {
73 HELP(false, 'h'),
74 DEBUG(false, '*'),
75 TRACE(false, '*'),
76 INPUT(true, 'i'),
77 STYLE(true, 's'),
78 SETTING(true, '*'),
79 OUTPUT(true, 'o'),
80 ZOOM(true, 'z'),
81 SCALE(true, '*'),
82 BOUNDS(true, 'b'),
83 ANCHOR(true, '*'),
84 WIDTH_M(true, '*'),
85 HEIGHT_M(true, '*'),
86 WIDTH_PX(true, '*'),
87 HEIGHT_PX(true, '*'),
88 PROJECTION(true, '*'),
89 MAX_IMAGE_SIZE(true, '*');
90
91 private final String name;
92 private final boolean requiresArg;
93 private final char shortOption;
94
95 Option(boolean requiresArgument, char shortOption) {
96 this.name = name().toLowerCase(Locale.US).replace('_', '-');
97 this.requiresArg = requiresArgument;
98 this.shortOption = shortOption;
99 }
100
101 /**
102 * Replies the option name
103 * @return The option name, in lowercase
104 */
105 public String getName() {
106 return name;
107 }
108
109 /**
110 * Determines if this option requires an argument.
111 * @return {@code true} if this option requires an argument, {@code false} otherwise
112 */
113 public boolean requiresArgument() {
114 return requiresArg;
115 }
116
117 /**
118 * Replies the short option (single letter) associated with this option.
119 * @return the short option or '*' if there is no short option
120 */
121 public char getShortOption() {
122 return shortOption;
123 }
124
125 LongOpt toLongOpt() {
126 return new LongOpt(getName(), requiresArgument() ? LongOpt.REQUIRED_ARGUMENT : LongOpt.NO_ARGUMENT, null, getShortOption());
127 }
128 }
129
130 /**
131 * Data class to hold return values for {@link #determineRenderingArea(DataSet)}.
132 *
133 * Package private access for unit tests.
134 */
135 static class RenderingArea {
136 public Bounds bounds;
137 public double scale; // in east-north units per pixel (unlike the --scale option, which is in meter per meter)
138 }
139
140 RenderingCLI() {
141 // hide constructor (package private access for unit tests)
142 }
143
144 @Override
145 public String getActionKeyword() {
146 return "render";
147 }
148
149 @Override
150 public void processArguments(String[] argArray) {
151 try {
152 parseArguments(argArray);
153 initialize();
154 DataSet ds = loadDataset();
155 RenderingArea area = determineRenderingArea(ds);
156 RenderingHelper rh = new RenderingHelper(ds, area.bounds, area.scale, argStyles);
157 rh.setOutputFile(argOutput);
158 checkPreconditions(rh);
159 rh.render();
160 } catch (FileNotFoundException e) {
161 if (Logging.isDebugEnabled()) {
162 e.printStackTrace();
163 }
164 System.err.println(tr("Error - file not found: ''{0}''", e.getMessage()));
165 System.exit(1);
166 } catch (IllegalArgumentException | IllegalDataException | IOException e) {
167 if (Logging.isDebugEnabled()) {
168 e.printStackTrace();
169 }
170 if (e.getMessage() != null) {
171 System.err.println(tr("Error: {0}", e.getMessage()));
172 }
173 System.exit(1);
174 }
175 System.exit(0);
176 }
177
178 /**
179 * Parse command line arguments and do some low-level error checking.
180 * @param argArray the arguments array
181 */
182 void parseArguments(String[] argArray) {
183 Getopt.setI18nHandler(I18n::tr);
184 Logging.setLogLevel(Level.INFO);
185
186 LongOpt[] opts = new LongOpt[Option.values().length];
187 StringBuilder optString = new StringBuilder();
188 for (Option o : Option.values()) {
189 opts[o.ordinal()] = o.toLongOpt();
190 if (o.getShortOption() != '*') {
191 optString.append(o.getShortOption());
192 if (o.requiresArgument()) {
193 optString.append(':');
194 }
195 }
196 }
197
198 Getopt getopt = new Getopt("JOSM rendering", argArray, optString.toString(), opts);
199
200 StyleData currentStyle = new StyleData();
201 argStyles = new ArrayList<>();
202
203 int c;
204 while ((c = getopt.getopt()) != -1) {
205 switch (c) {
206 case 'h':
207 showHelp();
208 System.exit(0);
209 case 'i':
210 argInput = getopt.getOptarg();
211 break;
212 case 's':
213 if (currentStyle.styleUrl != null) {
214 argStyles.add(currentStyle);
215 currentStyle = new StyleData();
216 }
217 currentStyle.styleUrl = getopt.getOptarg();
218 break;
219 case 'o':
220 argOutput = getopt.getOptarg();
221 break;
222 case 'z':
223 try {
224 argZoom = Integer.parseInt(getopt.getOptarg());
225 } catch (NumberFormatException nfe) {
226 throw new IllegalArgumentException(
227 tr("Expected integer number for option {0}, but got ''{1}''", "--zoom", getopt.getOptarg()));
228 }
229 if (argZoom < 0)
230 throw new IllegalArgumentException(
231 tr("Expected integer number >= 0 for option {0}, but got ''{1}''", "--zoom", getopt.getOptarg()));
232 break;
233 case 'b':
234 if (!getopt.getOptarg().equals("auto")) {
235 try {
236 argBounds = new Bounds(getopt.getOptarg(), ",", Bounds.ParseMethod.LEFT_BOTTOM_RIGHT_TOP, false);
237 } catch (IllegalArgumentException iae) { // NOPMD
238 throw new IllegalArgumentException(tr("Unable to parse {0} parameter: {1}", "--bounds", iae.getMessage()));
239 }
240 }
241 break;
242 case '*':
243 switch (Option.values()[getopt.getLongind()]) {
244 case DEBUG:
245 argDebug = true;
246 break;
247 case TRACE:
248 argTrace = true;
249 break;
250 case SETTING:
251 String keyval = getopt.getOptarg();
252 String[] comp = keyval.split(":");
253 if (comp.length != 2)
254 throw new IllegalArgumentException(
255 tr("Expected key and value, separated by '':'' character for option {0}, but got ''{1}''",
256 "--setting", getopt.getOptarg()));
257 currentStyle.settings.put(comp[0].trim(), comp[1].trim());
258 break;
259 case SCALE:
260 try {
261 argScale = Double.parseDouble(getopt.getOptarg());
262 } catch (NumberFormatException nfe) {
263 throw new IllegalArgumentException(
264 tr("Expected floating point number for option {0}, but got ''{1}''", "--scale", getopt.getOptarg()));
265 }
266 break;
267 case ANCHOR:
268 String[] parts = getopt.getOptarg().split(",");
269 if (parts.length != 2)
270 throw new IllegalArgumentException(
271 tr("Expected two coordinates, separated by comma, for option {0}, but got ''{1}''",
272 "--anchor", getopt.getOptarg()));
273 try {
274 double lon = LatLonParser.parseCoordinate(parts[0]);
275 double lat = LatLonParser.parseCoordinate(parts[1]);
276 argAnchor = new LatLon(lat, lon);
277 } catch (IllegalArgumentException iae) { // NOPMD
278 throw new IllegalArgumentException(tr("In option {0}: {1}", "--anchor", iae.getMessage()));
279 }
280 break;
281 case WIDTH_M:
282 try {
283 argWidthM = Double.parseDouble(getopt.getOptarg());
284 } catch (NumberFormatException nfe) {
285 throw new IllegalArgumentException(
286 tr("Expected floating point number for option {0}, but got ''{1}''", "--width-m", getopt.getOptarg()));
287 }
288 if (argWidthM <= 0) throw new IllegalArgumentException(
289 tr("Expected floating point number > 0 for option {0}, but got ''{1}''", "--width-m", getopt.getOptarg()));
290 break;
291 case HEIGHT_M:
292 try {
293 argHeightM = Double.parseDouble(getopt.getOptarg());
294 } catch (NumberFormatException nfe) {
295 throw new IllegalArgumentException(
296 tr("Expected floating point number for option {0}, but got ''{1}''", "--height-m", getopt.getOptarg()));
297 }
298 if (argHeightM <= 0) throw new IllegalArgumentException(
299 tr("Expected floating point number > 0 for option {0}, but got ''{1}''", "--width-m", getopt.getOptarg()));
300 break;
301 case WIDTH_PX:
302 try {
303 argWidthPx = Integer.parseInt(getopt.getOptarg());
304 } catch (NumberFormatException nfe) {
305 throw new IllegalArgumentException(
306 tr("Expected integer number for option {0}, but got ''{1}''", "--width-px", getopt.getOptarg()));
307 }
308 if (argWidthPx <= 0) throw new IllegalArgumentException(
309 tr("Expected integer number > 0 for option {0}, but got ''{1}''", "--width-px", getopt.getOptarg()));
310 break;
311 case HEIGHT_PX:
312 try {
313 argHeightPx = Integer.parseInt(getopt.getOptarg());
314 } catch (NumberFormatException nfe) {
315 throw new IllegalArgumentException(
316 tr("Expected integer number for option {0}, but got ''{1}''", "--height-px", getopt.getOptarg()));
317 }
318 if (argHeightPx <= 0) throw new IllegalArgumentException(
319 tr("Expected integer number > 0 for option {0}, but got ''{1}''", "--height-px", getopt.getOptarg()));
320 break;
321 case PROJECTION:
322 argProjection = getopt.getOptarg();
323 break;
324 case MAX_IMAGE_SIZE:
325 try {
326 argMaxImageSize = Integer.parseInt(getopt.getOptarg());
327 } catch (NumberFormatException nfe) {
328 throw new IllegalArgumentException(
329 tr("Expected integer number for option {0}, but got ''{1}''", "--max-image-size", getopt.getOptarg()));
330 }
331 if (argMaxImageSize < 0) throw new IllegalArgumentException(
332 tr("Expected integer number >= 0 for option {0}, but got ''{1}''", "--max-image-size", getopt.getOptarg()));
333 break;
334 default:
335 throw new AssertionError("Unexpected option index: " + getopt.getLongind());
336 }
337 break;
338 case '?':
339 throw new IllegalArgumentException(); // getopt error
340 default:
341 throw new AssertionError("Unrecognized option: " + c);
342 }
343 }
344 if (currentStyle.styleUrl != null) {
345 argStyles.add(currentStyle);
346 }
347 }
348
349 /**
350 * Displays help on the console
351 */
352 public static void showHelp() {
353 System.out.println(getHelp());
354 }
355
356 private static String getHelp() {
357 return tr("JOSM rendering command line interface")+"\n\n"+
358 tr("Usage")+":\n"+
359 "\tjava -jar josm.jar render <options>\n\n"+
360 tr("Description")+":\n"+
361 tr("Renders data and saves the result to an image file.")+"\n\n"+
362 tr("Options")+":\n"+
363 "\t--help|-h "+tr("Show this help")+"\n"+
364 "\t--input|-i <file> "+tr("Input data file name (.osm)")+"\n"+
365 "\t--output|-o <file> "+tr("Output image file name (.png); defaults to ''{0}''", "out.png")+"\n"+
366 "\t--style|-s <file> "+tr("Style file to use for rendering (.mapcss or .zip)")+"\n"+
367 "\t "+tr("This option can be repeated to load multiple styles.")+"\n"+
368 "\t--setting <key>:<value> "+tr("Style setting (in JOSM accessible in the style list dialog right click menu)")+"\n"+
369 "\t "+tr("Applies to the last style loaded with the {0} option.", "--style")+"\n"+
370 "\t--zoom|-z <lvl> "+tr("Select zoom level to render. (integer value, 0=entire earth, 18=street level)")+"\n"+
371 "\t--scale <scale> "+tr("Select the map scale")+"\n"+
372 "\t "+tr("A value of 10000 denotes a scale of 1:10000 (1 cm on the map equals 100 m on the ground; "
373 + "display resolution: 96 dpi)")+"\n"+
374 "\t "+tr("Options {0} and {1} are mutually exclusive.", "--zoom", "--scale")+"\n"+
375 "\t--bounds|-b auto|<min_lon>,<min_lat>,<max_lon>,<max_lat>\n"+
376 "\t "+tr("Area to render, default value is ''{0}''", "auto")+"\n"+
377 "\t "+tr("With keyword ''{0}'', the downloaded area in the .osm input file will be used (if recorded).",
378 "auto")+"\n"+
379 "\t--anchor <lon>,<lat> "+tr("Specify bottom left corner of the rendering area")+"\n"+
380 "\t "+tr("Used in combination with width and height options to determine the area to render.")+"\n"+
381 "\t--width-m <number> "+tr("Width of the rendered area, in meter")+"\n"+
382 "\t--height-m <number> "+tr("Height of the rendered area, in meter")+"\n"+
383 "\t--width-px <number> "+tr("Width of the target image, in pixel")+"\n"+
384 "\t--height-px <number> "+tr("Height of the target image, in pixel")+"\n"+
385 "\t--projection <code> "+tr("Projection to use, default value ''{0}'' (web-Mercator)", "epsg:3857")+"\n"+
386 "\t--max-image-size <number> "+tr("Maximum image width/height in pixel (''{0}'' means no limit), default value: {1}",
387 0, Integer.toString(DEFAULT_MAX_IMAGE_SIZE))+"\n"+
388 "\n"+
389 tr("To specify the rendered area and scale, the options can be combined in various ways")+":\n"+
390 " * --bounds (--zoom|--scale|--width-px|--height-px)\n"+
391 " * --anchor (--width-m|--width-px) (--height-m|--height-px) (--zoom|--scale)\n"+
392 " * --anchor --width-m --height-m (--width-px|--height-px)\n"+
393 " * --anchor --width-px --height-px (--width-m|--height-m)\n"+
394 tr("If neither ''{0}'' nor ''{1}'' is given, the default value {2} takes effect "
395 + "and the bounds of the download area in the .osm input file are used.",
396 "bounds", "anchor", "--bounds=auto")+"\n\n"+
397 tr("Examples")+":\n"+
398 " java -jar josm.jar render -i data.osm -s style.mapcss -z 16\n"+
399 " josm render -i data.osm -s style.mapcss --scale 5000\n"+
400 " josm render -i data.osm -s style.mapcss -z 16 -o image.png\n"+
401 " josm render -i data.osm -s elemstyles.mapcss --setting hide_icons:false -z 16\n"+
402 " josm render -i data.osm -s style.mapcss -s another_style.mapcss -z 16 -o image.png\n"+
403 " josm render -i data.osm -s style.mapcss --bounds 21.151,51.401,21.152,51.402 -z 16\n"+
404 " josm render -i data.osm -s style.mapcss --anchor 21.151,51.401 --width-m 500 --height-m 300 -z 16\n"+
405 " josm render -i data.osm -s style.mapcss --anchor 21.151,51.401 --width-m 500 --height-m 300 --width-px 1800\n"+
406 " josm render -i data.osm -s style.mapcss --scale 5000 --projection epsg:4326\n";
407 }
408
409 /**
410 * Initialization.
411 *
412 * Requires arguments to be parsed already ({@link #parseArguments(java.lang.String[])}).
413 */
414 void initialize() {
415 Logging.setLogLevel(getLogLevel());
416
417 Config.setBaseDirectoriesProvider(new Preferences()); // for right-left-hand traffic cache file
418 Config.setPreferencesInstance(new MemoryPreferences());
419 Config.getPref().putBoolean("mappaint.auto_reload_local_styles", false); // unnecessary to listen for external changes
420 String projCode = Optional.ofNullable(argProjection).orElse("epsg:3857");
421 Main.setProjection(Projections.getProjectionByCode(projCode.toUpperCase(Locale.US)));
422
423 RightAndLefthandTraffic.initialize();
424 }
425
426 private Level getLogLevel() {
427 if (argTrace) {
428 return Logging.LEVEL_TRACE;
429 } else if (argDebug) {
430 return Logging.LEVEL_DEBUG;
431 } else {
432 return Logging.LEVEL_INFO;
433 }
434 }
435
436 /**
437 * Find the area to render and the scale, given certain command line options and the dataset.
438 * @param ds the dataset
439 * @return area to render and the scale
440 */
441 RenderingArea determineRenderingArea(DataSet ds) {
442
443 Projection proj = Main.getProjection();
444 Double scale = null; // scale in east-north units per pixel
445 if (argZoom != null) {
446 scale = OsmMercator.EARTH_RADIUS * Math.PI * 2 / Math.pow(2, argZoom) / OsmMercator.DEFAUL_TILE_SIZE / proj.getMetersPerUnit();
447 }
448 Bounds bounds = argBounds;
449 ProjectionBounds pb = null;
450
451 if (bounds == null) {
452 if (argAnchor != null) {
453 EastNorth projAnchor = proj.latlon2eastNorth(argAnchor);
454
455 Double enPerMeter = null;
456 Supplier<Double> getEnPerMeter = () -> {
457 double shiftMeter = 10;
458 EastNorth projAnchorShifted = projAnchor.add(
459 shiftMeter / proj.getMetersPerUnit(), shiftMeter / proj.getMetersPerUnit());
460 LatLon anchorShifted = proj.eastNorth2latlon(projAnchorShifted);
461 return projAnchor.distance(projAnchorShifted) / argAnchor.greatCircleDistance(anchorShifted);
462 };
463
464 if (scale == null) {
465 if (argScale != null) {
466 enPerMeter = getEnPerMeter.get();
467 scale = argScale * enPerMeter / PIXEL_PER_METER;
468 } else if (argWidthM != null && argWidthPx != null) {
469 enPerMeter = getEnPerMeter.get();
470 scale = argWidthM / argWidthPx * enPerMeter;
471 } else if (argHeightM != null && argHeightPx != null) {
472 enPerMeter = getEnPerMeter.get();
473 scale = argHeightM / argHeightPx * enPerMeter;
474 } else {
475 throw new IllegalArgumentException(
476 tr("Argument {0} given, but scale cannot be determined from remaining arguments", "--anchor"));
477 }
478 }
479
480 double widthEn;
481 if (argWidthM != null) {
482 enPerMeter = Optional.ofNullable(enPerMeter).orElseGet(getEnPerMeter);
483 widthEn = argWidthM * enPerMeter;
484 } else if (argWidthPx != null) {
485 widthEn = argWidthPx * scale;
486 } else {
487 throw new IllegalArgumentException(
488 tr("Argument {0} given, expected {1} or {2}", "--anchor", "--width-m", "--width-px"));
489 }
490
491 double heightEn;
492 if (argHeightM != null) {
493 enPerMeter = Optional.ofNullable(enPerMeter).orElseGet(getEnPerMeter);
494 heightEn = argHeightM * enPerMeter;
495 } else if (argHeightPx != null) {
496 heightEn = argHeightPx * scale;
497 } else {
498 throw new IllegalArgumentException(
499 tr("Argument {0} given, expected {1} or {2}", "--anchor", "--height-m", "--height-px"));
500 }
501 pb = new ProjectionBounds(projAnchor);
502 pb.extend(new EastNorth(projAnchor.east() + widthEn, projAnchor.north() + heightEn));
503 bounds = new Bounds(proj.eastNorth2latlon(pb.getMin()), false);
504 bounds.extend(proj.eastNorth2latlon(pb.getMax()));
505 } else {
506 if (ds.getDataSourceBounds().isEmpty()) {
507 throw new IllegalArgumentException(tr("{0} mode, but no bounds found in osm data input file", "--bounds=auto"));
508 }
509 bounds = ds.getDataSourceBounds().get(0);
510 }
511 }
512
513 if (pb == null) {
514 pb = new ProjectionBounds();
515 pb.extend(proj.latlon2eastNorth(bounds.getMin()));
516 pb.extend(proj.latlon2eastNorth(bounds.getMax()));
517 }
518
519 if (scale == null) {
520 if (argScale != null) {
521 double enPerMeter = pb.getMin().distance(pb.getMax()) / bounds.getMin().greatCircleDistance(bounds.getMax());
522 scale = argScale * enPerMeter / PIXEL_PER_METER;
523 } else if (argWidthPx != null) {
524 scale = (pb.maxEast - pb.minEast) / argWidthPx;
525 } else if (argHeightPx != null) {
526 scale = (pb.maxNorth - pb.minNorth) / argHeightPx;
527 } else {
528 throw new IllegalArgumentException(
529 tr("Unable to determine scale, one of the options {0}, {1}, {2} or {3} expected",
530 "--zoom", "--scale", "--width-px", "--height-px"));
531 }
532 }
533
534 RenderingArea ra = new RenderingArea();
535 ra.bounds = bounds;
536 ra.scale = scale;
537 return ra;
538 }
539
540 private DataSet loadDataset() throws FileNotFoundException, IllegalDataException {
541 if (argInput == null) {
542 throw new IllegalArgumentException(tr("Missing argument - input data file ({0})", "--input|-i"));
543 }
544 try {
545 return OsmReader.parseDataSet(new FileInputStream(argInput), null);
546 } catch (IllegalDataException e) {
547 throw new IllegalDataException(tr("In .osm data file ''{0}'' - ", argInput) + e.getMessage());
548 }
549 }
550
551 private void checkPreconditions(RenderingHelper rh) {
552 if (argStyles.isEmpty())
553 throw new IllegalArgumentException(tr("Missing argument - at least one style expected ({0})", "--style"));
554
555 Dimension imgSize = rh.getImageSize();
556 Logging.debug("image size (px): {0}x{1}", imgSize.width, imgSize.height);
557 int maxSize = Optional.ofNullable(argMaxImageSize).orElse(DEFAULT_MAX_IMAGE_SIZE);
558 if (maxSize != 0 && (imgSize.width > maxSize || imgSize.height > maxSize)) {
559 throw new IllegalArgumentException(
560 tr("Image dimensions ({0}x{1}) exceeds maximum image size {2} (use option {3} to change limit)",
561 imgSize.width, imgSize.height, maxSize, "--max-image-size"));
562 }
563 }
564}
Note: See TracBrowser for help on using the repository browser.