forked from gradientspace/geometry3Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathColorHSV.cs
150 lines (124 loc) · 3.77 KB
/
ColorHSV.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace g3
{
public class ColorHSV
{
public float h;
public float s;
public float v;
public float a;
public ColorHSV(float h, float s, float v, float a = 1) { this.h = h; this.s = s; this.v = v; this.a = a; }
public ColorHSV(Colorf rgb) {
ConvertFromRGB(rgb);
}
public Colorf RGBA {
get {
return ConvertToRGB();
}
set { ConvertFromRGB(value); }
}
public Colorf ConvertToRGB()
{
float h = this.h;
float s = this.s;
float v = this.v;
if (h > 360)
h -= 360;
if (h < 0)
h += 360;
h = MathUtil.Clamp(h, 0.0f, 360.0f);
s = MathUtil.Clamp(s, 0.0f, 1.0f);
v = MathUtil.Clamp(v, 0.0f, 1.0f);
float c = v * s;
float x = c * (1 - Math.Abs( ((h / 60.0f) % 2) - 1) );
float m = v - c;
float rp, gp, bp;
int a = (int)(h / 60.0f);
switch (a) {
case 0:
rp = c;
gp = x;
bp = 0;
break;
case 1:
rp = x;
gp = c;
bp = 0;
break;
case 2:
rp = 0;
gp = c;
bp = x;
break;
case 3:
rp = 0;
gp = x;
bp = c;
break;
case 4:
rp = x;
gp = 0;
bp = c;
break;
default: // case 5:
rp = c;
gp = 0;
bp = x;
break;
}
return new Colorf(
MathUtil.Clamp(rp + m,0,1),
MathUtil.Clamp(gp + m,0,1),
MathUtil.Clamp(bp + m,0,1), this.a);
}
public void ConvertFromRGB(Colorf rgb)
{
this.a = rgb.a;
float rp = rgb.r, gp = rgb.g, bp = rgb.b;
float cmax = rp;
int cmaxwhich = 0; /* faster comparison afterwards */
if (gp > cmax) { cmax = gp; cmaxwhich = 1; }
if (bp > cmax) { cmax = bp; cmaxwhich = 2; }
float cmin = rp;
//int cminwhich = 0;
if (gp < cmin) { cmin = gp; /*cminwhich = 1;*/ }
if (bp < cmin) { cmin = bp; /*cminwhich = 2;*/ }
float delta = cmax - cmin;
/* HUE */
if (delta == 0) {
this.h = 0;
} else {
switch (cmaxwhich) {
case 0: /* cmax == rp */
h = 60.0f * ( ((gp - bp) / delta) % 6.0f );
break;
case 1: /* cmax == gp */
h = 60.0f * (((bp - rp) / delta) + 2);
break;
case 2: /* cmax == bp */
h = 60.0f * (((rp - gp) / delta) + 4);
break;
}
if (h < 0)
h += 360.0f;
}
/* LIGHTNESS/VALUE */
//l = (cmax + cmin) / 2;
v = cmax;
/* SATURATION */
/*if (delta == 0) {
*r_s = 0;
} else {
*r_s = delta / (1 - fabs (1 - (2 * (l - 1))));
}*/
if (cmax == 0) {
s = 0;
} else {
s = delta / cmax;
}
}
}
}