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

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

Add a gap to the gpx line if the coordinates of a WayPoint are not known.

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