BorrowedTorch.RayTracing
1.0.0
Prefix Reserved
See the version list below for details.
dotnet add package BorrowedTorch.RayTracing --version 1.0.0
NuGet\Install-Package BorrowedTorch.RayTracing -Version 1.0.0
<PackageReference Include="BorrowedTorch.RayTracing" Version="1.0.0" />
<PackageVersion Include="BorrowedTorch.RayTracing" Version="1.0.0" />
<PackageReference Include="BorrowedTorch.RayTracing" />
paket add BorrowedTorch.RayTracing --version 1.0.0
#r "nuget: BorrowedTorch.RayTracing, 1.0.0"
#:package BorrowedTorch.RayTracing@1.0.0
#addin nuget:?package=BorrowedTorch.RayTracing&version=1.0.0
#tool nuget:?package=BorrowedTorch.RayTracing&version=1.0.0
BorrowedTorch.RayTracing
Ray casting for MonoGame on the GPU and the CPU: a binned-SAH bounding volume hierarchy, per-mesh bottom-level and per-scene top-level acceleration structures (BLAS/TLAS), their upload to structured buffers, a stackless any-hit traversal in HLSL, and the depth/normal G-buffer that screen-space traced passes start from.
What you get:
- CPU queries: closest hit (picking, placement) and any hit (visibility), with barycentrics for attribute lookup.
- GPU queries:
RtTraceAnyin a compute (or pixel) shader. Shadows, ambient occlusion and other occlusion-style effects can be written on top of it. - Incremental updates: re-declare the scene every frame. The TLAS works out on its own whether that means nothing, a refit or a rebuild, and the GPU copy uploads only what changed. An idle scene costs a few comparisons a frame.
It does not shade hits, sort by material, or give the GPU a closest-hit walk: it answers "where does this ray hit" on the CPU and "is anything in the way" on both.
Requirements
- The MonoGame compute fork:
MonoGame.Framework.Compute.WindowsDX.NoMemoryLeak3.8.3.1 (DirectX 11, HiDef profile, compute shaders and structured buffers). - Shaders compiled for
DirectX_11, kernels ascs_5_0. - Windows, .NET 8 or later.
Installing
dotnet add package BorrowedTorch.RayTracing
The two HLSL headers, RayTraversal.fxh and GBuffer.fxh, are delivered to your build output at
Content/Effects/Lib/. If you compile effects at runtime from that folder, #include "Lib/RayTraversal.fxh" from an
effect in Content/Effects finds them as they are. If you build effects with the content pipeline instead, copy the
two headers beside your own effects: they are plain HLSL with no further includes.
Concepts
| Type | What it is |
|---|---|
ITriangleMesh |
Your mesh, as the library reads it: a triangle count and three positions per triangle. |
MeshBlas |
A BVH over one mesh's triangles, in the mesh's own space. Built once per mesh, shared by every instance of it. |
Tlas |
A BVH over the scene's instances: a MeshBlas placed by a world matrix, under an id of yours. |
GpuAccelerationStructure |
The GPU copy of a Tlas and every MeshBlas it uses, as four structured buffers. |
GBuffer |
Linear view-space depth and view-space normals, the input a screen-space traced pass reconstructs points from. |
RayTracingFlags |
Per-instance switches a query can require: CastsShadow, VisibleToGI, Pickable. |
Coordinates are MonoGame's: row vectors, p * M. Rays are traced in the space the instances' world matrices put
them in, so a shader has to hand the traversal origins in that same space.
1. Expose your meshes
Implement ITriangleMesh over whatever your engine keeps on the CPU. Triangle lists only: convert strips first.
using BorrowedTorch.RayTracing;
using Microsoft.Xna.Framework;
public sealed class IndexedTriangles : ITriangleMesh
{
private readonly Vector3[] _positions;
private readonly int[] _indices;
public IndexedTriangles(Vector3[] positions, int[] indices)
{
_positions = positions;
_indices = indices;
}
public int TriangleCount => _indices.Length / 3;
public void GetTriangle(int triangle, out Vector3 v0, out Vector3 v1, out Vector3 v2)
{
v0 = _positions[_indices[triangle * 3]];
v1 = _positions[_indices[triangle * 3 + 1]];
v2 = _positions[_indices[triangle * 3 + 2]];
}
}
2. Build a BLAS per mesh
// Once per mesh. Null for a mesh with no triangles - there is nothing to trace.
MeshBlas? crateBlas = MeshBlas.Build(new IndexedTriangles(cratePositions, crateIndices));
Share one MeshBlas between every instance of the mesh. Build a new one if the mesh itself is replaced. The mesh is
read twice at build time and once per refit; between those, the BLAS keeps its own copy of the triangles
(MeshBlas.Triangles, a vertex and two edges each, in the tree's order), which is what both the CPU walks and the GPU
upload read.
3. Declare the scene every frame
var tlas = new Tlas();
void UpdateScene()
{
tlas.BeginUpdate();
foreach (var obj in sceneObjects)
tlas.Add(obj.Id, obj.Blas, obj.WorldMatrix); // obj.Id is any ulong of yours, stable per object
TlasUpdateResult result = tlas.EndUpdate(); // Unchanged, Refitted or Rebuilt
}
- Declare in a stable order. Each
Addis compared against what the same position held last update. A different order is still correct, but reads as a structural change and forces a rebuild. - The id is yours. It is never interpreted beyond equality, and comes back in every hit. An ECS entity of an id and a generation packs into the 64 bits, so a recycled id reads as a new object.
- Flags default to
RayTracingFlags.Default(everything). Pass fewer to keep an object out of some queries:tlas.Add(id, blas, world, RayTracingFlags.Pickable)is clickable but casts no shadow. - Odd transforms. A transform that flattens an object (a zero scale on one axis) is still traced, through a stand-in a hair thick. One that collapses it to a line or a point, or puts it at infinity, is left out.
- Rebuilds are automatic. Moving objects only refits the tree. It rebuilds when the refit has grown the root's area 2x or the tree's surface-area cost 1.5x.
- An unchanged instance costs a few comparisons. Its box is reused as long as its transform and its BLAS (by version) are what they were.
4. Query on the CPU
Closest hit, for picking:
// Unproject the cursor into a world-space ray (MonoGame does the maths).
Vector3 near = viewport.Unproject(new Vector3(mouse.X, mouse.Y, 0f), projection, view, Matrix.Identity);
Vector3 far = viewport.Unproject(new Vector3(mouse.X, mouse.Y, 1f), projection, view, Matrix.Identity);
var ray = new Ray(near, Vector3.Normalize(far - near));
if (tlas.Intersect(ray, float.MaxValue, out RayHit hit, RayTracingFlags.Pickable))
{
ulong picked = hit.InstanceId;
Vector3 point = ray.Position + ray.Direction * hit.Distance;
}
hit.Distance is the ray parameter t: a world distance for a unit-length direction. The direction does not have to
be unit length; distances are then in its parameterisation.
Any hit, for visibility. It stops at the first occluder and is cheaper than asking for the nearest:
// Start a little off the surface, or the ray finds the surface it starts on.
var shadowRay = new Ray(point + surfaceNormal * 0.02f, directionToLight);
bool inShadow = tlas.IntersectAny(shadowRay, distanceToLight, RayTracingFlags.CastsShadow);
Attributes at a hit: hit.TriangleIndex and the barycentrics hit.U, hit.V (the third weight is 1 - U - V).
They interpolate any per-vertex attribute you keep. Positions are in the mesh's own space:
TlasInstance instance = tlas.Instances[hit.InstanceIndex];
instance.Blas.Geometry.GetTriangle(hit.TriangleIndex, out var a, out var b, out var c);
Vector3 local = a * (1 - hit.U - hit.V) + b * hit.U + c * hit.V;
Vector3 world = Vector3.Transform(local, instance.World);
The structures are not thread-safe: do not query a Tlas while it is being updated.
5. Upload to the GPU
var acceleration = new GpuAccelerationStructure(graphicsDevice);
// Every frame, after tlas.EndUpdate(), on the thread that owns the device.
acceleration.Upload(tlas);
Upload sends a mesh's geometry when its BLAS first appears - appended after the meshes already there - and re-sends
a refitted BLAS in place. The scene half (the tree and one record per instance) goes when the tree or an instance's
flags changed. The buffers are allocated with room to spare, so an object added or removed does not usually
reallocate anything; everything is laid out afresh only when that room runs out, which is also when meshes nothing
uses any more are dropped. A frame with no changes uploads nothing. IsReady is false while the scene is empty.
Version moves whenever the buffers change, so a pass can keep last frame's result while it has not moved.
GpuAccelerationStructure and GBuffer (section 7) own GPU resources: Dispose them with the device's other
resources.
6. Trace in a shader
A compute kernel that marks each pixel lit or shadowed by one directional light. It reads the G-buffer (section 7) for the point to trace from:
#include "Lib/RayTraversal.fxh"
#include "Lib/GBuffer.fxh"
Texture2D<float> DepthMap; // GBuffer.Depth
Texture2D<float4> NormalMap; // GBuffer.Normal
RWTexture2D<float4> ShadowMask; // 1 = lit, 0 = shadowed
float4x4 InverseView; // view -> the space the instances were declared in
float4x4 InverseProjection;
float4 ScreenSize; // (width, height, 1 / width, 1 / height)
float3 ToLight; // world space, towards the light
float NormalBias = 0.02;
[numthreads(8, 8, 1)]
void CS(uint3 id : SV_DispatchThreadID)
{
if (id.x >= (uint) ScreenSize.x || id.y >= (uint) ScreenSize.y) return;
float depth = DepthMap[id.xy];
if (depth <= 0.0) // nothing drawn here
{
ShadowMask[id.xy] = float4(1.0, 1.0, 1.0, 1.0);
return;
}
float3 position = GBufferWorldPosition(int2(id.xy), ScreenSize, depth, InverseProjection, InverseView);
float3 normal = GBufferWorldNormal(NormalMap[id.xy], InverseView);
// A directional light is far away, not infinitely far: give the ray a long, finite length.
bool blocked = RtTraceAny(position + normal * NormalBias, ToLight, 1e8, RT_FLAG_CASTS_SHADOW);
float lit = blocked ? 0.0 : 1.0;
ShadowMask[id.xy] = float4(lit, lit, lit, 1.0);
}
technique Shadow
{
pass P0
{
ComputeShader = compile cs_5_0 CS();
}
}
Dispatch it from C#. Bind hands the kernel the four buffers and the node count under the names
RayTraversal.fxh declares:
// A texture a compute shader can write to.
var shadowMask = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color, ShaderAccess.ReadWrite);
if (acceleration.IsReady && gBuffer.IsCurrent)
{
shadowEffect.Parameters["DepthMap"].SetValue(gBuffer.Depth);
shadowEffect.Parameters["NormalMap"].SetValue(gBuffer.Normal);
shadowEffect.Parameters["ShadowMask"].SetValue(shadowMask);
shadowEffect.Parameters["InverseView"].SetValue(Matrix.Invert(view));
shadowEffect.Parameters["InverseProjection"].SetValue(Matrix.Invert(projection));
shadowEffect.Parameters["ScreenSize"].SetValue(new Vector4(width, height, 1f / width, 1f / height));
shadowEffect.Parameters["ToLight"].SetValue(Vector3.Normalize(-sunDirection));
acceleration.Bind(shadowEffect);
foreach (var pass in shadowEffect.CurrentTechnique.Passes)
{
pass.ApplyCompute();
graphicsDevice.DispatchCompute((width + 7) / 8, (height + 7) / 8, 1); // one thread per pixel
}
}
The fork binds and unbinds compute resources itself, so the forward pass can sample shadowMask straight after.
HLSL reference
RayTraversal.fxh:
| Name | |
|---|---|
bool RtTraceAny(float3 origin, float3 direction, float maxDistance, int requiredFlags) |
Whether any instance carrying every flag in requiredFlags blocks the ray within maxDistance. The direction need not be unit length. |
bool RtTraceAnyCounted(..., inout uint steps) |
The same walk, adding every box and triangle it tests to steps, for heat maps and cost measurements. |
RT_FLAG_CASTS_SHADOW, RT_FLAG_VISIBLE_TO_GI |
The GPU's view of RayTracingFlags (Pickable is CPU-only). |
RT_MIN_DISTANCE |
Hits closer than this (1e-4) are ignored, as on the CPU. Still offset rays off the surface. |
RT_MAX_DISTANCE |
The longest a ray may be, float's largest finite value. A longer maxDistance is clamped to it. |
TlasNodes, Instances, BlasNodes, Triangles, TlasNodeCount |
What GpuAccelerationStructure.Bind sets. |
RayTraversal.fxh needs nothing compute-only, so a pixel shader can include it too.
GBuffer.fxh:
| Function | |
|---|---|
GBufferViewPosition(pixel, gBufferSize, depth, inverseProjection) |
The view-space point at a G-buffer pixel. Perspective projections only. |
GBufferWorldPosition(..., inverseView) |
The same point through inverseView. |
GBufferViewNormal(packed), GBufferWorldNormal(packed, inverseView) |
The unpacked normal. |
GBufferPixelOf(pixel, pixelScale), ReducedGridPosition(position, pixelScale) |
Mapping between a pass at 1/pixelScale resolution and the full-resolution G-buffer, when the pass reads one G-buffer pixel per pixel of its own. |
7. Fill the G-buffer
GBuffer owns two render targets: Depth (R32F, the linear view-space distance, 0 where nothing was drawn) and
Normal (RGBA8, the view-space normal packed into 0..1). Both are null until the first Resize. Your own prepass
fills them:
var gBuffer = new GBuffer(graphicsDevice);
// Every frame, before anything traces.
gBuffer.Resize(width, height); // a no-op unless the size changed; BindAndClear refuses to run before it
gBuffer.BindAndClear(); // both targets, depth cleared to 0 ("nothing here")
graphicsDevice.BlendState = BlendState.Opaque;
graphicsDevice.DepthStencilState = DepthStencilState.Default;
// ... draw your opaque meshes with the prepass effect below ...
gBuffer.Unbind(); // back to the back buffer; IsCurrent = true, ContentVersion moves
The prepass pixel shader writes the two values in this encoding, which GBuffer.fxh undoes:
struct PSOutput
{
float Depth : SV_Target0; // -PositionVS.z
float4 Normal : SV_Target1; // view-space normal * 0.5 + 0.5
};
PSOutput PS(VSOutput input)
{
PSOutput o;
o.Depth = -input.PositionVS.z;
o.Normal = float4(normalize(input.NormalVS) * 0.5 + 0.5, 1.0);
return o;
}
- What to draw: only what ends up the nearest surface on screen, which means opaque, depth-writing materials, drawn with the cull mode they are shaded with. A blended surface in the G-buffer would have the traced results of whatever is behind it applied to itself.
IsCurrentsays the targets hold this frame's surfaces. Gate every traced pass on it.- Skipping a frame: call
ConfirmCurrent()instead of redrawing when nothing changed, andInvalidate()when the prepass cannot run. ContentVersionmoves on every real redraw, so a pass can tell new surfaces from old.- Perspective cameras.
GBufferViewPositionfinds the surface along the line from the eye through the pixel; an orthographic projection needs a different reconstruction, which is not provided.
Deforming meshes
Update the positions your ITriangleMesh returns, then refit the BLAS:
skinnedMesh.UpdatePositions(currentPose);
characterBlas.Refit();
The next Tlas update sees the new bounds, and the next Upload re-sends that BLAS in place. A refit keeps the
tree's topology, so the mesh must keep its triangle count - Refit throws if it changed - and after a large change
of pose, MeshBlas.Build a fresh one.
Limits
- Triangles only: each one double-sided.
- No closest hit on the GPU: the HLSL is the any-hit query.
- Finite rays: the any-hit walks treat an infinite
maxDistanceasfloat.MaxValue, on both sides; the CPU closest hit accepts it as it is. - Units: the triangle test treats a determinant below 1e-12 as a degenerate triangle, so a mesh authored in units where triangles are smaller than about 1e-6 on a side is never hit. Metres or centimetres are fine; nanometres are not.
- Tree depth is capped at
Bvh.MaxTreeDepth(24). Deeper nodes stay leaves, so pathological input gets slower, never wrong. - One structure per scene: the
Tlasand its GPU copy are updated in place.
License
MIT.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0-windows7.0 is compatible. net9.0-windows was computed. net10.0-windows was computed. |
-
net8.0-windows7.0
- MonoGame.Framework.Compute.WindowsDX.NoMemoryLeak (>= 3.8.3.1)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on BorrowedTorch.RayTracing:
| Package | Downloads |
|---|---|
|
BorrowedTorch.Engine
Kindling, Borrowed Torch's game engine: what a game's own code builds against - its features registering components, systems, keys and UI handlers - for the Kindling editor and player to run |
GitHub repositories
This package is not used by any popular GitHub repositories.