| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include "color-util.h" |
| 4 |
#include "math-util.h" |
| 5 |
|
| 6 |
void rgb_to_hsv(double r, double g, double b, |
| 7 |
double *ret_h, double *ret_s, double *ret_v) { |
| 8 |
|
| 9 |
assert(r >= 0 && r <= 1); |
| 10 |
assert(g >= 0 && g <= 1); |
| 11 |
assert(b >= 0 && b <= 1); |
| 12 |
|
| 13 |
double max_color = MAX(r, MAX(g, b)); |
| 14 |
double min_color = MIN(r, MIN(g, b)); |
| 15 |
double delta = max_color - min_color; |
| 16 |
|
| 17 |
if (ret_v) |
| 18 |
*ret_v = max_color * 100.0; |
| 19 |
|
| 20 |
if (max_color <= 0) { |
| 21 |
if (ret_s) |
| 22 |
*ret_s = 0; |
| 23 |
if (ret_h) |
| 24 |
*ret_h = NAN; |
| 25 |
return; |
| 26 |
} |
| 27 |
|
| 28 |
if (ret_s) |
| 29 |
*ret_s = delta / max_color * 100.0; |
| 30 |
|
| 31 |
if (ret_h) { |
| 32 |
if (delta > 0) { |
| 33 |
if (r >= max_color) |
| 34 |
*ret_h = 60 * (g - b) / delta; |
| 35 |
else if (g >= max_color) |
| 36 |
*ret_h = 60 * (((b - r) / delta) + 2); |
| 37 |
else /* b >= max_color */ |
| 38 |
*ret_h = 60 * (((r - g) / delta) + 4); |
| 39 |
|
| 40 |
/* The r-max branch produces (-60, 60); fold the negative half up. */ |
| 41 |
if (*ret_h < 0) |
| 42 |
*ret_h += 360; |
| 43 |
} else |
| 44 |
*ret_h = NAN; |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
void hsv_to_rgb(double h, double s, double v, |
| 49 |
uint8_t* ret_r, uint8_t *ret_g, uint8_t *ret_b) { |
| 50 |
|
| 51 |
double c, x, m, r, g, b; |
| 52 |
|
| 53 |
assert(h >= 0 && h <= 360); |
| 54 |
assert(s >= 0 && s <= 100); |
| 55 |
assert(v >= 0 && v <= 100); |
| 56 |
assert(ret_r); |
| 57 |
assert(ret_g); |
| 58 |
assert(ret_b); |
| 59 |
|
| 60 |
c = (s / 100.0) * (v / 100.0); |
| 61 |
m = (v / 100) - c; |
| 62 |
|
| 63 |
/* Split h into sector index k ∈ [0, 6] and fractional offset f ∈ [0, 1) within the sector. |
| 64 |
* Within each sector exactly one of {r, g, b} equals c, one equals 0, and the third (x) |
| 65 |
* ramps linearly between them — ascending in even sectors, descending in odd. h == 360 is |
| 66 |
* the cyclic boundary equivalent to h == 0, and maps to sector 0. */ |
| 67 |
double seg = h / 60.0; |
| 68 |
int k = (int) seg % 6; |
| 69 |
double f = seg - (int) seg; |
| 70 |
x = c * (k & 1 ? 1.0 - f : f); |
| 71 |
|
| 72 |
switch (k) { |
| 73 |
case 0: r = c; g = x; b = 0.0; break; |
| 74 |
case 1: r = x; g = c; b = 0.0; break; |
| 75 |
case 2: r = 0.0; g = c; b = x; break; |
| 76 |
case 3: r = 0.0; g = x; b = c; break; |
| 77 |
case 4: r = x; g = 0.0; b = c; break; |
| 78 |
default: r = c; g = 0.0; b = x; break; |
| 79 |
} |
| 80 |
|
| 81 |
*ret_r = (uint8_t) ((r + m) * 255); |
| 82 |
*ret_g = (uint8_t) ((g + m) * 255); |
| 83 |
*ret_b = (uint8_t) ((b + m) * 255); |
| 84 |
} |