-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrgbhsl.lua
31 lines (29 loc) · 1009 Bytes
/
rgbhsl.lua
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
-- h, s, l, r, g, b, are all in range [0, 1]
local function hslToRgb(h, s, l)
if s == 0 then return l, l, l end
local function to(p, q, t)
if t < 0 then t = t + 1 end
if t > 1 then t = t - 1 end
if t < .16667 then return p + (q - p) * 6 * t end
if t < .5 then return q end
if t < .66667 then return p + (q - p) * (.66667 - t) * 6 end
return p
end
local q = l < .5 and l * (1 + s) or l + s - l * s
local p = 2 * l - q
return to(p, q, h + .33334), to(p, q, h), to(p, q, h - .33334)
end
local function rgbToHsl(r, g, b)
local max, min = math.max(r, g, b), math.min(r, g, b)
local b = max + min
local h = b / 2
if max == min then return 0, 0, h end
local s, l = h, h
local d = max - min
s = l > .5 and d / (2 - b) or d / b
if max == r then h = (g - b) / d + (g < b and 6 or 0)
elseif max == g then h = (b - r) / d + 2
elseif max == b then h = (r - g) / d + 4
end
return h * .16667, s, l
end