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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.

Diagram of Play2Train's 64-byte RayBvh4Node memory layout, 32-bit child word encoding, and conservative outward 16-bit quantization. Panel 1 shows sizeof(RayBvh4Node) == 64 bytes split into lo[3][4] (24 bytes of uint16_t minimums, exposed as uint lo[6] in GLSL std430), hi[3][4] (24 bytes of uint16_t maximums, uint hi[6] in GLSL), and child[4] (16 bytes of uint32_t words). Panel 2 breaks down a leaf child word: bit 31 is the leaf flag (1), bits 30..27 store count - 1 (1 to 16 triangles per leaf), bits 26..0 store the triIndices start offset (up to 2^27 triangles), and 0xFFFFFFFFu denotes an empty slot. Panel 3 illustrates conservative outward quantization from GpuRayShared.h: the root bounding box is padded by max(1e-4, 2*step, extent*1e-6), minimums round downward with floor(), and maximums round upward with ceil() without clamping t to [0,1], mathematically guaranteeing that every decoded uint16 box is a strict superset of the original floating-point triangle bounds.
Each RayBvh4Node fits in one 64-byte cache line, encodes four 16-bit quantized child boxes that never shrink, and is read identically by CPU and GLSL compute shaders.

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:

cpp
// 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:

  1. 16-bin Surface Area Heuristic (SAH) binary build. Starting from every triangle's AABB and centroid, BuildBinary evaluates 16 centroid bins along all three axes to find the split minimizing leftArea * leftCount + rightArea * rightCount, stopping at leaves of up to kLeafMax = 8 triangles. If a split becomes badly lopsided (min(leftCount, rightCount) < 4), it falls back to an std::nth_element median split — and enforces a hard depth cap kMaxDepthCap = (kBvhTraversalMaxStack / 3) + 1 = 86 so degenerate meshes cannot build a tree that would blow the GPU's fixed traversal stack.
  2. One-level collapse into 4-wide nodes. Collapser::Inner replaces each binary inner child with its two grandchildren (producing up to 4 children per node). If a depth-capped binary leaf holds more than kMaxLeafTriangles = 16 triangles, Collapser::Range subdivides 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 loop for (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:

  • ComputeConservativeQuantRange3 expands each axis of the root bounds by pad = max(1e-4f, max(2.0f * step, extent * 1e-6f)) (at least two 16-bit quantization steps plus relative and absolute margins).
  • QuantizeMinU16 always rounds down with std::floor(t * 65535.0f), and QuantizeMaxU16 always rounds up with std::ceil(t * 65535.0f) — deliberately avoiding clamping t to [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). Classic invD = 1.0 / rd slab tests produce 0 * INF = NaN when a ray runs parallel to a box face and sits directly on the slab boundary. Play2Train explicitly checks abs(d) < GPU_RAY_EPS (1e-8, injected from C++ Engine::GpuRayShared::kRayEpsilon so CPU and GPU tolerances cannot drift) and tests o < mn || o > mx without 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 becomes kz, 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 bytes per GpuRayTri).

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).

Architecture diagram of Play2Train's multi-mesh BVH packing and dual-key VRAM cache. Top panel shows entity routing in IntersectionDetail_GpuLaser.cpp: skinned meshes always take the per-mesh path after bone-proxy culling (Assembled space), small rigid entities with at most 4 meshes also use per-mesh dispatch to avoid CPU packing cost, and complex rigid entities with more than 4 meshes pack into a single MultiMeshBVHView atlas for one dispatch per entity. Middle dark panel details bindings 0..8 of gpu_ray_accum_multimesh.comp.glsl (local_size_x = 64): bindings 0 (Nodes), 1 (TriIdx), 2 (Tris), and 7 (Meshes descriptors with offsets, quantMin/Extent, and rootBmin/Bmax) form a static VRAM-cached atlas keyed by (cacheKey ^ kMultiMeshKeyXor, contentHash), while binding 8 (invMeshWorld[]) is uploaded separately per dispatch via UploadMultiMeshInvMeshWorld so moving entities never churn the atlas, and bindings 3..6 carry Rays, AsmToWorld, WorldMax, and read-modify-write BestHits. Bottom panel contrasts the 256-entry / 256 MiB LRU cache's dual keying: static rigid entries use pair keys Hash(cacheKey, contentHash) and support 4 MiB chunk streaming prewarm, while pose-updated skinned entries key by cacheKey alone so new poses overwrite in place without leaking memory.
Packing multiple rigid mesh BVHs into one SSBO atlas cuts complex entities down to a single compute dispatch, while isolating invMeshWorld in binding 8 stops moving entities from churning the GPU cache.

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:

