Play Windows games on Apple Silicon Macs. Free, open-source app that installs the official Battle.net, Steam, Epic and GOG launchers and lists your games in one library.
HTML apple-siliconbattle-netcrossover-alternatived3dmetaldiablo-ii-resurrecteddxmtea-appepic-gamesgame-porting-toolkitgogmac-gamingmacosmacos-gamingrockstar-gamessteamubisoft-connectwhisky-alternativewindows-gameswinewine-wrapper
D2R in VR (offline): soju vr setup / play (#70)
Mikekc4ab38231d7b
diff --git a/README.ko.md b/README.ko.mdindex 4a0b1490145..29248b2f9e4 100644--- a/README.ko.md+++ b/README.ko.md@@ -46,7 +46,8 @@ Steam은 별도의 wine-stable 환경을 사용합니다. Apple의 비공개 GPT| 게임 | 스토어 | 그래픽 | 상태 | 비고 || --- | --- | --- | :-: | --- |-| Diablo II: Resurrected | Battle.net | D3DMetal (D3D11) | ✅ 인게임, 온라인 | **macOS 26.4 이상**(전제조건 참고); `play.sh`가 `ROSETTA_ADVERTISE_AVX=1` 설정; [가이드](https://bcd1210.github.io/soju/guides/ko/diablo-2-mac.html) |+| Diablo II: Resurrected | Battle.net | D3DMetal (D3D12) | ✅ 인게임, 온라인 | **macOS 26.4 이상**(전제조건 참고); `play.sh`가 `ROSETTA_ADVERTISE_AVX=1` 설정; [가이드](https://bcd1210.github.io/soju/guides/ko/diablo-2-mac.html) |+| Diablo II: Resurrected VR(오프라인) | Battle.net | D3DMetal (D3D12) + OpenXR | 🧪 시뮬레이터만 확인 | `soju vr setup` / `soju vr play`: 오프라인 캐릭터용 D2R VR Unleashed, OXRSys 헤드셋 클라이언트로 스트리밍; [docs/VR.md](docs/VR.md) || Hogwarts Legacy | Epic | D3DMetal (D3D12) | ✅ 인게임 | UE4 "AMD 드라이버" 경고는 무해, 입력 소스를 영어로 || Unity D3D11 타이틀 | Steam | DXMT | ✅ 인게임, 창 모드 | `soju steam-games` 필요, [docs/STEAM-GAMES.md](docs/STEAM-GAMES.md) || Diablo II: Resurrected (Infernal Edition) | Steam | 해당 없음 | ⏳ 미검증 | Steam 보틀에는 GPTK가 없고 D2R 로더는 `libd3dshared`가 필요 |diff --git a/README.md b/README.mdindex bf0af4b9870..3d8fa27b1d1 100644--- a/README.md+++ b/README.md@@ -58,7 +58,8 @@ All verified on an M4 Pro running macOS 26.5. Separate bottles for each launcher| Game | Store | Graphics | Status | Notes || --- | --- | --- | :-: | --- |-| Diablo II: Resurrected | Battle.net | D3DMetal (D3D11) | ✅ in-game, online | **macOS 26.4 or later** (see prerequisites); `play.sh` sets `ROSETTA_ADVERTISE_AVX=1`; [guide](https://bcd1210.github.io/soju/guides/diablo-2-resurrected-apple-silicon.html) |+| Diablo II: Resurrected | Battle.net | D3DMetal (D3D12) | ✅ in-game, online | **macOS 26.4 or later** (see prerequisites); `play.sh` sets `ROSETTA_ADVERTISE_AVX=1`; [guide](https://bcd1210.github.io/soju/guides/diablo-2-resurrected-apple-silicon.html) |+| Diablo II: Resurrected in VR (offline) | Battle.net | D3DMetal (D3D12) + OpenXR | 🧪 simulator only | `soju vr setup` / `soju vr play`: D2R VR Unleashed for offline characters, streamed to an OXRSys headset client; [docs/VR.md](docs/VR.md) || Hogwarts Legacy | Epic | D3DMetal (D3D12) | ✅ in-game | UE4 "AMD driver" warning is harmless || Unity D3D11 title | Steam | DXMT | ✅ in-game, windowed | via `soju steam-games`; see [docs/STEAM-GAMES.md](docs/STEAM-GAMES.md) || Diablo II: Resurrected (Infernal Edition) | Steam | n/a | ⏳ not verified yet | the Steam bottle has no GPTK, and D2R's loader needs `libd3dshared` |diff --git a/README.zh.md b/README.zh.mdindex f212f79aa8d..04bc1c03658 100644--- a/README.zh.md+++ b/README.zh.md@@ -46,7 +46,8 @@ D2R 和 Hogwarts Legacy 是兼容案例,项目面向多个游戏启动器。| 游戏 | 平台 | 图形 | 状态 | 说明 || --- | --- | --- | :-: | --- |-| Diablo II: Resurrected | 战网 | D3DMetal (D3D11) | ✅ 进入游戏,可联网 | **需要 macOS 26.4 或更高**(见前提条件);`play.sh` 设置 `ROSETTA_ADVERTISE_AVX=1`;[指南](https://bcd1210.github.io/soju/guides/diablo-2-resurrected-apple-silicon.html) |+| Diablo II: Resurrected | 战网 | D3DMetal (D3D12) | ✅ 进入游戏,可联网 | **需要 macOS 26.4 或更高**(见前提条件);`play.sh` 设置 `ROSETTA_ADVERTISE_AVX=1`;[指南](https://bcd1210.github.io/soju/guides/diablo-2-resurrected-apple-silicon.html) |+| Diablo II: Resurrected VR(离线) | 战网 | D3DMetal (D3D12) + OpenXR | 🧪 仅在模拟器验证 | `soju vr setup` / `soju vr play`:离线角色的 D2R VR Unleashed,串流到 OXRSys 头显客户端;[docs/VR.md](docs/VR.md) || Hogwarts Legacy | Epic | D3DMetal (D3D12) | ✅ 进入游戏 | UE4 的"AMD 驱动"警告无害 || Unity D3D11 游戏 | Steam | DXMT | ✅ 进入游戏,窗口模式 | 需要 `soju steam-games`,见 [docs/STEAM-GAMES.md](docs/STEAM-GAMES.md) || Diablo II: Resurrected(Infernal Edition) | Steam | 不适用 | ⏳ 尚未验证 | Steam bottle 没有 GPTK,而 D2R 的加载器需要 `libd3dshared` |diff --git a/app/Library.swift b/app/Library.swiftindex 3182245327c..47be5fec755 100644--- a/app/Library.swift+++ b/app/Library.swift@@ -149,6 +149,38 @@ extension SojuModel {libraryIssue = "Could not start the game: " + error.localizedDescription}}+ /// D2R VR Unleashed in the VR copy of the Battle.net bottle (`soju vr play`, offline).+ func playVR(_ game: InstalledGame) {+ guard !busy, !launchingGames.contains(game.id) else { return }+ do {+ let (p, url) = try task(["vr", "play"], logName: "d2r-vr")+ launchingGames.insert(game.id); gameLaunches[game.id] = p+ p.terminationHandler = { [weak self] process in+ DispatchQueue.main.async {+ guard let self else { return }+ if self.gameLaunches[game.id] === process {+ self.gameLaunches.removeValue(forKey: game.id)+ self.launchingGames.remove(game.id)+ }+ if process.terminationStatus != 0 {+ let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""+ let reason = text.split(separator: "\n").last(where: { $0.hasPrefix("soju vr: ") })+ .map { String($0.dropFirst(9)) }+ self.issueTitle = "Couldn't start " + game.title + " in VR"+ self.libraryIssue = reason ?? "Run Set Up VR again, then try once more."+ }+ }+ }+ try p.run()+ activity = "Starting " + game.title + " in VR (offline characters)…"+ DispatchQueue.main.asyncAfter(deadline: .now() + 8) { [weak self, weak p] in+ guard let self, let p, self.gameLaunches[game.id] === p else { return }+ self.launchingGames.remove(game.id)+ }+ } catch {+ libraryIssue = "Could not start VR: " + error.localizedDescription+ }+ }/// An Xbox game runs inside Soju's task: SIGTERM reaches xbox-run.py, which asks the/// backend to close the game and copy its saves back (or stops first-launch setup).func stopGame(_ game: InstalledGame) {@@ -405,6 +437,12 @@ struct LibraryView: View {Button("Open " + game.platform.title) { model.launch(game.platform) }.disabled(model.busy)}Button("Diagnose") { diagnose(game) }.disabled(model.busy)+ if game.id == "battlenet:osi" && game.isInstalled {+ Divider()+ Button("Set Up VR (offline)") { model.run(["vr", "setup"], title: "Setting up D2R VR…") }+ .disabled(model.busy)+ Button("Play in VR") { model.playVR(game) }.disabled(model.busy)+ }}}diff --git a/docs/VR.md b/docs/VR.mdnew file mode 100644index 00000000000..2450827cf0a--- /dev/null+++ b/docs/VR.md@@ -0,0 +1,48 @@+# Diablo II: Resurrected in VR (offline, experimental)++Soju can set up [D2R VR Unleashed](https://github.com/bearstonem/d2r-pcvr) (D2R-PCVR 0.3.31, MPL-2.0), a+first-person VR mod for **offline characters**, and stream it to a headset from your Mac.++```bash+soju vr setup # once (about 2 minutes, ~110 MB of downloads)+soju vr play # every time+soju vr status+soju vr setup --refresh # after a D2R update or when the 30-day check appears+soju vr remove --yes+```++In the app: right-click Diablo II: Resurrected in the library, then **Set Up VR (offline)** and **Play in VR**.++## What it does++- Makes an APFS copy of your Battle.net bottle in `~/.battlenet-macos/d2r-vr/bottle`. The copy shares disk space with+ the original until files change, and **your Battle.net bottle is never modified**. Normal Play still starts the stock+ game.+- Downloads, each pinned by size and SHA-256 in `resources/d2r-vr.json`: the mod's release ZIP (GitHub), D2RLoader+ 1.3.1-beta (d2rloader.net), ReShade 6.8.0 (reshade.me; only `ReShade64.dll` is extracted, the setup never runs),+ Windows embeddable Python 3.12 (python.org) for the mod's own installer, and Soju's VR runtime.+- The VR runtime ([vr-runtime-v1](https://github.com/BCD1210/soju/releases/tag/vr-runtime-v1)) is built by+ `scripts/build-vr-runtime.sh` from pinned commits: the OXRSys OpenXR runtime for macOS (MPL-2.0) and a wineopenxr+ bridge (LGPL-2.1-or-later) that hands the game's D3D12 eye images to the runtime as Metal textures.+- Three changes inside the copy make the mod run on Soju's engine (D3DMetal): the game folder's `d3d12.dll` is renamed+ so D3D12 loads where ReShade watches for it, the windowed resolution is fixed at 1920x1080 so the game never resizes+ its swapchain, and one jump in `ReShade64.dll` skips work on a resource D3DMetal has already destroyed (pinned+ before/after hashes).+- `soju vr play` starts `D2RLoader.exe -mod D2R-PCVR`. `-mod` keeps D2R offline: no Battle.net game servers.++## Headset++The game streams to a headset running the **OXRSys client** (Meta Quest / PICO, sideloaded; see the+[OXRSys Quest guide](https://github.com/anoshmisiosdev/oxrsys/blob/main/docs/platforms/quest.md)), or to the OXRSys+Simulator on the Mac for testing. The Mac and the headset need to be on the same network (or USB with adb).++Status (November 2026): verified on M4 Pro / macOS 26.5 with the OXRSys Simulator: first-person view in Act 1 at+72 fps. **Not yet tested on a real headset.** Controller input therefore has not been checked.++## Notes++- Use **offline characters** only. Characters you make in VR live in the copy; `--refresh` keeps them.+- D2R requires an online sign-in within the last 30 days even for offline play. If it says so, play D2R online once+ from Battle.net, then run `soju vr setup --refresh`.+- The mod supports D2R 3.3.93847. Setup refuses other builds.+- Modding is your choice and the mod is not Blizzard's. Online play is never used by this mode.diff --git a/resources/d2r-vr.json b/resources/d2r-vr.jsonnew file mode 100644index 00000000000..e7833349a7d--- /dev/null+++ b/resources/d2r-vr.json@@ -0,0 +1,44 @@+{+ "schema": 1,+ "game_build": "3.3.93847",+ "note": "Offline only: D2R VR Unleashed runs through D2RLoader with -mod, which keeps D2R off Battle.net game servers.",+ "runtime": {+ "url": "https://github.com/BCD1210/soju/releases/download/vr-runtime-v1/soju-vr-runtime.tar.xz",+ "size": 622136,+ "sha256": "4f2c51bd41dd6a0688d8b8570827a7c5618e85b17de24419b7944e65017c730a",+ "license": "wineopenxr bridge LGPL-2.1-or-later, OXRSys MPL-2.0; scripts/build-vr-runtime.sh rebuilds it from pinned commits"+ },+ "python": {+ "url": "https://www.python.org/ftp/python/3.12.10/python-3.12.10-embed-amd64.zip",+ "size": 11133606,+ "sha256": "4acbed6dd1c744b0376e3b1cf57ce906f9dc9e95e68824584c8099a63025a3c3"+ },+ "mod": {+ "name": "D2R VR Unleashed 0.3.31 (D2R-PCVR, MPL-2.0)",+ "url": "https://github.com/bearstonem/d2r-pcvr/releases/download/v0.3.31-windows-preview/d2r-pcvr-windows.zip",+ "size": 41728732,+ "sha256": "705a7714f85d8a1f4ad3de8c73e64e4275f28cf560ba96544fc916b1c3e2b279",+ "folder": "d2r-pcvr-preview",+ "mod_name": "D2R-PCVR"+ },+ "loader": {+ "url": "https://d2rloader.net/downloads/D2RLoader-1.3.1-beta.zip",+ "size": 47652455,+ "sha256": "9286c6b5bff7f1043658411dbea305faa9698b6a455e6441668fc6d02c22aad7",+ "file": "D2RLoader-1.3.1-beta.zip"+ },+ "reshade": {+ "url": "https://reshade.me/downloads/ReShade_Setup_6.8.0_Addon.exe",+ "size": 4318424,+ "sha256": "afe4c8f13048306307983b8b3d41d5bf00a86820440b0e57dea10950e1176445",+ "member": "ReShade64.dll",+ "dll_sha256": "0cee63f9c9f13f3ac909c5b4903f4dbb4b719a7ab3b4f13b0deaf83c814b94f7",+ "patch": {+ "why": "D3DMetal releases ReShade's per-resource destroy tracker after the resource's C++ destructor ran, so ID3D12Resource::GetDesc (vtable slot 10) is null there. Skip the desc / GPU address cleanup and only free the tracker.",+ "file_offset": 1327846,+ "old": "488bcf488b07ff5050",+ "new": "e91804000090909090",+ "patched_sha256": "77e51ea578f972f7b33a77ab79b807d88975a1b06cb725af8b629dd01a137be5"+ }+ }+}diff --git a/scripts/build-vr-runtime.sh b/scripts/build-vr-runtime.shnew file mode 100755index 00000000000..084a824ed48--- /dev/null+++ b/scripts/build-vr-runtime.sh@@ -0,0 +1,85 @@+#!/usr/bin/env bash+# Build the VR runtime Soju's D2R VR mode uses, from pinned sources, and pack+# it as the release file resources/d2r-vr.json points at.+#+# wineopxdms.dll/.so wineopenxr bridge (LGPL-2.1-or-later): the game's+# OpenXR calls go through Wine to the macOS runtime, and+# D3D12 swapchain images are D3DMetal resources backed+# by the runtime's Metal textures. Renamed from+# wineopenxr so it cannot clash with an engine's own.+# liboxrsys-runtime OXRSys OpenXR runtime for macOS (MPL-2.0), x86_64 so+# it loads inside the game's Rosetta process, plus its+# arm64 hardware HEVC encoder helper. It streams to a+# headset running the OXRSys client.+#+# Requirements: Xcode command line tools, Homebrew cmake, ninja, mingw-w64.+# Usage: scripts/build-vr-runtime.sh [output.tar.xz]+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+OUT="${1:-$ROOT/dist/soju-vr-runtime.tar.xz}"+WORK="${WORK:-$HOME/.battlenet-macos/build/vr-runtime}"+export PATH="/opt/homebrew/bin:$PATH"++BRIDGE_URL="https://github.com/anoshmisiosdev/oxrsys-winebridge.git"+BRIDGE_COMMIT="88a97e9" # superproject+WINEOPENXR_COMMIT="1cfaac97bda3f45ac756510c59c45a630c74502a" # bridge/ submodule+OXRSYS_COMMIT="204f0933ea5b4fe4d4f28b2248fc9727f6655d3c" # oxrsys-src/ submodule++for tool in cmake ninja x86_64-w64-mingw32-gcc git python3 xcrun; do+ command -v "$tool" >/dev/null || { echo "Missing $tool (brew install cmake ninja mingw-w64)" >&2; exit 1; }+done++mkdir -p "$WORK"+SRC="$WORK/oxrsys-winebridge"+if [ ! -d "$SRC/.git" ]; then+ git clone --quiet "$BRIDGE_URL" "$SRC"+fi+git -C "$SRC" fetch --quiet origin+git -C "$SRC" checkout --quiet --detach "$BRIDGE_COMMIT"+git -C "$SRC" submodule update --init --recursive bridge oxrsys-src+[ "$(git -C "$SRC/bridge" rev-parse HEAD)" = "$WINEOPENXR_COMMIT" ] || { echo "bridge is not at $WINEOPENXR_COMMIT" >&2; exit 1; }+[ "$(git -C "$SRC/oxrsys-src" rev-parse HEAD)" = "$OXRSYS_COMMIT" ] || { echo "oxrsys-src is not at $OXRSYS_COMMIT" >&2; exit 1; }++echo "==> Building the wineopenxr bridge (PE + unix side, x86_64)"+cmake -S "$SRC/bridge" -B "$WORK/bridge-build" -G Ninja -DCMAKE_BUILD_TYPE=Release >/dev/null+cmake --build "$WORK/bridge-build"++echo "==> Building the OXRSys runtime (x86_64) and its encoder helper"+cmake -S "$SRC/oxrsys-src" -B "$WORK/oxrsys-build" -G Ninja -DCMAKE_OSX_ARCHITECTURES=x86_64 \+ -DCMAKE_BUILD_TYPE=Release -DOXRSYS_ENABLE_CTS=OFF >/dev/null+cmake --build "$WORK/oxrsys-build" --target oxrsys_runtime oxrsys-encoder-helper++STAGE="$WORK/stage"+rm -rf "$STAGE"; mkdir -p "$STAGE/wine/x86_64-windows" "$STAGE/wine/x86_64-unix" "$STAGE/runtime" "$STAGE/licenses"+python3 "$SRC/test/dmsubst/rename_pe_export.py" "$WORK/bridge-build/src/pe/wineopenxr.dll" \+ "$STAGE/wine/x86_64-windows/wineopxdms.dll" wineopxdms.dll >/dev/null+cp "$WORK/bridge-build/src/unix/wineopenxr.so" "$STAGE/wine/x86_64-unix/wineopxdms.so"+RT="$WORK/oxrsys-build/runtime"+cp "$RT/liboxrsys-runtime.dylib" "$RT/oxrsys-encoder-helper" "$RT/oxrsys-runtime.toml" "$STAGE/runtime/"+cat > "$STAGE/runtime/oxrsys-runtime.json" <<'JSON'+{+ "file_format_version": "1.0.0",+ "runtime": {+ "name": "OXRSys Runtime",+ "library_path": "./liboxrsys-runtime.dylib"+ }+}+JSON+for f in "$STAGE/wine/x86_64-unix/wineopxdms.so" "$STAGE/runtime/liboxrsys-runtime.dylib" "$STAGE/runtime/oxrsys-encoder-helper"; do+ codesign --force --sign - "$f"+done+cp "$SRC/bridge/LICENSE" "$STAGE/licenses/wineopenxr-LICENSE"+cp "$SRC/bridge/COPYING.LIB" "$STAGE/licenses/wineopenxr-COPYING.LIB"+cp "$SRC/oxrsys-src/LICENSE" "$STAGE/licenses/oxrsys-LICENSE"+cat > "$STAGE/SOURCES.txt" <<EOF+Built by scripts/build-vr-runtime.sh from:+ $BRIDGE_URL @ $BRIDGE_COMMIT+ wineopenxr (bridge/) https://github.com/anoshmisiosdev/wineopenxr @ $WINEOPENXR_COMMIT LGPL-2.1-or-later+ OXRSys (oxrsys-src/) https://github.com/anoshmisiosdev/oxrsys @ $OXRSYS_COMMIT MPL-2.0+EOF++mkdir -p "$(dirname "$OUT")"+COPYFILE_DISABLE=1 tar --no-mac-metadata --no-xattrs -cf - -C "$STAGE" . | xz -T0 -6 > "$OUT"+echo "==> $OUT"+shasum -a 256 "$OUT"diff --git a/scripts/d2r-vr.py b/scripts/d2r-vr.pynew file mode 100644index 00000000000..d792331985b--- /dev/null+++ b/scripts/d2r-vr.py@@ -0,0 +1,447 @@+#!/usr/bin/env python3+"""Diablo II: Resurrected in VR (offline): set up and play D2R VR Unleashed.++ soju vr setup [--refresh] copy the Battle.net bottle and install the mod there+ soju vr play start D2R in VR (offline characters only)+ soju vr status what is installed (JSON with --json)+ soju vr remove delete the VR copy (your Battle.net bottle is untouched)++The mod goes into an APFS copy of the Battle.net bottle (d2r-vr/bottle): the+copy takes almost no extra disk space at first, and the bottle Battle.net uses+is never modified. D2RLoader starts D2R with -mod, which keeps it offline.++Every download is pinned by size and SHA-256 in resources/d2r-vr.json. The VR+runtime (OXRSys + the wineopenxr bridge) is Soju's own build of pinned sources+(scripts/build-vr-runtime.sh). The mod's own installer runs under Windows+Python inside the copy, with the dependencies passed in already checked.++Three things the mod needs on Soju's engine, all inside the copy:+- the game folder's d3d12.dll is renamed, so D3D12 loads from system32, where+ ReShade watches for it (Wine already uses its builtin d3d12 either way);+- the windowed resolution is fixed at 1920x1080, the size the game first creates+ its swapchain at, so it never resizes it;+- one jump in ReShade64.dll skips work on a resource D3DMetal already destroyed+ (resources/d2r-vr.json, reshade.patch).+"""+import argparse+import hashlib+import json+import os+from pathlib import Path, PurePosixPath+import shutil+import subprocess+import sys+import tempfile+import zipfile++ROOT = Path(__file__).resolve().parents[1]+MANIFEST = ROOT / 'resources/d2r-vr.json'+BASE = Path(os.environ.get('SOJU_BASE', Path.home() / '.battlenet-macos'))+ENGINE = Path(os.environ.get('ENGINE', BASE / 'cx26-engine'))+SOURCE = BASE / 'bottle'+VR = BASE / 'd2r-vr'+BOTTLE = VR / 'bottle'+GAME_REL = 'drive_c/Program Files (x86)/Diablo II Resurrected'+SAVES_REL = 'drive_c/users/crossover/Saved Games/Diablo II Resurrected'+STATE = VR / 'state.json'+LIMIT = 256 * 1024 * 1024+++class VRError(Exception):+ pass+++def say(text):+ print(text, flush=True)+++def digest(path):+ h = hashlib.sha256()+ with Path(path).open('rb') as f:+ for block in iter(lambda: f.read(1024 * 1024), b''):+ h.update(block)+ return h.hexdigest()+++def manifest():+ return json.loads(MANIFEST.read_text())+++def recipe(m):+ return hashlib.sha256(json.dumps(m, sort_keys=True).encode()).hexdigest()+++def fetch(entry, name, label):+ """Download entry['url'] into the cache unless a checked copy is there."""+ cache = VR / 'downloads'+ cache.mkdir(parents=True, exist_ok=True)+ dest = cache / name+ if dest.is_file() and dest.stat().st_size == entry['size'] and digest(dest) == entry['sha256']:+ return dest+ if not entry.get('sha256') or not entry.get('size'):+ raise VRError(label + ' is not published yet for this Soju version.')+ say('Downloading ' + label + ' (' + str(max(1, entry['size'] // 1000000)) + ' MB)…')+ part = dest.with_suffix(dest.suffix + '.part')+ subprocess.run(['/usr/bin/curl', '--fail', '--silent', '--show-error', '--location', '--proto', '=https',+ '--proto-redir', '=https', '--retry', '3', '--connect-timeout', '20', '--max-time', '1800',+ entry['url'], '--output', str(part)], check=True)+ if part.stat().st_size != entry['size'] or digest(part) != entry['sha256']:+ part.unlink(missing_ok=True)+ raise VRError(label + ' did not match its pinned checksum; nothing was installed.')+ part.replace(dest)+ return dest+++def safe_extract_zip(archive, target):+ target.mkdir(parents=True, exist_ok=True)+ with zipfile.ZipFile(archive) as z:+ for info in z.infolist():+ path = PurePosixPath(info.filename.replace('\\', '/'))+ if path.is_absolute() or '..' in path.parts:+ raise VRError('Unsafe path in ' + archive.name + ': ' + info.filename)+ out = target.joinpath(*path.parts)+ if info.is_dir():+ out.mkdir(parents=True, exist_ok=True)+ continue+ out.parent.mkdir(parents=True, exist_ok=True)+ with z.open(info) as src, out.open('wb') as dst:+ shutil.copyfileobj(src, dst)+++def safe_extract_tar(archive, target):+ import tarfile+ target.mkdir(parents=True, exist_ok=True)+ with tarfile.open(archive) as t:+ for member in t.getmembers():+ path = PurePosixPath(member.name)+ if path.is_absolute() or '..' in path.parts or not (member.isfile() or member.isdir()):+ raise VRError('Unexpected entry in the VR runtime: ' + member.name)+ if hasattr(tarfile, 'data_filter'):+ t.extractall(target, filter='data')+ else: # macOS's /usr/bin/python3 3.9: members were checked above+ t.extractall(target)+++def winpath(path):+ return 'Z:' + str(Path(path).resolve()).replace('/', '\\')+++def wine_env(prefix):+ env = dict(os.environ)+ env.update({+ 'WINEPREFIX': str(prefix),+ 'WINEDEBUG': os.environ.get('SOJU_VR_WINEDEBUG', 'fixme-all'),+ 'WINEMSYNC': '1',+ 'ROSETTA_ADVERTISE_AVX': '1',+ 'WINE_SIMULATE_WRITECOPY': '1',+ 'CX_ACTIVE_GRAPHICS_BACKEND': 'd3dmetal',+ 'CX_GRAPHICS_BACKEND': 'd3dmetal',+ 'CX_APPLEGPTK_LIBD3DSHARED_PATH': str(ENGINE / 'lib/external/libd3dshared.dylib'),+ 'DYLD_FALLBACK_LIBRARY_PATH': str(ENGINE / 'lib') + ':/usr/lib',+ })+ env.pop('XR_RUNTIME_JSON', None)+ return env+++def wine(prefix, args, **kwargs):+ return subprocess.run([str(ENGINE / 'bin/wine')] + args, env=wine_env(prefix), **kwargs)+++def game_build(bottle):+ info = bottle / GAME_REL / '.build.info'+ try:+ text = info.read_text(errors='replace')+ except OSError:+ return None+ for line in reversed(text.splitlines()[1:]):+ for field in line.split('|'):+ parts = field.split('.')+ if len(parts) == 3 and all(p.isdigit() for p in parts):+ return field+ return None+++SHELLS = {'bash', 'zsh', '-zsh', 'sh', 'grep', 'pgrep', 'ps', 'python3', 'python', 'osascript'}+++def running(names):+ """Wine processes whose command line names one of these executables.++ A shell or script that only mentions the name (pgrep -f would match it)+ does not count."""+ out = subprocess.run(['/bin/ps', '-axo', 'args='], capture_output=True, text=True).stdout+ found = []+ for line in out.splitlines():+ first = line.strip().split(' ', 1)[0].replace('\\', '/').rsplit('/', 1)[-1]+ if first.lower() in SHELLS:+ continue+ if any(name.lower() in line.lower() for name in names):+ found.append(line)+ return found+++def stop_bottle(prefix):+ subprocess.run([str(ENGINE / 'bin/wineserver'), '-k'], env=wine_env(prefix),+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+++def patch_reshade(dll, spec):+ data = bytearray(dll.read_bytes())+ current = hashlib.sha256(data).hexdigest()+ patch = spec['patch']+ if current == patch['patched_sha256']:+ return False+ if current != spec['dll_sha256']:+ raise VRError('ReShade64.dll is not the pinned ReShade 6.8.0 build; not patching it.')+ at = patch['file_offset']+ old, new = bytes.fromhex(patch['old']), bytes.fromhex(patch['new'])+ if bytes(data[at:at + len(old)]) != old:+ raise VRError('ReShade64.dll does not have the expected code at the patch site.')+ data[at:at + len(new)] = new+ if hashlib.sha256(data).hexdigest() != patch['patched_sha256']:+ raise VRError('Patched ReShade64.dll did not come out as expected.')+ tmp = dll.with_suffix('.dll.soju-tmp')+ tmp.write_bytes(bytes(data))+ tmp.replace(dll)+ return True+++def fix_settings(saves):+ settings = saves / 'Settings.json'+ data = json.loads(settings.read_text(encoding='utf-8-sig'))+ if data.get('Screen Resolution (Windowed)') == '1920x1080' and str(data.get('Window Mode')) == '0':+ return+ data['Screen Resolution (Windowed)'] = '1920x1080'+ data['Window Mode'] = 0+ settings.write_text(json.dumps(data, indent=4), encoding='utf-8')+++def write_runtime_routing(m):+ runtime = VR / 'runtime'+ openxr = BOTTLE / 'drive_c/openxr'+ openxr.mkdir(parents=True, exist_ok=True)+ shutil.copy2(runtime / 'wine/x86_64-windows/wineopxdms.dll', openxr / 'wineopxdms.dll')+ (openxr / 'wineopxdms.json').write_text(json.dumps({+ 'file_format_version': '1.0.0',+ 'runtime': {'name': 'Soju wineopenxr (D3DMetal)', 'library_path': 'C:\\openxr\\wineopxdms.dll'},+ }, indent=2) + '\n')+ # The bridge applies these to its own (macOS) side when it loads; the+ # Windows OpenXR loader keeps reading the registry below.+ (VR / 'logs').mkdir(parents=True, exist_ok=True)+ (VR / 'bridge.env').write_text('XR_RUNTIME_JSON=' + str(runtime / 'runtime/oxrsys-runtime.json') + '\n'+ 'OXR_BRIDGE_LOG=' + str(VR / 'logs/bridge.log') + '\n')+ wine(BOTTLE, ['reg', 'add', 'HKLM\\Software\\Khronos\\OpenXR\\1', '/v', 'ActiveRuntime', '/t', 'REG_SZ',+ '/d', 'C:\\openxr\\wineopxdms.json', '/f'],+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)+++def setup(refresh=False):+ m = manifest()+ if not (ENGINE / 'bin/wine').is_file():+ raise VRError('The Soju engine is not installed. Run: soju install')+ if not (SOURCE / GAME_REL / 'D2R.exe').is_file() and not (BOTTLE / GAME_REL / 'D2R.exe').is_file():+ raise VRError('Diablo II: Resurrected is not installed in the Battle.net bottle.')+ if running(['D2R.exe', 'D2RLoader.exe']):+ raise VRError('Close Diablo II: Resurrected first.')++ kept = VR / 'saves-kept'+ if refresh and BOTTLE.exists():+ # Check the new source first: a D2R update the mod does not support+ # must not cost the copy that still works.+ build = game_build(SOURCE)+ if build != m['game_build']:+ raise VRError('Battle.net now has D2R ' + str(build) + '; D2R VR Unleashed supports '+ + m['game_build'] + '. Your current VR copy was kept.')+ if running(['Battle.net.exe']):+ raise VRError('Close Battle.net first, so the copy is consistent.')+ stop_bottle(BOTTLE)+ # Offline characters made in VR (and the VR video settings) live only+ # in the copy: keep them across the new copy.+ saves = BOTTLE / SAVES_REL+ if saves.is_dir() and not kept.exists():+ saves.rename(kept)+ say('Removing the old VR copy…')+ shutil.rmtree(BOTTLE)+ STATE.unlink(missing_ok=True)+ if not BOTTLE.exists():+ build = game_build(SOURCE)+ if build != m['game_build']:+ raise VRError('D2R VR Unleashed supports D2R ' + m['game_build'] + '; this install is '+ + str(build) + '.')+ if running(['Battle.net.exe']):+ raise VRError('Close Battle.net first, so the copy is consistent.')+ say('Copying the Battle.net bottle (APFS copy, shares disk space until files change)…')+ VR.mkdir(parents=True, exist_ok=True)+ source = SOURCE.resolve()+ result = subprocess.run(['/bin/cp', '-c', '-R', str(source), str(BOTTLE)], capture_output=True, text=True)+ if result.returncode:+ shutil.rmtree(BOTTLE, ignore_errors=True)+ raise VRError('Could not make an APFS copy of the bottle (the bottle must be on an APFS volume): '+ + result.stderr.strip())+ if kept.is_dir():+ saves = BOTTLE / SAVES_REL+ shutil.rmtree(saves, ignore_errors=True)+ saves.parent.mkdir(parents=True, exist_ok=True)+ kept.rename(saves)+ say('Kept the saves and settings of the previous VR copy.')+ elif game_build(BOTTLE) != m['game_build']:+ raise VRError('The VR copy has D2R ' + str(game_build(BOTTLE)) + '; D2R VR Unleashed supports '+ + m['game_build'] + '.')++ state = {}+ try:+ state = json.loads(STATE.read_text())+ except (OSError, ValueError):+ pass+ if state.get('recipe') == recipe(m) and (BOTTLE / GAME_REL / 'D2RLoader.exe').is_file():+ say('D2R VR is already set up. Play with: soju vr play')+ return 0++ runtime_archive = fetch(m['runtime'], 'soju-vr-runtime.tar.xz', 'the VR runtime')+ python_zip = fetch(m['python'], 'python-embed-amd64.zip', 'Windows Python (python.org)')+ mod_zip = fetch(m['mod'], 'd2r-pcvr-windows.zip', m['mod']['name'])+ loader_zip = fetch(m['loader'], m['loader']['file'], 'D2RLoader (d2rloader.net)')+ reshade_exe = fetch(m['reshade'], 'ReShade_Setup_Addon.exe', 'ReShade (reshade.me)')++ for name in ('runtime', 'python', 'mod', 'deps'):+ shutil.rmtree(VR / name, ignore_errors=True)+ safe_extract_tar(runtime_archive, VR / 'runtime')+ safe_extract_zip(python_zip, VR / 'python')+ safe_extract_zip(mod_zip, VR / 'mod')+ mod = VR / 'mod' / m['mod']['folder']+ deps = VR / 'deps'+ (deps / 'reshade-6.8').mkdir(parents=True)+ shutil.copy2(loader_zip, deps / m['loader']['file'])+ with zipfile.ZipFile(reshade_exe) as z:+ dll = z.read(m['reshade']['member'])+ if hashlib.sha256(dll).hexdigest() != m['reshade']['dll_sha256']:+ raise VRError('ReShade64.dll inside the ReShade setup did not match its pin.')+ (deps / 'reshade-6.8/ReShade64.dll').write_bytes(dll)+ # The embeddable Python only imports from its ._pth paths; add the mod's.+ (VR / 'python/python312._pth').write_text('python312.zip\r\n.\r\n' + winpath(mod / 'steamvr') + '\r\n')++ game = BOTTLE / GAME_REL+ off = game / 'd3d12.dll.soju-vr-off'+ if off.exists() and not (game / 'd3d12.dll').exists():+ off.rename(game / 'd3d12.dll') # the installer checks the stock game first+ stop_bottle(BOTTLE)+ say('Installing D2R VR Unleashed into the VR copy…')+ args = [winpath(VR / 'python/python.exe'), winpath(mod / 'steamvr/install.py'),+ '--game', 'C:\\Program Files (x86)\\Diablo II Resurrected',+ '--saves', 'C:\\users\\crossover\\Saved Games\\Diablo II Resurrected',+ '--deps', winpath(deps), '--plugin', winpath(mod / 'bin/d2rl-pcvr.dll'),+ '--openxr-loader', winpath(mod / 'bin/openxr_loader.dll'), '--casclib', winpath(mod / 'bin/CascLib.dll'),+ '--backup-dir', winpath(VR / 'backups'), '--store', 'battlenet', '--experimental-battlenet']+ if (game / 'D2RLoader.exe').is_file():+ args.append('--preserve-settings')+ result = wine(BOTTLE, args, capture_output=True, text=True)+ log = VR / 'logs/install.log'+ log.parent.mkdir(parents=True, exist_ok=True)+ log.write_text(result.stdout + result.stderr)+ if result.returncode or 'Installed offline VR mod' not in result.stdout:+ tail = [line for line in (result.stdout + result.stderr).splitlines() if line.strip()][-3:]+ raise VRError('The mod installer stopped: ' + ' | '.join(tail) + ' (log: ' + str(log) + ')')++ patch_reshade(game / 'mods' / m['mod']['mod_name'] / 'reshade/ReShade64.dll', m['reshade'])+ if (game / 'd3d12.dll').exists():+ (game / 'd3d12.dll').rename(off)+ fix_settings(BOTTLE / SAVES_REL)+ write_runtime_routing(m)+ stop_bottle(BOTTLE)+ STATE.write_text(json.dumps({'recipe': recipe(m), 'game_build': game_build(BOTTLE),+ 'mod': m['mod']['name']}, indent=2) + '\n')+ say('D2R VR is set up. Play with: soju vr play')+ say('Use an OFFLINE character. Start the OXRSys client on your headset (or the OXRSys Simulator) to see it.')+ say('If D2R says you have not been online for 30 days: play D2R online once from Battle.net, '+ 'then run: soju vr setup --refresh (VR characters are kept).')+ return 0+++def status():+ m = manifest()+ state = {}+ try:+ state = json.loads(STATE.read_text())+ except (OSError, ValueError):+ pass+ return {+ 'installed': BOTTLE.is_dir() and (BOTTLE / GAME_REL / 'D2RLoader.exe').is_file(),+ 'current': state.get('recipe') == recipe(m),+ 'game_build': game_build(BOTTLE) if BOTTLE.is_dir() else None,+ 'supported_build': m['game_build'],+ 'source_build': game_build(SOURCE),+ 'mod': m['mod']['name'],+ 'path': str(VR),+ }+++def play(extra):+ info = status()+ if not info['installed'] or not info['current']:+ raise VRError('D2R VR is not set up for this Soju version. Run: soju vr setup')+ if running(['D2R.exe', 'D2RLoader.exe']):+ raise VRError('Diablo II: Resurrected is already running.')+ env = wine_env(BOTTLE)+ env['WINEDLLPATH'] = str(VR / 'runtime/wine')+ env['OXR_BRIDGE_ENV_FILE'] = str(VR / 'bridge.env')+ os.chdir(BOTTLE / GAME_REL)+ # -mod keeps D2R offline: no Battle.net game servers.+ os.execve(str(ENGINE / 'bin/wine'), [str(ENGINE / 'bin/wine'), 'D2RLoader.exe', '-mod',+ manifest()['mod']['mod_name']] + extra, env)+++def remove(yes):+ if not VR.exists():+ say('D2R VR is not set up.')+ return 0+ if not yes:+ raise VRError('This deletes ' + str(VR) + ' (offline characters made in VR included). '+ 'Run again with --yes to confirm.')+ if running(['D2R.exe', 'D2RLoader.exe']):+ raise VRError('Close Diablo II: Resurrected first.')+ if BOTTLE.exists():+ stop_bottle(BOTTLE)+ shutil.rmtree(VR)+ say('Removed ' + str(VR) + '. Your Battle.net bottle was not changed.')+ return 0+++def main(argv):+ parser = argparse.ArgumentParser(prog='soju vr')+ sub = parser.add_subparsers(dest='command', required=True)+ p = sub.add_parser('setup')+ p.add_argument('--refresh', action='store_true', help='copy the Battle.net bottle again (after a game update)')+ sub.add_parser('play')+ p = sub.add_parser('status')+ p.add_argument('--json', action='store_true')+ p = sub.add_parser('remove')+ p.add_argument('--yes', action='store_true')+ args, extra = parser.parse_known_args(argv)+ try:+ if args.command == 'setup':+ return setup(args.refresh)+ if args.command == 'play':+ return play(extra)+ if args.command == 'status':+ info = status()+ if args.json:+ print(json.dumps(info))+ else:+ say('D2R VR: ' + ('ready' if info['installed'] and info['current'] else 'not set up'))+ say(' game build in the VR copy: ' + str(info['game_build']) + ' (supported '+ + info['supported_build'] + ')')+ say(' Battle.net bottle build: ' + str(info['source_build']))+ return 0+ if args.command == 'remove':+ return remove(args.yes)+ except VRError as error:+ print('soju vr: ' + str(error), file=sys.stderr)+ return 1+ except subprocess.CalledProcessError as error:+ print('soju vr: a step failed (' + ' '.join(map(str, error.cmd[:2])) + ')', file=sys.stderr)+ return 1+ return 0+++if __name__ == '__main__':+ sys.exit(main(sys.argv[1:]))diff --git a/scripts/desktop-action.sh b/scripts/desktop-action.shindex 851ecdb80d6..ff5b87971bf 100755--- a/scripts/desktop-action.sh+++ b/scripts/desktop-action.sh@@ -15,6 +15,9 @@ case "$ACTION" inlaunch)case "${1:-}" in battlenet|steam|epic|gog) exec bash "$ROOT/scripts/play.sh" "$1" ;;*) echo "Choose one of the four launchers."; exit 64 ;; esac ;;+ vr)+ case "${1:-}" in setup|play|status) exec python3 "$ROOT/scripts/d2r-vr.py" "$1" ;;+ *) echo "Unknown VR action."; exit 64 ;; esac ;;xbox)case "${1:-}" in login|logout|kill|status) exec bash "$ROOT/scripts/xbox.sh" "$1" ;;*) echo "Unknown Xbox action."; exit 64 ;; esac ;;diff --git a/scripts/soju b/scripts/sojuindex 84258a9eb82..c1d535b1c40 100755--- a/scripts/soju+++ b/scripts/soju@@ -27,6 +27,9 @@ Usage:soju d2r Launch Diablo II: Resurrected directlysoju kill Stop everything in the Battle.net bottlesoju controllers Game Controllers panel of the Battle.net bottle (is my pad seen?)+ soju vr setup D2R in VR (offline): copy the Battle.net bottle and install D2R VR Unleashed+ soju vr play Play D2R in VR (OXRSys client on the headset; offline characters)+ soju vr status|removesoju epic-install Set up the Epic Games Launcher bottle (same engine)soju epic Launch the Epic Games Launcher@@ -71,6 +74,7 @@ case "${1:-}" inepic-install) shift; exec bash "$ROOT/scripts/create-epic-bottle.sh" "$@" ;;gog-install) shift; exec bash "$ROOT/scripts/create-gog-bottle.sh" "$@" ;;steam-install) shift; export SOJU_PLATFORMS=steam; exec bash "$ROOT/install.sh" "$@" ;;+ vr) shift; exec python3 "$ROOT/scripts/d2r-vr.py" "$@" ;;xbox-install) exec bash "$ROOT/scripts/xbox.sh" install ;;xbox-login) exec bash "$ROOT/scripts/xbox.sh" login ;;xbox-logout) shift; exec bash "$ROOT/scripts/xbox.sh" logout "$@" ;;diff --git a/tests/test_d2r_vr.py b/tests/test_d2r_vr.pynew file mode 100644index 00000000000..52f5bf11d0e--- /dev/null+++ b/tests/test_d2r_vr.py@@ -0,0 +1,137 @@+import hashlib+import importlib.util+import json+from pathlib import Path+import tempfile+import unittest+import zipfile++ROOT = Path(__file__).resolve().parents[1]+spec = importlib.util.spec_from_file_location('d2r_vr', ROOT / 'scripts/d2r-vr.py')+vr = importlib.util.module_from_spec(spec)+spec.loader.exec_module(vr)+++class ManifestTests(unittest.TestCase):+ def test_every_download_is_pinned_https(self):+ m = json.loads((ROOT / 'resources/d2r-vr.json').read_text())+ for key in ('runtime', 'python', 'mod', 'loader', 'reshade'):+ self.assertTrue(m[key]['url'].startswith('https://'), key)+ self.assertRegex(m[key]['sha256'], '^[0-9a-f]{64}$', key)+ self.assertGreater(m[key]['size'], 0, key)+ self.assertEqual(m['runtime']['url'],+ 'https://github.com/BCD1210/soju/releases/download/vr-runtime-v1/soju-vr-runtime.tar.xz')+ patch = m['reshade']['patch']+ self.assertEqual(len(bytes.fromhex(patch['old'])), len(bytes.fromhex(patch['new'])))+ self.assertRegex(patch['patched_sha256'], '^[0-9a-f]{64}$')++ def test_cli_routes_vr_to_the_script(self):+ self.assertIn('vr) shift; exec python3 "$ROOT/scripts/d2r-vr.py" "$@" ;;',+ (ROOT / 'scripts/soju').read_text())++ def test_app_actions_are_routed(self):+ action = (ROOT / 'scripts/desktop-action.sh').read_text()+ self.assertIn('setup|play|status) exec python3 "$ROOT/scripts/d2r-vr.py" "$1"', action)+ library = (ROOT / 'app/Library.swift').read_text()+ self.assertIn('model.run(["vr", "setup"]', library)+ self.assertIn('task(["vr", "play"]', library)+++class ReShadePatchTests(unittest.TestCase):+ def spec_for(self, data, at):+ old, new = b'\x48\x8b\xcf\x48\x8b\x07\xff\x50\x50', b'\xe9\x18\x04\x00\x00\x90\x90\x90\x90'+ patched = bytearray(data)+ patched[at:at + len(new)] = new+ return {'dll_sha256': hashlib.sha256(data).hexdigest(),+ 'patch': {'file_offset': at, 'old': old.hex(), 'new': new.hex(),+ 'patched_sha256': hashlib.sha256(bytes(patched)).hexdigest()}}++ def test_patches_the_pinned_build_once(self):+ data = b'\0' * 100 + bytes.fromhex('488bcf488b07ff5050') + b'\1' * 50+ spec = self.spec_for(data, 100)+ with tempfile.TemporaryDirectory() as d:+ dll = Path(d) / 'ReShade64.dll'+ dll.write_bytes(data)+ self.assertTrue(vr.patch_reshade(dll, spec))+ self.assertEqual(hashlib.sha256(dll.read_bytes()).hexdigest(), spec['patch']['patched_sha256'])+ self.assertFalse(vr.patch_reshade(dll, spec)) # already patched: left alone++ def test_refuses_another_build(self):+ data = b'\0' * 100 + bytes.fromhex('488bcf488b07ff5050')+ spec = self.spec_for(data, 100)+ with tempfile.TemporaryDirectory() as d:+ dll = Path(d) / 'ReShade64.dll'+ dll.write_bytes(data + b'x')+ with self.assertRaises(vr.VRError):+ vr.patch_reshade(dll, spec)+ self.assertEqual(dll.read_bytes(), data + b'x')+++class HelperTests(unittest.TestCase):+ def test_zip_extraction_refuses_escaping_paths(self):+ with tempfile.TemporaryDirectory() as d:+ archive = Path(d) / 'a.zip'+ with zipfile.ZipFile(archive, 'w') as z:+ z.writestr('../evil.txt', 'x')+ with self.assertRaises(vr.VRError):+ vr.safe_extract_zip(archive, Path(d) / 'out')+ self.assertFalse((Path(d) / 'evil.txt').exists())++ def test_game_build_reads_build_info(self):+ with tempfile.TemporaryDirectory() as d:+ game = Path(d) / vr.GAME_REL+ game.mkdir(parents=True)+ (game / '.build.info').write_text('Branch!STRING:0|Active!DEC:1|Version!STRING:0\n'+ 'kr|1|3.3.93847\n')+ self.assertEqual(vr.game_build(Path(d)), '3.3.93847')+ self.assertIsNone(vr.game_build(Path(d) / 'missing'))++ def test_settings_fixed_at_the_first_swapchain_size(self):+ with tempfile.TemporaryDirectory() as d:+ settings = Path(d) / 'Settings.json'+ settings.write_text('\ufeff' + json.dumps({'Screen Resolution (Windowed)': '1731x932', 'Window Mode': 1}),+ encoding='utf-8')+ vr.fix_settings(Path(d))+ data = json.loads(settings.read_text(encoding='utf-8-sig'))+ self.assertEqual(data['Screen Resolution (Windowed)'], '1920x1080')+ self.assertEqual(data['Window Mode'], 0)++ def test_running_ignores_shells_that_only_mention_the_game(self):+ from unittest import mock+ ps = ('/bin/zsh -c pgrep -fl "D2RLoader.exe"\n'+ 'bash /opt/soju/scripts/play.sh d2r D2R.exe\n'+ 'C:\\Program Files (x86)\\Diablo II Resurrected\\D2R.exe -uid osi\n'+ 'D2RLoader.exe -mod D2R-PCVR\n')+ with mock.patch.object(vr.subprocess, 'run', return_value=mock.Mock(stdout=ps)):+ found = vr.running(['D2R.exe', 'D2RLoader.exe'])+ self.assertEqual(len(found), 2)+ self.assertTrue(all('zsh' not in line and 'bash' not in line for line in found))++ def test_refresh_keeps_the_copy_when_the_new_build_is_unsupported(self):+ from unittest import mock+ with tempfile.TemporaryDirectory() as d:+ base = Path(d)+ source, vr_dir = base / 'bottle', base / 'd2r-vr'+ bottle = vr_dir / 'bottle'+ for b, build in ((source, '3.3.99999'), (bottle, '3.3.93847')):+ game = b / vr.GAME_REL+ game.mkdir(parents=True)+ (game / 'D2R.exe').write_bytes(b'')+ (game / '.build.info').write_text('Version!STRING:0\n' + build + '\n')+ engine = base / 'engine'+ (engine / 'bin').mkdir(parents=True)+ (engine / 'bin/wine').write_bytes(b'')+ with mock.patch.multiple(vr, ENGINE=engine, SOURCE=source, VR=vr_dir, BOTTLE=bottle,+ STATE=vr_dir / 'state.json'), \+ mock.patch.object(vr, 'running', return_value=[]):+ with self.assertRaises(vr.VRError) as caught:+ vr.setup(refresh=True)+ self.assertIn('was kept', str(caught.exception))+ self.assertTrue((bottle / vr.GAME_REL / 'D2R.exe').exists())++ def test_windows_paths_go_through_z(self):+ self.assertTrue(vr.winpath('/tmp').startswith('Z:\\'))+++if __name__ == '__main__':+ unittest.main()