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

Last change on this file since 11587 was 11587, checked in by Don-vip, 7 years ago

checkstyle - enable BooleanExpressionComplexity / 6

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