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

Last change on this file since 9234 was 9234, checked in by simon04, 10 years ago

fix #11338 - Gpx tracks: speed outliers and coloring

  • Property svn:eol-style set to native
File size: 23.3 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.BasicStroke;
8import java.awt.Color;
9import java.awt.Graphics2D;
10import java.awt.Point;
11import java.awt.RenderingHints;
12import java.awt.Stroke;
13import java.util.ArrayList;
14import java.util.Collection;
15import java.util.Collections;
16import java.util.Date;
17import java.util.List;
18
19import org.openstreetmap.josm.Main;
20import org.openstreetmap.josm.data.coor.LatLon;
21import org.openstreetmap.josm.data.gpx.GpxConstants;
22import org.openstreetmap.josm.data.gpx.GpxData;
23import org.openstreetmap.josm.data.gpx.WayPoint;
24import org.openstreetmap.josm.gui.MapView;
25import org.openstreetmap.josm.tools.ColorScale;
26
27/**
28 * Class that helps to draw large set of GPS tracks with different colors and options
29 * @since 7319
30 */
31public class GpxDrawHelper {
32 private final GpxData data;
33
34 // draw lines between points belonging to different segments
35 private boolean forceLines;
36 // draw direction arrows on the lines
37 private boolean direction;
38 /** don't draw lines if longer than x meters **/
39 private int lineWidth;
40 private int maxLineLength;
41 private boolean lines;
42 /** paint large dots for points **/
43 private boolean large;
44 private int largesize;
45 private boolean hdopCircle;
46 /** paint direction arrow with alternate math. may be faster **/
47 private boolean alternateDirection;
48 /** don't draw arrows nearer to each other than this **/
49 private int delta;
50 private double minTrackDurationForTimeColoring;
51
52 private int hdopfactor;
53
54 private static final double PHI = Math.toRadians(15);
55
56 //// Variables used only to check cache validity
57 private boolean computeCacheInSync;
58 private int computeCacheMaxLineLengthUsed;
59 private Color computeCacheColorUsed;
60 private boolean computeCacheColorDynamic;
61 private ColorMode computeCacheColored;
62 private int computeCacheColorTracksTune;
63
64 //// Color-related fields
65 /** Mode of the line coloring **/
66 private ColorMode colored;
67 /** max speed for coloring - allows to tweak line coloring for different speed levels. **/
68 private int colorTracksTune;
69 private boolean colorModeDynamic;
70 private Color neutralColor;
71 private int largePointAlpha;
72
73 // default access is used to allow changing from plugins
74 private ColorScale velocityScale;
75 /** Colors (without custom alpha channel, if given) for HDOP painting. **/
76 private ColorScale hdopScale;
77 private ColorScale dateScale;
78 private ColorScale directionScale;
79
80 /** Opacity for hdop points **/
81 private int hdopAlpha;
82
83
84 // lookup array to draw arrows without doing any math
85 private static final int ll0 = 9;
86 private static final int sl4 = 5;
87 private static final int sl9 = 3;
88 private static final int[][] dir = {
89 {+sl4, +ll0, +ll0, +sl4}, {-sl9, +ll0, +sl9, +ll0}, {-ll0, +sl4, -sl4, +ll0},
90 {-ll0, -sl9, -ll0, +sl9}, {-sl4, -ll0, -ll0, -sl4}, {+sl9, -ll0, -sl9, -ll0},
91 {+ll0, -sl4, +sl4, -ll0}, {+ll0, +sl9, +ll0, -sl9}, {+sl4, +ll0, +ll0, +sl4},
92 {-sl9, +ll0, +sl9, +ll0}, {-ll0, +sl4, -sl4, +ll0}, {-ll0, -sl9, -ll0, +sl9}};
93
94 private void setupColors() {
95 hdopAlpha = Main.pref.getInteger("hdop.color.alpha", -1);
96 velocityScale = ColorScale.createHSBScale(256).addTitle(tr("Velocity, km/h"));
97 /** Colors (without custom alpha channel, if given) for HDOP painting. **/
98 hdopScale = ColorScale.createHSBScale(256).makeReversed().addTitle(tr("HDOP, m"));
99 dateScale = ColorScale.createHSBScale(256).addTitle(tr("Time"));
100 directionScale = ColorScale.createCyclicScale(256).setIntervalCount(4).addTitle(tr("Direction"));
101 }
102
103 /**
104 * Different color modes
105 */
106 public enum ColorMode {
107 NONE, VELOCITY, HDOP, DIRECTION, TIME
108 }
109
110 /**
111 * Constructs a new {@code GpxDrawHelper}.
112 * @param gpxData GPX data
113 */
114 public GpxDrawHelper(GpxData gpxData) {
115 data = gpxData;
116 setupColors();
117 }
118
119 private static String specName(String layerName) {
120 return "layer " + layerName;
121 }
122
123 /**
124 * Get the default color for gps tracks for specified layer
125 * @param layerName name of the GpxLayer
126 * @param ignoreCustom do not use preferences
127 * @return the color or null if the color is not constant
128 */
129 public Color getColor(String layerName, boolean ignoreCustom) {
130 Color c = Main.pref.getColor(marktr("gps point"), specName(layerName), Color.gray);
131 return ignoreCustom || getColorMode(layerName) == ColorMode.NONE ? c : null;
132 }
133
134 /**
135 * Read coloring mode for specified layer from preferences
136 * @param layerName name of the GpxLayer
137 * @return coloting mode
138 */
139 public ColorMode getColorMode(String layerName) {
140 try {
141 int i = Main.pref.getInteger("draw.rawgps.colors", specName(layerName), 0);
142 return ColorMode.values()[i];
143 } catch (Exception e) {
144 Main.warn(e);
145 }
146 return ColorMode.NONE;
147 }
148
149 /** Reads generic color from preferences (usually gray)
150 * @return the color
151 **/
152 public static Color getGenericColor() {
153 return Main.pref.getColor(marktr("gps point"), Color.gray);
154 }
155
156 /**
157 * Read all drawing-related settings from preferences
158 * @param layerName layer name used to access its specific preferences
159 **/
160 public void readPreferences(String layerName) {
161 String spec = specName(layerName);
162 forceLines = Main.pref.getBoolean("draw.rawgps.lines.force", spec, false);
163 direction = Main.pref.getBoolean("draw.rawgps.direction", spec, false);
164 lineWidth = Main.pref.getInteger("draw.rawgps.linewidth", spec, 0);
165
166 if (!data.fromServer) {
167 maxLineLength = Main.pref.getInteger("draw.rawgps.max-line-length.local", spec, -1);
168 lines = Main.pref.getBoolean("draw.rawgps.lines.local", spec, true);
169 } else {
170 maxLineLength = Main.pref.getInteger("draw.rawgps.max-line-length", spec, 200);
171 lines = Main.pref.getBoolean("draw.rawgps.lines", spec, true);
172 }
173 large = Main.pref.getBoolean("draw.rawgps.large", spec, false);
174 largesize = Main.pref.getInteger("draw.rawgps.large.size", spec, 3);
175 hdopCircle = Main.pref.getBoolean("draw.rawgps.hdopcircle", spec, false);
176 colored = getColorMode(layerName);
177 alternateDirection = Main.pref.getBoolean("draw.rawgps.alternatedirection", spec, false);
178 delta = Main.pref.getInteger("draw.rawgps.min-arrow-distance", spec, 40);
179 colorTracksTune = Main.pref.getInteger("draw.rawgps.colorTracksTune", spec, 45);
180 colorModeDynamic = Main.pref.getBoolean("draw.rawgps.colors.dynamic", spec, false);
181 hdopfactor = Main.pref.getInteger("hdop.factor", 25);
182 minTrackDurationForTimeColoring = Main.pref.getInteger("draw.rawgps.date-coloring-min-dt", 60);
183 largePointAlpha = Main.pref.getInteger("draw.rawgps.large.alpha", -1) & 0xFF;
184
185 neutralColor = getColor(layerName, true);
186 velocityScale.setNoDataColor(neutralColor);
187 dateScale.setNoDataColor(neutralColor);
188 hdopScale.setNoDataColor(neutralColor);
189 directionScale.setNoDataColor(neutralColor);
190
191 largesize += lineWidth;
192 }
193
194 public void drawAll(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
195
196 checkCache();
197
198 // STEP 2b - RE-COMPUTE CACHE DATA *********************
199 if (!computeCacheInSync) { // don't compute if the cache is good
200 calculateColors();
201 }
202
203 Stroke storedStroke = g.getStroke();
204
205 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
206 Main.pref.getBoolean("mappaint.gpx.use-antialiasing", false) ?
207 RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
208
209 if (lineWidth != 0) {
210 g.setStroke(new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
211 }
212 fixColors(visibleSegments);
213 drawLines(g, mv, visibleSegments);
214 drawArrows(g, mv, visibleSegments);
215 drawPoints(g, mv, visibleSegments);
216 if (lineWidth != 0) {
217 g.setStroke(storedStroke);
218 }
219 }
220
221 public void calculateColors() {
222 double minval = +1e10;
223 double maxval = -1e10;
224 WayPoint oldWp = null;
225
226 if (colorModeDynamic) {
227 if (colored == ColorMode.VELOCITY) {
228 final List<Double> velocities = new ArrayList<>();
229 for (Collection<WayPoint> segment : data.getLinesIterable(null)) {
230 if (!forceLines) {
231 oldWp = null;
232 }
233 for (WayPoint trkPnt : segment) {
234 LatLon c = trkPnt.getCoor();
235 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
236 continue;
237 }
238 if (oldWp != null && trkPnt.time > oldWp.time) {
239 double vel = c.greatCircleDistance(oldWp.getCoor())
240 / (trkPnt.time - oldWp.time);
241 velocities.add(vel);
242 if (vel > maxval) {
243 maxval = vel;
244 }
245 if (vel < minval) {
246 minval = vel;
247 }
248 }
249 oldWp = trkPnt;
250 }
251 }
252 Collections.sort(velocities);
253 minval = velocities.get(velocities.size() / 20); // 5% percentile to remove outliers
254 maxval = velocities.get(velocities.size() * 19 / 20); // 95% percentile to remove outliers
255 if (minval >= maxval) {
256 velocityScale.setRange(0, 120/3.6);
257 } else {
258 velocityScale.setRange(minval, maxval);
259 }
260 } else if (colored == ColorMode.HDOP) {
261 for (Collection<WayPoint> segment : data.getLinesIterable(null)) {
262 for (WayPoint trkPnt : segment) {
263 Object val = trkPnt.get(GpxConstants.PT_HDOP);
264 if (val != null) {
265 double hdop = ((Float) val).doubleValue();
266 if (hdop > maxval) {
267 maxval = hdop;
268 }
269 if (hdop < minval) {
270 minval = hdop;
271 }
272 }
273 }
274 }
275 if (minval >= maxval) {
276 hdopScale.setRange(0, 100);
277 } else {
278 hdopScale.setRange(minval, maxval);
279 }
280 }
281 oldWp = null;
282 } else { // color mode not dynamic
283 velocityScale.setRange(0, colorTracksTune);
284 hdopScale.setRange(0, 1.0/hdopfactor);
285 }
286 double now = System.currentTimeMillis()/1000.0;
287 if (colored == ColorMode.TIME) {
288 Date[] bounds = data.getMinMaxTimeForAllTracks();
289 if (bounds.length >= 2) {
290 minval = bounds[0].getTime()/1000.0;
291 maxval = bounds[1].getTime()/1000.0;
292 } else {
293 minval = 0;
294 maxval = now;
295 }
296 dateScale.setRange(minval, maxval);
297 }
298
299
300 // Now the colors for all the points will be assigned
301 for (Collection<WayPoint> segment : data.getLinesIterable(null)) {
302 if (!forceLines) { // don't draw lines between segments, unless forced to
303 oldWp = null;
304 }
305 for (WayPoint trkPnt : segment) {
306 LatLon c = trkPnt.getCoor();
307 trkPnt.customColoring = neutralColor;
308 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
309 continue;
310 }
311 // now we are sure some color will be assigned
312 Color color = null;
313
314 if (colored == ColorMode.HDOP) {
315 Float hdop = (Float) trkPnt.get(GpxConstants.PT_HDOP);
316 color = hdopScale.getColor(hdop);
317 }
318 if (oldWp != null) { // other coloring modes need segment for calcuation
319 double dist = c.greatCircleDistance(oldWp.getCoor());
320 boolean noDraw = false;
321 switch (colored) {
322 case VELOCITY:
323 double dtime = trkPnt.time - oldWp.time;
324 if (dtime > 0) {
325 color = velocityScale.getColor(dist / dtime);
326 } else {
327 color = velocityScale.getNoDataColor();
328 }
329 break;
330 case DIRECTION:
331 double dirColor = oldWp.getCoor().heading(trkPnt.getCoor());
332 color = directionScale.getColor(dirColor);
333 break;
334 case TIME:
335 double t = trkPnt.time;
336 // skip bad timestamps and very short tracks
337 if (t > 0 && t <= now && maxval - minval > minTrackDurationForTimeColoring) {
338 color = dateScale.getColor(t);
339 } else {
340 color = dateScale.getNoDataColor();
341 }
342 break;
343 }
344 if (!noDraw && (maxLineLength == -1 || dist <= maxLineLength)) {
345 trkPnt.drawLine = true;
346 trkPnt.dir = (int) oldWp.getCoor().heading(trkPnt.getCoor());
347 } else {
348 trkPnt.drawLine = false;
349 }
350 } else { // make sure we reset outdated data
351 trkPnt.drawLine = false;
352 color = neutralColor;
353 }
354 if (color != null) {
355 trkPnt.customColoring = color;
356 }
357 oldWp = trkPnt;
358 }
359 }
360
361 computeCacheInSync = true;
362 }
363
364 private void drawLines(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
365 if (lines) {
366 Point old = null;
367 for (WayPoint trkPnt : visibleSegments) {
368 LatLon c = trkPnt.getCoor();
369 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
370 continue;
371 }
372 Point screen = mv.getPoint(trkPnt.getEastNorth());
373 // skip points that are on the same screenposition
374 if (trkPnt.drawLine && old != null && ((old.x != screen.x) || (old.y != screen.y))) {
375 g.setColor(trkPnt.customColoring);
376 g.drawLine(old.x, old.y, screen.x, screen.y);
377 }
378 old = screen;
379 }
380 }
381 }
382
383 private void drawArrows(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
384 /****************************************************************
385 ********** STEP 3b - DRAW NICE ARROWS **************************
386 ****************************************************************/
387 if (lines && direction && !alternateDirection) {
388 Point old = null;
389 Point oldA = null; // last arrow painted
390 for (WayPoint trkPnt : visibleSegments) {
391 LatLon c = trkPnt.getCoor();
392 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
393 continue;
394 }
395 if (trkPnt.drawLine) {
396 Point screen = mv.getPoint(trkPnt.getEastNorth());
397 // skip points that are on the same screenposition
398 if (old != null
399 && (oldA == null || screen.x < oldA.x - delta || screen.x > oldA.x + delta
400 || screen.y < oldA.y - delta || screen.y > oldA.y + delta)) {
401 g.setColor(trkPnt.customColoring);
402 double t = Math.atan2(screen.y - old.y, screen.x - old.x) + Math.PI;
403 g.drawLine(screen.x, screen.y, (int) (screen.x + 10 * Math.cos(t - PHI)),
404 (int) (screen.y + 10 * Math.sin(t - PHI)));
405 g.drawLine(screen.x, screen.y, (int) (screen.x + 10 * Math.cos(t + PHI)),
406 (int) (screen.y + 10 * Math.sin(t + PHI)));
407 oldA = screen;
408 }
409 old = screen;
410 }
411 } // end for trkpnt
412 }
413
414 /****************************************************************
415 ********** STEP 3c - DRAW FAST ARROWS **************************
416 ****************************************************************/
417 if (lines && direction && alternateDirection) {
418 Point old = null;
419 Point oldA = null; // last arrow painted
420 for (WayPoint trkPnt : visibleSegments) {
421 LatLon c = trkPnt.getCoor();
422 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
423 continue;
424 }
425 if (trkPnt.drawLine) {
426 Point screen = mv.getPoint(trkPnt.getEastNorth());
427 // skip points that are on the same screenposition
428 if (old != null
429 && (oldA == null || screen.x < oldA.x - delta || screen.x > oldA.x + delta
430 || screen.y < oldA.y - delta || screen.y > oldA.y + delta)) {
431 g.setColor(trkPnt.customColoring);
432 g.drawLine(screen.x, screen.y, screen.x + dir[trkPnt.dir][0], screen.y
433 + dir[trkPnt.dir][1]);
434 g.drawLine(screen.x, screen.y, screen.x + dir[trkPnt.dir][2], screen.y
435 + dir[trkPnt.dir][3]);
436 oldA = screen;
437 }
438 old = screen;
439 }
440 } // end for trkpnt
441 }
442 }
443
444 private void drawPoints(Graphics2D g, MapView mv, List<WayPoint> visibleSegments) {
445 /****************************************************************
446 ********** STEP 3d - DRAW LARGE POINTS AND HDOP CIRCLE *********
447 ****************************************************************/
448 if (large || hdopCircle) {
449 final int halfSize = largesize/2;
450 for (WayPoint trkPnt : visibleSegments) {
451 LatLon c = trkPnt.getCoor();
452 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
453 continue;
454 }
455 Point screen = mv.getPoint(trkPnt.getEastNorth());
456
457
458 if (hdopCircle && trkPnt.get(GpxConstants.PT_HDOP) != null) {
459 // hdop value
460 float hdop = (Float) trkPnt.get(GpxConstants.PT_HDOP);
461 if (hdop < 0) {
462 hdop = 0;
463 }
464 Color customColoringTransparent = hdopAlpha < 0 ? trkPnt.customColoring :
465 new Color(trkPnt.customColoring.getRGB() & 0x00ffffff | hdopAlpha << 24, true);
466 g.setColor(customColoringTransparent);
467 // hdop cirles
468 int hdopp = mv.getPoint(new LatLon(
469 trkPnt.getCoor().lat(),
470 trkPnt.getCoor().lon() + 2*6*hdop*360/40000000d)).x - screen.x;
471 g.drawArc(screen.x-hdopp/2, screen.y-hdopp/2, hdopp, hdopp, 0, 360);
472 }
473 if (large) {
474 // color the large GPS points like the gps lines
475 if (trkPnt.customColoring != null) {
476 Color customColoringTransparent = largePointAlpha < 0 ? trkPnt.customColoring :
477 new Color(trkPnt.customColoring.getRGB() & 0x00ffffff | largePointAlpha << 24, true);
478
479 g.setColor(customColoringTransparent);
480 }
481 g.fillRect(screen.x-halfSize, screen.y-halfSize, largesize, largesize);
482 }
483 } // end for trkpnt
484 } // end if large || hdopcircle
485
486 /****************************************************************
487 ********** STEP 3e - DRAW SMALL POINTS FOR LINES ***************
488 ****************************************************************/
489 if (!large && lines) {
490 g.setColor(neutralColor);
491 for (WayPoint trkPnt : visibleSegments) {
492 LatLon c = trkPnt.getCoor();
493 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
494 continue;
495 }
496 if (!trkPnt.drawLine) {
497 Point screen = mv.getPoint(trkPnt.getEastNorth());
498 g.drawRect(screen.x, screen.y, 0, 0);
499 }
500 } // end for trkpnt
501 } // end if large
502
503 /****************************************************************
504 ********** STEP 3f - DRAW SMALL POINTS INSTEAD OF LINES ********
505 ****************************************************************/
506 if (!large && !lines) {
507 g.setColor(neutralColor);
508 for (WayPoint trkPnt : visibleSegments) {
509 LatLon c = trkPnt.getCoor();
510 if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) {
511 continue;
512 }
513 Point screen = mv.getPoint(trkPnt.getEastNorth());
514 g.setColor(trkPnt.customColoring);
515 g.drawRect(screen.x, screen.y, 0, 0);
516 } // end for trkpnt
517 } // end if large
518 }
519
520 private void fixColors(List<WayPoint> visibleSegments) {
521 for (WayPoint trkPnt : visibleSegments) {
522 if (trkPnt.customColoring == null) {
523 trkPnt.customColoring = neutralColor;
524 }
525 }
526 }
527
528 /**
529 * Check cache validity set necessary flags
530 */
531 private void checkCache() {
532 if ((computeCacheMaxLineLengthUsed != maxLineLength) || (!neutralColor.equals(computeCacheColorUsed))
533 || (computeCacheColored != colored) || (computeCacheColorTracksTune != colorTracksTune)
534 || (computeCacheColorDynamic != colorModeDynamic)) {
535 computeCacheMaxLineLengthUsed = maxLineLength;
536 computeCacheInSync = false;
537 computeCacheColorUsed = neutralColor;
538 computeCacheColored = colored;
539 computeCacheColorTracksTune = colorTracksTune;
540 computeCacheColorDynamic = colorModeDynamic;
541 }
542 }
543
544 public void dataChanged() {
545 computeCacheInSync = false;
546 }
547
548 public void drawColorBar(Graphics2D g, MapView mv) {
549 int w = mv.getWidth();
550 if (colored == ColorMode.HDOP) {
551 hdopScale.drawColorBar(g, w-30, 50, 20, 100, 1.0);
552 } else if (colored == ColorMode.VELOCITY) {
553 velocityScale.drawColorBar(g, w-30, 50, 20, 100, 3.6);
554 } else if (colored == ColorMode.DIRECTION) {
555 directionScale.drawColorBar(g, w-30, 50, 20, 100, 180.0/Math.PI);
556 }
557 }
558}
Note: See TracBrowser for help on using the repository browser.