Welcome to the Umamusume Wiki! If you want to contribute, please read the guidelines.

Module:Colors

From Umamusume Wiki
Jump to navigation Jump to search

Documentation for this module may be created at Module:Colors/doc

local p = {}

-- https://gist.github.com/fernandohenriques/12661bf250c8c2d8047188222cab7e28
function p.hexToRgb(hex)
    local hexR = hex:gsub("#","")
    if hexR:len() == 3 then
      return (tonumber("0x"..hexR:sub(1,1))*17)/255, (tonumber("0x"..hexR:sub(2,2))*17)/255, (tonumber("0x"..hexR:sub(3,3))*17)/255
    else
      return tonumber("0x"..hexR:sub(1,2))/255, tonumber("0x"..hexR:sub(3,4))/255, tonumber("0x"..hexR:sub(5,6))/255
    end
end

function p.rgbToHex(r, g, b)
    local rp = math.floor(r * 255)
    local gp = math.floor(g * 255)
    local bp = math.floor(b * 255)
    local raw = (rp * 0x10000) + (gp * 0x100) + bp
    return string.format("%x", raw)
end

-- HSV/RGB formulas from https://en.wikipedia.org/wiki/HSL_and_HSV#Color_conversion_formulae

function p.rgbToHsv(r, g, b)
    local cMax = math.max(r, g, b)
    local cMin = math.min(r, g, b)
    local delta = cMax - cMin

    local h, s, v

    -- hue
    if cMax == cMin then
        h = 0
    else
        if cMax == r then
            h = (g - b) / delta
            if h < 0 then
                h = h + 6
            end
        elseif cMax == g then
            h = ((b - r) / delta) + 2
        elseif cMax == b then
            h = ((r - g) / delta) + 4
        end
        h = (h / 6) -- rescale from 0 to 1
    end

    -- saturation
    if cMax == 0 then
        s = 0
    else
        s = delta / cMax
    end

    -- value
    v = cMax

    return h, s, v
end

function p.hsvToRgb(h, s, v)
    local c = s * v
    local hp = h * 6
    local hpf = math.floor(hp)
    local x = c * (1 - math.abs(hp % 2 - 1))

    local r1, g1, b1
    if hpf == 0 then
        r1, g1, b1 = c, x, 0
    elseif hpf == 1 then
        r1, g1, b1 = x, c, 0
    elseif hpf == 2 then
        r1, g1, b1 = 0, c, x
    elseif hpf == 3 then
        r1, g1, b1 = 0, x, c
    elseif hpf == 4 then
        r1, g1, b1 = x, 0, c
    elseif hpf == 5 then
        r1, g1, b1 = c, 0, x
    end

    local m = v - c

    return r1 + m, g1 + m, b1 + m
end

function p.hexToHsv(hex)
    local r, g, b = p.hexToRgb(hex)
    return p.rgbToHsv(r, g, b)
end

function p.hsvToHex(h, s, v)
    local r, g, b = p.hsvToRgb(h, s, v)
    return p.rgbToHex(r, g, b)
end

function p.findHighContrastColor(colorHex, backColorHex)
    local h, s, v = p.hexToHsv(colorHex)
    local bh, bs, bv = p.hexToHsv(backColorHex)
    if bv < 0.5 and v < 0.5 then
        v = 0.6
    elseif bv >= 0.5 and v >= 0.5 then
        v = 0.5
    end
    return p.hsvToHex(h, s, v)
end

return p