]> git.lizzy.rs Git - nothing.git/blob - src/color.c
(#893) Implement level_editor_dump
[nothing.git] / src / color.c
1 #include <SDL.h>
2 #include <string.h>
3
4 #include "color.h"
5
6 Color rgba(float r, float g, float b, float a)
7 {
8     const Color result = {
9         .r = r,
10         .g = g,
11         .b = b,
12         .a = a
13     };
14
15     return result;
16 }
17
18 static Uint8 hex2dec_digit(char c)
19 {
20     if (c >= '0' && c <= '9') {
21         return (Uint8) (c - '0');
22     }
23
24     if (c >= 'A' && c <= 'F') {
25         return (Uint8) (10 + c - 'A');
26     }
27
28     if (c >= 'a' && c <= 'f') {
29         return (Uint8) (10 + c - 'a');
30     }
31
32     return 0;
33 }
34
35 static Uint8 parse_color_component(const char *component)
36 {
37     return (Uint8) (hex2dec_digit(component[0]) * 16 + hex2dec_digit(component[1]));
38 }
39
40 Color hexstr(const char *hexstr)
41 {
42     if (strlen(hexstr) != 6) {
43         return rgba(0.0f, 0.0f, 0.0f, 1.0f);
44     }
45
46     return rgba(
47         parse_color_component(hexstr) / 255.0f,
48         parse_color_component(hexstr + 2) / 255.0f,
49         parse_color_component(hexstr + 4) / 255.0f,
50         1.0f);
51 }
52
53 SDL_Color color_for_sdl(Color color)
54 {
55     const SDL_Color result = {
56         .r = (Uint8)roundf(color.r * 255.0f),
57         .g = (Uint8)roundf(color.g * 255.0f),
58         .b = (Uint8)roundf(color.b * 255.0f),
59         .a = (Uint8)roundf(color.a * 255.0f)
60     };
61
62     return result;
63 }
64
65 Color color_desaturate(Color c)
66 {
67     const float k = (c.r + c.g + c.b) / 3.0f;
68     return rgba(k, k, k, c.a);
69 }
70
71 Color color_darker(Color c, float d)
72 {
73     return rgba(fmaxf(c.r - d, 0.0f),
74                 fmaxf(c.g - d, 0.0f),
75                 fmaxf(c.b - d, 0.0f),
76                 c.a);
77 }
78
79 Color color_invert(Color c)
80 {
81     return rgba(1.0f - c.r, 1.0f - c.g, 1.0f - c.b, c.a);
82 }
83
84 Color color_scale(Color c, Color fc)
85 {
86     return rgba(
87         fmaxf(fminf(c.r * fc.r, 1.0f), 0.0f),
88         fmaxf(fminf(c.g * fc.g, 1.0f), 0.0f),
89         fmaxf(fminf(c.b * fc.b, 1.0f), 0.0f),
90         fmaxf(fminf(c.a * fc.a, 1.0f), 0.0f));
91 }
92
93 int color_hex_to_stream(Color color, FILE *stream)
94 {
95     SDL_Color sdl = color_for_sdl(color);
96     return fprintf(stream, "%02x%02x%02x", sdl.r, sdl.g, sdl.b);
97 }