Ray tracing workflow
To use the API to trace rays in Unity, follow these steps:
- Create the ray tracing context.
- Create an acceleration structure.
- Create a shader.
- Build your acceleration structure.
- Execute your shader.
Create the ray tracing context
The context serves as the API entry point. Create it using the following parameters:
backend: The chosen backend, which can be eitherHardwareorCompute.resources: A collection of assets required by the context to function.
var rtContext = new RayTracingContext(backend, rtResources);
For more information, refer to Create the ray tracing Context.
Create an acceleration structure
The acceleration structure is the data structure used to represent a collection of instances and geometries that are used for GPU ray tracing.
IRayTracingAccelStruct rtAccelStruct = rtContext.CreateAccelerationStructure(options);
After creating the structure, populate it with mesh instances using the AddInstance method.
For more information, refer to Create an acceleration structure.
Create a unified ray tracing shader
Depending on the chosen backend, the RayTracingContext runs either a ComputeShader or a RayTracingShader. The API introduces the unified ray tracing shader (.urtshader), which is a shader type that generates both variants for you.
IRayTracingShader rtShader = rtContext.LoadRayTracingShader("Assets/yourShader.urtshader");
For more information, refer to Create a unified ray tracing shader.
Build your acceleration structure
Whenever it is modified or used for the first time, the acceleration structure needs to be built or rebuilt. This can be achieved with the following code:
rtAccelStruct.Build(cmd, buildScratchBuffer);
For more information, refer to Execute your ray tracing code.
Execute your shader
To execute your shader, call the Dispatch
method of IRayTracingShader.
rtShader.Dispatch(cmd, traceScratchBuffer, threadCountX, threadCountY, threadCountZ);
For more information, refer to Execute your ray tracing code.