Files
larp/shaders/replace/README.md
gamingwithhomie bf1be4abee Merge pull request #227
Build replacement shaders for both descriptor heap sizes
2026-12-06 04:59:44 +05:30

21 KiB
Raw Blame History

Replacement shaders

HLSL of our own for title programs whose translation is the wrong shape: written by hand, or made from the translation (below, "From a translation"). Each file here, <hash>.<stage>.hlsl, compiles to target/shader-replace/<hash>.<stage>.dxil; every run uses the compiled container in place of the translator's code for that program. The layer finds that folder from its executable's place (or shader-replace beside it, a distribution's), and LARP_SHADER_REPLACE=<folder, as a Windows path> names another. The mechanism, the folder's lookup and what it checks: crates/larp-gpu/src/shader_replace.rs.

  • <hash>: the program's 16 lower-case hex digits as the layer's log prints them (hash= in "first bind", "shader translated").
  • <stage>: compute, pixel, vertex or mesh (profiles cs_6_6, ps_6_6, vs_6_6, ms_6_6; entry main).
  • Nothing derived from the title's files goes in this folder beyond what the HLSL itself states.

Descriptor heap layouts

Include view_heap_layout.hlsli for the null slot, title view limit and shared heap view slot. The build writes the 1,000,000-slot DXIL to the replacement directory and the 2,097,152-slot DXIL to its heap-2097152/ subdirectory. The loader selects the variant using the active heap size and shares the base file's binding declarations with the wide variant. If any installed replacement lacks a usable wide variant, the layer uses the 1,000,000-slot heap for the whole run. When packaging a build, copy the entire target/shader-replace/ tree, including the subdirectory and the binding declarations.

Both layouts keep the layer's fixed-size slot shift and stride arrays. Their bounds are independent of the descriptor heap layout.

The one rule: you replace the code, not the interface

The translation of the program still runs, and the host builds its root signature, fills its user data and binds its views from the translation's binding interface. A replacement may bind any part of that interface and nothing else. So:

  • A program the translator refuses has no translation to take the interface from. Its replacement brings an .interface file, and the interface is made from the console layout and that file (below, "A program that does not translate"); without one the log says "shader replacement not used".
  • A replacement cannot bind something the translation does not, with one addition: the host structures a ray query traces, which a declaration beside the replacement adds (below, "Ray tracing").
  • What the layer knows of the program's memory writes comes from the console code: write only where the console program writes.
  • No root signature in the HLSL ([RootSignature(...)]): a container with an RTS0 part is refused.

The interface is printed: the shader replaced line (and a shader replacement refused line) lists it, for example

user data b0 space0 8 dwords [dword:root parameter/type/dword 0:2/Constants/0 1:2/Constants/1 4:3/Table/0];
root CBVs b space1 []; raw SRVs t space1 [1]; structures t space1 []; raw UAVs u space1 [4]; immediate samplers
s0..s-1 space0

To see it before writing anything, put the translator's own output for the program in a folder of its own under the replacement's name (it is saved by LARP_SHADER_SAVE=<dir> as <hash>.<stage>.dxil) and translate the program's console container offline with that folder named: LARP_SHADER_REPLACE=<folder> larp translate <hash>.<stage>.cdxil --pipelines --list. The translated program's DXIL, disassembled, shows how it reads each binding.

Bindings

User data: b0, space0

cbuffer UserData : register(b0, space0) { uint4 ud[N / 4]; }   // N: the "dwords" of the interface

Root constants, N dwords (a multiple of 4); declare no more. Dword i is the console's user-data dword i (i + 16 for a program with a spilled user-data table, the structure builder's; emit/lower.rs user_first); the dwords the host computes follow the program's own. The interface lists, for each dword the program reads, the title's root parameter, its type and the dword within it:

