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 thing it downloads is the third_party/rpf9-explorer submodule, when it is missing. 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 compute programs inside amd_fidelityfx_upscaler_xbox.dll and XboxBvhBuilder.dll 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 /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, 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; full logs land in /logs/. Pass --no-tui (or redirect stdout) for the plain interleaved console. """ import argparse import functools import glob import hashlib import json import ntpath import os import re import shlex import shutil import stat import struct import subprocess import sys import tempfile import threading import time from concurrent.futures import ThreadPoolExecutor 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 mc_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", ] 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) 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) 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 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'.""" cmd = cmd.strip().strip('"') if os.path.isfile(cmd): return True head = cmd.split()[0].strip('"') if cmd.split() 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 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 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): mismatches.append(f"Missing {name}.") 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 load_version(game: str) -> dict: reports = [] for version in versions(): mismatches = probe_mismatches(game, version) if not mismatches: return 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)) 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 //