Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions docs/fspx.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,9 @@ and `RSRC2`).

**Slot 57 (`DeserializeGraphicsPipelineStateX`, graphics FSPX).** At `game_scarlett_master.exe+0x2477578`, the retail
title calls device slot 57 (`+0x1c8`) with `IID_ID3D12PipelineState` (`{765a30f3-f624-4c6f-a828-ace948622445}`) and a
104-byte description (`+0x00..+0x60`) populated from the zlib-compressed pipeline library in `shaders.rpf`
([shader_library.md](shader_library.md): 25,471 graphics records + 2,693 compute records):
description populated from the zlib-compressed pipeline library in `shaders.rpf`. Its first two stage blocks
and the preceding fields occupy the 104-byte prefix (`+0x00..+0x60`) shown below. The library contains
25,471 graphics records and 2,693 compute records. [Pipeline library layout](shader_library.md)

| Offset | Field | Measured layout |
|---|---|---|
Expand All @@ -254,9 +255,14 @@ title calls device slot 57 (`+0x1c8`) with `IID_ID3D12PipelineState` (`{765a30f3
2. Record 8917 (`f7808a66fb6b97c1`): state 388 B (`0x4005d808`), pipeline blob 188 B (`0x542385d2`), `ps` prog 844 (768 B, SHA-256 `947014e8b0771be5...`), `vs` prog 845 (320 B, SHA-256 `a2dce0214f82c742...`).
3. Record 12511 (`e750e10eacb97b9c`): state 380 B (`0x4005d808`), pipeline blob 188 B (`0xfb724939`), no `ps`, `vs` prog 5636 (320 B, SHA-256 `f6bfddbad6aef3cd...`).
In the library, the 448/768 B program at `+0x28` is the pixel shader (`ps`, paired with the 208 B stage blob) and the
384/320 B program at `+0x48` is the vertex shader (`vs`, paired with the 752 B stage blob). Programs are looked up by
`sha256(program bytes)` in `<shaders>/fspx_gfx/index.json` (`ShaderLibrary::fspx_gfx_size()`, separate from
`fspx_size()`), and their `stage` (`"vs"` / `"ps"` / `"ms"`) is taken from the index entry rather than the blob slot.
384/320 B program at `+0x48` is the vertex shader (`vs`, paired with the 752 B stage blob).
- The Vulkan factory reads all seven stage blocks of the 0x108-byte description. A stage record's DXBC HASH
selects its source container through `native_hashes.txt`. A stage without a matching container identity can
resolve through the SHA-256 of its complete program in `<shaders>/fspx_gfx/index.json`. The indexed stage
identifies VS, PS or MS. A digest shared by different stages cannot select one from code alone. If a source
container fails validation or its PSO is refused, the factory can retry with indexed code for the same
stage, retaining the decoded state, input layout and root signature. `--trace-d3d12` records the number of
catalog and kind-6 stages submitted to the Vulkan factory and its HRESULT. [Build and coverage](shader_library.md)
- **Measured `pipeline blob` layout (188 B = `0xbc`):**
- `+0x00`: u32 per-PSO checksum (`0xea6f6e56` / `0x542385d2` / `0xfb724939`)
- `+0x04`: u32 `0x1000` (constant across 2,642 blobs), `+0x08`: `0`, `+0x0c`: `1`
Expand Down
27 changes: 26 additions & 1 deletion docs/shader_library.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,32 @@ library through DirectStorage zlib requests and passes each compute record's fou
`DeserializeComputePipelineStateX`, as kinds 0, 1, 6 and 7, so the code key is the program's bytes as the table gives
them and the state key is the record's state blob. The step is redone as a whole when `shaders.rpf`, the tools,
`llvm-mc`, the wave64 mode or the flags change (`library_build.json`, written last), and a clash of both keys between
different modules fails it, as for the FSPX step. Graphics pipelines are not translated by the build.
different modules fails it, as for the FSPX step.

For device slot 57 the same build unpacks the PS, VS and MS selections into `<work>/shaders/fspx_gfx`.
It disassembles the pipeline-specific kind-6 bytes and translates them into `<work>/shaders/spirv/fspx_gfx`.
Each published row names its stage and the SHA-256 of the entire kind-6 program, including its prologue. The
source container supplies signatures and PSV0 when available. Run the usual `make_game.py --stages shaders`
with the same game, work folder and translation options to add this index to an existing workspace. Compute
and graphics have separate build markers. The graphics marker also records the output index digest and the
number of extracted and translated programs. A missing module or a truncated index triggers a graphics rebuild.

In the original build shell, use the paths for that workspace and any adapter options used for its first
translation. The two CTests draw with hand-built native descriptions and check the GPU pixels.

```powershell
python -I make_game.py --game $game --work $work --out $port --stages shaders
ctest --test-dir $build -C RelWithDebInfo -R '^xbox_native_fspx_(draw|mesh)$' --output-on-failure
```

On 1.0.2.1 the 25,471 graphics records reference 18,837 distinct programs in the three identified stages.
In both native-wave64 and wave64-emulation builds, 9,671 of 9,996 PS, 1,342 of 1,343 VS and 7,480 of 7,498 MS
translated and passed `spirv-val`. Every published key matched the complete extracted program. Of the identified
programs, 18,829 have a 36-byte prologue and eight have the 24-byte two-carrier form. Looking up all stages
by raw code alone covered 24,983 records. The per-record layout digests linked all stages to the DXBC catalog
for 25,450 records. Two records also name the unidentified slot-6 program. A record
with all of its stage links still needs a valid root signature, fixed-function state and a device that supports
its pipeline before it can draw. [Slot 57 and native shader lookup](fspx.md)

### Resuming a compute-only batch on Linux

Expand Down
99 changes: 76 additions & 23 deletions make_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
sys.path.insert(0, TOOLS)
from mc_command import install_hint as mc_install_hint, mc_command # noqa: E402
import leonida_tui # noqa: E402
from shader_stage_manifest import shader_stems # noqa: E402
from shader_stage_manifest import shader_stages, shader_stems # noqa: E402
from replace_retry import replace as replace_retry # noqa: E402
from stale_build import newer_sources # noqa: E402

Expand Down Expand Up @@ -1463,7 +1463,7 @@ def fspx_shaders(game: str, work: str, mc_signature: str, emulate: bool = False,


def library_settings(archive: str, mc_signature: str, emulate: bool, fallbacks: tuple[str, ...]) -> str:
"""What the pipeline library's compute translations depend on, as one line: shaders.rpf, the unpacking and
"""What the pipeline library's translations depend on, as one line: shaders.rpf, the unpacking and
translating tools, llvm-mc, the wave64 mode and the fallback flags."""
return json.dumps({"archive": file_sha256(archive), "tools": sources_digest(TOOLS, LIBRARY_TOOLS),
"translator": translation_sources_digest(), "llvm_mc": mc_signature,
Expand All @@ -1472,31 +1472,38 @@ def library_settings(archive: str, mc_signature: str, emulate: bool, fallbacks:

def library_shaders(game: str, work: str, mc_signature: str, jobs: int, emulate: bool = False,
fallbacks: tuple[str, ...] = ()) -> None:
"""The compute pipelines of the pipeline library in shaders.rpf (docs/shader_library.md). The executable reads
the library through DirectStorage and creates each compute pipeline with Xbox device slot 67
(DeserializeComputePipelineStateX), passing the record's four parts as FSPX kinds 0, 1, 6 and 7 (docs/fspx.md).
tools/shader_library.py unpacks the compute programs with their kind-0 state into <work>/shaders/library, and
translate() runs rdna2spirv.py across jobs processes into <work>/shaders/spirv/library, where the runtime's
shader library finds them by fspx_code_sha256 and fspx_state_sha256 as it finds the FidelityFX DLL's. Graphics
pipelines are not translated here. The game's own shaders neither feed nor depend on this step, apart from the
carve that names each program's source container (the translator reads its signatures).

The step runs whole. Reuse requires the translation index, its named modules and a matching library_build.json
(library_settings)."""
"""Build the pipeline-library programs used by Xbox slots 67 (compute) and 57 (graphics).
Each directory has its own index and build marker so an existing compute translation can be reused."""
archive = os.path.join(game, LIBRARY_ARCHIVE)
unpacked = os.path.join(work, "shaders", "library")
spirv = os.path.join(work, "shaders", "spirv", "library")
settings = library_settings(archive, mc_signature, emulate, fallbacks) if os.path.isfile(archive) else None
if settings is None:
log(f"shaders: no {LIBRARY_ARCHIVE} in the game folder, so no pipeline library to translate")
for folder, stages in (("library", ("cs",)), ("fspx_gfx", ("ps", "vs", "ms"))):
translate_library_stages(archive, work, folder, stages, settings, jobs, emulate, fallbacks)


def translate_library_stages(archive: str, work: str, folder_name: str, stages: tuple[str, ...],
settings: str | None, jobs: int, emulate: bool, fallbacks: tuple[str, ...]) -> None:
unpacked = os.path.join(work, "shaders", folder_name)
spirv = os.path.join(work, "shaders", "spirv", folder_name)
translated = os.path.join(spirv, "index.json")
shard_plan = os.path.join(spirv, SHARD_PLAN)
settings_file = os.path.join(spirv, "library_build.json")
if not os.path.isfile(archive):
if settings is None:
drop(translated, settings_file, shard_plan)
log(f"shaders: no {LIBRARY_ARCHIVE} in the game folder, so no pipeline library to translate")
return
settings = library_settings(archive, mc_signature, emulate, fallbacks)
if read_shader_setting(settings_file) == settings and fspx_cache_complete(spirv):
return
log(f"shaders: unpacking and translating the compute pipelines of the pipeline library in {LIBRARY_ARCHIVE}")
graphics = folder_name == "fspx_gfx"
saved = read_shader_setting(settings_file)
if saved:
if graphics:
if saved == graphics_library_stamp(unpacked, spirv, settings):
report_graphics_library(saved)
return
elif saved == settings and (fspx_cache_complete(spirv) or
(read_shader_setting(translated) == "{}" and empty_library_selection(unpacked))):
return
stage_list = ",".join(stages)
log(f"shaders: unpacking and translating pipeline library programs ({stage_list}) in {LIBRARY_ARCHIVE}")
drop(translated, settings_file, shard_plan)
# A program that no longer translates or lost its carve container must not keep outputs from the run before.
for folder, suffixes in ((unpacked, (".dxbc",)),
Expand All @@ -1509,14 +1516,60 @@ def library_shaders(game: str, work: str, mc_signature: str, jobs: int, emulate:
if entry.name.endswith(suffixes) and entry.is_file(follow_symlinks=False):
os.unlink(entry.path)
carve = os.path.join(work, "shaders", "dxbc")
py("shader_library.py", archive, "--out", unpacked, "--stages", "cs", "--disasm", "--jobs", str(jobs),
py("shader_library.py", archive, "--out", unpacked, "--stages", stage_list, "--disasm", "--jobs", str(jobs),
*(["--carve", carve] if os.path.isdir(carve) else []))
translate(os.path.join(unpacked, "disasm"), spirv, jobs, emulate=emulate, fallbacks=fallbacks)
if empty_library_selection(unpacked):
# A library with only one pipeline type has a valid, empty selection for the other.
os.makedirs(spirv, exist_ok=True)
with open(translated, "w", encoding="utf-8", newline="\n") as f:
f.write("{}\n")
else:
translate(os.path.join(unpacked, "disasm"), spirv, jobs, emulate=emulate, fallbacks=fallbacks)
verify_fspx_key_clash(spirv, translated, "pipeline library")
if graphics:
settings = graphics_library_stamp(unpacked, spirv, settings)
if settings is None:
drop(translated)
fail("shaders: the graphics pipeline library index has missing modules or unusable stage/hash metadata")
report_graphics_library(settings)
with open(settings_file, "w", encoding="utf-8", newline="\n") as f:
f.write(settings + "\n")


def empty_library_selection(unpacked: str) -> bool:
try:
return not shader_stems(os.path.join(unpacked, "index.json"), "file", ".dxbc")
except (OSError, ValueError):
return False


def graphics_library_stamp(unpacked: str, spirv: str, settings: str) -> str | None:
"""Bind the build marker to the published index, including its coverage when a translation is refused."""
try:
extracted = shader_stages(os.path.join(unpacked, "index.json"), "file", ".dxbc")
with open(os.path.join(spirv, "index.json"), "rb") as f:
data = f.read()
index = json.loads(data)
except (OSError, ValueError):
return None
if not isinstance(index, dict) or (extracted and not index):
return None
for name, meta in index.items():
stage = extracted.get(name)
if (stage not in ("ps", "vs", "ms") or not isinstance(meta, dict) or meta.get("stage") != stage
or not isinstance(meta.get("fspx_code_sha256"), str)
or not re.fullmatch(r"[0-9a-f]{64}", meta["fspx_code_sha256"])
or not os.path.isfile(os.path.join(spirv, name + ".spv"))):
return None
return json.dumps({"inputs": json.loads(settings), "index_sha256": hashlib.sha256(data).hexdigest(),
"translated": len(index), "programs": len(extracted)}, sort_keys=True)


def report_graphics_library(stamp: str) -> None:
result = json.loads(stamp)
log(f"shaders: {result['translated']} of {result['programs']} graphics pipeline library programs translated")


def verify_fspx_key_clash(spirv: str, translated: str, label: str) -> None:
"""Reject an unreadable translation index or one whose kind-6 and kind-0 keys pick between different modules."""
try:
Expand Down
5 changes: 4 additions & 1 deletion runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3010,6 +3010,8 @@ if(TARGET Vulkan::Headers)
target_compile_options(d3d12_translated_draw_test PRIVATE /W4 /permissive- /utf-8)
add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test)
add_test(NAME xbox_native_base_draw COMMAND d3d12_translated_draw_test --native-pso)
add_test(NAME xbox_native_fspx_draw COMMAND d3d12_translated_draw_test --native-fspx)
set_tests_properties(xbox_native_fspx_draw PROPERTIES SKIP_RETURN_CODE 77)
add_test(NAME xbox_derived_mask_zero COMMAND d3d12_translated_draw_test --derived-zero)
add_test(NAME xbox_derived_mask_restore COMMAND d3d12_translated_draw_test --derived-restore)

Expand Down Expand Up @@ -3736,7 +3738,8 @@ if(TARGET Vulkan::Headers)
LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}")
target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8)
add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test)
set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77)
add_test(NAME xbox_native_fspx_mesh COMMAND d3d12_mesh_test --native-fspx)
set_tests_properties(d3d12_mesh xbox_native_fspx_mesh PROPERTIES SKIP_RETURN_CODE 77)
else()
message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built")
endif()
Expand Down
17 changes: 9 additions & 8 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7222,7 +7222,7 @@ class PipelineState final
VkShaderStageFlagBits bit;
const D3D12_SHADER_BYTECODE& code;
const leonida::ShaderEntry* entry = nullptr;
std::vector<std::uint8_t> fssm;
std::vector<std::uint8_t> program_bytes;
std::vector<std::uint32_t> words;
};
Stage stages[3] = {mesh ? Stage{"ms", VK_SHADER_STAGE_MESH_BIT_EXT, *ms}
Expand Down Expand Up @@ -7266,10 +7266,10 @@ class PipelineState final
if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only
const std::span<const std::uint8_t> raw_bytes{
static_cast<const std::uint8_t*>(stage.code.pShaderBytecode), stage.code.BytecodeLength};
stage.fssm = leonida::fssm_program(raw_bytes);
stage.program_bytes = leonida::fssm_program(raw_bytes);
const bool vertex = stage.bit == VK_SHADER_STAGE_VERTEX_BIT;
if (!stage.fssm.empty()) {
const std::string hash = leonida::sha256_hex(stage.fssm);
if (!stage.program_bytes.empty()) {
const std::string hash = leonida::sha256_hex(stage.program_bytes);
// Containers with the same program can differ in their input signature or bindings: a VS must have its
// inputs fed by this input layout (else the layout check below reports it).
stage.entry = pick_entry(library->candidates(stage.name, hash), [&](const leonida::ShaderEntry& e) {
Expand Down Expand Up @@ -7298,6 +7298,7 @@ class PipelineState final
stage.name, hash.c_str(), raw_bytes.size());
return stub_or(E_INVALIDARG, "graphics");
}
if (stage.entry->uses_code_base) stage.program_bytes.assign(raw_bytes.begin(), raw_bytes.end());
} else {
log_once("shader bytecode holds no FSSM or FSPX program; bytes", int(stage.code.BytecodeLength));
return E_INVALIDARG;
Expand Down Expand Up @@ -7796,9 +7797,9 @@ class PipelineState final

if (code_stage) {
VkDeviceSize offset = 0;
if (!device_.arena_allocate(code_stage->fssm.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY;
std::memcpy(device_.arena.mapped + offset, code_stage->fssm.data(), code_stage->fssm.size());
code_bytes_ = code_stage->fssm.size();
if (!device_.arena_allocate(code_stage->program_bytes.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY;
std::memcpy(device_.arena.mapped + offset, code_stage->program_bytes.data(), code_stage->program_bytes.size());
code_bytes_ = code_stage->program_bytes.size();
code_base_ = offset;
graphics_.code_base = offset;
}
Expand Down Expand Up @@ -10321,7 +10322,7 @@ class Device final
HRESULT create_native_graphics(const leonida::native_pso::GraphicsDesc& desc, REFIID iid, void** out) {
const auto* shaders = state_.library();
if (!shaders) return E_NOTIMPL;
return state_.native_graphics.create(shaders->directory(), desc, out, [&](const auto& pc, const auto& mesh, const auto& containers) {
return state_.native_graphics.create(*shaders, desc, out, [&](const auto& pc, const auto& mesh, const auto& containers) {
return shared_native_graphics(pc, mesh, containers, iid, out);
});
}
Expand Down
Loading
Loading