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

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

Fix #14847: Fix reload of colors if data was added to/removed from gpx layer.

  • Property svn:eol-style set to native
File size: 59.9 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.GpxData.GpxDataChangeEvent;
43import org.openstreetmap.josm.data.gpx.GpxData.GpxDataChangeListener;
44import org.openstreetmap.josm.data.gpx.WayPoint;
45import org.openstreetmap.josm.data.preferences.ColorProperty;
46import org.openstreetmap.josm.gui.MapView;
47import org.openstreetmap.josm.gui.MapViewState;
48import org.openstreetmap.josm.gui.layer.GpxLayer;
49import org.openstreetmap.josm.gui.layer.MapViewGraphics;
50import org.openstreetmap.josm.gui.layer.MapViewPaintable;
51import org.openstreetmap.josm.gui.layer.MapViewPaintable.MapViewEvent;
52import org.openstreetmap.josm.gui.layer.MapViewPaintable.PaintableInvalidationEvent;
53import org.openstreetmap.josm.gui.layer.MapViewPaintable.PaintableInvalidationListener;
54import org.openstreetmap.josm.io.CachedFile;
55import org.openstreetmap.josm.tools.ColorScale;
56import org.openstreetmap.josm.tools.JosmRuntimeException;
57import org.openstreetmap.josm.tools.Utils;
58
59/**
60 * Class that helps to draw large set of GPS tracks with different colors and options
61 * @since 7319
62 */
63public class GpxDrawHelper implements SoMChangeListener, MapViewPaintable.LayerPainter, PaintableInvalidationListener, GpxDataChangeListener {
64
65 /**
66 * The color that is used for drawing GPX points.
67 * @since 10824
68 */
69 public static final ColorProperty DEFAULT_COLOR = new ColorProperty(marktr("gps point"), Color.magenta);
70
71 private final GpxData data;
72 private final GpxLayer layer;
73
74 // draw lines between points belonging to different segments
75 private boolean forceLines;
76 // use alpha blending for line draw
77 private boolean alphaLines;
78 // draw direction arrows on the lines
79 private boolean direction;
80 /** width of line for paint **/
81 private int lineWidth;
82 /** don't draw lines if longer than x meters **/
83 private int maxLineLength;
84 // draw lines
85 private boolean lines;
86 /** paint large dots for points **/
87 private boolean large;
88 private int largesize;
89 private boolean hdopCircle;
90 /** paint direction arrow with alternate math. may be faster **/
91 private boolean alternateDirection;
92 /** don't draw arrows nearer to each other than this **/
93 private int delta;
94 private double minTrackDurationForTimeColoring;
95
96 /** maximum value of displayed HDOP, minimum is 0 */
97 private int hdoprange;
98
99 private static final double PHI = Utils.toRadians(15);
100
101 //// Variables used only to check cache validity
102 private boolean computeCacheInSync;
103 private int computeCacheMaxLineLengthUsed;
104 private Color computeCacheColorUsed;
105 private boolean computeCacheColorDynamic;
106 private ColorMode computeCacheColored;
107 private int computeCacheColorTracksTune;
108 private int computeCacheHeatMapDrawColorTableIdx;
109 private boolean computeCacheHeatMapDrawPointMode;
110 private int computeCacheHeatMapDrawGain;
111 private int computeCacheHeatMapDrawLowerLimit;
112
113 //// Color-related fields
114 /** Mode of the line coloring **/
115 private ColorMode colored;
116 /** max speed for coloring - allows to tweak line coloring for different speed levels. **/
117 private int colorTracksTune;
118 private boolean colorModeDynamic;
119 private Color neutralColor;
120 private int largePointAlpha;
121
122 // default access is used to allow changing from plugins
123 private ColorScale velocityScale;
124 /** Colors (without custom alpha channel, if given) for HDOP painting. **/
125 private ColorScale hdopScale;
126 private ColorScale dateScale;
127 private ColorScale directionScale;
128
129 /** Opacity for hdop points **/
130 private int hdopAlpha;
131
132 // lookup array to draw arrows without doing any math
133 private static final int ll0 = 9;
134 private static final int sl4 = 5;
135 private static final int sl9 = 3;
136 private static final int[][] dir = {
137 {+sl4, +ll0, +ll0, +sl4}, {-sl9, +ll0, +sl9, +ll0},
138 {-ll0, +sl4, -sl4, +ll0}, {-ll0, -sl9, -ll0, +sl9},
139 {-sl4, -ll0, -ll0, -sl4}, {+sl9, -ll0, -sl9, -ll0},
140 {+ll0, -sl4, +sl4, -ll0}, {+ll0, +sl9, +ll0, -sl9}
141 };
142
143 /** heat map parameters **/
144
145 // enabled or not (override by settings)
146 private boolean heatMapEnabled;
147 // draw small extra line
148 private boolean heatMapDrawExtraLine;
149 // used index for color table (parameter)
150 private int heatMapDrawColorTableIdx;
151 // use point or line draw mode
152 private boolean heatMapDrawPointMode;
153 // extra gain > 0 or < 0 attenuation, 0 = default
154 private int heatMapDrawGain;
155 // do not draw elements with value lower than this limit
156 private int heatMapDrawLowerLimit;
157
158 // normal buffered image and draw object (cached)
159 private BufferedImage heatMapImgGray;
160 private Graphics2D heatMapGraph2d;
161
162 // some cached values
163 Rectangle heatMapCacheScreenBounds = new Rectangle();
164 MapViewState heatMapMapViewState;
165 int heatMapCacheLineWith;
166
167 // copied value for line drawing
168 private final List<Integer> heatMapPolyX = new ArrayList<>();
169 private final List<Integer> heatMapPolyY = new ArrayList<>();
170
171 // setup color maps used by heat map
172 private static Color[] heatMapLutColorJosmInferno = createColorFromResource("inferno");
173 private static Color[] heatMapLutColorJosmViridis = createColorFromResource("viridis");
174 private static Color[] heatMapLutColorJosmBrown2Green = createColorFromResource("brown2green");
175 private static Color[] heatMapLutColorJosmRed2Blue = createColorFromResource("red2blue");
176
177 // user defined heatmap color
178 private Color[] heatMapLutColor = createColorLut(0, Color.BLACK, Color.WHITE);
179
180 // The heat map was invalidated since the last draw.
181 private boolean gpxLayerInvalidated;
182
183 private void setupColors() {
184 hdopAlpha = Main.pref.getInteger("hdop.color.alpha", -1);
185 velocityScale = ColorScale.createHSBScale(256);
186 /** Colors (without custom alpha channel, if given) for HDOP painting. **/
187 hdopScale = ColorScale.createHSBScale(256).makeReversed().addTitle(tr("HDOP"));
188 dateScale = ColorScale.createHSBScale(256).addTitle(tr("Time"));
189 directionScale = ColorScale.createCyclicScale(256).setIntervalCount(4).addTitle(tr("Direction"));
190
191 systemOfMeasurementChanged(null, null);
192 }
193
194 @Override
195 public void systemOfMeasurementChanged(String oldSoM, String newSoM) {
196 SystemOfMeasurement som = SystemOfMeasurement.getSystemOfMeasurement();
197 velocityScale.addTitle(tr("Velocity, {0}", som.speedName));
198 layer.invalidate();
199 }
200
201 /**
202 * Different color modes
203 */
204 public enum ColorMode {
205 NONE, VELOCITY, HDOP, DIRECTION, TIME, HEATMAP;
206
207 static ColorMode fromIndex(final int index) {
208 return values()[index];
209 }
210
211 int toIndex() {
212 return Arrays.asList(values()).indexOf(this);
213 }
214 }
215
216 /**
217 * Constructs a new {@code GpxDrawHelper}.
218 * @param gpxLayer The layer to draw
219 * @since 12157
220 */
221 public GpxDrawHelper(GpxLayer gpxLayer) {
222 layer = gpxLayer;
223 data = gpxLayer.data;
224 data.addChangeListener(this);
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 if (hdopCircle && trkPnt.get(GpxConstants.PT_HDOP) != null) {
727 // hdop value
728 float hdop = (Float) trkPnt.get(GpxConstants.PT_HDOP);
729 if (hdop < 0) {
730 hdop = 0;
731 }
732 Color customColoringTransparent = hdopAlpha < 0 ? trkPnt.customColoring :
733 new Color((trkPnt.customColoring.getRGB() & 0x00ffffff) | (hdopAlpha << 24), true);
734 g.setColor(customColoringTransparent);
735 // hdop circles
736 int hdopp = mv.getPoint(new LatLon(
737 trkPnt.getCoor().lat(),
738 trkPnt.getCoor().lon() + 2d*6*hdop*360/40000000d)).x - screen.x;
739 g.drawArc(screen.x-hdopp/2, screen.y-hdopp/2, hdopp, hdopp, 0, 360);
740 }
741 if (large) {
742 // color the large GPS points like the gps lines
743 if (trkPnt.customColoring != null) {
744 Color customColoringTransparent = largePointAlpha < 0 ? trkPnt.customColoring :
745 new Color((trkPnt.customColoring.getRGB() & 0x00ffffff) | (largePointAlpha << 24), true);
746
747 g.setColor(customColoringTransparent);
748 }
749 g.fillRect(screen.x-halfSize, screen.y-halfSize, largesize, largesize);
750 }
751 } // end for trkpnt
752 } // end if large || hdopcircle
753
754 /****************************************************************
755 ********** STEP 3e - DRAW SMALL POINTS FOR LINES ***************
756 ****************************************************************/
757 if (!large && lines) {
758 g.setColor(neutralColor);
759 for (WayPoint trkPnt : visibleSegments) {
760 LatLon c = trkPnt.getCoor();
761 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
762 continue;
763 }
764 if (!trkPnt.drawLine) {
765 Point screen = mv.getPoint(trkPnt.getEastNorth());
766 g.drawRect(screen.x, screen.y, 0, 0);
767 }
768 } // end for trkpnt
769 } // end if large
770
771 /****************************************************************
772 ********** STEP 3f - DRAW SMALL POINTS INSTEAD OF LINES ********
773 ****************************************************************/
774 if (!large && !lines) {
775 g.setColor(neutralColor);
776 for (WayPoint trkPnt : visibleSegments) {
777 LatLon c = trkPnt.getCoor();
778 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
779 continue;
780 }
781 Point screen = mv.getPoint(trkPnt.getEastNorth());
782 g.setColor(trkPnt.customColoring);
783 g.drawRect(screen.x, screen.y, 0, 0);
784 } // end for trkpnt
785 } // end if large
786 }
787
788 /**
789 * Draw GPX lines by using alpha blending
790 * @param g the common draw object to use
791 * @param mv the meta data to current displayed area
792 * @param visibleSegments segments visible in the current scope of mv
793 * @param layerAlpha the color alpha value set for that operation
794 */
795 private void drawLinesAlpha(Graphics2D g, MapView mv, List<WayPoint> visibleSegments, float layerAlpha) {
796
797 // 1st. backup the paint environment ----------------------------------
798 Composite oldComposite = g.getComposite();
799 Stroke oldStroke = g.getStroke();
800 Paint oldPaint = g.getPaint();
801
802 // 2nd. determine current scale factors -------------------------------
803
804 // adjust global settings
805 final int globalLineWidth = Utils.clamp(lineWidth, 1, 20);
806
807 // cache scale of view
808 final double zoomScale = mv.getDist100Pixel() / 50.0f;
809
810 // 3rd. determine current paint parameters -----------------------------
811
812 // alpha value is based on zoom and line with combined with global layer alpha
813 float theLineAlpha = (float) Utils.clamp((0.50 / zoomScale) / (globalLineWidth + 1), 0.01, 0.50) * layerAlpha;
814 final int theLineWith = (int) (lineWidth / zoomScale) + 1;
815
816 // 4th setup virtual paint area ----------------------------------------
817
818 // set line format and alpha channel for all overlays (more lines -> few overlap -> more transparency)
819 g.setStroke(new BasicStroke(theLineWith, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
820 g.setComposite(AlphaComposite.SrcOver.derive(theLineAlpha));
821
822 // last used / calculated entries
823 Point lastPaintPnt = null;
824
825 // 5th draw the layer ---------------------------------------------------
826
827 // for all points
828 for (WayPoint trkPnt : visibleSegments) {
829
830 // transform coordinates
831 final Point paintPnt = mv.getPoint(trkPnt.getEastNorth());
832
833 // skip single points
834 if (lastPaintPnt != null && trkPnt.drawLine && !lastPaintPnt.equals(paintPnt)) {
835
836 // set different color
837 g.setColor(trkPnt.customColoring);
838
839 // draw it
840 g.drawLine(lastPaintPnt.x, lastPaintPnt.y, paintPnt.x, paintPnt.y);
841 }
842
843 lastPaintPnt = paintPnt;
844 }
845
846 // @last restore modified paint environment -----------------------------
847 g.setPaint(oldPaint);
848 g.setStroke(oldStroke);
849 g.setComposite(oldComposite);
850 }
851
852 /**
853 * Generates a linear gradient map image
854 *
855 * @param width image width
856 * @param height image height
857 * @param colors 1..n color descriptions
858 * @return image object
859 */
860 protected static BufferedImage createImageGradientMap(int width, int height, Color... colors) {
861
862 // create image an paint object
863 final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
864 final Graphics2D g = img.createGraphics();
865
866 float[] fract = new float[ colors.length ];
867
868 // distribute fractions (define position of color in map)
869 for (int i = 0; i < colors.length; ++i) {
870 fract[i] = i * (1.0f / colors.length);
871 }
872
873 // draw the gradient map
874 LinearGradientPaint gradient = new LinearGradientPaint(0, 0, width, height, fract, colors,
875 MultipleGradientPaint.CycleMethod.NO_CYCLE);
876 g.setPaint(gradient);
877 g.fillRect(0, 0, width, height);
878 g.dispose();
879
880 // access it via raw interface
881 return img;
882 }
883
884 /**
885 * Creates a distributed colormap by linear blending between colors
886 * @param lowerLimit lower limit for first visible color
887 * @param colors 1..n colors
888 * @return array of Color objects
889 */
890 protected static Color[] createColorLut(int lowerLimit, Color... colors) {
891
892 // number of lookup entries
893 final int tableSize = 256;
894
895 // access it via raw interface
896 final Raster imgRaster = createImageGradientMap(tableSize, 1, colors).getData();
897
898 // the pixel storage
899 int[] pixel = new int[1];
900
901 Color[] colorTable = new Color[tableSize];
902
903 // map the range 0..255 to 0..pi/2
904 final double mapTo90Deg = Math.PI / 2.0 / 255.0;
905
906 // create the lookup table
907 for (int i = 0; i < tableSize; i++) {
908
909 // get next single pixel
910 imgRaster.getDataElements(i, 0, pixel);
911
912 // get color and map
913 Color c = new Color(pixel[0]);
914
915 // smooth alpha like sin curve
916 int alpha = (i > lowerLimit) ? (int) (Math.sin((i-lowerLimit) * mapTo90Deg) * 255) : 0;
917
918 // alpha with pre-offset, first color -> full transparent
919 alpha = alpha > 0 ? (20 + alpha) : 0;
920
921 // shrink to maximum bound
922 if (alpha > 255) {
923 alpha = 255;
924 }
925
926 // increase transparency for higher values ( avoid big saturation )
927 if (i > 240 && 255 == alpha) {
928 alpha -= (i - 240);
929 }
930
931 // fill entry in table, assign a alpha value
932 colorTable[i] = new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha);
933 }
934
935 // transform into lookup table
936 return colorTable;
937 }
938
939 /**
940 * Creates a darker color
941 * @param in Color object
942 * @param adjust darker adjustment amount
943 * @return new Color
944 */
945 protected static Color darkerColor(Color in, float adjust) {
946
947 final float r = (float) in.getRed()/255;
948 final float g = (float) in.getGreen()/255;
949 final float b = (float) in.getBlue()/255;
950
951 return new Color(r*adjust, g*adjust, b*adjust);
952 }
953
954 /**
955 * Creates a colormap by using a static color map with 1..n colors (RGB 0.0 ..1.0)
956 * @param str the filename (without extension) to look for into data/gpx
957 * @return the parsed colormap
958 */
959 protected static Color[] createColorFromResource(String str) {
960
961 // create resource string
962 final String colorFile = "resource://data/gpx/" + str + ".txt";
963
964 List<Color> colorList = new ArrayList<>();
965
966 // try to load the file
967 try (CachedFile cf = new CachedFile(colorFile); BufferedReader br = cf.getContentReader()) {
968
969 String line;
970
971 // process lines
972 while ((line = br.readLine()) != null) {
973
974 // use comma as separator
975 String[] column = line.split(",");
976
977 // empty or comment line
978 if (column.length < 3 || column[0].startsWith("#")) {
979 continue;
980 }
981
982 // extract RGB value
983 float r = Float.parseFloat(column[0]);
984 float g = Float.parseFloat(column[1]);
985 float b = Float.parseFloat(column[2]);
986
987 // some color tables are 0..1.0 and some 0.255
988 float scale = (r < 1 && g < 1 && b < 1) ? 1 : 255;
989
990 colorList.add(new Color(r/scale, g/scale, b/scale));
991 }
992 } catch (IOException e) {
993 throw new JosmRuntimeException(e);
994 }
995
996 // fallback if empty or failed
997 if (colorList.isEmpty()) {
998 colorList.add(Color.BLACK);
999 colorList.add(Color.WHITE);
1000 } else {
1001 // add additional darker elements to end of list
1002 final Color lastColor = colorList.get(colorList.size() - 1);
1003 colorList.add(darkerColor(lastColor, 0.975f));
1004 colorList.add(darkerColor(lastColor, 0.950f));
1005 }
1006
1007 return createColorLut(0, colorList.toArray(new Color[ colorList.size() ]));
1008 }
1009
1010 /**
1011 * Returns the next user color map
1012 *
1013 * @param userColor - default or fallback user color
1014 * @param tableIdx - selected user color index
1015 * @return color array
1016 */
1017 protected static Color[] selectColorMap(Color userColor, int tableIdx) {
1018
1019 // generate new user color map ( dark, user color, white )
1020 Color[] userColor1 = createColorLut(0, userColor.darker(), userColor, userColor.brighter(), Color.WHITE);
1021
1022 // generate new user color map ( white -> color )
1023 Color[] userColor2 = createColorLut(0, Color.WHITE, Color.WHITE, userColor);
1024
1025 // generate new user color map
1026 Color[] colorTrafficLights = createColorLut(0, Color.WHITE, Color.GREEN.darker(), Color.YELLOW, Color.RED);
1027
1028 // decide what, keep order is sync with setting on GUI
1029 Color[][] lut = {
1030 userColor1,
1031 userColor2,
1032 colorTrafficLights,
1033 heatMapLutColorJosmInferno,
1034 heatMapLutColorJosmViridis,
1035 heatMapLutColorJosmBrown2Green,
1036 heatMapLutColorJosmRed2Blue
1037 };
1038
1039 // default case
1040 Color[] nextUserColor = userColor1;
1041
1042 // select by index
1043 if (tableIdx < lut.length) {
1044 nextUserColor = lut[ tableIdx ];
1045 }
1046
1047 // adjust color map
1048 return nextUserColor;
1049 }
1050
1051 /**
1052 * Generates a Icon
1053 *
1054 * @param userColor selected user color
1055 * @param tableIdx tabled index
1056 * @param size size of the image
1057 * @return a image icon that shows the
1058 */
1059 public static ImageIcon getColorMapImageIcon(Color userColor, int tableIdx, int size) {
1060 return new ImageIcon(createImageGradientMap(size, size, selectColorMap(userColor, tableIdx)));
1061 }
1062
1063 /**
1064 * Draw gray heat map with current Graphics2D setting
1065 * @param gB the common draw object to use
1066 * @param mv the meta data to current displayed area
1067 * @param listSegm segments visible in the current scope of mv
1068 * @param foreComp composite use to draw foreground objects
1069 * @param foreStroke stroke use to draw foreground objects
1070 * @param backComp composite use to draw background objects
1071 * @param backStroke stroke use to draw background objects
1072 */
1073 private void drawHeatGrayLineMap(Graphics2D gB, MapView mv, List<WayPoint> listSegm,
1074 Composite foreComp, Stroke foreStroke,
1075 Composite backComp, Stroke backStroke) {
1076
1077 // draw foreground
1078 boolean drawForeground = foreComp != null && foreStroke != null;
1079
1080 // set initial values
1081 gB.setStroke(backStroke); gB.setComposite(backComp);
1082
1083 // get last point in list
1084 final WayPoint lastPnt = !listSegm.isEmpty() ? listSegm.get(listSegm.size() - 1) : null;
1085
1086 // for all points, draw single lines by using optimized drawing
1087 for (WayPoint trkPnt : listSegm) {
1088
1089 // get transformed coordinates
1090 final Point paintPnt = mv.getPoint(trkPnt.getEastNorth());
1091
1092 // end of line segment or end of list reached
1093 if (!trkPnt.drawLine || (lastPnt == trkPnt)) {
1094
1095 // convert to primitive type
1096 final int[] polyXArr = heatMapPolyX.stream().mapToInt(Integer::intValue).toArray();
1097 final int[] polyYArr = heatMapPolyY.stream().mapToInt(Integer::intValue).toArray();
1098
1099 // a.) draw background
1100 gB.drawPolyline(polyXArr, polyYArr, polyXArr.length);
1101
1102 // b.) draw extra foreground
1103 if (drawForeground && heatMapDrawExtraLine) {
1104
1105 gB.setStroke(foreStroke); gB.setComposite(foreComp);
1106 gB.drawPolyline(polyXArr, polyYArr, polyXArr.length);
1107 gB.setStroke(backStroke); gB.setComposite(backComp);
1108 }
1109
1110 // drop used points
1111 heatMapPolyX.clear(); heatMapPolyY.clear();
1112 }
1113
1114 // store only the integer part (make sense because pixel is 1:1 here)
1115 heatMapPolyX.add((int) paintPnt.getX());
1116 heatMapPolyY.add((int) paintPnt.getY());
1117 }
1118 }
1119
1120 /**
1121 * Map the gray map to heat map and draw them with current Graphics2D setting
1122 * @param g the common draw object to use
1123 * @param imgGray gray scale input image
1124 * @param sampleRaster the line with for drawing
1125 * @param outlineWidth line width for outlines
1126 */
1127 private void drawHeatMapGrayMap(Graphics2D g, BufferedImage imgGray, int sampleRaster, int outlineWidth) {
1128
1129 final int[] imgPixels = ((DataBufferInt) imgGray.getRaster().getDataBuffer()).getData();
1130
1131 // samples offset and bounds are scaled with line width derived from zoom level
1132 final int offX = Math.max(1, sampleRaster);
1133 final int offY = Math.max(1, sampleRaster);
1134
1135 final int maxPixelX = imgGray.getWidth();
1136 final int maxPixelY = imgGray.getHeight();
1137
1138 // always full or outlines at big samples rasters
1139 final boolean drawOutlines = (outlineWidth > 0) && ((0 == sampleRaster) || (sampleRaster > 10));
1140
1141 // backup stroke
1142 final Stroke oldStroke = g.getStroke();
1143
1144 // use basic stroke for outlines and default transparency
1145 g.setStroke(new BasicStroke(outlineWidth));
1146
1147 int lastPixelX = 0;
1148 int lastPixelColor = 0;
1149
1150 // resample gray scale image with line linear weight of next sample in line
1151 // process each line and draw pixels / rectangles with same color with one operations
1152 for (int y = 0; y < maxPixelY; y += offY) {
1153
1154 // the lines offsets
1155 final int lastLineOffset = maxPixelX * (y+0);
1156 final int nextLineOffset = maxPixelX * (y+1);
1157
1158 for (int x = 0; x < maxPixelX; x += offX) {
1159
1160 int thePixelColor = 0; int thePixelCount = 0;
1161
1162 // sample the image (it is gray scale)
1163 int offset = lastLineOffset + x;
1164
1165 // merge next pixels of window of line
1166 for (int k = 0; k < offX && (offset + k) < nextLineOffset; k++) {
1167 thePixelColor += imgPixels[offset+k] & 0xFF;
1168 thePixelCount++;
1169 }
1170
1171 // mean value
1172 thePixelColor = thePixelCount > 0 ? (thePixelColor / thePixelCount) : 0;
1173
1174 // restart -> use initial sample
1175 if (0 == x) {
1176 lastPixelX = 0; lastPixelColor = thePixelColor - 1;
1177 }
1178
1179 boolean bDrawIt = false;
1180
1181 // when one of segment is mapped to black
1182 bDrawIt = bDrawIt || (lastPixelColor == 0) || (thePixelColor == 0);
1183
1184 // different color
1185 bDrawIt = bDrawIt || (Math.abs(lastPixelColor-thePixelColor) > 0);
1186
1187 // when line is finished draw always
1188 bDrawIt = bDrawIt || (y >= (maxPixelY-offY));
1189
1190 if (bDrawIt) {
1191
1192 // draw only foreground pixels
1193 if (lastPixelColor > 0) {
1194
1195 // gray to RGB mapping
1196 g.setColor(heatMapLutColor[ lastPixelColor ]);
1197
1198 // box from from last Y pixel to current pixel
1199 if (drawOutlines) {
1200 g.drawRect(lastPixelX, y, offX + x - lastPixelX, offY);
1201 } else {
1202 g.fillRect(lastPixelX, y, offX + x - lastPixelX, offY);
1203 }
1204 }
1205
1206 // restart detection
1207 lastPixelX = x; lastPixelColor = thePixelColor;
1208 }
1209 }
1210 }
1211
1212 // recover
1213 g.setStroke(oldStroke);
1214 }
1215
1216 /**
1217 * Collect and draw GPS segments and displays a heat-map
1218 * @param g the common draw object to use
1219 * @param mv the meta data to current displayed area
1220 * @param visibleSegments segments visible in the current scope of mv
1221 */
1222 private void drawHeatMap(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
1223
1224 // get bounds of screen image and projection, zoom and adjust input parameters
1225 final Rectangle screenBounds = new Rectangle(mv.getWidth(), mv.getHeight());
1226 final MapViewState mapViewState = mv.getState();
1227 final double zoomScale = mv.getDist100Pixel() / 50.0f;
1228
1229 // adjust global settings ( zero = default line width )
1230 final int globalLineWidth = (0 == lineWidth) ? 1 : Utils.clamp(lineWidth, 1, 20);
1231
1232 // 1st setup virtual paint area ----------------------------------------
1233
1234 // new image buffer needed
1235 final boolean imageSetup = null == heatMapImgGray || !heatMapCacheScreenBounds.equals(screenBounds);
1236
1237 // screen bounds changed, need new image buffer ?
1238 if (imageSetup) {
1239 // we would use a "pure" grayscale image, but there is not efficient way to map gray scale values to RGB)
1240 heatMapImgGray = new BufferedImage(screenBounds.width, screenBounds.height, BufferedImage.TYPE_INT_ARGB);
1241 heatMapGraph2d = heatMapImgGray.createGraphics();
1242 heatMapGraph2d.setBackground(new Color(0, 0, 0, 255));
1243 heatMapGraph2d.setColor(Color.WHITE);
1244
1245 // fast draw ( maybe help or not )
1246 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
1247 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
1248 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
1249 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
1250 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1251 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
1252 heatMapGraph2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
1253
1254 // cache it
1255 heatMapCacheScreenBounds = screenBounds;
1256 }
1257
1258 // 2nd. determine current scale factors -------------------------------
1259
1260 // the line width (foreground: draw extra small footprint line of track)
1261 int lineWidthB = (int) Math.max(1.5f * (globalLineWidth / zoomScale) + 1, 2);
1262 int lineWidthF = lineWidthB > 2 ? (globalLineWidth - 1) : 0;
1263
1264 // global alpha adjustment
1265 float lineAlpha = (float) Utils.clamp((0.40 / zoomScale) / (globalLineWidth + 1), 0.01, 0.40);
1266
1267 // adjust 0.15 .. 1.85
1268 float scaleAlpha = 1.0f + ((heatMapDrawGain/10.0f) * 0.85f);
1269
1270 // add to calculated values
1271 float lineAlphaBPoint = (float) Utils.clamp((lineAlpha * 0.65) * scaleAlpha, 0.001, 0.90);
1272 float lineAlphaBLine = (float) Utils.clamp((lineAlpha * 1.00) * scaleAlpha, 0.001, 0.90);
1273 float lineAlphaFLine = (float) Utils.clamp((lineAlpha / 1.50) * scaleAlpha, 0.001, 0.90);
1274
1275 // 3rd Calculate the heat map data by draw GPX traces with alpha value ----------
1276
1277 // recalculation of image needed
1278 final boolean imageRecalc = !mapViewState.equalsInWindow(heatMapMapViewState)
1279 || gpxLayerInvalidated
1280 || heatMapCacheLineWith != globalLineWidth;
1281
1282 // need re-generation of gray image ?
1283 if (imageSetup || imageRecalc) {
1284
1285 // clear background
1286 heatMapGraph2d.clearRect(0, 0, heatMapImgGray.getWidth(), heatMapImgGray.getHeight());
1287
1288 // point or line blending
1289 if (heatMapDrawPointMode) {
1290 heatMapGraph2d.setComposite(AlphaComposite.SrcOver.derive(lineAlphaBPoint));
1291 drawHeatGrayDotMap(heatMapGraph2d, mv, visibleSegments, lineWidthB);
1292
1293 } else {
1294 drawHeatGrayLineMap(heatMapGraph2d, mv, visibleSegments,
1295 lineWidthF > 1 ? AlphaComposite.SrcOver.derive(lineAlphaFLine) : null,
1296 new BasicStroke(lineWidthF, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND),
1297 AlphaComposite.SrcOver.derive(lineAlphaBLine),
1298 new BasicStroke(lineWidthB, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
1299 }
1300
1301 // remember draw parameter
1302 heatMapMapViewState = mapViewState;
1303 heatMapCacheLineWith = globalLineWidth;
1304 gpxLayerInvalidated = false;
1305 }
1306
1307 // 4th. Draw data on target layer, map data via color lookup table --------------
1308 drawHeatMapGrayMap(g, heatMapImgGray, lineWidthB > 2 ? (int) (lineWidthB*1.25f) : 1, lineWidth > 2 ? (lineWidth - 2) : 1);
1309 }
1310
1311 /**
1312 * Draw a dotted heat map
1313 *
1314 * @param gB the common draw object to use
1315 * @param mv the meta data to current displayed area
1316 * @param listSegm segments visible in the current scope of mv
1317 * @param drawSize draw size of draw element
1318 */
1319 private static void drawHeatGrayDotMap(Graphics2D gB, MapView mv, List<WayPoint> listSegm, int drawSize) {
1320
1321 // typical rendering rate -> use realtime preview instead of accurate display
1322 final double maxSegm = 25_000, nrSegms = listSegm.size();
1323
1324 // determine random drop rate
1325 final double randomDrop = Math.min(nrSegms > maxSegm ? (nrSegms - maxSegm) / nrSegms : 0, 0.70f);
1326
1327 // http://www.nstb.tc.faa.gov/reports/PAN94_0716.pdf#page=22
1328 // Global Average Position Domain Accuracy, typical -> not worst case !
1329 // < 4.218 m Vertical
1330 // < 2.168 m Horizontal
1331 final double pixelRmsX = (100 / mv.getDist100Pixel()) * 2.168;
1332 final double pixelRmsY = (100 / mv.getDist100Pixel()) * 4.218;
1333
1334 Point lastPnt = null;
1335
1336 // for all points, draw single lines
1337 for (WayPoint trkPnt : listSegm) {
1338
1339 // get transformed coordinates
1340 final Point paintPnt = mv.getPoint(trkPnt.getEastNorth());
1341
1342 // end of line segment or end of list reached
1343 if (trkPnt.drawLine && null != lastPnt) {
1344 drawHeatSurfaceLine(gB, paintPnt, lastPnt, drawSize, pixelRmsX, pixelRmsY, randomDrop);
1345 }
1346
1347 // remember
1348 lastPnt = paintPnt;
1349 }
1350 }
1351
1352 /**
1353 * Draw a dotted surface line
1354 *
1355 * @param g the common draw object to use
1356 * @param fromPnt start point
1357 * @param toPnt end point
1358 * @param drawSize size of draw elements
1359 * @param rmsSizeX RMS size of circle for X (width)
1360 * @param rmsSizeY RMS size of circle for Y (height)
1361 * @param dropRate Pixel render drop rate
1362 */
1363 private static void drawHeatSurfaceLine(Graphics2D g,
1364 Point fromPnt, Point toPnt, int drawSize, double rmsSizeX, double rmsSizeY, double dropRate) {
1365
1366 // collect frequently used items
1367 final int fromX = (int) fromPnt.getX(); final int deltaX = (int) (toPnt.getX() - fromX);
1368 final int fromY = (int) fromPnt.getY(); final int deltaY = (int) (toPnt.getY() - fromY);
1369
1370 // use same random values for each point
1371 final Random heatMapRandom = new Random(fromX+fromY+deltaX+deltaY);
1372
1373 // cache distance between start and end point
1374 final int dist = (int) Math.abs(fromPnt.distance(toPnt));
1375
1376 // number of increment ( fill wide distance tracks )
1377 double scaleStep = Math.max(1.0f / dist, dist > 100 ? 0.10f : 0.20f);
1378
1379 // number of additional random points
1380 int rounds = Math.min(drawSize/2, 1)+1;
1381
1382 // decrease random noise at high drop rate ( more accurate draw of fewer points )
1383 rmsSizeX *= (1.0d - dropRate);
1384 rmsSizeY *= (1.0d - dropRate);
1385
1386 double scaleVal = 0;
1387
1388 // interpolate line draw ( needs separate point instead of line )
1389 while (scaleVal < (1.0d-0.0001d)) {
1390
1391 // get position
1392 final double pntX = fromX + scaleVal * deltaX;
1393 final double pntY = fromY + scaleVal * deltaY;
1394
1395 // add random distribution around sampled point
1396 for (int k = 0; k < rounds; k++) {
1397
1398 // add error distribution, first point with less error
1399 int x = (int) (pntX + heatMapRandom.nextGaussian() * (k > 0 ? rmsSizeX : rmsSizeX/4));
1400 int y = (int) (pntY + heatMapRandom.nextGaussian() * (k > 0 ? rmsSizeY : rmsSizeY/4));
1401
1402 // draw it, even drop is requested
1403 if (heatMapRandom.nextDouble() >= dropRate) {
1404 g.fillRect(x-drawSize, y-drawSize, drawSize, drawSize);
1405 }
1406 }
1407 scaleVal += scaleStep;
1408 }
1409 }
1410
1411 /**
1412 * Apply default color configuration to way segments
1413 * @param visibleSegments segments visible in the current scope of mv
1414 */
1415 private void fixColors(List<WayPoint> visibleSegments) {
1416 for (WayPoint trkPnt : visibleSegments) {
1417 if (trkPnt.customColoring == null) {
1418 trkPnt.customColoring = neutralColor;
1419 }
1420 }
1421 }
1422
1423 /**
1424 * Check cache validity set necessary flags
1425 */
1426 private void checkCache() {
1427 // CHECKSTYLE.OFF: BooleanExpressionComplexity
1428 if ((computeCacheMaxLineLengthUsed != maxLineLength)
1429 || (computeCacheColored != colored)
1430 || (computeCacheColorTracksTune != colorTracksTune)
1431 || (computeCacheColorDynamic != colorModeDynamic)
1432 || (computeCacheHeatMapDrawColorTableIdx != heatMapDrawColorTableIdx)
1433 || (!neutralColor.equals(computeCacheColorUsed)
1434 || (computeCacheHeatMapDrawPointMode != heatMapDrawPointMode)
1435 || (computeCacheHeatMapDrawGain != heatMapDrawGain))
1436 || (computeCacheHeatMapDrawLowerLimit != heatMapDrawLowerLimit)
1437 ) {
1438 // CHECKSTYLE.ON: BooleanExpressionComplexity
1439 computeCacheMaxLineLengthUsed = maxLineLength;
1440 computeCacheInSync = false;
1441 computeCacheColorUsed = neutralColor;
1442 computeCacheColored = colored;
1443 computeCacheColorTracksTune = colorTracksTune;
1444 computeCacheColorDynamic = colorModeDynamic;
1445 computeCacheHeatMapDrawColorTableIdx = heatMapDrawColorTableIdx;
1446 computeCacheHeatMapDrawPointMode = heatMapDrawPointMode;
1447 computeCacheHeatMapDrawGain = heatMapDrawGain;
1448 computeCacheHeatMapDrawLowerLimit = heatMapDrawLowerLimit;
1449 }
1450 }
1451
1452 /**
1453 * callback when data is changed, invalidate cached configuration parameters
1454 */
1455 @Override
1456 public void gpxDataChanged(GpxDataChangeEvent e) {
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 data.removeChangeListener(this);
1491 }
1492}
Note: See TracBrowser for help on using the repository browser.