]> git.lizzy.rs Git - nothing.git/blobdiff - src/color.c
TODO(#388)
[nothing.git] / src / color.c
index aa1a5a63e86bf575d200e3cc71ca0932398ed8e9..32b46efa4cf463e5700ab06bba52546799a79b47 100644 (file)
@@ -1,10 +1,11 @@
 #include <SDL2/SDL.h>
+#include <string.h>
 
-#include "./color.h"
+#include "color.h"
 
-color_t color(float r, float g, float b, float a)
+Color color(float r, float g, float b, float a)
 {
-    const color_t result = {
+    const Color result = {
         .r = r,
         .g = g,
         .b = b,
@@ -14,7 +15,7 @@ color_t color(float r, float g, float b, float a)
     return result;
 }
 
-color_t color256(Uint8 r, Uint8 g, Uint8 b, Uint8 a)
+Color color256(Uint8 r, Uint8 g, Uint8 b, Uint8 a)
 {
     return color(
         (float) r / 255.0f,
@@ -23,7 +24,42 @@ color_t color256(Uint8 r, Uint8 g, Uint8 b, Uint8 a)
         (float) a / 255.0f);
 }
 
-SDL_Color color_for_sdl(color_t color)
+static Uint8 hex2dec_digit(char c)
+{
+    if (c >= '0' && c <= '9') {
+        return (Uint8) (c - '0');
+    }
+
+    if (c >= 'A' && c <= 'F') {
+        return (Uint8) (10 + c - 'A');
+    }
+
+    if (c >= 'a' && c <= 'f') {
+        return (Uint8) (10 + c - 'a');
+    }
+
+    return 0;
+}
+
+static Uint8 parse_color_component(const char *component)
+{
+    return (Uint8) (hex2dec_digit(component[0]) * 16 + hex2dec_digit(component[1]));
+}
+
+Color color_from_hexstr(const char *hexstr)
+{
+    if (strlen(hexstr) != 6) {
+        return color(0.0f, 0.0f, 0.0f, 1.0f);
+    }
+
+    return color256(
+        parse_color_component(hexstr),
+        parse_color_component(hexstr + 2),
+        parse_color_component(hexstr + 4),
+        255);
+}
+
+SDL_Color color_for_sdl(Color color)
 {
     const SDL_Color result = {
         .r = (Uint8)roundf(color.r * 255.0f),
@@ -35,8 +71,16 @@ SDL_Color color_for_sdl(color_t color)
     return result;
 }
 
-color_t color_desaturate(color_t c)
+Color color_desaturate(Color c)
 {
     const float k = (c.r + c.g + c.b) / 3.0f;
     return color(k, k, k, c.a);
 }
+
+Color color_darker(Color c, float d)
+{
+    return color(fmaxf(c.r - d, 0.0f),
+                 fmaxf(c.g - d, 0.0f),
+                 fmaxf(c.b - d, 0.0f),
+                 c.a);
+}