diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index 8100fefc7e..a9ecc4c359 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -34,6 +34,8 @@ on: - "tools/lane_masks.py" - "tools/mc_command.py" - "tools/mesh_compute_vs.py" + - "tools/rdna2_decode.py" + - "tools/rdna2_isa_tables.py" - "tools/rdna2spirv.py" - "tools/report_paths.py" - "tools/shader_carve.py" @@ -72,6 +74,8 @@ on: - "tools/lane_masks.py" - "tools/mc_command.py" - "tools/mesh_compute_vs.py" + - "tools/rdna2_decode.py" + - "tools/rdna2_isa_tables.py" - "tools/rdna2spirv.py" - "tools/report_paths.py" - "tools/shader_carve.py" diff --git a/docs/README.md b/docs/README.md index 1fe20c5bf5..71767ef116 100644 --- a/docs/README.md +++ b/docs/README.md @@ -79,6 +79,7 @@ method, scope and caveats. No game data is included. | [buffer_formats.md](buffer_formats.md) | Every GFX10 buffer data format a V# or MTBUF can name, loaded and stored, measured on a Radeon 880M (RDNA3.5, not RDNA2): 1.33 million validated elements, 0 mismatches; SCALED stores convert as NORM, float stores round toward zero. | | [fssm_crosscheck.md](fssm_crosscheck.md) | FSSM/RDNA2 facts cross-checked against SCARAB; code starts at `code_off + 0x28`. | | [fspx.md](fspx.md) | `FSPX`, the FidelityFX DLL's native compute programs (its shaders' `ACCC` part): directory as the DLL reads it, kind-0 dispatch state, the hash prologue, `gfx1030` for its `v_dot4` code; 13 of 29 translate with `tools/fspx_unpack.py`. | +| [lanterns.md](lanterns.md) | Lanterns, a synthetic title-shaped guest through `gta6rt --run`: hand-written RDNA2 shaders packed into FSSM containers, translated offline, drawn on the Vulkan device and checked pixel by pixel against a CPU reference, with a negative control; stage 1 (five instanced draws with depth) passes on an RTX 5080 under Wine. | | [first_light.md](first_light.md) | Draw an exported model's UVs or sample a supplied texture with `--dds`. The UV draw covered 78.1% on an RTX 2060 SUPER (4,213 vertices, 7,968 triangles). The first draw of a real game model with its own translated VS/PS on a GPU: 4,213 vertices / 7,968 triangles, 78.1% coverage on an RTX 2060 SUPER; `tools/first_light.py`, the `vk_harness` mesh mode, and the same draw through the D3D12 layer (`d3d12_first_light`). | | [material_pass_replay.md](material_pass_replay.md) | How one authored mesh writes packed draw indices, how six compute programs read the layout, and which sibling passes read the surface material. | | [embedded_shaders.md](embedded_shaders.md) | DXBC containers embedded in the package's DLLs: 52 in `XboxBvhBuilder.dll` (console `FSSM` via the `XDAT`/`XBCH` record; 51/52 pass `spirv-val` today) and 29 `ACCC`/`FSPX` in the FidelityFX upscaler; the scan/extract tool and the one rule still missing. | diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 8749bd331d..aa34d1303e 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3574,6 +3574,13 @@ M0–M2 do not need the executable. | **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; the builder's 52 console `FSSM` programs (51 pass `spirv-val`, one rule left: [embedded_shaders.md](embedded_shaders.md)) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the `FSSM` translator or a substitute; no unknown XDXR call remains | | **M7** | HDR, VRS, `PresentX` planes (2-plane HDR + GameDVR compose, `ImmediateThresholdPercent`), resize, alt-tab, `SuspendX`/`ResumeX`, frame pacing and `GetFrameStatisticsX` | Presentation polish | HDR and resize work on the target display; no validation errors over a long run. **Partly met:** `ImmediateThresholdPercent` (late frame flipped at once through `VK_KHR/EXT_swapchain_maintenance1` IMMEDIATE/FIFO_RELAXED, section 4.5; checked on the fake-clock decision and on the Vulkan present mode, 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1` on two GPUs, no tearing observed on a display; the console's real semantics are unmeasured). **Plane compose** (section 4.5): 1-2 planes scaled from a source rectangle to a destination placement, point or bilinear, plane 1 alpha-blended (premultiplied or straight), filtered and blended in linear light, SDR (sRGB or gamma 2.2) and HDR10 (PQ) planes converted to the swapchain, SDR white from Windows' setting when HDR10 is active (else 203 nits), checked against a CPU model on two GPUs with 0 VUIDs (exact for point filtering, within 1-2 levels for bilinear, alpha, tone map and PQ conversions); the layouts, flag values and alpha convention are ours, the console's plane semantics are unmeasured, and the public HDR sample's second plane is the GameDVR copy, not an overlay. HDR10 swapchain (ST.2084 surface): verified on an RTX 5080 with an HDR10 display by @JavierBlanco23 in #2069, not on AMD (our test displays list no ST.2084 surface); HDR10 on an SDR swapchain is tone mapped (identity below 0.8 of SDR white, Reinhard shoulder above, then clipped per channel). `SuspendX`/`ResumeX`, frame pacing and a minimal `GetFrameStatisticsX` exist; VRS, alt-tab, an AMD HDR10 display run are open | +**Milestones together in one guest.** [lanterns.md](lanterns.md) runs a synthetic title-shaped guest under +`gta6rt --run`, with hand-written shaders that take the title's FSSM container path (`fssm_unpack.py`, +`shader_disasm.py`, `rdna2spirv.py`). Its stage 1 covers the M1/M1.5 contracts in one frame: translated VS and PS +found by FSSM hash, V# vertex and instance fetch, root constants, a root CBV, the code base, and a depth buffer. Every +pixel is checked against a CPU reference, with a depth-off negative control. It is opt-in +(`-DLEONIDA_TEST_LANTERNS=ON`). + **M3 occlusion portability (D3D-209).** Vulkan's [occlusion query specification](https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#queries-occlusion) permits a count multiplied by the number of written color outputs, even with `VK_QUERY_CONTROL_PRECISE_BIT`. The original two-output query returned twice the CPU area on Intel UHD (Windows driver 31.0.101.4146), diff --git a/docs/lanterns.md b/docs/lanterns.md new file mode 100644 index 0000000000..0a1526bd7d --- /dev/null +++ b/docs/lanterns.md @@ -0,0 +1,316 @@ +# Lanterns: a synthetic title through `gta6rt --run` + +Lanterns is a test guest, an x64 Windows program shaped like a title. It goes through the same chain a title would: + +1. Its RDNA2 shaders are hand-written. They are packed into synthetic FSSM programs inside the container the title + ships: `DXBC { DXIL { XDAT { 0x0D: XBCH + zlib(FSSM) } } }`. +2. The project's offline tools translate them, the way `make_game.py`'s shaders stage does: `fssm_unpack.py`, + `shader_disasm.py` (code range from the FSSM header) and `rdna2spirv.py`. +3. `gta6rt --run` maps the guest and answers its imports. The guest gets its device only from + `d3d12_xs.dll!D3D12XboxCreateDevice`, which the shim registry answers with the Vulkan device + (`LEONIDA_D3D12=vulkan`). +4. The guest creates its pipelines from those containers through the D3D12 API. The layer finds each translated shader + by the SHA-256 of its FSSM program. +5. The guest draws, reads the frame back and compares every pixel with a CPU reference. A negative control then shows + that the check would have caught a wrong frame. + +Nothing comes from the game. The scene is abstract solids on a checkered floor, and the shaders, scene and reference +are ours. + +Code: `runtime/test/lanterns/`. `lanterns.cpp` is the guest and `lanterns_gpu.cpp` its D3D12 side. +`lanterns_scene.h` is the scene and `lanterns_reference.h` the CPU reference. `shaders/*.asm` are the shaders, +`fssm_pack.py` the packer, `run_lanterns.py` the runner and `lanterns.cmake` the build. + +## How it relates to the other synthetic tests + +Each boot milestone in [d3d12_vulkan.md](d3d12_vulkan.md) section 6 has its own gate: `d3d12_draw_test` (M1), +`d3d12_translated_draw_test` (M1.5), `d3d12_m2_textured_test`, `d3d12_m3_frame_test` and `d3d12_m4_compute_test`. These +are host programs. They link the layer and create the device directly, and most build their shaders with +`runtime/test/shaders/build.py`, which hands llvm-mc's listing straight to the translator. +`run_tiny_frame` (#3488) runs a mapped guest through `gta6rt --run` for a clear and a readback. + +Lanterns puts the pieces together in one guest. Its shaders take the title's path through the FSSM container, +`fssm_unpack.py` and `shader_disasm.py`, and the guest runs under `gta6rt --run`. Each stage then adds what the +milestone tests check one at a time. + +## Stages + +Each stage is its own run (`--stage N`) and prints its own PASS line. Every stage has a control the reference +predicts, so a check that could not tell a right frame from a wrong one fails. + +| Stage | What it adds | Control | +|---|---|---| +| [1](#stage-1) | Five indexed, instanced draws with a depth buffer | Depth test off changes the predicted pixels | +| [3](#stage-3-compute-on-a-second-queue) | A compute queue moves the points of light; the frame waits on its fence | Point states and records equal the CPU's; the points move the predicted pixels | +| [5](#stage-5-an-fp16-target-and-a-bloom-post-process) | An fp16 target, then a bloom whose waves share LDS across an `s_barrier` | Skipping the blur changes the predicted pixels | +| [6](#stage-6-compressed-textures-with-mip-chains) | BC1 and BC7 textures with full mip chains, trilinear and explicit-LOD sampling | Two mips down leaves the predicted pixels' bounds | +| [8](#stage-8-a-shadow-map) | A D32 shadow map with PSO depth bias, sampled with 2x2 PCF | The map cleared to far changes the predicted pixels | +| [9](#stage-9-deferred-lighting-with-tiled-light-culling) | A G-buffer of three render targets, then 256 point lights culled per 16x16 tile in LDS | One light moved changes the predicted pixels; culling off gives the same image | + +## Stage 1 + +Five `DrawIndexedInstanced` calls draw hexagonal prisms, cubes, octahedra, pyramids and a checker floor into a 384x256 +`R32G32B32A32_FLOAT` target with a `D32_FLOAT` depth buffer (depth test LESS). The frame is drawn twice: once with the +depth test (the image) and once without it (the negative control). + +What it covers: + +- The PE loader, the shims and `D3D12XboxCreateDevice` on Vulkan, called from a mapped guest. +- Pipelines from DXBC/XDAT/XBCH containers, with each shader found by its FSSM hash. The VS container has two 0x0D + payloads, as 195 of the title's do, and the layer must take the last one, as the tools do. +- Wave32 and wave64 shaders. The octahedra are drawn with a wave64 VS and PS pair; every VS in the title's census is + wave64. +- The title's register layout. The title's VS and PS read their first table pointer at `s8` + ([d3d12_vulkan.md](d3d12_vulkan.md) 3.5). The layer packs root arguments from `s0` in root-signature order, so a + root signature that starts with eight 32-bit constants puts them in `s0`..`s7` and the first table at `s8`. A + second, small draw does exactly that: a wave64 VS and PS (`vs_lanterns_edges`, `ps_lanterns_edges`) read their + constants from `s0`..`s3` and their table from `s[8:9]`, the VS its vertices through slot 0 and the PS one value + through slot 1. +- Vertex, index and instance buffers in DEFAULT heaps, filled from an upload buffer by `CopyBufferRegion`. +- The vertex shader fetches the vertex and the instance through two V#s in two descriptor tables. It reads the descriptor + heap start handles through heap slots 9 and 10. +- The model matrix and tint come from 16 root constants, and the camera from a root CBV. +- The floor's pixel shader reads its two checker colours from its own FSSM program, through the code base + (`s_getpc_b64`). +- The PS input table declares one flat input and one interpolated input. On the floor shader their slot bytes are + 6 and 3, not position + 1: the attr number is the table position, so a reader that used the slot would fail. +- Clear, depth, readback through `CopyTextureRegion`, and a fence wait. + +How the check works: + +- **Exact pixels.** Colours are short binary fractions, so every product the shaders form is exact in float. Pixels + that are clearly inside one face, or clearly background, must match the CPU reference bit for bit. +- **Uncertain pixels.** A few pixels depend on how the GPU rounds: triangle edges, depth near-ties and checker borders. + Each of these must be one of the colours the reference lists for it. The background is on that list only where no + surface certainly covers the pixel. Near an edge that two faces of one solid share, one of the two must cover it, + because both get the same vertex positions, so a crack there fails. +- **Shared edges.** The second draw is a fan of eight triangles around one vertex, every vertex on a pixel centre, with + inner edges horizontal, vertical and at slopes 1:1, 1:2, 3:2 and 1:4. 673 pixel centres lie exactly on an edge two + triangles share. Each triangle has its own flat colour, and additive blending counts how often each pixel is drawn. + The CPU applies D3D's top-left rule in exact integers (`lanterns_edges.h`). Every one of the 98,304 pixels must + match: each shared-edge centre drawn once, by the triangle the rule names, no pixel drawn twice, no gap. +- **Lookup control.** Before drawing, the guest writes two containers of the vertex shader's FSSM program with the + same writer (`runtime/test/d3d12_test_shaders.h`). The first holds the program as it is, and the layer must give a + pipeline for it. The second has one byte of the program's name changed (`vs_lanterns` to `vs_lanternS`), so its + FSSM hash is one no translated shader has, and the layer must refuse it with `E_INVALIDARG`. The two containers + differ only in that byte, so the refusal comes from the lookup, and a pass cannot come from a lookup that matches + anything. +- **Negative control.** With the depth test off, submission order decides what is visible. The reference predicts + which certain pixels change. The GPU frame must change exactly those pixels, and there must be at least 1,000 of + them. A layer that ignored the depth state, or a reference that could not tell the two frames apart, fails here. + +On success the guest prints one line and exits 0: + +``` +Lanterns stage 1: PASS, 97926 of 98304 pixels exact, 378 edge pixels plausible, depth-off control changed 11610 pixels; shared edges through a wave64 VS/PS with the title's s8 table: 98304 of 98304 pixels exact, 673 centres on shared edges each drawn once +``` + +`run_lanterns.py` passes the run only when all of these hold: exit code 0, this line exactly once, whole and with +numbers that fit together (exact and edge pixels add up to the frame, at least 1,000 changed), and the shim's +complete factory line, `[rt] d3d12_xs: D3D12XboxCreateDevice -> proxy 0x... (Vulkan device 0x...)`. That last line +means the device is the Vulkan one, not the host's. The guest waits for each fence for at most 30 s and fails with a +line saying so. With `--wine`, the runner first stops the prefix's `wineserver` (`wineserver -k`, then `-w`, +10 s each, killed with everything it started if it overruns): a launch under a new virtual X server while the last run's `explorer.exe` is still alive hangs in +winevulkan's device creation, because that explorer keeps the old, closed display. The runner's timeout kills everything the run started, so a stalled guest, Wine or GPU fails the run +with exit code 3 instead of hanging it. On Linux it also catches a process that left the launcher's session (it makes itself a child subreaper, and if the kernel +refuses that it does not launch at all and exits with code 4); if +anything survives the kill, or taskkill fails on Windows, the run fails with exit code 4 and names what is left. +Each run writes into a new folder under `--out`: the guest's dumps, the launcher's output, `lanterns-stage1.png` +and `lanterns-stage1-sheet.png`. The sheet shows the GPU frame, the reference, the control frame, a mask (grey: +exact, red: wrong, yellow: uncertain), and the edge fan from the GPU and from the CPU (each triangle in its own +colour, white where drawn twice, black where not drawn). + +Each check was made to fail on purpose, and each fix in it was shown to matter: + +- A wrong shader: the floor shader repacked with one checker colour changed (red 0.4375 to 0.5). The guest reported + 20,430 certain pixels wrong and exited 1. +- A crack: every face of the cubes pulled 0.16% of the way to its centre, so a sliver of background shows along the + edges, less than 1/32 pixel wide. The guest fails, on an edge pixel the reference gives to the pair of faces. With + the background still a candidate there, as before, the same frame passed. +- A lookup that refuses the guest's container: the runtime patched to refuse a DXBC container whose size field is 0. + The guest fails at the unmodified container's pipeline. With only the renamed container, as before, it passed. +- A fence nobody signals: frame 2 of stage 3 made to wait for one value more. The guest fails after 30 s with the + fence line. Before, the run hung until the runner's timeout. +- The register layout and the fill rule: the edge PS reading table slot 0 instead of slot 1 leaves 31,884 of + 98,304 pixels exact. A reference with a bottom-right rule instead of top-left leaves 0 of 673 shared-edge centres + right (319 gaps). Both fail. +- A stale `wineserver`: seen on another Linux setup, where 20 of 20 launches hung without the stop and 20 of 20 passed + with it. On the test machine two back-to-back runs passed either way, so here it rests on the runner's test with a + fake `wineserver` on `PATH`. + +## Stage 3: compute on a second queue + +A compute shader, `cs_lanterns_rise.asm` (wave32), runs on a COMPUTE queue. It moves 256 points of light in integer +fixed point, so the CPU can repeat every step exactly. It writes their instance records into a DEFAULT buffer with UAV +access. The direct queue waits on the compute fence and draws the points as a sixth `DrawIndexedInstanced`, whose +instance V# points at that buffer. + +- Frame 1: the compute work (24 steps) is submitted, then the frame. +- Frame 2: the frame is submitted first. It waits for a fence value that a later compute submission (24 more steps) + signals, so the layer must hold the direct queue until then. + +What it adds to stage 1: + +- A compute pipeline from an FSSM container. The thread-group size and `COMPUTE_PGM_RSRC2` come from the FSSM header. +- A compute root signature with four root constants and a table of two UAVs, as in `d3d12_m4_compute_test`. +- `Dispatch` on a compute queue, and `Wait`/`Signal` across the two queues. +- A draw whose instance data is what the compute shader wrote. + +How the check works: + +- The point states and the instance records are read back. They must equal the CPU's simulation of the same steps, + word for word. +- Both frames are checked as in stage 1: certain pixels exact, uncertain pixels one of their candidates. +- Between frame 1 and frame 2 the points must change exactly the certain pixels the reference predicts. +- Control: a third frame without the `Wait`, submitted before its compute work. It is reported, not required, because + a layer may order the queues by itself. On the test machine the result varies from run to run: the previous frame's state, + or a mix of the two (16,183 and 16,546 certain pixels differed from the new state in two runs). + +``` +Lanterns stage 3: PASS, 97675 and 97664 of 98304 pixels exact, 256 points exact after 24 and 48 compute steps, points moved 14839 pixels +``` + +## Stage 5: an fp16 target and a bloom post-process + +The stage-3 frame after 48 compute steps is drawn into an `R16G16B16A16_FLOAT` target. Then a post-process runs on +the same direct queue (`lanterns_post.h`): + +- Two compute passes blur what is brighter than a threshold, first along rows and then along columns. Each group + is 128 lanes sharing LDS across an `s_barrier`. The row pass reads the scene through a T# with `image_load`. +- The row pass is wave32 (four waves), and every sample a lane sums was loaded by a lane of another wave (lane i + loads sample i + 64 mod 128; the halos come from the other half too). The second half also walks four dependent + fetches before its write, so its write lands late. Only the `s_barrier` orders those writes before the reads. +- The column pass is wave64 (two waves), translated with `--wave64-emulate`. The emulation runs a wave64 program in + rounds that already put every LDS write before a later LDS read, so there a missing `s_barrier` cannot show; that + is why the row pass, the one whose barrier is measured, is wave32. +- A fullscreen pixel shader reads `SV_Position`, the scene texel and the blur, and writes their sum into an + `R32G32B32A32_FLOAT` target. + + +How the check works: + +- The fp16 scene is checked as in stage 1, against the reference rounded to half. +- The final frame must be exact where it is certain, and within bounds where the scene's edges leave it uncertain. +- The point states and instance records must equal the CPU's, as in stage 3. +- Control: the composite with the blur skipped must change exactly the certain pixels the reference says the bloom + changes, and at least 1,000 of them. +- Measured, not required: the row pass without its `s_barrier` (a race the reference cannot predict). On the test + machine it changed 8,449 to 14,849 certain pixels in five runs; the same shader without the barrier in place of + the real one fails the stage. + +``` +Lanterns stage 5: PASS, fp16 scene 97664 of 97664 certain pixels exact, bloom composite 82563 of 82563 certain pixels exact and 15741 bounded pixels within bounds, skipping the blur changed 15113 pixels as predicted +``` + +## Stage 6: compressed textures with mip chains + +The stage-1 scene, textured. `lanterns_bc.h` makes two patterns from integer formulas (a 256x256 mosaic and 64x64 +nested squares), box-filters them down to 1x1 and compresses them with its own encoders: BC1, and BC7 mode 6. The +textures go up the D3D12 way: `GetCopyableFootprints`, an upload buffer, one `CopyTextureRegion` per mip level. No +tiled layout is written or assumed. The floor samples the BC1 mosaic with `image_sample` (trilinear, LOD from the 2x2 +quad's derivatives). The solids sample the BC7 squares with `image_sample_l`, at a mip level each draw passes in a root +constant. The root signature gains an SRV table and a sampler table. + +How the check works. Texture filtering precision differs between GPUs, so the reference decodes the same blocks and +gives every pixel bounds instead of one colour (`lanterns_sampling.h`): + +- Solids: the exact bilinear sample, plus or minus 4/255. +- Floor: the trilinear sample over the whole LOD range Vulkan allows (coarse or fine derivatives, and a scale factor + anywhere from the largest component to their sum), plus or minus 4/255. +- Control: the solids drawn two mip levels down must leave the main bounds wherever the two references cannot overlap. + +``` +Lanterns stage 6: PASS, 98144 of 98144 certain pixels within the BC1/BC7 sampling bounds (trilinear floor, image_sample_l solids), control two mips down moved 10221 of 10221 predicted pixels +``` + +## Stage 8: a shadow map + +A depth-only pass draws the solids from a directional light into a 512x512 `R32_TYPELESS` map. It uses +`vs_lanterns`, no pixel shader and no render target, and the depth bias comes from the PSO (`DepthBias` 1000, +`SlopeScaledDepthBias` 3). The map has a `D32_FLOAT` depth view and an `R32_FLOAT` shader view. The main pass's +pixel shader, `ps_lanterns_shadow.asm`, moves the world position into light space and takes four comparison samples +half a texel apart (`image_sample_c`, `LESS_EQUAL`, point filtering: 2x2 PCF). It scales the face colour by +3/8 + 5/32 per lit sample. + +How the check works. `lanterns_shadow.h` rasterizes the map on the CPU. It bounds each texel's stored depth +(coverage, tolerance, and any bias D3D12 and Vulkan allow) and each sample's texel. A pixel whose four samples are all +certain has one exact colour; every other certain pixel must be within its bounds. Control: the depth pass without +casters leaves the map cleared to 1, and that must change exactly the pixels the reference says are shadowed. + +``` +Lanterns stage 8: PASS, 95699 of 95699 single-colour pixels exact and 98144 of 98144 certain pixels within bounds (D32 shadow map, PSO depth bias, 2x2 PCF with comparison samples), the map cleared to far changed 9539 pixels as predicted +``` + +## Stage 9: deferred lighting with tiled light culling + +The stage-1 scene drawn into a G-buffer of three render targets in one pass: `R8G8B8A8_UNORM` albedo, `R10G10B10A2_UNORM` +normal and `R32_FLOAT` view depth. `vs_lanterns_gbuf` exports each face's normal, packed into its vertices' shade word +as an exact integer float, and `ps_lanterns_gbuf` unpacks it with `v_bfe`. Then `cs_lanterns_tiled` runs one 256-lane +workgroup (eight wave32 waves) per 16x16 tile: + +- each lane rebuilds its pixel's world position from the view depth and folds it into the tile's box in LDS with + `ds_min_i32`/`ds_max_i32` on order-preserving float keys; +- lane i tests light i's sphere against the box, and a kept light takes a list slot with `ds_add_rtn_u32`; +- every lane loops over the list and adds each light's contribution in integers. + +How the check works. `lanterns_deferred.h` holds the lights, the root constants and the CPU reference. Each light's +contribution is an interval, because the rebuilt position is known only within the depth's snapping slack. + +- The albedo target must be exact on every certain pixel; probes of the normal codes and the view depth must be within + their bounds (D3D12 lets a float-to-UNORM conversion be off by 0.6 ULP). +- Every single-colour pixel of the lit frame must be exact, every other certain pixel within its bounds. +- Each tile's list must be exactly the set of lights whose sphere meets its box. The one tolerance: a light within 2e-3 + of the box test's threshold (the GPU forms the same numbers in float) may go either way. The PASS line gives how many + light-tile pairs are in that band (6 of 98,304 here), and more than 32 fails, so a culling error hiding inside the band + would have to stay that small. +- The output and list buffers start poisoned, and with culling off (every light in every tile) the image must be the + same bit for bit. +- Control: one light moved must change exactly the pixels the reference predicts and keep every other pixel. + +``` +Lanterns stage 9: PASS, G-buffer of 3 MRTs (RGBA8 albedo 98144 of 98144 exact, RGB10A2 normal and R32F depth 52643 of 52643 probes), 75462 of 75462 single-colour pixels exact through tiled culling with LDS atomics (10.4 of 256 lights per tile, the exact set in 384 of 384 tiles, 6 light-tile pairs within 2e-3 of the box test left free), culling off gave the same image bit for bit from poisoned buffers, one light moved changed 1231 of 1231 predicted pixels +``` + +## Build and run + +The guest is opt-in: `-DLEONIDA_TEST_LANTERNS=ON` (off by default). It needs llvm-mc 21 with the AMDGPU target +(`LLVM_MC`, as for `runtime/test/shaders`), spirv-tools, Python 3, and a Vulkan GPU at run time. Default CI builds and +runs none of the GPU part. It does run the CPU tests of the packer and the runner (`tests/test_fssm_pack.py`, +`tests/test_fssm_pack_chain.py`, `tests/test_run_lanterns.py`). + +Windows (native): + +```sh +cmake -S runtime -B runtime/build -DLEONIDA_TEST_LANTERNS=ON +cmake --build runtime/build --config RelWithDebInfo --target gta6rt lanterns +ctest --test-dir runtime/build -C RelWithDebInfo -R lanterns_stage --output-on-failure +``` + +Linux with Wine: cross-build with `runtime/cmake/clang-cl-xwin.cmake` as in +[testing.md](testing.md#the-windows-runtime-on-linux-under-wine-or-proton), adding `-DLEONIDA_TEST_LANTERNS=ON`, and +build the targets `gta6rt` and `lanterns`. Then run, in a virtual X server if there is no display: + +```sh +B=runtime/build/windows +WINEPREFIX="$HOME/.local/share/leonida-wine" xvfb-run -a python3 -I runtime/test/lanterns/run_lanterns.py --wine \ + --gta6rt $B/gta6rt.exe --guest $B/fixtures/lanterns/RelWithDebInfo/lanterns.exe \ + --shaders $B/generated/lanterns --out $B/lanterns_out --stage 1 +``` + +There is one ctest per stage (`lanterns_stage1`, `lanterns_stage3`, ...; `-R lanterns_stage9` runs one), and the +runner takes any stage in the table with `--stage N`. + +The packed containers are in `/generated/lanterns/*.dxbc`. The translated shaders and their index +(`spirv/index.json`, keyed by FSSM SHA-256) are in the same folder. The runner points `LEONIDA_SHADERS` at that +`spirv/` folder. + +## Limits + +- Tested on one machine so far: an RTX 5080 on Linux, under Wine 11, with the clang-cl/xwin cross-build. No native + Windows run and no AMD or Intel GPU yet. +- No validation claim. Vulkan validation layers under Wine on that machine are still being looked into, so this page + does not say the run is validation clean. +- A few frames per stage, offscreen. No present, no frame loop, no swapchain. +- The FSSM programs are synthetic. They use the measured layout (`docs/design.md`, `tools/fssm_header.py`), but only + the fields the tools read, and the code is ours. A title's programs carry more than this. +- The reference is computed on the CPU, not by another D3D12 implementation. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 58153376e4..4b4063d31c 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2654,6 +2654,8 @@ if(TARGET Vulkan::Headers) message(STATUS "tiny_guest_draw will build. For an external synthetic M1.5 fixture or Wine run see runtime/README.md.") endif() endif() + # Lanterns, a synthetic title-shaped guest for gta6rt --run (opt-in: -DLEONIDA_TEST_LANTERNS=ON, docs/lanterns.md). + include(test/lanterns/lanterns.cmake) # bvh_builder_test can put the package's XboxBvhBuilder on this device too (LEONIDA_BVH_DEVICE=vulkan). if(TARGET bvh_builder_test) target_link_libraries(bvh_builder_test PRIVATE gta6rt_d3d12_com) diff --git a/runtime/test/lanterns/fssm_pack.py b/runtime/test/lanterns/fssm_pack.py new file mode 100644 index 0000000000..c5cc09de42 --- /dev/null +++ b/runtime/test/lanterns/fssm_pack.py @@ -0,0 +1,411 @@ +"""Pack hand-written RDNA2 assembly into a synthetic FSSM program inside the title's shader container. + + python -I runtime/test/lanterns/fssm_pack.py [...] [--translate] [--mcpu gfx1013] + +It is a test helper: the Lanterns guest (runtime/test/lanterns) builds its pipelines from what it writes. It lives here, +not in tools/: make_game.py's translator_digest() hashes every file in tools/, so a new file there would make a resumed +shaders stage throw away the shards it had already translated, for a script the game build never runs. + +Each .asm is assembled with llvm-mc (-triple=amdgcn--amdpal -mcpu=gfx1013 -filetype=obj; LLVM_MC names it, see +mc_command.py), and its code is the object's .text section, so branches to labels are resolved by the assembler. The +code goes into an FSSM blob laid out the way docs/design.md and tools/fssm_header.py describe the game's, and the blob +into the container the game ships (DXBC { DXIL { stub, XDAT { 0x0D: XBCH + zlib(FSSM) } } }, tools/fssm_unpack.py), with an +ISG1 input signature part when the pixel shader reads SV_Position. +The tool writes /.dxbc and a carve index /index.json (name, file, stage), the folder shape +make_game.py gets from shader_carve.py. With --translate it then runs the project's own offline chain on that folder, +as make_game.py does for the game: fssm_unpack.py , shader_disasm.py /fssm --out /disasm --mcpu gfx1013, +rdna2spirv.py /disasm --out /spirv. It checks that every shader came back: the unpacked blob is the packed +one, its listing decoded with no invalid word, and spirv/index.json has it with the stage and fssm_sha256 of the +packed blob, which is the key the runtime looks a PSO's shader up by (docs/d3d12_vulkan.md 3.6). Nothing here comes +from the game: the code is ours, the layout is the measured one. + +FSSM fields written (offsets in the blob; every other header byte is zero): + 0x00 'FSSM', u16 version 0x0101 + 0x08 u32 blob size + 0xC0 u64 code-section offset (HEADER_SIZE); the instructions start CODE_SKIP (0x28) bytes into the section + 0xC8 u64 code-section size: CODE_SKIP + code + padding + data + 0xD4 u32 flags: bit 5 (0x20) set for wave32, clear for wave64 (fssm_header.wave_size) + 0xE8 u64 code end: section offset + size (fssm_header.binding_table) + 0x120 / 0x12C / 0x130 u32 section offset, size, and offset + size (fssm_header.directory_ok) + 0x138 PS: one 8-byte input record per "; input:" line (kind 6, semantic, mask 0xF, index, slot, read method); + CS: COMPUTE_PGM_RSRC2 and the thread-group size x, y, z (docs/design.md, "Compute shaders") + code end: 4 x 0xBF9F0000 (s_code_end), u32 0, u32 0, the "; binding:" records (20 bytes each, none by default), + 0xFFFFFFFF, u32 0, u16 0, u16 name length, the name (fssm_header.binding_table) + +Header comments an .asm may carry (before its first instruction): + ; stage: vs | ps | cs default: the name's prefix (vs_, ps_, cs_) + ; wave: 32 | 64 default 32 + ; input: flat | interp [fp16] [slot=N] + PS only, one per table position, in v_interp attr order. The record's parameter + slot (byte 6) is position + 1 unless slot= gives another: the table position, not + the slot, is the attr number the code reads (fssm_header.py) + ; binding: W0 W1 W2 W3 W4 one 20-byte binding record (five u32) in the tail, in order; the title's tails carry + 5,640,704 of them (fssm_header.py), nothing in the chain reads their fields yet + ; first-payload: NAME the container gets two XDAT 0x0D entries, as 195 of the title's do: first the same + code packed under NAME (another hash), then this shader's. fssm_unpack.py and the + runtime take the last one, so a reader that took the first would miss the shader + ; data-at: 0xOFFSET bytes from the first instruction to the data words (what s_getpc_b64 + K reaches) + ; data: 0xWORD ... u32 words placed there, after the code's s_endpgm; s_code_end fills the gap + ; group: X,Y,Z ; rsrc2: 0x... CS only (thread-group size and COMPUTE_PGM_RSRC2) + ; position: xy PS only: the shader reads SV_Position's x and y (any of xyzw). The container gets an + ISG1 part declaring it with that read mask, which rdna2spirv.py turns into the + system VGPRs v2.. (one per component read, in order), as for the title's shaders + ; native-variant: NAME also pack the same code as NAME (its tail name differs, so its FSSM hash does) and + translate NAME without --wave64-emulate even when the others get it: a wave64 + compute shader's native translation beside its exact one, to measure the difference + +With --wave64-emulate (or LEONIDA_W64_EMULATE=1, as for runtime/test/shaders/build.py) the shaders are translated with +rdna2spirv.py --wave64-emulate, which makes wave64 compute shaders exact on 32-wide subgroups; native variants are +translated in a second rdna2spirv.py run into the same spirv/ folder, whose index.json it merges into. +""" +import argparse +import hashlib +import json +import os +import re +import struct +import subprocess +import sys +import zlib + +TOOLS = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "tools")) +sys.path.insert(0, TOOLS) +import mc_command # noqa: E402 + +VERSION = 0x0101 +HEADER_SIZE = 0x200 # where the code section starts; leaves room for 25 PS input records from 0x138 +CODE_SKIP = 0x28 # docs/design.md: code starts at u32[0xC0] + 0x28 +WAVE32 = 0x20 +INPUT_TABLE = 0x138 +INPUT_KIND = 6 +READ_METHODS = {"flat": 0x01, "interp": 0x02} +FP16 = 0x10 +ENDPGM = 0xBF810000 +CODE_END_FILLER = 0xBF9F0000 +SENTINEL = 0xFFFFFFFF +STAGES = ("vs", "ps", "cs") +MAX_INPUTS = (HEADER_SIZE - INPUT_TABLE) // 8 - 1 # leaves a non-6 byte after the last record + + +class PackError(ValueError): + """An .asm header or code that cannot make a well-formed FSSM blob.""" + + +def header_fields(text, name): + """The packing options from an .asm's leading comment lines (see the module docstring).""" + fields = {"stage": name[:2].lower() if name[2:3] == "_" else None, "wave": 32, "inputs": [], + "data_at": None, "data": [], "group": (64, 1, 1), "rsrc2": 0x8088, "native_variant": None, + "position": 0, "bindings": [], "first_payload": None} + for ln in text.splitlines(): + s = ln.strip() + if not s: + continue + if not s.startswith(";"): + break + m = re.match(r";\s*(stage|wave|input|data-at|data|group|rsrc2|native-variant|position|binding|first-payload):\s*(.*?)\s*$", s) + if not m: + continue + key, value = m.groups() + try: + if key == "stage": + fields["stage"] = value.lower() + elif key == "wave": + fields["wave"] = int(value) + elif key == "input": + words = value.lower().split() + slots = [w for w in words[1:] if w.startswith("slot=")] + if (not words or words[0] not in READ_METHODS or set(words[1:]) - {"fp16"} - set(slots) + or len(slots) > 1): + raise PackError(f"{name}: input must be 'flat' or 'interp' [fp16] [slot=N], not {value!r}") + slot = int(slots[0][5:], 0) if slots else len(fields["inputs"]) + 1 + if not 0 <= slot <= 0xFF: + raise PackError(f"{name}: an input's slot is one byte, not {slot}") + fields["inputs"].append((READ_METHODS[words[0]], "fp16" in words[1:], slot)) + elif key == "binding": + words = [int(w, 0) for w in value.split()] + if len(words) != 5 or not all(0 <= w <= 0xFFFFFFFF for w in words) or words[0] == SENTINEL: + raise PackError(f"{name}: a binding is five u32 words, the first not 0xFFFFFFFF, not {value!r}") + fields["bindings"].append(tuple(words)) + elif key == "first-payload": + if not re.fullmatch(r"[A-Za-z0-9_]+", value) or value == name: + raise PackError(f"{name}: first-payload needs another plain name, not {value!r}") + fields["first_payload"] = value + elif key == "data-at": + fields["data_at"] = int(value, 0) + elif key == "data": + fields["data"] += [int(w, 0) for w in value.split()] + elif key == "group": + fields["group"] = tuple(int(v) for v in value.split(",")) + elif key == "rsrc2": + fields["rsrc2"] = int(value, 0) + elif key == "position": + letters = value.lower() + if not letters or set(letters) - set("xyzw"): + raise PackError(f"{name}: position must name components of xyzw, not {value!r}") + fields["position"] = sum(1 << "xyzw".index(c) for c in set(letters)) + elif key == "native-variant": + if not re.fullmatch(r"[A-Za-z0-9_]+", value) or value == name: + raise PackError(f"{name}: native-variant needs another plain name, not {value!r}") + fields["native_variant"] = value + except ValueError as e: + if isinstance(e, PackError): + raise + raise PackError(f"{name}: bad '{key}' value {value!r}") from None + if fields["stage"] not in STAGES: + raise PackError(f"{name}: stage must be one of {STAGES} (a '; stage:' line or a vs_/ps_/cs_ name)") + if fields["wave"] not in (32, 64): + raise PackError(f"{name}: wave must be 32 or 64") + if fields["position"] and fields["stage"] != "ps": + raise PackError(f"{name}: position is for pixel shaders") + if fields["inputs"] and fields["stage"] != "ps": + raise PackError(f"{name}: input records are for pixel shaders") + if len(fields["group"]) != 3: + raise PackError(f"{name}: group needs X,Y,Z") + return fields + + +def pack(code, *, stage, name, wave=32, inputs=(), data_at=None, data=(), group=(64, 1, 1), rsrc2=0x8088, + bindings=()): + """One FSSM blob: the header fields above, the code section and the binding-table tail. inputs: (read method, + fp16) or (read method, fp16, slot) per table position; bindings: five-word records for the tail.""" + if len(code) < 4 or len(code) % 4 or struct.unpack_from(" MAX_INPUTS: + raise PackError(f"{name}: at most {MAX_INPUTS} input records fit before the code section") + body = bytearray(code) + if data: + if data_at is None or data_at % 4 or data_at < len(code): + raise PackError(f"{name}: data-at must be a dword offset at or after the code's end (0x{len(code):x})") + if ENDPGM in data: + raise PackError(f"{name}: a data word equal to s_endpgm would end the code for shader_disasm.py") + body += struct.pack(" len(obj) or shstrndx >= shnum: + raise PackError(f"{name}.asm: llvm-mc's object has a section table this tool cannot read") + sections = [ELF_SECTION.unpack_from(obj, shoff + i * shentsize) for i in range(shnum)] + names_at = sections[shstrndx][4] + text = None + for section in sections: + start = names_at + section[0] + label = obj[start:obj.index(b"\0", start)].decode("ascii", "replace") + if label in (".rel.text", ".rela.text"): + raise PackError(f"{name}.asm: llvm-mc left relocations in .text (a branch to a label it does not define?)") + if label == ".text": + text = obj[section[4]:section[4] + section[5]] + if text is None: + raise PackError(f"{name}.asm: llvm-mc's object has no .text section") + return text + + +def assemble(text, name, mcpu="gfx1013", wave=32): + """The code bytes of the .asm text: llvm-mc assembles it into an ELF object (on stdout) and the code is its .text + section, so branches to labels come out resolved, as the assembler lays them out. Wave64 code is assembled with + +wavefrontsize64, so it can name VCC and 64-bit masks as such; the encodings are the same.""" + cmd = mc_command.mc_command() + ["-triple=amdgcn--amdpal", f"-mcpu={mcpu}", "-filetype=obj", "-o", "-"] + if wave == 64: + cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32") + r = mc_command.run(cmd, input=text.encode("utf-8"), capture_output=True) + errors = r.stderr.decode("utf-8", "replace") + if r.returncode or "error:" in errors: + raise PackError(f"{name}.asm did not assemble:\n{errors}") + return text_section(r.stdout, name) + + +def pack_file(path, mcpu="gfx1013"): + """Assemble and pack one .asm (and its native variant, if it names one). Writes nothing: main() checks every name + first. Returns [(name, stage, fssm blob, native, container, path)].""" + name = os.path.splitext(os.path.basename(path))[0] + with open(path, encoding="utf-8") as f: + text = f.read() + fields = header_fields(text, name) + variant = fields.pop("native_variant") + position = fields.pop("position") + first_name = fields.pop("first_payload") + code = assemble(text, name, mcpu, fields["wave"]) + first = pack(code, name=first_name, **fields) if first_name else None + packed = [] + for packed_name, native in ((name, False),) + (((variant, True),) if variant else ()): + blob = pack(code, name=packed_name, **fields) + packed.append((packed_name, fields["stage"], blob, native, container(blob, position, first), path)) + return packed + + +def name_clashes(entries): + """Names that would share an output file on a case-insensitive volume (Windows, macOS): every output is named + after the shader (.dxbc, fssm/.fssm, disasm/.s, the SPIR-V), so two names equal after casefold() + would overwrite each other's files. Returns one message per clash, naming the inputs.""" + seen = {} + for name, _, _, native, _, path in entries: + seen.setdefault(name.casefold(), []).append(f"{name} ({path}{', native variant' if native else ''})") + return [" and ".join(names) for names in seen.values() if len(names) > 1] + + +def run_tool(tool, *args): + r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, tool), *map(str, args)], + capture_output=True, text=True) + if r.returncode: + raise PackError(f"{tool} exited with {r.returncode}:\n{r.stdout[-2000:]}{r.stderr[-2000:]}") + return r.stdout + + +def translate(out, packed, mcpu="gfx1013", emulate=False): + """Run fssm_unpack.py, shader_disasm.py and rdna2spirv.py on and check that every packed shader made it + through. Returns the rows of spirv/index.json for the packed shaders.""" + run_tool("fssm_unpack.py", out) + disasm = os.path.join(out, "disasm") + os.makedirs(disasm, exist_ok=True) + run_tool("shader_disasm.py", os.path.join(out, "fssm"), "--out", disasm, "--mcpu", mcpu) + for name, _, blob, _ in packed: + with open(os.path.join(out, "fssm", name + ".fssm"), "rb") as f: + if f.read() != blob: + raise PackError(f"{name}: fssm_unpack.py did not give back the packed blob") + with open(os.path.join(disasm, name + ".s"), encoding="utf-8") as f: + first = f.readline() + if "(header)" not in first or not first.rstrip().endswith(" 0 invalid words"): + raise PackError(f"{name}: shader_disasm.py did not decode the code from the header: {first.strip()}") + spirv = os.path.join(out, "spirv") + natives = [name for name, _, _, native in packed if native] if emulate else [] + if natives: + # A second listing folder beside disasm/ (rdna2spirv.py reads fssm/, the .dxbc and index.json from the parent). + native_dir = os.path.join(out, "disasm_native") + os.makedirs(native_dir, exist_ok=True) + for name in natives: + os.replace(os.path.join(disasm, name + ".s"), os.path.join(native_dir, name + ".s")) + translated = run_tool("rdna2spirv.py", disasm, "--out", spirv, *(["--wave64-emulate"] if emulate else [])) + if natives: + translated += run_tool("rdna2spirv.py", native_dir, "--out", spirv) + with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: + index = json.load(f) + rows = {} + for name, stage, blob, _ in packed: + row = index.get(name) + want = hashlib.sha256(blob).hexdigest() + if not row or row.get("stage") != stage or row.get("fssm_sha256") != want: + raise PackError(f"{name}: spirv/index.json has no {stage} entry with fssm_sha256 {want}; " + f"rdna2spirv.py said:\n{translated[-2000:]}") + rows[name] = row + return rows + + +def main(argv=None): + ap = argparse.ArgumentParser(description="Pack RDNA2 assembly into synthetic FSSM programs in shader containers.") + ap.add_argument("out", help="folder for .dxbc and index.json (and fssm/, disasm/, spirv/ with --translate)") + ap.add_argument("asm", nargs="+", help="hand-written .asm files") + ap.add_argument("--translate", action="store_true", help="run fssm_unpack, shader_disasm and rdna2spirv after") + ap.add_argument("--mcpu", default="gfx1013") + ap.add_argument("--wave64-emulate", action="store_true", + help="translate with rdna2spirv.py --wave64-emulate (also LEONIDA_W64_EMULATE=1)") + a = ap.parse_args(argv) + emulate = a.wave64_emulate or os.environ.get("LEONIDA_W64_EMULATE") == "1" + # As build.py: CMake names the spirv-as/spirv-val folder instead of passing a whole PATH. + if os.environ.get("LEONIDA_SPIRV_TOOLS"): + os.environ["PATH"] = os.environ["LEONIDA_SPIRV_TOOLS"] + os.pathsep + os.environ.get("PATH", "") + try: + entries = [entry for p in a.asm for entry in pack_file(p, a.mcpu)] + clashes = name_clashes(entries) + if clashes: + raise PackError("shader names must differ in more than case, since each names its output files; nothing " + "was written: " + "; ".join(clashes)) + os.makedirs(a.out, exist_ok=True) + for name, _, _, _, data, _ in entries: + with open(os.path.join(a.out, name + ".dxbc"), "wb") as f: + f.write(data) + packed = [entry[:4] for entry in entries] + carve = [{"name": n, "file": n + ".dxbc", "stage": s, "size": os.path.getsize(os.path.join(a.out, n + ".dxbc"))} + for n, s, _, _ in packed] + with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump(carve, f, indent=1) + f.write("\n") + rows = translate(a.out, packed, a.mcpu, emulate) if a.translate else {} + except PackError as e: + print(f"ERROR: {e}", file=sys.stderr) + return 1 + for name, stage, blob, _ in packed: + row = rows.get(name, {}) + wave = 32 if struct.unpack_from("/generated/lanterns/.dxbc, what the guest hands to +# CreateGraphicsPipelineState) and runs tools/fssm_unpack.py, shader_disasm.py and rdna2spirv.py on that folder, which +# write spirv/index.json keyed by each program's FSSM SHA-256 (what LEONIDA_SHADERS points the runtime at). +# --wave64-emulate makes the wave64 compute shaders exact on 32-lane GPUs; a native variant is translated without it. +# The guest links nothing from src/ or shims/: its device comes from the D3D12XboxCreateDevice it imports from +# d3d12_xs.dll, which only gta6rt's shim registry can answer. The import library is tiny_frame's failing stub +# (d3d12_xs_stub, test/fixtures/d3d12_xs_stub.cpp), built into a folder the loader does not search. +# +# Running it: run_lanterns.py (native Windows, or Wine with --wine) checks the exit code, the guest's PASS line and the +# device line, and writes PNGs of the frames. On a native Windows build it is also the ctest `lanterns_stage1`. +option(LEONIDA_TEST_LANTERNS + "Build lanterns.exe, a synthetic title-shaped guest for gta6rt --run (needs a Vulkan GPU to run)" OFF) +if(LEONIDA_TEST_LANTERNS AND NOT TARGET d3d12_xs_stub) + message(STATUS "LEONIDA_TEST_LANTERNS: lanterns.exe needs gta6rt and the d3d12_xs_stub target; not built") +elseif(LEONIDA_TEST_LANTERNS) + set(_lanterns_src ${CMAKE_CURRENT_SOURCE_DIR}/test/lanterns) + add_executable(lanterns ${_lanterns_src}/lanterns.cpp ${_lanterns_src}/lanterns_gpu.cpp + ${_lanterns_src}/lanterns_edges_gpu.cpp ${_lanterns_src}/lanterns_textures_gpu.cpp + ${_lanterns_src}/lanterns_shadow_gpu.cpp ${_lanterns_src}/lanterns_post_gpu.cpp + ${_lanterns_src}/lanterns_deferred_gpu.cpp) + target_link_libraries(lanterns PRIVATE d3d12_xs_stub Vulkan::Headers) + target_compile_definitions(lanterns PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) + target_compile_options(lanterns PRIVATE /W4 /permissive- /utf-8) + set_target_properties(lanterns PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/lanterns/$") + + if(NOT LEONIDA_LLVM_MC) + if(DEFINED ENV{LLVM_MC}) + set(LEONIDA_LLVM_MC "$ENV{LLVM_MC}") + else() + find_program(LEONIDA_LLVM_MC llvm-mc HINTS "C:/msys64/ucrt64/bin") + endif() + endif() + find_program(LEONIDA_SPIRV_AS spirv-as HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") + if(LEONIDA_LLVM_MC AND LEONIDA_SPIRV_AS AND TARGET Python3::Interpreter) + set(LEONIDA_LANTERNS_SHADERS ${CMAKE_CURRENT_BINARY_DIR}/generated/lanterns) + set(_lanterns_tools ${CMAKE_CURRENT_SOURCE_DIR}/../tools) + # Every tools/*.py and tools/*.json: the translator imports many of the scripts (fssm_header, shader_ir, + # shader_meta, mc_command, rdna2_decode, ...) and reads data such as gfx10_formats.json (rdna2spirv.py, + # rdna2_decode.py), and a stale index.json must not survive a change to any of them. + file(GLOB _lanterns_tool_py CONFIGURE_DEPENDS ${_lanterns_tools}/*.py ${_lanterns_tools}/*.json) + set(_lanterns_asm ${_lanterns_src}/shaders/vs_lanterns.asm ${_lanterns_src}/shaders/ps_lanterns_lit.asm + ${_lanterns_src}/shaders/ps_lanterns_floor.asm ${_lanterns_src}/shaders/vs_lanterns_w64.asm + ${_lanterns_src}/shaders/ps_lanterns_lit_w64.asm ${_lanterns_src}/shaders/vs_lanterns_edges.asm + ${_lanterns_src}/shaders/ps_lanterns_edges.asm ${_lanterns_src}/shaders/cs_lanterns_rise.asm + ${_lanterns_src}/shaders/ps_lanterns_tex_floor.asm + ${_lanterns_src}/shaders/ps_lanterns_tex_solid.asm + ${_lanterns_src}/shaders/ps_lanterns_shadow.asm ${_lanterns_src}/shaders/cs_lanterns_bloom_h.asm + ${_lanterns_src}/shaders/cs_lanterns_bloom_h_nobarrier.asm + ${_lanterns_src}/shaders/cs_lanterns_bloom_v.asm ${_lanterns_src}/shaders/vs_lanterns_full.asm + ${_lanterns_src}/shaders/ps_lanterns_composite.asm + ${_lanterns_src}/shaders/vs_lanterns_gbuf.asm ${_lanterns_src}/shaders/ps_lanterns_gbuf.asm + ${_lanterns_src}/shaders/cs_lanterns_tiled.asm) + get_filename_component(_lanterns_spirv_tools ${LEONIDA_SPIRV_AS} DIRECTORY) + file(TO_NATIVE_PATH "${_lanterns_spirv_tools}" _lanterns_spirv_tools) + add_custom_command( + OUTPUT ${LEONIDA_LANTERNS_SHADERS}/spirv/index.json + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_LANTERNS_SHADERS} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${_lanterns_spirv_tools}" + $ -I ${_lanterns_src}/fssm_pack.py + ${LEONIDA_LANTERNS_SHADERS} ${_lanterns_asm} --translate --wave64-emulate + DEPENDS ${_lanterns_asm} ${_lanterns_src}/fssm_pack.py ${_lanterns_tool_py} + COMMENT "Packing and translating the Lanterns shaders" + VERBATIM) + add_custom_target(lanterns_shaders DEPENDS ${LEONIDA_LANTERNS_SHADERS}/spirv/index.json) + add_dependencies(lanterns lanterns_shaders) + if(CMAKE_HOST_WIN32 AND NOT CMAKE_CROSSCOMPILING) + # One test per stage (the runner gives each its own output folder under --out). + foreach(_stage 1 3 5 6 8 9) + add_test(NAME lanterns_stage${_stage} + COMMAND $ -I ${_lanterns_src}/run_lanterns.py + --gta6rt $ --guest $ + --shaders ${LEONIDA_LANTERNS_SHADERS} --out ${CMAKE_CURRENT_BINARY_DIR}/lanterns_out + --stage ${_stage}) + set_tests_properties(lanterns_stage${_stage} PROPERTIES TIMEOUT 300) + endforeach() + endif() + else() + message(STATUS "llvm-mc (set LLVM_MC), spirv-as or Python 3 not found: lanterns.exe builds without its shaders") + endif() +endif() diff --git a/runtime/test/lanterns/lanterns.cpp b/runtime/test/lanterns/lanterns.cpp new file mode 100644 index 0000000000..d4b3778c8f --- /dev/null +++ b/runtime/test/lanterns/lanterns.cpp @@ -0,0 +1,692 @@ +// Lanterns: an original stand-in title that runs under gta6rt --run and drives the whole chain a real title would: +// an x64 PE the loader maps, imports the loader's shims answer, the Xbox D3D12 device on Vulkan +// (D3D12XboxCreateDevice from d3d12_xs.dll, LEONIDA_D3D12=vulkan), pipelines from shader containers holding RDNA2 +// programs (DXBC { DXIL { XDAT { XBCH + zlib(FSSM) } } }, packed by fssm_pack.py beside this file, translated offline by +// fssm_unpack.py, shader_disasm.py and rdna2spirv.py; the layer finds each by the SHA-256 of its FSSM program), draws, +// compute, and readbacks checked against a CPU reference. Content: abstract solids on a checkered floor and rising +// points of light, colours from short binary fractions; no game data. How to build and run it: lanterns.cmake. +// +// lanterns.exe --stage 1|3|5|6|8|9 --shaders --out +// +// Stage 1: five DrawIndexedInstanced (hexagonal prisms, cubes, octahedra, pyramids, the floor) into a 384x256 +// R32G32B32A32_FLOAT target with a D32_FLOAT depth buffer. Vertex, index and instance buffers live in DEFAULT heaps, +// filled from an upload buffer by copies; the vertex shader reads vertices and instances through V#s in two descriptor +// tables, the model matrix and tint from root constants, the camera from a root CBV. The frame is drawn twice: with +// the depth test (the image) and without it (the negative control, which must change exactly the pixels the reference +// says it changes). +// +// Stage 3: a compute shader on a COMPUTE queue moves 256 light points (integer fixed point) and writes their instance +// records into a DEFAULT UAV buffer; the direct queue waits on the compute fence and draws them as a sixth +// DrawIndexedInstanced whose instance V# points at that buffer. Frame 1: compute submitted, then the frame. Frame 2: the +// frame is submitted first, waiting for a fence value the compute submission after it signals (the layer must hold +// it). Both frames, the state words and the instance records are compared with the CPU's simulation of the same steps; +// between the two frames the points must move exactly where the reference says. Control: frame 3 without the Wait, +// submitted before its compute work; it is reported (old state, new state or a mix), not required, since a layer may +// order the queues on its own. +// +// Stage 5: the stage-3 frame after two rounds of rise steps (the points drawn directly, their instances written by +// the compute shader) into an R16G16B16A16_FLOAT target, then a +// post-process on the same direct queue (lanterns_post.h): two compute passes (wave32 rows, wave64 columns), each 128 +// lanes in several waves sharing LDS across an s_barrier, blur what is brighter than a threshold along rows (reading the scene through a T# +// with image_load) and then columns; a fullscreen pixel shader reads SV_Position, the scene texel and the blur, and +// writes the sum into an R32G32B32A32_FLOAT target. The fp16 scene and the final frame are compared with the CPU +// (exact where certain, within bounds where the scene's edges leave it uncertain). Control: the composite with the +// blur skipped must change exactly the certain pixels the reference says the bloom changes. The row pass without its +// s_barrier is run too and its difference reported (a race: not predicted). +// +// Stage 6: the stage-1 scene textured. A BC1 mosaic (256x256, 9 mips) on the floor, sampled with image_sample +// (trilinear, LOD from derivatives); a BC7 pattern (64x64, 7 mips) on the solids, sampled with image_sample_l at a +// per-draw mip level from a root constant. The textures are made, mipmapped and compressed here (lanterns_bc.h) and +// uploaded with CopyTextureRegion per level; the reference decodes them and bounds every pixel (lanterns_sampling.h). +// Control: the solids two mip levels down must leave the main bounds wherever the two references cannot overlap. +// +// Stage 8: shadows. A depth-only pass (no render target, depth bias from the PSO) draws the solids from a directional +// light into a 512x512 D32 shadow map; the main pass's pixel shader takes four comparison samples (LESS_EQUAL, 2x2 PCF) +// and scales the face colour by the lit fraction (lanterns_shadow.h). Control: the map left cleared to 1 must change +// exactly the pixels the reference says are shadowed. +// +// Stage 9: deferred lighting. A G-buffer pass writes three render targets (RGBA8 albedo, RGB10A2 normal, R32F view +// depth); a compute pass, one 16x16 workgroup per tile, builds each tile's light list in LDS with atomics and shades +// with 256 point lights in integers (lanterns_deferred.h). Controls: culling off must give the same image bit for bit; +// one light moved must change exactly the pixels the reference predicts. +// +// On success the guest prints one line starting "Lanterns stage N: PASS" and exits 0; run_lanterns.py checks that +// line, the exit code and the device line. +#include "lanterns_edges_gpu.h" +#include "lanterns_gpu.h" +#include "lanterns_particles.h" +#include "lanterns_post.h" +#include "lanterns_post_gpu.h" +#include "lanterns_reference.h" +#include "lanterns_sampling.h" +#include "lanterns_scene.h" +#include "lanterns_shadow.h" +#include "lanterns_deferred_gpu.h" +#include "lanterns_textures_gpu.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using lanterns::Color; +using lanterns::kHeight; +using lanterns::kWidth; + +bool write_file(const std::filesystem::path& path, const void* data, std::size_t size) { + std::ofstream out(path, std::ios::binary); + out.write(static_cast(data), std::streamsize(size)); + return bool(out); +} + +// Writes /.gpu.rgba32f, .ref.rgba32f and .uncertain.u8 (one byte per pixel: 0 = compare the two exactly, +// 1 = uncertain, 2 = out of bounds, 3 = within bounds), which run_lanterns.py turns into PNGs. states, when given, +// replaces the bytes the reference's candidates make (0 or 1). +bool dump(const std::filesystem::path& out, const char* name, const std::vector& gpu, + const lanterns::Reference& ref, const std::vector* states = nullptr) { + std::vector uncertain(gpu.size()); + for (std::size_t i = 0; i < gpu.size(); ++i) uncertain[i] = ref.candidates[i].empty() ? 0 : 1; + if (states) uncertain = *states; + const std::string base = (out / name).string(); + const bool ok = write_file(base + ".gpu.rgba32f", gpu.data(), gpu.size() * sizeof(Color)) && + write_file(base + ".ref.rgba32f", ref.color.data(), ref.color.size() * sizeof(Color)) && + write_file(base + ".uncertain.u8", uncertain.data(), uncertain.size()); + if (!ok) std::fprintf(stderr, "lanterns: cannot write %s.*\n", base.c_str()); + return ok; +} + +void report(const char* what, const lanterns::Comparison& c) { + std::printf("lanterns: %s: %u of %u certain pixels exact, %u of %u uncertain pixels one of their candidates\n", + what, c.certain_exact, c.certain, c.uncertain_plausible, c.uncertain); + if (!c.pass()) + std::printf("lanterns: %s: first bad pixel (%u, %u): gpu (%g, %g, %g, %g), reference (%g, %g, %g, %g)\n", what, + c.first_bad_x, c.first_bad_y, c.first_bad_gpu[0], c.first_bad_gpu[1], c.first_bad_gpu[2], + c.first_bad_gpu[3], c.first_bad_ref[0], c.first_bad_ref[1], c.first_bad_ref[2], c.first_bad_ref[3]); +} + +// Pixels certain in both references whose expected colours differ, and how many of those differ on the GPU too. +struct Change { + unsigned expected = 0, changed = 0; +}; +Change changes(const std::vector& a, const lanterns::Reference& ra, const std::vector& b, + const lanterns::Reference& rb) { + Change c; + for (std::size_t i = 0; i < a.size(); ++i) { + if (!ra.candidates[i].empty() || !rb.candidates[i].empty()) continue; + if (lanterns::detail::same(ra.color[i], rb.color[i])) continue; + ++c.expected; + c.changed += !lanterns::detail::same(a[i], b[i]); + } + return c; +} + +int stage1(const std::filesystem::path& shader_dir, const std::filesystem::path& out_dir) { + const lanterns::Scene scene = lanterns::stage1(); + lanterns::Shaders shaders; + lanterns::EdgeShaders edge_shaders; + if (!lanterns::load_shaders(shader_dir, 1, shaders) || !lanterns::load_edge_shaders(shader_dir, edge_shaders)) return 1; + std::vector with_depth, without_depth, edges; + { + lanterns::Gpu gpu; + if (!gpu.create(scene, shaders)) return 1; + if (!gpu.submit_frame(scene, true) || !gpu.finish_frame(with_depth)) return 1; + if (!gpu.submit_frame(scene, false) || !gpu.finish_frame(without_depth)) return 1; + lanterns::EdgeDraw edge_draw; + if (!edge_draw.create(gpu, edge_shaders) || !edge_draw.run(edges)) return 1; + if (!gpu.idle()) return 1; + } + // The shared edges: every pixel exact (red = which triangles drew it, green and alpha = how many times). + const lanterns::EdgeReference edge_ref = lanterns::edge_reference(); + unsigned edge_exact = 0, edge_on_ok = 0, edge_twice = 0, edge_gap = 0; + for (std::size_t i = 0; i < edges.size(); ++i) { + const bool ok = lanterns::detail::same(edges[i], edge_ref.color[i]); + edge_exact += ok; + edge_twice += edges[i][1] > 1.0f; + edge_gap += edge_ref.color[i][1] == 1.0f && edges[i][1] == 0.0f; + if (!ok && edges.size() - edge_exact <= 3) + std::printf("lanterns: shared edges, pixel (%zu, %zu): gpu (%g %g %g %g) want (%g %g %g %g)\n", + i % lanterns::kWidth, i / lanterns::kWidth, edges[i][0], edges[i][1], edges[i][2], edges[i][3], + edge_ref.color[i][0], edge_ref.color[i][1], edge_ref.color[i][2], edge_ref.color[i][3]); + } + for (unsigned y = 0; y < lanterns::kHeight; ++y) + for (unsigned x = 0; x < lanterns::kWidth; ++x) { + const long long px = 2 * x + 1, py = 2 * y + 1; + bool on = false; + for (unsigned k = 0; k < lanterns::kEdgeTriangles && !on; ++k) { + const long long dx = lanterns::kEdgeRing[k][0] - lanterns::kEdgeCentre[0], + dy = lanterns::kEdgeRing[k][1] - lanterns::kEdgeCentre[1]; + const long long qx = px - lanterns::kEdgeCentre[0], qy = py - lanterns::kEdgeCentre[1]; + const long long t = qx * dx + qy * dy; + on = qx * dy - qy * dx == 0 && t >= 0 && t < dx * dx + dy * dy; + } + const std::size_t i = std::size_t(y) * lanterns::kWidth + x; + edge_on_ok += on && lanterns::detail::same(edges[i], edge_ref.color[i]); + } + { // The picture: each triangle's own colour from the bits the GPU (and the CPU) summed; white twice, black none. + const auto shown_of = [](const Color& c) { + static constexpr float palette[8][3] = {{0.9f, 0.3f, 0.2f}, {0.9f, 0.7f, 0.2f}, {0.5f, 0.8f, 0.3f}, + {0.2f, 0.7f, 0.6f}, {0.2f, 0.5f, 0.9f}, {0.5f, 0.3f, 0.9f}, + {0.8f, 0.3f, 0.7f}, {0.6f, 0.6f, 0.6f}}; + if (c[1] == 0.0f) return Color{0, 0, 0, 1}; + if (c[1] != 1.0f) return Color{1, 1, 1, 1}; + const unsigned k = unsigned(std::log2(std::max(1.0f, c[0]))) & 7u; + return Color{palette[k][0], palette[k][1], palette[k][2], 1}; + }; + std::vector shown_gpu(edges.size()); + lanterns::Reference shown_ref; + shown_ref.color.resize(edges.size()); + shown_ref.candidates.resize(edges.size()); + for (std::size_t i = 0; i < edges.size(); ++i) + shown_gpu[i] = shown_of(edges[i]), shown_ref.color[i] = shown_of(edge_ref.color[i]); + if (!dump(out_dir, "stage1-edges", shown_gpu, shown_ref)) return 1; + } + std::printf("lanterns: shared edges (wave64 VS and PS, root table at s8): %u of %u pixels exact; %u of %u pixel " + "centres exactly on an inner edge drawn once by the triangle the top-left rule names; %u pixels drawn " + "twice, %u gaps\n", edge_exact, unsigned(edges.size()), edge_on_ok, edge_ref.on_shared, edge_twice, + edge_gap); + const lanterns::Reference ref_on = lanterns::reference_frame(scene, true); + const lanterns::Reference ref_off = lanterns::reference_frame(scene, false); + const auto on = lanterns::compare(with_depth, ref_on), off = lanterns::compare(without_depth, ref_off); + report("depth test on", on); + report("depth test off (negative control)", off); + const Change control = changes(with_depth, ref_on, without_depth, ref_off); + std::printf("lanterns: the depth test changes %u certain pixels (the reference expects %u); %u faces edge-on\n", + control.changed, control.expected, ref_on.degenerate_faces); + std::printf("lanterns: %u pixels lie on an edge two faces of one solid share: one of the two must show there, not " + "what is behind them\n", ref_on.shared_edge_pixels); + if (!dump(out_dir, "stage1-depth", with_depth, ref_on) || !dump(out_dir, "stage1-nodepth", without_depth, ref_off)) + return 1; + if (!on.pass() || !off.pass() || control.expected < 1000 || control.changed != control.expected || + edge_exact != edges.size() || edge_on_ok != edge_ref.on_shared || edge_ref.on_shared < 500 || + edge_ref.covered < 50000) { + std::fprintf(stderr, "lanterns: stage 1 FAILED\n"); + return 1; + } + // Printed only here, after every check: run_lanterns.py wants this line once and exit code 0. + std::printf("Lanterns stage 1: PASS, %u of %u pixels exact, %u edge pixels plausible, depth-off control changed " + "%u pixels; shared edges through a wave64 VS/PS with the title's s8 table: %u of %u pixels exact, %u " + "centres on shared edges each drawn once\n", on.certain_exact, kWidth * kHeight, on.uncertain_plausible, + control.changed, edge_exact, unsigned(edges.size()), edge_on_ok); + return 0; +} + +// The GPU's state words and instance records against the CPU's simulation; prints the first difference. +bool same_particles(const char* what, const std::vector& state, + const std::vector& instances, const std::vector& want) { + const auto want_instances = lanterns::particle_instances(want); + unsigned bad_state = 0, bad_instances = 0; + for (unsigned i = 0; i < lanterns::kParticles; ++i) { + bad_state += std::memcmp(&state[i], &want[i], sizeof(lanterns::Particle)) != 0; + bad_instances += std::memcmp(&instances[i], &want_instances[i], sizeof(lanterns::Instance)) != 0; + } + std::printf("lanterns: %s: %u of %u point states and %u of %u instance records equal the CPU's\n", what, + lanterns::kParticles - bad_state, lanterns::kParticles, lanterns::kParticles - bad_instances, + lanterns::kParticles); + return !bad_state && !bad_instances; +} + +int stage3(const std::filesystem::path& shader_dir, const std::filesystem::path& out_dir) { + using lanterns::kStepsPerFrame; + std::vector cpu = lanterns::initial_particles(); + std::vector> cpu_after; // after 1, 2 and 3 frames' worth of steps + for (int f = 0; f < 3; ++f) { + for (unsigned k = 0; k < kStepsPerFrame; ++k) lanterns::step_particles(cpu); + cpu_after.push_back(cpu); + } + const lanterns::Scene scene1 = lanterns::stage3(cpu_after[0]), scene2 = lanterns::stage3(cpu_after[1]), + scene3 = lanterns::stage3(cpu_after[2]); + lanterns::Shaders shaders; + if (!lanterns::load_shaders(shader_dir, 3, shaders)) return 1; + std::vector frame1, frame2, frame3; + lanterns::Readback read1, read2; + { + lanterns::Gpu gpu; + if (!gpu.create(scene1, shaders)) return 1; + std::uint64_t signalled = 0; + // Frame 1: the compute work first, then the frame that waits for it. + if (!gpu.submit_compute(kStepsPerFrame, signalled) || !gpu.submit_frame(scene1, true, signalled) || + !gpu.finish_frame(frame1, &read1)) + return 1; + // Frame 2: the frame first, waiting for the value the compute submission after it will signal. + const std::uint64_t next = gpu.next_compute_value(); + if (!gpu.submit_frame(scene2, true, next) || !gpu.submit_compute(kStepsPerFrame, signalled) || signalled != next || + !gpu.finish_frame(frame2, &read2)) + return 1; + // Control: the same order without the Wait. + if (!gpu.submit_frame(scene3, true, 0) || !gpu.submit_compute(kStepsPerFrame, signalled) || + !gpu.finish_frame(frame3) || !gpu.idle()) + return 1; + } + const bool particles1 = + same_particles("frame 1 (compute, then the frame)", read1.state, read1.instances, cpu_after[0]); + const bool particles2 = same_particles("frame 2 (the frame waits for compute submitted after it)", read2.state, + read2.instances, cpu_after[1]); + const bool particles_ok = particles1 && particles2; + const lanterns::Reference ref1 = lanterns::reference_frame(scene1, true); + const lanterns::Reference ref2 = lanterns::reference_frame(scene2, true); + const lanterns::Reference ref3 = lanterns::reference_frame(scene3, true); + const auto c1 = lanterns::compare(frame1, ref1), c2 = lanterns::compare(frame2, ref2); + report("frame 1", c1); + report("frame 2", c2); + const Change moved = changes(frame1, ref1, frame2, ref2); + std::printf("lanterns: between the frames the points changed %u certain pixels (the reference expects %u)\n", + moved.changed, moved.expected); + // The control, reported only: did the frame without the Wait show the new points, the old ones, or a mix? + const auto as_new = lanterns::compare(frame3, ref3), as_old = lanterns::compare(frame3, ref2); + const char* verdict = as_new.pass() ? "the new state: the layer ordered the queues without the Wait" + : as_old.pass() ? "the previous frame's state: the draw ran before the compute work" + : "neither state exactly: the draw and the compute work overlapped"; + std::printf("lanterns: control without the Wait showed %s (%u certain pixels differ from the new state)\n", verdict, + as_new.certain - as_new.certain_exact); + if (!dump(out_dir, "stage3-frame1", frame1, ref1) || !dump(out_dir, "stage3-frame2", frame2, ref2) || + !dump(out_dir, "stage3-control", frame3, ref3)) + return 1; + if (!particles_ok || !c1.pass() || !c2.pass() || moved.expected < 50 || moved.changed != moved.expected) { + std::fprintf(stderr, "lanterns: stage 3 FAILED\n"); + return 1; + } + std::printf("Lanterns stage 3: PASS, %u and %u of %u pixels exact, %u points exact after %u and %u compute steps, " + "points moved %u pixels\n", c1.certain_exact, c2.certain_exact, kWidth * kHeight, lanterns::kParticles, + kStepsPerFrame, 2 * kStepsPerFrame, moved.changed); + return 0; +} + +// The post reference as a Reference for dump(): the exact colour (or the lower bound) and "uncertain" where bounded. +lanterns::Reference as_reference(const lanterns::PostReference& post) { + lanterns::Reference ref; + ref.color = post.lo; + ref.candidates.resize(post.lo.size()); + for (std::size_t i = 0; i < post.lo.size(); ++i) + if (!post.certain[i]) ref.candidates[i] = {post.lo[i], post.hi[i]}; + return ref; +} + +// Stage 5: the stage-3 frame into an fp16 target, then the bloom post-process (see the top of this file). +int stage5(const std::filesystem::path& shader_dir, const std::filesystem::path& out_dir) { + using lanterns::kStepsPerFrame; + std::vector cpu = lanterns::initial_particles(); + for (unsigned k = 0; k < 2 * kStepsPerFrame; ++k) lanterns::step_particles(cpu); + const lanterns::Scene scene = lanterns::stage3(cpu); + lanterns::Shaders shaders; + lanterns::PostShaders post_shaders; + if (!lanterns::load_shaders(shader_dir, 5, shaders) || !lanterns::load_post_shaders(shader_dir, post_shaders)) return 1; + std::vector scene_pixels, final_pixels, skipped, no_barrier; + lanterns::Readback read; + { + lanterns::Gpu gpu; + if (!gpu.create(scene, shaders, DXGI_FORMAT_R16G16B16A16_FLOAT)) return 1; + lanterns::Post post; // after gpu: released first + if (!post.create(gpu, post_shaders)) return 1; + std::uint64_t first = 0, second = 0; + if (!gpu.submit_compute(kStepsPerFrame, first) || !gpu.submit_compute(kStepsPerFrame, second) || + !gpu.submit_frame(scene, true, second) || !gpu.finish_frame(scene_pixels, &read)) + return 1; + if (!post.run(lanterns::PostMode::full, final_pixels) || !post.run(lanterns::PostMode::skip_blur, skipped) || + !post.run(lanterns::PostMode::no_barrier, no_barrier) || !gpu.idle()) + return 1; + } + const bool particles_ok = same_particles("the points after two rounds of rise steps", read.state, read.instances, cpu); + const lanterns::Reference ref = lanterns::reference_frame(scene, true); + const lanterns::Reference half = lanterns::half_reference(ref); + const lanterns::Comparison scene_check = lanterns::compare(scene_pixels, half); + report("the fp16 scene target", scene_check); + const lanterns::PostReference post = lanterns::post_reference(ref); + const lanterns::Comparison final_check = lanterns::compare_post(final_pixels, post); + std::printf("lanterns: the final frame: %u of %u certain pixels exact, %u of %u bounded pixels within their bounds " + "(the reference's float and double sums differ at %u values)\n", final_check.certain_exact, + final_check.certain, final_check.uncertain_plausible, final_check.uncertain, post.inexact); + if (!final_check.pass()) + report("the final frame", final_check); + const unsigned control = lanterns::certain_differences(skipped, post); + const unsigned misplaced = lanterns::misplaced_differences(skipped, post); + const unsigned race = lanterns::certain_differences(no_barrier, post); + std::printf("lanterns: control, the blur skipped: %u certain pixels differ (the reference predicts %u), %u of them " + "or of the predicted ones in the wrong place\n", control, post.bloom_pixels, misplaced); + std::printf("lanterns: measured, the row pass without s_barrier: %u certain pixels differ\n", race); + if (!dump(out_dir, "stage5-scene", scene_pixels, half) || + !dump(out_dir, "stage5-final", final_pixels, as_reference(post)) || + !dump(out_dir, "stage5-skipped", skipped, as_reference(post)) || + !dump(out_dir, "stage5-nobarrier", no_barrier, as_reference(post))) + return 1; + if (!particles_ok || !scene_check.pass() || !final_check.pass() || post.inexact || + post.bloom_pixels < 1000 || control != post.bloom_pixels || misplaced != 0) { + std::fprintf(stderr, "lanterns: stage 5 FAILED\n"); + return 1; + } + std::printf("Lanterns stage 5: PASS, fp16 scene %u of %u certain pixels exact, bloom composite %u of %u certain " + "pixels exact and %u bounded pixels within bounds, skipping the blur changed %u pixels as predicted\n", + scene_check.certain_exact, scene_check.certain, final_check.certain_exact, final_check.certain, + final_check.uncertain, control); + return 0; +} + +// Stage 6: the stage-1 scene with compressed, mipmapped textures (see the top of this file). +int stage6(const std::filesystem::path& shader_dir, const std::filesystem::path& out_dir) { + lanterns::Shaders shaders; + if (!lanterns::load_shaders(shader_dir, 6, shaders)) return 1; + const lanterns::BcTexture mosaic = lanterns::make_texture(lanterns::mosaic_pattern(), lanterns::BcFormat::bc1); + const lanterns::BcTexture squares = lanterns::make_texture(lanterns::squares_pattern(), lanterns::BcFormat::bc7); + const lanterns::Scene scene = lanterns::stage6(); + lanterns::Scene control = scene; // every solid two mip levels further down + for (unsigned d = 0; d < 4; ++d) control.draws[d].tint[3] += 2.0f; + std::vector frame, control_frame; + { + lanterns::Gpu gpu; + if (!gpu.create(scene, shaders)) return 1; + lanterns::Ref floor_tex, solid_tex; // after gpu: released first + if (!lanterns::upload_texture(gpu.device(), gpu.queue(), mosaic, floor_tex) || + !lanterns::upload_texture(gpu.device(), gpu.queue(), squares, solid_tex) || + !gpu.bind_textures(floor_tex.p, solid_tex.p)) + return 1; + std::printf("lanterns: textures: BC1 %ux%u with %zu mips, BC7 %ux%u with %zu mips, uploaded by " + "CopyTextureRegion per level\n", mosaic.width, mosaic.height, mosaic.blocks.size(), squares.width, + squares.height, squares.blocks.size()); + if (!gpu.submit_frame(scene, true, 0) || !gpu.finish_frame(frame) || + !gpu.submit_frame(control, true, 0) || !gpu.finish_frame(control_frame) || !gpu.idle()) + return 1; + } + const lanterns::TexturedReference ref = lanterns::textured_reference(scene, {&mosaic, &squares, 0.0f}); + const lanterns::TexturedReference ctl = lanterns::textured_reference(scene, {&mosaic, &squares, 2.0f}); + const lanterns::Comparison c = lanterns::compare_textured(frame, ref); + std::printf("lanterns: textured frame: %u of %u certain pixels within their bounds, %u of %u uncertain pixels " + "within their candidates' bounds\n", c.certain_exact, c.certain, c.uncertain_plausible, c.uncertain); + if (!c.pass()) report("textured frame", c); + // The control: wherever the references for LOD and LOD + 2 cannot overlap, the control frame must leave the + // main frame's bounds, and it must stay inside its own. + const auto predicted = lanterns::disjoint(ref, ctl); + unsigned expected = 0, moved = 0; + for (std::size_t i = 0; i < predicted.size(); ++i) { + expected += predicted[i]; + moved += predicted[i] && !lanterns::within(control_frame[i], ref.bounds[i]); + } + const lanterns::Comparison own = lanterns::compare_textured(control_frame, ctl); + std::printf("lanterns: control, the solids two mips down: %u of %u predicted pixels left the bounds; the control " + "frame is within its own bounds at %u of %u certain pixels\n", moved, expected, own.certain_exact, + own.certain); + // The dumps: the reference panel is the middle of each pixel's bounds; the mask is grey within bounds, yellow + // where coverage is uncertain, red outside the bounds (for the control: where it left them, as predicted). + lanterns::Reference shown; + shown.color.resize(ref.bounds.size()); + shown.candidates.resize(ref.bounds.size()); + std::vector states(ref.bounds.size()), control_states(ref.bounds.size()); + for (std::size_t i = 0; i < states.size(); ++i) { + for (int k = 0; k < 4; ++k) shown.color[i][k] = (ref.bounds[i].lo[k] + ref.bounds[i].hi[k]) / 2; + states[i] = !ref.certain[i] ? 1 : lanterns::within(frame[i], ref.bounds[i]) ? 3 : 2; + control_states[i] = !ref.certain[i] ? 1 : lanterns::within(control_frame[i], ref.bounds[i]) ? 3 : 2; + } + if (!dump(out_dir, "stage6-frame", frame, shown, &states) || + !dump(out_dir, "stage6-control", control_frame, shown, &control_states)) + return 1; + if (!c.pass() || !own.pass() || expected < 1000 || moved != expected) { + std::fprintf(stderr, "lanterns: stage 6 FAILED\n"); + return 1; + } + std::printf("Lanterns stage 6: PASS, %u of %u certain pixels within the BC1/BC7 sampling bounds (trilinear floor, " + "image_sample_l solids), control two mips down moved %u of %u predicted pixels\n", c.certain_exact, + c.certain, moved, expected); + return 0; +} + +// Stage 8: a shadow map from a directional light, sampled with 2x2 PCF (see the top of this file). +int stage8(const std::filesystem::path& shader_dir, const std::filesystem::path& out_dir) { + lanterns::Shaders shaders; + if (!lanterns::load_shaders(shader_dir, 8, shaders)) return 1; + const lanterns::Scene scene = lanterns::stage8(); + const lanterns::Light light = lanterns::make_light(); + std::vector frame, control; + { + lanterns::Gpu gpu; + if (!gpu.create(scene, shaders) || !gpu.set_light(light.clip, light.rows)) return 1; + if (!gpu.submit_frame(scene, true, 0) || !gpu.finish_frame(frame)) return 1; + gpu.set_shadow_casters(false); + if (!gpu.submit_frame(scene, true, 0) || !gpu.finish_frame(control) || !gpu.idle()) return 1; + } + const auto ref = lanterns::shadow_reference(scene, light, lanterns::shadow_map(scene, light, true)); + const auto ref_lit = lanterns::shadow_reference(scene, light, lanterns::shadow_map(scene, light, false)); + const lanterns::Comparison c = lanterns::compare_textured(frame, ref), cl = lanterns::compare_textured(control, ref_lit); + // Exact pixels: certain, with one possible colour (every tap certain), and equal to it. + unsigned exact = 0, single = 0, expected = 0, changed = 0; + for (std::size_t i = 0; i < frame.size(); ++i) { + const bool one = ref.certain[i] && lanterns::detail::same(ref.bounds[i].lo, ref.bounds[i].hi); + const bool one_lit = ref_lit.certain[i] && lanterns::detail::same(ref_lit.bounds[i].lo, ref_lit.bounds[i].hi); + single += one; + exact += one && lanterns::detail::same(frame[i], ref.bounds[i].lo); + if (one && one_lit && !lanterns::detail::same(ref.bounds[i].lo, ref_lit.bounds[i].lo)) { + ++expected; + changed += !lanterns::detail::same(frame[i], control[i]); + } + } + std::printf("lanterns: shadowed frame: %u of %u certain pixels within their bounds, %u of %u single-colour pixels " + "exact, %u of %u uncertain within bounds\n", c.certain_exact, c.certain, exact, single, + c.uncertain_plausible, c.uncertain); + if (!c.pass()) report("shadowed frame", c); + std::printf("lanterns: control, the map left cleared to 1: %u of %u certain pixels within the all-lit bounds; %u " + "pixels changed (the reference predicts %u)\n", cl.certain_exact, cl.certain, changed, expected); + // Each dump with its own reference: the middle of each pixel's bounds, and per pixel 3 (one colour, matched), + // 1 (bounded, within) or 2 (outside every box). + const auto bounds_dump = [&](const char* name, const std::vector& gpu, const lanterns::TexturedReference& r) { + lanterns::Reference shown; + shown.color.resize(gpu.size()); + shown.candidates.resize(gpu.size()); + std::vector states(gpu.size()); + for (std::size_t i = 0; i < gpu.size(); ++i) { + for (int k = 0; k < 4; ++k) shown.color[i][k] = (r.bounds[i].lo[k] + r.bounds[i].hi[k]) / 2; + const bool one = r.certain[i] && lanterns::detail::same(r.bounds[i].lo, r.bounds[i].hi); + states[i] = !lanterns::within_any(r, i, gpu[i]) ? 2 : one ? 3 : 1; + } + return dump(out_dir, name, gpu, shown, &states); + }; + if (!bounds_dump("stage8-frame", frame, ref) || !bounds_dump("stage8-control", control, ref_lit)) return 1; + if (!c.pass() || !cl.pass() || exact != single || expected < 1000 || changed != expected) { + std::fprintf(stderr, "lanterns: stage 8 FAILED\n"); + return 1; + } + std::printf("Lanterns stage 8: PASS, %u of %u single-colour pixels exact and %u of %u certain pixels within bounds " + "(D32 shadow map, PSO depth bias, 2x2 PCF with comparison samples), the map cleared to far changed %u " + "pixels as predicted\n", exact, single, c.certain_exact, c.certain, changed); + return 0; +} + +// Stage 9: deferred lighting with tiled light culling (see the top of this file). +int stage9(const std::filesystem::path& shader_dir, const std::filesystem::path& out_dir) { + lanterns::Shaders shaders; + std::vector tiled; + if (!lanterns::load_shaders(shader_dir, 9, shaders) || !lanterns::load_tiled_shader(shader_dir, tiled)) return 1; + const lanterns::Scene scene = lanterns::stage9(); + const std::vector lights = lanterns::make_lights(); + // The control light: the one nearest (0, 0.5) on the floor, moved 0.875 to the right. + std::size_t moved_index = 0; + for (std::size_t i = 1; i < lights.size(); ++i) + if (std::hypot(lights[i].pos[0], lights[i].pos[2] - 0.5f) < std::hypot(lights[moved_index].pos[0], lights[moved_index].pos[2] - 0.5f)) + moved_index = i; + std::vector moved = lights; + moved[moved_index].pos[0] += 0.875f; + std::vector albedo; + std::vector culled, all, shifted, counts, counts_all, counts_shifted, lists, lists_all, lists_shifted; + std::vector normal_words; + std::vector depth; + { + lanterns::Gpu gpu; + lanterns::Deferred deferred; + if (!gpu.create(scene, shaders, DXGI_FORMAT_R8G8B8A8_UNORM) || !gpu.submit_frame(scene, true, 0) || + !gpu.finish_frame(albedo) || !deferred.create(gpu, tiled) || !deferred.read_gbuffer(normal_words, depth)) + return 1; + if (!deferred.run(lights, lanterns::deferred_constants(scene, 0), culled, counts, lists) || + !deferred.run(lights, lanterns::deferred_constants(scene, 1), all, counts_all, lists_all) || + !deferred.run(moved, lanterns::deferred_constants(scene, 0), shifted, counts_shifted, lists_shifted) || + !gpu.idle()) + return 1; + } + // Poison: every pixel word and tile count of every run, and every list entry below its tile's count, was written. + unsigned poisoned = 0; + for (const auto* v : {&culled, &all, &shifted, &counts, &counts_all, &counts_shifted}) + for (std::uint32_t w : *v) poisoned += w == lanterns::kDeferredPoison; + // The exact light sets: each tile's list holds every light the CPU says it must keep, none it must not, none twice; + // with culling off, all 256. + const auto check_lists = [&](const std::vector& cnt, const std::vector& lst, + const std::vector* states, unsigned& tiles_ok, unsigned& either) { + tiles_ok = either = 0; + for (std::size_t t = 0; t < cnt.size(); ++t) { + std::vector seen(lanterns::kLights, 0); + bool ok = cnt[t] <= lanterns::kLights; + for (std::uint32_t j = 0; ok && j < cnt[t]; ++j) { + const std::uint32_t id = lst[t * lanterns::kLights + j]; + ok = id < lanterns::kLights && !seen[id]; + if (ok) seen[id] = 1; + } + for (unsigned l = 0; ok && l < lanterns::kLights; ++l) { + const std::uint8_t want = states ? (*states)[t * lanterns::kLights + l] : 1; + either += want == 2; + if (want != 2 && seen[l] != want) ok = false; + } + tiles_ok += ok; + } + }; + const auto light_states = lanterns::tile_light_states(depth, lanterns::deferred_constants(scene, 0), lights); + const auto states_moved = lanterns::tile_light_states(depth, lanterns::deferred_constants(scene, 0), moved); + unsigned sets_ok = 0, sets_either = 0, sets_all_ok = 0, sets_moved_ok = 0, unused = 0; + check_lists(counts, lists, &light_states, sets_ok, sets_either); + check_lists(counts_all, lists_all, nullptr, sets_all_ok, unused); + check_lists(counts_shifted, lists_shifted, &states_moved, sets_moved_ok, unused); + // G-buffer probes: every certain pixel whose depth bounds are tight (no other surface may be in front), its three + // normal codes and its view depth within the bounds. + const auto gref = lanterns::gbuffer_reference(scene); + unsigned probes = 0, probes_ok = 0, beyond_fixed = 0; + double worst = 0; + for (std::size_t i = 0; i < depth.size(); ++i) { + const auto& b = gref.bounds[i]; + if (!gref.certain[i] || !(b.lo[3] > 0) || b.hi[3] - b.lo[3] > 0.01 * b.lo[3]) continue; + ++probes; + bool ok = depth[i] >= b.lo[3] && depth[i] <= b.hi[3]; + // The old fixed slack: a depth error above kPosSlack moves the rebuilt point by more than kPosSlack (the view + // ray's clip-w-1 direction is at least 1 long). + const double mid = (double(b.lo[3]) + b.hi[3]) / 2, half = (double(b.hi[3]) - b.lo[3]) / 2; + beyond_fixed += std::fabs(depth[i] - mid) > lanterns::kPosSlack; + worst = std::max(worst, std::fabs(depth[i] - mid) / half); + for (int k = 0; k < 3; ++k) { + const unsigned code = (normal_words[i] >> (10 * k)) & 1023u; + ok = ok && code >= unsigned(b.lo[k]) && code <= unsigned(b.hi[k]); + } + probes_ok += ok; + if (!ok && probes - probes_ok <= 5) + std::printf("lanterns: probe (%zu, %zu): depth %.7g want %.7g..%.7g; codes %u %u %u want [%g..%g] [%g..%g] [%g..%g]\n", + i % lanterns::kWidth, i / lanterns::kWidth, double(depth[i]), double(b.lo[3]), double(b.hi[3]), + normal_words[i] & 1023u, (normal_words[i] >> 10) & 1023u, (normal_words[i] >> 20) & 1023u, + double(b.lo[0]), double(b.hi[0]), double(b.lo[1]), double(b.hi[1]), double(b.lo[2]), double(b.hi[2])); + } + const auto albedo_ref = lanterns::albedo_reference(scene); + const auto ref = lanterns::deferred_reference(scene, lights), ref_moved = lanterns::deferred_reference(scene, moved); + const std::vector frame = lanterns::unpack_rgba8(culled), frame_moved = lanterns::unpack_rgba8(shifted); + const lanterns::Comparison ca = lanterns::compare_textured(albedo, albedo_ref); + const lanterns::Comparison c = lanterns::compare_textured(frame, ref), cm = lanterns::compare_textured(frame_moved, ref_moved); + const auto single = [](const lanterns::TexturedReference& r, std::size_t i) { + return r.certain[i] && lanterns::detail::same(r.bounds[i].lo, r.bounds[i].hi); + }; + unsigned exact = 0, singles = 0, expected = 0, changed = 0, kept_still = 0, still = 0, same_as_all = 0; + for (std::size_t i = 0; i < frame.size(); ++i) { + same_as_all += culled[i] == all[i]; + if (!single(ref, i)) continue; + ++singles; + exact += lanterns::detail::same(frame[i], ref.bounds[i].lo); + if (!single(ref_moved, i)) continue; + if (!lanterns::detail::same(ref.bounds[i].lo, ref_moved.bounds[i].lo)) { + ++expected; + changed += culled[i] != shifted[i]; + } else { + ++still; + kept_still += culled[i] == shifted[i]; + } + } + std::uint64_t kept_total = 0; + unsigned kept_max = 0, empty_tiles = 0, all_full = 0; + for (std::size_t t = 0; t < counts.size(); ++t) { + kept_total += counts[t]; + kept_max = std::max(kept_max, counts[t]); + empty_tiles += counts[t] == 0; + all_full += counts_all[t] == lanterns::kLights; + } + std::printf("lanterns: G-buffer albedo (RGBA8 MRT0): %u of %u certain pixels exact, %u of %u uncertain within bounds\n", + ca.certain_exact, ca.certain, ca.uncertain_plausible, ca.uncertain); + if (!ca.pass()) report("G-buffer albedo", ca); + std::printf("lanterns: lit frame: %u of %u single-colour pixels exact, %u of %u certain pixels within bounds, %u of " + "%u uncertain within bounds\n", exact, singles, c.certain_exact, c.certain, c.uncertain_plausible, + c.uncertain); + if (!c.pass()) report("lit frame", c); + std::printf("lanterns: tiled culling kept %.1f lights per tile on average (max %u of %u, %u empty tiles); culling " + "off: %u of %zu tiles listed every light, %u of %zu pixels identical to the culled frame\n", + double(kept_total) / double(counts.size()), kept_max, lanterns::kLights, empty_tiles, all_full, + counts.size(), same_as_all, frame.size()); + std::printf("lanterns: depth slack: %u probes are off by more than the old fixed kPosSlack (%.0e), the largest error " + "is %.2f of its gradient slack, which the lighting and ray references now use\n", beyond_fixed, + lanterns::kPosSlack, worst); + std::printf("lanterns: G-buffer probes: %u of %u certain pixels with the expected 10-bit normal codes and view depth " + "(within the edge slack); exact light sets: %u of %zu tiles (%u light-tile pairs within 2e-3 of the box test either way), " + "culling off %u of %zu tiles with all 256 once, moved light %u of %zu; %u poisoned words left\n", + probes_ok, probes, sets_ok, counts.size(), sets_either, sets_all_ok, counts.size(), sets_moved_ok, + counts.size(), poisoned); + std::printf("lanterns: control, light %zu moved 0.875 right: %u of %u predicted pixels changed, %u of %u pixels " + "predicted unchanged kept; moved frame %u of %u certain pixels within its bounds\n", moved_index, + changed, expected, kept_still, still, cm.certain_exact, cm.certain); + if (!cm.pass()) report("moved-light frame", cm); + lanterns::Reference shown; + shown.color.resize(frame.size()); + shown.candidates.resize(frame.size()); + std::vector states(frame.size()); + for (std::size_t i = 0; i < frame.size(); ++i) { + for (int k = 0; k < 4; ++k) shown.color[i][k] = (ref.bounds[i].lo[k] + ref.bounds[i].hi[k]) / 2; + states[i] = !lanterns::within(frame[i], ref.bounds[i]) ? 2 : single(ref, i) ? 3 : 1; + } + if (!dump(out_dir, "stage9-frame", frame, shown, &states) || !dump(out_dir, "stage9-moved", frame_moved, shown, &states) || + !dump(out_dir, "stage9-albedo", albedo, shown)) + return 1; + if (!ca.pass() || !c.pass() || !cm.pass() || exact != singles || same_as_all != frame.size() || + all_full != counts.size() || poisoned || probes < 50000 || worst > 0.5 || probes_ok != probes || sets_ok != counts.size() || + sets_either > lanterns::kMaxEitherPairs || sets_all_ok != counts.size() || sets_moved_ok != counts.size() || expected < 500 || changed != expected || kept_still != still || + kept_total >= std::uint64_t(lanterns::kLights) * counts.size() / 2) { + std::fprintf(stderr, "lanterns: stage 9 FAILED\n"); + return 1; + } + std::printf("Lanterns stage 9: PASS, G-buffer of 3 MRTs (RGBA8 albedo %u of %u exact, RGB10A2 normal and R32F depth " + "%u of %u probes), %u of %u single-colour pixels exact through tiled culling with LDS atomics (%.1f of " + "256 lights per tile, the exact set in %u of %zu tiles, %u light-tile pairs within 2e-3 of the box test left free), " + "culling off gave the same image bit for bit " + "from poisoned buffers, one light moved changed %u of %u predicted pixels\n", + ca.certain_exact, ca.certain, probes_ok, probes, exact, singles, + double(kept_total) / double(counts.size()), sets_ok, counts.size(), sets_either, changed, expected); + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + std::setvbuf(stdout, nullptr, _IONBF, 0); // the marker reaches the launcher even if the process dies after it + int stage = 0; + std::filesystem::path shader_dir, out_dir; + for (int i = 1; i + 1 < argc; i += 2) { + const std::string key = argv[i]; + if (key == "--stage") stage = std::atoi(argv[i + 1]); + else if (key == "--shaders") shader_dir = argv[i + 1]; + else if (key == "--out") out_dir = argv[i + 1]; + } + if (shader_dir.empty() || out_dir.empty()) stage = 0; + std::error_code ec; + if (stage) std::filesystem::create_directories(out_dir, ec); + switch (stage) { + case 1: return stage1(shader_dir, out_dir); + case 3: return stage3(shader_dir, out_dir); + case 5: return stage5(shader_dir, out_dir); + case 6: return stage6(shader_dir, out_dir); + case 8: return stage8(shader_dir, out_dir); + case 9: return stage9(shader_dir, out_dir); + default: + std::fprintf(stderr, "usage: lanterns --stage 1|3|5|6|8|9 --shaders --out \n"); + return 2; + } +} diff --git a/runtime/test/lanterns/lanterns_bc.h b/runtime/test/lanterns/lanterns_bc.h new file mode 100644 index 0000000000..d423ba4e00 --- /dev/null +++ b/runtime/test/lanterns/lanterns_bc.h @@ -0,0 +1,274 @@ +// Lanterns stage 6: the textures, made here from integer formulas, mipmapped with a 2x2 box filter and compressed by +// the small encoders below: BC1 (four-colour blocks, endpoints from the block's bounding box, each texel the nearest of +// the four palette colours) and BC7 mode 6 (one subset, 7-bit RGBA endpoints with a p-bit each, 4-bit indices along +// the endpoint line). decode() is the reference decoder: BC7 as the format specifies it bit for bit; BC1's two +// interpolated colours as exact thirds, which hardware may round differently (lanterns_sampling.h's tolerance covers +// one 8-bit step). Nothing here comes from a game; the patterns are a stone mosaic and nested squares. +#pragma once + +#include "lanterns_reference.h" + +#include +#include +#include +#include +#include + +namespace lanterns { + +using Rgba8 = std::array; + +struct Image8 { + unsigned width = 0, height = 0; + std::vector texels; + const Rgba8& at(unsigned x, unsigned y) const { return texels[std::size_t(y) * width + x]; } +}; + +enum class BcFormat { bc1, bc7 }; + +// One compressed texture: every mip level's 4x4 blocks, row-major (8 bytes a block for BC1, 16 for BC7), and the +// levels decoded back to float (what the sampler reads, as the reference sees it). +struct BcTexture { + BcFormat format; + unsigned width, height; + std::vector> blocks; + std::vector> decoded; + unsigned block_bytes() const { return format == BcFormat::bc1 ? 8 : 16; } + unsigned mip_width(unsigned m) const { return std::max(1u, width >> m); } + unsigned mip_height(unsigned m) const { return std::max(1u, height >> m); } +}; + +// 256x256: 32-texel stone tiles in six muted colours with a soft diagonal shading, 2-texel dark grout between them. +inline Image8 mosaic_pattern() { + static constexpr Rgba8 stones[6] = {{{180, 170, 150, 255}}, {{150, 160, 170, 255}}, {{170, 140, 120, 255}}, + {{130, 150, 130, 255}}, {{160, 150, 175, 255}}, {{195, 185, 160, 255}}}; + Image8 img{256, 256, {}}; + for (unsigned y = 0; y < 256; ++y) + for (unsigned x = 0; x < 256; ++x) { + const unsigned tx = x / 32, ty = y / 32, lx = x % 32, ly = y % 32; + if (lx < 2 || ly < 2) { + img.texels.push_back({40, 40, 48, 255}); + continue; + } + Rgba8 c = stones[(tx * 7 + ty * 13 + (tx ^ ty)) % 6]; + const int shade = int(lx + ly) / 4 - 7; // -7..7 + for (int k = 0; k < 3; ++k) c[k] = std::uint8_t(std::clamp(int(c[k]) + 2 * shade, 0, 255)); + img.texels.push_back(c); + } + return img; +} + +// 64x64: nested squares around the centre, alternating gold and teal bands four texels wide, with a light rim. +inline Image8 squares_pattern() { + Image8 img{64, 64, {}}; + for (unsigned y = 0; y < 64; ++y) + for (unsigned x = 0; x < 64; ++x) { + const unsigned d = std::max(unsigned(std::abs(int(2 * x) - 63)), unsigned(std::abs(int(2 * y) - 63))) / 2; + const unsigned band = d / 4; + Rgba8 c = band % 2 ? Rgba8{40, 115, 125, 255} : Rgba8{235, 185, 90, 255}; + if (d % 4 == 3) c = {245, 240, 220, 255}; + img.texels.push_back(c); + } + return img; +} + +inline Image8 half_size(const Image8& in) { + Image8 out{std::max(1u, in.width / 2), std::max(1u, in.height / 2), {}}; + for (unsigned y = 0; y < out.height; ++y) + for (unsigned x = 0; x < out.width; ++x) { + const unsigned x0 = std::min(2 * x, in.width - 1), x1 = std::min(2 * x + 1, in.width - 1); + const unsigned y0 = std::min(2 * y, in.height - 1), y1 = std::min(2 * y + 1, in.height - 1); + Rgba8 c; + for (int k = 0; k < 4; ++k) + c[k] = std::uint8_t((in.at(x0, y0)[k] + in.at(x1, y0)[k] + in.at(x0, y1)[k] + in.at(x1, y1)[k] + 2) / 4); + out.texels.push_back(c); + } + return out; +} + +namespace bc { + +// The block's 16 texels (clamped at the level's edge, for levels smaller than a block). +inline std::array gather(const Image8& img, unsigned bx, unsigned by) { + std::array t; + for (unsigned i = 0; i < 16; ++i) + t[i] = img.at(std::min(bx * 4 + i % 4, img.width - 1), std::min(by * 4 + i / 4, img.height - 1)); + return t; +} + +inline int distance2(const Rgba8& a, const Rgba8& b, int channels) { + int d = 0; + for (int k = 0; k < channels; ++k) d += (int(a[k]) - int(b[k])) * (int(a[k]) - int(b[k])); + return d; +} + +// ---- BC1 +inline std::uint16_t pack565(const Rgba8& c) { + return std::uint16_t(((c[0] * 31 + 127) / 255) << 11 | ((c[1] * 63 + 127) / 255) << 5 | ((c[2] * 31 + 127) / 255)); +} +inline Rgba8 unpack565(std::uint16_t v) { + const unsigned r = v >> 11, g = (v >> 5) & 63, b = v & 31; + return {std::uint8_t(r << 3 | r >> 2), std::uint8_t(g << 2 | g >> 4), std::uint8_t(b << 3 | b >> 2), 255}; +} +// The four palette colours as floats; colours 2 and 3 are the exact thirds. +inline std::array bc1_palette(std::uint16_t c0, std::uint16_t c1) { + const Rgba8 a = unpack565(c0), b = unpack565(c1); + std::array p; + for (int k = 0; k < 3; ++k) { + p[0][k] = a[k] / 255.0f; + p[1][k] = b[k] / 255.0f; + p[2][k] = float((2.0 * a[k] + b[k]) / 3.0 / 255.0); + p[3][k] = float((a[k] + 2.0 * b[k]) / 3.0 / 255.0); + } + for (auto& c : p) c[3] = 1.0f; + return p; +} + +inline void encode_bc1(const std::array& t, std::uint8_t out[8]) { + Rgba8 lo{255, 255, 255, 255}, hi{0, 0, 0, 255}; + for (const Rgba8& c : t) + for (int k = 0; k < 3; ++k) lo[k] = std::min(lo[k], c[k]), hi[k] = std::max(hi[k], c[k]); + std::uint16_t c0 = pack565(hi), c1 = pack565(lo); + std::uint32_t indices = 0; + if (c0 == c1) { + c1 = c0 ? std::uint16_t(c0 - 1) : 0; // keep four-colour mode (c0 > c1); every texel takes c0 + if (c0 == 0) c0 = 1, c1 = 0; + if (pack565(hi) == 0) indices = 0x55555555u; // black: index 1 is the 0 endpoint + } else { + Rgba8 pal[4]; + const Rgba8 a = unpack565(c0), b = unpack565(c1); + for (int k = 0; k < 3; ++k) { + pal[0][k] = a[k], pal[1][k] = b[k]; + pal[2][k] = std::uint8_t((2 * a[k] + b[k] + 1) / 3), pal[3][k] = std::uint8_t((a[k] + 2 * b[k] + 1) / 3); + } + for (unsigned i = 0; i < 16; ++i) { + unsigned best = 0; + for (unsigned p = 1; p < 4; ++p) + if (distance2(t[i], pal[p], 3) < distance2(t[i], pal[best], 3)) best = p; + indices |= best << (2 * i); + } + } + out[0] = std::uint8_t(c0), out[1] = std::uint8_t(c0 >> 8), out[2] = std::uint8_t(c1), out[3] = std::uint8_t(c1 >> 8); + for (int k = 0; k < 4; ++k) out[4 + k] = std::uint8_t(indices >> (8 * k)); +} + +inline void decode_bc1(const std::uint8_t* b, Color out[16]) { + const std::uint16_t c0 = std::uint16_t(b[0] | b[1] << 8), c1 = std::uint16_t(b[2] | b[3] << 8); + const auto pal = bc1_palette(c0, c1); // the encoder always writes c0 > c1: four-colour mode + const std::uint32_t idx = std::uint32_t(b[4]) | std::uint32_t(b[5]) << 8 | std::uint32_t(b[6]) << 16 | + std::uint32_t(b[7]) << 24; + for (unsigned i = 0; i < 16; ++i) out[i] = pal[(idx >> (2 * i)) & 3]; +} + +// ---- BC7 mode 6 +constexpr int kWeights4[16] = {0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64}; + +struct Bits { + std::uint8_t* out; + unsigned at = 0; + void put(unsigned value, unsigned count) { + for (unsigned i = 0; i < count; ++i, ++at) + if (value >> i & 1) out[at / 8] |= std::uint8_t(1u << (at % 8)); + } +}; + +inline unsigned get_bits(const std::uint8_t* in, unsigned& at, unsigned count) { + unsigned v = 0; + for (unsigned i = 0; i < count; ++i, ++at) v |= unsigned(in[at / 8] >> (at % 8) & 1) << i; + return v; +} + +// An endpoint as 7 bits per channel and one p-bit: the 8-bit value is (c7 << 1) | p. +inline void quantize_endpoint(const Rgba8& c, std::array& c7, unsigned& p) { + unsigned odd = 0; + for (int k = 0; k < 4; ++k) odd += c[k] & 1; + p = odd >= 2 ? 1 : 0; + for (int k = 0; k < 4; ++k) c7[k] = unsigned(std::clamp((int(c[k]) - int(p) + 1) / 2, 0, 127)); +} + +inline void encode_bc7(const std::array& t, std::uint8_t out[16]) { + Rgba8 lo{255, 255, 255, 255}, hi{0, 0, 0, 0}; + for (const Rgba8& c : t) + for (int k = 0; k < 4; ++k) lo[k] = std::min(lo[k], c[k]), hi[k] = std::max(hi[k], c[k]); + std::array e7[2]; + unsigned pbit[2]; + quantize_endpoint(lo, e7[0], pbit[0]); + quantize_endpoint(hi, e7[1], pbit[1]); + int e[2][4]; + for (int s = 0; s < 2; ++s) + for (int k = 0; k < 4; ++k) e[s][k] = int(e7[s][k] << 1 | pbit[s]); + unsigned idx[16]; + for (unsigned i = 0; i < 16; ++i) { + unsigned best = 0; + int best_d = 1 << 30; + for (unsigned w = 0; w < 16; ++w) { + Rgba8 c; + for (int k = 0; k < 4; ++k) + c[k] = std::uint8_t(((64 - kWeights4[w]) * e[0][k] + kWeights4[w] * e[1][k] + 32) >> 6); + const int d = distance2(t[i], c, 4); + if (d < best_d) best_d = d, best = w; + } + idx[i] = best; + } + if (idx[0] >= 8) { // the anchor index has no top bit: swap the endpoints and mirror the indices + std::swap(e7[0], e7[1]); + std::swap(pbit[0], pbit[1]); + for (unsigned& i : idx) i = 15 - i; + } + std::fill(out, out + 16, std::uint8_t(0)); + Bits bits{out}; + bits.put(1u << 6, 7); // mode 6 + for (int k = 0; k < 4; ++k) bits.put(e7[0][k], 7), bits.put(e7[1][k], 7); + bits.put(pbit[0], 1); + bits.put(pbit[1], 1); + for (unsigned i = 0; i < 16; ++i) bits.put(idx[i], i ? 4 : 3); +} + +inline void decode_bc7(const std::uint8_t* in, Color out[16]) { + unsigned at = 7; // the encoder writes mode 6 only + int e[2][4]; + for (int k = 0; k < 4; ++k) e[0][k] = int(get_bits(in, at, 7)), e[1][k] = int(get_bits(in, at, 7)); + const unsigned p0 = get_bits(in, at, 1), p1 = get_bits(in, at, 1); + for (int k = 0; k < 4; ++k) e[0][k] = e[0][k] << 1 | int(p0), e[1][k] = e[1][k] << 1 | int(p1); + for (unsigned i = 0; i < 16; ++i) { + const unsigned w = kWeights4[get_bits(in, at, i ? 4 : 3)]; + for (int k = 0; k < 4; ++k) + out[i][k] = float(((64 - int(w)) * e[0][k] + int(w) * e[1][k] + 32) >> 6) / 255.0f; + } +} + +} // namespace bc + +// The texture of pattern (whose sides are powers of two, at least 4) with every mip level down to 1x1. +inline BcTexture make_texture(const Image8& pattern, BcFormat format) { + BcTexture tex{format, pattern.width, pattern.height, {}, {}}; + Image8 level = pattern; + for (;;) { + const unsigned bw = (level.width + 3) / 4, bh = (level.height + 3) / 4; + std::vector blocks(std::size_t(bw) * bh * tex.block_bytes()); + std::vector decoded(std::size_t(level.width) * level.height); + for (unsigned by = 0; by < bh; ++by) + for (unsigned bx = 0; bx < bw; ++bx) { + std::uint8_t* b = blocks.data() + (std::size_t(by) * bw + bx) * tex.block_bytes(); + Color texels[16]; + if (format == BcFormat::bc1) { + bc::encode_bc1(bc::gather(level, bx, by), b); + bc::decode_bc1(b, texels); + } else { + bc::encode_bc7(bc::gather(level, bx, by), b); + bc::decode_bc7(b, texels); + } + for (unsigned i = 0; i < 16; ++i) { + const unsigned x = bx * 4 + i % 4, y = by * 4 + i / 4; + if (x < level.width && y < level.height) decoded[std::size_t(y) * level.width + x] = texels[i]; + } + } + tex.blocks.push_back(std::move(blocks)); + tex.decoded.push_back(std::move(decoded)); + if (level.width == 1 && level.height == 1) break; + level = half_size(level); + } + return tex; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_d3d12.h b/runtime/test/lanterns/lanterns_d3d12.h new file mode 100644 index 0000000000..22820d2d91 --- /dev/null +++ b/runtime/test/lanterns/lanterns_d3d12.h @@ -0,0 +1,78 @@ +// Lanterns: small D3D12 helpers the GPU files share. The heap-handle calls through slots 9/10 and the V# encoding are +// ported from test/d3d12_translated_draw_test.cpp (M1.5), as lanterns_gpu.cpp first had them. +#pragma once + +#include "../d3d12_test_shaders.h" +#include "../../src/gfx10_descriptors.h" + +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "lanterns: %s:%d: %s\n", __FILE__, __LINE__, #condition); return false; } \ +} while (0) + +namespace lanterns { + +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +// The heap's first CPU handle (slot 9) and, for a shader-visible heap, its first GPU handle (slot 10). +inline std::uint64_t heap_cpu(ID3D12DescriptorHeap* heap) { + return reinterpret_cast(d3d12test::slot(heap, 9))(heap); +} +inline std::uint64_t heap_gpu(ID3D12DescriptorHeap* heap) { + return reinterpret_cast(d3d12test::slot(heap, 10))(heap); +} + +inline std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +inline std::uint64_t align(std::uint64_t v, std::uint64_t a) { return (v + a - 1) / a * a; } + +// Waits until the fence reaches value, for at most kFenceWaitMs: a lost signal or a hung GPU fails the check with a +// line saying so, instead of blocking the guest until run_lanterns.py's timeout kills it. It polls +// GetCompletedValue, so it needs no event object. +constexpr ULONGLONG kFenceWaitMs = 30000; +template +bool wait_fence(Fence& fence, UINT64 value) { + const ULONGLONG deadline = GetTickCount64() + kFenceWaitMs; + for (UINT64 now = fence->GetCompletedValue(); now < value; now = fence->GetCompletedValue()) { + if (GetTickCount64() > deadline) { + std::fprintf(stderr, "lanterns: a fence stayed at %llu for %llu ms, waiting for %llu\n", + static_cast(now), kFenceWaitMs, static_cast(value)); + return false; + } + Sleep(1); + } + return true; +} + +// A V# over records of 'stride' bytes, format 32_32_32_32_FLOAT, structured out-of-range checks (an idxen access). +inline std::array make_vsharp(std::uint64_t base, std::uint32_t stride, std::uint32_t records) { + leonida::gfx10::Buffer buffer; + buffer.address = base; + buffer.stride = stride; + buffer.num_records = records; + buffer.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT + buffer.oob_select = leonida::gfx10::OobSelect::structured; + return leonida::gfx10::encode(buffer); +} + +// A raw V# (stride 0: offen addressing checked against a byte count). +inline std::array make_raw(std::uint64_t base, std::uint32_t bytes) { + leonida::gfx10::Buffer buffer; + buffer.address = base; + buffer.num_records = bytes; + buffer.format = 77; + buffer.oob_select = leonida::gfx10::OobSelect::raw; + return leonida::gfx10::encode(buffer); +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_deferred.h b/runtime/test/lanterns/lanterns_deferred.h new file mode 100644 index 0000000000..af93681c71 --- /dev/null +++ b/runtime/test/lanterns/lanterns_deferred.h @@ -0,0 +1,321 @@ +// Lanterns stage 9: deferred lighting. A G-buffer pass writes three render targets: the albedo (RGBA8_UNORM, the +// draw's tint times the instance colour), the face normal (R10G10B10A2_UNORM, from a normal packed into the vertex's +// shade word as three 8-bit codes) and the view depth (R32_FLOAT, the clip w). A compute pass, one 16x16 workgroup per +// screen tile, rebuilds each pixel's world position from the depth, takes the tile's bounding box with LDS min/max +// atomics, keeps the point lights whose sphere meets the box in an LDS list (ds_add_rtn_u32 hands out the slots), and +// shades each pixel with the kept lights in integers: +// q = floor(64 * max(0, 1 - d^2 / r^2)) for a light the face looks towards (n . (L - p) > 0), else 0 +// out = min(255, (albedo8 * (384 + sum q * colour)) >> 12) per channel +// The sums are integers, so the order the atomics give the list does not matter: with culling off every light is in +// every list and the image must be the same, bit for bit. +// +// The CPU knows every pixel's world position up to kPosSlack (interpolation and reconstruction in float) and computes +// each light's q as an interval from it; a pixel whose intervals are all one value has one exact colour. +#pragma once + +#include "lanterns_sampling.h" + +#include +#include +#include +#include +#include + +namespace lanterns { + +constexpr unsigned kLights = 256, kTile = 16, kTilesX = kWidth / kTile, kTilesY = kHeight / kTile; +constexpr float kLightRadius2 = 1.5625f, kLightInvRadius2 = 0.64f; +constexpr float kCullRadius2 = kLightRadius2 * 1.001f + 0.001f; // the GPU's box test, a little generous +constexpr std::uint32_t kAmbient = 384, kLightShift = 12; +constexpr std::uint32_t kBackground = 0xff201010u; // r 16, g 16, b 32, a 255: where the view depth is 0 (cleared) +constexpr double kPosSlack = 5e-4; +// How far vertex snapping may move a face's plane at a pixel centre, in pixels: twice an 8-bit sub-pixel step (the +// coverage margin kMargin is eight times it). Stage 9's probes measure the real error against it (at most 0.24 of it). +constexpr double kSnapSlack = 1.0 / 128.0; +constexpr double kNormalWindow = 0.1; // the 10-bit normal codes: D3D12's 0.6 ULP conversion tolerance + +// One light as cs_lanterns_tiled reads it through a V# of stride 32. +struct PointLight { + float pos[4]; + std::uint32_t color[4]; +}; +static_assert(sizeof(PointLight) == 32); + +// 256 lights over the floor, a 16 x 16 grid with jitter, heights 0.2 to 1.0, colours 1..15 per channel. +inline std::vector make_lights() { + std::vector lights(kLights); + for (unsigned i = 0; i < kLights; ++i) { + const float jx = float(int((i * 37u) % 9u) - 4) * 0.0625f, jz = float(int((i * 23u) % 7u) - 3) * 0.0625f; + lights[i].pos[0] = -6.0f + 0.75f * float(i % 16) + 0.375f + jx; + lights[i].pos[1] = 0.2f + 0.2f * float((i * 7u) % 5u); + lights[i].pos[2] = -1.5f + 0.625f * float(i / 16) + jz; + lights[i].pos[3] = 0; + lights[i].color[0] = 1 + (i * 7u) % 15u; + lights[i].color[1] = 1 + (i * 11u) % 15u; + lights[i].color[2] = 1 + (i * 13u) % 15u; + lights[i].color[3] = 0; + } + return lights; +} + +// The compute pass's 16 root constants: eye, the ray at the centre of the view (its clip w is 1), the ray's change +// per pixel right and down, 1/r^2, the mode (0 cull, 1 every light in every tile), the box test's r^2, 0. +// The eye and rays are solved from the view-projection rows x, y and w, so they match the float matrix. +inline std::array deferred_constants(const Scene& scene, std::uint32_t mode) { + const auto& m = scene.view_projection; + const double a[3][3] = {{m[0], m[1], m[2]}, {m[4], m[5], m[6]}, {m[12], m[13], m[14]}}; + const double det = a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - + a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]) + + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]); + const auto solve = [&](const double b[3], double x[3]) { // Cramer's rule + for (int c = 0; c < 3; ++c) { + double t[3][3]; + for (int r = 0; r < 3; ++r) + for (int k = 0; k < 3; ++k) t[r][k] = k == c ? b[r] : a[r][k]; + x[c] = (t[0][0] * (t[1][1] * t[2][2] - t[1][2] * t[2][1]) - t[0][1] * (t[1][0] * t[2][2] - t[1][2] * t[2][0]) + + t[0][2] * (t[1][0] * t[2][1] - t[1][1] * t[2][0])) / det; + } + }; + const double be[3] = {-double(m[3]), -double(m[7]), -double(m[15])}, b0[3] = {0, 0, 1}, bx[3] = {1, 0, 0}, + by[3] = {0, 1, 0}; + double eye[3], d0[3], dx[3], dy[3]; + solve(be, eye), solve(b0, d0), solve(bx, dx), solve(by, dy); + std::array c{}; + for (int k = 0; k < 3; ++k) { + c[k] = float(eye[k]); + c[3 + k] = float(d0[k]); + c[6 + k] = float(dx[k] * 2.0 / kWidth); + c[9 + k] = float(-dy[k] * 2.0 / kHeight); + } + c[12] = kLightInvRadius2; + std::uint32_t bits = mode; + std::memcpy(&c[13], &bits, 4); + c[14] = kCullRadius2; + return c; +} + +// A scene for vs_lanterns_gbuf (stage 9: stage 1's): each face's outward normal packed into its vertices' shade word as an integer +// How far, per axis, the world position the compute passes rebuild from the G-buffer's view depth may be from +// site.world at the pixel centre. The depth is the clip w at the centre of a plane the rasterizer may have moved by +// up to kSnapSlack pixels (vertex snapping), so it may be off by its change over that distance (plus 1e-5 relative); +// the rebuilt p = eye + w (p - eye) / w moves along the view ray by that much. kPosSlack covers the float arithmetic. +// Before this, a fixed kPosSlack was used, which steep faces exceed (stage 9 measures how often). +inline std::array position_slack(const Scene& scene, const PixelSite& site) { + const auto& vp = scene.view_projection; + const auto clip_w = [&](double px, double py, double p[3]) { + site.world(px, py, p); + return vp[12] * p[0] + vp[13] * p[1] + vp[14] * p[2] + vp[15]; + }; + double p[3], q[3]; + const double cw = clip_w(site.px, site.py, p); + const double dw = (std::fabs(clip_w(site.px + 1, site.py, q) - cw) + std::fabs(clip_w(site.px, site.py + 1, q) - cw)) * + kSnapSlack + 1e-5 * cw; + const auto k = deferred_constants(scene, 0); + std::array out; + for (int c = 0; c < 3; ++c) out[c] = kPosSlack + dw * std::fabs(p[c] - double(k[c])) / cw; + return out; +} + +// float: three codes 128 + round(127 n), x in bits 0-7, y 8-15, z 16-23 (below 2^24, so exact). +inline std::uint32_t pack_normal(double nx, double ny, double nz) { + const double l = std::sqrt(nx * nx + ny * ny + nz * nz); + const auto code = [&](double v) { return std::uint32_t(128 + std::lround(127.0 * v / l)); }; + return code(nx) | code(ny) << 8 | code(nz) << 16; +} + +inline Scene with_packed_normals(Scene s) { + for (Mesh& mesh : s.meshes) + for (const Face& face : mesh.faces) { + double n[3] = {0, 0, 0}; + for (unsigned i = 0; i < face.count; ++i) { // Newell's method; faces are wound outward + const Vertex& a = mesh.vertices[face.v[i]]; + const Vertex& b = mesh.vertices[face.v[(i + 1) % face.count]]; + n[0] += (double(a.y) - b.y) * (double(a.z) + b.z); + n[1] += (double(a.z) - b.z) * (double(a.x) + b.x); + n[2] += (double(a.x) - b.x) * (double(a.y) + b.y); + } + const float word = float(pack_normal(n[0], n[1], n[2])); + for (unsigned i = 0; i < face.count; ++i) mesh.vertices[face.v[i]].shade = word; + } + return s; +} + +inline Scene stage9() { return with_packed_normals(stage1()); } + +// A float's UNORM code(s): one, or the two neighbours when x * max is within `window` of a rounding tie. D3D12 lets +// FLOAT -> UNORM conversion be off by 0.6 ULP (window 0.1); the albedo target is checked with a near-exact window. +inline void unorm_codes(float x, unsigned max, unsigned& lo, unsigned& hi, double window = 1e-3) { + const double v = double(x) * max, f = std::floor(v); + if (std::fabs(v - f - 0.5) < window) lo = unsigned(f), hi = unsigned(f) + 1; + else lo = hi = unsigned(std::lround(v)); +} + +namespace detail { + +struct Iv { + double lo, hi; +}; +inline Iv iv_mul(Iv a, Iv b) { + const double p[4] = {a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi}; + return {*std::min_element(p, p + 4), *std::max_element(p, p + 4)}; +} +inline Iv iv_sq(Iv a) { + if (a.lo >= 0) return {a.lo * a.lo, a.hi * a.hi}; + if (a.hi <= 0) return {a.hi * a.hi, a.lo * a.lo}; + return {0, std::max(a.lo * a.lo, a.hi * a.hi)}; +} +inline unsigned q_floor(double x) { return x <= 0 ? 0u : unsigned(std::min(64.0, std::floor(x))); } + +// The albedo codes the G-buffer holds for a site (tint times instance colour, as vs_lanterns_gbuf multiplies). +inline void albedo_codes(const PixelSite& site, unsigned lo[4], unsigned hi[4]) { + for (int k = 0; k < 4; ++k) unorm_codes(site.draw->tint[k] * site.inst->color[k], 255, lo[k], hi[k]); +} + +} // namespace detail + +// The G-buffer's albedo target (RGBA8): its bounds (codes / 255), cleared to 0. +inline TexturedReference albedo_reference(const Scene& scene) { + unsigned degenerate = 0; + const auto shade = [](const PixelSite& site, detail::Fragment& f) { + unsigned lo[4], hi[4]; + detail::albedo_codes(site, lo, hi); + for (int k = 0; k < 4; ++k) f.colors[0][k] = float(lo[k]) / 255.0f, f.colors[1][k] = float(hi[k]) / 255.0f; + f.count = 2; + }; + return resolve_bounds(detail::fragments(scene, shade, degenerate), Color{0, 0, 0, 0}); +} + +// The lit image's bounds (codes / 255): every light, as the GPU with culling off. +inline TexturedReference deferred_reference(const Scene& scene, const std::vector& lights) { + using detail::Iv; + unsigned degenerate = 0; + const auto shade = [&](const PixelSite& site, detail::Fragment& f) { + unsigned alo[4], ahi[4]; + detail::albedo_codes(site, alo, ahi); + // The normal: 8-bit code -> code / 255 in float -> a 10-bit UNORM code (or two) -> 2 f - 1. + const auto packed = std::uint32_t(site.shade); + Iv n[3]; + for (int k = 0; k < 3; ++k) { + const float f8 = float((packed >> (8 * k)) & 255u) * (1.0f / 255.0f); + unsigned lo, hi; + unorm_codes(f8, 1023, lo, hi, kNormalWindow); + n[k] = {2.0 * double(float(lo / 1023.0)) - 1.0 - 1e-6, 2.0 * double(float(hi / 1023.0)) - 1.0 + 1e-6}; + } + double w[3]; + site.world(site.px, site.py, w); + const auto slack = position_slack(scene, site); + std::uint64_t acc_lo[3] = {0, 0, 0}, acc_hi[3] = {0, 0, 0}; + for (const PointLight& light : lights) { + Iv lp[3]; + double d2_lo = 0; + for (int k = 0; k < 3; ++k) { + lp[k] = {light.pos[k] - (w[k] + slack[k]), light.pos[k] - (w[k] - slack[k])}; + d2_lo += detail::iv_sq(lp[k]).lo; + } + if (d2_lo * kLightInvRadius2 > 1.0001) continue; + double d2_hi = 0, dot_lo = 0, dot_hi = 0; + for (int k = 0; k < 3; ++k) { + d2_hi += detail::iv_sq(lp[k]).hi; + const Iv p = detail::iv_mul(n[k], lp[k]); + dot_lo += p.lo, dot_hi += p.hi; + } + if (dot_hi < -1e-5) continue; + unsigned q_lo = detail::q_floor((1.0 - d2_hi * 1.000001 * kLightInvRadius2) * 64.0 - 1e-3); + const unsigned q_hi = detail::q_floor((1.0 - d2_lo * 0.999999 * kLightInvRadius2) * 64.0 + 1e-3); + if (dot_lo <= 1e-5) q_lo = 0; + for (int c = 0; c < 3; ++c) acc_lo[c] += q_lo * light.color[c], acc_hi[c] += q_hi * light.color[c]; + } + for (int c = 0; c < 3; ++c) { + const auto out = [&](unsigned a, std::uint64_t acc) { + return float(std::min(255, (a * (kAmbient + acc)) >> kLightShift)) / 255.0f; + }; + f.colors[0][c] = out(alo[c], acc_lo[c]); + f.colors[1][c] = out(ahi[c], acc_hi[c]); + } + f.colors[0][3] = f.colors[1][3] = 1.0f; + f.count = 2; + }; + const Color background{float(kBackground & 255u) / 255.0f, float((kBackground >> 8) & 255u) / 255.0f, + float((kBackground >> 16) & 255u) / 255.0f, 1.0f}; + return resolve_bounds(detail::fragments(scene, shade, degenerate), background); +} + +// Which lights each tile must keep (1), must not keep (0) or may keep either way (2), from the view depths the GPU +// wrote (read back) and the pass's constants: the tile's box of rebuilt world positions p = eye + t (d0 + cx R + cy U) +// over its pixels with t > 0, then the squared distance from each light to the box against the box test's r^2 (k[14]), +// in double. A light within 2e-3 of the threshold is "either": the GPU forms the same numbers in float. An empty tile +// keeps nothing. Index: tile * kLights + light. At most kMaxEitherPairs pairs may be "either": the check reports how many, +// so a culling error hiding inside that band would have to stay this small. +constexpr unsigned kMaxEitherPairs = 32; // of kTilesX * kTilesY * kLights = 98304 +inline std::vector tile_light_states(const std::vector& depth, const std::array& k, + const std::vector& lights) { + std::vector out(std::size_t(kTilesX) * kTilesY * kLights, 0); + for (unsigned ty = 0; ty < kTilesY; ++ty) + for (unsigned tx = 0; tx < kTilesX; ++tx) { + double lo[3] = {1e300, 1e300, 1e300}, hi[3] = {-1e300, -1e300, -1e300}; + bool any = false; + for (unsigned y = ty * 16; y < ty * 16 + 16; ++y) + for (unsigned x = tx * 16; x < tx * 16 + 16; ++x) { + const double t = depth[std::size_t(y) * kWidth + x]; + if (!(t > 0)) continue; + any = true; + const double cx = double(x) - 191.5, cy = double(y) - 127.5; + for (int c = 0; c < 3; ++c) { + const double p = k[c] + t * (double(k[3 + c]) + cx * k[6 + c] + cy * k[9 + c]); + lo[c] = std::min(lo[c], p), hi[c] = std::max(hi[c], p); + } + } + if (!any) continue; + for (unsigned l = 0; l < kLights; ++l) { + double d2 = 0; + for (int c = 0; c < 3; ++c) { + const double d = std::max(0.0, std::max(lo[c] - lights[l].pos[c], lights[l].pos[c] - hi[c])); + d2 += d * d; + } + const double r2 = k[14]; + out[(std::size_t(ty) * kTilesX + tx) * kLights + l] = d2 < r2 - 2e-3 ? 1 : d2 > r2 + 2e-3 ? 0 : 2; + } + } + return out; +} + +// The G-buffer's normal codes and view depth at every pixel: per fragment, the three 10-bit codes (lo in colors[0], +// hi in colors[1], from the 8-bit codes as the reference's lighting reads them) and the clip w at the pixel centre, +// widened by its change over kSnapSlack pixels (vertex snapping moves the plane that much) and 1e-5 relative (.w of +// colors[0] and colors[1]). +inline TexturedReference gbuffer_reference(const Scene& scene) { + unsigned degenerate = 0; + const auto& vp = scene.view_projection; + const auto shade = [&](const PixelSite& site, detail::Fragment& f) { + const auto packed = std::uint32_t(site.shade); + for (int k = 0; k < 3; ++k) { + unsigned lo, hi; + unorm_codes(float((packed >> (8 * k)) & 255u) * (1.0f / 255.0f), 1023, lo, hi, kNormalWindow); + f.colors[0][k] = float(lo), f.colors[1][k] = float(hi); + } + double w[3]; + site.world(site.px, site.py, w); + const auto clip_w = [&](double px, double py) { + double p[3]; + site.world(px, py, p); + return vp[12] * p[0] + vp[13] * p[1] + vp[14] * p[2] + vp[15]; + }; + const double cw = clip_w(site.px, site.py); + const double slack = (std::fabs(clip_w(site.px + 1, site.py) - cw) + std::fabs(clip_w(site.px, site.py + 1) - cw)) * + kSnapSlack + 1e-5 * cw; + (void)w; + f.colors[0][3] = float(cw - slack), f.colors[1][3] = float(cw + slack); + f.count = 2; + }; + return resolve_bounds(detail::fragments(scene, shade, degenerate), Color{0, 0, 0, 0}); +} + +// The compute pass's packed RGBA8 words as colours (code / 255). +inline std::vector unpack_rgba8(const std::vector& words) { + std::vector out(words.size()); + for (std::size_t i = 0; i < words.size(); ++i) + for (int k = 0; k < 4; ++k) out[i][k] = float((words[i] >> (8 * k)) & 255u) / 255.0f; + return out; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_deferred_gpu.cpp b/runtime/test/lanterns/lanterns_deferred_gpu.cpp new file mode 100644 index 0000000000..18ee0616ff --- /dev/null +++ b/runtime/test/lanterns/lanterns_deferred_gpu.cpp @@ -0,0 +1,202 @@ +// Lanterns stage 9: the tiled lighting pass (lanterns_deferred_gpu.h, cs_lanterns_tiled.asm). +#include "lanterns_deferred_gpu.h" + +#include "lanterns_d3d12.h" + +#include + +using namespace d3d12test; + +namespace lanterns { +namespace { + +constexpr std::uint64_t kPixelBytes = std::uint64_t(kWidth) * kHeight * 4, kTiles = kTilesX * kTilesY; +constexpr std::uint64_t kLightBytes = kLights * sizeof(PointLight), kCountBytes = kTiles * 4; +constexpr std::uint64_t kListBytes = kTiles * kLights * 4; // the largest output: the poison source is this big + +} // namespace + +bool load_tiled_shader(const std::filesystem::path& dir, std::vector& out) { + out = read_file(dir / "cs_lanterns_tiled.dxbc"); + CHECK(out.size() > 64); + return true; +} + +bool Deferred::create(Gpu& gpu, const std::vector& shader) { + gpu_ = &gpu; + device_ = gpu.device(); + queue_ = gpu.queue(); + CHECK(device_ && queue_ && gpu.gbuffer_normal() && gpu.gbuffer_depth()); + // [0] a table (t0 albedo, t1 normal, t2 view depth, t3 lights, u0 pixels, u1 tile counts, u2 tile lists) -> s[0:1]; + // [1] 16 constants -> s2..s17. + const D3D12_DESCRIPTOR_RANGE ranges[2] = {{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 4, 0, 0, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 3, 0, 0, 4}}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {2, ranges}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 16}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; + desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto blob = serialize_root_signature(desc); + CHECK(!blob.empty()); + CHECK(SUCCEEDED(device_->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root_.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC cs{}; + cs.pRootSignature = root_.p; + cs.CS = {shader.data(), shader.size()}; + CHECK(SUCCEEDED(device_->CreateComputePipelineState(&cs, IID_PPV_ARGS(&pso_.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT, {}, {}, 0, 0}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD, {}, {}, 0, 0}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK, {}, {}, 0, 0}; + const auto make = [&](const D3D12_HEAP_PROPERTIES& heap, std::uint64_t bytes, D3D12_RESOURCE_STATES state, + Ref& out, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + const auto d = buffer_desc(bytes, flags); + return SUCCEEDED(device_->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, + IID_PPV_ARGS(&out.p))); + }; + const auto uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + // The lights are read through a V#, so they live in a DEFAULT buffer, copied from an UPLOAD one before each pass + // (a V# over an UPLOAD heap is outside what the layer maps for the guest; see docs/d3d12_vulkan.md). + CHECK(make(default_heap, kLightBytes, D3D12_RESOURCE_STATE_COMMON, lights_)); + CHECK(make(upload_heap, kLightBytes, D3D12_RESOURCE_STATE_GENERIC_READ, lights_upload_)); + CHECK(make(default_heap, kPixelBytes, D3D12_RESOURCE_STATE_COMMON, output_, uav)); + CHECK(make(default_heap, kCountBytes, D3D12_RESOURCE_STATE_COMMON, counts_, uav)); + CHECK(make(default_heap, kListBytes, D3D12_RESOURCE_STATE_COMMON, lists_, uav)); + CHECK(make(upload_heap, kListBytes, D3D12_RESOURCE_STATE_GENERIC_READ, poison_)); + CHECK(make(readback_heap, kPixelBytes + kCountBytes + kListBytes, D3D12_RESOURCE_STATE_COPY_DEST, readback_)); + CHECK(make(readback_heap, 2 * kPixelBytes, D3D12_RESOURCE_STATE_COPY_DEST, gbuffer_readback_)); + { + void* mapped = nullptr; + CHECK(SUCCEEDED(poison_->Map(0, nullptr, &mapped))); + auto* words = static_cast(mapped); + for (std::uint64_t i = 0; i < kListBytes / 4; ++i) words[i] = kDeferredPoison; + poison_->Unmap(0, nullptr); + } + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 7, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap_.p)))); + const std::uint64_t cpu = heap_cpu(heap_.p); + heap_gpu_ = heap_gpu(heap_.p); + CHECK(device_->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) == 32); + const auto texture_view = [&](ID3D12Resource* texture, DXGI_FORMAT format, unsigned slot) { + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + device_->CreateShaderResourceView(texture, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + slot * 32)}); + }; + texture_view(gpu.target(), DXGI_FORMAT_R8G8B8A8_UNORM, 0); + texture_view(gpu.gbuffer_normal(), kGbufferNormalFormat, 1); + texture_view(gpu.gbuffer_depth(), kGbufferDepthFormat, 2); + const std::array sharps[4] = {make_vsharp(lights_->GetGPUVirtualAddress(), sizeof(PointLight), kLights), + make_raw(output_->GetGPUVirtualAddress(), std::uint32_t(kPixelBytes)), + make_raw(counts_->GetGPUVirtualAddress(), std::uint32_t(kCountBytes)), + make_raw(lists_->GetGPUVirtualAddress(), std::uint32_t(kListBytes))}; + for (unsigned s = 0; s < 4; ++s) std::memcpy(reinterpret_cast(cpu + (3 + s) * 32), sharps[s].data(), 16); + + CHECK(SUCCEEDED(device_->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator_.p)))); + CHECK(SUCCEEDED(device_->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator_.p, nullptr, + IID_PPV_ARGS(&list_.p)))); + CHECK(list_->Close() == S_OK); + CHECK(SUCCEEDED(device_->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence_.p)))); + return true; +} + +bool Deferred::run(const std::vector& lights, const std::array& constants, + std::vector& pixels, std::vector& tile_counts, + std::vector& tile_lists) { + CHECK(lights.size() == kLights); + void* mapped = nullptr; + CHECK(SUCCEEDED(lights_upload_->Map(0, nullptr, &mapped))); + std::memcpy(mapped, lights.data(), kLightBytes); + lights_upload_->Unmap(0, nullptr); + + CHECK(SUCCEEDED(allocator_->Reset())); + CHECK(SUCCEEDED(list_->Reset(allocator_.p, nullptr))); + const auto copy_src = D3D12_RESOURCE_STATE_COPY_SOURCE, read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + const auto uav = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + const auto out_from = first_run_ ? D3D12_RESOURCE_STATE_COMMON : copy_src; + const auto lights_from = first_run_ ? D3D12_RESOURCE_STATE_COMMON : read; + first_run_ = false; + // Poison first: a run that skips a store leaves 0xdeadbeef, not the previous run's value. + const auto dest = D3D12_RESOURCE_STATE_COPY_DEST; + const D3D12_RESOURCE_BARRIER poison[4] = {transition(output_.p, out_from, dest), transition(counts_.p, out_from, dest), + transition(lists_.p, out_from, dest), transition(lights_.p, lights_from, dest)}; + list_->ResourceBarrier(4, poison); + list_->CopyBufferRegion(lights_.p, 0, lights_upload_.p, 0, kLightBytes); + list_->CopyBufferRegion(output_.p, 0, poison_.p, 0, kPixelBytes); + list_->CopyBufferRegion(counts_.p, 0, poison_.p, 0, kCountBytes); + list_->CopyBufferRegion(lists_.p, 0, poison_.p, 0, kListBytes); + // The albedo is the Gpu's target, which a frame leaves in COPY_SOURCE; it goes back there afterwards. + const D3D12_RESOURCE_BARRIER start[5] = {transition(gpu_->target(), copy_src, read), transition(output_.p, dest, uav), + transition(counts_.p, dest, uav), transition(lists_.p, dest, uav), + transition(lights_.p, dest, read)}; // stays readable until the next run + list_->ResourceBarrier(5, start); + ID3D12DescriptorHeap* heaps[] = {heap_.p}; + list_->SetDescriptorHeaps(1, heaps); + list_->SetComputeRootSignature(root_.p); + list_->SetComputeRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{heap_gpu_}); + list_->SetComputeRoot32BitConstants(1, 16, constants.data(), 0); + list_->SetPipelineState(pso_.p); + list_->Dispatch(kTilesX, kTilesY, 1); + const D3D12_RESOURCE_BARRIER end[4] = {transition(gpu_->target(), read, copy_src), transition(output_.p, uav, copy_src), + transition(counts_.p, uav, copy_src), transition(lists_.p, uav, copy_src)}; + list_->ResourceBarrier(4, end); + list_->CopyBufferRegion(readback_.p, 0, output_.p, 0, kPixelBytes); + list_->CopyBufferRegion(readback_.p, kPixelBytes, counts_.p, 0, kCountBytes); + list_->CopyBufferRegion(readback_.p, kPixelBytes + kCountBytes, lists_.p, 0, kListBytes); + CHECK(list_->Close() == S_OK); + ID3D12CommandList* lists[] = {list_.p}; + queue_->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue_->Signal(fence_.p, ++fence_value_))); + CHECK(wait_fence(fence_, fence_value_)); + + CHECK(SUCCEEDED(readback_->Map(0, nullptr, &mapped))); + const auto* bytes = static_cast(mapped); + pixels.resize(std::size_t(kWidth) * kHeight); + tile_counts.resize(kTiles); + std::memcpy(pixels.data(), bytes, kPixelBytes); + std::memcpy(tile_counts.data(), bytes + kPixelBytes, kCountBytes); + tile_lists.resize(kTiles * kLights); + std::memcpy(tile_lists.data(), bytes + kPixelBytes + kCountBytes, kListBytes); + readback_->Unmap(0, nullptr); + return true; +} + +bool Deferred::read_gbuffer(std::vector& normal, std::vector& depth) { + CHECK(SUCCEEDED(allocator_->Reset())); + CHECK(SUCCEEDED(list_->Reset(allocator_.p, nullptr))); + const auto read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, copy_src = D3D12_RESOURCE_STATE_COPY_SOURCE; + ID3D12Resource* targets[2] = {gpu_->gbuffer_normal(), gpu_->gbuffer_depth()}; + const DXGI_FORMAT formats[2] = {kGbufferNormalFormat, kGbufferDepthFormat}; + const D3D12_RESOURCE_BARRIER to_copy[2] = {transition(targets[0], read, copy_src), transition(targets[1], read, copy_src)}; + list_->ResourceBarrier(2, to_copy); + for (unsigned k = 0; k < 2; ++k) { + D3D12_TEXTURE_COPY_LOCATION dst{gbuffer_readback_.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + dst.PlacedFootprint = {k * kPixelBytes, {formats[k], kWidth, kHeight, 1, kWidth * 4}}; + D3D12_TEXTURE_COPY_LOCATION src{targets[k], D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + src.SubresourceIndex = 0; + list_->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + const D3D12_RESOURCE_BARRIER back[2] = {transition(targets[0], copy_src, read), transition(targets[1], copy_src, read)}; + list_->ResourceBarrier(2, back); + CHECK(list_->Close() == S_OK); + ID3D12CommandList* lists[] = {list_.p}; + queue_->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue_->Signal(fence_.p, ++fence_value_))); + CHECK(wait_fence(fence_, fence_value_)); + void* mapped = nullptr; + CHECK(SUCCEEDED(gbuffer_readback_->Map(0, nullptr, &mapped))); + normal.resize(std::size_t(kWidth) * kHeight); + depth.resize(normal.size()); + std::memcpy(normal.data(), mapped, kPixelBytes); + std::memcpy(depth.data(), static_cast(mapped) + kPixelBytes, kPixelBytes); + gbuffer_readback_->Unmap(0, nullptr); + return true; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_deferred_gpu.h b/runtime/test/lanterns/lanterns_deferred_gpu.h new file mode 100644 index 0000000000..2f185ff285 --- /dev/null +++ b/runtime/test/lanterns/lanterns_deferred_gpu.h @@ -0,0 +1,46 @@ +// Lanterns stage 9: the tiled lighting compute pass on the G-buffer a Gpu (created with R8G8B8A8_UNORM and the stage-9 +// shaders) rendered. Its own root signature, heap, list and fence, on the Gpu's device and direct queue. +#pragma once + +#include "lanterns_deferred.h" +#include "lanterns_gpu.h" + +#include +#include +#include +#include + +namespace lanterns { + +bool load_tiled_shader(const std::filesystem::path& dir, std::vector& out); + +constexpr std::uint32_t kDeferredPoison = 0xdeadbeefu; + +class Deferred { +public: + bool create(Gpu& gpu, const std::vector& shader); + // Uploads the lights, poisons the three outputs (kDeferredPoison), runs the pass over the Gpu's last frame with + // these constants (deferred_constants) and reads back the packed pixels, each tile's light count and each tile's + // list of kept light indices (kLights words a tile, the first count of them written). + bool run(const std::vector& lights, const std::array& constants, + std::vector& pixels, std::vector& tile_counts, + std::vector& tile_lists); + // The G-buffer's normal (RGB10A2 words) and view depth (R32_FLOAT) targets of the Gpu's last frame. + bool read_gbuffer(std::vector& normal, std::vector& depth); + +private: + Gpu* gpu_ = nullptr; + ID3D12Device* device_ = nullptr; + ID3D12CommandQueue* queue_ = nullptr; + Ref root_; + Ref pso_; + Ref heap_; + Ref lights_, lights_upload_, output_, counts_, lists_, poison_, readback_, gbuffer_readback_; + Ref allocator_; + Ref list_; + Ref fence_; + std::uint64_t fence_value_ = 0, heap_gpu_ = 0; + bool first_run_ = true; +}; + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_edges.h b/runtime/test/lanterns/lanterns_edges.h new file mode 100644 index 0000000000..09b47ec831 --- /dev/null +++ b/runtime/test/lanterns/lanterns_edges.h @@ -0,0 +1,97 @@ +// Lanterns stage 1, the shared edges: eight triangles fanned around one vertex, every vertex on a pixel centre, each +// triangle a different flat colour, drawn with additive blending by a wave64 VS and PS that read their root data where +// the title's do (docs/d3d12_vulkan.md 3.5: the lowest table pointer at s8; eight root constants s0..s7 below it). +// The fan's inner edges run horizontally, vertically, at 1:1, 1:2, 3:2 and 1:4, so many pixel centres lie exactly on +// an edge two triangles share; D3D's top-left rule gives each such pixel to exactly one of them. With red = 2^k for +// triangle k, green and alpha 1 per triangle, a pixel drawn twice or not at all shows it. The CPU applies the rule with +// exact integers (coordinates in half pixels). +#pragma once + +#include "lanterns_reference.h" + +#include +#include +#include + +namespace lanterns { + +constexpr unsigned kEdgeTriangles = 8; +constexpr float kEdgeWrongAttr = 1000.0f; // the two non-provoking vertices' red: wrong if flat used them + +// The fan in half pixels (a pixel centre x + 0.5 is 2x + 1): the centre, then the ring in screen order. +constexpr int kEdgeCentre[2] = {385, 257}; +constexpr int kEdgeRing[kEdgeTriangles][2] = {{705, 257}, {705, 417}, {545, 497}, {225, 497}, + {65, 337}, {65, 97}, {385, 17}, {625, 17}}; + +struct EdgeVertex { + float pos[4]; // screen x, y (pixels), z, w + float attr[4]; // param0: red 2^k, green 1, blue 0, alpha unused +}; +static_assert(sizeof(EdgeVertex) == 32); + +// Triangle k: the centre (its provoking vertex, carrying the flat colour), ring k, ring k + 1. +inline std::vector edge_vertices() { + std::vector out; + for (unsigned k = 0; k < kEdgeTriangles; ++k) { + const int* p[3] = {kEdgeCentre, kEdgeRing[k], kEdgeRing[(k + 1) % kEdgeTriangles]}; + for (unsigned v = 0; v < 3; ++v) { + EdgeVertex e{{float(p[v][0]) * 0.5f, float(p[v][1]) * 0.5f, 0.5f, 1.0f}, {}}; + e.attr[0] = v == 0 ? float(1u << k) : kEdgeWrongAttr + float(k); + e.attr[1] = v == 0 ? 1.0f : kEdgeWrongAttr; + out.push_back(e); + } + } + return out; +} + +namespace detail { + +// Whether triangle (a, b, c) in half pixels owns the point p (also in half pixels) under the top-left rule. +inline bool owns(const int* a, const int* b, const int* c, long long px, long long py) { + const long long area = (long long)(b[0] - a[0]) * (c[1] - a[1]) - (long long)(b[1] - a[1]) * (c[0] - a[0]); + if (area == 0) return false; + const int* v[3] = {a, area > 0 ? b : c, area > 0 ? c : b}; // clockwise on screen (y down): inside is E > 0 + for (int e = 0; e < 3; ++e) { + const int* s = v[e]; + const int* t = v[(e + 1) % 3]; + const long long dx = t[0] - s[0], dy = t[1] - s[1]; + const long long f = dx * (py - s[1]) - dy * (px - s[0]); + if (f < 0) return false; + if (f == 0 && !((dy == 0 && dx > 0) || dy < 0)) return false; // only top and left edges own their points + } + return true; +} + +} // namespace detail + +struct EdgeReference { + std::vector color; // red: the sum of 2^k over the owners, green and alpha: their count + unsigned on_shared = 0; // pixel centres exactly on an inner edge (the centre included) + unsigned covered = 0; +}; + +inline EdgeReference edge_reference() { + EdgeReference out; + out.color.assign(std::size_t(kWidth) * kHeight, Color{0, 0, 0, 0}); + for (unsigned y = 0; y < kHeight; ++y) + for (unsigned x = 0; x < kWidth; ++x) { + const long long px = 2 * x + 1, py = 2 * y + 1; + Color& c = out.color[std::size_t(y) * kWidth + x]; + for (unsigned k = 0; k < kEdgeTriangles; ++k) + if (detail::owns(kEdgeCentre, kEdgeRing[k], kEdgeRing[(k + 1) % kEdgeTriangles], px, py)) + c[0] += float(1u << k), c[1] += 1.0f, c[3] += 1.0f; + out.covered += c[1] > 0; + for (unsigned k = 0; k < kEdgeTriangles; ++k) { // on segment centre -> ring k? + const long long dx = kEdgeRing[k][0] - kEdgeCentre[0], dy = kEdgeRing[k][1] - kEdgeCentre[1]; + const long long qx = px - kEdgeCentre[0], qy = py - kEdgeCentre[1]; + const long long t = qx * dx + qy * dy; + if (qx * dy - qy * dx == 0 && t >= 0 && t < dx * dx + dy * dy) { + ++out.on_shared; + break; + } + } + } + return out; +} + +} // namespace lanterns \ No newline at end of file diff --git a/runtime/test/lanterns/lanterns_edges_gpu.cpp b/runtime/test/lanterns/lanterns_edges_gpu.cpp new file mode 100644 index 0000000000..5b37e7c08e --- /dev/null +++ b/runtime/test/lanterns/lanterns_edges_gpu.cpp @@ -0,0 +1,174 @@ +// Lanterns stage 1: the shared edges on the GPU (lanterns_edges_gpu.h). +#include "lanterns_edges_gpu.h" + +#include "lanterns_d3d12.h" + +#include + +using namespace d3d12test; + +namespace lanterns { + +bool load_edge_shaders(const std::filesystem::path& dir, EdgeShaders& out) { + out.vs = read_file(dir / "vs_lanterns_edges.dxbc"); + out.ps = read_file(dir / "ps_lanterns_edges.dxbc"); + CHECK(out.vs.size() > 64 && out.ps.size() > 64); + return true; +} + +bool EdgeDraw::create(Gpu& gpu, const EdgeShaders& shaders) { + device_ = gpu.device(); + queue_ = gpu.queue(); + CHECK(device_ && queue_); + // [0] eight constants -> s0..s7; [1] a table (t0 the vertices, t1 the alpha) -> s[8:9]. + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 2, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 8}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &range}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; + desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto blob = serialize_root_signature(desc); + CHECK(!blob.empty()); + CHECK(SUCCEEDED(device_->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root_.p)))); + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = root_.p; + pso.VS = {shaders.vs.data(), shaders.vs.size()}; + pso.PS = {shaders.ps.data(), shaders.ps.size()}; + auto& blend = pso.BlendState.RenderTarget[0]; + blend.BlendEnable = TRUE; + blend.SrcBlend = blend.DestBlend = D3D12_BLEND_ONE; + blend.SrcBlendAlpha = blend.DestBlendAlpha = D3D12_BLEND_ONE; + blend.BlendOp = blend.BlendOpAlpha = D3D12_BLEND_OP_ADD; + blend.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso.SampleMask = 0xffffffff; + pso.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso.RasterizerState.DepthClipEnable = TRUE; + pso.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pso.NumRenderTargets = 1; + pso.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pso.SampleDesc.Count = 1; + CHECK(SUCCEEDED(device_->CreateGraphicsPipelineState(&pso, IID_PPV_ARGS(&pso_.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT, {}, {}, 0, 0}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD, {}, {}, 0, 0}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK, {}, {}, 0, 0}; + const auto vertices = edge_vertices(); + const std::uint64_t vertex_bytes = vertices.size() * sizeof(EdgeVertex); + const auto make = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC& d, D3D12_RESOURCE_STATES state, + Ref& out) { + return SUCCEEDED(device_->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, + IID_PPV_ARGS(&out.p))); + }; + // The vertices and the PS's alpha word live in DEFAULT buffers, filled from one UPLOAD staging buffer by + // CopyBufferRegion, as the main scene's buffers are (lanterns_gpu.cpp). Reading them straight from UPLOAD heaps + // drew nothing on an Intel UHD 770 under native Windows. + const std::uint64_t alpha_offset = align(vertex_bytes, 256); + CHECK(make(default_heap, buffer_desc(vertex_bytes), D3D12_RESOURCE_STATE_COPY_DEST, vertices_)); + CHECK(make(default_heap, buffer_desc(256), D3D12_RESOURCE_STATE_COPY_DEST, alpha_)); + Ref staging; // kept alive until the copy's fence has passed + CHECK(make(upload_heap, buffer_desc(alpha_offset + 256), D3D12_RESOURCE_STATE_GENERIC_READ, staging)); + CHECK(make(readback_heap, buffer_desc(std::uint64_t(kPitch) * kHeight), D3D12_RESOURCE_STATE_COPY_DEST, readback_)); + std::uint8_t* mapped = nullptr; + CHECK(SUCCEEDED(staging->Map(0, nullptr, reinterpret_cast(&mapped)))); + std::memcpy(mapped, vertices.data(), vertex_bytes); + const float alpha[4] = {1.0f, 0.0f, 0.0f, 0.0f}; + std::memcpy(mapped + alpha_offset, alpha, sizeof(alpha)); + staging->Unmap(0, nullptr); + D3D12_RESOURCE_DESC tex{}; + tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + tex.Width = kWidth; + tex.Height = kHeight; + tex.DepthOrArraySize = 1; + tex.MipLevels = 1; + tex.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + tex.SampleDesc.Count = 1; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + CHECK(make(default_heap, tex, D3D12_RESOURCE_STATE_COMMON, target_)); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap_.p)))); + const std::uint64_t cpu = heap_cpu(heap_.p); + heap_gpu_ = heap_gpu(heap_.p); + CHECK(device_->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) == 32); + const auto v0 = make_vsharp(vertices_->GetGPUVirtualAddress(), sizeof(EdgeVertex), std::uint32_t(vertices.size())); + const auto v1 = make_raw(alpha_->GetGPUVirtualAddress(), 16); + std::memcpy(reinterpret_cast(cpu), v0.data(), 16); + std::memcpy(reinterpret_cast(cpu + 32), v1.data(), 16); + const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap_.p)))); + device_->CreateRenderTargetView(target_.p, nullptr, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(heap_cpu(rtv_heap_.p))}); + + CHECK(SUCCEEDED(device_->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator_.p)))); + CHECK(SUCCEEDED(device_->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator_.p, nullptr, + IID_PPV_ARGS(&list_.p)))); + CHECK(SUCCEEDED(device_->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence_.p)))); + list_->CopyBufferRegion(vertices_.p, 0, staging.p, 0, vertex_bytes); + list_->CopyBufferRegion(alpha_.p, 0, staging.p, alpha_offset, sizeof(alpha)); + const D3D12_RESOURCE_BARRIER filled[] = { + transition(vertices_.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(alpha_.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)}; + list_->ResourceBarrier(2, filled); + CHECK(list_->Close() == S_OK); + ID3D12CommandList* lists[] = {list_.p}; + queue_->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue_->Signal(fence_.p, ++fence_value_))); + CHECK(wait_fence(fence_, fence_value_)); + return true; +} + +bool EdgeDraw::run(std::vector& pixels) { + CHECK(SUCCEEDED(allocator_->Reset())); + CHECK(SUCCEEDED(list_->Reset(allocator_.p, nullptr))); + const auto to_rt = transition(target_.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET); + list_->ResourceBarrier(1, &to_rt); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{SIZE_T(heap_cpu(rtv_heap_.p))}; + const float zero[4] = {0, 0, 0, 0}; + list_->ClearRenderTargetView(rtv, zero, 0, nullptr); + ID3D12DescriptorHeap* heaps[] = {heap_.p}; + list_->SetDescriptorHeaps(1, heaps); + list_->SetGraphicsRootSignature(root_.p); + // s0..s3: clip x = x / 192 - 1, clip y = 1 - y / 128; s4..s7: words nothing reads. + const float constants[8] = {1.0f / 192.0f, -1.0f, -1.0f / 128.0f, 1.0f, 0, 0, 0, 0}; + std::uint32_t words[8]; + std::memcpy(words, constants, sizeof(words)); + for (unsigned i = 4; i < 8; ++i) words[i] = 0x4c4e5400u | i; + list_->SetGraphicsRoot32BitConstants(0, 8, words, 0); + list_->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{heap_gpu_}); + list_->SetPipelineState(pso_.p); + const D3D12_VIEWPORT viewport{0, 0, float(kWidth), float(kHeight), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(kWidth), LONG(kHeight)}; + list_->RSSetViewports(1, &viewport); + list_->RSSetScissorRects(1, &scissor); + list_->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + list_->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list_->DrawInstanced(3 * kEdgeTriangles, 1, 0, 0); + const auto to_copy = transition(target_.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list_->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{readback_.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, kWidth, kHeight, 1, kPitch}}; + D3D12_TEXTURE_COPY_LOCATION src{target_.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + src.SubresourceIndex = 0; + list_->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + const auto back = transition(target_.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + list_->ResourceBarrier(1, &back); + CHECK(list_->Close() == S_OK); + ID3D12CommandList* lists[] = {list_.p}; + queue_->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue_->Signal(fence_.p, ++fence_value_))); + CHECK(wait_fence(fence_, fence_value_)); + void* mapped = nullptr; + CHECK(SUCCEEDED(readback_->Map(0, nullptr, &mapped))); + pixels.resize(std::size_t(kWidth) * kHeight); + for (unsigned y = 0; y < kHeight; ++y) + std::memcpy(pixels.data() + std::size_t(y) * kWidth, static_cast(mapped) + y * kPitch, + kWidth * sizeof(Color)); + readback_->Unmap(0, nullptr); + return true; +} + +} // namespace lanterns \ No newline at end of file diff --git a/runtime/test/lanterns/lanterns_edges_gpu.h b/runtime/test/lanterns/lanterns_edges_gpu.h new file mode 100644 index 0000000000..f0c1d9561e --- /dev/null +++ b/runtime/test/lanterns/lanterns_edges_gpu.h @@ -0,0 +1,40 @@ +// Lanterns stage 1, the shared edges on the GPU (lanterns_edges.h): its own root signature (eight constants, then a +// table of two buffer SRVs, so the table pointer lands at s8 as in the title's shaders), PSO with additive blending, +// target, list and fence, on a Gpu's device and direct queue. +#pragma once + +#include "lanterns_edges.h" +#include "lanterns_gpu.h" + +#include +#include +#include + +namespace lanterns { + +struct EdgeShaders { + std::vector vs, ps; +}; +bool load_edge_shaders(const std::filesystem::path& dir, EdgeShaders& out); + +class EdgeDraw { +public: + bool create(Gpu& gpu, const EdgeShaders& shaders); + // Clears the target to 0, draws the fan's 24 vertices once and reads the target back. + bool run(std::vector& pixels); + +private: + ID3D12Device* device_ = nullptr; + ID3D12CommandQueue* queue_ = nullptr; + Ref root_; + Ref pso_; + Ref heap_, rtv_heap_; + Ref vertices_, alpha_, target_, readback_; + Ref allocator_; + Ref list_; + Ref fence_; + std::uint64_t heap_gpu_ = 0; + UINT64 fence_value_ = 0; +}; + +} // namespace lanterns \ No newline at end of file diff --git a/runtime/test/lanterns/lanterns_gpu.cpp b/runtime/test/lanterns/lanterns_gpu.cpp new file mode 100644 index 0000000000..781c3c71d5 --- /dev/null +++ b/runtime/test/lanterns/lanterns_gpu.cpp @@ -0,0 +1,608 @@ +// Lanterns: the GPU side (lanterns_gpu.h). Borrowed pieces, all from this repository under its licence: the +// D3D12XboxCreateDevice import (tiny_frame's, #3488), and from test/d3d12_translated_draw_test.cpp (M1.5) the heap-handle calls +// through slots 9/10, the V# encoding and the upload-to-DEFAULT copies; the compute root signature's shape (constants, +// then a UAV table at s[4:5]) follows test/d3d12_m4_compute_test.cpp (M4). +#include "lanterns_gpu.h" + +#include "lanterns_d3d12.h" + +#include +#include +#include + +// Resolved at link time against test/fixtures/d3d12_xs_stub.cpp (which fails), at run time by gta6rt's shim registry. +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, + const IID* riid, void** out); + +using namespace d3d12test; + +namespace lanterns { +namespace { + +Geometry flatten(const Scene& scene) { + Geometry g; + for (const Mesh& mesh : scene.meshes) { + g.first_vertex.push_back(std::uint32_t(g.vertices.size())); + g.vertex_count.push_back(std::uint32_t(mesh.vertices.size())); + g.first_index.push_back(std::uint32_t(g.indices.size())); + g.vertices.insert(g.vertices.end(), mesh.vertices.begin(), mesh.vertices.end()); + for (const Face& face : mesh.faces) + for (unsigned k = 1; k + 1 < face.count; ++k) // indices are relative to the mesh: its V# starts there + g.indices.insert(g.indices.end(), {face.v[0], face.v[k], face.v[k + 1]}); + g.index_count.push_back(std::uint32_t(g.indices.size()) - g.first_index.back()); + } + for (const Draw& draw : scene.draws) { + g.first_instance.push_back(std::uint32_t(g.instances.size())); + if (!draw.gpu_instances) + g.instances.insert(g.instances.end(), draw.instances.begin(), draw.instances.end()); + } + return g; +} + +constexpr std::uint64_t kImageBytes = std::uint64_t(kPitch) * kHeight; +constexpr std::uint64_t kStateBytes = kParticles * sizeof(Particle), kInstanceBytes = kParticles * sizeof(Instance); +// The readback buffer: the image, then the compute outputs (the state and the instance records). +constexpr std::uint64_t kOffState = kImageBytes, kOffInstances = kOffState + kStateBytes, + kReadbackBytes = kOffInstances + kInstanceBytes; +constexpr unsigned kComputeSlots = 2; // the compute table: state, instance records + +} // namespace + +bool load_shaders(const std::filesystem::path& dir, int stage, Shaders& out) { + out.vs = read_file(dir / "vs_lanterns.dxbc"); + out.ps_lit = read_file(dir / "ps_lanterns_lit.dxbc"); + out.ps_floor = read_file(dir / "ps_lanterns_floor.dxbc"); + out.vs_w64 = read_file(dir / "vs_lanterns_w64.dxbc"); + out.ps_lit_w64 = read_file(dir / "ps_lanterns_lit_w64.dxbc"); + CHECK(out.vs.size() > 64 && out.ps_lit.size() > 64 && out.ps_floor.size() > 64); + CHECK(out.vs_w64.size() > 64 && out.ps_lit_w64.size() > 64); + if (stage == 9) { + out.vs_gbuf = read_file(dir / "vs_lanterns_gbuf.dxbc"); + out.ps_gbuf = read_file(dir / "ps_lanterns_gbuf.dxbc"); + CHECK(out.vs_gbuf.size() > 64 && out.ps_gbuf.size() > 64); + } + if (stage == 8) { + out.ps_shadow = read_file(dir / "ps_lanterns_shadow.dxbc"); + CHECK(out.ps_shadow.size() > 64); + } + if (stage == 6) { + out.ps_tex_floor = read_file(dir / "ps_lanterns_tex_floor.dxbc"); + out.ps_tex_solid = read_file(dir / "ps_lanterns_tex_solid.dxbc"); + CHECK(out.ps_tex_floor.size() > 64 && out.ps_tex_solid.size() > 64); + } + if (stage == 3 || stage == 5) { + out.cs_rise = read_file(dir / "cs_lanterns_rise.dxbc"); + CHECK(out.cs_rise.size() > 64); + } + // The lookup control (create_pipelines): the VS's FSSM program (fssm_unpack.py's copy) in a container the guest + // writes itself (d3d12_test_shaders.h), once as it is and once with one byte of the program's name changed (so + // another FSSM hash). One writer for both, so the hash is the only difference between them. + const auto program = read_file(dir / "fssm" / "vs_lanterns.fssm"); + CHECK(program.size() > 0x200 && std::memcmp(program.data(), "FSSM", 4) == 0); + out.rebuilt_vs = shader_container(program); + static constexpr char kName[] = "vs_lanterns"; + const auto name_end = kName + sizeof(kName) - 1; + auto renamed = program; + const auto at = std::search(renamed.begin(), renamed.end(), kName, name_end); + CHECK(at != renamed.end() && std::search(at + 1, renamed.end(), kName, name_end) == renamed.end()); + at[sizeof(kName) - 2] ^= 0x20; // "vs_lanternS": the tail's name, not padding + out.unknown_vs = shader_container(renamed); + return true; +} + +bool Gpu::create(const Scene& scene, const Shaders& shaders, DXGI_FORMAT target_format) { + CHECK(target_format == DXGI_FORMAT_R32G32B32A32_FLOAT || target_format == DXGI_FORMAT_R16G16B16A16_FLOAT || + (target_format == DXGI_FORMAT_R8G8B8A8_UNORM && !shaders.ps_gbuf.empty())); + target_format_ = target_format; + const std::uint32_t device_params[24] = {}; + const IID device_iid = __uuidof(ID3D12Device); + const HRESULT created = D3D12XboxCreateDevice(nullptr, device_params, &device_iid, reinterpret_cast(&device_.p)); + if (FAILED(created) || !device_.p) { + std::fprintf(stderr, "lanterns: D3D12XboxCreateDevice failed (hr=0x%08lx)\n", static_cast(created)); + return false; + } + compute_ = !shaders.cs_rise.empty(); + textured_ = !shaders.ps_tex_floor.empty() && !shaders.ps_tex_solid.empty(); + shadow_ = !shaders.ps_shadow.empty(); + gbuffer_ = !shaders.ps_gbuf.empty(); + if (shadow_) vs_ = shaders.vs; // the depth pass's pipeline (create_shadow) uses it too + geometry_ = flatten(scene); + CHECK(create_pipelines(shaders)); + if (compute_) CHECK(create_compute(shaders)); + CHECK(create_resources(scene)); + CHECK(fill_descriptors(scene)); + if (shadow_) CHECK(create_shadow()); + return initialize(scene); +} + +// The root tables and constants of draw d (the mesh V#, the draw's instance V#, its model matrix and tint). +void Gpu::bind_draw(const Scene& scene, std::size_t d) { + const Draw& draw = scene.draws[d]; + list_->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu_ + draw.mesh * srv_step_}); + list_->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu_ + (scene.meshes.size() + d) * srv_step_}); + float constants[16]; + std::memcpy(constants, draw.model.data(), sizeof(draw.model)); + std::memcpy(constants + 12, draw.tint.data(), sizeof(draw.tint)); + list_->SetGraphicsRoot32BitConstants(2, 16, constants, 0); +} + +bool Gpu::create_pipelines(const Shaders& shaders) { + // [0] table: the mesh V# (t0) [1] table: the instance V# (t1) [2] 16 constants (b0) [3] root CBV (b1) + // -> s[0:1], s[2:3], s4..s19, s[20:21]: what vs_lanterns.asm reads. + // Stage 6 adds [4] a table of the two textures (t2, t3) and [5] a table of one sampler -> s[22:23], s[24:25]. + D3D12_DESCRIPTOR_RANGE ranges[4] = {{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 1, 0, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 2, 2, 0, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0, 0, 0}}; + D3D12_ROOT_PARAMETER params[6] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &ranges[0]}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &ranges[1]}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[2].Constants = {0, 0, 16}; + params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + params[3].Descriptor = {1, 0}; + params[4].ParameterType = params[5].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[4].DescriptorTable = {1, &ranges[2]}; + params[5].DescriptorTable = {1, &ranges[3]}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {textured_ || shadow_ ? 6u : 4u, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + CHECK(!root_blob.empty()); + CHECK(SUCCEEDED(device_->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root_.p)))); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root_.p; + desc.VS = gbuffer_ ? D3D12_SHADER_BYTECODE{shaders.vs_gbuf.data(), shaders.vs_gbuf.size()} + : D3D12_SHADER_BYTECODE{shaders.vs.data(), shaders.vs.size()}; + for (auto& target : desc.BlendState.RenderTarget) target.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + desc.SampleMask = 0xffffffff; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = gbuffer_ ? 3 : 1; + desc.RTVFormats[0] = target_format_; + desc.RTVFormats[1] = kGbufferNormalFormat; // stage 9's G-buffer: albedo (the target), normal, view depth + desc.RTVFormats[2] = kGbufferDepthFormat; + if (!gbuffer_) desc.RTVFormats[1] = desc.RTVFormats[2] = DXGI_FORMAT_UNKNOWN; + desc.DSVFormat = DXGI_FORMAT_D32_FLOAT; + desc.SampleDesc.Count = 1; + for (int floor = 0; floor < 2; ++floor) + for (int depth = 0; depth < 2; ++depth) { + const auto& ps = gbuffer_ ? shaders.ps_gbuf + : shadow_ ? shaders.ps_shadow + : textured_ ? (floor ? shaders.ps_tex_floor : shaders.ps_tex_solid) + : (floor ? shaders.ps_floor : shaders.ps_lit); + desc.PS = {ps.data(), ps.size()}; + desc.DepthStencilState.DepthEnable = depth ? TRUE : FALSE; + CHECK(SUCCEEDED(device_->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso_[floor][depth].p)))); + if (floor || gbuffer_) continue; // the G-buffer pass has its own VS and PS for every draw + // The wave64 pair, for the draws marked wave64: vs_lanterns_w64, and ps_lanterns_lit_w64 where the solids + // use ps_lanterns_lit (another stage's pixel shader stays as it is). + const auto& ps64 = &ps == &shaders.ps_lit ? shaders.ps_lit_w64 : ps; + desc.VS = {shaders.vs_w64.data(), shaders.vs_w64.size()}; + desc.PS = {ps64.data(), ps64.size()}; + CHECK(SUCCEEDED(device_->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso_w64_[depth].p)))); + desc.VS = {shaders.vs.data(), shaders.vs.size()}; // not the G-buffer pass: it skipped the pair + } + // The lookup control: the guest's own container of the VS program must give a pipeline, and the same writer's + // container with one name byte changed must be refused, so the refusal can only come from the lookup. Both use + // stage 1's pairing (vs_lanterns with ps_lanterns_lit, one target) whatever this stage draws with: the G-buffer PS + // reads an attribute vs_lanterns does not export, and a VS that leaves a PS input unwritten is not a valid pipeline. + D3D12_GRAPHICS_PIPELINE_STATE_DESC control = desc; + control.PS = {shaders.ps_lit.data(), shaders.ps_lit.size()}; + control.NumRenderTargets = 1; + control.RTVFormats[1] = control.RTVFormats[2] = DXGI_FORMAT_UNKNOWN; + Ref rebuilt, unknown; + control.VS = {shaders.rebuilt_vs.data(), shaders.rebuilt_vs.size()}; + CHECK(SUCCEEDED(device_->CreateGraphicsPipelineState(&control, IID_PPV_ARGS(&rebuilt.p))) && rebuilt.p); + std::printf("lanterns: pipelines made (wave32 and wave64), and one from the guest's own container of vs_lanterns " + "(paired as in stage 1: ps_lanterns_lit, one target); " + "next, that container with one name byte changed, which the layer must refuse (its 'no translated vs' " + "line is expected)\n"); + control.VS = {shaders.unknown_vs.data(), shaders.unknown_vs.size()}; + CHECK(device_->CreateGraphicsPipelineState(&control, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p); + return true; +} + +bool Gpu::create_compute(const Shaders& shaders) { + // [0] four 32-bit constants (s0..s3), [1] a table of two UAVs (s[4:5]), as M4's compute root signature. + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, kComputeSlots, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 4}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &range}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto blob = serialize_root_signature(root_desc); + CHECK(!blob.empty()); + CHECK(SUCCEEDED(device_->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&compute_root_.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = compute_root_.p; + desc.CS = {shaders.cs_rise.data(), shaders.cs_rise.size()}; + CHECK(SUCCEEDED(device_->CreateComputePipelineState(&desc, IID_PPV_ARGS(&compute_pso_.p)))); + return true; +} + +bool Gpu::create_resources(const Scene& scene) { + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT, {}, {}, 0, 0}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD, {}, {}, 0, 0}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK, {}, {}, 0, 0}; + const std::uint64_t vb_bytes = geometry_.vertices.size() * sizeof(Vertex); + const std::uint64_t ib_bytes = align(geometry_.indices.size() * sizeof(std::uint16_t), 4); + const std::uint64_t inst_bytes = std::max(geometry_.instances.size() * sizeof(Instance), 256); + // Upload layout: vertices, indices, instances, the camera's 64 bytes (the root CBV reads them in place: root views + // are 64-bit console VAs, docs/d3d12_vulkan.md 3.3), then the particles' first state. + upload_vb_ = 0; + upload_ib_ = align(upload_vb_ + vb_bytes, 256); + upload_inst_ = align(upload_ib_ + ib_bytes, 256); + upload_cbv_ = align(upload_inst_ + inst_bytes, 256); + upload_light_ = upload_cbv_ + 256; // stage 8: the light's clip matrix, the depth pass's root CBV + upload_particles_ = upload_light_ + 256; + const std::uint64_t upload_bytes = upload_particles_ + kStateBytes; + const auto make_buffer = [&](const D3D12_HEAP_PROPERTIES& heap, std::uint64_t bytes, D3D12_RESOURCE_STATES state, + Ref& out, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + const auto desc = buffer_desc(bytes, flags); + return SUCCEEDED(device_->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(&out.p))); + }; + CHECK(make_buffer(default_heap, vb_bytes, D3D12_RESOURCE_STATE_COPY_DEST, vertex_buffer_)); + CHECK(make_buffer(default_heap, ib_bytes, D3D12_RESOURCE_STATE_COPY_DEST, index_buffer_)); + CHECK(make_buffer(default_heap, inst_bytes, D3D12_RESOURCE_STATE_COPY_DEST, instance_buffer_)); + CHECK(make_buffer(upload_heap, upload_bytes, D3D12_RESOURCE_STATE_GENERIC_READ, upload_)); + CHECK(make_buffer(readback_heap, kReadbackBytes, D3D12_RESOURCE_STATE_COPY_DEST, readback_)); + if (compute_) { + CHECK(make_buffer(default_heap, kStateBytes, D3D12_RESOURCE_STATE_COPY_DEST, particle_state_, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); + CHECK(make_buffer(default_heap, kInstanceBytes, D3D12_RESOURCE_STATE_COMMON, particle_instances_, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); + } + + D3D12_RESOURCE_DESC tex{}; + tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + tex.Width = kWidth; + tex.Height = kHeight; + tex.DepthOrArraySize = 1; + tex.MipLevels = 1; + tex.Format = target_format_; + tex.SampleDesc.Count = 1; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + CHECK(SUCCEEDED(device_->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target_.p)))); + if (gbuffer_) { + tex.Format = kGbufferNormalFormat; + CHECK(SUCCEEDED(device_->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&gbuffer_normal_.p)))); + tex.Format = kGbufferDepthFormat; + CHECK(SUCCEEDED(device_->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&gbuffer_depth_.p)))); + } + tex.Format = DXGI_FORMAT_D32_FLOAT; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + D3D12_CLEAR_VALUE depth_clear{}; + depth_clear.Format = DXGI_FORMAT_D32_FLOAT; + depth_clear.DepthStencil = {1.0f, 0}; + CHECK(SUCCEEDED(device_->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex, + D3D12_RESOURCE_STATE_DEPTH_WRITE, &depth_clear, + IID_PPV_ARGS(&depth_.p)))); + + const D3D12_DESCRIPTOR_HEAP_DESC srv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 32, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&srv_desc, IID_PPV_ARGS(&srv_heap_.p)))); + CHECK(scene.meshes.size() + scene.draws.size() + kComputeSlots + 2 <= 32); + const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 3, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap_.p)))); + const D3D12_DESCRIPTOR_HEAP_DESC dsv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&dsv_desc, IID_PPV_ARGS(&dsv_heap_.p)))); + rtv_ = {SIZE_T(heap_cpu(rtv_heap_.p))}; + dsv_ = {SIZE_T(heap_cpu(dsv_heap_.p))}; + device_->CreateRenderTargetView(target_.p, nullptr, rtv_); + if (gbuffer_) { + const UINT step = device_->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + device_->CreateRenderTargetView(gbuffer_normal_.p, nullptr, D3D12_CPU_DESCRIPTOR_HANDLE{rtv_.ptr + step}); + device_->CreateRenderTargetView(gbuffer_depth_.p, nullptr, D3D12_CPU_DESCRIPTOR_HANDLE{rtv_.ptr + 2 * step}); + } + device_->CreateDepthStencilView(depth_.p, nullptr, dsv_); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + CHECK(SUCCEEDED(device_->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue_.p)))); + CHECK(SUCCEEDED(device_->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator_.p)))); + CHECK(SUCCEEDED(device_->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator_.p, nullptr, + IID_PPV_ARGS(&list_.p)))); + CHECK(list_->Close() == S_OK); + CHECK(SUCCEEDED(device_->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence_.p)))); + if (compute_) { + queue_desc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + CHECK(SUCCEEDED(device_->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&compute_queue_.p)))); + CHECK(SUCCEEDED(device_->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, + IID_PPV_ARGS(&compute_allocator_.p)))); + CHECK(SUCCEEDED(device_->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, compute_allocator_.p, nullptr, + IID_PPV_ARGS(&compute_list_.p)))); + CHECK(compute_list_->Close() == S_OK); + CHECK(SUCCEEDED(device_->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&compute_fence_.p)))); + } + return true; +} + +// The descriptor tables: slot m holds mesh m's V#, slot (meshes + d) draw d's instance V#, then the compute shader's +// two V#s (state, instance records). Raw V# bytes, written through the CPU handle as the title writes them. +bool Gpu::fill_descriptors(const Scene& scene) { + srv_cpu_ = heap_cpu(srv_heap_.p); + srv_gpu_ = heap_gpu(srv_heap_.p); + srv_step_ = device_->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + CHECK(srv_cpu_ && srv_gpu_ >= 0x10000 && srv_step_ >= 16); + // cs_lanterns_rise.asm loads its second V# 0x20 bytes after the first, as M4's shaders do. + CHECK(!compute_ || srv_step_ == 32); + const auto put = [&](std::size_t index, const std::array& v) { + std::memcpy(reinterpret_cast(srv_cpu_ + index * srv_step_), v.data(), 16); + }; + const std::uint64_t vb = vertex_buffer_->GetGPUVirtualAddress(), inst = instance_buffer_->GetGPUVirtualAddress(); + const std::size_t meshes = scene.meshes.size(), draws = scene.draws.size(); + for (std::size_t m = 0; m < meshes; ++m) + put(m, make_vsharp(vb + geometry_.first_vertex[m] * sizeof(Vertex), sizeof(Vertex), geometry_.vertex_count[m])); + for (std::size_t d = 0; d < draws; ++d) { + const Draw& draw = scene.draws[d]; + const auto count = std::uint32_t(draw.instances.size()); + if (draw.gpu_instances) { + CHECK(compute_ && count == kParticles); + put(meshes + d, make_vsharp(particle_instances_->GetGPUVirtualAddress(), sizeof(Instance), count)); + } else { + put(meshes + d, make_vsharp(inst + geometry_.first_instance[d] * sizeof(Instance), sizeof(Instance), count)); + } + } + srv_texture_slot_ = meshes + draws + kComputeSlots; + if (compute_) { + // The compute table: [state, instance records]. + srv_compute_slot_ = meshes + draws; + put(srv_compute_slot_, make_vsharp(particle_state_->GetGPUVirtualAddress(), sizeof(Particle), kParticles)); + put(srv_compute_slot_ + 1, + make_vsharp(particle_instances_->GetGPUVirtualAddress(), sizeof(Instance), kParticles)); + } + return true; +} + +// One direct-queue submission, waited for: the uploads into the DEFAULT buffers, and the target into COPY_SOURCE. +bool Gpu::initialize(const Scene& scene) { + std::uint8_t* up = nullptr; + CHECK(SUCCEEDED(upload_->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up + upload_vb_, geometry_.vertices.data(), geometry_.vertices.size() * sizeof(Vertex)); + std::memcpy(up + upload_ib_, geometry_.indices.data(), geometry_.indices.size() * sizeof(std::uint16_t)); + if (!geometry_.instances.empty()) + std::memcpy(up + upload_inst_, geometry_.instances.data(), geometry_.instances.size() * sizeof(Instance)); + std::memcpy(up + upload_cbv_, scene.view_projection.data(), sizeof(scene.view_projection)); + const auto particles = initial_particles(); + std::memcpy(up + upload_particles_, particles.data(), kStateBytes); + + CHECK(SUCCEEDED(allocator_->Reset())); + CHECK(SUCCEEDED(list_->Reset(allocator_.p, nullptr))); + list_->CopyBufferRegion(vertex_buffer_.p, 0, upload_.p, upload_vb_, geometry_.vertices.size() * sizeof(Vertex)); + list_->CopyBufferRegion(index_buffer_.p, 0, upload_.p, upload_ib_, + align(geometry_.indices.size() * sizeof(std::uint16_t), 4)); + if (!geometry_.instances.empty()) + list_->CopyBufferRegion(instance_buffer_.p, 0, upload_.p, upload_inst_, + geometry_.instances.size() * sizeof(Instance)); + std::vector barriers = { + transition(vertex_buffer_.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(index_buffer_.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER), + transition(instance_buffer_.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(target_.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)}; + if (compute_) { + list_->CopyBufferRegion(particle_state_.p, 0, upload_.p, upload_particles_, kStateBytes); + barriers.push_back(transition(particle_state_.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)); + } + list_->ResourceBarrier(UINT(barriers.size()), barriers.data()); + CHECK(list_->Close() == S_OK); + ID3D12CommandList* lists[] = {list_.p}; + queue_->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue_->Signal(fence_.p, ++fence_value_))); + CHECK(wait_fence(fence_, fence_value_)); + return true; +} + +bool Gpu::submit_frame(const Scene& scene, bool depth_test, std::uint64_t wait_compute) { + CHECK(SUCCEEDED(allocator_->Reset())); + CHECK(SUCCEEDED(list_->Reset(allocator_.p, nullptr))); + std::vector before = { + transition(target_.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + if (compute_) + before.push_back(transition(particle_instances_.p, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)); + if (gbuffer_) { // the compute pass leaves them as shader resources; they start in COMMON + const auto from = gbuffer_written_ ? D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE : D3D12_RESOURCE_STATE_COMMON; + before.push_back(transition(gbuffer_normal_.p, from, D3D12_RESOURCE_STATE_RENDER_TARGET)); + before.push_back(transition(gbuffer_depth_.p, from, D3D12_RESOURCE_STATE_RENDER_TARGET)); + gbuffer_written_ = true; + } + list_->ResourceBarrier(UINT(before.size()), before.data()); + if (shadow_) record_shadow_pass(scene); + if (gbuffer_) { // albedo 0, normal 0, view depth 0 (no geometry: the compute pass writes the background) + const float zero[4] = {0, 0, 0, 0}; + const UINT step = device_->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + for (UINT k = 0; k < 3; ++k) + list_->ClearRenderTargetView(D3D12_CPU_DESCRIPTOR_HANDLE{rtv_.ptr + k * step}, zero, 0, nullptr); + } else { + list_->ClearRenderTargetView(rtv_, kClear.data(), 0, nullptr); + } + list_->ClearDepthStencilView(dsv_, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + list_->SetGraphicsRootSignature(root_.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap_.p, sampler_heap_.p}; + list_->SetDescriptorHeaps(textured_ || shadow_ ? 2 : 1, heaps); + if (textured_ || shadow_) { + CHECK(textures_bound_); + list_->SetGraphicsRootDescriptorTable(4, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu_ + srv_texture_slot_ * srv_step_}); + list_->SetGraphicsRootDescriptorTable(5, D3D12_GPU_DESCRIPTOR_HANDLE{heap_gpu(sampler_heap_.p)}); + } + list_->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_INDEX_BUFFER_VIEW ibv{index_buffer_->GetGPUVirtualAddress(), + UINT(align(geometry_.indices.size() * sizeof(std::uint16_t), 4)), + DXGI_FORMAT_R16_UINT}; + list_->IASetIndexBuffer(&ibv); + const D3D12_VIEWPORT viewport{0, 0, float(kWidth), float(kHeight), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(kWidth), LONG(kHeight)}; + list_->RSSetViewports(1, &viewport); + list_->RSSetScissorRects(1, &scissor); + list_->OMSetRenderTargets(gbuffer_ ? 3 : 1, &rtv_, TRUE, &dsv_); // one contiguous range of RTVs + list_->SetGraphicsRootConstantBufferView(3, upload_->GetGPUVirtualAddress() + upload_cbv_); + for (std::size_t d = 0; d < scene.draws.size(); ++d) { + const Draw& draw = scene.draws[d]; + if (draw.hidden) continue; + list_->SetPipelineState(draw.wave64 && !draw.floor && !gbuffer_ ? pso_w64_[depth_test ? 1 : 0].p + : pso_[draw.floor ? 1 : 0][depth_test ? 1 : 0].p); + bind_draw(scene, d); + list_->DrawIndexedInstanced(geometry_.index_count[draw.mesh], UINT(draw.instances.size()), + geometry_.first_index[draw.mesh], 0, 0); + } + std::vector to_copy = { + transition(target_.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)}; + if (gbuffer_) + for (ID3D12Resource* r : {gbuffer_normal_.p, gbuffer_depth_.p}) + to_copy.push_back(transition(r, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)); + if (compute_) { + to_copy.push_back(transition(particle_instances_.p, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_COPY_SOURCE)); + to_copy.push_back(transition(particle_state_.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)); + } + list_->ResourceBarrier(UINT(to_copy.size()), to_copy.data()); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback_.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {target_format_, kWidth, kHeight, 1, kPitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target_.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list_->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + if (compute_) { + list_->CopyBufferRegion(readback_.p, kOffState, particle_state_.p, 0, kStateBytes); + list_->CopyBufferRegion(readback_.p, kOffInstances, particle_instances_.p, 0, kInstanceBytes); + } + std::vector back; + if (compute_) + for (ID3D12Resource* r : {particle_instances_.p, particle_state_.p}) + back.push_back(transition(r, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)); + if (!back.empty()) list_->ResourceBarrier(UINT(back.size()), back.data()); + CHECK(list_->Close() == S_OK); + if (wait_compute) CHECK(compute_ && SUCCEEDED(queue_->Wait(compute_fence_.p, wait_compute))); + ID3D12CommandList* lists[] = {list_.p}; + queue_->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue_->Signal(fence_.p, ++fence_value_))); + return true; +} + +bool Gpu::finish_frame(std::vector& pixels, Readback* readback) { + CHECK(wait_fence(fence_, fence_value_)); + void* mapped = nullptr; + CHECK(SUCCEEDED(readback_->Map(0, nullptr, &mapped))); + const auto* bytes = static_cast(mapped); + pixels.resize(std::size_t(kWidth) * kHeight); + if (target_format_ == DXGI_FORMAT_R8G8B8A8_UNORM) { // stage 9's albedo: code / 255 + for (unsigned y = 0; y < kHeight; ++y) + for (unsigned x = 0; x < kWidth; ++x) + for (unsigned c = 0; c < 4; ++c) + pixels[std::size_t(y) * kWidth + x][c] = float(bytes[y * kPitch + x * 4 + c]) / 255.0f; + } else if (target_format_ == DXGI_FORMAT_R16G16B16A16_FLOAT) { + for (unsigned y = 0; y < kHeight; ++y) + for (unsigned x = 0; x < kWidth; ++x) + for (unsigned c = 0; c < 4; ++c) { + std::uint16_t h; + std::memcpy(&h, bytes + y * kPitch + (x * 4 + c) * 2, 2); + pixels[std::size_t(y) * kWidth + x][c] = half_value(h); + } + } else { + for (unsigned y = 0; y < kHeight; ++y) + std::memcpy(pixels.data() + std::size_t(y) * kWidth, bytes + y * kPitch, kWidth * sizeof(Color)); + } + if (readback) { + const auto take = [&](auto& out, std::uint64_t offset, std::size_t count) { + out.resize(count); + std::memcpy(out.data(), bytes + offset, count * sizeof(out[0])); + }; + take(readback->state, kOffState, kParticles); + take(readback->instances, kOffInstances, kParticles); + } + readback_->Unmap(0, nullptr); + return true; +} + +bool Gpu::submit_compute(unsigned steps, std::uint64_t& signalled) { + CHECK(compute_); + // The allocator is reused: the previous compute submission must be done (it signalled compute_value_). + CHECK(wait_fence(compute_fence_, compute_value_)); + CHECK(SUCCEEDED(compute_allocator_->Reset())); + CHECK(SUCCEEDED(compute_list_->Reset(compute_allocator_.p, compute_pso_.p))); + const std::vector written = {particle_state_.p, particle_instances_.p}; + std::vector to_uav, back_to_common; + for (ID3D12Resource* r : written) { + to_uav.push_back(transition(r, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)); + back_to_common.push_back(transition(r, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON)); + } + compute_list_->ResourceBarrier(UINT(to_uav.size()), to_uav.data()); + compute_list_->SetComputeRootSignature(compute_root_.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap_.p}; + compute_list_->SetDescriptorHeaps(1, heaps); + const UINT constants[4] = {UINT(kTop), UINT(kRange), kParticles, 0}; + compute_list_->SetComputeRoot32BitConstants(0, 4, constants, 0); + // The compute V#s follow the graphics ones (fill_descriptors); the table's first slot is the state. + const std::uint64_t first = srv_gpu_ + srv_compute_slot_ * srv_step_; + compute_list_->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{first}); + D3D12_RESOURCE_BARRIER uav[2] = {}; + uav[0].Type = uav[1].Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + uav[0].UAV.pResource = particle_state_.p; + uav[1].UAV.pResource = particle_instances_.p; + for (unsigned k = 0; k < steps; ++k) { + compute_list_->Dispatch(kParticles / 64, 1, 1); + compute_list_->ResourceBarrier(2, uav); // the next step reads what this one wrote + } + compute_list_->ResourceBarrier(UINT(back_to_common.size()), back_to_common.data()); + CHECK(compute_list_->Close() == S_OK); + ID3D12CommandList* lists[] = {compute_list_.p}; + compute_queue_->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(compute_queue_->Signal(compute_fence_.p, ++compute_value_))); + signalled = compute_value_; + return true; +} + +bool Gpu::bind_textures(ID3D12Resource* floor, ID3D12Resource* solid) { + CHECK(textured_ && floor && solid); + // The texture slots follow the compute ones (fill_descriptors): the mosaic, then the squares. + for (unsigned t = 0; t < 2; ++t) { + ID3D12Resource* texture = t ? solid : floor; + const D3D12_RESOURCE_DESC desc = texture->GetDesc(); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = desc.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = desc.MipLevels; + device_->CreateShaderResourceView(texture, &srv, + D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(srv_cpu_ + (srv_texture_slot_ + t) * srv_step_)}); + } + const D3D12_DESCRIPTOR_HEAP_DESC sampler_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&sampler_desc, IID_PPV_ARGS(&sampler_heap_.p)))); + D3D12_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; + sampler.MaxAnisotropy = 1; + sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + device_->CreateSampler(&sampler, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(heap_cpu(sampler_heap_.p))}); + textures_bound_ = true; + return true; +} + +bool Gpu::idle() { + CHECK(wait_fence(fence_, fence_value_)); + if (compute_) CHECK(wait_fence(compute_fence_, compute_value_)); + return true; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_gpu.h b/runtime/test/lanterns/lanterns_gpu.h new file mode 100644 index 0000000000..e69f87ae77 --- /dev/null +++ b/runtime/test/lanterns/lanterns_gpu.h @@ -0,0 +1,126 @@ +// Lanterns: the GPU side, through the D3D12 API only. The device comes from the D3D12XboxCreateDevice the guest +// imports from d3d12_xs.dll (test/fixtures/tiny_frame.cpp does the same); pipelines come from the shader +// containers fssm_pack.py wrote. See lanterns.cpp for what each stage draws and checks. +#pragma once + +#include "../d3d12_test_shaders.h" +#include "lanterns_particles.h" +#include "lanterns_post.h" +#include "lanterns_scene.h" + +#include +#include +#include +#include + +namespace lanterns { + +using Color = std::array; +using d3d12test::Ref; + +constexpr DXGI_FORMAT kGbufferNormalFormat = DXGI_FORMAT_R10G10B10A2_UNORM, kGbufferDepthFormat = DXGI_FORMAT_R32_FLOAT; + +// The containers the guest hands to the pipelines, read from the folder fssm_pack.py wrote. +struct Shaders { + std::vector vs, ps_lit, ps_floor, unknown_vs, rebuilt_vs, vs_w64, ps_lit_w64, cs_rise; + std::vector ps_tex_floor, ps_tex_solid; // stage 6: they replace ps_floor and ps_lit + std::vector ps_shadow; // stage 8: replaces both + std::vector vs_gbuf, ps_gbuf; // stage 9: replace vs and both pixel shaders +}; +// stage 1: graphics only; 3 and 5: plus cs_lanterns_rise; 6: plus the textured pixel shaders; 8: plus the shadow +// pixel shader. +bool load_shaders(const std::filesystem::path& dir, int stage, Shaders& out); + +// What a frame's readback holds besides the pixels (stages 3 and 5). +struct Readback { + std::vector state; + std::vector instances; // what cs_lanterns_rise wrote +}; + +// The scene's meshes as one vertex array and one 16-bit index array (each face fanned), with where each mesh starts, +// and the uploaded instances of the draws that do not take theirs from the compute shader. +struct Geometry { + std::vector vertices; + std::vector indices; + std::vector first_vertex, vertex_count, first_index, index_count; + std::vector instances; + std::vector first_instance; +}; + +class Gpu { +public: + // Device, pipelines, buffers, and an initial direct-queue submission that copies the uploads into the DEFAULT + // buffers (and the particles' first state, when the shaders include the compute shader). + // target_format: R32G32B32A32_FLOAT (the other stages) or R16G16B16A16_FLOAT (stage 5's HDR target, which the post-process + // reads; finish_frame returns its pixels widened to float). + bool create(const Scene& scene, const Shaders& shaders, + DXGI_FORMAT target_format = DXGI_FORMAT_R32G32B32A32_FLOAT); + // Records and submits one frame on the direct queue. With wait_compute != 0 the queue first waits for the + // compute fence to reach that value (which may be signalled by a submission made after this one). + bool submit_frame(const Scene& scene, bool depth_test, std::uint64_t wait_compute = 0); + // Waits for the last frame and reads back its pixels (and, if asked, the particle state and instance records). + bool finish_frame(std::vector& pixels, Readback* readback = nullptr); + // Submits `steps` dispatches of cs_lanterns_rise on the compute queue and signals the fence. + bool submit_compute(unsigned steps, std::uint64_t& signalled); + std::uint64_t next_compute_value() const { return compute_value_ + 1; } + // Stage 6: the textures' SRVs (the floor's mosaic, the solids' squares) and the sampler, before the first frame. + bool bind_textures(ID3D12Resource* floor, ID3D12Resource* solid); + // Stage 8: the light (its clip matrix for the depth pass, the shadow pixel shader's three rows after the camera's + // matrix) and whether the depth pass draws the casters (false: the map stays cleared to 1, the control). + bool set_light(const std::array& clip, const std::array& rows); + void set_shadow_casters(bool casters) { shadow_casters_ = casters; } + // Waits until both queues are idle (before the objects are released). + bool idle(); + // For the post-process (stage 5), which records on the same device and queue after the frame. Between frames the + // target is in COPY_SOURCE. + ID3D12Device* device() const { return device_.p; } + ID3D12CommandQueue* queue() const { return queue_.p; } + ID3D12Resource* target() const { return target_.p; } + // Stage 9 (create with R8G8B8A8_UNORM): the target is the G-buffer's albedo; these are its normal and view depth, + // left in NON_PIXEL_SHADER_RESOURCE after each frame. + ID3D12Resource* gbuffer_normal() const { return gbuffer_normal_.p; } + ID3D12Resource* gbuffer_depth() const { return gbuffer_depth_.p; } + +private: + bool create_pipelines(const Shaders& shaders); + bool create_compute(const Shaders& shaders); + bool create_shadow(); // lanterns_shadow_gpu.cpp + void record_shadow_pass(const Scene& scene); // lanterns_shadow_gpu.cpp + void bind_draw(const Scene& scene, std::size_t d); + bool create_resources(const Scene& scene); + bool initialize(const Scene& scene); + bool fill_descriptors(const Scene& scene); + + // Declared first, released last: everything below is a child of the device. + Ref device_; + Ref root_, compute_root_; + Ref pso_[2][2]; // [floor][depth test] + Ref pso_w64_[2]; // [depth test]: the wave64 pair, for the draws marked wave64 + Ref compute_pso_; + Ref shadow_map_, gbuffer_normal_, gbuffer_depth_; + bool gbuffer_ = false, gbuffer_written_ = false; + std::vector vs_; + Ref shadow_pso_; + D3D12_CPU_DESCRIPTOR_HANDLE shadow_dsv_{}; + bool shadow_ = false, shadow_casters_ = true, shadow_written_ = false; + std::uint64_t upload_light_ = 0; + Ref vertex_buffer_, index_buffer_, instance_buffer_, upload_, readback_, target_, depth_; + Ref particle_state_, particle_instances_; + Ref srv_heap_, rtv_heap_, dsv_heap_, sampler_heap_; + Ref queue_, compute_queue_; + Ref allocator_, compute_allocator_; + Ref list_, compute_list_; + Ref fence_, compute_fence_; + Geometry geometry_; + DXGI_FORMAT target_format_ = DXGI_FORMAT_R32G32B32A32_FLOAT; + bool compute_ = false, textured_ = false, textures_bound_ = false; + std::uint64_t srv_texture_slot_ = 0; // the two texture SRVs (stage 6), after the compute tables + std::uint64_t upload_vb_ = 0, upload_ib_ = 0, upload_inst_ = 0, upload_cbv_ = 0, upload_particles_ = 0; + std::uint64_t srv_cpu_ = 0, srv_gpu_ = 0; + UINT srv_step_ = 0; + std::uint64_t srv_compute_slot_ = 0; // the compute table's first slot (after the graphics V#s) + D3D12_CPU_DESCRIPTOR_HANDLE rtv_{}, dsv_{}; + UINT64 fence_value_ = 0, compute_value_ = 0; +}; + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_particles.h b/runtime/test/lanterns/lanterns_particles.h new file mode 100644 index 0000000000..114156360c --- /dev/null +++ b/runtime/test/lanterns/lanterns_particles.h @@ -0,0 +1,80 @@ +// Lanterns, stage 3: the rising light points. Their state lives on the GPU and a compute shader +// (shaders/cs_lanterns_rise.asm) moves it one step per dispatch; this is the same integer arithmetic on the CPU, so the +// state the GPU reads back can be compared word for word, and the instance records it writes for the draw bit for bit. +// Positions are fixed point in 1/256 units: converting them to float and scaling by 1/256 is exact. +#pragma once + +#include "lanterns_scene.h" + +#include +#include +#include + +namespace lanterns { + +constexpr unsigned kParticles = 256; // 4 groups of 64 threads +constexpr std::int32_t kTop = 896; // 3.5 units: a point at or above it ... +constexpr std::int32_t kRange = 832; // ... drops back by 3.25 units +constexpr unsigned kStepsPerFrame = 24; + +// One point as cs_lanterns_rise.asm reads and writes it through its state V# (stride 16). +struct Particle { + std::int32_t x, y, z; + std::uint32_t packed; // bits 0-7: rise per step (1/256 units); bit 8: big; bits 9-10: green; bits 11-12: blue +}; +static_assert(sizeof(Particle) == 16); + +inline std::vector initial_particles() { + std::vector p(kParticles); + for (unsigned i = 0; i < kParticles; ++i) { + p[i].x = (std::int32_t((i * 53) % 193) - 96) * 6; // -2.25 .. 2.25 units + p[i].z = std::int32_t((i * 29) % 113) * 12 - 256; // -1 .. 4.3 units + p[i].y = 64 + std::int32_t((i * 97) % 832); // 0.25 .. 3.5 units + p[i].packed = (4 + (i * 7) % 9) | (((i * 13) & 0xff) << 8); + } + return p; +} + +// One dispatch of cs_lanterns_rise.asm: y += speed; if (y >= top) y -= range. +inline void step_particles(std::vector& p) { + for (Particle& q : p) { + q.y += std::int32_t(q.packed & 0xff); + if (q.y >= kTop) q.y -= kRange; + } +} + +// The instance record the same dispatch writes for each point (what the draw's instance V# reads). +inline Instance particle_instance(const Particle& q) { + const float big = float((q.packed >> 8) & 1), green = float(5 + ((q.packed >> 9) & 3)), + blue = float(1 + ((q.packed >> 11) & 3)); + return {{float(q.x) * 0.00390625f, float(q.y) * 0.00390625f, float(q.z) * 0.00390625f}, + 0.125f + 0.0625f * big, + {1.0f, green * 0.125f, blue * 0.125f, 1.0f}}; +} + +inline std::vector particle_instances(const std::vector& p) { + std::vector out; + for (const Particle& q : p) out.push_back(particle_instance(q)); + return out; +} + +// A light point: an octahedron with every face at full shade, so it reads as one bright diamond. +inline Mesh light_point() { + Mesh m = octahedron(1.0); + m.name = "light point"; + for (Vertex& v : m.vertices) v.shade = 1.0f; + return m; +} + +// Stage 3: stage 1's scene plus the points as a sixth draw, whose instances come from the compute shader on the GPU. +// The instances here are what the reference draws: the CPU's simulation of the same steps. +inline Scene stage3(const std::vector& state) { + Scene s = stage1(); + s.meshes.push_back(light_point()); + Draw points{unsigned(s.meshes.size() - 1), false, particle_instances(state), rotation_y(0), {1.0f, 1.0f, 1.0f, 1.0f}}; + points.gpu_instances = true; + s.draws.push_back(points); + return s; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_post.h b/runtime/test/lanterns/lanterns_post.h new file mode 100644 index 0000000000..e9a8032020 --- /dev/null +++ b/runtime/test/lanterns/lanterns_post.h @@ -0,0 +1,194 @@ +// Lanterns stage 5: the post-process and its CPU reference. The scene is drawn into an R16G16B16A16_FLOAT target, as +// a game draws into an HDR target. Then: +// cs_lanterns_bloom_h (wave32, 128 lanes: four waves sharing LDS) keeps what is brighter than kBloomThreshold, +// quantized to 1/kBloomSteps, and blurs it along rows with the 9-tap binomial filter; +// cs_lanterns_bloom_v (wave64, two waves, along columns) blurs that result; +// ps_lanterns_composite (fullscreen, SV_Position) adds the blur times kBloomGain to the scene, into the final target. +// The arithmetic is exact by construction: a quantized value is a small integer (q < 64), each blur sums integer +// multiples of it (weights 1..70, total 256), so both sums are integers below 2^20, and the composite adds an +// integer times 2^-21 to an fp16 value. post_reference() computes it in float as the shaders do, checks every value +// against the same computation in double, and says per pixel either "this exact colour" or "between these bounds" +// (where the stage-1 reference is uncertain: the bounds come from its candidates, through the monotone blur). +#pragma once + +#include "lanterns_reference.h" + +#include +#include +#include +#include +#include +#include + +namespace lanterns { + +constexpr float kBloomThreshold = 0.625f; +constexpr float kBloomSteps = 64.0f; // quantization of (colour - threshold) +constexpr int kBloomRadius = 4; // 9 taps +constexpr float kBloomWeights[2 * kBloomRadius + 1] = {1, 8, 28, 56, 70, 56, 28, 8, 1}; +constexpr float kBloomGain = 0x1p-19f; // 8 / (64 * 256 * 256): a fully bright area adds 8 * (c - 0.625) + +// float -> fp16 bits, rounding to nearest even (what a render target write of a float16 format does). +inline std::uint16_t half_bits(float value) { + std::uint32_t x; + std::memcpy(&x, &value, 4); + const std::uint32_t sign = (x >> 16) & 0x8000u, mag = x & 0x7fffffffu; + if (mag >= 0x7f800000u) return std::uint16_t(sign | 0x7c00u | (mag > 0x7f800000u ? 0x200u : 0u)); + if (mag >= 0x477ff000u) return std::uint16_t(sign | 0x7c00u); // rounds past 65504 + if (mag < 0x38800000u) // below 2^-14: subnormal or zero + return std::uint16_t(sign | std::uint32_t(std::nearbyint(std::fabs(value) * 0x1p24f))); + return std::uint16_t(sign | ((mag - (112u << 23) + 0xfffu + ((mag >> 13) & 1u)) >> 13)); +} + +inline float half_value(std::uint16_t h) { + const std::uint32_t sign = std::uint32_t(h & 0x8000u) << 16, exponent = (h >> 10) & 0x1fu, mantissa = h & 0x3ffu; + float magnitude; + if (exponent == 0) magnitude = float(mantissa) * 0x1p-24f; + else if (exponent == 31) magnitude = mantissa ? NAN : INFINITY; + else magnitude = std::ldexp(float(mantissa | 0x400u), int(exponent) - 25); + std::uint32_t bits; + std::memcpy(&bits, &magnitude, 4); + bits |= sign; + float out; + std::memcpy(&out, &bits, 4); + return out; +} + +inline Color to_half(const Color& c) { + return {half_value(half_bits(c[0])), half_value(half_bits(c[1])), half_value(half_bits(c[2])), + half_value(half_bits(c[3]))}; +} + +// The stage-1 reference of a frame drawn into the fp16 target: every colour and candidate rounded to fp16. +inline Reference half_reference(const Reference& ref) { + Reference out = ref; + for (auto& c : out.color) c = to_half(c); + for (auto& list : out.candidates) { + std::vector rounded; + for (const Color& c : list) detail::add_unique(rounded, to_half(c)); + list = rounded.size() > 1 ? std::move(rounded) : std::vector{}; + } + return out; +} + +// What cs_lanterns_bloom_h does to one channel before the blur: floor(max(c - threshold, 0) * steps). +inline float bloom_quantize(float c) { return std::floor(std::max(c - kBloomThreshold, 0.0f) * kBloomSteps); } + +struct PostReference { + std::vector lo, hi; // bounds of the final colour, per channel; equal where certain + std::vector certain; + std::vector bloom; // certain pixels the bloom changes: where skipping the blur must differ + unsigned bloom_pixels = 0; // how many of them + unsigned inexact = 0; // values where float and double disagree (0, by construction) +}; + +namespace detail { + +// One separable pass over per-channel bounds: out(x, y) = sum_k w_k in(x + (k - r) * step, clamped). +inline void blur(const std::vector& in, std::vector& out, bool rows, unsigned& inexact) { + out.assign(in.size(), Color{}); + for (unsigned y = 0; y < kHeight; ++y) + for (unsigned x = 0; x < kWidth; ++x) + for (int ch = 0; ch < 3; ++ch) { + float acc = 0.0f; + double exact = 0.0; + for (int k = 0; k <= 2 * kBloomRadius; ++k) { + const int d = k - kBloomRadius; + const int sx = rows ? std::clamp(int(x) + d, 0, int(kWidth) - 1) : int(x); + const int sy = rows ? int(y) : std::clamp(int(y) + d, 0, int(kHeight) - 1); + const float v = in[std::size_t(sy) * kWidth + sx][ch]; + acc = std::fma(kBloomWeights[k], v, acc); + exact += double(kBloomWeights[k]) * v; + } + inexact += double(acc) != exact; + out[std::size_t(y) * kWidth + x][ch] = acc; + } +} + +} // namespace detail + +// The final frame of stage 5 for the scene whose stage-1 reference (depth test on) is ref. +inline PostReference post_reference(const Reference& ref) { + const Reference scene = half_reference(ref); + const std::size_t n = scene.color.size(); + std::vector qlo(n), qhi(n), slo(n), shi(n); + for (std::size_t i = 0; i < n; ++i) { + const auto& cand = scene.candidates[i]; + const std::vector one{scene.color[i]}; + const auto& list = cand.empty() ? one : cand; + for (int ch = 0; ch < 4; ++ch) { + float lo = INFINITY, hi = -INFINITY; + for (const Color& c : list) lo = std::min(lo, c[ch]), hi = std::max(hi, c[ch]); + slo[i][ch] = lo, shi[i][ch] = hi; + qlo[i][ch] = ch < 3 ? bloom_quantize(lo) : 0.0f; + qhi[i][ch] = ch < 3 ? bloom_quantize(hi) : 0.0f; + } + } + PostReference out; + std::vector hlo, hhi, vlo, vhi; + detail::blur(qlo, hlo, true, out.inexact); + detail::blur(qhi, hhi, true, out.inexact); + detail::blur(hlo, vlo, false, out.inexact); + detail::blur(hhi, vhi, false, out.inexact); + out.lo.resize(n), out.hi.resize(n), out.certain.resize(n), out.bloom.resize(n); + for (std::size_t i = 0; i < n; ++i) { + bool certain = scene.candidates[i].empty(), changes = false; + for (int ch = 0; ch < 4; ++ch) { + const float lo = std::fma(vlo[i][ch], kBloomGain, slo[i][ch]); + const float hi = std::fma(vhi[i][ch], kBloomGain, shi[i][ch]); + out.inexact += double(lo) != double(vlo[i][ch]) * kBloomGain + slo[i][ch]; + out.inexact += double(hi) != double(vhi[i][ch]) * kBloomGain + shi[i][ch]; + out.lo[i][ch] = lo, out.hi[i][ch] = hi; + certain = certain && vlo[i][ch] == vhi[i][ch]; + changes = changes || vlo[i][ch] != 0.0f; + } + out.certain[i] = certain; + out.bloom[i] = certain && changes; + out.bloom_pixels += out.bloom[i]; + } + return out; +} + +// Certain pixels must equal the reference bit for bit; the others must lie within their bounds. +inline Comparison compare_post(const std::vector& gpu, const PostReference& ref) { + Comparison c; + bool reported = false; + for (std::size_t i = 0; i < gpu.size(); ++i) { + bool ok; + if (ref.certain[i]) { + ++c.certain; + ok = detail::same(gpu[i], ref.lo[i]); + c.certain_exact += ok; + } else { + ++c.uncertain; + ok = true; + for (int ch = 0; ch < 4; ++ch) ok = ok && gpu[i][ch] >= ref.lo[i][ch] && gpu[i][ch] <= ref.hi[i][ch]; + c.uncertain_plausible += ok; + } + if (!ok && !reported) { + reported = true; + c.first_bad_x = unsigned(i % kWidth), c.first_bad_y = unsigned(i / kWidth); + c.first_bad_gpu = gpu[i], c.first_bad_ref = ref.lo[i]; + } + } + return c; +} + +// How many certain pixels of a frame differ from the reference. +inline unsigned certain_differences(const std::vector& frame, const PostReference& ref) { + unsigned n = 0; + for (std::size_t i = 0; i < frame.size(); ++i) n += ref.certain[i] && !detail::same(frame[i], ref.lo[i]); + return n; +} + +// How many certain pixels break the skipped-blur prediction: a pixel the bloom changes that the frame leaves equal to +// the reference, or a pixel the bloom leaves alone that the frame changes. A count alone would accept a mask of the +// right size in the wrong place. +inline unsigned misplaced_differences(const std::vector& frame, const PostReference& ref) { + unsigned n = 0; + for (std::size_t i = 0; i < frame.size(); ++i) + n += ref.certain[i] && bool(ref.bloom[i]) == detail::same(frame[i], ref.lo[i]); + return n; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_post_gpu.cpp b/runtime/test/lanterns/lanterns_post_gpu.cpp new file mode 100644 index 0000000000..7fada6f6c6 --- /dev/null +++ b/runtime/test/lanterns/lanterns_post_gpu.cpp @@ -0,0 +1,235 @@ +// Lanterns stage 5: the post-process on the GPU (lanterns_post_gpu.h). The texture SRVs go through +// CreateShaderResourceView, as test/d3d12_m2_textured_test.cpp (M2) makes its T#s; the buffers get raw V#s written +// through the CPU handle, as the rest of Lanterns does. +#include "lanterns_post_gpu.h" + +#include "lanterns_d3d12.h" + +#include + +using namespace d3d12test; + +namespace lanterns { +namespace { + +constexpr std::uint32_t kPixels = kWidth * kHeight; +constexpr std::uint64_t kBufferBytes = std::uint64_t(kPixels) * 16; // one float4 per pixel +constexpr std::uint64_t kImageBytes = std::uint64_t(kPitch) * kHeight; +// Descriptor slots (32 bytes apart): three tables of two. +constexpr unsigned kRowsTable = 0; // [scene T#, rows V#] cs_lanterns_bloom_h +constexpr unsigned kColumnsTable = 2; // [rows V#, bloom V#] cs_lanterns_bloom_v +constexpr unsigned kCompositeTable = 4; // [scene T#, bloom V#] ps_lanterns_composite +constexpr unsigned kControlTable = 6; // [scene T#, zero V#] ps_lanterns_composite, skip_blur +constexpr unsigned kSlots = 8; + +} // namespace + +bool load_post_shaders(const std::filesystem::path& dir, PostShaders& out) { + out.bloom_h = read_file(dir / "cs_lanterns_bloom_h.dxbc"); + out.bloom_h_no_barrier = read_file(dir / "cs_lanterns_bloom_h_nobarrier.dxbc"); + out.bloom_v = read_file(dir / "cs_lanterns_bloom_v.dxbc"); + out.vs_full = read_file(dir / "vs_lanterns_full.dxbc"); + out.ps_composite = read_file(dir / "ps_lanterns_composite.dxbc"); + for (const auto* blob : {&out.bloom_h, &out.bloom_h_no_barrier, &out.bloom_v, &out.vs_full, &out.ps_composite}) + CHECK(blob->size() > 64); + return true; +} + +bool Post::create(Gpu& gpu, const PostShaders& shaders) { + device_ = gpu.device(); + queue_ = gpu.queue(); + scene_ = gpu.target(); + CHECK(device_ && queue_ && scene_ && scene_->GetDesc().Format == DXGI_FORMAT_R16G16B16A16_FLOAT); + CHECK(create_pipelines(shaders)); + CHECK(create_resources()); + CHECK(fill_descriptors()); + CHECK(SUCCEEDED(device_->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator_.p)))); + CHECK(SUCCEEDED(device_->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator_.p, nullptr, + IID_PPV_ARGS(&list_.p)))); + CHECK(list_->Close() == S_OK); + CHECK(SUCCEEDED(device_->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence_.p)))); + return true; +} + +// One table of two descriptors, [0] t0 and [1] u0 for compute, t0 and t1 for graphics -> s[0:1] in every shader here. +static bool make_root(ID3D12Device* device, bool compute, Ref& out) { + D3D12_DESCRIPTOR_RANGE ranges[2] = { + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}, + {compute ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, compute ? 0u : 1u, 0, 1}}; + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + param.DescriptorTable = {2, ranges}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; + desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + desc.Desc_1_0 = {1, ¶m, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto blob = serialize_root_signature(desc); + CHECK(!blob.empty()); + CHECK(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&out.p)))); + return true; +} + +bool Post::create_pipelines(const PostShaders& shaders) { + CHECK(make_root(device_, true, compute_root_)); + CHECK(make_root(device_, false, graphics_root_)); + D3D12_COMPUTE_PIPELINE_STATE_DESC cs{}; + cs.pRootSignature = compute_root_.p; + const std::pair*, Ref*> computes[] = { + {&shaders.bloom_h, &bloom_h_}, {&shaders.bloom_h_no_barrier, &bloom_h_no_barrier_}, {&shaders.bloom_v, &bloom_v_}}; + for (const auto& [code, pso] : computes) { + cs.CS = {code->data(), code->size()}; + CHECK(SUCCEEDED(device_->CreateComputePipelineState(&cs, IID_PPV_ARGS(&pso->p)))); + } + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = graphics_root_.p; + desc.VS = {shaders.vs_full.data(), shaders.vs_full.size()}; + desc.PS = {shaders.ps_composite.data(), shaders.ps_composite.size()}; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + desc.SampleMask = 0xffffffff; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + desc.SampleDesc.Count = 1; + CHECK(SUCCEEDED(device_->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&composite_.p)))); + return true; +} + +bool Post::create_resources() { + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT, {}, {}, 0, 0}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD, {}, {}, 0, 0}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK, {}, {}, 0, 0}; + const auto make = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, + Ref& out) { + return SUCCEEDED(device_->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(&out.p))); + }; + const auto uav = buffer_desc(kBufferBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + CHECK(make(default_heap, uav, D3D12_RESOURCE_STATE_COMMON, rows_)); + CHECK(make(default_heap, uav, D3D12_RESOURCE_STATE_COMMON, bloom_)); + CHECK(make(upload_heap, buffer_desc(kBufferBytes), D3D12_RESOURCE_STATE_GENERIC_READ, zero_)); + CHECK(make(readback_heap, buffer_desc(kImageBytes), D3D12_RESOURCE_STATE_COPY_DEST, readback_)); + void* mapped = nullptr; + CHECK(SUCCEEDED(zero_->Map(0, nullptr, &mapped))); + std::memset(mapped, 0, kBufferBytes); + zero_->Unmap(0, nullptr); + D3D12_RESOURCE_DESC tex{}; + tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + tex.Width = kWidth; + tex.Height = kHeight; + tex.DepthOrArraySize = 1; + tex.MipLevels = 1; + tex.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + tex.SampleDesc.Count = 1; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + CHECK(make(default_heap, tex, D3D12_RESOURCE_STATE_COMMON, final_)); + return true; +} + +bool Post::fill_descriptors() { + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, kSlots, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap_.p)))); + const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap_.p)))); + const std::uint64_t cpu = heap_cpu(heap_.p); + heap_gpu_ = heap_gpu(heap_.p); + step_ = device_->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + // The shaders load the second descriptor of a table 0x20 bytes after the first. + CHECK(cpu && heap_gpu_ >= 0x10000 && step_ == 32); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + for (unsigned slot : {kRowsTable, kCompositeTable, kControlTable}) + device_->CreateShaderResourceView(scene_, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + slot * step_)}); + const auto put = [&](unsigned slot, ID3D12Resource* buffer) { + const auto v = make_vsharp(buffer->GetGPUVirtualAddress(), 16, kPixels); + std::memcpy(reinterpret_cast(cpu + slot * step_), v.data(), 16); + }; + put(kRowsTable + 1, rows_.p); + put(kColumnsTable, rows_.p); + put(kColumnsTable + 1, bloom_.p); + put(kCompositeTable + 1, bloom_.p); + put(kControlTable + 1, zero_.p); + rtv_ = {SIZE_T(heap_cpu(rtv_heap_.p))}; + device_->CreateRenderTargetView(final_.p, nullptr, rtv_); + return true; +} + +void Post::record_blur(PostMode mode) { + list_->SetComputeRootSignature(compute_root_.p); + list_->SetPipelineState(mode == PostMode::no_barrier ? bloom_h_no_barrier_.p : bloom_h_.p); + list_->SetComputeRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{heap_gpu_ + kRowsTable * step_}); + list_->Dispatch(kWidth / 128, kHeight, 1); + D3D12_RESOURCE_BARRIER uav{}; + uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + uav.UAV.pResource = rows_.p; + list_->ResourceBarrier(1, &uav); // the column pass reads what the row pass wrote + list_->SetPipelineState(bloom_v_.p); + list_->SetComputeRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{heap_gpu_ + kColumnsTable * step_}); + list_->Dispatch(kWidth, kHeight / 128, 1); +} + +bool Post::run(PostMode mode, std::vector& pixels) { + CHECK(SUCCEEDED(allocator_->Reset())); + CHECK(SUCCEEDED(list_->Reset(allocator_.p, nullptr))); + const auto read_states = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + const D3D12_RESOURCE_BARRIER before[] = { + transition(scene_, D3D12_RESOURCE_STATE_COPY_SOURCE, read_states), + transition(rows_.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + transition(bloom_.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + transition(final_.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list_->ResourceBarrier(4, before); + ID3D12DescriptorHeap* heaps[] = {heap_.p}; + list_->SetDescriptorHeaps(1, heaps); + if (mode != PostMode::skip_blur) record_blur(mode); + const D3D12_RESOURCE_BARRIER to_read = transition(bloom_.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + list_->ResourceBarrier(1, &to_read); + list_->SetGraphicsRootSignature(graphics_root_.p); + list_->SetPipelineState(composite_.p); + const unsigned table = mode == PostMode::skip_blur ? kControlTable : kCompositeTable; + list_->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{heap_gpu_ + table * step_}); + const D3D12_VIEWPORT viewport{0, 0, float(kWidth), float(kHeight), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(kWidth), LONG(kHeight)}; + list_->RSSetViewports(1, &viewport); + list_->RSSetScissorRects(1, &scissor); + list_->OMSetRenderTargets(1, &rtv_, FALSE, nullptr); + list_->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list_->DrawInstanced(3, 1, 0, 0); + const D3D12_RESOURCE_BARRIER to_copy = transition(final_.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list_->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback_.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, kWidth, kHeight, 1, kPitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = final_.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list_->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + const D3D12_RESOURCE_BARRIER after[] = { + transition(scene_, read_states, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(rows_.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON), + transition(bloom_.p, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON), + transition(final_.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)}; + list_->ResourceBarrier(4, after); + CHECK(list_->Close() == S_OK); + ID3D12CommandList* lists[] = {list_.p}; + queue_->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue_->Signal(fence_.p, ++fence_value_))); + CHECK(wait_fence(fence_, fence_value_)); + void* mapped = nullptr; + CHECK(SUCCEEDED(readback_->Map(0, nullptr, &mapped))); + const auto* bytes = static_cast(mapped); + pixels.resize(kPixels); + for (unsigned y = 0; y < kHeight; ++y) + std::memcpy(pixels.data() + std::size_t(y) * kWidth, bytes + y * kPitch, kWidth * sizeof(Color)); + readback_->Unmap(0, nullptr); + return true; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_post_gpu.h b/runtime/test/lanterns/lanterns_post_gpu.h new file mode 100644 index 0000000000..ca5abb24f7 --- /dev/null +++ b/runtime/test/lanterns/lanterns_post_gpu.h @@ -0,0 +1,54 @@ +// Lanterns stage 5: the post-process on the GPU (what it computes: lanterns_post.h). It records on the device and the +// direct queue of a Gpu whose target is R16G16B16A16_FLOAT, after that Gpu's frame: two wave64 compute passes with LDS +// and s_barrier, then a fullscreen pixel shader that reads the scene through a T# and the blur through a V#. +#pragma once + +#include "lanterns_gpu.h" + +#include +#include +#include + +namespace lanterns { + +struct PostShaders { + std::vector bloom_h, bloom_h_no_barrier, bloom_v, vs_full, ps_composite; +}; +bool load_post_shaders(const std::filesystem::path& dir, PostShaders& out); + +enum class PostMode { + full, // blur rows, blur columns, composite + no_barrier, // the same with cs_lanterns_bloom_h_nobarrier (a measured control) + skip_blur, // composite with a zero bloom buffer (the control the reference predicts) +}; + +class Post { +public: + // The Gpu must outlive this object (its device owns everything here) and must have been created with the fp16 target. + bool create(Gpu& gpu, const PostShaders& shaders); + // One submission on the Gpu's queue, waited for: the passes of the mode and a readback of the final target. + bool run(PostMode mode, std::vector& pixels); + +private: + bool create_pipelines(const PostShaders& shaders); + bool create_resources(); + bool fill_descriptors(); + void record_blur(PostMode mode); + + ID3D12Device* device_ = nullptr; // the Gpu's + ID3D12CommandQueue* queue_ = nullptr; // the Gpu's direct queue + ID3D12Resource* scene_ = nullptr; // the Gpu's target + Ref compute_root_, graphics_root_; + Ref bloom_h_, bloom_h_no_barrier_, bloom_v_, composite_; + Ref rows_, bloom_, zero_, final_, readback_; + Ref heap_, rtv_heap_; + Ref allocator_; + Ref list_; + Ref fence_; + std::uint64_t heap_gpu_ = 0; + UINT step_ = 0; + D3D12_CPU_DESCRIPTOR_HANDLE rtv_{}; + UINT64 fence_value_ = 0; +}; + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_reference.h b/runtime/test/lanterns/lanterns_reference.h new file mode 100644 index 0000000000..f3d4129252 --- /dev/null +++ b/runtime/test/lanterns/lanterns_reference.h @@ -0,0 +1,331 @@ +// Lanterns: the CPU reference for a stage-1 frame. It rasterizes the scene of lanterns_scene.h in double precision, +// face by face (each face is a convex polygon; the GPU draws it as a triangle fan, which covers the same pixels), and +// says for every pixel either "this exact colour" or "uncertain, one of these colours". A pixel is uncertain when a +// tiny change in where the GPU puts a vertex could change it: its centre lies within kMargin pixels of a face edge, +// two faces with different colours are within their depth tolerance of each other, or (on the floor) the centre is +// within kMargin pixels of a checker border. kMargin is 1/32 pixel, eight times the vertex snapping of an 8-bit +// sub-pixel rasterizer. Background is a candidate only where no surface certainly covers the centre: a centre near +// an edge that two faces of one solid share (and no other edge of either) is covered by one of the two, since both +// get the same vertex positions and the rasterizer leaves no gap between them; a crack there fails. Every other pixel must match bit for bit: its colour is a product of short binary fractions +// (lanterns_scene.h), which float arithmetic computes exactly, and nothing near it is in doubt. The uncertain pixels +// are counted apart, as d3d12_translated_draw_test counts its diagonal, and each must still be one of its candidates. +#pragma once + +#include "lanterns_scene.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace lanterns { + +using Color = std::array; +constexpr double kMargin = 1.0 / 32.0; + +struct Reference { + std::vector color; // the expected colour (the most likely one where uncertain) + std::vector> candidates; // empty: certain; else every colour the pixel may have + unsigned degenerate_faces = 0; // faces seen edge-on, which cover nothing for certain + unsigned shared_edge_pixels = 0; // pixels a pair of faces covers (detail::covers) +}; + +namespace detail { + +struct ScreenVertex { + double x, y, z, q; // screen position (pixels, y down), depth z/w, q = 1/w + double wx, wy, wz; // world position (the floor's checker and stage 6's textures read it) +}; + +struct Fragment { + unsigned seq; // submission order of the face + double depth, tol; + bool certain_cover; // the centre is more than kMargin inside every edge + unsigned count; // 1 or 2 colours (2: a floor pixel on a checker border) + Color colors[2]; + unsigned group = 0; // the draw instance (one solid) the face belongs to + bool on_edge = false; // the centre is within kMargin of exactly one edge of the face, this one: + std::array edge{}; // its screen end points, ordered, so the face across it has the same four + int side = 0; // which side of that edge the face lies on +}; + +// Whether two fragments of one solid share the one edge each is near, from opposite sides: then the centre is inside +// one of the two faces (both get the same vertex positions, and a rasterizer leaves no gap along a shared edge). +inline bool share_edge(const Fragment& a, const Fragment& b) { + return a.on_edge && b.on_edge && a.group == b.group && a.edge == b.edge && a.side == -b.side; +} + +// What certainly covers a pixel centre: a fragment more than kMargin inside its face, or two faces of one solid that +// share the one edge the centre is near (share_edge), one of which covers it; the pair's depth spans both. +struct Cover { + const Fragment* a; + const Fragment* b; // the pair's other face, or null + double depth, tol; + unsigned seq; +}; + +inline std::vector covers(const std::vector& list) { + std::vector out; + for (const Fragment& f : list) + if (f.certain_cover) out.push_back({&f, nullptr, f.depth, f.tol, f.seq}); + for (const Fragment& f : list) + for (const Fragment& g : list) + if (&f < &g && share_edge(f, g)) { + const double lo = std::min(f.depth - f.tol, g.depth - g.tol); + const double hi = std::max(f.depth + f.tol, g.depth + g.tol); + out.push_back({&f, &g, (lo + hi) / 2, (hi - lo) / 2, std::max(f.seq, g.seq)}); + } + return out; +} + +inline bool same(const Color& a, const Color& b) { return std::memcmp(a.data(), b.data(), sizeof(Color)) == 0; } + +inline void add_unique(std::vector& out, const Color& c) { + for (const Color& o : out) + if (same(o, c)) return; + out.push_back(c); +} + +// The vertex shader's arithmetic, in double: local = M * (p, 1), world = local * scale + offset, clip = VP * world. +inline ScreenVertex transform(const Scene& scene, const Draw& draw, const Instance& inst, const Vertex& v, + unsigned width = kWidth, unsigned height = kHeight) { + const auto& m = draw.model; + double local[3], world[3], clip[4]; + for (int r = 0; r < 3; ++r) + local[r] = double(m[r * 4]) * v.x + double(m[r * 4 + 1]) * v.y + double(m[r * 4 + 2]) * v.z + m[r * 4 + 3]; + for (int r = 0; r < 3; ++r) world[r] = local[r] * inst.scale + inst.offset[r]; + const auto& vp = scene.view_projection; + for (int r = 0; r < 4; ++r) + clip[r] = double(vp[r * 4]) * world[0] + double(vp[r * 4 + 1]) * world[1] + double(vp[r * 4 + 2]) * world[2] + + vp[r * 4 + 3]; + const double q = 1.0 / clip[3]; + return {(clip[0] * q + 1.0) * 0.5 * width, (1.0 - clip[1] * q) * 0.5 * height, clip[2] * q, q, world[0], + world[1], world[2]}; +} + +// The colour vs_lanterns.asm exports for a face, as the float products it forms: (tint * colour) * shade. +inline Color face_color(const Draw& draw, const Instance& inst, float shade) { + Color c; + for (int k = 0; k < 3; ++k) c[k] = (draw.tint[k] * inst.color[k]) * shade; + c[3] = draw.tint[3] * inst.color[3]; + return c; +} + +inline Color times(const std::array& a, const Color& b) { + return {a[0] * b[0], a[1] * b[1], a[2] * b[2], a[3] * b[3]}; +} + +inline double cross(double ax, double ay, double bx, double by) { return ax * by - ay * bx; } + +} // namespace detail + +// Where a face covers a pixel centre: what a shading function gets to colour the fragment. world(px, py) is the +// perspective-correct world position at any screen point of the face's plane (what the PS's v_interp_p1/p2 of the +// VS's param1 reads), so a function can also take differences across the pixel's 2x2 quad. +struct PixelSite { + const Draw* draw; + const Instance* inst; + Color lit; // the face colour vs_lanterns.asm exports (flat) + double px, py; // the pixel centre + std::function world; + float shade = 0; // the face's vertex shade word (stage 9: its packed normal) +}; + +namespace detail { + +// Every fragment of every face, in submission order, coloured by shade(site, fragment) (which sets colors and count), +// on a width x height target (the frame by default; stage 8's shadow map is another). +template +std::vector> fragments(const Scene& scene, Shade shade, unsigned& degenerate_faces, + unsigned width = kWidth, unsigned height = kHeight) { + std::vector> frags(std::size_t(width) * height); + unsigned seq = 0, groups = 0; + for (const Draw& draw : scene.draws) { + if (draw.hidden) continue; + const Mesh& mesh = scene.meshes[draw.mesh]; + for (const Instance& inst : draw.instances) { + const unsigned group = groups++; + for (const Face& face : mesh.faces) { + const unsigned self = seq++; + ScreenVertex s[6]; + for (unsigned k = 0; k < face.count; ++k) + s[k] = transform(scene, draw, inst, mesh.vertices[face.v[k]], width, height); + double area = 0; + for (unsigned k = 0; k < face.count; ++k) { + const auto& a = s[k]; + const auto& b = s[(k + 1) % face.count]; + area += cross(a.x, a.y, b.x, b.y); + } + const double a012 = cross(s[1].x - s[0].x, s[1].y - s[0].y, s[2].x - s[0].x, s[2].y - s[0].y); + if (std::fabs(area) < 1e-6 || std::fabs(a012) < 1e-9) { + ++degenerate_faces; + continue; + } + const double orient = area > 0 ? 1.0 : -1.0; + double cx = 0, cy = 0; // the face's centre, to tell which side of an edge it lies on + for (unsigned k = 0; k < face.count; ++k) cx += s[k].x / face.count, cy += s[k].y / face.count; + // Barycentrics of the plane through s0, s1, s2 (the whole face lies in it). + const auto bary = [&](double px, double py, double l[3]) { + l[1] = cross(px - s[0].x, py - s[0].y, s[2].x - s[0].x, s[2].y - s[0].y) / a012; + l[2] = cross(s[1].x - s[0].x, s[1].y - s[0].y, px - s[0].x, py - s[0].y) / a012; + l[0] = 1.0 - l[1] - l[2]; + }; + const auto depth_at = [&](double px, double py) { + double l[3]; + bary(px, py, l); + return l[0] * s[0].z + l[1] * s[1].z + l[2] * s[2].z; + }; + // Perspective-correct world position, as the PS's v_interp_p1/p2 reads it. + const auto world_at = [&](double px, double py, double w[3]) { + double l[3]; + bary(px, py, l); + const double qs = l[0] * s[0].q + l[1] * s[1].q + l[2] * s[2].q; + w[0] = (l[0] * s[0].wx * s[0].q + l[1] * s[1].wx * s[1].q + l[2] * s[2].wx * s[2].q) / qs; + w[1] = (l[0] * s[0].wy * s[0].q + l[1] * s[1].wy * s[1].q + l[2] * s[2].wy * s[2].q) / qs; + w[2] = (l[0] * s[0].wz * s[0].q + l[1] * s[1].wz * s[1].q + l[2] * s[2].wz * s[2].q) / qs; + }; + const double dzdx = depth_at(1, 0) - depth_at(0, 0), dzdy = depth_at(0, 1) - depth_at(0, 0); + const double tol = (std::fabs(dzdx) + std::fabs(dzdy)) * kMargin + 1e-6; + const Color lit = face_color(draw, inst, mesh.vertices[face.v[0]].shade); + double minx = 1e30, maxx = -1e30, miny = 1e30, maxy = -1e30; + for (unsigned k = 0; k < face.count; ++k) { + minx = std::min(minx, s[k].x), maxx = std::max(maxx, s[k].x); + miny = std::min(miny, s[k].y), maxy = std::max(maxy, s[k].y); + } + const int x0 = std::max(0, int(std::floor(minx)) - 1), x1 = std::min(int(width) - 1, int(maxx) + 1); + const int y0 = std::max(0, int(std::floor(miny)) - 1), y1 = std::min(int(height) - 1, int(maxy) + 1); + for (int y = y0; y <= y1; ++y) + for (int x = x0; x <= x1; ++x) { + const double px = x + 0.5, py = y + 0.5; + double inside = 1e30; + unsigned near_count = 0, near_edge = 0; + for (unsigned k = 0; k < face.count; ++k) { + const auto& a = s[k]; + const auto& b = s[(k + 1) % face.count]; + const double ex = b.x - a.x, ey = b.y - a.y; + const double d = orient * cross(ex, ey, px - a.x, py - a.y) / std::sqrt(ex * ex + ey * ey); + inside = std::min(inside, d); + if (d <= kMargin) ++near_count, near_edge = k; + } + if (inside < -kMargin) continue; + Fragment f{self, depth_at(px, py), tol, inside > kMargin, 1, {lit, lit}}; + f.group = group; + if (near_count == 1) { + const auto& a = s[near_edge]; + const auto& b = s[(near_edge + 1) % face.count]; + const bool swap = b.x < a.x || (b.x == a.x && b.y < a.y); + const auto& p = swap ? b : a; + const auto& q = swap ? a : b; + f.on_edge = true; + f.edge = {p.x, p.y, q.x, q.y}; + f.side = cross(q.x - p.x, q.y - p.y, cx - p.x, cy - p.y) > 0 ? 1 : -1; + } + shade(PixelSite{&draw, &inst, lit, px, py, world_at, mesh.vertices[face.v[0]].shade}, f); + frags[std::size_t(y) * width + x].push_back(f); + } + } + } + } + + return frags; +} + +// Stage 1's shading: the face colour, and on the floor the checker (both colours near a checker border). +inline void checker_shade(const PixelSite& site, Fragment& f) { + if (!site.draw->floor) return; + double w[3], w1[3], w2[3]; + site.world(site.px, site.py, w); + site.world(site.px + 1, site.py, w1); + site.world(site.px, site.py + 1, w2); + const double gx = std::fabs(w1[0] - w[0]) + std::fabs(w2[0] - w[0]); + const double gz = std::fabs(w1[2] - w[2]) + std::fabs(w2[2] - w[2]); + const auto near_border = [](double v, double g) { return std::fabs(v - std::round(v)) <= g * kMargin + 1e-5; }; + const long parity = (long(std::floor(w[0])) + long(std::floor(w[2]))) & 1; + f.colors[0] = times(parity ? kFloorB : kFloorA, site.lit); + f.colors[1] = times(parity ? kFloorA : kFloorB, site.lit); + f.count = near_border(w[0], gx) || near_border(w[2], gz) ? 2 : 1; +} + +} // namespace detail + +// The frame the stage-1 draws make, with the depth test on (LESS, cleared to 1) or off (submission order wins). +inline Reference reference_frame(const Scene& scene, bool depth_test) { + using namespace detail; + Reference ref; + const auto frags = fragments(scene, checker_shade, ref.degenerate_faces); + ref.color.assign(frags.size(), Color{kClear[0], kClear[1], kClear[2], kClear[3]}); + ref.candidates.resize(frags.size()); + for (std::size_t i = 0; i < frags.size(); ++i) { + const auto& list = frags[i]; + const std::vector found = covers(list); + // Without the depth test the order inside a pair decides which face shows, so a pair is no cover there; it + // still rules out the background. + const Cover* winner = nullptr; + bool paired = false; + for (const Cover& c : found) { + paired = paired || c.b; + if (c.b && !depth_test) continue; + if (!winner || (depth_test ? c.depth < winner->depth : c.seq > winner->seq)) winner = &c; + } + std::vector cand; + if (winner) { + ref.color[i] = winner->a->colors[0]; + for (const Fragment* m : {winner->a, winner->b}) + if (m) + for (unsigned k = 0; k < m->count; ++k) add_unique(cand, m->colors[k]); + ref.shared_edge_pixels += winner->b != nullptr; + } else if (!paired) { + add_unique(cand, ref.color[i]); + } + for (const Fragment& f : list) { + if (winner && (&f == winner->a || &f == winner->b)) continue; + // Could f be what the GPU shows instead? With the depth test, if it may be nearer; without, if it comes + // later. An uncertain fragment counts wherever it might be covered. + const bool may_win = !winner ? true + : depth_test ? f.depth - f.tol <= winner->depth + winner->tol + : f.seq > winner->seq; + if (!may_win) continue; + for (unsigned k = 0; k < f.count; ++k) add_unique(cand, f.colors[k]); + } + if (cand.size() > 1) ref.candidates[i] = std::move(cand); + } + return ref; +} + +struct Comparison { + unsigned certain = 0, certain_exact = 0, uncertain = 0, uncertain_plausible = 0; + unsigned first_bad_x = 0, first_bad_y = 0; + Color first_bad_gpu{}, first_bad_ref{}; + bool pass() const { return certain_exact == certain && uncertain_plausible == uncertain; } +}; + +inline Comparison compare(const std::vector& gpu, const Reference& ref) { + using detail::same; + Comparison c; + bool reported = false; + for (std::size_t i = 0; i < gpu.size(); ++i) { + bool ok; + if (ref.candidates[i].empty()) { + ++c.certain; + ok = same(gpu[i], ref.color[i]); + c.certain_exact += ok; + } else { + ++c.uncertain; + ok = std::any_of(ref.candidates[i].begin(), ref.candidates[i].end(), + [&](const Color& k) { return same(gpu[i], k); }); + c.uncertain_plausible += ok; + } + if (!ok && !reported) { + reported = true; + c.first_bad_x = unsigned(i % kWidth), c.first_bad_y = unsigned(i / kWidth); + c.first_bad_gpu = gpu[i], c.first_bad_ref = ref.color[i]; + } + } + return c; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_sampling.h b/runtime/test/lanterns/lanterns_sampling.h new file mode 100644 index 0000000000..41f84fe63f --- /dev/null +++ b/runtime/test/lanterns/lanterns_sampling.h @@ -0,0 +1,229 @@ +// Lanterns stage 6: the CPU reference of the textured frame. The floor samples the BC1 mosaic with image_sample +// (trilinear, implicit LOD from the 2x2 quad's derivatives); the solids sample the BC7 squares with image_sample_l at +// the LOD their draw's tint.a gives. Sampling is not bit-reproducible across GPUs (bilinear weights and the LOD are +// fixed point, the BC1 thirds may round either way, and Vulkan lets the LOD's scale factor lie anywhere between the +// largest component and the sum of the components), so every fragment gets per-channel bounds instead of one colour: +// - the solids: the bilinear sample at the pixel centre's (u, v), exactly, then +- kTextureTolerance; +// - the floor: the trilinear sample over every LOD the rules allow for that pixel (coarse or fine derivatives, any +// scale factor in the allowed range, +- 1/32), whose extremes lie at the range's ends or the integer LODs inside +// it, then +- kTextureTolerance. +// kTextureTolerance (4/255) covers 8-bit sub-texel and LOD-fraction weights and one 8-bit step of BC1 rounding. The +// alpha written is 1 everywhere and is compared exactly. Pixels whose stage-1 coverage is uncertain take the union of +// their candidates' bounds. +#pragma once + +#include "lanterns_bc.h" +#include "lanterns_reference.h" + +#include +#include +#include + +namespace lanterns { + +constexpr float kTextureTolerance = 4.0f / 255.0f; +constexpr double kFloorTexScale = 0.25; // floor uv = world xz * 0.25 (the mosaic repeats every 4 units) +constexpr double kSolidTexScale = 0.5; // solid uv = ((x + z) * 0.5, y * 0.5) + +inline Color bilinear(const BcTexture& tex, unsigned mip, double u, double v) { + const unsigned w = tex.mip_width(mip), h = tex.mip_height(mip); + const double x = u * w - 0.5, y = v * h - 0.5; + const double fx = std::floor(x), fy = std::floor(y); + const double ax = x - fx, ay = y - fy; + const auto wrap = [](long i, unsigned n) { return unsigned(((i % long(n)) + long(n)) % long(n)); }; + const unsigned x0 = wrap(long(fx), w), x1 = wrap(long(fx) + 1, w), y0 = wrap(long(fy), h), y1 = wrap(long(fy) + 1, h); + const auto& t = tex.decoded[mip]; + Color c; + for (int k = 0; k < 4; ++k) { + const double top = t[y0 * w + x0][k] * (1 - ax) + t[y0 * w + x1][k] * ax; + const double bottom = t[y1 * w + x0][k] * (1 - ax) + t[y1 * w + x1][k] * ax; + c[k] = float(top * (1 - ay) + bottom * ay); + } + return c; +} + +inline Color trilinear(const BcTexture& tex, double u, double v, double lod) { + const double top = double(tex.decoded.size() - 1); + lod = std::clamp(lod, 0.0, top); + const unsigned m0 = unsigned(std::floor(lod)); + const double f = lod - m0; + const Color a = bilinear(tex, m0, u, v); + if (f == 0.0 || m0 + 1 > unsigned(top)) return a; + const Color b = bilinear(tex, m0 + 1, u, v); + Color c; + for (int k = 0; k < 4; ++k) c[k] = float(a[k] * (1 - f) + b[k] * f); + return c; +} + +struct Bounds { + Color lo, hi; +}; + +inline void widen(Bounds& b, const Color& c) { + for (int k = 0; k < 4; ++k) b.lo[k] = std::min(b.lo[k], c[k]), b.hi[k] = std::max(b.hi[k], c[k]); +} + +inline Bounds empty_bounds() { + return {{INFINITY, INFINITY, INFINITY, INFINITY}, {-INFINITY, -INFINITY, -INFINITY, -INFINITY}}; +} + +// The textured colour's bounds: texture bounds times the flat face colour, +- the tolerance, alpha 1. +inline Bounds lit_bounds(const Bounds& texel, const Color& lit) { + Bounds b; + for (int k = 0; k < 3; ++k) { + b.lo[k] = texel.lo[k] * lit[k] - kTextureTolerance; + b.hi[k] = texel.hi[k] * lit[k] + kTextureTolerance; + } + b.lo[3] = b.hi[3] = 1.0f; + return b; +} + +// The floor's LOD range at a pixel: log2 of the scale factor, over coarse and fine derivatives and the factor's +// allowed range (max component .. sum of components of each axis's derivative, then the larger axis). +inline void floor_lod_range(const PixelSite& site, const BcTexture& tex, double& lod_lo, double& lod_hi) { + const auto uv = [&](double px, double py, double out[2]) { + double w[3]; + site.world(px, py, w); + out[0] = w[0] * kFloorTexScale, out[1] = w[2] * kFloorTexScale; + }; + const double qx = std::floor(site.px / 2) * 2 + 0.5, qy = std::floor(site.py / 2) * 2 + 0.5; + const double size[2] = {double(tex.width), double(tex.height)}; + double rho_lo = INFINITY, rho_hi = 0; + // Coarse: the quad's top-left differences. Fine: this pixel's row and column within the quad. + const double rows[2][2] = {{qy, qx}, {site.py, site.px}}; + for (const auto& r : rows) { + double a[2], bx[2], ay[2], by[2]; + uv(qx, r[0], a), uv(qx + 1, r[0], bx), uv(r[1], qy, ay), uv(r[1], qy + 1, by); + double lo_axis[2], hi_axis[2]; + for (int axis = 0; axis < 2; ++axis) { + const double du = std::fabs((axis ? by[0] - ay[0] : bx[0] - a[0]) * size[0]); + const double dv = std::fabs((axis ? by[1] - ay[1] : bx[1] - a[1]) * size[1]); + lo_axis[axis] = std::max(du, dv); + hi_axis[axis] = du + dv; + } + rho_lo = std::min(rho_lo, std::max(lo_axis[0], lo_axis[1])); + rho_hi = std::max(rho_hi, std::max(hi_axis[0], hi_axis[1])); + } + lod_lo = std::log2(std::max(rho_lo, 1e-9)) - 1.0 / 32; + lod_hi = std::log2(std::max(rho_hi, 1e-9)) + 1.0 / 32; +} + +struct TexturedScene { + const BcTexture* floor; + const BcTexture* solid; + float lod_offset = 0.0f; // added to every solid draw's LOD (the control) +}; + +// What a textured fragment may show: its bounds go in colors[0] (lo) and colors[1] (hi). +inline void textured_shade(const TexturedScene& ts, const PixelSite& site, detail::Fragment& f) { + Bounds texel = empty_bounds(); + double w[3]; + site.world(site.px, site.py, w); + if (site.draw->floor) { + const double u = w[0] * kFloorTexScale, v = w[2] * kFloorTexScale; + double lo, hi; + floor_lod_range(site, *ts.floor, lo, hi); + widen(texel, trilinear(*ts.floor, u, v, lo)); + widen(texel, trilinear(*ts.floor, u, v, hi)); + for (double m = std::ceil(std::max(lo, 0.0)); m < hi; m += 1.0) widen(texel, trilinear(*ts.floor, u, v, m)); + } else { + const double u = (w[0] + w[2]) * kSolidTexScale, v = w[1] * kSolidTexScale; + const double lod = std::clamp(double(site.draw->tint[3] + ts.lod_offset), 0.0, double(ts.solid->decoded.size() - 1)); + widen(texel, bilinear(*ts.solid, unsigned(lod), u, v)); + } + const Bounds b = lit_bounds(texel, site.lit); + f.colors[0] = b.lo, f.colors[1] = b.hi, f.count = 2; +} + +struct TexturedReference { + std::vector bounds; // the nearest certain surface's (or the clear colour's) bounds + std::vector certain; // 1: bounds is the only box + std::vector> others; // else the box of each other surface that may show instead +}; + +// Per pixel: the bounds of the nearest certainly covering fragment, widened by every fragment that may be nearer +// (within its depth tolerance) or may cover instead; the clear colour where nothing certainly covers. Each fragment's +// colors[0] and colors[1] are its lower and upper bounds. +inline TexturedReference resolve_bounds(const std::vector>& frags, + const Color& clear = Color{kClear[0], kClear[1], kClear[2], kClear[3]}) { + TexturedReference ref; + ref.bounds.resize(frags.size()); + ref.certain.resize(frags.size()); + ref.others.resize(frags.size()); + for (std::size_t i = 0; i < frags.size(); ++i) { + // The nearest cover (detail::covers): a certain fragment, or two faces of one solid sharing the edge the + // centre is near. The clear colour only where nothing covers. + const auto found = detail::covers(frags[i]); + const detail::Cover* winner = nullptr; + for (const auto& c : found) + if (!winner || c.depth < winner->depth) winner = &c; + const auto box = [](const detail::Fragment& f) { + Bounds own = empty_bounds(); + widen(own, f.colors[0]), widen(own, f.colors[1]); + return own; + }; + Bounds b = empty_bounds(); + if (winner) b = box(*winner->a); + else widen(b, clear); + bool certain = !winner || !winner->b; + if (winner && winner->b) ref.others[i].push_back(box(*winner->b)); + for (const auto& f : frags[i]) { + if (winner && (&f == winner->a || &f == winner->b)) continue; + if (winner && f.depth - f.tol > winner->depth + winner->tol) continue; + // Each surface keeps its own box: a pixel must be within one of them, not within their union, which + // would also take a mix of two surfaces' channels. + ref.others[i].push_back(box(f)); + certain = false; + } + ref.bounds[i] = b; + ref.certain[i] = certain; + } + return ref; +} + +inline TexturedReference textured_reference(const Scene& scene, const TexturedScene& ts) { + unsigned degenerate = 0; + return resolve_bounds(detail::fragments( + scene, [&](const PixelSite& site, detail::Fragment& f) { textured_shade(ts, site, f); }, degenerate)); +} + +inline bool within(const Color& c, const Bounds& b) { + for (int k = 0; k < 4; ++k) + if (!(c[k] >= b.lo[k] && c[k] <= b.hi[k])) return false; + return true; +} + +// Pixel i is within its bounds or within the box of one of the other surfaces that may show there. +inline bool within_any(const TexturedReference& ref, std::size_t i, const Color& c) { + return within(c, ref.bounds[i]) || + std::any_of(ref.others[i].begin(), ref.others[i].end(), [&](const Bounds& b) { return within(c, b); }); +} + +inline Comparison compare_textured(const std::vector& gpu, const TexturedReference& ref) { + Comparison c; + bool reported = false; + for (std::size_t i = 0; i < gpu.size(); ++i) { + const bool ok = within_any(ref, i, gpu[i]); + if (ref.certain[i]) ++c.certain, c.certain_exact += ok; + else ++c.uncertain, c.uncertain_plausible += ok; + if (!ok && !reported) { + reported = true; + c.first_bad_x = unsigned(i % kWidth), c.first_bad_y = unsigned(i / kWidth); + c.first_bad_gpu = gpu[i], c.first_bad_ref = ref.bounds[i].lo; + } + } + return c; +} + +// Certain pixels where the two references' bounds do not overlap: there the control frame must leave the main bounds. +inline std::vector disjoint(const TexturedReference& a, const TexturedReference& b) { + std::vector out(a.bounds.size()); + for (std::size_t i = 0; i < out.size(); ++i) { + if (!a.certain[i] || !b.certain[i]) continue; + for (int k = 0; k < 3; ++k) + out[i] |= a.bounds[i].hi[k] < b.bounds[i].lo[k] || b.bounds[i].hi[k] < a.bounds[i].lo[k]; + } + return out; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_scene.h b/runtime/test/lanterns/lanterns_scene.h new file mode 100644 index 0000000000..05ef1d5d3b --- /dev/null +++ b/runtime/test/lanterns/lanterns_scene.h @@ -0,0 +1,239 @@ +// Lanterns, stage 1: the scene, as data both the guest's draws and its CPU reference read (lanterns_reference.h). +// Everything here is ours and abstract: a few convex solids (hexagonal prisms, cubes, octahedra, square pyramids) +// standing on a floor plane, seen by a perspective camera. Colours come from short binary fractions (multiples of +// 1/8 for the instance colours, the per-draw tint and the per-face shade; 1/16 for the floor's two checker colours), +// so every product the shaders form is exact in float and the CPU reference can compare interior pixels bit for bit. +// Positions and matrices are ordinary floats: the reference treats the pixels they make uncertain (edges, depth +// near-ties, checker borders) apart. No Windows or D3D12 types: lanterns.cpp turns this into buffers and draws. +#pragma once + +#include +#include +#include +#include +#include + +namespace lanterns { + +constexpr unsigned kWidth = 384, kHeight = 256; // render target, R32G32B32A32_FLOAT +constexpr unsigned kPitch = kWidth * 16; // 6144 bytes, a multiple of D3D12's 256 +constexpr std::array kClear = {0.0625f, 0.0625f, 0.125f, 1.0f}; + +// One vertex as vs_lanterns.asm fetches it through the mesh V# (stride 16): position xyz, then the face's shade. +struct Vertex { + float x, y, z, shade; +}; +// One instance as vs_lanterns.asm fetches it through the instance V# (stride 32): offset xyz, uniform scale, colour. +struct Instance { + float offset[3]; + float scale; + float color[4]; +}; +static_assert(sizeof(Vertex) == 16 && sizeof(Instance) == 32); + +// A convex planar face: 3 to 6 vertex indices into its mesh, wound consistently; the index buffer fans it. +struct Face { + unsigned count; + std::array v; +}; + +struct Mesh { + const char* name; + std::vector vertices; // each face has its own vertices, so a face's shade is constant across it + std::vector faces; +}; + +// The shade of a face from its local normal and a fixed light: 0.5 + 0.5 * max(0, n.l), rounded to 1/8, clamped to +// [0.25, 1]. Integer eighths keep the colour products exact. +inline float face_shade(double nx, double ny, double nz) { + const double lx = -0.4, ly = 0.8, lz = -0.45; // towards the light, roughly from above and in front + const double len = std::sqrt(nx * nx + ny * ny + nz * nz) * std::sqrt(lx * lx + ly * ly + lz * lz); + const double d = (nx * lx + ny * ly + nz * lz) / len; + long eighths = std::lround((0.5 + 0.5 * (d > 0 ? d : 0.0)) * 8.0); + eighths = eighths < 2 ? 2 : eighths > 8 ? 8 : eighths; + return float(eighths) / 8.0f; +} + +// Adds one face from positions; the shade comes from the face's own normal (Newell's method), turned to point away +// from `inside` (a point inside the convex solid), and the face is wound the same way for every face. +inline void add_face(Mesh& mesh, std::vector> p, const std::array& inside) { + double nx = 0, ny = 0, nz = 0, cx = 0, cy = 0, cz = 0; + for (std::size_t i = 0; i < p.size(); ++i) { + const auto& a = p[i]; + const auto& b = p[(i + 1) % p.size()]; + nx += (a[1] - b[1]) * (a[2] + b[2]); + ny += (a[2] - b[2]) * (a[0] + b[0]); + nz += (a[0] - b[0]) * (a[1] + b[1]); + cx += a[0], cy += a[1], cz += a[2]; + } + const double n = double(p.size()); + if (nx * (cx / n - inside[0]) + ny * (cy / n - inside[1]) + nz * (cz / n - inside[2]) < 0) { + nx = -nx, ny = -ny, nz = -nz; + std::reverse(p.begin(), p.end()); + } + const float shade = face_shade(nx, ny, nz); + Face face{unsigned(p.size()), {}}; + for (std::size_t i = 0; i < p.size(); ++i) { + face.v[i] = std::uint16_t(mesh.vertices.size()); + mesh.vertices.push_back({float(p[i][0]), float(p[i][1]), float(p[i][2]), shade}); + } + mesh.faces.push_back(face); +} + +// A prism with an n-gon cross-section, axis along y from y0 to y1, circumradius r. +inline Mesh prism(const char* name, unsigned n, double r, double y0, double y1) { + Mesh m{name, {}, {}}; + const double pi = 3.14159265358979323846; + const std::array centre{0.0, (y0 + y1) / 2, 0.0}; + std::vector> ring(n); + for (unsigned i = 0; i < n; ++i) + ring[i] = {r * std::cos(2 * pi * i / n), 0.0, r * std::sin(2 * pi * i / n)}; + for (unsigned i = 0; i < n; ++i) { + const auto& a = ring[i]; + const auto& b = ring[(i + 1) % n]; + add_face(m, {{a[0], y0, a[2]}, {a[0], y1, a[2]}, {b[0], y1, b[2]}, {b[0], y0, b[2]}}, centre); + } + std::vector> top, bottom; + for (unsigned i = 0; i < n; ++i) { + top.push_back({ring[i][0], y1, ring[i][2]}); + bottom.push_back({ring[i][0], y0, ring[i][2]}); + } + add_face(m, top, centre); + add_face(m, bottom, centre); + return m; +} + +inline Mesh octahedron(double r) { + Mesh m{"octahedron", {}, {}}; + for (double sy : {1.0, -1.0}) + for (double sx : {1.0, -1.0}) + for (double sz : {1.0, -1.0}) + add_face(m, {{sx * r, 0, 0}, {0, sy * r, 0}, {0, 0, sz * r}}, {0, 0, 0}); + // Lift it so its lowest vertex rests at y = 0 when the instance offset is on the floor. + for (Vertex& v : m.vertices) v.y += float(r); + return m; +} + +inline Mesh pyramid(double half, double height) { + Mesh m{"pyramid", {}, {}}; + const std::array c[4] = {{-half, 0, -half}, {half, 0, -half}, {half, 0, half}, {-half, 0, half}}; + const std::array apex{0, height, 0}; + const std::array centre{0, height / 4, 0}; + for (int i = 0; i < 4; ++i) add_face(m, {c[i], apex, c[(i + 1) % 4]}, centre); + add_face(m, {c[0], c[1], c[2], c[3]}, centre); + return m; +} + +inline Mesh floor_quad(double x0, double x1, double z0, double z1) { + Mesh m{"floor", {}, {}}; + Face face{4, {0, 1, 2, 3}}; + m.vertices = {{float(x0), 0, float(z0), 1}, {float(x0), 0, float(z1), 1}, {float(x1), 0, float(z1), 1}, + {float(x1), 0, float(z0), 1}}; + m.faces.push_back(face); + return m; +} + +// The floor pixel shader's two checker colours, the data words ps_lanterns_floor.asm carries in its own FSSM program +// (read through s_getpc_b64, the code base): colour A where floor(x) + floor(z) is even, B where it is odd. +constexpr std::array kFloorA = {0.4375f, 0.4375f, 0.5f, 1.0f}; +constexpr std::array kFloorB = {0.125f, 0.1875f, 0.25f, 1.0f}; + +// One DrawIndexedInstanced: a mesh, its instances, the root constants (a 3x4 model matrix, row-major, then a tint). +struct Draw { + unsigned mesh; + bool floor; // drawn with ps_lanterns_floor (the checker) instead of ps_lanterns_lit + std::vector instances; + std::array model; // rows: local = M * (x, y, z, 1) + std::array tint; + bool wave64 = false; // drawn with the wave64 pair (vs_lanterns_w64, ps_lanterns_lit_w64) + bool gpu_instances = false; // the instance V# reads what a compute shader wrote (stage 3), not uploaded data + bool hidden = false; // not drawn (keeps the other draws' descriptor slots where they are) +}; + +inline std::array rotation_y(double degrees) { + const double a = degrees * 3.14159265358979323846 / 180.0; + const float c = float(std::cos(a)), s = float(std::sin(a)); + return {c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0}; +} + +// Instance colour i of a family: the base colour in eighths, red raised by i mod 2 and blue by i / 2 (capped at 8/8). +inline Instance instance(float x, float y, float z, float scale, std::array base_eighths, unsigned i) { + const int r = std::min(8, base_eighths[0] + int(i % 2)), b = std::min(8, base_eighths[2] + int(i / 2)); + return {{x, y, z}, scale, {float(r) / 8.0f, float(base_eighths[1]) / 8.0f, float(b) / 8.0f, 1.0f}}; +} + +struct Scene { + std::vector meshes; + std::vector draws; + std::array view_projection; // rows: clip = VP * (world, 1); the root CBV's 64 bytes +}; + +// Camera: left-handed, y up, looking from the eye at the target; D3D-style depth (0 at near, 1 at far). +inline std::array camera(const double eye[3], const double target[3], double fov_y_deg, double aspect, + double znear, double zfar) { + double f[3] = {target[0] - eye[0], target[1] - eye[1], target[2] - eye[2]}; + const double fl = std::sqrt(f[0] * f[0] + f[1] * f[1] + f[2] * f[2]); + for (double& v : f) v /= fl; + double r[3] = {f[2], 0, -f[0]}; // up (0,1,0) x forward + const double rl = std::sqrt(r[0] * r[0] + r[2] * r[2]); + for (double& v : r) v /= rl; + const double u[3] = {f[1] * r[2] - f[2] * r[1], f[2] * r[0] - f[0] * r[2], f[0] * r[1] - f[1] * r[0]}; + const double ys = 1.0 / std::tan(fov_y_deg * 3.14159265358979323846 / 360.0), xs = ys / aspect; + const double zf = zfar / (zfar - znear), zn = -znear * zfar / (zfar - znear); + const auto dot_eye = [&](const double* a) { return -(a[0] * eye[0] + a[1] * eye[1] + a[2] * eye[2]); }; + const double view[3][4] = {{r[0], r[1], r[2], dot_eye(r)}, {u[0], u[1], u[2], dot_eye(u)}, + {f[0], f[1], f[2], dot_eye(f)}}; + std::array m{}; + for (int c = 0; c < 4; ++c) { + m[0 + c] = float(xs * view[0][c]); + m[4 + c] = float(ys * view[1][c]); + m[8 + c] = float(zf * view[2][c] + (c == 3 ? zn : 0.0)); + m[12 + c] = float(view[2][c]); + } + return m; +} + +// Stage 1. Draws are submitted nearest family first and the floor last, so with the depth test off the floor paints +// over everything and the far solids over the near ones: the negative control has plenty to change. +inline Scene stage1() { + Scene s; + s.meshes.push_back(prism("lantern", 6, 0.45, 0.0, 1.5)); // 0: hexagonal prisms, the "lanterns" + s.meshes.push_back(prism("cube", 4, 0.70710678, 0.0, 1.0)); // 1: square prism = a unit cube (turned 45 degrees) + s.meshes.push_back(octahedron(0.6)); // 2 + s.meshes.push_back(pyramid(0.6, 1.1)); // 3 + s.meshes.push_back(floor_quad(-6.0, 6.0, -3.0, 9.0)); // 4 + + Draw lanterns{0, false, {}, rotation_y(10), {1.0f, 1.0f, 1.0f, 1.0f}}; + for (unsigned i = 0; i < 3; ++i) + lanterns.instances.push_back(instance(-2.25f + 2.25f * float(i), 0.0f, -0.5f + 0.75f * float(i % 2), 1.0f, + {7, 5, 1}, i)); + Draw cubes{1, false, {}, rotation_y(20), {1.0f, 0.875f, 1.0f, 1.0f}}; + const float cube_x[3] = {-1.25f, 1.125f, 3.375f}; + for (unsigned i = 0; i < 3; ++i) + cubes.instances.push_back(instance(cube_x[i], 0.0f, 2.0f, 0.875f + 0.125f * float(i % 2), {2, 6, 6}, i)); + Draw octahedra{2, false, {}, rotation_y(30), {1.0f, 1.0f, 1.0f, 1.0f}}; + for (unsigned i = 0; i < 2; ++i) + octahedra.instances.push_back(instance(-1.5f + 3.0f * float(i), 0.0f, 4.0f, 1.25f, {5, 3, 7}, i)); + Draw pyramids{3, false, {}, rotation_y(-15), {1.0f, 1.0f, 0.875f, 1.0f}}; + for (unsigned i = 0; i < 2; ++i) + pyramids.instances.push_back(instance(-4.0f + 8.0f * float(i), 0.0f, 5.5f, 1.5f, {7, 3, 2}, i)); + Draw floor{4, true, {}, rotation_y(0), {1.0f, 0.875f, 0.75f, 1.0f}}; + floor.instances.push_back({{0.0f, 0.0f, 0.0f}, 1.0f, {1.0f, 1.0f, 1.0f, 1.0f}}); + octahedra.wave64 = true; + s.draws = {lanterns, cubes, octahedra, pyramids, floor}; + + const double eye[3] = {0.5, 3.25, -6.5}, target[3] = {0.0, 0.6, 2.5}; + s.view_projection = camera(eye, target, 52.0, double(kWidth) / double(kHeight), 0.5, 40.0); + return s; +} + +// Stage 6: the stage-1 scene with textures. A solid draw's tint.a is the mip level its pixel shader samples with +// image_sample_l (the vertex shader's alpha output is not used); the floor samples trilinearly. +inline Scene stage6() { + Scene s = stage1(); + const float lods[4] = {0.0f, 1.0f, 2.0f, 1.0f}; // lanterns, cubes, octahedra, pyramids + for (unsigned d = 0; d < 4; ++d) s.draws[d].tint[3] = lods[d]; + return s; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_shadow.h b/runtime/test/lanterns/lanterns_shadow.h new file mode 100644 index 0000000000..32de5f2826 --- /dev/null +++ b/runtime/test/lanterns/lanterns_shadow.h @@ -0,0 +1,131 @@ +// Lanterns stage 8: shadows from a directional light. A depth-only pass draws the solids (the floor receives but does +// not cast) from the light, through an orthographic light matrix, into a 512x512 D32 shadow map, with the PSO's depth +// bias (constant and slope-scaled). The main pass's pixel shader moves its world position into light space and takes +// four comparison samples (LESS_EQUAL, point filtered) half a texel apart: 2x2 PCF, so a pixel is lit by 0, 1/4, 2/4, +// 3/4 or all of the light. Colour = face colour * (3/8 + 5/8 * lit fraction), exact in float. +// +// The reference rasterizes the shadow map too, but a texel's stored depth is only known within bounds: coverage at a +// triangle edge, the depth tolerance, and a bias anywhere in what D3D12 and Vulkan allow (the slope factor m between the +// largest and the sum of |dz/dx| and |dz/dy|, the constant term between 0 and DepthBias * 2^-23). A tap is certainly lit +// or certainly shadowed when the receiver's light-space depth is clear of those bounds, and the texel a tap reads is +// uncertain within 1/64 texel of a texel border. Pixels where every tap is certain have one exact colour. +#pragma once + +#include "lanterns_sampling.h" + +#include +#include +#include +#include + +namespace lanterns { + +constexpr unsigned kShadowSize = 512; +constexpr int kShadowDepthBias = 1000; +constexpr float kShadowSlopeBias = 3.0f; +constexpr float kShadowAmbient = 0.375f, kShadowStep = 0.15625f; // shade = 3/8 + 5/32 * lit taps +constexpr double kShadowTexelSlack = 1.0 / 64.0, kShadowDepthSlack = 1e-5; + +struct Light { + std::array clip; // world -> light clip space (x, y in -1..1, z in 0..1, w = 1), row-major + std::array rows; // world -> (u, v, depth): the shadow map coordinates the pixel shader computes +}; + +inline Light make_light() { + const double dir_raw[3] = {0.45, -1.0, -0.55}, centre[3] = {0.0, 0.5, 3.0}, half = 10.0, depth = 30.0; + double d[3], len = 0; + for (int k = 0; k < 3; ++k) len += dir_raw[k] * dir_raw[k]; + for (int k = 0; k < 3; ++k) d[k] = dir_raw[k] / std::sqrt(len); + // right = normalize(d x up), up' = right x d + double r[3] = {d[1] * 0 - d[2] * 1, d[2] * 0 - d[0] * 0, d[0] * 1 - d[1] * 0}; + const double rl = std::sqrt(r[0] * r[0] + r[1] * r[1] + r[2] * r[2]); + for (double& x : r) x /= rl; + const double u[3] = {r[1] * d[2] - r[2] * d[1], r[2] * d[0] - r[0] * d[2], r[0] * d[1] - r[1] * d[0]}; + const auto dot = [&](const double* a) { return a[0] * centre[0] + a[1] * centre[1] + a[2] * centre[2]; }; + double clip[4][4] = {{r[0] / half, r[1] / half, r[2] / half, -dot(r) / half}, + {u[0] / half, u[1] / half, u[2] / half, -dot(u) / half}, + {d[0] / depth, d[1] / depth, d[2] / depth, -dot(d) / depth + 0.5}, + {0, 0, 0, 1}}; + Light light; + for (int i = 0; i < 16; ++i) light.clip[i] = float(clip[i / 4][i % 4]); + for (int k = 0; k < 4; ++k) { + light.rows[k] = float(0.5 * light.clip[k] + (k == 3 ? 0.5 : 0.0)); // u = 0.5 x + 0.5 + light.rows[4 + k] = float(-0.5 * light.clip[4 + k] + (k == 3 ? 0.5 : 0.0)); // v = 0.5 - 0.5 y + light.rows[8 + k] = light.clip[8 + k]; // depth = z + } + return light; +} + +// What a shadow-map texel can hold (depth plus bias): [lo, hi]. A texel no solid certainly covers may hold 1 (clear). +struct ShadowMap { + std::vector lo, hi; +}; + +inline ShadowMap shadow_map(const Scene& scene, const Light& light, bool casters) { + ShadowMap map{std::vector(kShadowSize * kShadowSize, 1.0), std::vector(kShadowSize * kShadowSize, 1.0)}; + if (!casters) return map; + Scene from_light = scene; + for (auto& k : from_light.view_projection) k = 0; + std::copy(light.clip.begin(), light.clip.end(), from_light.view_projection.begin()); + for (Draw& d : from_light.draws) d.hidden = d.hidden || d.floor; + unsigned degenerate = 0; + const auto frags = detail::fragments( + from_light, [](const PixelSite&, detail::Fragment&) {}, degenerate, kShadowSize, kShadowSize); + for (std::size_t i = 0; i < frags.size(); ++i) { + double lo = 1.0, hi = 1.0; + for (const auto& f : frags[i]) { + const double slope_sum = (f.tol - 1e-6) / kMargin; // |dz/dx| + |dz/dy| per texel (see fragments()) + const double bias_lo = kShadowSlopeBias * slope_sum / 2; + const double bias_hi = kShadowSlopeBias * slope_sum + kShadowDepthBias * std::ldexp(1.0, -23); + lo = std::min(lo, f.depth - f.tol + bias_lo); + if (f.certain_cover) hi = std::min(hi, f.depth + f.tol + bias_hi); + } + map.lo[i] = lo, map.hi[i] = std::max(lo, hi); + } + return map; +} + +// The lit fraction's bounds (0..4 taps) at a world position. +inline void lit_taps(const ShadowMap& map, const Light& light, const double w[3], int& lo, int& hi) { + const auto row = [&](int r) { + return light.rows[r * 4] * w[0] + light.rows[r * 4 + 1] * w[1] + light.rows[r * 4 + 2] * w[2] + light.rows[r * 4 + 3]; + }; + const double u = row(0) * kShadowSize, v = row(1) * kShadowSize, depth = row(2); + lo = hi = 0; + for (int tap = 0; tap < 4; ++tap) { + const double x = u + (tap & 1 ? 0.5 : -0.5), y = v + (tap & 2 ? 0.5 : -0.5); + bool may_lit = false, may_shadow = false; + for (double ex : {-kShadowTexelSlack, kShadowTexelSlack}) + for (double ey : {-kShadowTexelSlack, kShadowTexelSlack}) { + const int tx = std::clamp(int(std::floor(x + ex)), 0, int(kShadowSize) - 1); + const int ty = std::clamp(int(std::floor(y + ey)), 0, int(kShadowSize) - 1); + const std::size_t t = std::size_t(ty) * kShadowSize + tx; + if (depth - kShadowDepthSlack <= map.hi[t]) may_lit = true; // depth <= stored may hold + if (depth + kShadowDepthSlack > map.lo[t]) may_shadow = true; // depth > stored may hold + } + lo += may_shadow ? 0 : 1; + hi += may_lit ? 1 : 0; + } +} + +inline float shadow_shade_factor(int lit) { return std::fma(float(lit), kShadowStep, kShadowAmbient); } + +inline TexturedReference shadow_reference(const Scene& scene, const Light& light, const ShadowMap& map) { + unsigned degenerate = 0; + const auto shade = [&](const PixelSite& site, detail::Fragment& f) { + double w[3]; + site.world(site.px, site.py, w); + int lo, hi; + lit_taps(map, light, w, lo, hi); + const float a = shadow_shade_factor(lo), b = shadow_shade_factor(hi); + for (int k = 0; k < 3; ++k) f.colors[0][k] = site.lit[k] * a, f.colors[1][k] = site.lit[k] * b; + f.colors[0][3] = f.colors[1][3] = site.lit[3]; + f.count = 2; + }; + return resolve_bounds(detail::fragments(scene, shade, degenerate)); +} + +// The stage-8 scene: stage 1's solids on a plain floor (the shadow pixel shader has no checker). +inline Scene stage8() { return stage1(); } + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_shadow_gpu.cpp b/runtime/test/lanterns/lanterns_shadow_gpu.cpp new file mode 100644 index 0000000000..44f8a49468 --- /dev/null +++ b/runtime/test/lanterns/lanterns_shadow_gpu.cpp @@ -0,0 +1,125 @@ +// Lanterns stage 8: the shadow map's resources and its depth-only pass, as members of Gpu (lanterns_gpu.h). The map is +// an R32_TYPELESS texture with a D32_FLOAT depth view and an R32_FLOAT shader view; the sampler compares LESS_EQUAL with +// point filtering. Depth bias comes from the depth pass's PSO. +#include "lanterns_d3d12.h" +#include "lanterns_gpu.h" +#include "lanterns_shadow.h" + +#include + +using namespace d3d12test; + +namespace lanterns { + +bool Gpu::create_shadow() { + D3D12_RESOURCE_DESC tex{}; + tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + tex.Width = kShadowSize; + tex.Height = kShadowSize; + tex.DepthOrArraySize = 1; + tex.MipLevels = 1; + tex.Format = DXGI_FORMAT_R32_TYPELESS; + tex.SampleDesc.Count = 1; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + D3D12_CLEAR_VALUE clear{}; + clear.Format = DXGI_FORMAT_D32_FLOAT; + clear.DepthStencil = {1.0f, 0}; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT, {}, {}, 0, 0}; + CHECK(SUCCEEDED(device_->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex, + D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear, + IID_PPV_ARGS(&shadow_map_.p)))); + shadow_dsv_ = {dsv_.ptr + device_->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV)}; + D3D12_DEPTH_STENCIL_VIEW_DESC dsv{}; + dsv.Format = DXGI_FORMAT_D32_FLOAT; + dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + device_->CreateDepthStencilView(shadow_map_.p, &dsv, shadow_dsv_); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_FLOAT; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + device_->CreateShaderResourceView(shadow_map_.p, &srv, + D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(srv_cpu_ + srv_texture_slot_ * srv_step_)}); + const D3D12_DESCRIPTOR_HEAP_DESC sampler_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&sampler_desc, IID_PPV_ARGS(&sampler_heap_.p)))); + D3D12_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.MaxAnisotropy = 1; + sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + device_->CreateSampler(&sampler, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(heap_cpu(sampler_heap_.p))}); + textures_bound_ = true; + + // The depth-only pipeline: vs_lanterns, no pixel shader, no render target, the bias. + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root_.p; + desc.VS = {vs_.data(), vs_.size()}; + desc.SampleMask = 0xffffffff; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.RasterizerState.DepthBias = kShadowDepthBias; + desc.RasterizerState.SlopeScaledDepthBias = kShadowSlopeBias; + desc.DepthStencilState.DepthEnable = TRUE; + desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 0; + desc.DSVFormat = DXGI_FORMAT_D32_FLOAT; + desc.SampleDesc.Count = 1; + CHECK(SUCCEEDED(device_->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&shadow_pso_.p)))); + return true; +} + +bool Gpu::set_light(const std::array& clip, const std::array& rows) { + CHECK(shadow_); + void* mapped = nullptr; + CHECK(SUCCEEDED(upload_->Map(0, nullptr, &mapped))); + auto* up = static_cast(mapped); + std::memcpy(up + upload_cbv_ + 64, rows.data(), sizeof(rows)); + std::memcpy(up + upload_light_, clip.data(), sizeof(clip)); + upload_->Unmap(0, nullptr); + return true; +} + +// Before the main pass: the map cleared to 1, the solids drawn into it from the light (unless the control), and the +// map left in PIXEL_SHADER_RESOURCE for the main pass's comparison samples. +void Gpu::record_shadow_pass(const Scene& scene) { + const auto read = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, write = D3D12_RESOURCE_STATE_DEPTH_WRITE; + if (shadow_written_) { + const D3D12_RESOURCE_BARRIER to_write = transition(shadow_map_.p, read, write); + list_->ResourceBarrier(1, &to_write); + } + shadow_written_ = true; + list_->ClearDepthStencilView(shadow_dsv_, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + if (shadow_casters_) { + const D3D12_VIEWPORT viewport{0, 0, float(kShadowSize), float(kShadowSize), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(kShadowSize), LONG(kShadowSize)}; + list_->RSSetViewports(1, &viewport); + list_->RSSetScissorRects(1, &scissor); + list_->OMSetRenderTargets(0, nullptr, FALSE, &shadow_dsv_); + list_->SetGraphicsRootSignature(root_.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap_.p, sampler_heap_.p}; + list_->SetDescriptorHeaps(2, heaps); + list_->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_INDEX_BUFFER_VIEW ibv{index_buffer_->GetGPUVirtualAddress(), + UINT(align(geometry_.indices.size() * sizeof(std::uint16_t), 4)), + DXGI_FORMAT_R16_UINT}; + list_->IASetIndexBuffer(&ibv); + list_->SetGraphicsRootConstantBufferView(3, upload_->GetGPUVirtualAddress() + upload_light_); + list_->SetPipelineState(shadow_pso_.p); + for (std::size_t d = 0; d < scene.draws.size(); ++d) { + const Draw& draw = scene.draws[d]; + if (draw.hidden || draw.floor || draw.gpu_instances) continue; // the floor only receives + bind_draw(scene, d); + list_->DrawIndexedInstanced(geometry_.index_count[draw.mesh], UINT(draw.instances.size()), + geometry_.first_index[draw.mesh], 0, 0); + } + } + const D3D12_RESOURCE_BARRIER to_read = transition(shadow_map_.p, write, read); + list_->ResourceBarrier(1, &to_read); +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_textures_gpu.cpp b/runtime/test/lanterns/lanterns_textures_gpu.cpp new file mode 100644 index 0000000000..d6e9504c11 --- /dev/null +++ b/runtime/test/lanterns/lanterns_textures_gpu.cpp @@ -0,0 +1,82 @@ +// Lanterns stage 6: texture upload (lanterns_textures_gpu.h). The footprint-per-subresource upload follows +// test/d3d12_m2_formats_test.cpp (M2), which uploads hand-built BC1 and BC7 mips the same way. +#include "lanterns_textures_gpu.h" + +#include "lanterns_d3d12.h" + +#include + +using namespace d3d12test; + +namespace lanterns { + +bool upload_texture(ID3D12Device* device, ID3D12CommandQueue* queue, const BcTexture& tex, Ref& out) { + const UINT mips = UINT(tex.blocks.size()); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = tex.width; + desc.Height = tex.height; + desc.DepthOrArraySize = 1; + desc.MipLevels = UINT16(mips); + desc.Format = tex.format == BcFormat::bc1 ? DXGI_FORMAT_BC1_UNORM : DXGI_FORMAT_BC7_UNORM; + desc.SampleDesc.Count = 1; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT, {}, {}, 0, 0}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD, {}, {}, 0, 0}; + CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&out.p)))); + std::vector layouts(mips); + std::vector rows(mips); + std::vector row_bytes(mips); + UINT64 total = 0; + device->GetCopyableFootprints(&desc, 0, mips, 0, layouts.data(), rows.data(), row_bytes.data(), &total); + CHECK(total != ~0ull && total > 0); + Ref upload; + const auto upload_desc = buffer_desc(total); + CHECK(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload.p)))); + std::uint8_t* mapped = nullptr; + CHECK(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&mapped)))); + for (UINT m = 0; m < mips; ++m) { + // A footprint row is a row of 4x4 blocks. + const std::size_t block_row = std::size_t((tex.mip_width(m) + 3) / 4) * tex.block_bytes(); + const bool fits = row_bytes[m] == block_row && rows[m] == (tex.mip_height(m) + 3) / 4; + if (!fits) { + upload->Unmap(0, nullptr); + CHECK(fits); + } + for (UINT r = 0; r < rows[m]; ++r) + std::memcpy(mapped + layouts[m].Offset + std::size_t(r) * layouts[m].Footprint.RowPitch, + tex.blocks[m].data() + r * block_row, block_row); + } + upload->Unmap(0, nullptr); + + Ref allocator; + Ref list; + Ref fence; + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + for (UINT m = 0; m < mips; ++m) { + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = out.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + dst.SubresourceIndex = m; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = upload.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + src.PlacedFootprint = layouts[m]; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + const D3D12_RESOURCE_BARRIER ready = transition(out.p, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + list->ResourceBarrier(1, &ready); + CHECK(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue->Signal(fence.p, 1))); + CHECK(wait_fence(fence, 1)); // the upload buffer is released after this + return true; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_textures_gpu.h b/runtime/test/lanterns/lanterns_textures_gpu.h new file mode 100644 index 0000000000..3fbae209b5 --- /dev/null +++ b/runtime/test/lanterns/lanterns_textures_gpu.h @@ -0,0 +1,15 @@ +// Lanterns stage 6: a compressed texture with its whole mip chain, created on the device and uploaded the way the +// D3D12 API offers it: GetCopyableFootprints, an upload buffer, one CopyTextureRegion per mip level. The layer lays the +// texels out; nothing here knows or writes the console's tiled layout (a title that wrote BC blocks straight into a +// texture's memory would need that layout, and Lanterns does not do it). +#pragma once + +#include "lanterns_bc.h" +#include "lanterns_gpu.h" + +namespace lanterns { + +// Creates the texture (DEFAULT heap), uploads every level on queue, waits, and leaves it in PIXEL_SHADER_RESOURCE. +bool upload_texture(ID3D12Device* device, ID3D12CommandQueue* queue, const BcTexture& tex, Ref& out); + +} // namespace lanterns diff --git a/runtime/test/lanterns/run_lanterns.py b/runtime/test/lanterns/run_lanterns.py new file mode 100644 index 0000000000..4957d48ba5 --- /dev/null +++ b/runtime/test/lanterns/run_lanterns.py @@ -0,0 +1,418 @@ +"""Run Lanterns under gta6rt --run, check what it printed, and turn its frame dumps into PNGs. + + python -I runtime/test/lanterns/run_lanterns.py --gta6rt --guest + --shaders --out [--stage 1] [--wine] [--timeout 240] [--png FILE] + +It sets LEONIDA_D3D12=vulkan and LEONIDA_SHADERS=/spirv and runs +"gta6rt --run lanterns.exe -- --stage N --shaders --out " (under Wine with --wine, paths turned into +Z:\\ paths). The run passes only if all of these hold, which a loader that exits 0 early, a guest that prints and then +fails, or the host's PC device instead of the shim's Vulkan device would each break: + - the exit code is 0; + - stdout has the stage's PASS line exactly once, whole, with numbers that fit together (PASS_LINES; the guest + prints it after every check); + - the output has the shim's complete factory line "[rt] d3d12_xs: D3D12XboxCreateDevice -> proxy 0x... (Vulkan + device 0x...)" (the guard PR #3913's run_guest_draw.cmake uses). +The timeout is a promise: when it expires everything the run started is killed and the run fails with exit code 3, +whatever the guest, Wine or the GPU are doing. On Linux the runner is a child subreaper, so a process that left the +launcher's session and lost its parent still comes back to it and is killed too; on Windows the process tree is +killed with taskkill /T. If anything survives (or taskkill fails), the run fails with exit code 4 and says what is +left. tests/test_run_lanterns.py checks it with a launcher that never ends and a child that escapes its session. + +With --wine the prefix's wineserver is stopped (wineserver -k, then -w, each under a 10 s timeout) before the +launch: a launch under a new virtual X server while the previous run's explorer.exe is alive hangs in winevulkan. + +Each run writes into a new folder, /stage--