r"""Build the PC port from your own copy of the game. Build.bat # double-click: finds your copy and builds python -I make_game.py # same, from a terminal python -I make_game.py --find # list the copies found on this PC python -I make_game.py --pick # choose the game folder in a folder dialog python -I make_game.py --game "D:\path\to\your\package" --out "D:\Games\Leonida" python -I make_game.py --game "..." --check # only check the copy, build nothing python -I make_game.py --stages shaders,assets # only some stages The game folder is your own Xbox Series package, version 1.0.2.1, with its files already readable on disk (see game/xbox-1.0.2.1.json for the file list). It is found automatically in Downloads, Desktop, Documents (also where Windows keeps them, such as in OneDrive), Games, your home folder, the top of each drive on Windows and the usual mount points elsewhere (/mnt, /media, /run/media, /Volumes, and the per-user /media/ and /run/media/ where Linux desktops mount drives), two folder levels down. A share path (\\server\share\...) can't be listed, so give it to --game. This script never decrypts or works around anything: it reads plain files and writes everything it makes under --out. The only things it downloads are the third_party/rpf9-explorer submodule, when it is missing, and, for the Windows runtime stage, the pinned SDL3 release CMake checks by SHA-256 (controller, keyboard and mouse input; --no-sdl3 skips it). Never share what it makes. 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/.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 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 and reads confirmed history from /bcpack-history.json. For local calibration use /bcpack-calibration.json. runtime build the loader (needs the game's executable to run, not to build). On Linux it is cross-built with clang-cl and an xwin SDK (docs/testing.md) and gta6rt.sh starts it with Wine; --runtime-build DIR takes a Windows build of runtime/ instead (the runtime-windows artifact of the Runtime workflow) pipelines create every translated shader on your GPU's driver as a pipeline, report anything the driver rejects or that has to be skipped, and save the pipeline cache next to the port (the runtime doesn't load that cache yet) shaders, assets and runtime do not depend on each other and run together after check. pipelines starts once the translated shaders are ready and, when this run includes runtime, that stage has finished rebuilding vk_pipeline_check (a checker already on disk is enough only when runtime is not selected), so it can overlap the rest of assets. When shaders and assets share the machine, --jobs is split between them and passed to rpf9dump; a solo assets run still lets rpf9dump use every core. Long steps log percent and a rough ETA (shader translation shards, asset exports, XMA decode, pipeline batches weighted by module size, and overall weighted stage completion while they overlap). On an interactive terminal, a LEONIDA setup screen asks for --jobs and whether to overlap stages, then a key-switchable per-stage log view (1-4 / Tab) keeps parallel output demuxed. Pass --no-tui (or redirect stdout) for the plain interleaved console. Either way each build stage's full log lands in /logs/.log. """ import argparse import codecs import functools import glob import hashlib import json import locale import ntpath import os import re import shlex import shutil import stat import struct import subprocess import sys import tempfile import threading import time import traceback from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed if __name__ == "__main__" and sys.version_info < (3, 12): # before code an older Python can't run sys.exit("ERROR: Python 3.12 or newer is needed: https://www.python.org/downloads/") ROOT = os.path.dirname(os.path.abspath(__file__)) TOOLS = os.path.join(ROOT, "tools") sys.path.insert(0, TOOLS) from mc_command import install_hint as mc_install_hint, mc_command, split_command # noqa: E402 import leonida_tui # noqa: E402 from shader_stage_manifest import shader_stems # noqa: E402 from replace_retry import replace as replace_retry # noqa: E402 from stale_build import newer_sources # noqa: E402 VERSIONS = os.path.join(ROOT, "game") STAGES = ["check", "shaders", "assets", "runtime", "pipelines"] WINDOWS_ONLY = ("runtime",) # off Windows: the clang-cl + xwin cross-build, or --runtime-build CROSS_TOOLS = ("clang-cl", "lld-link", "llvm-lib", "llvm-rc", "llvm-mt") CROSS_VARS = {"C_COMPILER": "clang-cl", "CXX_COMPILER": "clang-cl", "LINKER": "lld-link", "AR": "llvm-lib", "RC_COMPILER": "llvm-rc", "MT": "llvm-mt"} # the toolchain's CMAKE_ defaults XWIN_DEFAULT = os.path.join("~", ".local", "share", "xwin-sdk") RUNTIME_FILES = ("gta6rt.exe", "gta6rt_tls_host.dll") # Archives scanned for models and texture dictionaries, small to large. MODEL_ARCHIVES = [ "common.rpf", "textures.rpf", "data.rpf", "pack/story000_restofworld/story000_restofworld.rpf", "pack/shared_minigame000/shared_minigame000.rpf", "pack/core_restofworld/core_restofworld.rpf", "pack/core_restofworld001/core_restofworld001.rpf", "packs.rpf", "pack/story000/story000.rpf", "levels.rpf", ] class PlainStageLogs: """The stage logs of a build without the LEONIDA board (--no-tui, or stdout redirected). The console keeps the plain interleaved output, and each stage's lines also go to /logs/.log, the files the board writes: log() and fail() lines, and the output of the commands run() starts, one line per \\r- or \\n-ended piece as the board splits it. Active (module-level _plain_logs) while run_build_stages runs. A stage's file is opened with its first line; when the folder can't be written, one note goes to stderr and the build goes on without the logs. A command's output is decoded once, and the console and the log both get that text.""" def __init__(self, stages: list, log_dir: str): self.log_dir = log_dir self.stages = tuple(stages) self.consoles: dict = {} self._lock = threading.Lock() self._unwritable = False # What a text-mode pipe decodes with, so a line reads the same as in the board's log. self.encoding = locale.getpreferredencoding(False) def _console(self, stage: "str | None"): if stage not in self.stages: return None with self._lock: console = self.consoles.get(stage) if console is None and not self._unwritable: try: console = self.consoles[stage] = leonida_tui.StageConsole( stage, os.path.join(self.log_dir, f"{stage}.log")) except OSError as e: self._unwritable = True print(f"cannot write the stage logs in {self.log_dir} ({e.strerror or e}); the build goes on " "without them", file=sys.stderr, flush=True) return console def __enter__(self) -> "PlainStageLogs": global _plain_logs _plain_logs = self return self def __exit__(self, exc_type, exc, tb) -> bool: global _plain_logs if _plain_logs is self: _plain_logs = None for console in self.consoles.values(): console.close() if self.consoles: print(f"stage logs in {self.log_dir}", flush=True) return False def write(self, stage: "str | None", line: str) -> None: console = self._console(stage) if console is not None: console.write_line(line) def _write_pieces(self, stage: str, data: str) -> str: """Log each \\r- or \\n-ended piece of data (stripped, empty ones dropped); return the unended rest.""" *ended, rest = re.split(r"[\r\n]", data) for piece in ended: text = piece.strip() if text: self.write(stage, text) return rest @staticmethod def _echo(text: str) -> None: """Show a command's text on the console as it wrote it (\\r and \\r\\n kept), in the console's encoding: a Windows console's sys.stdout.buffer takes UTF-8, so the command's own OEM or ANSI bytes would show wrong.""" sys.stdout.flush() # a log() line printed by another stage's thread goes out first buffer = getattr(sys.stdout, "buffer", None) if buffer is None: sys.stdout.write(text) sys.stdout.flush() return buffer.write(text.encode(sys.stdout.encoding or "utf-8", errors="replace")) buffer.flush() def run(self, cmd: list, stage: str, encoding: "str | None" = None, **kw) -> int: """Run cmd with its stdout and stderr through one pipe. Its output is decoded as it comes, with encoding (the one the command writes in; by default what a text-mode pipe decodes with, as on the board), then goes on to the console (so a \\r progress line still redraws in place) and piece by piece to the stage's log. The child keeps the console, so Ctrl+C reaches it as before. Returns the exit code.""" decoder = codecs.getincrementaldecoder(encoding or self.encoding)(errors="replace") with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw) as proc: try: rest = "" while True: chunk = proc.stdout.read1(65536) # what has arrived, not a full buffer: progress shows at once text = decoder.decode(chunk, final=not chunk) # a character split between reads waits for the rest if text: self._echo(text) rest = self._write_pieces(stage, rest + text) if not chunk: break self._write_pieces(stage, rest + "\n") except KeyboardInterrupt: # the child got the Ctrl+C too: a moment to stop on its own, as subprocess.run try: proc.wait(timeout=0.25) except subprocess.TimeoutExpired: pass proc.kill() raise except BaseException: # a failed write: do not leave the child running proc.kill() raise return proc.wait() _plain_logs: "PlainStageLogs | None" = None def log(msg: str) -> None: line = f"{time.strftime('%H:%M:%S')} {msg}" board = leonida_tui.current_board() if board is not None: board.write(leonida_tui.current_stage(), line) return print(line, flush=True) if _plain_logs is not None: _plain_logs.write(leonida_tui.current_stage(), line) def fail(msg: str) -> "None": board = leonida_tui.current_board() if board is not None: stage = leonida_tui.current_stage() board.write(stage, f"ERROR: {msg}") if stage: board.set_status(stage, "failed") # Do not print through the board's stderr proxy (would duplicate into the pane). sys.exit(1) if _plain_logs is not None: _plain_logs.write(leonida_tui.current_stage(), f"ERROR: {msg}") print(f"\nERROR: {msg}", file=sys.stderr) sys.exit(1) def fmt_duration(seconds: float) -> str: """Short wall-clock remaining/elapsed text for progress lines.""" seconds = max(0, int(round(seconds))) if seconds < 60: return f"{seconds}s" minutes, sec = divmod(seconds, 60) if minutes < 60: return f"{minutes}m" if sec == 0 else f"{minutes}m {sec:02d}s" hours, minutes = divmod(minutes, 60) return f"{hours}h {minutes:02d}m" # Rough relative cost of each stage when run alone (docs: translate ~80 min, assets largest on disk, # pipelines ~2.8 h wall). Used only for overall percent while stages overlap; not a schedule. STAGE_WEIGHTS = {"shaders": 40, "assets": 45, "runtime": 2, "pipelines": 55} class Progress: """Thread-safe counter that logs percent and ETA. total 0 logs once and stays quiet.""" def __init__(self, label: str, total: int, *, every_s: float = 5.0): self.label = label self.total = max(0, int(total)) self.done = 0 self.every_s = every_s self._t0 = time.monotonic() self._lock = threading.Lock() self._last_log = 0.0 if self.total == 0: log(f"{label}: nothing to do") else: self._emit(force=True) def tick(self, n: int = 1, *, force: bool = False) -> None: with self._lock: self.done = min(self.total, self.done + max(0, n)) self._emit(force=force or self.done >= self.total) def set(self, done: int, *, force: bool = False) -> None: with self._lock: self.done = min(self.total, max(0, int(done))) self._emit(force=force or self.done >= self.total) def _emit(self, *, force: bool) -> None: if self.total <= 0: return now = time.monotonic() if not force and (now - self._last_log) < self.every_s and self.done < self.total: return self._last_log = now pct = 100 * self.done // self.total elapsed = now - self._t0 if 0 < self.done < self.total: left = elapsed * (self.total - self.done) / self.done eta = f", ~{fmt_duration(left)} left" elif self.done >= self.total and elapsed >= 1: eta = f", {fmt_duration(elapsed)} elapsed" else: eta = "" log(f"{self.label}: {self.done}/{self.total} ({pct}%){eta}") class StageBoard: """Overall build percent from weighted stage completion (stages may finish out of order).""" def __init__(self, stages: list[str]): self.weights = {s: STAGE_WEIGHTS[s] for s in stages if s in STAGE_WEIGHTS} self._done: set[str] = set() self._t0 = time.monotonic() self._lock = threading.Lock() if self.weights: self._announce(f"build: 0% · waiting on {', '.join(self.weights)}") def _announce(self, text: str) -> None: board = leonida_tui.current_board() if board is not None: board.set_summary(text) board.note(text) else: log(text) def complete(self, name: str) -> None: with self._lock: if name not in self.weights or name in self._done: return self._done.add(name) finished = sum(self.weights[s] for s in self._done) total = sum(self.weights.values()) pct = 100 * finished // total if total else 100 left = [s for s in self.weights if s not in self._done] elapsed = time.monotonic() - self._t0 if left and finished: eta = f", ~{fmt_duration(elapsed * (total - finished) / finished)} left" elif not left and elapsed >= 1: eta = f", {fmt_duration(elapsed)} elapsed" else: eta = "" rest = f" · still {', '.join(left)}" if left else "" self._announce(f"build: {pct}% · {name} done{rest}{eta}") def require_folder(flag: str, path: str) -> None: """Fail before any work when a destination, or its nearest existing parent, is a file: os.makedirs would raise a traceback later, and with a separate --work the build reported success without creating --out.""" probe = path while not os.path.exists(probe): parent = os.path.dirname(probe) if parent == probe: return probe = parent if not os.path.isdir(probe): fail(f"{flag} is not a folder: {path}") def below_normal() -> None: """Keep the PC usable while a long build runs.""" if os.name == "nt": import ctypes from ctypes import wintypes k32 = ctypes.windll.kernel32 k32.GetCurrentProcess.argtypes = () k32.GetCurrentProcess.restype = wintypes.HANDLE k32.SetPriorityClass.argtypes = (wintypes.HANDLE, wintypes.DWORD) k32.SetPriorityClass.restype = wintypes.BOOL k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) def run(args: list, hint: str = "", check: bool = True, **kw) -> int: """Run a command, logging it. A non-zero exit stops the build unless check is False; returns the exit code.""" log(" " + " ".join(os.path.basename(str(a)) if i == 0 else str(a) for i, a in enumerate(args))) board = leonida_tui.current_board() # Capture into the stage pane when the LEONIDA board is up and the caller did not set its own pipes. if (board is not None and kw.get("stdout") is None and kw.get("stderr") is None and not kw.get("capture_output")): cmd = [str(a) for a in args] capture = leonida_tui.capture_popen_kwargs() # Caller flags (cwd, env, …) merge in; capture owns the stdio / console-detach bits. extra = {k: v for k, v in kw.items() if k not in ("stdout", "stderr", "capture_output", "text", "universal_newlines", "encoding", "errors", "creationflags")} if "creationflags" in kw and os.name == "nt": capture["creationflags"] = capture.get("creationflags", 0) | int(kw["creationflags"]) proc = subprocess.Popen(cmd, **capture, **extra) code = leonida_tui.pump_process(proc, leonida_tui.current_stage(), board) if check and code != 0: fail(f"{os.path.basename(str(args[0]))} exited with {code}" + (f". {hint}" if hint else "")) return code # Without the board, a build stage's commands also go to its log (PlainStageLogs), with the same rule for pipes. stage = leonida_tui.current_stage() if (_plain_logs is not None and stage in _plain_logs.stages and kw.get("stdout") is None and kw.get("stderr") is None and not kw.get("capture_output")): extra = {k: v for k, v in kw.items() if k not in ("stdout", "stderr", "capture_output", "text", "universal_newlines", "encoding", "errors")} # A caller's encoding= names what the command writes in; the log and the console get the decoded text. code = _plain_logs.run([str(a) for a in args], stage, encoding=kw.get("encoding"), **extra) if check and code != 0: fail(f"{os.path.basename(str(args[0]))} exited with {code}" + (f". {hint}" if hint else "")) return code r = subprocess.run([str(a) for a in args], **kw) if check and r.returncode != 0: fail(f"{os.path.basename(str(args[0]))} exited with {r.returncode}" + (f". {hint}" if hint else "")) return r.returncode def py(tool: str, *args) -> None: run([sys.executable, "-I", os.path.join(TOOLS, tool), *args]) def tool_available(cmd: str) -> bool: """A PATH name, a path, or a whole command line such as 'wsl -e /usr/lib/llvm-21/bin/llvm-mc'.""" try: parts = split_command(cmd) except SystemExit: return False head = parts[0] if parts else "" return bool(head and (shutil.which(head) or os.path.isfile(head))) def appdata_hint(cmd: str) -> str: """Why a tool under AppData may look missing on Windows, or "". `python` from the Python install manager (the app execution alias in WindowsApps) doesn't see folders that other programs create under %LOCALAPPDATA% or %APPDATA%; `py`, or the same python.exe started by its full path, does. scripts\\build_llvm_mc.ps1 used to install llvm-mc.exe to %LOCALAPPDATA%\\Leonida\\llvm-mc.""" if os.name != "nt": return "" path = ntpath.normcase(cmd.strip().strip('"')) for var in ("LOCALAPPDATA", "APPDATA"): base = os.environ.get(var, "").strip() if base and path.startswith(ntpath.normcase(ntpath.join(base, ""))): return (f" LLVM_MC points into %{var}%, which `python` from the Python install manager can't see: copy " "llvm-mc.exe out of AppData (scripts\\build_llvm_mc.ps1 now installs it to " "%USERPROFILE%\\.leonida\\llvm-mc), set LLVM_MC to the new path and reopen the terminal, or start " "make_game.py with `py`.") return "" def spirv_tools_hint() -> str: """Where spirv-as and spirv-val come from on this OS.""" if os.name == "nt" or sys.platform == "darwin": return "install the Vulkan SDK, https://vulkan.lunarg.com/ (then reopen the terminal)" return ("install your distribution's SPIRV-Tools package (Debian and Ubuntu: sudo apt install spirv-tools), " "or the Vulkan SDK, https://vulkan.lunarg.com/") def need(exe: str, hint: str) -> str: if not tool_available(exe): fail(f"'{exe}' was not found on PATH. {hint}") return exe # ---------------------------------------------------------------- check def versions() -> list: out = [] for name in sorted(os.listdir(VERSIONS)): if name.endswith(".json"): with open(os.path.join(VERSIONS, name), encoding="utf-8") as f: out.append(json.load(f)) return out # Small files checked by size to recognise a version without reading anything large. PROBES = ("MicrosoftGame.Config", "Catalog000.bin", "appdata0.rpf") def other_case(folder: str, name: str) -> "str | None": """A file in folder whose name differs from name only in letter case, or None. Only reached when name itself is missing, which on a case-insensitive file system (Windows, macOS by default) means no variant exists either; on Linux a copy whose names were lower-cased on the way is otherwise reported as just missing.""" try: with os.scandir(folder) as it: return next((e.name for e in it if e.name != name and e.name.casefold() == name.casefold()), None) except OSError: return None def probe_mismatches(game: str, version: dict) -> list[str]: """Describe which probe files prevent a version match, using only filesystem metadata.""" files = version["files"] probes = [name for name in PROBES if name in files] if not probes: return ["No version probe files are listed in the manifest."] mismatches = [] for name in probes: expected_size = files[name]["size"] try: info = os.stat(os.path.join(game, name)) except (FileNotFoundError, NotADirectoryError): other = other_case(game, name) mismatches.append(f"Missing {name}." if other is None else f"Missing {name}: there is {other}, but file names are case-sensitive on this file " f"system and the build opens the package's files by their exact names. Rename it " f"to {name}, or copy the package again with its names unchanged.") continue except OSError as error: mismatches.append(f"Cannot read file metadata for {name} ({error.strerror}).") continue if not stat.S_ISREG(info.st_mode): mismatches.append(f"{name} is not a regular file.") elif info.st_size != expected_size: mismatches.append(f"Wrong size for {name} ({info.st_size} bytes, expected {expected_size}).") return mismatches def match_version(game: str): """The supported version this folder is, or None. Only names and sizes are read.""" return next((v for v in versions() if not probe_mismatches(game, v)), None) def manifest_presence(game: str, version: dict) -> tuple[int, list[str], list[str], list[str]]: """How much of a version's manifest the folder holds, from names and sizes only: (files present with the manifest's size, the names that are missing or not a regular file, the names with another size, and "name (reason)" for each file whose metadata can't be read). As in probe_mismatches(), only a name that is not there counts as missing: a file that exists but can't be read (permissions, a drive error) is listed apart.""" matched, missing, wrong, unreadable = 0, [], [], [] for rel, info in version["files"].items(): try: st = os.stat(os.path.join(game, *rel.split("/"))) except (FileNotFoundError, NotADirectoryError): missing.append(rel) continue except OSError as error: unreadable.append(f"{rel} ({error.strerror or error})") continue if not stat.S_ISREG(st.st_mode): missing.append(rel) elif st.st_size != info["size"]: wrong.append(rel) else: matched += 1 return matched, missing, wrong, unreadable def partial_version_message(game: str, version: dict) -> str | None: """The message for a folder that holds at least half of a version's manifest files with their sizes but misses a probe file, so it is an incomplete copy of that version rather than another game. None below half, and None when a probe file is there with another size: a download that stopped early leaves files missing, while a probe with another size (MicrosoftGame.Config above all) is what a complete copy of another build looks like, so load_version() keeps its "not a supported version" message, which lists those sizes.""" total = len(version["files"]) matched, missing, wrong, unreadable = manifest_presence(game, version) if not total or not matched or 2 * matched < total: return None if any(name in wrong for name in PROBES): return None files = version["files"] name = f"{version['title']} {version['version']}" head = f"an incomplete copy of {name}" if missing or wrong else f"{name}, but not every file could be checked" lines = [f"This looks like {head}: {matched} of {total} manifest files are present with matching sizes."] if missing: lines.append(f"{len(missing)} file(s) missing ({sum(files[n]['size'] for n in missing):,} bytes):") lines += [f" missing {n}" for n in missing] if wrong: lines.append(f"{len(wrong)} file(s) with another size (still being copied or downloaded?):") lines += [f" wrong size {n} (expected {files[n]['size']:,} bytes)" for n in wrong] if unreadable: lines.append(f"Cannot read file metadata for {len(unreadable)} file(s) (not counted as missing):") lines += [f" cannot read {n}" for n in unreadable] if missing or wrong: lines.append(f"Finish the download or copy of version {version['version']} into {game}, then build again.") if unreadable: lines.append("Make those files readable for this user (check their permissions and the drive), then build " "again.") return "\n".join(lines) def load_version(game: str) -> dict: reports, candidates = [], [] for version in versions(): mismatches = probe_mismatches(game, version) if not mismatches: return version candidates.append(version) reports.append(f" {version['title']} {version['version']}\n " + "\n ".join(mismatches)) notes = "".join(f"\n{container_message(p, h)}" for p, h in containers_in(game)) # A copy that stopped downloading early misses a probe file but holds most of one version: say which and what # is missing instead of calling it unsupported. The closest version (most files present) is named. partial = max(candidates, key=lambda v: manifest_presence(game, v)[0], default=None) message = partial_version_message(game, partial) if partial else None if message: fail(message + notes) fail("This doesn't look like a supported version of the game. Point --game at the folder that holds " "MicrosoftGame.Config and the .rpf archives.\nSupported:\n" + "\n".join(reports or [" No version manifests found."]) + notes) # ---------------------------------------------------------------- packaged containers # The store keeps the game as one packaged container (.xvc), an XVD file whose contents are encrypted. Nothing here # reads keys or decrypts (docs/design.md, "Ground rules"), so the build can't use it. Pointed at one, or at a folder # that only holds one, the build reads the plain 4 KiB header to say what it is instead of "not found". # Offsets are from the start of the file: xvdtool's XvdHeader + 0x200, the signature in front of it. XVD_MAGIC = b"msft-xvd" XVD_HEADER_SIZE = 0x1000 XVD_ENCRYPTION_DISABLED = 0x2 # VolumeFlags bit CONTAINER_SUFFIXES = (".xvc", ".msixvc", ".xvd") VOLUME_ROOTS = ("/mnt", "/media", "/run/media", "/Volumes") # POSIX: where drives and shares are mounted # udisks2, which mounts removable and internal drives on Linux desktops, puts a drive at //