1 package org.opentrafficsim.core.gtu.animation;
2
3 import java.awt.Color;
4 import java.io.Serializable;
5 import java.util.ArrayList;
6 import java.util.Collections;
7 import java.util.List;
8
9 import org.djunits.value.vdouble.scalar.Speed;
10 import org.opentrafficsim.core.gtu.GTU;
11
12
13
14
15
16
17
18
19
20
21
22
23 public class SpeedGTUColorer implements GTUColorer, Serializable
24 {
25
26 private static final long serialVersionUID = 20150000L;
27
28
29 private final ArrayList<LegendEntry> legend;
30
31
32 private final Speed maximumSpeed;
33
34
35
36
37
38 public SpeedGTUColorer(final Speed maximumSpeed)
39 {
40 this.maximumSpeed = maximumSpeed;
41 this.legend = new ArrayList<>(4);
42 Color[] colorTable = { Color.RED, Color.YELLOW, Color.GREEN };
43 Speed zeroValue = new Speed(0, maximumSpeed.getUnit());
44 for (int index = 0; index < colorTable.length; index++)
45 {
46 double ratio = index * 1.0 / (colorTable.length - 1);
47 Speed speed = Speed.interpolate(zeroValue, maximumSpeed, ratio);
48 String label = speed.toString().replaceFirst("\\.0*|,0*", ".0");
49 this.legend.add(new LegendEntry(colorTable[index], label, index == 0 ? "stationary" : "driving " + label));
50 }
51 }
52
53
54 @Override
55 public final Color getColor(final GTU gtu)
56 {
57 Speed speed = gtu.getSpeed();
58 double ratio = speed.getSI() / this.maximumSpeed.getSI() * (this.legend.size() - 1);
59 if (ratio <= 0)
60 {
61 return this.legend.get(0).getColor();
62 }
63 if (ratio >= this.legend.size() - 1)
64 {
65 return this.legend.get(this.legend.size() - 1).getColor();
66 }
67
68 int floor = (int) Math.floor(ratio);
69 return ColorInterpolator.interpolateColor(this.legend.get(floor).getColor(), this.legend.get(floor + 1).getColor(),
70 ratio - floor);
71 }
72
73
74 @Override
75 public final List<LegendEntry> getLegend()
76 {
77 return Collections.unmodifiableList(this.legend);
78 }
79
80
81 @Override
82 public final String toString()
83 {
84 return "Speed";
85 }
86
87 }