cpp
// 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, bindings 0..6) after bone-proxy culling, with RaySpaceMode::Assembled (because skinned vertices and refitted BVH4 nodes are already in the model's assembled coordinate space).
  • Rigid entities with ≤ 4 meshes also stay on the per-mesh path (RaySpaceMode::MeshLocal, passing uInvMeshWorld as a uniform) to avoid unnecessary CPU atlas packing work.
  • Rigid entities with > 4 meshes use the packed multi-mesh atlas (gpu_ray_accum_multimesh.comp.glsl, bindings 0..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 cacheKey alone, a hot reload or content swap can silently collide with stale bytes. So for rigid meshes (ownerKey == 0, nodesVersion == 0, trisVersion == 0), UsePairKey(false) returns true and keys the index by HashCombine64(cacheKey, contentHash). On a cache hit, UploadBVH / UploadMultiMeshBVH performs 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-new contentHash — you would insert 60 new cache entries per second per character and thrash the 256-entry LRU cache! So for pose-updated entries (ownerKey != 0 or nonzero versions), UsePairKey(true) returns false: the cache keys by cacheKey alone and treats a contentHash mismatch as "refresh this entry's buffers in place". When a character entity is destroyed, PurgeOwner(ownerKey) frees its pose buffers immediately without disturbing ownerKey == 0 shared 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:

  1. CPU vertex skinning (EnsureRayDerivedPositions)
  2. Parallel BVH4 refitting (RefitSkinnedBVH / RefitRayBvh4)
  3. Skinned triangle edge generation (BuildSkinnedRayTris)
  4. GPU SSBO pose upload (UploadBVH)
  5. The GPU compute dispatch itself!
Two-part diagram of Play2Train's joint-local bind-space bone proxy cull. Top-left panel (1A) contrasts a naive single per-joint AABB — which balloons across limbs and bridges the gap between a character's legs, forcing full BVH refits on clean misses — against Play2Train's GlbMeshCache.cpp builder, which assigns each bind-pose vertex to every joint with weight >= 0.25, transforms vertices into joint-local bind space via invBind, splits spans over 0.05 m with >= 128 vertices into up to kMaxProxySplits = 4 bins targeting 0.25 m each, and applies tiny 1.5 mm margin and 2.5 mm minRadius inflation so gaps stay open. Top-right panel (1B) shows GlbRaycast::ComposeBoneProxyJointWorldMatrix recovering pure jointWorld = skinMat * bindMat so inverseBind cancels out cleanly with O(bones) cost. Bottom panel (2) traces GpuLaserMayHitViaBoneProxies in GlbRaycast_BoneProxies.cpp through three stages: A) conservative readiness guards returning true (no cull) whenever data is missing or unready; B) a circumscribed bounding-sphere pre-test using scaled half-extents; and C) a tight OBB slab test along normalized joint axes that intentionally excludes extraSpheres on OBB miss when outHitJoints == nullptr, yielding either Definitive Miss (skipping skinning, refit, tri rebuild, upload, and dispatch) or May Hit (proceeding to exact GPU BVH4 trace).
Splitting joint-local proxies into tight bins preserves gaps like the space between legs, turning near-miss shots into an O(bones) definitive miss that bypasses skinning and BVH refits.

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):

  1. Mathematically conservative 0.25 skin-weight threshold. In glTF/GLB skinning, every vertex carries up to 4 bone weights that sum to 1.0. By the pigeonhole principle, at least one weight is guaranteed to be ≥ 0.25. Assigning each vertex to every joint with weight >= 0.25f (specifically skipping only w < weightThreshold so an exact 4 × 0.25 vertex is never dropped!) guarantees every vertex belongs to at least one proxy while preventing tiny 0.02 incidental hip weights from bloating torso boxes across the legs.
  2. Transform into joint-local bind space via invBind. Each vertex assigned to joint j is transformed by the skin's inverseBindMatrices[j], placing it in the bone's native local coordinates. Meanwhile, the builder precomputes and caches jointBindMatrices[j] = invertAffine(invBind) (falling back to identity if non-invertible).
  3. 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 exceeds 0.05 m and owns at least 128 unique vertices, Play2Train partitions those vertices into clamp(ceil(axisSpan / 0.25f), 1, 4) bins along the widest axis and emits a tight OBB per bin.
  4. Minimal inflation (margin = 1.5 mm, minRadius = 2.5 mm). Each box's half-extents receive only 0.0015 m of numerical margin (clamped to a minimum 0.0025 m so 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:

