diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..b6f592e28 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,132 @@ +# Guide for coding agents + +Read this before changing anything. [TODO.md](TODO.md) is the work list, [docs/asset-policy.md](docs/asset-policy.md) +the rule that matters most, and [docs/architecture.md](docs/architecture.md) how the crates fit together. + +## What this is + +Leonida Legacy runs the Xbox Series build of Grand Theft Auto VI natively on Windows, from the user's own copy. The +game's x86-64 code runs unchanged inside our process; we supply the console platform under it: the loader, the +runtime services, a Direct3D 12 back end and a shader recompiler (console GPU code to DXIL, on first use, cached). + +The goal is a console-like experience on PC: straight into play, a steady 30 fps (33 ms a frame) or better, the +console's picture, no stutter, no crashes. + +It is a fork of [fxceless/victory-gta6](https://github.com/fxceless/victory-gta6), itself a fork of +[Marvisak/VIctory](https://github.com/Marvisak/VIctory), renamed to Leonida Legacy. GPL-3.0-or-later. + +## Hard rules + +- **No game data, ever.** No assets, executables or parts of them, shaders in any form, disassembly, dumps, + screenshots, keys, or logs that quote any of it, in commits, issues, pull requests or test fixtures. Tests build + their input with our own code, or read real files from a path in an environment variable and skip when it is unset. + The one exception is `crates/leonida-formats/src/bcpack-tables.bin`; no new ones. +- **Derived data stays outside the repository.** Anything that writes caches, converted data or logs goes through + `leonida_core::ensure_outside_repo` (or `Config::cache_subdir` / `data_subdir`, which call it). +- **The repository is text only.** `cargo xtask policy` allows these extensions: `rs toml md txt lock yml yaml json + hlsl hlsli ps1 cmd sh`, files under 512 KiB, no long hex or base64 runs. No Python files: write helpers in Rust + (`xtask`) or PowerShell. +- **Keep the credits.** Links, upstream commit and issue references (`upstream VIctory 86a5ed6`, `VIctory #1122`) and + the README's credits name VIctory and victory-gta6 on purpose. Don't rename them, and don't remove the license or + copyright notices. +- **Offline by design.** The title must not reach the network. +- **Never touch `leonida.toml`** in a commit. It is the user's own config and git ignores it. + +## Before you start + +- Pick an item from [TODO.md](TODO.md). Search the open pull requests on + [ProjectLeonidaL/leonida](https://github.com/ProjectLeonidaL/leonida) for its ID; if someone has it, pick another. +- Claim it by opening a draft pull request with the ID in the title (`P-3: ...`) as soon as you start. +- One item, one pull request. Touch only the files the item needs. The pull request that finishes an item deletes + its row in `TODO.md` and edits no other row. New work goes in as a new row with the next free ID; never renumber. +- Read the code and [docs/fork-notes.md](docs/fork-notes.md) before guessing: many things were already measured + there. Quote where a number comes from, or say it is a guess. + +## Where things are + +| Path | What | +|------|------| +| `apps/leonida` | the `leonida` command: `run`, `config`, `translate`, `inspect`, `census`, `shader-info` | +| `crates/leonida-core` | config (`leonida.toml`, `LEONIDA_*` env), the asset-policy guard, logging | +| `crates/leonida-loader` | prepares, maps, binds and starts the title image; crash reports | +| `crates/leonida-hle` | console APIs: files, memory, audio, input, saves, DirectStorage | +| `crates/leonida-gpu` | D3D12.X objects, command lists and title memory on host D3D12 | +| `crates/leonida-shader` | console shader containers to DXIL | +| `crates/leonida-formats` | texture layouts and detiling, audio codecs, BCPack | +| `crates/leonida-pe`, `-pipeline`, `-game` | PE reading, the converter cache, game-specific formats and build ids | +| `xtask` | `cargo xtask policy` and `cargo xtask install-hooks` | +| `scripts/rename-from-upstream.ps1` | renames code taken from upstream (`victory` to `leonida`) | +| `run-gta6.ps1` | builds and starts the game with the measured frame-rate switches | +| `docs/` | architecture, asset policy, ray tracing, the fork's measurement log | + +## Commands + +Windows only; the toolchain is pinned in `rust-toolchain.toml`. None of these need the game except the last two. + +```powershell +cargo xtask install-hooks # once: asset-policy check on every commit +cargo check --workspace --all-targets --locked +cargo test -p --locked # while you iterate +cargo test --workspace --locked # before the pull request +cargo clippy --workspace --all-targets --locked -- -D warnings # what CI runs +cargo clippy --workspace --all-targets --all-features --locked -- -D warnings # CI, diagnostics build +cargo xtask policy +cargo build --release -p leonida; target\release\leonida.exe run --execute # asks for the game folder once +cargo build --profile diag -p leonida --features diagnostics # debugging aids, target\diag +``` + +If `cargo xtask` fails with "The directory name is invalid" after the folder was moved, run `cargo clean -p xtask`. + +## Known red, not yours + +`main` already fails CI: 9 clippy errors in `leonida-gpu` (TODO C-1) and the test +`warp_budget_saturates_without_wraparound_and_preserves_draw_fields` (TODO C-2), both inherited from victory-gta6. +Compare against `main` before and after your change; a pull request must not add a new failure or warning. Fixing +those is its own item, not something to fold into another pull request. + +## Conventions + +- **Formatting:** `rustfmt.toml` sets a width of 100, but the tree isn't formatted yet (TODO C-3). Don't run + `cargo fmt` on the whole tree; it rewrites almost every file and conflicts with every open pull request. Keep the + lines you write within 100 columns and formatted the way `rustfmt` would. +- **Match the surrounding code:** its naming, its comment density and its plain-prose comments that say why. +- **Switches:** a new behaviour that might break a picture or lose the device goes behind a `LEONIDA_*` environment + variable, off by default, described in a comment where it is read and in `docs/fork-notes.md`. +- **`shortcut:`** marks code that approximates what the console does. Add the marker when you approximate; remove it + when you replace one with the real behaviour. +- **Unsafe:** `unsafe_op_in_unsafe_fn` is denied. Give every new `unsafe` block a `// SAFETY:` comment. +- **Line endings:** `.ps1` and `.cmd` files are CRLF, everything else LF (`.gitattributes`). + +## Measuring + +- Measure on your own machine before and after, in the same scene, and put both figures in the pull request with + your CPU, GPU and driver. Most numbers in the docs come from one RTX 4070. +- Post figures, never log files: logs can quote game data. +- The first run after a change to `leonida-shader` re-translates every shader (the cache keys on the translator's + source), so it stutters. Don't measure that run. + +## Upstream + +A fresh clone has neither upstream as a remote. Add them once: + +```powershell +git remote add upstream https://github.com/fxceless/victory-gta6.git +git remote add victory https://github.com/Marvisak/VIctory.git +``` + +To bring a fix in: + +```powershell +git fetch victory +git cherry-pick +powershell -ExecutionPolicy Bypass -File scripts\rename-from-upstream.ps1 +cargo check --workspace --all-targets --locked +``` + +One upstream commit (or a few related ones) per pull request, with the upstream hash in the description. + +## Commits and pull requests + +- Conventional Commits, short and specific: `fix(gpu): ...`, `feat: ...`, `docs: ...`. +- Pull requests go to `ProjectLeonidaL/leonida`, branch `main`. Put the TODO ID in the title, say what you tested + and on which GPU and driver, and say if it was AI-assisted. diff --git a/README.md b/README.md index 430e0c886..26e625971 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,16 @@ The first run asks for the folder of your copy of the game (the one with `Micros `leonida.toml`, which git ignores. `leonida config` shows what is set, and `leonida.example.toml` lists the other settings. +`run-gta6.ps1` does the build and the run in one step, with the frame-rate switches that measured faster (they are +off by default). It asks for the game folder too, and whether to remember it: + +```powershell +powershell -ExecutionPolicy Bypass -File . un-gta6.ps1 +``` + +`measure-gta6.ps1` does the same with the diagnostics build, the frame log and the card meter on, and saves +everything the game prints to `%LOCALAPPDATA%\leonida\logs`. + Saves, settings and `crashes.log` are kept in `%LOCALAPPDATA%\leonida\data`, derived data in `%LOCALAPPDATA%\leonida\cache`. diff --git a/TODO.md b/TODO.md new file mode 100644 index 000000000..0b430fd53 --- /dev/null +++ b/TODO.md @@ -0,0 +1,87 @@ +# TODO + +The goal: a console-like experience on PC. The game starts straight into play, holds a steady 30 fps (the console's +33 ms frame) or better, looks like it does on the console, and doesn't stutter or crash. + +## How to use this list + +- **One item, one pull request.** Keep it small, and touch only the files the item needs. +- **Claim an item by opening a draft pull request** with its ID in the title (for example `P-3: ...`) as soon as + you start. Search the open pull requests for the ID first. If someone already has it, pick another one. +- **The pull request that finishes an item deletes that item's row.** Don't edit other rows in it. +- **New item:** add a row at the end of its section with the next free ID. Never renumber. +- **Needs:** `game` means your own copy of the game, `GPU` a real Direct3D 12 card, `-` nothing beyond Rust. +- **Numbers** come from [docs/fork-notes.md](docs/fork-notes.md) unless a row says otherwise, and most were measured + on one RTX 4070. Measure on your machine before and after a change, and put both figures in the pull request. + Post figures, never log files: logs can quote game data (see [docs/asset-policy.md](docs/asset-policy.md)). + +## Rendering: looks like the console + +| ID | Task | Where | Needs | +|----|------|-------|-------| +| R-1 | Everything out of direct sun is black: the ray-traced bounce light and lamp and sun shadows don't run. The structure-builder programs translate and 59 of 64 trace programs translate, but nothing is lit by them yet. | [docs/fork-ray-tracing.md](docs/fork-ray-tracing.md), `leonida-shader`, `leonida-gpu` | game, GPU | +| R-2 | The first gameplay room is sometimes not drawn after the cutscene hands over to gameplay. | `leonida-gpu` | game, GPU | +| R-3 | Washed-out frames turn up in about 6 of 21 runs with no switch on. Cause not known. | `leonida-gpu` | game, GPU | +| R-4 | An indirect compute pass asks for about 77,500 thread groups in x, where one dispatch runs 65,535. The rest is cut off; split the dispatch. | `leonida-gpu` | game, GPU | +| R-5 | Real queries, depth bounds, HDR output and scaling are missing. | `leonida-gpu` | game, GPU | +| R-6 | Render-target metadata planes are not handled. | `leonida-formats`, `leonida-gpu` | game, GPU | +| R-7 | Shaders that don't translate drop their draws. Count them again on this tree with `leonida translate --list` (the upstream counts in the fork notes are from 2026-11-23) and work down the list. | `leonida-shader` | game | +| R-8 | Mapping pool pages in a row as one view made remaps cheaper but broke texture streaming (black or red faces, garbage in 3 of 3 runs). Find out why before trying it again; see P-4. | `leonida-hle` (`xmem`) | game, GPU | + +## Performance: a steady 30 fps + +| ID | Task | Where | Needs | +|----|------|-------|-------| +| P-1 | Measure the frame-rate switches that `run-gta6.ps1` sets on more cards (AMD, NVIDIA 30 and 40 series, Intel). Turn on by default the ones that help everywhere without a device loss. | `leonida-gpu` | game, GPU | +| P-2 | The per-record clamp before indirect draws is most of the card's time. About 2,400 indirect commands a frame still get a clamp pass, and about 1,000 mesh records sit scattered through a 100 MB argument buffer. | `leonida-gpu` | game, GPU | +| P-3 | Copies between the PC's memory and the card's are most of the submit thread's time. | `leonida-gpu` | game, GPU | +| P-4 | While the camera moves, about half the time goes to frames of about 490 ms in which the card is idle for about 330 ms. The title's page-mapping copies (`CopyPageMappingsBatchX` to `xmem::map_alias`) cost 32 ms of every cutscene frame and 246 ms of a streaming frame. | `leonida-hle` | game | +| P-5 | The title paces itself with `monitorx` / `mwaitx`, which only AMD processors have: about 280,000 emulated exceptions a second on an Intel processor. Find a cheaper way. | `leonida-loader` | game; an Intel CPU to measure | +| P-6 | Translated shaders are too expensive: about 50 ms of a 97 ms frame are the title's own passes as translated. With every pass of the layer's gone, the first rooms would still be near 20 fps. | `leonida-shader` | game, GPU | +| P-7 | The first run stutters while shaders translate and pipelines build. Warm the cache before play (`leonida translate --warm`), with progress shown, so the first session starts smooth. | `apps/leonida`, `run-gta6.ps1` | game | +| P-8 | About 24 GB of memory is in use during play. | all | game | +| P-9 | A 12 GB card is full from the first world frame (9.2 of a 10.3 GB budget), and thousands of textures are dropped and made again. Levels on demand (`LEONIDA_LEVELS_ON_DEMAND=1`) saved 3.1 GB in one run; test it more and make it the default if it holds. | `leonida-gpu` | game, GPU | + +## Stability + +| ID | Task | Where | Needs | +|----|------|-------|-------| +| S-1 | One device loss with indirect draw windows on (`LEONIDA_INDIRECT_WINDOW=1`), 44 s into the world. Cause not found. Don't combine it with `LEONIDA_CARD_FETCH_INFLIGHT=1`. | `leonida-gpu` | game, GPU | +| S-2 | A session past the first rooms lost the device in the open world with no driver entry ("device removed"). | `leonida-gpu` | game, GPU | +| S-3 | Menu frame pacing drifts on one screen in release builds. | `leonida-gpu` | game, GPU | + +## Audio, input and system services + +| ID | Task | Where | Needs | +|----|------|-------|-------| +| A-1 | Reverb is silent. | `leonida-hle` (audio) | game | +| A-2 | Opus decoding is not checked against what the title expects. | `leonida-formats`, `leonida-hle` | game | +| A-3 | Trigger rumble. | `leonida-hle` (input) | game, an Xbox pad | +| A-4 | Speech is silent. The text entry dialog and the title relaunching itself are untested live. | `leonida-hle` | game | +| A-5 | Series S mode stops at the loading screen. | all | game | + +## Console-like experience + +| ID | Task | Where | Needs | +|----|------|-------|-------| +| U-1 | One step from download to playing: build, warm the cache (P-7) and run, with no terminal knowledge needed. | `run-gta6.ps1` | - | +| U-2 | Fullscreen and borderless window, and a choice of output resolution. | `leonida-gpu` | GPU | +| U-3 | The frame-rate switches as settings in `leonida.toml` instead of environment variables, with the tested ones on by default. | `leonida-core` (config) | - | +| U-4 | Pad first: after launch, the game is playable without touching the keyboard. | `leonida-hle` (input) | game | +| U-5 | Clear messages for the common failures: no AVX2, missing title DLLs, Windows error 1455 (not enough commit). Upstream VIctory has commits for the first two; see UP-1. | `apps/leonida` | - | + +## Code health + +| ID | Task | Where | Needs | +|----|------|-------|-------| +| C-1 | CI is red on clippy: `resource.rs:2553` (`placed_filler_twins` unused), `indirect.rs:2453` (`depth_written` never read), `fpsbox.rs:174` (`contains_key` then `insert`), `draw.rs:2577` (`sort_unstable_by_key`), `queue.rs:672`, `shadow.rs:2803` and `shadow.rs:3325` (`is_multiple_of`). All in `leonida-gpu`, all inherited from victory-gta6. | `leonida-gpu` | - | +| C-2 | Failing test `indirect::tests::warp_budget_saturates_without_wraparound_and_preserves_draw_fields`, inherited from victory-gta6. Upstream VIctory `4ab20fc` ("the indirect budget is charged in record order and no longer wraps") may fix it; not checked. | `leonida-gpu` | - | +| C-3 | `cargo fmt --check` reports about 1,420 differences. Run `cargo fmt` once, in a pull request of its own, at a moment when no other pull request is open (it touches almost every file), then add the check to CI. | all | - | +| C-4 | 163 `shortcut:` markers where the code approximates the console (79 in `leonida-gpu`, 55 in `leonida-shader`, 23 in `leonida-hle`, 4 in `leonida-formats`, 2 in `leonida-loader`). Replace them with the console's real behaviour, one per pull request. | all | game | +| C-5 | Some style lints are switched off for this fork in the workspace `Cargo.toml`. Turn them back on and tidy the code they flag. | `Cargo.toml` | - | + +## Upstream + +| ID | Task | Where | Needs | +|----|------|-------|-------| +| UP-1 | Upstream VIctory has 265 commits this fork lacks (counted on 2026-11-25 with `git cherry`). Go through them and cherry-pick the useful ones: `git remote add victory https://github.com/Marvisak/VIctory.git`, `git fetch victory`, `git cherry-pick `, then `scripts/rename-from-upstream.ps1` and `cargo check --workspace --all-targets`. Candidates by title, none tried yet: `4ab20fc` (indirect budget, C-2), `534e1dd` (AVX2 check), `e9cb14a` (missing title DLLs message), `42961e8` (warns when GPU hang settings would freeze the PC), `a3acc87` (checks the required startup archive). Many of the GPU commits touch code victory-gta6 changed, so expect conflicts there. | whole tree | - | diff --git a/apps/leonida/src/main.rs b/apps/leonida/src/main.rs index e561b60be..6964300f5 100644 --- a/apps/leonida/src/main.rs +++ b/apps/leonida/src/main.rs @@ -9,7 +9,7 @@ mod run; mod shader; mod translate; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use clap::{Parser, Subcommand, ValueEnum}; @@ -116,7 +116,11 @@ enum Command { title_args: Vec, }, /// Show the resolved configuration and check it. - Config, + Config { + /// First save this folder as the game folder in leonida.toml. + #[arg(long)] + game_dir: Option, + }, } #[derive(Clone, Copy, ValueEnum)] @@ -191,7 +195,14 @@ fn main() -> Result<()> { }; run::run(&exe, unimplemented, strict, execute, console) } - Command::Config => show_config(), + Command::Config { game_dir } => { + if let Some(dir) = game_dir { + check_game_dir(&dir)?; + let saved = leonida_core::Config::save_game_dir(&dir)?; + println!("game folder saved to {}", saved.display()); + } + show_config() + } } } @@ -233,12 +244,8 @@ fn ask_game_dir() -> Result { if dir.as_os_str().is_empty() { continue; } - if !dir.join("MicrosoftGame.config").is_file() { - println!("no MicrosoftGame.config in {}, try again:", dir.display()); - continue; - } - if let Err(e) = leonida_core::ensure_outside_repo(&dir) { - println!("{e}"); + if let Err(e) = check_game_dir(&dir) { + println!("{e:#}, try again:"); continue; } let saved = leonida_core::Config::save_game_dir(&dir)?; @@ -247,6 +254,18 @@ fn ask_game_dir() -> Result { } } +/// A game folder holds the title's MicrosoftGame.config and lies outside +/// the repository. +fn check_game_dir(dir: &Path) -> Result<()> { + anyhow::ensure!( + dir.join("MicrosoftGame.config").is_file(), + "no MicrosoftGame.config in {}", + dir.display() + ); + leonida_core::ensure_outside_repo(dir)?; + Ok(()) +} + /// The `Name` of the manifest's first `` element (not /// ``, which holds them). fn manifest_exe(manifest: &str) -> Option<&str> { diff --git a/measure-gta6.ps1 b/measure-gta6.ps1 new file mode 100644 index 000000000..866b58cdb --- /dev/null +++ b/measure-gta6.ps1 @@ -0,0 +1,79 @@ +# Like run-gta6.ps1, but with the diagnostics build: frame log and card meter +# (per pipeline) on, and everything the emulator prints saved to a log file. +# Logs go under %LOCALAPPDATA%\leonida\logs (game-derived output stays out of the repo). +# +# The first time, it asks for the folder of your copy of the game (the one with +# MicrosoftGame.config in it) and offers to remember it in leonida.toml, which git ignores. +# +# powershell -ExecutionPolicy Bypass -File .\measure-gta6.ps1 +# powershell -ExecutionPolicy Bypass -File .\measure-gta6.ps1 -GameDir 'D:\Games\GTA VI' # this run only + +param( + [string]$GameDir = '' +) + +$ErrorActionPreference = 'Stop' + +function Test-GameDir([string]$dir) { + $dir -ne '' -and (Test-Path -LiteralPath (Join-Path $dir 'MicrosoftGame.config') -PathType Leaf) +} + +# leonida.toml is read from the current folder. +Push-Location $PSScriptRoot +try { + cargo build --profile diag -p leonida --features diagnostics + if ($LASTEXITCODE -ne 0) { throw "cargo build failed (exit $LASTEXITCODE); is leonida.exe still running?" } + $exe = Join-Path $PSScriptRoot 'target\diag\leonida.exe' + + if ($GameDir -ne '') { + if (-not (Test-GameDir $GameDir)) { throw "no MicrosoftGame.config in $GameDir" } + $dir = $GameDir + } else { + # What leonida.toml or LEONIDA_GAME_DIR already says. + $out = & $exe config + if ($LASTEXITCODE -ne 0) { throw "leonida config failed (exit $LASTEXITCODE); check leonida.toml" } + $dir = '' + $line = $out | Where-Object { $_ -match '^game_dir\s*:' } | Select-Object -First 1 + if ($line -match '^game_dir\s*:\s*(.+?)\s*$') { $dir = $Matches[1] -replace '\s+\(does not exist\)$', '' } + + if (-not (Test-GameDir $dir)) { + if ($dir -ne '' -and $dir -ne '(not set)') { Write-Host "The saved game folder has no MicrosoftGame.config: $dir" } + do { + $dir = (Read-Host 'Folder of your copy of the game (the one with MicrosoftGame.config in it)').Trim().Trim('"') + if (-not (Test-GameDir $dir)) { Write-Host "No MicrosoftGame.config in '$dir', try again." } + } until (Test-GameDir $dir) + + $answer = Read-Host 'Remember this folder for next time? [Y/n]' + if ($answer.Trim() -match '^(y|yes)?$') { + & $exe config --game-dir $dir | Out-Null + if ($LASTEXITCODE -ne 0) { throw "saving the game folder failed (exit $LASTEXITCODE)" } + Write-Host 'Saved to leonida.toml.' + } + } + } + $env:LEONIDA_GAME_DIR = $dir + + $env:LEONIDA_ASYNC_SUBMIT = '1' + $env:LEONIDA_QUEUE2 = '1' + $env:LEONIDA_INDIRECT_WINDOW = '1' + $env:LEONIDA_COPY_PLAIN = '1' + $env:LEONIDA_JOIN_PARTS = '1' + $env:LEONIDA_BACK_OWN_VIEW = '1' + $env:LEONIDA_INDIRECT_GATHER = '1' + $env:LEONIDA_CARD_REHASH_RUNS = '1' + + $env:LEONIDA_FRAME_LOG = '1' + $env:LEONIDA_CARD_METER = '1' + $env:LEONIDA_CARD_METER_PIPELINES = '1' + + $logDir = Join-Path $env:LOCALAPPDATA 'leonida\logs' + New-Item -ItemType Directory -Force $logDir | Out-Null + $log = Join-Path $logDir ("measure-{0:yyyyMMdd-HHmmss}.log" -f (Get-Date)) + Write-Host "logging to $log" + + # The emulator logs to stderr; PowerShell 5.1 wraps those lines as errors, so don't stop on them. + $ErrorActionPreference = 'Continue' + & $exe run --execute 2>&1 | ForEach-Object { "$_" } | Tee-Object -FilePath $log +} finally { + Pop-Location +} diff --git a/run-gta6.ps1 b/run-gta6.ps1 new file mode 100644 index 000000000..ced6b0789 --- /dev/null +++ b/run-gta6.ps1 @@ -0,0 +1,69 @@ +# Builds Leonida Legacy and starts the game with the frame-rate switches measured to help +# (all off by default). Remove LEONIDA_INDIRECT_WINDOW if the device gets lost. +# +# The first time, it asks for the folder of your copy of the game (the one with +# MicrosoftGame.config in it) and offers to remember it in leonida.toml, which git ignores. +# +# powershell -ExecutionPolicy Bypass -File .\run-gta6.ps1 +# powershell -ExecutionPolicy Bypass -File .\run-gta6.ps1 -GameDir 'D:\Games\GTA VI' # this run only +# +# To change the remembered folder: target\release\leonida.exe config --game-dir + +param( + [string]$GameDir = '' +) + +$ErrorActionPreference = 'Stop' + +function Test-GameDir([string]$dir) { + $dir -ne '' -and (Test-Path -LiteralPath (Join-Path $dir 'MicrosoftGame.config') -PathType Leaf) +} + +# leonida.toml is read from the current folder. +Push-Location $PSScriptRoot +try { + cargo build --release -p leonida + if ($LASTEXITCODE -ne 0) { throw "cargo build failed (exit $LASTEXITCODE); is leonida.exe still running?" } + $exe = Join-Path $PSScriptRoot 'target\release\leonida.exe' + + if ($GameDir -ne '') { + if (-not (Test-GameDir $GameDir)) { throw "no MicrosoftGame.config in $GameDir" } + $dir = $GameDir + } else { + # What leonida.toml or LEONIDA_GAME_DIR already says. + $out = & $exe config + if ($LASTEXITCODE -ne 0) { throw "leonida config failed (exit $LASTEXITCODE); check leonida.toml" } + $dir = '' + $line = $out | Where-Object { $_ -match '^game_dir\s*:' } | Select-Object -First 1 + if ($line -match '^game_dir\s*:\s*(.+?)\s*$') { $dir = $Matches[1] -replace '\s+\(does not exist\)$', '' } + + if (-not (Test-GameDir $dir)) { + if ($dir -ne '' -and $dir -ne '(not set)') { Write-Host "The saved game folder has no MicrosoftGame.config: $dir" } + do { + $dir = (Read-Host 'Folder of your copy of the game (the one with MicrosoftGame.config in it)').Trim().Trim('"') + if (-not (Test-GameDir $dir)) { Write-Host "No MicrosoftGame.config in '$dir', try again." } + } until (Test-GameDir $dir) + + $answer = Read-Host 'Remember this folder for next time? [Y/n]' + if ($answer.Trim() -match '^(y|yes)?$') { + & $exe config --game-dir $dir | Out-Null + if ($LASTEXITCODE -ne 0) { throw "saving the game folder failed (exit $LASTEXITCODE)" } + Write-Host 'Saved to leonida.toml.' + } + } + } + $env:LEONIDA_GAME_DIR = $dir + + $env:LEONIDA_ASYNC_SUBMIT = '1' + $env:LEONIDA_QUEUE2 = '1' + $env:LEONIDA_INDIRECT_WINDOW = '1' + $env:LEONIDA_COPY_PLAIN = '1' + $env:LEONIDA_JOIN_PARTS = '1' + $env:LEONIDA_BACK_OWN_VIEW = '1' + $env:LEONIDA_INDIRECT_GATHER = '1' + $env:LEONIDA_CARD_REHASH_RUNS = '1' + + & $exe run --execute +} finally { + Pop-Location +}