001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui.mappaint; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.awt.Color; 007import java.awt.Dimension; 008import java.awt.Graphics2D; 009import java.awt.Point; 010import java.awt.RenderingHints; 011import java.awt.image.BufferedImage; 012import java.io.IOException; 013import java.io.PrintStream; 014import java.util.Collection; 015import java.util.HashMap; 016import java.util.Map; 017import java.util.Optional; 018 019import org.openstreetmap.josm.data.Bounds; 020import org.openstreetmap.josm.data.ProjectionBounds; 021import org.openstreetmap.josm.data.osm.DataSet; 022import org.openstreetmap.josm.data.osm.OsmPrimitive; 023import org.openstreetmap.josm.data.osm.visitor.paint.StyledMapRenderer; 024import org.openstreetmap.josm.data.projection.Projection; 025import org.openstreetmap.josm.data.projection.ProjectionRegistry; 026import org.openstreetmap.josm.gui.NavigatableComponent; 027import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource; 028import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement; 029import org.openstreetmap.josm.data.osm.visitor.paint.MapPaintSettings; 030import org.openstreetmap.josm.io.IllegalDataException; 031import org.openstreetmap.josm.tools.CheckParameterUtil; 032import org.openstreetmap.josm.tools.Logging; 033 034/** 035 * Class to render osm data to a file. 036 * @since 12963 037 */ 038public class RenderingHelper { 039 040 private final DataSet ds; 041 private final Bounds bounds; 042 private final ProjectionBounds projBounds; 043 private final double scale; 044 private final Collection<StyleData> styles; 045 private Color backgroundColor; 046 private boolean fillBackground = true; 047 private String prefix = ""; 048 private PrintStream debugStream; 049 050 /** 051 * Data class to save style settings along with the corresponding style URL. 052 */ 053 public static class StyleData { 054 public String styleUrl; 055 public Map<String, String> settings = new HashMap<>(); 056 } 057 058 /** 059 * Construct a new {@code RenderingHelper}. 060 * @param ds the dataset to render 061 * @param bounds the bounds of the are to render 062 * @param scale the scale to render at (east/north units per pixel) 063 * @param styles the styles to use for rendering 064 */ 065 public RenderingHelper(DataSet ds, Bounds bounds, double scale, Collection<StyleData> styles) { 066 CheckParameterUtil.ensureParameterNotNull(ds, "ds"); 067 CheckParameterUtil.ensureParameterNotNull(bounds, "bounds"); 068 CheckParameterUtil.ensureParameterNotNull(styles, "styles"); 069 this.ds = ds; 070 this.bounds = bounds; 071 this.scale = scale; 072 this.styles = styles; 073 Projection proj = ProjectionRegistry.getProjection(); 074 projBounds = new ProjectionBounds(); 075 projBounds.extend(proj.latlon2eastNorth(bounds.getMin())); 076 projBounds.extend(proj.latlon2eastNorth(bounds.getMax())); 077 } 078 079 /** 080 * Set the background color to use for rendering. 081 * 082 * @param backgroundColor the background color to use, {@code} means 083 * to determine the background color automatically from the style 084 * @see #setFillBackground(boolean) 085 * @since 12966 086 */ 087 public void setBackgroundColor(Color backgroundColor) { 088 this.backgroundColor = backgroundColor; 089 } 090 091 /** 092 * Decide if background should be filled or left transparent. 093 * @param fillBackground true, if background should be filled 094 * @see #setBackgroundColor(java.awt.Color) 095 * @since 12966 096 */ 097 public void setFillBackground(boolean fillBackground) { 098 this.fillBackground = fillBackground; 099 } 100 101 Dimension getImageSize() { 102 double widthEn = projBounds.maxEast - projBounds.minEast; 103 double heightEn = projBounds.maxNorth - projBounds.minNorth; 104 int widthPx = (int) Math.round(widthEn / scale); 105 int heightPx = (int) Math.round(heightEn / scale); 106 return new Dimension(widthPx, heightPx); 107 } 108 109 /** 110 * Invoke the renderer. 111 * 112 * @return the rendered image 113 * @throws IOException in case of an IOException 114 * @throws IllegalDataException when illegal data is encountered (style has errors, etc.) 115 */ 116 public BufferedImage render() throws IOException, IllegalDataException { 117 // load the styles 118 ElemStyles elemStyles = new ElemStyles(); 119 MapCSSStyleSource.STYLE_SOURCE_LOCK.writeLock().lock(); 120 try { 121 for (StyleData sd : styles) { 122 MapCSSStyleSource source = new MapCSSStyleSource(sd.styleUrl, "cliRenderingStyle", "cli rendering style '" + sd.styleUrl + "'"); 123 source.loadStyleSource(); 124 elemStyles.add(source); 125 if (!source.getErrors().isEmpty()) { 126 throw new IllegalDataException("Failed to load style file. Errors: " + source.getErrors()); 127 } 128 for (String key : sd.settings.keySet()) { 129 StyleSetting.PropertyStyleSetting<?> match = source.settings.stream() 130 .filter(s -> s instanceof StyleSetting.PropertyStyleSetting) 131 .map(s -> (StyleSetting.PropertyStyleSetting<?>) s) 132 .filter(bs -> bs.getKey().endsWith(":" + key)) 133 .findFirst().orElse(null); 134 if (match == null) { 135 Logging.warn(tr("Style setting not found: ''{0}''", key)); 136 } else { 137 String value = sd.settings.get(key); 138 Logging.trace("setting applied: ''{0}:{1}''", key, value); 139 match.setStringValue(value); 140 } 141 } 142 if (!sd.settings.isEmpty()) { 143 source.loadStyleSource(); // reload to apply settings 144 } 145 } 146 } finally { 147 MapCSSStyleSource.STYLE_SOURCE_LOCK.writeLock().unlock(); 148 } 149 150 Dimension imgDimPx = getImageSize(); 151 NavigatableComponent nc = new NavigatableComponent() { 152 { 153 setBounds(0, 0, imgDimPx.width, imgDimPx.height); 154 updateLocationState(); 155 } 156 157 @Override 158 protected boolean isVisibleOnScreen() { 159 return true; 160 } 161 162 @Override 163 public Point getLocationOnScreen() { 164 return new Point(0, 0); 165 } 166 }; 167 nc.zoomTo(projBounds.getCenter(), scale); 168 169 // render the data 170 BufferedImage image = new BufferedImage(imgDimPx.width, imgDimPx.height, BufferedImage.TYPE_INT_ARGB); 171 Graphics2D g = image.createGraphics(); 172 173 // Force all render hints to be defaults - do not use platform values 174 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 175 g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); 176 g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); 177 g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE); 178 g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); 179 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 180 g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); 181 g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); 182 g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); 183 184 if (fillBackground) { 185 g.setColor(Optional.ofNullable(backgroundColor).orElse(elemStyles.getBackgroundColor())); 186 g.fillRect(0, 0, imgDimPx.width, imgDimPx.height); 187 } 188 StyledMapRenderer smr = new StyledMapRenderer(g, nc, false, MapPaintSettings.createSettings(prefix)); 189 smr.setStyles(elemStyles); 190 smr.render(ds, false, bounds); 191 192 // For debugging, write computed StyleElement to debugStream for primitives marked with debug=yes 193 if (debugStream != null) { 194 for (OsmPrimitive primitive : ds.allPrimitives()) { 195 if (!primitive.isKeyTrue("debug")) { 196 continue; 197 } 198 debugStream.println(primitive); 199 for (StyleElement styleElement : elemStyles.get(primitive, scale, nc)) { 200 debugStream.append(" * ").println(styleElement); 201 } 202 } 203 } 204 205 return image; 206 } 207 208 void setDebugStream(PrintStream debugStream) { 209 this.debugStream = debugStream; 210 } 211 212 /** 213 * Set a prefix for rendering style defaults. 214 * @param prefix the option prefix used when accessing style settings, should be lowercase with a dot at the end 215 * @since 19589 216 */ 217 void setPrefix(String prefix) { 218 this.prefix = prefix; 219 } 220}