Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Does Shader Graph Reuse nodes internally?

Discussion in 'Shader Graph' started by Dorodo, Feb 8, 2021.

  1. Dorodo

    Dorodo

    Joined:
    Mar 8, 2015
    Posts:
    44
    Just wondering if when I use nodes such as Position (World), Screen Position, Normal (World) multiple times throughout a graph, Shader Graph manages to keep the same reference internally, or if I'm going to get the matrix conversion cost for each time that node was called.
     
    Last edited: Feb 8, 2021
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
    Yes and No, but also No.

    In some cases the values those nodes use are precomputed before the Shader Graph part of the shader runs. For example Position (World) doesn’t do anything but grab the already available world position vector. Something like Position (View) has to transform the world space position to view space to use it. And it calls the code to do so every time the node shows up. Heck, it probably calls it every time you link another node to that node so consolidating multiple Position nodes into one probably doesn’t help.

    But that doesn’t mean you pay that cost multiple times. Shader compilers are (generally) very good at removing duplicate code. So even if the shader code generated by Shader Graph had a dozen separate Position (View) nodes, the actual compiled shader the GPU uses wouldn’t call it a dozen times. Only once and reuse it.

    Generally speaking. Some old and/or really terrible shader compilers for Android devices might not, which is a problem because every OpenGLES device basically has its own unique shader compiler that takes an uncompiled shader as an input. But Unity works around that problem to some degree by generating its OpenGL shader code from pre-compiled Direct3D shaders, which hopefully have done the bulk of those optimizations already.

    So, no. Shader Graph is generally not smart about generating code that reuses computed values, and will call the same function over and over to recalculate the value.

    But also no. You don’t pay the cost of that because shader compilers make it all go away.
     
  3. Double-V

    Double-V

    Joined:
    Aug 13, 2016
    Posts:
    21
    So if I understand this correctly, this means that if I, for example, put duplicate nodes for a property/the same subgraph node with no inputs/etc just to make the graph look nice it will know that it's the same - except not when generating code, but 1 step later?
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
    Correct.
     
    Extelen1 and Double-V like this.