Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved HDRP + MaterialPropertyBlock.SetVectorArray + Graphics.DrawMeshInstanced + Shader Graph

Discussion in 'Shader Graph' started by neekoh, Sep 21, 2021.

  1. neekoh

    neekoh

    Joined:
    Nov 16, 2012
    Posts:
    9
    It sure is difficult to accurately find questions and answers to this problem. Maybe there is no such problem?
    For what it's worth here's a report of actually getting
    MaterialPropertyBlock.SetVectorArray and Graphics.DrawMeshInstanced working on HDRP with Shader Graph accessing the instance variables.
    Unity 2020.3.17f1 + HDRP / Shader Graph Version 10.6.0 + Windows.

    (This is not about Graphics.DrawMeshInstancedIndirect, or using MaterialPropertyBlock with SRP Batching)

    It's straight forward enough to be usable, and I hope this method won't be invalidated too soon.
    A custom function node sets up the buffer and retrieves the instance parameters like a standard vert + frag shader would, without the need for any UNITY_SETUP_INSTANCE_ID mechanisms.

    So, the script side using MaterialPropertyBlock:

    Code (CSharp):
    1.  
    2. // set instanceMatrices and instanceColors for your batch
    3. ...
    4.  
    5. // apply instanceColors for MPB
    6. materialPropertyBlock.SetVectorArray("_BaseColor", instanceColors);
    7.  
    8. // render batch
    9. Graphics.DrawMeshInstanced(mesh, 0, material, instanceMatrices, batchCount, materialPropertyBlock, shadowCastMode, receiveShadows);
    10.  
    The shader graph side (what we used):
    - Create a HDRP/Lit Shader Graph and a material using it
    - Enable GPU Instancing on the material!
    - Add a Custom Function node to shader graph, File: YourInstancePropertiesInclude.hlsl
    - Add the outputs you need and call the function that retrieves the instance property you're looking for

    In the example case the contents of the file:
    Code (CSharp):
    1.  
    2. // Set up instance properties buffer
    3. UNITY_INSTANCING_BUFFER_START(Props)
    4.   UNITY_DEFINE_INSTANCED_PROP(float4, _BaseColor)
    5. UNITY_INSTANCING_BUFFER_END(Props)
    6.  
    7. // Returns _BaseColor for this instance
    8. void InstanceBaseColor_float(out float4 BaseColor)
    9. {
    10.   BaseColor = UNITY_ACCESS_INSTANCED_PROP(Props, _BaseColor);
    11. }
    12.  

    Here's the part of the graph: ShaderGraphInstanceProps.png
     
    Chmyke, ButtCleaves, Rs and 1 other person like this.
  2. ButtCleaves

    ButtCleaves

    Joined:
    Jun 17, 2015
    Posts:
    4
    why is this not documented. thank you!
     
    Chmyke likes this.