要创建运行计算着色器的渲染通道,请执行以下操作:
要检查平台是否支持计算着色器,请使用 SystemInfo.supportsComputeShaders API
创建 ScriptableRenderPass 时,请执行以下操作:
AddComputePass 而不是 AddRasterRenderPass。ComputeGraphContext 而不是 RasterGraphContext。例如:
class ComputePass : ScriptableRenderPass
{
...
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer contextData)
{
...
// Use AddComputePass instead of AddRasterRenderPass.
using (var builder = renderGraph.AddComputePass("MyComputePass", out PassData data))
{
...
// Use ComputeGraphContext instead of RasterGraphContext.
builder.SetRenderFunc((PassData data, ComputeGraphContext context) => ExecutePass(data, context));
...
}
}
}
要创建计算着色器输出到的缓冲区,请遵循以下步骤:
创建一个图形缓冲区,然后在通道数据中添加一个句柄。
// Declare an output buffer
public GraphicsBuffer outputBuffer;
// Add a handle to the output buffer in your pass data
class PassData
{
public BufferHandle output;
}
// Create the buffer in the render pass constructor
public ComputePass(ComputeShader computeShader)
{
// Create the output buffer as a structured buffer
// Create the buffer with a length of 5 integers, so the compute shader can output 5 values.
outputBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, 5, sizeof(int));
}
使用 ImportBuffer 渲染图 API 将缓冲区转换为渲染图系统可以使用的句柄,然后在通道数据中设置 BufferHandle 字段。例如:
BufferHandle outputHandleRG = renderGraph.ImportBuffer(outputBuffer);
passData.output = outputHandleRG;
使用 UseBuffer 方法可将缓冲区设置为渲染图形系统中的可写缓冲区。
builder.UseBuffer(passData.output, AccessFlags.Write);
请遵循以下步骤:
将计算着色器传递到渲染通道。例如,在 ScriptableRendererFeature 类中,显示 ComputeShader 属性,然后将计算着色器传递给渲染通道类。
将 ComputeShader 字段添加到通道数据,并将其设置为计算着色器。例如:
// Add a `ComputeShader` field to your pass data
class PassData
{
...
public ComputeShader computeShader;
}
// Set the `ComputeShader` field to the compute shader
passData.computeShader = yourComputeShader;
在 SetRenderFunc 方法中,使用 SetComputeBufferParam API 将缓冲区附加到计算着色器。例如:
// The first parameter is the compute shader
// The second parameter is the function that uses the buffer
// The third parameter is the StructuredBuffer output variable to attach the buffer to
// The fourth parameter is the handle to the output buffer
context.cmd.SetComputeBufferParam(passData.computeShader, passData.computeShader.FindKernel("Main"), "outputData", passData.output);
使用 DispatchCompute API 执行计算着色器。
context.cmd.DispatchCompute(passData.computeShader, passData.computeShader.FindKernel("CSMain"), 1, 1, 1);
要从输出缓冲区获取数据,请使用 GraphicsBuffer.GetData API。
只有在渲染通道执行和计算着色器运行完毕后,才能获取数据。
例如:
// Create an array to store the output data
outputData = new int[5];
// Copy the output data from the output buffer to the array
outputBuffer.GetData(outputData);
有关完整示例,请参阅渲染图系统 URP 包示例中名为 Compute 的示例。