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:

  1. 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 .glsl file. The only arithmetic edit anywhere in the pipeline is a 4-line vertex wrapper converting OpenGL's clip-space depth to Vulkan's.
  2. 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.py parses the validated SPIR-V binary's own OpDecorate and OpMemberDecorate instructions to emit exact byte offsets, array strides, normalized bindings, and cross-stage locations directly into C++ headers (RenderShaderInterface).
  3. One pinned render graph with fail-closed capability admission. src/engine/renderer/FullSceneWorld.h pins 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-CPU WorldStageCapabilities struct — 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 write uniform mat4 u_mvp; and uniform 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 a UniformBuffer block (or push constants) with explicit byte offsets, an explicit DescriptorSet, and an explicit Binding number.
  • Name-linked varyings vs. location-linked varyings. In OpenGL, if a vertex shader outputs out vec3 v_worldNormal; and the fragment shader declares in vec3 v_worldNormal;, the driver matches them by name. If the vertex shader also writes out vec2 v_texCoord; that the fragment shader never reads, OpenGL quietly ignores it. In Vulkan SPIR-V, stages link by integer Location numbers, and an unconsumed vertex Output variable 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.
Architecture diagram contrasting Play2Train's single shared source of truth against its two native backends. Top-left shows the 47 unchanged GL 3.3/4.3 world shader kernels under Resources/Shaders/Engine and GLB with no Vulkan fork. Top-right shows the pure-CPU frame contracts in FullSceneFrame.h and FullSceneWorld.h/.cpp pinning 12 frame stages, 4 world pass names, and 9 admission checks. Both converge on the backend-neutral boundary in the middle: RenderShaderInterface (parameters, bindings, vertex/color IO) and ValidateWorldStageFrame followed by BuildWorldStagePasses. Below, OpenGL 3.3 (caps {true, true, true}) reflects linked programs live in GeometryPrograms.cpp and runs all 4 pinned world passes interleaved with GLB and HZB culling in RendererScene.cpp, while Vulkan 1.2 (caps {true, false, false}) consumes offline SPIR-V and static ABI headers from compile_world_program.py and executes the same neutral typed passes in WorldViewRenderer.cpp while explicitly refusing legacyGlbBatch.
Both backends share one set of GL 3.3 shaders and one neutral world-stage contract, meeting at RenderShaderInterface and ValidateWorldStageFrame.

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.

Six-stage diagram of cmake/compile_world_program.py. Step 1 (Preprocess and Hash) checks #version 330/430, injects optional fragment-only --define variant macros such as OIT_PASS, expands #include files via glslangValidator -E, and records SHA-256 kernelHashes and CMake .d dependencies. Step 2 (Clip-Z Vertex Wrap) applies the pipeline's only arithmetic adaptation: wrapping main() as p2tGraphVertexMain() and appending gl_Position.z = (gl_Position.z + gl_Position.w) * 0.5 while leaving the fragment source byte-identical. Step 3 (Link and Prune Dead IO) runs glslangValidator -V -R --target-env vulkan1.2 with --set-default-uniform-block P2T_GraphParameters 0 0, validates with spirv-val, prunes dead interface variables with spirv-opt, and disassembles via spirv-dis --raw-id. Step 4 (Deterministic SPIR-V Assembly Normalization) performs three surgical rewrites without touching math or storage offsets: A) privatizes unconsumed vertex exports (such as terrain's v_texCoord) from Output to Private storage; B) strips unreferenced descriptor declarations and sorts bindings alphabetically with P2T_GraphParameters pinned at 0; C) aligns consumed varying locations alphabetically across stages while reserving 3 slots for Mat3 and 4 for Mat4. Step 5 reassembles with spirv-as --preserve-numeric-ids, re-validates with spirv-val, and cross-checks every offset, stride, and type via SpirvInterface. Step 6 emits the C++ RenderShaderInterface header, embedded uint32_t SPIR-V vertex/fragment headers via embed_spirv.py (checking magic 0x07230203), JSON audit metadata, and the CMake .d depfile.
Every GL 3.3 world shader passes through the same six build-time stages: preprocess, clip-Z wrap, link/prune, deterministic SPIR-V normalization, validation, and C++ header emission.

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:

python
# 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.glsl outputs five varyings: v_color, v_texCoord, v_worldNormal, v_worldPos, and v_previousClip.
  • terrain.frag.glsl samples terrain textures using world-space triplanar projection (v_worldPos) and never reads v_texCoord.
  • Because glslang assigns locations per stage in declaration order, the vertex shader puts v_texCoord at Location 1, shifting v_worldNormal to 2, v_worldPos to 3, and v_previousClip to 4 — while the fragment shader expects v_worldNormal at 1, v_worldPos at 2, and v_previousClip at 3! Every varying from Location 1 upward is wired to the wrong variable.
