Created
January 25, 2024 04:27
-
-
Save nouvist/5eda2e14cb7ed4dfbaf07cd3343fc039 to your computer and use it in GitHub Desktop.
GLSL RGB-HSL Conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reference: | |
// https://stackoverflow.com/a/9493060/10940544 | |
vec4 toHsl(vec4 rgb) { | |
float r = rgb.r; | |
float g = rgb.g; | |
float b = rgb.b; | |
float maxColor = max(max(r, g), b); | |
float minColor = min(min(r, g), b); | |
float chroma = maxColor - minColor; | |
float h = 0.0; | |
float s = 0.0; | |
float l = (maxColor + minColor) / 2.0; | |
if (chroma == 0.0) { | |
return vec4(0.0, 0.0, l, rgb.a); | |
} | |
if (l < 0.5) { | |
s = chroma / (maxColor + minColor); | |
} else { | |
s = chroma / (2.0 - maxColor - minColor); | |
} | |
if (maxColor == r) { | |
h = (g - b) / chroma + ((g < b) ? 6.0 : 0.0); | |
} else if (maxColor == g) { | |
h = (b - r) / chroma + 2.0; | |
} else { | |
h = (r - g) / chroma + 4.0; | |
} | |
h /= 6.0; | |
return vec4(h, s, l, rgb.a); | |
} | |
float hslHelper(float p, float q, float t) { | |
if (t < 0.0) t += 1.0; | |
if (t > 1.0) t -= 1.0; | |
if (t < 1.0/6.0) return p + (q - p) * 6.0 * t; | |
if (t < 1.0/2.0) return q; | |
if (t < 2.0/3.0) return p + (q - p) * (2.0/3.0 - t) * 6; | |
return p; | |
} | |
vec4 fromHsl(vec4 hsl) { | |
float h = hsl.x; | |
float s = hsl.y; | |
float l = hsl.z; | |
if (s == 0.0) { | |
return vec4(l, l, l, hsl.a); | |
} | |
float q = 0.0; | |
if (l < 0.5) { | |
q = l * (1.0 + s); | |
} else { | |
q = l + s - l * s; | |
} | |
float p = 2.0 * l - q; | |
float r = hslHelper(p, q, h + 1.0/3.0); | |
float g = hslHelper(p, q, h); | |
float b = hslHelper(p, q, h - 1.0/3.0); | |
return vec4(r, g, b, hsl.a); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment