要创建运行计算着色器在 GPU 上运行的程序。 更多信息
参见 术语表的渲染 Pass,请执行以下操作
要检查平台是否支持计算着色器,请使用 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));
...
}
}
}
要创建计算着色器输出到的缓冲区,请按照以下步骤操作
创建图形缓冲区,然后在您的 Pass 数据中添加其句柄。
// 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 将缓冲区转换为渲染图系统可以使用的句柄,然后设置 Pass 数据中的 BufferHandle 字段。例如
BufferHandle outputHandleRG = renderGraph.ImportBuffer(outputBuffer);
passData.output = outputHandleRG;
使用 UseBuffer 方法将缓冲区设置为渲染图系统中的可写缓冲区。
builder.UseBuffer(passData.output, AccessFlags.Write);
请按照以下步骤操作
将计算着色器传递到渲染 Pass。例如,在 ScriptableRendererFeature 类中,公开 ComputeShader 属性,然后将计算着色器传递到渲染 Pass 类。
向您的 Pass 数据添加 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。
只有在渲染 Pass 执行完毕且计算着色器完成运行后,才能获取数据。
例如
// 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 的示例。