Before-and-after SPIR-V normalization diagram using real build outputs from terrain_world.json and particle_emit.json. Top-left shows glslang's unnormalized auto-mapped locations on terrain.vert.glsl vs terrain.frag.glsl: vertex exports v_texCoord at Location 1 (unconsumed by fragment), shifting v_worldNormal, v_worldPos, and v_previousClip to Locations 2, 3, and 4 while fragment expects them at Locations 1, 2, and 3. Top-right shows the rewritten SPIR-V after privatize_unconsumed_outputs and normalize_locations: v_texCoord becomes an invocation-local OpVariable Private with its math preserved and Location stripped, and the four live varyings align identically across both stages in alphabetical order (v_color=0, v_previousClip=1, v_worldNormal=2, v_worldPos=3). Bottom-left lists real descriptor binding rewrites from terrain_world.json (P2T_GraphParameters pinned at 0, uClusterLightIndices 4->3, u_aoTex 13->7, u_cloudShadowMap 5->8, u_shadowMap 12->10, u_terrainTex0..3 8..11->11..14). Bottom-right illustrates strip_unused_resources on particle_emit.json, where shared particle_common.glsl declares all pool SSBOs so IndirectDraw is stripped from the disassembly and ParticleData moves from 0 to 5 to avoid colliding with P2T_GraphParameters.
Real SPIR-V rewrites recorded in terrain_world.json and particle_emit.json: unconsumed exports become Private storage, live varyings align by name, and descriptor bindings sort deterministically.

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:

  1. 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 vertex Output missing from the fragment's Input set and moves its OpVariable (and every pointer alias through OpAccessChain, OpInBoundsAccessChain, OpPtrAccessChain, OpInBoundsPtrAccessChain, and OpCopyObject) from Output storage to Private storage, stripping its Location, Component, and interpolation decorations. Crucially, it clones only the specific OpTypePointer types needed by those variables — never cloning gl_PerVertex, which would illegally place BuiltIn Position into Private storage. 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), and mblur_tile_max_world (vUV).
  2. Strip leftover unused descriptors (strip_unused_resources in shader_reflection.py). Shared GLSL headers like particles/particle_common.glsl declare every storage buffer in the particle pool even when an individual shader phase only touches a subset. glslang omits unreferenced blocks from its reflection report while leaving their OpVariable declarations inside the SPIR-V assembly with colliding binding numbers. strip_unused_resources removes each unreferenced declaration, its OpName/OpDecorate lines, and its OpEntryPoint operand — verifying with a regex check that no instruction in the module still references the stripped ID (in particle_emit.json, for example, IndirectDraw is cleanly dropped while ParticleData moves from 0 to 5).
  3. Normalize bindings and varying locations deterministically. resource_bindings() sorts every live descriptor alphabetically by its original GLSL name with P2T_GraphParameters always pinned at binding 0. varying_locations() assigns dense cross-stage Location indices alphabetically across both modules, reserving 3 locations for Mat3 and 4 locations for Mat4. Both stages are then reassembled with spirv-as --preserve-numeric-ids and checked one final time by spirv-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).

Detailed memory and interface diagram for terrain_world_interface. Top dark panel contrasts naive C++ guesses or glslang's relaxed reflection (arrayStride 4 -> offsets 400, 404, 408, 412, corrupting lights) against the authoritative SPIR-V binary decoration (OpDecorate %20 ArrayStride 16 -> offsets 400, 416, 432, 448, totaling 64 bytes for uniform float uExtraLightIntensity[4]). Middle panel maps the real 1,068-byte P2T_GraphParameters block across 34 reflected fields (u_mvp at 0, u_previousMvp at 64, Bool u_motionHistoryValid backed by 32-bit UInt at 128, Mat3 u_normalMatrix at 208 with ColMajor and MatrixStride 16, uExtraLight arrays at 272..527, Mat4Array u_shadowVP[4] at 752 with stride 64, through AO/Height uniforms ending at 1068) and lists the structural invariants enforced by SpirvInterface.block(). Bottom three panels display terrain_world's 15 normalized Descriptor Set 0 bindings (0..14), 4 vertex inputs (Locations 0..3), and 2 color outputs (FragColor at Location 0, FragVelocity at Location 1 with explicit unroutedColorOutputs = 1 when velocity is unpublished).
Play2Train reads every byte offset, array stride, matrix orientation, and binding straight from validated SPIR-V decorations, producing terrain_world_interface without a single hand-written C++ struct.

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

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

