- Home /
How to compare colors in Shaders?
How do I compare two colors inside the shader fragment function?
I want to make a simple shader to swap a pixel color so I'm using this line:
if (all(c.rgb == _InColor.rgb)) c = _OutColor;
Both c and _InColor are typed as half4. The colors are not swapping at all.
I known this type of comparation is bad for performance but idk how to make it better. Suggestions?
Full shader:
Shader "Sprites/Palette 01"
{
Properties
{
[PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
_Color("Tint", Color) = (1,1,1,1)
_InColor("In Color", Color) = (0,0,0,0)
_OutColor("Out Color", Color) = (0,0,0,0)
[MaterialToggle] PixelSnap("Pixel snap", Float) = 0
[HideInInspector] _RendererColor("RendererColor", Color) = (1,1,1,1)
[HideInInspector] _Flip("Flip", Vector) = (1,1,1,1)
[PerRendererData] _AlphaTex("External Alpha", 2D) = "white" {}
[PerRendererData] _EnableExternalAlpha("Enable External Alpha", Float) = 0
}
SubShader
{
Tags
{
"Queue" = "Transparent"
"IgnoreProjector" = "True"
"RenderType" = "Transparent"
"PreviewType" = "Plane"
"CanUseSpriteAtlas" = "True"
}
Cull Off
Lighting Off
ZWrite Off
Blend One OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex SpriteVert
#pragma fragment PaletteSwapFrag
#pragma target 2.0
#pragma multi_compile_instancing
#pragma multi_compile_local _ PIXELSNAP_ON
#pragma multi_compile _ ETC1_EXTERNAL_ALPHA
#include "UnitySprites.cginc"
half4 _InColor;
half4 _OutColor;
half4 PaletteSwapFrag(v2f IN) : SV_Target
{
half4 c = tex2D(_MainTex, IN.texcoord);
if (all(c.rgb == _InColor.rgb)) c = _OutColor;
c.rgb *= c.a * IN.color;
return c;
}
ENDCG
}
}
}
Answer by pmerilainen · Jul 11, 2019 at 10:07 AM
could this work (note that I made up the variable names, 0.1 is the tolerance value; you can add it as a parameter as well)
half3 delta = abs(texColor.rgb - colorKey.rgb);
half3 rgb =length(delta) < 0.1 ? replace_color.rgb : IN.color.rgb;
result.color = half4(rgb, IN.color.a);
directly subtracting the two colors for a total difference is taking time to evaluate all three color channel's differences every time. ins$$anonymous$$d of using the color class's subtraction operator. you could reduce the tollerance calculation in half by not looking at the other channels if the first channels do not match.
Actually, no. The GPU is a pipeline processor. A pipeline is setup with a series of instructions which should be executed one after another through parallel calculation units. The actual instructions will run in parallel. That's why any kind of branches are actually bad on GPUs. On modern GPUs it's not that bad as it was back then but still a branch interrupts the pipeline execution. This is actually true for CPUs as well. However CPUs have quite advanced branch prediction code and when a branch is co$$anonymous$$g up it might even prefetch both outcomes and just throw away the one that didn't make it. GPUs are designed to perform the same operations on a huge amount of similar data. Extra calculations almost never matters. Just letting the GPU crunch through all the data will be faster in most cases.
The GPU has specialized opcodes to work with float, float2, float3 or float4 values. The execution time is essentially the same. That's why it's generally better to use functions like step in combination with lerp to perform a "branch" between two arbitrary values. GPUs work entirely different to CPUs. If you develop shaders you have to get used to that difference.
Thanks for the answer. Now it's working fine.
Here is the shader cleaned if anyone wants it.
Since the length method uses a square root and a dot product, I changed it to just sum the color channels and check if they are less than the tolerance value. I imagine performance can be boosted this way.
half3 delta = abs(c.rgb - _InColor.rgb);
c = (delta.r + delta.g + delta.b) < 0.001 ? _OutColor : c;
This is a bit less accurate than length() but if it produces acceptable results for you, this could be slightly faster; depending on the GPU you are targeting. $$anonymous$$ostly stuff like sqrt() and dot() are in silicon an can possibly be executed in parallel.
Answer by toddisarockstar · Jul 11, 2019 at 03:28 AM
with something like this you usualy need some sort of tollerance.
//instead of doing this
if(color1==color2){do stuff}
// try something like this instead:
if(Mathf.Abs (color1.r-color2.r)<.1f){
if(Mathf.Abs (color1.b-color2.b)<.1f){
if(Mathf.Abs (color1.g-color2.g)<.1f){
do stuff
}}}
actual color channel numbers can slightly change because of compression.
when you save a photo. its standard in most formats that color channels are rounded off and averaged. so pixels color numbers may not be EXACTLY what they started with. this reduces size.
checking colors the the == operator is not going to do you any good. unless nothing is compressed
also unity has default texture import settings that also can effect these numbers when unity loads them.
an alternate answer whould be to make sure you are saving your pics in a lossless format and go through unitys texture import settings and make sure that is lossless too. but these things are in place for proficiency reasons. so unless you have very small textures i would recommend the "tollerance" approach to solve your problem
using several ifs in fragment shader can be really devastating to the shader performance
the code part of my answer was pseudo code to explain to you guys what the problem was. I have a habit of explaining my answer so people can help themselves. I dont always give copy and paste code. This way people can learn. Apparently 7 hours after he posted no one could figure out this guys problem till i explained it to you in my answer.
do you have any clue why "if's" are not recommended?
the "if" in in itself is not harmfull. it's just recommended to check as little as possible for shader calculations because they are multiplied out so many times for pixels every frame. the ifs in this code example are in place to REDUCE calculations and speed up preformance.
directing people to avoid using "if" might be a nice habit for a beginner folks who dont really know what they are doing. but don't post "hear say" info like this without understanding.
Thanks for the explanation. I didn't know about the 'ifs' branches.
Your answer
![](https://koobas.hobune.stream/wayback/20220612204706im_/https://answers.unity.com/themes/thub/images/avi.jpg)