Version: Unity 6.5 Alpha (6000.5)
Language : English
Write to and read output data from a compute shader in URP
Analyze a render graph in URP

Read input data into a compute shader in URP

To read input data into the compute shaderA program that runs on the GPU. More info
See in Glossary
, do the following:

  1. Create a graphics buffer using CreateBuffer, then add a handle to it in your pass data. For example:

    // Declare a buffer handle
    BufferHandle m_InputBufferHandle;
    
    // Add the handle to your pass data
    class PassData
    {
        public BufferHandle input;
        // ...
    }
    
    // Create the buffer in RecordRenderGraph
    public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
    {
        // Create the input buffer as a structured buffer of 20 ints
        BufferDesc desc = new BufferDesc
        {
            name   = "InputBuffer",
            count  = 20,
            stride = sizeof(int),
            target = GraphicsBuffer.Target.Structured
        };
    
        m_InputBufferHandle = renderGraph.CreateBuffer(desc);
    }
    
  2. Create placeholder data in the buffer to read from for this example:

    // Placeholder input data for the compute shader
    private List<int> inputData = new List<int>();
    
    // Initialize in the render pass constructor
    public ComputePass()
    {
        for (int i = 0; i < 20; i++)
        {
            inputData.Add(i);
        }
    }
    
  3. Attach the buffer handle and data to the pass data.

    using (var builder = renderGraph.AddComputePass("ComputePass", out PassData passData))
    {
        passData.input = m_InputBufferHandle;
        passData.bufferData = inputData;
    }
    
  4. Use the UseBuffer method to declare the buffer as an input of this pass in the render graph system. For example:

    builder.UseBuffer(passData.input, AccessFlags.Read);
    
  5. In your SetRenderFunc method, use the SetBufferData API to upload the input data to the buffer and the SetComputeBufferParam API to attach the buffer to the compute shader. For example:

    // Upload input data to the Render Graph buffer
    context.commandBuffer.SetBufferData(passData.input, passData.bufferData);
    
    // Attach buffer to the compute shader
    
    // The first parameter is the compute shader
    // The second parameter is the function that uses the buffer
    // The third parameter is the RWStructuredBuffer input variable to attach the buffer to
    // The fourth parameter is the handle to the input buffer
    context.commandBuffer.SetComputeBufferParam(passData.computeShader, passData.computeShader.FindKernel("Main"), "inputData", passData.input);
    

Example

For a full example, refer to the example called Compute in the Universal Render Pipeline (URP) package samples.

Additional resources

Write to and read output data from a compute shader in URP
Analyze a render graph in URP