Two-tier diagram of Play2Train's backend-neutral render graph. Top panel shows the 12 pinned production stages in FullSceneFrame.h / FullSceneFrame.cpp in strict order: 0 SkyClear (req: none) -> 1 EarlyZ (req: SkyClear) -> 2 OpaqueWorld (req: SkyClear, EarlyZ) -> 3 Scatter (req: SkyClear, EarlyZ, OpaqueWorld) -> 4 Water (req: SkyClear, EarlyZ, OpaqueWorld) -> 5 Volumetric (req: Water) -> 6 Precipitation (req: Water) -> 7 Particles (req: EarlyZ, OpaqueWorld) -> 8 HzbBuild (req: EarlyZ, OpaqueWorld) -> 9 Post (req: EarlyZ, OpaqueWorld) -> 10 Resolve (req: Post) -> 11 Overlay (req: Resolve). Bottom dark panel zooms into EarlyZ and OpaqueWorld owned by FullSceneWorld.h / FullSceneWorld.cpp, showing the four pinned pass names and attachment policies: Pass 0 "Culling depth clear" (Clear/Store SceneDepth to 0.0 revZ or 1.0 fwdZ), Pass 1 "Culling terrain depth" (optional when terrainDepth draws are non-empty, Load/Store SceneDepth), Pass 2 "Culling depth restore" (Clear/Store SceneDepth), and Pass 3 "Opaque meshes" (Load/Store SceneColor, optional SceneVelocity, SceneDepth, setting unroutedColorOutputs when velocity is unpublished). Below, two side-by-side cards compare OpenGL's RendererScene.cpp (caps {T, T, T}, interleaving "Culling setup", "Culling models and HZB", and "Culling" around the neutral passes) against Vulkan's WorldViewRenderer.cpp (caps {T, F, F}, running the four neutral passes across 4 depth-by-winding raster variants and rejecting legacyGlbBatch before building any pass).
FullSceneFrame pins the 12-stage frame DAG once; FullSceneWorld pins the 4 world-stage passes, their exact names, and their depth/velocity policies for both backends.

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:

  1. Both executed (stages the backend runs on the shared graph) and published (stages whose outputs the caller already produced) follow strict production order with zero duplicates.
  2. No stage appears in both lists.
  3. 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 SceneDepth with a clean clear guarantees the OpaqueWorld color pass owns scene depth cleanly rather than leaving stale fragments that fail GL_LESS or VK_COMPARE_OP_GREATER at equal depth.
  • Explicit unrouted color outputs instead of shader forks or silent drops. Remember that Play2Train's unchanged terrain.frag.glsl and default.frag.glsl always write two color outputs: FragColor (Location 0) and FragVelocity (Location 1). What happens when a view renders a single-color capture (such as a portal reflection or velocity-disabled frame) that binds only SceneColor? Instead of compiling a second shader without FragVelocity, allocating a wasteful scratch velocity texture, or silently dropping output 1, FullSceneWorld.cpp records:
cpp
// 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:

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

Fail-closed admission funnel diagram for ValidateWorldStageFrame in FullSceneWorld.h/.cpp. Top dark banner quotes the production rule: "A frame that asks for one it does not have is an admission error, never a silently skipped pass or a stub." Four sequential gates inspect every incoming WorldStageFrame before any RenderPass is created: Check 1 (Capability: InvalidFrameView, UnsupportedWorldStage, MissingCapability); Check 2 (Targets: ExtentMismatch, MissingTarget, VelocityMismatch); Check 3 (Payloads: UnexpectedPrepassDraws, InvalidDrawPacket, InvalidResourceUse); and Verdict (All-or-Nothing std::expected<void, WorldStageError>: either Admitted -> BuildWorldStagePasses emits pinned passes, or Refused -> std::unexpected with 0 passes emitted). Bottom panel shows the pure-CPU constexpr capability matrix comparing OpenGL ({true, true, true} -> Admitted), Vulkan ({true, false, false} -> Refused with MissingCapability when legacyGlbBatch is requested), and empty/partial capability sets (Refused with UnsupportedWorldStage or MissingCapability).
ValidateWorldStageFrame evaluates nine sequential checks before BuildWorldStagePasses runs; any failure refuses the entire world stage with zero passes emitted.

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.py translates shaders offline during the CMake build and embeds validated SPIR-V bytes directly into C++ headers. It does not ship glslang at runtime, and it deliberately avoids running arithmetic optimization passes in spirv-opt (invoking only --remove-unused-interface-variables and --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.py such as luminance_histogram, hzb_batch, and the four particle-pool compute kernels) must use descriptor set 0, column-major matrices with MatrixStride 16, unpacked Location slots (Component == 0, Index == 0), explicit StorageBuffer blocks (never implicit Buffer variable reflection), 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. QueryWorldStageCapabilities is constexpr and never queries a Vulkan physical device. Hardware-dependent requirements — such as optional independentBlend when 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 FullSceneViewRenderer on Vulkan now owns all 12 FullSceneStage view renderers (including WorldViewRenderer for terrain/rigid draws and GlbBatchViewRenderer for Vulkan GLB instanced batches), FullSceneWorld intentionally keeps legacyGlbBatch and cullingProducers unclaimed 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 in src/engine/renderer/README.md.

Sources and further reading