diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e843d8debc..e62d6c202b 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2823,6 +2823,22 @@ Pipeline creation: `LEONIDA_TRACE_PIPELINE_COMPILE=1` records each graphics and compute build's trigger, thread, elapsed time, SPIR-V size, shader names and Vulkan application-cache feedback (1 hit, 0 miss, -1 unavailable). It also times cache reads, merges, writes and draw/dispatch pipeline lookups that take at least 1 ms. + The `pipeline-compile-begin`, `pipeline-compile` and (for a draw) `pipeline-use` lines carry `id=` and the + `variant=` it was built or asked for. `id=` is the identity of a graphics pipeline's description, the same in every + run of the same shaders: a SHA-256 of the decoded state blocks (blend, sample mask, rasterizer, depth and stencil, + stream output), the checksum and size of each stage's DXBC container (VS, PS, DS, HS, GS, and the MS of a mesh + pipeline; an AS is hashed too, but a pipeline with one is refused before it gets an identity), the render target and + depth formats, the sample count, the input layout, strip cut and topology type (not for a mesh pipeline, whose D3D12 + reading ignores them), and for a stream the back face's stencil masks and the depth bounds test. Those two are only + passed on the `ID3D12Device2::CreatePipelineState` path: a console stream prepared at bind time (`resolve_type`) + builds without them, so the same stream of the title gets another `id` there. The identity is that of what is built + (`graphics_identity`, `runtime/shims/d3d12_graphics_identity.h`). The root signature, an address and the device are + not in it. `PipelineState::create_graphics` computes it, so every graphics creation path sets it + (`CreateGraphicsPipelineState`, slot 57, and `ID3D12Device2::CreatePipelineState`, mesh pipelines included). `id=-` + is a compute pipeline. `key=` is the other name, the description the PC runtime matches a `CachedPSO` against: it + holds the root signature (its content, or its address for an object that is not ours), so it can differ between + runs, and the stream path leaves it `-`. `id=` is for telling the same pipeline apart from another across runs; it + does not change what is built or the driver's cache key. `LEONIDA_ASYNC_PIPELINES=1` schedules cold first-use builds on the warm-up worker ahead of speculative work; how long a submission waits for them, and what is skipped, is "Pipelines still being built" below. Strict replay builds synchronously and waits for every build. `LEONIDA_COMPUTE_WARMUP=0` restricts the worker to pipelines requested by diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..813c71ef55 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1517,6 +1517,13 @@ if(BUILD_TESTING) target_compile_options(pso_stream_test PRIVATE /W4 /permissive- /utf-8) target_link_options(pso_stream_test PRIVATE /OPT:NOREF) add_test(NAME pso_stream COMMAND pso_stream_test) + # The identity of a graphics description (d3d12_graphics_identity.h): header only, synthetic descriptions. + add_executable(graphics_identity_test test/graphics_identity_test.cpp) + target_include_directories(graphics_identity_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(graphics_identity_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(graphics_identity_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(graphics_identity_test PRIVATE /OPT:NOREF) + add_test(NAME graphics_identity COMMAND graphics_identity_test) endif() if(TARGET root_sig_test) diff --git a/runtime/shims/d3d12_graphics_identity.h b/runtime/shims/d3d12_graphics_identity.h new file mode 100644 index 0000000000..58cc0002c7 --- /dev/null +++ b/runtime/shims/d3d12_graphics_identity.h @@ -0,0 +1,122 @@ +// The identity of a graphics pipeline description: a hash of what defines the pipeline and nothing of the run. +// +// pipeline_key (ID3D12PipelineState::GetCachedBlob, the `key=` of the pipeline-compile log line) is what the PC +// runtime matches a CachedPSO against. It names the root signature (its content, or its address for an object that is +// not ours, which can differ between runs), it is not set on the stream creation path, and it has no MS or AS. +// The identity below is for finding the same pipeline again in another run, so it takes none of those: the decoded +// state blocks, the checksum of the shader of every stage, the formats and the topology the description declares. +// The root signature, an address and a pointer are not in it. Nothing here reads a device or changes what is built. +#pragma once + +#include "../src/cached_pso.h" +#include "../src/shader_library.h" + +#include + +#include +#include +#include +#include +#include +#include + +namespace rt::d3d12 { + +// The back face's stencil masks of a DEPTH_STENCIL2 subobject. D3D12_DEPTH_STENCIL_DESC has one read and one write +// mask for both faces, so the face masks travel beside the description. +struct StencilFaceMasks { + UINT8 read = D3D12_DEFAULT_STENCIL_READ_MASK; + UINT8 write = D3D12_DEFAULT_STENCIL_WRITE_MASK; +}; + +// A shader as the key sees it, without reading the whole program on every PSO: a DXBC container already carries a +// checksum of its contents (bytes 4..19), so that and the size stand for it. A container without one (all zero, as +// hand-built test containers have) or other bytecode is hashed with FNV-1a. +inline void key_shader(leonida::cached_pso::KeyBuilder& key, const char* stage, const D3D12_SHADER_BYTECODE& code) { + const auto* bytes = static_cast(code.pShaderBytecode); + const std::size_t size = bytes ? code.BytecodeLength : 0; + key.tag(stage).u32(std::uint32_t(size)).u32(std::uint32_t(std::uint64_t(size) >> 32)); + if (size >= 20 && std::memcmp(bytes, "DXBC", 4) == 0 && + std::any_of(bytes + 4, bytes + 20, [](std::uint8_t b) { return b != 0; })) { + key.bytes(bytes + 4, 16); + return; + } + std::uint64_t h = 0xcbf29ce484222325ull; + for (std::size_t i = 0; i < size; ++i) h = (h ^ bytes[i]) * 0x100000001b3ull; + key.u32(std::uint32_t(h)).u32(std::uint32_t(h >> 32)); +} + +// Everything of a graphics description but its root signature, in the order pipeline_key has always hashed it. +// `input_assembly` false leaves out the input layout, the strip cut and the topology type: D3D12 ignores them for a +// mesh pipeline. +inline void key_graphics_state(leonida::cached_pso::KeyBuilder& key, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, + bool input_assembly) { + key_shader(key, "vs", desc.VS); + key_shader(key, "ps", desc.PS); + key_shader(key, "ds", desc.DS); + key_shader(key, "hs", desc.HS); + key_shader(key, "gs", desc.GS); + const D3D12_STREAM_OUTPUT_DESC& so = desc.StreamOutput; + key.u32(so.pSODeclaration ? so.NumEntries : 0); + for (UINT i = 0; so.pSODeclaration && i < so.NumEntries; ++i) { + const D3D12_SO_DECLARATION_ENTRY& e = so.pSODeclaration[i]; + key.u32(e.Stream).text(e.SemanticName).u32(e.SemanticIndex).u32(e.StartComponent).u32(e.ComponentCount); + key.u32(e.OutputSlot); + } + key.u32(so.pBufferStrides ? so.NumStrides : 0); + for (UINT i = 0; so.pBufferStrides && i < so.NumStrides; ++i) key.u32(so.pBufferStrides[i]); + key.u32(so.RasterizedStream); + const D3D12_BLEND_DESC& blend = desc.BlendState; + key.u32(blend.AlphaToCoverageEnable).u32(blend.IndependentBlendEnable); + for (const D3D12_RENDER_TARGET_BLEND_DESC& t : blend.RenderTarget) + key.u32(t.BlendEnable).u32(t.LogicOpEnable).u32(t.SrcBlend).u32(t.DestBlend).u32(t.BlendOp).u32(t.SrcBlendAlpha) + .u32(t.DestBlendAlpha).u32(t.BlendOpAlpha).u32(t.LogicOp).u32(t.RenderTargetWriteMask); + key.u32(desc.SampleMask); + const D3D12_RASTERIZER_DESC& r = desc.RasterizerState; + std::uint32_t bias_clamp = 0, slope = 0; + std::memcpy(&bias_clamp, &r.DepthBiasClamp, 4); + std::memcpy(&slope, &r.SlopeScaledDepthBias, 4); + key.u32(r.FillMode).u32(r.CullMode).u32(r.FrontCounterClockwise).u32(std::uint32_t(r.DepthBias)).u32(bias_clamp); + key.u32(slope).u32(r.DepthClipEnable).u32(r.MultisampleEnable).u32(r.AntialiasedLineEnable); + key.u32(r.ForcedSampleCount).u32(r.ConservativeRaster); + const D3D12_DEPTH_STENCIL_DESC& d = desc.DepthStencilState; + key.u32(d.DepthEnable).u32(d.DepthWriteMask).u32(d.DepthFunc).u32(d.StencilEnable).u32(d.StencilReadMask); + key.u32(d.StencilWriteMask); + for (const D3D12_DEPTH_STENCILOP_DESC& face : {d.FrontFace, d.BackFace}) + key.u32(face.StencilFailOp).u32(face.StencilDepthFailOp).u32(face.StencilPassOp).u32(face.StencilFunc); + if (input_assembly) { + const D3D12_INPUT_LAYOUT_DESC& input = desc.InputLayout; + const UINT input_count = input.pInputElementDescs + ? std::min(input.NumElements, D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) + : 0; + key.u32(input_count); + for (UINT i = 0; i < input_count; ++i) { + const D3D12_INPUT_ELEMENT_DESC& e = input.pInputElementDescs[i]; + key.text(e.SemanticName).u32(e.SemanticIndex).u32(e.Format).u32(e.InputSlot).u32(e.AlignedByteOffset); + key.u32(e.InputSlotClass).u32(e.InstanceDataStepRate); + } + key.u32(desc.IBStripCutValue).u32(std::bit_cast(desc.PrimitiveTopologyType)); + } + key.u32(desc.NumRenderTargets); + for (const DXGI_FORMAT format : desc.RTVFormats) key.u32(format); + key.u32(desc.DSVFormat).u32(desc.SampleDesc.Count).u32(desc.SampleDesc.Quality).u32(desc.NodeMask); +} + +// The identity of what create_graphics is given: the description, an MS or AS stage, the back face's stencil masks +// and the depth bounds test of a pipeline state stream. 64 lowercase hex digits (SHA-256). +inline std::string graphics_identity(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, + const D3D12_SHADER_BYTECODE* ms = nullptr, + const D3D12_SHADER_BYTECODE* as = nullptr, + const StencilFaceMasks* back_masks = nullptr, bool depth_bounds = false) { + const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength; + leonida::cached_pso::KeyBuilder key; + key.tag("graphics identity 1"); + key_graphics_state(key, desc, !mesh); + key_shader(key, "ms", ms ? *ms : D3D12_SHADER_BYTECODE{}); + key_shader(key, "as", as ? *as : D3D12_SHADER_BYTECODE{}); + key.u32(back_masks ? 1u : 0u).u32(back_masks ? back_masks->read : 0u).u32(back_masks ? back_masks->write : 0u); + key.u32(depth_bounds ? 1u : 0u); + return leonida::sha256_hex(key.data()); +} + +} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_pipeline_compile.h b/runtime/shims/d3d12_pipeline_compile.h index 674fba6938..cf488db7ec 100644 --- a/runtime/shims/d3d12_pipeline_compile.h +++ b/runtime/shims/d3d12_pipeline_compile.h @@ -113,14 +113,18 @@ inline long long compile_wall_ms() { std::chrono::system_clock::now().time_since_epoch()).count(); } -template VkPipeline replay_pipeline(const char* trigger, Build&& get) { +// `description_id` is the graphics_identity of the pipeline being used ("-" for none, as for a compute pipeline) and +// `variant` the variant asked for. +template VkPipeline replay_pipeline(const char* trigger, Build&& get, const std::string& description_id = {}, + std::uint32_t variant = 0) { if (!trace_pipeline_compile()) return get(); const auto start = compile_us(); auto handle = get(); auto elapsed = compile_us() - start; if (elapsed >= 1000) - std::fprintf(stderr, "[rt] pipeline-use trigger=%s tid=%lu us=%lld ready=%d end_ms=%lld\n", - trigger, GetCurrentThreadId(), elapsed, int(handle != VK_NULL_HANDLE), compile_wall_ms()); + std::fprintf(stderr, "[rt] pipeline-use trigger=%s tid=%lu us=%lld ready=%d end_ms=%lld id=%s variant=%u\n", + trigger, GetCurrentThreadId(), elapsed, int(handle != VK_NULL_HANDLE), compile_wall_ms(), + description_id.empty() ? "-" : description_id.c_str(), variant); return handle; } @@ -130,15 +134,18 @@ struct CompileTrace { nullptr, &feedback, 0, nullptr}; long long started = 0; const char* key = "-"; + const char* id = "-"; // graphics_identity of a graphics pipeline, "-" for a compute pipeline bool linked = false; // chain is in a create info's pNext chain template void begin(Info& info, bool supported, const char* trigger, const char* shaders, - std::uint32_t variant, std::size_t bytes, const std::string& description_key) { + std::uint32_t variant, std::size_t bytes, const std::string& description_key, + const std::string& description_id = {}) { if (!trace_pipeline_compile()) return; if (!description_key.empty()) key = description_key.c_str(); + if (!description_id.empty()) id = description_id.c_str(); if (supported) request_feedback(info); - std::fprintf(stderr, "[rt] pipeline-compile-begin trigger=%s tid=%lu bytes=%zu variant=%u begin_ms=%lld key=%s shaders=%s\n", - trigger, GetCurrentThreadId(), bytes, variant, compile_wall_ms(), key, shaders); + std::fprintf(stderr, "[rt] pipeline-compile-begin trigger=%s tid=%lu bytes=%zu variant=%u begin_ms=%lld key=%s id=%s shaders=%s\n", + trigger, GetCurrentThreadId(), bytes, variant, compile_wall_ms(), key, id, shaders); started = compile_us(); } @@ -163,8 +170,9 @@ struct CompileTrace { const auto ended = compile_us(); const int hit = this->hit(); std::fprintf(stderr, "[rt] pipeline-compile trigger=%s tid=%lu start_us=%lld us=%lld hit=%d bytes=%zu " - "variant=%u result=%d end_ms=%lld key=%s shaders=%s\n", trigger, GetCurrentThreadId(), started, - ended - started, hit, bytes, variant, int(result), compile_wall_ms(), key, shaders); + "variant=%u result=%d end_ms=%lld key=%s id=%s shaders=%s\n", trigger, GetCurrentThreadId(), + started, ended - started, hit, bytes, variant, int(result), compile_wall_ms(), key, id, + shaders); } }; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 748d6144a5..b3c96ae6e7 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -12,6 +12,7 @@ #include "d3d12_com.h" #include "d3d12_compile_exit.h" #include "d3d12_pipeline_compile.h" +#include "d3d12_graphics_identity.h" #include "d3d12_precompile.h" #include "d3d12_compile_helper.h" #include "d3d12_pipeline_checkpoint.h" @@ -11206,23 +11207,6 @@ class CachedBlob final : public ID3DBlob { std::atomic refs_{1}; }; -// A shader as the key sees it, without reading the whole program on every PSO: a DXBC container already carries a -// checksum of its contents (bytes 4..19), so that and the size stand for it. A container without one (all zero, as -// hand-built test containers have) or other bytecode is hashed with FNV-1a. -void key_shader(leonida::cached_pso::KeyBuilder& key, const char* stage, const D3D12_SHADER_BYTECODE& code) { - const auto* bytes = static_cast(code.pShaderBytecode); - const std::size_t size = bytes ? code.BytecodeLength : 0; - key.tag(stage).u32(std::uint32_t(size)).u32(std::uint32_t(std::uint64_t(size) >> 32)); - if (size >= 20 && std::memcmp(bytes, "DXBC", 4) == 0 && - std::any_of(bytes + 4, bytes + 20, [](std::uint8_t b) { return b != 0; })) { - key.bytes(bytes + 4, 16); - return; - } - std::uint64_t h = 0xcbf29ce484222325ull; - for (std::size_t i = 0; i < size; ++i) h = (h ^ bytes[i]) * 0x100000001b3ull; - key.u32(std::uint32_t(h)).u32(std::uint32_t(h >> 32)); -} - void key_root_signature(leonida::cached_pso::KeyBuilder& key, ID3D12RootSignature* signature); // The parts of a compute description the PC runtime matches a cached PSO against (not Flags, measured). @@ -11239,52 +11223,7 @@ leonida::cached_pso::Key pipeline_key(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& leonida::cached_pso::KeyBuilder key; key.tag("graphics"); key_root_signature(key, desc.pRootSignature); - key_shader(key, "vs", desc.VS); - key_shader(key, "ps", desc.PS); - key_shader(key, "ds", desc.DS); - key_shader(key, "hs", desc.HS); - key_shader(key, "gs", desc.GS); - const D3D12_STREAM_OUTPUT_DESC& so = desc.StreamOutput; - key.u32(so.pSODeclaration ? so.NumEntries : 0); - for (UINT i = 0; so.pSODeclaration && i < so.NumEntries; ++i) { - const D3D12_SO_DECLARATION_ENTRY& e = so.pSODeclaration[i]; - key.u32(e.Stream).text(e.SemanticName).u32(e.SemanticIndex).u32(e.StartComponent).u32(e.ComponentCount); - key.u32(e.OutputSlot); - } - key.u32(so.pBufferStrides ? so.NumStrides : 0); - for (UINT i = 0; so.pBufferStrides && i < so.NumStrides; ++i) key.u32(so.pBufferStrides[i]); - key.u32(so.RasterizedStream); - const D3D12_BLEND_DESC& blend = desc.BlendState; - key.u32(blend.AlphaToCoverageEnable).u32(blend.IndependentBlendEnable); - for (const D3D12_RENDER_TARGET_BLEND_DESC& t : blend.RenderTarget) - key.u32(t.BlendEnable).u32(t.LogicOpEnable).u32(t.SrcBlend).u32(t.DestBlend).u32(t.BlendOp).u32(t.SrcBlendAlpha) - .u32(t.DestBlendAlpha).u32(t.BlendOpAlpha).u32(t.LogicOp).u32(t.RenderTargetWriteMask); - key.u32(desc.SampleMask); - const D3D12_RASTERIZER_DESC& r = desc.RasterizerState; - std::uint32_t bias_clamp = 0, slope = 0; - std::memcpy(&bias_clamp, &r.DepthBiasClamp, 4); - std::memcpy(&slope, &r.SlopeScaledDepthBias, 4); - key.u32(r.FillMode).u32(r.CullMode).u32(r.FrontCounterClockwise).u32(std::uint32_t(r.DepthBias)).u32(bias_clamp); - key.u32(slope).u32(r.DepthClipEnable).u32(r.MultisampleEnable).u32(r.AntialiasedLineEnable); - key.u32(r.ForcedSampleCount).u32(r.ConservativeRaster); - const D3D12_DEPTH_STENCIL_DESC& d = desc.DepthStencilState; - key.u32(d.DepthEnable).u32(d.DepthWriteMask).u32(d.DepthFunc).u32(d.StencilEnable).u32(d.StencilReadMask); - key.u32(d.StencilWriteMask); - for (const D3D12_DEPTH_STENCILOP_DESC& face : {d.FrontFace, d.BackFace}) - key.u32(face.StencilFailOp).u32(face.StencilDepthFailOp).u32(face.StencilPassOp).u32(face.StencilFunc); - const D3D12_INPUT_LAYOUT_DESC& input = desc.InputLayout; - const UINT input_count = - input.pInputElementDescs ? std::min(input.NumElements, D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) : 0; - key.u32(input_count); - for (UINT i = 0; i < input_count; ++i) { - const D3D12_INPUT_ELEMENT_DESC& e = input.pInputElementDescs[i]; - key.text(e.SemanticName).u32(e.SemanticIndex).u32(e.Format).u32(e.InputSlot).u32(e.AlignedByteOffset); - key.u32(e.InputSlotClass).u32(e.InstanceDataStepRate); - } - key.u32(desc.IBStripCutValue).u32(std::bit_cast(desc.PrimitiveTopologyType)) - .u32(desc.NumRenderTargets); - for (const DXGI_FORMAT format : desc.RTVFormats) key.u32(format); - key.u32(desc.DSVFormat).u32(desc.SampleDesc.Count).u32(desc.SampleDesc.Quality).u32(desc.NodeMask); + key_graphics_state(key, desc, true); return leonida::sha256_hex(key.data()); } @@ -11321,13 +11260,6 @@ class XboxPipelineStateStubs : public ID3D12PipelineStateStubs { // subobject that is absent takes the runtime's default (the CD3DX12 defaults: depth test on with LESS, back-face // culling, no blending, sample mask 0xFFFFFFFF, one sample). A type given twice, a truncated stream or an unknown // type is E_INVALIDARG, as on the PC runtime; state this layer cannot honour yet is E_NOTIMPL with a log. -// The back face's stencil masks of a DEPTH_STENCIL2 subobject. D3D12_DEPTH_STENCIL_DESC has one read and one write -// mask for both faces, so the face masks travel beside the description. -struct StencilFaceMasks { - UINT8 read = D3D12_DEFAULT_STENCIL_READ_MASK; - UINT8 write = D3D12_DEFAULT_STENCIL_WRITE_MASK; -}; - struct PipelineStream { D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics{}; bool back_masks = false; // DEPTH_STENCIL2: back_stencil holds the back face's masks @@ -12233,6 +12165,8 @@ class PipelineState final } if (desc.NodeMask & ~1u) return E_INVALIDARG; if (static_cast(desc.Flags) & ~kKnownPipelineStateFlags) return E_INVALIDARG; + // Observation only (the pipeline-compile and pipeline-use log lines): every creation path ends here. + description_id_ = graphics_identity(desc, ms, as, back_masks, depth_bounds); if (!device_.arena.mapped) { return stream_unsupported("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1); } @@ -12941,7 +12875,7 @@ class PipelineState final graphics_.variant = [this](std::uint32_t unbound) { return replay_pipeline("draw", [&] { return graphics_.async_build ? queue_build(false, unbound) : variant(unbound, "draw"); - }); + }, description_id_, unbound); }; graphics_.built = [this](std::uint32_t unbound) { std::unique_lock lock(variants_mutex_, std::try_to_lock); // held: another thread is compiling one @@ -13620,7 +13554,7 @@ class PipelineState final } } CompileTrace trace; - trace.begin(info, device_.info.pipeline_creation_feedback, trigger, profile_shaders_.c_str(), unbound, bytes, cache_key_); + trace.begin(info, device_.info.pipeline_creation_feedback, trigger, profile_shaders_.c_str(), unbound, bytes, cache_key_, description_id_); const leonida::dev_status::Build dev_build(r.mesh ? "mesh pipeline" : "graphics pipeline"); const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", program, fragment, unbound); @@ -13818,6 +13752,8 @@ class PipelineState final bool native_source_ready_ = false; std::shared_ptr native_owner_; leonida::cached_pso::Key cache_key_; + // graphics_identity of the description create_graphics was given; empty for a compute pipeline. + std::string description_id_; leonida::cached_pso::Key order_key_; // see set_order_key; empty: cache_key_ std::uint64_t order_hash_ = 0; // 0: this pipeline is not in the order log char order_kind_ = 'c'; diff --git a/runtime/test/graphics_identity_test.cpp b/runtime/test/graphics_identity_test.cpp new file mode 100644 index 0000000000..73d4f8642b --- /dev/null +++ b/runtime/test/graphics_identity_test.cpp @@ -0,0 +1,212 @@ +// The identity of a graphics pipeline description (d3d12_graphics_identity.h) with synthetic descriptions only: no +// D3D12 device, no GPU, no game data. The shader "containers" are hand-built DXBC headers with an invented checksum. +// +// The identity must tell two descriptions apart by what defines the pipeline (state blocks, the checksum of each +// stage's shader, formats, topology, an MS or AS stage) and must not move with what differs from run to run (the +// root signature the title builds, an address, the copy of the bytecode in memory, flags and a cached blob). +#include + +#include +#include +#include +#include +#include + +#include "d3d12_graphics_identity.h" + +namespace { + +int g_failures = 0; + +void check(bool ok, const char* what) { + std::printf("%s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) ++g_failures; +} + +using rt::d3d12::StencilFaceMasks; + +// A DXBC header (magic, 16 checksum bytes, version, size, no parts) whose checksum is `seed` repeated. +std::vector container(std::uint8_t seed, std::size_t size = 32) { + std::vector bytes(size, 0); + std::memcpy(bytes.data(), "DXBC", 4); + for (int i = 0; i < 16; ++i) bytes[4 + i] = std::uint8_t(seed + i); + return bytes; +} + +D3D12_SHADER_BYTECODE view(const std::vector& bytes) { return {bytes.data(), bytes.size()}; } + +struct Fixture { + std::vector vs = container(0x10), ps = container(0x40), ms = container(0x70), as = container(0x90); + D3D12_INPUT_ELEMENT_DESC element{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}; + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + + Fixture() { + desc.VS = view(vs); + desc.PS = view(ps); + for (auto& target : desc.BlendState.RenderTarget) { + target.SrcBlend = target.SrcBlendAlpha = D3D12_BLEND_ONE; + target.DestBlend = target.DestBlendAlpha = D3D12_BLEND_ZERO; + target.BlendOp = target.BlendOpAlpha = D3D12_BLEND_OP_ADD; + target.LogicOp = D3D12_LOGIC_OP_NOOP; + target.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + } + desc.SampleMask = 0xFFFFFFFFu; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_BACK; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.DepthStencilState.DepthEnable = TRUE; + desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + desc.InputLayout = {&element, 1}; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 2; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.RTVFormats[1] = DXGI_FORMAT_R16G16B16A16_FLOAT; + desc.DSVFormat = DXGI_FORMAT_D32_FLOAT; + desc.SampleDesc = {1, 0}; + } +}; + +std::string id(const Fixture& f) { return rt::d3d12::graphics_identity(f.desc); } + +// A description with the VS and the input stage of a mesh pipeline left out and `f.ms` as its mesh stage. +std::string mesh_id(Fixture f, const std::vector& mesh, const StencilFaceMasks* back = nullptr, + bool depth_bounds = false, const D3D12_SHADER_BYTECODE* task = nullptr) { + f.desc.VS = {}; + f.desc.InputLayout = {}; + f.desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED; + const D3D12_SHADER_BYTECODE ms = view(mesh); + return rt::d3d12::graphics_identity(f.desc, &ms, task, back, depth_bounds); +} + +bool hex64(const std::string& s) { + if (s.size() != 64) return false; + for (const char c : s) + if (!std::isdigit(static_cast(c)) && !(c >= 'a' && c <= 'f')) return false; + return true; +} + +} // namespace + +int main() { + const Fixture base; + const std::string reference = id(base); + check(hex64(reference), "the identity is 64 lowercase hex digits"); + check(id(Fixture{}) == reference, "two descriptions built the same way share an identity"); + + // Frozen values. key_graphics_state also feeds pipeline_key, whose hash names entries of a cache on disk: a + // field moved, widened or reordered there would orphan every user's cache without any other test noticing. + // The first value was computed with the code of main before the function was shared. + { + leonida::cached_pso::KeyBuilder state; + rt::d3d12::key_graphics_state(state, base.desc, true); + check(leonida::sha256_hex(state.data()) == "484d5f08252d7e0e80ca370520841e2b9fe2cc59306208e70508d60e841ac3e1", + "the bytes key_graphics_state feeds the cache key are the ones main hashed"); + check(reference == "d2b87fb92c4fbc33728f50dde1c1011baa729388403a47fce753bad3282c367e", + "the identity of the reference description is the frozen one"); + } + + // What is not part of the description: a copy of the bytecode elsewhere in memory, the root signature, flags, + // a cached blob. + { + Fixture f; + const auto vs_copy = f.vs, ps_copy = f.ps; + f.desc.VS = view(vs_copy); + f.desc.PS = view(ps_copy); + check(id(f) == reference, "the same bytecode at another address keeps the identity"); + } + { + Fixture f; + f.desc.pRootSignature = reinterpret_cast(std::uintptr_t(0x1000)); + const std::string first = id(f); + f.desc.pRootSignature = reinterpret_cast(std::uintptr_t(0x2468ace0)); + check(first == reference && id(f) == reference, "another root signature (or its address) keeps the identity"); + } + { + Fixture f; + f.desc.Flags = D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG; + const char blob[4] = {1, 2, 3, 4}; + f.desc.CachedPSO = {blob, sizeof blob}; + check(id(f) == reference, "flags and a cached blob keep the identity"); + } + { + Fixture f; + const std::string name_copy = "POSITION"; + f.element.SemanticName = name_copy.c_str(); + check(id(f) == reference, "an input semantic name at another address keeps the identity"); + } + + // What defines it: each change moves the identity. + const auto differs = [&](const char* what, auto&& change) { + Fixture f; + change(f); + check(id(f) != reference, what); + }; + differs("a vertex shader with another checksum changes it", [](Fixture& f) { f.vs = container(0x11); f.desc.VS = view(f.vs); }); + differs("a pixel shader with another checksum changes it", [](Fixture& f) { f.ps = container(0x41); f.desc.PS = view(f.ps); }); + differs("a pixel shader of another size changes it", [](Fixture& f) { f.ps = container(0x40, 48); f.desc.PS = view(f.ps); }); + differs("a geometry shader changes it", [](Fixture& f) { f.desc.GS = view(f.ms); }); + differs("no pixel shader changes it", [](Fixture& f) { f.desc.PS = {}; }); + differs("a blend factor changes it", [](Fixture& f) { f.desc.BlendState.RenderTarget[1].SrcBlend = D3D12_BLEND_SRC_ALPHA; }); + differs("blending on changes it", [](Fixture& f) { f.desc.BlendState.RenderTarget[0].BlendEnable = TRUE; }); + differs("a write mask changes it", [](Fixture& f) { f.desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0x7; }); + differs("the sample mask changes it", [](Fixture& f) { f.desc.SampleMask = 0xF; }); + differs("the cull mode changes it", [](Fixture& f) { f.desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; }); + differs("the depth bias changes it", [](Fixture& f) { f.desc.RasterizerState.DepthBias = 4; }); + differs("the depth function changes it", [](Fixture& f) { f.desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_GREATER; }); + differs("stencil on changes it", [](Fixture& f) { f.desc.DepthStencilState.StencilEnable = TRUE; }); + differs("a stencil operation changes it", [](Fixture& f) { f.desc.DepthStencilState.BackFace.StencilPassOp = D3D12_STENCIL_OP_REPLACE; }); + differs("a render target format changes it", [](Fixture& f) { f.desc.RTVFormats[1] = DXGI_FORMAT_R11G11B10_FLOAT; }); + differs("the number of render targets changes it", [](Fixture& f) { f.desc.NumRenderTargets = 1; }); + differs("the depth format changes it", [](Fixture& f) { f.desc.DSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT; }); + differs("the sample count changes it", [](Fixture& f) { f.desc.SampleDesc.Count = 4; }); + differs("the topology type changes it", [](Fixture& f) { f.desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; }); + differs("the strip cut value changes it", [](Fixture& f) { f.desc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF; }); + differs("an input element format changes it", [](Fixture& f) { f.element.Format = DXGI_FORMAT_R32G32_FLOAT; }); + differs("an input semantic name changes it", [](Fixture& f) { f.element.SemanticName = "TEXCOORD"; }); + differs("an input offset changes it", [](Fixture& f) { f.element.AlignedByteOffset = 12; }); + differs("no input element changes it", [](Fixture& f) { f.desc.InputLayout = {}; }); + + // The stream path: an MS stage, an AS stage, the back face's masks and the depth bounds test. + const Fixture mesh_base; + const std::string mesh_ref = mesh_id(mesh_base, mesh_base.ms); + check(hex64(mesh_ref) && mesh_ref != reference, "a mesh description has an identity of its own"); + check(mesh_id(Fixture{}, container(0x70)) == mesh_ref, "the same mesh stage in another buffer keeps the identity"); + check(mesh_id(mesh_base, container(0x71)) != mesh_ref, "a mesh stage with another checksum changes it"); + { + // Two pipelines that differ only in the mesh stage: the cache key of the stream path does not tell them apart. + const std::string other = mesh_id(mesh_base, container(0x72)); + check(other != mesh_ref && other != mesh_id(mesh_base, container(0x71)), "two mesh stages give two identities"); + } + { + const D3D12_SHADER_BYTECODE task = view(mesh_base.as); + check(mesh_id(mesh_base, mesh_base.ms, nullptr, false, &task) != mesh_ref, "an amplification stage changes it"); + } + { + const StencilFaceMasks masks{0x0f, 0xf0}; + const StencilFaceMasks other{0x0f, 0xf1}; + check(mesh_id(mesh_base, mesh_base.ms, &masks) != mesh_ref, "the back face's stencil masks change it"); + check(mesh_id(mesh_base, mesh_base.ms, &masks) != mesh_id(mesh_base, mesh_base.ms, &other), + "another back face write mask changes it"); + check(mesh_id(mesh_base, mesh_base.ms, &masks) == mesh_id(Fixture{}, container(0x70), &masks), + "the same back face masks keep it"); + } + check(mesh_id(mesh_base, mesh_base.ms, nullptr, true) != mesh_ref, "the depth bounds test changes it"); + { + // D3D12 ignores the input layout, the strip cut and the topology of a mesh pipeline, so they do not count. + Fixture f; + const D3D12_SHADER_BYTECODE ms = view(f.ms); + f.desc.VS = {}; + const std::string with_input = rt::d3d12::graphics_identity(f.desc, &ms); + check(with_input == mesh_ref, "a mesh pipeline ignores the input layout and topology the description carries"); + } + { + Fixture f; + f.desc.pRootSignature = reinterpret_cast(std::uintptr_t(0x77770)); + check(mesh_id(f, f.ms) == mesh_ref, "another root signature keeps a mesh identity"); + } + + std::printf(g_failures ? "FAILED: %d\n" : "all passed\n", g_failures); + return g_failures ? 1 : 0; +}