Skip to content

Instantly share code, notes, and snippets.

@mminer
Created March 11, 2022 23:36
Show Gist options
  • Save mminer/fb994ee73c4f6ef2b3e9fa851e2de2b0 to your computer and use it in GitHub Desktop.
Save mminer/fb994ee73c4f6ef2b3e9fa851e2de2b0 to your computer and use it in GitHub Desktop.
Structs to represent HSL and HSV colours in Unity.
using UnityEngine;
/// <summary>
/// Represents a color with hue, saturation, and lightness.
/// </summary>
readonly struct HSL
{
public Color Color => HSV.FromHSL(this).Color;
public readonly float H;
public readonly float S;
public readonly float L;
public HSL(float H, float S, float L)
{
this.H = H;
this.S = S;
this.L = L;
}
public static HSL FromColor(Color color)
{
var hsv = HSV.FromColor(color);
return FromHSV(hsv);
}
public static HSL FromHSV(HSV hsv)
{
// https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_HSL
var H = hsv.H;
var L = hsv.V * (1 - hsv.S / 2);
var S = L > 0 && L < 1 ? (hsv.V - L) / Mathf.Min(L, 1 - L) : 0;
return new HSL(H, S, L);
}
}
/// <summary>
/// Represents a color with hue, saturation, and value.
/// </summary>
readonly struct HSV
{
public Color Color => Color.HSVToRGB(H, S, V);
public readonly float H;
public readonly float S;
public readonly float V;
public HSV(float H, float S, float V)
{
this.H = H;
this.S = S;
this.V = V;
}
public static HSV FromColor(Color color)
{
Color.RGBToHSV(color, out var H, out var S, out var V);
return new HSV(H, S, V);
}
public static HSV FromHSL(HSL hsl)
{
// https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_HSV
var H = hsl.H;
var V = hsl.L + hsl.S * Mathf.Min(hsl.L, 1 - hsl.L);
var S = V > 0 ? 2 * (1 - hsl.L / V) : 0;
return new HSV(H, S, V);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment