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

Last change on this file was 19106, checked in by taylor.smock, 4 months ago

Cleanup some new PMD warnings from PMD 7.x (followup of r19101)

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