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