diff --git a/d3d12/crates/leonida-gpu/src/compose.rs b/d3d12/crates/leonida-gpu/src/compose.rs index 798db1d8da..18aafe39f5 100644 --- a/d3d12/crates/leonida-gpu/src/compose.rs +++ b/d3d12/crates/leonida-gpu/src/compose.rs @@ -11,12 +11,10 @@ use windows::core::{PCSTR, s}; use crate::host::Host; const SOURCE: &str = r#" -#define RS "DescriptorTable(SRV(t0, numDescriptors=2), visibility=SHADER_VISIBILITY_PIXEL), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)" Texture2D scene : register(t0); Texture2D over : register(t1); SamplerState smooth_ : register(s0); struct V { float4 at : SV_Position; float2 uv : TEXCOORD0; }; -[RootSignature(RS)] V vs(uint id : SV_VertexID) { V v; v.uv = float2((id << 1) & 2, id & 2); @@ -58,7 +56,6 @@ float clean1(float x) { float3 clean(float3 x) { return float3(clean1(x.r), clean1(x.g), clean1(x.b)); } -[RootSignature(RS)] float4 ps(V v) : SV_Target { float3 s = sharpened(v.uv); float4 o = over.SampleLevel(smooth_, v.uv, 0); @@ -137,11 +134,41 @@ impl Composer { ); // SAFETY: the blobs' own bytes, alive through the calls. unsafe { - let bytes = |b: &ID3DBlob| { - std::slice::from_raw_parts(b.GetBufferPointer().cast::(), b.GetBufferSize()) - }; let device = &host.device; - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes(&vs))?; + let ranges = [D3D12_DESCRIPTOR_RANGE1 { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 2, + BaseShaderRegister: 0, + RegisterSpace: 0, + Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE, + OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND, + }]; + let parameters = [D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 { + NumDescriptorRanges: ranges.len() as u32, + pDescriptorRanges: ranges.as_ptr(), + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + }]; + let samplers = [D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + MipLODBias: 0.0, + MaxAnisotropy: 16, + ComparisonFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, + BorderColor: D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + MinLOD: 0.0, + MaxLOD: f32::MAX, + ShaderRegister: 0, + RegisterSpace: 0, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }]; + let root = crate::host::root_signature(device, ¶meters, &samplers)?; let code = |b: &ID3DBlob| D3D12_SHADER_BYTECODE { pShaderBytecode: b.GetBufferPointer(), BytecodeLength: b.GetBufferSize(), diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index d616ed59e8..35f0197b13 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -1686,6 +1686,33 @@ pub(crate) fn compile( Ok(bytes.to_vec()) } +pub(crate) fn root_signature( + device: &ID3D12Device, + parameters: &[D3D12_ROOT_PARAMETER1], + samplers: &[D3D12_STATIC_SAMPLER_DESC], +) -> windows::core::Result { + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: parameters.len() as u32, + pParameters: if parameters.is_empty() { std::ptr::null() } else { parameters.as_ptr() }, + NumStaticSamplers: samplers.len() as u32, + pStaticSamplers: if samplers.is_empty() { std::ptr::null() } else { samplers.as_ptr() }, + Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }, + }, + }; + let mut blob: Option = None; + unsafe { + D3D12SerializeVersionedRootSignature(&desc, &mut blob, None)?; + let blob = blob.ok_or_else(windows::core::Error::empty)?; + let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()); + device.CreateRootSignature(0, bytes) + } +} + impl PlanePass { /// The root signature and pipeline for a twin of 16-bit steps (`steps`) /// or of floats and the depth format `format`. diff --git a/d3d12/crates/leonida-gpu/src/host/trainer.rs b/d3d12/crates/leonida-gpu/src/host/trainer.rs index f0c4d4fa33..b61e4a83af 100644 --- a/d3d12/crates/leonida-gpu/src/host/trainer.rs +++ b/d3d12/crates/leonida-gpu/src/host/trainer.rs @@ -36,11 +36,9 @@ use leonida_menu::paint::{LEFT, TOP}; use super::{Host, HostList, transition}; const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=8, b0), DescriptorTable(SRV(t0))" cbuffer Place : register(b0) { float2 target; float2 origin; float2 size; float band_top; float band_bottom; }; Texture2D menu : register(t0); struct V { float4 pos : SV_Position; }; -[RootSignature(RS)] V vs(uint id : SV_VertexID) { float2 corner = float2(id & 1, id >> 1); float2 px = origin + corner * size; @@ -48,7 +46,6 @@ V vs(uint id : SV_VertexID) { v.pos = float4(px / target * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); return v; } -[RootSignature(RS)] float4 ps(V v) : SV_Target { float2 p = v.pos.xy - origin; int layer = (p.y >= band_top && p.y < band_bottom) ? 1 : 0; @@ -105,13 +102,6 @@ fn compile( code.ok_or_else(windows::core::Error::empty) } -fn bytes(blob: &ID3DBlob) -> &[u8] { - // SAFETY: the blob's own bytes, alive as long as it is. - unsafe { - std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()) - } -} - /// The pipeline for one target format. struct Pipeline { root: ID3D12RootSignature, @@ -122,10 +112,36 @@ struct Pipeline { fn pipeline(device: &ID3D12Device, format: DXGI_FORMAT) -> windows::core::Result { let vs = compile(windows::core::s!("vs"), windows::core::s!("vs_5_1"))?; let ps = compile(windows::core::s!("ps"), windows::core::s!("ps_5_1"))?; - // SAFETY: the blobs' own bytes (the root signature is inside them); - // plain object creation. + // SAFETY: the blobs' own bytes; plain object creation. unsafe { - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes(&vs))?; + let ranges = [D3D12_DESCRIPTOR_RANGE1 { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE, + OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND, + }]; + let parameters = [ + D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 8 }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 { + NumDescriptorRanges: ranges.len() as u32, + pDescriptorRanges: ranges.as_ptr(), + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + ]; + let root = super::root_signature(device, ¶meters, &[])?; let mut blend = D3D12_BLEND_DESC::default(); blend.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC { BlendEnable: true.into(), diff --git a/docs/boot.md b/docs/boot.md index ecd0ddc37c..36bf8bd0c8 100644 --- a/docs/boot.md +++ b/docs/boot.md @@ -177,7 +177,8 @@ and the one line that names the cause is `CreateRootSignature`. Copying the DLLs a Proton prefix installs is not enough on its own: Wine keeps preferring its own copy next to -them. Name them in the overrides. +them. Name them in the overrides. For the D3D12 runtime (`leonida.exe`), `scripts/play-linux.sh` does both itself, +under a Proton or the system's Wine ([linux.md](linux.md#the-d3d12-runtime-leonidaexe-under-wine)). ```bash GE=$HOME/GE-Proton11-13-x86_64/files/lib/wine diff --git a/docs/launcher.md b/docs/launcher.md index d58929f72c..0f6efb0d9c 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -15,16 +15,24 @@ Standard library only (`tools/leonida_launcher.py`). ## Pages -- **Play**: PLAY runs `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\play-d3d12.ps1 -Game - -Data ` plus the switches chosen in Settings (on Linux `scripts/play-linux.sh /game_scarlett_master.exe`, - with `--series-x` if chosen). The script's output goes into the log box. The state line reads a few of the script's - own messages: Starting, Building the runtime, Preparing shaders, Running, Exited with code N (a guess from the text; - the log is the truth). Only one thing runs at a time: while it runs PLAY is replaced by Stop, which, after a - confirmation, ends the process and everything it started (`taskkill /T /F`; on Linux the process group). +- **Play**: PLAY runs `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\play-d3d12.ps1 -Game -Data + ` plus the switches chosen in Settings (on Linux `scripts/play-linux.sh /game_scarlett_master.exe` + with `--series-x` and `--log` if chosen; without a usable Proton or Wine, PLAY opens Settings). The script's output + goes into the log box. The state line reads a few of the script's own messages: Starting, Building the runtime, + Preparing shaders, Running, Exited with code N (a guess from the text; the log is the truth). Only one thing runs at a + time: while it runs PLAY is replaced by Stop, which, after a confirmation, ends the process and everything it started + (`taskkill /T /F`; on Linux the process group). - **Settings**: the game folder (a picker, and a check that `game_scarlett_master.exe` is in it), the data folder - (empty = the script's default), the mods folder, and the options of `play-d3d12.ps1`: DLSS (off is `-NoDlss`), + (empty = the script's default), the mods folder and the options of `play-d3d12.ps1`: DLSS (off is `-NoDlss`), `-RayTracing`, `-SmoothMotion`, shader preparation (off is `-NoPrecompile`), `-SeriesX`, `-Quality`, `-Resolution` - (default = none), `-Capture`, `-Log`. On Linux only the game folder and Series X are used. + (default = none), `-Capture`, `-Log`. Log to a file (`-Log`, on Linux `--log`) writes the runtime's error output to + `play-.log` in the logs folder and keeps the five newest. +- **Settings on Linux**: only the game folder, Proton or Wine, Series X and Log to a file are used. The Proton or Wine + list starts with "Automatic" (the default: the script's own pick, named beside it), then the usable Proton builds + (highest version first) and "System Wine" when `wine` is on `PATH`; a named entry is stored as that folder. Browse + picks another Proton folder. A line below the list appears only when a folder picked with Browse cannot be used. + How the script picks and runs a Proton or Wine: + [linux.md](linux.md#the-d3d12-runtime-leonidaexe-under-wine). - **Mods**: the `mods\*\mod.json` of the mods folder (this repository's `mods` unless changed), with the enabled flag written back as the mod manager does it (`tools/leonida_mods.py`); a button opens that manager. - **Saves**: the D3D12 runtime's saves under the data folder, `\data\7952987A\saves\\\~`, built yourself from this checkout's `runtime/xma_decoder` with the command in [runtime/xma_decoder/README.md](../runtime/xma_decoder/README.md). +### The D3D12 runtime (`leonida.exe`) under Wine + +`scripts/play-linux.sh` and PLAY in the launcher start `leonida.exe`, the D3D12 runtime in `d3d12/`. `./Build.sh` +does not build it. On Linux: + +```sh +cargo install --locked cargo-xwin # once; also needs clang and lld +XWIN_ACCEPT_LICENSE=1 sh scripts/build-d3d12-linux.sh # leonida.exe, VKD3D-Proton, DXVK's dxgi.dll, d3dcompiler_47 +sh scripts/play-linux.sh /path/to/game_scarlett_master.exe +``` + +cargo-xwin downloads Microsoft's CRT and Windows SDK on its first run. `XWIN_ACCEPT_LICENSE=1` accepts their licence; +without it the script stops before downloading. The runtime lands in `d3d12/target/x86_64-pc-windows-msvc/diag/`, +VKD3D-Proton in `d3d12/target/vkd3d-proton/` (fetching it needs Python 3.14 or newer), DXVK's `dxgi.dll` in +`d3d12/target/dxvk/` (`scripts/fetch_dxvk.py`, which fetches it on its own too). The fetch scripts write +`SOURCE.txt` last, and the build script fetches again while a folder lacks one of its files. `play-linux.sh` looks for +`leonida.exe` beside itself, then under `d3d12/target/`. `LEONIDA_RUNTIME` and `LEONIDA_VKD3D` select other files. + +The script takes `LEONIDA_PROTON` (a Proton folder or its `files/bin/wine`), else `LEONIDA_WINE` (a Wine program, such +as `wine`), else the usable Proton build with the highest version, else `wine` on `PATH`. Every folder with +`files/bin/wine` counts as a Proton build, whatever its name, in Steam's `compatibilitytools.d` and `steamapps/common` +(all libraries, Flatpak and Snap too), `STEAM_EXTRA_COMPAT_TOOLS_PATHS` and the system's `compatibilitytools.d`; it is +usable when it also has `files/lib/wine` or `files/lib64/wine`; others are left out. Builds are ranked by the numbers +in their version. `--find-proton` prints the Proton or Wine the script would use, `--list-protons` every usable build; +neither changes anything. + +The game needs DXVK's `dxgi.dll`: with Wine's own (on `wined3d`) it crashes when it creates its swap chain, and Wine's +own `d3d12.dll` (vkd3d) creates no device for it. The `dxgi.dll` comes from `LEONIDA_DXVK` (a folder with a 64-bit +`dxgi.dll`) when it is set, else from the Proton; if it has none, or under the system's Wine, from the package (`dxvk/` +beside the script, then `d3d12/target/dxvk/`), else the distribution's DXVK (under `/usr/share/dxvk` or +`/usr/lib/dxvk`), else another Proton. Without any, the script stops and names `fetch_dxvk.py`. It copies that dxgi.dll +and the bundled VKD3D-Proton into its own prefix (`LEONIDA_WINEPREFIX`, made and updated with the Wine in use) and sets +`WINEDLLOVERRIDES=d3d12,d3d12core,dxgi=n`, after any overrides already set, since Wine keeps the last one for a DLL +([boot.md](boot.md#under-wine-on-linux)). Under a Proton it puts the build's +libraries first in `WINEDLLPATH` and `LD_LIBRARY_PATH`, as Proton's own `proton` script does. VKD3D-Proton's shader +cache goes to `/vkd3d-proton`. With `VKD3D_SHADER_CACHE_PATH=0` it keeps none (the same as +`VKD3D_CONFIG=pipeline_library_app_cache`), and the title's D3D12 pipeline library then holds the SPIR-V and the +driver's pipeline cache. + +Wine's own `d3dcompiler_47.dll` rejects the runtime's indirect-argument clamp (`E5005`, `InterlockedOr` on a +`RWByteAddressBuffer`), and then every indirect draw is dropped: the intro shows, gameplay and cutscenes have no 3D. +`play-linux.sh` installs Microsoft's 64-bit `d3dcompiler_47.dll` into its prefix (`d3dcompiler_47=n`), from +`LEONIDA_D3DCOMPILER`, else `d3dcompiler/` beside the script, else `d3d12/target/d3dcompiler/`, else fetched there by +`scripts/fetch_d3dcompiler.py` (pinned NuGet package and SHA-256). Without it the script warns and starts anyway. + +VKD3D-Proton releases without dxil-spirv's new structurizer turn some of the title's compute shaders into invalid +SPIR-V, and the Vulkan driver crashes on them (`vkCreateComputePipelines`, exception `0xc0000005`). A `d3d12core.dll` +counts as having it when it names the `legacy_structurizer` option (VKD3D-Proton `v3.1-22` to `v3.1-96`) or when its +build is `v3.1-22` or later: `v3.1-97` removed the legacy structurizer and with it that name. The build is read as +`v3.1-97-g` from the DLL or the `version` file beside it, else as `vkd3d-1.1--g`, the form Proton +writes in that file (`v3.1` is `vkd3d-1.1-5686`), else from the release number the DLL carries (3.2 on). When the +bundled `d3d12core.dll` lacks it, `play-linux.sh` takes the newest such VKD3D-Proton among the Proton in use and the +other Protons found, the Proton in use first among equal builds, also when `LEONIDA_PROTON` chose the Proton. If none +has it, the script warns and uses the bundled one. `LEONIDA_VKD3D` selects a VKD3D-Proton and skips this check. + ### Why there is no native Linux `gta6rt` A native (ELF) loader is not a matter of build flags: diff --git a/scripts/build-d3d12-linux.sh b/scripts/build-d3d12-linux.sh new file mode 100755 index 0000000000..496626177c --- /dev/null +++ b/scripts/build-d3d12-linux.sh @@ -0,0 +1,87 @@ +#!/bin/sh +set -eu + +here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +root=$(dirname -- "$here") +d3d12=$root/d3d12 +target=x86_64-pc-windows-msvc +features=diagnostics,mimalloc +vkd3d=yes +for arg in "$@"; do + case $arg in + --no-vkd3d) vkd3d=no ;; + *) echo "usage: $0 [--no-vkd3d]" >&2; exit 2 ;; + esac +done + +bundle_complete() { + dir=$1 + shift + for file in "$@" SOURCE.txt; do + [ -f "$dir/$file" ] || return 1 + done +} + +missing= +command -v cargo >/dev/null 2>&1 || missing="$missing rustup/cargo (https://rustup.rs)" +command -v cargo-xwin >/dev/null 2>&1 || missing="$missing cargo-xwin (cargo install --locked cargo-xwin)" +command -v clang >/dev/null 2>&1 || missing="$missing clang" +command -v lld-link >/dev/null 2>&1 || command -v ld.lld >/dev/null 2>&1 || missing="$missing lld" +if [ -n "$missing" ]; then + echo "Building leonida.exe on Linux needs:$missing" >&2 + exit 1 +fi +if [ "${XWIN_ACCEPT_LICENSE:-}" != 1 ]; then + echo "cargo-xwin downloads Microsoft's CRT and Windows SDK (once, into its cache). Read" >&2 + echo "https://go.microsoft.com/fwlink/?LinkId=2086102 and, if you accept it, run again with" >&2 + echo "XWIN_ACCEPT_LICENSE=1 sh $0" >&2 + exit 1 +fi + +echo "Building leonida.exe ($target, profile diag, features $features)" +(cd "$d3d12" && rustup target add "$target" >/dev/null 2>&1 || true + cd "$d3d12" && cargo xwin build --locked --target "$target" --target-dir "$d3d12/target" --profile diag -p leonida \ + --features "$features") +exe=$d3d12/target/$target/diag/leonida.exe +[ -f "$exe" ] || { echo "cargo finished without $exe" >&2; exit 1; } +printf '%s\n' "$features" > "$d3d12/target/$target/diag/built-with.txt" +echo "Built: $exe" + +if [ "$vkd3d" = yes ]; then + out=$d3d12/target/vkd3d-proton + if bundle_complete "$out" d3d12.dll d3d12core.dll LICENSE COPYING; then + echo "VKD3D-Proton: already in $out" + else + py= + for candidate in python3.16 python3.15 python3.14 python3; do + command -v "$candidate" >/dev/null 2>&1 || continue + if "$candidate" -c 'import compression.zstd' >/dev/null 2>&1; then py=$candidate; break; fi + done + if [ -z "$py" ]; then + echo "VKD3D-Proton not fetched: scripts/fetch_vkd3d_proton.py needs Python 3.14 or newer." >&2 + echo "Install it and run" >&2 + echo " python3.14 -I $here/fetch_vkd3d_proton.py --out $out" >&2 + exit 1 + fi + "$py" -I "$here/fetch_vkd3d_proton.py" --out "$out" + fi + out=$d3d12/target/dxvk + if bundle_complete "$out" dxgi.dll LICENSE; then + echo "DXVK: already in $out" + elif command -v python3 >/dev/null 2>&1; then + python3 -I "$here/fetch_dxvk.py" --out "$out" + else + echo "DXVK not fetched (needed under the system's Wine, not under Proton): run" >&2 + echo " python3 -I $here/fetch_dxvk.py --out $out" >&2 + fi + out=$d3d12/target/d3dcompiler + if bundle_complete "$out" d3dcompiler_47.dll LICENSE; then + echo "d3dcompiler_47: already in $out" + elif command -v python3 >/dev/null 2>&1; then + python3 -I "$here/fetch_d3dcompiler.py" --out "$out" + else + echo "d3dcompiler_47 not fetched (no python3; without it most of the 3D picture is missing): run" >&2 + echo " python3 -I $here/fetch_d3dcompiler.py --out $out" >&2 + fi +fi +echo "Next: sh $here/play-linux.sh /path/to/game_scarlett_master.exe (or PLAY in the launcher)" diff --git a/scripts/fetch_d3dcompiler.py b/scripts/fetch_d3dcompiler.py new file mode 100755 index 0000000000..0006743ec3 --- /dev/null +++ b/scripts/fetch_d3dcompiler.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +import argparse +import hashlib +import io +import os +import sys +import urllib.request +import zipfile + +PACKAGE = "Microsoft.WindowsDesktop.App.Runtime.win-x64" +VERSION = "10.0.15" +RELEASE = (f"https://api.nuget.org/v3-flatcontainer/{PACKAGE.lower()}/{VERSION}/" + f"{PACKAGE.lower()}.{VERSION}.nupkg", + "a036c174bac57a716e21dedccf96459804e4d8d8c31a08e3a8de649bf7684497") +MEMBER = "runtimes/win-x64/native/D3DCompiler_47_cor3.dll" +DLL = ("d3dcompiler_47.dll", "a05f99734f7c4822fefc12b367af21fd0976ed6608752fb1e1e80b6ece7ecbbb") + + +def fetch(url, sha256): + with urllib.request.urlopen(url, timeout=300) as response: + data = response.read() + got = hashlib.sha256(data).hexdigest() + if got != sha256: + raise SystemExit(f"{url}: SHA-256 {got}, expected {sha256}; not used") + return data + + +def publish(out, files): + os.makedirs(out, exist_ok=True) + note = os.path.join(out, "SOURCE.txt") + if os.path.lexists(note): + os.remove(note) + for name, data in files.items(): + partial = os.path.join(out, name + ".part") + with open(partial, "wb") as dst: + dst.write(data) + os.replace(partial, os.path.join(out, name)) + + +def main(): + parser = argparse.ArgumentParser(description="Fetch Microsoft's 64-bit d3dcompiler_47.dll for Leonida under Wine.") + parser.add_argument("--out", default=os.path.join("dist", "linux", "d3dcompiler"), + help="folder for the DLL, license and source note (created)") + args = parser.parse_args() + + with zipfile.ZipFile(io.BytesIO(fetch(*RELEASE))) as package: + dll = package.read(MEMBER) + license_text = package.read("LICENSE") + got = hashlib.sha256(dll).hexdigest() + if got != DLL[1]: + raise SystemExit(f"{MEMBER}: SHA-256 {got}, expected {DLL[1]}; not used") + note = (f"Microsoft d3dcompiler_47.dll, unmodified 64-bit {MEMBER.rsplit('/', 1)[1]} of {PACKAGE} " + f"{VERSION} from\n{RELEASE[0]}\n(SHA-256 {RELEASE[1]}; the DLL {DLL[1]}).\n" + f"Licensed as the package says (LICENSE).\n") + publish(args.out, {DLL[0]: dll, "LICENSE": license_text, "SOURCE.txt": note.encode("utf-8")}) + print(f"d3dcompiler_47.dll ({PACKAGE} {VERSION}), LICENSE and SOURCE.txt in {args.out}") + return 0 + + +if __name__ == "__main__": + sys.stdout.reconfigure(errors="replace") + sys.exit(main()) diff --git a/scripts/fetch_dxvk.py b/scripts/fetch_dxvk.py new file mode 100755 index 0000000000..7a03cc84ea --- /dev/null +++ b/scripts/fetch_dxvk.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +import argparse +import hashlib +import io +import os +import sys +import tarfile +import urllib.request + +VERSION = "3.1.1" +RELEASE = (f"https://github.com/doitsujin/dxvk/releases/download/v{VERSION}/dxvk-{VERSION}.tar.gz", + "40565b4a724aadc4433fa4e010b4b23916d9b1f1baeee64e17186db94f54e608") +LICENSE = (f"https://raw.githubusercontent.com/doitsujin/dxvk/v{VERSION}/LICENSE", + "a5cb1a6ded7d2d7e92d550ba28edd21be2d1d4044662b399887351023e30ce64") +DLLS = ("dxgi.dll",) + + +def fetch(url, sha256): + with urllib.request.urlopen(url, timeout=120) as response: + data = response.read() + got = hashlib.sha256(data).hexdigest() + if got != sha256: + raise SystemExit(f"{url}: SHA-256 {got}, expected {sha256}; not used") + return data + + +def publish(out, files): + os.makedirs(out, exist_ok=True) + note = os.path.join(out, "SOURCE.txt") + if os.path.lexists(note): + os.remove(note) + for name, data in files.items(): + partial = os.path.join(out, name + ".part") + with open(partial, "wb") as dst: + dst.write(data) + os.replace(partial, os.path.join(out, name)) + + +def main(): + parser = argparse.ArgumentParser(description="Fetch the pinned DXVK release for Leonida's Linux package.") + parser.add_argument("--out", default=os.path.join("dist", "linux", "dxvk"), + help="folder for the DLL, license and source note (created)") + args = parser.parse_args() + + files = {} + with tarfile.open(fileobj=io.BytesIO(fetch(*RELEASE)), mode="r:gz") as tar: + for name in DLLS: + member = tar.getmember(f"dxvk-{VERSION}/x64/{name}") + with tar.extractfile(member) as src: + files[name] = src.read() + files["LICENSE"] = fetch(*LICENSE) + files["SOURCE.txt"] = (f"DXVK {VERSION}, unmodified 64-bit {', '.join(DLLS)} from\n" + f"{RELEASE[0]}\n(SHA-256 {RELEASE[1]}).\n" + f"Licensed under the zlib/libpng license (LICENSE).\n" + f"Source: https://github.com/doitsujin/dxvk/tree/v{VERSION}\n").encode("utf-8") + publish(args.out, files) + print(f"DXVK {VERSION}: {', '.join(DLLS)}, LICENSE and SOURCE.txt in {args.out}") + return 0 + + +if __name__ == "__main__": + sys.stdout.reconfigure(errors="replace") + sys.exit(main()) diff --git a/scripts/fetch_vkd3d_proton.py b/scripts/fetch_vkd3d_proton.py index bf4bb9c5d7..838a00bd7c 100755 --- a/scripts/fetch_vkd3d_proton.py +++ b/scripts/fetch_vkd3d_proton.py @@ -42,6 +42,18 @@ def fetch(url, sha256): return data +def publish(out, files): + os.makedirs(out, exist_ok=True) + note = os.path.join(out, "SOURCE.txt") + if os.path.lexists(note): + os.remove(note) + for name, data in files.items(): + partial = os.path.join(out, name + ".part") + with open(partial, "wb") as dst: + dst.write(data) + os.replace(partial, os.path.join(out, name)) + + def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--out", default=os.path.join("dist", "linux", "vkd3d-proton"), @@ -52,21 +64,21 @@ def main(): except ImportError: raise SystemExit("Python 3.14 or newer is needed (compression.zstd reads the .tar.zst release)") - os.makedirs(args.out, exist_ok=True) + files = {} archive = zstd.decompress(fetch(*RELEASE)) with tarfile.open(fileobj=io.BytesIO(archive)) as tar: for name in DLLS: member = tar.getmember(f"vkd3d-proton-{VERSION}/x64/{name}") - with tar.extractfile(member) as src, open(os.path.join(args.out, name), "wb") as dst: - dst.write(src.read()) + with tar.extractfile(member) as src: + files[name] = src.read() for name, (url, sha256) in LICENSE_FILES.items(): - with open(os.path.join(args.out, name), "wb") as dst: - dst.write(fetch(url, sha256)) - with open(os.path.join(args.out, "SOURCE.txt"), "w", encoding="utf-8", newline="\n") as note: - note.write(f"VKD3D-Proton {VERSION}, unmodified 64-bit d3d12.dll and d3d12core.dll from\n" - f"{RELEASE[0]}\n(SHA-256 {RELEASE[1]}).\n" - f"Licensed under the GNU Lesser General Public License 2.1 or later (LICENSE, COPYING).\n" - f"Source: https://github.com/HansKristian-Work/vkd3d-proton/tree/v{VERSION}\n") + files[name] = fetch(url, sha256) + note = (f"VKD3D-Proton {VERSION}, unmodified 64-bit d3d12.dll and d3d12core.dll from\n" + f"{RELEASE[0]}\n(SHA-256 {RELEASE[1]}).\n" + f"Licensed under the GNU Lesser General Public License 2.1 or later (LICENSE, COPYING).\n" + f"Source: https://github.com/HansKristian-Work/vkd3d-proton/tree/v{VERSION}\n") + files["SOURCE.txt"] = note.encode("utf-8") + publish(args.out, files) print(f"VKD3D-Proton {VERSION}: {', '.join(DLLS)}, LICENSE, COPYING and SOURCE.txt in {args.out}") return 0 diff --git a/scripts/play-linux.sh b/scripts/play-linux.sh index e7d48d78ea..3c8a5b9685 100755 --- a/scripts/play-linux.sh +++ b/scripts/play-linux.sh @@ -1,54 +1,460 @@ #!/bin/sh -# Starts Leonida's D3D12 runtime (d3d12/, a Windows program) on Linux under Wine, with the VKD3D-Proton that comes in -# the package (scripts/fetch_vkd3d_proton.py puts it in vkd3d-proton/ beside this script), so nothing else needs to be -# downloaded for Direct3D 12. Wine itself and a Vulkan driver (Mesa or NVIDIA's) are the system's. +# Starts Leonida's D3D12 runtime (d3d12/, a Windows program) on Linux under an installed Proton build or the system's +# Wine, with the VKD3D-Proton that comes in the package (scripts/fetch_vkd3d_proton.py puts it in vkd3d-proton/ beside +# this script) and DXVK's dxgi.dll (docs/linux.md says where both come from). A Vulkan driver (Mesa or NVIDIA's) is +# the system's. # -# ./play-linux.sh /path/to/your/game_scarlett_master.exe [--series-x] +# ./play-linux.sh /path/to/your/game_scarlett_master.exe [--series-x] [--log] +# ./play-linux.sh --find-proton | --list-protons # # Leonida keeps its own Wine prefix (LEONIDA_WINEPREFIX, default ~/.local/share/leonida/prefix): the bundled # d3d12.dll and d3d12core.dll are installed there and preferred over Wine's (WINEDLLOVERRIDES), so no other prefix # is changed. LEONIDA_* variables already set win over the defaults below. set -eu +unset CDPATH + +proton_problem() { + if [ ! -x "$1/files/bin/wine" ]; then + echo "no files/bin/wine" + elif [ ! -d "$1/files/lib/wine" ] && [ ! -d "$1/files/lib64/wine" ]; then + echo "incomplete, no files/lib/wine or files/lib64/wine" + fi +} + +proton_ok() { + [ -z "$(proton_problem "$1")" ] +} + +proton_dxvk() { + for lib_dir in "$1/files/lib/wine/dxvk/x86_64-windows" "$1/files/lib64/wine/dxvk/x86_64-windows" \ + "$1/files/lib64/wine/dxvk"; do + if [ -f "$lib_dir/dxgi.dll" ]; then + printf '%s\n' "$lib_dir" + return 0 + fi + done + return 1 +} + +proton_new_vkd3d() { + for lib_dir in "$1/files/lib/wine/vkd3d-proton/x86_64-windows" "$1/files/lib64/wine/vkd3d-proton/x86_64-windows" \ + "$1/files/lib64/wine/vkd3d-proton"; do + if vkd3d_new_structurizer "$lib_dir"; then + printf '%s\n' "$lib_dir" + return 0 + fi + done + return 1 +} + +proton_name() { + name= + if [ -f "$1/version" ]; then + name=$(awk 'NR == 1 { print (NF > 1 ? $2 : $1) }' "$1/version") + fi + [ -n "$name" ] || name=$(basename "$1") + printf '%s\n' "$name" +} + +steam_roots() { + for root in "${XDG_DATA_HOME:-$HOME/.local/share}/Steam" "$HOME/.steam/root" "$HOME/.steam/steam" \ + "$HOME/.steam/debian-installation" "$HOME/.var/app/com.valvesoftware.Steam/data/Steam" \ + "$HOME/snap/steam/common/.local/share/Steam"; do + if [ -d "$root" ]; then + printf '%s\n' "$root" + for vdf in "$root/steamapps/libraryfolders.vdf" "$root/config/libraryfolders.vdf"; do + if [ -f "$vdf" ]; then + sed -n 's/^[[:space:]]*"path"[[:space:]]*"\(.*\)"[[:space:]]*$/\1/p' "$vdf" + fi + done + fi + done +} + +proton_candidates() { + { + steam_roots | while IFS= read -r root; do + for dir in "$root"/compatibilitytools.d/* "$root"/steamapps/common/*; do + printf '%s\n' "$dir" + done + done + printf '%s\n' "${STEAM_EXTRA_COMPAT_TOOLS_PATHS:-}" | tr ':' '\n' | while IFS= read -r tools; do + if [ -n "$tools" ]; then + printf '%s\n' "$tools" + for dir in "$tools"/*; do + printf '%s\n' "$dir" + done + fi + done + for tools in /usr/share/steam/compatibilitytools.d /usr/local/share/steam/compatibilitytools.d; do + for dir in "$tools"/*; do + printf '%s\n' "$dir" + done + done + } | while IFS= read -r dir; do + if [ -d "$dir" ] && [ -e "$dir/files/bin/wine" ]; then + real=$(cd -P "$dir" && pwd) + printf '%s\t%s\t%s\n' "$(proton_name "$real")" "$real" "$(proton_problem "$real")" + fi + done +} + +all_protons() { + proton_candidates | awk -F '\t' '{ + key = $1 + gsub(/[^0-9]+/, " ", key) + split(key, part, " ") + printf "%d %012d %012d %012d\t%s\t%s%s\n", ($3 == ""), part[1], part[2], part[3], $1, $2, + ($3 == "" ? "" : "\t" $3) + }' | sort -r -u | cut -f 2- +} + +ranked_protons() { + all_protons | awk -F '\t' '$3 == "" { print $1 "\t" $2 }' +} + +newest_proton() { + ranked_protons | head -n 1 +} + +vkd3d_version() { + [ -f "$1/d3d12core.dll" ] || return 1 + { cat "${1%/x86_64-windows}/version" 2>/dev/null || true; LC_ALL=C tr -c '[:print:]' '\n' < "$1/d3d12core.dll"; } | + LC_ALL=C grep -a -E 'v[0-9]+\.[0-9]+-[0-9]+-g|vkd3d-1\.1-[0-9]+-g|^vkd3d$|^[0-9]+\.[0-9]+\.[0-9]+$' | + LC_ALL=C awk ' + match($0, /v[0-9]+\.[0-9]+-[0-9]+-g[0-9a-f]+/) { + split(substr($0, RSTART + 1, RLENGTH - 1), part, /[.-]/) + printf "%d %d %d\n", part[1], part[2], part[3] + found = 1 + exit + } + !counted && match($0, /vkd3d-1\.1-[0-9]+-g[0-9a-f]+/) { + split(substr($0, RSTART, RLENGTH), part, "-") + if (part[3] + 0 >= 5686) counted = sprintf("3 1 %d", part[3] - 5686) + } + !released && last == "vkd3d" && /^[0-9]+\.[0-9]+\.[0-9]+$/ { + split($0, part, ".") + released = sprintf("%d %d 0", part[1], part[2]) + } + { last = $0 } + END { + if (found) exit 0 + version = counted ? counted : released + if (version == "") exit 1 + print version + }' +} + +vkd3d_new_structurizer() { + [ -f "$1/d3d12.dll" ] && [ -f "$1/d3d12core.dll" ] || return 1 + grep -q -a legacy_structurizer "$1/d3d12core.dll" && return 0 + vkd3d_version "$1" | awk '{ new = $1 > 3 || ($1 == 3 && ($2 > 1 || ($2 == 1 && $3 >= 22))) } END { exit !new }' +} + +proton_with_new_vkd3d() { + { [ -z "$proton" ] || printf '%s\n' "$proton"; ranked_protons | cut -f 2-; } | + while IFS= read -r dir; do + if lib_dir=$(proton_new_vkd3d "$dir"); then + version=$(vkd3d_version "$lib_dir") || version="3 1 22" + printf '%s\t%s\n' "$version" "$dir" + fi + done | awk -F '\t' '{ + split($1, part, " ") + if (best == "" || part[1] > major || (part[1] == major && (part[2] > minor || + (part[2] == minor && part[3] > ahead)))) { + major = part[1]; minor = part[2]; ahead = part[3]; best = $2 + } + } + END { if (best != "") print best }' +} + +system_wine() { + wine=$(command -v "$1" 2>/dev/null) || return 1 + [ -f "$wine" ] && [ -x "$wine" ] || return 1 + version=$("$wine" --version 2>/dev/null | head -n 1) || version= + wine_label="Wine${version:+ ${version#wine-}}" +} + +install_dll() { + if [ -L "$2" ] || ! cmp -s "$1" "$2"; then + stage=$(mktemp -d "$2.leonida-XXXXXX") + cp "$1" "$stage/new" + if [ -L "$2" ] && [ -d "$2" ]; then rm -f "$2"; fi + mv -f "$stage/new" "$2" + rmdir "$stage" + fi +} + +system_dxvk() { + for dir in /usr/share/dxvk/x64 /usr/lib/dxvk/x64 /usr/lib/dxvk/wine64 /usr/share/dxvk/x86_64-windows \ + /usr/lib/dxvk/x86_64-windows; do + if [ -f "$dir/dxgi.dll" ]; then + printf '%s\n' "$dir" + return + fi + done +} + +find_dxgi() { + if [ -n "${LEONIDA_DXVK:-}" ]; then + dxgi_dir=${LEONIDA_DXVK%/} + if [ ! -f "$dxgi_dir/dxgi.dll" ]; then + echo "Leonida: LEONIDA_DXVK=$LEONIDA_DXVK has no dxgi.dll" >&2 + exit 1 + fi + dxgi_label="DXVK's dxgi from $dxgi_dir (LEONIDA_DXVK)" + return + fi + if [ -n "$proton" ] && dxgi_dir=$(proton_dxvk "$proton"); then + dxgi_label="DXVK's dxgi" + return + fi + for dxgi_dir in "$here/dxvk" "$root/d3d12/target/dxvk"; do + if [ -f "$dxgi_dir/dxgi.dll" ]; then + dxgi_label="the bundled DXVK's dxgi ($(sed -n '1s/,.*//p' "$dxgi_dir/SOURCE.txt" 2>/dev/null | grep . || echo bundled))" + return + fi + done + dxgi_dir=$(system_dxvk) + if [ -n "$dxgi_dir" ]; then + dxgi_label="DXVK's dxgi from $dxgi_dir" + return + fi + found=$(all_protons | cut -f 1,2 | while IFS= read -r line; do + if proton_dxvk "$(printf '%s\n' "$line" | cut -f 2-)" >/dev/null; then printf '%s\n' "$line"; break; fi + done) + if [ -n "$found" ]; then + dxgi_dir=$(proton_dxvk "$(printf '%s\n' "$found" | cut -f 2-)") + dxgi_label="DXVK's dxgi of $(printf '%s\n' "$found" | cut -f 1)" + return + fi + cat >&2 <&2 + exit 1 + fi + return + fi + for d3dcompiler_dir in "$here/d3dcompiler" "$root/d3d12/target/d3dcompiler"; do + if [ -f "$d3dcompiler_dir/d3dcompiler_47.dll" ]; then return; fi + done + d3dcompiler_dir=$root/d3d12/target/d3dcompiler + if [ -f "$here/fetch_d3dcompiler.py" ] && command -v python3 >/dev/null 2>&1; then + echo "Leonida: fetching Microsoft's d3dcompiler_47.dll into $d3dcompiler_dir" + if python3 -I "$here/fetch_d3dcompiler.py" --out "$d3dcompiler_dir" >/dev/null && + [ -f "$d3dcompiler_dir/d3dcompiler_47.dll" ]; then + return + fi + fi + d3dcompiler_dir= + cat >&2 <&2 + exit 1 + fi + problem=$(proton_problem "$proton") + if [ -n "$problem" ]; then + echo "Leonida: LEONIDA_PROTON=$LEONIDA_PROTON is not a Proton build ($problem)" >&2 + exit 1 + fi + proton=$(cd -P "$proton" && pwd) + wine_label=$(proton_name "$proton") + elif [ -n "${LEONIDA_WINE:-}" ]; then + if ! system_wine "$LEONIDA_WINE"; then + echo "Leonida: LEONIDA_WINE=$LEONIDA_WINE is not a Wine program" >&2 + exit 1 + fi + else + found=$(newest_proton) + if [ -n "$found" ]; then + wine_label=$(printf '%s\n' "$found" | cut -f 1) + proton=$(printf '%s\n' "$found" | cut -f 2-) + elif ! system_wine wine; then + cat >&2 <<'MESSAGE' +Leonida: no Proton and no Wine found. Install GE-Proton, Valve's Proton or your distribution's Wine, or set +LEONIDA_PROTON to a Proton folder or LEONIDA_WINE to a Wine program. +MESSAGE + exit 1 + fi + fi + if [ -n "$proton" ]; then + wine=$proton/files/bin/wine + runner=$proton + else + runner=$wine + fi + find_dxgi +} + +here=$(cd "$(dirname "$0")" && pwd) +root=$(dirname "$here") + +if [ "${1:-}" = "--list-protons" ]; then + ranked_protons + exit 0 +fi + +if [ "${1:-}" = "--find-proton" ]; then + find_proton + printf '%s\t%s\n' "$wine_label" "$runner" + exit 0 +fi if [ $# -lt 1 ]; then - echo "usage: $0 /path/to/game_scarlett_master.exe [--series-x]" >&2 + echo "usage: $0 /path/to/game_scarlett_master.exe [--series-x] [--log]" >&2 exit 2 fi game_exe=$1 shift console=series-s -if [ "${1:-}" = "--series-x" ]; then console=series-x; fi +log= +for arg in "$@"; do + case $arg in + --series-x) console=series-x ;; + --log) log=1 ;; + *) echo "usage: $0 /path/to/game_scarlett_master.exe [--series-x] [--log]" >&2; exit 2 ;; + esac +done [ -f "$game_exe" ] || { echo "No $game_exe" >&2; exit 1; } -here=$(cd "$(dirname "$0")" && pwd) -runtime=${LEONIDA_RUNTIME:-$here/leonida.exe} -vkd3d=${LEONIDA_VKD3D:-$here/vkd3d-proton} -[ -f "$runtime" ] || { echo "No $runtime (the Windows build of d3d12/)" >&2; exit 1; } +build="sh $here/build-d3d12-linux.sh" +if [ -n "${LEONIDA_RUNTIME:-}" ]; then + runtime=$LEONIDA_RUNTIME + [ -f "$runtime" ] || { echo "No $runtime (LEONIDA_RUNTIME)" >&2; exit 1; } +else + runtime= + for candidate in "$here/leonida.exe" \ + "$root/d3d12/target/x86_64-pc-windows-msvc/diag/leonida.exe" \ + "$root/d3d12/target/x86_64-pc-windows-msvc/play/leonida.exe" \ + "$root/d3d12/target/x86_64-pc-windows-msvc/release/leonida.exe" \ + "$root/d3d12/target/diag/leonida.exe" \ + "$root/d3d12/target/play/leonida.exe" \ + "$root/d3d12/target/release/leonida.exe"; do + if [ -f "$candidate" ]; then runtime=$candidate; break; fi + done + if [ -z "$runtime" ]; then + echo "No leonida.exe beside this script or in $root/d3d12/target/. Build it with" >&2 + echo " XWIN_ACCEPT_LICENSE=1 $build" >&2 + echo "(in the launcher: Tools, Rebuild the runtime), or set LEONIDA_RUNTIME to a leonida.exe." >&2 + exit 1 + fi +fi +if [ -n "${LEONIDA_VKD3D:-}" ]; then + vkd3d=$LEONIDA_VKD3D +else + vkd3d=$here/vkd3d-proton + if [ ! -f "$vkd3d/d3d12.dll" ] && [ -f "$root/d3d12/target/vkd3d-proton/d3d12.dll" ]; then + vkd3d=$root/d3d12/target/vkd3d-proton + fi +fi +find_proton +if [ -n "${LEONIDA_VKD3D:-}" ]; then + vkd3d_label="the VKD3D-Proton in $vkd3d (LEONIDA_VKD3D)" +else + vkd3d_label="the bundled VKD3D-Proton ($(sed -n '1s/,.*//p' "$vkd3d/SOURCE.txt" 2>/dev/null | grep . || echo bundled))" +fi +if [ -z "${LEONIDA_VKD3D:-}" ] && ! vkd3d_new_structurizer "$vkd3d"; then + vkd3d_from=$(proton_with_new_vkd3d) + if [ -n "$vkd3d_from" ]; then + vkd3d=$(proton_new_vkd3d "$vkd3d_from") + vkd3d_build=$(sed -n '1s/.*(\(.*\)).*/\1/p' "${vkd3d%/x86_64-windows}/version" 2>/dev/null || true) + vkd3d_label="the VKD3D-Proton of $(proton_name "$vkd3d_from")${vkd3d_build:+ ($vkd3d_build)}" + elif [ -f "$vkd3d/d3d12core.dll" ]; then + echo "Leonida: the bundled VKD3D-Proton lacks dxil-spirv's new structurizer, and the Vulkan driver can" \ + "crash on some of the title's compute shaders. No Proton build found has a newer one. Install a" \ + "current GE-Proton, or set LEONIDA_VKD3D to a newer VKD3D-Proton folder." >&2 + fi +fi for dll in d3d12.dll d3d12core.dll; do - [ -f "$vkd3d/$dll" ] || { echo "No $vkd3d/$dll: run scripts/fetch_vkd3d_proton.py when packaging" >&2; exit 1; } + if [ ! -f "$vkd3d/$dll" ]; then + echo "No $vkd3d/$dll (VKD3D-Proton). Fetch it with" >&2 + echo " XWIN_ACCEPT_LICENSE=1 $build" >&2 + echo "or python3.14 -I $here/fetch_vkd3d_proton.py --out $root/d3d12/target/vkd3d-proton," >&2 + echo "or set LEONIDA_VKD3D to a folder with d3d12.dll and d3d12core.dll." >&2 + exit 1 + fi done -command -v wine >/dev/null 2>&1 || { echo "Wine is needed (your distribution's wine package, or Proton's)" >&2; exit 1; } +if [ -n "$proton" ]; then + for dir in "$proton/files/lib/wine" "$proton/files/lib/vkd3d" "$proton/files/lib64/wine" \ + "$proton/files/lib64/vkd3d"; do + if [ -d "$dir" ]; then WINEDLLPATH=$dir${WINEDLLPATH:+:$WINEDLLPATH}; fi + done + for dir in "$proton/files/lib/i386-linux-gnu" "$proton/files/lib/x86_64-linux-gnu" "$proton/files/lib64"; do + if [ -d "$dir" ]; then LD_LIBRARY_PATH=$dir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}; fi + done + export WINEDLLPATH LD_LIBRARY_PATH +fi data=${XDG_DATA_HOME:-$HOME/.local/share}/leonida export WINEPREFIX=${LEONIDA_WINEPREFIX:-$data/prefix} export WINEARCH=win64 -if [ ! -d "$WINEPREFIX/drive_c/windows/system32" ]; then - echo "Leonida: making its Wine prefix in $WINEPREFIX" - mkdir -p "$WINEPREFIX" - WINEDEBUG=-all wineboot -u >/dev/null 2>&1 +stamp=$WINEPREFIX/.leonida-proton +system32=$WINEPREFIX/drive_c/windows/system32 +if [ ! -d "$system32" ] || [ "$(cat "$stamp" 2>/dev/null)" != "$wine_label $runner" ] || + { [ -n "$proton" ] && { [ -f "$proton/files/lib/vkd3d/x86_64-windows/libvkd3d-1.dll" ] || + [ -f "$proton/files/lib64/vkd3d/x86_64-windows/libvkd3d-1.dll" ]; } && + [ ! -f "$system32/libvkd3d-1.dll" ]; }; then + if [ -d "$system32" ]; then + echo "Leonida: updating its Wine prefix in $WINEPREFIX for $wine_label" + else + echo "Leonida: making its Wine prefix in $WINEPREFIX with $wine_label" + mkdir -p "$WINEPREFIX" + fi + WINEDEBUG=-all "$wine" wineboot -u >/dev/null 2>&1 || { + echo "Leonida: $wine_label could not set up the prefix $WINEPREFIX" >&2 + exit 1 + } + server=$(dirname "$wine")/wineserver + if [ ! -x "$server" ] && [ -z "$proton" ]; then server=$(command -v wineserver 2>/dev/null || true); fi + if [ -n "$server" ] && [ -x "$server" ]; then + "$server" -w || true + fi + printf '%s\n' "$wine_label $runner" > "$stamp" fi # The bundled VKD3D-Proton, copied in when it is missing or differs (a new package). -system32=$WINEPREFIX/drive_c/windows/system32 for dll in d3d12.dll d3d12core.dll; do - if ! cmp -s "$vkd3d/$dll" "$system32/$dll"; then cp "$vkd3d/$dll" "$system32/$dll"; fi + install_dll "$vkd3d/$dll" "$system32/$dll" done -export WINEDLLOVERRIDES="d3d12,d3d12core=n${WINEDLLOVERRIDES:+;$WINEDLLOVERRIDES}" +install_dll "$dxgi_dir/dxgi.dll" "$system32/dxgi.dll" +native=d3d12,d3d12core,dxgi +find_d3dcompiler +if [ -n "$d3dcompiler_dir" ]; then + install_dll "$d3dcompiler_dir/d3dcompiler_47.dll" "$system32/d3dcompiler_47.dll" + native=$native,d3dcompiler_47 +fi +export WINEDLLOVERRIDES="${WINEDLLOVERRIDES:+$WINEDLLOVERRIDES;}$native=n" # Where the title's files are, and where the caches and saves go. export LEONIDA_GAME_DIR=${LEONIDA_GAME_DIR:-$(cd "$(dirname "$game_exe")" && pwd)} export LEONIDA_CACHE_DIR=${LEONIDA_CACHE_DIR:-$data/cache} export LEONIDA_DATA_DIR=${LEONIDA_DATA_DIR:-$data/data} +export VKD3D_SHADER_CACHE_PATH=${VKD3D_SHADER_CACHE_PATH:-$LEONIDA_CACHE_DIR/vkd3d-proton} mkdir -p "$LEONIDA_CACHE_DIR" "$LEONIDA_DATA_DIR" +if [ "$VKD3D_SHADER_CACHE_PATH" != 0 ]; then mkdir -p "$VKD3D_SHADER_CACHE_PATH"; fi # The settings scripts/play-nvidia.ps1 measured (d3d12/README.md), as defaults. set_default() { eval "[ -n \"\${$1:-}\" ] || export $1=\"$2\""; } @@ -67,5 +473,13 @@ set_default LEONIDA_NAN_SCRUB 1 set_default LEONIDA_AMBIENT_AIR 1.5 set_default LEONIDA_AMBIENT_MOST 2 -echo "Leonida: $console under Wine with the bundled VKD3D-Proton ($(head -n 1 "$vkd3d/SOURCE.txt" 2>/dev/null || echo bundled))" -exec wine "$runtime" run "$game_exe" --execute --console "$console" +echo "Leonida: $console under $wine_label ($runner) with $dxgi_label and $vkd3d_label" +if [ -n "$log" ]; then + logs=$data/logs + mkdir -p "$logs" + ls -1t "$logs"/play-*.log 2>/dev/null | tail -n +5 | while IFS= read -r old; do rm -f "$old"; done + log_file=$logs/play-$(date +%m%d-%H%M%S).log + echo "log: $log_file" + exec "$wine" "$runtime" run "$game_exe" --execute --console "$console" 2>"$log_file" +fi +exec "$wine" "$runtime" run "$game_exe" --execute --console "$console" diff --git a/tests/test_build_d3d12_linux.py b/tests/test_build_d3d12_linux.py new file mode 100644 index 0000000000..4305374f25 --- /dev/null +++ b/tests/test_build_d3d12_linux.py @@ -0,0 +1,216 @@ +import hashlib +import importlib.util +import io +import os +import shutil +import subprocess +import sys +import tarfile +import tempfile +import types +import unittest +import zipfile +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts" / "build-d3d12-linux.sh" +TARGET = "x86_64-pc-windows-msvc" + +CARGO = """#!/bin/sh +printf '%s\\n' "$*" >> "$LEONIDA_TEST_LOG.cargo" +target_dir=${CARGO_TARGET_DIR:-target} +while [ $# -gt 0 ]; do + if [ "$1" = --target-dir ]; then target_dir=$2; fi + shift +done +mkdir -p "$target_dir/x86_64-pc-windows-msvc/diag" +printf 'MZ' > "$target_dir/x86_64-pc-windows-msvc/diag/leonida.exe" +""" + +PYTHON = """#!/bin/sh +[ "$1" = -c ] && exit 0 +printf '%s\\n' "$*" >> "$LEONIDA_TEST_LOG.python" +""" + +STUB = "#!/bin/sh\nexit 0\n" + + +def load(name): + spec = importlib.util.spec_from_file_location(name, ROOT / "scripts" / f"{name}.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def tar_bytes(files, mode="w:gz"): + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode=mode) as tar: + for name, data in files.items(): + info = tarfile.TarInfo(name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + return buffer.getvalue() + + +@unittest.skipIf(os.name == "nt" or not os.path.exists("/bin/sh"), "POSIX shell script") +class BuildD3d12LinuxTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.tmp = Path(tmp.name) + self.repo = self.tmp / "repo" + (self.repo / "scripts").mkdir(parents=True) + (self.repo / "d3d12").mkdir() + shutil.copy(SCRIPT, self.repo / "scripts" / "build-d3d12-linux.sh") + self.bin = self.tmp / "bin" + self.bin.mkdir() + for name, text in (("cargo", CARGO), ("cargo-xwin", STUB), ("clang", STUB), ("lld-link", STUB), + ("rustup", STUB), ("python3", PYTHON)): + (self.bin / name).write_text(text, encoding="utf-8", newline="\n") + (self.bin / name).chmod(0o755) + for tool in ("dirname", "mkdir"): + os.symlink(shutil.which(tool), self.bin / tool) + self.log = self.tmp / "log" + self.target = self.repo / "d3d12" / "target" + + def build(self, **env): + environment = {"PATH": str(self.bin), "HOME": str(self.tmp / "home"), "XWIN_ACCEPT_LICENSE": "1", + "LEONIDA_TEST_LOG": str(self.log), **env} + return subprocess.run(["/bin/sh", str(self.repo / "scripts" / "build-d3d12-linux.sh")], env=environment, + capture_output=True, text=True, timeout=60) + + def bundle(self, folder, *names): + folder = self.target / folder + folder.mkdir(parents=True, exist_ok=True) + for name in names: + (folder / name).write_bytes(b"x") + + def fetched(self): + path = Path(str(self.log) + ".python") + return path.read_text(encoding="utf-8") if path.exists() else "" + + def test_a_custom_cargo_target_dir_still_builds_into_d3d12_target(self): + elsewhere = self.tmp / "elsewhere" + p = self.build(CARGO_TARGET_DIR=str(elsewhere)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertTrue((self.target / TARGET / "diag" / "leonida.exe").is_file()) + self.assertTrue((self.target / TARGET / "diag" / "built-with.txt").is_file()) + self.assertFalse(elsewhere.exists()) + self.assertIn(f"--target-dir {self.target}", Path(str(self.log) + ".cargo").read_text(encoding="utf-8")) + + def test_complete_bundles_are_not_fetched_again(self): + self.bundle("vkd3d-proton", "d3d12.dll", "d3d12core.dll", "LICENSE", "COPYING", "SOURCE.txt") + self.bundle("dxvk", "dxgi.dll", "LICENSE", "SOURCE.txt") + self.bundle("d3dcompiler", "d3dcompiler_47.dll", "LICENSE", "SOURCE.txt") + p = self.build() + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("VKD3D-Proton: already in", p.stdout) + self.assertIn("DXVK: already in", p.stdout) + self.assertIn("d3dcompiler_47: already in", p.stdout) + self.assertEqual(self.fetched(), "") + + def test_a_bundle_missing_a_file_is_fetched_again(self): + self.bundle("vkd3d-proton", "d3d12.dll", "d3d12core.dll", "LICENSE", "SOURCE.txt") + self.bundle("dxvk", "dxgi.dll") + self.bundle("d3dcompiler", "d3dcompiler_47.dll", "LICENSE") + p = self.build() + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("fetch_vkd3d_proton.py", self.fetched()) + self.assertIn("fetch_dxvk.py", self.fetched()) + self.assertIn("fetch_d3dcompiler.py", self.fetched()) + + +class FetchBundleTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.out = Path(tmp.name) / "out" + + def run_main(self, module, fetch): + with mock.patch.object(module, "fetch", fetch), \ + mock.patch.object(sys, "argv", ["fetch", "--out", str(self.out)]), \ + mock.patch("sys.stdout", io.StringIO()): + return module.main() + + def assert_complete(self, names): + self.assertEqual(sorted(p.name for p in self.out.iterdir()), sorted([*names, "SOURCE.txt"])) + + def test_dxvk_is_published_only_when_every_file_was_fetched(self): + module = load("fetch_dxvk") + archive = tar_bytes({f"dxvk-{module.VERSION}/x64/dxgi.dll": b"dxgi"}) + + def fails_on_license(url, sha256): + if url == module.LICENSE[0]: + raise SystemExit("license download failed") + return archive + + with self.assertRaises(SystemExit): + self.run_main(module, fails_on_license) + self.assertFalse((self.out / "dxgi.dll").exists()) + self.assertEqual(self.run_main(module, lambda url, sha256: b"license" if url == module.LICENSE[0] + else archive), 0) + self.assert_complete(["dxgi.dll", "LICENSE"]) + self.assertEqual((self.out / "dxgi.dll").read_bytes(), b"dxgi") + + def test_a_new_dxvk_fetch_takes_the_old_source_note_first(self): + module = load("fetch_dxvk") + writes = [] + real_replace = os.replace + + def replace(src, dst): + writes.append((Path(dst).name, (self.out / "SOURCE.txt").exists())) + real_replace(src, dst) + + self.out.mkdir() + (self.out / "SOURCE.txt").write_text("old", encoding="utf-8") + archive = tar_bytes({f"dxvk-{module.VERSION}/x64/dxgi.dll": b"dxgi"}) + with mock.patch.object(module.os, "replace", replace): + self.run_main(module, lambda url, sha256: b"license" if url == module.LICENSE[0] else archive) + self.assertEqual(writes, [("dxgi.dll", False), ("LICENSE", False), ("SOURCE.txt", False)]) + + def test_d3dcompiler_is_published_with_its_source_note_last(self): + module = load("fetch_d3dcompiler") + dll = b"MZ d3dcompiler_47" + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as package: + package.writestr(module.MEMBER, dll) + package.writestr("LICENSE", b"license") + writes = [] + real_replace = os.replace + + def replace(src, dst): + writes.append(Path(dst).name) + real_replace(src, dst) + + with mock.patch.object(module, "DLL", (module.DLL[0], hashlib.sha256(dll).hexdigest())), \ + mock.patch.object(module.os, "replace", replace): + self.assertEqual(self.run_main(module, lambda url, sha256: buffer.getvalue()), 0) + self.assertEqual(writes, ["d3dcompiler_47.dll", "LICENSE", "SOURCE.txt"]) + self.assert_complete(["d3dcompiler_47.dll", "LICENSE"]) + + def test_vkd3d_proton_is_published_only_when_every_file_was_fetched(self): + module = load("fetch_vkd3d_proton") + archive = tar_bytes({f"vkd3d-proton-{module.VERSION}/x64/{name}": name.encode() for name in module.DLLS}, + mode="w") + compression = types.ModuleType("compression") + compression.zstd = types.SimpleNamespace(decompress=lambda data: data) + licenses = {url: name.encode() for name, (url, _sha256) in module.LICENSE_FILES.items()} + last = module.LICENSE_FILES["LICENSE"][0] + + def fails_on_last_license(url, sha256): + if url == last: + raise SystemExit("license download failed") + return licenses.get(url, archive) + + with mock.patch.dict(sys.modules, {"compression": compression, "compression.zstd": compression.zstd}): + with self.assertRaises(SystemExit): + self.run_main(module, fails_on_last_license) + self.assertFalse(self.out.exists() and any(self.out.iterdir())) + self.assertEqual(self.run_main(module, lambda url, sha256: licenses.get(url, archive)), 0) + self.assert_complete([*module.DLLS, *module.LICENSE_FILES]) + self.assertEqual((self.out / "COPYING").read_bytes(), b"COPYING") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_leonida_launcher.py b/tests/test_leonida_launcher.py index 4317cd5998..5a2d2b4857 100644 --- a/tests/test_leonida_launcher.py +++ b/tests/test_leonida_launcher.py @@ -10,10 +10,15 @@ import unittest ROOT = Path(__file__).resolve().parents[1] +SYSTEM_TOOLS = (Path("/usr/share/steam/compatibilitytools.d"), Path("/usr/local/share/steam/compatibilitytools.d")) sys.path.insert(0, str(ROOT / "tools")) import leonida_launcher as launcher # noqa: E402 +def system_proton_installed(): + return any(tools.is_dir() and any(tools.iterdir()) for tools in SYSTEM_TOOLS) + + def settings(**changes): value = dict(launcher.DEFAULTS, game_dir="D:/Games/GTA") value.update(changes) @@ -49,6 +54,21 @@ def test_wrong_types_and_unknown_keys_are_dropped(self): self.assertNotIn("extra", got) self.assertEqual(launcher.normalise([1]), launcher.DEFAULTS) + def test_linux_keeps_logs_in_the_leonida_data_folder(self): + with tempfile.TemporaryDirectory() as tmp: + saved = (launcher.WINDOWS, os.environ.get("XDG_DATA_HOME")) + launcher.WINDOWS = False + os.environ["XDG_DATA_HOME"] = tmp + try: + self.assertEqual(launcher.logs_dir(), os.path.join(tmp, "leonida", "logs")) + self.assertEqual(launcher.captures_dir(), os.path.join(tmp, "leonida", "captures")) + finally: + launcher.WINDOWS = saved[0] + if saved[1] is None: + os.environ.pop("XDG_DATA_HOME", None) + else: + os.environ["XDG_DATA_HOME"] = saved[1] + def test_game_folder_check(self): with tempfile.TemporaryDirectory() as tmp: self.assertFalse(launcher.game_exe_present(tmp)) @@ -111,6 +131,120 @@ def test_linux_command(self): windows=False) self.assertEqual(command, ["sh", os.path.join("/r", "scripts", "play-linux.sh"), os.path.join("/g", launcher.EXPECTED_EXE), "--series-x"]) + command = launcher.play_command(settings(game_dir="/g", log=True), repo="/r", windows=False) + self.assertEqual(command[2:], [os.path.join("/g", launcher.EXPECTED_EXE), "--log"]) + + def test_the_proton_folder_goes_to_play_linux_sh(self): + base = {"PATH": "/bin", "LEONIDA_PROTON": "/from/the/shell"} + self.assertEqual(launcher.play_environment(settings(proton_dir=" /p "), base)["LEONIDA_PROTON"], "/p") + self.assertEqual(launcher.play_environment(settings(), base), base) + self.assertNotIn("LEONIDA_PROTON", launcher.play_environment(settings(), {"PATH": "/bin"})) + self.assertEqual(launcher.proton_command(repo="/r"), + ["sh", os.path.join("/r", "scripts", "play-linux.sh"), "--find-proton"]) + self.assertIn('"--find-proton"', (ROOT / "scripts" / "play-linux.sh").read_text(encoding="utf-8")) + + def test_system_wine_goes_to_play_linux_sh_as_leonida_wine(self): + base = {"PATH": "/bin", "LEONIDA_PROTON": "/from/the/shell"} + env = launcher.play_environment(settings(proton_dir=launcher.SYSTEM_WINE), base) + self.assertEqual(env["LEONIDA_WINE"], "wine") + self.assertNotIn("LEONIDA_PROTON", env) + self.assertEqual(base["LEONIDA_PROTON"], "/from/the/shell") + self.assertIn("LEONIDA_WINE", (ROOT / "scripts" / "play-linux.sh").read_text(encoding="utf-8")) + + @unittest.skipIf(os.name == "nt" or not os.path.exists("/bin/sh"), "POSIX shell script") + def test_find_proton_names_the_system_wine_when_it_is_chosen(self): + with tempfile.TemporaryDirectory() as tmp: + bin_dir = Path(tmp, "bin") + bin_dir.mkdir() + wine = bin_dir / "wine" + wine.write_text('#!/bin/sh\n[ "$1" = --version ] && echo wine-99.0\nexit 0\n', encoding="utf-8") + wine.chmod(0o755) + dxvk = Path(tmp, "dxvk") + dxvk.mkdir() + (dxvk / "dxgi.dll").write_bytes(b"x") + base = {"PATH": os.pathsep.join([str(bin_dir), "/usr/bin", "/bin"]), "HOME": tmp, + "LEONIDA_DXVK": str(dxvk)} + self.assertEqual(launcher.find_proton(settings(proton_dir=launcher.SYSTEM_WINE), repo=str(ROOT), + base=base), (True, "Wine 99.0", str(wine))) + if not system_proton_installed(): + self.assertEqual(launcher.list_protons(repo=str(ROOT), base=dict(base, LEONIDA_WINE="nowhere")), []) + + @unittest.skipIf(os.name == "nt" or not os.path.exists("/bin/sh"), "POSIX shell script") + def test_find_proton_reports_what_play_linux_sh_uses(self): + with tempfile.TemporaryDirectory() as tmp: + proton = Path(tmp, "GE-Proton99-4") + (proton / "files" / "bin").mkdir(parents=True) + (proton / "files" / "bin" / "wine").write_text("#!/bin/sh\n", encoding="utf-8") + (proton / "files" / "bin" / "wine").chmod(0o755) + dxvk = proton / "files" / "lib" / "wine" / "dxvk" / "x86_64-windows" + dxvk.mkdir(parents=True) + (dxvk / "dxgi.dll").write_bytes(b"x") + base = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": tmp} + found, name, folder = launcher.find_proton(settings(proton_dir=str(proton)), repo=str(ROOT), base=base) + self.assertEqual((found, name, folder), (True, "GE-Proton99-4", str(proton.resolve()))) + found, message, folder = launcher.find_proton(settings(proton_dir=os.path.join(tmp, "missing")), + repo=str(ROOT), base=base) + self.assertFalse(found) + self.assertIn("is not a Proton build", message) + self.assertEqual(folder, "") + + @unittest.skipIf(os.name == "nt" or not os.path.exists("/bin/sh"), "POSIX shell script") + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_list_protons_reports_every_build_play_linux_sh_finds(self): + with tempfile.TemporaryDirectory() as tmp: + tools = Path(tmp, ".local", "share", "Steam", "compatibilitytools.d") + partial = tools / "Proton-Wineland Latest" + (partial / "files" / "bin").mkdir(parents=True) + (partial / "files" / "bin" / "wine").write_text("#!/bin/sh\n", encoding="utf-8") + (partial / "files" / "bin" / "wine").chmod(0o755) + (partial / "version").write_text("1 wineland-99.0\n", encoding="utf-8") + for name in ("GE-Proton98-1", "GE-Proton99-2"): + proton = tools / name + (proton / "files" / "lib" / "wine").mkdir(parents=True) + (proton / "files" / "bin").mkdir(parents=True) + (proton / "files" / "bin" / "wine").write_text("#!/bin/sh\n", encoding="utf-8") + (proton / "files" / "bin" / "wine").chmod(0o755) + dxvk = proton / "files" / "lib" / "wine" / "dxvk" / "x86_64-windows" + dxvk.mkdir(parents=True) + (dxvk / "dxgi.dll").write_bytes(b"x") + base = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": tmp, "LEONIDA_PROTON": "/elsewhere"} + self.assertEqual(launcher.list_protons(repo=str(ROOT), base=base), + [("GE-Proton99-2", str((tools / "GE-Proton99-2").resolve())), + ("GE-Proton98-1", str((tools / "GE-Proton98-1").resolve()))]) + self.assertEqual(launcher.list_protons(repo=os.path.join(tmp, "nowhere"), base=base), []) + + def test_automatic_is_its_own_entry_and_named_protons_store_their_folder(self): + found = [("GE-Proton99-2", "/p/99"), ("GE-Proton98-1", "/p/98")] + choices = launcher.proton_choices(found, "/usr/bin/wine") + self.assertEqual(choices, [("Automatic: GE-Proton99-2 (/p/99)", "", "/p/99"), + ("GE-Proton99-2 (/p/99)", "/p/99", "/p/99"), + ("GE-Proton98-1 (/p/98)", "/p/98", "/p/98"), + ("System Wine (/usr/bin/wine)", launcher.SYSTEM_WINE, launcher.SYSTEM_WINE)]) + self.assertEqual(launcher.proton_label(choices, ""), "Automatic: GE-Proton99-2 (/p/99)") + self.assertEqual(launcher.proton_label(choices, "/p/99"), "GE-Proton99-2 (/p/99)") + self.assertEqual(launcher.proton_label(choices, "/p/98"), "GE-Proton98-1 (/p/98)") + self.assertEqual(launcher.proton_label(choices, launcher.SYSTEM_WINE), "System Wine (/usr/bin/wine)") + self.assertEqual(launcher.proton_label(choices, "/my/proton"), "/my/proton") + self.assertFalse(any(label.startswith("Newest") for label, _value, _target in choices)) + + def test_the_first_named_proton_wins_over_an_inherited_runner(self): + found = [("GE-Proton99-2", "/p/99"), ("GE-Proton98-1", "/p/98")] + first = launcher.proton_choices(found, None)[1] + base = {"PATH": "/bin", "LEONIDA_PROTON": "/p/98", "LEONIDA_WINE": "wine"} + env = launcher.play_environment(settings(proton_dir=first[1]), base) + self.assertEqual(env["LEONIDA_PROTON"], "/p/99") + self.assertNotIn("LEONIDA_WINE", env) + self.assertEqual(base["LEONIDA_PROTON"], "/p/98") + + def test_without_a_proton_the_system_wine_is_the_automatic_entry(self): + choices = launcher.proton_choices([], "/usr/bin/wine") + self.assertEqual(choices, [("Automatic: System Wine (/usr/bin/wine)", "", launcher.SYSTEM_WINE), + ("System Wine (/usr/bin/wine)", launcher.SYSTEM_WINE, launcher.SYSTEM_WINE)]) + self.assertEqual(launcher.proton_label(choices, ""), "Automatic: System Wine (/usr/bin/wine)") + self.assertEqual(launcher.proton_label(choices, launcher.SYSTEM_WINE), "System Wine (/usr/bin/wine)") + nothing = launcher.proton_choices([], None) + self.assertEqual(nothing, [("No Proton or Wine found", "", "")]) + self.assertEqual(launcher.proton_label(nothing, launcher.SYSTEM_WINE), "System Wine (not found)") def test_no_game_folder_is_refused(self): with self.assertRaises(ValueError): @@ -119,8 +253,13 @@ def test_no_game_folder_is_refused(self): def test_tools(self): self.assertEqual(launcher.tool_command("get_dlss", repo="R", windows=True)[:2], ["cmd", "/c"]) self.assertTrue(launcher.tool_command("build", repo="R", windows=True)[-1].endswith("build-nvidia.ps1")) + self.assertEqual(launcher.tool_command("build", repo="/r", windows=False), + ["sh", os.path.join("/r", "scripts", "build-d3d12-linux.sh")]) + self.assertEqual(launcher.tool_command("build", repo="/r", windows=False, accept_sdk_licence=True)[:2], + ["env", "XWIN_ACCEPT_LICENSE=1"]) + self.assertTrue((ROOT / "scripts" / "build-d3d12-linux.sh").is_file()) with self.assertRaises(ValueError): - launcher.tool_command("build", windows=False) + launcher.tool_command("get_dlss", windows=False) with self.assertRaises(ValueError): launcher.tool_command("nope", windows=True) diff --git a/tests/test_play_linux.py b/tests/test_play_linux.py new file mode 100644 index 0000000000..b985a702f3 --- /dev/null +++ b/tests/test_play_linux.py @@ -0,0 +1,1065 @@ +import os +import shutil +import subprocess +import tempfile +import time +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +TARGET = Path("d3d12") / "target" +CROSS = TARGET / "x86_64-pc-windows-msvc" / "diag" / "leonida.exe" +SCRIPT = ROOT / "scripts" / "play-linux.sh" +DXVK = Path("files", "lib", "wine", "dxvk", "x86_64-windows") +PROTON_VKD3D = Path("files", "lib", "wine", "vkd3d-proton", "x86_64-windows") +NEW_STRUCTURIZER = b"MZ vkd3d-proton legacy_structurizer" +SYSTEM_TOOLS = (Path("/usr/share/steam/compatibilitytools.d"), Path("/usr/local/share/steam/compatibilitytools.d")) + +STUB_WINE = """#!/bin/sh +if [ "$1" = wineboot ]; then + mkdir -p "$WINEPREFIX/drive_c/windows/system32" + exit 0 +fi +for a in "$@"; do printf '%s\\n' "$a"; done > "$LEONIDA_STUB_LOG" +exit 0 +""" + +HELD_CP = """#!/bin/sh +"$LEONIDA_REAL_CP" "$@" || exit +case $1 in + */d3d12.dll) + if mkdir "$LEONIDA_HOLD" 2>/dev/null; then + : > "$LEONIDA_HOLD/copied" + while [ ! -e "$LEONIDA_HOLD/release" ]; do sleep 0.05; done + fi + ;; +esac +""" + +PROTON_WINE = """#!/bin/sh +printf '%s\\n' "$*" >> "$LEONIDA_TEST_LOG" +printf '%s\\n' "$WINEDLLOVERRIDES" > "$LEONIDA_TEST_LOG.overrides" +printf '%s\\n' "${WINEDLLPATH:-}" > "$LEONIDA_TEST_LOG.dllpath" +printf '%s\\n' "${LD_LIBRARY_PATH:-}" > "$LEONIDA_TEST_LOG.ldpath" +printf '%s\\n' "${VKD3D_SHADER_CACHE_PATH:-}" > "$LEONIDA_TEST_LOG.shadercache" +if [ "$1" = wineboot ]; then + [ -n "${LEONIDA_TEST_WINEBOOT_FAILS:-}" ] && exit 3 + mkdir -p "$WINEPREFIX/drive_c/windows/system32" + exit 0 +fi +echo "runtime error output" >&2 +echo "runtime output" +exit 0 +""" + +SYSTEM_WINE = """#!/bin/sh +printf '%s\\n' "$*" >> "$LEONIDA_TEST_LOG.system" +exit 0 +""" + + +WINE_RUNS = """#!/bin/sh +if [ "$1" = --version ]; then + echo "wine-99.0 (Staging)" + exit 0 +fi +printf '%s\\n' "$*" >> "$LEONIDA_TEST_LOG" +printf '%s\\n' "$WINEDLLOVERRIDES" > "$LEONIDA_TEST_LOG.overrides" +printf '%s\\n' "${WINEDLLPATH:-}" > "$LEONIDA_TEST_LOG.dllpath" +if [ "$1" = wineboot ]; then + mkdir -p "$WINEPREFIX/drive_c/windows/system32" +fi +exit 0 +""" + +SYSTEM_DXVK = tuple(Path(d) for d in ("/usr/share/dxvk/x64", "/usr/lib/dxvk/x64", "/usr/lib/dxvk/wine64", + "/usr/share/dxvk/x86_64-windows", "/usr/lib/dxvk/x86_64-windows")) + + +def system_proton_installed(): + return any(tools.is_dir() and any(tools.iterdir()) for tools in SYSTEM_TOOLS) + + +def system_dxvk_installed(): + return any((folder / "dxgi.dll").is_file() for folder in SYSTEM_DXVK) + + +@unittest.skipIf(os.name == "nt" or not os.path.exists("/bin/sh"), "POSIX shell script") +class PlayLinuxTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.tmp = Path(tmp.name) + self.repo = self.tmp / "repo" + (self.repo / "scripts").mkdir(parents=True) + shutil.copy(ROOT / "scripts" / "play-linux.sh", self.repo / "scripts" / "play-linux.sh") + self.game = self.tmp / "game" / "game_scarlett_master.exe" + self.game.parent.mkdir() + self.game.write_bytes(b"MZ") + self.proton = self.tmp / "proton" + (self.proton / "files" / "bin").mkdir(parents=True) + (self.proton / "files" / "bin" / "wine").write_text(STUB_WINE, encoding="utf-8", newline="\n") + (self.proton / "files" / "bin" / "wine").chmod(0o755) + (self.proton / DXVK).mkdir(parents=True) + (self.proton / DXVK / "dxgi.dll").write_bytes(b"dxgi") + self.log = self.tmp / "wine.log" + + def touch(self, relative): + path = self.repo / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"x") + return path + + def vkd3d(self, folder): + for dll in ("d3d12.dll", "d3d12core.dll"): + self.touch(Path(folder) / dll) + + def play(self, **extra): + env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(self.tmp / "home"), + "LEONIDA_PROTON": str(self.proton), "LEONIDA_STUB_LOG": str(self.log), **extra} + return subprocess.run(["/bin/sh", str(self.repo / "scripts" / "play-linux.sh"), str(self.game)], + env=env, capture_output=True, text=True, timeout=60) + + def started(self): + return self.log.read_text(encoding="utf-8").splitlines() + + def test_no_runtime_names_the_build_script(self): + result = self.play() + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("build-d3d12-linux.sh", result.stderr) + self.assertIn("LEONIDA_RUNTIME", result.stderr) + self.assertFalse(self.log.exists()) + + def test_checkout_layout(self): + exe = self.touch(CROSS) + self.vkd3d(TARGET / "vkd3d-proton") + result = self.play() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.started()[:2], [str(exe), "run"]) + + def test_windows_build_copied_into_the_checkout(self): + exe = self.touch(TARGET / "diag" / "leonida.exe") + self.vkd3d(TARGET / "vkd3d-proton") + result = self.play() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.started()[0], str(exe)) + + def test_package_layout_comes_first(self): + self.touch(CROSS) + exe = self.touch(Path("scripts") / "leonida.exe") + self.vkd3d(Path("scripts") / "vkd3d-proton") + result = self.play() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.started()[0], str(exe)) + + def test_leonida_runtime_wins(self): + self.touch(CROSS) + self.vkd3d(TARGET / "vkd3d-proton") + own = self.touch("elsewhere/leonida.exe") + result = self.play(LEONIDA_RUNTIME=str(own)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.started()[0], str(own)) + missing = self.play(LEONIDA_RUNTIME=str(self.tmp / "nope.exe")) + self.assertEqual(missing.returncode, 1) + self.assertIn("LEONIDA_RUNTIME", missing.stderr) + + def proton_vkd3d(self, core, build=None, lib="lib"): + folder = self.proton / "files" / lib / PROTON_VKD3D.relative_to(Path("files", "lib")) + folder.mkdir(parents=True) + (folder / "d3d12.dll").write_bytes(b"MZ proton d3d12") + (folder / "d3d12core.dll").write_bytes(core) + if build is not None: + (folder.parent / "version").write_text(f" 0123abcd vkd3d-proton ({build})\n", encoding="utf-8") + return folder + + def installed(self, dll): + system32 = self.tmp / "home" / ".local" / "share" / "leonida" / "prefix" / "drive_c" / "windows" / "system32" + return (system32 / dll).read_bytes() + + def test_a_proton_vkd3d_with_the_new_structurizer_replaces_the_bundled_one(self): + self.touch(CROSS) + self.vkd3d(TARGET / "vkd3d-proton") + folder = self.proton_vkd3d(NEW_STRUCTURIZER, "vkd3d-1.1-9999-g0123abcd") + result = self.play() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("the VKD3D-Proton of proton (vkd3d-1.1-9999-g0123abcd)", result.stdout) + self.assertNotIn("structurizer", result.stderr) + for dll in ("d3d12.dll", "d3d12core.dll"): + self.assertEqual(self.installed(dll), (folder / dll).read_bytes()) + + def test_a_proton_vkd3d_under_lib64_replaces_the_bundled_one(self): + self.touch(CROSS) + self.vkd3d(TARGET / "vkd3d-proton") + folder = self.proton_vkd3d(NEW_STRUCTURIZER, "vkd3d-1.1-9999-g0123abcd", lib="lib64") + result = self.play() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("the VKD3D-Proton of proton (vkd3d-1.1-9999-g0123abcd)", result.stdout) + for dll in ("d3d12.dll", "d3d12core.dll"): + self.assertEqual(self.installed(dll), (folder / dll).read_bytes()) + + def test_an_old_layout_proton_vkd3d_under_lib64_replaces_the_bundled_one(self): + self.touch(CROSS) + self.vkd3d(TARGET / "vkd3d-proton") + folder = self.proton / "files" / "lib64" / "wine" / "vkd3d-proton" + folder.mkdir(parents=True) + (folder / "d3d12.dll").write_bytes(b"MZ proton d3d12") + (folder / "d3d12core.dll").write_bytes(NEW_STRUCTURIZER) + (folder / "version").write_text(" 0123abcd vkd3d-proton (vkd3d-1.1-9999-g0123abcd)\n", encoding="utf-8") + result = self.play() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("the VKD3D-Proton of proton (vkd3d-1.1-9999-g0123abcd)", result.stdout) + for dll in ("d3d12.dll", "d3d12core.dll"): + self.assertEqual(self.installed(dll), (folder / dll).read_bytes()) + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_a_proton_vkd3d_stands_in_for_a_missing_bundled_one(self): + self.touch(CROSS) + folder = self.proton_vkd3d(NEW_STRUCTURIZER) + result = self.play() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("the VKD3D-Proton of proton", result.stdout) + self.assertEqual(self.installed("d3d12core.dll"), (folder / "d3d12core.dll").read_bytes()) + + def test_a_bundled_vkd3d_with_the_new_structurizer_is_kept(self): + self.touch(CROSS) + bundled = self.repo / TARGET / "vkd3d-proton" + self.vkd3d(TARGET / "vkd3d-proton") + (bundled / "d3d12core.dll").write_bytes(NEW_STRUCTURIZER + b" bundled") + self.proton_vkd3d(NEW_STRUCTURIZER) + result = self.play() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("the bundled VKD3D-Proton", result.stdout) + self.assertEqual(self.installed("d3d12core.dll"), (bundled / "d3d12core.dll").read_bytes()) + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_without_a_newer_vkd3d_the_start_says_what_to_install(self): + self.touch(CROSS) + self.vkd3d(TARGET / "vkd3d-proton") + self.proton_vkd3d(b"MZ vkd3d-proton 3.0") + result = self.play() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("new structurizer", result.stderr) + self.assertIn("LEONIDA_VKD3D", result.stderr) + self.assertIn("the bundled VKD3D-Proton", result.stdout) + self.assertEqual(self.installed("d3d12core.dll"), b"x") + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_another_proton_lends_its_vkd3d_when_none_was_chosen(self): + self.touch(CROSS) + self.vkd3d(TARGET / "vkd3d-proton") + tools = self.tmp / "home" / ".local" / "share" / "Steam" / "compatibilitytools.d" + tools.mkdir(parents=True) + older = tools / "GE-Proton98-1" + shutil.copytree(self.proton, tools / "GE-Proton99-4") + shutil.copytree(self.proton, older) + (older / PROTON_VKD3D).mkdir(parents=True) + for dll in ("d3d12.dll", "d3d12core.dll"): + (older / PROTON_VKD3D / dll).write_bytes(NEW_STRUCTURIZER + dll.encode()) + result = self.play(LEONIDA_PROTON="") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("under GE-Proton99-4", result.stdout) + self.assertIn("the VKD3D-Proton of GE-Proton98-1", result.stdout) + self.assertEqual(self.installed("d3d12core.dll"), NEW_STRUCTURIZER + b"d3d12core.dll") + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_another_proton_lends_its_vkd3d_to_a_chosen_one(self): + self.touch(CROSS) + self.vkd3d(TARGET / "vkd3d-proton") + other = self.tmp / "home" / ".local" / "share" / "Steam" / "compatibilitytools.d" / "GE-Proton99-4" + shutil.copytree(self.proton, other) + (other / PROTON_VKD3D).mkdir(parents=True) + for dll in ("d3d12.dll", "d3d12core.dll"): + (other / PROTON_VKD3D / dll).write_bytes(NEW_STRUCTURIZER + dll.encode()) + result = self.play() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("structurizer", result.stderr) + self.assertIn("under proton", result.stdout) + self.assertIn("the VKD3D-Proton of GE-Proton99-4", result.stdout) + self.assertEqual(self.installed("d3d12core.dll"), NEW_STRUCTURIZER + b"d3d12core.dll") + + def lending_proton(self, name, core, build=None): + folder = self.tmp / "home" / ".local" / "share" / "Steam" / "compatibilitytools.d" / name + shutil.copytree(self.proton, folder) + (folder / "version").write_text(f"1700000000 {name}\n", encoding="utf-8") + (folder / PROTON_VKD3D).mkdir(parents=True) + (folder / PROTON_VKD3D / "d3d12.dll").write_bytes(b"MZ d3d12 " + name.encode()) + (folder / PROTON_VKD3D / "d3d12core.dll").write_bytes(core + b" " + name.encode()) + if build is not None: + (folder / PROTON_VKD3D.parent / "version").write_text(f" 0123abcd vkd3d-proton ({build})\n", + encoding="utf-8") + return folder + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_a_build_without_the_legacy_structurizer_name_is_known_by_its_version(self): + cases = ( + (b"MZ vkd3d-proton", "v3.1-97-g71cae091b", True), + (b"MZ vkd3d-proton", "vkd3d-1.1-5783-g71cae091b", True), + (b"MZ vkd3d-proton", "vkd3d-1.1-5708-g0123abcd", True), + (b"MZ vkd3d-proton\0v3.1-97-g71cae091b-GE-Proton(dirty)+\0", None, True), + (b"MZ vkd3d-proton\0vkd3d\0003.2.0\0", None, True), + (b"MZ vkd3d-proton\0v3.2-4-g0123abcd\0", "vkd3d-1.1-5700-g0123abcd", True), + (b"MZ vkd3d-proton", "vkd3d-1.1-5707-g0123abcd", False), + (b"MZ vkd3d-proton", "vkd3d-1.1-5600-g0123abcd", False), + (b"MZ vkd3d-proton", "v3.1-21-g0123abcd", False), + (b"MZ vkd3d-proton\0vkd3d\0003.1.0\0", None, False), + (b"MZ vkd3d-proton\0v3.0-120-g0123abcd\0", "vkd3d-1.1-5783-g71cae091b", False), + (b"MZ vkd3d-proton 3.2.0", None, False), + (b"MZ vkd3d-proton", None, False), + ) + for core, build, new in cases: + with self.subTest(core=core, build=build): + shutil.rmtree(self.proton / "files" / "lib" / "wine" / "vkd3d-proton", ignore_errors=True) + shutil.rmtree(self.tmp / "home", ignore_errors=True) + self.touch(CROSS) + self.vkd3d(TARGET / "vkd3d-proton") + folder = self.proton_vkd3d(core, build) + result = self.play() + self.assertEqual(result.returncode, 0, result.stderr) + if new: + self.assertIn("the VKD3D-Proton of proton", result.stdout) + self.assertNotIn("structurizer", result.stderr) + self.assertEqual(self.installed("d3d12core.dll"), (folder / "d3d12core.dll").read_bytes()) + else: + self.assertIn("the bundled VKD3D-Proton", result.stdout) + self.assertIn("new structurizer", result.stderr) + self.assertEqual(self.installed("d3d12core.dll"), b"x") + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_the_newest_vkd3d_build_is_taken_whichever_proton_ranks_first(self): + self.touch(CROSS) + self.vkd3d(TARGET / "vkd3d-proton") + self.lending_proton("hotfix-20261110", NEW_STRUCTURIZER, "vkd3d-1.1-5729-g00b6ef057") + newest = self.lending_proton("GE-Proton11-15", b"MZ vkd3d-proton", "v3.1-97-g71cae091b") + self.lending_proton("GE-Proton11-14", NEW_STRUCTURIZER + b"\0v3.1-83-gcae8353ed-GE-Proton(dirty)+\0", + "vkd3d-1.1-5769-gcae8353ed") + for chosen in ("", str(newest), str(newest.parent / "hotfix-20261110")): + with self.subTest(chosen=chosen): + result = self.play(LEONIDA_PROTON=chosen) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("structurizer", result.stderr) + self.assertIn("the VKD3D-Proton of GE-Proton11-15 (v3.1-97-g71cae091b)", result.stdout) + self.assertEqual(self.installed("d3d12core.dll"), b"MZ vkd3d-proton GE-Proton11-15") + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_among_equal_builds_the_proton_in_use_then_the_highest_ranked_lends_its_vkd3d(self): + self.touch(CROSS) + self.vkd3d(TARGET / "vkd3d-proton") + self.lending_proton("hotfix-20261110", NEW_STRUCTURIZER, "vkd3d-1.1-5729-g00b6ef057") + same = self.lending_proton("GE-Proton11-15", b"MZ vkd3d-proton", "vkd3d-1.1-5783-g71cae091b") + self.lending_proton("GE-Proton99-1", b"MZ vkd3d-proton\0v3.1-97-g71cae091b\0") + result = self.play(LEONIDA_PROTON=str(same)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("under GE-Proton11-15", result.stdout) + self.assertIn("the VKD3D-Proton of GE-Proton11-15 (vkd3d-1.1-5783-g71cae091b)", result.stdout) + self.assertEqual(self.installed("d3d12core.dll"), b"MZ vkd3d-proton GE-Proton11-15") + result = self.play(LEONIDA_PROTON="") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("under hotfix-20261110", result.stdout) + self.assertIn("the VKD3D-Proton of GE-Proton99-1", result.stdout) + self.assertEqual(self.installed("d3d12core.dll"), b"MZ vkd3d-proton\0v3.1-97-g71cae091b\0 GE-Proton99-1") + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_a_build_known_only_by_the_legacy_structurizer_name_comes_after_newer_builds(self): + self.touch(CROSS) + self.vkd3d(TARGET / "vkd3d-proton") + self.lending_proton("GE-Proton99-4", NEW_STRUCTURIZER) + self.lending_proton("GE-Proton98-1", b"MZ vkd3d-proton", "v3.1-97-g71cae091b") + result = self.play(LEONIDA_PROTON="") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("under GE-Proton99-4", result.stdout) + self.assertIn("the VKD3D-Proton of GE-Proton98-1", result.stdout) + self.assertEqual(self.installed("d3d12core.dll"), b"MZ vkd3d-proton GE-Proton98-1") + + def test_leonida_vkd3d_wins_over_a_proton_vkd3d(self): + self.touch(CROSS) + own = self.repo / "own-vkd3d" + self.vkd3d("own-vkd3d") + self.proton_vkd3d(NEW_STRUCTURIZER) + result = self.play(LEONIDA_VKD3D=str(own)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("structurizer", result.stderr) + self.assertIn(f"the VKD3D-Proton in {own} (LEONIDA_VKD3D)", result.stdout) + self.assertEqual(self.installed("d3d12core.dll"), (own / "d3d12core.dll").read_bytes()) + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_missing_vkd3d_names_the_fetch(self): + self.touch(CROSS) + result = self.play() + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("fetch_vkd3d_proton.py", result.stderr) + self.assertIn("build-d3d12-linux.sh", result.stderr) + + +@unittest.skipIf(os.name == "nt" or not os.path.exists("/bin/sh"), "POSIX shell script") +class PlayLinuxProtonTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.tmp = Path(tmp.name) + self.home = self.tmp / "home" + self.steam = self.home / ".local" / "share" / "Steam" + self.steam.mkdir(parents=True) + self.script = self.tmp / "repo" / "scripts" / "play-linux.sh" + self.script.parent.mkdir(parents=True) + shutil.copy(SCRIPT, self.script) + self.log = self.tmp / "log" + bin_dir = self.tmp / "bin" + bin_dir.mkdir() + for name in ("wine", "wine64", "wineboot", "wineserver"): + stub = bin_dir / name + stub.write_text(SYSTEM_WINE, encoding="utf-8", newline="\n") + stub.chmod(0o755) + self.path = os.pathsep.join([str(bin_dir), os.environ.get("PATH", "/usr/bin:/bin")]) + self.package = self.tmp / "package" + (self.package / "vkd3d-proton").mkdir(parents=True) + for dll in ("d3d12.dll", "d3d12core.dll"): + (self.package / "vkd3d-proton" / dll).write_bytes(b"vkd3d " + dll.encode()) + (self.package / "leonida.exe").write_bytes(b"MZ") + (self.package / "d3dcompiler").mkdir() + (self.package / "d3dcompiler" / "d3dcompiler_47.dll").write_bytes(b"MZ d3dcompiler_47") + self.game = self.tmp / "game" / "game_scarlett_master.exe" + self.game.parent.mkdir() + self.game.write_bytes(b"MZ") + + def proton(self, folder, version=None, dxvk=True, wine=True, lib=True, lib_name="lib"): + folder = Path(folder) + (folder / "files" / "bin").mkdir(parents=True) + if lib: + (folder / "files" / lib_name / "wine").mkdir(parents=True, exist_ok=True) + if wine: + stub = folder / "files" / "bin" / "wine" + stub.write_text(PROTON_WINE, encoding="utf-8", newline="\n") + stub.chmod(0o755) + server = folder / "files" / "bin" / "wineserver" + server.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8", newline="\n") + server.chmod(0o755) + if dxvk: + dxgi = folder / "files" / lib_name / DXVK.relative_to(Path("files", "lib")) + dxgi.mkdir(parents=True) + (dxgi / "dxgi.dll").write_bytes(b"dxvk dxgi " + folder.name.encode()) + if version is not None: + (folder / "version").write_text(version + "\n", encoding="utf-8") + return folder + + def run_script(self, *args, **env): + environment = {"PATH": self.path, "HOME": str(self.home), "LEONIDA_TEST_LOG": str(self.log), + "LEONIDA_RUNTIME": str(self.package / "leonida.exe"), + "LEONIDA_VKD3D": str(self.package / "vkd3d-proton"), + "LEONIDA_D3DCOMPILER": str(self.package / "d3dcompiler")} + environment.update(env) + return subprocess.run(["/bin/sh", str(self.script), *args], env=environment, capture_output=True, text=True, + timeout=60) + + def start_script(self, *args, **env): + environment = {"PATH": self.path, "HOME": str(self.home), "LEONIDA_TEST_LOG": str(self.log), + "LEONIDA_RUNTIME": str(self.package / "leonida.exe"), + "LEONIDA_VKD3D": str(self.package / "vkd3d-proton")} + environment.update(env) + return subprocess.Popen(["/bin/sh", str(self.script), *args], env=environment, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True) + + def found(self, **env): + p = self.run_script("--find-proton", **env) + self.assertEqual(p.returncode, 0, p.stderr) + name, folder = p.stdout.strip().split("\t") + return name, Path(folder) + + def calls(self): + return self.log.read_text(encoding="utf-8").splitlines() if self.log.exists() else [] + + def assert_system_wine_unused(self): + self.assertFalse(Path(str(self.log) + ".system").exists(), "the system's Wine was started") + + def test_the_newest_complete_proton_is_picked(self): + tools = self.steam / "compatibilitytools.d" + self.proton(tools / "GE-Proton98-30", "1700000000 GE-Proton98-30") + newest = self.proton(tools / "GE-Proton99-4", "1700000000 GE-Proton99-4") + self.proton(tools / "GE-Proton99-12-partial", "1700000000 GE-Proton99-12", dxvk=False, lib=False) + self.proton(tools / "GE-Proton99-13-nowine", "1700000000 GE-Proton99-13", wine=False) + (tools / "not-a-proton").mkdir() + self.proton(self.steam / "steamapps" / "common" / "Proton - Experimental", + "1700000000 experimental-99.0-20261120") + self.proton(self.steam / "steamapps" / "common" / "Proton 99.0", "1700000000 proton-99.0-3") + self.assertEqual(self.found(), ("GE-Proton99-4", newest.resolve())) + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_list_protons_names_every_usable_build_newest_first_once(self): + tools = self.steam / "compatibilitytools.d" + older = self.proton(tools / "GE-Proton98-30", "1700000000 GE-Proton98-30") + newest = self.proton(tools / "GE-Proton99-4", "1700000000 GE-Proton99-4") + self.proton(tools / "Proton-Wineland Latest", "1700000000 wineland-99.0-20261127", dxvk=False, lib=False) + valve = self.proton(self.steam / "steamapps" / "common" / "Proton 99.0", "1700000000 proton-99.0-3") + (self.home / ".steam").mkdir() + (self.home / ".steam" / "root").symlink_to(self.steam) + p = self.run_script("--list-protons", LEONIDA_PROTON=str(older)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertEqual([line.split("\t") for line in p.stdout.splitlines()], + [["GE-Proton99-4", str(newest.resolve())], ["proton-99.0-3", str(valve.resolve())], + ["GE-Proton98-30", str(older.resolve())]]) + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_list_protons_without_any_build_is_empty(self): + p = self.run_script("--list-protons") + self.assertEqual((p.returncode, p.stdout), (0, "")) + + def test_valve_proton_is_ranked_by_its_version(self): + common = self.steam / "steamapps" / "common" + self.proton(common / "Proton 99.0", "1700000000 proton-99.0-3") + experimental = self.proton(common / "Proton - Experimental", "1700000000 experimental-99.0-20261120") + self.proton(common / "Proton EasyAntiCheat Runtime", dxvk=False, wine=False) + self.assertEqual(self.found(), ("experimental-99.0-20261120", experimental.resolve())) + + def test_without_a_version_file_the_folder_name_is_the_version(self): + tools = self.steam / "compatibilitytools.d" + self.proton(tools / "GE-Proton98-1") + newest = self.proton(tools / "GE-Proton99-2") + self.assertEqual(self.found(), ("GE-Proton99-2", newest.resolve())) + + def test_other_steam_folders_libraries_and_extra_paths_are_searched(self): + library = self.tmp / "games" / "SteamLibrary" + steam_root = self.home / ".steam" / "root" + (steam_root / "steamapps").mkdir(parents=True) + (steam_root / "steamapps" / "libraryfolders.vdf").write_text( + '"libraryfolders"\n{\n\t"1"\n\t{\n\t\t"path"\t\t"' + str(library) + '"\n\t}\n}\n', encoding="utf-8") + in_library = self.proton(library / "steamapps" / "common" / "Proton 99.0", "1700000000 proton-99.0-7") + self.assertEqual(self.found(), ("proton-99.0-7", in_library.resolve())) + extra = self.tmp / "extra" + flatpak = self.home / ".var" / "app" / "com.valvesoftware.Steam" / "data" / "Steam" + in_flatpak = self.proton(flatpak / "compatibilitytools.d" / "GE-Proton99-8", "1 GE-Proton99-8") + self.assertEqual(self.found(), ("GE-Proton99-8", in_flatpak.resolve())) + in_extra = self.proton(extra / "GE-Proton99-9", "1 GE-Proton99-9") + self.assertEqual(self.found(STEAM_EXTRA_COMPAT_TOOLS_PATHS=f"/nowhere:{extra}"), + ("GE-Proton99-9", in_extra.resolve())) + + def test_leonida_proton_wins_and_takes_the_folder_or_its_wine(self): + tools = self.steam / "compatibilitytools.d" + self.proton(tools / "GE-Proton99-9", "1 GE-Proton99-9") + chosen = self.proton(self.tmp / "my proton", "1 GE-Proton10-25") + for value in (str(chosen), str(chosen) + "/", str(chosen / "files" / "bin" / "wine")): + with self.subTest(value=value): + self.assertEqual(self.found(LEONIDA_PROTON=value), ("GE-Proton10-25", chosen.resolve())) + + def test_a_leonida_proton_that_is_no_proton_is_refused(self): + self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-9", "1 GE-Proton99-9") + partial = self.proton(self.tmp / "partial proton", dxvk=False, lib=False) + for value in (str(partial), str(self.tmp / "missing")): + with self.subTest(value=value): + p = self.run_script(str(self.game), LEONIDA_PROTON=value) + self.assertEqual(p.returncode, 1) + self.assertIn("is not a Proton build", p.stderr) + self.assertEqual(self.calls(), []) + self.assert_system_wine_unused() + + def test_a_proton_without_dxvk_runs_with_the_dxgi_of_another(self): + tools = self.steam / "compatibilitytools.d" + lender = self.proton(tools / "GE-Proton98-30", "1 GE-Proton98-30") + self.proton(tools / "DW-Proton Latest", "1 dwproton-99.0-17", dxvk=False) + p = self.run_script(str(self.game)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("under dwproton-99.0-17", p.stdout) + self.assertIn("with DXVK's dxgi of GE-Proton98-30", p.stdout) + system32 = self.home / ".local" / "share" / "leonida" / "prefix" / "drive_c" / "windows" / "system32" + self.assertEqual((system32 / "dxgi.dll").read_bytes(), (lender / DXVK / "dxgi.dll").read_bytes()) + self.assert_system_wine_unused() + + def test_the_game_runs_under_the_proton_wine_with_dxvk_dxgi(self): + proton = self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + p = self.run_script(str(self.game), "--series-x", WINEDLLOVERRIDES="mscoree=") + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("series-x under GE-Proton99-4", p.stdout) + self.assertEqual(self.calls(), ["wineboot -u", f"{self.package / 'leonida.exe'} run {self.game} " + "--execute --console series-x"]) + self.assertEqual(Path(str(self.log) + ".overrides").read_text(encoding="utf-8").strip(), + "mscoree=;d3d12,d3d12core,dxgi,d3dcompiler_47=n") + system32 = self.home / ".local" / "share" / "leonida" / "prefix" / "drive_c" / "windows" / "system32" + self.assertEqual((system32 / "dxgi.dll").read_bytes(), (proton / DXVK / "dxgi.dll").read_bytes()) + for dll in ("d3d12.dll", "d3d12core.dll"): + self.assertEqual((system32 / dll).read_bytes(), (self.package / "vkd3d-proton" / dll).read_bytes()) + self.assertEqual((system32 / "d3dcompiler_47.dll").read_bytes(), b"MZ d3dcompiler_47") + self.assert_system_wine_unused() + + def test_a_leonida_d3dcompiler_without_the_dll_is_refused(self): + self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + empty = self.tmp / "empty" + empty.mkdir() + p = self.run_script(str(self.game), LEONIDA_D3DCOMPILER=str(empty)) + self.assertEqual(p.returncode, 1) + self.assertIn(f"LEONIDA_D3DCOMPILER={empty} has no d3dcompiler_47.dll", p.stderr) + self.assertNotIn(f"{self.package / 'leonida.exe'} run", "\n".join(self.calls())) + + def test_the_required_native_overrides_come_after_inherited_ones(self): + self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + p = self.run_script(str(self.game), WINEDLLOVERRIDES="dxgi=b;d3d12=b") + self.assertEqual(p.returncode, 0, p.stderr) + self.assertEqual(Path(str(self.log) + ".overrides").read_text(encoding="utf-8").strip(), + "dxgi=b;d3d12=b;d3d12,d3d12core,dxgi,d3dcompiler_47=n") + + def test_prefix_dll_links_are_replaced_and_their_targets_kept(self): + proton = self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + system32 = self.home / ".local" / "share" / "leonida" / "prefix" / "drive_c" / "windows" / "system32" + system32.mkdir(parents=True) + shared = self.tmp / "shared" + shared.mkdir() + (shared / "dxgi.dll").write_bytes(b"shared dxgi") + (shared / "d3d12.dll").write_bytes(b"vkd3d d3d12.dll") + (system32 / "dxgi.dll").symlink_to(shared / "dxgi.dll") + (system32 / "d3d12.dll").symlink_to(shared / "d3d12.dll") + (system32 / "d3d12core.dll").symlink_to(self.tmp / "missing.dll") + (system32 / "d3dcompiler_47.dll").symlink_to(shared / "dxgi.dll") + p = self.run_script(str(self.game)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertEqual((shared / "dxgi.dll").read_bytes(), b"shared dxgi") + self.assertEqual((shared / "d3d12.dll").read_bytes(), b"vkd3d d3d12.dll") + self.assertFalse((self.tmp / "missing.dll").exists()) + self.assertEqual((system32 / "dxgi.dll").read_bytes(), (proton / DXVK / "dxgi.dll").read_bytes()) + self.assertEqual((system32 / "d3dcompiler_47.dll").read_bytes(), b"MZ d3dcompiler_47") + for dll in ("dxgi.dll", "d3d12.dll", "d3d12core.dll", "d3dcompiler_47.dll"): + self.assertFalse((system32 / dll).is_symlink(), dll) + self.assertEqual(sorted(path.name for path in system32.glob("*.leonida*")), []) + for dll in ("d3d12.dll", "d3d12core.dll"): + self.assertEqual((system32 / dll).read_bytes(), (self.package / "vkd3d-proton" / dll).read_bytes()) + + def test_two_starts_with_one_prefix_install_the_dlls_side_by_side(self): + proton = self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + p = self.run_script(str(self.game)) + self.assertEqual(p.returncode, 0, p.stderr) + (self.package / "vkd3d-proton" / "d3d12.dll").write_bytes(b"vkd3d d3d12.dll newer") + hold = self.tmp / "hold" + held_bin = self.tmp / "held-bin" + held_bin.mkdir() + cp = held_bin / "cp" + cp.write_text(HELD_CP, encoding="utf-8", newline="\n") + cp.chmod(0o755) + env = {"PATH": os.pathsep.join([str(held_bin), self.path]), "LEONIDA_HOLD": str(hold), + "LEONIDA_REAL_CP": shutil.which("cp")} + first = self.start_script(str(self.game), **env) + try: + for _ in range(600): + if (hold / "copied").exists() or first.poll() is not None: + break + time.sleep(0.05) + self.assertTrue((hold / "copied").exists(), "the first start did not reach its copy") + second = self.run_script(str(self.game), **env) + self.assertEqual(second.returncode, 0, second.stderr) + finally: + hold.mkdir(exist_ok=True) + (hold / "release").touch() + _, err = first.communicate(timeout=60) + self.assertEqual(first.returncode, 0, err) + system32 = self.home / ".local" / "share" / "leonida" / "prefix" / "drive_c" / "windows" / "system32" + for dll in ("d3d12.dll", "d3d12core.dll"): + self.assertEqual((system32 / dll).read_bytes(), (self.package / "vkd3d-proton" / dll).read_bytes()) + self.assertEqual((system32 / "dxgi.dll").read_bytes(), (proton / DXVK / "dxgi.dll").read_bytes()) + self.assertEqual(sorted(path.name for path in system32.glob("*.leonida*")), []) + + def test_a_relative_leonida_proton_ignores_cdpath(self): + chosen = self.proton(self.tmp / "work" / "proton", "1 GE-Proton10-25") + decoy = self.proton(self.tmp / "decoy" / "proton", "1 GE-Proton11-1") + environment = {"PATH": self.path, "HOME": str(self.home), "LEONIDA_PROTON": "proton", + "CDPATH": str(decoy.parent)} + p = subprocess.run(["/bin/sh", str(self.script), "--find-proton"], env=environment, cwd=chosen.parent, + capture_output=True, text=True, timeout=60) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertEqual(p.stdout.splitlines(), [f"GE-Proton10-25\t{chosen.resolve()}"]) + + def test_the_proton_wine_finds_its_own_libraries(self): + proton = self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + lib = proton / "files" / "lib" + for sub in ("vkd3d/x86_64-windows", "wine/x86_64-windows", "x86_64-linux-gnu", "i386-linux-gnu"): + (lib / sub).mkdir(parents=True, exist_ok=True) + p = self.run_script(str(self.game), WINEDLLPATH="/extra/dlls", LD_LIBRARY_PATH="/extra/lib") + self.assertEqual(p.returncode, 0, p.stderr) + real = lib.resolve() + self.assertEqual(Path(str(self.log) + ".dllpath").read_text(encoding="utf-8").strip(), + f"{real / 'vkd3d'}:{real / 'wine'}:/extra/dlls") + self.assertEqual(Path(str(self.log) + ".ldpath").read_text(encoding="utf-8").strip(), + f"{real / 'x86_64-linux-gnu'}:{real / 'i386-linux-gnu'}:/extra/lib") + + def test_a_proton_with_only_lib64_is_listed_found_and_runs_with_its_own_libraries(self): + proton = self.proton(self.steam / "compatibilitytools.d" / "Proton-lib64", "1 GE-Proton99-4", + lib_name="lib64") + lib64 = proton / "files" / "lib64" + (lib64 / "vkd3d" / "x86_64-windows").mkdir(parents=True) + listed = self.run_script("--list-protons") + self.assertEqual(listed.returncode, 0, listed.stderr) + self.assertIn(str(proton.resolve()), listed.stdout) + self.assertEqual(self.found(), ("GE-Proton99-4", proton.resolve())) + p = self.run_script(str(self.game), WINEDLLPATH="/extra/dlls", LD_LIBRARY_PATH="/extra/lib") + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("with DXVK's dxgi", p.stdout) + real = lib64.resolve() + self.assertEqual(Path(str(self.log) + ".dllpath").read_text(encoding="utf-8").strip(), + f"{real / 'vkd3d'}:{real / 'wine'}:/extra/dlls") + self.assertEqual(Path(str(self.log) + ".ldpath").read_text(encoding="utf-8").strip(), f"{real}:/extra/lib") + system32 = self.home / ".local" / "share" / "leonida" / "prefix" / "drive_c" / "windows" / "system32" + self.assertEqual((system32 / "dxgi.dll").read_bytes(), + (lib64 / "wine" / "dxvk" / "x86_64-windows" / "dxgi.dll").read_bytes()) + self.assert_system_wine_unused() + + def test_with_lib_and_lib64_the_lib64_libraries_come_first(self): + proton = self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + for lib in ("lib", "lib64"): + for sub in ("wine", "vkd3d"): + (proton / "files" / lib / sub).mkdir(parents=True, exist_ok=True) + p = self.run_script(str(self.game)) + self.assertEqual(p.returncode, 0, p.stderr) + real = (proton / "files").resolve() + self.assertEqual(Path(str(self.log) + ".dllpath").read_text(encoding="utf-8").strip(), + f"{real / 'lib64' / 'vkd3d'}:{real / 'lib64' / 'wine'}:{real / 'lib' / 'vkd3d'}:" + f"{real / 'lib' / 'wine'}") + + def test_an_old_layout_proton_dxvk_under_lib64_is_used(self): + proton = self.proton(self.steam / "compatibilitytools.d" / "Proton-5", "1 proton-5.13-6", dxvk=False, + lib_name="lib64") + dxvk = proton / "files" / "lib64" / "wine" / "dxvk" + dxvk.mkdir(parents=True) + (dxvk / "dxgi.dll").write_bytes(b"dxvk dxgi old layout") + p = self.run_script(str(self.game), LEONIDA_PROTON=str(proton)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("with DXVK's dxgi", p.stdout) + system32 = self.home / ".local" / "share" / "leonida" / "prefix" / "drive_c" / "windows" / "system32" + self.assertEqual((system32 / "dxgi.dll").read_bytes(), b"dxvk dxgi old layout") + self.assert_system_wine_unused() + + def test_the_vkd3d_shader_cache_goes_to_the_leonida_cache(self): + self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + cache = self.tmp / "cache" + self.assertEqual(self.run_script(str(self.game), LEONIDA_CACHE_DIR=str(cache)).returncode, 0) + recorded = Path(str(self.log) + ".shadercache") + self.assertEqual(recorded.read_text(encoding="utf-8").strip(), str(cache / "vkd3d-proton")) + self.assertTrue((cache / "vkd3d-proton").is_dir()) + own = self.tmp / "own shader cache" + self.assertEqual(self.run_script(str(self.game), LEONIDA_CACHE_DIR=str(cache), + VKD3D_SHADER_CACHE_PATH=str(own)).returncode, 0) + self.assertEqual(recorded.read_text(encoding="utf-8").strip(), str(own)) + + def test_a_disabled_vkd3d_shader_cache_creates_no_folder(self): + self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + cache = self.tmp / "cache" + work = self.tmp / "read-only work" + work.mkdir() + work.chmod(0o555) + self.addCleanup(work.chmod, 0o755) + environment = {"PATH": self.path, "HOME": str(self.home), "LEONIDA_TEST_LOG": str(self.log), + "LEONIDA_RUNTIME": str(self.package / "leonida.exe"), + "LEONIDA_VKD3D": str(self.package / "vkd3d-proton"), "LEONIDA_CACHE_DIR": str(cache), + "VKD3D_SHADER_CACHE_PATH": "0"} + p = subprocess.run(["/bin/sh", str(self.script), str(self.game)], env=environment, cwd=work, + capture_output=True, text=True, timeout=60) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertEqual(Path(str(self.log) + ".shadercache").read_text(encoding="utf-8").strip(), "0") + self.assertEqual(list(work.iterdir()), []) + self.assertTrue(cache.is_dir()) + self.assertFalse((cache / "vkd3d-proton").exists()) + + def test_log_sends_the_runtime_error_output_to_a_file_and_keeps_five(self): + self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + logs = self.home / ".local" / "share" / "leonida" / "logs" + logs.mkdir(parents=True) + for index in range(6): + old = logs / f"play-0101-00000{index}.log" + old.write_text("old", encoding="utf-8") + os.utime(old, (1000 + index, 1000 + index)) + (logs / "other.log").write_text("kept", encoding="utf-8") + p = self.run_script(str(self.game), "--log", "--series-x") + self.assertEqual(p.returncode, 0, p.stderr) + self.assertNotIn("runtime error output", p.stderr) + self.assertIn("runtime output", p.stdout) + line = [l for l in p.stdout.splitlines() if l.startswith("log: ")] + self.assertEqual(len(line), 1, p.stdout) + written = Path(line[0][len("log: "):]) + self.assertEqual(written.parent, logs) + self.assertRegex(written.name, r"^play-\d{4}-\d{6}\.log$") + self.assertEqual(written.read_text(encoding="utf-8").strip(), "runtime error output") + self.assertIn("--console series-x", self.calls()[-1]) + kept = sorted(path.name for path in logs.glob("play-*.log")) + self.assertEqual(len(kept), 5) + self.assertIn(written.name, kept) + self.assertNotIn("play-0101-000000.log", kept) + self.assertNotIn("play-0101-000001.log", kept) + self.assertTrue((logs / "other.log").exists()) + + def test_without_log_the_error_output_stays_on_the_console(self): + self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + p = self.run_script(str(self.game)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("runtime error output", p.stderr) + self.assertNotIn("log: ", p.stdout) + self.assertFalse((self.home / ".local" / "share" / "leonida" / "logs").exists()) + + def test_an_unknown_option_is_refused(self): + self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + p = self.run_script(str(self.game), "--nope") + self.assertEqual(p.returncode, 2) + self.assertIn("--log", p.stderr) + self.assertEqual(self.calls(), []) + + def test_the_prefix_follows_the_proton_in_use(self): + tools = self.steam / "compatibilitytools.d" + prefix = self.tmp / "prefix" + (prefix / "drive_c" / "windows" / "system32").mkdir(parents=True) + (prefix / "drive_c" / "windows" / "system32" / "dxgi.dll").write_bytes(b"wine's own dxgi") + first = self.proton(tools / "GE-Proton99-4", "1 GE-Proton99-4") + self.assertEqual(self.run_script(str(self.game), LEONIDA_WINEPREFIX=str(prefix)).returncode, 0) + self.assertEqual(self.calls()[0], "wineboot -u", "a prefix another Wine made is updated first") + self.assertEqual((prefix / "drive_c" / "windows" / "system32" / "dxgi.dll").read_bytes(), + (first / DXVK / "dxgi.dll").read_bytes()) + self.log.unlink() + self.assertEqual(self.run_script(str(self.game), LEONIDA_WINEPREFIX=str(prefix)).returncode, 0) + self.assertNotIn("wineboot -u", self.calls(), "the same Proton reuses the prefix as it is") + self.log.unlink() + second = self.proton(tools / "GE-Proton99-5", "1 GE-Proton99-5") + p = self.run_script(str(self.game), LEONIDA_WINEPREFIX=str(prefix)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("updating its Wine prefix", p.stdout) + self.assertEqual(self.calls()[0], "wineboot -u") + self.assertEqual((prefix / "drive_c" / "windows" / "system32" / "dxgi.dll").read_bytes(), + (second / DXVK / "dxgi.dll").read_bytes()) + + def test_a_prefix_without_the_proton_vkd3d_libraries_is_updated(self): + proton = self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + vkd3d = proton / "files" / "lib" / "vkd3d" / "x86_64-windows" + vkd3d.mkdir(parents=True) + (vkd3d / "libvkd3d-1.dll").write_bytes(b"vkd3d") + prefix = self.tmp / "prefix" + system32 = prefix / "drive_c" / "windows" / "system32" + system32.mkdir(parents=True) + (prefix / ".leonida-proton").write_text(f"GE-Proton99-4 {proton.resolve()}\n", encoding="utf-8") + p = self.run_script(str(self.game), LEONIDA_WINEPREFIX=str(prefix)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("updating its Wine prefix", p.stdout) + self.assertEqual(self.calls()[0], "wineboot -u") + self.log.unlink() + (system32 / "libvkd3d-1.dll").write_bytes(b"vkd3d") + self.assertEqual(self.run_script(str(self.game), LEONIDA_WINEPREFIX=str(prefix)).returncode, 0) + self.assertNotIn("wineboot -u", self.calls()) + + def test_a_prefix_proton_cannot_set_up_stops_the_start(self): + self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + p = self.run_script(str(self.game), LEONIDA_TEST_WINEBOOT_FAILS="1") + self.assertEqual(p.returncode, 1) + self.assertIn("could not set up the prefix", p.stderr) + self.assertEqual(self.calls(), ["wineboot -u"]) + + def test_a_chosen_proton_wins_over_leonida_wine(self): + proton = self.proton(self.steam / "compatibilitytools.d" / "GE-Proton99-4", "1 GE-Proton99-4") + self.assertEqual(self.found(LEONIDA_PROTON=str(proton), LEONIDA_WINE="wine"), + ("GE-Proton99-4", proton.resolve())) + self.assert_system_wine_unused() + + def test_the_script_is_executable_and_lf(self): + self.assertTrue(os.access(SCRIPT, os.X_OK)) + self.assertNotIn(b"\r", SCRIPT.read_bytes()) + self.assertTrue(SCRIPT.read_bytes().startswith(b"#!/bin/sh\n")) + if shutil.which("dash"): + self.assertEqual(subprocess.run(["dash", "-n", str(SCRIPT)]).returncode, 0) + + +@unittest.skipIf(os.name == "nt" or not os.path.exists("/bin/sh"), "POSIX shell script") +class PlayLinuxSystemWineTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.tmp = Path(tmp.name) + self.home = self.tmp / "home" + self.home.mkdir() + self.repo = self.tmp / "repo" + (self.repo / "scripts").mkdir(parents=True) + shutil.copy(SCRIPT, self.repo / "scripts" / "play-linux.sh") + self.log = self.tmp / "log" + self.bin = self.tmp / "bin" + self.bin.mkdir() + self.wine = self.bin / "wine" + self.wine.write_text(WINE_RUNS, encoding="utf-8", newline="\n") + self.wine.chmod(0o755) + server = self.bin / "wineserver" + server.write_text('#!/bin/sh\nprintf \'%s\\n\' "wineserver $*" >> "$LEONIDA_TEST_LOG.server"\n', + encoding="utf-8", newline="\n") + server.chmod(0o755) + self.package = self.tmp / "package" + (self.package / "vkd3d-proton").mkdir(parents=True) + for dll in ("d3d12.dll", "d3d12core.dll"): + (self.package / "vkd3d-proton" / dll).write_bytes(NEW_STRUCTURIZER + dll.encode()) + (self.package / "leonida.exe").write_bytes(b"MZ") + self.game = self.tmp / "game" / "game_scarlett_master.exe" + self.game.parent.mkdir() + self.game.write_bytes(b"MZ") + self.system32 = self.home / ".local" / "share" / "leonida" / "prefix" / "drive_c" / "windows" / "system32" + + def bundled_dxvk(self, folder=TARGET / "dxvk"): + folder = self.repo / folder + folder.mkdir(parents=True) + (folder / "dxgi.dll").write_bytes(b"bundled dxvk dxgi " + str(folder).encode()) + (folder / "SOURCE.txt").write_text("DXVK 99.1, unmodified 64-bit dxgi.dll from\n", encoding="utf-8") + return folder + + def run_script(self, *args, **env): + environment = {"PATH": os.pathsep.join([str(self.bin), "/usr/bin", "/bin"]), "HOME": str(self.home), + "LEONIDA_TEST_LOG": str(self.log), "LEONIDA_RUNTIME": str(self.package / "leonida.exe"), + "LEONIDA_VKD3D": str(self.package / "vkd3d-proton")} + environment.update(env) + return subprocess.run(["/bin/sh", str(self.repo / "scripts" / "play-linux.sh"), *args], env=environment, + capture_output=True, text=True, timeout=60) + + def calls(self): + return self.log.read_text(encoding="utf-8").splitlines() if self.log.exists() else [] + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_without_proton_the_system_wine_runs_with_the_bundled_dxvk(self): + bundled = self.bundled_dxvk() + p = self.run_script(str(self.game), WINEDLLOVERRIDES="mscoree=") + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn(f"series-s under Wine 99.0 (Staging) ({self.wine}) with the bundled DXVK's dxgi " + "(DXVK 99.1) and", p.stdout) + self.assertEqual(self.calls(), ["wineboot -u", f"{self.package / 'leonida.exe'} run {self.game} " + "--execute --console series-s"]) + self.assertEqual(Path(str(self.log) + ".overrides").read_text(encoding="utf-8").strip(), + "mscoree=;d3d12,d3d12core,dxgi=n") + self.assertEqual(Path(str(self.log) + ".dllpath").read_text(encoding="utf-8").strip(), "") + self.assertEqual(Path(str(self.log) + ".server").read_text(encoding="utf-8").strip(), "wineserver -w") + self.assertEqual((self.system32 / "dxgi.dll").read_bytes(), (bundled / "dxgi.dll").read_bytes()) + for dll in ("d3d12.dll", "d3d12core.dll"): + self.assertEqual((self.system32 / dll).read_bytes(), NEW_STRUCTURIZER + dll.encode()) + self.assertEqual((self.system32.parents[2] / ".leonida-proton").read_text(encoding="utf-8").strip(), + f"Wine 99.0 (Staging) {self.wine}") + self.log.unlink() + self.assertEqual(self.run_script(str(self.game)).returncode, 0) + self.assertNotIn("wineboot -u", self.calls(), "the same Wine reuses the prefix as it is") + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_the_dxvk_beside_the_script_comes_first(self): + self.bundled_dxvk() + package = self.bundled_dxvk(Path("scripts") / "dxvk") + p = self.run_script(str(self.game)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertEqual((self.system32 / "dxgi.dll").read_bytes(), (package / "dxgi.dll").read_bytes()) + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_the_bundled_d3dcompiler_is_installed_and_preferred(self): + self.bundled_dxvk() + bundled = self.repo / TARGET / "d3dcompiler" + bundled.mkdir(parents=True) + (bundled / "d3dcompiler_47.dll").write_bytes(b"MZ bundled d3dcompiler_47") + p = self.run_script(str(self.game)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertNotIn("d3dcompiler_47.dll", p.stderr) + self.assertEqual((self.system32 / "d3dcompiler_47.dll").read_bytes(), b"MZ bundled d3dcompiler_47") + self.assertEqual(Path(str(self.log) + ".overrides").read_text(encoding="utf-8").strip(), + "d3d12,d3d12core,dxgi,d3dcompiler_47=n") + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_a_missing_d3dcompiler_is_fetched_into_the_checkout(self): + self.bundled_dxvk() + fetch = self.repo / "scripts" / "fetch_d3dcompiler.py" + fetch.write_text("import os, sys\n" + "out = sys.argv[sys.argv.index('--out') + 1]\n" + "os.makedirs(out, exist_ok=True)\n" + "open(os.path.join(out, 'd3dcompiler_47.dll'), 'wb').write(b'MZ fetched')\n", + encoding="utf-8", newline="\n") + p = self.run_script(str(self.game)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("fetching Microsoft's d3dcompiler_47.dll", p.stdout) + self.assertEqual((self.repo / TARGET / "d3dcompiler" / "d3dcompiler_47.dll").read_bytes(), b"MZ fetched") + self.assertEqual((self.system32 / "d3dcompiler_47.dll").read_bytes(), b"MZ fetched") + self.assertEqual(Path(str(self.log) + ".overrides").read_text(encoding="utf-8").strip(), + "d3d12,d3d12core,dxgi,d3dcompiler_47=n") + + @unittest.skipIf(system_proton_installed(), "a Proton is installed system-wide on this machine") + def test_without_a_d3dcompiler_the_start_says_what_to_fetch_and_goes_on(self): + self.bundled_dxvk() + fetch = self.repo / "scripts" / "fetch_d3dcompiler.py" + fetch.write_text("raise SystemExit('offline')\n", encoding="utf-8", newline="\n") + p = self.run_script(str(self.game)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("no Microsoft d3dcompiler_47.dll", p.stderr) + self.assertIn("fetch_d3dcompiler.py", p.stderr) + self.assertFalse((self.system32 / "d3dcompiler_47.dll").exists()) + self.assertEqual(Path(str(self.log) + ".overrides").read_text(encoding="utf-8").strip(), + "d3d12,d3d12core,dxgi=n") + self.assertIn(f"{self.package / 'leonida.exe'} run {self.game}", "\n".join(self.calls())) + + def test_leonida_wine_picks_the_wine_and_find_proton_names_it(self): + self.bundled_dxvk() + other = self.tmp / "other wine" / "wine-custom" + other.parent.mkdir() + shutil.copy(self.wine, other) + for value, wine in (("wine", self.wine), (str(other), other)): + with self.subTest(value=value): + p = self.run_script("--find-proton", LEONIDA_WINE=value) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertEqual(p.stdout.strip().split("\t"), ["Wine 99.0 (Staging)", str(wine)]) + + def test_a_leonida_wine_that_is_no_wine_is_refused(self): + self.bundled_dxvk() + for value in (str(self.tmp / "missing"), "no-such-wine", str(self.tmp)): + with self.subTest(value=value): + p = self.run_script(str(self.game), LEONIDA_WINE=value) + self.assertEqual(p.returncode, 1) + self.assertIn("is not a Wine program", p.stderr) + self.assertEqual(self.calls(), []) + + def test_leonida_dxvk_wins_and_must_have_a_dxgi(self): + self.bundled_dxvk() + own = self.tmp / "own dxvk" + own.mkdir() + p = self.run_script(str(self.game), LEONIDA_WINE="wine", LEONIDA_DXVK=str(own)) + self.assertEqual(p.returncode, 1) + self.assertIn("has no dxgi.dll", p.stderr) + self.assertEqual(self.calls(), []) + (own / "dxgi.dll").write_bytes(b"own dxgi") + p = self.run_script(str(self.game), LEONIDA_WINE="wine", LEONIDA_DXVK=str(own) + "/") + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn(f"DXVK's dxgi from {own} (LEONIDA_DXVK)", p.stdout) + self.assertEqual((self.system32 / "dxgi.dll").read_bytes(), b"own dxgi") + + @unittest.skipIf(system_dxvk_installed(), "DXVK is installed system-wide on this machine") + def test_an_installed_proton_lends_its_dxvk_to_the_system_wine(self): + proton = self.home / ".local" / "share" / "Steam" / "compatibilitytools.d" / "GE-Proton99-4" + (proton / "files" / "bin").mkdir(parents=True) + (proton / "files" / "bin" / "wine").write_text("#!/bin/sh\ntouch \"$LEONIDA_TEST_LOG.proton\"\n", + encoding="utf-8", newline="\n") + (proton / "files" / "bin" / "wine").chmod(0o755) + (proton / DXVK).mkdir(parents=True) + (proton / DXVK / "dxgi.dll").write_bytes(b"proton dxvk dxgi") + (proton / "version").write_text("1 GE-Proton99-4\n", encoding="utf-8") + p = self.run_script(str(self.game), LEONIDA_WINE="wine") + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("under Wine 99.0 (Staging)", p.stdout) + self.assertIn("with DXVK's dxgi of GE-Proton99-4", p.stdout) + self.assertEqual((self.system32 / "dxgi.dll").read_bytes(), b"proton dxvk dxgi") + self.assertFalse(Path(str(self.log) + ".proton").exists(), "the Proton's Wine was started") + + @unittest.skipIf(system_dxvk_installed() or system_proton_installed(), + "DXVK or a Proton is installed system-wide on this machine") + def test_without_any_dxvk_the_start_says_what_to_fetch(self): + for args in (("--find-proton",), (str(self.game),)): + with self.subTest(args=args): + p = self.run_script(*args) + self.assertEqual(p.returncode, 1) + self.assertIn("swap chain", p.stderr) + self.assertIn("fetch_dxvk.py", p.stderr) + self.assertIn("LEONIDA_DXVK", p.stderr) + self.assertEqual(self.calls(), []) + + @unittest.skipIf(system_proton_installed() or shutil.which("wine", path="/usr/bin:/bin"), + "a Proton or Wine is installed system-wide on this machine") + def test_without_proton_and_wine_the_start_says_what_to_install(self): + p = self.run_script(str(self.game), PATH="/usr/bin:/bin") + self.assertEqual(p.returncode, 1) + self.assertIn("no Proton and no Wine found", p.stderr) + self.assertIn("LEONIDA_PROTON", p.stderr) + self.assertIn("LEONIDA_WINE", p.stderr) + + def test_the_prefix_is_updated_when_the_wine_changes(self): + self.bundled_dxvk() + prefix = self.tmp / "prefix" + (prefix / "drive_c" / "windows" / "system32").mkdir(parents=True) + (prefix / ".leonida-proton").write_text("GE-Proton99-4 /somewhere/GE-Proton99-4\n", encoding="utf-8") + p = self.run_script(str(self.game), LEONIDA_WINE="wine", LEONIDA_WINEPREFIX=str(prefix)) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("updating its Wine prefix", p.stdout) + self.assertEqual(self.calls()[0], "wineboot -u") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/leonida_launcher.py b/tools/leonida_launcher.py index 7c13dbccd2..64b93c0c00 100644 --- a/tools/leonida_launcher.py +++ b/tools/leonida_launcher.py @@ -35,6 +35,7 @@ # Switches of scripts/play-d3d12.ps1 that the Settings page offers, with the value they have by default. RESOLUTIONS = ("", "2160", "1440", "1080", "720", "540", "480") +SYSTEM_WINE = "system-wine" DLSS_MODES = ("", "quality", "balanced", "performance", "ultra") FRAME_GEN = (0, 2, 3, 4, 5, 6) PRESENT_SCALES = ("", "fit", "stretch") @@ -60,6 +61,7 @@ "present_scale": "", # -PresentScale, with -Aspect; empty = the script's default (fit) "adapter": "", # -Adapter "background": "", # the picture behind PLAY in launcher/; "" = background.* in config_dir() + "proton_dir": "", } # The options with a fixed set of values, and the others whose text has to match a pattern. CHOICES: dict = {"resolution": RESOLUTIONS, "dlss_mode": DLSS_MODES, "frame_gen": FRAME_GEN, @@ -178,13 +180,92 @@ def play_command(settings: dict, repo: str = REPO, windows: bool = WINDOWS) -> l command = ["sh", os.path.join(repo, "scripts", "play-linux.sh"), os.path.join(game, EXPECTED_EXE)] if settings["series_x"]: command.append("--series-x") + if settings["log"]: + command.append("--log") return command -def tool_command(name: str, repo: str = REPO, windows: bool = WINDOWS) -> list[str]: - """The command of a Tools button: `get_dlss` or `build`. Both are Windows scripts.""" +def play_environment(settings: dict, base: dict | None = None) -> dict: + env = dict(os.environ if base is None else base) + proton = settings.get("proton_dir", "").strip() + if proton == SYSTEM_WINE: + env.pop("LEONIDA_PROTON", None) + env["LEONIDA_WINE"] = "wine" + elif proton: + env.pop("LEONIDA_WINE", None) + env["LEONIDA_PROTON"] = proton + return env + + +def proton_command(repo: str = REPO) -> list[str]: + return ["sh", os.path.join(repo, "scripts", "play-linux.sh"), "--find-proton"] + + +def list_protons(repo: str = REPO, base: dict | None = None) -> list[tuple[str, str]]: + env = dict(os.environ if base is None else base) + env.pop("LEONIDA_PROTON", None) + env.pop("LEONIDA_WINE", None) + try: + done = subprocess.run(["sh", os.path.join(repo, "scripts", "play-linux.sh"), "--list-protons"], env=env, + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60, check=False) + except (OSError, subprocess.TimeoutExpired): + return [] + if done.returncode != 0: + return [] + found = [] + for line in done.stdout.splitlines(): + name, _, folder = line.partition("\t") + if name and folder: + found.append((name, folder)) + return found + + +def proton_choices(found: list[tuple[str, str]], wine: str | None) -> list[tuple[str, str, str]]: + if found: + choices = [(f"Automatic: {found[0][0]} ({found[0][1]})", "", found[0][1])] + elif wine: + choices = [(f"Automatic: System Wine ({wine})", "", SYSTEM_WINE)] + else: + return [("No Proton or Wine found", "", "")] + choices += [(f"{name} ({folder})", folder, folder) for name, folder in found] + if wine: + choices.append((f"System Wine ({wine})", SYSTEM_WINE, SYSTEM_WINE)) + return choices + + +def proton_label(choices: list[tuple[str, str, str]], setting: str) -> str: + for label, value, _target in choices: + if value == setting: + return label + for label, _value, target in choices: + if setting and target == setting: + return label + return "System Wine (not found)" if setting == SYSTEM_WINE else setting + + +def find_proton(settings: dict, repo: str = REPO, base: dict | None = None) -> tuple[bool, str, str]: + try: + done = subprocess.run(proton_command(repo), env=play_environment(settings, base), stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=60, check=False) + except (OSError, subprocess.TimeoutExpired) as exc: + return False, f"Could not look for Proton or Wine: {exc}", "" + if done.returncode == 0: + line = done.stdout.strip().splitlines()[-1] if done.stdout.strip() else "" + name, _, folder = line.partition("\t") + if name and folder: + return True, name, folder + return False, (done.stderr.strip() or done.stdout.strip() or "No Proton or Wine found."), "" + + +def tool_command(name: str, repo: str = REPO, windows: bool = WINDOWS, accept_sdk_licence: bool = False) -> list[str]: + """The command of a Tools button: `get_dlss` or `build`.""" if not windows: - raise ValueError("This tool is a Windows script; on Linux see docs/linux.md.") + if name == "build": + command = ["sh", os.path.join(repo, "scripts", "build-d3d12-linux.sh")] + return (["env", "XWIN_ACCEPT_LICENSE=1"] + command) if accept_sdk_licence else command + if name == "get_dlss": + raise ValueError("This tool is a Windows script; on Linux see docs/linux.md.") + raise ValueError(f"unknown tool {name}") runtime = os.path.join(repo, "d3d12") if name == "get_dlss": return ["cmd", "/c", os.path.join(runtime, "Get-NVIDIA-DLSS.cmd")] @@ -216,17 +297,22 @@ def local_data_dir() -> str: return os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share") +def leonida_data_dir() -> str: + return os.path.join(local_data_dir(), "Leonida" if WINDOWS else "leonida") + + def logs_dir() -> str: - return os.path.join(local_data_dir(), "Leonida", "logs") + return os.path.join(leonida_data_dir(), "logs") def captures_dir() -> str: - return os.path.join(local_data_dir(), "Leonida", "captures") + return os.path.join(leonida_data_dir(), "captures") def screenshot_dirs(repo: str = REPO) -> list[str]: """Where the runtime saves pictures: the F4 menu's screenshots (next to the exe) and F9 captures.""" - return [os.path.join(repo, "d3d12", "target", "diag", "screenshots"), captures_dir()] + return [os.path.join(repo, "d3d12", "target", "diag", "screenshots"), + os.path.join(repo, "d3d12", "target", "x86_64-pc-windows-msvc", "diag", "screenshots"), captures_dir()] def newest_picture(folders: list[str], limit: int = 2000) -> str | None: @@ -320,13 +406,13 @@ def stop_tree(process: subprocess.Popen) -> None: process.terminate() -def spawn(command: list[str], cwd: str) -> subprocess.Popen: +def spawn(command: list[str], cwd: str, env: dict | None = None) -> subprocess.Popen: kwargs: dict = {} if WINDOWS: kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW else: kwargs["start_new_session"] = True - return subprocess.Popen(command, cwd=cwd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + return subprocess.Popen(command, cwd=cwd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kwargs) @@ -578,9 +664,17 @@ def play(self): except ValueError as exc: messagebox.showwarning("Play", str(exc)) return - self.run(command, "the game", "Starting") + env = None + if not WINDOWS: + found, name, _folder = find_proton(self.settings) + if not found: + messagebox.showerror("Proton or Wine", name) + self.show("Settings") + return + env = play_environment(self.settings) + self.run(command, "the game", "Starting", env) - def run(self, command, what, state): + def run(self, command, what, state, env=None): if self.process is not None: messagebox.showinfo("Leonida", "Something is already running. Stop it first.") return @@ -589,7 +683,7 @@ def run(self, command, what, state): self.log.configure(state="disabled") self.append("> " + " ".join(f'"{c}"' if " " in c else c for c in command) + "\n") try: - self.process = spawn(command, REPO) + self.process = spawn(command, REPO, env) except OSError as exc: self.append(f"Could not start: {exc}\n") self.set_state("Could not start") @@ -657,6 +751,38 @@ def folder_row(self, parent, row, title, key, note): ttk.Label(parent, text=note, style="Muted.TLabel", wraplength=640).grid( row=row + 1, column=1, sticky="w", padx=8) + def proton_row(self, parent, row): + ttk.Label(parent, text="Proton or Wine").grid(row=row, column=0, sticky="w", pady=(10, 0)) + var = tk.StringVar(value=self.settings["proton_dir"]) + self.vars["proton_dir"] = var + self.proton_choice = tk.StringVar() + self.proton_folders: dict[str, str] = {} + self.proton_choices: list[tuple[str, str, str]] = [] + self.proton_box = ttk.Combobox(parent, textvariable=self.proton_choice, state="readonly", + postcommand=self.refresh_protons) + self.proton_box.grid(row=row, column=1, sticky="ew", padx=8, pady=(10, 0)) + self.proton_box.bind("<>", + lambda _event: var.set(self.proton_folders.get(self.proton_choice.get(), ""))) + ttk.Button(parent, text="Browse ...", command=lambda: self.browse(var)).grid(row=row, column=2, + pady=(10, 0)) + self.refresh_protons() + + def refresh_protons(self): + self.proton_choices = proton_choices(list_protons(), shutil.which("wine")) + self.show_proton_choice() + + def show_proton_choice(self): + setting = self.vars["proton_dir"].get().strip() + label = proton_label(self.proton_choices, setting) + self.proton_folders = {choice: value for choice, value, _target in self.proton_choices} + self.proton_folders.setdefault(label, setting) + self.proton_box["values"] = list(self.proton_folders) + self.proton_choice.set(label) + + def proton_changed(self): + self.show_proton_choice() + self.schedule_proton_check() + def build_settings(self): page = self.pages["Settings"] page.columnconfigure(0, weight=1) @@ -673,18 +799,30 @@ def build_settings(self): self.folder_row(inner, 4, "Data folder", "data_dir", "Shader caches and saves. Empty: the default (%LOCALAPPDATA%\\Leonida\\d3d12).") self.folder_row(inner, 6, "Mods folder", "mods_dir", "Empty: the mods folder of this repository.") + if not WINDOWS: + self.proton_row(inner, 8) + self.proton_check = tk.StringVar() + ttk.Label(inner, textvariable=self.proton_check, wraplength=720).grid( + row=9, column=1, sticky="w", padx=8) + self.proton_after = None + self.vars["proton_dir"].trace_add("write", lambda *_: self.proton_changed()) + ttk.Label(inner, text="On Linux only the game folder, Proton or Wine, the Series X profile and " + f"Log to a file are used. Log files go to {logs_dir()} (the five newest are kept).", + style="Muted.TLabel", wraplength=720).grid(row=11, column=0, columnspan=3, sticky="w", + pady=(10, 0)) options = ttk.LabelFrame(inner, text="Options (the switches of scripts\\play-d3d12.ps1)", padding=12) - options.grid(row=8, column=0, columnspan=3, sticky="ew", pady=(20, 0)) + options.grid(row=12, column=0, columnspan=3, sticky="ew", pady=(20, 0)) options.columnconfigure(0, weight=1) options.columnconfigure(1, weight=1) checks = (("dlss", "DLSS (off = -NoDlss: the picture is stretched)"), ("ray_tracing", "Ray tracing (-RayTracing, slower)"), ("smooth_motion", "Smooth Motion (-SmoothMotion, RTX 40 and 50)"), ("precompile", "Prepare shaders before starting (off = -NoPrecompile)"), - ("series_x", "Series X profile (-SeriesX, much slower)"), + ("series_x", "Series X profile (-SeriesX, much slower)" if WINDOWS + else "Series X profile (--series-x, much slower)"), ("quality", "Quality (-Quality, slower)"), ("capture", "Capture: F9 saves a frame (-Capture)"), - ("log", "Log to a file (-Log)")) + ("log", "Log to a file (-Log)" if WINDOWS else "Log to a file (--log)")) for index, (key, text) in enumerate(checks): var = tk.BooleanVar(value=self.settings[key]) self.vars[key] = var @@ -696,17 +834,13 @@ def build_settings(self): ttk.Combobox(options, textvariable=res, state="readonly", width=12, values=["default"] + [r for r in RESOLUTIONS if r]).grid(row=4, column=1, sticky="w", pady=(10, 0)) - if not WINDOWS: - ttk.Label(inner, text="On Linux the launcher starts scripts/play-linux.sh, which takes the " - "game folder and the Series X profile; the other options are for Windows.", - style="Muted.TLabel", wraplength=720).grid(row=9, column=0, columnspan=3, sticky="w", - pady=(10, 0)) buttons = ttk.Frame(inner) - buttons.grid(row=10, column=0, columnspan=3, sticky="w", pady=(18, 0)) + buttons.grid(row=13, column=0, columnspan=3, sticky="w", pady=(18, 0)) ttk.Button(buttons, text="Save", command=self.save).pack(side="left") self.saved_var = tk.StringVar() ttk.Label(buttons, textvariable=self.saved_var, style="Muted.TLabel").pack(side="left", padx=12) self.check_game() + self.check_proton() def browse(self, var): chosen = filedialog.askdirectory(initialdir=var.get() or os.path.expanduser("~")) @@ -722,6 +856,19 @@ def check_game(self): else: self.game_check.set(f"{EXPECTED_EXE} is not in this folder.") + def schedule_proton_check(self): + if self.proton_after is not None: + self.root.after_cancel(self.proton_after) + self.proton_after = self.root.after(400, self.check_proton) + + def check_proton(self): + if WINDOWS: + return + self.proton_after = None + self.collect_settings() + found, name, _folder = find_proton(self.settings) + self.proton_check.set("" if found else name) + def collect_settings(self): for key, var in self.vars.items(): value = var.get() @@ -737,6 +884,7 @@ def save(self): self.saved_var.set("Saved to " + config_path()) except OSError as exc: self.saved_var.set(f"Could not save: {exc}") + self.check_proton() self.refresh_hint() # ---- Mods @@ -1020,7 +1168,9 @@ def build_tools(self): sticky="w", pady=(0, 10)) items = (("Fetch NVIDIA DLSS files", "Downloads about 70 MB from NVIDIA's GitHub, once.", self.fetch_dlss), - ("Rebuild the runtime", "d3d12\\scripts\\build-nvidia.ps1 (a few minutes).", self.rebuild), + ("Rebuild the runtime", ("d3d12\\scripts\\build-nvidia.ps1" if WINDOWS + else "scripts/build-d3d12-linux.sh") + " (a few minutes).", + self.rebuild), ("Open the logs folder", logs_dir(), lambda: self.open(logs_dir())), ("Open the screenshots folder", "The F4 menu's screenshots, else the F9 captures.", self.open_screenshots)) @@ -1037,11 +1187,19 @@ def fetch_dlss(self): self.run_tool("get_dlss", "the DLSS download") def rebuild(self): - self.run_tool("build", "the runtime build") + accept = False + if not WINDOWS: + accept = messagebox.askokcancel( + "Rebuild the runtime", + "The build uses cargo-xwin, which downloads Microsoft's CRT and Windows SDK on its first run " + "(https://go.microsoft.com/fwlink/?LinkId=2086102). OK accepts Microsoft's licence for them.") + if not accept: + return + self.run_tool("build", "the runtime build", accept_sdk_licence=accept) - def run_tool(self, name, what): + def run_tool(self, name, what, **options): try: - command = tool_command(name) + command = tool_command(name, **options) except ValueError as exc: messagebox.showinfo("Tools", str(exc)) return