summaryrefslogtreecommitdiff
path: root/color.c
blob: 9522fd5dc7cf79f7c6e47cda3c7e8768650d3887 (plain)
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
#include <math.h>

#include "color.h"


void hsv_to_rgb(struct hsvf *hsv, struct rgbf *rgb) {
    float h = hsv->h, s = hsv->s, v = hsv->v;
    float c = v * s; // Chroma
    float hmod = fmodf(h * 6.0f, 6.0f);
    float x = c * (1.0f - fabsf(fmodf(hmod, 2.0f) - 1.0f));
    float m = v - c;

    switch ((int)hmod) {
        case 0:
            rgb->r = c; rgb->g = x; rgb->b = 0;
            break;
        case 1:
            rgb->r = x; rgb->g = c; rgb->b = 0;
            break;
        case 2:
            rgb->r = 0; rgb->g = c; rgb->b = x;
            break;
        case 3:
            rgb->r = 0; rgb->g = x; rgb->b = c;
            break;
        case 4:
            rgb->r = x; rgb->g = 0; rgb->b = c;
            break;
        case 5:
            rgb->r = c; rgb->g = 0; rgb->b = x;
            break;
        default:
            rgb->r = 0; rgb->g = 0; rgb->b = 0;
    }

    rgb->r += m;
    rgb->g += m;
    rgb->b += m;
}