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 Cost of calling a vertex shader function inside another one in HLSL

Discussion in 'Shaders' started by Beauque, Jun 2, 2023.

  1. Beauque

    Beauque

    Joined:
    Mar 7, 2017
    Posts:
    61
    Hi,
    I am working on a custom instanced terrain shader based on the URP/Terrain/Lit and I am looking for ways to reuse the original shader library as much as I can, and just add the code I need for my custom features (=> less code maintenance over URP updates).

    I found a hacky way to reuse the original fragment input struct and vertex shader and add the custom parts, without copy-pasting the whole code, like so:

    Code (CSharp):
    1.  
    2. #include "Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitPasses.hlsl"
    3.  
    4. struct C_Varyings // Custom Fragment Input
    5. {
    6.     Varyings varyings; // Original Fragment Input
    7. // my code
    8.    UNITY_VERTEX_OUTPUT_STEREO // do I need to re-insert this btw ?
    9. };
    10.  
    11.  
    12. C_Varyings C_SplatmapVert(Attributes v) // Custom Vertex Shader
    13. {
    14.     C_Varyings o = (C_Varyings)0;
    15.     o.varyings = SplatmapVert(v); // Original Vertex Shader
    16. // my code
    17.     return o;
    18. }
    19.  
    20.  
    21.  half4 C_SplatmapFragment(C_Varyings C_IN) : SV_TARGET // Custom Fragment Shader
    22. {
    23.     Varyings IN = C_IN.varyings;
    24. //... fragment shader code
    25. }
    26.  
    It seems to work just fine, however it is to be used on mobile VR hardware and as I haven't seen it done before, I would like to be certain it does not break any optimisation or add uneccessary complexity/instructions to the compiled shader that could reduce its performances in any way.

    Can any one confirm it's a safe practice ?
     
    Last edited: Jun 2, 2023
  2. aleksandrk

    aleksandrk

    Unity Technologies

    Joined:
    Jul 3, 2017
    Posts:
    2,983
    Hi!

    The compiler will flatten everything and inline all the functions anyway. It should not cause any unnecessary instructions.

    Regarding the question in your code about UNITY_VERTEX_OUTPUT_STEREO: it needs to be present once in the final struct. Some platform compilers will throw an error in this case.
     
    Beauque likes this.
  3. Beauque

    Beauque

    Joined:
    Mar 7, 2017
    Posts:
    61
    I see, perfect then, thanks ! :)