Devlog: Better Color Lerping in Shaders

After reading a few articles about color interpolation, I whipped up a  quick CG solution for lerping colors through the HSV color model.

You can read about this in this excellent series by Alan Zucconi. Happy shadering!

The Secrets of Colour Interpolation

Code Snippet

float3 HueToRGB(float hue)
{
 float h = hue * 6;

 return saturate(float3(abs(h - 3) - 1, 2 - abs(h - 2), 2 - abs(h - 4)));
}

float3 HSVToRGB(float3 hsv)
{
 float3 rgb = HueToRGB(hsv.x);
 float3 vc = ((rgb - 1) * hsv.y + 1) * hsv.z;

 return vc;
}

float3 RGBToHCV(float3 rgb)
{
 float4 p = (rgb.g < rgb.b) ? float4(rgb.b, rgb.g, -1, 2f / 3f) : float4(rgb.g, rgb.b, 0, -1f / 3f);
 float4 q = (rgb.r < p.x) ? float4(p.x, p.y, p.w, rgb.r) : float4(rgb.r, p.y, p.z, p.x);
 float c = q.x - min(q.w, q.y);
 float h = abs((q.w - q.y) / (6 * c + 1.0e-10f) + q.z);

 return float3(h, c, q.x);
}

float3 RGBToHSV(float3 rgb)
{
 float3 hcv = RGBToHCV(rgb);
 float s = hcv.y / (hcv.z + 1.0e-10f);

 return float3(hcv.x, s, hcv.z);
}

float3 LerpThroughHSV(float3 rgb1, float3 rgb2, float t)
{
 float3 hsv1 = RGBToHSV(rgb1);
 float3 hsv2 = RGBToHSV(rgb2);

 float3 hsv = lerp(hsv1, hsv2, t);

 return HSVToRGB(hsv);
}