diff --git a/docs/first_light.md b/docs/first_light.md index 9eaff8f37c..965158c1cb 100644 --- a/docs/first_light.md +++ b/docs/first_light.md @@ -203,7 +203,65 @@ 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 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. + +```sh +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 +``` + +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..a6afa41fb3 --- /dev/null +++ b/runtime/test/d3d12_first_light_textured_test.cpp @@ -0,0 +1,414 @@ +// 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, 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" +#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() { + // _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(); + 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 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..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, 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 = {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; + 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, 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); + 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; + 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; + 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(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); + 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, 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) + 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, 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) { + 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; + 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])); + 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; %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); + 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..635db1b563 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") @@ -1019,5 +1023,142 @@ 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_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_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(" 0 + + +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, 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)] 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]) + px0 = max(0, int(((min(xs) + 1) * 0.5) * width - 0.5) - 1) + px1 = min(width - 1, int(((max(xs) + 1) * 0.5) * width - 0.5) + 1) + py0 = max(0, int(((min(ys) + 1) * 0.5) * height - 0.5) - 1) + py1 = min(height - 1, int(((max(ys) + 1) * 0.5) * height - 0.5) + 1) + for py in range(py0, py1 + 1): + for px in range(px0, px1 + 1): + 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: + 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], + ) + 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 + # 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(): + edges, interior = [], None + for uv, on_edge, side in reversed(entries): + if not on_edge: + interior = uv + break + edges.append((uv, side)) + if not edges: + continue + 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 = 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 + + +def tsharp_load_offset(listing: str) -> 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).""" + texels, data = ramp_texture() + with open(os.path.join(out_dir, "texture.bin"), "wb") as f: + f.write(data) + expected = bytearray() + covered = 0 + 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])) + with open(os.path.join(out_dir, "expected.raw"), "wb") as f: + f.write(expected) + # layer_* keys: "texture" and files["texture"] belong to the --dds harness path (harness_env reads them). + return {"layer_texture": "ramp", "layer_texture_size": [RAMP_SIZE, RAMP_SIZE], + "layer_texture_format": "R16G16B16A16_FLOAT", + "layer_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} + + 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 +1065,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 +1286,15 @@ 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)) + # 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) print(f"{len(vertices)} vertices, {len(indices) // 3} triangles -> {out_dir}")