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

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

Extent the unit test for GpxDrawHelper

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