BorrowedTorch.RayTracing
1.7.1
Prefix Reserved
dotnet add package BorrowedTorch.RayTracing --version 1.7.1
NuGet\Install-Package BorrowedTorch.RayTracing -Version 1.7.1
<PackageReference Include="BorrowedTorch.RayTracing" Version="1.7.1" />
<PackageVersion Include="BorrowedTorch.RayTracing" Version="1.7.1" />
<PackageReference Include="BorrowedTorch.RayTracing" />
paket add BorrowedTorch.RayTracing --version 1.7.1
#r "nuget: BorrowedTorch.RayTracing, 1.7.1"
#:package BorrowedTorch.RayTracing@1.7.1
#addin nuget:?package=BorrowedTorch.RayTracing&version=1.7.1
#tool nuget:?package=BorrowedTorch.RayTracing&version=1.7.1
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, any-hit and closest-hit traversals 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:
RtTraceAnyandRtTraceClosestin a compute (or pixel) shader. Shadows, ambient occlusion and other occlusion-style effects can be written on top of the first; bounced light and reflections, which need to know what a ray landed on, on top of the second. - 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 or sort them by material: it answers "is anything in the way" and "where does this ray hit", on both sides, and what is there - a material, a colour - is yours to look up by what the hit names.
Requirements
- BorrowedTorch's MonoGame compute fork:
BorrowedTorch.MonoGame.Framework.Compute.WindowsDX3.8.6.101 (DirectX 11, HiDef profile, compute shaders and structured buffers), which comes with the package. 1.5.0 and earlier came with the old fork,MonoGame.Framework.Compute.WindowsDX.NoMemoryLeak3.8.3.1. - Shaders compiled for
DirectX_11, kernels ascs_5_0, by that fork's effect compiler: it loads effects of its own format (MGFX 100) only, and the old fork's content builder (dotnet-mgcb-compute3.8.3) writes effects it refuses. - 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 - and, optionally, texture coordinates and normals. |
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 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 - and AlphaTested, for an instance with holes in it (section 6a). |
AnyHitFilter |
Your test of whether a hit on an alpha-tested instance counts, on the CPU; RtAnyHit is its HLSL twin. |
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.
A large tree - from some 32,000 triangles, or instances - is built on several threads, and the call returns once it is done. The tree is exactly the one a single thread would build, on any number of cores; the mesh itself is still read on the calling thread only.
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 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.
6a. Alpha-tested geometry
Leaves, fences and grates are a few quads with holes cut in them by a texture's alpha. Traced as their triangles, they cast the shadow of the whole quad. To trace them as their texture says:
Give the mesh its texture coordinates.
ITriangleMeshhas two optional members,HasTextureCoordinatesandGetTextureCoordinates(triangle, out uv0, out uv1, out uv2); a mesh that implements them has its coordinates kept in the BLAS (MeshBlas.TextureCoordinates) and uploaded beside its triangles.public bool HasTextureCoordinates => _uvs != null; public void GetTextureCoordinates(int triangle, out Vector2 uv0, out Vector2 uv1, out Vector2 uv2) { uv0 = _uvs![_indices[triangle * 3]]; uv1 = _uvs[_indices[triangle * 3 + 1]]; uv2 = _uvs[_indices[triangle * 3 + 2]]; }Flag the instance, and say what to test it against.
RayTracingFlags.AlphaTested, and a value of yours - which texture, which cutoff - as its user data:tlas.Add(fence.Id, fenceBlas, fence.World, RayTracingFlags.Default | RayTracingFlags.AlphaTested, fenceAlphaSlot);Changing an instance's user data alone moves
Tlas.FlagsVersion, as a flag edit does.Test the hits. On the GPU, define
RT_ANY_HITbefore includingRayTraversal.fxhand defineRtAnyHitafter it. It is asked about every hit on an alpha-tested instance, and afalselets the ray through:#define RT_ANY_HIT #include "Lib/RayTraversal.fxh" Texture2D<float4> FenceAlpha; // yours: an atlas, an array - whatever userData indexes float AlphaCutoff; bool RtAnyHit(int userData, int triangleIndex, float2 barycentrics) { float2 uv = frac(RtTriangleUv(triangleIndex, barycentrics)); // a repeating texture uint width, height; FenceAlpha.GetDimensions(width, height); // Load or SampleLevel: a compute shader has no derivatives to pick a mip with. return FenceAlpha.Load(int3(uv * float2(width, height), 0)).a > AlphaCutoff; }On the CPU, pass an
AnyHitFiltertoTlas.IntersectAnyorTlas.Intersect- the same test, so that a click goes through the holes too:bool Solid(in TlasInstance instance, int triangle, float u, float v) { instance.Blas.Geometry.GetTextureCoordinates(triangle, out var uv0, out var uv1, out var uv2); return SampleAlpha(instance.UserData, new GpuTriangleUv(uv0, uv1, uv2).At(u, v)) > cutoff; } tlas.Intersect(ray, float.MaxValue, out var hit, RayTracingFlags.Pickable, Solid);
An alpha-tested instance whose query has no test - no RT_ANY_HIT, a null filter - is solid. Instances without the
flag are never tested, so they cost nothing more than before. The test answers yes or no: light through stained glass,
partly blocked, is not something an any-hit query can say.
6b. Closest hit on the GPU
A bounce or a reflection has to know what the ray landed on, not only whether something was in the way.
RtTraceClosest finds the nearest hit, through the holes of alpha-tested instances as the any-hit walk does when the
kernel defines RT_ANY_HIT, and says where it is:
#include "Lib/RayTraversal.fxh"
StructuredBuffer<float4> Albedos; // yours: one per instance, by the user data each was declared with
float3 Bounce(float3 position, float3 normal, float3 direction)
{
RtHit hit;
if (!RtTraceClosest(position + normal * 0.02, direction, 1e8, RT_FLAG_VISIBLE_TO_GI, hit))
return SkyRadiance(direction); // yours: nothing hit, the ray left the scene
float3 hitPosition = position + normal * 0.02 + direction * hit.Distance;
float3 hitNormal = RtHitShadingNormal(hit, direction); // world space, facing back along the ray
float2 uv = RtHitUv(hit); // for a texture of yours
return Albedos[hit.UserData].rgb * LightAt(hitPosition, hitNormal); // yours
}
What an RtHit holds:
Distance- the ray parameter t, asRayHit.Distanceis: the hit is at origin + t * direction.maxDistancewhen nothing was hit.UserData- the instance's, as it was declared (Tlas.Add). This is how a kernel finds its own data about what was hit - a material, an albedo - which is why it is worth giving every instance some, not only the alpha-tested ones.Instance,Triangle,Barycentrics- forRtHitNormal,RtHitShadingNormalandRtHitUv. These are the GPU's own numbering, notRayHit's:Instanceindexes the uploaded records, in the TLAS's tree order rather thanTlas.Instances', andTrianglethe uploaded triangles, in each tree's order rather than the mesh's. -1 for no hit.
A kernel of yours that wants one mesh's triangles - to pick a point on a glowing one and aim a ray at it, say, or to
tell by a hit's Triangle which of them it landed on - finds them with GpuAccelerationStructure.TryGetTriangles(blas, out first, out count): the run of Triangles (and TriangleUvs, TriangleNormals) that mesh's tree occupies, first
numbered as RtHit.Triangle is. In the mesh's own space, as MeshBlas.Triangles has them - an instance's world
transform is yours to apply - and good until the next Upload, which may lay everything out afresh.
Two normals can be had at a hit, each in world space, unit, and turned to face the side the ray came from, as every triangle here is two-sided - and right under any transform, mirrored and non-uniformly scaled included:
RtHitNormal- the triangle's own plane: flat, faceted on a sphere.RtHitShadingNormal- the mesh's own normals, weighted at the hit asRtHitUvweighs texture coordinates: smooth across the triangles, as the mesh is shaded. For it the mesh hands its normals over, as it does texture coordinates for 6a -HasNormalsandGetNormals(triangle, out n0, out n1, out n2)onITriangleMesh, in the mesh's own space and its corners' order. They are read when the BLAS is built and again on everyRefit, as a deforming mesh's turn with it. A mesh that hands none over getsRtHitNormal.
The walk is Tlas.Intersect's, line for line: it opens the nearer of two children first, so a hit found in it can
turn the other down unopened, and keeps the child it put off on a stack. That stack - 24 entries for each of the two
levels, one per level of the deepest tree - is a per-thread array the compiler keeps in scratch memory, and is what
the any-hit walk does without. A ray that only asks whether it is blocked should still ask RtTraceAny.
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. |
bool RtTraceClosest(float3 origin, float3 direction, float maxDistance, int requiredFlags, out RtHit hit) |
The nearest hit on an instance carrying every flag in requiredFlags, within maxDistance (section 6b). The direction need not be unit length. |
bool RtTraceClosestCounted(..., out RtHit hit, inout uint steps) |
The same walk, counting as RtTraceAnyCounted does. |
struct RtHit |
Distance, Instance, Triangle, UserData, Barycentrics - see section 6b. |
float3 RtHitNormal(RtHit hit, float3 direction) |
The hit triangle's normal, world space and unit, facing back along direction. |
float3 RtHitShadingNormal(RtHit hit, float3 direction) |
The mesh's own normal at the hit, its corners' weighted, world space and unit, on the side RtHitNormal faces - or RtHitNormal for a mesh without normals. |
float3 RtTriangleNormal(int triangleIndex, float2 barycentrics) |
The corners' normals weighted at a hit, in the mesh's space, not renormalised; zero for a mesh without normals. |
float2 RtHitUv(RtHit hit) |
The texture coordinate where the hit landed. |
RT_TRAVERSAL_STACK_SIZE |
The closest-hit walk's stack, per level: Bvh.MaxTreeDepth. |
RT_FLAG_CASTS_SHADOW, RT_FLAG_VISIBLE_TO_GI, RT_FLAG_ALPHA_TESTED |
The GPU's view of RayTracingFlags (Pickable is CPU-only). |
RT_ANY_HIT |
Defined by a kernel before the include: hits on alpha-tested instances are put to its RtAnyHit. |
bool RtAnyHit(int userData, int triangleIndex, float2 barycentrics) |
The kernel's own, defined after the include: whether a hit counts. userData is the instance's. |
float2 RtTriangleUv(int triangleIndex, float2 barycentrics) |
The texture coordinate at a hit. |
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, TriangleUvs, TriangleNormals, 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, under a perspective or an orthographic projection. |
GBufferWorldPosition(..., inverseView) |
The same point through inverseView. |
GBufferViewLine(pixel, gBufferSize, inverseProjection, out origin, out through) |
The pixel's line of sight in view space: origin + through * depth is its point at that depth. From the eye under perspective; parallel, from the pixel's own point on the z = 0 plane, under orthographic. through.z is -1. |
GBufferViewLineAt(ndc, inverseProjection, out origin, out through) |
The same for any point on the screen, in normalized device coordinates. |
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.- Either projection.
GBufferViewPositionfinds the surface along the pixel's line of sight, whichGBufferViewLinegives: from the eye through the pixel under a perspective camera, and parallel to the view axis from the pixel's own point under an orthographic one. Both come from un-projecting the pixel at the near and far clip depths, so a jittered or off-centre projection works the same. A traced pass that starts rays at the viewer starts them atorigin, not the eye.
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.
Deforming meshes on the GPU
A mesh whose vertices never leave the GPU - a cloth simulated there, a mesh skinned in a compute pass - is refitted
there too. Build it as a deformable BLAS, over its rest pose, from a mesh that can also name each triangle's vertices
(IIndexedTriangleMesh):
var clothBlas = MeshBlas.BuildDeformable(restMesh);
Each frame, write its vertices - position and normal, RtVertex, 24 bytes, in its own space, indexed as
GetTriangleIndices indexes them - into a structured buffer of your own, then, after the Upload that placed it:
clothBlas.SetBounds(reachOfTheCloth); // for the TLAS: a box holding every pose it can take, in its own space
tlas.BeginUpdate(); /* ... */ tlas.Add(id, clothBlas, Matrix.Identity, flags); /* ... */ tlas.EndUpdate();
gpu.Upload(tlas);
if (moved || gpu.NeedsRefit(clothBlas))
gpu.Refit(blasRefitEffect, clothBlas, vertexBuffer);
Refitrewrites its triangles, their normals and every box of its tree in place in the shared buffers: one dispatch over its triangles, then one per level of the tree, deepest first.Versionmoves, as for any change the traced kernels have to see;RefitCountcounts the refits among its moves, for a pass that keeps what it gathered over frames to tell a mesh deforming in place from the scene changing.BlasRefit.fxis the effect it runs: it ships besideRayTraversal.fxh, atContent/Effects/Lib, for you to compile as you compile your other kernels. Its parameters are bound byRefit-RefitVertices,RefitVertexIndices,RefitLevelNodes,RefitTriangles,RefitNormals,RefitNodes,RefitTriangleOffset,RefitTriangleCount,RefitNodeOffset,RefitLevelStart,RefitLevelCount- under names of its own, never to be compiled withRayTraversal.fxh, which reads the same buffers.NeedsRefitis true until the first refit, and again whenever anUploadhas laid everything out afresh and written its rest pose back: a host that refits only when its mesh moved refits then too.SetBoundsis what the CPU knows of it: theTlasboxes its instance by it, and nothing of its geometry is sent again for it. The CPU's own queries -Intersect,IntersectAny, picking through theTlas- still find the rest pose.- One instance each: a deforming mesh's tree is its own.
Limits
- Triangles only: each one double-sided.
- Smooth normals only from the mesh:
RtHitShadingNormalweighs the normals the mesh hands over, and is the flatRtHitNormalfor a mesh that hands over none. Per corner, asITriangleMeshgives them: a normal map is the caller's to apply. - Finite rays: the any-hit walks treat an infinite
maxDistanceasfloat.MaxValue, on both sides; the closest-hit walks accept it as it is, on both sides too. - 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
- BorrowedTorch.MonoGame.Framework.Compute.WindowsDX (>= 3.8.6.101)
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.