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