Search Unity

Is it better to avoid a branch or a texture lookup?

Discussion in 'Shaders' started by awardell, Dec 28, 2021.

  1. awardell

    awardell

    Joined:
    Feb 5, 2014
    Posts:
    71
    I'm writing a shader, part of which reads from two textures and combines their output. It uses two other variables derived from UV coordinates to scale each texture's contribution. A simplified pseudo-code version is:

    float4 output = tex2D(_TexA, uv_TexA) * texcoord3.x + tex2D(_TexB, uv_TexB) * texcoord3.y;


    Now, I know that texture lookups are expensive. I also know that there will be large swaths of the mesh where one or both of the
    texcoord3
    dimensions are going to be 0, rendering the texture lookups effectively unused.

    But I also know to avoid creating branches in a shader. I presume that an if-statement checking if
    texcoord.x > 0
    is going to cause a branch.

    What is my best option here? Just always perform the lookups? Does it depend on anything such as pipeline or where I'm deploying to?
     
  2. bart_the_13th

    bart_the_13th

    Joined:
    Jan 16, 2012
    Posts:
    498
    even on opengl es 2, the graphic engine can sample up to 8 textures in one pass (although I think in surface shader it can only do 4, maybe 6 depends on how many interpolators and lightmaps are getting used) so it should be fast enough even on low spec mobile platform.