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
28 changes: 20 additions & 8 deletions docs/embedded_shaders.md
Original file line number Diff line number Diff line change
Expand Up @@ -291,12 +291,13 @@ The last line also gets `--wave64-emulate` and the fallback flags of the build,
`0x80004001`) after 28 creations.

**Run time.** `ShaderLibrary::load(dir)` (`runtime/src/shader_library.h`) reads `<dir>/index.json`, then
`<dir>/fspx/index.json` and `<dir>/bvh/index.json` when they are there. The builder's entries are named
`bvh/<name>`, the path of their module below `<dir>`, and go into the table of the game's shaders, so
`create_compute` finds them through the lookup it already had (`compute_program()` gives an `FSSM` program, looked up
by `(cs, fssm_sha256)`). A missing or unreadable `bvh/index.json` leaves the other indexes loaded, and the main
index is still required. `bvh_size()` counts the entries, which `shader_library_corpus_test` leaves out of the
entries a carved container must reach, like the FSPX ones.
`<dir>/fspx/index.json`, `<dir>/bvh/index.json`, and `<dir>/exe/index.json` when they are there. The builder's
entries are named `bvh/<name>` and the executable's `exe/<name>`, the path of their module below `<dir>`, and both
go into the table of the game's shaders, so graphics and compute pipeline creation find them through the lookup they
already had (`fssm_program()` / `compute_program()` gives an `FSSM` program, looked up by `(stage, fssm_sha256)`). A
missing or unreadable subfolder `index.json` leaves the other indexes loaded, and the main index is still required.
`bvh_size()` and `exe_size()` count those entries, which `shader_library_corpus_test` leaves out of the entries a
carved container must reach, like the FSPX ones.