text
skinMatrix = jointWorld * inverseBind

If 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:

cpp
// 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:

  1. Circumscribed bounding-sphere pre-check. From jWorld, the engine extracts the animated OBB center (column 3) and basis vectors axisX, axisY, axisZ (columns 0–2), scales the proxy's half-extents by their axis lengths (extentX/Y/Z), computes radius = sqrt(eX² + eY² + eZ²), and runs a cheap quadratic ray–sphere test. If the ray misses the sphere, it skips the OBB math completely.
  2. Tight OBB slab test. If the sphere hits, rayOBBHit normalizes axisX/Y/Z, projects rayOrigin - center and dir into 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. RayHitsBoneProxies serves two callers: joint-collection queries (passing a non-null outHitJoints vector) and the GPU laser's definitive-miss cull (GpuLaserMayHitViaBoneProxies, which passes outHitJoints = nullptr). When outHitJoints == nullptr, the function intentionally refuses to count proxy.extraSpheres as hits after an OBB miss, returning true immediately on the first OBB hit and false if 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 GpuLaserMayHitViaBoneProxies and RayHitsBoneProxies — null model data, unready pose cache, rigid mesh (skinIndex < 0), missing CPU prep, empty boneProxies, empty jointMatrices, or degenerate zero-length ray direction — returns true ("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 returns false!

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:

Timeline diagram contrasting same-frame blocking GPU readback against Play2Train's cross-frame parked accumulation with two-buffer ping-pong. Top panel (A) shows same-frame readback stalling the CPU across the entire queued GPU scene render plus compute trace before memcpy can resume. Bottom dark panel (B) shows Frame N submitting BeginAccumulation, UploadAccumulationRays, all target dispatches, EndAccumulationBeginReadback (inserting a GlSync fence with zero glFlush), and ParkAccumulationForDeferredCollect into Slot A; while the GPU finishes Frame N rendering and Compute Trace A in parallel, Frame N+1 calls CollectParkedAccumulation to read Slot A via zero-wait persistent coherent memcpy, retires Slot A into m_spareAccum, and immediately adopts Slot B for Frame N+1's submission. Three bottom cards detail persistent coherent mapping (glBufferStorage with MAP_READ | PERSISTENT | COHERENT and glGetBufferSubData fallback), no-flush fencing (glClientWaitSync(fence, 0, 0) fast-path poll), and zero allocation churn via m_parkedAccum <-> m_spareAccum recycling.
Parking an accumulation session across one frame boundary lets the GPU finish the compute trace alongside normal rendering, turning next frame's readback into a zero-stall memcpy from persistently mapped memory.
  1. 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), initializes m_bestHitsSSBO with each ray's starting bestWorld distance and hit = 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-side glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT). Inside the shader, a hit overwrites bestHits[idx] only if worldDist > 0.0 && worldDist <= wMax && worldDist < bestWorld, stamping hit = 1u and targetId = uTargetId only on strict improvement.
  2. Persistently mapped coherent BestHits + no-flush fencing. When glBufferStorage is available (OpenGL 4.4 / ARB_buffer_storage), EnsureAccumulationStorage allocates m_bestHitsSSBO with GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT | GL_DYNAMIC_STORAGE_BIT and keeps it permanently mapped (m_bestHitsMappedPtr), eliminating per-frame map/unmap driver stalls (falling back cleanly to glGetBufferSubData on drivers without buffer storage). Crucially, EndAccumulationBeginReadback inserts a GlSync fence (CreateFence()) and deliberately does NOT call glFlush() — because flushing once per target hammers the driver and causes frame spikes. Instead, EndAccumulationFinalize first polls glClientWaitSync(fence, 0, 0) without flushing, and only passes GL_SYNC_FLUSH_COMMANDS_BIT if the GPU is genuinely not finished yet.
  3. 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 with maxDistance = 0 sentinels for inactive rays), inserting the fence, and calling ParkAccumulationForDeferredCollect(). That detaches (ssbo, mappedPtr, fence, rayCount) into m_parkedAccum and resets the active raycaster so the frame finishes immediately with zero GPU stall. On the next laser update, CollectParkedAccumulation finds the fence already signaled, memcpys the hits straight out of mappedPtr, and retires the buffer set into m_spareAccum — which the very next EnsureAccumulationStorage adopts 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:

