diff --git a/colors.lua b/colors.lua index 363a40c..7812a28 100644 --- a/colors.lua +++ b/colors.lua @@ -2,9 +2,19 @@ This is a collection of functions for performing color operations, designed to work with the LÖVE game engine. - See `README_COLOR_TOOLS.md` for full documentation. - LICENSE is BEER-WARE. + + # Documentation # + + Supports following color formats: + + - `rgb255`: The standard computer representation, with each + channel (red, green, blue, alpha) in the [0-255] range. Alpha + channel (index 4), can either be explicit or implicit (and taken + to be 255.) + - `rgb1`: As above, except channels are in the [0-1] range. + - `hsl`: Hue-saturation-lightness representation (does not support alpha). + Hue channel is in the [0-1] range, instead of the standard [0-2*pi] range. ]] local GAMMA = 2.2 @@ -12,11 +22,59 @@ local GAMMA_INV = 1/GAMMA local colors = {} +-------------------------------------------------------------------------------- +-- Formats + +local function is_rgb255 (c) + -- Assert table with certain length + if type(c) ~= 'table' or #c < 3 then + return false + end + + -- Check that entries are numbers + for i = 1, math.min(#c, 3) do + if type(c[i]) ~= 'number' then return false end + end + + -- + return true +end + +is_rgb1 = is_rgb255 + +local function is_hsl (c) + -- Assert table with certain length + if type(c) ~= 'table' or #c < 3 then + return false + end + + -- Check that entries are numbers + for i = 1, math.min(#c, 3) do + if type(c[i]) ~= 'number' then return false end + end + + -- + return true +end + -------------------------------------------------------------------------------- -- Conversion -colors.rgb255_to_rgb1 = function (color) - return { color[1]/255, color[2]/255, color[3]/255, (color[4] or 255)/255 } +local function mult_channels (multiplier, default, color, ...) + local r, g, b, a = color, ... + if type(color) == 'table' then + r, g, b, a = unpack(color) + end + + return { r*multiplier, g*multiplier, b*multiplier, a and a*multiplier or default } +end + +colors.rgb255_to_rgb1 = function (...) + return mult_channels(1/255, 1, ...) +end + +colors.rgb1_to_rgb255 = function (...) + return mult_channels(255, 255, ...) end colors.rgb_to_hsl = function (color)