]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network/src/org/simantics/district/network/profile/Colors.java
Make more discrete colors available to support more steep functions
[simantics/district.git] / org.simantics.district.network / src / org / simantics / district / network / profile / Colors.java
1 package org.simantics.district.network.profile;
2
3 import java.awt.Color;
4
5 /**
6  * @author Tuukka Lehtonen
7  * @since 1.35.0
8  */
9 public class Colors {
10
11     private static class Cache implements ColorGradient {
12         private final ColorGradient proxy;
13         private final int discretization;
14         private final Color[] cache;
15
16         public Cache(ColorGradient proxy, int discretization) {
17             this.proxy = proxy;
18             this.discretization = discretization;
19             this.cache = new Color[discretization+1];
20         }
21
22         private int discretize(double t) {
23             return (int) (saturate(t) * discretization);
24         }
25
26         @Override
27         public Color get(double t) {
28             int d = discretize(t);
29             Color cached = cache[d];
30             if (cached != null)
31                 return cached;
32             cached = cache[d] = proxy.get(t);
33             return cached;
34         }
35     }
36
37     public static final ColorGradient cached(ColorGradient cg) {
38         return new Cache(cg, 2048);
39     }
40
41     public static final ColorGradient hsvGradient(float hue, float saturation) {
42         return t -> {
43             return Color.getHSBColor(hue, saturation, saturate((float) t));
44         };
45     }
46
47     private static float saturate(float t) {
48         return Math.max(0f, Math.min(t, 1f));
49     }
50
51     private static double saturate(double t) {
52         return Math.max(0, Math.min(t, 1));
53     }
54
55 }