Architecture snapshot: December 2026. This article documents Play2Train's compute-shader GPU raycasting and animated-character culling subsystem (src/engine/renderer/GpuRaycaster.h/.cpp, GpuRaycasterGlobal.h, GpuRayErrorCode.h, GpuRayEligibility.h/.cpp, GpuRayShared.h, GpuRayTraversalPolicy.h, src/engine/components/GlbRayBvh4.h/.cpp, GlbRaycast.h, GlbRaycast_BoneProxies.cpp, GlbRaycast_Gpu.cpp, GlbMeshCache.cpp, and Resources/Shaders/Engine/gpu_ray_common.glsl, gpu_ray_accum.comp.glsl, and gpu_ray_accum_multimesh.comp.glsl — roughly 5,460 lines of C++23 and OpenGL 4.3 GLSL, plus conformance tests in tests/ray_cache_conformance.h and tests/gpu_ray_prewarm_conformance.h) inside Gattic's closed-source Play2Train SDK. Robot Universe builds its GPU-only gameplay laser (IntersectionSystem.h, IntersectionDetail_GpuLaser.cpp) on top of this pipeline; PloppyPals runs on the same engine and does not currently use the gameplay laser.
Fire a laser beam across a 3D city block and ask a simple question: what exact triangle did that beam hit first?
If the world were made only of rigid, frozen statues, that question would be a textbook graphics problem. Real games are much messier. A single character or vehicle can contain dozens of sub-meshes and tens of thousands of triangles. Worse, animated characters are skinned: every frame, dozens of skeleton bones bend, twist, and stretch the skin's triangles into a brand-new pose. If you aim a laser right between a running character's legs, the game must know whether you clipped a shin by a millimeter or missed cleanly through empty air — sixty times a second, without needing an expensive "RTX" hardware ray-tracing card.
When people hear "GPU ray tracing," they usually picture modern hardware RT cores (VK_KHR_ray_tracing_pipeline or DXR). Those cores are fast, but requiring them cuts off older GPUs, integrated graphics, and OpenGL-class platforms. Play2Train takes a different path: it runs triangle-accurate GPU ray tracing entirely in standard OpenGL 4.3 compute shaders using plain Shader Storage Buffer Objects (SSBOs).
Making non-RTX compute ray tracing both fast and trustworthy against animated characters comes down to solving four interlocking engineering problems:
- Compact, refittable geometry trees. Sending raw triangles to a compute shader is too slow; rebuilding a brand-new acceleration tree from scratch every time a character takes a step is even slower. Play2Train stores a 64-byte quantized 4-wide BVH (
RayBvh4Node) whose structure is built once and whose bounds can be refitted in place when a skeleton moves. - Dispatch overhead on complex entities. Tracing a 20-mesh building or robot with 20 separate GPU compute dispatches floods the driver with CPU overhead. Play2Train packs multiple mesh BVHs into a single multi-mesh SSBO atlas for one compute dispatch per entity, while keeping per-frame mesh transforms in a separate buffer so moving objects never invalidate the cached atlas.
- Avoiding wasted work on animated misses. Most laser rays that enter a character's outer bounding box still miss the character's actual body (passing beside an arm or between the legs). Play2Train wraps each bone in tight joint-local bind-space bone proxies (
GlbRaycast_BoneProxies.cpp) that give a fast "definitive miss" cull — skipping vertex skinning, BVH refitting, and GPU uploads whenever every ray misses the skeleton's silhouette. - Never confusing a broken sensor with empty air. In gameplay, silently turning a shader failure, missing mesh, or stack overflow into a "miss" creates invisible armor and ghost shots that are almost impossible to debug. Play2Train enforces a strict rule across every layer of the stack (
GpuRaycaster.h): "Correctness > performance: any inability to run must be surfaced as an explicit failure, never as a silent miss."
Why ray tracing a moving character is harder than it looks
For non-technical readers, imagine trying to check whether a laser pointer hits a marionette puppet hanging in a dark room.
A naive computer program checks every single tiny triangle on the puppet's jacket, sleeves, and boots one by one. For a 40,000-triangle character, checking every triangle for every laser ray is painfully slow.
To speed things up, 3D engines sort triangles into Russian nesting dolls of invisible boxes called a Bounding Volume Hierarchy (BVH). If the laser misses the big box around the whole torso, you skip 15,000 torso triangles in one step. If it enters the torso box, you check four smaller boxes inside it (chest, left shoulder, right shoulder, waist), and keep drilling down until you only test a handful of actual triangles.
Here is the catch: nesting dolls break as soon as the puppet moves. When the puppet swings its arm forward, the skin triangles on the sleeve move right out of their old bind-pose box. Now you face an ugly tradeoff:
- If you keep a single giant box around the whole character, rays fired between the puppet's legs or past its raised elbow hit the big box and force the engine to recalculate all 40,000 skinned triangles and rebuild the nesting dolls — just to discover the beam hit empty air!
- If you skip the GPU and rely on cheap physics capsules instead of real triangles, shots either clip invisible air bubbles around the character or pass straight through detailed armor plates.
- If you require RTX hardware, players on older GPUs or OpenGL 4.3 drivers are locked out completely.
Play2Train threads that needle with a four-stage pipeline:
| Pipeline stage | What it does (plain English) | Engine implementation | Runs on |
|---|---|---|---|
| 1. Scene broad phase | Skips entities whose world box the laser never enters | IntersectionDetail scene BVH + world AABB slab gate |
CPU |
| 2. Bone-proxy definitive miss | Checks tight rotated armor boxes attached to each animated bone; skips skinning & GPU work if all rays miss | GLBModelRenderer::GpuLaserMayHitViaBoneProxies (GlbRaycast_BoneProxies.cpp) |
CPU (O(bones)) |
| 3. Pose refit or static atlas | Either refits a skinned mesh's 4-wide BVH bounds in place, or binds a cached multi-mesh rigid atlas | RefitRayBvh4, BuildSkinnedRayTris, UploadMultiMeshBVH |
CPU + VRAM cache |
| 4. Compute BVH4 trace + accumulation | Traces all active rays in parallel (64 rays per workgroup), keeps the closest hit in world units, and flags overflows as sticky hit = 2 |
gpu_ray_accum.comp.glsl & gpu_ray_accum_multimesh.comp.glsl |
GPU (OpenGL 4.3 Compute) |
Inside the 64-byte quantized BVH4: fast on any GPU, never shrinks a box
Play2Train does not maintain one BVH format for CPU raycasts and a second, different format for GPU raycasts. Both sides share one single data structure defined in src/engine/components/GlbRayBvh4.h: a 4-wide quantized bounding volume hierarchy (RayBvh4).
Why 4-wide instead of a standard 2-wide binary tree? Every time a compute-shader thread fetches a node from GPU memory, it pays memory latency. Packing four child bounding boxes into a single 64-byte node — the exact size of one modern CPU/GPU cache line — cuts tree height roughly in half and lets one memory fetch evaluate four branches at once.
Exact node and child-word layout (GlbRayBvh4.h)
A naive 4-wide node storing four 32-bit float AABBs would need 4 × 6 × 4 = 96 bytes for bounds alone, plus 16 bytes for child indices (112 bytes total). By quantizing each child's minimum and maximum coordinates to 16-bit unsigned integers (0..65535) relative to the hierarchy's root frame (quantMin, quantExtent), Play2Train shrinks every node to exactly 64 bytes:
// src/engine/components/GlbRayBvh4.h
struct RayBvh4Node {
// Child c's bounds on axis a: lo[a][c]..hi[a][c], decoded as
// quantMin + quantExtent * (q / 65535) in the hierarchy's frame.
std::uint16_t lo[3][4];
std::uint16_t hi[3][4];
// An inner node index, a leaf triangle range, or empty (RayBvh4Child).
std::uint32_t child[4];
};
static_assert(sizeof(RayBvh4Node) == 64, "RayBvh4Node is shader-visible");In GLSL std430 storage (gpu_ray_common.glsl), the same 64 bytes appear as uint lo[6], uint hi[6], and uint child[4], where each uint packs two 16-bit child bounds (low 16 bits for even child c, high 16 bits for odd child c). Every 32-bit child[c] word encodes one of three states:
child[c] bit pattern |
Meaning | Decoding formula (GlbRayBvh4.h & gpu_ray_common.glsl) |
|---|---|---|
0xFFFFFFFFu (BVH4_EMPTY) |
Empty slot (fewer than 4 children) | Skipped immediately during traversal |
Bit 31 == 1 (kLeafBit) |
Leaf containing 1–16 triangles | start = word & 0x07FFFFFFu (27 bits, up to 2^27 = 134,217,728 triangles); count = ((word >> 27) & 0xFu) + 1u |
Bit 31 == 0 (and != 0xFFFFFFFFu) |
Inner node index in bvhNodes[] |
Direct index (rebased by md.nodeOffset inside multi-mesh atlases) |
Building, collapsing, and conservative outward quantization
BuildRayBvh4 (src/engine/components/GlbRayBvh4.cpp) constructs the hierarchy in two clean passes:
- 16-bin Surface Area Heuristic (SAH) binary build. Starting from every triangle's AABB and centroid,
BuildBinaryevaluates 16 centroid bins along all three axes to find the split minimizingleftArea * leftCount + rightArea * rightCount, stopping at leaves of up tokLeafMax = 8triangles. If a split becomes badly lopsided (min(leftCount, rightCount) < 4), it falls back to anstd::nth_elementmedian split — and enforces a hard depth capkMaxDepthCap = (kBvhTraversalMaxStack / 3) + 1 = 86so degenerate meshes cannot build a tree that would blow the GPU's fixed traversal stack. - One-level collapse into 4-wide nodes.
Collapser::Innerreplaces each binary inner child with its two grandchildren (producing up to 4 children per node). If a depth-capped binary leaf holds more thankMaxLeafTriangles = 16triangles,Collapser::Rangesubdivides it cleanly into a 4-ary subtree of≤ 16-triangle leaves. Crucially, parents are emitted before their children (nodes[0]is always the root), so a reverse index loopfor (i = nodeCount; i-- > 0;)visits every child before its parent — which makes bottom-up refitting trivial and recursion-free!
Shrinking float coordinates to 16-bit integers carries one classic danger: rounding error. If a child's quantized box rounds inward by even a fraction of a millimeter, a ray grazing a triangle edge can miss the box and report a false miss. GpuRayShared.h eliminates that failure mode mathematically:
ComputeConservativeQuantRange3expands each axis of the root bounds bypad = max(1e-4f, max(2.0f * step, extent * 1e-6f))(at least two 16-bit quantization steps plus relative and absolute margins).QuantizeMinU16always rounds down withstd::floor(t * 65535.0f), andQuantizeMaxU16always rounds up withstd::ceil(t * 65535.0f)— deliberately avoiding clampingtto[0, 1]before rounding because clamping can shrink a bound.
The result is a strict invariant: every decoded 16-bit child AABB is guaranteed to be a superset of its true floating-point triangles.
Watertight ray–triangle tests and in-place skinned refitting
Inside each compute shader (Resources/Shaders/Engine/gpu_ray_common.glsl), traversal walks the BVH4 near-first: whenever a node pops off the stack, all hit child boxes (up to 4) are insertion-sorted farthest-first before pushing onto stack[] and stackNear[], so the closest child pops next and tightens bestT early. Any popped entry whose entryNear > bestT is discarded immediately without even reading its node from VRAM.
Two subtle geometric safeguards live in gpu_ray_common.glsl:
- NaN-proof AABB slab test (
intersectAABB). ClassicinvD = 1.0 / rdslab tests produce0 * INF = NaNwhen a ray runs parallel to a box face and sits directly on the slab boundary. Play2Train explicitly checksabs(d) < GPU_RAY_EPS(1e-8, injected from C++Engine::GpuRayShared::kRayEpsilonso CPU and GPU tolerances cannot drift) and testso < mn || o > mxwithout dividing. - Watertight Woop ray–triangle intersection (
intersectTri). Instead of an epsilon-heavy Möller–Trumbore test that can leak rays through shared edges between adjacent triangles, Play2Train uses Sven Woop et al.'s watertight projection test: it permutes coordinates so the ray's dominant axis becomeskz, shears the three triangle vertices(v0, v0 + e1, v0 + e2)into ray space, and checks the 2D edge determinants(U, V, W)for consistent sign. Both CPU triangle prep (RayTriangleSource::Prepared) and GPU SSBOs store each triangle as precomputed(v0, e1 = v1 - v0, e2 = v2 - v0)(36 bytesperGpuRayTri).
And when a skinned character moves into a new animation pose, Play2Train never rebuilds the SAH tree from scratch. GLBModelRenderer::RefitSkinnedBVH (GlbMeshCache.cpp) computes the posed triangle min/max bounds (parallelizing across FixedThreadPool whenever triCount >= 4096) and calls RefitRayBvh4: a single linear reverse-order sweep over the existing RayBvh4 topology that recomputes child boxes, calculates a fresh conservative quantization frame (poseFrame), and re-quantizes lo/hi into per-instance cache.poseNodes. Because the child topology never changes, every traversal-depth and stack-safety guarantee certified for the shared bind-pose BVH automatically holds for every animated pose too.
Packing a whole entity into one compute dispatch
Imagine checking a detailed sci-fi building or hovercar made of 25 separate GLB sub-meshes (chassis, doors, windows, wheels, antennas, thrusters). If you bind one mesh's BVH, call glDispatchCompute, issue a glMemoryBarrier, bind the next mesh, and repeat 25 times per entity, the CPU spends more time talking to the OpenGL driver than the GPU spends tracing rays.
GpuRaycaster solves this with multi-mesh BVH packing (src/engine/renderer/GpuRaycaster.h, GpuRaycaster.cpp, and Resources/Shaders/Engine/gpu_ray_accum_multimesh.comp.glsl).
One atlas, one dispatch — without matrix churn
When an entity has more than kPreferPerMeshDispatchMaxMeshes = 4 rigid meshes, the gameplay laser (BuildOrGetPackedMultiMeshAtlasShared in IntersectionDetail_GpuLaser.cpp) concatenates every mesh's RayBvh4Node array, triIndices array, and prepared GpuRayTri array into three contiguous buffers, rebasing each inner node index by nodeOffset, each leaf start by triIndexOffset, and each triangle index by triOffset. Alongside them sits a flat array of MultiMeshDesc headers:
// src/engine/renderer/GpuRaycaster.h
struct MultiMeshDesc {
uint32_t nodeOffset = 0;
uint32_t nodeCount = 0;
uint32_t triIndexOffset = 0;
uint32_t triIndexCount = 0;
uint32_t triOffset = 0;
uint32_t triCount = 0;
uint32_t raySpaceMode = 0; // 0 = Assembled, 1 = MeshLocal
uint32_t _pad0 = 0;
float quantMin[3] = {0.0f, 0.0f, 0.0f}; uint32_t _pad1 = 0;
float quantExtent[3] = {1.0f, 1.0f, 1.0f}; uint32_t _pad2 = 0;
float rootBmin[3] = {0.0f, 0.0f, 0.0f}; uint32_t _pad3 = 0;
float rootBmax[3] = {0.0f, 0.0f, 0.0f}; uint32_t _pad4 = 0;
};Look closely at what is deliberately missing from MultiMeshDesc: the mesh's inverse transform matrix invMeshWorld!
As the comment in GpuRaycaster.h explains, rigid geometry inside an atlas is usually static, whereas transforms change every time a vehicle moves or a door swings open. Embedding invMeshWorld inside MultiMeshDesc would change the atlas's contentHash every frame and force repeated multi-megabyte SSBO re-uploads. Instead, MultiMeshDesc stays purely geometric and immutable, while per-mesh mat4 invMeshWorld[] transforms stream through a tiny dedicated buffer (UploadMultiMeshInvMeshWorld, binding 8).
Every compute thread (local_size_x = 64) owns one ray, loops for (uint mi = 0u; mi < uMeshCount; ++mi), transforms the ray into mesh-local space via invMeshWorld[mi] when md.raySpaceMode == 1, checks md.rootBmin/md.rootBmax first to skip irrelevant sub-meshes cheaply, walks the quantized BVH4, and continuously tightens bestWorld across all meshes of the entity in one single glDispatchCompute call.
| SSBO binding | Buffer name (gpu_ray_accum_multimesh.comp.glsl) |
Access | Lifetime / Update cadence |
|---|---|---|---|
0 |
bvhNodes[] (RayBvh4Node, 64 B/node) |
readonly |
Cached in GpuRaycaster VRAM LRU cache |
1 |
triIndices[] (uint32_t) |
readonly |
Cached in GpuRaycaster VRAM LRU cache |
2 |
tris[] (GpuRayTri, 36 B: v0, e1, e2) |
readonly |
Cached in GpuRaycaster VRAM LRU cache |
3 |
rays[] (Ray, 32 B: origin, maxDistance, direction, _pad) |
readonly |
Uploaded once per accumulation batch |
4 |
assembledToWorld[] (float scale per ray) |
readonly |
Uploaded once per accumulation batch |
5 |
worldMax[] (float broad-phase max world distance) |
readonly |
Uploaded once per accumulation batch |
6 |
bestHits[] (Hit, 16 B: hit, distance, targetId, _pad) |
read/write |
Persistent accumulator across all targets; parkable across frames |
7 |
meshes[] (MultiMeshDesc, multi-mesh only) |
readonly |
Cached alongside bindings 0–2 in VRAM LRU cache |
8 |
invMeshWorld[] (mat4, multi-mesh only) |
readonly |
Uploaded per entity dispatch (UploadMultiMeshInvMeshWorld) |
Notice also how the router splits work in IntersectionDetail_GpuLaser.cpp:
- Skinned meshes are never packed into multi-mesh atlases. They always run through the per-mesh path (
gpu_ray_accum.comp.glsl, bindings0..6) after bone-proxy culling, withRaySpaceMode::Assembled(because skinned vertices and refitted BVH4 nodes are already in the model's assembled coordinate space). - Rigid entities with
≤ 4meshes also stay on the per-mesh path (RaySpaceMode::MeshLocal, passinguInvMeshWorldas a uniform) to avoid unnecessary CPU atlas packing work. - Rigid entities with
> 4meshes use the packed multi-mesh atlas (gpu_ray_accum_multimesh.comp.glsl, bindings0..8) for one dispatch per entity.
Dual-key VRAM caching and bounded 4 MiB streaming prewarm
GpuRaycaster owns a bounded GPU BVH cache (kMaxBVHCacheEntries = 256, kMaxBVHCacheBytes = 256 MiB) with O(1) lookup (m_bvhCacheIndex), LRU eviction (EnforceCacheLimits), and full residency accounting via ResourceResidencyManager. Single-mesh and multi-mesh keys share one hash table cleanly by XORing multi-mesh keys with kMultiMeshKeyXor = 0x8000000000000000ULL.
One subtle cache bug trips up almost every ray-tracing engine that mixes static buildings with animated characters: how do you key the cache?
- If you key static/rigid BVHs by
cacheKeyalone, a hot reload or content swap can silently collide with stale bytes. So for rigid meshes (ownerKey == 0,nodesVersion == 0,trisVersion == 0),UsePairKey(false)returnstrueand keys the index byHashCombine64(cacheKey, contentHash). On a cache hit,UploadBVH/UploadMultiMeshBVHperforms zero GPU uploads (cacheHitsNoUpload++). - If you used that same
(cacheKey, contentHash)pair key for skinned characters, every single animation frame has a brand-new pose and a brand-newcontentHash— you would insert 60 new cache entries per second per character and thrash the 256-entry LRU cache! So for pose-updated entries (ownerKey != 0or nonzero versions),UsePairKey(true)returnsfalse: the cache keys bycacheKeyalone and treats acontentHashmismatch as "refresh this entry's buffers in place". When a character entity is destroyed,PurgeOwner(ownerKey)frees its pose buffers immediately without disturbingownerKey == 0shared rigid assets.
Finally, static rigid models can prewarm their GPU BVH buffers incrementally during streaming (UploadBVHIncremental in GpuRaycaster.cpp and PrewarmGpuRayResourceIncremental in GlbRaycast_Gpu.cpp), uploading at most 4 MiB per call (kIncrementalUploadChunkBytes) across nodes, indices, and triangles without hitching the frame. Skinned models deliberately skip incremental prewarm — as verified by tests/gpu_ray_prewarm_conformance.h — because a skinned character's payload is its live pose, which is uploaded on demand only when a ray actually survives the bone-proxy cull.
Bone proxies in joint-local bind space: the "definitive miss" cull
Now comes the heart of animated-character performance: how do you avoid skinning 40,000 vertices and refitting a BVH4 every time a laser whizzes past an animated character without touching it?
Picture putting a tight, custom-fitted suit of rectangular armor plates on a stunt performer — two snug plates along each thigh, two along each shin, separate plates on each forearm, torso, and head — bolted directly to the bones of their skeleton. When the performer runs, jumps, or crouches, you do not have to recalculate a single stitch of their fabric costume to move those armor plates; you just move the rigid plates along with the 30–60 skeleton joints!
If a laser beam misses every single armor plate, it is mathematically guaranteed to miss every triangle of the character's animated skin. Play2Train calls that a "definitive miss" (src/engine/components/GlbRaycast_BoneProxies.cpp). When all active laser rays produce a definitive miss on a skinned mesh, the gameplay laser skips:
- CPU vertex skinning (
EnsureRayDerivedPositions) - Parallel BVH4 refitting (
RefitSkinnedBVH/RefitRayBvh4) - Skinned triangle edge generation (
BuildSkinnedRayTris) - GPU SSBO pose upload (
UploadBVH) - The GPU compute dispatch itself!
Building tight, gap-preserving proxies once in joint-local bind space
Why are bone proxies stored in joint-local bind space instead of world space or mesh bind space? Because a thigh bone rotates wildly as a character runs. An axis-aligned box wrapped around a diagonal thigh in mesh space turns into a fat cube that bridges right across the empty space between the left and right legs! In the joint's own local coordinate frame, the thigh is neatly aligned with the bone axis — so its bounding box stays razor-thin and rotates smoothly as an Oriented Bounding Box (OBB) when the character moves.
GlbMeshCache.cpp builds each mesh's BoneProxyCacheEntry once (shared across all instances of the model via a 2,048-entry / 128 MiB snapshot cache and persisted to disk under kBoneProxyBuildVersion = 5):
- Mathematically conservative
0.25skin-weight threshold. In glTF/GLB skinning, every vertex carries up to 4 bone weights that sum to1.0. By the pigeonhole principle, at least one weight is guaranteed to be≥ 0.25. Assigning each vertex to every joint withweight >= 0.25f(specifically skipping onlyw < weightThresholdso an exact4 × 0.25vertex is never dropped!) guarantees every vertex belongs to at least one proxy while preventing tiny0.02incidental hip weights from bloating torso boxes across the legs. - Transform into joint-local bind space via
invBind. Each vertex assigned to jointjis transformed by the skin'sinverseBindMatrices[j], placing it in the bone's native local coordinates. Meanwhile, the builder precomputes and cachesjointBindMatrices[j] = invertAffine(invBind)(falling back to identity if non-invertible). - Subdivide long limbs into up to 4 bins (
kMaxProxySplits = 4). Even in joint-local space, a single box around a curved coat or long torso can still bridge gaps. Whenever a joint's widest local span exceeds0.05 mand owns at least128unique vertices, Play2Train partitions those vertices intoclamp(ceil(axisSpan / 0.25f), 1, 4)bins along the widest axis and emits a tight OBB per bin. - Minimal inflation (
margin = 1.5 mm,minRadius = 2.5 mm). Each box's half-extents receive only0.0015 mof numerical margin (clamped to a minimum0.0025 mso flat geometry stays non-degenerate) — intentionally tiny so gaps between limbs stay wide open.
Recovering jointWorld at runtime (ComposeBoneProxyJointWorldMatrix)
Here is a subtle matrix bug that catches almost everyone implementing bone proxies the first time: the renderer's m_instanceState.jointMatrices does not store plain joint world matrices — it stores skinning matrices:
skinMatrix = jointWorld * inverseBindIf you transformed a joint-local proxy directly by skinMatrix, you would apply inverseBind twice (once when building the proxy, and a second time inside skinMatrix), warping every proxy box off into outer space!
Play2Train solves this explicitly in src/engine/components/GlbRaycast.h:
// src/engine/components/GlbRaycast.h
// Recover the current joint-world matrix from a skinning matrix
// (jointWorld * inverseBind) and the corresponding bind matrix.
inline void ComposeBoneProxyJointWorldMatrix(const float skinMatrix[16],
const float* bindMatrix,
float outJointWorld[16])
{
if (!skinMatrix || !outJointWorld) return;
if (!bindMatrix) {
std::memcpy(outJointWorld, skinMatrix, sizeof(float) * 16);
return;
}
// outJointWorld = skinMatrix * bindMatrix
// = (jointWorld * inverseBind) * bindMatrix = jointWorld
float composed[16];
for (int column = 0; column < 4; ++column) {
for (int row = 0; row < 4; ++row) {
float value = 0.0f;
for (int k = 0; k < 4; ++k) {
value += skinMatrix[k * 4 + row] * bindMatrix[column * 4 + k];
}
composed[column * 4 + row] = value;
}
}
std::memcpy(outJointWorld, composed, sizeof(composed));
}Two-stage test and why outHitJoints == nullptr drops auxiliary spheres
Inside GLBModelRenderer::RayHitsBoneProxies (src/engine/components/GlbRaycast_BoneProxies.cpp), each proxy runs a fast two-stage intersection against the assembled-space ray:
- Circumscribed bounding-sphere pre-check. From
jWorld, the engine extracts the animated OBBcenter(column 3) and basis vectorsaxisX, axisY, axisZ(columns 0–2), scales the proxy's half-extents by their axis lengths (extentX/Y/Z), computesradius = sqrt(eX² + eY² + eZ²), and runs a cheap quadratic ray–sphere test. If the ray misses the sphere, it skips the OBB math completely. - Tight OBB slab test. If the sphere hits,
rayOBBHitnormalizesaxisX/Y/Z, projectsrayOrigin - centeranddirinto the box's rotated local frame via three dot products, and runs an exact slab intersection over[-worldExtents, +worldExtents].
Look at two especially sharp engineering choices in GlbRaycast_BoneProxies.cpp:
- Strict gap preservation in definitive-miss mode.
RayHitsBoneProxiesserves two callers: joint-collection queries (passing a non-nulloutHitJointsvector) and the GPU laser's definitive-miss cull (GpuLaserMayHitViaBoneProxies, which passesoutHitJoints = nullptr). WhenoutHitJoints == nullptr, the function intentionally refuses to countproxy.extraSpheresas hits after an OBB miss, returningtrueimmediately on the first OBB hit andfalseif every OBB misses — ensuring auxiliary broad-phase spheres can never bridge the gap between legs and defeat culling. - Conservative "when in doubt, do not cull" defaults. Every single uncertain path inside
GpuLaserMayHitViaBoneProxiesandRayHitsBoneProxies— null model data, unready pose cache, rigid mesh (skinIndex < 0), missing CPU prep, emptyboneProxies, emptyjointMatrices, or degenerate zero-length ray direction — returnstrue("may hit — do not cull"). A bone proxy can never silently drop a hit because its cache was unready; only a complete, verified miss across all active proxies returnsfalse!
And as a bonus, GlbRaycast_BoneProxies.cpp also tracks AccumulateDynamicPoseBounds (versioned by m_jointUpdateVersion), merging animated pose extrema into the entity's broad-phase assembled AABB (BuildRayWorldQueryContext) so limbs reaching outside a character's bind-pose box are never clipped by stale broad-phase bounds.
Keeping the CPU moving: accumulation, persistent mapping, and cross-frame parking
Even a blazing-fast 0.1-millisecond compute shader can ruin a 60 fps game if you read its results back carelessly.
Why? Think of the GPU like a restaurant kitchen with a long ticket rail. Your game's main rendering commands (shadows, terrain, buildings, characters, lighting) sit on that ticket rail ahead of your laser compute shader. If the CPU submits the laser compute dispatch and immediately calls glGetBufferSubData to wait for the answer in the same frame, the CPU freezes completely until the kitchen cooks every single ticket ahead of the laser — stalling for milliseconds on a busy GPU!
GpuRaycaster avoids those stalls with three layered mechanisms in src/engine/renderer/GpuRaycaster.h/.cpp:
- World-space closest-hit accumulation (one readback, not one per mesh). Instead of reading hits back after every mesh or every entity, the caller starts an accumulation session once (
BeginAccumulation), initializesm_bestHitsSSBOwith each ray's startingbestWorlddistance andhit = 0, uploads the rays once (UploadAccumulationRays), and fires as many single-mesh or multi-mesh dispatches as needed. Each dispatch is separated only by a lightweight GPU-sideglMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT). Inside the shader, a hit overwritesbestHits[idx]only ifworldDist > 0.0 && worldDist <= wMax && worldDist < bestWorld, stampinghit = 1uandtargetId = uTargetIdonly on strict improvement. - Persistently mapped coherent
BestHits+ no-flush fencing. WhenglBufferStorageis available (OpenGL 4.4/ARB_buffer_storage),EnsureAccumulationStorageallocatesm_bestHitsSSBOwithGL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT | GL_DYNAMIC_STORAGE_BITand keeps it permanently mapped (m_bestHitsMappedPtr), eliminating per-frame map/unmap driver stalls (falling back cleanly toglGetBufferSubDataon drivers without buffer storage). Crucially,EndAccumulationBeginReadbackinserts aGlSyncfence (CreateFence()) and deliberately does NOT callglFlush()— because flushing once per target hammers the driver and causes frame spikes. Instead,EndAccumulationFinalizefirst pollsglClientWaitSync(fence, 0, 0)without flushing, and only passesGL_SYNC_FLUSH_COMMANDS_BITif the GPU is genuinely not finished yet. - Cross-frame deferred parking with two-buffer ping-pong (
ParkAccumulationForDeferredCollect). For the gameplay laser (IntersectionDetail_GpuLaser.cpp), even a single same-frame drain can be expensive when the GPU is saturated. Play2Train solves this by running one accumulation session across all targets (scattering per-target active rays into ray-index-aligned slots withmaxDistance = 0sentinels for inactive rays), inserting the fence, and callingParkAccumulationForDeferredCollect(). That detaches(ssbo, mappedPtr, fence, rayCount)intom_parkedAccumand resets the active raycaster so the frame finishes immediately with zero GPU stall. On the next laser update,CollectParkedAccumulationfinds the fence already signaled,memcpys the hits straight out ofmappedPtr, and retires the buffer set intom_spareAccum— which the very nextEnsureAccumulationStorageadopts cleanly, ping-ponging two buffer sets forever with zero reallocation churn.
Never as a silent miss: Play2Train's fail-closed correctness contract
In many game engines, error handling around acceleration structures is quiet and forgiving: if a mesh has no BVH yet, skip it; if a shader stack overflows, break out of the loop and return whatever you found so far; if a GPU context resets, return "no hit."
That sounds convenient — until a player shoots a laser straight through an enemy's chest in production and the game politely reports "Miss." Worse, because a broken raycaster looks identical to a player aiming slightly to the left, silent misses hide real engine bugs for months.
Play2Train forbids that pattern outright. The stated contract in src/engine/renderer/GpuRaycaster.h is explicit:
"Correctness > performance: any inability to run must be surfaced as an explicit failure, never as a silent miss."
Every layer from C++ eligibility checks down to GLSL loop boundaries enforces that rule as a four-gate pipeline:
Gate 1: Mathematical stack-overflow proof before a BVH ever reaches the GPU
Compute shaders cannot allocate dynamic heap memory for their traversal stack; gpu_ray_accum*.comp.glsl uses a fixed stack of GPU_RAY_MAX_STACK = 256 entries, injected from a single C++ source of truth (Engine::GpuRayTraversalPolicy::kBvhTraversalMaxStack in GpuRayTraversalPolicy.h).
Before any mesh is accepted for GPU raycasting, GpuRayEligibility::ValidateSharedBvhPayload and ValidateBvh4TraversalSafety check two numbers computed at build time by ComputeRayBvh4TraversalStats: the tree's maxDepth (levels, root = 1) and measured worst-case maxStack. In a 4-wide BVH, popping one parent pushes at most 4 children — a net stack growth of at most +3 per level — giving a traversal-order-independent upper bound:
ConservativeBvh4MaxStackFromDepth(maxDepth) = 1 + 3 * (maxDepth - 1)If maxDepth == 0 or maxStack == 0 (uncertified stats), eligibility fails closed with NotAvailable. If either maxStack > 256 or 1 + 3 * (maxDepth - 1) > 256, or if maxStack exceeds the conservative bound, eligibility immediately rejects the mesh with GpuRayErrorCode::TraversalFailure.
Gate 2: Mandatory content hashing and pose-version lockstep
In GpuRaycaster::UploadBVH and UploadMultiMeshBVH, view.contentHash == 0 is an unconditional hard rejection (InvalidArgs) — never a "best-effort" cache lookup that might silently reuse stale VRAM buffers.
Similarly, GLBModelRenderer::PublishGpuRayBVHView (GlbRaycast_Gpu.cpp) refuses to mix pose-refitted BVH nodes with bind-pose triangles (or a stale pose). For any skinned mesh, cache.skinnedBVHVersion must be nonzero, cache.poseNodes.size() must equal shared.bvh.nodes.size(), cache.skinnedTrisBuilt must be true, cache.skinnedTrisVersion must equal cache.skinnedBVHVersion, and cache.gpuRayPoseError must be None (remember: BuildSkinnedRayTris checks every transformed vertex coordinate with std::isfinite and stamps NonFiniteInput if any NaN/Inf sneaks in). If any piece is out of sync, the view fails closed instead of silently falling back to the bind pose.
Gate 3: Sticky hit == 2u inside the compute shader
Even with static stack certification, Play2Train practices defense-in-depth inside the shader itself. If stackPtr >= MAX_STACK ever happens at runtime inside either gpu_ray_accum.comp.glsl or gpu_ray_accum_multimesh.comp.glsl, the shader does not quietly drop children and pretend the ray missed:
// Resources/Shaders/Engine/gpu_ray_accum_multimesh.comp.glsl
Hit cur = bestHits[idx];
// Sticky failure: once a ray has reported a traversal failure, preserve it
// across subsequent dispatches so it cannot be overwritten and silently disappear.
if (cur.hit == 2u) {
return;
}
...
if (overflowed) {
cur.hit = 2u;
cur.targetId = uTargetId;
bestHits[idx] = cur;
return;
}Because cur.hit == 2u triggers an immediate early-out at the top of every subsequent mesh and entity dispatch in the accumulation batch, a traversal failure is sticky per ray: it survives all later dispatches, gets surfaced via outTraversalFailures in EndAccumulationFinalize / CollectParkedAccumulation, and fails closed for the affected ray without discarding valid hits from healthy rays in the same batch.
Gate 4: Priority-ordered GpuRayErrorCode, per-mesh attribution, and LaserStatus
Because gameplay code should never have to include OpenGL headers just to understand why a ray failed, src/engine/renderer/GpuRayErrorCode.h defines a standalone, version-stable error enum ordered by GpuRayEligibility::ErrorPriority:
GpuRayErrorCode |
Priority (ErrorPriority) |
LaserStatus mapping |
Trigger / Meaning |
|---|---|---|---|
TraversalFailure |
100 |
TraversalFailure (4) |
BVH4 exceeds 256-entry stack bound, inconsistent stats, or shader returned hit == 2u |
NonFiniteInput |
100 |
TraversalFailure (4) |
NaN/Inf in ray origin/direction, invMeshWorld, quantization metadata, or skinned vertices |
ValidationMismatch |
100 |
TraversalFailure (4) |
Strict validation detected GPU vs. CPU shader-equivalent oracle drift (> 1e-3 distance or entity mismatch) |
GLFailure |
80 |
Unavailable (3) |
Buffer allocation/upload failure (DynamicBufferFailure), missing SSBO, or lost parked session |
NoBVH |
60 |
Unavailable (3) |
Required scene mesh has no valid BVH view (nodeCount == 0 or empty geometry) |
InvalidArgs |
40 |
Unavailable (3) |
contentHash == 0, mismatched residency/matrix counts, singular entity matrix, or API misuse |
NotAvailable |
20 |
Unavailable (3) |
Compute shaders unavailable, IsGpuRayEnabled() == false, off render thread, or session quarantined |
None |
0 |
Hit (2) / Miss (1) |
Pipeline ran cleanly (or InvalidInput (0) if caller supplied a degenerate ray) |
Two finer details in Robot Universe's IntersectionDetail_GpuLaser.cpp keep this strictness surgical rather than over-broad:
- Per-missing-mesh bounds attribution. If a target entity is missing GPU ray coverage on one sub-mesh,
BuildActiveRayListForTargetImplchecks each ray against that specific missing mesh's bounding box (target.gpuMissingMeshes). Only rays that could actually intersect the missing sub-mesh fail closed; rays aimed elsewhere across the entity still get clean results. - CPU shader-equivalent validation and quarantine. In strict validation mode, the gameplay laser can cross-check GPU hits against a CPU reference trace using the exact same BVH4 bounds and tolerances (
GPU_RAY_EPS = 1e-8). Any entity mismatch or distance difference above1e-3logs full ray diagnostics, upgrades that ray toValidationMismatch(LaserStatus::TraversalFailure), and — when strict abort-on-mismatch is active — callsSetGpuLaserQuarantined(true, ValidationMismatch)so subsequent queries immediately fail closed viaEvaluatePipelineuntil the fault is inspected.
Honest boundaries and where the system stops
Play2Train's headers and conformance suites document the exact engineering trade-offs and boundaries of this architecture:
- OpenGL 4.3 compute baseline (no RTX, no GL 3.3 fallback inside
GpuRaycaster). While Play2Train's core rasterizer retains an OpenGL 3.3 baseline,GpuRaycasterexplicitly requires OpenGL 4.3 compute shaders and SSBOs (#version 430). On hardware without compute shaders,Initialize()returnsfalsewithErrorCode::NotAvailable(andm_initAttemptedensures the synchronous ~650 ms shader compile is attempted at most once during loading-screen prewarm). Callers in GPU-only mode surfaceLaserStatus::Unavailable; callers that permit CPU fallback useTraverseRayBvh4on the exact sameRayBvh4data. - Skinned hits still pay CPU skinning and BVH refit. Bone proxies eliminate animated overhead on definitive misses, not on hits. Once a ray pierces any bone proxy of a skinned character, Play2Train still evaluates
EnsureRayDerivedPositions,RefitRayBvh4, andBuildSkinnedRayTrison the CPU (parallelized acrossFixedThreadPoolfor meshes with≥ 4,096triangles) and uploads the posed buffers for that frame. - Single-consumer cross-frame parking.
GpuRaycastersupports exactly one parked accumulation session at a time (m_parkedAccum), tailored to the gameplay laser. CallingParkAccumulationForDeferredCollect()while a previous parked result is uncollected fails closed withInvalidArgs. - Hard capacity caps.
RayBvh4Childaddresses up to2^27(134,217,728) triangle indices per BVH or packed multi-mesh atlas;GpuRaycastercaps its GPU BVH cache at256entries and256 MiBof VRAM (CachePayloadFitsrejects oversized single payloads before allocation). - Render-thread ownership.
GetGlobalGpuRaycaster()returnsnullptroff the render thread, forcing gameplay threads to submit async laser work through the render-thread mailbox (IntersectionDetail_AsyncMailbox.cpp) rather than touching OpenGL contexts unsafely. - Verified conformance invariants.
tests/ray_cache_conformance.hverifies initialization idempotence, zero-upload cache hits, exact byte parity betweenglGetBufferParameteri64v,GetBvhCacheBytes(), andResourceResidencyManager, safePurgeAll()while GPU work is still in flight (confirming retired bindings fail withNoBVHwhile already-queued hits still read back accurately), and independent hit/miss oracles for both single-mesh and multi-mesh shaders.tests/gpu_ray_prewarm_conformance.hverifies that production residency streams rigid models (cyberpunk_car.glb) incrementally while leaving skinned models (quadruped-cat.glb) to on-demand ray queries.
Sources and further reading
- Play2Train SDK (closed-source) — Gattic's internal C++23 engine containing
src/engine/renderer/GpuRaycaster.h/.cpp,GpuRaycasterGlobal.h,GpuRayErrorCode.h,GpuRayEligibility.h/.cpp,GpuRayShared.h,GpuRayTraversalPolicy.h,src/engine/components/GlbRayBvh4.h/.cpp,GlbRaycast.h,GlbRaycast_BoneProxies.cpp,GlbRaycast_Gpu.cpp,GlbMeshCache.cpp,Resources/Shaders/Engine/gpu_ray_common.glsl,gpu_ray_accum.comp.glsl,gpu_ray_accum_multimesh.comp.glsl,tests/ray_cache_conformance.h, andtests/gpu_ray_prewarm_conformance.h. - Sven Woop, Carsten Benthin, and Ingo Wald, "Watertight Ray/Triangle Intersection" (Journal of Computer Graphics Techniques, 2013) — the watertight projection algorithm implemented in
Resources/Shaders/Engine/gpu_ray_common.glsl. - Seamless Portals and a Budgeted View Scheduler in Play2Train — companion architecture deep dive covering exact portal pose mapping, oblique near-plane clipping, content-hardened bases, and Play2Train's GL-free view scheduler.
- Determinism as an Execution Contract in Play2Train — companion architecture deep dive covering
DeterminismMode, queued pump points, stable-partition parallelism, SSEMXCSRguards, andP2TR v6replays. - Active Ragdolls with Staged Recovery in Play2Train — companion architecture deep dive covering Play2Train's soft D6 joint solver, implicit spring-damper drives, five-stage recovery state machine, and
1e6 J/kgfail-safe. - AI-Drivable Animation Authoring in Play2Train — companion architecture deep dive covering Play2Train's embedded Unix-socket posing server, two-bone IK, timeline HUD, and procedural quadruped generator.
- Robot Universe (closed-source, in development) — open-world cyberpunk action adventure set in Haven City, consuming
Play2Train::Engineand building its GPU-only gameplay laser (IntersectionSystem.h,IntersectionDetail_GpuLaser.cpp) on top ofGpuRaycasterand bone-proxy culling. - PloppyPals (closed-source, in development) — companion creature-care game built on
Play2Train::Engine; it does not currently use the gameplay laser.