Search Unity

Accessing tagents in shader issue

Discussion in 'Shaders' started by shaofent, Aug 2, 2019.

  1. shaofent

    shaofent

    Joined:
    Aug 28, 2017
    Posts:
    8
    I have a mesh which has Tangents set to None in Mesh Import Setting. And I am sure that there is no data in mesh.tagents array. However, in the shader, I specify a field in vertex shader input structure as TANGENT. And when I try to output the value of tangents in the fragmetn shader, it gives me red. I wonder what happens here? Can I access tangent value in shader when the mesh have no tangetns? If I can access, what's the default value for it? Thanks a lot.
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,339
    To prevent shader errors.

    Uninitialized data isn't itself a problem, graphics APIs will default any vertex data to a float4(0,0,0,1) value if the shader requests data the mesh doesn't have.

    The problem with that is shaders that use the vertex tangent will eventually try to normalize the xyz values, and normalizing float3(0,0,0) produces a NaN (not a number). NaN values are bad news, and cause all sorts of problems as using a NaN value in almost any operation produces a NaN, so they tend to spread. Best case with non HDR rendering, it turns your object black. Worst case it spreads to the post processing and large sections of your screen go black as bloom or DoF blurs the screen data.

    There's code you can add to shaders to detect NaN values or to protect against their creation, but that makes the shaders slower for something that is hopefully infrequently needed. So having the mesh data get filled with default tangents (or normals) if a shader uses those values prevents all that.
     
  3. shaofent

    shaofent

    Joined:
    Aug 28, 2017
    Posts:
    8
    Thanks for your answer.