Architecture snapshot: December 2026. This article documents Play2Train's dual-backend shader packaging and backend-neutral world render-graph layer (cmake/compile_world_program.py, cmake/shader_reflection.py, cmake/embed_spirv.py, src/engine/renderer/RenderShaderInterface.h, src/engine/renderer/FullSceneWorld.h/.cpp, and src/engine/renderer/FullSceneFrame.h/.cpp — roughly 1,292 lines of Python and C++23, alongside their OpenGL and Vulkan consumers in RendererScene.cpp, backends/opengl/GeometryPrograms.cpp, backends/vulkan/WorldViewRenderer.h/.cpp, and backends/vulkan/FullSceneViewRenderer.h/.cpp, plus conformance suites in tests/test_world_shader.py, tests/fullscene_world_conformance.h, and tests/test_fullscene_world_contract.py) inside Gattic's closed-source Play2Train SDK. Both Robot Universe and PloppyPals render on top of Play2Train.
Running a 3D game engine on two different graphics APIs — an established OpenGL 3.3 backend and a newer Vulkan 1.2 backend — usually creates an immediate maintenance crisis.
For non-technical readers, imagine running one busy restaurant kitchen that suddenly has to serve two completely different dining rooms. Dining Room A (OpenGL) accepts handwritten recipe cards with casual labels like "a pinch of sun direction" and figures out where to put every bowl on the fly. Dining Room B (Vulkan) runs like an automated sushi conveyor belt: every ingredient must be packed into a numbered container of an exact millimeter width before the doors even open, and the kitchen is forbidden from improvising mid-service.
Most engines solve that by maintaining two separate copies of everything: two sets of shader files, two lists of rendering passes, and hand-typed C++ data structures trying to mirror how the GPU lays out memory. Inevitably, the two copies drift apart. Someone fixes a lighting bug in OpenGL and forgets Vulkan; someone adds a float to a shader and misses a 12-byte padding rule in C++; or the newer backend quietly skips an unimplemented rendering pass and produces a frame that almost looks right until a shadow or character vanishes in production.
Play2Train rejects all three compromises with a single architectural contract built on three rules:
- Unchanged GL 3.3 shaders compiled offline into linked Vulkan modules. A build-time Python script (
cmake/compile_world_program.py) compiles 47 production OpenGL 3.3/4.3 world, foliage, water, particle, volumetric, post-processing, and GLB shaders into validated Vulkan 1.2 SPIR-V modules — without forking a single.glslfile. The only arithmetic edit anywhere in the pipeline is a 4-line vertex wrapper converting OpenGL's clip-space depth to Vulkan's. - SPIR-V decorations as the single source of truth — never C++ guesses. Instead of hand-writing C++ uniform structs or even trusting
glslang's relaxed text reflection,cmake/shader_reflection.pyparses the validated SPIR-V binary's ownOpDecorateandOpMemberDecorateinstructions to emit exact byte offsets, array strides, normalized bindings, and cross-stage locations directly into C++ headers (RenderShaderInterface). - One pinned render graph with fail-closed capability admission.
src/engine/renderer/FullSceneWorld.hpins the world stage's pass names, execution order, attachment policies, and resource intents once for both backends. Each backend declares what it can execute through a pure-CPUWorldStageCapabilitiesstruct — and as the header states plainly, "a frame that asks for one it does not have is an admission error, never a silently skipped pass or a stub."
Why supporting two graphics APIs usually splits an engine in half
At a high level, OpenGL 3.3 and Vulkan 1.2 draw the exact same triangles on the exact same GPU hardware. They simply disagree on who is responsible for wiring the plumbing and when that wiring happens:
- Loose parameters vs. explicit binary blocks. In an OpenGL 3.3 shader like
Resources/Shaders/Engine/terrain.vert.glsl, an author can writeuniform mat4 u_mvp;anduniform bool u_motionHistoryValid;directly at global scope. The OpenGL driver assigns each uniform a handle at link time and accepts per-name uploads. Vulkan forbids loose global uniforms altogether: every parameter must live inside aUniformBufferblock (or push constants) with explicit byte offsets, an explicitDescriptorSet, and an explicitBindingnumber. - Name-linked varyings vs. location-linked varyings. In OpenGL, if a vertex shader outputs
out vec3 v_worldNormal;and the fragment shader declaresin vec3 v_worldNormal;, the driver matches them by name. If the vertex shader also writesout vec2 v_texCoord;that the fragment shader never reads, OpenGL quietly ignores it. In Vulkan SPIR-V, stages link by integerLocationnumbers, and an unconsumed vertexOutputvariable becomes an interface mismatch. - Clip-space depth range. OpenGL maps projected depth (
clip.z / clip.w) to[-1, +1], while Vulkan maps it to[0, +1]. - Silent partial implementations. When migrating a mature OpenGL renderer to Vulkan, teams naturally port one feature at a time — terrain first, then rigid meshes, then water, then animated characters. Without an explicit admission gate, the easiest shortcut is to leave an
if (vulkan) return;stub where an unported pass belongs, hiding missing work behind a successful return code.
Rather than accepting shader forks, hand-maintained buffer layouts, or stubbed passes, Play2Train puts a thin, deterministic boundary between what a frame means and which graphics API executes it:
| Concern | Common dual-backend shortcut | Play2Train contract |
|---|---|---|
| Shader authoring | Maintain separate .gl.glsl and .vk.glsl files, or transpile at runtime on player machines |
Author one GL 3.3/4.3 shader; cmake/compile_world_program.py compiles and validates Vulkan 1.2 SPIR-V offline at build time |
| Uniform memory layout | Hand-write matching C++ alignas(16) structs and hope std140 padding matches |
Parse authoritative SPIR-V OpDecorate / OpMemberDecorate offsets and strides into generated RenderShaderInterface headers |
| Pass names and order | Each backend builds its own pass list with slightly different names and clear rules | FullSceneFrame.h and FullSceneWorld.h pin all 12 frame stages and 4 world passes once in pure C++ |
| Unported backend features | Log a warning, skip the pass, or insert a no-op stub so the frame still "succeeds" | ValidateWorldStageFrame returns a typed std::expected<void, WorldStageError> admission refusal and emits zero passes |
Compiling unchanged GL 3.3 shaders into linked Vulkan 1.2 modules
Play2Train does not ship glslangValidator or SPIR-V compiler libraries inside the game executable, and it never compiles Vulkan GLSL on a player's CPU at startup. Instead, CMake invokes cmake/compile_world_program.py during the build for 47 production raster programs listed in src/engine/CMakeLists.txt — covering terrain, terrain_depth, default (rigid meshes), water, sky, surface, ten vegetation/scatter shaders (grass_blade through grass_lilypad), four wildlife shaders, twelve post-processing/AO/TAA/motion-blur/HZB shaders, four particle variants (particle, particle_mesh, particle_oit, particle_oit_mesh), oit_composite_world, UI/overlay batches, five volumetric fire/rain/snow passes, and the production glb_color_world (instanced_skinned) shader.
For non-technical readers, think of compile_world_program.py as an automated factory packaging line with six quality inspectors. A regular OpenGL shader walks in one end untouched; a sealed, SHA-256 hashed, Vulkan-ready C++ header rolls out the other end — and if any wire is loose or mislabeled, the line stops the entire build immediately.
Step 1–2: Preprocessing, variant macros, and the single arithmetic edit
preprocess() verifies that every input shader starts with #version 330 or #version 430 (refusing anything else), injects optional fragment-stage variant macros right after the version line (for example --define OIT_PASS on particle_oit and particle_oit_mesh, mirroring the exact preamble the OpenGL particle renderer prepends at runtime), and enables GL_GOOGLE_include_directive so glslangValidator -E expands every #include.
Every #line directive emitted by the preprocessor is harvested into a standard Makefile/Ninja .d dependency file. For terrain_world, CMake automatically tracks all 9 source and include files (terrain.vert.glsl, terrain.frag.glsl, aerial_haze.glsl, cloud_shadow.glsl, cloud_shadow_field.glsl, local_lights.glsl, terrain_projection.glsl, p2t_lighting_ubo.glsl, and p2t_screen_space_ao.glsl) — so editing any shared lighting include triggers a clean rebuild instead of leaving stale SPIR-V behind.
Before modifying a single character, the script records SHA-256 kernelHashes of the expanded vertex and fragment kernels. Then it applies the only arithmetic change in the entire compiler — four lines wrapped around the vertex shader:
# cmake/compile_world_program.py
vertex = sources[0].split('\n', 1)
sources[0] = (
vertex[0]
+ '\n#define main p2tGraphVertexMain\n'
+ '#define gl_VertexID gl_VertexIndex\n'
+ '#define gl_InstanceID gl_InstanceIndex\n'
+ vertex[1]
+ '\n#undef main\n'
+ 'void main() { p2tGraphVertexMain(); '
+ 'gl_Position.z = (gl_Position.z + gl_Position.w) * 0.5; }\n'
)Why does that one equation work? In OpenGL, clip-space z runs from -w (near plane) to +w (far plane). Adding w shifts the range to [0, 2w], and multiplying by 0.5 maps it cleanly to Vulkan's [0, w] clip volume — matching Play2Train's existing draw-device convention without touching a single projection matrix or shading formula inside the shader body. Notice also that the fragment shader is never wrapped at all: in the emitted terrain_world.json build receipt, sourceHashes[1] and kernelHashes[1] are SHA-256 identical (d1e03180...), proving zero bytes of fragment code were altered, and tests/test_world_shader.py asserts that exact hash equality on real production shaders.
Step 3–4: Privatizing unused exports and normalizing SPIR-V interfaces
Next, glslangValidator links the pair for Vulkan 1.2 with --auto-map-bindings, --auto-map-locations, and --set-default-uniform-block P2T_GraphParameters 0 0. That last flag sweeps every loose GL 3.3 uniform across both stages into one std140 uniform buffer block named P2T_GraphParameters. The resulting .spv binaries pass through spirv-val, then spirv-opt --remove-unused-interface-variables --eliminate-dead-variables, then spirv-val again, and are disassembled with spirv-dis --raw-id.
Now comes the part that trips up naive GL-to-Vulkan pipelines: glslang's auto-mapper is not a stable cross-stage ABI. Look at what actually happens on Play2Train's real production terrain.vert.glsl and terrain.frag.glsl:
terrain.vert.glsloutputs five varyings:v_color,v_texCoord,v_worldNormal,v_worldPos, andv_previousClip.terrain.frag.glslsamples terrain textures using world-space triplanar projection (v_worldPos) and never readsv_texCoord.- Because
glslangassigns locations per stage in declaration order, the vertex shader putsv_texCoordat Location1, shiftingv_worldNormalto2,v_worldPosto3, andv_previousClipto4— while the fragment shader expectsv_worldNormalat1,v_worldPosat2, andv_previousClipat3! Every varying from Location1upward is wired to the wrong variable.
compile_world_program.py fixes this cleanly in three surgical passes over the SPIR-V assembly — leaving every arithmetic instruction, storage offset, and consumed interpolation qualifier (Flat, NoPerspective, Centroid) untouched:
- Privatize unconsumed vertex outputs (
privatize_unconsumed_outputs). Instead of running an aggressive optimizer that might rewrite vertex math, or inventing fake fragment reads, the script finds every vertexOutputmissing from the fragment'sInputset and moves itsOpVariable(and every pointer alias throughOpAccessChain,OpInBoundsAccessChain,OpPtrAccessChain,OpInBoundsPtrAccessChain, andOpCopyObject) fromOutputstorage toPrivatestorage, stripping itsLocation,Component, and interpolation decorations. Crucially, it clones only the specificOpTypePointertypes needed by those variables — never cloninggl_PerVertex, which would illegally placeBuiltIn PositionintoPrivatestorage. Across Play2Train's 47 compiled world programs, four real shaders trigger this cleanly:terrain_world(v_texCoord),grass_lilypad_world(v_seed),hzb_downsample_world(vUV), andmblur_tile_max_world(vUV). - Strip leftover unused descriptors (
strip_unused_resourcesinshader_reflection.py). Shared GLSL headers likeparticles/particle_common.glsldeclare every storage buffer in the particle pool even when an individual shader phase only touches a subset.glslangomits unreferenced blocks from its reflection report while leaving theirOpVariabledeclarations inside the SPIR-V assembly with colliding binding numbers.strip_unused_resourcesremoves each unreferenced declaration, itsOpName/OpDecoratelines, and itsOpEntryPointoperand — verifying with a regex check that no instruction in the module still references the stripped ID (inparticle_emit.json, for example,IndirectDrawis cleanly dropped whileParticleDatamoves from0to5). - Normalize bindings and varying locations deterministically.
resource_bindings()sorts every live descriptor alphabetically by its original GLSL name withP2T_GraphParametersalways pinned at binding0.varying_locations()assigns dense cross-stageLocationindices alphabetically across both modules, reserving 3 locations forMat3and 4 locations forMat4. Both stages are then reassembled withspirv-as --preserve-numeric-idsand checked one final time byspirv-val --target-env vulkan1.2.
Finally, cmake/embed_spirv.py verifies the SPIR-V magic word (0x07230203) and 4-byte word alignment before emitting <symbol>_vertex.h and <symbol>_fragment.h as inline constexpr std::uint32_t[] arrays, while emit_header() generates <symbol>.h containing the reflected RenderShaderInterface.
Reading the binary truth: why SPIR-V decorations beat C++ guesses
Once the SPIR-V binaries are validated, how does C++ know which byte offset inside P2T_GraphParameters holds u_sunDirection or uExtraLightIntensity[2]?
For non-technical readers, imagine packing fragile equipment into cargo crates for an airline. On paper, four 4-byte floating-point numbers look like they should fit into a 16-byte box (4 × 4 = 16). Under Vulkan's std140 packing rules, however, every single element of a uniform array must start on a 16-byte boundary — so four floats actually occupy 64 bytes (4 × 16), with 12 bytes of empty foam padding after each number. If the C++ packer guesses 4-byte spacing while the GPU reads at 16-byte spacing, the first light works and lights two through four read garbage padding!
Even worse, Play2Train discovered that you cannot even trust glslang's own text reflection output for default uniform blocks. As the header comment in cmake/shader_reflection.py warns:
"SPIR-V decorations are authoritative: glslang's relaxed-default-block reflection can report a float array's dense stride even when the emitted std140 stride is 16."
In fact, tests/test_world_shader.py explicitly constructs a reflection fixture where glslang prints u_values: offset 128, type 1406, size 4, ..., arrayStride 4 while the SPIR-V disassembly carries OpDecorate %20 ArrayStride 16, asserting that compile_world_program.py ignores the relaxed text stride and emits ('u_values', 'FloatArray', 128, 4, 16).
What SpirvInterface actually verifies (cmake/shader_reflection.py)
SpirvInterface parses OpName, OpMemberName, OpDecorate, OpMemberDecorate, OpType*, OpConstant, and OpVariable directly from the final spirv-dis --raw-id output after spirv-val succeeds. Before a single line of C++ is written, SpirvInterface and reflect() reject the build if any structural invariant fails:
| Invariant checked | Rule enforced in shader_reflection.py / compile_world_program.py |
Failure prevented |
|---|---|---|
| Matrix layout | Every OpTypeMatrix (Mat3, Mat4) must carry ColMajor and MatrixStride 16; RowMajor or MatrixStride 12 throws ValueError |
Silent matrix transpose or column-stride corruption between CPU and GPU |
| Array & runtime-array strides | OpTypeArray reads OpDecorate ArrayStride directly and checks stride >= element_storage_size; OpTypeRuntimeArray is permitted only as the final member of a StorageBuffer |
glslang relaxed arrayStride 4 bug; truncated or misaligned SSBO tails |
| Non-overlapping block members | block() checks earlier_offset < offset + size && offset < earlier_end for every pair of struct fields and validates total byteSize against glslang block reflection |
Overlapping uniform offsets or silent tail truncation |
| Stage & type semantics | Bool uniform members must be backed by 32-bit UInt in SPIR-V and are refused as vertex/color locations; UVec4 (e.g., aJoints at Location 6 for skeletal skinning) is allowed as a vertex input, never as a default uniform or color output |
Misinterpreted vertex attribute types or invalid framebuffer formats |
| Exact sampled image signatures | OpTypeImage must have multisampled == 0, sampled == 1, image_format == Unknown, and match one of 7 exact (scalar, dim, depth, arrayed) signatures (Texture2D, Texture2DArray, TextureCube, Texture3D, Depth2DArray, FloatTexelBuffer, IntTexelBuffer) |
Binding a 2D image to a 3D volume or depth-array sampler |
| Cross-stage agreement | Shared resources (like u_texture in water_world, `stages = VertexShader |
FragmentShader = 17) must match type, binding, and byteSizeacross both stages;P2T_GraphParametersmust match identically across VS and FS; every fragmentInputmust match the vertexOutputin both type andLocation` |
Here is an excerpt from the real C++ header that compile_world_program.py emits for Play2Train's production terrain shader (build/src/engine/generated/vulkan/terrain_world.h):
// Generated from unchanged Resources/Shaders/Engine/terrain.{vert,frag}.glsl
namespace Engine::Vulkan::Shaders {
inline const RenderShaderInterface terrain_world_interface{
{{
{"u_mvp", RenderShaderValueType::Mat4, 0, 1, 0},
{"u_previousMvp", RenderShaderValueType::Mat4, 64, 1, 0},
{"u_motionHistoryValid", RenderShaderValueType::Bool, 128, 1, 0},
{"u_model", RenderShaderValueType::Mat4, 144, 1, 0},
{"u_normalMatrix", RenderShaderValueType::Mat3, 208, 1, 0},
// ... 29 more reflected fields, including std140 float arrays:
{"uExtraLightIntensity", RenderShaderValueType::FloatArray, 400, 4, 16},
{"uExtraLightRange", RenderShaderValueType::FloatArray, 464, 4, 16},
{"u_shadowVP", RenderShaderValueType::Mat4Array, 752, 4, 64},
// ... ending at offset 1064 (u_heightEnabled, Int):
}, 1068},
{
{"P2T_GraphParameters", RenderShaderResourceType::UniformBuffer, 0,
RenderPipelineStage::VertexShader | RenderPipelineStage::FragmentShader, 1068},
{"P2T_Lighting", RenderShaderResourceType::UniformBuffer, 1,
RenderPipelineStage::FragmentShader, 576},
{"uClusterLightData", RenderShaderResourceType::FloatTexelBuffer, 2,
RenderPipelineStage::FragmentShader, 0},
// ... bindings 3..14 sorted alphabetically (uCluster*, uScreenSpaceAO*, u_aoTex..u_terrainTex3)
},
{
{"a_position", RenderShaderValueType::Vec3, 0},
{"a_color", RenderShaderValueType::Vec3, 1},
{"a_texCoord", RenderShaderValueType::Vec2, 2},
{"a_normal", RenderShaderValueType::Vec3, 3},
},
{
{"FragColor", RenderShaderValueType::Vec4, 0},
{"FragVelocity", RenderShaderValueType::Vec2, 1},
}
};
}And notice the symmetry on the OpenGL side: src/engine/renderer/backends/opengl/GeometryPrograms.cpp reflects a live linked OpenGL 3.3 program via glGetActiveUniform, glGetActiveUniformBlockName, and glGetActiveAttrib into the exact same RenderShaderInterface type (RenderShaderInterface.h), inserting a synthetic P2T_GraphParameters uniform buffer at binding 0 and packing uniforms by name. Both backends validate their interfaces through the same ValidRenderShaderInterface() predicate, and both pack draw uniforms through PackRenderUniforms() — zero GL enums and zero Vulkan handles leak into shared rendering code.
Pinning the render graph once: FullSceneFrame and FullSceneWorld
Matching shaders across backends is only half the battle. If OpenGL and Vulkan disagree on which passes run, what order they run in, or how attachments are cleared and loaded, the same shader still produces different pixels.
For non-technical readers, think of a single 3D frame like a movie production schedule with strict cause-and-effect rules:
- You cannot draw semi-transparent water or smoke before solid hills, because water needs to know how deep the hill behind it is.
- You cannot build a visibility occlusion map (
HzbBuild) before every solid depth writer has finished, or hidden objects will pop in and out. - You cannot draw crisp 2D menus (
Overlay) before HDR camera tonemapping (Resolve), or the UI text gets bloomed and color-graded along with the sunlight.
Play2Train encodes that entire production order once in two pure-CPU, backend-neutral headers: FullSceneFrame.h (the 12-stage frame skeleton) and FullSceneWorld.h (the detailed world-geometry stage inside it).
The 12-stage frame contract (FullSceneFrame.h/.cpp)
FullSceneFrame.h defines FullSceneStage in a single immutable sequence:
SkyClear → EarlyZ → OpaqueWorld → Scatter → Water → Volumetric → Precipitation → Particles → HzbBuild → Post → Resolve → Overlay.
Each stage carries an explicit prerequisite list (FullSceneStageRequires). When a backend composes a frame, ValidateFullSceneStages(executed, published) checks that:
- Both
executed(stages the backend runs on the shared graph) andpublished(stages whose outputs the caller already produced) follow strict production order with zero duplicates. - No stage appears in both lists.
- Every prerequisite of every executed or published stage is satisfied by an earlier executed stage or a published stage.
A multi-view or split-screen frame also passes all output rectangles through ValidateFullSceneViewLayouts (using 64-bit coordinate sums to prevent integer wraparound) so overlapping or out-of-bounds viewports are refused before any pass is composed.
The 4 pinned world passes (FullSceneWorld.h/.cpp)
Zooming into EarlyZ and OpaqueWorld, FullSceneWorld.h pins the exact pass enum, order, and visible diagnostic names used by both backends, scene-graph JSON dumps, and native conformance tests:
WorldStagePass |
Pinned production name | When emitted | Attachments & load/store policy |
|---|---|---|---|
EarlyZDepthClear |
"Culling depth clear" |
frame.earlyDepth == true |
SceneDepth (Write): Clear (0.0f reversed-Z, 1.0f forward-Z) / Store |
EarlyZTerrainDepth |
"Culling terrain depth" |
frame.earlyDepth == true and !draws.terrainDepth.empty() |
SceneDepth (ReadWrite): Load / Store, plus deduplicated terrainDepthReads |
EarlyZDepthRestore |
"Culling depth restore" |
frame.earlyDepth == true |
SceneDepth (Write): Clear (0.0f or 1.0f) / Store — always resets depth before color |
OpaqueWorld |
"Opaque meshes" |
Always | SceneColor (ReadWrite), optional SceneVelocity (ReadWrite if frame.velocity), SceneDepth (ReadWrite), all Load / Store |
Look closely at two subtle invariants encoded in BuildWorldStagePasses (src/engine/renderer/FullSceneWorld.cpp) that eliminate whole classes of dual-backend bugs:
- Depth restore always clears, even with zero terrain occluders. Early-Z model depth precedes camera LOD selection and does not need to match color geometry bit-for-bit. Restoring
SceneDepthwith a clean clear guarantees theOpaqueWorldcolor pass owns scene depth cleanly rather than leaving stale fragments that failGL_LESSorVK_COMPARE_OP_GREATERat equal depth. - Explicit unrouted color outputs instead of shader forks or silent drops. Remember that Play2Train's unchanged
terrain.frag.glslanddefault.frag.glslalways write two color outputs:FragColor(Location0) andFragVelocity(Location1). What happens when a view renders a single-color capture (such as a portal reflection or velocity-disabled frame) that binds onlySceneColor? Instead of compiling a second shader withoutFragVelocity, allocating a wasteful scratch velocity texture, or silently dropping output1,FullSceneWorld.cpprecords:
// src/engine/renderer/FullSceneWorld.cpp
const auto colors = static_cast<std::uint32_t>(1 + (frame.velocity ? 1 : 0));
// A pass with no draws produces no outputs, so it cannot route any: declaring
// the kernel's surplus outputs unrouted would describe a draw that never runs.
if (!draws.opaque.empty() && draws.opaqueColorOutputs > colors)
opaque.geometry->unroutedColorOutputs = draws.opaqueColorOutputs - colors;OpenGL lowers that contract by routing draw buffers per draw and restoring full routing before clears; Vulkan lowers it into an immutable pipeline with zero write mask / VK_ATTACHMENT_UNUSED subpass reference for the ignored trailing slot (m_terrainColorSingle vs m_terrainColor, compiled across the four forward/reversed Z × CCW/CW winding raster variants in WorldViewRenderer.cpp). The exact same GL 3.3 shader binary runs in both modes, and any mismatch between physical attachments and declared unrouted outputs is rejected before a single command buffer records.
"An admission error, never a silently skipped pass or a stub"
Now we reach the heart of Play2Train's dual-backend reliability model.
For non-technical readers, imagine booking a train ticket with a bicycle reservation. A silent skip lets you board the train, takes your fare, and quietly leaves your bicycle on the platform without telling anyone — you only discover the problem hours later at your destination. An admission error stops you at the ticket gate before you ever step onto the train and prints the exact reason: "This carriage has no bicycle rack."
In src/engine/renderer/FullSceneWorld.h, Play2Train puts that exact ticket gate in front of every single world frame. First, each backend declares what it can execute through a pure-CPU constexpr capability struct — never probing a GPU driver or allocating a device object:
// src/engine/renderer/FullSceneWorld.h
struct WorldStageCapabilities {
// Executes the neutral typed passes (early-Z triple and opaque world).
bool typedWorldDraws = false;
// Executes the GLB instanced batch inside the opaque world stage.
bool legacyGlbBatch = false;
// Publishes the CPU culling/HZB state the GLB batch and the world draws read.
bool cullingProducers = false;
};
constexpr WorldStageCapabilities QueryWorldStageCapabilities(
Platform::GraphicsBackend backend) noexcept {
switch (backend) {
case Platform::GraphicsBackend::OpenGL:
return {true, true, true};
case Platform::GraphicsBackend::Vulkan:
// The Vulkan world view renderer executes the neutral typed passes
// over caller-published terrain geometry. The GLB instanced batch and
// the CPU culling/HZB producers stay unclaimed until their own
// production view exists, so a frame that requests the batch is
// refused instead of run against unpublished culling state.
return {true, false, false};
}
return {};
}Both FullSceneViewRenderer.cpp and tests/fullscene_world_contract.cpp pin those capability booleans with compile-time static_assert statements so a backend can never accidentally claim a producer it does not own.
Notice the subtle coupling enforced by ValidateWorldStageFrame: OpenGL's legacy GLB instanced batch inside the world stage depends on the CPU culling and HZB setup passes ("Culling setup", "Culling models and HZB", "Culling" in RendererScene.cpp). Therefore, requesting frame.legacyGlbBatch == true requires both capabilities.legacyGlbBatch and capabilities.cullingProducers. Even a hypothetical backend claiming {true, true, false} (GLB batch without culling producers) is rejected as WorldStageError::MissingCapability — because running the legacy batch without its culling producers would draw against unpublished visibility state. (On Vulkan, GLB instanced models run through the separate, explicitly admitted GlbBatchViewRenderer inside FullSceneViewRenderer, not through OpenGL's legacy culling callbacks.)
Every rejection code in WorldStageError
ValidateWorldStageFrame returns std::expected<void, WorldStageError>, checking nine exact conditions in deterministic order. Every error maps to a stable diagnostic string in WorldStageErrorName and a distinct failure in both backends (std::logic_error in OpenGL's RendererScene.cpp; an explicit switch over all nine cases returning a distinct Failure operation name in Vulkan's WorldViewRenderer.cpp):
WorldStageError |
Diagnostic string | Trigger condition in FullSceneWorld.cpp |
Silent bug it prevents |
|---|---|---|---|
InvalidFrameView |
"invalid_frame_view" |
Zero render/output extent, non-finite matrix/camera/sea-level float, or zero-length cameraRight/cameraUp |
NaN transforms or collapsed billboards/UI quads |
UnsupportedWorldStage |
"unsupported_world_stage" |
!capabilities.typedWorldDraws |
Executing or silently dropping a world stage on an unimplemented backend |
MissingCapability |
"missing_capability" |
`frame.legacyGlbBatch && (!capabilities.legacyGlbBatch | |
ExtentMismatch |
"extent_mismatch" |
targets.width != frame.view.width or targets.height != frame.view.height |
Rendering at one resolution into a target allocated for another |
MissingTarget |
"missing_target" |
Invalid targets.color or targets.depth handle |
Drawing into an unbound or retired framebuffer attachment |
VelocityMismatch |
"velocity_mismatch" |
frame.velocity != ValidTarget(targets.velocity) |
Claiming velocity writes with no target, or leaking an unused velocity attachment |
UnexpectedPrepassDraws |
"unexpected_prepass_draws" |
!frame.earlyDepth && !draws.terrainDepth.empty() |
Silently dropping terrain prepass draws when early-Z is disabled |
InvalidDrawPacket |
"invalid_draw_packet" |
Any draw in terrainDepth or opaque fails ValidRenderGeometryDraw (e.g., zero vertex count, invalid byte range) |
Issuing malformed vertex/index draws to the GPU driver |
InvalidResourceUse |
"invalid_resource_use" |
Any read in terrainDepthReads or opaqueReads fails ValidRenderResourceUseIntent |
Missing barrier/layout metadata or dangling resource declarations |
And FullSceneWorld.cpp enforces one more subtle rule when draws.opaque is empty: it skips appending opaqueReads and skips setting unroutedColorOutputs, because a pass with zero draws reads nothing and writes nothing — declaring unbound reads or unrouted outputs for a draw that never runs would violate the graph's own resource-intent admission rules. Every one of these admission rejections, empty-terrain cases, reversed-Z vs forward-Z depth clears, and deduplicated reads is exercised without a display by tests/fullscene_world_conformance.h (Play2TrainFullSceneWorldTests) and verified statically by tests/test_fullscene_world_contract.py.
Honest boundaries and where the system stops
Play2Train's dual-backend shader and render-graph contract is deliberately narrow and explicit about what it does not try to do:
- Build-time packaging only — no runtime compiler or math optimizer.
cmake/compile_world_program.pytranslates shaders offline during the CMake build and embeds validated SPIR-V bytes directly into C++ headers. It does not shipglslangat runtime, and it deliberately avoids running arithmetic optimization passes inspirv-opt(invoking only--remove-unused-interface-variablesand--eliminate-dead-variables) so Vulkan executes the same floating-point expressions as OpenGL. - Strict GLSL interface subset. World raster programs (and sibling compute programs compiled via
cmake/compile_compute_program.pysuch asluminance_histogram,hzb_batch, and the four particle-pool compute kernels) must use descriptor set0, column-major matrices withMatrixStride 16, unpackedLocationslots (Component == 0,Index == 0), explicitStorageBufferblocks (never implicitBuffer variablereflection), and the seven supported sampled image signatures. Shaders outside that subset fail the build loudly rather than falling back to heuristics. - Pure-CPU capability admission vs. GPU hardware limits.
QueryWorldStageCapabilitiesisconstexprand never queries a Vulkan physical device. Hardware-dependent requirements — such as optionalindependentBlendwhen a batch uses unequal per-attachment color write masks, or texture dimension/format limits — are validated separately during native Vulkan pipeline creation without tightening base-device selection. - Incremental FullScene parity. While
FullSceneViewRendereron Vulkan now owns all 12FullSceneStageview renderers (includingWorldViewRendererfor terrain/rigid draws andGlbBatchViewRendererfor Vulkan GLB instanced batches),FullSceneWorldintentionally keepslegacyGlbBatchandcullingProducersunclaimed on Vulkan until OpenGL's legacy CPU culling/HZB callbacks are completely retired, and full production FullScene backend switching and remaining legacy GL callbacks remain ongoing migration phases documented insrc/engine/renderer/README.md.
Sources and further reading
- Khronos SPIR-V Specification (Unified) — authoritative reference for
OpDecorate,OpMemberDecorate,ArrayStride,MatrixStride,ColMajor,Location,Binding, and storage classes (Output,Private,Uniform,UniformConstant,StorageBuffer). - Khronos Vulkan 1.2 Specification — Vulkan shader interface matching,
std140uniform block layout, descriptor sets, andVK_ATTACHMENT_UNUSEDsubpass references. - The OpenGL Shading Language 3.30 Specification (PDF) — the GL 3.3 shader dialect preserved unchanged across Play2Train's world kernels.
- Khronos OpenGL Wiki: Interface Block (GLSL) &
std140Layout — reference for the 16-byte array-element alignment rules that makeArrayStride 16mandatory for uniform float arrays. - Play2Train internal source files (closed-source SDK, architecture snapshot December 2026):
cmake/compile_world_program.py,cmake/shader_reflection.py,cmake/embed_spirv.py,src/engine/CMakeLists.txt,src/engine/renderer/RenderShaderInterface.h,src/engine/renderer/FullSceneFrame.h/.cpp,src/engine/renderer/FullSceneWorld.h/.cpp,src/engine/renderer/RendererScene.cpp,src/engine/renderer/backends/opengl/GeometryPrograms.cpp,src/engine/renderer/backends/vulkan/WorldViewRenderer.h/.cpp,src/engine/renderer/backends/vulkan/FullSceneViewRenderer.h/.cpp,tests/test_world_shader.py,tests/fullscene_world_conformance.h, andtests/test_fullscene_world_contract.py. - Related Play2Train architecture articles on Gattic: GPU Ray Tracing Against Skinned Characters Without RTX in Play2Train, Seamless Portals and a GL-Free Budgeted View Scheduler in Play2Train, and Deterministic Replays and the Execution Contract in Play2Train.