From c838d6018181d0831b42ef8dea111d70476e4226 Mon Sep 17 00:00:00 2001 From: Rafael Date: Sun, 22 Nov 2026 15:39:22 -0300 Subject: [PATCH 1/8] First light with a texture: the real model through a game PS that samples a T# (TEST-524) d3d12_first_light_textured_test draws the first-light mesh through the D3D12 layer with the game's VS and $PS_PassthroughCopy, picked by census (780 of 12,101 PS do one image_sample and nothing else; 148 of those link with the VS). The PS loads its T# through the table pointer in s8 and samples with a literal S#; the root signature puts a one-SRV table at s8:s9 behind eight padding constants. first_light.py --texture ramp writes texture.bin, a 64x64 coordinate ramp (texel (x, y) holds its own centre, so bilinear sampling gives back the UV), and expected.raw, the CPU reference at every covered pixel's UV. RTX 3060: 12,804 pixels, the same coverage as d3d12_first_light, worst channel error 0.00028 against a 0.002 tolerance; point sampling is off by up to 1/128, which is what this draw gave before #2887. Co-Authored-By: Claude Opus 5.5 --- docs/first_light.md | 41 +- runtime/CMakeLists.txt | 6 + .../test/d3d12_first_light_textured_test.cpp | 386 ++++++++++++++++++ tests/test_first_light.py | 40 ++ tools/first_light.py | 78 ++++ 5 files changed, 550 insertions(+), 1 deletion(-) create mode 100644 runtime/test/d3d12_first_light_textured_test.cpp diff --git a/docs/first_light.md b/docs/first_light.md index 9eaff8f37c..93c98fe68a 100644 --- a/docs/first_light.md +++ b/docs/first_light.md @@ -203,7 +203,46 @@ python -I tools/first_light.py --game "" --work ~/leonida-work \ LEONIDA_FIRST_LIGHT_DIR=~/leonida-work/first_light/camera python -I tests/test_first_light.py -v ``` -## 8. Limits and next +## 8. With a texture, through the D3D12 layer + +`runtime/test/d3d12_first_light_textured_test.cpp` (ctest `d3d12_first_light_textured`, TEST-524) draws the same +mesh through the D3D12 layer (as section 5 does for section 3) with a game pixel shader that samples a texture. The PS is chosen by census: + +- Of the corpus's 12,101 PS, 780 do one `image_sample` and no other memory access. +- 148 of those link with this VS (`shader_link_check.py`). +- The pick is `$PS_PassthroughCopy`. It interpolates the TEXCOORD, `s_load`s an 8-dword T# through the 32-bit + table pointer in user SGPR `s8`, samples with a **literal S#** (`0x92, 0xC00000, 0x14500000, 0`: CLAMP_LAST_TEXEL, + bilinear, mip point) and exports the colour with `v_cvt_pkrtz_f16_f32`. + +How the draw is fed: + +- The root signature is [0] eight 32-bit constants (`s0..s7`, zero) and [1] a one-SRV descriptor table. The layer's + packing ([d3d12_vulkan.md](d3d12_vulkan.md) 3.5) puts the table at `s8:s9`. +- The texture goes through `CopyTextureRegion` into a DEFAULT texture, and `CreateShaderResourceView` writes its T# + into a shader-visible heap. +- The literal S# is in no heap. `CreateGraphicsPipelineState` registers it from the index (`literal_samplers`; see + `docs/design.md`, Literal samplers). + +The texture is a 64×64 R16G16B16A16_FLOAT **coordinate ramp**: texel (x, y) holds its own centre, +((x+½)/64, (y+½)/64, 0, 1). Bilinear sampling with clamp therefore gives back the UV, clamped to the outer texel +centres, so the image has an exact oracle. `first_light.py --texture ramp` writes `texture.bin` and +`expected.raw`, which samples the ramp on the CPU at every covered pixel's interpolated UV. + +On an RTX 3060 (Windows 11, driver 616.64), the draw covers the same **12,804 pixels** as section 5, with no +coverage mismatch. The worst channel error is **0.00028** and the mean 0.000045, against a tolerance of 0.002. +Point sampling would be off by up to half a texel (1/128 = 0.0078). That is what this draw gave before literal S#s +were registered (#2887), because the shader's lookup found the fallback sampler: worst error 0.0078, with 18,616 +channels over the tolerance. + +```sh +python -I tools/first_light.py ... --no-fit --vs VS_main_170e32e6_Wrapped --ps '$PS_PassthroughCopy_1a08fc46_Wrapped' --texture ramp +LEONIDA_FIRST_LIGHT_TEX_DIR=~/leonida-work/first_light/out_tex ctest --test-dir -R d3d12_first_light_textured -V +``` + +Without `LEONIDA_FIRST_LIGHT_TEX_DIR` the test prints SKIP and exits 77. The drawn image is written next to the +inputs as `d3d12_textured.raw`; it stays in the user's folder. + +## 9. Limits and next * The camera draw (section 7) runs in `vk_harness` only. Through the D3D12 layer, s9 and the table it points at have to come from root arguments, which `d3d12_first_light_test` does not set up yet. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 7a8f61de85..412a1ff534 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2011,6 +2011,12 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_first_light_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_first_light COMMAND d3d12_first_light_test) set_tests_properties(d3d12_first_light PROPERTIES SKIP_RETURN_CODE 77) + add_executable(d3d12_first_light_textured_test test/d3d12_first_light_textured_test.cpp shims/d3d12_xs_device.cpp) + target_link_libraries(d3d12_first_light_textured_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_first_light_textured_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_first_light_textured_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_first_light_textured COMMAND d3d12_first_light_textured_test) + set_tests_properties(d3d12_first_light_textured PROPERTIES SKIP_RETURN_CODE 77) # M1.5 (D3D-53): a draw whose VS and PS are translator output. test/shaders/vs_m15.asm and ps_m15.asm are assembled # with llvm-mc and translated by tools/rdna2spirv.py through test/shaders/build.py, which also writes the FSSM diff --git a/runtime/test/d3d12_first_light_textured_test.cpp b/runtime/test/d3d12_first_light_textured_test.cpp new file mode 100644 index 0000000000..4747bc13ca --- /dev/null +++ b/runtime/test/d3d12_first_light_textured_test.cpp @@ -0,0 +1,386 @@ +// First light with a texture (TEST-524, docs/first_light.md): the real model, the game's VS and a game pixel shader +// that samples one texture, drawn through the Xbox-ABI device proxy over the Vulkan device. Package-gated like +// d3d12_first_light_test: everything is read at run time from LEONIDA_FIRST_LIGHT_TEX_DIR (a tools/first_light.py +// output folder made with --texture), and the test prints SKIP and exits 77 when that is unset. +// - The PS s_loads its T# through a 32-bit table pointer in user SGPR s8 and builds its S# from literals. The root +// signature is [0] eight 32-bit constants (s0..s7, zero) and [1] a one-SRV descriptor table, which the layer's +// packing (docs/d3d12_vulkan.md 3.5) puts at s8:s9. The literal S# is registered by the layer from the index. +// - texture.bin (u32 width, height, DXGI format, then tightly packed rows) is uploaded to a DEFAULT texture with +// CopyTextureRegion, and CreateShaderResourceView writes its T# into a shader-visible heap. +// - expected.raw (first_light.py's CPU reference: the texture sampled bilinearly with clamp at each covered pixel's +// interpolated UV, -1 where uncovered, in vk_harness row order) is compared pixel by pixel with a tolerance. +// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: CPU handle, 10: GPU handle, in RAX +using Pixel = std::array; + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +double number(const leonida::Json& object, std::string_view key, double fallback = -1) { + const leonida::Json* value = object.find(key); + return value && value->kind == leonida::Json::Kind::number ? value->number : fallback; +} + +std::string stage_hash(const leonida::Json& manifest, std::string_view stage) { + const leonida::Json* entry = manifest.find(stage); + const leonida::Json* hash = entry ? entry->find("fssm_sha256") : nullptr; + return hash && hash->kind == leonida::Json::Kind::string ? hash->string : std::string(); +} + +UINT texel_bytes(DXGI_FORMAT format) { + switch (format) { + case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return 4; + case DXGI_FORMAT_R16G16B16A16_FLOAT: return 8; + default: return 0; + } +} + +} // namespace + +int main() { + const char* dir_env = std::getenv("LEONIDA_FIRST_LIGHT_TEX_DIR"); + if (!dir_env || !*dir_env) { + std::printf("SKIP: LEONIDA_FIRST_LIGHT_TEX_DIR is not set (run tools/first_light.py --texture first)\n"); + return 77; + } + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(device_status == vktest::DeviceStatus::ready); + if (!d.bindless) { + std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n"); + return 77; + } + + const std::filesystem::path dir = dir_env; + const auto manifest_text = read_file(dir / "manifest.json"); + leonida::Json manifest; + EXPECT(leonida::JsonReader(std::string_view(reinterpret_cast(manifest_text.data()), + manifest_text.size())) + .parse(manifest)); + for (const char* name : {"vs.dxbc", "ps.dxbc", "index.json", "vs.spv", "ps.spv", "mesh.bin", "texture.bin", + "expected.raw"}) { + if (!std::filesystem::is_regular_file(dir / name)) { + std::fprintf(stderr, "%s has no %s: re-run tools/first_light.py with --texture\n", dir.string().c_str(), + name); + return 1; + } + } + const UINT width = UINT(number(manifest, "width")), height = UINT(number(manifest, "height")); + EXPECT(width > 0 && width <= 4096 && height > 0 && height <= 4096); + const UINT pitch = (width * sizeof(Pixel) + 255) / 256 * 256; + + const auto vs_container = read_file(dir / "vs.dxbc"), ps_container = read_file(dir / "ps.dxbc"); + const std::string vs_hash = leonida::sha256_hex(leonida::fssm_program(vs_container)); + const std::string ps_hash = leonida::sha256_hex(leonida::fssm_program(ps_container)); + EXPECT(vs_hash == stage_hash(manifest, "vs") && ps_hash == stage_hash(manifest, "ps")); + leonida::ShaderLibrary library; + EXPECT(library.load(dir.string())); + EXPECT(library.find("vs", vs_hash) && library.find("ps", ps_hash)); + + const auto mesh = read_file(dir / "mesh.bin"); + EXPECT(mesh.size() >= 8); + std::uint32_t vertex_count = 0, index_count = 0; + std::memcpy(&vertex_count, mesh.data(), 4); + std::memcpy(&index_count, mesh.data() + 4, 4); + constexpr UINT stride = 5 * sizeof(float); + const std::size_t vertex_bytes = std::size_t(vertex_count) * stride, index_bytes = std::size_t(index_count) * 4; + EXPECT(vertex_count && index_count && mesh.size() == 8 + vertex_bytes + index_bytes); + const std::size_t index_offset = (vertex_bytes + 255) / 256 * 256; + + // texture.bin: u32 width, height, DXGI format, then rows with no padding. + const auto texture = read_file(dir / "texture.bin"); + EXPECT(texture.size() >= 12); + std::uint32_t tex_w = 0, tex_h = 0, tex_format = 0; + std::memcpy(&tex_w, texture.data(), 4); + std::memcpy(&tex_h, texture.data() + 4, 4); + std::memcpy(&tex_format, texture.data() + 8, 4); + const UINT texel = texel_bytes(DXGI_FORMAT(tex_format)); + EXPECT(texel && tex_w && tex_h && tex_w <= 16384 && tex_h <= 16384); + EXPECT(texture.size() == 12 + std::size_t(tex_w) * tex_h * texel); + const UINT tex_row = tex_w * texel, tex_pitch = (tex_row + 255) / 256 * 256; + const std::size_t tex_offset = (index_offset + index_bytes + 511) / 512 * 512; + + std::vector pixels(std::size_t(width) * height); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.bindless = d.bindless; + info.bindless_partially_bound = d.partially_bound; + info.image_view_min_lod = d.image_view_min_lod; + info.subgroup = d.subgroup; + info.shader_dir = dir.string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + // [0] s0..s7: eight zero constants; [1] s8:s9: the SRV table whose low dword the PS reads as its pointer. + D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 8}; + params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &srv_range}; + params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + 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_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + const D3D12_INPUT_ELEMENT_DESC elements[2] = { + {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}}; + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.InputLayout = {elements, 2}; + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pso_desc.SampleDesc.Count = 1; + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref vertex_buffer, index_buffer, upload, readback, target, tex; + const auto vb_desc = buffer_desc(vertex_bytes), ib_desc = buffer_desc(index_bytes); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&vertex_buffer.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &ib_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&index_buffer.p)))); + const auto upload_desc = buffer_desc(tex_offset + std::size_t(tex_pitch) * tex_h); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(UINT64(pitch) * height); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = width; + rt_desc.Height = height; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + D3D12_RESOURCE_DESC tex_desc = rt_desc; + tex_desc.Width = tex_w; + tex_desc.Height = tex_h; + tex_desc.Format = DXGI_FORMAT(tex_format); + tex_desc.Flags = D3D12_RESOURCE_FLAG_NONE; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&tex.p)))); + + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up, mesh.data() + 8, vertex_bytes); + std::memcpy(up + index_offset, mesh.data() + 8 + vertex_bytes, index_bytes); + for (UINT row = 0; row < tex_h; ++row) + std::memcpy(up + tex_offset + std::size_t(row) * tex_pitch, texture.data() + 12 + std::size_t(row) * tex_row, + tex_row); + + const D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap, srv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rtv_heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + const std::uint64_t srv_cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); + const std::uint64_t srv_gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); + // The PS keeps only the low dword of the table pointer (s9 is zeroed), so the heap must sit below 4 GiB. + EXPECT(srv_gpu >> 32 == 0); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT(tex_format); + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + device->CreateShaderResourceView(tex.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(srv_cpu)}); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, vertex_bytes); + list->CopyBufferRegion(index_buffer.p, 0, upload.p, index_offset, index_bytes); + { + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = tex.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = upload.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + src.PlacedFootprint = {tex_offset, {DXGI_FORMAT(tex_format), tex_w, tex_h, 1, tex_pitch}}; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + D3D12_RESOURCE_BARRIER barriers[4] = { + transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER), + transition(index_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER), + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET), + transition(tex.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)}; + list->ResourceBarrier(4, barriers); + const FLOAT clear[4] = {-1, -1, -1, -1}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + + list->SetGraphicsRootSignature(root.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu}); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_VERTEX_BUFFER_VIEW vbv{vertex_buffer->GetGPUVirtualAddress(), UINT(vertex_bytes), stride}; + list->IASetVertexBuffers(0, 1, &vbv); + const D3D12_INDEX_BUFFER_VIEW ibv{index_buffer->GetGPUVirtualAddress(), UINT(index_bytes), + DXGI_FORMAT_R32_UINT}; + list->IASetIndexBuffer(&ibv); + const D3D12_VIEWPORT viewport{0, 0, float(width), float(height), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(width), LONG(height)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + list->DrawIndexedInstanced(index_count, 1, 0, 0, 0); + + D3D12_RESOURCE_BARRIER 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{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, width, height, 1, pitch}}; + 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); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + std::uint8_t* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, reinterpret_cast(&mapped)))); + for (UINT row = 0; row < height; ++row) + std::memcpy(&pixels[std::size_t(row) * width], mapped + std::size_t(row) * pitch, width * sizeof(Pixel)); + + for (auto* r : {&vertex_buffer, &index_buffer, &upload, &readback, &target, &tex}) r->reset(); + pso.reset(); + root.reset(); + rtv_heap.reset(); + srv_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + // The image as drawn, rows in vk_harness order, for first_light.py --check-textured to read back. + { + std::ofstream out(dir / "d3d12_textured.raw", std::ios::binary); + for (UINT vk_y = 0; vk_y < height; ++vk_y) + out.write(reinterpret_cast(&pixels[std::size_t(height - 1 - vk_y) * width]), + std::streamsize(width * sizeof(Pixel))); + } + + // expected.raw is in vk_harness row order; row r here is row H-1-r there (the layer flips the viewport). + const auto expected = read_file(dir / "expected.raw"); + EXPECT(expected.size() == pixels.size() * sizeof(Pixel)); + const double tolerance = number(manifest, "texture_tolerance", 4.0 / 255.0); + unsigned covered = 0, compared = 0, coverage_mismatch = 0, over = 0; + double worst = 0.0, sum = 0.0; + for (UINT vk_y = 0; vk_y < height; ++vk_y) { + for (UINT x = 0; x < width; ++x) { + Pixel want; + std::memcpy(want.data(), expected.data() + (std::size_t(vk_y) * width + x) * sizeof(Pixel), sizeof(Pixel)); + const Pixel& got = pixels[std::size_t(height - 1 - vk_y) * width + x]; + const bool got_covered = got[3] != -1.0f, want_covered = want[3] != -1.0f; + covered += got_covered; + if (got_covered != want_covered) { + ++coverage_mismatch; + continue; + } + if (!want_covered) continue; + ++compared; + for (int c = 0; c < 4; ++c) { + const double e = std::fabs(double(got[c]) - double(want[c])); + worst = std::max(worst, e); + sum += e; + if (e > tolerance) ++over; + } + } + } + std::printf("covered %u/%u; %u pixels compared with the CPU reference: worst %.5f, mean %.6f, %u channels over " + "%.5f; %u coverage mismatches\n", covered, width * height, compared, worst, + compared ? sum / (compared * 4.0) : 0.0, over, tolerance, coverage_mismatch); + EXPECT(compared > 0); + // Coverage is the same rasterisation as d3d12_first_light; the CPU reference marks pixel centres inside a + // triangle, so only edge pixels may disagree. + EXPECT(coverage_mismatch <= covered / 100); + EXPECT(over <= compared / 1000); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("first light with a texture: the game's VS + texture-sampling PS drew %u triangles\n", index_count / 3); + return 0; +} diff --git a/tests/test_first_light.py b/tests/test_first_light.py index 6191177daa..9d9fcbc017 100644 --- a/tests/test_first_light.py +++ b/tests/test_first_light.py @@ -1019,5 +1019,45 @@ def test_harness_env_passes_only_the_manifests_constants(self): os.environ[k] = v +class LayerTexturedOracleTests(unittest.TestCase): + """The D3D12-layer textured first light's CPU reference (#2906), without a GPU or a package.""" + + def test_ramp_texels_hold_their_own_centre(self): + texels, data = fl.ramp_texture(4) + self.assertEqual(struct.unpack_from(" dict: + """texture.bin and expected.raw for d3d12_first_light_textured_test: the ramp, and the CPU reference of the + draw (the texture sampled at each covered pixel's UV, -1 elsewhere, in the harness's row order).""" + texels, data = ramp_texture() + with open(os.path.join(out_dir, "texture.bin"), "wb") as f: + f.write(data) + expected = bytearray() + covered = 0 + for uv in uv_map(vertices, indices, width, height): + if uv is None: + expected += struct.pack("<4f", -1.0, -1.0, -1.0, -1.0) + else: + covered += 1 + expected += struct.pack("<4f", *sample_bilinear_clamp(texels, RAMP_SIZE, RAMP_SIZE, uv[0], uv[1])) + with open(os.path.join(out_dir, "expected.raw"), "wb") as f: + f.write(expected) + return {"texture": "ramp", "texture_size": [RAMP_SIZE, RAMP_SIZE], "texture_format": "R16G16B16A16_FLOAT", + "texture_sha256": hashlib.sha256(data).hexdigest(), "expected_covered": covered, + # Half a texel is 1/128 = 0.0078: a point-sampled draw exceeds this everywhere; bilinear rounding stays + # under 0.0005 (RTX 3060). + "texture_tolerance": 0.002} + + def uv_probes(vertices, indices, width: int, height: int, limit: int = 4) -> list[dict]: """Pixels whose predicted UV has U and V far apart, so a swapped-U/V image cannot pass. @@ -915,6 +987,9 @@ def main(argv=None) -> int: "--dds", help="an exported DDS texture (e.g. BCPack-decoded TTPF albedo) to bind via set-0 T# and sampler S#", ) + ap.add_argument("--texture", choices=["ramp"], + help="also write texture.bin and expected.raw for d3d12_first_light_textured_test " + "(pick a --ps that samples one texture through a table at s8)") ap.add_argument("--width", type=int, default=128) ap.add_argument("--height", type=int, default=128) ap.add_argument( @@ -1133,6 +1208,9 @@ def main(argv=None) -> int: ) if tex_probes: manifest["rgba_probes"] = tex_probes + if a.texture and vertices: + manifest.update(write_textured_inputs(out_dir, vertices, indices, a.width, a.height)) + manifest["files"].update(texture="texture.bin", expected="expected.raw") with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(manifest, f, indent=1) print(f"{len(vertices)} vertices, {len(indices) // 3} triangles -> {out_dir}") From 996591f284e15c8712f2f92ab4615c3ec351a6ad Mon Sep 17 00:00:00 2001 From: Rafael Date: Sun, 22 Nov 2026 15:54:02 -0300 Subject: [PATCH 2/8] first_light: UV-seam pixels are reported, not guessed, in the textured reference A sample on a shared edge between triangles that give it different UVs belongs to whichever triangle the rasteriser's tie-break rule picks; uv_map let the last one win, so a correct draw could fail at a seam. Those pixels are now marked in expected.raw (alpha -2): coverage is still checked, the colour is not, and the test counts them. Found by @whattheflop's diagonal-quad fixture, which is now a unit test. The first-light model has no seam pixels; its result is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../test/d3d12_first_light_textured_test.cpp | 15 ++++++--- tests/test_first_light.py | 23 ++++++++++++- tools/first_light.py | 32 ++++++++++++++++--- 3 files changed, 61 insertions(+), 9 deletions(-) diff --git a/runtime/test/d3d12_first_light_textured_test.cpp b/runtime/test/d3d12_first_light_textured_test.cpp index 4747bc13ca..8a2f6b627c 100644 --- a/runtime/test/d3d12_first_light_textured_test.cpp +++ b/runtime/test/d3d12_first_light_textured_test.cpp @@ -8,7 +8,8 @@ // - texture.bin (u32 width, height, DXGI format, then tightly packed rows) is uploaded to a DEFAULT texture with // CopyTextureRegion, and CreateShaderResourceView writes its T# into a shader-visible heap. // - expected.raw (first_light.py's CPU reference: the texture sampled bilinearly with clamp at each covered pixel's -// interpolated UV, -1 where uncovered, in vk_harness row order) is compared pixel by pixel with a tolerance. +// interpolated UV, -1 where uncovered, alpha -2 on a UV seam where the edge rule picks the triangle, in vk_harness +// row order) is compared pixel by pixel with a tolerance; seam pixels count for coverage only. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. #include "vk_test_device.h" #include "d3d12_test_shaders.h" @@ -346,7 +347,7 @@ int main() { const auto expected = read_file(dir / "expected.raw"); EXPECT(expected.size() == pixels.size() * sizeof(Pixel)); const double tolerance = number(manifest, "texture_tolerance", 4.0 / 255.0); - unsigned covered = 0, compared = 0, coverage_mismatch = 0, over = 0; + unsigned covered = 0, compared = 0, coverage_mismatch = 0, over = 0, ambiguous = 0; double worst = 0.0, sum = 0.0; for (UINT vk_y = 0; vk_y < height; ++vk_y) { for (UINT x = 0; x < width; ++x) { @@ -360,6 +361,10 @@ int main() { continue; } if (!want_covered) continue; + if (want[3] == -2.0f) { // on a UV seam: the edge rule picks the triangle, so the colour is not compared + ++ambiguous; + continue; + } ++compared; for (int c = 0; c < 4; ++c) { const double e = std::fabs(double(got[c]) - double(want[c])); @@ -370,9 +375,11 @@ int main() { } } std::printf("covered %u/%u; %u pixels compared with the CPU reference: worst %.5f, mean %.6f, %u channels over " - "%.5f; %u coverage mismatches\n", covered, width * height, compared, worst, - compared ? sum / (compared * 4.0) : 0.0, over, tolerance, coverage_mismatch); + "%.5f; %u coverage mismatches; %u on a UV seam (colour not compared)\n", covered, width * height, + compared, worst, compared ? sum / (compared * 4.0) : 0.0, over, tolerance, coverage_mismatch, + ambiguous); EXPECT(compared > 0); + EXPECT(ambiguous <= covered / 100); // seams are edges: a large count means the reference is wrong // Coverage is the same rasterisation as d3d12_first_light; the CPU reference marks pixel centres inside a // triangle, so only edge pixels may disagree. EXPECT(coverage_mismatch <= covered / 100); diff --git a/tests/test_first_light.py b/tests/test_first_light.py index 9d9fcbc017..cbfd76bd87 100644 --- a/tests/test_first_light.py +++ b/tests/test_first_light.py @@ -1053,11 +1053,32 @@ def test_uv_map_matches_uv_at(self): vertices = [(-1.0, -1.0, 0.5, 0.0, 0.0), (1.0, -1.0, 0.5, 1.0, 0.0), (-1.0, 1.0, 0.5, 0.0, 1.0), (-0.5, -0.5, 0.5, 0.9, 0.9), (0.9, -0.5, 0.5, 0.8, 0.9), (-0.5, 0.9, 0.5, 0.9, 0.8)] indices = [0, 1, 2, 3, 4, 5] - got = fl.uv_map(vertices, indices, 16, 12) + got, ambiguous = fl.uv_map(vertices, indices, 16, 12) for py in range(12): for px in range(16): self.assertEqual(got[py * 16 + px], fl.uv_at(vertices, indices, px, py, 16, 12), (px, py)) self.assertTrue(any(g is None for g in got) and any(g is not None for g in got)) + self.assertEqual(ambiguous, set()) # overlapping interiors, not a seam: draw order decides + + def test_uv_seam_pixels_are_not_guessed(self): + # @whattheflop's fixture (#2906): a quad over framebuffer (4,4)-(28,28) on 32x32, split on its diagonal, the + # two halves with constant but different UVs. Which triangle owns a diagonal sample is the rasteriser's edge + # rule, so swapping the draw order must change nothing outside the reported seam. + def ndc(v): + return v / 32 * 2 - 1 + p = [(ndc(4), ndc(4)), (ndc(28), ndc(4)), (ndc(28), ndc(28)), (ndc(4), ndc(28))] + vertices = [(p[0][0], p[0][1], 0.5, 0.25, 0.75), (p[1][0], p[1][1], 0.5, 0.25, 0.75), + (p[2][0], p[2][1], 0.5, 0.25, 0.75), + (p[0][0], p[0][1], 0.5, 0.75, 0.25), (p[2][0], p[2][1], 0.5, 0.75, 0.25), + (p[3][0], p[3][1], 0.5, 0.75, 0.25)] + forward, seam_f = fl.uv_map(vertices, [0, 1, 2, 3, 4, 5], 32, 32) + backward, seam_b = fl.uv_map(vertices, [3, 4, 5, 0, 1, 2], 32, 32) + self.assertEqual(seam_f, seam_b) + self.assertEqual(len(seam_f), 24) # the diagonal's sample points + self.assertEqual(sum(uv is not None for uv in forward), 576) + for k in range(32 * 32): + if k not in seam_f: + self.assertEqual(forward[k], backward[k], k) if __name__ == "__main__": sys.exit(unittest.main()) diff --git a/tools/first_light.py b/tools/first_light.py index 1fa0adc911..8671f97c56 100644 --- a/tools/first_light.py +++ b/tools/first_light.py @@ -589,9 +589,16 @@ def sample_bilinear_clamp(texels, w: int, h: int, u: float, v: float): for c in range(4)) +AMBIGUOUS = -2.0 # expected.raw alpha for a covered pixel whose colour depends on the rasteriser's edge rule + + def uv_map(vertices, indices, width: int, height: int): - """uv_at for every pixel centre at once (the last covering triangle wins), by triangle bounding box.""" + """uv_at for every pixel centre at once (the last covering triangle wins), by triangle bounding box, plus the + pixels whose UV the edge rule decides: a sample on a shared edge between triangles that give it different + UVs (a UV seam). Vulkan gives such a sample to exactly one of them by its tie-break rule, which this reference + does not model, so those pixels are reported instead of guessed. Returns (uvs, ambiguous pixel indices).""" found = [None] * (width * height) + hits = {} # pixel -> [(uv, on_edge)] for pixels covered more than once for i in range(0, len(indices), 3): a, b, c = (vertices[indices[i + k]] for k in range(3)) xs, ys = (a[0], b[0], c[0]), (a[1], b[1], c[1]) @@ -604,11 +611,23 @@ def uv_map(vertices, indices, width: int, height: int): x, y = pixel_ndc(px, py, width, height) weights = barycentric(x, y, a[0], a[1], b[0], b[1], c[0], c[1]) if weights: - found[py * width + px] = ( + k = py * width + px + uv = ( weights[0] * a[3] + weights[1] * b[3] + weights[2] * c[3], weights[0] * a[4] + weights[1] * b[4] + weights[2] * c[4], ) - return found + on_edge = min(weights) <= 1e-6 + if found[k] is not None or on_edge: + hits.setdefault(k, []).append((uv, on_edge)) + found[k] = uv + ambiguous = set() + for k, entries in hits.items(): + if len(entries) < 2 or not any(edge for _, edge in entries): + continue # overlapping interiors: draw order decides, and the last one wins as uv_at says + uvs = [uv for uv, _ in entries] + if any(abs(u[0] - uvs[0][0]) > 1e-6 or abs(u[1] - uvs[0][1]) > 1e-6 for u in uvs[1:]): + ambiguous.add(k) + return found, ambiguous def write_textured_inputs(out_dir: str, vertices, indices, width: int, height: int) -> dict: @@ -619,9 +638,13 @@ def write_textured_inputs(out_dir: str, vertices, indices, width: int, height: i f.write(data) expected = bytearray() covered = 0 - for uv in uv_map(vertices, indices, width, height): + uvs, ambiguous = uv_map(vertices, indices, width, height) + for k, uv in enumerate(uvs): if uv is None: expected += struct.pack("<4f", -1.0, -1.0, -1.0, -1.0) + elif k in ambiguous: + covered += 1 + expected += struct.pack("<4f", 0.0, 0.0, 0.0, AMBIGUOUS) else: covered += 1 expected += struct.pack("<4f", *sample_bilinear_clamp(texels, RAMP_SIZE, RAMP_SIZE, uv[0], uv[1])) @@ -629,6 +652,7 @@ def write_textured_inputs(out_dir: str, vertices, indices, width: int, height: i f.write(expected) return {"texture": "ramp", "texture_size": [RAMP_SIZE, RAMP_SIZE], "texture_format": "R16G16B16A16_FLOAT", "texture_sha256": hashlib.sha256(data).hexdigest(), "expected_covered": covered, + "expected_ambiguous": len(ambiguous), # Half a texel is 1/128 = 0.0078: a point-sampled draw exceeds this everywhere; bilinear rounding stays # under 0.0005 (RTX 3060). "texture_tolerance": 0.002} From 178d4c86587691e2cbf3c3bc8c5cdfc1f1b6540f Mon Sep 17 00:00:00 2001 From: Rafael Date: Sun, 22 Nov 2026 16:04:06 -0300 Subject: [PATCH 3/8] first_light: a seam is judged from the latest hit back to the first interior one An earlier edge no longer exempts a pixel that a later interior owns (@whattheflop's nested-triangle fixture), and a lone edge over an older interior with another UV is ambiguous. Edge hits after the last interior that share one UV are an edge both triangles share, which the tie-break gives to one of them: not ambiguous. Without that rule the flattened first-light model's front layer, drawn over its back layer, marked 188 pixels; with it, 0, and all 12,804 are compared. Co-Authored-By: Claude Opus 5.5 --- tests/test_first_light.py | 34 ++++++++++++++++++++++++++++++++++ tools/first_light.py | 31 +++++++++++++++++++++++-------- 2 files changed, 57 insertions(+), 8 deletions(-) diff --git a/tests/test_first_light.py b/tests/test_first_light.py index cbfd76bd87..c5eaa16be0 100644 --- a/tests/test_first_light.py +++ b/tests/test_first_light.py @@ -1080,5 +1080,39 @@ def ndc(v): if k not in seam_f: self.assertEqual(forward[k], backward[k], k) + def test_an_interior_hides_earlier_edges(self): + # @whattheflop's second fixture (#2906): an inner triangle whose left edge (x = 24.5, on pixel centres) lies + # inside a larger outer one, the two with different UVs. Drawn inner-then-outer, the outer interior owns + # every sample on the inner's edge: nothing is ambiguous and the image equals a solid outer reference. + # Drawn outer-then-inner, the inner is last and those samples are on its edge, so the edge rule decides + # whether they show the inner or the outer UV: exactly those 48 samples are ambiguous. + def tri(pts, uv): + return [((x / 128) * 2 - 1, (y / 128) * 2 - 1, 0.5, uv[0], uv[1]) for x, y in pts] + outer = tri([(8, 8), (104, 8), (8, 103)], (0.25, 0.75)) + inner = tri([(24.5, 20), (56, 20), (24.5, 68)], (0.75, 0.25)) + vertices = outer + inner + uvs_oi, seam_oi = fl.uv_map(vertices, [0, 1, 2, 3, 4, 5], 128, 128) + uvs_io, seam_io = fl.uv_map(vertices, [3, 4, 5, 0, 1, 2], 128, 128) + self.assertEqual(seam_io, set()) + self.assertEqual(len(seam_oi), 48) + self.assertEqual({k % 128 for k in seam_oi}, {24}) # pixel column 24: centre x = 24.5 + solid, _ = fl.uv_map(outer, [0, 1, 2], 128, 128) + self.assertEqual(uvs_io, solid) # outer drawn last covers the inner one everywhere + + def test_a_shared_edge_over_an_older_interior_is_not_ambiguous(self): + # A front quad (two triangles sharing a diagonal, continuous UVs) drawn over a back triangle with another + # UV: the diagonal's samples belong to one of the two front triangles, both of which give the same UV. + def tri(pts, uvs): + return [((x / 64) * 2 - 1, (y / 64) * 2 - 1, 0.5, u, v) for (x, y), (u, v) in zip(pts, uvs)] + back = tri([(2, 2), (62, 2), (2, 62)], [(0.9, 0.9)] * 3) + quad = [(8.5, 8.5), (40.5, 8.5), (40.5, 40.5), (8.5, 40.5)] + quv = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] + front = tri([quad[0], quad[1], quad[2]], [quv[0], quv[1], quv[2]]) + \ + tri([quad[0], quad[2], quad[3]], [quv[0], quv[2], quv[3]]) + _, seam = fl.uv_map(back + front, list(range(9)), 64, 64) + self.assertEqual(seam & {32 * 64 + 32, 20 * 64 + 20}, set()) # two diagonal samples + # The quad's outer edges over the back triangle are lone edges with another UV behind: ambiguous. + self.assertIn(20 * 64 + 8, seam) + if __name__ == "__main__": sys.exit(unittest.main()) diff --git a/tools/first_light.py b/tools/first_light.py index 8671f97c56..a6f3e42b03 100644 --- a/tools/first_light.py +++ b/tools/first_light.py @@ -598,7 +598,7 @@ def uv_map(vertices, indices, width: int, height: int): UVs (a UV seam). Vulkan gives such a sample to exactly one of them by its tie-break rule, which this reference does not model, so those pixels are reported instead of guessed. Returns (uvs, ambiguous pixel indices).""" found = [None] * (width * height) - hits = {} # pixel -> [(uv, on_edge)] for pixels covered more than once + hits = {} # pixel -> [(uv, on_edge)] in draw order for i in range(0, len(indices), 3): a, b, c = (vertices[indices[i + k]] for k in range(3)) xs, ys = (a[0], b[0], c[0]), (a[1], b[1], c[1]) @@ -616,16 +616,31 @@ def uv_map(vertices, indices, width: int, height: int): weights[0] * a[3] + weights[1] * b[3] + weights[2] * c[3], weights[0] * a[4] + weights[1] * b[4] + weights[2] * c[4], ) - on_edge = min(weights) <= 1e-6 - if found[k] is not None or on_edge: - hits.setdefault(k, []).append((uv, on_edge)) + hits.setdefault(k, []).append((uv, min(weights) <= 1e-6)) found[k] = uv + # The colour a pixel ends with comes from the last triangle that owns its sample. A hit strictly inside a + # triangle owns it and hides every earlier hit. A hit on an edge may not own it: the tie-break rule decides, so + # the hit before it is still a candidate. Walk from the latest hit back to the first interior one (@whattheflop, + # #2906). Two or more edge hits there with the same UV are an edge both triangles share, drawn after anything + # older: the rule gives the sample to exactly one of them, so that UV is the colour's. Otherwise the pixel is + # ambiguous when the candidates' UVs differ (a UV seam, or a lone edge over an older interior). + def same(p, q): + return abs(p[0] - q[0]) <= 1e-6 and abs(p[1] - q[1]) <= 1e-6 + ambiguous = set() for k, entries in hits.items(): - if len(entries) < 2 or not any(edge for _, edge in entries): - continue # overlapping interiors: draw order decides, and the last one wins as uv_at says - uvs = [uv for uv, _ in entries] - if any(abs(u[0] - uvs[0][0]) > 1e-6 or abs(u[1] - uvs[0][1]) > 1e-6 for u in uvs[1:]): + edges, interior = [], None + for uv, on_edge in reversed(entries): + if not on_edge: + interior = uv + break + edges.append(uv) + if not edges: + continue + if len(edges) >= 2 and all(same(uv, edges[0]) for uv in edges[1:]): + continue + candidates = edges + ([interior] if interior is not None else []) + if any(not same(uv, candidates[0]) for uv in candidates[1:]): ambiguous.add(k) return found, ambiguous From 44db1edf2d6a72d118113da2b864a3938ea0e667 Mon Sep 17 00:00:00 2001 From: Rafael Date: Sun, 22 Nov 2026 16:12:55 -0300 Subject: [PATCH 4/8] first_light: the shared-edge shortcut needs a real shared edge Equal UVs don't make two triangles share an edge. The rasteriser gives one owner only to triangles on opposite sides of a common edge with identical endpoints, so the shortcut now requires such a pair among the later edge hits; a sample on a vertex never takes it. @whattheflop's overlapping right edges (same side, different endpoints) stay ambiguous. The first-light model: 8 ambiguous samples, 12,796 compared, unchanged worst error. Co-Authored-By: Claude Opus 5.5 --- tests/test_first_light.py | 14 ++++++++++++++ tools/first_light.py | 32 +++++++++++++++++++++++++++----- 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/tests/test_first_light.py b/tests/test_first_light.py index c5eaa16be0..634e8ce90c 100644 --- a/tests/test_first_light.py +++ b/tests/test_first_light.py @@ -1114,5 +1114,19 @@ def tri(pts, uvs): # The quad's outer edges over the back triangle are lone edges with another UV behind: ambiguous. self.assertIn(20 * 64 + 8, seam) + def test_overlapping_edges_on_the_same_side_are_ambiguous(self): + # @whattheflop's third fixture (#2906): two front triangles with equal UVs whose right edges overlap and + # whose interiors both lie to the left, over an older triangle with another UV. They don't share an edge + # (different endpoints, same side), so a top-left rule can exclude both: those samples stay ambiguous. + def tri(pts, uv): + return [((x / 128) * 2 - 1, (y / 128) * 2 - 1, 0.5, uv[0], uv[1]) for x, y in pts] + outer = tri([(8, 8), (104, 8), (8, 103)], (0.25, 0.75)) + f1 = tri([(16, 20), (32.5, 20), (32.5, 52)], (0.75, 0.25)) + f2 = tri([(12, 16), (32.5, 16), (32.5, 56)], (0.75, 0.25)) + for order in ([0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 6, 7, 8, 3, 4, 5]): + _, seam = fl.uv_map(outer + f1 + f2, order, 128, 128) + column = {k for k in seam if k % 128 == 32} + self.assertGreaterEqual(len(column), 32, order) + if __name__ == "__main__": sys.exit(unittest.main()) diff --git a/tools/first_light.py b/tools/first_light.py index a6f3e42b03..9c29fbf518 100644 --- a/tools/first_light.py +++ b/tools/first_light.py @@ -589,6 +589,23 @@ def sample_bilinear_clamp(texels, w: int, h: int, u: float, v: float): for c in range(4)) +def edge_side(a, b, c, weights): + """For a sample on exactly one edge of triangle abc: (the edge's endpoints as a sorted pair of positions, the + side of that edge the third vertex is on). None for a sample inside, or on a vertex (two zero weights).""" + zero = [i for i, w in enumerate(weights) if w <= 1e-6] + if len(zero) != 1: + return None + verts = (a, b, c) + third = verts[zero[0]] + p, q = (verts[i] for i in range(3) if i != zero[0]) + cross = (q[0] - p[0]) * (third[1] - p[1]) - (q[1] - p[1]) * (third[0] - p[0]) + key = tuple(sorted(((p[0], p[1]), (q[0], q[1])))) + # The side is relative to the sorted direction, so two triangles agree on it exactly when on the same side. + if key[0] != (p[0], p[1]): + cross = -cross + return key, cross > 0 + + AMBIGUOUS = -2.0 # expected.raw alpha for a covered pixel whose colour depends on the rasteriser's edge rule @@ -616,7 +633,7 @@ def uv_map(vertices, indices, width: int, height: int): weights[0] * a[3] + weights[1] * b[3] + weights[2] * c[3], weights[0] * a[4] + weights[1] * b[4] + weights[2] * c[4], ) - hits.setdefault(k, []).append((uv, min(weights) <= 1e-6)) + hits.setdefault(k, []).append((uv, min(weights) <= 1e-6, edge_side(a, b, c, weights))) found[k] = uv # The colour a pixel ends with comes from the last triangle that owns its sample. A hit strictly inside a # triangle owns it and hides every earlier hit. A hit on an edge may not own it: the tie-break rule decides, so @@ -630,16 +647,21 @@ def same(p, q): ambiguous = set() for k, entries in hits.items(): edges, interior = [], None - for uv, on_edge in reversed(entries): + for uv, on_edge, side in reversed(entries): if not on_edge: interior = uv break - edges.append(uv) + edges.append((uv, side)) if not edges: continue - if len(edges) >= 2 and all(same(uv, edges[0]) for uv in edges[1:]): + uvs = [uv for uv, _ in edges] + # The rule gives one owner only to two triangles on opposite sides of a common edge with identical + # endpoints (@whattheflop, #2906): equal UVs alone don't make a shared edge. + shared = any(s1 and s2 and s1[0] == s2[0] and s1[1] != s2[1] + for i, (_, s1) in enumerate(edges) for _, s2 in edges[i + 1:]) + if shared and all(same(uv, uvs[0]) for uv in uvs[1:]): continue - candidates = edges + ([interior] if interior is not None else []) + candidates = uvs + ([interior] if interior is not None else []) if any(not same(uv, candidates[0]) for uv in candidates[1:]): ambiguous.add(k) return found, ambiguous From 16003a633004a39565c7421552a81a50aa3fc9b7 Mon Sep 17 00:00:00 2001 From: Rafael Date: Sun, 22 Nov 2026 16:49:46 -0300 Subject: [PATCH 5/8] d3d12_first_light_textured_test: read LEONIDA_FIRST_LIGHT_TEX_DIR with _dupenv_s MSVC warns about std::getenv (C4996); pe_loader_test reads its environment the same way. Reported by @JRamos1993. Co-Authored-By: Claude Opus 5.5 --- .../test/d3d12_first_light_textured_test.cpp | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/runtime/test/d3d12_first_light_textured_test.cpp b/runtime/test/d3d12_first_light_textured_test.cpp index 8a2f6b627c..cd040dfef1 100644 --- a/runtime/test/d3d12_first_light_textured_test.cpp +++ b/runtime/test/d3d12_first_light_textured_test.cpp @@ -60,10 +60,18 @@ UINT texel_bytes(DXGI_FORMAT format) { } // namespace int main() { - const char* dir_env = std::getenv("LEONIDA_FIRST_LIGHT_TEX_DIR"); - if (!dir_env || !*dir_env) { - std::printf("SKIP: LEONIDA_FIRST_LIGHT_TEX_DIR is not set (run tools/first_light.py --texture first)\n"); - return 77; + // _dupenv_s, as pe_loader_test reads its environment: MSVC warns about std::getenv (C4996). + std::filesystem::path dir; + { + char* env = nullptr; + std::size_t env_size = 0; + if (_dupenv_s(&env, &env_size, "LEONIDA_FIRST_LIGHT_TEX_DIR") != 0 || !env || !*env) { + std::free(env); + std::printf("SKIP: LEONIDA_FIRST_LIGHT_TEX_DIR is not set (run tools/first_light.py --texture first)\n"); + return 77; + } + dir = env; + std::free(env); } vktest::Device d; const auto device_status = d.initialize(); @@ -77,7 +85,6 @@ int main() { return 77; } - const std::filesystem::path dir = dir_env; const auto manifest_text = read_file(dir / "manifest.json"); leonida::Json manifest; EXPECT(leonida::JsonReader(std::string_view(reinterpret_cast(manifest_text.data()), From 7a08f9fbcf58f9ecd9df9c8546f94d022e0db871 Mon Sep 17 00:00:00 2001 From: Rafael Date: Sun, 22 Nov 2026 17:17:12 -0300 Subject: [PATCH 6/8] d3d12_first_light_textured_test: the comment on d3d12_textured.raw names no option that doesn't exist Reported by @zzEmmazz. Co-Authored-By: Claude Opus 5.5 --- runtime/test/d3d12_first_light_textured_test.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/runtime/test/d3d12_first_light_textured_test.cpp b/runtime/test/d3d12_first_light_textured_test.cpp index cd040dfef1..98d0b7426a 100644 --- a/runtime/test/d3d12_first_light_textured_test.cpp +++ b/runtime/test/d3d12_first_light_textured_test.cpp @@ -342,7 +342,8 @@ int main() { EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } - // The image as drawn, rows in vk_harness order, for first_light.py --check-textured to read back. + // The image as drawn, rows in vk_harness order, next to the inputs (d3d12_textured.raw), so a run on one GPU can + // be compared with another's byte for byte; nothing in the repository reads it. { std::ofstream out(dir / "d3d12_textured.raw", std::ios::binary); for (UINT vk_y = 0; vk_y < height; ++vk_y) From 5cb119cc3a53ed54438e5c3df23a614ff2bd7c51 Mon Sep 17 00:00:00 2001 From: Rafael Date: Sun, 22 Nov 2026 19:48:09 -0300 Subject: [PATCH 7/8] first_light: the ramp's manifest keys no longer collide with the --dds harness path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since the rebase onto 7e1aecf0, --texture ramp exited with a TypeError: write_textured_inputs stored "texture": "ramp" and files["texture"], which harness_env reads as the --dds dict. The ramp's keys are now layer_texture*; a unit test feeds harness_env a ramp manifest (fails on the old keys). The vk_harness tests skip a ramp folder, which only the D3D12-layer test can draw. docs/first_light.md §7: the command names its --out, and the count without #2887 is 19,041 channels (measured here and on three other GPUs). Found by @zzEmmazz. Co-Authored-By: Claude Opus 5.5 --- docs/first_light.md | 9 ++++++--- tests/test_first_light.py | 19 +++++++++++++++++++ tools/first_light.py | 8 +++++--- 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/docs/first_light.md b/docs/first_light.md index 93c98fe68a..22f41c01f3 100644 --- a/docs/first_light.md +++ b/docs/first_light.md @@ -231,11 +231,14 @@ centres, so the image has an exact oracle. `first_light.py --texture ramp` write On an RTX 3060 (Windows 11, driver 616.64), the draw covers the same **12,804 pixels** as section 5, with no coverage mismatch. The worst channel error is **0.00028** and the mean 0.000045, against a tolerance of 0.002. Point sampling would be off by up to half a texel (1/128 = 0.0078). That is what this draw gave before literal S#s -were registered (#2887), because the shader's lookup found the fallback sampler: worst error 0.0078, with 18,616 -channels over the tolerance. +were registered (#2887), because the shader's lookup found the fallback sampler: worst error 0.0078, with 19,041 +channels over the tolerance. The same count was measured on an RTX 3070, a Ryzen RDNA2 iGPU and an RTX 5090. + +The ramp folder is for this test only: its PS samples a T# that only the D3D12 layer binds, so +`tests/test_first_light.py`'s `vk_harness` tests skip it. ```sh -python -I tools/first_light.py ... --no-fit --vs VS_main_170e32e6_Wrapped --ps '$PS_PassthroughCopy_1a08fc46_Wrapped' --texture ramp +python -I tools/first_light.py ... --no-fit --out ~/leonida-work/first_light/out_tex --vs VS_main_170e32e6_Wrapped --ps '$PS_PassthroughCopy_1a08fc46_Wrapped' --texture ramp LEONIDA_FIRST_LIGHT_TEX_DIR=~/leonida-work/first_light/out_tex ctest --test-dir -R d3d12_first_light_textured -V ``` diff --git a/tests/test_first_light.py b/tests/test_first_light.py index 634e8ce90c..fd243b2595 100644 --- a/tests/test_first_light.py +++ b/tests/test_first_light.py @@ -117,6 +117,10 @@ def setUp(self): ) with open(os.path.join(self.out, "manifest.json"), encoding="utf-8") as f: self.manifest = json.load(f) + if self.manifest.get("layer_texture"): + # A --texture ramp folder feeds d3d12_first_light_textured (LEONIDA_FIRST_LIGHT_TEX_DIR): its PS samples a + # T# that only the D3D12 layer binds, so vk_harness has nothing to draw it with (@zzEmmazz, #2906). + self.skipTest("a --texture ramp folder is for d3d12_first_light_textured, not vk_harness") def test_draw_matches_the_manifest(self): raw = os.path.join(self.out, "image_first_light.raw") @@ -1022,6 +1026,21 @@ def test_harness_env_passes_only_the_manifests_constants(self): class LayerTexturedOracleTests(unittest.TestCase): """The D3D12-layer textured first light's CPU reference (#2906), without a GPU or a package.""" + def test_ramp_inputs_leave_the_harness_texture_keys_alone(self): + # @zzEmmazz (#2906): the ramp's manifest keys once shared "texture" and files["texture"] with the --dds + # harness path, so harness_env read the string "ramp" as the --dds dict and the tool exited with a + # TypeError. The ramp's keys are layer_*; harness_env must neither fail nor bind a harness texture. + with tempfile.TemporaryDirectory() as tmp: + verts = [(-0.5, -0.5, 0.5, 0.0, 0.0), (0.5, -0.5, 0.5, 1.0, 0.0), (-0.5, 0.5, 0.5, 0.0, 1.0)] + manifest = {"files": {"mesh": "mesh.bin"}} + manifest.update(fl.write_textured_inputs(tmp, verts, [0, 1, 2], 8, 8)) + manifest["files"].update(layer_texture="texture.bin", expected="expected.raw") + self.assertNotIn("texture", manifest) + self.assertNotIn("texture", manifest["files"]) + env = fl.harness_env(manifest, tmp, base_env={}) + self.assertNotIn("VKH_TEX_RGBA", env) + self.assertTrue(os.path.isfile(os.path.join(tmp, "texture.bin"))) + def test_ramp_texels_hold_their_own_centre(self): texels, data = fl.ramp_texture(4) self.assertEqual(struct.unpack_from(" int: manifest["rgba_probes"] = tex_probes if a.texture and vertices: manifest.update(write_textured_inputs(out_dir, vertices, indices, a.width, a.height)) - manifest["files"].update(texture="texture.bin", expected="expected.raw") + manifest["files"].update(layer_texture="texture.bin", expected="expected.raw") with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(manifest, f, indent=1) print(f"{len(vertices)} vertices, {len(indices) // 3} triangles -> {out_dir}") From 9410b624281ca854a732750ce9145b6856b12747 Mon Sep 17 00:00:00 2001 From: Rafael Date: Sun, 22 Nov 2026 19:57:44 -0300 Subject: [PATCH 8/8] first_light textured: the PS's pointer SGPR and T# slot come from the PS (13 game copy shaders pass) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit d3d12_first_light_textured fixed the table at s8 and the T# at slot 0. It now reads layer_ptr_sgpr (from the index's user_sgpr_reads) and layer_tsharp_offset (the PS's first s_load_dwordx8 offset), pads the root signature to that SGPR and puts the SRV in that slot, so any 2D copy PS can be checked. Of the 24 copy PS that link with the first-light VS, all 13 comparable ones pass on an RTX 3060 with worst error 0.00028 (11 plain copies, 2 that remap channels, checked per channel); 7 transform the UV and 4 use array/cube textures. docs/first_light.md §7 has the table. Co-Authored-By: Claude Opus 5.5 --- docs/first_light.md | 16 +++++++++++ .../test/d3d12_first_light_textured_test.cpp | 27 ++++++++++++++----- tests/test_first_light.py | 13 +++++++++ tools/first_light.py | 21 +++++++++++++++ 4 files changed, 70 insertions(+), 7 deletions(-) diff --git a/docs/first_light.md b/docs/first_light.md index 22f41c01f3..965158c1cb 100644 --- a/docs/first_light.md +++ b/docs/first_light.md @@ -234,6 +234,22 @@ Point sampling would be off by up to half a texel (1/128 = 0.0078). That is what were registered (#2887), because the shader's lookup found the fallback sampler: worst error 0.0078, with 19,041 channels over the tolerance. The same count was measured on an RTX 3070, a Ryzen RDNA2 iGPU and an RTX 5090. +The test takes the PS's layout from the PS itself. The pointer SGPR comes from the index (`user_sgpr_reads`, +`layer_ptr_sgpr`), and the root signature pads up to it. The T#'s byte offset in the table comes from the PS's +`s_load_dwordx8` (`layer_tsharp_offset`), and the SRV goes in that slot. So any 2D copy PS can be checked, not only +`$PS_PassthroughCopy`. Of the 148 single-sample PS that link with this VS (section 6's census), 24 sample once and +export the result with no arithmetic. On an RTX 3060: + +| group | PS | result | +|---|---:|---| +| plain copies (`PS_Copy*`, `PS_TexCopy`, `PS_mipMap`, `$PS_PassthroughCopy`, `#PS_DownsampleCopy`, `PS_CopyWetMap`, `'PS_FreezeFrameCapture`, `!PS_AIFComposite`, `-PS_SecondPassRefractionBlit`) | 11 | pass, worst 0.00028 | +| copies that remap channels: `&PS_HDRPassThroughRGB` exports (r, g, b, b) and `PS_BlitNormal` (r, g, 1, 1), checked per channel | 2 | pass, worst 0.00028 | +| the UV transformed before the sample (overlays, zoom, live renderer, lens distortion) | 7 | not a copy, so not comparable to the ramp | +| 2D-array or cube textures | 4 | not run | + +All 13 comparable game PS give the same worst error as `$PS_PassthroughCopy`. `!PS_AIFComposite` reads its T# at +offset `0xA0` (slot 5), which a single-slot table had missed. Pass `--ps=` when the name starts with `-`. + The ramp folder is for this test only: its PS samples a T# that only the D3D12 layer binds, so `tests/test_first_light.py`'s `vk_harness` tests skip it. diff --git a/runtime/test/d3d12_first_light_textured_test.cpp b/runtime/test/d3d12_first_light_textured_test.cpp index 98d0b7426a..a6afa41fb3 100644 --- a/runtime/test/d3d12_first_light_textured_test.cpp +++ b/runtime/test/d3d12_first_light_textured_test.cpp @@ -155,18 +155,28 @@ int main() { reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); - // [0] s0..s7: eight zero constants; [1] s8:s9: the SRV table whose low dword the PS reads as its pointer. - D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + // [0] s0..s(p-1): zero constants; [1] s(p):s(p+1): the SRV table whose low dword the PS reads as its + // pointer. p is the PS's pointer SGPR from the index (layer_ptr_sgpr; s8 for $PS_PassthroughCopy). + const UINT ptr_sgpr = UINT(number(manifest, "layer_ptr_sgpr", 8)); + EXPECT(ptr_sgpr <= 30); + // The PS s_loads its T# at a byte offset in the table (layer_tsharp_offset, from its listing): the table + // holds that many descriptors before it, and the texture's SRV goes in that slot. + const UINT tsharp_offset = UINT(number(manifest, "layer_tsharp_offset", 0)); + EXPECT(tsharp_offset % 32 == 0 && tsharp_offset <= 32 * 63); + const UINT srv_slot = tsharp_offset / 32; + D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srv_slot + 1, 0, 0, 0}; D3D12_ROOT_PARAMETER params[2] = {}; params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - params[0].Constants = {0, 0, 8}; + params[0].Constants = {0, 0, ptr_sgpr}; params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; params[1].DescriptorTable = {1, &srv_range}; params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const UINT table_param = ptr_sgpr ? 1 : 0; // with the pointer at s0 there is nothing to pad 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_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; + root_desc.Desc_1_0 = {table_param + 1, ptr_sgpr ? params : params + 1, 0, nullptr, + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; const auto root_blob = serialize_root_signature(root_desc); EXPECT(!root_blob.empty()); Ref root; @@ -245,7 +255,7 @@ int main() { const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; device->CreateRenderTargetView(target.p, nullptr, rtv); - const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, srv_slot + 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); const std::uint64_t srv_cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); @@ -257,7 +267,10 @@ int main() { srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srv.Texture2D.MipLevels = 1; - device->CreateShaderResourceView(tex.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(srv_cpu)}); + const UINT srv_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(srv_step == 32); // the console's T# is 32 bytes: a byte offset in the table is a slot + device->CreateShaderResourceView(tex.p, &srv, + D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(srv_cpu + std::uint64_t(srv_slot) * srv_step)}); D3D12_COMMAND_QUEUE_DESC queue_desc{}; Ref queue; @@ -294,7 +307,7 @@ int main() { list->SetGraphicsRootSignature(root.p); ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; list->SetDescriptorHeaps(1, heaps); - list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu}); + list->SetGraphicsRootDescriptorTable(table_param, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu}); list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); const D3D12_VERTEX_BUFFER_VIEW vbv{vertex_buffer->GetGPUVirtualAddress(), UINT(vertex_bytes), stride}; list->IASetVertexBuffers(0, 1, &vbv); diff --git a/tests/test_first_light.py b/tests/test_first_light.py index fd243b2595..635db1b563 100644 --- a/tests/test_first_light.py +++ b/tests/test_first_light.py @@ -1041,6 +1041,19 @@ def test_ramp_inputs_leave_the_harness_texture_keys_alone(self): self.assertNotIn("VKH_TEX_RGBA", env) self.assertTrue(os.path.isfile(os.path.join(tmp, "texture.bin"))) + def test_tsharp_load_offset_reads_the_first_8_dword_load(self): + # The T# slot comes from the PS's own s_load_dwordx8; a missing listing or a null offset is slot 0. + with tempfile.TemporaryDirectory() as tmp: + listing = os.path.join(tmp, "ps.s") + with open(listing, "w", encoding="utf-8") as f: + f.write("\ts_load_dwordx4 s[8:11], s[2:3], 0x40\n\ts_load_dwordx8 s[0:7], s[2:3], 0xa0 ; T#\n" + "\ts_load_dwordx8 s[12:19], s[2:3], 0x20\n") + self.assertEqual(fl.tsharp_load_offset(listing), 0xA0) + with open(listing, "w", encoding="utf-8") as f: + f.write("\ts_load_dwordx8 s[4:11], s[8:9], null\n") + self.assertEqual(fl.tsharp_load_offset(listing), 0) + self.assertEqual(fl.tsharp_load_offset(os.path.join(tmp, "missing.s")), 0) + def test_ramp_texels_hold_their_own_centre(self): texels, data = fl.ramp_texture(4) self.assertEqual(struct.unpack_from(" int: + """The byte offset of the PS's first 8-dword scalar load (its T#) in its table, 0 when the listing has none or + doesn't exist. d3d12_first_light_textured puts the texture's SRV at that slot (32-byte descriptors).""" + try: + with open(listing, encoding="utf-8", errors="replace") as f: + text = f.read() + except OSError: + return 0 + m = re.search(r"^\s*s_load_dwordx8\s+s\[\d+:\d+\],\s*s\[\d+:\d+\],\s*(0x[0-9a-fA-F]+|\d+|null)", text, re.M) + if not m or m.group(1) == "null": + return 0 + return int(m.group(1), 0) + + def write_textured_inputs(out_dir: str, vertices, indices, width: int, height: int) -> dict: """texture.bin and expected.raw for d3d12_first_light_textured_test: the ramp, and the CPU reference of the draw (the texture sampled at each covered pixel's UV, -1 elsewhere, in the harness's row order).""" @@ -1273,6 +1288,12 @@ def main(argv=None) -> int: manifest["rgba_probes"] = tex_probes if a.texture and vertices: manifest.update(write_textured_inputs(out_dir, vertices, indices, a.width, a.height)) + # The SGPR the PS reads its T# table pointer from; d3d12_first_light_textured pads the root signature to it. + manifest["layer_ptr_sgpr"] = next( + (int(r["sgpr"]) for r in (meta["ps"].get("user_sgpr_reads") or []) + if r.get("kind") in ("ptr32_lo", "ptr64_lo")), DEFAULT_PTR_SGPR) + manifest["layer_tsharp_offset"] = tsharp_load_offset( + os.path.join(work, "shaders", "dxbc", "disasm", picked[1]["name"] + ".s")) manifest["files"].update(layer_texture="texture.bin", expected="expected.raw") with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(manifest, f, indent=1)