authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2023-09-14 20:22:25 -07:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2023-09-14 20:22:25 -07:00
log80ac29e7cdcfdc1728c92047ea571cb01dc9f626
treed77b9784de4081d96791886e0f7abc280b06a308
parent91c035aab08e631ab7592635ae945c4921cfc696

add HSL


4 files changed, 49 insertions(+), 0 deletions(-)

HSL.zig created+26
...@@ -0,0 +1,26 @@
1//! object representing a single color in the HSL colorspace with h channel value from 0-360 and s,l channel values from 0-1
2
3const std = @import("std");
4const Self = @This();
5
6h: f32, // hue
7s: f32, // saturation
8l: f32, // luminance
9a: f32, // alpha
10
11pub fn initHSLA(h: f32, s: f32, l: f32, a: f32) Self {
12 std.debug.assert(h >= 0.0 and h <= 1.0);
13 std.debug.assert(s >= 0.0 and s <= 1.0);
14 std.debug.assert(l >= 0.0 and l <= 1.0);
15 std.debug.assert(a >= 0.0 and a <= 1.0);
16 return Self{
17 .h = h,
18 .s = s,
19 .l = l,
20 .a = a,
21 };
22}
23
24pub fn eql(x: Self, y: Self) bool {
25 return x.h == y.h and x.s == y.s and x.l == y.l and x.a == y.a;
26}
mod.zig+1
...@@ -4,3 +4,4 @@ const color = @This();...@@ -4,3 +4,4 @@ const color = @This();
4pub const sRGB = @import("./sRGB.zig");4pub const sRGB = @import("./sRGB.zig");
5pub const LinearRgb = @import("./LinearRgb.zig");5pub const LinearRgb = @import("./LinearRgb.zig");
6pub const CMYK = @import("./CMYK.zig");6pub const CMYK = @import("./CMYK.zig");
7pub const HSL = @import("./HSL.zig");
sRGB.zig+19
...@@ -3,6 +3,7 @@...@@ -3,6 +3,7 @@
3const std = @import("std");3const std = @import("std");
4const Self = @This();4const Self = @This();
5const color = @import("./mod.zig");5const color = @import("./mod.zig");
6const _x = @import("./x.zig");
67
7r: u8, // red value8r: u8, // red value
8g: u8, // green value9g: u8, // green value
...@@ -107,3 +108,21 @@ pub fn to_cmyk(x: Self) color.CMYK {...@@ -107,3 +108,21 @@ pub fn to_cmyk(x: Self) color.CMYK {
107 const a = f.a;108 const a = f.a;
108 return color.CMYK.initCMYKA(c, m, y, k, a);109 return color.CMYK.initCMYKA(c, m, y, k, a);
109}110}
111
112pub fn to_hsl(x: Self) color.HSL {
113 const f = x.to_float();
114 const cmax = @max(f.r, f.g, f.b);
115 const cmin = @min(f.r, f.g, f.b);
116 const delta = cmax - cmin;
117 const h = blk: {
118 if (delta == 0) break :blk 0;
119 if (cmax == f.r) break :blk ((((f.g - f.b) / delta) % 6) * 60) % 360;
120 if (cmax == f.g) break :blk ((((f.b - f.r) / delta) + 2) * 60) % 360;
121 if (cmax == f.b) break :blk ((((f.r - f.g) / delta) + 4) * 60) % 360;
122 unreachable;
123 };
124 const l = (cmax + cmin) / 2;
125 const s = if (delta == 0) 0 else delta / (1 - _x.abs(2 * l - 1));
126 const a = f.a;
127 return color.HSL.initHSLA(h, s, l, a);
128}
x.zig created+3
...@@ -0,0 +1,3 @@
1pub fn abs(x: f32) f32 {
2 return if (x < 0.0) -x else x;
3}