diff --git a/docs/experiments/startup-pso-recipe.md b/docs/experiments/startup-pso-recipe.md
new file mode 100644
index 0000000000..266c2adefa
--- /dev/null
+++ b/docs/experiments/startup-pso-recipe.md
@@ -0,0 +1,61 @@
+# Translated PSO recipes
+
+The shader cache stores the translated vertex and pixel bytecode, the root signature and the
+sampler descriptions. It does not store the draw state that produced a desktop graphics pipeline
+state object: the blend state, depth-stencil state, rasterizer state, target formats and DSV format.
+A run therefore creates each translated PSO on its first draw.
+
+`X2W_PSO_RECIPE_DIR=
` records that state after a successful
+`CreateGraphicsPipelineState` and replays matching records before creating a new PSO on a later
+run. It is off by default.
+
+## Format
+
+One text file per translation key: `/pso_.txt`. The file holds up to 64
+records and 64 KiB. Each record starts with `x2w-pso-recipe 1` and ends with `end`. It carries the
+translation key, the target/depth/raster state key, the target count and formats, the DSV format,
+the `indexed_rect` flag, the effective blend state after export write masks, the depth-stencil
+state, the rasterizer state, the sample mask and count, and the topology type. No pointers or
+process addresses are written.
+
+The parser recomputes the state key from the recorded fields. A record whose recomputed key does
+not match the key it names, whose target formats or DSV do not match the current pass, or whose
+version is unknown is ignored and the unchanged creation path runs. A malformed or oversized file
+is counted and ignored.
+
+The writer applies the same parser before it appends. It refuses to add a record when the file
+already holds 64 complete records, when any existing line is rejected, or when the new record
+would cross 64 KiB. A 65th record would never be read back, so refusing it keeps the cache and the
+parser at the same boundary. It also refuses when a non-empty file does not end in LF: the parser
+accepts such a final record, but appending would join its `end` to the next header on one line. The
+file is left unchanged.
+
+The read, count/size check and append share one exclusive file handle. A second process that
+reaches the append path while the file is owned keeps the PSO it already created and skips the
+cache write; a reader denied by that handle also falls back to the unchanged creation path.
+Neither side can seek to an end offset that another writer selected.
+
+## Scope and limits
+
+This is state reconstruction, not a D3D12 pipeline library. A replayed record still calls
+`CreateGraphicsPipelineState`; the driver may compile or find the PSO in its own cache. The change
+moves the state reconstruction and the first-use creation earlier, and makes the exact draw state
+available without a title run. It does not claim to eliminate driver compilation.
+
+The device-free test `startup_pso_recipe` covers the serializer/parser round trip, two appended
+records, a corrupt state key, an unknown version, an oversized file, target-format and DSV
+mismatches, and the 63/64/65 record boundary (63 accepts one more, 64 refuses a 65th, and the
+parser rejects a 65th). `startup_stream_draw_warp` runs the two-process replay: the first
+translated stream draw writes a recipe, a second process with the same directory loads and
+precreates it, and all 32 RGBA bytes match. It also holds the recipe file exclusively during a
+draw and checks that the draw still renders with exact pixels while the file size stays unchanged.
+It then seeds 63 valid records for another translation key, checks that the next draw appends the
+matching record as number 64 and the following process logs `precreated 1`, and seeds 64 records to
+check that the draw still renders while the file stays at 64. It removes the final LF from that
+parseable file, runs another draw and checks that the file is byte-for-byte unchanged and still
+readable. That test covers the unused depth-stencil normalisation as well.
+
+```powershell
+ctest --preset dev --no-tests=error -R '^startup_pso_recipe$' -V
+ctest --preset dev --no-tests=error -R '^startup_stream_draw_warp$' -V
+```
diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl
index 5ae702805b..18803087f4 100644
--- a/src/startup_stubs/d3d12_draw.inl
+++ b/src/startup_stubs/d3d12_draw.inl
@@ -171,6 +171,7 @@ struct Translation {
int indirect_base_word = -1;
x2w_startup::ComPtr indexed_signature;
std::unordered_map pipelines; // by target formats
+ std::vector pso_recipes; // opt-in X2W_PSO_RECIPE_DIR records for this key
u64 key = 0;
LONG logged_draws = 0, logged_bindings = 0, logged_large = 0; // diagnostics budget per translation
};
@@ -190,6 +191,7 @@ struct BoundPipeline {
D3D12_RASTERIZER_DESC rasterizer{};
DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN;
std::unordered_map pipelines; // by target formats
+ std::unordered_set pso_recipe_targets_tried; // target/dsv signatures already replayed
};
// Looks for a desktop-layout D3D12_BLEND_DESC inside a state block: two flags, then eight render
@@ -222,6 +224,7 @@ std::unordered_map& translation_by_key() { static std::unorde
LONG translated_draws, untranslated_draws, translation_ready, translation_missing, null_bindings;
LONG formatted_draws_refused; // draws whose formatted buffer load had no resolved descriptor word 3 (also untranslated)
LONG null_by_cause[x2w_local::null_cause_count]; // null_bindings split by cause; the parts add up to it
+LONG pso_recipes_loaded, pso_recipes_precreated, pso_recipe_mismatches, pso_recipe_fallbacks;
void count_null_binding(x2w_local::NullCause cause)
{
@@ -257,6 +260,124 @@ bool read_text(const wchar_t* path, std::string& out)
return true;
}
+bool pso_recipe_path(wchar_t* out, u64 translation_key)
+{
+ wchar_t dir[MAX_PATH];
+ const DWORD saved = GetLastError();
+ const DWORD length = GetEnvironmentVariableW(L"X2W_PSO_RECIPE_DIR", dir, MAX_PATH);
+ SetLastError(saved);
+ if (!length || length >= MAX_PATH) return false;
+ const wchar_t separator = dir[length - 1] == L'\\' || dir[length - 1] == L'/' ? L'\0' : L'\\';
+ const int written = separator
+ ? swprintf(out, MAX_PATH, L"%s\\pso_%016llx.txt", dir, static_cast(translation_key))
+ : swprintf(out, MAX_PATH, L"%spso_%016llx.txt", dir, static_cast(translation_key));
+ return written > 0 && written < MAX_PATH;
+}
+
+bool read_pso_recipe_text(const wchar_t* path, std::string& out, bool& too_large)
+{
+ too_large = false;
+ // Deny writers for the whole read: a concurrent append holds the file exclusively, and this
+ // reader either sees the previous complete file or no file at all.
+ HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
+ if (file == INVALID_HANDLE_VALUE) return false;
+ LARGE_INTEGER size{};
+ if (!GetFileSizeEx(file, &size) || size.QuadPart < 0 || size.QuadPart > static_cast(x2w_startup::pso_recipe_file_limit)) {
+ too_large = true;
+ CloseHandle(file);
+ return false;
+ }
+ out.resize(static_cast(size.QuadPart));
+ std::size_t done = 0;
+ while (done < out.size()) {
+ DWORD got = 0;
+ const DWORD wanted = static_cast(std::min(out.size() - done, 1u << 20));
+ if (!ReadFile(file, out.data() + done, wanted, &got, nullptr) || !got) break;
+ done += got;
+ }
+ CloseHandle(file);
+ if (done != out.size()) out.clear();
+ return done == size.QuadPart;
+}
+
+// Called once a translation is ready. A missing directory or file is not an error; the runtime then
+// follows the unchanged creation path.
+void load_pso_recipes(Translation& tr)
+{
+ wchar_t path[MAX_PATH];
+ if (!pso_recipe_path(path, tr.key)) return;
+ std::string text;
+ bool too_large = false;
+ if (!read_pso_recipe_text(path, text, too_large)) {
+ if (too_large) {
+ InterlockedIncrement(&pso_recipe_mismatches);
+ static LONG logged;
+ if (first_calls(logged, 16)) log("x2w-draw pso recipe file for %016llx is above the size limit; ignored", tr.key);
+ }
+ return;
+ }
+ auto parsed = x2w_startup::parse_pso_recipe_file(text);
+ unsigned rejected = parsed.rejected;
+ parsed.recipes.erase(std::remove_if(parsed.recipes.begin(), parsed.recipes.end(), [&](const x2w_startup::PsoRecipe& recipe) {
+ if (recipe.translation_key == tr.key) return false;
+ ++rejected;
+ return true;
+ }), parsed.recipes.end());
+ if (rejected) InterlockedAdd(&pso_recipe_mismatches, static_cast(rejected));
+ if (!parsed.recipes.empty()) {
+ const std::size_t count = parsed.recipes.size();
+ InterlockedAdd(&pso_recipes_loaded, static_cast(std::min(count, LONG_MAX)));
+ tr.pso_recipes = std::move(parsed.recipes);
+ }
+ if (rejected || !tr.pso_recipes.empty()) {
+ log("x2w-draw pso recipes %016llx: %zu loaded, %u rejected%s%s", tr.key, tr.pso_recipes.size(), rejected,
+ parsed.error.empty() ? "" : "; first error: ", parsed.error.c_str());
+ }
+}
+
+bool append_pso_recipe(const wchar_t* path, const x2w_startup::PsoRecipe& recipe)
+{
+ const std::string record = x2w_startup::serialize_pso_recipe(recipe);
+ if (record.size() > x2w_startup::pso_recipe_file_limit) return false;
+ // One writer owns the file for the whole count/size check and append. A second process that
+ // reaches this path at the same time fails to open it and keeps the PSO it already created;
+ // that draw simply does not add a record. Readers also deny writers, so neither side observes
+ // a half-written record.
+ HANDLE file = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS,
+ FILE_ATTRIBUTE_NORMAL, nullptr);
+ if (file == INVALID_HANDLE_VALUE) return false;
+ LARGE_INTEGER size{};
+ bool ok = GetFileSizeEx(file, &size) && size.QuadPart >= 0 &&
+ static_cast(size.QuadPart) <= x2w_startup::pso_recipe_file_limit;
+ std::string existing;
+ if (ok) {
+ existing.resize(static_cast(size.QuadPart));
+ LARGE_INTEGER begin{};
+ ok = SetFilePointerEx(file, begin, nullptr, FILE_BEGIN) != 0;
+ std::size_t read = 0;
+ while (ok && read < existing.size()) {
+ DWORD got = 0;
+ const DWORD wanted = static_cast(std::min(existing.size() - read, 1u << 20));
+ ok = ReadFile(file, existing.data() + read, wanted, &got, nullptr) != 0 && got != 0;
+ read += got;
+ }
+ ok = ok && read == existing.size();
+ }
+ ok = ok && x2w_startup::pso_recipe_append_allowed(existing, record);
+ LARGE_INTEGER at{};
+ at.QuadPart = size.QuadPart;
+ if (ok) ok = SetFilePointerEx(file, at, nullptr, FILE_BEGIN) != 0;
+ std::size_t done = 0;
+ while (ok && done < record.size()) {
+ DWORD written = 0;
+ const DWORD wanted = static_cast(std::min(record.size() - done, 1u << 20));
+ ok = WriteFile(file, record.data() + done, wanted, &written, nullptr) != 0 && written == wanted;
+ done += written;
+ }
+ CloseHandle(file);
+ return ok && done == record.size();
+}
+
// Publish each input atomically. The callers write the request's ready marker last.
bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std::size_t bytes)
{
@@ -376,6 +497,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {})
return;
}
tr.state = 1;
+ load_pso_recipes(tr);
if (previously_missing) InterlockedDecrement(&translation_missing);
InterlockedIncrement(&translation_ready);
log("x2w-draw pipeline %016llx translated: %zu entry values, %zu resources, %zu writable textures, %zu static samplers, sampler_heap=%u",
@@ -942,57 +1064,117 @@ inline DXGI_FORMAT pass_dsv_format(const BoundPipeline& bound, const Pass& pass)
return pass.dsv_format != DXGI_FORMAT_UNKNOWN ? pass.dsv_format : bound.dsv_format;
}
+bool effective_blend_state(const BoundPipeline& bound, const Translation& tr, UINT target_count, D3D12_BLEND_DESC& blend)
+{
+ blend = x2w_startup::default_pso_blend();
+ if (bound.has_blend) blend = bound.blend;
+ return x2w_startup::apply_export_write_masks(blend, tr.write_masks, target_count);
+}
+
+bool prepare_translated_pso_desc(Translation& tr, bool indexed_rect, D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc)
+{
+ desc.pRootSignature = tr.root;
+ desc.VS = {tr.vs->GetBufferPointer(), tr.vs->GetBufferSize()};
+ desc.PS = {tr.ps->GetBufferPointer(), tr.ps->GetBufferSize()};
+ if (!indexed_rect) return true;
+ if (!tr.indexed_rect_geometry_attempted) {
+ tr.indexed_rect_geometry_attempted = true;
+ x2w_startup::ComPtr errors;
+ const HRESULT hr = x2w_startup::compile_indexed_rect_geometry(tr.vs, tr.ps, &tr.indexed_rect_geometry, &errors);
+ if (FAILED(hr))
+ log("x2w-draw %016llx: indexed rectangle geometry unavailable (0x%08lx) %s", tr.key,
+ static_cast(hr), errors ? static_cast(errors->GetBufferPointer()) : "");
+ }
+ if (!tr.indexed_rect_geometry) return false;
+ desc.GS = {tr.indexed_rect_geometry->GetBufferPointer(), tr.indexed_rect_geometry->GetBufferSize()};
+ return true;
+}
+
+// A recipe can only be used when its draw state and the pass match the recipe's key. Other records
+// in the same translation file stay on disk for a later pass and are ignored here.
+bool replay_pso_recipes(BoundPipeline& bound, Translation& tr, const Pass& pass, DXGI_FORMAT dsv_format,
+ bool use_depth_stencil, const D3D12_BLEND_DESC& effective_blend)
+{
+ unsigned precreated = 0, mismatched = 0, failed = 0;
+ const D3D12_RASTERIZER_DESC bound_rasterizer = bound.has_rasterizer ? bound.rasterizer : x2w_startup::default_pso_rasterizer();
+ for (const x2w_startup::PsoRecipe& recipe : tr.pso_recipes) {
+ if (recipe.translation_key != tr.key || !x2w_startup::pso_recipe_targets_match(recipe, pass.target_count,
+ pass.target_formats, dsv_format))
+ continue;
+ if (recipe.use_depth_stencil != use_depth_stencil ||
+ (use_depth_stencil && !x2w_startup::same_pso_depth(recipe.depth_stencil, bound.depth_stencil)) ||
+ recipe.has_rasterizer != bound.has_rasterizer ||
+ !x2w_startup::same_pso_rasterizer(recipe.rasterizer, bound_rasterizer) ||
+ !x2w_startup::same_pso_blend(recipe.blend, effective_blend) || recipe.sample_count != 1 ||
+ recipe.sample_mask != ~0u || recipe.topology != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) {
+ ++mismatched;
+ continue;
+ }
+ const u64 key = x2w_startup::pso_state_key(pass.target_count, pass.target_formats, dsv_format,
+ use_depth_stencil, bound.depth_stencil, bound.has_rasterizer,
+ bound.rasterizer, recipe.indexed_rect);
+ if (key != recipe.state_key) {
+ ++mismatched;
+ continue;
+ }
+ if (bound.pipelines.count(key)) continue;
+ D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{};
+ if (!prepare_translated_pso_desc(tr, recipe.indexed_rect, desc)) {
+ ++failed;
+ continue;
+ }
+ x2w_startup::apply_pso_recipe(recipe, desc);
+ ID3D12PipelineState* pipeline = nullptr;
+ X2W_ZONE("desktop pipeline creation from recipe");
+ const HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline));
+ check_device("translated CreateGraphicsPipelineState from recipe", 0);
+ if (FAILED(hr) || !pipeline) {
+ if (pipeline) pipeline->Release();
+ ++failed;
+ continue;
+ }
+ bound.pipelines[key] = pipeline;
+ ++precreated;
+ }
+ if (precreated || mismatched || failed) {
+ log("x2w-draw pso recipes %016llx: precreated %u, mismatched %u, failed %u", tr.key, precreated, mismatched, failed);
+ InterlockedAdd(&pso_recipes_precreated, static_cast(precreated));
+ InterlockedAdd(&pso_recipe_mismatches, static_cast(mismatched));
+ }
+ return precreated || mismatched || failed;
+}
+
ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const Pass& pass, bool indexed_rect)
{
const DXGI_FORMAT dsv_format = pass_dsv_format(bound, pass);
- u64 key = pass.target_count;
- for (UINT i = 0; i < pass.target_count; ++i) key = key * 131 + static_cast(pass.target_formats[i]);
- key = fnv_bytes(&dsv_format, sizeof(dsv_format), key);
// A state decoded from registers needs a depth view to act on; with none bound the pass keeps the desktop default.
const bool use_depth_stencil = bound.has_depth_stencil && (!bound.depth_from_registers || dsv_format != DXGI_FORMAT_UNKNOWN);
- if (use_depth_stencil) key = fnv_bytes(&bound.depth_stencil, sizeof(bound.depth_stencil), key);
- if (bound.has_rasterizer) key = fnv_bytes(&bound.rasterizer, sizeof(bound.rasterizer), key);
- key = fnv_bytes(&indexed_rect, sizeof(indexed_rect), key);
+ const u64 key = x2w_startup::pso_state_key(pass.target_count, pass.target_formats, dsv_format, use_depth_stencil,
+ bound.depth_stencil, bound.has_rasterizer, bound.rasterizer, indexed_rect);
const auto found = bound.pipelines.find(key);
if (found != bound.pipelines.end()) return found->second;
- D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{};
- desc.pRootSignature = tr.root;
- desc.VS = {tr.vs->GetBufferPointer(), tr.vs->GetBufferSize()};
- desc.PS = {tr.ps->GetBufferPointer(), tr.ps->GetBufferSize()};
- if (indexed_rect) {
- if (!tr.indexed_rect_geometry_attempted) {
- tr.indexed_rect_geometry_attempted = true;
- x2w_startup::ComPtr errors;
- const HRESULT hr = x2w_startup::compile_indexed_rect_geometry(tr.vs, tr.ps, &tr.indexed_rect_geometry, &errors);
- if (FAILED(hr))
- log("x2w-draw %016llx: indexed rectangle geometry unavailable (0x%08lx) %s", tr.key,
- static_cast(hr), errors ? static_cast(errors->GetBufferPointer()) : "");
- }
- if (!tr.indexed_rect_geometry) return nullptr;
- desc.GS = {tr.indexed_rect_geometry->GetBufferPointer(), tr.indexed_rect_geometry->GetBufferSize()};
- }
- // Blend state as found in the pipeline's state block, else opaque. Depth-stencil state and
- // DSVFormat come from the stream PSO (or bound DSV), else disabled. Raster state comes from
- // the stream RASTERIZER / RASTERIZER1 subobject, else solid fill, no culling, depth clip on.
- for (auto& target : desc.BlendState.RenderTarget)
- target = {FALSE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, D3D12_BLEND_ZERO,
- D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL};
- if (bound.has_blend) desc.BlendState = bound.blend;
- // Channels the translated exports leave unwritten stay out of the write mask (#1674).
- if (!x2w_startup::apply_export_write_masks(desc.BlendState, tr.write_masks, pass.target_count)) {
+ D3D12_BLEND_DESC blend{};
+ if (!effective_blend_state(bound, tr, pass.target_count, blend)) {
log("x2w-draw export write masks incompatible with shared logic op for %016llx", tr.key);
bound.pipelines[key] = nullptr;
return nullptr;
}
+ const u64 targets_key = x2w_startup::pso_targets_key(pass.target_count, pass.target_formats, dsv_format);
+ if (!tr.pso_recipes.empty() && bound.pso_recipe_targets_tried.insert(targets_key).second) {
+ const bool attempted = replay_pso_recipes(bound, tr, pass, dsv_format, use_depth_stencil, blend);
+ const auto replayed = bound.pipelines.find(key);
+ if (replayed != bound.pipelines.end()) return replayed->second;
+ if (attempted) InterlockedIncrement(&pso_recipe_fallbacks);
+ }
+ D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{};
+ if (!prepare_translated_pso_desc(tr, indexed_rect, desc)) return nullptr;
+ // Blend state as found in the pipeline's state block, else opaque. Depth-stencil state and
+ // DSVFormat come from the stream PSO (or bound DSV), else disabled. Raster state comes from
+ // the stream RASTERIZER / RASTERIZER1 subobject, else solid fill, no culling, depth clip on.
+ desc.BlendState = blend;
if (use_depth_stencil) desc.DepthStencilState = bound.depth_stencil;
desc.SampleMask = ~0u;
- if (bound.has_rasterizer) {
- desc.RasterizerState = bound.rasterizer;
- } else {
- desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
- desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
- desc.RasterizerState.DepthClipEnable = TRUE;
- }
+ desc.RasterizerState = bound.has_rasterizer ? bound.rasterizer : x2w_startup::default_pso_rasterizer();
desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
desc.NumRenderTargets = pass.target_count;
for (UINT i = 0; i < pass.target_count; ++i) desc.RTVFormats[i] = pass.target_formats[i];
@@ -1006,6 +1188,17 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P
static_cast(dsv_format), desc.DepthStencilState.DepthEnable ? 1 : 0);
check_device("translated CreateGraphicsPipelineState", 0);
bound.pipelines[key] = pipeline;
+ if (pipeline) {
+ wchar_t path[MAX_PATH];
+ if (pso_recipe_path(path, tr.key)) {
+ const x2w_startup::PsoRecipe recipe = x2w_startup::make_pso_recipe(
+ tr.key, key, indexed_rect, use_depth_stencil, bound.has_rasterizer, desc);
+ if (!append_pso_recipe(path, recipe)) {
+ static LONG logged;
+ if (first_calls(logged, 16)) log("x2w-draw pso recipe for %016llx was not written (directory, size limit or I/O)", tr.key);
+ }
+ }
+ }
return pipeline;
}
diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp
index 84efa5756f..7bde8cf882 100644
--- a/src/startup_stubs/d3d12_xs_device.cpp
+++ b/src/startup_stubs/d3d12_xs_device.cpp
@@ -26,6 +26,7 @@
#include "startup_stubs/pixel_history.h"
#include "startup_stubs/translated_sampler_bindings.h"
#include "startup_stubs/export_write_mask.h"
+#include "startup_stubs/pso_recipe.h"
#include "startup_stubs/depth_state_apply.h"
#include "startup_stubs/d16_image_format.h"
#include "startup_stubs/formatted_buffer.h"
@@ -7341,6 +7342,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa
heap_root_refusals[static_cast(x2w_startup::RealRootDecision::both_heaps_missing)],
heap_root_refusals[static_cast(x2w_startup::RealRootDecision::state_not_restorable)], indirect_first_lookups,
compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words);
+ if (render_mode() && frame % 300 == 0 && (pso_recipes_loaded || pso_recipes_precreated || pso_recipe_mismatches || pso_recipe_fallbacks))
+ log("x2w-draw pso recipes totals: loaded %ld, precreated %ld, mismatches %ld, fallbacks %ld", pso_recipes_loaded,
+ pso_recipes_precreated, pso_recipe_mismatches, pso_recipe_fallbacks);
if (render_mode() && frame % 300 == 0) {
log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld, not modelled %ld, builder gate refused %ld",
compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled,
diff --git a/src/startup_stubs/pso_recipe.h b/src/startup_stubs/pso_recipe.h
new file mode 100644
index 0000000000..64028e2352
--- /dev/null
+++ b/src/startup_stubs/pso_recipe.h
@@ -0,0 +1,653 @@
+// Experimental: a versioned on-disk recipe for a translated desktop graphics pipeline.
+//
+// The shader cache stores the vertex and pixel bytecode, the root signature and the sampler
+// descriptions. It does not store the draw state that produced a desktop pipeline state object
+// (PSO). With X2W_PSO_RECIPE_DIR set, the runtime appends that state here after a successful
+// CreateGraphicsPipelineState and replays it on a later run before creating another PSO. This is
+// state reconstruction, not a D3D12 pipeline library: the driver may still compile or cache the
+// PSO internally.
+#pragma once
+
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include
+
+// windows.h may already have been included by the translation unit, so NOMINMAX above is too late
+// to prevent the min/max function-like macros. std::numeric_limits::max is used below.
+#ifdef min
+#undef min
+#endif
+#ifdef max
+#undef max
+#endif
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace x2w_startup {
+
+constexpr unsigned pso_recipe_version = 1;
+constexpr std::size_t pso_recipe_file_limit = 64u * 1024u;
+constexpr std::size_t pso_recipe_record_limit = 64;
+constexpr unsigned pso_recipe_target_limit = 8;
+
+struct PsoRecipe {
+ std::uint64_t translation_key = 0; // the shader-cache key this record belongs to
+ std::uint64_t state_key = 0; // pipeline_for's target/depth/raster/indexed key
+ UINT target_count = 0;
+ DXGI_FORMAT target_formats[pso_recipe_target_limit]{};
+ DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN;
+ bool indexed_rect = false;
+ bool use_depth_stencil = false; // whether DepthStencilState participated in the PSO
+ bool has_rasterizer = false; // whether a decoded rasterizer state participated in the key
+ D3D12_BLEND_DESC blend{}; // effective state, after apply_export_write_masks
+ D3D12_DEPTH_STENCIL_DESC depth_stencil{};
+ D3D12_RASTERIZER_DESC rasterizer{};
+ UINT sample_mask = ~0u;
+ UINT sample_count = 1;
+ D3D12_PRIMITIVE_TOPOLOGY_TYPE topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
+};
+
+struct PsoRecipeParseResult {
+ std::vector recipes;
+ unsigned rejected = 0;
+ std::string error;
+};
+
+inline std::uint64_t pso_recipe_hash(const void* data, std::size_t bytes,
+ std::uint64_t hash = 1469598103934665603ull)
+{
+ const auto* p = static_cast(data);
+ for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ p[i]) * 1099511628211ull;
+ return hash;
+}
+
+inline std::uint64_t pso_targets_key(UINT target_count, const DXGI_FORMAT* target_formats, DXGI_FORMAT dsv_format)
+{
+ std::uint64_t key = target_count;
+ for (UINT i = 0; i < target_count; ++i) key = key * 131 + static_cast(target_formats[i]);
+ return pso_recipe_hash(&dsv_format, sizeof(dsv_format), key);
+}
+
+// The same key pipeline_for uses. Keeping it here lets a parsed record prove that its own fields
+// reproduce the state key it names.
+inline std::uint64_t pso_state_key(UINT target_count, const DXGI_FORMAT* target_formats, DXGI_FORMAT dsv_format,
+ bool use_depth_stencil, const D3D12_DEPTH_STENCIL_DESC& depth_stencil,
+ bool has_rasterizer, const D3D12_RASTERIZER_DESC& rasterizer, bool indexed_rect)
+{
+ std::uint64_t key = pso_targets_key(target_count, target_formats, dsv_format);
+ if (use_depth_stencil) key = pso_recipe_hash(&depth_stencil, sizeof(depth_stencil), key);
+ if (has_rasterizer) key = pso_recipe_hash(&rasterizer, sizeof(rasterizer), key);
+ key = pso_recipe_hash(&indexed_rect, sizeof(indexed_rect), key);
+ return key;
+}
+
+inline std::uint64_t pso_recipe_state_key(const PsoRecipe& recipe)
+{
+ return pso_state_key(recipe.target_count, recipe.target_formats, recipe.dsv_format, recipe.use_depth_stencil,
+ recipe.depth_stencil, recipe.has_rasterizer, recipe.rasterizer, recipe.indexed_rect);
+}
+
+inline D3D12_RENDER_TARGET_BLEND_DESC default_render_target_blend()
+{
+ return {FALSE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE,
+ D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL};
+}
+
+inline D3D12_BLEND_DESC default_pso_blend()
+{
+ D3D12_BLEND_DESC blend{};
+ for (auto& target : blend.RenderTarget) target = default_render_target_blend();
+ return blend;
+}
+
+inline D3D12_RASTERIZER_DESC default_pso_rasterizer()
+{
+ D3D12_RASTERIZER_DESC rasterizer{};
+ rasterizer.FillMode = D3D12_FILL_MODE_SOLID;
+ rasterizer.CullMode = D3D12_CULL_MODE_NONE;
+ rasterizer.DepthClipEnable = TRUE;
+ return rasterizer;
+}
+
+// A valid depth-stencil state for a recipe that does not use one. The serializer writes every
+// field, and the parser rejects an invalid stencil op; the zero-filled D3D12 struct is not a
+// valid serialized state even when the PSO ignores it.
+inline D3D12_DEPTH_STENCIL_DESC default_pso_depth()
+{
+ D3D12_DEPTH_STENCIL_DESC depth{};
+ depth.DepthEnable = FALSE;
+ depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;
+ depth.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
+ depth.StencilEnable = FALSE;
+ depth.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK;
+ depth.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK;
+ depth.FrontFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP,
+ D3D12_COMPARISON_FUNC_ALWAYS};
+ depth.BackFace = depth.FrontFace;
+ return depth;
+}
+
+inline bool same_float_bits(float a, float b)
+{
+ std::uint32_t left = 0, right = 0;
+ std::memcpy(&left, &a, sizeof(left));
+ std::memcpy(&right, &b, sizeof(right));
+ return left == right;
+}
+
+inline bool same_render_target_blend(const D3D12_RENDER_TARGET_BLEND_DESC& a, const D3D12_RENDER_TARGET_BLEND_DESC& b)
+{
+ return a.BlendEnable == b.BlendEnable && a.LogicOpEnable == b.LogicOpEnable && a.SrcBlend == b.SrcBlend &&
+ a.DestBlend == b.DestBlend && a.BlendOp == b.BlendOp && a.SrcBlendAlpha == b.SrcBlendAlpha &&
+ a.DestBlendAlpha == b.DestBlendAlpha && a.BlendOpAlpha == b.BlendOpAlpha && a.LogicOp == b.LogicOp &&
+ a.RenderTargetWriteMask == b.RenderTargetWriteMask;
+}
+
+inline bool same_pso_blend(const D3D12_BLEND_DESC& a, const D3D12_BLEND_DESC& b)
+{
+ if (a.AlphaToCoverageEnable != b.AlphaToCoverageEnable || a.IndependentBlendEnable != b.IndependentBlendEnable)
+ return false;
+ for (unsigned i = 0; i < 8; ++i)
+ if (!same_render_target_blend(a.RenderTarget[i], b.RenderTarget[i])) return false;
+ return true;
+}
+
+inline bool same_pso_depth(const D3D12_DEPTH_STENCIL_DESC& a, const D3D12_DEPTH_STENCIL_DESC& b)
+{
+ return a.DepthEnable == b.DepthEnable && a.DepthWriteMask == b.DepthWriteMask && a.DepthFunc == b.DepthFunc &&
+ a.StencilEnable == b.StencilEnable && a.StencilReadMask == b.StencilReadMask &&
+ a.StencilWriteMask == b.StencilWriteMask && a.FrontFace.StencilFailOp == b.FrontFace.StencilFailOp &&
+ a.FrontFace.StencilDepthFailOp == b.FrontFace.StencilDepthFailOp &&
+ a.FrontFace.StencilPassOp == b.FrontFace.StencilPassOp && a.FrontFace.StencilFunc == b.FrontFace.StencilFunc &&
+ a.BackFace.StencilFailOp == b.BackFace.StencilFailOp &&
+ a.BackFace.StencilDepthFailOp == b.BackFace.StencilDepthFailOp &&
+ a.BackFace.StencilPassOp == b.BackFace.StencilPassOp && a.BackFace.StencilFunc == b.BackFace.StencilFunc;
+}
+
+inline bool same_pso_rasterizer(const D3D12_RASTERIZER_DESC& a, const D3D12_RASTERIZER_DESC& b)
+{
+ return a.FillMode == b.FillMode && a.CullMode == b.CullMode && a.FrontCounterClockwise == b.FrontCounterClockwise &&
+ a.DepthBias == b.DepthBias && same_float_bits(a.DepthBiasClamp, b.DepthBiasClamp) &&
+ same_float_bits(a.SlopeScaledDepthBias, b.SlopeScaledDepthBias) && a.DepthClipEnable == b.DepthClipEnable &&
+ a.MultisampleEnable == b.MultisampleEnable && a.AntialiasedLineEnable == b.AntialiasedLineEnable &&
+ a.ForcedSampleCount == b.ForcedSampleCount && a.ConservativeRaster == b.ConservativeRaster;
+}
+
+inline bool pso_recipe_targets_match(const PsoRecipe& recipe, UINT target_count, const DXGI_FORMAT* target_formats,
+ DXGI_FORMAT dsv_format)
+{
+ if (target_count != recipe.target_count || dsv_format != recipe.dsv_format) return false;
+ for (UINT i = 0; i < target_count; ++i)
+ if (target_formats[i] != recipe.target_formats[i]) return false;
+ return true;
+}
+
+inline PsoRecipe make_pso_recipe(std::uint64_t translation_key, std::uint64_t state_key, bool indexed_rect,
+ bool use_depth_stencil, bool has_rasterizer,
+ const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc)
+{
+ PsoRecipe recipe;
+ recipe.translation_key = translation_key;
+ recipe.state_key = state_key;
+ recipe.target_count = desc.NumRenderTargets;
+ for (UINT i = 0; i < pso_recipe_target_limit; ++i) recipe.target_formats[i] = desc.RTVFormats[i];
+ recipe.dsv_format = desc.DSVFormat;
+ recipe.indexed_rect = indexed_rect;
+ recipe.use_depth_stencil = use_depth_stencil;
+ recipe.has_rasterizer = has_rasterizer;
+ recipe.blend = desc.BlendState;
+ recipe.depth_stencil = use_depth_stencil ? desc.DepthStencilState : default_pso_depth();
+ recipe.rasterizer = has_rasterizer ? desc.RasterizerState : default_pso_rasterizer();
+ recipe.sample_mask = desc.SampleMask;
+ recipe.sample_count = desc.SampleDesc.Count;
+ recipe.topology = desc.PrimitiveTopologyType;
+ return recipe;
+}
+
+inline void apply_pso_recipe(const PsoRecipe& recipe, D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc)
+{
+ desc.BlendState = recipe.blend;
+ desc.DepthStencilState = recipe.use_depth_stencil ? recipe.depth_stencil : D3D12_DEPTH_STENCIL_DESC{};
+ desc.RasterizerState = recipe.rasterizer;
+ desc.SampleMask = recipe.sample_mask;
+ desc.PrimitiveTopologyType = recipe.topology;
+ desc.NumRenderTargets = recipe.target_count;
+ for (UINT i = 0; i < pso_recipe_target_limit; ++i)
+ desc.RTVFormats[i] = i < recipe.target_count ? recipe.target_formats[i] : DXGI_FORMAT_UNKNOWN;
+ desc.DSVFormat = recipe.dsv_format;
+ desc.SampleDesc.Count = recipe.sample_count;
+ desc.SampleDesc.Quality = 0;
+}
+
+inline void append_hex(std::string& out, std::uint64_t value)
+{
+ char text[17];
+ std::snprintf(text, sizeof(text), "%016llx", static_cast(value));
+ out += text;
+}
+
+inline std::string serialize_pso_recipe(const PsoRecipe& recipe)
+{
+ std::string out;
+ out.reserve(1536);
+ out += "x2w-pso-recipe 1\nstate 0x";
+ append_hex(out, recipe.state_key);
+ out += "\ntranslation 0x";
+ append_hex(out, recipe.translation_key);
+ out += "\ntargets ";
+ out += std::to_string(recipe.target_count);
+ for (DXGI_FORMAT format : recipe.target_formats) {
+ out += ' ';
+ out += std::to_string(static_cast(format));
+ }
+ out += "\ndsv ";
+ out += std::to_string(static_cast(recipe.dsv_format));
+ out += "\nindexed ";
+ out += recipe.indexed_rect ? '1' : '0';
+ out += "\nblend ";
+ out += recipe.blend.AlphaToCoverageEnable ? '1' : '0';
+ out += ' ';
+ out += recipe.blend.IndependentBlendEnable ? '1' : '0';
+ out += '\n';
+ for (unsigned i = 0; i < 8; ++i) {
+ const auto& t = recipe.blend.RenderTarget[i];
+ out += "blend";
+ out += std::to_string(i);
+ out += ' ';
+ out += t.BlendEnable ? '1' : '0';
+ out += ' ';
+ out += t.LogicOpEnable ? '1' : '0';
+ const unsigned values[] = {static_cast(t.SrcBlend), static_cast(t.DestBlend),
+ static_cast(t.BlendOp), static_cast(t.SrcBlendAlpha),
+ static_cast(t.DestBlendAlpha), static_cast(t.BlendOpAlpha),
+ static_cast(t.LogicOp), static_cast(t.RenderTargetWriteMask)};
+ for (unsigned value : values) {
+ out += ' ';
+ out += std::to_string(value);
+ }
+ out += '\n';
+ }
+ out += "depth ";
+ out += recipe.use_depth_stencil ? '1' : '0';
+ const unsigned depth_values[] = {
+ recipe.depth_stencil.DepthEnable ? 1u : 0u, static_cast(recipe.depth_stencil.DepthWriteMask),
+ static_cast(recipe.depth_stencil.DepthFunc), recipe.depth_stencil.StencilEnable ? 1u : 0u,
+ recipe.depth_stencil.StencilReadMask, recipe.depth_stencil.StencilWriteMask,
+ static_cast(recipe.depth_stencil.FrontFace.StencilFailOp),
+ static_cast(recipe.depth_stencil.FrontFace.StencilDepthFailOp),
+ static_cast(recipe.depth_stencil.FrontFace.StencilPassOp),
+ static_cast(recipe.depth_stencil.FrontFace.StencilFunc),
+ static_cast(recipe.depth_stencil.BackFace.StencilFailOp),
+ static_cast(recipe.depth_stencil.BackFace.StencilDepthFailOp),
+ static_cast(recipe.depth_stencil.BackFace.StencilPassOp),
+ static_cast(recipe.depth_stencil.BackFace.StencilFunc)};
+ for (unsigned value : depth_values) {
+ out += ' ';
+ out += std::to_string(value);
+ }
+ out += "\nraster ";
+ out += recipe.has_rasterizer ? '1' : '0';
+ std::uint32_t clamp_bits = 0, slope_bits = 0;
+ std::memcpy(&clamp_bits, &recipe.rasterizer.DepthBiasClamp, sizeof(clamp_bits));
+ std::memcpy(&slope_bits, &recipe.rasterizer.SlopeScaledDepthBias, sizeof(slope_bits));
+ const unsigned raster_values[] = {static_cast(recipe.rasterizer.FillMode),
+ static_cast(recipe.rasterizer.CullMode),
+ recipe.rasterizer.FrontCounterClockwise ? 1u : 0u};
+ for (unsigned value : raster_values) {
+ out += ' ';
+ out += std::to_string(value);
+ }
+ out += ' ';
+ out += std::to_string(recipe.rasterizer.DepthBias);
+ char hex[32];
+ std::snprintf(hex, sizeof(hex), " 0x%08x 0x%08x", clamp_bits, slope_bits);
+ out += hex;
+ const unsigned raster_tail[] = {recipe.rasterizer.DepthClipEnable ? 1u : 0u,
+ recipe.rasterizer.MultisampleEnable ? 1u : 0u,
+ recipe.rasterizer.AntialiasedLineEnable ? 1u : 0u,
+ recipe.rasterizer.ForcedSampleCount,
+ static_cast(recipe.rasterizer.ConservativeRaster)};
+ for (unsigned value : raster_tail) {
+ out += ' ';
+ out += std::to_string(value);
+ }
+ out += "\nsample ";
+ out += std::to_string(recipe.sample_count);
+ out += ' ';
+ out += std::to_string(recipe.sample_mask);
+ out += "\ntopology ";
+ out += std::to_string(static_cast(recipe.topology));
+ out += "\nend\n";
+ return out;
+}
+
+inline bool parse_unsigned(std::string_view token, std::uint64_t& value, int base = 10)
+{
+ if (token.empty()) return false;
+ if (base == 16 && token.size() >= 2 && token[0] == '0' && (token[1] == 'x' || token[1] == 'X')) token.remove_prefix(2);
+ if (token.empty() || token[0] == '+' || token[0] == '-') return false;
+ std::uint64_t result = 0;
+ for (char c : token) {
+ unsigned digit = 0;
+ if (c >= '0' && c <= '9') digit = static_cast(c - '0');
+ else if (base == 16 && c >= 'a' && c <= 'f') digit = static_cast(c - 'a' + 10);
+ else if (base == 16 && c >= 'A' && c <= 'F') digit = static_cast(c - 'A' + 10);
+ else return false;
+ if (digit >= static_cast(base)) return false;
+ if (result > (std::numeric_limits::max() - digit) / static_cast(base)) return false;
+ result = result * static_cast(base) + digit;
+ }
+ value = result;
+ return true;
+}
+
+inline bool parse_integer(std::string_view token, std::int64_t& value)
+{
+ if (token.empty()) return false;
+ const bool negative = token[0] == '-';
+ if (negative) token.remove_prefix(1);
+ std::uint64_t magnitude = 0;
+ if (!parse_unsigned(token, magnitude)) return false;
+ if (negative) {
+ if (magnitude > static_cast(std::numeric_limits::max()) + 1) return false;
+ value = magnitude == static_cast(std::numeric_limits::max()) + 1
+ ? std::numeric_limits::min()
+ : -static_cast(magnitude);
+ } else {
+ if (magnitude > static_cast(std::numeric_limits::max())) return false;
+ value = static_cast(magnitude);
+ }
+ return true;
+}
+
+inline std::vector pso_recipe_tokens(std::string_view line)
+{
+ std::vector tokens;
+ std::size_t at = 0;
+ while (at < line.size()) {
+ while (at < line.size() && line[at] == ' ') ++at;
+ const std::size_t begin = at;
+ while (at < line.size() && line[at] != ' ') ++at;
+ if (begin != at) tokens.push_back(line.substr(begin, at - begin));
+ }
+ return tokens;
+}
+
+inline bool read_bool(const std::vector& tokens, std::size_t at, bool& out)
+{
+ std::uint64_t value = 0;
+ if (at >= tokens.size() || !parse_unsigned(tokens[at], value) || value > 1) return false;
+ out = value != 0;
+ return true;
+}
+
+inline bool read_bool(const std::vector& tokens, std::size_t at, BOOL& out)
+{
+ bool value = false;
+ if (!read_bool(tokens, at, value)) return false;
+ out = value ? TRUE : FALSE;
+ return true;
+}
+
+inline bool read_uint(const std::vector& tokens, std::size_t at, unsigned& out)
+{
+ std::uint64_t value = 0;
+ if (at >= tokens.size() || !parse_unsigned(tokens[at], value) || value > std::numeric_limits::max()) return false;
+ out = static_cast(value);
+ return true;
+}
+
+inline bool read_uint_range(const std::vector& tokens, std::size_t at, unsigned low, unsigned high,
+ unsigned& out)
+{
+ return read_uint(tokens, at, out) && out >= low && out <= high;
+}
+
+inline bool read_hex32(const std::vector& tokens, std::size_t at, std::uint32_t& out)
+{
+ std::uint64_t value = 0;
+ if (at >= tokens.size() || !parse_unsigned(tokens[at], value, 16) || value > 0xffffffffull) return false;
+ out = static_cast(value);
+ return true;
+}
+
+inline bool parse_pso_recipe_lines(const std::vector& lines, std::size_t at, PsoRecipe& recipe,
+ std::string& why)
+{
+ if (at + 20 > lines.size()) {
+ why = "truncated record";
+ return false;
+ }
+ if (lines[at] != "x2w-pso-recipe 1") {
+ why = "unknown recipe version";
+ return false;
+ }
+ recipe = {};
+ auto line = [&](std::size_t index) { return pso_recipe_tokens(lines[at + index]); };
+
+ auto tokens = line(1);
+ if (tokens.size() != 2 || tokens[0] != "state" || !parse_unsigned(tokens[1], recipe.state_key, 16)) {
+ why = "malformed state line";
+ return false;
+ }
+ tokens = line(2);
+ if (tokens.size() != 2 || tokens[0] != "translation" || !parse_unsigned(tokens[1], recipe.translation_key, 16)) {
+ why = "malformed translation line";
+ return false;
+ }
+ tokens = line(3);
+ if (tokens.size() != 10 || tokens[0] != "targets" || !read_uint(tokens, 1, recipe.target_count) ||
+ recipe.target_count > pso_recipe_target_limit) {
+ why = "malformed targets line";
+ return false;
+ }
+ for (unsigned i = 0; i < pso_recipe_target_limit; ++i) {
+ unsigned format = 0;
+ if (!read_uint(tokens, 2 + i, format) || format > 0xffff) {
+ why = "malformed target format";
+ return false;
+ }
+ recipe.target_formats[i] = static_cast(format);
+ }
+ tokens = line(4);
+ unsigned dsv = 0;
+ if (tokens.size() != 2 || tokens[0] != "dsv" || !read_uint(tokens, 1, dsv) || dsv > 0xffff) {
+ why = "malformed dsv line";
+ return false;
+ }
+ recipe.dsv_format = static_cast(dsv);
+ tokens = line(5);
+ if (tokens.size() != 2 || tokens[0] != "indexed" || !read_bool(tokens, 1, recipe.indexed_rect)) {
+ why = "malformed indexed line";
+ return false;
+ }
+ tokens = line(6);
+ if (tokens.size() != 3 || tokens[0] != "blend" || !read_bool(tokens, 1, recipe.blend.AlphaToCoverageEnable) ||
+ !read_bool(tokens, 2, recipe.blend.IndependentBlendEnable)) {
+ why = "malformed blend line";
+ return false;
+ }
+ for (unsigned i = 0; i < 8; ++i) {
+ tokens = line(7 + i);
+ const std::string expected = "blend" + std::to_string(i);
+ auto& target = recipe.blend.RenderTarget[i];
+ unsigned src = 0, dest = 0, op = 0, src_alpha = 0, dest_alpha = 0, op_alpha = 0, logic = 0, write_mask = 0;
+ if (tokens.size() != 11 || tokens[0] != expected || !read_bool(tokens, 1, target.BlendEnable) ||
+ !read_bool(tokens, 2, target.LogicOpEnable) || !read_uint_range(tokens, 3, 1, 19, src) ||
+ !read_uint_range(tokens, 4, 1, 19, dest) || !read_uint_range(tokens, 5, 1, 5, op) ||
+ !read_uint_range(tokens, 6, 1, 19, src_alpha) || !read_uint_range(tokens, 7, 1, 19, dest_alpha) ||
+ !read_uint_range(tokens, 8, 1, 5, op_alpha) || !read_uint_range(tokens, 9, 0, 15, logic) ||
+ !read_uint_range(tokens, 10, 0, 15, write_mask)) {
+ why = "malformed " + expected + " line";
+ return false;
+ }
+ target.SrcBlend = static_cast(src);
+ target.DestBlend = static_cast(dest);
+ target.BlendOp = static_cast(op);
+ target.SrcBlendAlpha = static_cast(src_alpha);
+ target.DestBlendAlpha = static_cast(dest_alpha);
+ target.BlendOpAlpha = static_cast(op_alpha);
+ target.LogicOp = static_cast(logic);
+ target.RenderTargetWriteMask = static_cast(write_mask);
+ }
+ tokens = line(15);
+ unsigned depth_enable = 0, write_mask = 0, depth_func = 0, stencil_enable = 0, read_mask = 0, stencil_write_mask = 0;
+ unsigned front_fail = 0, front_depth_fail = 0, front_pass = 0, front_func = 0;
+ unsigned back_fail = 0, back_depth_fail = 0, back_pass = 0, back_func = 0;
+ if (tokens.size() != 16 || tokens[0] != "depth" || !read_bool(tokens, 1, recipe.use_depth_stencil) ||
+ !read_bool(tokens, 2, recipe.depth_stencil.DepthEnable) ||
+ !read_uint_range(tokens, 3, 0, 1, write_mask) || !read_uint_range(tokens, 4, 1, 8, depth_func) ||
+ !read_bool(tokens, 5, recipe.depth_stencil.StencilEnable) || !read_uint_range(tokens, 6, 0, 255, read_mask) ||
+ !read_uint_range(tokens, 7, 0, 255, stencil_write_mask) || !read_uint_range(tokens, 8, 1, 8, front_fail) ||
+ !read_uint_range(tokens, 9, 1, 8, front_depth_fail) || !read_uint_range(tokens, 10, 1, 8, front_pass) ||
+ !read_uint_range(tokens, 11, 1, 8, front_func) || !read_uint_range(tokens, 12, 1, 8, back_fail) ||
+ !read_uint_range(tokens, 13, 1, 8, back_depth_fail) || !read_uint_range(tokens, 14, 1, 8, back_pass) ||
+ !read_uint_range(tokens, 15, 1, 8, back_func)) {
+ why = "malformed depth line";
+ return false;
+ }
+ recipe.depth_stencil.DepthWriteMask = static_cast(write_mask);
+ recipe.depth_stencil.DepthFunc = static_cast(depth_func);
+ recipe.depth_stencil.StencilReadMask = static_cast(read_mask);
+ recipe.depth_stencil.StencilWriteMask = static_cast(stencil_write_mask);
+ recipe.depth_stencil.FrontFace.StencilFailOp = static_cast(front_fail);
+ recipe.depth_stencil.FrontFace.StencilDepthFailOp = static_cast(front_depth_fail);
+ recipe.depth_stencil.FrontFace.StencilPassOp = static_cast(front_pass);
+ recipe.depth_stencil.FrontFace.StencilFunc = static_cast(front_func);
+ recipe.depth_stencil.BackFace.StencilFailOp = static_cast(back_fail);
+ recipe.depth_stencil.BackFace.StencilDepthFailOp = static_cast(back_depth_fail);
+ recipe.depth_stencil.BackFace.StencilPassOp = static_cast(back_pass);
+ recipe.depth_stencil.BackFace.StencilFunc = static_cast(back_func);
+
+ tokens = line(16);
+ unsigned fill = 0, cull = 0, conservative = 0;
+ std::int64_t depth_bias = 0;
+ std::uint32_t clamp_bits = 0, slope_bits = 0;
+ if (tokens.size() != 13 || tokens[0] != "raster" || !read_bool(tokens, 1, recipe.has_rasterizer) ||
+ !read_uint_range(tokens, 2, 2, 3, fill) || !read_uint_range(tokens, 3, 1, 3, cull) ||
+ !read_bool(tokens, 4, recipe.rasterizer.FrontCounterClockwise) || !parse_integer(tokens[5], depth_bias) ||
+ depth_bias < std::numeric_limits::min() || depth_bias > std::numeric_limits::max() ||
+ !read_hex32(tokens, 6, clamp_bits) || !read_hex32(tokens, 7, slope_bits) ||
+ !read_bool(tokens, 8, recipe.rasterizer.DepthClipEnable) ||
+ !read_bool(tokens, 9, recipe.rasterizer.MultisampleEnable) ||
+ !read_bool(tokens, 10, recipe.rasterizer.AntialiasedLineEnable) ||
+ !read_uint(tokens, 11, recipe.rasterizer.ForcedSampleCount) || !read_uint_range(tokens, 12, 0, 2, conservative)) {
+ why = "malformed raster line";
+ return false;
+ }
+ recipe.rasterizer.FillMode = static_cast(fill);
+ recipe.rasterizer.CullMode = static_cast(cull);
+ recipe.rasterizer.DepthBias = static_cast(depth_bias);
+ std::memcpy(&recipe.rasterizer.DepthBiasClamp, &clamp_bits, sizeof(clamp_bits));
+ std::memcpy(&recipe.rasterizer.SlopeScaledDepthBias, &slope_bits, sizeof(slope_bits));
+ recipe.rasterizer.ConservativeRaster = static_cast(conservative);
+
+ tokens = line(17);
+ if (tokens.size() != 3 || tokens[0] != "sample" || !read_uint_range(tokens, 1, 1, 16, recipe.sample_count) ||
+ !read_uint(tokens, 2, recipe.sample_mask)) {
+ why = "malformed sample line";
+ return false;
+ }
+ unsigned topology = 0;
+ tokens = line(18);
+ if (tokens.size() != 2 || tokens[0] != "topology" || !read_uint_range(tokens, 1, 0, 4, topology)) {
+ why = "malformed topology line";
+ return false;
+ }
+ recipe.topology = static_cast(topology);
+ if (line(19).size() != 1 || line(19)[0] != "end") {
+ why = "missing end line";
+ return false;
+ }
+
+ // The serializer records a valid default for an unused state so that every field it writes is
+ // a legal enum. The state key ignores both blocks when their flags are clear; normalize them
+ // here so a replay compares the same zero/default values the creation path uses.
+ if (!recipe.use_depth_stencil) recipe.depth_stencil = {};
+ if (!recipe.has_rasterizer) recipe.rasterizer = default_pso_rasterizer();
+ if (pso_recipe_state_key(recipe) != recipe.state_key) {
+ why = "state key does not match the recorded state";
+ return false;
+ }
+ return true;
+}
+
+inline PsoRecipeParseResult parse_pso_recipe_file(std::string_view text)
+{
+ PsoRecipeParseResult result;
+ if (text.size() > pso_recipe_file_limit) {
+ result.rejected = 1;
+ result.error = "recipe file exceeds the size limit";
+ return result;
+ }
+ std::vector lines;
+ std::size_t at = 0;
+ while (at <= text.size()) {
+ const std::size_t end = text.find('\n', at);
+ std::string_view line = text.substr(at, end == std::string_view::npos ? std::string_view::npos : end - at);
+ if (!line.empty() && line.back() == '\r') line.remove_suffix(1);
+ if (!line.empty()) lines.push_back(line);
+ if (end == std::string_view::npos) break;
+ at = end + 1;
+ }
+ std::size_t i = 0;
+ while (i < lines.size()) {
+ if (lines[i].substr(0, 15) != "x2w-pso-recipe ") {
+ result.rejected++;
+ if (result.error.empty()) result.error = "unexpected line outside a recipe";
+ ++i;
+ continue;
+ }
+ if (lines[i] != "x2w-pso-recipe 1") {
+ result.rejected++;
+ if (result.error.empty()) result.error = "unknown recipe version";
+ i += (i + 20 <= lines.size()) ? 20 : 1;
+ continue;
+ }
+ if (result.recipes.size() >= pso_recipe_record_limit) {
+ result.rejected++;
+ if (result.error.empty()) result.error = "recipe record limit reached";
+ i += (i + 20 <= lines.size()) ? 20 : 1;
+ continue;
+ }
+ PsoRecipe recipe;
+ std::string why;
+ if (!parse_pso_recipe_lines(lines, i, recipe, why)) {
+ result.rejected++;
+ if (result.error.empty()) result.error = why;
+ i += (i + 20 <= lines.size()) ? 20 : 1;
+ continue;
+ }
+ result.recipes.push_back(recipe);
+ i += 20;
+ }
+ return result;
+}
+
+// The parser accepts at most pso_recipe_record_limit complete records. The writer must stop at
+// the same boundary instead of appending a record the next process will reject. A file with any
+// rejected line is left alone: one more append cannot make it parse cleanly.
+inline bool pso_recipe_append_allowed(std::string_view existing, std::string_view record)
+{
+ if (record.empty() || record.size() > pso_recipe_file_limit) return false;
+ // A parseable last record may still lack its final LF. Appending then joins its `end` to the
+ // next header on one line, so the next read loses both records. Refuse without writing.
+ if (!existing.empty() && existing.back() != '\n') return false;
+ if (existing.size() > pso_recipe_file_limit || record.size() > pso_recipe_file_limit - existing.size())
+ return false;
+ const PsoRecipeParseResult parsed = parse_pso_recipe_file(existing);
+ if (parsed.rejected != 0) return false;
+ return parsed.recipes.size() < pso_recipe_record_limit;
+}
+
+} // namespace x2w_startup
diff --git a/tests/cmake/startup_pso_recipe.cmake b/tests/cmake/startup_pso_recipe.cmake
new file mode 100644
index 0000000000..67ebb03ff5
--- /dev/null
+++ b/tests/cmake/startup_pso_recipe.cmake
@@ -0,0 +1,6 @@
+# Device-free checks for the opt-in translated-PSO recipe format
+# (src/startup_stubs/pso_recipe.h).
+add_executable(startup_pso_recipe_check tests/startup_pso_recipe_check.cpp)
+target_include_directories(startup_pso_recipe_check PRIVATE src)
+target_compile_features(startup_pso_recipe_check PRIVATE cxx_std_17)
+add_test(NAME startup_pso_recipe COMMAND startup_pso_recipe_check)
diff --git a/tests/startup_pso_recipe_check.cpp b/tests/startup_pso_recipe_check.cpp
new file mode 100644
index 0000000000..267c55b300
--- /dev/null
+++ b/tests/startup_pso_recipe_check.cpp
@@ -0,0 +1,173 @@
+// Device-free checks for the opt-in translated-PSO recipe format. The runtime reads the same
+// serializer/parser and reconstructs the desktop pipeline description from these fields.
+#include "startup_stubs/pso_recipe.h"
+
+#include
+#include
+#include
+
+namespace {
+int failures = 0;
+
+void expect(bool condition, const char* what)
+{
+ std::printf("%s: %s\n", what, condition ? "ok" : "MISMATCH");
+ failures += !condition;
+}
+
+x2w_startup::PsoRecipe sample_recipe()
+{
+ x2w_startup::PsoRecipe recipe;
+ recipe.translation_key = 0x1122334455667788ull;
+ recipe.target_count = 2;
+ recipe.target_formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
+ recipe.target_formats[1] = DXGI_FORMAT_R16G16B16A16_FLOAT;
+ recipe.dsv_format = DXGI_FORMAT_D32_FLOAT;
+ recipe.indexed_rect = true;
+ recipe.use_depth_stencil = true;
+ recipe.has_rasterizer = true;
+ recipe.blend = x2w_startup::default_pso_blend();
+ recipe.blend.IndependentBlendEnable = TRUE;
+ recipe.blend.RenderTarget[0].BlendEnable = TRUE;
+ recipe.blend.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
+ recipe.blend.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
+ recipe.blend.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
+ recipe.blend.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
+ recipe.blend.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
+ recipe.blend.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
+ recipe.blend.RenderTarget[0].RenderTargetWriteMask = 0x9;
+ recipe.blend.RenderTarget[1].RenderTargetWriteMask = 0x3;
+ recipe.depth_stencil.DepthEnable = TRUE;
+ recipe.depth_stencil.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
+ recipe.depth_stencil.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;
+ recipe.depth_stencil.StencilEnable = TRUE;
+ recipe.depth_stencil.StencilReadMask = 0x7f;
+ recipe.depth_stencil.StencilWriteMask = 0x0f;
+ recipe.depth_stencil.FrontFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_INCR, D3D12_STENCIL_OP_REPLACE,
+ D3D12_COMPARISON_FUNC_EQUAL};
+ recipe.depth_stencil.BackFace = {D3D12_STENCIL_OP_ZERO, D3D12_STENCIL_OP_DECR, D3D12_STENCIL_OP_KEEP,
+ D3D12_COMPARISON_FUNC_ALWAYS};
+ recipe.rasterizer = x2w_startup::default_pso_rasterizer();
+ recipe.rasterizer.CullMode = D3D12_CULL_MODE_BACK;
+ recipe.rasterizer.FrontCounterClockwise = TRUE;
+ recipe.rasterizer.DepthBias = -3;
+ recipe.rasterizer.DepthBiasClamp = 0.5f;
+ recipe.rasterizer.SlopeScaledDepthBias = -1.25f;
+ recipe.rasterizer.MultisampleEnable = TRUE;
+ recipe.sample_mask = 0xf0f0u;
+ recipe.sample_count = 1;
+ recipe.topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
+ recipe.state_key = x2w_startup::pso_recipe_state_key(recipe);
+ return recipe;
+}
+
+std::string replace_state_key(std::string text)
+{
+ const std::string marker = "state 0x";
+ const std::size_t at = text.find(marker);
+ if (at == std::string::npos) return text;
+ for (std::size_t i = 0; i < 16; ++i) text[at + marker.size() + i] = '0';
+ return text;
+}
+} // namespace
+
+int main()
+{
+ using namespace x2w_startup;
+ const PsoRecipe recipe = sample_recipe();
+ const std::string text = serialize_pso_recipe(recipe);
+ expect(text.rfind("x2w-pso-recipe 1\n", 0) == 0, "serialized record starts with version 1");
+ expect(text.size() <= pso_recipe_file_limit, "one record stays inside the file-size bound");
+
+ const PsoRecipeParseResult parsed = parse_pso_recipe_file(text);
+ expect(parsed.rejected == 0 && parsed.recipes.size() == 1, "record parses");
+ if (parsed.recipes.size() == 1) {
+ expect(serialize_pso_recipe(parsed.recipes[0]) == text, "serializer/parser round-trips byte-for-byte");
+
+ D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{};
+ desc.NumRenderTargets = 8;
+ desc.DSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
+ desc.SampleMask = 0;
+ desc.SampleDesc.Count = 4;
+ desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT;
+ apply_pso_recipe(parsed.recipes[0], desc);
+ expect(same_pso_blend(desc.BlendState, recipe.blend), "blend state recreated");
+ expect(same_pso_depth(desc.DepthStencilState, recipe.depth_stencil), "depth-stencil state recreated");
+ expect(same_pso_rasterizer(desc.RasterizerState, recipe.rasterizer), "rasterizer state recreated");
+ expect(desc.SampleMask == recipe.sample_mask && desc.SampleDesc.Count == recipe.sample_count,
+ "sample mask and count recreated");
+ expect(desc.PrimitiveTopologyType == recipe.topology, "topology recreated");
+ expect(desc.NumRenderTargets == recipe.target_count && desc.RTVFormats[0] == recipe.target_formats[0] &&
+ desc.RTVFormats[1] == recipe.target_formats[1] && desc.RTVFormats[2] == DXGI_FORMAT_UNKNOWN &&
+ desc.DSVFormat == recipe.dsv_format,
+ "target formats and DSV recreated");
+ }
+
+ PsoRecipe second = recipe;
+ second.target_count = 1;
+ second.target_formats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;
+ second.target_formats[1] = DXGI_FORMAT_UNKNOWN;
+ second.dsv_format = DXGI_FORMAT_UNKNOWN;
+ second.indexed_rect = false;
+ second.state_key = pso_recipe_state_key(second);
+ const std::string two_records = text + serialize_pso_recipe(second);
+ const PsoRecipeParseResult both = parse_pso_recipe_file(two_records);
+ expect(both.rejected == 0 && both.recipes.size() == 2, "two appended records parse");
+ if (both.recipes.size() == 2)
+ expect(serialize_pso_recipe(both.recipes[0]) + serialize_pso_recipe(both.recipes[1]) == two_records,
+ "two-record file round-trips byte-for-byte");
+
+ const PsoRecipeParseResult corrupted = parse_pso_recipe_file(replace_state_key(text));
+ expect(corrupted.recipes.empty() && corrupted.rejected == 1, "corrupt state key is rejected");
+
+ std::string unknown = text;
+ unknown.replace(0, std::strlen("x2w-pso-recipe 1"), "x2w-pso-recipe 2");
+ const PsoRecipeParseResult future = parse_pso_recipe_file(unknown);
+ expect(future.recipes.empty() && future.rejected == 1, "unknown recipe version is rejected");
+
+ const PsoRecipeParseResult oversized = parse_pso_recipe_file(std::string(pso_recipe_file_limit + 1, 'x'));
+ expect(oversized.recipes.empty() && oversized.rejected == 1, "oversized recipe file is rejected");
+
+ DXGI_FORMAT wrong_formats[2] = {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT};
+ expect(pso_recipe_targets_match(recipe, 2, recipe.target_formats, recipe.dsv_format),
+ "matching target formats and DSV accepted");
+ expect(!pso_recipe_targets_match(recipe, 2, wrong_formats, recipe.dsv_format), "target-format mismatch rejected");
+ expect(!pso_recipe_targets_match(recipe, 2, recipe.target_formats, DXGI_FORMAT_D24_UNORM_S8_UINT),
+ "DSV-format mismatch rejected");
+
+ // The writer stops where the parser stops. At 63 records the next append is still readable;
+ // at 64 it would become the record the next process rejects, so it is refused instead.
+ std::string sixty_three;
+ for (unsigned i = 0; i < pso_recipe_record_limit - 1; ++i) sixty_three += text;
+ const PsoRecipeParseResult at_63 = parse_pso_recipe_file(sixty_three);
+ expect(at_63.rejected == 0 && at_63.recipes.size() == pso_recipe_record_limit - 1, "63 records parse");
+ expect(pso_recipe_append_allowed(sixty_three, text), "63 records accept one more append");
+ expect(pso_recipe_append_allowed("", text), "an empty file accepts the first record");
+
+ const std::string sixty_four = sixty_three + text;
+ const PsoRecipeParseResult at_64 = parse_pso_recipe_file(sixty_four);
+ expect(at_64.rejected == 0 && at_64.recipes.size() == pso_recipe_record_limit, "64 records parse");
+ expect(!pso_recipe_append_allowed(sixty_four, text), "64 records refuse a 65th append");
+
+ const PsoRecipeParseResult at_65 = parse_pso_recipe_file(sixty_four + text);
+ expect(at_65.recipes.size() == pso_recipe_record_limit && at_65.rejected == 1 &&
+ at_65.error == "recipe record limit reached",
+ "65 records reject the extra record");
+ expect(!pso_recipe_append_allowed(replace_state_key(text), text), "a malformed file is not appended to");
+ expect(!pso_recipe_append_allowed(std::string(pso_recipe_file_limit, 'x'), text),
+ "an unparseable full-size file is not appended to");
+
+ // A record without its final LF still parses, but appending would put `end` and the next
+ // header on one line. The writer refuses and leaves the parseable record intact.
+ const std::string no_final_lf = text.substr(0, text.size() - 1);
+ const PsoRecipeParseResult parsed_no_lf = parse_pso_recipe_file(no_final_lf);
+ expect(parsed_no_lf.rejected == 0 && parsed_no_lf.recipes.size() == 1,
+ "a record without a final LF still parses");
+ expect(!pso_recipe_append_allowed(no_final_lf, text), "a file without a final LF refuses an append");
+ const PsoRecipeParseResult after_refusal = parse_pso_recipe_file(no_final_lf);
+ expect(after_refusal.rejected == 0 && after_refusal.recipes.size() == 1,
+ "the earlier record remains readable after the refused append");
+
+ std::printf("startup pso recipe checks: %d failed\n", failures);
+ return failures ? 1 : 0;
+}
diff --git a/tests/startup_stream_draw_check.py b/tests/startup_stream_draw_check.py
index 565b912b71..11ec21a0b7 100644
--- a/tests/startup_stream_draw_check.py
+++ b/tests/startup_stream_draw_check.py
@@ -1,6 +1,9 @@
"""Draw two source-built gfx1013 pixel shaders through a slot-86 wrapper and check every RGBA byte."""
+import ctypes
+from ctypes import wintypes
import os
from pathlib import Path
+import re
import subprocess
import sys
import tempfile
@@ -34,11 +37,13 @@ def pixel(green):
def check(directory, consumer, backend):
cache = directory / "cache"
cache.mkdir()
+ recipes = directory / "recipes"
+ recipes.mkdir()
vs, ps, root, output = (directory / name for name in ("vs", "ps", "root", "pixels"))
vs.write_bytes(vertex())
args = [consumer, vs, ps, root]
env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1",
- X2W_SHADER_CACHE=str(cache))
+ X2W_SHADER_CACHE=str(cache), X2W_PSO_RECIPE_DIR=str(recipes))
env.setdefault("X2W_D3D12_DEBUG", "0")
observations = []
for green in (False, True):
@@ -63,9 +68,40 @@ def check(directory, consumer, backend):
if pixels != expected:
raise AssertionError(f"actual {pixels.hex()} expected {expected.hex()}")
observations.append(pixels)
+ # The translated stream draw creates its desktop PSO through pipeline_for. A second
+ # process with the same recipe directory must replay it instead of reconstructing the
+ # state from scratch.
+ assert list(recipes.glob("pso_*.txt")), "the successful draw wrote no PSO recipe"
+ replay = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True)
+ assert replay.returncode == 0, replay.stderr
+ assert "pso recipes" in replay.stderr and "precreated" in replay.stderr, replay.stderr
+ assert output.read_bytes() == pixels, "the recipe replay changed the drawn pixels"
+ # A second writer cannot enter while this process owns the recipe file exclusively. The
+ # draw must still render through the PSO it creates; only the cache append is skipped.
+ recipe_key = gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes())
+ recipe_file = recipes / f"pso_{recipe_key:016x}.txt"
+ assert recipe_file.is_file(), f"missing recipe {recipe_file}"
+ size_before = recipe_file.stat().st_size
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.LPVOID,
+ wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
+ kernel32.CreateFileW.restype = wintypes.HANDLE
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ handle = kernel32.CreateFileW(str(recipe_file), 0x80000000, 0, None, 3, 0, None)
+ assert handle != wintypes.HANDLE(-1).value, ctypes.get_last_error()
+ try:
+ locked = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True)
+ assert locked.returncode == 0, locked.stderr
+ assert output.read_bytes() == pixels, "the locked recipe path changed the drawn pixels"
+ assert recipe_file.stat().st_size == size_before, "a contending draw appended to the locked recipe"
+ finally:
+ kernel32.CloseHandle(handle)
+ print(f"{backend}: exclusive recipe ownership keeps the draw on the fallback path")
# Hold back the last-published marker while keeping the generated shader bytecode in place.
key = gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes())
manifest = cache / f"{key:016x}.txt"
+ green_recipe = recipes / f"pso_{key:016x}.txt"
+ assert green_recipe.is_file(), f"missing green recipe {green_recipe}"
manifest.rename(str(manifest) + ".pending")
run = subprocess.run(args + [backend, output], env=dict(env, X2W_TEST_PUBLISH_MANIFEST=str(manifest)),
capture_output=True, text=True, timeout=30)
@@ -87,6 +123,49 @@ def check(directory, consumer, backend):
if output.read_bytes() != expected:
raise AssertionError(f"{mode}: got {output.read_bytes().hex()} expected {expected.hex()}")
print(f"{backend} {mode} green={green}: 32 pixels exact, drawn byte {value}")
+
+ # Seed the file with valid records that belong to another translation key. They parse but
+ # never replay, so the next successful draw appends the matching record as number 64 and the
+ # process after it precreates that record. At 64 records the writer must refuse the 65th.
+ ps.write_bytes(pixel(True))
+ original = green_recipe.read_text(encoding="ascii")
+ records = original.split("x2w-pso-recipe 1\n")
+ assert len(records) >= 2, original
+ original = "x2w-pso-recipe 1\n" + records[1]
+ foreign = re.sub(r"(?m)^translation 0x[0-9a-f]{16}$", "translation 0xdeadbeefcafef00d", original)
+ assert foreign != original
+ green_recipe.write_text(foreign * 63, encoding="ascii")
+ run = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True)
+ assert run.returncode == 0, run.stderr
+ assert output.read_bytes() == observations[1]
+ assert green_recipe.read_text(encoding="ascii").count("x2w-pso-recipe 1") == 64
+ replay = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True)
+ assert replay.returncode == 0, replay.stderr
+ assert "precreated 1" in replay.stderr, replay.stderr
+ assert output.read_bytes() == observations[1]
+
+ green_recipe.write_text(foreign * 64, encoding="ascii")
+ run = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True)
+ assert run.returncode == 0, run.stderr
+ assert output.read_bytes() == observations[1]
+ assert green_recipe.read_text(encoding="ascii").count("x2w-pso-recipe 1") == 64, \
+ "a full recipe file accepted a 65th record"
+ print(f"{backend}: 63+1 records precreate; 64 records refuse the 65th")
+
+ # A record without its final LF still parses, but appending would join `end` and the next
+ # header on one line. The draw must render and leave the parseable file byte-for-byte intact.
+ no_final_lf = green_recipe.read_bytes()
+ assert no_final_lf.rstrip(b"\r\n").endswith(b"end"), no_final_lf[-40:]
+ green_recipe.write_bytes(no_final_lf[:-1])
+ before = green_recipe.read_bytes()
+ run = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True)
+ assert run.returncode == 0, run.stderr
+ assert output.read_bytes() == observations[1]
+ assert green_recipe.read_bytes() == before, "a no-LF recipe file was modified by the refused append"
+ replay = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True)
+ assert replay.returncode == 0, replay.stderr
+ assert output.read_bytes() == observations[1]
+ print(f"{backend}: a recipe without a final LF stays readable and refuses the append")
return 0