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

Last change on this file since 9338 was 9338, checked in by simon04, 9 years ago

fix #12312 - Error when loading GPX file with single point and track dynamic track coloring

Regression of r9234.

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