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

Last change on this file since 12167 was 12167, checked in by michael2402, 9 years ago

Make WayPoint implement ILatLon.

  • Property svn:eol-style set to native
File size: 59.6 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 if (!trkPnt.isLatLonKnown()) {
481 continue;
482 }
483 if (oldWp != null && trkPnt.time > oldWp.time) {
484 double vel = trkPnt.getCoor().greatCircleDistance(oldWp.getCoor())
485 / (trkPnt.time - oldWp.time);
486 velocities.add(vel);
487 }
488 oldWp = trkPnt;
489 }
490 }
491 Collections.sort(velocities);
492 if (velocities.isEmpty()) {
493 velocityScale.setRange(0, 120/3.6);
494 } else {
495 minval = velocities.get(velocities.size() / 20); // 5% percentile to remove outliers
496 maxval = velocities.get(velocities.size() * 19 / 20); // 95% percentile to remove outliers
497 velocityScale.setRange(minval, maxval);
498 }
499 } else if (colored == ColorMode.HDOP) {
500 for (Collection<WayPoint> segment : data.getLinesIterable(null)) {
501 for (WayPoint trkPnt : segment) {
502 Object val = trkPnt.get(GpxConstants.PT_HDOP);
503 if (val != null) {
504 double hdop = ((Float) val).doubleValue();
505 if (hdop > maxval) {
506 maxval = hdop;
507 }
508 if (hdop < minval) {
509 minval = hdop;
510 }
511 }
512 }
513 }
514 if (minval >= maxval) {
515 hdopScale.setRange(0, 100);
516 } else {
517 hdopScale.setRange(minval, maxval);
518 }
519 }
520 oldWp = null;
521 } else { // color mode not dynamic
522 velocityScale.setRange(0, colorTracksTune);
523 hdopScale.setRange(0, hdoprange);
524 }
525 double now = System.currentTimeMillis()/1000.0;
526 if (colored == ColorMode.TIME) {
527 Date[] bounds = data.getMinMaxTimeForAllTracks();
528 if (bounds.length >= 2) {
529 minval = bounds[0].getTime()/1000.0;
530 maxval = bounds[1].getTime()/1000.0;
531 } else {
532 minval = 0;
533 maxval = now;
534 }
535 dateScale.setRange(minval, maxval);
536 }
537
538 // Now the colors for all the points will be assigned
539 for (Collection<WayPoint> segment : data.getLinesIterable(null)) {
540 if (!forceLines) { // don't draw lines between segments, unless forced to
541 oldWp = null;
542 }
543 for (WayPoint trkPnt : segment) {
544 LatLon c = trkPnt.getCoor();
545 trkPnt.customColoring = neutralColor;
546 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
547 continue;
548 }
549 // now we are sure some color will be assigned
550 Color color = null;
551
552 if (colored == ColorMode.HDOP) {
553 Float hdop = (Float) trkPnt.get(GpxConstants.PT_HDOP);
554 color = hdopScale.getColor(hdop);
555 }
556 if (oldWp != null) { // other coloring modes need segment for calcuation
557 double dist = c.greatCircleDistance(oldWp.getCoor());
558 boolean noDraw = false;
559 switch (colored) {
560 case VELOCITY:
561 double dtime = trkPnt.time - oldWp.time;
562 if (dtime > 0) {
563 color = velocityScale.getColor(dist / dtime);
564 } else {
565 color = velocityScale.getNoDataColor();
566 }
567 break;
568 case DIRECTION:
569 double dirColor = oldWp.getCoor().bearing(trkPnt.getCoor());
570 color = directionScale.getColor(dirColor);
571 break;
572 case TIME:
573 double t = trkPnt.time;
574 // skip bad timestamps and very short tracks
575 if (t > 0 && t <= now && maxval - minval > minTrackDurationForTimeColoring) {
576 color = dateScale.getColor(t);
577 } else {
578 color = dateScale.getNoDataColor();
579 }
580 break;
581 default: // Do nothing
582 }
583 if (!noDraw && (maxLineLength == -1 || dist <= maxLineLength)) {
584 trkPnt.drawLine = true;
585 double bearing = oldWp.getCoor().bearing(trkPnt.getCoor());
586 trkPnt.dir = ((int) (bearing / Math.PI * 4 + 1.5)) % 8;
587 } else {
588 trkPnt.drawLine = false;
589 }
590 } else { // make sure we reset outdated data
591 trkPnt.drawLine = false;
592 color = neutralColor;
593 }
594 if (color != null) {
595 trkPnt.customColoring = color;
596 }
597 oldWp = trkPnt;
598 }
599 }
600
601 // heat mode
602 if (ColorMode.HEATMAP == colored) {
603
604 // get new user color map and refresh visibility level
605 heatMapLutColor = createColorLut(heatMapDrawLowerLimit,
606 selectColorMap(neutralColor != null ? neutralColor : Color.WHITE, heatMapDrawColorTableIdx));
607
608 // force redraw of image
609 heatMapMapViewState = null;
610 }
611
612 computeCacheInSync = true;
613 }
614
615 /**
616 * Draw all GPX ways segments
617 * @param g the common draw object to use
618 * @param mv the meta data to current displayed area
619 * @param visibleSegments segments visible in the current scope of mv
620 */
621 private void drawLines(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
622 if (lines) {
623 Point old = null;
624 for (WayPoint trkPnt : visibleSegments) {
625 if (!trkPnt.isLatLonKnown()) {
626 continue;
627 }
628 Point screen = mv.getPoint(trkPnt.getEastNorth());
629 // skip points that are on the same screenposition
630 if (trkPnt.drawLine && old != null && ((old.x != screen.x) || (old.y != screen.y))) {
631 g.setColor(trkPnt.customColoring);
632 g.drawLine(old.x, old.y, screen.x, screen.y);
633 }
634 old = screen;
635 }
636 }
637 }
638
639 /**
640 * Draw all GPX arrays
641 * @param g the common draw object to use
642 * @param mv the meta data to current displayed area
643 * @param visibleSegments segments visible in the current scope of mv
644 */
645 private void drawArrows(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
646 /****************************************************************
647 ********** STEP 3b - DRAW NICE ARROWS **************************
648 ****************************************************************/
649 if (lines && direction && !alternateDirection) {
650 Point old = null;
651 Point oldA = null; // last arrow painted
652 for (WayPoint trkPnt : visibleSegments) {
653 if (!trkPnt.isLatLonKnown()) {
654 continue;
655 }
656 if (trkPnt.drawLine) {
657 Point screen = mv.getPoint(trkPnt.getEastNorth());
658 // skip points that are on the same screenposition
659 if (old != null
660 && (oldA == null || screen.x < oldA.x - delta || screen.x > oldA.x + delta
661 || screen.y < oldA.y - delta || screen.y > oldA.y + delta)) {
662 g.setColor(trkPnt.customColoring);
663 double t = Math.atan2((double) screen.y - old.y, (double) screen.x - old.x) + Math.PI;
664 g.drawLine(screen.x, screen.y, (int) (screen.x + 10 * Math.cos(t - PHI)),
665 (int) (screen.y + 10 * Math.sin(t - PHI)));
666 g.drawLine(screen.x, screen.y, (int) (screen.x + 10 * Math.cos(t + PHI)),
667 (int) (screen.y + 10 * Math.sin(t + PHI)));
668 oldA = screen;
669 }
670 old = screen;
671 }
672 } // end for trkpnt
673 }
674
675 /****************************************************************
676 ********** STEP 3c - DRAW FAST ARROWS **************************
677 ****************************************************************/
678 if (lines && direction && alternateDirection) {
679 Point old = null;
680 Point oldA = null; // last arrow painted
681 for (WayPoint trkPnt : visibleSegments) {
682 LatLon c = trkPnt.getCoor();
683 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
684 continue;
685 }
686 if (trkPnt.drawLine) {
687 Point screen = mv.getPoint(trkPnt.getEastNorth());
688 // skip points that are on the same screenposition
689 if (old != null
690 && (oldA == null || screen.x < oldA.x - delta || screen.x > oldA.x + delta
691 || screen.y < oldA.y - delta || screen.y > oldA.y + delta)) {
692 g.setColor(trkPnt.customColoring);
693 g.drawLine(screen.x, screen.y, screen.x + dir[trkPnt.dir][0], screen.y
694 + dir[trkPnt.dir][1]);
695 g.drawLine(screen.x, screen.y, screen.x + dir[trkPnt.dir][2], screen.y
696 + dir[trkPnt.dir][3]);
697 oldA = screen;
698 }
699 old = screen;
700 }
701 } // end for trkpnt
702 }
703 }
704
705 /**
706 * Draw all GPX points
707 * @param g the common draw object to use
708 * @param mv the meta data to current displayed area
709 * @param visibleSegments segments visible in the current scope of mv
710 */
711 private void drawPoints(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
712 /****************************************************************
713 ********** STEP 3d - DRAW LARGE POINTS AND HDOP CIRCLE *********
714 ****************************************************************/
715 if (large || hdopCircle) {
716 final int halfSize = largesize/2;
717 for (WayPoint trkPnt : visibleSegments) {
718 LatLon c = trkPnt.getCoor();
719 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
720 continue;
721 }
722 Point screen = mv.getPoint(trkPnt.getEastNorth());
723
724
725 if (hdopCircle && trkPnt.get(GpxConstants.PT_HDOP) != null) {
726 // hdop value
727 float hdop = (Float) trkPnt.get(GpxConstants.PT_HDOP);
728 if (hdop < 0) {
729 hdop = 0;
730 }
731 Color customColoringTransparent = hdopAlpha < 0 ? trkPnt.customColoring :
732 new Color((trkPnt.customColoring.getRGB() & 0x00ffffff) | (hdopAlpha << 24), true);
733 g.setColor(customColoringTransparent);
734 // hdop circles
735 int hdopp = mv.getPoint(new LatLon(
736 trkPnt.getCoor().lat(),
737 trkPnt.getCoor().lon() + 2d*6*hdop*360/40000000d)).x - screen.x;
738 g.drawArc(screen.x-hdopp/2, screen.y-hdopp/2, hdopp, hdopp, 0, 360);
739 }
740 if (large) {
741 // color the large GPS points like the gps lines
742 if (trkPnt.customColoring != null) {
743 Color customColoringTransparent = largePointAlpha < 0 ? trkPnt.customColoring :
744 new Color((trkPnt.customColoring.getRGB() & 0x00ffffff) | (largePointAlpha << 24), true);
745
746 g.setColor(customColoringTransparent);
747 }
748 g.fillRect(screen.x-halfSize, screen.y-halfSize, largesize, largesize);
749 }
750 } // end for trkpnt
751 } // end if large || hdopcircle
752
753 /****************************************************************
754 ********** STEP 3e - DRAW SMALL POINTS FOR LINES ***************
755 ****************************************************************/
756 if (!large && lines) {
757 g.setColor(neutralColor);
758 for (WayPoint trkPnt : visibleSegments) {
759 LatLon c = trkPnt.getCoor();
760 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
761 continue;
762 }
763 if (!trkPnt.drawLine) {
764 Point screen = mv.getPoint(trkPnt.getEastNorth());
765 g.drawRect(screen.x, screen.y, 0, 0);
766 }
767 } // end for trkpnt
768 } // end if large
769
770 /****************************************************************
771 ********** STEP 3f - DRAW SMALL POINTS INSTEAD OF LINES ********
772 ****************************************************************/
773 if (!large && !lines) {
774 g.setColor(neutralColor);
775 for (WayPoint trkPnt : visibleSegments) {
776 LatLon c = trkPnt.getCoor();
777 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
778 continue;
779 }
780 Point screen = mv.getPoint(trkPnt.getEastNorth());
781 g.setColor(trkPnt.customColoring);
782 g.drawRect(screen.x, screen.y, 0, 0);
783 } // end for trkpnt
784 } // end if large
785 }
786
787 /**
788 * Draw GPX lines by using alpha blending
789 * @param g the common draw object to use
790 * @param mv the meta data to current displayed area
791 * @param visibleSegments segments visible in the current scope of mv
792 * @param layerAlpha the color alpha value set for that operation
793 */
794 private void drawLinesAlpha(Graphics2D g, MapView mv, List<WayPoint> visibleSegments, float layerAlpha) {
795
796 // 1st. backup the paint environment ----------------------------------
797 Composite oldComposite = g.getComposite();
798 Stroke oldStroke = g.getStroke();
799 Paint oldPaint = g.getPaint();
800
801 // 2nd. determine current scale factors -------------------------------
802
803 // adjust global settings
804 final int globalLineWidth = Utils.clamp(lineWidth, 1, 20);
805
806 // cache scale of view
807 final double zoomScale = mv.getDist100Pixel() / 50.0f;
808
809 // 3rd. determine current paint parameters -----------------------------
810
811 // alpha value is based on zoom and line with combined with global layer alpha
812 float theLineAlpha = (float) Utils.clamp((0.50 / zoomScale) / (globalLineWidth + 1), 0.01, 0.50) * layerAlpha;
813 final int theLineWith = (int) (lineWidth / zoomScale) + 1;
814
815 // 4th setup virtual paint area ----------------------------------------
816
817 // set line format and alpha channel for all overlays (more lines -> few overlap -> more transparency)
818 g.setStroke(new BasicStroke(theLineWith, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
819 g.setComposite(AlphaComposite.SrcOver.derive(theLineAlpha));
820
821 // last used / calculated entries
822 Point lastPaintPnt = null;
823
824 // 5th draw the layer ---------------------------------------------------
825
826 // for all points
827 for (WayPoint trkPnt : visibleSegments) {
828
829 // transform coordinates
830 final Point paintPnt = mv.getPoint(trkPnt.getEastNorth());
831
832 // skip single points
833 if (lastPaintPnt != null && trkPnt.drawLine && !lastPaintPnt.equals(paintPnt)) {
834
835 // set different color
836 g.setColor(trkPnt.customColoring);
837
838 // draw it
839 g.drawLine(lastPaintPnt.x, lastPaintPnt.y, paintPnt.x, paintPnt.y);
840 }
841
842 lastPaintPnt = paintPnt;
843 }
844
845 // @last restore modified paint environment -----------------------------
846 g.setPaint(oldPaint);
847 g.setStroke(oldStroke);
848 g.setComposite(oldComposite);
849 }
850
851 /**
852 * Generates a linear gradient map image
853 *
854 * @param width image width
855 * @param height image height
856 * @param colors 1..n color descriptions
857 * @return image object
858 */
859 protected static BufferedImage createImageGradientMap(int width, int height, Color... colors) {
860
861 // create image an paint object
862 final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
863 final Graphics2D g = img.createGraphics();
864
865 float[] fract = new float[ colors.length ];
866
867 // distribute fractions (define position of color in map)
868 for (int i = 0; i < colors.length; ++i) {
869 fract[i] = i * (1.0f / colors.length);
870 }
871
872 // draw the gradient map
873 LinearGradientPaint gradient = new LinearGradientPaint(0, 0, width, height, fract, colors,
874 MultipleGradientPaint.CycleMethod.NO_CYCLE);
875 g.setPaint(gradient);
876 g.fillRect(0, 0, width, height);
877 g.dispose();
878
879 // access it via raw interface
880 return img;
881 }
882
883 /**
884 * Creates a distributed colormap by linear blending between colors
885 * @param lowerLimit lower limit for first visible color
886 * @param colors 1..n colors
887 * @return array of Color objects
888 */
889 protected static Color[] createColorLut(int lowerLimit, Color... colors) {
890
891 // number of lookup entries
892 final int tableSize = 256;
893
894 // access it via raw interface
895 final Raster imgRaster = createImageGradientMap(tableSize, 1, colors).getData();
896
897 // the pixel storage
898 int[] pixel = new int[1];
899
900 Color[] colorTable = new Color[tableSize];
901
902 // map the range 0..255 to 0..pi/2
903 final double mapTo90Deg = Math.PI / 2.0 / 255.0;
904
905 // create the lookup table
906 for (int i = 0; i < tableSize; i++) {
907
908 // get next single pixel
909 imgRaster.getDataElements(i, 0, pixel);
910
911 // get color and map
912 Color c = new Color(pixel[0]);
913
914 // smooth alpha like sin curve
915 int alpha = (i > lowerLimit) ? (int) (Math.sin((i-lowerLimit) * mapTo90Deg) * 255) : 0;
916
917 // alpha with pre-offset, first color -> full transparent
918 alpha = alpha > 0 ? (20 + alpha) : 0;
919
920 // shrink to maximum bound
921 if (alpha > 255) {
922 alpha = 255;
923 }
924
925 // increase transparency for higher values ( avoid big saturation )
926 if (i > 240 && 255 == alpha) {
927 alpha -= (i - 240);
928 }
929
930 // fill entry in table, assign a alpha value
931 colorTable[i] = new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha);
932 }
933
934 // transform into lookup table
935 return colorTable;
936 }
937
938 /**
939 * Creates a darker color
940 * @param in Color object
941 * @param adjust darker adjustment amount
942 * @return new Color
943 */
944 protected static Color darkerColor(Color in, float adjust) {
945
946 final float r = (float) in.getRed()/255;
947 final float g = (float) in.getGreen()/255;
948 final float b = (float) in.getBlue()/255;
949
950 return new Color(r*adjust, g*adjust, b*adjust);
951 }
952
953 /**
954 * Creates a colormap by using a static color map with 1..n colors (RGB 0.0 ..1.0)
955 * @param str the filename (without extension) to look for into data/gpx
956 * @return the parsed colormap
957 */
958 protected static Color[] createColorFromResource(String str) {
959
960 // create resource string
961 final String colorFile = "resource://data/gpx/" + str + ".txt";
962
963 List<Color> colorList = new ArrayList<>();
964
965 // try to load the file
966 try (CachedFile cf = new CachedFile(colorFile); BufferedReader br = cf.getContentReader()) {
967
968 String line;
969
970 // process lines
971 while ((line = br.readLine()) != null) {
972
973 // use comma as separator
974 String[] column = line.split(",");
975
976 // empty or comment line
977 if (column.length < 3 || column[0].startsWith("#")) {
978 continue;
979 }
980
981 // extract RGB value
982 float r = Float.parseFloat(column[0]);
983 float g = Float.parseFloat(column[1]);
984 float b = Float.parseFloat(column[2]);
985
986 // some color tables are 0..1.0 and some 0.255
987 float scale = (r < 1 && g < 1 && b < 1) ? 1 : 255;
988
989 colorList.add(new Color(r/scale, g/scale, b/scale));
990 }
991 } catch (IOException e) {
992 throw new JosmRuntimeException(e);
993 }
994
995 // fallback if empty or failed
996 if (colorList.isEmpty()) {
997 colorList.add(Color.BLACK);
998 colorList.add(Color.WHITE);
999 } else {
1000 // add additional darker elements to end of list
1001 final Color lastColor = colorList.get(colorList.size() - 1);
1002 colorList.add(darkerColor(lastColor, 0.975f));
1003 colorList.add(darkerColor(lastColor, 0.950f));
1004 }
1005
1006 return createColorLut(0, colorList.toArray(new Color[ colorList.size() ]));
1007 }
1008
1009 /**
1010 * Returns the next user color map
1011 *
1012 * @param userColor - default or fallback user color
1013 * @param tableIdx - selected user color index
1014 * @return color array
1015 */
1016 protected static Color[] selectColorMap(Color userColor, int tableIdx) {
1017
1018 // generate new user color map ( dark, user color, white )
1019 Color[] userColor1 = createColorLut(0, userColor.darker(), userColor, userColor.brighter(), Color.WHITE);
1020
1021 // generate new user color map ( white -> color )
1022 Color[] userColor2 = createColorLut(0, Color.WHITE, Color.WHITE, userColor);
1023
1024 // generate new user color map
1025 Color[] colorTrafficLights = createColorLut(0, Color.WHITE, Color.GREEN.darker(), Color.YELLOW, Color.RED);
1026
1027 // decide what, keep order is sync with setting on GUI
1028 Color[][] lut = {
1029 userColor1,
1030 userColor2,
1031 colorTrafficLights,
1032 heatMapLutColorJosmInferno,
1033 heatMapLutColorJosmViridis,
1034 heatMapLutColorJosmBrown2Green,
1035 heatMapLutColorJosmRed2Blue
1036 };
1037
1038 // default case
1039 Color[] nextUserColor = userColor1;
1040
1041 // select by index
1042 if (tableIdx < lut.length) {
1043 nextUserColor = lut[ tableIdx ];
1044 }
1045
1046 // adjust color map
1047 return nextUserColor;
1048 }
1049
1050 /**
1051 * Generates a Icon
1052 *
1053 * @param userColor selected user color
1054 * @param tableIdx tabled index
1055 * @param size size of the image
1056 * @return a image icon that shows the
1057 */
1058 public static ImageIcon getColorMapImageIcon(Color userColor, int tableIdx, int size) {
1059 return new ImageIcon(createImageGradientMap(size, size, selectColorMap(userColor, tableIdx)));
1060 }
1061
1062 /**
1063 * Draw gray heat map with current Graphics2D setting
1064 * @param gB the common draw object to use
1065 * @param mv the meta data to current displayed area
1066 * @param listSegm segments visible in the current scope of mv
1067 * @param foreComp composite use to draw foreground objects
1068 * @param foreStroke stroke use to draw foreground objects
1069 * @param backComp composite use to draw background objects
1070 * @param backStroke stroke use to draw background objects
1071 */
1072 private void drawHeatGrayLineMap(Graphics2D gB, MapView mv, List<WayPoint> listSegm,
1073 Composite foreComp, Stroke foreStroke,
1074 Composite backComp, Stroke backStroke) {
1075
1076 // draw foreground
1077 boolean drawForeground = foreComp != null && foreStroke != null;
1078
1079 // set initial values
1080 gB.setStroke(backStroke); gB.setComposite(backComp);
1081
1082 // get last point in list
1083 final WayPoint lastPnt = !listSegm.isEmpty() ? listSegm.get(listSegm.size() - 1) : null;
1084
1085 // for all points, draw single lines by using optimized drawing
1086 for (WayPoint trkPnt : listSegm) {
1087
1088 // get transformed coordinates
1089 final Point paintPnt = mv.getPoint(trkPnt.getEastNorth());
1090
1091 // end of line segment or end of list reached
1092 if (!trkPnt.drawLine || (lastPnt == trkPnt)) {
1093
1094 // convert to primitive type
1095 final int[] polyXArr = heatMapPolyX.stream().mapToInt(Integer::intValue).toArray();
1096 final int[] polyYArr = heatMapPolyY.stream().mapToInt(Integer::intValue).toArray();
1097
1098 // a.) draw background
1099 gB.drawPolyline(polyXArr, polyYArr, polyXArr.length);
1100
1101 // b.) draw extra foreground
1102 if (drawForeground && heatMapDrawExtraLine) {
1103
1104 gB.setStroke(foreStroke); gB.setComposite(foreComp);
1105 gB.drawPolyline(polyXArr, polyYArr, polyXArr.length);
1106 gB.setStroke(backStroke); gB.setComposite(backComp);
1107 }
1108
1109 // drop used points
1110 heatMapPolyX.clear(); heatMapPolyY.clear();
1111 }
1112
1113 // store only the integer part (make sense because pixel is 1:1 here)
1114 heatMapPolyX.add((int) paintPnt.getX());
1115 heatMapPolyY.add((int) paintPnt.getY());
1116 }
1117 }
1118
1119 /**
1120 * Map the gray map to heat map and draw them with current Graphics2D setting
1121 * @param g the common draw object to use
1122 * @param imgGray gray scale input image
1123 * @param sampleRaster the line with for drawing
1124 * @param outlineWidth line width for outlines
1125 */
1126 private void drawHeatMapGrayMap(Graphics2D g, BufferedImage imgGray, int sampleRaster, int outlineWidth) {
1127
1128 final int[] imgPixels = ((DataBufferInt) imgGray.getRaster().getDataBuffer()).getData();
1129
1130 // samples offset and bounds are scaled with line width derived from zoom level
1131 final int offX = Math.max(1, sampleRaster);
1132 final int offY = Math.max(1, sampleRaster);
1133
1134 final int maxPixelX = imgGray.getWidth();
1135 final int maxPixelY = imgGray.getHeight();
1136
1137 // always full or outlines at big samples rasters
1138 final boolean drawOutlines = (outlineWidth > 0) && ((0 == sampleRaster) || (sampleRaster > 10));
1139
1140 // backup stroke
1141 final Stroke oldStroke = g.getStroke();
1142
1143 // use basic stroke for outlines and default transparency
1144 g.setStroke(new BasicStroke(outlineWidth));
1145
1146 int lastPixelX = 0;
1147 int lastPixelColor = 0;
1148
1149 // resample gray scale image with line linear weight of next sample in line
1150 // process each line and draw pixels / rectangles with same color with one operations
1151 for (int y = 0; y < maxPixelY; y += offY) {
1152
1153 // the lines offsets
1154 final int lastLineOffset = maxPixelX * (y+0);
1155 final int nextLineOffset = maxPixelX * (y+1);
1156
1157 for (int x = 0; x < maxPixelX; x += offX) {
1158
1159 int thePixelColor = 0; int thePixelCount = 0;
1160
1161 // sample the image (it is gray scale)
1162 int offset = lastLineOffset + x;
1163
1164 // merge next pixels of window of line
1165 for (int k = 0; k < offX && (offset + k) < nextLineOffset; k++) {
1166 thePixelColor += imgPixels[offset+k] & 0xFF;
1167 thePixelCount++;
1168 }
1169
1170 // mean value
1171 thePixelColor = thePixelCount > 0 ? (thePixelColor / thePixelCount) : 0;
1172
1173 // restart -> use initial sample
1174 if (0 == x) {
1175 lastPixelX = 0; lastPixelColor = thePixelColor - 1;
1176 }
1177
1178 boolean bDrawIt = false;
1179
1180 // when one of segment is mapped to black
1181 bDrawIt = bDrawIt || (lastPixelColor == 0) || (thePixelColor == 0);
1182
1183 // different color
1184 bDrawIt = bDrawIt || (Math.abs(lastPixelColor-thePixelColor) > 0);
1185
1186 // when line is finished draw always
1187 bDrawIt = bDrawIt || (y >= (maxPixelY-offY));
1188
1189 if (bDrawIt) {
1190
1191 // draw only foreground pixels
1192 if (lastPixelColor > 0) {
1193
1194 // gray to RGB mapping
1195 g.setColor(heatMapLutColor[ lastPixelColor ]);
1196
1197 // box from from last Y pixel to current pixel
1198 if (drawOutlines) {
1199 g.drawRect(lastPixelX, y, offX + x - lastPixelX, offY);
1200 } else {
1201 g.fillRect(lastPixelX, y, offX + x - lastPixelX, offY);
1202 }
1203 }
1204
1205 // restart detection
1206 lastPixelX = x; lastPixelColor = thePixelColor;
1207 }
1208 }
1209 }
1210
1211 // recover
1212 g.setStroke(oldStroke);
1213 }
1214
1215 /**
1216 * Collect and draw GPS segments and displays a heat-map
1217 * @param g the common draw object to use
1218 * @param mv the meta data to current displayed area
1219 * @param visibleSegments segments visible in the current scope of mv
1220 */
1221 private void drawHeatMap(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
1222
1223 // get bounds of screen image and projection, zoom and adjust input parameters
1224 final Rectangle screenBounds = new Rectangle(mv.getWidth(), mv.getHeight());
1225 final MapViewState mapViewState = mv.getState();
1226 final double zoomScale = mv.getDist100Pixel() / 50.0f;
1227
1228 // adjust global settings ( zero = default line width )
1229 final int globalLineWidth = (0 == lineWidth) ? 1 : Utils.clamp(lineWidth, 1, 20);
1230
1231 // 1st setup virtual paint area ----------------------------------------
1232
1233 // new image buffer needed
1234 final boolean imageSetup = null == heatMapImgGray || !heatMapCacheScreenBounds.equals(screenBounds);
1235
1236 // screen bounds changed, need new image buffer ?
1237 if (imageSetup) {
1238 // we would use a "pure" grayscale image, but there is not efficient way to map gray scale values to RGB)
1239 heatMapImgGray = new BufferedImage(screenBounds.width, screenBounds.height, BufferedImage.TYPE_INT_ARGB);
1240 heatMapGraph2d = heatMapImgGray.createGraphics();
1241 heatMapGraph2d.setBackground(new Color(0, 0, 0, 255));
1242 heatMapGraph2d.setColor(Color.WHITE);
1243
1244 // fast draw ( maybe help or not )
1245 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
1246 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
1247 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
1248 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
1249 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1250 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
1251 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
1252
1253 // cache it
1254 heatMapCacheScreenBounds = screenBounds;
1255 }
1256
1257 // 2nd. determine current scale factors -------------------------------
1258
1259 // the line width (foreground: draw extra small footprint line of track)
1260 int lineWidthB = (int) Math.max(1.5f * (globalLineWidth / zoomScale) + 1, 2);
1261 int lineWidthF = lineWidthB > 2 ? (globalLineWidth - 1) : 0;
1262
1263 // global alpha adjustment
1264 float lineAlpha = (float) Utils.clamp((0.40 / zoomScale) / (globalLineWidth + 1), 0.01, 0.40);
1265
1266 // adjust 0.15 .. 1.85
1267 float scaleAlpha = 1.0f + ((heatMapDrawGain/10.0f) * 0.85f);
1268
1269 // add to calculated values
1270 float lineAlphaBPoint = (float) Utils.clamp((lineAlpha * 0.65) * scaleAlpha, 0.001, 0.90);
1271 float lineAlphaBLine = (float) Utils.clamp((lineAlpha * 1.00) * scaleAlpha, 0.001, 0.90);
1272 float lineAlphaFLine = (float) Utils.clamp((lineAlpha / 1.50) * scaleAlpha, 0.001, 0.90);
1273
1274 // 3rd Calculate the heat map data by draw GPX traces with alpha value ----------
1275
1276 // recalculation of image needed
1277 final boolean imageRecalc = !mapViewState.equalsInWindow(heatMapMapViewState)
1278 || gpxLayerInvalidated
1279 || heatMapCacheLineWith != globalLineWidth;
1280
1281 // need re-generation of gray image ?
1282 if (imageSetup || imageRecalc) {
1283
1284 // clear background
1285 heatMapGraph2d.clearRect(0, 0, heatMapImgGray.getWidth(), heatMapImgGray.getHeight());
1286
1287 // point or line blending
1288 if (heatMapDrawPointMode) {
1289 heatMapGraph2d.setComposite(AlphaComposite.SrcOver.derive(lineAlphaBPoint));
1290 drawHeatGrayDotMap(heatMapGraph2d, mv, visibleSegments, lineWidthB);
1291
1292 } else {
1293 drawHeatGrayLineMap(heatMapGraph2d, mv, visibleSegments,
1294 lineWidthF > 1 ? AlphaComposite.SrcOver.derive(lineAlphaFLine) : null,
1295 new BasicStroke(lineWidthF, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND),
1296 AlphaComposite.SrcOver.derive(lineAlphaBLine),
1297 new BasicStroke(lineWidthB, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
1298 }
1299
1300 // remember draw parameter
1301 heatMapMapViewState = mapViewState;
1302 heatMapCacheLineWith = globalLineWidth;
1303 gpxLayerInvalidated = false;
1304 }
1305
1306 // 4th. Draw data on target layer, map data via color lookup table --------------
1307 drawHeatMapGrayMap(g, heatMapImgGray, lineWidthB > 2 ? (int) (lineWidthB*1.25f) : 1, lineWidth > 2 ? (lineWidth - 2) : 1);
1308 }
1309
1310 /**
1311 * Draw a dotted heat map
1312 *
1313 * @param gB the common draw object to use
1314 * @param mv the meta data to current displayed area
1315 * @param listSegm segments visible in the current scope of mv
1316 * @param drawSize draw size of draw element
1317 */
1318 private static void drawHeatGrayDotMap(Graphics2D gB, MapView mv, List<WayPoint> listSegm, int drawSize) {
1319
1320 // typical rendering rate -> use realtime preview instead of accurate display
1321 final double maxSegm = 25_000, nrSegms = listSegm.size();
1322
1323 // determine random drop rate
1324 final double randomDrop = Math.min(nrSegms > maxSegm ? (nrSegms - maxSegm) / nrSegms : 0, 0.70f);
1325
1326 // http://www.nstb.tc.faa.gov/reports/PAN94_0716.pdf#page=22
1327 // Global Average Position Domain Accuracy, typical -> not worst case !
1328 // < 4.218 m Vertical
1329 // < 2.168 m Horizontal
1330 final double pixelRmsX = (100 / mv.getDist100Pixel()) * 2.168;
1331 final double pixelRmsY = (100 / mv.getDist100Pixel()) * 4.218;
1332
1333 Point lastPnt = null;
1334
1335 // for all points, draw single lines
1336 for (WayPoint trkPnt : listSegm) {
1337
1338 // get transformed coordinates
1339 final Point paintPnt = mv.getPoint(trkPnt.getEastNorth());
1340
1341 // end of line segment or end of list reached
1342 if (trkPnt.drawLine && null != lastPnt) {
1343 drawHeatSurfaceLine(gB, paintPnt, lastPnt, drawSize, pixelRmsX, pixelRmsY, randomDrop);
1344 }
1345
1346 // remember
1347 lastPnt = paintPnt;
1348 }
1349 }
1350
1351 /**
1352 * Draw a dotted surface line
1353 *
1354 * @param g the common draw object to use
1355 * @param fromPnt start point
1356 * @param toPnt end point
1357 * @param drawSize size of draw elements
1358 * @param rmsSizeX RMS size of circle for X (width)
1359 * @param rmsSizeY RMS size of circle for Y (height)
1360 * @param dropRate Pixel render drop rate
1361 */
1362 private static void drawHeatSurfaceLine(Graphics2D g,
1363 Point fromPnt, Point toPnt, int drawSize, double rmsSizeX, double rmsSizeY, double dropRate) {
1364
1365 // collect frequently used items
1366 final int fromX = (int) fromPnt.getX(); final int deltaX = (int) (toPnt.getX() - fromX);
1367 final int fromY = (int) fromPnt.getY(); final int deltaY = (int) (toPnt.getY() - fromY);
1368
1369 // use same random values for each point
1370 final Random heatMapRandom = new Random(fromX+fromY+deltaX+deltaY);
1371
1372 // cache distance between start and end point
1373 final int dist = (int) Math.abs(fromPnt.distance(toPnt));
1374
1375 // number of increment ( fill wide distance tracks )
1376 double scaleStep = Math.max(1.0f / dist, dist > 100 ? 0.10f : 0.20f);
1377
1378 // number of additional random points
1379 int rounds = Math.min(drawSize/2, 1)+1;
1380
1381 // decrease random noise at high drop rate ( more accurate draw of fewer points )
1382 rmsSizeX *= (1.0d - dropRate);
1383 rmsSizeY *= (1.0d - dropRate);
1384
1385 double scaleVal = 0;
1386
1387 // interpolate line draw ( needs separate point instead of line )
1388 while (scaleVal < (1.0d-0.0001d)) {
1389
1390 // get position
1391 final double pntX = fromX + scaleVal * deltaX;
1392 final double pntY = fromY + scaleVal * deltaY;
1393
1394 // add random distribution around sampled point
1395 for (int k = 0; k < rounds; k++) {
1396
1397 // add error distribution, first point with less error
1398 int x = (int) (pntX + heatMapRandom.nextGaussian() * (k > 0 ? rmsSizeX : rmsSizeX/4));
1399 int y = (int) (pntY + heatMapRandom.nextGaussian() * (k > 0 ? rmsSizeY : rmsSizeY/4));
1400
1401 // draw it, even drop is requested
1402 if (heatMapRandom.nextDouble() >= dropRate) {
1403 g.fillRect(x-drawSize, y-drawSize, drawSize, drawSize);
1404 }
1405 }
1406 scaleVal += scaleStep;
1407 }
1408 }
1409
1410 /**
1411 * Apply default color configuration to way segments
1412 * @param visibleSegments segments visible in the current scope of mv
1413 */
1414 private void fixColors(List<WayPoint> visibleSegments) {
1415 for (WayPoint trkPnt : visibleSegments) {
1416 if (trkPnt.customColoring == null) {
1417 trkPnt.customColoring = neutralColor;
1418 }
1419 }
1420 }
1421
1422 /**
1423 * Check cache validity set necessary flags
1424 */
1425 private void checkCache() {
1426 // CHECKSTYLE.OFF: BooleanExpressionComplexity
1427 if ((computeCacheMaxLineLengthUsed != maxLineLength)
1428 || (computeCacheColored != colored)
1429 || (computeCacheColorTracksTune != colorTracksTune)
1430 || (computeCacheColorDynamic != colorModeDynamic)
1431 || (computeCacheHeatMapDrawColorTableIdx != heatMapDrawColorTableIdx)
1432 || (!neutralColor.equals(computeCacheColorUsed)
1433 || (computeCacheHeatMapDrawPointMode != heatMapDrawPointMode)
1434 || (computeCacheHeatMapDrawGain != heatMapDrawGain))
1435 || (computeCacheHeatMapDrawLowerLimit != heatMapDrawLowerLimit)
1436 ) {
1437 // CHECKSTYLE.ON: BooleanExpressionComplexity
1438 computeCacheMaxLineLengthUsed = maxLineLength;
1439 computeCacheInSync = false;
1440 computeCacheColorUsed = neutralColor;
1441 computeCacheColored = colored;
1442 computeCacheColorTracksTune = colorTracksTune;
1443 computeCacheColorDynamic = colorModeDynamic;
1444 computeCacheHeatMapDrawColorTableIdx = heatMapDrawColorTableIdx;
1445 computeCacheHeatMapDrawPointMode = heatMapDrawPointMode;
1446 computeCacheHeatMapDrawGain = heatMapDrawGain;
1447 computeCacheHeatMapDrawLowerLimit = heatMapDrawLowerLimit;
1448 }
1449 }
1450
1451 /**
1452 * callback when data is changed, invalidate cached configuration parameters
1453 */
1454 public void dataChanged() {
1455 computeCacheInSync = false;
1456 }
1457
1458 /**
1459 * Draw all GPX arrays
1460 * @param g the common draw object to use
1461 * @param mv the meta data to current displayed area
1462 */
1463 public void drawColorBar(Graphics2D g, MapView mv) {
1464 int w = mv.getWidth();
1465
1466 // set do default
1467 g.setComposite(AlphaComposite.SrcOver.derive(1.00f));
1468
1469 if (colored == ColorMode.HDOP) {
1470 hdopScale.drawColorBar(g, w-30, 50, 20, 100, 1.0);
1471 } else if (colored == ColorMode.VELOCITY) {
1472 SystemOfMeasurement som = SystemOfMeasurement.getSystemOfMeasurement();
1473 velocityScale.drawColorBar(g, w-30, 50, 20, 100, som.speedValue);
1474 } else if (colored == ColorMode.DIRECTION) {
1475 directionScale.drawColorBar(g, w-30, 50, 20, 100, 180.0/Math.PI);
1476 }
1477 }
1478
1479 @Override
1480 public void paintableInvalidated(PaintableInvalidationEvent event) {
1481 gpxLayerInvalidated = true;
1482 }
1483
1484 @Override
1485 public void detachFromMapView(MapViewEvent event) {
1486 SystemOfMeasurement.removeSoMChangeListener(this);
1487 layer.removeInvalidationListener(this);
1488 }
1489}
Note: See TracBrowser for help on using the repository browser.