Four-gate fail-closed correctness pipeline enforcing Play2Train's 'never as a silent miss' contract. Top dark banner quotes GpuRaycaster.h. Gate 1 (Eligibility, GpuRayEligibility.h) verifies GPU availability, feature flag, quarantine status, finite geometry, and the static BVH4 stack proof 1 + 3*(maxDepth - 1) <= 256 before dispatch. Gate 2 (Upload, GpuRaycaster.cpp) requires non-zero contentHash, exact version matching between pose nodes and pose triangles, and bound invMeshWorld matrices. Gate 3 (Shader, gpu_ray_accum*.glsl) writes sticky hit = 2u into bestHits[idx] on fixed 256-entry stack overflow and makes all subsequent dispatches early-out when cur.hit == 2u so the failure can never be overwritten. Gate 4 (Caller, IntersectionSystem.h) merges failures by ErrorPriority, attributes missing-mesh coverage only to rays whose bounds intersect the missing mesh, and quarantines the laser session on strict CPU/GPU validation mismatches. The bottom panel displays all five explicit LaserStatus outputs separating valid geometric outcomes (Hit, Miss, InvalidInput) from explicit failures (Unavailable and priority-100 TraversalFailure).
Four sequential gates ensure a pipeline error, stale cache, NaN vertex, or shader stack overflow can never masquerade as a clean geometric miss.

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:

text
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:

glsl
// 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, BuildActiveRayListForTargetImpl checks 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 above 1e-3 logs full ray diagnostics, upgrades that ray to ValidationMismatch (LaserStatus::TraversalFailure), and — when strict abort-on-mismatch is active — calls SetGpuLaserQuarantined(true, ValidationMismatch) so subsequent queries immediately fail closed via EvaluatePipeline until 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, GpuRaycaster explicitly requires OpenGL 4.3 compute shaders and SSBOs (#version 430). On hardware without compute shaders, Initialize() returns false with ErrorCode::NotAvailable (and m_initAttempted ensures the synchronous ~650 ms shader compile is attempted at most once during loading-screen prewarm). Callers in GPU-only mode surface LaserStatus::Unavailable; callers that permit CPU fallback use TraverseRayBvh4 on the exact same RayBvh4 data.
  • 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, and BuildSkinnedRayTris on the CPU (parallelized across FixedThreadPool for meshes with ≥ 4,096 triangles) and uploads the posed buffers for that frame.
  • Single-consumer cross-frame parking. GpuRaycaster supports exactly one parked accumulation session at a time (m_parkedAccum), tailored to the gameplay laser. Calling ParkAccumulationForDeferredCollect() while a previous parked result is uncollected fails closed with InvalidArgs.
  • Hard capacity caps. RayBvh4Child addresses up to 2^27 (134,217,728) triangle indices per BVH or packed multi-mesh atlas; GpuRaycaster caps its GPU BVH cache at 256 entries and 256 MiB of VRAM (CachePayloadFits rejects oversized single payloads before allocation).
  • Render-thread ownership. GetGlobalGpuRaycaster() returns nullptr off 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.h verifies initialization idempotence, zero-upload cache hits, exact byte parity between glGetBufferParameteri64v, GetBvhCacheBytes(), and ResourceResidencyManager, safe PurgeAll() while GPU work is still in flight (confirming retired bindings fail with NoBVH while 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.h verifies 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, and tests/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, SSE MXCSR guards, and P2TR v6 replays.
  • 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/kg fail-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::Engine and building its GPU-only gameplay laser (IntersectionSystem.h, IntersectionDetail_GpuLaser.cpp) on top of GpuRaycaster and bone-proxy culling.
  • PloppyPals (closed-source, in development) — companion creature-care game built on Play2Train::Engine; it does not currently use the gameplay laser.