Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by hyagogow · Jul 11, 2019 at 02:24 AM · unity 5shadercg

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
         }
         }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

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);

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image toddisarockstar · Jul 11, 2019 at 09:09 PM 0
Share

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.

avatar image Bunny83 toddisarockstar · Jul 12, 2019 at 02:59 AM 0
Share

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.

avatar image hyagogow · Jul 11, 2019 at 11:12 PM 0
Share

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;
avatar image pmerilainen hyagogow · Jul 12, 2019 at 08:46 AM 0
Share

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.

avatar image
1

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

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image pmerilainen · Jul 11, 2019 at 10:41 AM 0
Share

using several ifs in fragment shader can be really devastating to the shader performance

avatar image toddisarockstar pmerilainen · Jul 11, 2019 at 08:55 PM 0
Share

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.

avatar image hyagogow toddisarockstar · Jul 11, 2019 at 11:16 PM 0
Share

Thanks for the explanation. I didn't know about the 'ifs' branches.

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

266 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

CG compiled to GLSL: hyperbolic functions not found. 0 Answers

Unity5 v Unity4 Shader array errors 1 Answer

Transparent shader disappears with multiple objects 1 Answer

How to force the compilation of a shader in Unity? 5 Answers

Difference between pos.z and pos.w? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges