HSV to RGB Material Function in Unreal Engine
Unlike in previous posts, this one is not about any specific shader, but rather about a material function that I find pretty useful at times. Sometimes it might be desirable not to work with RGB colors, but use a more natural HSV (hue, saturation, value) model. Unreal Engine offers a node to transform RGB to HSV, but unfortunately not back.
Algorithm
The simplest way to transform color from HSV to RGB, along with the explanation, can be found at this wiki page. This way however requires branching, which is often not perfect for GPUs. Instead we can use branch-less computation (for more details I suggest you take a look at Sam's Lolengine.com page, as the algorithm is taken from there).
Setup
Create material function within UE and add Custom Node. It will have one input parameter, I'll call it HSV and it will return Vector3. For function to work we will also need Vector3 Input Node to feed the value to the function from outside.
Code
Following code was taken from Sam's Lolengine.com post and transformed to work with UE.
float s = HSV.y;
float v = HSV.z;
float4 K = float4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
float3 p = abs(frac(HSV.xxx + K.xyz) * 6.0 - K.www);
return v * lerp(K.xxx, clamp(p - K.xxx, 0.0, 1.0), s);
float v = HSV.z;
float4 K = float4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
float3 p = abs(frac(HSV.xxx + K.xyz) * 6.0 - K.www);
return v * lerp(K.xxx, clamp(p - K.xxx, 0.0, 1.0), s);
References
HSV model - wiki page for HSV model
Fast RGB to HSV implementation - by Sam from Lolengine.com
HSV to RGB in GLSL - by Sam from Lolengine.com
Comments
Post a Comment