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

Last change on this file was 19316, checked in by stoecker, 14 months ago

support 2 more circle drawing data sources for NMEA, patch by StephaneP (slightly modified), fix #21007

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