source: josm/trunk/src/org/openstreetmap/josm/gui/layer/gpx/GpxDrawHelper.java@ 12157

Last change on this file since 12157 was 12157, checked in by michael2402, 7 years ago

See #13124: Refresh the heat map on every invalidation (visible tacks changed, ...)

  • Property svn:eol-style set to native
File size: 59.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.layer.gpx;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.AlphaComposite;
8import java.awt.BasicStroke;
9import java.awt.Color;
10import java.awt.Composite;
11import java.awt.Graphics2D;
12import java.awt.LinearGradientPaint;
13import java.awt.MultipleGradientPaint;
14import java.awt.Paint;
15import java.awt.Point;
16import java.awt.Rectangle;
17import java.awt.RenderingHints;
18import java.awt.Stroke;
19import java.awt.image.BufferedImage;
20import java.awt.image.DataBufferInt;
21import java.awt.image.Raster;
22import java.io.BufferedReader;
23import java.io.IOException;
24import java.util.ArrayList;
25import java.util.Arrays;
26import java.util.Collection;
27import java.util.Collections;
28import java.util.Date;
29import java.util.LinkedList;
30import java.util.List;
31import java.util.Random;
32
33import javax.swing.ImageIcon;
34
35import org.openstreetmap.josm.Main;
36import org.openstreetmap.josm.data.Bounds;
37import org.openstreetmap.josm.data.SystemOfMeasurement;
38import org.openstreetmap.josm.data.SystemOfMeasurement.SoMChangeListener;
39import org.openstreetmap.josm.data.coor.LatLon;
40import org.openstreetmap.josm.data.gpx.GpxConstants;
41import org.openstreetmap.josm.data.gpx.GpxData;
42import org.openstreetmap.josm.data.gpx.WayPoint;
43import org.openstreetmap.josm.data.preferences.ColorProperty;
44import org.openstreetmap.josm.gui.MapView;
45import org.openstreetmap.josm.gui.MapViewState;
46import org.openstreetmap.josm.gui.layer.GpxLayer;
47import org.openstreetmap.josm.gui.layer.MapViewGraphics;
48import org.openstreetmap.josm.gui.layer.MapViewPaintable;
49import org.openstreetmap.josm.gui.layer.MapViewPaintable.MapViewEvent;
50import org.openstreetmap.josm.gui.layer.MapViewPaintable.PaintableInvalidationEvent;
51import org.openstreetmap.josm.gui.layer.MapViewPaintable.PaintableInvalidationListener;
52import org.openstreetmap.josm.io.CachedFile;
53import org.openstreetmap.josm.tools.ColorScale;
54import org.openstreetmap.josm.tools.JosmRuntimeException;
55import org.openstreetmap.josm.tools.Utils;
56
57/**
58 * Class that helps to draw large set of GPS tracks with different colors and options
59 * @since 7319
60 */
61public class GpxDrawHelper implements SoMChangeListener, MapViewPaintable.LayerPainter, PaintableInvalidationListener {
62
63 /**
64 * The color that is used for drawing GPX points.
65 * @since 10824
66 */
67 public static final ColorProperty DEFAULT_COLOR = new ColorProperty(marktr("gps point"), Color.magenta);
68
69 private final GpxData data;
70 private final GpxLayer layer;
71
72 // draw lines between points belonging to different segments
73 private boolean forceLines;
74 // use alpha blending for line draw
75 private boolean alphaLines;
76 // draw direction arrows on the lines
77 private boolean direction;
78 /** width of line for paint **/
79 private int lineWidth;
80 /** don't draw lines if longer than x meters **/
81 private int maxLineLength;
82 // draw lines
83 private boolean lines;
84 /** paint large dots for points **/
85 private boolean large;
86 private int largesize;
87 private boolean hdopCircle;
88 /** paint direction arrow with alternate math. may be faster **/
89 private boolean alternateDirection;
90 /** don't draw arrows nearer to each other than this **/
91 private int delta;
92 private double minTrackDurationForTimeColoring;
93
94 /** maximum value of displayed HDOP, minimum is 0 */
95 private int hdoprange;
96
97 private static final double PHI = Utils.toRadians(15);
98
99 //// Variables used only to check cache validity
100 private boolean computeCacheInSync;
101 private int computeCacheMaxLineLengthUsed;
102 private Color computeCacheColorUsed;
103 private boolean computeCacheColorDynamic;
104 private ColorMode computeCacheColored;
105 private int computeCacheColorTracksTune;
106 private int computeCacheHeatMapDrawColorTableIdx;
107 private boolean computeCacheHeatMapDrawPointMode;
108 private int computeCacheHeatMapDrawGain;
109 private int computeCacheHeatMapDrawLowerLimit;
110
111 //// Color-related fields
112 /** Mode of the line coloring **/
113 private ColorMode colored;
114 /** max speed for coloring - allows to tweak line coloring for different speed levels. **/
115 private int colorTracksTune;
116 private boolean colorModeDynamic;
117 private Color neutralColor;
118 private int largePointAlpha;
119
120 // default access is used to allow changing from plugins
121 private ColorScale velocityScale;
122 /** Colors (without custom alpha channel, if given) for HDOP painting. **/
123 private ColorScale hdopScale;
124 private ColorScale dateScale;
125 private ColorScale directionScale;
126
127 /** Opacity for hdop points **/
128 private int hdopAlpha;
129
130 // lookup array to draw arrows without doing any math
131 private static final int ll0 = 9;
132 private static final int sl4 = 5;
133 private static final int sl9 = 3;
134 private static final int[][] dir = {
135 {+sl4, +ll0, +ll0, +sl4}, {-sl9, +ll0, +sl9, +ll0},
136 {-ll0, +sl4, -sl4, +ll0}, {-ll0, -sl9, -ll0, +sl9},
137 {-sl4, -ll0, -ll0, -sl4}, {+sl9, -ll0, -sl9, -ll0},
138 {+ll0, -sl4, +sl4, -ll0}, {+ll0, +sl9, +ll0, -sl9}
139 };
140
141 /** heat map parameters **/
142
143 // enabled or not (override by settings)
144 private boolean heatMapEnabled;
145 // draw small extra line
146 private boolean heatMapDrawExtraLine;
147 // used index for color table (parameter)
148 private int heatMapDrawColorTableIdx;
149 // use point or line draw mode
150 private boolean heatMapDrawPointMode;
151 // extra gain > 0 or < 0 attenuation, 0 = default
152 private int heatMapDrawGain;
153 // do not draw elements with value lower than this limit
154 private int heatMapDrawLowerLimit;
155
156 // normal buffered image and draw object (cached)
157 private BufferedImage heatMapImgGray;
158 private Graphics2D heatMapGraph2d;
159
160 // some cached values
161 Rectangle heatMapCacheScreenBounds = new Rectangle();
162 MapViewState heatMapMapViewState;
163 int heatMapCacheLineWith;
164
165 // copied value for line drawing
166 private final List<Integer> heatMapPolyX = new ArrayList<>();
167 private final List<Integer> heatMapPolyY = new ArrayList<>();
168
169 // setup color maps used by heat map
170 private static Color[] heatMapLutColorJosmInferno = createColorFromResource("inferno");
171 private static Color[] heatMapLutColorJosmViridis = createColorFromResource("viridis");
172 private static Color[] heatMapLutColorJosmBrown2Green = createColorFromResource("brown2green");
173 private static Color[] heatMapLutColorJosmRed2Blue = createColorFromResource("red2blue");
174
175 // user defined heatmap color
176 private Color[] heatMapLutColor = createColorLut(0, Color.BLACK, Color.WHITE);
177
178 // The heat map was invalidated since the last draw.
179 private boolean gpxLayerInvalidated;
180
181
182 private void setupColors() {
183 hdopAlpha = Main.pref.getInteger("hdop.color.alpha", -1);
184 velocityScale = ColorScale.createHSBScale(256);
185 /** Colors (without custom alpha channel, if given) for HDOP painting. **/
186 hdopScale = ColorScale.createHSBScale(256).makeReversed().addTitle(tr("HDOP"));
187 dateScale = ColorScale.createHSBScale(256).addTitle(tr("Time"));
188 directionScale = ColorScale.createCyclicScale(256).setIntervalCount(4).addTitle(tr("Direction"));
189
190 systemOfMeasurementChanged(null, null);
191 }
192
193 @Override
194 public void systemOfMeasurementChanged(String oldSoM, String newSoM) {
195 SystemOfMeasurement som = SystemOfMeasurement.getSystemOfMeasurement();
196 velocityScale.addTitle(tr("Velocity, {0}", som.speedName));
197 if (oldSoM != null && newSoM != null && Main.isDisplayingMapView()) {
198 Main.map.mapView.repaint();
199 }
200 }
201
202 /**
203 * Different color modes
204 */
205 public enum ColorMode {
206 NONE, VELOCITY, HDOP, DIRECTION, TIME, HEATMAP;
207
208 static ColorMode fromIndex(final int index) {
209 return values()[index];
210 }
211
212 int toIndex() {
213 return Arrays.asList(values()).indexOf(this);
214 }
215 }
216
217 /**
218 * Constructs a new {@code GpxDrawHelper}.
219 * @param gpxLayer The layer to draw
220 * @since 12157
221 */
222 public GpxDrawHelper(GpxLayer gpxLayer) {
223 layer = gpxLayer;
224 data = gpxLayer.data;
225
226 layer.addInvalidationListener(this);
227 SystemOfMeasurement.addSoMChangeListener(this);
228 setupColors();
229 }
230
231 private static String specName(String layerName) {
232 return "layer " + layerName;
233 }
234
235 /**
236 * Get the default color for gps tracks for specified layer
237 * @param layerName name of the GpxLayer
238 * @param ignoreCustom do not use preferences
239 * @return the color or null if the color is not constant
240 */
241 public Color getColor(String layerName, boolean ignoreCustom) {
242 if (ignoreCustom || getColorMode(layerName) == ColorMode.NONE) {
243 return DEFAULT_COLOR.getChildColor(specName(layerName)).get();
244 } else {
245 return null;
246 }
247 }
248
249 /**
250 * Read coloring mode for specified layer from preferences
251 * @param layerName name of the GpxLayer
252 * @return coloring mode
253 */
254 public ColorMode getColorMode(String layerName) {
255 try {
256 int i = Main.pref.getInteger("draw.rawgps.colors", specName(layerName), 0);
257 return ColorMode.fromIndex(i);
258 } catch (IndexOutOfBoundsException e) {
259 Main.warn(e);
260 }
261 return ColorMode.NONE;
262 }
263
264 /** Reads generic color from preferences (usually gray)
265 * @return the color
266 **/
267 public static Color getGenericColor() {
268 return DEFAULT_COLOR.get();
269 }
270
271 /**
272 * Read all drawing-related settings from preferences
273 * @param layerName layer name used to access its specific preferences
274 **/
275 public void readPreferences(String layerName) {
276 String spec = specName(layerName);
277 forceLines = Main.pref.getBoolean("draw.rawgps.lines.force", spec, false);
278 direction = Main.pref.getBoolean("draw.rawgps.direction", spec, false);
279 lineWidth = Main.pref.getInteger("draw.rawgps.linewidth", spec, 0);
280 alphaLines = Main.pref.getBoolean("draw.rawgps.lines.alpha-blend", spec, false);
281
282 if (!data.fromServer) {
283 maxLineLength = Main.pref.getInteger("draw.rawgps.max-line-length.local", spec, -1);
284 lines = Main.pref.getBoolean("draw.rawgps.lines.local", spec, true);
285 } else {
286 maxLineLength = Main.pref.getInteger("draw.rawgps.max-line-length", spec, 200);
287 lines = Main.pref.getBoolean("draw.rawgps.lines", spec, true);
288 }
289 large = Main.pref.getBoolean("draw.rawgps.large", spec, false);
290 largesize = Main.pref.getInteger("draw.rawgps.large.size", spec, 3);
291 hdopCircle = Main.pref.getBoolean("draw.rawgps.hdopcircle", spec, false);
292 colored = getColorMode(layerName);
293 alternateDirection = Main.pref.getBoolean("draw.rawgps.alternatedirection", spec, false);
294 delta = Main.pref.getInteger("draw.rawgps.min-arrow-distance", spec, 40);
295 colorTracksTune = Main.pref.getInteger("draw.rawgps.colorTracksTune", spec, 45);
296 colorModeDynamic = Main.pref.getBoolean("draw.rawgps.colors.dynamic", spec, false);
297 /* good HDOP's are between 1 and 3, very bad HDOP's go into 3 digit values */
298 hdoprange = Main.pref.getInteger("hdop.range", 7);
299 minTrackDurationForTimeColoring = Main.pref.getInteger("draw.rawgps.date-coloring-min-dt", 60);
300 largePointAlpha = Main.pref.getInteger("draw.rawgps.large.alpha", -1) & 0xFF;
301
302 // get heatmap parameters
303 heatMapEnabled = Main.pref.getBoolean("draw.rawgps.heatmap.enabled", spec, false);
304 heatMapDrawExtraLine = Main.pref.getBoolean("draw.rawgps.heatmap.line-extra", spec, false);
305 heatMapDrawColorTableIdx = Main.pref.getInteger("draw.rawgps.heatmap.colormap", spec, 0);
306 heatMapDrawPointMode = Main.pref.getBoolean("draw.rawgps.heatmap.use-points", spec, false);
307 heatMapDrawGain = Main.pref.getInteger("draw.rawgps.heatmap.gain", spec, 0);
308 heatMapDrawLowerLimit = Main.pref.getInteger("draw.rawgps.heatmap.lower-limit", spec, 0);
309
310 // shrink to range
311 heatMapDrawGain = Utils.clamp(heatMapDrawGain, -10, 10);
312
313 neutralColor = getColor(layerName, true);
314 velocityScale.setNoDataColor(neutralColor);
315 dateScale.setNoDataColor(neutralColor);
316 hdopScale.setNoDataColor(neutralColor);
317 directionScale.setNoDataColor(neutralColor);
318
319 largesize += lineWidth;
320 }
321
322 @Override
323 public void paint(MapViewGraphics graphics) {
324 List<WayPoint> visibleSegments = listVisibleSegments(graphics.getClipBounds().getLatLonBoundsBox());
325 if (!visibleSegments.isEmpty()) {
326 readPreferences(layer.getName());
327 drawAll(graphics.getDefaultGraphics(), graphics.getMapView(), visibleSegments);
328 if (graphics.getMapView().getLayerManager().getActiveLayer() == layer) {
329 drawColorBar(graphics.getDefaultGraphics(), graphics.getMapView());
330 }
331 }
332 }
333
334 private List<WayPoint> listVisibleSegments(Bounds box) {
335 WayPoint last = null;
336 LinkedList<WayPoint> visibleSegments = new LinkedList<>();
337
338 ensureTrackVisibilityLength();
339 for (Collection<WayPoint> segment : data.getLinesIterable(layer.trackVisibility)) {
340
341 for (WayPoint pt : segment) {
342 Bounds b = new Bounds(pt.getCoor());
343 if (pt.drawLine && last != null) {
344 b.extend(last.getCoor());
345 }
346 if (b.intersects(box)) {
347 if (last != null && (visibleSegments.isEmpty()
348 || visibleSegments.getLast() != last)) {
349 if (last.drawLine) {
350 WayPoint l = new WayPoint(last);
351 l.drawLine = false;
352 visibleSegments.add(l);
353 } else {
354 visibleSegments.add(last);
355 }
356 }
357 visibleSegments.add(pt);
358 }
359 last = pt;
360 }
361 }
362 return visibleSegments;
363 }
364
365 /** ensures the trackVisibility array has the correct length without losing data.
366 * TODO: Make this nicer by syncing the trackVisibility automatically.
367 * additional entries are initialized to true;
368 */
369 private void ensureTrackVisibilityLength() {
370 final int l = data.getTracks().size();
371 if (l == layer.trackVisibility.length)
372 return;
373 final int m = Math.min(l, layer.trackVisibility.length);
374 layer.trackVisibility = Arrays.copyOf(layer.trackVisibility, l);
375 for (int i = m; i < l; i++) {
376 layer.trackVisibility[i] = true;
377 }
378 }
379
380 /**
381 * Draw all enabled GPX elements of layer.
382 * @param g the common draw object to use
383 * @param mv the meta data to current displayed area
384 * @param visibleSegments segments visible in the current scope of mv
385 */
386 public void drawAll(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
387
388 final long timeStart = System.currentTimeMillis();
389
390 checkCache();
391
392 // STEP 2b - RE-COMPUTE CACHE DATA *********************
393 if (!computeCacheInSync) { // don't compute if the cache is good
394 calculateColors();
395 }
396
397 fixColors(visibleSegments);
398
399 // backup the environment
400 Composite oldComposite = g.getComposite();
401 Stroke oldStroke = g.getStroke();
402 Paint oldPaint = g.getPaint();
403
404 // set hints for the render
405 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
406 Main.pref.getBoolean("mappaint.gpx.use-antialiasing", false) ?
407 RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
408
409 if (lineWidth != 0) {
410 g.setStroke(new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
411 }
412
413 // global enabled or select via color
414 boolean useHeatMap = heatMapEnabled || ColorMode.HEATMAP == colored;
415
416 // default global alpha level
417 float layerAlpha = 1.00f;
418
419 // extract current alpha blending value
420 if (oldComposite instanceof AlphaComposite) {
421 layerAlpha = ((AlphaComposite) oldComposite).getAlpha();
422 }
423
424 // use heatmap background layer
425 if (useHeatMap) {
426 drawHeatMap(g, mv, visibleSegments);
427 } else {
428 // use normal line style or alpha-blending lines
429 if (!alphaLines) {
430 drawLines(g, mv, visibleSegments);
431 } else {
432 drawLinesAlpha(g, mv, visibleSegments, layerAlpha);
433 }
434 }
435
436 // override global alpha settings (smooth overlay)
437 if (alphaLines || useHeatMap) {
438 g.setComposite(AlphaComposite.SrcOver.derive(0.25f * layerAlpha));
439 }
440
441 // normal overlays
442 drawArrows(g, mv, visibleSegments);
443 drawPoints(g, mv, visibleSegments);
444
445 // restore environment
446 g.setPaint(oldPaint);
447 g.setStroke(oldStroke);
448 g.setComposite(oldComposite);
449
450 // show some debug info
451 if (Main.isDebugEnabled() && !visibleSegments.isEmpty()) {
452 final long timeDiff = System.currentTimeMillis() - timeStart;
453
454 Main.debug("gpxdraw::draw takes " +
455 Utils.getDurationString(timeDiff) +
456 "(" +
457 "segments= " + visibleSegments.size() +
458 ", per 10000 = " + Utils.getDurationString(10_000 * timeDiff / visibleSegments.size()) +
459 ")"
460 );
461 }
462 }
463
464 /**
465 * Calculate colors of way segments based on latest configuration settings
466 */
467 public void calculateColors() {
468 double minval = +1e10;
469 double maxval = -1e10;
470 WayPoint oldWp = null;
471
472 if (colorModeDynamic) {
473 if (colored == ColorMode.VELOCITY) {
474 final List<Double> velocities = new ArrayList<>();
475 for (Collection<WayPoint> segment : data.getLinesIterable(null)) {
476 if (!forceLines) {
477 oldWp = null;
478 }
479 for (WayPoint trkPnt : segment) {
480 LatLon c = trkPnt.getCoor();
481 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
482 continue;
483 }
484 if (oldWp != null && trkPnt.time > oldWp.time) {
485 double vel = c.greatCircleDistance(oldWp.getCoor())
486 / (trkPnt.time - oldWp.time);
487 velocities.add(vel);
488 }
489 oldWp = trkPnt;
490 }
491 }
492 Collections.sort(velocities);
493 if (velocities.isEmpty()) {
494 velocityScale.setRange(0, 120/3.6);
495 } else {
496 minval = velocities.get(velocities.size() / 20); // 5% percentile to remove outliers
497 maxval = velocities.get(velocities.size() * 19 / 20); // 95% percentile to remove outliers
498 velocityScale.setRange(minval, maxval);
499 }
500 } else if (colored == ColorMode.HDOP) {
501 for (Collection<WayPoint> segment : data.getLinesIterable(null)) {
502 for (WayPoint trkPnt : segment) {
503 Object val = trkPnt.get(GpxConstants.PT_HDOP);
504 if (val != null) {
505 double hdop = ((Float) val).doubleValue();
506 if (hdop > maxval) {
507 maxval = hdop;
508 }
509 if (hdop < minval) {
510 minval = hdop;
511 }
512 }
513 }
514 }
515 if (minval >= maxval) {
516 hdopScale.setRange(0, 100);
517 } else {
518 hdopScale.setRange(minval, maxval);
519 }
520 }
521 oldWp = null;
522 } else { // color mode not dynamic
523 velocityScale.setRange(0, colorTracksTune);
524 hdopScale.setRange(0, hdoprange);
525 }
526 double now = System.currentTimeMillis()/1000.0;
527 if (colored == ColorMode.TIME) {
528 Date[] bounds = data.getMinMaxTimeForAllTracks();
529 if (bounds.length >= 2) {
530 minval = bounds[0].getTime()/1000.0;
531 maxval = bounds[1].getTime()/1000.0;
532 } else {
533 minval = 0;
534 maxval = now;
535 }
536 dateScale.setRange(minval, maxval);
537 }
538
539 // Now the colors for all the points will be assigned
540 for (Collection<WayPoint> segment : data.getLinesIterable(null)) {
541 if (!forceLines) { // don't draw lines between segments, unless forced to
542 oldWp = null;
543 }
544 for (WayPoint trkPnt : segment) {
545 LatLon c = trkPnt.getCoor();
546 trkPnt.customColoring = neutralColor;
547 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
548 continue;
549 }
550 // now we are sure some color will be assigned
551 Color color = null;
552
553 if (colored == ColorMode.HDOP) {
554 Float hdop = (Float) trkPnt.get(GpxConstants.PT_HDOP);
555 color = hdopScale.getColor(hdop);
556 }
557 if (oldWp != null) { // other coloring modes need segment for calcuation
558 double dist = c.greatCircleDistance(oldWp.getCoor());
559 boolean noDraw = false;
560 switch (colored) {
561 case VELOCITY:
562 double dtime = trkPnt.time - oldWp.time;
563 if (dtime > 0) {
564 color = velocityScale.getColor(dist / dtime);
565 } else {
566 color = velocityScale.getNoDataColor();
567 }
568 break;
569 case DIRECTION:
570 double dirColor = oldWp.getCoor().bearing(trkPnt.getCoor());
571 color = directionScale.getColor(dirColor);
572 break;
573 case TIME:
574 double t = trkPnt.time;
575 // skip bad timestamps and very short tracks
576 if (t > 0 && t <= now && maxval - minval > minTrackDurationForTimeColoring) {
577 color = dateScale.getColor(t);
578 } else {
579 color = dateScale.getNoDataColor();
580 }
581 break;
582 default: // Do nothing
583 }
584 if (!noDraw && (maxLineLength == -1 || dist <= maxLineLength)) {
585 trkPnt.drawLine = true;
586 double bearing = oldWp.getCoor().bearing(trkPnt.getCoor());
587 trkPnt.dir = ((int) (bearing / Math.PI * 4 + 1.5)) % 8;
588 } else {
589 trkPnt.drawLine = false;
590 }
591 } else { // make sure we reset outdated data
592 trkPnt.drawLine = false;
593 color = neutralColor;
594 }
595 if (color != null) {
596 trkPnt.customColoring = color;
597 }
598 oldWp = trkPnt;
599 }
600 }
601
602 // heat mode
603 if (ColorMode.HEATMAP == colored) {
604
605 // get new user color map and refresh visibility level
606 heatMapLutColor = createColorLut(heatMapDrawLowerLimit,
607 selectColorMap(neutralColor != null ? neutralColor : Color.WHITE, heatMapDrawColorTableIdx));
608
609 // force redraw of image
610 heatMapMapViewState = null;
611 }
612
613 computeCacheInSync = true;
614 }
615
616 /**
617 * Draw all GPX ways segments
618 * @param g the common draw object to use
619 * @param mv the meta data to current displayed area
620 * @param visibleSegments segments visible in the current scope of mv
621 */
622 private void drawLines(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
623 if (lines) {
624 Point old = null;
625 for (WayPoint trkPnt : visibleSegments) {
626 LatLon c = trkPnt.getCoor();
627 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
628 continue;
629 }
630 Point screen = mv.getPoint(trkPnt.getEastNorth());
631 // skip points that are on the same screenposition
632 if (trkPnt.drawLine && old != null && ((old.x != screen.x) || (old.y != screen.y))) {
633 g.setColor(trkPnt.customColoring);
634 g.drawLine(old.x, old.y, screen.x, screen.y);
635 }
636 old = screen;
637 }
638 }
639 }
640
641 /**
642 * Draw all GPX arrays
643 * @param g the common draw object to use
644 * @param mv the meta data to current displayed area
645 * @param visibleSegments segments visible in the current scope of mv
646 */
647 private void drawArrows(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
648 /****************************************************************
649 ********** STEP 3b - DRAW NICE ARROWS **************************
650 ****************************************************************/
651 if (lines && direction && !alternateDirection) {
652 Point old = null;
653 Point oldA = null; // last arrow painted
654 for (WayPoint trkPnt : visibleSegments) {
655 LatLon c = trkPnt.getCoor();
656 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
657 continue;
658 }
659 if (trkPnt.drawLine) {
660 Point screen = mv.getPoint(trkPnt.getEastNorth());
661 // skip points that are on the same screenposition
662 if (old != null
663 && (oldA == null || screen.x < oldA.x - delta || screen.x > oldA.x + delta
664 || screen.y < oldA.y - delta || screen.y > oldA.y + delta)) {
665 g.setColor(trkPnt.customColoring);
666 double t = Math.atan2((double) screen.y - old.y, (double) screen.x - old.x) + Math.PI;
667 g.drawLine(screen.x, screen.y, (int) (screen.x + 10 * Math.cos(t - PHI)),
668 (int) (screen.y + 10 * Math.sin(t - PHI)));
669 g.drawLine(screen.x, screen.y, (int) (screen.x + 10 * Math.cos(t + PHI)),
670 (int) (screen.y + 10 * Math.sin(t + PHI)));
671 oldA = screen;
672 }
673 old = screen;
674 }
675 } // end for trkpnt
676 }
677
678 /****************************************************************
679 ********** STEP 3c - DRAW FAST ARROWS **************************
680 ****************************************************************/
681 if (lines && direction && alternateDirection) {
682 Point old = null;
683 Point oldA = null; // last arrow painted
684 for (WayPoint trkPnt : visibleSegments) {
685 LatLon c = trkPnt.getCoor();
686 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
687 continue;
688 }
689 if (trkPnt.drawLine) {
690 Point screen = mv.getPoint(trkPnt.getEastNorth());
691 // skip points that are on the same screenposition
692 if (old != null
693 && (oldA == null || screen.x < oldA.x - delta || screen.x > oldA.x + delta
694 || screen.y < oldA.y - delta || screen.y > oldA.y + delta)) {
695 g.setColor(trkPnt.customColoring);
696 g.drawLine(screen.x, screen.y, screen.x + dir[trkPnt.dir][0], screen.y
697 + dir[trkPnt.dir][1]);
698 g.drawLine(screen.x, screen.y, screen.x + dir[trkPnt.dir][2], screen.y
699 + dir[trkPnt.dir][3]);
700 oldA = screen;
701 }
702 old = screen;
703 }
704 } // end for trkpnt
705 }
706 }
707
708 /**
709 * Draw all GPX points
710 * @param g the common draw object to use
711 * @param mv the meta data to current displayed area
712 * @param visibleSegments segments visible in the current scope of mv
713 */
714 private void drawPoints(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
715 /****************************************************************
716 ********** STEP 3d - DRAW LARGE POINTS AND HDOP CIRCLE *********
717 ****************************************************************/
718 if (large || hdopCircle) {
719 final int halfSize = largesize/2;
720 for (WayPoint trkPnt : visibleSegments) {
721 LatLon c = trkPnt.getCoor();
722 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
723 continue;
724 }
725 Point screen = mv.getPoint(trkPnt.getEastNorth());
726
727
728 if (hdopCircle && trkPnt.get(GpxConstants.PT_HDOP) != null) {
729 // hdop value
730 float hdop = (Float) trkPnt.get(GpxConstants.PT_HDOP);
731 if (hdop < 0) {
732 hdop = 0;
733 }
734 Color customColoringTransparent = hdopAlpha < 0 ? trkPnt.customColoring :
735 new Color((trkPnt.customColoring.getRGB() & 0x00ffffff) | (hdopAlpha << 24), true);
736 g.setColor(customColoringTransparent);
737 // hdop circles
738 int hdopp = mv.getPoint(new LatLon(
739 trkPnt.getCoor().lat(),
740 trkPnt.getCoor().lon() + 2d*6*hdop*360/40000000d)).x - screen.x;
741 g.drawArc(screen.x-hdopp/2, screen.y-hdopp/2, hdopp, hdopp, 0, 360);
742 }
743 if (large) {
744 // color the large GPS points like the gps lines
745 if (trkPnt.customColoring != null) {
746 Color customColoringTransparent = largePointAlpha < 0 ? trkPnt.customColoring :
747 new Color((trkPnt.customColoring.getRGB() & 0x00ffffff) | (largePointAlpha << 24), true);
748
749 g.setColor(customColoringTransparent);
750 }
751 g.fillRect(screen.x-halfSize, screen.y-halfSize, largesize, largesize);
752 }
753 } // end for trkpnt
754 } // end if large || hdopcircle
755
756 /****************************************************************
757 ********** STEP 3e - DRAW SMALL POINTS FOR LINES ***************
758 ****************************************************************/
759 if (!large && lines) {
760 g.setColor(neutralColor);
761 for (WayPoint trkPnt : visibleSegments) {
762 LatLon c = trkPnt.getCoor();
763 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
764 continue;
765 }
766 if (!trkPnt.drawLine) {
767 Point screen = mv.getPoint(trkPnt.getEastNorth());
768 g.drawRect(screen.x, screen.y, 0, 0);
769 }
770 } // end for trkpnt
771 } // end if large
772
773 /****************************************************************
774 ********** STEP 3f - DRAW SMALL POINTS INSTEAD OF LINES ********
775 ****************************************************************/
776 if (!large && !lines) {
777 g.setColor(neutralColor);
778 for (WayPoint trkPnt : visibleSegments) {
779 LatLon c = trkPnt.getCoor();
780 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
781 continue;
782 }
783 Point screen = mv.getPoint(trkPnt.getEastNorth());
784 g.setColor(trkPnt.customColoring);
785 g.drawRect(screen.x, screen.y, 0, 0);
786 } // end for trkpnt
787 } // end if large
788 }
789
790 /**
791 * Draw GPX lines by using alpha blending
792 * @param g the common draw object to use
793 * @param mv the meta data to current displayed area
794 * @param visibleSegments segments visible in the current scope of mv
795 * @param layerAlpha the color alpha value set for that operation
796 */
797 private void drawLinesAlpha(Graphics2D g, MapView mv, List<WayPoint> visibleSegments, float layerAlpha) {
798
799 // 1st. backup the paint environment ----------------------------------
800 Composite oldComposite = g.getComposite();
801 Stroke oldStroke = g.getStroke();
802 Paint oldPaint = g.getPaint();
803
804 // 2nd. determine current scale factors -------------------------------
805
806 // adjust global settings
807 final int globalLineWidth = Utils.clamp(lineWidth, 1, 20);
808
809 // cache scale of view
810 final double zoomScale = mv.getDist100Pixel() / 50.0f;
811
812 // 3rd. determine current paint parameters -----------------------------
813
814 // alpha value is based on zoom and line with combined with global layer alpha
815 float theLineAlpha = (float) Utils.clamp((0.50 / zoomScale) / (globalLineWidth + 1), 0.01, 0.50) * layerAlpha;
816 final int theLineWith = (int) (lineWidth / zoomScale) + 1;
817
818 // 4th setup virtual paint area ----------------------------------------
819
820 // set line format and alpha channel for all overlays (more lines -> few overlap -> more transparency)
821 g.setStroke(new BasicStroke(theLineWith, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
822 g.setComposite(AlphaComposite.SrcOver.derive(theLineAlpha));
823
824 // last used / calculated entries
825 Point lastPaintPnt = null;
826
827 // 5th draw the layer ---------------------------------------------------
828
829 // for all points
830 for (WayPoint trkPnt : visibleSegments) {
831
832 // transform coordinates
833 final Point paintPnt = mv.getPoint(trkPnt.getEastNorth());
834
835 // skip single points
836 if (lastPaintPnt != null && trkPnt.drawLine && !lastPaintPnt.equals(paintPnt)) {
837
838 // set different color
839 g.setColor(trkPnt.customColoring);
840
841 // draw it
842 g.drawLine(lastPaintPnt.x, lastPaintPnt.y, paintPnt.x, paintPnt.y);
843 }
844
845 lastPaintPnt = paintPnt;
846 }
847
848 // @last restore modified paint environment -----------------------------
849 g.setPaint(oldPaint);
850 g.setStroke(oldStroke);
851 g.setComposite(oldComposite);
852 }
853
854 /**
855 * Generates a linear gradient map image
856 *
857 * @param width image width
858 * @param height image height
859 * @param colors 1..n color descriptions
860 * @return image object
861 */
862 protected static BufferedImage createImageGradientMap(int width, int height, Color... colors) {
863
864 // create image an paint object
865 final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
866 final Graphics2D g = img.createGraphics();
867
868 float[] fract = new float[ colors.length ];
869
870 // distribute fractions (define position of color in map)
871 for (int i = 0; i < colors.length; ++i) {
872 fract[i] = i * (1.0f / colors.length);
873 }
874
875 // draw the gradient map
876 LinearGradientPaint gradient = new LinearGradientPaint(0, 0, width, height, fract, colors,
877 MultipleGradientPaint.CycleMethod.NO_CYCLE);
878 g.setPaint(gradient);
879 g.fillRect(0, 0, width, height);
880 g.dispose();
881
882 // access it via raw interface
883 return img;
884 }
885
886 /**
887 * Creates a distributed colormap by linear blending between colors
888 * @param lowerLimit lower limit for first visible color
889 * @param colors 1..n colors
890 * @return array of Color objects
891 */
892 protected static Color[] createColorLut(int lowerLimit, Color... colors) {
893
894 // number of lookup entries
895 final int tableSize = 256;
896
897 // access it via raw interface
898 final Raster imgRaster = createImageGradientMap(tableSize, 1, colors).getData();
899
900 // the pixel storage
901 int[] pixel = new int[1];
902
903 Color[] colorTable = new Color[tableSize];
904
905 // map the range 0..255 to 0..pi/2
906 final double mapTo90Deg = Math.PI / 2.0 / 255.0;
907
908 // create the lookup table
909 for (int i = 0; i < tableSize; i++) {
910
911 // get next single pixel
912 imgRaster.getDataElements(i, 0, pixel);
913
914 // get color and map
915 Color c = new Color(pixel[0]);
916
917 // smooth alpha like sin curve
918 int alpha = (i > lowerLimit) ? (int) (Math.sin((i-lowerLimit) * mapTo90Deg) * 255) : 0;
919
920 // alpha with pre-offset, first color -> full transparent
921 alpha = alpha > 0 ? (20 + alpha) : 0;
922
923 // shrink to maximum bound
924 if (alpha > 255) {
925 alpha = 255;
926 }
927
928 // increase transparency for higher values ( avoid big saturation )
929 if (i > 240 && 255 == alpha) {
930 alpha -= (i - 240);
931 }
932
933 // fill entry in table, assign a alpha value
934 colorTable[i] = new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha);
935 }
936
937 // transform into lookup table
938 return colorTable;
939 }
940
941 /**
942 * Creates a darker color
943 * @param in Color object
944 * @param adjust darker adjustment amount
945 * @return new Color
946 */
947 protected static Color darkerColor(Color in, float adjust) {
948
949 final float r = (float) in.getRed()/255;
950 final float g = (float) in.getGreen()/255;
951 final float b = (float) in.getBlue()/255;
952
953 return new Color(r*adjust, g*adjust, b*adjust);
954 }
955
956 /**
957 * Creates a colormap by using a static color map with 1..n colors (RGB 0.0 ..1.0)
958 * @param str the filename (without extension) to look for into data/gpx
959 * @return the parsed colormap
960 */
961 protected static Color[] createColorFromResource(String str) {
962
963 // create resource string
964 final String colorFile = "resource://data/gpx/" + str + ".txt";
965
966 List<Color> colorList = new ArrayList<>();
967
968 // try to load the file
969 try (CachedFile cf = new CachedFile(colorFile); BufferedReader br = cf.getContentReader()) {
970
971 String line;
972
973 // process lines
974 while ((line = br.readLine()) != null) {
975
976 // use comma as separator
977 String[] column = line.split(",");
978
979 // empty or comment line
980 if (column.length < 3 || column[0].startsWith("#")) {
981 continue;
982 }
983
984 // extract RGB value
985 float r = Float.parseFloat(column[0]);
986 float g = Float.parseFloat(column[1]);
987 float b = Float.parseFloat(column[2]);
988
989 // some color tables are 0..1.0 and some 0.255
990 float scale = (r < 1 && g < 1 && b < 1) ? 1 : 255;
991
992 colorList.add(new Color(r/scale, g/scale, b/scale));
993 }
994 } catch (IOException e) {
995 throw new JosmRuntimeException(e);
996 }
997
998 // fallback if empty or failed
999 if (colorList.isEmpty()) {
1000 colorList.add(Color.BLACK);
1001 colorList.add(Color.WHITE);
1002 } else {
1003 // add additional darker elements to end of list
1004 final Color lastColor = colorList.get(colorList.size() - 1);
1005 colorList.add(darkerColor(lastColor, 0.975f));
1006 colorList.add(darkerColor(lastColor, 0.950f));
1007 }
1008
1009 return createColorLut(0, colorList.toArray(new Color[ colorList.size() ]));
1010 }
1011
1012 /**
1013 * Returns the next user color map
1014 *
1015 * @param userColor - default or fallback user color
1016 * @param tableIdx - selected user color index
1017 * @return color array
1018 */
1019 protected static Color[] selectColorMap(Color userColor, int tableIdx) {
1020
1021 // generate new user color map ( dark, user color, white )
1022 Color[] userColor1 = createColorLut(0, userColor.darker(), userColor, userColor.brighter(), Color.WHITE);
1023
1024 // generate new user color map ( white -> color )
1025 Color[] userColor2 = createColorLut(0, Color.WHITE, Color.WHITE, userColor);
1026
1027 // generate new user color map
1028 Color[] colorTrafficLights = createColorLut(0, Color.WHITE, Color.GREEN.darker(), Color.YELLOW, Color.RED);
1029
1030 // decide what, keep order is sync with setting on GUI
1031 Color[][] lut = {
1032 userColor1,
1033 userColor2,
1034 colorTrafficLights,
1035 heatMapLutColorJosmInferno,
1036 heatMapLutColorJosmViridis,
1037 heatMapLutColorJosmBrown2Green,
1038 heatMapLutColorJosmRed2Blue
1039 };
1040
1041 // default case
1042 Color[] nextUserColor = userColor1;
1043
1044 // select by index
1045 if (tableIdx < lut.length) {
1046 nextUserColor = lut[ tableIdx ];
1047 }
1048
1049 // adjust color map
1050 return nextUserColor;
1051 }
1052
1053 /**
1054 * Generates a Icon
1055 *
1056 * @param userColor selected user color
1057 * @param tableIdx tabled index
1058 * @param size size of the image
1059 * @return a image icon that shows the
1060 */
1061 public static ImageIcon getColorMapImageIcon(Color userColor, int tableIdx, int size) {
1062 return new ImageIcon(createImageGradientMap(size, size, selectColorMap(userColor, tableIdx)));
1063 }
1064
1065 /**
1066 * Draw gray heat map with current Graphics2D setting
1067 * @param gB the common draw object to use
1068 * @param mv the meta data to current displayed area
1069 * @param listSegm segments visible in the current scope of mv
1070 * @param foreComp composite use to draw foreground objects
1071 * @param foreStroke stroke use to draw foreground objects
1072 * @param backComp composite use to draw background objects
1073 * @param backStroke stroke use to draw background objects
1074 */
1075 private void drawHeatGrayLineMap(Graphics2D gB, MapView mv, List<WayPoint> listSegm,
1076 Composite foreComp, Stroke foreStroke,
1077 Composite backComp, Stroke backStroke) {
1078
1079 // draw foreground
1080 boolean drawForeground = foreComp != null && foreStroke != null;
1081
1082 // set initial values
1083 gB.setStroke(backStroke); gB.setComposite(backComp);
1084
1085 // get last point in list
1086 final WayPoint lastPnt = !listSegm.isEmpty() ? listSegm.get(listSegm.size() - 1) : null;
1087
1088 // for all points, draw single lines by using optimized drawing
1089 for (WayPoint trkPnt : listSegm) {
1090
1091 // get transformed coordinates
1092 final Point paintPnt = mv.getPoint(trkPnt.getEastNorth());
1093
1094 // end of line segment or end of list reached
1095 if (!trkPnt.drawLine || (lastPnt == trkPnt)) {
1096
1097 // convert to primitive type
1098 final int[] polyXArr = heatMapPolyX.stream().mapToInt(Integer::intValue).toArray();
1099 final int[] polyYArr = heatMapPolyY.stream().mapToInt(Integer::intValue).toArray();
1100
1101 // a.) draw background
1102 gB.drawPolyline(polyXArr, polyYArr, polyXArr.length);
1103
1104 // b.) draw extra foreground
1105 if (drawForeground && heatMapDrawExtraLine) {
1106
1107 gB.setStroke(foreStroke); gB.setComposite(foreComp);
1108 gB.drawPolyline(polyXArr, polyYArr, polyXArr.length);
1109 gB.setStroke(backStroke); gB.setComposite(backComp);
1110 }
1111
1112 // drop used points
1113 heatMapPolyX.clear(); heatMapPolyY.clear();
1114 }
1115
1116 // store only the integer part (make sense because pixel is 1:1 here)
1117 heatMapPolyX.add((int) paintPnt.getX());
1118 heatMapPolyY.add((int) paintPnt.getY());
1119 }
1120 }
1121
1122 /**
1123 * Map the gray map to heat map and draw them with current Graphics2D setting
1124 * @param g the common draw object to use
1125 * @param imgGray gray scale input image
1126 * @param sampleRaster the line with for drawing
1127 * @param outlineWidth line width for outlines
1128 */
1129 private void drawHeatMapGrayMap(Graphics2D g, BufferedImage imgGray, int sampleRaster, int outlineWidth) {
1130
1131 final int[] imgPixels = ((DataBufferInt) imgGray.getRaster().getDataBuffer()).getData();
1132
1133 // samples offset and bounds are scaled with line width derived from zoom level
1134 final int offX = Math.max(1, sampleRaster);
1135 final int offY = Math.max(1, sampleRaster);
1136
1137 final int maxPixelX = imgGray.getWidth();
1138 final int maxPixelY = imgGray.getHeight();
1139
1140 // always full or outlines at big samples rasters
1141 final boolean drawOutlines = (outlineWidth > 0) && ((0 == sampleRaster) || (sampleRaster > 10));
1142
1143 // backup stroke
1144 final Stroke oldStroke = g.getStroke();
1145
1146 // use basic stroke for outlines and default transparency
1147 g.setStroke(new BasicStroke(outlineWidth));
1148
1149 int lastPixelX = 0;
1150 int lastPixelColor = 0;
1151
1152 // resample gray scale image with line linear weight of next sample in line
1153 // process each line and draw pixels / rectangles with same color with one operations
1154 for (int y = 0; y < maxPixelY; y += offY) {
1155
1156 // the lines offsets
1157 final int lastLineOffset = maxPixelX * (y+0);
1158 final int nextLineOffset = maxPixelX * (y+1);
1159
1160 for (int x = 0; x < maxPixelX; x += offX) {
1161
1162 int thePixelColor = 0; int thePixelCount = 0;
1163
1164 // sample the image (it is gray scale)
1165 int offset = lastLineOffset + x;
1166
1167 // merge next pixels of window of line
1168 for (int k = 0; k < offX && (offset + k) < nextLineOffset; k++) {
1169 thePixelColor += imgPixels[offset+k] & 0xFF;
1170 thePixelCount++;
1171 }
1172
1173 // mean value
1174 thePixelColor = thePixelCount > 0 ? (thePixelColor / thePixelCount) : 0;
1175
1176 // restart -> use initial sample
1177 if (0 == x) {
1178 lastPixelX = 0; lastPixelColor = thePixelColor - 1;
1179 }
1180
1181 boolean bDrawIt = false;
1182
1183 // when one of segment is mapped to black
1184 bDrawIt = bDrawIt || (lastPixelColor == 0) || (thePixelColor == 0);
1185
1186 // different color
1187 bDrawIt = bDrawIt || (Math.abs(lastPixelColor-thePixelColor) > 0);
1188
1189 // when line is finished draw always
1190 bDrawIt = bDrawIt || (y >= (maxPixelY-offY));
1191
1192 if (bDrawIt) {
1193
1194 // draw only foreground pixels
1195 if (lastPixelColor > 0) {
1196
1197 // gray to RGB mapping
1198 g.setColor(heatMapLutColor[ lastPixelColor ]);
1199
1200 // box from from last Y pixel to current pixel
1201 if (drawOutlines) {
1202 g.drawRect(lastPixelX, y, offX + x - lastPixelX, offY);
1203 } else {
1204 g.fillRect(lastPixelX, y, offX + x - lastPixelX, offY);
1205 }
1206 }
1207
1208 // restart detection
1209 lastPixelX = x; lastPixelColor = thePixelColor;
1210 }
1211 }
1212 }
1213
1214 // recover
1215 g.setStroke(oldStroke);
1216 }
1217
1218 /**
1219 * Collect and draw GPS segments and displays a heat-map
1220 * @param g the common draw object to use
1221 * @param mv the meta data to current displayed area
1222 * @param visibleSegments segments visible in the current scope of mv
1223 */
1224 private void drawHeatMap(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
1225
1226 // get bounds of screen image and projection, zoom and adjust input parameters
1227 final Rectangle screenBounds = new Rectangle(mv.getWidth(), mv.getHeight());
1228 final MapViewState mapViewState = mv.getState();
1229 final double zoomScale = mv.getDist100Pixel() / 50.0f;
1230
1231 // adjust global settings ( zero = default line width )
1232 final int globalLineWidth = (0 == lineWidth) ? 1 : Utils.clamp(lineWidth, 1, 20);
1233
1234 // 1st setup virtual paint area ----------------------------------------
1235
1236 // new image buffer needed
1237 final boolean imageSetup = null == heatMapImgGray || !heatMapCacheScreenBounds.equals(screenBounds);
1238
1239 // screen bounds changed, need new image buffer ?
1240 if (imageSetup) {
1241 // we would use a "pure" grayscale image, but there is not efficient way to map gray scale values to RGB)
1242 heatMapImgGray = new BufferedImage(screenBounds.width, screenBounds.height, BufferedImage.TYPE_INT_ARGB);
1243 heatMapGraph2d = heatMapImgGray.createGraphics();
1244 heatMapGraph2d.setBackground(new Color(0, 0, 0, 255));
1245 heatMapGraph2d.setColor(Color.WHITE);
1246
1247 // fast draw ( maybe help or not )
1248 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
1249 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
1250 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
1251 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
1252 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1253 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
1254 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
1255
1256 // cache it
1257 heatMapCacheScreenBounds = screenBounds;
1258 }
1259
1260 // 2nd. determine current scale factors -------------------------------
1261
1262 // the line width (foreground: draw extra small footprint line of track)
1263 int lineWidthB = (int) Math.max(1.5f * (globalLineWidth / zoomScale) + 1, 2);
1264 int lineWidthF = lineWidthB > 2 ? (globalLineWidth - 1) : 0;
1265
1266 // global alpha adjustment
1267 float lineAlpha = (float) Utils.clamp((0.40 / zoomScale) / (globalLineWidth + 1), 0.01, 0.40);
1268
1269 // adjust 0.15 .. 1.85
1270 float scaleAlpha = 1.0f + ((heatMapDrawGain/10.0f) * 0.85f);
1271
1272 // add to calculated values
1273 float lineAlphaBPoint = (float) Utils.clamp((lineAlpha * 0.65) * scaleAlpha, 0.001, 0.90);
1274 float lineAlphaBLine = (float) Utils.clamp((lineAlpha * 1.00) * scaleAlpha, 0.001, 0.90);
1275 float lineAlphaFLine = (float) Utils.clamp((lineAlpha / 1.50) * scaleAlpha, 0.001, 0.90);
1276
1277 // 3rd Calculate the heat map data by draw GPX traces with alpha value ----------
1278
1279 // recalculation of image needed
1280 final boolean imageRecalc = !mapViewState.equalsInWindow(heatMapMapViewState)
1281 || gpxLayerInvalidated
1282 || heatMapCacheLineWith != globalLineWidth;
1283
1284 // need re-generation of gray image ?
1285 if (imageSetup || imageRecalc) {
1286
1287 // clear background
1288 heatMapGraph2d.clearRect(0, 0, heatMapImgGray.getWidth(), heatMapImgGray.getHeight());
1289
1290 // point or line blending
1291 if (heatMapDrawPointMode) {
1292 heatMapGraph2d.setComposite(AlphaComposite.SrcOver.derive(lineAlphaBPoint));
1293 drawHeatGrayDotMap(heatMapGraph2d, mv, visibleSegments, lineWidthB);
1294
1295 } else {
1296 drawHeatGrayLineMap(heatMapGraph2d, mv, visibleSegments,
1297 lineWidthF > 1 ? AlphaComposite.SrcOver.derive(lineAlphaFLine) : null,
1298 new BasicStroke(lineWidthF, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND),
1299 AlphaComposite.SrcOver.derive(lineAlphaBLine),
1300 new BasicStroke(lineWidthB, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
1301 }
1302
1303 // remember draw parameter
1304 heatMapMapViewState = mapViewState;
1305 heatMapCacheLineWith = globalLineWidth;
1306 gpxLayerInvalidated = false;
1307 }
1308
1309 // 4th. Draw data on target layer, map data via color lookup table --------------
1310 drawHeatMapGrayMap(g, heatMapImgGray, lineWidthB > 2 ? (int) (lineWidthB*1.25f) : 1, lineWidth > 2 ? (lineWidth - 2) : 1);
1311 }
1312
1313 /**
1314 * Draw a dotted heat map
1315 *
1316 * @param gB the common draw object to use
1317 * @param mv the meta data to current displayed area
1318 * @param listSegm segments visible in the current scope of mv
1319 * @param drawSize draw size of draw element
1320 */
1321 private static void drawHeatGrayDotMap(Graphics2D gB, MapView mv, List<WayPoint> listSegm, int drawSize) {
1322
1323 // typical rendering rate -> use realtime preview instead of accurate display
1324 final double maxSegm = 25_000, nrSegms = listSegm.size();
1325
1326 // determine random drop rate
1327 final double randomDrop = Math.min(nrSegms > maxSegm ? (nrSegms - maxSegm) / nrSegms : 0, 0.70f);
1328
1329 // http://www.nstb.tc.faa.gov/reports/PAN94_0716.pdf#page=22
1330 // Global Average Position Domain Accuracy, typical -> not worst case !
1331 // < 4.218 m Vertical
1332 // < 2.168 m Horizontal
1333 final double pixelRmsX = (100 / mv.getDist100Pixel()) * 2.168;
1334 final double pixelRmsY = (100 / mv.getDist100Pixel()) * 4.218;
1335
1336 Point lastPnt = null;
1337
1338 // for all points, draw single lines
1339 for (WayPoint trkPnt : listSegm) {
1340
1341 // get transformed coordinates
1342 final Point paintPnt = mv.getPoint(trkPnt.getEastNorth());
1343
1344 // end of line segment or end of list reached
1345 if (trkPnt.drawLine && null != lastPnt) {
1346 drawHeatSurfaceLine(gB, paintPnt, lastPnt, drawSize, pixelRmsX, pixelRmsY, randomDrop);
1347 }
1348
1349 // remember
1350 lastPnt = paintPnt;
1351 }
1352 }
1353
1354 /**
1355 * Draw a dotted surface line
1356 *
1357 * @param g the common draw object to use
1358 * @param fromPnt start point
1359 * @param toPnt end point
1360 * @param drawSize size of draw elements
1361 * @param rmsSizeX RMS size of circle for X (width)
1362 * @param rmsSizeY RMS size of circle for Y (height)
1363 * @param dropRate Pixel render drop rate
1364 */
1365 private static void drawHeatSurfaceLine(Graphics2D g,
1366 Point fromPnt, Point toPnt, int drawSize, double rmsSizeX, double rmsSizeY, double dropRate) {
1367
1368 // collect frequently used items
1369 final int fromX = (int) fromPnt.getX(); final int deltaX = (int) (toPnt.getX() - fromX);
1370 final int fromY = (int) fromPnt.getY(); final int deltaY = (int) (toPnt.getY() - fromY);
1371
1372 // use same random values for each point
1373 final Random heatMapRandom = new Random(fromX+fromY+deltaX+deltaY);
1374
1375 // cache distance between start and end point
1376 final int dist = (int) Math.abs(fromPnt.distance(toPnt));
1377
1378 // number of increment ( fill wide distance tracks )
1379 double scaleStep = Math.max(1.0f / dist, dist > 100 ? 0.10f : 0.20f);
1380
1381 // number of additional random points
1382 int rounds = Math.min(drawSize/2, 1)+1;
1383
1384 // decrease random noise at high drop rate ( more accurate draw of fewer points )
1385 rmsSizeX *= (1.0d - dropRate);
1386 rmsSizeY *= (1.0d - dropRate);
1387
1388 double scaleVal = 0;
1389
1390 // interpolate line draw ( needs separate point instead of line )
1391 while (scaleVal < (1.0d-0.0001d)) {
1392
1393 // get position
1394 final double pntX = fromX + scaleVal * deltaX;
1395 final double pntY = fromY + scaleVal * deltaY;
1396
1397 // add random distribution around sampled point
1398 for (int k = 0; k < rounds; k++) {
1399
1400 // add error distribution, first point with less error
1401 int x = (int) (pntX + heatMapRandom.nextGaussian() * (k > 0 ? rmsSizeX : rmsSizeX/4));
1402 int y = (int) (pntY + heatMapRandom.nextGaussian() * (k > 0 ? rmsSizeY : rmsSizeY/4));
1403
1404 // draw it, even drop is requested
1405 if (heatMapRandom.nextDouble() >= dropRate) {
1406 g.fillRect(x-drawSize, y-drawSize, drawSize, drawSize);
1407 }
1408 }
1409 scaleVal += scaleStep;
1410 }
1411 }
1412
1413 /**
1414 * Apply default color configuration to way segments
1415 * @param visibleSegments segments visible in the current scope of mv
1416 */
1417 private void fixColors(List<WayPoint> visibleSegments) {
1418 for (WayPoint trkPnt : visibleSegments) {
1419 if (trkPnt.customColoring == null) {
1420 trkPnt.customColoring = neutralColor;
1421 }
1422 }
1423 }
1424
1425 /**
1426 * Check cache validity set necessary flags
1427 */
1428 private void checkCache() {
1429 // CHECKSTYLE.OFF: BooleanExpressionComplexity
1430 if ((computeCacheMaxLineLengthUsed != maxLineLength)
1431 || (computeCacheColored != colored)
1432 || (computeCacheColorTracksTune != colorTracksTune)
1433 || (computeCacheColorDynamic != colorModeDynamic)
1434 || (computeCacheHeatMapDrawColorTableIdx != heatMapDrawColorTableIdx)
1435 || (!neutralColor.equals(computeCacheColorUsed)
1436 || (computeCacheHeatMapDrawPointMode != heatMapDrawPointMode)
1437 || (computeCacheHeatMapDrawGain != heatMapDrawGain))
1438 || (computeCacheHeatMapDrawLowerLimit != heatMapDrawLowerLimit)
1439 ) {
1440 // CHECKSTYLE.ON: BooleanExpressionComplexity
1441 computeCacheMaxLineLengthUsed = maxLineLength;
1442 computeCacheInSync = false;
1443 computeCacheColorUsed = neutralColor;
1444 computeCacheColored = colored;
1445 computeCacheColorTracksTune = colorTracksTune;
1446 computeCacheColorDynamic = colorModeDynamic;
1447 computeCacheHeatMapDrawColorTableIdx = heatMapDrawColorTableIdx;
1448 computeCacheHeatMapDrawPointMode = heatMapDrawPointMode;
1449 computeCacheHeatMapDrawGain = heatMapDrawGain;
1450 computeCacheHeatMapDrawLowerLimit = heatMapDrawLowerLimit;
1451 }
1452 }
1453
1454 /**
1455 * callback when data is changed, invalidate cached configuration parameters
1456 */
1457 public void dataChanged() {
1458 computeCacheInSync = false;
1459 }
1460
1461 /**
1462 * Draw all GPX arrays
1463 * @param g the common draw object to use
1464 * @param mv the meta data to current displayed area
1465 */
1466 public void drawColorBar(Graphics2D g, MapView mv) {
1467 int w = mv.getWidth();
1468
1469 // set do default
1470 g.setComposite(AlphaComposite.SrcOver.derive(1.00f));
1471
1472 if (colored == ColorMode.HDOP) {
1473 hdopScale.drawColorBar(g, w-30, 50, 20, 100, 1.0);
1474 } else if (colored == ColorMode.VELOCITY) {
1475 SystemOfMeasurement som = SystemOfMeasurement.getSystemOfMeasurement();
1476 velocityScale.drawColorBar(g, w-30, 50, 20, 100, som.speedValue);
1477 } else if (colored == ColorMode.DIRECTION) {
1478 directionScale.drawColorBar(g, w-30, 50, 20, 100, 180.0/Math.PI);
1479 }
1480 }
1481
1482 @Override
1483 public void paintableInvalidated(PaintableInvalidationEvent event) {
1484 gpxLayerInvalidated = true;
1485 }
1486
1487 @Override
1488 public void detachFromMapView(MapViewEvent event) {
1489 SystemOfMeasurement.removeSoMChangeListener(this);
1490 layer.removeInvalidationListener(this);
1491 }
1492}
Note: See TracBrowser for help on using the repository browser.