| 1 | //! object representing a single color in the HSV colorspace with h channel value from 0-360 and s,v channel values from 0-1 |
| 2 | |
| 3 | const std = @import("std"); |
| 4 | const Self = @This(); |
| 5 | const color = @import("./mod.zig"); |
| 6 | const _x = @import("./_x.zig"); |
| 7 | |
| 8 | h: f32, // hue [ 0 .. 1 ] |
| 9 | s: f32, // saturation [ 0 .. 1 ] |
| 10 | v: f32, // value [ 0 .. 1 ] |
| 11 | a: f32, // alpha [ 0 .. 1 ] |
| 12 | |
| 13 | pub fn initHSVA(h: f32, s: f32, v: f32, a: f32) Self { |
| 14 | std.debug.assert(h >= 0.0 and h <= 1.0); |
| 15 | std.debug.assert(s >= 0.0 and s <= 1.0); |
| 16 | std.debug.assert(v >= 0.0 and v <= 1.0); |
| 17 | std.debug.assert(a >= 0.0 and a <= 1.0); |
| 18 | return Self{ |
| 19 | .h = h, |
| 20 | .s = s, |
| 21 | .v = v, |
| 22 | .a = a, |
| 23 | }; |
| 24 | } |
| 25 | |
| 26 | pub fn eql(x: Self, y: Self) bool { |
| 27 | return x.h == y.h and x.s == y.s and x.v == y.v and x.a == y.a; |
| 28 | } |
| 29 | |
| 30 | const M = _x.mixin(@This(), f32, .h, .s, .v); |
| 31 | pub const to_vec = M.to_vec; |
| 32 | pub const from_vec = M.from_vec; |
| 33 | pub const to_array = M.to_array; |
| 34 | |
| 35 | // https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB |
| 36 | // https://www.rapidtables.com/convert/color/hsv-to-rgb.html |
| 37 | pub fn to_srgb(t: Self) color.sRGB { |
| 38 | var h, const s, const v, const a = t.to_array(); |
| 39 | h *= 360.0; |
| 40 | h /= 60.0; |
| 41 | const c = v * s; |
| 42 | const x = c * (1 - @abs(@rem(h, 2.0) - 1.0)); |
| 43 | const r, const g, const b = blk: { |
| 44 | if (h >= 0.0 and h < 1.0) break :blk .{ c, x, 0 }; |
| 45 | if (h >= 1.0 and h < 2.0) break :blk .{ x, c, 0 }; |
| 46 | if (h >= 2.0 and h < 3.0) break :blk .{ 0, c, x }; |
| 47 | if (h >= 3.0 and h < 4.0) break :blk .{ 0, x, c }; |
| 48 | if (h >= 4.0 and h < 5.0) break :blk .{ x, 0, c }; |
| 49 | if (h >= 5.0 and h < 6.0) break :blk .{ c, 0, x }; |
| 50 | unreachable; |
| 51 | }; |
| 52 | const m = v - c; |
| 53 | return color.sRGB.from_float(.{ r + m, g + m, b + m, a }); |
| 54 | } |