Search Unity

Resolved Can't pass an integer to a shader

Discussion in 'Shaders' started by Orimay, Aug 12, 2020.

  1. Orimay

    Orimay

    Joined:
    Nov 16, 2012
    Posts:
    304
    I am passing my generated RGBA32 texture with Point filter mode to my shader, packing 8 bits per color (32 bytes total), which don't seem to be passing accurately. For instance, if I send 1 bit as 00000001 in a red cannel like new Color32(1, 0, 0, 0), when I get my color tex2D(_MainTex, uv0) * 255 doesn't result in 1. Same issue with packing any other bit. Also, they seem to appear randomly. Almost every bit results in the first one set to 1, which is totally unexpected. I get, that every 0-255 byte gets mapped to 0-1 float, but I can't see how there could be any info loss. Is there any workaround to get exact color values from texture?
     
    zackjrcollins likes this.
  2. Orimay

    Orimay

    Joined:
    Nov 16, 2012
    Posts:
    304
    It seems like the issue is that I can't seem to pass an integer into a shader property, that is used for masking :c
    The texture channels seem fine
     
  3. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    Make sure the texture is set to be using linear color space and not sRGB when you're creating it. After that floating point math can be funny, so I'd recommend rounding rather than flooring a value when getting an integer.

    Code (csharp):
    1. int4 values = (int)(tex2D(_MainTex, uv) * 255.0 + 0.5);
     
  4. Orimay

    Orimay

    Joined:
    Nov 16, 2012
    Posts:
    304
    Awesome, thank you! But it still seems like I can't pass an integer as a color to have a mask and check it
     
  5. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    Code (csharp):
    1. // in c#
    2. mat.SetInt("_MyInt", myInt);
    3. // technically just casts the integer to a float, is equivalent to
    4. mat.SetFloat("_MyInt", (float)myInt);
    5.  
    6. // shader property
    7. _MyInt ("My Integer", Int) = 1.0
    8. // in the inspector is treated the same as a float and doesn't force integer values
    9.  
    10. // shader uniform defined as uint, native c++ casts the float passed around in c# to an integer
    11. uint _MyInt;
     
    Orimay likes this.
  6. Orimay

    Orimay

    Joined:
    Nov 16, 2012
    Posts:
    304
    Awesome, thank you! Seems to be working now