Type in the list The dword holds
Constants the title's root constant
Table a CBV/SRV/UAV table: the byte offset of the table's list of host view slots in t252 times 8 (below, "Descriptors"); a sampler table: the byte offset of its first descriptor in the sampler heap, descriptor index × 16 (the console's sampler descriptor size)
Other(256) the view-heap slot of the copies of title memory (t254)
Other(257), Other(258) low and high 32 bits of the title address of the buffer view at that dword of that table
Other(259) the bytes (0 to 15) the raw view bound for that root view begins before the title's address: add it to every byte offset through that view
Other(260) the first thread group in x of this part of a dispatch: a 1-D dispatch of more than 65,535 groups runs in parts; add it to SV_GroupID.x
Other(261) + k not read: names the structure view whose host top level is bound at t<248+k> (a substituted walk's, or a declared one: "Ray tracing")

A dword not in the list is not filled. Constant numbers: larp_shader::emit::USER_*, emit::sites::USER_RTAS.

Descriptors: the heaps, directly indexed

ResourceDescriptorHeap[i] and SamplerDescriptorHeap[i] (SM 6.6; the root signature has both *_HEAP_DIRECTLY_INDEXED flags).

  • A view table (CBV/SRV/UAV) is read through its list in t252 space1 (ByteAddressBuffer, SLOT_TABLES): the descriptor at byte b of the table (its address as the console code computes it, from ud[...] of the Table dword) is the view at the heap slot in dword (ud + b) / 32 of the buffer, the dword at byte ((ud + b) >> 5) << 2. The translation reads it so and clamps the slot to the heap's null slot, min(t252.Load(((ud + b) >> 5) << 2), null); read it the same way.
  • A constant view of a table is no descriptor of its own. Its dword in the list says where its constants lie, and they are read as raw bytes (table_cbv(e, row) in the files here, e the dword unclamped, row the 16-byte row): with the top bit set, in the heap view (a raw view of the title's graphics heap in place, at the heap slot after the null slot that ends the title's slots, larp_shader::emit::heap_view_slot; 606,783 in a heap of 1,000,000 views) at the byte offset e << 4; otherwise at byte 0 of the raw view at heap slot e. A constant view the program picks from the heap by an index it computes is a constant buffer view at that slot, as before.
  • A sampler table keeps the title's descriptor order: the descriptor at byte o of the table is at index o / 16, so ud[...] divided by 16, plus the descriptor's place in the table.
  • An index the program computes into the view heap (a descriptor index read from memory, root type ResourceHeap) is a title slot: the translation clamps it to the end of the title's slots (view_title_limit, a null slot) and to the heap's null slot.

The heap has an end: index only what the console code would index (the translation clamps; a replacement that computes an index has no such clamp unless it writes one).

A buffer in the view heap is viewed as the translation reads it, and must be read the same way: ByteAddressBuffer / RWByteAddressBuffer (raw) for every untyped access (dword loads, stores, atomics, typed-format loads, and indexed ones at index x the console descriptor's stride); Buffer<float4> / RWBuffer<float4> for buffer_load_format / buffer_store_format. A raw view begins on the 16 bytes at or below the console view's start: add the slot's shift from t253 to every byte offset through it, unless the sum passes 2^32, and take it from a size (shifted(slot, offset) in the files here). Texture atomics: R32_UINT (RWTexture*<uint>) for 32-bit, R32G32_UINT (RWTexture*<uint2>) for 64-bit operations.

Root views: space1, register = the title's root parameter index

cbuffer Root2 : register(b2, space1) { ... }            // a root CBV the interface lists
ByteAddressBuffer   r1 : register(t1, space1);          // a root SRV
RWByteAddressBuffer r4 : register(u4, space1);          // a root UAV

Root SRVs and UAVs are raw only (ByteAddressBuffer, RWByteAddressBuffer); anything else is refused. The title's are one-view tables of a raw view of the host's copy, so a read or write past the copy's size reads zeros / is dropped; a root view may begin at any byte of title memory, and the raw view on 16 bytes: Other(259) gives the bias.

The layer's own registers in space1, bound only when the translation declares them:

Register What
t255 per view-heap slot, the bytes per element of the buffer view there (SLOT_STRIDES); bits 30 and 31 mark a typed view of an integer format (VIEW_SIGNED, VIEW_INTEGER), so a stride is the dword & 1073741823u (VIEW_STRIDE_BITS)
t253 per view-heap slot, the bytes (0, 4, 8, 12) the raw buffer view there begins before the console's view (SLOT_SHIFTS)
t254, u253 title memory by address: the directory of 64 KiB pages and the fault notes (SLOT_MEMORY, SLOT_FAULTS; emit/shader.rs)
t252 the lists of host view slots view tables are read through (SLOT_TABLES; "Descriptors")
t248..t251 RaytracingAccelerationStructure: the host structure for the program's structure view k (emit::sites::SLOT_RTAS)
u252 diagnostics builds: the ray-query comparison counters (emit::sites::SLOT_RT_COUNTS); a replacement that declares positions: its counters ("Ray tracing")
u248..u251 a replacement that declares positions: the instance array of the top level at t<248+k> (crate::rt::SLOT_INSTANCES)
u254 a replacement that declares positions: the pool of the triangles' positions (crate::rt::SLOT_POOL)

Immediate samplers: s<n>, space0

SamplerState s0 : register(s0, space0) up to the count the interface gives; the host declares them as static samplers from the console's sampler words. One the translation uses for comparison has a comparison filter: SamplerComparisonState.

Per stage

  • Compute. The host dispatches one group per console group, as many as the console asks (SV_GroupID is the console's group, plus Other(260) in x where listed). Keep the console's group size ([numthreads] of the translated program) unless the program is written to do one console group's work with another. Host waves are 32 lanes on this card; [WaveSize(64)] needs a host that supports it.
  • Vertex, pixel, mesh. The signatures must be the translated program's: the same semantics, indices, registers, masks and component types (the input layout and the other stage are the title's and the translator's). Pixel outputs are plain 32-bit values. A mesh program keeps the console's lanes per group, its vertex and primitive maxima, triangles; the host draws DispatchMesh(x, 1, 1). A mismatch shows as "host pipeline refused" after the "shader replaced" line.

Ray tracing

A host ray query traces t<248+k> space1 (k 0 to 3), a root SRV the host binds at each dispatch to the host top level of one of the title's structure views (crate::rt; a view with no host structure gets an empty top level, a miss). The translation declares it only for a program listed in crates/larp-shader/src/emit/sites.rs (TABLE) whose substitution of the walk succeeded. For any other program the replacement declares it, in <hash>.<stage>.views beside its source (copied beside the container by the build): one line per structure view,

# k  root parameter  dword  [positions]
0 1 24

k the register t<248+k>; the title's root parameter, a descriptor table, and the dword within it at which the view's descriptor begins (a multiple of 8); positions, optional, below ("The hit triangle's positions"). # begins a comment. The place is the translation's own: the console's s_load_dwordx4 of the view, whose address words the translation reads as user-data dwords of kind Other(257) and Other(258) with that root parameter and dword. The layer then adds t<248+k> and a user-data dword of kind Other(261) + k (after the translation's last) to the interface, as a substituted walk's translation has them; the replacement uses

RaytracingAccelerationStructure scene : register(t248, space1);
RayQuery<RAY_FLAG_NONE> q; q.TraceRayInline(scene, flags, mask, ray); ...
  • A declaration of a view the translation already declares must name the same place; a different one is refused.
  • A declaration that does not parse, or with no container beside it, is refused; the container beside a refused declaration is not used.
  • t<248+k> binds only a RaytracingAccelerationStructure, and a RaytracingAccelerationStructure binds only there.
  • Title memory by address (t254, u253) stays bound whether or not the replacement reads it: the interface is the translation's.
  • A line heap says the replacement also traces structures it takes from the view heap by an index (RaytracingAccelerationStructure s = ResourceDescriptorHeap[i]). A title slot holding a structure view shows the host top level at that view's address there, or the empty top level while there is none (crates/larp-gpu/src/rt.rs). Each bind of such a program keeps what those slots show for its list. Index only slots the title wrote with a structure view: any other slot holds another kind of view.
  • A candidate loop (the loop over a query's Proceed() that runs the title's code for a non-opaque candidate) stops where the console's walk at that site stops: it counts its passes and tests the count against the cap the walk tests, with the walk's comparison (a dword the program loads from its constants, or a literal in its code), ends the query with Abort() there, and gives the code after it the count and the cap flag the walk leaves. Each file's header has its sites' caps and the console addresses of their compares.

The hit triangle's positions

The host keeps, per host bottom level, a copy of its triangles' positions, and per host top level an instance array (crates/larp-gpu/src/rt.rs, Range). A view declared with positions adds to the interface:

  • u<248+k> space1, the instance array of the top level bound at t<248+k>: dword i, for InstanceIndex i, is the pool offset of the copy of the instance's bottom level, or 0xFFFFFFFF (none: no host structure, or its copy refused for want of room);
  • u254 space1, the pool (one for all views). A copy: dword 0 the geometries G, dwords 1 to G the first triangle of each geometry, dword G + 1 the triangles; from byte 4 (G + 2) 36 bytes a triangle, for primitive p of geometry g at 4 (G + 2) + 36 (first[g] + p): its three vertices' float3 in the order of the triangle's indices, after the geometry's Transform3x4 (the bottom level's space, as ObjectToWorld3x4 takes it). The vertices are decoded as D3D12 reads the build's format (a two-component format's z 0);
  • u252 space1, the counters: the replacement may add to the 16 dwords from byte 34000 (crate::rt::POSITION_COUNTS_AT): per block b (0 to 3) at dword 3b lanes at its position test, 3b + 1 lanes with positions, 3b + 2 normals of length 0; at 12 lanes at the facing test, at 13 lanes passing it. The diagnostics report prints them per frame.

All three are root UAVs (RWByteAddressBuffer), read only but the counters: the pool is written on one list and read on others, on both queues, so it stays in unordered access. Root views have no bounds: read an instance array only at an index a committed hit of its own top level gives, and a copy only through its header (G, and first[g + 1] - first[g] triangles in geometry g). The arrays and copies stay as the top level and bottom level the dispatch is bound to were built.

A container that reads them but whose .views does not declare positions is refused at its program's first use: it binds u254, which the host does not declare.

A program that does not translate

<hash>.<stage>.interface beside the source (copied by the build) is used only when the program does not translate. The interface is then made from the console layout:

  • user data: for each Constants and Table root parameter, dword d at index user_data + d (the layout's user-SGPR, as the translation places it);
  • t252 (the table lists) when a table holds views;
  • a root descriptor parameter as the root view b, t or u<root parameter> space1 of the kind the program reads it as (a root UAV gets no bias dword);

and the file adds, one per line (# begins a comment):

user 7 group-base                              # Other(260) at user-data dword 7
strides                                        # t255, with the heap's buffer views made ready
sampler 0 00000000 00c00000 18500000 00000000  # s0 from the console's four words (hex); `compare` after them

The .views structure views follow, as for any replacement. Take the indices and samplers from the translation of the program changed so that it translates (the "Starting text" of 07c93bfb77fecebb.compute.hlsl says how); the shader does not translate: its replacement's interface is made ... line prints the interface made. A program with a spilled user-data table is refused.

From a translation

Some files here are the translation itself turned into HLSL (dxil-spirv, SPIRV-Cross) with its bindings restored: <hash>.compute.hlsl and <hash>.compute.views for a program whose query sites the translator substitutes by host ray queries (an entry in crates/larp-shader/src/emit/sites/table.rs). Such a file reads the user data as the translation without the entry numbers it, so it is for a build whose table no longer has the entry. The heap's clamps and the heap view's slot in it are this host's (null slot 999,999). Its header comment is the reading of the sites, and each TraceRayInline is marked with its site. In some, each waterfall loop of the translation over the wave's textures (the console compiler's loop that serves one texture a pass, by v_readfirstlane) is one read of the lane's own texture.

Others started from the translation without an entry, its walks left in: the starting point of a replacement converted by hand, as 6d7fe7745ab9c6d8's was.

Compiling

The program's build compiles this folder into target/shader-replace/ and copies the .views declarations and .interface files there (apps/larp/build.rs, which says when a file is compiled and with which dxc and flags), so cargo build of the program is enough and a file that fails fails the build. A launch refuses a source changed since the build. One file by hand, into a folder of one's own: dxc with the build script's flags (validated, so the container's digest is set, and reflection stripped). A container compiled without validation (-Vd, digest zero) is accepted: the layer sets the digest native D3D12 checks and says so in the log line.

What the log says

  • shader replacements with the folder, the usable files, those with declared structure views, those with an interface (with_interface) and the refused files, at the first program looked up; before it, shader replacement refused: <why> for each file that is misnamed, not a DXIL container, of another stage than its name, or carries a root signature, and for each declaration refused.
  • shader replaced per program: hash, stage, file, size, blake3 (of the bytes used), vkd3d_hash (the name of vkd3d-proton's dumps), digest kept or set, structure_views declared (t<248+k>=<root parameter>/<dword>, +positions(u<248+k>,u254) for one declared with positions), positions (whether the container reads the pool), heap_structures (a heap line), and the interface with them.
  • shader does not translate: its replacement's interface is made from the console layout and its .interface file, with that interface, before shader replaced, for a program that does not translate.
  • shader replacement refused: it binds <binding>, which the host does not declare at the program's first use, or it declares structure view k at ..., the translation at ...: the translation runs instead.
  • Diagnostics report: in host ray tracing, query programs per frame, per program with declared views, (a replacement with declared structure views) and its views bound to a host top level, to the empty one, and its dispatches dropped before the host side was ready.
  • Diagnostics report: shader replacements (since the start) with the counts, without_translation among them.
  • Diagnostics report: host ray tracing: structures in view-heap slots: slots showing a host top level and the empty one, slots made before the host side was ready, remakes after a build retired and run, dispatches of programs with a heap line and those with no slot showing a structure (warned once).
  • Diagnostics report: host ray tracing, vertex positions: the pool, the copies and arrays alive, what was written and refused per frame, instances with and without a copy, and the counters a replacement added ("The hit triangle's positions").