**Measured: `LEONIDA_BVH_DEVICE=vulkan bvh_builder_test`** (package 1.0.2.1, `LEONIDA_BVH_RECORD62=1`,
`LEONIDA_SHADERS` on a folder holding this step's output and an empty main index, since only this step was run).
Expand Down Expand Up @@ -390,6 +391,17 @@ constructor's pipelines are created, not that a build produces the right tree (s
`tests/test_bvh_shaders_stage.py` runs the step on a synthetic DLL (hand-built containers around a made-up `FSSM`
blob, no game data): the key the extracted layout gives the translator, the tools and arguments, reuse and each
reason to run again, a second run that leaves no duplicate containers, the report of an untranslated program on
every run and the failure when nothing translates. `shader_library_test` covers the `bvh/` index (found by the
container's program hash, counted apart, a broken or missing index beside the others) and `d3d12_compute_test`
every run and the failure when nothing translates. `shader_library_test` covers the `bvh/` and `exe/` indexes (found
by the container's program hash, counted apart, a broken or missing index beside the others) and `d3d12_compute_test`
creates a pipeline through slot 62 whose only translation is in `<shaders>/bvh/index.json`.

**Retail executable (`exe_shaders()`).** After `bvh_shaders()`, `make_game.py`'s `shaders` stage runs
`exe_shaders()` on `<game>/game_scarlett_master.exe` when present (skipping cleanly and dropping any stale
`<work>/shaders/spirv/exe/index.json` and `exe_build.json` when the package has no executable). It runs the same
four tools into `<work>/shaders/exe` and `<work>/shaders/spirv/exe` (without `--max-shared-memory`, since the
executable's containers are 1 VS + 9 PS graphics shaders), tracking inputs in `exe_build.json` and logging
translated/missing counts on every run. Measured on 1.0.2.1: 10 of 10 programs translate and pass `spirv-val`
natively and with `--wave64-emulate`, `ShaderLibrary::load` finds all 10 (`1 VS + 9 PS`) by `(stage, fssm_sha256)`,
and `vk_pipeline_check` passes 10/10 modules and 10/10 pipelines (0 failed, 0 skipped) on an AMD Radeon RX 9070 XT
(RADV GFX1201, Mesa 26.2.6) and an AMD Ryzen 7 9800X3D integrated GPU (RADV RAPHAEL_MENDOCINO, Mesa 26.2.6).
`tests/test_exe_shaders_stage.py` covers the step on synthetic VS/PS `PSV0` containers without game data.
85 changes: 84 additions & 1 deletion make_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
Stages (each skips work that is already done, so a stopped build continues where it left off):
check always first: file names and sizes against game/<version>.json (add --full-check for SHA-256, slow)
shaders carve shaders.rpf, unpack the native RDNA2 code, disassemble, translate to SPIR-V; then the same for the
compute programs inside amd_fidelityfx_upscaler_xbox.dll and XboxBvhBuilder.dll
programs inside amd_fidelityfx_upscaler_xbox.dll, XboxBvhBuilder.dll and game_scarlett_master.exe
assets models (OBJ), texture dictionaries and texture pools (DDS), audio banks (AWC; --wav adds PCM WAV)
BCPack uses strict decoding by default. For local calibration use <work>/bcpack-calibration.json.
runtime build the loader (needs the game's executable to run, not to build). On Linux it is cross-built with
Expand Down Expand Up @@ -1344,6 +1344,7 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate
fspx_shaders(game, work, signature, emulate=emulate, fallbacks=fallbacks)
bvh_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks)
library_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks)
exe_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks)
log("shaders: done")


Expand Down Expand Up @@ -1633,6 +1634,88 @@ def bvh_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate:
f.write(settings + "\n")


EXE_FILE = "game_scarlett_master.exe"
EXE_TOOLS = BVH_TOOLS # pe_shader_containers.py, fssm_unpack.py and shader_disasm.py


def exe_settings(exe: str, mc_signature: str, emulate: bool, fallbacks: tuple[str, ...]) -> str:
"""What the executable's embedded shader outputs depend on, as one line: the executable, the extracting,
unpacking and translating tools, llvm-mc, the wave64 mode and the fallback flags."""
return json.dumps({"exe": file_sha256(exe), "tools": sources_digest(TOOLS, EXE_TOOLS),
"translator": translation_sources_digest(), "llvm_mc": mc_signature,
"wave64_emulate": bool(emulate), "fallbacks": list(fallbacks)}, sort_keys=True)


def exe_report(programs: "tuple[list[str], list[str]]") -> None:
"""One line with the counts, and one that names every program left without a module. It is printed on every
run, also when the step itself is reused: a program the translator has no rule for is never dropped quietly."""
extracted, missing = programs
log(f"shaders: {len(extracted) - len(missing)} of {len(extracted)} {EXE_FILE} programs translated")
if missing:
log(f"shaders: NOT translated: {', '.join(missing)}. The runtime has no module for "
f"{'it' if len(missing) == 1 else 'them'}, so any pipeline using it will miss its shader. "
"When the step runs, rdna2spirv.py prints the instruction each one stops at "
"(docs/embedded_shaders.md, section 2)")


def exe_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate: bool = False,
fallbacks: tuple[str, ...] = ()) -> None:
"""game_scarlett_master.exe's embedded graphics shaders (docs/embedded_shaders.md, section 2):
pe_shader_containers.py extracts the executable's DXBC containers into <work>/shaders/exe, fssm_unpack.py and
shader_disasm.py unpack and disassemble their FSSM programs there, as for a shader from shaders.rpf, and
rdna2spirv.py translates them into <work>/shaders/spirv/exe, where the runtime's shader library finds them by
fssm_sha256. The game's RPF shaders neither feed nor depend on this step.

The 10 programs take seconds, so the step runs whole. Reuse requires both indexes, the translated modules and a
matching exe_build.json (exe_settings)."""
exe = os.path.join(game, EXE_FILE)
unpacked = os.path.join(work, "shaders", "exe")
spirv = os.path.join(work, "shaders", "spirv", "exe")
extracted = os.path.join(unpacked, "index.json")
unpack_index = os.path.join(unpacked, "fssm_index.json")
translated = os.path.join(spirv, "index.json")
settings_file = os.path.join(spirv, "exe_build.json")
if not os.path.isfile(exe):
# A work folder used before with a package that had the executable still holds that run's index, and the
# runtime loads <shaders>/exe/index.json whenever it is there. Without the index the old modules are not found.
drop(translated, settings_file)
log(f"shaders: no {EXE_FILE} in the game folder, so no executable shader programs to translate")
return
settings = exe_settings(exe, mc_signature, emulate, fallbacks)
programs = bvh_programs(unpacked, spirv) if read_shader_setting(settings_file) == settings else None
if programs:
exe_report(programs)
return
log(f"shaders: extracting and translating the embedded shader programs of {EXE_FILE}")
drop(translated, settings_file, extracted, unpack_index)
# pe_shader_containers.py never overwrites a container (a second run would write <stem>_NN.dxbc beside the
# first), and a program that no longer translates must not keep a module from the run before.
for folder, suffixes in ((unpacked, (".dxbc",)), (os.path.join(unpacked, "fssm"), (".fssm",)),
(os.path.join(unpacked, "disasm"), (".s",)), (spirv, (".spv", ".spvasm"))):
if os.path.isdir(folder):
with os.scandir(folder) as entries:
for entry in entries:
if entry.name.endswith(suffixes) and entry.is_file(follow_symlinks=False):
os.unlink(entry.path)
py("pe_shader_containers.py", exe, "--extract", unpacked)
py("fssm_unpack.py", unpacked, "--carve-index", extracted)
# rdna2spirv.py reads each program's stage from index.json and its FSSM blob from fssm/, both in the parent of
# the listings' folder, so the disassembly sits inside the extraction folder as it does for shaders.rpf.
disasm = os.path.join(unpacked, "disasm")
py("shader_disasm.py", os.path.join(unpacked, "fssm"), "--unpack-index", unpack_index, "--out", disasm,
"--mcpu", "gfx1013", "--jobs", jobs)
extra = (["--wave64-emulate"] if emulate else []) + list(fallbacks)
py("rdna2spirv.py", disasm, "--out", spirv, "--no-asm", *extra)
programs = bvh_programs(unpacked, spirv)
if not programs or len(programs[1]) == len(programs[0]):
drop(translated) # an empty or unreadable index would read as a finished step
fail(f"shaders: none of the {EXE_FILE} programs translated, so their index is not kept. Run the shaders "
"stage again; if it happens again, the tool output above is why.")
exe_report(programs)
with open(settings_file, "w", encoding="utf-8", newline="\n") as f:
f.write(settings + "\n")


WAVE64_MODES = ("auto", "on", "off")

# The translator's fallback flags make_game.py can forward, and the argparse attribute each one reads.
Expand Down
20 changes: 14 additions & 6 deletions runtime/src/shader_library.h
Original file line number Diff line number Diff line change
Expand Up @@ -843,16 +843,18 @@ struct ShaderEntry {

class ShaderLibrary {
public:
// Reads <dir>/index.json, then the indexes of the programs make_game.py translates from the package's DLLs, each
// when it is there:
// Reads <dir>/index.json, then the indexes of the programs make_game.py translates from the package's PE images,
// each when it is there:
// - <dir>/fspx/index.json, the FidelityFX DLL's FSPX programs, entries named "fspx/<name>" (docs/fspx.md);
// - <dir>/bvh/index.json, XboxBvhBuilder.dll's FSSM programs, entries named "bvh/<name>" and found by
// fssm_sha256 like the game's own shaders (docs/embedded_shaders.md);
// - <dir>/library/index.json, the compute programs of the pipeline library in shaders.rpf, which the executable
// creates with slot 67; entries named "library/<name>" and found by fspx_code_sha256 and fspx_state_sha256
// like the FSPX ones (docs/shader_library.md).
// Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. Both folders
// are optional: a missing or unreadable index there leaves the main one, and the other folder's, loaded.
// like the FSPX ones (docs/shader_library.md);
// - <dir>/exe/index.json, game_scarlett_master.exe's embedded FSSM programs, entries named "exe/<name>" and
// found by fssm_sha256 like the game's own shaders (docs/embedded_shaders.md).
// Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. The folders
// are optional: a missing or unreadable index there leaves the main one, and the other folders', loaded.
bool load(const std::filesystem::path& dir, std::string* error = nullptr) {
const auto fail = [&](const std::string& why) {
if (error) *error = why;
Expand All @@ -870,7 +872,7 @@ class ShaderLibrary {
} catch (...) {
return fail("index.json could not be read");
}
for (const char* sub_folder : {"fspx", "bvh", "library"}) {
for (const char* sub_folder : {"fspx", "bvh", "library", "exe"}) {
try {
const auto ignore = [](const std::string&) { return false; };
const std::filesystem::path sub = folder / sub_folder;
Expand All @@ -893,6 +895,9 @@ class ShaderLibrary {
// Entries loaded from <dir>/bvh/index.json. No RPF container reaches these either: XboxBvhBuilder.dll passes
// their containers itself.
std::size_t bvh_size() const { return bvh_count_; }
// Entries loaded from <dir>/exe/index.json. No RPF container reaches these either: game_scarlett_master.exe
// embeds their containers itself.
std::size_t exe_size() const { return exe_count_; }

// The first entry for this program. Two containers can hold the same FSSM program with different input
// signatures; `candidates` returns all of them.
Expand Down Expand Up @@ -1000,6 +1005,7 @@ class ShaderLibrary {
count_ = 0;
fspx_count_ = 0;
bvh_count_ = 0;
exe_count_ = 0;
}
for (const auto& [name, meta] : root.object) {
const Json* hash = meta.find("fssm_sha256");
Expand Down Expand Up @@ -1065,6 +1071,7 @@ class ShaderLibrary {
if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e));
if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_;
if (prefix == "bvh/") ++bvh_count_;
if (prefix == "exe/") ++exe_count_;
++count_;
}
return true;
Expand All @@ -1074,6 +1081,7 @@ class ShaderLibrary {
std::size_t count_ = 0;
std::size_t fspx_count_ = 0;
std::size_t bvh_count_ = 0;
std::size_t exe_count_ = 0;
// Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order.
Entries entries_;
Entries fspx_entries_;
Expand Down
8 changes: 4 additions & 4 deletions runtime/test/shader_library_corpus_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -192,16 +192,16 @@ int main() {
}

if (containers == 0) fail("no .dxbc containers in", dxbc_dir);
const std::size_t rpf_entries = library.size() - library.fspx_size() - library.bvh_size();
const std::size_t rpf_entries = library.size() - library.fspx_size() - library.bvh_size() - library.exe_size();
if (reached.size() != rpf_entries)
fail(std::to_string(reached.size() > rpf_entries ? reached.size() - rpf_entries : rpf_entries - reached.size()) +
" RPF index entries not matched one to one",
spirv_dir);
std::printf("%zu containers, %zu RPF index entries, %zu reached, %zu FSPX index entries, %zu BVH builder index "
"entries; %zu containers with more than one program; "
"entries, %zu executable index entries; %zu containers with more than one program; "
"%zu not translated; %d failures\n",
containers, rpf_entries, reached.size(), library.fspx_size(), library.bvh_size(), multi, untranslated,
failures);
containers, rpf_entries, reached.size(), library.fspx_size(), library.bvh_size(), library.exe_size(),
multi, untranslated, failures);
if (untranslated)
std::fprintf(stderr, "%zu container(s) have no index entry: the translator left them out, so the lookup had "
"nothing to find. Run the shaders stage again with a current translator.\n",
Expand Down
Loading
Loading