Read input data into a compute shader in URP
Allocate a buffer that reads input data into a compute shader in a render pass.
Read time 2 minutesLast updated a month ago
To read input data into the compute shader, do the following:
-
Create a graphics buffer using, then add a handle to it in your pass data. For example:
CreateBuffer// Declare a buffer handleBufferHandle m_InputBufferHandle;// Add the handle to your pass dataclass PassData{ public BufferHandle input; // ...}// Create the buffer in RecordRenderGraphpublic 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);} -
Create placeholder data in the buffer to read from for this example:// Placeholder input data for the compute shaderprivate List<int> inputData = new List<int>();// Initialize in the render pass constructorpublic ComputePass(){ for (int i = 0; i < 20; i++) { inputData.Add(i); }}
-
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;}
-
Use themethod to declare the buffer as an input of this pass in the render graph system. For example:
UseBufferbuilder.UseBuffer(passData.input, AccessFlags.Read); -
In yourmethod, use the
SetRenderFuncAPI to upload the input data to the buffer and theSetBufferDataAPI to attach the buffer to the compute shader. For example:SetComputeBufferParam// Upload input data to the Render Graph buffercontext.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 buffercontext.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.