Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6b00bc787 | ||
|
|
638bc75724 | ||
|
|
02fe867cf1 | ||
|
|
742094ea1e | ||
|
|
c8ba395e4f | ||
|
|
4e99d2c484 | ||
|
|
42b8275151 | ||
|
|
594ff5ab54 | ||
|
|
41088d5377 | ||
|
|
d94c8fe687 | ||
|
|
de967dd993 | ||
|
|
dc5e637e20 | ||
|
|
240ee81712 | ||
|
|
6e65cec4c0 | ||
|
|
aa952e7cca | ||
|
|
5983e3f3e2 | ||
|
|
662e837ab2 | ||
|
|
8636d0b71d | ||
|
|
97707f533d | ||
|
|
ada635ecc7 | ||
|
|
deffcd6dde | ||
|
|
4e72bf3746 | ||
|
|
3aac60c8a3 | ||
|
|
dbc21182a2 | ||
|
|
5c09c4e47a | ||
|
|
dce9b59765 | ||
|
|
e8122d7c6b | ||
|
|
aa7a6e7d02 | ||
|
|
fd9d25d346 | ||
|
|
8fbaeb4228 | ||
|
|
4999c7f5a3 | ||
|
|
d0e4797fe7 | ||
|
|
f1ec034994 | ||
|
|
646be7afb9 | ||
|
|
7bd17c4f74 | ||
|
|
be772c0cea | ||
|
|
fa7f68b942 | ||
|
|
899fb5d91b | ||
|
|
3f0e08c5b7 | ||
|
|
fb7d07f4f9 | ||
|
|
2d5e268083 | ||
|
|
66bbdf7192 | ||
|
|
bf2ce539e7 | ||
|
|
3ed41bdd60 | ||
|
|
a23629fe69 | ||
|
|
1535bd032b | ||
|
|
de9ba52b85 | ||
|
|
82ec1c47ff | ||
|
|
e284ea7ed6 | ||
|
|
ae1e5ec65b | ||
|
|
c55ec4ed57 | ||
|
|
f3d04d137f | ||
|
|
96077153c6 | ||
|
|
90bd5a315d | ||
|
|
1c6f5c9fc4 | ||
|
|
cab73f92f9 | ||
|
|
1c24adbd83 |
No files matched your search
@@ -0,0 +1,35 @@
|
|||||||
|
## 简体中文
|
||||||
|
|
||||||
|
> **重要升级提示:** 所有使用 **Gaijin 官方独立版客户端**,或者 **Steam 版但曾经通过官方启动器(更新器)启动过游戏** 的用户,**必须更新到 `v0.1.1` 启动器**(更新后请对已有离线副本重新执行一次「构建客户端」)。旧版启动器在存在官方清单 `content/warthunder.blk` 时会触发游戏拉起官方启动器并还原离线补丁,导致启动闪退、弹出官服更新或报原版备份不一致。
|
||||||
|
|
||||||
|
`v0.1.1` 是 WTOffline 启动器的重要维护更新,重点修复官方客户端/官方启动器用户无法正常启动的问题、修复对局中非本机载具受损提示串台,并增强启动稳定性与故障诊断能力。
|
||||||
|
|
||||||
|
### 修复与改进
|
||||||
|
|
||||||
|
- **解决官方独立版 / 官方启动器拉起官服更新的问题。** 启动参数新增 `-skip_pkg_validation`,跳过 `aces.exe` 启动时对官方 `content/warthunder.blk` 的文件体积校验;同时新增可执行文件隔离补丁,阻止游戏在异常情况下拉起官方 `launcher.exe -fullcheck` 联网覆盖离线文件,修复“启动数秒后以退出码 `1` 退出 → 弹出官服更新 → 离线文件被还原/报备份不一致”的死循环。
|
||||||
|
- **局内受损提示与敌方部件归属。** 修复空战与现代陆战中 AI 载具航电、传感器、雷达、红外干扰和瞄准吊舱受损时错误向玩家弹出白字提示(及误退光电视角)的问题;过滤陆战与海战右侧敌方部件损毁列表及特殊命中反馈中的非本机攻击记录,保留本机在途弹药与观战视角显示。
|
||||||
|
- **启动与写盘稳定性。** 游戏补丁文件写入改为临时文件原子替换并带短暂占用重试,降低安全软件实时扫描导致写入失败的风险;优化 `wto_ws.dll` 加载时的钩子批量启用流程,减少初始化期的线程冻结次数并记录详细错误码。
|
||||||
|
- **原版备份检测与报错。** 修复旧版 `wtoffline\stock` 备份在客户端更新后遮蔽实际版本、无法自动刷新的问题;启动时区分「原版文件备份缺失/损坏」与「版本不一致」,并在日志中记录双方实际版本号。
|
||||||
|
- **启动前检查与诊断导出。** 启动游戏前核对核心文件是否可读(提前提示可能被安全软件隔离);异常退出时在启动器日志记录现场文件状态与带十六进制的系统退出码;导出的诊断 ZIP 自动附带 `wto_ws.log`、最新一份游戏 `.clog` 日志和环境摘要(不含玩家存档)。
|
||||||
|
|
||||||
|
### 客户端兼容性
|
||||||
|
|
||||||
|
支持已核对版本 `2.61.0.37`、`2.61.0.43` 和 `2.61.0.55`(自带补丁集 `2026.12.02`),并支持按特征码自动尝试适配后续小版本更新。
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
> **Important upgrade notice:** All users on the **standalone Gaijin client**, as well as **Steam users who have ever launched the game through the official Gaijin launcher/updater**, **must upgrade to `v0.1.1`** (and rebuild existing offline copies after updating). On earlier launcher versions, the presence of `content/warthunder.blk` causes `aces.exe` to spawn the official launcher and overwrite patched offline files, resulting in startup exit code `1`, official updater popups, or stock-backup version mismatches.
|
||||||
|
|
||||||
|
`v0.1.1` is an important maintenance release of the WTOffline Launcher that fixes startup failures on standalone/official-launcher clients, fixes cross-unit battle damage notices, improves launch reliability, and strengthens crash diagnostics.
|
||||||
|
|
||||||
|
### Fixes and improvements
|
||||||
|
|
||||||
|
- **Skip startup package validation and block official launcher spawns.** Added `-skip_pkg_validation` to offline launch arguments so `aces.exe` skips the startup `content/warthunder.blk` file-size integrity check, and added an executable isolation patch that blocks `aces.exe` from spawning the official `launcher.exe -fullcheck` updater. This eliminates the loop where the game exits with code `1`, opens the official launcher, and overwrites offline files back to the online build.
|
||||||
|
- **In-battle damage notices and enemy parts feedback.** Fixed AI avionics, sensor, radar, RWR/countermeasures, and targeting-pod failures in air and modern ground battles incorrectly showing white damage notices (or forcing the player out of optic view). Filtered non-local AI-on-AI hits out of the ground/naval enemy damaged-parts list and special hit-camera events while preserving in-flight player munitions and spectator views.
|
||||||
|
- **Launch and file-write reliability.** Rebuilt game files are now written via temporary files with atomic rename and brief retry on transient antivirus locks. Batched MinHook activation in `wto_ws.dll` into two passes to cut startup thread-freeze cycles and log detailed `MH_STATUS` diagnostics on failure.
|
||||||
|
- **Stock backup detection and errors.** Fixed stale `wtoffline\stock` backups masking an externally updated client and blocking backup refresh. Launch checks now distinguish missing/unreadable backups from version mismatches and log the exact copy and backup versions.
|
||||||
|
- **Pre-launch checks and richer diagnostics.** Verify core launch files before starting `aces.exe` (flagging possible antivirus quarantine early), log post-exit file snapshots and hex-annotated Windows exit codes, and include `wto_ws.log`, the latest `.clog`, and a metadata summary (without player saves) in exported diagnostic ZIPs.
|
||||||
|
|
||||||
|
### Client compatibility
|
||||||
|
|
||||||
|
Verified with client versions `2.61.0.37`, `2.61.0.43`, and `2.61.0.55` (bundled patch set `2026.12.02`), with pattern-based matching for later minor updates.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
## 简体中文
|
||||||
|
|
||||||
|
`v0.1.2` 是 WTOffline 启动器的维护更新,重点放开「节省空间的复制」对游戏版本的硬锁定、修复维护页更新客户端时的路径校验误报,并内置 `2.61.0.58` 版本核对记录。
|
||||||
|
|
||||||
|
### 修复与改进
|
||||||
|
|
||||||
|
- **省空间复制改为跨版本规则。** 取消原先绑定单一版本号(`2.61.0.43`)与 8 MiB 体积门槛的静态哈希清单,改为基于只读资源规则自动共用 `content/` 与 `content.hq/` 下的 `.dxp.bin` 和 `.grp` 资源包;小版本更新后无需等待新清单即可继续省空间安装或转换,且同卷省空间客户端执行「从在线版更新」时会保持或重建硬链接,不再拆分为完整复制。
|
||||||
|
- **修复维护页「从在线版更新」误报路径越界。** 扫描安装来源时排除顶层残留的 `wtoffline` 目录;安装向导第 3 步与后台同步拦截将数据目录设为客户端目录或其父目录的配置,并解除旧安装把数据目录放在客户端父目录时的误报;所有路径安全校验失败均在启动器日志中记录具体原因与路径以便排查。
|
||||||
|
- **「关于」页快速导出日志与关闭日志开关。** 在「关于」页新增「保存日志 ZIP…」快捷按钮(导出内容同时纳入最新一份内置浏览器 `-browser.log`,仍不含玩家存档),并在「设置 → 诊断」新增「生成运行日志」开关,允许关闭启动器日志、本地服务器流量日志及 `wto_ws.log` 的磁盘写入。
|
||||||
|
|
||||||
|
### 客户端兼容性
|
||||||
|
|
||||||
|
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`(自带补丁集 `2026.12.02`),并支持按特征码自动尝试适配后续小版本更新。
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
`v0.1.2` is a maintenance release of the WTOffline Launcher that makes space-saving copies resilient across minor game updates, fixes false path-scope errors during client updates, and bundles the `2.61.0.58` version check record.
|
||||||
|
|
||||||
|
### Fixes and improvements
|
||||||
|
|
||||||
|
- **Version-independent space-saving copies.** Replaced the single-version (`2.61.0.43`) SHA-256 manifest and 8 MiB cutoff with declarative read-only asset rules covering `.dxp.bin` and `.grp` archives under `content/` and `content.hq/`. Space-saving installs and conversions now keep working across minor updates, and updating a same-volume space-saving client preserves or recreates hard links instead of detaching them into full copies.
|
||||||
|
- **Fix false `maintenance_location` errors when updating.** Ignore stray top-level `wtoffline` folders when scanning a stock source, prevent picking a data folder that equals or contains the client folder during installation (with inline Step 3 validation), stop blocking updates when an existing installation placed `dataPath` at an ancestor of the client folder, and log the exact reason and paths on every path-scope rejection.
|
||||||
|
- **Quick log ZIP export on About and runtime logging toggle.** Added a quick "Save log ZIP…" button on the About page (now also bundling the latest embedded browser `-browser.log`, still excluding saves), and added a "Record runtime logs" toggle under Settings → Diagnostics to stop writing launcher logs, local server traffic logs, and `wto_ws.log`.
|
||||||
|
|
||||||
|
### Client compatibility
|
||||||
|
|
||||||
|
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58` (bundled patch set `2026.12.02`), with pattern-based matching for later minor updates.
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
## 简体中文
|
||||||
|
|
||||||
|
`v0.1.3` 是 WTOffline的一次大型功能更新,正式引入**第一版模组系统(开放社区模组制作)**、初步接通**原子雷霆**模式,并包含多项对局机制、存档容量、贴花导入与更新链路修复。
|
||||||
|
|
||||||
|
### 该下载哪一个文件?
|
||||||
|
|
||||||
|
- **绝大多数玩家**:下载 **`wtoffline-launcher-0.1.3-win-x64.exe`** ,下载后安装即可。
|
||||||
|
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.3-win-x64-portable.zip`** ,解压到任意目录后运行其中的启动器即可。
|
||||||
|
|
||||||
|
### 重点新功能
|
||||||
|
|
||||||
|
- **第一版模组系统与开放模组制作(实验性)。**
|
||||||
|
- 启动器新增「模组」管理页:支持为每个客户端独立开关模组、调整加载顺序、保存/切换模组方案以及自定义模组目录,并可直接一键打开完整模组开发文档。
|
||||||
|
- 支持客户端数据包增量覆写(BLK / CSV / 附加包挂载,且核心隔离补丁受保护不可被误覆盖)、服务端 JS/TS 脚本钩子与独立模组数据存储,以及数值列表增量修改。
|
||||||
|
- 内置并首次自动生成 3 套官方示例模组模板(含可直接使用的「官方地图选择器」、服务端脚本示例与载具参数微调示例),配套完整中英文 `mod-dev-docs` 开发手册,欢迎玩家与创作者制作并分享自己的模组。
|
||||||
|
- **接通「原子雷霆」模式。**
|
||||||
|
- 完整接入空战历史子模式「原子雷霆」的专用 HUD、阶段推进门槛、不限出击次数与机场独立冷却机制,并按 10 国与房间权重自动分配战术核弹载机(5 kt / 30 kt)。
|
||||||
|
- 在启动器「数值 → 对局」新增「原子雷霆战略核轰炸机」开关(默认开启),可在阶段 3 追加战略核轰炸机(`B-52H` / `Tu-95M`)。
|
||||||
|
|
||||||
|
### 修复与改进
|
||||||
|
|
||||||
|
- **对局与战斗体验**:
|
||||||
|
- 恢复陆战街机空中支援事件(呼叫战斗机 / 攻击机 / 轰炸机);
|
||||||
|
- 修复本地主机下玩家乘员技能与专家 / 王牌资格在战局内未生效的问题;
|
||||||
|
- 恢复空战街机模式下的空中重新装填弹药;
|
||||||
|
- 修复部分载具出生时改装件效果反转,以及单弹链航空武器被未选中的隐身弹链覆盖导致无曳光弹的问题;
|
||||||
|
- 恢复对战模式飞机有限燃油消耗与油量倒计时,并修复局内小队黄色标记;
|
||||||
|
- 支持在机库切换并保存载具的可选分房权重(如部分直升机 / 挂载升档),开局按所选权重参与匹配;
|
||||||
|
- 修复空战街机等多槽模式下 AI 飞机重生次数受限,以及坦克 AI 重生次数配置未对全部模式生效的问题(感谢 `duduyagame`);
|
||||||
|
- 修复新手教程完成进度未保存的问题:通关后重启不再反复提示教程,并按原版规则发放首次通关的贴花、基础教程金鹰及各难度银狮奖励(感谢 `duduyagame`)。
|
||||||
|
- **启动器、存档与更新链路**:
|
||||||
|
- 修复新版在线客户端贴花与可下载涂装缓存导入失败的问题(兼容现行 `regional.vromfs.bin` + `.ddsx` 及旧版缓存格式);
|
||||||
|
- 修复全车库改装件总数超过 65,535 个时的存档溢出问题;
|
||||||
|
- 将启动器「存档 → 载具和研发」中的「全部研发」与「获得常规载具」合并为一步到位的「全部研发并购买」;
|
||||||
|
- 优化默认更新线路并保留 GitHub 自动回退,全流程继续保持 Ed25519 签名校验;
|
||||||
|
- 「关于」页改版为双栏布局,新增「项目主页」与「Discord」快捷入口,修复切换页面时维护进度丢失的问题。
|
||||||
|
|
||||||
|
### 社区交流与模组分享
|
||||||
|
|
||||||
|
欢迎加入 WTOffline 官方 Discord 服务器,一起交流玩法、反馈 Bug、分享你的调参或自制模组,并关注最新客户端适配进度:
|
||||||
|
|
||||||
|
- **Discord 社区**:https://discord.gg/P566xWNpEs
|
||||||
|
- **项目主页**:https://wto-project.net
|
||||||
|
|
||||||
|
### 客户端兼容性
|
||||||
|
|
||||||
|
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`,并支持按特征码自动尝试适配后续小版本更新。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
`v0.1.3` is a major feature release of WTOffline introducing the **first version of the experimental Mod System** (opening up community mod authoring), Add support for **Nuclear Escalation**, and a broad set of battle, save, decal import, and launcher fixes.
|
||||||
|
|
||||||
|
### Which file should I download?
|
||||||
|
|
||||||
|
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.3-win-x64.exe`** — the standard Windows installer with built-in automatic update checks.
|
||||||
|
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.3-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
- **Experimental Mod System v1 & Mod Authoring.**
|
||||||
|
- New **Mods** page in the launcher with per-client enablement, load-order management, presets, custom mod repository folder, and a quick-open button for the mod developer handbook.
|
||||||
|
- Supports additive client archive overlays (BLK / CSV / addon mounts while protecting essential isolation patches), server-side JS/TS lifecycle hooks with isolated mod storage, and tuning list operations.
|
||||||
|
- Ships with 3 bundled example mod templates (including a ready-to-use **Official Map Selector**, a server script example, and a vehicle tweak example) plus full bilingual documentation in `mod-dev-docs/`.
|
||||||
|
- **Nuclear Escalation mode.**
|
||||||
|
- Full support for Air Realistic sub-mode **Nuclear Escalation**, including custom HUD, stage thresholds, unlimited respawns, per-airfield cooldowns, and nation-matched tactical nuclear carriers (5 kt / 30 kt) scaled to room BR.
|
||||||
|
- Added a **Nuclear Escalation strategic bombers** toggle under **Tuning → Battle** (enabled by default) to unlock stage-3 strategic nuclear bombers (`B-52H` / `Tu-95M`).
|
||||||
|
|
||||||
|
### Fixes and improvements
|
||||||
|
|
||||||
|
- **Battles & gameplay**:
|
||||||
|
- Restored Ground Arcade air support events (fighters, attackers, bombers).
|
||||||
|
- Fixed player crew skills and Expert / Ace qualifications not applying on the local host.
|
||||||
|
- Restored in-flight ammunition reload in Air Arcade.
|
||||||
|
- Fixed inverted modification effects on spawn and single-belt aircraft tracers being overwritten by unselected stealth belts.
|
||||||
|
- Restored limited fuel consumption / HUD fuel timer in versus modes and yellow squad target markers.
|
||||||
|
- Persisted selectable battle ratings for units with BR-changing modifications and applied them during matchmaking.
|
||||||
|
- Fixed AI aircraft respawn limits in Air Arcade and other multi-slot modes, and applied configured ground AI respawn counts across all modes (thanks to `duduyagame`).
|
||||||
|
- Persisted stock training/tutorial completion progress so finished tutorials no longer re-prompt after restart, and granted one-time first-completion decals, basic tutorial Golden Eagles, and per-difficulty Silver Lions rewards (thanks to `duduyagame`).
|
||||||
|
- **Launcher, saves & updates**:
|
||||||
|
- Fixed online decal and downloadable skin cache import on modern 2.61 clients (supports both `regional.vromfs.bin` + `.ddsx` and legacy cache layouts).
|
||||||
|
- Fixed save overflow when total owned modifications exceed 65,535 by splitting across native sibling blocks.
|
||||||
|
- Merged "Research all" and "Grant regular vehicles" into a single **Research and buy all** action in the launcher.
|
||||||
|
- Improved default release update routing with automatic GitHub fallback and continued Ed25519 signature verification.
|
||||||
|
- Updated the About page to a two-column layout with **Project homepage** and **Discord** buttons, and preserved copy maintenance progress across tab switches.
|
||||||
|
|
||||||
|
### Community & Mod Sharing
|
||||||
|
|
||||||
|
Join the official WTOffline Discord server to chat, report issues, share tuning presets or custom mods, and follow client adaptation updates:
|
||||||
|
|
||||||
|
- **Discord**: https://discord.gg/P566xWNpEs
|
||||||
|
- **Homepage**: https://wto-project.net
|
||||||
|
|
||||||
|
### Client compatibility
|
||||||
|
|
||||||
|
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58`, with signature-based matching for later minor updates.
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
# Build, sign, and publish a Windows installer of the WTOffline Launcher as a GitHub release
|
# Build, sign, and publish a Windows installer of the WTOffline Launcher as a GitHub release
|
||||||
# tagged v<version>. The launcher's update check reads v<version> releases and expects all three
|
# tagged v<version>. The launcher's update check reads v<version> releases and expects the three
|
||||||
# files (installer, manifest, signature); a release missing any of them breaks the check for
|
# signed files (installer, manifest, signature); a release missing any of them breaks the check
|
||||||
# already-installed launchers.
|
# for already-installed launchers. The workflow also packages and signs the portable zip with its
|
||||||
|
# own manifest and signature so portable installations can update in place.
|
||||||
#
|
#
|
||||||
# Start it either way:
|
# Start it either way:
|
||||||
# - push a tag: git tag v0.1.0 && git push origin v0.1.0
|
# - push a tag: git tag v0.1.0 && git push origin v0.1.0
|
||||||
@@ -67,7 +68,7 @@ jobs:
|
|||||||
npm run typecheck
|
npm run typecheck
|
||||||
npm run typecheck --workspace "@wto/launcher"
|
npm run typecheck --workspace "@wto/launcher"
|
||||||
|
|
||||||
- name: Build and package the Windows installer
|
- name: Build and package the Windows installer and portable archive
|
||||||
run: npm --workspace "@wto/launcher" run package:win
|
run: npm --workspace "@wto/launcher" run package:win
|
||||||
|
|
||||||
- name: Sign the release
|
- name: Sign the release
|
||||||
@@ -87,6 +88,9 @@ jobs:
|
|||||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.exe" \
|
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.exe" \
|
||||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json" \
|
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json" \
|
||||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json.sig" \
|
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json.sig" \
|
||||||
|
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.zip" \
|
||||||
|
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.manifest.json" \
|
||||||
|
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.manifest.json.sig" \
|
||||||
"${flags[@]}" \
|
"${flags[@]}" \
|
||||||
--title "WTOffline Launcher $VERSION" \
|
--title "WTOffline Launcher $VERSION" \
|
||||||
--notes-file ".github/release-notes/v$VERSION.md" \
|
--notes-file ".github/release-notes/v$VERSION.md" \
|
||||||
|
|||||||
+5
-1
@@ -1,5 +1,8 @@
|
|||||||
# Never commit game files (copyright, size). The build reads them from a game folder.
|
# Never commit game files (copyright, size). The build reads them from a game folder.
|
||||||
*.vromfs.bin
|
*.vromfs.bin
|
||||||
|
# Allow additive patch directories named after target packs inside mod templates (never binary archives).
|
||||||
|
!mod-dev-docs/templates/**/client/packs/*.vromfs.bin/
|
||||||
|
!mod-dev-docs/templates/**/client/packs/ui/*.vromfs.bin/
|
||||||
*.vromfs.bin.orig
|
*.vromfs.bin.orig
|
||||||
aces.exe
|
aces.exe
|
||||||
aces*.exe
|
aces*.exe
|
||||||
@@ -25,10 +28,11 @@ __pycache__/
|
|||||||
*.pyc
|
*.pyc
|
||||||
.venv/
|
.venv/
|
||||||
|
|
||||||
# Saves, logs, local runtime data
|
# Saves, logs, local runtime data, local secrets
|
||||||
/data/
|
/data/
|
||||||
/saves/
|
/saves/
|
||||||
*.log
|
*.log
|
||||||
|
.env*.local
|
||||||
|
|
||||||
# Editors / OS
|
# Editors / OS
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
<a id="zh-cn"></a>
|
<a id="zh-cn"></a>
|
||||||
|
|
||||||
简体中文 · [English](#english)
|
简体中文 · [English](#english) · [Discord](https://discord.gg/P566xWNpEs)
|
||||||
|
|
||||||
------
|
------
|
||||||
|
|
||||||
@@ -21,6 +21,10 @@ WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线
|
|||||||
|
|
||||||
`patches/versions/` 中每份核对记录对应一个检查通过并在游戏中验证过的客户端版本。补丁和 native 模块按特征码、字符串引用和从代码中读出的值定位,不依赖固定地址,小版本更新后通常仍能命中,但没有核对记录的版本不保证功能正确。
|
`patches/versions/` 中每份核对记录对应一个检查通过并在游戏中验证过的客户端版本。补丁和 native 模块按特征码、字符串引用和从代码中读出的值定位,不依赖固定地址,小版本更新后通常仍能命中,但没有核对记录的版本不保证功能正确。
|
||||||
|
|
||||||
|
## 开发讨论、交流与求助
|
||||||
|
|
||||||
|
欢迎加入 [WTOffline Discord 服务器](https://discord.gg/P566xWNpEs),用于日常交流、使用求助、问题反馈、调参分享以及开发和版本适配讨论。
|
||||||
|
|
||||||
## 功能
|
## 功能
|
||||||
|
|
||||||
| 领域 | 已实现 |
|
| 领域 | 已实现 |
|
||||||
@@ -73,7 +77,7 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
|
|||||||
|
|
||||||
- **服务地址**:`config/network.blk`(`char.vromfs.bin`)和 `config/settings.blk`(`aces.vromfs.bin`)中所有 Gaijin 地址改写为 `127.0.0.1:<端口>`。端口在构建时写入,因此服务器必须使用相同的端口。
|
- **服务地址**:`config/network.blk`(`char.vromfs.bin`)和 `config/settings.blk`(`aces.vromfs.bin`)中所有 Gaijin 地址改写为 `127.0.0.1:<端口>`。端口在构建时写入,因此服务器必须使用相同的端口。
|
||||||
- **配置表**:开启离线需要的功能开关,放出隐藏载具,写入贴花索引,为本地商店的礼包登记 GUID。
|
- **配置表**:开启离线需要的功能开关,放出隐藏载具,写入贴花索引,为本地商店的礼包登记 GUID。
|
||||||
- **exe 补丁**:`patches/exe/` 下共 12 项,见下表。
|
- **exe 补丁**:`patches/exe/` 下共 13 项,见下表。
|
||||||
- **界面脚本补丁**:`patches/gui/` 下共 40 项,用于本地账号注册、本地对局的开局与结算、本地商店的购买回执,以及库存签名公钥等。
|
- **界面脚本补丁**:`patches/gui/` 下共 40 项,用于本地账号注册、本地对局的开局与结算、本地商店的购买回执,以及库存签名公钥等。
|
||||||
- **网络钩子库**:exe 的导入表把 `WS2_32.dll` 改为同长度的 `wto_ws.dll`。该库转发系统 `ws2_32.dll` 的全部导出,并用 MinHook 挂钩域名解析(`getaddrinfo` 等)、连接(`connect`、`ConnectEx` 等)和 UDP 发送,把所有外部连接重定向到本地服务器端口。端口从 exe 旁的 `wto_ws.cfg` 读取。
|
- **网络钩子库**:exe 的导入表把 `WS2_32.dll` 改为同长度的 `wto_ws.dll`。该库转发系统 `ws2_32.dll` 的全部导出,并用 MinHook 挂钩域名解析(`getaddrinfo` 等)、连接(`connect`、`ConnectEx` 等)和 UDP 发送,把所有外部连接重定向到本地服务器端口。端口从 exe 旁的 `wto_ws.cfg` 读取。
|
||||||
|
|
||||||
@@ -84,6 +88,7 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
|
|||||||
| `isolation/registry-key` | 注册表位置改为 `Software\WTOffline` |
|
| `isolation/registry-key` | 注册表位置改为 `Software\WTOffline` |
|
||||||
| `isolation/never-load-battleye` | 不加载 BattlEye |
|
| `isolation/never-load-battleye` | 不加载 BattlEye |
|
||||||
| `isolation/never-upload-crash-reports` | 不上传崩溃报告 |
|
| `isolation/never-upload-crash-reports` | 不上传崩溃报告 |
|
||||||
|
| `isolation/never-launch-official-launcher` | 不拉起官方启动器 `launcher.exe` |
|
||||||
| `online/network-hook-library` | 加载 `wto_ws.dll` 代替 `WS2_32.dll` |
|
| `online/network-hook-library` | 加载 `wto_ws.dll` 代替 `WS2_32.dll` |
|
||||||
| `online/accept-local-tls-certificate` | 让 libcurl 接受本地服务器的自签名证书 |
|
| `online/accept-local-tls-certificate` | 让 libcurl 接受本地服务器的自签名证书 |
|
||||||
| `online/matching-server-public-key` | 匹配服务器公钥替换为本地服务器的公钥,用于解出会话密钥 |
|
| `online/matching-server-public-key` | 匹配服务器公钥替换为本地服务器的公钥,用于解出会话密钥 |
|
||||||
@@ -150,7 +155,7 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
|
|||||||
|
|
||||||
## 开发
|
## 开发
|
||||||
|
|
||||||
开发规范、补丁指南和 PR 自查清单见 [Dev Docs](dev-docs/README.md#zh-cn)。
|
开发规范、补丁指南和 PR 自查清单见 [Dev Docs](dev-docs/README.md#zh-cn),开发与版本适配讨论欢迎前往 [Discord](https://discord.gg/P566xWNpEs)。
|
||||||
|
|
||||||
### 环境要求
|
### 环境要求
|
||||||
|
|
||||||
@@ -264,7 +269,7 @@ tools/ wtotools,补丁检查工具(Python)
|
|||||||
|
|
||||||
# WTOffline (English)
|
# WTOffline (English)
|
||||||
|
|
||||||
[简体中文](#zh-cn) · English
|
[简体中文](#zh-cn) · English · [Discord](https://discord.gg/P566xWNpEs)
|
||||||
|
|
||||||
WTOffline is a single-player offline project for the Windows client of War Thunder. A local server emulates Gaijin's online services, and the client sends all of its requests to the local machine. The client logs in, loads its profile, enters the hangar, and submits player actions as usual. Game rules, saves, and battle settlement run on the local server, and all allies and opponents are AI.
|
WTOffline is a single-player offline project for the Windows client of War Thunder. A local server emulates Gaijin's online services, and the client sends all of its requests to the local machine. The client logs in, loads its profile, enters the hangar, and submits player actions as usual. Game rules, saves, and battle settlement run on the local server, and all allies and opponents are AI.
|
||||||
|
|
||||||
@@ -281,6 +286,10 @@ The repository contains source code and patch definitions only. It does not cont
|
|||||||
|
|
||||||
Each check record in `patches/versions/` stands for a client version that passed the checks and was verified in game. Patches and native modules are located by signatures, string references and values read from the code rather than fixed addresses, so they usually still match after a minor update, but correct behavior is not guaranteed for a version without a check record.
|
Each check record in `patches/versions/` stands for a client version that passed the checks and was verified in game. Patches and native modules are located by signatures, string references and values read from the code rather than fixed addresses, so they usually still match after a minor update, but correct behavior is not guaranteed for a version without a check record.
|
||||||
|
|
||||||
|
## Community
|
||||||
|
|
||||||
|
Join the [WTOffline Discord server](https://discord.gg/P566xWNpEs) for general discussion, troubleshooting, bug reports, and development or patch adaptation discussions.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
| Area | Implemented |
|
| Area | Implemented |
|
||||||
@@ -333,7 +342,7 @@ Static data such as vehicles, tech trees, prices, and reward factors is extracte
|
|||||||
|
|
||||||
- **Service addresses**: every Gaijin address in `config/network.blk` (`char.vromfs.bin`) and `config/settings.blk` (`aces.vromfs.bin`) is rewritten to `127.0.0.1:<port>`. The port is written at build time, so the server must use the same port.
|
- **Service addresses**: every Gaijin address in `config/network.blk` (`char.vromfs.bin`) and `config/settings.blk` (`aces.vromfs.bin`) is rewritten to `127.0.0.1:<port>`. The port is written at build time, so the server must use the same port.
|
||||||
- **Config tables**: enables feature flags the offline copy needs, reveals hidden vehicles, adds a decal index, and registers GUIDs for local store packs.
|
- **Config tables**: enables feature flags the offline copy needs, reveals hidden vehicles, adds a decal index, and registers GUIDs for local store packs.
|
||||||
- **exe patches**: 12 patches under `patches/exe/`, listed below.
|
- **exe patches**: 13 patches under `patches/exe/`, listed below.
|
||||||
- **UI script patches**: 40 patches under `patches/gui/`, covering local account registration, battle start and settlement, store purchase receipts, and the inventory signing key.
|
- **UI script patches**: 40 patches under `patches/gui/`, covering local account registration, battle start and settlement, store purchase receipts, and the inventory signing key.
|
||||||
- **Network hook library**: the import table entry `WS2_32.dll` is renamed to `wto_ws.dll`, which has the same length. The library forwards every export of the system `ws2_32.dll` and uses MinHook to hook name resolution (`getaddrinfo` and others), connections (`connect`, `ConnectEx`, and others), and UDP sends, redirecting every external connection to the local server port. The port is read from `wto_ws.cfg` next to the exe.
|
- **Network hook library**: the import table entry `WS2_32.dll` is renamed to `wto_ws.dll`, which has the same length. The library forwards every export of the system `ws2_32.dll` and uses MinHook to hook name resolution (`getaddrinfo` and others), connections (`connect`, `ConnectEx`, and others), and UDP sends, redirecting every external connection to the local server port. The port is read from `wto_ws.cfg` next to the exe.
|
||||||
|
|
||||||
@@ -344,6 +353,7 @@ Static data such as vehicles, tech trees, prices, and reward factors is extracte
|
|||||||
| `isolation/registry-key` | Moves registry settings to `Software\WTOffline` |
|
| `isolation/registry-key` | Moves registry settings to `Software\WTOffline` |
|
||||||
| `isolation/never-load-battleye` | Never loads BattlEye |
|
| `isolation/never-load-battleye` | Never loads BattlEye |
|
||||||
| `isolation/never-upload-crash-reports` | Never uploads crash reports |
|
| `isolation/never-upload-crash-reports` | Never uploads crash reports |
|
||||||
|
| `isolation/never-launch-official-launcher` | Never launches the official `launcher.exe` |
|
||||||
| `online/network-hook-library` | Loads `wto_ws.dll` instead of `WS2_32.dll` |
|
| `online/network-hook-library` | Loads `wto_ws.dll` instead of `WS2_32.dll` |
|
||||||
| `online/accept-local-tls-certificate` | Makes libcurl accept the local server's self-signed certificate |
|
| `online/accept-local-tls-certificate` | Makes libcurl accept the local server's self-signed certificate |
|
||||||
| `online/matching-server-public-key` | Replaces the matching server public key with the local server's, so it can decrypt the session key |
|
| `online/matching-server-public-key` | Replaces the matching server public key with the local server's, so it can decrypt the session key |
|
||||||
@@ -410,7 +420,7 @@ To override defaults, create `tuning/<same file name>.jsonc` in the data folder
|
|||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
See [Dev Docs](dev-docs/README.md#english) for development rules, patch templates, and the PR checklist.
|
See [Dev Docs](dev-docs/README.md#english) for development rules, patch templates, and the PR checklist, or join [Discord](https://discord.gg/P566xWNpEs) for development and patch adaptation discussions.
|
||||||
|
|
||||||
### Requirements
|
### Requirements
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@wto/launcher",
|
"name": "@wto/launcher",
|
||||||
"productName": "WTOffline Launcher",
|
"productName": "WTOffline Launcher",
|
||||||
"version": "0.1.0",
|
"version": "0.1.3",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Installer and launcher of the War Thunder offline project.",
|
"description": "Installer and launcher of the War Thunder offline project.",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
@@ -14,6 +14,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fontsource/roboto-condensed": "^5.3.0",
|
"@fontsource/roboto-condensed": "^5.3.0",
|
||||||
|
"@wto/mods": "*",
|
||||||
"@wto/patcher": "*",
|
"@wto/patcher": "*",
|
||||||
"@wto/server": "*",
|
"@wto/server": "*",
|
||||||
"fflate": "^0.8.2",
|
"fflate": "^0.8.2",
|
||||||
|
|||||||
@@ -5,18 +5,31 @@ import { appUpdatesSupported, checkAppUpdate, downloadAppUpdate, installAppUpdat
|
|||||||
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
|
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
|
||||||
import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.ts';
|
import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.ts';
|
||||||
import { getSettings, updateSettings } from '../services/config/settings-store.ts';
|
import { getSettings, updateSettings } from '../services/config/settings-store.ts';
|
||||||
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress } from '../services/copies/copy-maintenance.ts';
|
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress, maintenanceState } from '../services/copies/copy-maintenance.ts';
|
||||||
import { relocateCopy } from '../services/copies/relocate-copy.ts';
|
import { relocateCopy } from '../services/copies/relocate-copy.ts';
|
||||||
import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts';
|
import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts';
|
||||||
import { measureFolder } from '../services/game-folder/folder-size.ts';
|
import { measureFolder } from '../services/game-folder/folder-size.ts';
|
||||||
import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts';
|
import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts';
|
||||||
import { inspectPickedTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
|
import { inspectPickedTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
|
||||||
import { changeDecalSource, decalImportInProgress } from '../services/install/decals.ts';
|
import { changeDecalSource, decalImportInProgress } from '../services/install/decals.ts';
|
||||||
import { cancelInstall, checkGameFolder, installGame, installationInProgress } from '../services/install/install-game.ts';
|
import { cancelInstall, checkGameFolder, dataFolderProblem, installGame, installationInProgress } from '../services/install/install-game.ts';
|
||||||
import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesStatus, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts';
|
import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesStatus, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts';
|
||||||
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
|
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
|
||||||
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
|
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
|
||||||
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
|
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
|
||||||
|
import {
|
||||||
|
applyModPreset,
|
||||||
|
autoSortMods,
|
||||||
|
deleteModPreset,
|
||||||
|
exportModPreset,
|
||||||
|
getModsState,
|
||||||
|
importModPreset,
|
||||||
|
openModsFolder,
|
||||||
|
saveModPreset,
|
||||||
|
setModEnabled,
|
||||||
|
setModsFolder,
|
||||||
|
setModsOrder,
|
||||||
|
} from '../services/mods/mods-service.ts';
|
||||||
import { resourcePaths } from '../services/resources/resource-paths.ts';
|
import { resourcePaths } from '../services/resources/resource-paths.ts';
|
||||||
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
|
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
|
||||||
import { broadcast, handle } from './register.ts';
|
import { broadcast, handle } from './register.ts';
|
||||||
@@ -66,14 +79,23 @@ export function registerIpcHandlers(): void {
|
|||||||
handle('install:inspectGameFolder', ({ path }) => inspectGameFolder(path));
|
handle('install:inspectGameFolder', ({ path }) => inspectGameFolder(path));
|
||||||
handle('install:inspectTargetFolder', ({ path, stockPath, version }) =>
|
handle('install:inspectTargetFolder', ({ path, stockPath, version }) =>
|
||||||
inspectPickedTargetFolder(path, stockPath, version ?? null));
|
inspectPickedTargetFolder(path, stockPath, version ?? null));
|
||||||
handle('install:inspectDataFolder', async ({ path }) => {
|
handle('install:inspectDataFolder', async ({ path, copyPath, sourcePath, stockSourcePath }) => {
|
||||||
const resolved = await canonicalCopyPath(path);
|
const [resolved, resolvedCopy, resolvedSource, resolvedStock] = await Promise.all([
|
||||||
return { path: resolved, inSteam: isInSteamLibrary(path) || isInSteamLibrary(resolved) };
|
canonicalCopyPath(path),
|
||||||
|
copyPath ? canonicalCopyPath(copyPath) : Promise.resolve(null),
|
||||||
|
sourcePath ? canonicalCopyPath(sourcePath) : Promise.resolve(null),
|
||||||
|
stockSourcePath ? canonicalCopyPath(stockSourcePath) : Promise.resolve(null),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
path: resolved,
|
||||||
|
inSteam: isInSteamLibrary(path) || isInSteamLibrary(resolved),
|
||||||
|
problem: dataFolderProblem(resolved, resolvedCopy, resolvedSource, resolvedStock),
|
||||||
|
};
|
||||||
});
|
});
|
||||||
handle('install:measureFolder', async ({ path, version }) => {
|
handle('install:measureFolder', async ({ path }) => {
|
||||||
await requireFolder(path);
|
await requireFolder(path);
|
||||||
try {
|
try {
|
||||||
return await measureFolder(path, version);
|
return await measureFolder(path);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('[install] measuring the folder failed:', error);
|
console.warn('[install] measuring the folder failed:', error);
|
||||||
throw new AppError('folder_unreadable', { path });
|
throw new AppError('folder_unreadable', { path });
|
||||||
@@ -126,6 +148,7 @@ export function registerIpcHandlers(): void {
|
|||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id));
|
handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id));
|
||||||
|
handle('copies:maintenanceState', () => maintenanceState());
|
||||||
handle('copies:maintain', async (request) => {
|
handle('copies:maintain', async (request) => {
|
||||||
if (saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy');
|
if (saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy');
|
||||||
const updated = await hydrateCopiesStatus(await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress)));
|
const updated = await hydrateCopiesStatus(await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress)));
|
||||||
@@ -165,6 +188,48 @@ export function registerIpcHandlers(): void {
|
|||||||
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
|
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
|
||||||
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
|
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
|
||||||
|
|
||||||
|
const requireModsWritable = (): void => {
|
||||||
|
if (launchInProgress() || maintenanceInProgress()) throw new AppError('mods_read_only');
|
||||||
|
};
|
||||||
|
handle('mods:getState', ({ copyId }) => getModsState(copyId));
|
||||||
|
handle('mods:setEnabled', ({ copyId, modId, enabled }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return setModEnabled(copyId, modId, enabled);
|
||||||
|
});
|
||||||
|
handle('mods:setOrder', ({ copyId, order }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return setModsOrder(copyId, order);
|
||||||
|
});
|
||||||
|
handle('mods:autoSort', ({ copyId }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return autoSortMods(copyId);
|
||||||
|
});
|
||||||
|
handle('mods:savePreset', ({ copyId, name, overwriteId }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return saveModPreset(copyId, name, overwriteId);
|
||||||
|
});
|
||||||
|
handle('mods:applyPreset', ({ copyId, presetId }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return applyModPreset(copyId, presetId);
|
||||||
|
});
|
||||||
|
handle('mods:deletePreset', ({ copyId, presetId }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return deleteModPreset(copyId, presetId);
|
||||||
|
});
|
||||||
|
handle('mods:exportPreset', ({ copyId, presetId }, sender) =>
|
||||||
|
exportModPreset(copyId, presetId, BrowserWindow.fromWebContents(sender)));
|
||||||
|
handle('mods:importPreset', ({ copyId }, sender) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return importModPreset(copyId, BrowserWindow.fromWebContents(sender));
|
||||||
|
});
|
||||||
|
handle('mods:openFolder', () => openModsFolder());
|
||||||
|
handle('mods:setFolder', async ({ copyId, path }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
const state = await setModsFolder(copyId, path);
|
||||||
|
broadcast('event:settings-changed', await getSettings());
|
||||||
|
return state;
|
||||||
|
});
|
||||||
|
|
||||||
handle('launch:getState', () => getLaunchState());
|
handle('launch:getState', () => getLaunchState());
|
||||||
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
|
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
|
||||||
handle('launch:start', () => {
|
handle('launch:start', () => {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { compareAppVersions, packSigningPublicKey, PatchPackError, patchPackTuni
|
|||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import {
|
import {
|
||||||
LauncherReleaseManifest,
|
LauncherReleaseManifest,
|
||||||
|
PortableReleaseManifest,
|
||||||
type AppUpdateCheck, type AppUpdateProgress,
|
type AppUpdateCheck, type AppUpdateProgress,
|
||||||
} from '@shared/schemas/app-update.ts';
|
} from '@shared/schemas/app-update.ts';
|
||||||
import { gameProcessRunning } from '../launch/game-process.ts';
|
import { gameProcessRunning } from '../launch/game-process.ts';
|
||||||
@@ -20,11 +21,15 @@ import {
|
|||||||
import {
|
import {
|
||||||
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
|
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
|
||||||
} from '../patch-pack/release-assets.ts';
|
} from '../patch-pack/release-assets.ts';
|
||||||
import { installerDigest, launcherSignaturePayload } from './installer-integrity.ts';
|
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
|
||||||
|
import { isPortableLauncher, launchPortableUpdater, preparePortableInstall } from './portable-update.ts';
|
||||||
|
|
||||||
|
type UpdateMode = 'installer' | 'portable';
|
||||||
|
|
||||||
interface OfferedUpdate {
|
interface OfferedUpdate {
|
||||||
|
readonly mode: UpdateMode;
|
||||||
readonly release: LauncherRelease;
|
readonly release: LauncherRelease;
|
||||||
readonly manifest: LauncherReleaseManifest;
|
readonly manifest: LauncherReleaseManifest | PortableReleaseManifest;
|
||||||
}
|
}
|
||||||
|
|
||||||
class ManifestSignatureError extends Error {}
|
class ManifestSignatureError extends Error {}
|
||||||
@@ -46,11 +51,15 @@ async function exclusively<T>(action: () => Promise<T>): Promise<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function stagedInstaller(): string {
|
function updatesRoot(): string {
|
||||||
return join(app.getPath('userData'), 'launcher-updates', 'installer.exe');
|
return join(app.getPath('userData'), 'launcher-updates');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function matchesInstaller(path: string, manifest: LauncherReleaseManifest): Promise<boolean> {
|
function stagedArtifact(mode: UpdateMode): string {
|
||||||
|
return join(updatesRoot(), mode === 'portable' ? 'portable.zip' : 'installer.exe');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function matchesArtifact(path: string, manifest: LauncherReleaseManifest | PortableReleaseManifest): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
const digest = await installerDigest(path, manifest.size);
|
const digest = await installerDigest(path, manifest.size);
|
||||||
return digest.size === manifest.size && digest.sha256 === manifest.sha256;
|
return digest.size === manifest.size && digest.sha256 === manifest.sha256;
|
||||||
@@ -76,6 +85,18 @@ function selectedOffer(version: string): OfferedUpdate {
|
|||||||
|
|
||||||
async function signedOffer(release: LauncherRelease, key: string): Promise<OfferedUpdate> {
|
async function signedOffer(release: LauncherRelease, key: string): Promise<OfferedUpdate> {
|
||||||
const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
|
const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
|
||||||
|
if (isPortableLauncher(app.isPackaged) && release.portable) {
|
||||||
|
const [bytes, signature] = await Promise.all([
|
||||||
|
readReleaseAsset(release.portable.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
|
||||||
|
readReleaseAsset(release.portable.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
|
||||||
|
]);
|
||||||
|
if (!verifyEd25519(portableSignaturePayload(bytes), new TextDecoder().decode(signature), key)) {
|
||||||
|
throw new ManifestSignatureError('The portable release manifest signature does not match.');
|
||||||
|
}
|
||||||
|
const manifest = PortableReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
||||||
|
if (manifest.version !== release.version) throw new Error('The signed portable manifest version does not match the release tag.');
|
||||||
|
return { mode: 'portable', release, manifest };
|
||||||
|
}
|
||||||
const [bytes, signature] = await Promise.all([
|
const [bytes, signature] = await Promise.all([
|
||||||
readReleaseAsset(release.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
|
readReleaseAsset(release.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
|
||||||
readReleaseAsset(release.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
|
readReleaseAsset(release.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
|
||||||
@@ -85,7 +106,7 @@ async function signedOffer(release: LauncherRelease, key: string): Promise<Offer
|
|||||||
}
|
}
|
||||||
const manifest = LauncherReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
const manifest = LauncherReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
||||||
if (manifest.version !== release.version) throw new Error('The signed manifest version does not match the release tag.');
|
if (manifest.version !== release.version) throw new Error('The signed manifest version does not match the release tag.');
|
||||||
return { release, manifest };
|
return { mode: 'installer', release, manifest };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function checkAppUpdate(): Promise<AppUpdateCheck> {
|
export function checkAppUpdate(): Promise<AppUpdateCheck> {
|
||||||
@@ -102,7 +123,7 @@ export function checkAppUpdate(): Promise<AppUpdateCheck> {
|
|||||||
});
|
});
|
||||||
if (!offer) return { status: 'current' };
|
if (!offer) return { status: 'current' };
|
||||||
offered = offer;
|
offered = offer;
|
||||||
return offerResult(offer, await matchesInstaller(stagedInstaller(), offer.manifest));
|
return offerResult(offer, await matchesArtifact(stagedArtifact(offer.mode), offer.manifest));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('[app-update] checking the release failed:', error);
|
console.warn('[app-update] checking the release failed:', error);
|
||||||
if (error instanceof ReleasePageLimitError) return { status: 'failed', problem: 'page_limit' };
|
if (error instanceof ReleasePageLimitError) return { status: 'failed', problem: 'page_limit' };
|
||||||
@@ -121,24 +142,26 @@ export function downloadAppUpdate(
|
|||||||
): Promise<AppUpdateCheck> {
|
): Promise<AppUpdateCheck> {
|
||||||
return exclusively(async () => {
|
return exclusively(async () => {
|
||||||
const offer = selectedOffer(version);
|
const offer = selectedOffer(version);
|
||||||
const target = stagedInstaller();
|
const target = stagedArtifact(offer.mode);
|
||||||
if (await matchesInstaller(target, offer.manifest)) return offerResult(offer, true);
|
if (await matchesArtifact(target, offer.manifest)) return offerResult(offer, true);
|
||||||
try {
|
try {
|
||||||
await withReleaseSources(async (source) => {
|
await withReleaseSources(async (source) => {
|
||||||
const release = sameReleaseSource(source, offer.release.source)
|
const release = sameReleaseSource(source, offer.release.source)
|
||||||
? offer.release : await projectReleaseVersion('launcher', version, source);
|
? offer.release : await projectReleaseVersion('launcher', version, source);
|
||||||
await stageInstaller(release, offer.manifest, target, report);
|
const assetUrl = offer.mode === 'portable' ? release.portable?.archive : release.installer;
|
||||||
|
if (!assetUrl) throw new FeedUnreachableError(`This update source does not have the ${offer.mode} asset for ${version}.`);
|
||||||
|
await stageArtifact(assetUrl, release.source, offer.manifest, target, report);
|
||||||
}, offer.release.source);
|
}, offer.release.source);
|
||||||
return offerResult(offer, true);
|
return offerResult(offer, true);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('[app-update] preparing the installer failed:', error);
|
console.warn('[app-update] preparing the update asset failed:', error);
|
||||||
throw new AppError('app_update_download_failed');
|
throw new AppError('app_update_download_failed');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function stageInstaller(
|
async function stageArtifact(
|
||||||
release: LauncherRelease, manifest: LauncherReleaseManifest, target: string,
|
assetUrl: URL, source: LauncherRelease['source'], manifest: LauncherReleaseManifest | PortableReleaseManifest, target: string,
|
||||||
report: (progress: AppUpdateProgress) => void,
|
report: (progress: AppUpdateProgress) => void,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const partial = `${target}.partial`;
|
const partial = `${target}.partial`;
|
||||||
@@ -151,12 +174,12 @@ async function stageInstaller(
|
|||||||
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
||||||
if (error.code !== 'ENOENT') throw error;
|
if (error.code !== 'ENOENT') throw error;
|
||||||
});
|
});
|
||||||
const response = await requestReleaseAsset(release.installer, deadline, release.source);
|
const response = await requestReleaseAsset(assetUrl, deadline, source);
|
||||||
const monitor = new Transform({
|
const monitor = new Transform({
|
||||||
transform(chunk: Buffer, _encoding, done) {
|
transform(chunk: Buffer, _encoding, done) {
|
||||||
size += chunk.length;
|
size += chunk.length;
|
||||||
if (size > manifest.size) {
|
if (size > manifest.size) {
|
||||||
done(new Error('The download is larger than the signed installer size.'));
|
done(new Error('The download is larger than the signed release size.'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
hash.update(chunk);
|
hash.update(chunk);
|
||||||
@@ -168,11 +191,11 @@ async function stageInstaller(
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline });
|
await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline });
|
||||||
if (size !== manifest.size) throw new FeedUnreachableError('The installer download is incomplete.');
|
if (size !== manifest.size) throw new FeedUnreachableError('The update download is incomplete.');
|
||||||
if (hash.digest('hex') !== manifest.sha256) throw new Error('The installer download does not match the signed release.');
|
if (hash.digest('hex') !== manifest.sha256) throw new Error('The update download does not match the signed release.');
|
||||||
await rename(partial, target);
|
await rename(partial, target);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (deadline.aborted) throw new FeedUnreachableError('The installer download timed out.', { cause: error });
|
if (deadline.aborted) throw new FeedUnreachableError('The update download timed out.', { cause: error });
|
||||||
throw error;
|
throw error;
|
||||||
} finally {
|
} finally {
|
||||||
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
||||||
@@ -185,17 +208,23 @@ export function installAppUpdate(version: string, launcherBusy: () => boolean):
|
|||||||
return exclusively(async () => {
|
return exclusively(async () => {
|
||||||
const offer = selectedOffer(version);
|
const offer = selectedOffer(version);
|
||||||
if (launcherBusy()) throw new AppError('app_update_launcher_busy');
|
if (launcherBusy()) throw new AppError('app_update_launcher_busy');
|
||||||
const path = stagedInstaller();
|
const path = stagedArtifact(offer.mode);
|
||||||
if (!await matchesInstaller(path, offer.manifest)) throw new AppError('app_update_installer_invalid');
|
if (!await matchesArtifact(path, offer.manifest)) throw new AppError('app_update_installer_invalid');
|
||||||
const signal = AbortSignal.timeout(5000);
|
const signal = AbortSignal.timeout(5000);
|
||||||
if (await gameProcessRunning(signal) || launcherBusy()) throw new AppError('app_update_launcher_busy');
|
if (await gameProcessRunning(signal) || launcherBusy()) throw new AppError('app_update_launcher_busy');
|
||||||
try {
|
try {
|
||||||
|
if (offer.mode === 'portable') {
|
||||||
|
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
|
||||||
|
launchPortableUpdater(prepared);
|
||||||
|
app.quit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
const installer = spawn(path, [], { cwd: dirname(path), detached: true, stdio: 'ignore', shell: false });
|
const installer = spawn(path, [], { cwd: dirname(path), detached: true, stdio: 'ignore', shell: false });
|
||||||
await once(installer, 'spawn');
|
await once(installer, 'spawn');
|
||||||
installer.unref();
|
installer.unref();
|
||||||
app.quit();
|
app.quit();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('[app-update] starting the installer failed:', error);
|
console.warn('[app-update] starting the update failed:', error);
|
||||||
throw new AppError('app_update_install_failed');
|
throw new AppError('app_update_install_failed');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,11 +3,16 @@ import { createReadStream } from 'node:fs';
|
|||||||
import { MAX_INSTALLER_BYTES } from '../../../shared/schemas/app-update.ts';
|
import { MAX_INSTALLER_BYTES } from '../../../shared/schemas/app-update.ts';
|
||||||
|
|
||||||
const SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher release v1\n', 'utf8');
|
const SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher release v1\n', 'utf8');
|
||||||
|
const PORTABLE_SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher portable release v1\n', 'utf8');
|
||||||
|
|
||||||
export function launcherSignaturePayload(manifest: Uint8Array): Uint8Array {
|
export function launcherSignaturePayload(manifest: Uint8Array): Uint8Array {
|
||||||
return Buffer.concat([SIGNATURE_DOMAIN, manifest]);
|
return Buffer.concat([SIGNATURE_DOMAIN, manifest]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function portableSignaturePayload(manifest: Uint8Array): Uint8Array {
|
||||||
|
return Buffer.concat([PORTABLE_SIGNATURE_DOMAIN, manifest]);
|
||||||
|
}
|
||||||
|
|
||||||
export async function installerDigest(path: string, limit = MAX_INSTALLER_BYTES): Promise<{ size: number; sha256: string }> {
|
export async function installerDigest(path: string, limit = MAX_INSTALLER_BYTES): Promise<{ size: number; sha256: string }> {
|
||||||
const hash = createHash('sha256');
|
const hash = createHash('sha256');
|
||||||
let size = 0;
|
let size = 0;
|
||||||
|
|||||||
@@ -0,0 +1,283 @@
|
|||||||
|
/**
|
||||||
|
* In-place updater for portable (unpacked ZIP) launcher builds on Windows.
|
||||||
|
*
|
||||||
|
* Extraction and path validation happen while the launcher is still running so a bad archive or
|
||||||
|
* read-only folder fails cleanly before quitting. Once staged, a detached PowerShell helper waits
|
||||||
|
* for this process to exit, overwrites only files listed in the new portable inventory, removes
|
||||||
|
* only obsolete files listed in the previous portable inventory (never touching unrelated user
|
||||||
|
* files in the same folder), and restarts the updated executable.
|
||||||
|
*/
|
||||||
|
import { execFile, spawn } from 'node:child_process';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { existsSync } from 'node:fs';
|
||||||
|
import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||||
|
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
||||||
|
import { promisify } from 'node:util';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
const execute = promisify(execFile);
|
||||||
|
|
||||||
|
export const PORTABLE_MARKER_FILE = 'portable-mode';
|
||||||
|
export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
|
||||||
|
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
|
||||||
|
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
|
||||||
|
|
||||||
|
const PortableInventorySchema = z.object({
|
||||||
|
format: z.literal(1),
|
||||||
|
version: z.string().min(1),
|
||||||
|
files: z.array(z.string().min(1)).min(1),
|
||||||
|
});
|
||||||
|
|
||||||
|
export interface PreparedPortableUpdate {
|
||||||
|
readonly scriptPath: string;
|
||||||
|
readonly planPath: string;
|
||||||
|
readonly stagingDir: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PortableUpdatePlan {
|
||||||
|
readonly pid: number;
|
||||||
|
readonly installDir: string;
|
||||||
|
readonly stagingDir: string;
|
||||||
|
readonly archivePath: string;
|
||||||
|
readonly logPath: string;
|
||||||
|
readonly executable: string;
|
||||||
|
readonly newFiles: readonly string[];
|
||||||
|
readonly staleFiles: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isPortableLauncher(isPackaged: boolean): boolean {
|
||||||
|
if (!isPackaged || process.platform !== 'win32') return false;
|
||||||
|
if (existsSync(join(process.resourcesPath, PORTABLE_MARKER_FILE))) return true;
|
||||||
|
return !existsSync(join(dirname(process.execPath), UNINSTALLER_EXECUTABLE));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Validate a POSIX-style relative path from a portable inventory against traversal or drive prefixes. */
|
||||||
|
export function isSafePortableRelativePath(entry: string): boolean {
|
||||||
|
if (!entry || entry.includes('\\') || entry.includes(':') || entry.startsWith('/')) return false;
|
||||||
|
if (/[\0-\x1f]/.test(entry)) return false;
|
||||||
|
const parts = entry.split('/');
|
||||||
|
return parts.every((part) => part.length > 0 && part !== '.' && part !== '..');
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveInside(root: string, relPosix: string): string {
|
||||||
|
if (!isSafePortableRelativePath(relPosix)) throw new Error(`Unsafe portable path: ${relPosix}`);
|
||||||
|
const target = resolve(root, ...relPosix.split('/'));
|
||||||
|
const rel = relative(root, target);
|
||||||
|
if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
|
||||||
|
throw new Error(`Portable path escapes root: ${relPosix}`);
|
||||||
|
}
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readPortableInventory(resourcesDir: string): Promise<readonly string[] | null> {
|
||||||
|
try {
|
||||||
|
const raw = await readFile(join(resourcesDir, PORTABLE_FILES_MANIFEST), 'utf8');
|
||||||
|
const parsed = PortableInventorySchema.parse(JSON.parse(raw));
|
||||||
|
return parsed.files.filter(isSafePortableRelativePath);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertWritableFolder(folder: string): Promise<void> {
|
||||||
|
const probe = join(folder, `.wto-update-probe-${randomUUID()}.tmp`);
|
||||||
|
await writeFile(probe, '', { flag: 'wx' });
|
||||||
|
await rm(probe, { force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function extractPortableArchive(zipPath: string, stagingDir: string, updatesRoot: string): Promise<void> {
|
||||||
|
const extractScriptPath = join(updatesRoot, `extract-portable-${randomUUID()}.ps1`);
|
||||||
|
const script = [
|
||||||
|
'param([string]$ZipPath, [string]$DestDir)',
|
||||||
|
"$ErrorActionPreference = 'Stop'",
|
||||||
|
'Add-Type -AssemblyName System.IO.Compression.FileSystem',
|
||||||
|
'$destFull = [System.IO.Path]::GetFullPath($DestDir)',
|
||||||
|
'if (-not $destFull.EndsWith([System.IO.Path]::DirectorySeparatorChar)) { $destFull += [System.IO.Path]::DirectorySeparatorChar }',
|
||||||
|
'$zip = [System.IO.Compression.ZipFile]::OpenRead($ZipPath)',
|
||||||
|
'try {',
|
||||||
|
' foreach ($entry in $zip.Entries) {',
|
||||||
|
' $name = $entry.FullName',
|
||||||
|
' if ([string]::IsNullOrEmpty($name) -or $name.EndsWith("/") -or $name.EndsWith("\\")) { continue }',
|
||||||
|
' if ($name.Contains("..") -or $name.StartsWith("/") -or $name.StartsWith("\\") -or $name.Contains(":")) {',
|
||||||
|
' throw "Unsafe zip entry: $name"',
|
||||||
|
' }',
|
||||||
|
' $target = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($destFull, $name))',
|
||||||
|
' if (-not $target.StartsWith($destFull, [System.StringComparison]::OrdinalIgnoreCase)) {',
|
||||||
|
' throw "Zip entry escapes destination: $name"',
|
||||||
|
' }',
|
||||||
|
' $parent = [System.IO.Path]::GetDirectoryName($target)',
|
||||||
|
' if ($parent) { [System.IO.Directory]::CreateDirectory($parent) | Out-Null }',
|
||||||
|
' [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $target, $true)',
|
||||||
|
' }',
|
||||||
|
'} finally {',
|
||||||
|
' $zip.Dispose()',
|
||||||
|
'}',
|
||||||
|
].join('\r\n');
|
||||||
|
// UTF-8 BOM ensures Windows PowerShell 5.1 decodes non-ASCII paths properly.
|
||||||
|
await writeFile(extractScriptPath, `\uFEFF${script}\r\n`, 'utf8');
|
||||||
|
try {
|
||||||
|
await execute('powershell.exe', [
|
||||||
|
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
|
||||||
|
'-File', extractScriptPath, zipPath, stagingDir,
|
||||||
|
], { windowsHide: true, timeout: 180_000 });
|
||||||
|
} finally {
|
||||||
|
await rm(extractScriptPath, { force: true }).catch(() => undefined);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPortableApplyScript(): string {
|
||||||
|
return [
|
||||||
|
'param([string]$PlanPath)',
|
||||||
|
"$ErrorActionPreference = 'Stop'",
|
||||||
|
'$utf8 = New-Object System.Text.UTF8Encoding($false)',
|
||||||
|
'$plan = [System.IO.File]::ReadAllText($PlanPath, $utf8) | ConvertFrom-Json',
|
||||||
|
'function Write-Log([string]$msg) {',
|
||||||
|
' try {',
|
||||||
|
' $line = "$(Get-Date -Format o) $msg`r`n"',
|
||||||
|
' [System.IO.File]::AppendAllText($plan.logPath, $line, $utf8)',
|
||||||
|
' } catch {}',
|
||||||
|
'}',
|
||||||
|
'try {',
|
||||||
|
' Write-Log "Starting portable update in $($plan.installDir) (waiting for pid $($plan.pid))"',
|
||||||
|
' $deadline = (Get-Date).AddSeconds(30)',
|
||||||
|
' while ((Get-Date) -lt $deadline) {',
|
||||||
|
' if (-not (Get-Process -Id $plan.pid -ErrorAction SilentlyContinue)) { break }',
|
||||||
|
' Start-Sleep -Milliseconds 200',
|
||||||
|
' }',
|
||||||
|
' Start-Sleep -Milliseconds 400',
|
||||||
|
' foreach ($rel in $plan.newFiles) {',
|
||||||
|
' $winRel = $rel -replace "/", "\\"',
|
||||||
|
' $src = [System.IO.Path]::Combine($plan.stagingDir, $winRel)',
|
||||||
|
' $dst = [System.IO.Path]::Combine($plan.installDir, $winRel)',
|
||||||
|
' $parent = [System.IO.Path]::GetDirectoryName($dst)',
|
||||||
|
' if ($parent) { [System.IO.Directory]::CreateDirectory($parent) | Out-Null }',
|
||||||
|
' $copied = $false',
|
||||||
|
' for ($attempt = 1; $attempt -le 20; $attempt++) {',
|
||||||
|
' try {',
|
||||||
|
' if ([System.IO.File]::Exists($dst)) { [System.IO.File]::SetAttributes($dst, [System.IO.FileAttributes]::Normal) }',
|
||||||
|
' [System.IO.File]::Copy($src, $dst, $true)',
|
||||||
|
' $copied = $true',
|
||||||
|
' break',
|
||||||
|
' } catch {',
|
||||||
|
' if ($attempt -eq 20) { throw }',
|
||||||
|
' Start-Sleep -Milliseconds 300',
|
||||||
|
' }',
|
||||||
|
' }',
|
||||||
|
' if (-not $copied) { throw "Failed to copy $rel" }',
|
||||||
|
' }',
|
||||||
|
' $installRoot = [System.IO.Path]::GetFullPath($plan.installDir).TrimEnd("\\")',
|
||||||
|
' foreach ($rel in $plan.staleFiles) {',
|
||||||
|
' $winRel = $rel -replace "/", "\\"',
|
||||||
|
' $old = [System.IO.Path]::Combine($plan.installDir, $winRel)',
|
||||||
|
' if ([System.IO.File]::Exists($old)) {',
|
||||||
|
' try {',
|
||||||
|
' [System.IO.File]::SetAttributes($old, [System.IO.FileAttributes]::Normal)',
|
||||||
|
' [System.IO.File]::Delete($old)',
|
||||||
|
' } catch { Write-Log "Could not remove stale file ${rel}: $_" }',
|
||||||
|
' }',
|
||||||
|
' $dir = [System.IO.Path]::GetDirectoryName($old)',
|
||||||
|
' while ($dir -and ($dir.TrimEnd("\\") -ne $installRoot)) {',
|
||||||
|
' if (-not [System.IO.Directory]::Exists($dir)) { break }',
|
||||||
|
' $entries = [System.IO.Directory]::GetFileSystemEntries($dir)',
|
||||||
|
' if ($entries.Length -gt 0) { break }',
|
||||||
|
' try { [System.IO.Directory]::Delete($dir) } catch { break }',
|
||||||
|
' $dir = [System.IO.Path]::GetDirectoryName($dir)',
|
||||||
|
' }',
|
||||||
|
' }',
|
||||||
|
' Write-Log "Replaced $($plan.newFiles.Count) files and cleaned $($plan.staleFiles.Count) obsolete files."',
|
||||||
|
' if ($plan.stagingDir -and [System.IO.Directory]::Exists($plan.stagingDir)) {',
|
||||||
|
' try { Remove-Item -LiteralPath $plan.stagingDir -Recurse -Force } catch {}',
|
||||||
|
' }',
|
||||||
|
' if ($plan.archivePath -and [System.IO.File]::Exists($plan.archivePath)) {',
|
||||||
|
' try { Remove-Item -LiteralPath $plan.archivePath -Force } catch {}',
|
||||||
|
' }',
|
||||||
|
' if ([System.IO.File]::Exists($PlanPath)) {',
|
||||||
|
' try { Remove-Item -LiteralPath $PlanPath -Force } catch {}',
|
||||||
|
' }',
|
||||||
|
' $exe = [System.IO.Path]::Combine($plan.installDir, $plan.executable)',
|
||||||
|
' if ([System.IO.File]::Exists($exe)) {',
|
||||||
|
' Start-Process -FilePath $exe -WorkingDirectory $plan.installDir',
|
||||||
|
' Write-Log "Relaunched $exe"',
|
||||||
|
' }',
|
||||||
|
'} catch {',
|
||||||
|
' Write-Log "Portable update failed: $_"',
|
||||||
|
' exit 1',
|
||||||
|
'}',
|
||||||
|
].join('\r\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function preparePortableInstall(
|
||||||
|
archivePath: string,
|
||||||
|
expectedVersion: string,
|
||||||
|
updatesRoot: string,
|
||||||
|
installDir = dirname(process.execPath),
|
||||||
|
resourcesDir = process.resourcesPath,
|
||||||
|
parentPid = process.pid,
|
||||||
|
): Promise<PreparedPortableUpdate> {
|
||||||
|
await assertWritableFolder(installDir);
|
||||||
|
await mkdir(updatesRoot, { recursive: true });
|
||||||
|
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
|
||||||
|
await mkdir(stagingDir, { recursive: true });
|
||||||
|
try {
|
||||||
|
await extractPortableArchive(archivePath, stagingDir, updatesRoot);
|
||||||
|
|
||||||
|
const stagedInventoryRaw = await readFile(join(stagingDir, 'resources', PORTABLE_FILES_MANIFEST), 'utf8');
|
||||||
|
const stagedInventory = PortableInventorySchema.parse(JSON.parse(stagedInventoryRaw));
|
||||||
|
if (stagedInventory.version !== expectedVersion) {
|
||||||
|
throw new Error(`Portable archive inventory version ${stagedInventory.version} does not match ${expectedVersion}.`);
|
||||||
|
}
|
||||||
|
const newFiles = stagedInventory.files;
|
||||||
|
const newSet = new Set(newFiles);
|
||||||
|
const requiredEntries = [
|
||||||
|
LAUNCHER_EXECUTABLE,
|
||||||
|
`resources/${PORTABLE_MARKER_FILE}`,
|
||||||
|
`resources/${PORTABLE_FILES_MANIFEST}`,
|
||||||
|
];
|
||||||
|
for (const required of requiredEntries) {
|
||||||
|
if (!newSet.has(required)) throw new Error(`Portable archive inventory is missing ${required}.`);
|
||||||
|
}
|
||||||
|
for (const rel of newFiles) {
|
||||||
|
const stagedPath = resolveInside(stagingDir, rel);
|
||||||
|
const stats = await lstat(stagedPath);
|
||||||
|
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldFiles = await readPortableInventory(resourcesDir);
|
||||||
|
const staleFiles = oldFiles
|
||||||
|
? oldFiles.filter((rel) => !newSet.has(rel) && isSafePortableRelativePath(rel))
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const planPath = join(updatesRoot, `portable-plan-${randomUUID()}.json`);
|
||||||
|
const scriptPath = join(updatesRoot, 'apply-portable-update.ps1');
|
||||||
|
const plan: PortableUpdatePlan = {
|
||||||
|
pid: parentPid,
|
||||||
|
installDir: resolve(installDir),
|
||||||
|
stagingDir,
|
||||||
|
archivePath,
|
||||||
|
logPath: join(updatesRoot, 'portable-update.log'),
|
||||||
|
executable: LAUNCHER_EXECUTABLE,
|
||||||
|
newFiles,
|
||||||
|
staleFiles,
|
||||||
|
};
|
||||||
|
await writeFile(planPath, `${JSON.stringify(plan, null, 2)}\n`, 'utf8');
|
||||||
|
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
|
||||||
|
return { scriptPath, planPath, stagingDir };
|
||||||
|
} catch (error) {
|
||||||
|
await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function launchPortableUpdater(prepared: PreparedPortableUpdate): void {
|
||||||
|
const child = spawn('powershell.exe', [
|
||||||
|
'-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',
|
||||||
|
'-File', prepared.scriptPath, prepared.planPath,
|
||||||
|
], {
|
||||||
|
cwd: dirname(prepared.scriptPath),
|
||||||
|
detached: true,
|
||||||
|
stdio: 'ignore',
|
||||||
|
windowsHide: true,
|
||||||
|
shell: false,
|
||||||
|
});
|
||||||
|
child.unref();
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import { app } from 'electron';
|
|||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import { defaultSettings, SettingsSchema, type Settings, type SettingsPatch } from '@shared/schemas/settings.ts';
|
import { defaultSettings, SettingsSchema, type Settings, type SettingsPatch } from '@shared/schemas/settings.ts';
|
||||||
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
|
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||||
|
import { setLauncherLoggingEnabled } from '../diagnostics/launcher-log.ts';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The launcher's settings file, `<user data>/settings.json`. Read once and cached; every change is
|
* The launcher's settings file, `<user data>/settings.json`. Read once and cached; every change is
|
||||||
@@ -47,6 +48,7 @@ export function updateSettings(patch: SettingsPatch): Promise<Settings> {
|
|||||||
throw new AppError('settings_write_failed');
|
throw new AppError('settings_write_failed');
|
||||||
}
|
}
|
||||||
cached = merged;
|
cached = merged;
|
||||||
|
setLauncherLoggingEnabled(merged.loggingEnabled);
|
||||||
return merged;
|
return merged;
|
||||||
});
|
});
|
||||||
pending = operation.then(() => undefined, () => undefined);
|
pending = operation.then(() => undefined, () => undefined);
|
||||||
|
|||||||
@@ -1,14 +1,22 @@
|
|||||||
import type { BigIntStats } from 'node:fs';
|
import type { BigIntStats } from 'node:fs';
|
||||||
import { copyFile, lstat, mkdir } from 'node:fs/promises';
|
import { copyFile, lstat, mkdir } from 'node:fs/promises';
|
||||||
import { dirname, join, normalize } from 'node:path';
|
import { dirname, join, normalize, relative, sep } from 'node:path';
|
||||||
import { compareVersions, GAME_FILES } from '@wto/patcher';
|
import { compareVersions, GAME_FILES, isHardlinkableResource } from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
|
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
|
||||||
import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts';
|
import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts';
|
||||||
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||||
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
|
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
|
||||||
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts';
|
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts';
|
||||||
import { fileHash, hardlinkResource, hasHardlinkEvidence, linkVerifiedResource, sameResource, verifyHardlinkResource } from '../install/hardlink-files.ts';
|
import {
|
||||||
|
fileHash,
|
||||||
|
linkVerifiedResource,
|
||||||
|
sameInode,
|
||||||
|
sameResource,
|
||||||
|
statFile,
|
||||||
|
statHardlinkResource,
|
||||||
|
verifyMatchingResource,
|
||||||
|
} from '../install/hardlink-files.ts';
|
||||||
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
|
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
|
||||||
import { checkPatches } from '../install/patch-check.ts';
|
import { checkPatches } from '../install/patch-check.ts';
|
||||||
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
||||||
@@ -40,6 +48,14 @@ export async function repair(record: InstallRecord, root: string, applying: () =
|
|||||||
}, listCopies);
|
}, listCopies);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function updatePreservesSpaceSaving(
|
||||||
|
record: InstallRecord,
|
||||||
|
source: GameFolderInspection,
|
||||||
|
root: string,
|
||||||
|
): Promise<boolean> {
|
||||||
|
return (record.hardlinkedFiles?.length ?? 0) > 0 && await canShareVolume(source.path, root);
|
||||||
|
}
|
||||||
|
|
||||||
export async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
|
export async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
|
||||||
const game = await readSource(record);
|
const game = await readSource(record);
|
||||||
if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update');
|
if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update');
|
||||||
@@ -50,8 +66,11 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
|
|||||||
const found = new Set(inventory.map(key));
|
const found = new Set(inventory.map(key));
|
||||||
const linked = record.hardlinkedFiles ?? [];
|
const linked = record.hardlinkedFiles ?? [];
|
||||||
const linkedPaths = new Set(linked.map(key));
|
const linkedPaths = new Set(linked.map(key));
|
||||||
|
const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root);
|
||||||
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
|
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
|
||||||
const copy = await planChangedFiles(game.path, root, dataPath, plan, linkedPaths, signal);
|
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
|
||||||
|
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
|
||||||
|
);
|
||||||
for (const file of remove) await scopedInstallFile(dataPath, root, file);
|
for (const file of remove) await scopedInstallFile(dataPath, root, file);
|
||||||
|
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
@@ -66,43 +85,86 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
|
|||||||
report('copying', doneBytes, copy.totalBytes);
|
report('copying', doneBytes, copy.totalBytes);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
const stagedLinks = new Map<string, BigIntStats>();
|
||||||
|
for (const [relativePath, sourceStamp] of linksToStage) {
|
||||||
|
signal.throwIfAborted();
|
||||||
|
const staged = join(incoming, relativePath);
|
||||||
|
await mkdir(dirname(staged), { recursive: true });
|
||||||
|
const linkedStamp = await linkVerifiedResource(join(game.path, relativePath), staged, sourceStamp);
|
||||||
|
stagedLinks.set(staged, linkedStamp);
|
||||||
|
}
|
||||||
const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
|
const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
|
||||||
for (const file of Object.values(GAME_FILES)) {
|
for (const file of Object.values(GAME_FILES)) {
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file));
|
await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file));
|
||||||
}
|
}
|
||||||
await verifySourceFiles(game.path, plan, signal);
|
await verifySourceFiles(game.path, plan, signal);
|
||||||
|
if (stagedLinks.size > 0) await verifyStagedLinks(record, game.version, stagedLinks, signal);
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
report('applying', copy.totalBytes, copy.totalBytes);
|
report('applying', copy.totalBytes, copy.totalBytes);
|
||||||
return { replace: [...copy.files.map(({ relativePath }) => relativePath), ...stockFiles], remove };
|
return {
|
||||||
|
replace: [...copy.files.map(({ relativePath }) => relativePath), ...linksToStage.keys(), ...stockFiles],
|
||||||
|
remove,
|
||||||
|
};
|
||||||
}, () => updateCopyRecord(record.id, (latest) => ({
|
}, () => updateCopyRecord(record.id, (latest) => ({
|
||||||
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
|
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
|
||||||
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
|
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
|
||||||
...(linked.length ? { hardlinkedFiles: [] } : {}),
|
...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}),
|
||||||
})));
|
})));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function planChangedFiles(
|
interface UpdateFilePlan {
|
||||||
source: string, root: string, dataPath: string, plan: CopyPlan, linked: ReadonlySet<string>, signal: AbortSignal,
|
readonly copy: CopyPlan;
|
||||||
): Promise<CopyPlan> {
|
readonly linksToStage: ReadonlyMap<string, BigIntStats>;
|
||||||
|
readonly hardlinkedFiles: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function planUpdateFiles(
|
||||||
|
source: string,
|
||||||
|
root: string,
|
||||||
|
dataPath: string,
|
||||||
|
plan: CopyPlan,
|
||||||
|
linked: ReadonlySet<string>,
|
||||||
|
preserveHardlinks: boolean,
|
||||||
|
signal: AbortSignal,
|
||||||
|
): Promise<UpdateFilePlan> {
|
||||||
const changed: CopyPlan['files'][number][] = [];
|
const changed: CopyPlan['files'][number][] = [];
|
||||||
|
const linksToStage = new Map<string, BigIntStats>();
|
||||||
|
const hardlinkedFiles: string[] = [];
|
||||||
for (const file of plan.files) {
|
for (const file of plan.files) {
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
const target = await scopedInstallFile(dataPath, root, file.relativePath);
|
const target = await scopedInstallFile(dataPath, root, file.relativePath);
|
||||||
const old = await fileInfo(target);
|
const sourceFile = join(source, file.relativePath);
|
||||||
if (linked.has(key(file.relativePath)) || !old?.isFile() || old.size !== file.bytes) {
|
const old = await statFile(target);
|
||||||
|
if (preserveHardlinks && isHardlinkableResource(file.relativePath, file.bytes)) {
|
||||||
|
const sourceStamp = await statHardlinkResource(sourceFile, file.bytes, signal);
|
||||||
|
if (!sourceStamp) throw new AppError('maintenance_source_changed');
|
||||||
|
if (!old || !sameResource(old, sourceStamp)) linksToStage.set(file.relativePath, sourceStamp);
|
||||||
|
hardlinkedFiles.push(file.relativePath);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const sourceStamp = await statFile(sourceFile);
|
||||||
|
if (!sourceStamp?.isFile() || sourceStamp.size !== BigInt(file.bytes)) {
|
||||||
|
throw new AppError('maintenance_source_changed');
|
||||||
|
}
|
||||||
|
if (linked.has(key(file.relativePath)) || !old?.isFile() || sameInode(old, sourceStamp) ||
|
||||||
|
old.size !== BigInt(file.bytes)) {
|
||||||
changed.push(file);
|
changed.push(file);
|
||||||
} else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) {
|
} else if (Math.trunc(Number(old.mtimeMs)) !== Math.trunc(file.modifiedAt)) {
|
||||||
const [targetHash, sourceHash] = await Promise.all([
|
const [targetHash, sourceHash] = await Promise.all([
|
||||||
fileHash(target, signal), fileHash(join(source, file.relativePath), signal),
|
fileHash(target, signal), fileHash(sourceFile, signal),
|
||||||
]);
|
]);
|
||||||
if (targetHash !== sourceHash) changed.push(file);
|
if (targetHash !== sourceHash) changed.push(file);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
files: changed,
|
copy: {
|
||||||
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
|
files: changed,
|
||||||
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
|
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
|
||||||
|
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
|
||||||
|
},
|
||||||
|
linksToStage,
|
||||||
|
hardlinkedFiles,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,8 +179,8 @@ async function verifySourceFiles(source: string, plan: CopyPlan, signal: AbortSi
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function convertibleCopy(record: InstallRecord, source: GameFolderInspection, root: string): Promise<boolean> {
|
export async function convertibleCopy(record: InstallRecord, source: GameFolderInspection, root: string): Promise<boolean> {
|
||||||
return record.method === 'copy' && source.version === record.gameVersion &&
|
return record.method === 'copy' && source.version !== null &&
|
||||||
hasHardlinkEvidence(source.version) && await sameVolume(source.path, root);
|
source.version === record.gameVersion && await canShareVolume(source.path, root);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
|
export async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
|
||||||
@@ -129,11 +191,8 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
|
|||||||
}
|
}
|
||||||
|
|
||||||
const plan = await planCopy(source.path);
|
const plan = await planCopy(source.path);
|
||||||
const candidates = plan.files.flatMap(({ relativePath, bytes }) => {
|
const candidates = plan.files.filter(({ relativePath, bytes }) => isHardlinkableResource(relativePath, bytes));
|
||||||
const evidence = hardlinkResource(source.version, relativePath, bytes);
|
const total = candidates.reduce((bytes, file) => bytes + file.bytes, 0);
|
||||||
return evidence ? [{ relativePath, evidence }] : [];
|
|
||||||
});
|
|
||||||
const total = candidates.reduce((bytes, file) => bytes + file.evidence.bytes, 0);
|
|
||||||
const dataPath = await canonicalCopyPath(record.dataPath);
|
const dataPath = await canonicalCopyPath(record.dataPath);
|
||||||
const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path]));
|
const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path]));
|
||||||
return changeCopyFiles(root, async (incoming) => {
|
return changeCopyFiles(root, async (incoming) => {
|
||||||
@@ -143,24 +202,24 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
|
|||||||
let matches = 0;
|
let matches = 0;
|
||||||
let lastReport = 0;
|
let lastReport = 0;
|
||||||
report('checking', 0, total);
|
report('checking', 0, total);
|
||||||
for (const { relativePath, evidence } of candidates) {
|
for (const { relativePath, bytes } of candidates) {
|
||||||
const target = await scopedInstallFile(dataPath, root, relativePath);
|
const target = await scopedInstallFile(dataPath, root, relativePath);
|
||||||
const original = join(source.path, relativePath);
|
const original = join(source.path, relativePath);
|
||||||
const copyStamp = await verifyHardlinkResource(target, evidence, signal);
|
const match = await verifyMatchingResource(target, original, bytes, signal);
|
||||||
const sourceStamp = copyStamp ? await verifyHardlinkResource(original, evidence, signal) : null;
|
if (match.status === 'already-linked') {
|
||||||
if (copyStamp && sourceStamp) {
|
linked.set(key(relativePath), relativePath);
|
||||||
if (!sameResource(copyStamp, sourceStamp)) {
|
matches += 1;
|
||||||
const staged = join(incoming, relativePath);
|
} else if (match.status === 'matched') {
|
||||||
await mkdir(dirname(staged), { recursive: true });
|
const staged = join(incoming, relativePath);
|
||||||
const stagedStamp = await linkVerifiedResource(original, staged, sourceStamp);
|
await mkdir(dirname(staged), { recursive: true });
|
||||||
unchanged.set(target, copyStamp);
|
const stagedStamp = await linkVerifiedResource(original, staged, match.sourceStamp);
|
||||||
unchanged.set(staged, stagedStamp);
|
unchanged.set(target, match.copyStamp);
|
||||||
replacements.push(relativePath);
|
unchanged.set(staged, stagedStamp);
|
||||||
}
|
replacements.push(relativePath);
|
||||||
linked.set(key(relativePath), relativePath);
|
linked.set(key(relativePath), relativePath);
|
||||||
matches += 1;
|
matches += 1;
|
||||||
}
|
}
|
||||||
checked += evidence.bytes;
|
checked += bytes;
|
||||||
if (checked === total || Date.now() - lastReport >= 250) {
|
if (checked === total || Date.now() - lastReport >= 250) {
|
||||||
lastReport = Date.now();
|
lastReport = Date.now();
|
||||||
report('checking', checked, total);
|
report('checking', checked, total);
|
||||||
@@ -175,6 +234,10 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
|
|||||||
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
|
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function canShareVolume(sourcePath: string, root: string): Promise<boolean> {
|
||||||
|
return await sameVolume(sourcePath, root) && await sameVolume(sourcePath, dirname(root));
|
||||||
|
}
|
||||||
|
|
||||||
async function verifyStagedLinks(
|
async function verifyStagedLinks(
|
||||||
record: InstallRecord, version: string | null, unchanged: ReadonlyMap<string, BigIntStats>, signal: AbortSignal,
|
record: InstallRecord, version: string | null, unchanged: ReadonlyMap<string, BigIntStats>, signal: AbortSignal,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
@@ -191,11 +254,32 @@ function key(path: string): string {
|
|||||||
return process.platform === 'win32' ? name.toLowerCase() : name;
|
return process.platform === 'win32' ? name.toLowerCase() : name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const OFFLINE_DATA_ENTRIES = new Set(['accounts.json', 'saves', 'tuning', 'logs', 'asset-pack', 'decals', 'cache']);
|
||||||
|
|
||||||
|
function failLocation(reason: string, details: Record<string, unknown>): never {
|
||||||
|
console.warn('[copies] maintenance_location:', reason, details);
|
||||||
|
throw new AppError('maintenance_location');
|
||||||
|
}
|
||||||
|
|
||||||
async function scopedInstallFile(dataPath: string, root: string, name: string): Promise<string> {
|
async function scopedInstallFile(dataPath: string, root: string, name: string): Promise<string> {
|
||||||
const target = await stagedPath(root, name);
|
const target = await stagedPath(root, name);
|
||||||
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target) ||
|
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target)) {
|
||||||
copyPathContains(dataPath, target)) {
|
failLocation('target_inside_wtoffline', { root, target, name });
|
||||||
throw new AppError('maintenance_location');
|
}
|
||||||
|
// Protect the data folder when it is nested inside the client folder. If an older installation
|
||||||
|
// placed dataPath at an ancestor of the client folder, files inside the client folder do not
|
||||||
|
// overlap data files stored at the ancestor root.
|
||||||
|
if (copyPathContains(root, dataPath)) {
|
||||||
|
if (relative(root, dataPath) !== '') {
|
||||||
|
if (copyPathContains(dataPath, target)) {
|
||||||
|
failLocation('target_inside_nested_data_folder', { root, dataPath, target, name });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const topSegment = normalize(name).split(sep)[0]?.toLowerCase() ?? '';
|
||||||
|
if (OFFLINE_DATA_ENTRIES.has(topSegment)) {
|
||||||
|
failLocation('target_collides_with_data_entry', { root, dataPath, target, name });
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return target;
|
return target;
|
||||||
}
|
}
|
||||||
@@ -203,6 +287,8 @@ async function scopedInstallFile(dataPath: string, root: string, name: string):
|
|||||||
async function stageBackup(folder: string, file: string, target: string): Promise<void> {
|
async function stageBackup(folder: string, file: string, target: string): Promise<void> {
|
||||||
await mkdir(dirname(target), { recursive: true });
|
await mkdir(dirname(target), { recursive: true });
|
||||||
const source = join(folder, file);
|
const source = join(folder, file);
|
||||||
if (!(await fileInfo(source))?.isFile()) throw new AppError('maintenance_location');
|
if (!(await fileInfo(source))?.isFile()) {
|
||||||
|
failLocation('stock_backup_source_missing', { folder, file, source });
|
||||||
|
}
|
||||||
await copyFile(source, target);
|
await copyFile(source, target);
|
||||||
}
|
}
|
||||||
@@ -13,14 +13,22 @@ import { gameProcessRunning, launchInProgress } from '../launch/launch-controlle
|
|||||||
import { readInstalledLab } from '../launch/lab-handoff.ts';
|
import { readInstalledLab } from '../launch/lab-handoff.ts';
|
||||||
import { localServerReady } from '../launch/local-server.ts';
|
import { localServerReady } from '../launch/local-server.ts';
|
||||||
import { fileInfo } from './change-copy-files.ts';
|
import { fileInfo } from './change-copy-files.ts';
|
||||||
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, type Report } from './copy-file-maintenance.ts';
|
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
|
||||||
|
|
||||||
let current: { stop: AbortController; interruptible: boolean } | null = null;
|
let current: {
|
||||||
|
stop: AbortController;
|
||||||
|
interruptible: boolean;
|
||||||
|
progress: MaintenanceProgress;
|
||||||
|
} | null = null;
|
||||||
|
|
||||||
export function maintenanceInProgress(): boolean {
|
export function maintenanceInProgress(): boolean {
|
||||||
return current !== null;
|
return current !== null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function maintenanceState(): MaintenanceProgress | null {
|
||||||
|
return current ? { ...current.progress } : null;
|
||||||
|
}
|
||||||
|
|
||||||
export function cancelMaintenance(): void {
|
export function cancelMaintenance(): void {
|
||||||
if (current?.interruptible) current.stop.abort();
|
if (current?.interruptible) current.stop.abort();
|
||||||
}
|
}
|
||||||
@@ -34,6 +42,7 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
|
|||||||
return {
|
return {
|
||||||
sourceVersion: source?.version ?? null,
|
sourceVersion: source?.version ?? null,
|
||||||
updateAvailable: isNewer(source, record.gameVersion),
|
updateAvailable: isNewer(source, record.gameVersion),
|
||||||
|
updatePreservesSpaceSaving: source !== null && await updatePreservesSpaceSaving(record, source, record.copyPath),
|
||||||
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
|
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
|
||||||
steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath),
|
steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath),
|
||||||
steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null,
|
steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null,
|
||||||
@@ -42,18 +51,28 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
|
|||||||
|
|
||||||
export async function maintainCopy(
|
export async function maintainCopy(
|
||||||
request: MaintenanceRequest,
|
request: MaintenanceRequest,
|
||||||
publish: (progress: MaintenanceProgress) => void,
|
publish: (progress: MaintenanceProgress | null) => void,
|
||||||
): Promise<Copies> {
|
): Promise<Copies> {
|
||||||
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
|
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
|
||||||
|
const initial: MaintenanceProgress = {
|
||||||
|
id: request.id,
|
||||||
|
operation: request.operation,
|
||||||
|
phase: 'checking',
|
||||||
|
doneBytes: 0,
|
||||||
|
totalBytes: 0,
|
||||||
|
};
|
||||||
const job = {
|
const job = {
|
||||||
stop: new AbortController(),
|
stop: new AbortController(),
|
||||||
interruptible: request.operation === 'update' || request.operation === 'compact',
|
interruptible: request.operation === 'update' || request.operation === 'compact',
|
||||||
|
progress: initial,
|
||||||
};
|
};
|
||||||
current = job;
|
current = job;
|
||||||
const signal = job.stop.signal;
|
const signal = job.stop.signal;
|
||||||
const report: Report = (phase, doneBytes = 0, totalBytes = 0) => {
|
const report: Report = (phase, doneBytes = 0, totalBytes = 0) => {
|
||||||
if (phase === 'applying') job.interruptible = false;
|
if (phase === 'applying') job.interruptible = false;
|
||||||
publish({ id: request.id, operation: request.operation, phase, doneBytes, totalBytes });
|
const next: MaintenanceProgress = { id: request.id, operation: request.operation, phase, doneBytes, totalBytes };
|
||||||
|
job.progress = next;
|
||||||
|
publish(next);
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -66,6 +85,7 @@ export async function maintainCopy(
|
|||||||
throw new AppError('maintenance_failed');
|
throw new AppError('maintenance_failed');
|
||||||
} finally {
|
} finally {
|
||||||
current = null;
|
current = null;
|
||||||
|
publish(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,7 +106,7 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign
|
|||||||
case 'confirm-steam':
|
case 'confirm-steam':
|
||||||
if (!steamLocations || !isAbsolute(steamLocations.copyPath) || !isAbsolute(steamLocations.dataPath) ||
|
if (!steamLocations || !isAbsolute(steamLocations.copyPath) || !isAbsolute(steamLocations.dataPath) ||
|
||||||
relative(root, steamLocations.copyPath) !== '' || relative(dataPath, steamLocations.dataPath) !== '') {
|
relative(root, steamLocations.copyPath) !== '' || relative(dataPath, steamLocations.dataPath) !== '') {
|
||||||
throw new AppError('maintenance_location');
|
failLocation('steam_confirmation_mismatch', { root, dataPath, steamLocations });
|
||||||
}
|
}
|
||||||
if (!needsConfirmation) return listCopies();
|
if (!needsConfirmation) return listCopies();
|
||||||
return updateCopyRecord(id, (copy) => ({
|
return updateCopyRecord(id, (copy) => ({
|
||||||
@@ -112,13 +132,23 @@ async function requireCopy(id: string): Promise<InstallRecord> {
|
|||||||
return record;
|
return record;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function failLocation(reason: string, details: Record<string, unknown>): never {
|
||||||
|
console.warn('[copies] maintenance_location:', reason, details);
|
||||||
|
throw new AppError('maintenance_location');
|
||||||
|
}
|
||||||
|
|
||||||
async function checkedRoot(record: InstallRecord): Promise<string> {
|
async function checkedRoot(record: InstallRecord): Promise<string> {
|
||||||
const root = await safeFolder(record.copyPath, true);
|
const root = await safeFolder(record.copyPath, true);
|
||||||
const backup = await canonicalCopyPath(record.stockBackupPath);
|
const backup = await canonicalCopyPath(record.stockBackupPath);
|
||||||
if (relative(join(root, STOCK_BACKUP_FOLDER), backup) !== '') throw new AppError('maintenance_location');
|
const expectedBackup = join(root, STOCK_BACKUP_FOLDER);
|
||||||
|
if (relative(expectedBackup, backup) !== '') {
|
||||||
|
failLocation('stock_backup_outside_copy', { root, expectedBackup, backup, recordedBackup: record.stockBackupPath });
|
||||||
|
}
|
||||||
if (record.sourcePath) {
|
if (record.sourcePath) {
|
||||||
const source = await canonicalCopyPath(record.sourcePath);
|
const source = await canonicalCopyPath(record.sourcePath);
|
||||||
if (copyPathContains(source, root) || copyPathContains(root, source)) throw new AppError('maintenance_location');
|
if (copyPathContains(source, root) || copyPathContains(root, source)) {
|
||||||
|
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return root;
|
return root;
|
||||||
}
|
}
|
||||||
@@ -126,12 +156,15 @@ async function checkedRoot(record: InstallRecord): Promise<string> {
|
|||||||
async function safeFolder(path: string, steamAllowed = false): Promise<string> {
|
async function safeFolder(path: string, steamAllowed = false): Promise<string> {
|
||||||
const root = await canonicalCopyPath(path);
|
const root = await canonicalCopyPath(path);
|
||||||
const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root);
|
const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root);
|
||||||
|
const appPath = await canonicalCopyPath(app.getAppPath());
|
||||||
|
const userDataPath = await canonicalCopyPath(app.getPath('userData'));
|
||||||
if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) ||
|
if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) ||
|
||||||
copyPathContains(root, await canonicalCopyPath(app.getAppPath())) ||
|
copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) {
|
||||||
copyPathContains(root, await canonicalCopyPath(app.getPath('userData')))) {
|
failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath });
|
||||||
throw new AppError('maintenance_location');
|
}
|
||||||
|
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) {
|
||||||
|
failLocation('folder_is_symlink', { path, root });
|
||||||
}
|
}
|
||||||
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) throw new AppError('maintenance_location');
|
|
||||||
return root;
|
return root;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,7 +183,7 @@ async function recordCheck(record: InstallRecord, folder: string): Promise<Copie
|
|||||||
|
|
||||||
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
|
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
|
||||||
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) {
|
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) {
|
||||||
if (deleteData) throw new AppError('maintenance_location');
|
if (deleteData) failLocation('delete_data_blocked_in_steam', { copyPath: record.copyPath, root });
|
||||||
return removeCopyRecord(record.id);
|
return removeCopyRecord(record.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,7 +191,7 @@ async function remove(record: InstallRecord, root: string, deleteData: boolean):
|
|||||||
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
|
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
|
||||||
if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) ||
|
if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) ||
|
||||||
(relative(data, root) !== '' && copyPathContains(data, root)))) {
|
(relative(data, root) !== '' && copyPathContains(data, root)))) {
|
||||||
throw new AppError('maintenance_location');
|
failLocation('delete_data_overlaps_source_or_copy', { root, data, source });
|
||||||
}
|
}
|
||||||
if (!deleteData && copyPathContains(root, data)) {
|
if (!deleteData && copyPathContains(root, data)) {
|
||||||
await removeExcept(root, data);
|
await removeExcept(root, data);
|
||||||
@@ -175,7 +208,7 @@ async function removeExcept(folder: string, kept: string): Promise<void> {
|
|||||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
||||||
const path = join(folder, entry.name);
|
const path = join(folder, entry.name);
|
||||||
if (copyPathContains(path, kept)) {
|
if (copyPathContains(path, kept)) {
|
||||||
if (!entry.isDirectory()) throw new AppError('maintenance_location');
|
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
|
||||||
await removeExcept(path, kept);
|
await removeExcept(path, kept);
|
||||||
} else {
|
} else {
|
||||||
await rm(path, { recursive: true, force: true });
|
await rm(path, { recursive: true, force: true });
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { AppError } from '@shared/errors.ts';
|
|||||||
import type { Copies } from '@shared/schemas/install.ts';
|
import type { Copies } from '@shared/schemas/install.ts';
|
||||||
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||||
import { hydrateCopiesStatus, relocateCopyRecord } from '../install/install-record.ts';
|
import { hydrateCopiesStatus, relocateCopyRecord } from '../install/install-record.ts';
|
||||||
import { backUpStockFiles } from '../install/stock-backup.ts';
|
import { backUpStockFiles, installStockSource, refreshStockBackup } from '../install/stock-backup.ts';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Re-point an existing registered client to its moved folder while keeping its id, name, saves,
|
* Re-point an existing registered client to its moved folder while keeping its id, name, saves,
|
||||||
@@ -12,7 +12,10 @@ export async function relocateCopy(id: string, newPath: string): Promise<Copies>
|
|||||||
const game = await inspectGameFolder(newPath);
|
const game = await inspectGameFolder(newPath);
|
||||||
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path: newPath });
|
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path: newPath });
|
||||||
if (game.needsStockSource) throw new AppError('stock_source_invalid');
|
if (game.needsStockSource) throw new AppError('stock_source_invalid');
|
||||||
const stockBackupPath = await backUpStockFiles(game.resolvedPath);
|
const stock = await installStockSource(game.resolvedPath, game.version);
|
||||||
|
const stockBackupPath = stock.refresh
|
||||||
|
? await refreshStockBackup(game.resolvedPath)
|
||||||
|
: await backUpStockFiles(game.resolvedPath);
|
||||||
const updated = await relocateCopyRecord(id, {
|
const updated = await relocateCopyRecord(id, {
|
||||||
copyPath: newPath,
|
copyPath: newPath,
|
||||||
stockBackupPath,
|
stockBackupPath,
|
||||||
|
|||||||
@@ -1,15 +1,31 @@
|
|||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
||||||
import { join } from 'node:path';
|
import { release } from 'node:os';
|
||||||
|
import { dirname, join } from 'node:path';
|
||||||
import { app, dialog, shell, type BrowserWindow } from 'electron';
|
import { app, dialog, shell, type BrowserWindow } from 'electron';
|
||||||
import { zipSync } from 'fflate';
|
import { zipSync } from 'fflate';
|
||||||
|
import { GAME_FILES } from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||||
import { getSettings } from '../config/settings-store.ts';
|
import { getSettings } from '../config/settings-store.ts';
|
||||||
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
|
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
|
||||||
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
|
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
|
||||||
|
|
||||||
type ArchiveFiles = Record<string, Uint8Array>;
|
type ArchiveFiles = Record<string, Uint8Array>;
|
||||||
|
|
||||||
|
/** Bound individual client log files so a huge crash dump or session log cannot exhaust memory. */
|
||||||
|
const MAX_CLIENT_LOG_BYTES = 16 * 1024 * 1024;
|
||||||
|
/** Number of recent .game_logs entries listed in client-logs/summary.json. */
|
||||||
|
const RECENT_GAME_LOGS_LIMIT = 10;
|
||||||
|
const HOOK_LOG_FILENAME = 'wto_ws.log';
|
||||||
|
const HOOK_CONFIG_FILENAME = 'wto_ws.cfg';
|
||||||
|
|
||||||
|
interface ListedFile {
|
||||||
|
readonly name: string;
|
||||||
|
readonly size: number;
|
||||||
|
readonly modifiedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
export async function openLogsFolder(): Promise<void> {
|
export async function openLogsFolder(): Promise<void> {
|
||||||
const path = launcherLogFolder();
|
const path = launcherLogFolder();
|
||||||
try {
|
try {
|
||||||
@@ -45,6 +61,7 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
|
|||||||
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
||||||
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
|
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
|
||||||
if (dataPath) await addServerLogs(files, dataPath);
|
if (dataPath) await addServerLogs(files, dataPath);
|
||||||
|
if (record) await addClientLogs(files, record, settings.loggingEnabled);
|
||||||
|
|
||||||
const temporary = `${result.filePath}.${randomUUID()}.tmp`;
|
const temporary = `${result.filePath}.${randomUUID()}.tmp`;
|
||||||
try {
|
try {
|
||||||
@@ -73,6 +90,173 @@ async function addServerLogs(files: ArchiveFiles, dataPath: string): Promise<voi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Include the hook library log, the latest game .clog and embedded browser log, and a small
|
||||||
|
* metadata summary for the active client so crashes and web-UI issues can be diagnosed without
|
||||||
|
* touching player saves.
|
||||||
|
*/
|
||||||
|
async function addClientLogs(files: ArchiveFiles, record: InstallRecord, loggingEnabled: boolean): Promise<void> {
|
||||||
|
const exeFolder = join(record.copyPath, dirname(GAME_FILES.executable));
|
||||||
|
const hookLogPath = join(exeFolder, HOOK_LOG_FILENAME);
|
||||||
|
const hookConfigPath = join(exeFolder, HOOK_CONFIG_FILENAME);
|
||||||
|
const gameLogsFolder = join(record.copyPath, '.game_logs');
|
||||||
|
|
||||||
|
const [hookLogStat, hookConfigStat] = await Promise.all([
|
||||||
|
readRegularFileStat(hookLogPath),
|
||||||
|
readRegularFileStat(hookConfigPath),
|
||||||
|
]);
|
||||||
|
|
||||||
|
let hookLogIncluded = false;
|
||||||
|
let hookLogOmittedReason: string | null = null;
|
||||||
|
if (hookLogStat) {
|
||||||
|
const added = await addBoundedClientFile(files, `client-logs/${HOOK_LOG_FILENAME}`, hookLogPath, hookLogStat.size);
|
||||||
|
hookLogIncluded = added.included;
|
||||||
|
hookLogOmittedReason = added.omittedReason;
|
||||||
|
}
|
||||||
|
|
||||||
|
const recentGameLogs: ListedFile[] = [];
|
||||||
|
let latestClog: ListedFile | null = null;
|
||||||
|
let latestClogIncluded = false;
|
||||||
|
let latestClogOmittedReason: string | null = null;
|
||||||
|
let latestBrowserLog: ListedFile | null = null;
|
||||||
|
let latestBrowserLogIncluded = false;
|
||||||
|
let latestBrowserLogOmittedReason: string | null = null;
|
||||||
|
|
||||||
|
const gameLogsDirStat = await safeStat(gameLogsFolder);
|
||||||
|
if (gameLogsDirStat?.isDirectory()) {
|
||||||
|
const entries = await safeReadDir(gameLogsFolder);
|
||||||
|
const inspected: Array<ListedFile & { readonly mtimeMs: number }> = [];
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!entry.isFile()) continue;
|
||||||
|
const stats = await readRegularFileStat(join(gameLogsFolder, entry.name));
|
||||||
|
if (!stats) continue;
|
||||||
|
inspected.push({
|
||||||
|
name: entry.name,
|
||||||
|
size: stats.size,
|
||||||
|
modifiedAt: new Date(stats.mtimeMs).toISOString(),
|
||||||
|
mtimeMs: stats.mtimeMs,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
inspected.sort((left, right) => right.mtimeMs - left.mtimeMs);
|
||||||
|
for (const item of inspected.slice(0, RECENT_GAME_LOGS_LIMIT)) {
|
||||||
|
recentGameLogs.push({ name: item.name, size: item.size, modifiedAt: item.modifiedAt });
|
||||||
|
}
|
||||||
|
const newestClog = inspected.find((item) => item.name.toLowerCase().endsWith('.clog')) ?? null;
|
||||||
|
if (newestClog) {
|
||||||
|
latestClog = { name: newestClog.name, size: newestClog.size, modifiedAt: newestClog.modifiedAt };
|
||||||
|
const added = await addBoundedClientFile(
|
||||||
|
files,
|
||||||
|
`client-logs/game-logs/${newestClog.name}`,
|
||||||
|
join(gameLogsFolder, newestClog.name),
|
||||||
|
newestClog.size,
|
||||||
|
);
|
||||||
|
latestClogIncluded = added.included;
|
||||||
|
latestClogOmittedReason = added.omittedReason;
|
||||||
|
}
|
||||||
|
const newestBrowserLog = inspected.find((item) => item.name.toLowerCase().endsWith('-browser.log')) ?? null;
|
||||||
|
if (newestBrowserLog) {
|
||||||
|
latestBrowserLog = {
|
||||||
|
name: newestBrowserLog.name,
|
||||||
|
size: newestBrowserLog.size,
|
||||||
|
modifiedAt: newestBrowserLog.modifiedAt,
|
||||||
|
};
|
||||||
|
const added = await addBoundedClientFile(
|
||||||
|
files,
|
||||||
|
`client-logs/game-logs/${newestBrowserLog.name}`,
|
||||||
|
join(gameLogsFolder, newestBrowserLog.name),
|
||||||
|
newestBrowserLog.size,
|
||||||
|
);
|
||||||
|
latestBrowserLogIncluded = added.included;
|
||||||
|
latestBrowserLogOmittedReason = added.omittedReason;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const summary = {
|
||||||
|
exportedAt: new Date().toISOString(),
|
||||||
|
launcherVersion: app.getVersion(),
|
||||||
|
loggingEnabled,
|
||||||
|
platform: process.platform,
|
||||||
|
arch: process.arch,
|
||||||
|
osRelease: release(),
|
||||||
|
copyId: record.id,
|
||||||
|
gameVersion: record.gameVersion,
|
||||||
|
hookConfig: hookConfigStat
|
||||||
|
? { present: true, size: hookConfigStat.size, modifiedAt: new Date(hookConfigStat.mtimeMs).toISOString() }
|
||||||
|
: { present: false },
|
||||||
|
hookLog: hookLogStat
|
||||||
|
? {
|
||||||
|
present: true,
|
||||||
|
size: hookLogStat.size,
|
||||||
|
modifiedAt: new Date(hookLogStat.mtimeMs).toISOString(),
|
||||||
|
included: hookLogIncluded,
|
||||||
|
...(hookLogOmittedReason ? { omittedReason: hookLogOmittedReason } : {}),
|
||||||
|
}
|
||||||
|
: { present: false },
|
||||||
|
gameLogsFolderPresent: gameLogsDirStat?.isDirectory() ?? false,
|
||||||
|
recentGameLogs,
|
||||||
|
latestClog: latestClog
|
||||||
|
? {
|
||||||
|
...latestClog,
|
||||||
|
included: latestClogIncluded,
|
||||||
|
...(latestClogOmittedReason ? { omittedReason: latestClogOmittedReason } : {}),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
latestBrowserLog: latestBrowserLog
|
||||||
|
? {
|
||||||
|
...latestBrowserLog,
|
||||||
|
included: latestBrowserLogIncluded,
|
||||||
|
...(latestBrowserLogOmittedReason ? { omittedReason: latestBrowserLogOmittedReason } : {}),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
files['client-logs/summary.json'] = new TextEncoder().encode(`${JSON.stringify(summary, null, 2)}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addBoundedClientFile(
|
||||||
|
files: ArchiveFiles,
|
||||||
|
entry: string,
|
||||||
|
path: string,
|
||||||
|
size: number,
|
||||||
|
): Promise<{ readonly included: boolean; readonly omittedReason: string | null }> {
|
||||||
|
if (size > MAX_CLIENT_LOG_BYTES) return { included: false, omittedReason: 'too-large' };
|
||||||
|
try {
|
||||||
|
const bytes = await readFile(path);
|
||||||
|
if (bytes.byteLength > MAX_CLIENT_LOG_BYTES) return { included: false, omittedReason: 'too-large' };
|
||||||
|
files[entry] = bytes;
|
||||||
|
return { included: true, omittedReason: null };
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[diagnostics] could not read client log:', path, error);
|
||||||
|
return { included: false, omittedReason: 'unreadable' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readRegularFileStat(path: string) {
|
||||||
|
const stats = await safeStat(path);
|
||||||
|
return stats?.isFile() ? stats : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function safeStat(path: string) {
|
||||||
|
try {
|
||||||
|
return await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||||
|
console.warn('[diagnostics] could not inspect path:', path, error);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function safeReadDir(path: string) {
|
||||||
|
try {
|
||||||
|
return await readdir(path, { withFileTypes: true });
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||||
|
console.warn('[diagnostics] could not read folder:', path, error);
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function addFile(files: ArchiveFiles, entry: string, path: string): Promise<void> {
|
async function addFile(files: ArchiveFiles, entry: string, path: string): Promise<void> {
|
||||||
if (!(await ifPresent(() => lstat(path)))?.isFile()) return;
|
if (!(await ifPresent(() => lstat(path)))?.isFile()) return;
|
||||||
const bytes = await ifPresent(() => readFile(path));
|
const bytes = await ifPresent(() => readFile(path));
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Console } from 'node:console';
|
import { Console } from 'node:console';
|
||||||
import { appendFileSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { Writable } from 'node:stream';
|
import { Writable } from 'node:stream';
|
||||||
import { app } from 'electron';
|
import { app } from 'electron';
|
||||||
@@ -12,13 +12,26 @@ export const LAUNCHER_LOG_FILES = [
|
|||||||
'launcher.4.log',
|
'launcher.4.log',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
let loggingEnabled = true;
|
||||||
|
let activeLogPath: string | null = null;
|
||||||
|
let fileFailed = false;
|
||||||
|
let originalConsole = console;
|
||||||
|
|
||||||
export function launcherLogFolder(): string {
|
export function launcherLogFolder(): string {
|
||||||
return join(app.getPath('userData'), 'logs');
|
return join(app.getPath('userData'), 'logs');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Rotate after taking the single-instance lock and keep the original console destinations. */
|
function readInitialLoggingEnabled(): boolean {
|
||||||
export function startLauncherLogging(): void {
|
try {
|
||||||
const originalConsole = console;
|
const raw = JSON.parse(readFileSync(join(app.getPath('userData'), 'settings.json'), 'utf8')) as { loggingEnabled?: unknown };
|
||||||
|
return raw?.loggingEnabled !== false;
|
||||||
|
} catch {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureLogFileReady(): boolean {
|
||||||
|
if (activeLogPath) return !fileFailed;
|
||||||
const folder = launcherLogFolder();
|
const folder = launcherLogFolder();
|
||||||
const active = join(folder, LAUNCHER_LOG_FILES[0]);
|
const active = join(folder, LAUNCHER_LOG_FILES[0]);
|
||||||
try {
|
try {
|
||||||
@@ -28,17 +41,37 @@ export function startLauncherLogging(): void {
|
|||||||
if (existsSync(previous)) renameSync(previous, join(folder, LAUNCHER_LOG_FILES[index]!));
|
if (existsSync(previous)) renameSync(previous, join(folder, LAUNCHER_LOG_FILES[index]!));
|
||||||
}
|
}
|
||||||
writeFileSync(active, '', { flag: 'wx' });
|
writeFileSync(active, '', { flag: 'wx' });
|
||||||
|
activeLogPath = active;
|
||||||
|
fileFailed = false;
|
||||||
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
fileFailed = true;
|
||||||
originalConsole.error('[logs] opening the launcher log failed:', error);
|
originalConsole.error('[logs] opening the launcher log failed:', error);
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Enable or disable writing launcher console output to launcher.log at runtime. */
|
||||||
|
export function setLauncherLoggingEnabled(enabled: boolean): void {
|
||||||
|
loggingEnabled = enabled;
|
||||||
|
if (enabled && !activeLogPath && !fileFailed) {
|
||||||
|
if (ensureLogFileReady()) {
|
||||||
|
console.info(`WTOffline Launcher ${app.getVersion()} logging enabled.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rotate after taking the single-instance lock and keep the original console destinations. */
|
||||||
|
export function startLauncherLogging(): void {
|
||||||
|
originalConsole = console;
|
||||||
|
loggingEnabled = readInitialLoggingEnabled();
|
||||||
|
if (loggingEnabled) ensureLogFileReady();
|
||||||
|
|
||||||
let fileFailed = false;
|
|
||||||
const mirror = (destination: NodeJS.WriteStream, stream: string): Writable => new Writable({
|
const mirror = (destination: NodeJS.WriteStream, stream: string): Writable => new Writable({
|
||||||
write(chunk: Buffer, _encoding, done) {
|
write(chunk: Buffer, _encoding, done) {
|
||||||
if (!fileFailed) {
|
if (loggingEnabled && activeLogPath && !fileFailed) {
|
||||||
try {
|
try {
|
||||||
appendFileSync(active, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`);
|
appendFileSync(activeLogPath, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
fileFailed = true;
|
fileFailed = true;
|
||||||
originalConsole.error('[logs] writing the launcher log failed:', error);
|
originalConsole.error('[logs] writing the launcher log failed:', error);
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
|
import { isHardlinkableResource } from '@wto/patcher';
|
||||||
import type { FolderSize } from '@shared/schemas/install.ts';
|
import type { FolderSize } from '@shared/schemas/install.ts';
|
||||||
import { planCopy } from '../install/copy-game.ts';
|
import { planCopy } from '../install/copy-game.ts';
|
||||||
import { hardlinkResource } from '../install/hardlink-files.ts';
|
|
||||||
|
|
||||||
/** Estimate the installation size and the bytes eligible for content verification. */
|
/** Estimate the installation size and the bytes eligible for space-saving hard links. */
|
||||||
export async function measureFolder(root: string, version?: string | null): Promise<FolderSize> {
|
export async function measureFolder(root: string): Promise<FolderSize> {
|
||||||
const plan = await planCopy(root);
|
const plan = await planCopy(root);
|
||||||
const linkableBytes = plan.files.reduce((total, file) =>
|
const linkableBytes = plan.files.reduce((total, file) =>
|
||||||
total + (hardlinkResource(version, file.relativePath, file.bytes)?.bytes ?? 0), 0);
|
total + (isHardlinkableResource(file.relativePath, file.bytes) ? file.bytes : 0), 0);
|
||||||
return { bytes: plan.totalBytes, files: plan.files.length, linkableBytes };
|
return { bytes: plan.totalBytes, files: plan.files.length, linkableBytes };
|
||||||
}
|
}
|
||||||
@@ -23,28 +23,43 @@ export async function inspectGameFolder(path: string): Promise<GameFolderInspect
|
|||||||
if (!(await exists(join(resolved, file)))) missingFiles.push(file);
|
if (!(await exists(join(resolved, file)))) missingFiles.push(file);
|
||||||
}
|
}
|
||||||
const stockRoot = join(resolved, STOCK_BACKUP_FOLDER);
|
const stockRoot = join(resolved, STOCK_BACKUP_FOLDER);
|
||||||
let hasOfflineBackup = true;
|
let hasStockFiles = true;
|
||||||
for (const file of required) {
|
for (const file of required) {
|
||||||
if (!(await exists(join(stockRoot, file)))) {
|
if (!(await exists(join(stockRoot, file)))) {
|
||||||
hasOfflineBackup = false;
|
hasStockFiles = false;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const resources = resourcePaths();
|
const resources = resourcePaths();
|
||||||
const executablePath = hasOfflineBackup
|
const liveExeBytes = missingFiles.includes(GAME_FILES.executable)
|
||||||
? join(stockRoot, GAME_FILES.executable)
|
|
||||||
: join(resolved, GAME_FILES.executable);
|
|
||||||
const executableBytes = (!hasOfflineBackup && missingFiles.includes(GAME_FILES.executable))
|
|
||||||
? null
|
? null
|
||||||
: await readBytes(executablePath);
|
: await readBytes(join(resolved, GAME_FILES.executable));
|
||||||
const version = executableBytes ? readVersionFromBytes(executableBytes) : null;
|
const liveVersion = liveExeBytes ? readVersionFromBytes(liveExeBytes) : null;
|
||||||
|
const backupExeBytes = hasStockFiles
|
||||||
|
? await readBytes(join(stockRoot, GAME_FILES.executable))
|
||||||
|
: null;
|
||||||
|
const backupVersion = backupExeBytes ? readVersionFromBytes(backupExeBytes) : null;
|
||||||
|
|
||||||
|
// Always report the live executable's version when readable so an externally updated client
|
||||||
|
// (for example, an in-place folder updated by the official launcher) is never masked by a stale
|
||||||
|
// wtoffline/stock backup.
|
||||||
|
const version = liveVersion ?? backupVersion;
|
||||||
|
const hasOfflineBackup = hasStockFiles && backupVersion !== null && (liveVersion === null || backupVersion === liveVersion);
|
||||||
|
const liveExePatched = liveExeBytes !== null && liveExeBytes.includes(PATCHED_EXE_MARKER);
|
||||||
|
|
||||||
let needsStockSource = false;
|
let needsStockSource = false;
|
||||||
if (!hasOfflineBackup && missingFiles.length === 0) {
|
if (!hasOfflineBackup && missingFiles.length === 0) {
|
||||||
const exeDir = join(resolved, dirname(GAME_FILES.executable));
|
if (hasStockFiles && backupVersion !== null && liveVersion !== null && backupVersion !== liveVersion) {
|
||||||
const hasMarkerFile = (await Promise.all(
|
// A stale stock backup only needs an external stock source if the live executable is already
|
||||||
PATCH_MARKER_FILES.map((file) => exists(join(exeDir, file))),
|
// patched; an unpatched live executable can refresh wtoffline/stock directly during install.
|
||||||
)).some(Boolean);
|
needsStockSource = liveExePatched;
|
||||||
needsStockSource = hasMarkerFile || (executableBytes !== null && executableBytes.includes(PATCHED_EXE_MARKER));
|
} else {
|
||||||
|
const exeDir = join(resolved, dirname(GAME_FILES.executable));
|
||||||
|
const hasMarkerFile = (await Promise.all(
|
||||||
|
PATCH_MARKER_FILES.map((file) => exists(join(exeDir, file))),
|
||||||
|
)).some(Boolean);
|
||||||
|
needsStockSource = hasMarkerFile || liveExePatched;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
path,
|
path,
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
|
|||||||
* game creates these folders again when it needs them.
|
* game creates these folders again when it needs them.
|
||||||
*/
|
*/
|
||||||
export const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']);
|
export const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']);
|
||||||
|
/** Top-level folders ignored when scanning a stock source, including any stray offline backup directory. */
|
||||||
|
const SKIPPED_SOURCE_FOLDERS = new Set([...PLAYER_DATA_FOLDERS, 'wtoffline']);
|
||||||
|
|
||||||
interface CopyEntry {
|
interface CopyEntry {
|
||||||
readonly relativePath: string;
|
readonly relativePath: string;
|
||||||
@@ -46,7 +48,7 @@ export async function planCopy(source: string): Promise<CopyPlan> {
|
|||||||
const folder = pending.pop()!;
|
const folder = pending.pop()!;
|
||||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
||||||
const path = join(folder, entry.name);
|
const path = join(folder, entry.name);
|
||||||
if (folder === source && PLAYER_DATA_FOLDERS.has(entry.name.toLowerCase())) continue;
|
if (folder === source && SKIPPED_SOURCE_FOLDERS.has(entry.name.toLowerCase())) continue;
|
||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
folders.push(relative(source, path));
|
folders.push(relative(source, path));
|
||||||
pending.push(path);
|
pending.push(path);
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises';
|
import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises';
|
||||||
import { dirname, isAbsolute, join, relative } from 'node:path';
|
import { dirname, isAbsolute, join, relative } from 'node:path';
|
||||||
import { isInSteamLibrary, playerDecalCacheProblem } from '@wto/patcher';
|
import {
|
||||||
|
isInSteamLibrary,
|
||||||
|
playerDecalCacheProblem,
|
||||||
|
resolvePlayerDecalCacheFolder,
|
||||||
|
writeDecalCacheIndexSnapshot,
|
||||||
|
} from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import type { Copies } from '@shared/schemas/install.ts';
|
import type { Copies } from '@shared/schemas/install.ts';
|
||||||
import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts';
|
import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts';
|
||||||
@@ -33,8 +38,13 @@ export async function importDecalCache(
|
|||||||
dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false,
|
dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid');
|
if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid');
|
||||||
const source = await realpath(sourcePath).catch(() => null);
|
const rawSource = await realpath(sourcePath).catch(() => null);
|
||||||
if (!source || playerDecalCacheProblem(source)) throw new AppError('decal_source_invalid');
|
const source = rawSource ? await realpath(resolvePlayerDecalCacheFolder(rawSource)).catch(() => null) : null;
|
||||||
|
const problem = source ? playerDecalCacheProblem(source) : 'selected folder could not be resolved';
|
||||||
|
if (!source || problem) {
|
||||||
|
console.warn('[decals] invalid decal cache source:', sourcePath, '->', problem);
|
||||||
|
throw new AppError('decal_source_invalid');
|
||||||
|
}
|
||||||
|
|
||||||
const root = await cacheRoot(dataPath, steamDataConfirmed);
|
const root = await cacheRoot(dataPath, steamDataConfirmed);
|
||||||
if (copyPathContains(source, root) || copyPathContains(root, source)) {
|
if (copyPathContains(source, root) || copyPathContains(root, source)) {
|
||||||
@@ -56,7 +66,12 @@ export async function importDecalCache(
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
signal?.throwIfAborted();
|
signal?.throwIfAborted();
|
||||||
if (playerDecalCacheProblem(target)) throw new AppError('decal_source_invalid');
|
writeDecalCacheIndexSnapshot(source, target);
|
||||||
|
const copiedProblem = playerDecalCacheProblem(target);
|
||||||
|
if (copiedProblem) {
|
||||||
|
console.warn('[decals] copied decal cache failed validation:', copiedProblem);
|
||||||
|
throw new AppError('decal_source_invalid');
|
||||||
|
}
|
||||||
return id;
|
return id;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await discardDecalCache(dataPath, id, steamDataConfirmed);
|
await discardDecalCache(dataPath, id, steamDataConfirmed);
|
||||||
|
|||||||
@@ -2,30 +2,11 @@ import { createHash } from 'node:crypto';
|
|||||||
import { createReadStream, type BigIntStats } from 'node:fs';
|
import { createReadStream, type BigIntStats } from 'node:fs';
|
||||||
import { link, lstat } from 'node:fs/promises';
|
import { link, lstat } from 'node:fs/promises';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import evidence from './hardlink-resources-2.61.0.43.json' with { type: 'json' };
|
|
||||||
|
|
||||||
interface ResourceEvidence {
|
export type ResourceMatchResult =
|
||||||
readonly bytes: number;
|
| { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
|
||||||
readonly sha256: string;
|
| { readonly status: 'matched'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
|
||||||
}
|
| { readonly status: 'mismatch' };
|
||||||
|
|
||||||
const resources: Readonly<Record<string, ResourceEvidence>> = evidence.files;
|
|
||||||
|
|
||||||
export function hasHardlinkEvidence(version: string | null | undefined): boolean {
|
|
||||||
return version === evidence.gameVersion;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Only an exact path and size from the sampled build can be offered as a candidate. */
|
|
||||||
export function hardlinkResource(
|
|
||||||
version: string | null | undefined,
|
|
||||||
relativePath: string,
|
|
||||||
bytes: number,
|
|
||||||
): ResourceEvidence | undefined {
|
|
||||||
if (!hasHardlinkEvidence(version)) return undefined;
|
|
||||||
const path = relativePath.replaceAll('\\', '/').toLowerCase();
|
|
||||||
const resource = Object.hasOwn(resources, path) ? resources[path] : undefined;
|
|
||||||
return resource?.bytes === bytes ? resource : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fileHash(path: string, signal: AbortSignal): Promise<string> {
|
export async function fileHash(path: string, signal: AbortSignal): Promise<string> {
|
||||||
const hash = createHash('sha256');
|
const hash = createHash('sha256');
|
||||||
@@ -33,22 +14,56 @@ export async function fileHash(path: string, signal: AbortSignal): Promise<strin
|
|||||||
return hash.digest('hex');
|
return hash.digest('hex');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Read the measured bytes and retain the observed file identity until the link is created. */
|
export async function statFile(path: string): Promise<BigIntStats | null> {
|
||||||
export async function verifyHardlinkResource(
|
return lstat(path, { bigint: true }).catch((error: NodeJS.ErrnoException) => {
|
||||||
path: string,
|
|
||||||
resource: ResourceEvidence,
|
|
||||||
signal: AbortSignal,
|
|
||||||
): Promise<BigIntStats | null> {
|
|
||||||
signal.throwIfAborted();
|
|
||||||
const before = await lstat(path, { bigint: true }).catch((error: NodeJS.ErrnoException) => {
|
|
||||||
if (error.code === 'ENOENT') return null;
|
if (error.code === 'ENOENT') return null;
|
||||||
throw error;
|
throw error;
|
||||||
});
|
});
|
||||||
if (!before?.isFile() || before.size !== BigInt(resource.bytes)) return null;
|
}
|
||||||
const checksum = await fileHash(path, signal);
|
|
||||||
const after = await lstat(path, { bigint: true });
|
/** Capture the file identity of a stock asset right before hardlinking it. */
|
||||||
if (!sameResource(before, after)) throw new AppError('hardlink_file_changed');
|
export async function statHardlinkResource(
|
||||||
return checksum === resource.sha256 ? after : null;
|
path: string,
|
||||||
|
expectedBytes: number,
|
||||||
|
signal: AbortSignal,
|
||||||
|
): Promise<BigIntStats | null> {
|
||||||
|
signal.throwIfAborted();
|
||||||
|
const stats = await statFile(path);
|
||||||
|
if (!stats?.isFile() || stats.size !== BigInt(expectedBytes)) return null;
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify that an existing copy file and stock file have identical contents before replacing the
|
||||||
|
* copy file with a hard link. Already-linked pairs return immediately without re-hashing.
|
||||||
|
*/
|
||||||
|
export async function verifyMatchingResource(
|
||||||
|
copyPath: string,
|
||||||
|
sourcePath: string,
|
||||||
|
expectedBytes: number,
|
||||||
|
signal: AbortSignal,
|
||||||
|
): Promise<ResourceMatchResult> {
|
||||||
|
signal.throwIfAborted();
|
||||||
|
const [copyBefore, sourceBefore] = await Promise.all([statFile(copyPath), statFile(sourcePath)]);
|
||||||
|
const size = BigInt(expectedBytes);
|
||||||
|
if (!copyBefore?.isFile() || !sourceBefore?.isFile() || copyBefore.size !== size || sourceBefore.size !== size) {
|
||||||
|
return { status: 'mismatch' };
|
||||||
|
}
|
||||||
|
if (sameResource(copyBefore, sourceBefore)) {
|
||||||
|
return { status: 'already-linked', copyStamp: copyBefore, sourceStamp: sourceBefore };
|
||||||
|
}
|
||||||
|
const [copyHash, sourceHash] = await Promise.all([fileHash(copyPath, signal), fileHash(sourcePath, signal)]);
|
||||||
|
const [copyAfter, sourceAfter] = await Promise.all([statFile(copyPath), statFile(sourcePath)]);
|
||||||
|
if (!copyAfter || !sourceAfter || !sameResource(copyBefore, copyAfter) || !sameResource(sourceBefore, sourceAfter)) {
|
||||||
|
throw new AppError('hardlink_file_changed');
|
||||||
|
}
|
||||||
|
return copyHash === sourceHash
|
||||||
|
? { status: 'matched', copyStamp: copyAfter, sourceStamp: sourceAfter }
|
||||||
|
: { status: 'mismatch' };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sameInode(left: BigIntStats, right: BigIntStats): boolean {
|
||||||
|
return left.isFile() && right.isFile() && left.dev === right.dev && left.ino === right.ino;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sameResource(left: BigIntStats, right: BigIntStats): boolean {
|
export function sameResource(left: BigIntStats, right: BigIntStats): boolean {
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,18 +1,18 @@
|
|||||||
import type { BigIntStats } from 'node:fs';
|
import type { BigIntStats } from 'node:fs';
|
||||||
import { access, mkdir } from 'node:fs/promises';
|
import { access, mkdir } from 'node:fs/promises';
|
||||||
import { isAbsolute, join, relative } from 'node:path';
|
import { dirname, isAbsolute, join, relative } from 'node:path';
|
||||||
import { isInSteamLibrary } from '@wto/patcher';
|
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
||||||
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||||
import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts';
|
import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts';
|
||||||
import { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts';
|
import { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts';
|
||||||
import { requireUnredirectedData } from './data-location.ts';
|
import { requireUnredirectedData } from './data-location.ts';
|
||||||
import { discardDecalCache, importDecalCache } from './decals.ts';
|
import { discardDecalCache, importDecalCache } from './decals.ts';
|
||||||
import { hardlinkResource, hasHardlinkEvidence, verifyHardlinkResource } from './hardlink-files.ts';
|
import { statHardlinkResource } from './hardlink-files.ts';
|
||||||
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
|
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
|
||||||
import { checkPatches } from './patch-check.ts';
|
import { checkPatches } from './patch-check.ts';
|
||||||
import { backUpStockFiles, backUpStockFilesFrom, installStockSource, refreshStockBackup, requireStockBackupLocation, stockBackupPath } from './stock-backup.ts';
|
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation, STOCK_BACKUP_FOLDER } from './stock-backup.ts';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Install the offline version: check the patches against the player's game,
|
* Install the offline version: check the patches against the player's game,
|
||||||
@@ -90,12 +90,12 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const copied = request.method === 'copy'
|
const copied = request.method === 'copy'
|
||||||
? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks ? version : null, signal, report)
|
? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks, version, signal, report)
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||||
const stockBackup = externalStockPath
|
const stockBackup = externalStockPath
|
||||||
? await backUpStockFilesFrom(copyPath, externalStockPath)
|
? await refreshStockBackupFrom(copyPath, externalStockPath)
|
||||||
: (request.method === 'in-place' || request.method === 'existing') && stock.refresh
|
: (request.method === 'in-place' || request.method === 'existing') && stock.refresh
|
||||||
? await refreshStockBackup(copyPath)
|
? await refreshStockBackup(copyPath)
|
||||||
: await backUpStockFiles(copyPath);
|
: await backUpStockFiles(copyPath);
|
||||||
@@ -141,16 +141,20 @@ async function inspectInstallation(request: InstallRequest) {
|
|||||||
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
|
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
|
||||||
]);
|
]);
|
||||||
await requireAvailableCopy(request.id, copyPath, dataPath);
|
await requireAvailableCopy(request.id, copyPath, dataPath);
|
||||||
if (!isAbsolute(request.dataPath) || copyPathContains(stockBackupPath(copyPath), dataPath) ||
|
const dataProblem = dataFolderProblem(
|
||||||
(request.method === 'copy' && copyPathContains(sourcePath, dataPath)) ||
|
dataPath,
|
||||||
(externalStockPath && copyPathContains(externalStockPath, dataPath))) {
|
copyPath,
|
||||||
throw new AppError('target_not_usable', { problem: 'overlaps_stock' });
|
request.method === 'copy' ? sourcePath : null,
|
||||||
|
externalStockPath,
|
||||||
|
);
|
||||||
|
if (!isAbsolute(request.dataPath) || dataProblem !== null) {
|
||||||
|
throw new AppError('target_not_usable', { problem: dataProblem ?? 'overlaps_stock' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, sourcePath) : null;
|
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, sourcePath) : null;
|
||||||
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
|
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
|
||||||
const useHardLinks = request.method === 'copy' && request.useHardLinks === true;
|
const useHardLinks = request.method === 'copy' && request.useHardLinks === true;
|
||||||
if (useHardLinks && (!target?.sameDriveAsStock || !hasHardlinkEvidence(game.version))) {
|
if (useHardLinks && !target?.sameDriveAsStock) {
|
||||||
throw new AppError('hardlink_unavailable');
|
throw new AppError('hardlink_unavailable');
|
||||||
}
|
}
|
||||||
const copyInSteam = isInSteamLibrary(requestedCopyPath) || isInSteamLibrary(copyPath);
|
const copyInSteam = isInSteamLibrary(requestedCopyPath) || isInSteamLibrary(copyPath);
|
||||||
@@ -165,6 +169,28 @@ async function inspectInstallation(request: InstallRequest) {
|
|||||||
return { version: game.version, requestedCopyPath, copyPath, dataPath, sourcePath, externalStockPath, target, useHardLinks, copyInSteam, dataInSteam };
|
return { version: game.version, requestedCopyPath, copyPath, dataPath, sourcePath, externalStockPath, target, useHardLinks, copyInSteam, dataInSteam };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate where the offline data folder sits relative to the client and stock folders.
|
||||||
|
* A subfolder inside the client (outside wtoffline/) is allowed, while setting dataPath to the
|
||||||
|
* client folder itself or an ancestor of it would mix game files into the data root.
|
||||||
|
*/
|
||||||
|
export function dataFolderProblem(
|
||||||
|
dataPath: string,
|
||||||
|
copyPath: string | null,
|
||||||
|
sourcePath: string | null,
|
||||||
|
externalStockPath: string | null,
|
||||||
|
): DataFolderProblem | null {
|
||||||
|
if (copyPath && (copyPathContains(dataPath, copyPath) ||
|
||||||
|
copyPathContains(join(copyPath, dirname(STOCK_BACKUP_FOLDER)), dataPath))) {
|
||||||
|
return 'overlaps_client';
|
||||||
|
}
|
||||||
|
if ((sourcePath && copyPathContains(sourcePath, dataPath)) ||
|
||||||
|
(externalStockPath && copyPathContains(externalStockPath, dataPath))) {
|
||||||
|
return 'overlaps_stock';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
async function resolveExternalStockSource(stockSourcePath: string, expectedVersion: string | null) {
|
async function resolveExternalStockSource(stockSourcePath: string, expectedVersion: string | null) {
|
||||||
const stockGame = await requireGameFolder(stockSourcePath);
|
const stockGame = await requireGameFolder(stockSourcePath);
|
||||||
if (stockGame.needsStockSource) throw new AppError('stock_source_invalid');
|
if (stockGame.needsStockSource) throw new AppError('stock_source_invalid');
|
||||||
@@ -178,16 +204,17 @@ async function copyGame(
|
|||||||
source: string,
|
source: string,
|
||||||
target: string,
|
target: string,
|
||||||
initialFreeBytes: number | null,
|
initialFreeBytes: number | null,
|
||||||
hardlinkVersion: string | null,
|
useHardLinks: boolean,
|
||||||
|
sourceVersion: string | null,
|
||||||
signal: AbortSignal,
|
signal: AbortSignal,
|
||||||
report: (progress: InstallProgress) => void,
|
report: (progress: InstallProgress) => void,
|
||||||
): Promise<Pick<InstallRecord, 'sourceFiles' | 'hardlinkedFiles'>> {
|
): Promise<Pick<InstallRecord, 'sourceFiles' | 'hardlinkedFiles'>> {
|
||||||
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||||
const plan = await planCopy(source);
|
const plan = await planCopy(source);
|
||||||
const hardlinks = hardlinkVersion ? await confirmHardlinks(source, hardlinkVersion, plan, signal, report) : undefined;
|
const hardlinks = useHardLinks ? await prepareHardlinks(source, plan, signal, report) : undefined;
|
||||||
const linkedBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0;
|
const linkedBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0;
|
||||||
const neededBytes = plan.totalBytes - linkedBytes + SPARE_BYTES;
|
const neededBytes = plan.totalBytes - linkedBytes + SPARE_BYTES;
|
||||||
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== hardlinkVersion)) {
|
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) {
|
||||||
throw new AppError('hardlink_file_changed');
|
throw new AppError('hardlink_file_changed');
|
||||||
}
|
}
|
||||||
const available = hardlinks ? await freeBytes(target) : initialFreeBytes;
|
const available = hardlinks ? await freeBytes(target) : initialFreeBytes;
|
||||||
@@ -200,7 +227,7 @@ async function copyGame(
|
|||||||
try {
|
try {
|
||||||
await copyPlannedFiles(source, target, plan, signal,
|
await copyPlannedFiles(source, target, plan, signal,
|
||||||
(done) => report({ phase: 'copying', ...done, ...totals }), hardlinks);
|
(done) => report({ phase: 'copying', ...done, ...totals }), hardlinks);
|
||||||
if (hardlinks && (await inspectGameFolder(source)).version !== hardlinkVersion) throw new AppError('hardlink_file_changed');
|
if (hardlinks && (await inspectGameFolder(source)).version !== sourceVersion) throw new AppError('hardlink_file_changed');
|
||||||
return {
|
return {
|
||||||
sourceFiles: plan.files.map((file) => file.relativePath),
|
sourceFiles: plan.files.map((file) => file.relativePath),
|
||||||
...(hardlinks ? { hardlinkedFiles: [...hardlinks.keys()] } : {}),
|
...(hardlinks ? { hardlinkedFiles: [...hardlinks.keys()] } : {}),
|
||||||
@@ -214,26 +241,22 @@ async function copyGame(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function confirmHardlinks(
|
async function prepareHardlinks(
|
||||||
source: string,
|
source: string,
|
||||||
version: string,
|
|
||||||
plan: CopyPlan,
|
plan: CopyPlan,
|
||||||
signal: AbortSignal,
|
signal: AbortSignal,
|
||||||
report: (progress: InstallProgress) => void,
|
report: (progress: InstallProgress) => void,
|
||||||
): Promise<ReadonlyMap<string, BigIntStats>> {
|
): Promise<ReadonlyMap<string, BigIntStats>> {
|
||||||
const candidates = plan.files.flatMap((file) => {
|
const candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
|
||||||
const evidence = hardlinkResource(version, file.relativePath, file.bytes);
|
const totalBytes = candidates.reduce((total, file) => total + file.bytes, 0);
|
||||||
return evidence ? [{ path: file.relativePath, evidence }] : [];
|
|
||||||
});
|
|
||||||
const totalBytes = candidates.reduce((total, file) => total + file.evidence.bytes, 0);
|
|
||||||
const links = new Map<string, BigIntStats>();
|
const links = new Map<string, BigIntStats>();
|
||||||
let doneBytes = 0;
|
let doneBytes = 0;
|
||||||
let doneFiles = 0;
|
let doneFiles = 0;
|
||||||
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
||||||
for (const { path, evidence } of candidates) {
|
for (const file of candidates) {
|
||||||
const verified = await verifyHardlinkResource(join(source, path), evidence, signal);
|
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
|
||||||
if (verified) links.set(path, verified);
|
if (verified) links.set(file.relativePath, verified);
|
||||||
doneBytes += evidence.bytes;
|
doneBytes += file.bytes;
|
||||||
doneFiles += 1;
|
doneFiles += 1;
|
||||||
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,22 +50,36 @@ export async function backUpStockFilesFrom(copyFolder: string, sourceFolder: str
|
|||||||
return backup;
|
return backup;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A new game version must pass the patch checks before replacing an existing stock backup. */
|
/** A new game version or damaged backup must pass the patch checks before replacing wtoffline/stock. */
|
||||||
export async function installStockSource(copyFolder: string, version: string | null) {
|
export async function installStockSource(copyFolder: string, version: string | null) {
|
||||||
const backup = await requireStockBackupLocation(copyFolder);
|
const backup = await requireStockBackupLocation(copyFolder);
|
||||||
if (!await exists(join(backup, GAME_FILES.executable))) return { path: copyFolder, refresh: await exists(backup) };
|
const backupExe = join(backup, GAME_FILES.executable);
|
||||||
const backedUpVersion = executableVersion(await readFile(join(backup, GAME_FILES.executable)));
|
if (!await exists(backupExe)) return { path: copyFolder, refresh: await exists(backup) };
|
||||||
return version !== null && backedUpVersion !== version ? { path: copyFolder, refresh: true } : { path: backup, refresh: false };
|
let backedUpVersion: string | null = null;
|
||||||
|
try {
|
||||||
|
backedUpVersion = executableVersion(await readFile(backupExe));
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[stock-backup] unreadable backed-up executable, will refresh:', backupExe, error);
|
||||||
|
return { path: copyFolder, refresh: true };
|
||||||
|
}
|
||||||
|
return backedUpVersion === null || (version !== null && backedUpVersion !== version)
|
||||||
|
? { path: copyFolder, refresh: true }
|
||||||
|
: { path: backup, refresh: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function refreshStockBackup(copyFolder: string): Promise<string> {
|
export async function refreshStockBackup(copyFolder: string): Promise<string> {
|
||||||
|
return refreshStockBackupFrom(copyFolder, copyFolder);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replace wtoffline/stock atomically with the four stock files from `sourceFolder`. */
|
||||||
|
export async function refreshStockBackupFrom(copyFolder: string, sourceFolder: string): Promise<string> {
|
||||||
const backup = await requireStockBackupLocation(copyFolder);
|
const backup = await requireStockBackupLocation(copyFolder);
|
||||||
return await changeCopyFiles(copyFolder, async (incoming) => {
|
return await changeCopyFiles(copyFolder, async (incoming) => {
|
||||||
const replace = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
|
const replace = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
|
||||||
for (const file of Object.values(GAME_FILES)) {
|
for (const file of Object.values(GAME_FILES)) {
|
||||||
const target = join(incoming, STOCK_BACKUP_FOLDER, file);
|
const target = join(incoming, STOCK_BACKUP_FOLDER, file);
|
||||||
await mkdir(dirname(target), { recursive: true });
|
await mkdir(dirname(target), { recursive: true });
|
||||||
await copyFile(join(copyFolder, file), target);
|
await copyFile(join(sourceFolder, file), target);
|
||||||
}
|
}
|
||||||
return { replace, remove: [] };
|
return { replace, remove: [] };
|
||||||
}, async () => backup);
|
}, async () => backup);
|
||||||
|
|||||||
@@ -1,12 +1,22 @@
|
|||||||
import { execFile, spawn } from 'node:child_process';
|
import { execFile, spawn } from 'node:child_process';
|
||||||
import { join } from 'node:path';
|
import { constants } from 'node:fs';
|
||||||
|
import { access, lstat, open, readdir } from 'node:fs/promises';
|
||||||
|
import { dirname, join } from 'node:path';
|
||||||
import { promisify } from 'node:util';
|
import { promisify } from 'node:util';
|
||||||
import { GAME_FILES } from '@wto/patcher';
|
import { GAME_FILES } from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import offlineGameArguments from '@shared/offline-game-arguments.json';
|
import offlineGameArguments from '@shared/offline-game-arguments.json';
|
||||||
import type { GameExit } from '@shared/schemas/launch.ts';
|
import { formatExitCode, type GameExit } from '@shared/schemas/launch.ts';
|
||||||
|
|
||||||
const execute = promisify(execFile);
|
const execute = promisify(execFile);
|
||||||
|
const HOOK_DLL_FILENAME = 'wto_ws.dll';
|
||||||
|
const HOOK_CFG_FILENAME = 'wto_ws.cfg';
|
||||||
|
const HOOK_LOG_FILENAME = 'wto_ws.log';
|
||||||
|
const HOOK_LOG_TAIL_BYTES = 8 * 1024;
|
||||||
|
const HOOK_LOG_TAIL_LINES = 8;
|
||||||
|
const HOOK_LOG_LINE_LIMIT = 200;
|
||||||
|
/** Allow small filesystem timestamp skew when matching newly created .game_logs entries. */
|
||||||
|
const MTIME_SKEW_MS = 2000;
|
||||||
|
|
||||||
export async function gameProcessRunning(signal: AbortSignal): Promise<boolean> {
|
export async function gameProcessRunning(signal: AbortSignal): Promise<boolean> {
|
||||||
if (process.platform !== 'win32') return false;
|
if (process.platform !== 'win32') return false;
|
||||||
@@ -18,8 +28,13 @@ export async function runGameProcess(
|
|||||||
copyPath: string, additionalArguments: readonly string[], signal: AbortSignal, onStart: () => void,
|
copyPath: string, additionalArguments: readonly string[], signal: AbortSignal, onStart: () => void,
|
||||||
): Promise<GameExit> {
|
): Promise<GameExit> {
|
||||||
if (await gameProcessRunning(signal)) throw new AppError('launch_game_running');
|
if (await gameProcessRunning(signal)) throw new AppError('launch_game_running');
|
||||||
|
await verifyLaunchFiles(copyPath);
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
const child = spawn(join(copyPath, GAME_FILES.executable), [...offlineGameArguments, ...additionalArguments], {
|
const executable = join(copyPath, GAME_FILES.executable);
|
||||||
|
const args = [...offlineGameArguments, ...additionalArguments];
|
||||||
|
const startedAt = Date.now();
|
||||||
|
console.info('[game] starting:', executable, args);
|
||||||
|
const child = spawn(executable, args, {
|
||||||
cwd: copyPath, shell: false, stdio: 'ignore',
|
cwd: copyPath, shell: false, stdio: 'ignore',
|
||||||
});
|
});
|
||||||
const stop = (): void => { child.kill(); };
|
const stop = (): void => { child.kill(); };
|
||||||
@@ -27,6 +42,7 @@ export async function runGameProcess(
|
|||||||
try {
|
try {
|
||||||
return await new Promise<GameExit>((resolve, reject) => {
|
return await new Promise<GameExit>((resolve, reject) => {
|
||||||
child.once('spawn', () => {
|
child.once('spawn', () => {
|
||||||
|
console.info('[game] process started, pid:', child.pid ?? 'unknown');
|
||||||
if (signal.aborted) stop();
|
if (signal.aborted) stop();
|
||||||
else onStart();
|
else onStart();
|
||||||
});
|
});
|
||||||
@@ -36,9 +52,16 @@ export async function runGameProcess(
|
|||||||
});
|
});
|
||||||
child.once('close', (code, reason) => {
|
child.once('close', (code, reason) => {
|
||||||
const logFolder = join(copyPath, '.game_logs');
|
const logFolder = join(copyPath, '.game_logs');
|
||||||
|
const elapsedMs = Date.now() - startedAt;
|
||||||
|
const summary = code !== null ? formatExitCode(code) : (reason ?? 'unknown');
|
||||||
if (code !== 0 && !signal.aborted) {
|
if (code !== 0 && !signal.aborted) {
|
||||||
console.warn('[game] process exited:', code ?? reason, logFolder);
|
console.warn('[game] process exited:', summary, `after ${elapsedMs} ms`, logFolder);
|
||||||
|
void logAbnormalExitContext(copyPath, startedAt)
|
||||||
|
.catch((error: unknown) => console.warn('[game] inspecting post-exit files failed:', error))
|
||||||
|
.finally(() => resolve({ code, signal: reason, logFolder }));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
console.info('[game] process exited:', summary, `after ${elapsedMs} ms`);
|
||||||
resolve({ code, signal: reason, logFolder });
|
resolve({ code, signal: reason, logFolder });
|
||||||
});
|
});
|
||||||
signal.addEventListener('abort', stop, { once: true });
|
signal.addEventListener('abort', stop, { once: true });
|
||||||
@@ -47,3 +70,103 @@ export async function runGameProcess(
|
|||||||
signal.removeEventListener('abort', stop);
|
signal.removeEventListener('abort', stop);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Verify the patched executable and hook files are still present and readable right before spawn. */
|
||||||
|
async function verifyLaunchFiles(copyPath: string): Promise<void> {
|
||||||
|
const exeFolder = dirname(GAME_FILES.executable);
|
||||||
|
const required = [
|
||||||
|
GAME_FILES.executable,
|
||||||
|
join(exeFolder, HOOK_DLL_FILENAME),
|
||||||
|
join(exeFolder, HOOK_CFG_FILENAME),
|
||||||
|
];
|
||||||
|
const missing: string[] = [];
|
||||||
|
for (const relativePath of required) {
|
||||||
|
const fullPath = join(copyPath, relativePath);
|
||||||
|
try {
|
||||||
|
const stats = await lstat(fullPath);
|
||||||
|
if (!stats.isFile() || stats.size === 0) {
|
||||||
|
missing.push(`${relativePath} (not a non-empty file)`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await access(fullPath, constants.R_OK);
|
||||||
|
} catch (error) {
|
||||||
|
const code = (error as NodeJS.ErrnoException).code ?? 'error';
|
||||||
|
missing.push(`${relativePath} (${code})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (missing.length > 0) {
|
||||||
|
console.error('[game] required launch files unavailable before start:', missing.join(', '));
|
||||||
|
throw new AppError('launch_game_files_missing');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Record a compact read-only snapshot of hook and game log files after an unexpected non-zero exit. */
|
||||||
|
async function logAbnormalExitContext(copyPath: string, startedAt: number): Promise<void> {
|
||||||
|
const exeFolder = join(copyPath, dirname(GAME_FILES.executable));
|
||||||
|
const [dllState, cfgState, hookLogStat, newGameLogs] = await Promise.all([
|
||||||
|
describeFile(join(exeFolder, HOOK_DLL_FILENAME)),
|
||||||
|
describeFile(join(exeFolder, HOOK_CFG_FILENAME)),
|
||||||
|
safeRegularStat(join(exeFolder, HOOK_LOG_FILENAME)),
|
||||||
|
listNewGameLogs(join(copyPath, '.game_logs'), startedAt),
|
||||||
|
]);
|
||||||
|
const hookLogDesc = hookLogStat
|
||||||
|
? `${hookLogStat.size} bytes (${hookLogStat.mtimeMs >= startedAt - MTIME_SKEW_MS ? 'updated' : 'stale'})`
|
||||||
|
: 'missing';
|
||||||
|
console.warn(
|
||||||
|
`[game] post-exit check: ${HOOK_DLL_FILENAME}=${dllState}, ${HOOK_CFG_FILENAME}=${cfgState}, ` +
|
||||||
|
`${HOOK_LOG_FILENAME}=${hookLogDesc}, newGameLogs=${newGameLogs}`,
|
||||||
|
);
|
||||||
|
if (hookLogStat && hookLogStat.size > 0) {
|
||||||
|
const tail = await readTailLines(join(exeFolder, HOOK_LOG_FILENAME), hookLogStat.size);
|
||||||
|
if (tail.length > 0) {
|
||||||
|
console.warn(`[game] ${HOOK_LOG_FILENAME} tail:\n ${tail.join('\n ')}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function describeFile(path: string): Promise<string> {
|
||||||
|
const stats = await safeRegularStat(path);
|
||||||
|
return stats ? `${stats.size} bytes` : 'missing';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function safeRegularStat(path: string) {
|
||||||
|
try {
|
||||||
|
const stats = await lstat(path);
|
||||||
|
return stats.isFile() ? stats : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function listNewGameLogs(folder: string, startedAt: number): Promise<string> {
|
||||||
|
try {
|
||||||
|
const entries = await readdir(folder, { withFileTypes: true });
|
||||||
|
const recent: string[] = [];
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!entry.isFile()) continue;
|
||||||
|
const stats = await safeRegularStat(join(folder, entry.name));
|
||||||
|
if (!stats || stats.mtimeMs < startedAt - MTIME_SKEW_MS) continue;
|
||||||
|
recent.push(`${entry.name} (${stats.size} bytes)`);
|
||||||
|
}
|
||||||
|
return recent.length > 0 ? recent.slice(0, 6).join(', ') : 'none';
|
||||||
|
} catch {
|
||||||
|
return 'unavailable';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readTailLines(path: string, fileSize: number): Promise<string[]> {
|
||||||
|
const length = Math.min(fileSize, HOOK_LOG_TAIL_BYTES);
|
||||||
|
const start = fileSize - length;
|
||||||
|
const handle = await open(path, 'r');
|
||||||
|
try {
|
||||||
|
const buffer = Buffer.alloc(length);
|
||||||
|
const { bytesRead } = await handle.read(buffer, 0, length, start);
|
||||||
|
const text = buffer.subarray(0, bytesRead).toString('utf8');
|
||||||
|
const lines = text.split(/\r?\n/).filter((line) => line.length > 0);
|
||||||
|
return lines.slice(-HOOK_LOG_TAIL_LINES).map((line) => (
|
||||||
|
line.length > HOOK_LOG_LINE_LIMIT ? `${line.slice(0, HOOK_LOG_LINE_LIMIT)}…` : line
|
||||||
|
));
|
||||||
|
} finally {
|
||||||
|
await handle.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import type { Settings } from '@shared/schemas/settings.ts';
|
|||||||
import { getSettings } from '../config/settings-store.ts';
|
import { getSettings } from '../config/settings-store.ts';
|
||||||
import { decalCachePath } from '../install/decals.ts';
|
import { decalCachePath } from '../install/decals.ts';
|
||||||
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
|
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
|
||||||
|
import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts';
|
||||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||||
import { saveBackup } from '../saves/save-archive.ts';
|
import { saveBackup } from '../saves/save-archive.ts';
|
||||||
import { buildCopy } from './build-copy.ts';
|
import { buildCopy } from './build-copy.ts';
|
||||||
@@ -108,8 +109,8 @@ async function launch(job: LaunchJob): Promise<void> {
|
|||||||
job.copyId = record.id;
|
job.copyId = record.id;
|
||||||
const plan = await planLaunch(job, record, settings);
|
const plan = await planLaunch(job, record, settings);
|
||||||
if (plan === null) return;
|
if (plan === null) return;
|
||||||
const { lab, copyPath, stockPath, dataPath, port } = plan;
|
const { lab, copyPath, stockPath, dataPath, port, modsDir, enabledModIds } = plan;
|
||||||
await buildForLaunch(job, record, plan, settings.autoSaveBackups);
|
await buildForLaunch(job, record, plan, settings);
|
||||||
|
|
||||||
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
|
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
|
||||||
if (signal.aborted) return;
|
if (signal.aborted) return;
|
||||||
@@ -123,7 +124,15 @@ async function launch(job: LaunchJob): Promise<void> {
|
|||||||
update(job, { phase: 'ready' });
|
update(job, { phase: 'ready' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const gameExit = await runOrdinaryLaunch(copyPath, dataPath, port, settings, signal, publish);
|
const gameExit = await runOrdinaryLaunch(
|
||||||
|
copyPath,
|
||||||
|
dataPath,
|
||||||
|
port,
|
||||||
|
settings,
|
||||||
|
signal,
|
||||||
|
publish,
|
||||||
|
{ modsDir, enabledModIds },
|
||||||
|
);
|
||||||
update(job, { phase: 'game-exited', gameExit });
|
update(job, { phase: 'game-exited', gameExit });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,6 +143,8 @@ interface LaunchPlan {
|
|||||||
readonly dataPath: string;
|
readonly dataPath: string;
|
||||||
readonly steamLibraryConfirmed: boolean;
|
readonly steamLibraryConfirmed: boolean;
|
||||||
readonly port: number;
|
readonly port: number;
|
||||||
|
readonly modsDir: string;
|
||||||
|
readonly enabledModIds: readonly string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
|
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
|
||||||
@@ -144,6 +155,10 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
|
|||||||
}
|
}
|
||||||
const currentVersion = await readVersion(record.copyPath, signal);
|
const currentVersion = await readVersion(record.copyPath, signal);
|
||||||
if (!currentVersion || currentVersion !== record.gameVersion) {
|
if (!currentVersion || currentVersion !== record.gameVersion) {
|
||||||
|
console.warn(
|
||||||
|
`[launch] client version changed: recorded=${record.gameVersion ?? 'unknown'}, ` +
|
||||||
|
`actual=${currentVersion ?? 'missing'} (${record.copyPath})`,
|
||||||
|
);
|
||||||
update(job, { phase: 'version-changed', actualVersion: currentVersion });
|
update(job, { phase: 'version-changed', actualVersion: currentVersion });
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -171,17 +186,24 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
|
|||||||
]);
|
]);
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
if (!copyVersion || copyVersion !== stockVersion) {
|
if (!copyVersion || copyVersion !== stockVersion) {
|
||||||
|
console.warn(
|
||||||
|
`[launch] copy/stock version mismatch: copy=${copyVersion ?? 'missing'} (${copyPath}), ` +
|
||||||
|
`stock=${stockVersion ?? 'missing'} (${stockPath})`,
|
||||||
|
);
|
||||||
|
if (!lab && !stockVersion) throw new AppError('launch_stock_missing');
|
||||||
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
|
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
|
||||||
}
|
}
|
||||||
if (games) throw new AppError('launch_game_running');
|
if (games) throw new AppError('launch_game_running');
|
||||||
|
const { modsDir, enabledMods } = await resolveEnabledModsForLaunch(dataPath, copyVersion);
|
||||||
|
const enabledModIds = enabledMods.map((mod) => mod.manifest.id);
|
||||||
const port = await selectPort(requestedPort);
|
const port = await selectPort(requestedPort);
|
||||||
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port };
|
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port, modsDir, enabledModIds };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, autoSaveBackups: boolean): Promise<void> {
|
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
|
||||||
const signal = job.stop.signal;
|
const signal = job.stop.signal;
|
||||||
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan;
|
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed, modsDir, enabledModIds } = plan;
|
||||||
if (autoSaveBackups) {
|
if (settings.autoSaveBackups) {
|
||||||
for (const { userId } of new AccountStore(dataPath).all()) {
|
for (const { userId } of new AccountStore(dataPath).all()) {
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
await saveBackup({ ...record, dataPath }, userId, 'launch');
|
await saveBackup({ ...record, dataPath }, userId, 'launch');
|
||||||
@@ -189,6 +211,8 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
|
|||||||
}
|
}
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
update(job, { phase: 'building', port });
|
update(job, { phase: 'building', port });
|
||||||
|
const buildStart = Date.now();
|
||||||
|
let writtenFiles = 0;
|
||||||
await buildCopy({
|
await buildCopy({
|
||||||
kind: 'build',
|
kind: 'build',
|
||||||
stockPath,
|
stockPath,
|
||||||
@@ -198,12 +222,17 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
|
|||||||
steamLibraryConfirmed,
|
steamLibraryConfirmed,
|
||||||
...resourcePaths(),
|
...resourcePaths(),
|
||||||
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
|
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
|
||||||
|
hookLogging: settings.loggingEnabled,
|
||||||
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
|
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
|
||||||
|
modsDir,
|
||||||
|
enabledModIds,
|
||||||
}, signal, (filesWritten, filesTotal, file) => {
|
}, signal, (filesWritten, filesTotal, file) => {
|
||||||
|
writtenFiles = filesWritten;
|
||||||
if (!signal.aborted) update(job, {
|
if (!signal.aborted) update(job, {
|
||||||
phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
|
phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
console.info(`[launch] prepared ${writtenFiles} game files for port ${port} in ${Date.now() - buildStart} ms`);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function readVersion(folder: string, signal: AbortSignal): Promise<string | null> {
|
async function readVersion(folder: string, signal: AbortSignal): Promise<string | null> {
|
||||||
|
|||||||
@@ -33,14 +33,27 @@ export async function localServerReady(port: number, pid?: number, signal?: Abor
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface StartLocalServerOptions extends Omit<ServerOptions, 'report' | 'mods'> {
|
||||||
|
readonly modsDir?: string;
|
||||||
|
readonly enabledModIds?: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
export async function startLocalServer(
|
export async function startLocalServer(
|
||||||
{ gameFolder, dataFolder, port }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
|
{ gameFolder, dataFolder, port, loggingEnabled = true, modsDir, enabledModIds }: StartLocalServerOptions, signal: AbortSignal,
|
||||||
): Promise<LocalServer> {
|
): Promise<LocalServer> {
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
const worker = utilityProcess.fork(join(import.meta.dirname, 'server-worker.js'), [gameFolder, dataFolder, String(port)], {
|
const workerArgs = [gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'];
|
||||||
serviceName: 'WTOffline local server',
|
if (modsDir && enabledModIds && enabledModIds.length > 0) {
|
||||||
stdio: 'pipe',
|
workerArgs.push(modsDir, JSON.stringify(enabledModIds));
|
||||||
});
|
}
|
||||||
|
const worker = utilityProcess.fork(
|
||||||
|
join(import.meta.dirname, 'server-worker.js'),
|
||||||
|
workerArgs,
|
||||||
|
{
|
||||||
|
serviceName: 'WTOffline local server',
|
||||||
|
stdio: 'pipe',
|
||||||
|
},
|
||||||
|
);
|
||||||
forwardProcessOutput(worker.stdout, 'server', 'info');
|
forwardProcessOutput(worker.stdout, 'server', 'info');
|
||||||
forwardProcessOutput(worker.stderr, 'server', 'error');
|
forwardProcessOutput(worker.stderr, 'server', 'error');
|
||||||
|
|
||||||
|
|||||||
@@ -45,11 +45,21 @@ type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-r
|
|||||||
export async function runOrdinaryLaunch(
|
export async function runOrdinaryLaunch(
|
||||||
copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal,
|
copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal,
|
||||||
publish: (phase: OrdinaryPhase, gameExit?: GameExit) => void,
|
publish: (phase: OrdinaryPhase, gameExit?: GameExit) => void,
|
||||||
|
mods?: { readonly modsDir: string; readonly enabledModIds: readonly string[] },
|
||||||
): Promise<GameExit> {
|
): Promise<GameExit> {
|
||||||
const args = parseLaunchArguments(settings.launchArguments);
|
const args = parseLaunchArguments(settings.launchArguments);
|
||||||
if (!args) throw new AppError('launch_game_failed');
|
if (!args) throw new AppError('launch_game_failed');
|
||||||
publish('starting-server');
|
publish('starting-server');
|
||||||
const server = await startLocalServer({ gameFolder: copyPath, dataFolder: dataPath, port }, signal);
|
const server = await startLocalServer(
|
||||||
|
{
|
||||||
|
gameFolder: copyPath,
|
||||||
|
dataFolder: dataPath,
|
||||||
|
port,
|
||||||
|
loggingEnabled: settings.loggingEnabled,
|
||||||
|
...(mods && mods.enabledModIds.length > 0 ? { modsDir: mods.modsDir, enabledModIds: mods.enabledModIds } : {}),
|
||||||
|
},
|
||||||
|
signal,
|
||||||
|
);
|
||||||
const stop = new AbortController();
|
const stop = new AbortController();
|
||||||
const runSignal = AbortSignal.any([signal, stop.signal]);
|
const runSignal = AbortSignal.any([signal, stop.signal]);
|
||||||
const serverExited = server.exited.then(() => { throw new AppError('launch_server_exited'); });
|
const serverExited = server.exited.then(() => { throw new AppError('launch_server_exited'); });
|
||||||
|
|||||||
@@ -0,0 +1,428 @@
|
|||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { access, cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
|
||||||
|
import { isAbsolute, join } from 'node:path';
|
||||||
|
import { app, BrowserWindow, dialog, shell } from 'electron';
|
||||||
|
import {
|
||||||
|
computeAutoSortOrder,
|
||||||
|
discoverMods,
|
||||||
|
emptyClientModsConfig,
|
||||||
|
MOD_API_VERSION,
|
||||||
|
normalizeClientModsConfig,
|
||||||
|
resolveModLoadOrder,
|
||||||
|
type ClientModsConfig,
|
||||||
|
type DiscoveredMod,
|
||||||
|
type ModPreset,
|
||||||
|
} from '@wto/mods';
|
||||||
|
import { AppError } from '@shared/errors.ts';
|
||||||
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||||
|
import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts';
|
||||||
|
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||||
|
import { getSettings, updateSettings } from '../config/settings-store.ts';
|
||||||
|
import { listCopies } from '../install/install-record.ts';
|
||||||
|
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||||
|
|
||||||
|
const CLIENT_MODS_CONFIG_FILE = 'mods-config.json';
|
||||||
|
const EXAMPLES_SEEDED_MARKER = '.wto-examples-seeded';
|
||||||
|
const inFlightSeeds = new Map<string, Promise<void>>();
|
||||||
|
|
||||||
|
export function defaultModsFolder(): string {
|
||||||
|
return join(app.getPath('userData'), 'mods');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resolveModsFolder(): Promise<{ readonly modsDir: string; readonly defaultModsDir: string; readonly isCustomModsDir: boolean }> {
|
||||||
|
const settings = await getSettings();
|
||||||
|
const defaultModsDir = defaultModsFolder();
|
||||||
|
const isCustomModsDir = settings.modsFolder !== null;
|
||||||
|
const modsDir = settings.modsFolder ?? defaultModsDir;
|
||||||
|
await mkdir(modsDir, { recursive: true });
|
||||||
|
await seedBundledExampleModsOnce(modsDir);
|
||||||
|
return { modsDir, defaultModsDir, isCustomModsDir };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copy newly shipped bundled template mods into the mods folder once each (disabled by default).
|
||||||
|
* Tracks which template folder names have already been seeded in `.wto-examples-seeded` so
|
||||||
|
* deleting a bundled template never restores it, while newly added official templates still
|
||||||
|
* appear for existing users. Serialized per directory to prevent concurrent seeding races.
|
||||||
|
*/
|
||||||
|
async function seedBundledExampleModsOnce(modsDir: string): Promise<void> {
|
||||||
|
const key = modsDir.toLowerCase();
|
||||||
|
const pending = inFlightSeeds.get(key);
|
||||||
|
if (pending) {
|
||||||
|
await pending;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const task = (async () => {
|
||||||
|
const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER);
|
||||||
|
try {
|
||||||
|
const templatesRoot = resourcePaths().modTemplates;
|
||||||
|
if (!(await pathExists(templatesRoot))) return;
|
||||||
|
const seeded = await readSeededTemplateNames(markerPath, modsDir);
|
||||||
|
const templates = await readdir(templatesRoot, { withFileTypes: true });
|
||||||
|
let changed = false;
|
||||||
|
for (const entry of templates) {
|
||||||
|
if (!entry.isDirectory()) continue;
|
||||||
|
if (seeded.has(entry.name)) continue;
|
||||||
|
const dest = join(modsDir, entry.name);
|
||||||
|
if (!(await pathExists(dest))) {
|
||||||
|
await cp(join(templatesRoot, entry.name), dest, { recursive: true });
|
||||||
|
}
|
||||||
|
seeded.add(entry.name);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (changed || !(await pathExists(markerPath))) {
|
||||||
|
await writeFile(markerPath, JSON.stringify({ seeded: [...seeded].sort() }, null, 2) + '\n', 'utf8');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[mods] seeding bundled example mods skipped:', error);
|
||||||
|
}
|
||||||
|
})().finally(() => {
|
||||||
|
inFlightSeeds.delete(key);
|
||||||
|
});
|
||||||
|
inFlightSeeds.set(key, task);
|
||||||
|
await task;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readSeededTemplateNames(markerPath: string, modsDir: string): Promise<Set<string>> {
|
||||||
|
if (!(await pathExists(markerPath))) return new Set();
|
||||||
|
try {
|
||||||
|
const raw = (await readFile(markerPath, 'utf8')).trim();
|
||||||
|
if (raw === '1') {
|
||||||
|
// Legacy marker from initial 2-template version: mark existing folders as already seeded
|
||||||
|
// so newly added official templates (e.g. official-map-selector) are still delivered once.
|
||||||
|
const existing = await readdir(modsDir);
|
||||||
|
const set = new Set(['example-vehicle-tweak', 'example-server-script']);
|
||||||
|
for (const name of existing) set.add(name);
|
||||||
|
return set;
|
||||||
|
}
|
||||||
|
const parsed = JSON.parse(raw) as { seeded?: unknown };
|
||||||
|
if (Array.isArray(parsed.seeded)) {
|
||||||
|
return new Set(parsed.seeded.filter((item): item is string => typeof item === 'string'));
|
||||||
|
}
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
return new Set();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pathExists(path: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
await access(path);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function openModsFolder(): Promise<void> {
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const failure = await shell.openPath(modsDir);
|
||||||
|
if (failure) console.warn('[mods] opening the mods folder failed:', modsDir, failure);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getModsState(copyId: string): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
return buildModsStateView(copy);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setModEnabled(copyId: string, modId: string, enabled: boolean): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||||
|
const next: ClientModsConfig = {
|
||||||
|
...current,
|
||||||
|
activePresetId: null,
|
||||||
|
enabled: { ...current.enabled, [modId]: enabled },
|
||||||
|
};
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return buildModsStateView(copy, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setModsOrder(copyId: string, order: readonly string[]): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||||
|
const next = normalizeClientModsConfig({ ...current, activePresetId: null, order }, discovered.mods);
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return buildModsStateView(copy, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function autoSortMods(copyId: string): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||||
|
const sortedOrder = computeAutoSortOrder(discovered.mods, current.order);
|
||||||
|
const next: ClientModsConfig = {
|
||||||
|
...current,
|
||||||
|
activePresetId: null,
|
||||||
|
order: sortedOrder,
|
||||||
|
};
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return buildModsStateView(copy, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveModPreset(copyId: string, name: string, overwriteId?: string): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
let presets: ModPreset[];
|
||||||
|
let presetId: string;
|
||||||
|
if (overwriteId && current.presets.some((preset) => preset.id === overwriteId)) {
|
||||||
|
presetId = overwriteId;
|
||||||
|
presets = current.presets.map((preset) => (
|
||||||
|
preset.id === overwriteId
|
||||||
|
? { id: preset.id, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now }
|
||||||
|
: preset
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
presetId = randomUUID();
|
||||||
|
presets = [
|
||||||
|
...current.presets,
|
||||||
|
{ id: presetId, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const next: ClientModsConfig = {
|
||||||
|
...current,
|
||||||
|
activePresetId: presetId,
|
||||||
|
presets,
|
||||||
|
};
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return buildModsStateView(copy, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function applyModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||||
|
const preset = current.presets.find((item) => item.id === presetId);
|
||||||
|
if (!preset) throw new AppError('mods_preset_invalid');
|
||||||
|
|
||||||
|
const next = normalizeClientModsConfig({
|
||||||
|
...current,
|
||||||
|
order: preset.order,
|
||||||
|
enabled: preset.enabled,
|
||||||
|
activePresetId: preset.id,
|
||||||
|
}, discovered.mods);
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return buildModsStateView(copy, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const current = await readClientModsConfig(copy.dataPath);
|
||||||
|
const next: ClientModsConfig = {
|
||||||
|
...current,
|
||||||
|
activePresetId: current.activePresetId === presetId ? null : current.activePresetId,
|
||||||
|
presets: current.presets.filter((preset) => preset.id !== presetId),
|
||||||
|
};
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return buildModsStateView(copy, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function exportModPreset(
|
||||||
|
copyId: string,
|
||||||
|
presetId: string,
|
||||||
|
window: BrowserWindow | null,
|
||||||
|
): Promise<{ readonly path: string | null }> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const current = await readClientModsConfig(copy.dataPath);
|
||||||
|
const preset = current.presets.find((item) => item.id === presetId);
|
||||||
|
if (!preset) throw new AppError('mods_preset_invalid');
|
||||||
|
|
||||||
|
const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset';
|
||||||
|
const dialogOptions = {
|
||||||
|
defaultPath: `${safeName}.wto-mods-preset.json`,
|
||||||
|
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
|
||||||
|
};
|
||||||
|
const choice = window
|
||||||
|
? await dialog.showSaveDialog(window, dialogOptions)
|
||||||
|
: await dialog.showSaveDialog(dialogOptions);
|
||||||
|
if (choice.canceled || !choice.filePath) return { path: null };
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
format: 1 as const,
|
||||||
|
name: preset.name,
|
||||||
|
order: [...preset.order],
|
||||||
|
enabled: { ...preset.enabled },
|
||||||
|
};
|
||||||
|
await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
|
||||||
|
return { path: choice.filePath };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function importModPreset(
|
||||||
|
copyId: string,
|
||||||
|
window: BrowserWindow | null,
|
||||||
|
): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const dialogOptions = {
|
||||||
|
properties: ['openFile'] as Array<'openFile'>,
|
||||||
|
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
|
||||||
|
};
|
||||||
|
const choice = window
|
||||||
|
? await dialog.showOpenDialog(window, dialogOptions)
|
||||||
|
: await dialog.showOpenDialog(dialogOptions);
|
||||||
|
if (choice.canceled || !choice.filePaths[0]) {
|
||||||
|
return { imported: false, state: await buildModsStateView(copy) };
|
||||||
|
}
|
||||||
|
|
||||||
|
let parsedRaw: unknown;
|
||||||
|
try {
|
||||||
|
parsedRaw = JSON.parse(await readFile(choice.filePaths[0], 'utf8')) as unknown;
|
||||||
|
} catch {
|
||||||
|
throw new AppError('mods_preset_invalid');
|
||||||
|
}
|
||||||
|
const validated = ModPresetTransferSchema.safeParse(parsedRaw);
|
||||||
|
if (!validated.success) throw new AppError('mods_preset_invalid');
|
||||||
|
|
||||||
|
const current = await readClientModsConfig(copy.dataPath);
|
||||||
|
const newPreset: ModPreset = {
|
||||||
|
id: randomUUID(),
|
||||||
|
name: validated.data.name,
|
||||||
|
order: validated.data.order,
|
||||||
|
enabled: validated.data.enabled,
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
const next: ClientModsConfig = {
|
||||||
|
...current,
|
||||||
|
presets: [...current.presets, newPreset],
|
||||||
|
};
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return { imported: true, state: await buildModsStateView(copy, next) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setModsFolder(copyId: string, folderPath: string | null): Promise<ModsStateView> {
|
||||||
|
if (folderPath !== null) {
|
||||||
|
if (!isAbsolute(folderPath)) throw new AppError('mods_folder_invalid');
|
||||||
|
try {
|
||||||
|
await mkdir(folderPath, { recursive: true });
|
||||||
|
const info = await stat(folderPath);
|
||||||
|
if (!info.isDirectory()) throw new AppError('mods_folder_invalid');
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AppError) throw error;
|
||||||
|
throw new AppError('mods_folder_invalid');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await updateSettings({ modsFolder: folderPath });
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
return buildModsStateView(copy);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve ordered enabled mods for a launch; rejects when blocking dependency/conflict errors exist. */
|
||||||
|
export async function resolveEnabledModsForLaunch(
|
||||||
|
dataPath: string,
|
||||||
|
gameVersion: string | null,
|
||||||
|
): Promise<{ readonly modsDir: string; readonly enabledMods: readonly DiscoveredMod[] }> {
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const config = normalizeClientModsConfig(await readClientModsConfig(dataPath), discovered.mods);
|
||||||
|
const resolved = resolveModLoadOrder(discovered.mods, config, gameVersion);
|
||||||
|
if (resolved.hasBlockingErrors) {
|
||||||
|
console.error('[mods] blocking mod issues prevented launch:', resolved.issues.filter((i) => i.severity === 'error'));
|
||||||
|
throw new AppError('mods_blocking_issues');
|
||||||
|
}
|
||||||
|
return { modsDir, enabledMods: resolved.enabledMods };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildModsStateView(copy: InstallRecord, preloadedConfig?: ClientModsConfig): Promise<ModsStateView> {
|
||||||
|
const { modsDir, defaultModsDir, isCustomModsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const rawConfig = preloadedConfig ?? await readClientModsConfig(copy.dataPath);
|
||||||
|
const config = normalizeClientModsConfig(rawConfig, discovered.mods);
|
||||||
|
const resolved = resolveModLoadOrder(discovered.mods, config, copy.gameVersion);
|
||||||
|
|
||||||
|
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
||||||
|
const orderedMods: ModListItem[] = config.order
|
||||||
|
.map((id) => byId.get(id))
|
||||||
|
.filter((mod): mod is DiscoveredMod => mod !== undefined)
|
||||||
|
.map(toModListItem);
|
||||||
|
|
||||||
|
return {
|
||||||
|
modsDir,
|
||||||
|
defaultModsDir,
|
||||||
|
isCustomModsDir,
|
||||||
|
apiVersion: MOD_API_VERSION,
|
||||||
|
mods: orderedMods,
|
||||||
|
discoveryErrors: [...discovered.errors],
|
||||||
|
order: [...config.order],
|
||||||
|
enabled: { ...config.enabled },
|
||||||
|
activePresetId: config.activePresetId,
|
||||||
|
presets: config.presets.map((preset) => ({
|
||||||
|
id: preset.id,
|
||||||
|
name: preset.name,
|
||||||
|
order: [...preset.order],
|
||||||
|
enabled: { ...preset.enabled },
|
||||||
|
updatedAt: preset.updatedAt,
|
||||||
|
})),
|
||||||
|
issues: [...resolved.issues],
|
||||||
|
hasBlockingErrors: resolved.hasBlockingErrors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toModListItem(mod: DiscoveredMod): ModListItem {
|
||||||
|
return {
|
||||||
|
id: mod.manifest.id,
|
||||||
|
folderName: mod.folderName,
|
||||||
|
rootDir: mod.rootDir,
|
||||||
|
name: mod.manifest.name,
|
||||||
|
...(mod.manifest.description !== undefined ? { description: mod.manifest.description } : {}),
|
||||||
|
version: mod.manifest.version,
|
||||||
|
author: mod.manifest.author,
|
||||||
|
apiVersion: mod.manifest.apiVersion,
|
||||||
|
gameVersions: [...mod.manifest.gameVersions],
|
||||||
|
requires: [...mod.manifest.requires],
|
||||||
|
conflicts: [...mod.manifest.conflicts],
|
||||||
|
loadAfter: [...mod.manifest.loadAfter],
|
||||||
|
loadBefore: [...mod.manifest.loadBefore],
|
||||||
|
badges: [...mod.content.badges],
|
||||||
|
hasServerScript: mod.content.serverEntry !== undefined,
|
||||||
|
serverTuningFiles: [...mod.content.serverTuningFiles],
|
||||||
|
packOperations: [...mod.content.packOperations],
|
||||||
|
guiPatchCount: mod.content.guiPatchDirs.length,
|
||||||
|
exePatchCount: mod.content.exePatchDirs.length,
|
||||||
|
hasClientAddon: mod.content.hasClientAddon,
|
||||||
|
addonFileCount: mod.content.addonRelativeFiles.length,
|
||||||
|
clientFileCount: mod.content.clientFiles.length,
|
||||||
|
hasConfigBlkPatch: mod.content.configBlkPatch !== undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requireCopy(copyId: string): Promise<InstallRecord> {
|
||||||
|
const copies = await listCopies();
|
||||||
|
const copy = copies.copies.find((entry) => entry.id === copyId);
|
||||||
|
if (!copy) throw new AppError('copy_not_found');
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readClientModsConfig(dataPath: string): Promise<ClientModsConfig> {
|
||||||
|
const path = join(dataPath, CLIENT_MODS_CONFIG_FILE);
|
||||||
|
try {
|
||||||
|
const raw = await readJsonOr(path, null);
|
||||||
|
if (!raw || typeof raw !== 'object') return emptyClientModsConfig();
|
||||||
|
const obj = raw as Partial<ClientModsConfig>;
|
||||||
|
return {
|
||||||
|
format: 1,
|
||||||
|
order: Array.isArray(obj.order) ? obj.order.filter((item): item is string => typeof item === 'string') : [],
|
||||||
|
enabled: obj.enabled && typeof obj.enabled === 'object' ? { ...obj.enabled } : {},
|
||||||
|
activePresetId: typeof obj.activePresetId === 'string' ? obj.activePresetId : null,
|
||||||
|
presets: Array.isArray(obj.presets) ? obj.presets : [],
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[mods] unreadable client mods config, using defaults:', path, error);
|
||||||
|
return emptyClientModsConfig();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function writeClientModsConfig(dataPath: string, config: ClientModsConfig): Promise<void> {
|
||||||
|
try {
|
||||||
|
await writeJsonAtomic(join(dataPath, CLIENT_MODS_CONFIG_FILE), config);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[mods] writing client mods config failed:', error);
|
||||||
|
throw new AppError('mods_write_failed');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
/**
|
/**
|
||||||
* The launcher and adaptation pack channels share an anonymous, GitHub-compatible release list.
|
* The launcher and adaptation pack channels share an anonymous, GitHub-compatible release list.
|
||||||
* The project repository is tried first, with an optional player-configured fallback.
|
* The primary release source is tried first, followed by any player-configured mirror and default fallbacks.
|
||||||
*/
|
*/
|
||||||
import { net } from 'electron';
|
import { net } from 'electron';
|
||||||
import {
|
import {
|
||||||
compareAppVersions, comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning,
|
compareAppVersions, comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning,
|
||||||
} from '@wto/patcher';
|
} from '@wto/patcher';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { AppReleaseVersionSchema, launcherReleaseFiles } from '@shared/schemas/app-update.ts';
|
import { AppReleaseVersionSchema, launcherReleaseFiles, portableLauncherReleaseFiles } from '@shared/schemas/app-update.ts';
|
||||||
import { releaseRepositoryUrl } from '@shared/update-source.ts';
|
import { releaseRepositoryUrl } from '@shared/update-source.ts';
|
||||||
import { getSettings } from '../config/settings-store.ts';
|
import { getSettings } from '../config/settings-store.ts';
|
||||||
import { FeedUnreachableError, UPDATE_USER_AGENT } from './release-assets.ts';
|
import { FeedUnreachableError, UPDATE_USER_AGENT } from './release-assets.ts';
|
||||||
@@ -17,6 +17,12 @@ export interface ReleaseSource {
|
|||||||
readonly githubDownloads: URL | null;
|
readonly githubDownloads: URL | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PortableReleaseAssets {
|
||||||
|
readonly archive: URL;
|
||||||
|
readonly manifest: URL;
|
||||||
|
readonly signature: URL;
|
||||||
|
}
|
||||||
|
|
||||||
export interface LauncherRelease {
|
export interface LauncherRelease {
|
||||||
readonly source: ReleaseSource;
|
readonly source: ReleaseSource;
|
||||||
readonly version: string;
|
readonly version: string;
|
||||||
@@ -24,6 +30,7 @@ export interface LauncherRelease {
|
|||||||
readonly installer: URL;
|
readonly installer: URL;
|
||||||
readonly manifest: URL;
|
readonly manifest: URL;
|
||||||
readonly signature: URL;
|
readonly signature: URL;
|
||||||
|
readonly portable?: PortableReleaseAssets;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PackReleaseFiles {
|
export interface PackReleaseFiles {
|
||||||
@@ -91,18 +98,35 @@ export function sameReleaseSource(a: ReleaseSource, b: ReleaseSource): boolean {
|
|||||||
export async function withReleaseSources<T>(
|
export async function withReleaseSources<T>(
|
||||||
read: (source: ReleaseSource) => Promise<T>, preferred?: ReleaseSource,
|
read: (source: ReleaseSource) => Promise<T>, preferred?: ReleaseSource,
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
const primary = releaseSource(new URL(`https://github.com/${patchPackTuning().repository}`));
|
const tuning = patchPackTuning();
|
||||||
const repository = releaseRepositoryUrl((await getSettings()).updateMirrorUrl);
|
const candidates: ReleaseSource[] = [];
|
||||||
const mirror = repository ? releaseSource(repository) : null;
|
const add = (url: URL | null): void => {
|
||||||
if (!mirror || sameReleaseSource(primary, mirror)) return read(primary);
|
if (!url) return;
|
||||||
const [first, second] = preferred && sameReleaseSource(preferred, mirror) ? [mirror, primary] : [primary, mirror];
|
const source = releaseSource(url);
|
||||||
try {
|
if (!candidates.some((existing) => sameReleaseSource(existing, source))) candidates.push(source);
|
||||||
return await read(first);
|
};
|
||||||
} catch (error) {
|
add(releaseRepositoryUrl(tuning.primarySource));
|
||||||
if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error;
|
add(releaseRepositoryUrl((await getSettings()).updateMirrorUrl));
|
||||||
console.info(`[release-feed] ${first.feed.hostname} was unavailable, trying ${second.feed.hostname}.`);
|
for (const fallback of tuning.fallbackSources) add(releaseRepositoryUrl(fallback));
|
||||||
return read(second);
|
if (candidates.length === 0) throw new FeedUnreachableError('No valid release sources are configured.');
|
||||||
|
|
||||||
|
const ordered = preferred
|
||||||
|
? [preferred, ...candidates.filter((source) => !sameReleaseSource(source, preferred))]
|
||||||
|
: candidates;
|
||||||
|
|
||||||
|
let lastError: unknown;
|
||||||
|
for (let index = 0; index < ordered.length; index += 1) {
|
||||||
|
const current = ordered[index]!;
|
||||||
|
try {
|
||||||
|
return await read(current);
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error;
|
||||||
|
lastError = error;
|
||||||
|
const next = ordered[index + 1];
|
||||||
|
if (next) console.info(`[release-feed] ${current.feed.hostname} was unavailable, trying ${next.feed.hostname}.`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
throw lastError;
|
||||||
}
|
}
|
||||||
|
|
||||||
function listingFor(source: ReleaseSource): Promise<ReleaseListing> {
|
function listingFor(source: ReleaseSource): Promise<ReleaseListing> {
|
||||||
@@ -226,12 +250,27 @@ function launcherRelease(entry: Record<string, unknown>, version: string, source
|
|||||||
if (!parsed.success) return null;
|
if (!parsed.success) return null;
|
||||||
const { assets, body } = parsed.data;
|
const { assets, body } = parsed.data;
|
||||||
const names = launcherReleaseFiles(version);
|
const names = launcherReleaseFiles(version);
|
||||||
|
const portableNames = portableLauncherReleaseFiles(version);
|
||||||
const urls = assetUrls(assets, `v${version}`, source);
|
const urls = assetUrls(assets, `v${version}`, source);
|
||||||
const installer = urls.get(names.installer);
|
const installer = urls.get(names.installer);
|
||||||
const manifest = urls.get(names.manifest);
|
const manifest = urls.get(names.manifest);
|
||||||
const signature = urls.get(names.signature);
|
const signature = urls.get(names.signature);
|
||||||
if (!installer || !manifest || !signature) return null;
|
if (!installer || !manifest || !signature) return null;
|
||||||
return { source, version, notes: body?.trim().slice(0, 1600) ?? '', installer, manifest, signature };
|
const portableArchive = urls.get(portableNames.archive);
|
||||||
|
const portableManifest = urls.get(portableNames.manifest);
|
||||||
|
const portableSignature = urls.get(portableNames.signature);
|
||||||
|
const portable = portableArchive && portableManifest && portableSignature
|
||||||
|
? { archive: portableArchive, manifest: portableManifest, signature: portableSignature }
|
||||||
|
: undefined;
|
||||||
|
return {
|
||||||
|
source,
|
||||||
|
version,
|
||||||
|
notes: body?.trim().slice(0, 1600) ?? '',
|
||||||
|
installer,
|
||||||
|
manifest,
|
||||||
|
signature,
|
||||||
|
...(portable ? { portable } : {}),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function packRelease(release: Record<string, unknown>, version: string, tag: string, source: ReleaseSource): PackReleaseFiles | null {
|
function packRelease(release: Record<string, unknown>, version: string, tag: string, source: ReleaseSource): PackReleaseFiles | null {
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ export interface ResourcePaths {
|
|||||||
readonly networkHookLibrary: string;
|
readonly networkHookLibrary: string;
|
||||||
/** Multi-resolution Windows icon for the window and system tray. */
|
/** Multi-resolution Windows icon for the window and system tray. */
|
||||||
readonly appIcon: string;
|
readonly appIcon: string;
|
||||||
|
/** Bundled example mod templates seeded into an empty mods folder on first use. */
|
||||||
|
readonly modTemplates: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resourcePaths(): ResourcePaths {
|
export function resourcePaths(): ResourcePaths {
|
||||||
@@ -32,6 +34,7 @@ export function bundledResourcePaths(): ResourcePaths {
|
|||||||
patches: join(process.resourcesPath, 'patches'),
|
patches: join(process.resourcesPath, 'patches'),
|
||||||
networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'),
|
networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'),
|
||||||
appIcon: join(process.resourcesPath, 'icon.ico'),
|
appIcon: join(process.resourcesPath, 'icon.ico'),
|
||||||
|
modTemplates: join(process.resourcesPath, 'mod-templates'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// The app path is apps/launcher; the repository is two levels up.
|
// The app path is apps/launcher; the repository is two levels up.
|
||||||
@@ -40,6 +43,7 @@ export function bundledResourcePaths(): ResourcePaths {
|
|||||||
patches: join(repository, 'patches'),
|
patches: join(repository, 'patches'),
|
||||||
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
|
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
|
||||||
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
|
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
|
||||||
|
modTemplates: join(repository, 'mod-dev-docs', 'templates'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,10 @@ export interface BuildRequest {
|
|||||||
readonly patches: string;
|
readonly patches: string;
|
||||||
readonly networkHookLibrary: string;
|
readonly networkHookLibrary: string;
|
||||||
readonly decalCache?: string;
|
readonly decalCache?: string;
|
||||||
|
readonly hookLogging: boolean;
|
||||||
readonly acceptedUnavailable: readonly string[];
|
readonly acceptedUnavailable: readonly string[];
|
||||||
|
readonly modsDir?: string;
|
||||||
|
readonly enabledModIds?: readonly string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export type BuildCommand = BuildRequest | { readonly kind: 'write' };
|
export type BuildCommand = BuildRequest | { readonly kind: 'write' };
|
||||||
|
|||||||
@@ -1,7 +1,21 @@
|
|||||||
import { readFileSync, realpathSync } from 'node:fs';
|
import { readFileSync, realpathSync } from 'node:fs';
|
||||||
import { relative } from 'node:path';
|
import { relative } from 'node:path';
|
||||||
import type { MessageEvent } from 'electron';
|
import type { MessageEvent } from 'electron';
|
||||||
import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCacheProblem, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher';
|
import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
|
||||||
|
import {
|
||||||
|
assertWritableCopy,
|
||||||
|
buildGameCopy,
|
||||||
|
computeModsBuildFingerprint,
|
||||||
|
copyPlayerDecalCache,
|
||||||
|
CORE_BUILD_PACKS,
|
||||||
|
playerDecalCacheProblem,
|
||||||
|
prepareOptionalStockPacks,
|
||||||
|
readPlayerDecalIndexFiles,
|
||||||
|
readStockGameFiles,
|
||||||
|
syncExternalModFiles,
|
||||||
|
writeGameCopy,
|
||||||
|
type GameCopyFile,
|
||||||
|
} from '@wto/patcher';
|
||||||
import { multiVehiclePackIds } from '@wto/server';
|
import { multiVehiclePackIds } from '@wto/server';
|
||||||
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
|
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
|
||||||
|
|
||||||
@@ -9,6 +23,9 @@ let prepared: {
|
|||||||
readonly request: BuildRequest;
|
readonly request: BuildRequest;
|
||||||
readonly files: readonly GameCopyFile[];
|
readonly files: readonly GameCopyFile[];
|
||||||
readonly decalCache: string | undefined;
|
readonly decalCache: string | undefined;
|
||||||
|
readonly enabledMods: readonly DiscoveredMod[];
|
||||||
|
readonly optionalPacksInBuild: readonly ModdableClientPack[];
|
||||||
|
readonly fingerprint: string;
|
||||||
} | null = null;
|
} | null = null;
|
||||||
|
|
||||||
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
|
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
|
||||||
@@ -31,16 +48,41 @@ function importedDecals(path: string | undefined): string | undefined {
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly string[] | undefined): DiscoveredMod[] {
|
||||||
|
if (!modsDir || !enabledModIds || enabledModIds.length === 0) return [];
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
||||||
|
const ordered: DiscoveredMod[] = [];
|
||||||
|
for (const id of enabledModIds) {
|
||||||
|
const mod = byId.get(id);
|
||||||
|
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
|
||||||
|
ordered.push(mod);
|
||||||
|
}
|
||||||
|
return ordered;
|
||||||
|
}
|
||||||
|
|
||||||
function build(request: BuildRequest): void {
|
function build(request: BuildRequest): void {
|
||||||
checkBuildLocation(request);
|
checkBuildLocation(request);
|
||||||
const decalCache = importedDecals(request.decalCache);
|
const decalCache = importedDecals(request.decalCache);
|
||||||
|
const decalIndexFiles = decalCache ? readPlayerDecalIndexFiles(decalCache) : undefined;
|
||||||
|
const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds);
|
||||||
|
const touchedPacks = touchedClientPacks(enabledMods);
|
||||||
|
const optionalPacksInBuild = touchedPacks.filter((pack) => !CORE_BUILD_PACKS.has(pack));
|
||||||
|
const extraStockPacks = optionalPacksInBuild.length > 0
|
||||||
|
? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
const result = buildGameCopy({
|
const result = buildGameCopy({
|
||||||
stock: readStockGameFiles(request.stockPath),
|
stock: readStockGameFiles(request.stockPath),
|
||||||
patches: request.patches,
|
patches: request.patches,
|
||||||
networkHookLibrary: readFileSync(request.networkHookLibrary),
|
networkHookLibrary: readFileSync(request.networkHookLibrary),
|
||||||
port: request.port,
|
port: request.port,
|
||||||
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info),
|
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info, enabledMods),
|
||||||
placeholderDecals: decalCache === undefined,
|
placeholderDecals: decalCache === undefined,
|
||||||
|
...(decalIndexFiles ? { decalIndexFiles } : {}),
|
||||||
|
hookLogging: request.hookLogging,
|
||||||
|
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
|
||||||
|
...(extraStockPacks ? { extraStockPacks } : {}),
|
||||||
});
|
});
|
||||||
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
|
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
|
||||||
const accepted = new Set(request.acceptedUnavailable);
|
const accepted = new Set(request.acceptedUnavailable);
|
||||||
@@ -49,7 +91,19 @@ function build(request: BuildRequest): void {
|
|||||||
send({ kind: 'failed', error: 'launch_build_unavailable' });
|
send({ kind: 'failed', error: 'launch_build_unavailable' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
prepared = { request, files: result.files, decalCache };
|
if (result.mods.enabledModIds.length > 0) {
|
||||||
|
console.info(
|
||||||
|
`[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` +
|
||||||
|
`(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` +
|
||||||
|
`gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` +
|
||||||
|
`exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`,
|
||||||
|
);
|
||||||
|
for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) {
|
||||||
|
console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const fingerprint = computeModsBuildFingerprint(enabledMods, request.port, request.patches);
|
||||||
|
prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint };
|
||||||
send({ kind: 'prepared', total: prepared.files.length });
|
send({ kind: 'prepared', total: prepared.files.length });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,15 +115,22 @@ process.parentPort.on('message', (event: MessageEvent) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!prepared) throw new Error('No build is ready to write.');
|
if (!prepared) throw new Error('No build is ready to write.');
|
||||||
const { request, files, decalCache } = prepared;
|
const { request, files, decalCache, enabledMods, optionalPacksInBuild, fingerprint } = prepared;
|
||||||
prepared = null;
|
prepared = null;
|
||||||
checkBuildLocation(request);
|
checkBuildLocation(request);
|
||||||
const { copyPath } = request;
|
const { copyPath, stockPath } = request;
|
||||||
if (decalCache) copyPlayerDecalCache(decalCache, copyPath);
|
if (decalCache) copyPlayerDecalCache(decalCache, copyPath);
|
||||||
for (const [index, file] of files.entries()) {
|
for (const [index, file] of files.entries()) {
|
||||||
writeGameCopy(copyPath, [file]);
|
writeGameCopy(copyPath, [file]);
|
||||||
send({ kind: 'progress', written: index + 1, total: files.length, file: file.path });
|
send({ kind: 'progress', written: index + 1, total: files.length, file: file.path });
|
||||||
}
|
}
|
||||||
|
const deployResult = syncExternalModFiles(copyPath, stockPath, enabledMods, optionalPacksInBuild, fingerprint);
|
||||||
|
for (const warning of deployResult.warnings) {
|
||||||
|
console.warn(`[mods] skipped "${warning.targetRelPath}" from "${warning.modId}": ${warning.reason}`);
|
||||||
|
}
|
||||||
|
if (deployResult.restoredOptionalPacks.length > 0) {
|
||||||
|
console.info(`[mods] restored stock pack(s): ${deployResult.restoredOptionalPacks.join(', ')}`);
|
||||||
|
}
|
||||||
send({ kind: 'written' });
|
send({ kind: 'written' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[build] preparing the game copy failed:', error);
|
console.error('[build] preparing the game copy failed:', error);
|
||||||
|
|||||||
@@ -1,15 +1,42 @@
|
|||||||
|
import { discoverMods, type DiscoveredMod } from '@wto/mods';
|
||||||
import { startServer } from '@wto/server';
|
import { startServer } from '@wto/server';
|
||||||
|
|
||||||
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
|
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
|
||||||
|
|
||||||
|
function loadOrderedMods(modsDir: string | undefined, enabledJson: string | undefined): DiscoveredMod[] {
|
||||||
|
if (!modsDir || !enabledJson) return [];
|
||||||
|
const ids = JSON.parse(enabledJson) as unknown;
|
||||||
|
if (!Array.isArray(ids) || ids.length === 0) return [];
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
||||||
|
const mods: DiscoveredMod[] = [];
|
||||||
|
for (const id of ids) {
|
||||||
|
if (typeof id !== 'string') continue;
|
||||||
|
const mod = byId.get(id);
|
||||||
|
if (!mod) throw new Error(`Enabled mod "${id}" not found in ${modsDir}`);
|
||||||
|
mods.push(mod);
|
||||||
|
}
|
||||||
|
return mods;
|
||||||
|
}
|
||||||
|
|
||||||
async function serve(): Promise<void> {
|
async function serve(): Promise<void> {
|
||||||
const [gameFolder, dataFolder, portText] = process.argv.slice(2);
|
const [gameFolder, dataFolder, portText, loggingFlag, modsDir, enabledModIdsJson] = process.argv.slice(2);
|
||||||
const port = Number(portText);
|
const port = Number(portText);
|
||||||
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
|
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
|
||||||
throw new Error('Invalid local server arguments.');
|
throw new Error('Invalid local server arguments.');
|
||||||
}
|
}
|
||||||
const server = await startServer({ gameFolder, dataFolder, port, report: console.info });
|
const loggingEnabled = loggingFlag !== '0';
|
||||||
console.info('Traffic log:', server.logFolder);
|
const mods = loadOrderedMods(modsDir, enabledModIdsJson);
|
||||||
|
const server = await startServer({
|
||||||
|
gameFolder,
|
||||||
|
dataFolder,
|
||||||
|
port,
|
||||||
|
loggingEnabled,
|
||||||
|
...(mods.length > 0 ? { mods } : {}),
|
||||||
|
report: console.info,
|
||||||
|
});
|
||||||
|
if (server.logFolder) console.info('Traffic log:', server.logFolder);
|
||||||
|
if (server.loadedModIds.length > 0) console.info('Loaded server script mods:', server.loadedModIds.join(', '));
|
||||||
process.parentPort.once('message', () => {
|
process.parentPort.once('message', () => {
|
||||||
void server.close().then(() => process.exit(0)).catch((error: unknown) => {
|
void server.close().then(() => process.exit(0)).catch((error: unknown) => {
|
||||||
console.error('Could not close the local server:', error);
|
console.error('Could not close the local server:', error);
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { applyLanguage, resolveLanguage } from './i18n/index.ts';
|
|||||||
import { ipcInvoke, ipcOn } from './ipc.ts';
|
import { ipcInvoke, ipcOn } from './ipc.ts';
|
||||||
import { AboutPage } from './pages/about/AboutPage.tsx';
|
import { AboutPage } from './pages/about/AboutPage.tsx';
|
||||||
import { CopyMaintenance } from './pages/copies/CopyMaintenance.tsx';
|
import { CopyMaintenance } from './pages/copies/CopyMaintenance.tsx';
|
||||||
|
import { useCopyMaintenance } from './pages/copies/useCopyMaintenance.ts';
|
||||||
import { CopyList } from './pages/copies/CopyList.tsx';
|
import { CopyList } from './pages/copies/CopyList.tsx';
|
||||||
import { CopySummary } from './pages/copies/CopySummary.tsx';
|
import { CopySummary } from './pages/copies/CopySummary.tsx';
|
||||||
import { FeatureStatus } from './pages/copies/FeatureStatus.tsx';
|
import { FeatureStatus } from './pages/copies/FeatureStatus.tsx';
|
||||||
@@ -21,6 +22,7 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
|
|||||||
import { WizardMain } from './pages/install/WizardMain.tsx';
|
import { WizardMain } from './pages/install/WizardMain.tsx';
|
||||||
import { WizardSide } from './pages/install/WizardSide.tsx';
|
import { WizardSide } from './pages/install/WizardSide.tsx';
|
||||||
import { wizardBar } from './pages/install/wizard-bar.ts';
|
import { wizardBar } from './pages/install/wizard-bar.ts';
|
||||||
|
import { ModsPage } from './pages/mods/ModsPage.tsx';
|
||||||
import { TuningPage } from './pages/tuning/TuningPage.tsx';
|
import { TuningPage } from './pages/tuning/TuningPage.tsx';
|
||||||
import { SavesPage } from './pages/saves/SavesPage.tsx';
|
import { SavesPage } from './pages/saves/SavesPage.tsx';
|
||||||
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
|
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
|
||||||
@@ -31,7 +33,7 @@ import { Background } from './shell/Background.tsx';
|
|||||||
import { BottomBar } from './shell/BottomBar.tsx';
|
import { BottomBar } from './shell/BottomBar.tsx';
|
||||||
import type { BarModel } from './shell/bar-model.ts';
|
import type { BarModel } from './shell/bar-model.ts';
|
||||||
import { Footer } from './shell/Footer.tsx';
|
import { Footer } from './shell/Footer.tsx';
|
||||||
import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
|
import { COPY_SECTIONS, MODS_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
|
||||||
import { SubNav } from './shell/SubNav.tsx';
|
import { SubNav } from './shell/SubNav.tsx';
|
||||||
import { TitleBar } from './shell/TitleBar.tsx';
|
import { TitleBar } from './shell/TitleBar.tsx';
|
||||||
import { useBackgrounds } from './shell/useBackgrounds.ts';
|
import { useBackgrounds } from './shell/useBackgrounds.ts';
|
||||||
@@ -68,6 +70,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
|||||||
// The setting as the window opened: turning it on later does not check right away.
|
// The setting as the window opened: turning it on later does not check right away.
|
||||||
const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report);
|
const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report);
|
||||||
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
|
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
|
||||||
|
const maintenance = useCopyMaintenance(report);
|
||||||
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
|
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
|
||||||
|
|
||||||
const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) });
|
const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) });
|
||||||
@@ -149,13 +152,26 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
|||||||
bar: home,
|
bar: home,
|
||||||
};
|
};
|
||||||
case 'about':
|
case 'about':
|
||||||
return { side: homeSide, main: <AboutPage launcherVersion={info.version} supportedVersions={supported} patchPack={patchPack} appUpdate={appUpdate} />, bar: home };
|
return {
|
||||||
|
side: homeSide,
|
||||||
|
main: (
|
||||||
|
<AboutPage
|
||||||
|
launcherVersion={info.version}
|
||||||
|
supportedVersions={supported}
|
||||||
|
patchPack={patchPack}
|
||||||
|
appUpdate={appUpdate}
|
||||||
|
loggingEnabled={settings.loggingEnabled}
|
||||||
|
onError={report}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
bar: home,
|
||||||
|
};
|
||||||
case 'settings': {
|
case 'settings': {
|
||||||
const sections = SETTINGS_SECTIONS.filter((section) => info.development || section !== 'dev');
|
const sections = SETTINGS_SECTIONS.filter((section) => info.development || section !== 'dev');
|
||||||
const content = {
|
const content = {
|
||||||
general: <GeneralSettings settings={settings} appUpdatesSupported={info.appUpdatesSupported} pictures={backgrounds.pictures} onError={report} />,
|
general: <GeneralSettings settings={settings} appUpdatesSupported={info.appUpdatesSupported} pictures={backgrounds.pictures} onError={report} />,
|
||||||
launch: <LaunchSettings settings={settings} development={info.development} onError={report} />,
|
launch: <LaunchSettings settings={settings} development={info.development} onError={report} />,
|
||||||
diag: <DiagnosticsSettings onError={report} serverRunning={launch.phase === 'running' || launch.phase === 'server-running'} />,
|
diag: <DiagnosticsSettings settings={settings} onError={report} serverRunning={launch.phase === 'running' || launch.phase === 'server-running'} />,
|
||||||
dev: <DeveloperSettings settings={settings} onError={report} />,
|
dev: <DeveloperSettings settings={settings} onError={report} />,
|
||||||
};
|
};
|
||||||
return {
|
return {
|
||||||
@@ -180,6 +196,14 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
|||||||
: <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>,
|
: <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>,
|
||||||
bar: home,
|
bar: home,
|
||||||
};
|
};
|
||||||
|
case 'mods':
|
||||||
|
return {
|
||||||
|
side: <SubNav sections={MODS_SECTIONS} active={route.mods} label={(section) => t(`mods.sections.${section}`)} onSelect={(section) => go({ page: 'mods', section })} />,
|
||||||
|
main: record
|
||||||
|
? <ModsPage key={record.id} copy={record} section={route.mods} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'server-running', 'stopping'].includes(launch.phase)} onError={report} />
|
||||||
|
: <Sheet title={t(`mods.sections.${route.mods}`)}><p className="lead">{t('mods.noCopy')}</p></Sheet>,
|
||||||
|
bar: home,
|
||||||
|
};
|
||||||
case 'copies': {
|
case 'copies': {
|
||||||
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
|
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
|
||||||
if (route.copies === 'list') {
|
if (route.copies === 'list') {
|
||||||
@@ -210,7 +234,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (route.copies === 'maintain') {
|
if (route.copies === 'maintain') {
|
||||||
return { side, main: <CopyMaintenance key={record.id} record={record} onError={report} />, bar: home };
|
return { side, main: <CopyMaintenance key={record.id} record={record} maintenance={maintenance} onError={report} />, bar: home };
|
||||||
}
|
}
|
||||||
const main = route.copies === 'features'
|
const main = route.copies === 'features'
|
||||||
? <FeatureStatus record={record} supportedVersions={supported} onError={report} />
|
? <FeatureStatus record={record} supportedVersions={supported} onError={report} />
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
"home": "Home",
|
"home": "Home",
|
||||||
"saves": "Saves",
|
"saves": "Saves",
|
||||||
"tuning": "Tuning",
|
"tuning": "Tuning",
|
||||||
|
"mods": "Mods",
|
||||||
"copies": "Clients",
|
"copies": "Clients",
|
||||||
"settings": "Settings",
|
"settings": "Settings",
|
||||||
"about": "About"
|
"about": "About"
|
||||||
@@ -96,7 +97,7 @@
|
|||||||
},
|
},
|
||||||
"decals": {
|
"decals": {
|
||||||
"source": "Decal source",
|
"source": "Decal source",
|
||||||
"hint": "Import the online game's cache/content folder. The client uses placeholder decals when no cache is available.",
|
"hint": "Import the online game's cache/content (or cache) folder for cached decals and downloadable skins. Placeholder decals are used when no cache is available.",
|
||||||
"choose": "Choose decal cache…",
|
"choose": "Choose decal cache…",
|
||||||
"useDefault": "Use placeholder decals",
|
"useDefault": "Use placeholder decals",
|
||||||
"importing": "Importing decal cache",
|
"importing": "Importing decal cache",
|
||||||
@@ -157,9 +158,9 @@
|
|||||||
"copy": "Copy installation (recommended)",
|
"copy": "Copy installation (recommended)",
|
||||||
"copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.",
|
"copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.",
|
||||||
"spaceSaving": "Space-saving copy",
|
"spaceSaving": "Space-saving copy",
|
||||||
"spaceSavingBody": "Shares verified large resources on the same volume. Estimated space required is {{size}}. A Steam update in place can change shared files in the client.",
|
"spaceSavingBody": "Shares read-only resource archives on the same volume. Estimated space required is {{size}}. An in-place update to the source client can change shared files in this client.",
|
||||||
"spaceSavingPending": "Calculating how much space can be saved.",
|
"spaceSavingPending": "Calculating how much space can be saved.",
|
||||||
"spaceSavingUnavailable": "This installation has no large resources eligible for space-saving copying.",
|
"spaceSavingUnavailable": "This installation has no read-only resource archives eligible for space-saving copying.",
|
||||||
"sameVolumeRequired": "Select a destination on the same volume as the original installation.",
|
"sameVolumeRequired": "Select a destination on the same volume as the original installation.",
|
||||||
"targetTitle": "Select an install location (a WTOffline subfolder will be created)",
|
"targetTitle": "Select an install location (a WTOffline subfolder will be created)",
|
||||||
"targetSubfolderHint": "A dedicated WTOffline folder is automatically created under the selected location to keep game files organized.",
|
"targetSubfolderHint": "A dedicated WTOffline folder is automatically created under the selected location to keep game files organized.",
|
||||||
@@ -188,7 +189,11 @@
|
|||||||
},
|
},
|
||||||
"data": {
|
"data": {
|
||||||
"body": "Select a folder for saves, caches, and logs.",
|
"body": "Select a folder for saves, caches, and logs.",
|
||||||
"dialogTitle": "Select the data folder"
|
"dialogTitle": "Select the data folder",
|
||||||
|
"problem": {
|
||||||
|
"overlaps_client": "The data folder cannot be the client folder, contain the client folder, or lie inside its wtoffline folder. Choose a separate folder or a dedicated subfolder inside the client (for example, data).",
|
||||||
|
"overlaps_stock": "The data folder cannot lie inside the online installation folder."
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"check": {
|
"check": {
|
||||||
"running": "Checking patches for the selected game version.",
|
"running": "Checking patches for the selected game version.",
|
||||||
@@ -226,18 +231,22 @@
|
|||||||
"missingFolder": "Folder missing",
|
"missingFolder": "Folder missing",
|
||||||
"relocate": "Relocate…",
|
"relocate": "Relocate…",
|
||||||
"relocateDialogTitle": "Select the moved client folder",
|
"relocateDialogTitle": "Select the moved client folder",
|
||||||
"list": { "current": "Current", "select": "Set as current" },
|
"list": {
|
||||||
|
"current": "Current",
|
||||||
|
"select": "Set as current"
|
||||||
|
},
|
||||||
"none": "The offline edition is not installed yet.",
|
"none": "The offline edition is not installed yet.",
|
||||||
"maintenance": {
|
"maintenance": {
|
||||||
"update": "Update from online installation",
|
"update": "Update from online installation",
|
||||||
"updateAction": "Update client",
|
"updateAction": "Update client",
|
||||||
"newVersion": "Version {{version}} is available from the installation source.",
|
"newVersion": "Version {{version}} is available from the installation source.",
|
||||||
"updateDetaches": "Version {{version}} is available. Updating copies shared resources into independent files and requires additional space.",
|
"updateKeepsSpaceSaving": "Version {{version}} is available. Updating continues sharing read-only resource archives with the source.",
|
||||||
|
"updateDetaches": "Version {{version}} is available. Because the client and source are on different volumes, updating copies shared resources into independent files and requires additional space.",
|
||||||
"currentVersion": "Installation source version {{version}}",
|
"currentVersion": "Installation source version {{version}}",
|
||||||
"noSource": "Installation source unavailable",
|
"noSource": "Installation source unavailable",
|
||||||
"spaceSaving": "Save space",
|
"spaceSaving": "Save space",
|
||||||
"spaceSavingHint": "Share identical verified resources with the source. A Steam update in place can change the shared files.",
|
"spaceSavingHint": "Share identical read-only resource archives with the source. An in-place update to the source client can change the shared files.",
|
||||||
"spaceSavingUnavailable": "Requires a client and source installation of the same checked version on the same volume.",
|
"spaceSavingUnavailable": "Requires a client and source installation of the same version on the same volume.",
|
||||||
"compactAction": "Convert",
|
"compactAction": "Convert",
|
||||||
"check": "Recheck patches",
|
"check": "Recheck patches",
|
||||||
"checkHint": "Check the original file backup.",
|
"checkHint": "Check the original file backup.",
|
||||||
@@ -336,8 +345,7 @@
|
|||||||
"country": "Country",
|
"country": "Country",
|
||||||
"type": "Vehicle type",
|
"type": "Vehicle type",
|
||||||
"actions": "Bulk actions",
|
"actions": "Bulk actions",
|
||||||
"research": "Research all",
|
"purchase": "Research and buy all",
|
||||||
"purchase": "Grant regular vehicles",
|
|
||||||
"equipment": "Unlock modifications",
|
"equipment": "Unlock modifications",
|
||||||
"empty": "This client has no eligible research branches.",
|
"empty": "This client has no eligible research branches.",
|
||||||
"rank": "Rank {{rank}}",
|
"rank": "Rank {{rank}}",
|
||||||
@@ -431,7 +439,8 @@
|
|||||||
"premiumDays": "Premium account days",
|
"premiumDays": "Premium account days",
|
||||||
"avatar": "Avatar",
|
"avatar": "Avatar",
|
||||||
"avatarUnavailable": "Avatar unavailable",
|
"avatarUnavailable": "Avatar unavailable",
|
||||||
"level": "Account level",␍ "apply": "Save changes",
|
"level": "Account level",
|
||||||
|
"apply": "Save changes",
|
||||||
"saved": "Changes saved.",
|
"saved": "Changes saved.",
|
||||||
"noBattles": "The save has no recorded battles.",
|
"noBattles": "The save has no recorded battles.",
|
||||||
"win": "Victory",
|
"win": "Victory",
|
||||||
@@ -458,6 +467,7 @@
|
|||||||
"tankBotRespawns": "AI tank respawns",
|
"tankBotRespawns": "AI tank respawns",
|
||||||
"airBotRespawns": "AI aircraft respawns",
|
"airBotRespawns": "AI aircraft respawns",
|
||||||
"strikeUcavSpawnScore": "Strike UCAV spawn points",
|
"strikeUcavSpawnScore": "Strike UCAV spawn points",
|
||||||
|
"nuclearEscalationStrategicBombers": "Nuclear Escalation stage-3 strategic bombers (B-52H / Tu-95M)",
|
||||||
"silverLions": "Starting Silver Lions",
|
"silverLions": "Starting Silver Lions",
|
||||||
"goldenEagles": "Starting Golden Eagles",
|
"goldenEagles": "Starting Golden Eagles",
|
||||||
"preferLineSuccessor": "Prefer the next vehicle in the line",
|
"preferLineSuccessor": "Prefer the next vehicle in the line",
|
||||||
@@ -489,7 +499,7 @@
|
|||||||
"appUpdates": "Launcher updates",
|
"appUpdates": "Launcher updates",
|
||||||
"appUpdatesToggle": "Check for launcher updates at start",
|
"appUpdatesToggle": "Check for launcher updates at start",
|
||||||
"patchPacks": "Adaptation pack updates",
|
"patchPacks": "Adaptation pack updates",
|
||||||
"patchPacksHint": "After a game update, the patches for the new version are released on GitHub as an adaptation pack.",
|
"patchPacksHint": "After a game update, patches for the new version are released as an adaptation pack.",
|
||||||
"updateMirror": "Update mirror repository",
|
"updateMirror": "Update mirror repository",
|
||||||
"updateMirrorHint": "Enter an HTTPS mirror with a GitHub-compatible releases list. It is used if the primary source is unreachable. Leave blank to disable it.",
|
"updateMirrorHint": "Enter an HTTPS mirror with a GitHub-compatible releases list. It is used if the primary source is unreachable. Leave blank to disable it.",
|
||||||
"updateMirrorInvalid": "Enter a valid HTTPS repository address or leave the field blank.",
|
"updateMirrorInvalid": "Enter a valid HTTPS repository address or leave the field blank.",
|
||||||
@@ -524,11 +534,15 @@
|
|||||||
"reset": "Restore default"
|
"reset": "Restore default"
|
||||||
},
|
},
|
||||||
"diagnostics": {
|
"diagnostics": {
|
||||||
|
"recordLogs": "Record runtime logs",
|
||||||
|
"recordLogsToggle": "Write launcher, local server, and hook logs",
|
||||||
|
"recordLogsHint": "When disabled, stops writing launcher logs, local server traffic logs, and wto_ws.log (the game engine's own .game_logs are unaffected). Re-enable before exporting logs for troubleshooting.",
|
||||||
|
"loggingDisabledNotice": "Runtime logging is currently disabled; exported archives include only existing logs and configuration.",
|
||||||
"logs": "Logs",
|
"logs": "Logs",
|
||||||
"logsHint": "Logs recorded by the launcher",
|
"logsHint": "Logs recorded by the launcher",
|
||||||
"openLogs": "Open log folder",
|
"openLogs": "Open log folder",
|
||||||
"export": "Export diagnostics",
|
"export": "Export diagnostics",
|
||||||
"exportHint": "Save logs, settings and the installation record to a ZIP file",
|
"exportHint": "Save launcher, local server, and game logs, settings, and the installation record to a ZIP file (excludes saves)",
|
||||||
"save": "Export…",
|
"save": "Export…",
|
||||||
"saved": "Diagnostics saved to {{path}}.",
|
"saved": "Diagnostics saved to {{path}}.",
|
||||||
"serverStatus": "Local server status",
|
"serverStatus": "Local server status",
|
||||||
@@ -566,6 +580,12 @@
|
|||||||
"about": {
|
"about": {
|
||||||
"launcher": "Launcher {{version}}",
|
"launcher": "Launcher {{version}}",
|
||||||
"supported": "Supported game versions: {{versions}}",
|
"supported": "Supported game versions: {{versions}}",
|
||||||
|
"feedback": {
|
||||||
|
"title": "Feedback and logs",
|
||||||
|
"export": "Save all logs",
|
||||||
|
"exportHint": "Pack launcher, local server, and game logs into a ZIP file for issue reports (excludes saves).",
|
||||||
|
"exportButton": "Save log ZIP…"
|
||||||
|
},
|
||||||
"pack": {
|
"pack": {
|
||||||
"title": "Adaptation data",
|
"title": "Adaptation data",
|
||||||
"current": "In use",
|
"current": "In use",
|
||||||
@@ -623,7 +643,17 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"statement": "Project information",
|
"statement": "Project information",
|
||||||
"statementBody": "WTOffline is a noncommercial hobby project independent of Gaijin. Running it requires your own War Thunder base game files."
|
"statementBody": "WTOffline is a noncommercial hobby project independent of Gaijin. Running it requires your own War Thunder base game files.",
|
||||||
|
"homepage": {
|
||||||
|
"title": "Project homepage",
|
||||||
|
"hint": "Project overview, release catalog, and community links.",
|
||||||
|
"open": "Open homepage"
|
||||||
|
},
|
||||||
|
"community": {
|
||||||
|
"discord": "Discord",
|
||||||
|
"discordHint": "Development discussion, general chat, troubleshooting, and bug reports.",
|
||||||
|
"openDiscord": "Open Discord"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"features": {
|
"features": {
|
||||||
"A-Offline startup": "Offline startup",
|
"A-Offline startup": "Offline startup",
|
||||||
@@ -646,6 +676,7 @@
|
|||||||
"J-Ground arcade and realistic": "Ground battles (arcade, realistic)",
|
"J-Ground arcade and realistic": "Ground battles (arcade, realistic)",
|
||||||
"J-Air arcade and realistic": "Air battles (arcade, realistic)",
|
"J-Air arcade and realistic": "Air battles (arcade, realistic)",
|
||||||
"J-Naval arcade and realistic": "Naval battles (arcade, realistic)",
|
"J-Naval arcade and realistic": "Naval battles (arcade, realistic)",
|
||||||
|
"E-Crew skills in battle": "Crew skills and qualifications in battle",
|
||||||
"J-Sub-modes": "Additional modes (such as night battles)",
|
"J-Sub-modes": "Additional modes (such as night battles)",
|
||||||
"K-AI opponents and teammates": "AI opponents and allies",
|
"K-AI opponents and teammates": "AI opponents and allies",
|
||||||
"K-Spawn score and respawns": "Spawn points and respawning",
|
"K-Spawn score and respawns": "Spawn points and respawning",
|
||||||
@@ -659,6 +690,96 @@
|
|||||||
"L-Debriefing": "Battle results",
|
"L-Debriefing": "Battle results",
|
||||||
"L-Battle awards": "Battle awards"
|
"L-Battle awards": "Battle awards"
|
||||||
},
|
},
|
||||||
|
"mods": {
|
||||||
|
"sections": {
|
||||||
|
"list": "Mod list",
|
||||||
|
"presets": "Presets & repository"
|
||||||
|
},
|
||||||
|
"loading": "Loading mods…",
|
||||||
|
"noCopy": "Install or select an offline client first to configure its mods.",
|
||||||
|
"enabledSummary": "{{enabled}} / {{total}} enabled",
|
||||||
|
"experimentalChip": "Experimental",
|
||||||
|
"experimentalTitle": "Experimental mod API notice:",
|
||||||
|
"experimentalBody": "WTOffline is in early development (API {{api}}). Server script hooks, internal data structures, and declarative exe patch contracts may change at any time without backwards compatibility; only enable mods from trusted sources.",
|
||||||
|
"readOnlyNotice": "Mod toggles, load order, and presets are read-only while the game, local server, or maintenance is running.",
|
||||||
|
"searchPlaceholder": "Filter by mod name, ID, or author…",
|
||||||
|
"autoSort": "Auto-sort by dependencies",
|
||||||
|
"autoSorted": "Reordered mods based on dependencies and load-order hints.",
|
||||||
|
"refresh": "Refresh",
|
||||||
|
"openFolder": "Open mods folder",
|
||||||
|
"openDocs": "Mod docs",
|
||||||
|
"discoveryErrorsTitle": "{{count}} mod folder(s) could not be loaded:",
|
||||||
|
"blockingIssuesTitle": "{{count}} blocking mod error(s) prevent launching:",
|
||||||
|
"issuesTitle": "{{count}} mod notice(s) or overlap(s):",
|
||||||
|
"severity": {
|
||||||
|
"error": "Error",
|
||||||
|
"warning": "Warning",
|
||||||
|
"info": "Info"
|
||||||
|
},
|
||||||
|
"emptyTitle": "No mods found in the global mods folder yet.",
|
||||||
|
"emptyHint": "Place mod folders containing mod.jsonc into {{path}}, then click Refresh. Standalone skins, sights, and user missions continue to work directly via the game's native UserSkins / UserSights / UserMissions folders.",
|
||||||
|
"noSearchMatch": "No mods match the current search filter.",
|
||||||
|
"loadOrderHint": "Load order: lower items load later and take higher priority (drag or use arrows)",
|
||||||
|
"moveUp": "Move up",
|
||||||
|
"moveDown": "Move down",
|
||||||
|
"showDetails": "Details",
|
||||||
|
"hideDetails": "Hide",
|
||||||
|
"errorCount": "{{count}} error",
|
||||||
|
"warnCount": "{{count}} warn",
|
||||||
|
"badges": {
|
||||||
|
"data": "Data / Assets",
|
||||||
|
"gui": "GUI Patch",
|
||||||
|
"script": "Server Script",
|
||||||
|
"exe": "Exe Patch"
|
||||||
|
},
|
||||||
|
"details": {
|
||||||
|
"folder": "Folder",
|
||||||
|
"gameVersions": "Declared game versions",
|
||||||
|
"requires": "Requires",
|
||||||
|
"conflicts": "Conflicts",
|
||||||
|
"tuning": "Server tuning overlays: {{count}}",
|
||||||
|
"serverScript": "Executable server JS/TS script",
|
||||||
|
"packOps": "Client pack operations: {{count}}",
|
||||||
|
"addon": "3D model / texture addon: {{count}} file(s)",
|
||||||
|
"guiPatches": "GUI script patches: {{count}}",
|
||||||
|
"exePatches": "Declarative exe patches: {{count}}",
|
||||||
|
"companionFiles": "Companion files: {{count}}",
|
||||||
|
"configBlk": "Includes config.blk patch"
|
||||||
|
},
|
||||||
|
"presets": {
|
||||||
|
"heading": "Mod presets (saved per client)",
|
||||||
|
"description": "Save the current mod toggles and load order as named presets for quick switching or JSON export/import.",
|
||||||
|
"quickSwitch": "Switch mod preset",
|
||||||
|
"customOption": "Custom active selection",
|
||||||
|
"namePlaceholder": "New preset name, e.g. Modern Vehicles",
|
||||||
|
"saveCurrent": "Save preset",
|
||||||
|
"import": "Import preset…",
|
||||||
|
"empty": "No presets saved for this client yet.",
|
||||||
|
"activeTag": "Active",
|
||||||
|
"summary": "{{count}} enabled / {{total}} tracked",
|
||||||
|
"apply": "Apply",
|
||||||
|
"overwrite": "Update",
|
||||||
|
"export": "Export",
|
||||||
|
"delete": "Delete",
|
||||||
|
"saved": "Saved preset \"{{name}}\".",
|
||||||
|
"applied": "Applied preset \"{{name}}\".",
|
||||||
|
"updated": "Updated preset \"{{name}}\" with current setup.",
|
||||||
|
"exported": "Exported preset to: {{path}}",
|
||||||
|
"imported": "Imported mod preset."
|
||||||
|
},
|
||||||
|
"repo": {
|
||||||
|
"heading": "Global mods repository",
|
||||||
|
"description": "All clients share one mod folder (large 3D model and texture addons mount across drives via NTFS Junctions with zero copying), while each client keeps its own toggles, load order, and presets.",
|
||||||
|
"pathLabel": "Repository folder",
|
||||||
|
"defaultNote": "Using launcher default mods folder",
|
||||||
|
"customNote": "Using custom mods folder (can live on a larger drive or the same drive as your client)",
|
||||||
|
"changeFolder": "Change folder…",
|
||||||
|
"resetDefault": "Reset to default",
|
||||||
|
"pickTitle": "Select global mods repository folder",
|
||||||
|
"updated": "Updated global mods repository folder.",
|
||||||
|
"resetDone": "Reset to default mods repository folder."
|
||||||
|
}
|
||||||
|
},
|
||||||
"errors": {
|
"errors": {
|
||||||
"app_update_unavailable": "There is no launcher update available to install.",
|
"app_update_unavailable": "There is no launcher update available to install.",
|
||||||
"app_update_busy": "A launcher update operation is already in progress.",
|
"app_update_busy": "A launcher update operation is already in progress.",
|
||||||
@@ -682,10 +803,15 @@
|
|||||||
"save_avatar_invalid": "Select an avatar available in this client.",
|
"save_avatar_invalid": "Select an avatar available in this client.",
|
||||||
"save_level_invalid": "Enter a level supported by this client.",
|
"save_level_invalid": "Enter a level supported by this client.",
|
||||||
"tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.",
|
"tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.",
|
||||||
|
"mods_read_only": "Mods cannot be changed while the game, local server, or maintenance is running.",
|
||||||
|
"mods_write_failed": "The mod configuration could not be saved. See the launcher log.",
|
||||||
|
"mods_preset_invalid": "The selected file is not a valid WTOffline mod preset.",
|
||||||
|
"mods_blocking_issues": "Enabled mods have missing dependencies or conflicts. Resolve them on the Mods page before launching.",
|
||||||
|
"mods_folder_invalid": "The selected global mods folder is invalid or not writable.",
|
||||||
"copy_not_found": "The selected client is no longer available.",
|
"copy_not_found": "The selected client is no longer available.",
|
||||||
"copies_write_failed": "The client registry could not be saved.",
|
"copies_write_failed": "The client registry could not be saved.",
|
||||||
"copy_location_in_use": "The client or data location overlaps an existing client.",
|
"copy_location_in_use": "The client or data location overlaps an existing client.",
|
||||||
"decal_source_invalid": "The selected folder does not contain a usable decal cache.",
|
"decal_source_invalid": "The selected folder does not contain a usable decal cache. Log into the online hangar once to populate it, then choose cache/content (or cache).",
|
||||||
"decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.",
|
"decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.",
|
||||||
"maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.",
|
"maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.",
|
||||||
"maintenance_location": "The operation would affect files outside the registered client or data folder.",
|
"maintenance_location": "The operation would affect files outside the registered client or data folder.",
|
||||||
@@ -706,12 +832,14 @@
|
|||||||
"launch_steam_confirmation_required": "Confirm the Steam locations in Client Maintenance before launching.",
|
"launch_steam_confirmation_required": "Confirm the Steam locations in Client Maintenance before launching.",
|
||||||
"launch_location": "The client, stock backup, or data folder location is invalid.",
|
"launch_location": "The client, stock backup, or data folder location is invalid.",
|
||||||
"launch_stock_version": "The stock backup and client versions do not match.",
|
"launch_stock_version": "The stock backup and client versions do not match.",
|
||||||
|
"launch_stock_missing": "The original file backup (wtoffline\\stock) is missing or unreadable. Check your security software, or remove this client entry and add it again.",
|
||||||
"launch_build_failed": "The game files could not be generated.",
|
"launch_build_failed": "The game files could not be generated.",
|
||||||
"launch_build_unavailable": "The build found unavailable patches that require review.",
|
"launch_build_unavailable": "The build found unavailable patches that require review.",
|
||||||
"launch_port_busy": "The local server port is already in use.",
|
"launch_port_busy": "The local server port is already in use.",
|
||||||
"launch_server_failed": "The local server could not be started. See the launcher log.",
|
"launch_server_failed": "The local server could not be started. See the launcher log.",
|
||||||
"launch_server_exited": "The local server is unavailable.",
|
"launch_server_exited": "The local server is unavailable.",
|
||||||
"launch_game_failed": "The game process could not start. See the launcher log.",
|
"launch_game_failed": "The game process could not start. See the launcher log.",
|
||||||
|
"launch_game_files_missing": "Required game launch files are missing or unreadable (they may have been quarantined by antivirus software). Check your security software and the launcher log.",
|
||||||
"settings_write_failed": "The settings could not be saved.",
|
"settings_write_failed": "The settings could not be saved.",
|
||||||
"folder_unreadable": "The folder cannot be read: {{path}}",
|
"folder_unreadable": "The folder cannot be read: {{path}}",
|
||||||
"not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}",
|
"not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}",
|
||||||
@@ -724,8 +852,8 @@
|
|||||||
"missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.",
|
"missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.",
|
||||||
"patch_check_failed": "An error occurred while checking patches.",
|
"patch_check_failed": "An error occurred while checking patches.",
|
||||||
"copy_failed": "Copying the game files failed. The copied files have been deleted.",
|
"copy_failed": "Copying the game files failed. The copied files have been deleted.",
|
||||||
"hardlink_unavailable": "Space-saving copying requires a verified game version and a destination on the same volume.",
|
"hardlink_unavailable": "Space-saving copying requires the destination and source to be on the same volume, and converting an existing client also requires matching versions.",
|
||||||
"hardlink_no_match": "The files do not match the verified resources for space-saving copying.",
|
"hardlink_no_match": "No matching read-only resource archives were found, or their contents differ from the source.",
|
||||||
"hardlink_file_changed": "A resource changed during verification or copying. Finish any other file operation, then retry.",
|
"hardlink_file_changed": "A resource changed during verification or copying. Finish any other file operation, then retry.",
|
||||||
"install_cancelled": "Installation cancelled. The copied files have been deleted.",
|
"install_cancelled": "Installation cancelled. The copied files have been deleted.",
|
||||||
"install_busy": "An installation is already in progress.",
|
"install_busy": "An installation is already in progress.",
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
"home": "首页",
|
"home": "首页",
|
||||||
"saves": "存档",
|
"saves": "存档",
|
||||||
"tuning": "数值",
|
"tuning": "数值",
|
||||||
|
"mods": "模组",
|
||||||
"copies": "客户端",
|
"copies": "客户端",
|
||||||
"settings": "设置",
|
"settings": "设置",
|
||||||
"about": "关于"
|
"about": "关于"
|
||||||
@@ -96,7 +97,7 @@
|
|||||||
},
|
},
|
||||||
"decals": {
|
"decals": {
|
||||||
"source": "贴花来源",
|
"source": "贴花来源",
|
||||||
"hint": "可导入在线版游戏的 cache/content。未导入时使用占位贴花。",
|
"hint": "可导入在线版游戏的 cache/content(或 cache),同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。",
|
||||||
"choose": "选择贴花缓存…",
|
"choose": "选择贴花缓存…",
|
||||||
"useDefault": "使用占位贴花",
|
"useDefault": "使用占位贴花",
|
||||||
"importing": "正在导入贴花缓存",
|
"importing": "正在导入贴花缓存",
|
||||||
@@ -157,9 +158,9 @@
|
|||||||
"copy": "复制安装(推荐)",
|
"copy": "复制安装(推荐)",
|
||||||
"copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。",
|
"copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。",
|
||||||
"spaceSaving": "节省空间的复制",
|
"spaceSaving": "节省空间的复制",
|
||||||
"spaceSavingBody": "与同一磁盘卷上的原版共用已核对的大资源,预计需要 {{size}}。Steam 就地更新可能改变客户端中的共享文件。",
|
"spaceSavingBody": "与同一磁盘卷上的原版共用只读资源包,预计需要 {{size}}。原版就地更新可能改变客户端中的共享文件。",
|
||||||
"spaceSavingPending": "正在估算可节省的空间。",
|
"spaceSavingPending": "正在估算可节省的空间。",
|
||||||
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的大型资源。",
|
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。",
|
||||||
"sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。",
|
"sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。",
|
||||||
"targetTitle": "选择安装位置(将自动创建 WTOffline 子文件夹)",
|
"targetTitle": "选择安装位置(将自动创建 WTOffline 子文件夹)",
|
||||||
"targetSubfolderHint": "将在所选位置下自动创建独立的 WTOffline 文件夹存放游戏文件,避免文件散落。",
|
"targetSubfolderHint": "将在所选位置下自动创建独立的 WTOffline 文件夹存放游戏文件,避免文件散落。",
|
||||||
@@ -188,7 +189,11 @@
|
|||||||
},
|
},
|
||||||
"data": {
|
"data": {
|
||||||
"body": "选择用于保存存档、缓存和日志的文件夹。",
|
"body": "选择用于保存存档、缓存和日志的文件夹。",
|
||||||
"dialogTitle": "选择数据目录"
|
"dialogTitle": "选择数据目录",
|
||||||
|
"problem": {
|
||||||
|
"overlaps_client": "数据目录不能与客户端目录相同、包含客户端目录,或位于客户端的 wtoffline 目录内。请选择独立文件夹或客户端内的专用子文件夹(例如 data)。",
|
||||||
|
"overlaps_stock": "数据目录不能位于在线版安装目录内。"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"check": {
|
"check": {
|
||||||
"running": "正在检查所选游戏版本的补丁。",
|
"running": "正在检查所选游戏版本的补丁。",
|
||||||
@@ -226,18 +231,22 @@
|
|||||||
"missingFolder": "目录不存在",
|
"missingFolder": "目录不存在",
|
||||||
"relocate": "重新定位…",
|
"relocate": "重新定位…",
|
||||||
"relocateDialogTitle": "选择挪动后的客户端文件夹",
|
"relocateDialogTitle": "选择挪动后的客户端文件夹",
|
||||||
"list": { "current": "当前", "select": "设为当前" },
|
"list": {
|
||||||
|
"current": "当前",
|
||||||
|
"select": "设为当前"
|
||||||
|
},
|
||||||
"none": "尚未安装离线版。",
|
"none": "尚未安装离线版。",
|
||||||
"maintenance": {
|
"maintenance": {
|
||||||
"update": "从在线版更新",
|
"update": "从在线版更新",
|
||||||
"updateAction": "更新客户端",
|
"updateAction": "更新客户端",
|
||||||
"newVersion": "安装来源已更新至 {{version}}。",
|
"newVersion": "安装来源已更新至 {{version}}。",
|
||||||
"updateDetaches": "安装来源中有新版本 {{version}}。更新会把共享资源复制为独立文件,需要额外空间。",
|
"updateKeepsSpaceSaving": "安装来源中有新版本 {{version}}。更新时会继续与原版共用只读资源包。",
|
||||||
|
"updateDetaches": "安装来源中有新版本 {{version}}。当前与安装来源不在同一磁盘卷,更新会把共享资源复制为独立文件,需要额外空间。",
|
||||||
"currentVersion": "安装来源版本 {{version}}",
|
"currentVersion": "安装来源版本 {{version}}",
|
||||||
"noSource": "安装来源不可用",
|
"noSource": "安装来源不可用",
|
||||||
"spaceSaving": "节省空间",
|
"spaceSaving": "节省空间",
|
||||||
"spaceSavingHint": "将内容一致且已核对的资源与原版共用。Steam 就地更新可能改变这些文件。",
|
"spaceSavingHint": "将内容一致的只读资源包与原版共用。原版就地更新可能改变这些文件。",
|
||||||
"spaceSavingUnavailable": "客户端和安装来源须位于同一磁盘卷,并且使用相同的已核对版本。",
|
"spaceSavingUnavailable": "客户端和安装来源须位于同一磁盘卷,并且版本一致。",
|
||||||
"compactAction": "转换",
|
"compactAction": "转换",
|
||||||
"check": "重新检查补丁",
|
"check": "重新检查补丁",
|
||||||
"checkHint": "核对原版文件备份。",
|
"checkHint": "核对原版文件备份。",
|
||||||
@@ -336,8 +345,7 @@
|
|||||||
"country": "国家",
|
"country": "国家",
|
||||||
"type": "兵种",
|
"type": "兵种",
|
||||||
"actions": "批量操作",
|
"actions": "批量操作",
|
||||||
"research": "全部研发",
|
"purchase": "全部研发并购买",
|
||||||
"purchase": "获得常规载具",
|
|
||||||
"equipment": "解锁改装件",
|
"equipment": "解锁改装件",
|
||||||
"empty": "此客户端没有可编辑的研发分支。",
|
"empty": "此客户端没有可编辑的研发分支。",
|
||||||
"rank": "等级 {{rank}}",
|
"rank": "等级 {{rank}}",
|
||||||
@@ -431,7 +439,8 @@
|
|||||||
"premiumDays": "高级账户剩余天数",
|
"premiumDays": "高级账户剩余天数",
|
||||||
"avatar": "头像",
|
"avatar": "头像",
|
||||||
"avatarUnavailable": "头像不可用",
|
"avatarUnavailable": "头像不可用",
|
||||||
"level": "账号等级",␍ "apply": "保存更改",
|
"level": "账号等级",
|
||||||
|
"apply": "保存更改",
|
||||||
"saved": "更改已保存。",
|
"saved": "更改已保存。",
|
||||||
"noBattles": "此存档没有对局记录。",
|
"noBattles": "此存档没有对局记录。",
|
||||||
"win": "胜利",
|
"win": "胜利",
|
||||||
@@ -458,6 +467,7 @@
|
|||||||
"tankBotRespawns": "AI 坦克重生次数",
|
"tankBotRespawns": "AI 坦克重生次数",
|
||||||
"airBotRespawns": "AI 飞机重生次数",
|
"airBotRespawns": "AI 飞机重生次数",
|
||||||
"strikeUcavSpawnScore": "打击无人机所需出生点数",
|
"strikeUcavSpawnScore": "打击无人机所需出生点数",
|
||||||
|
"nuclearEscalationStrategicBombers": "核战冲突启用第 3 阶段战略核轰炸机(B-52H / Tu-95M)",
|
||||||
"silverLions": "初始银狮",
|
"silverLions": "初始银狮",
|
||||||
"goldenEagles": "初始金鹰",
|
"goldenEagles": "初始金鹰",
|
||||||
"preferLineSuccessor": "优先研发同系载具",
|
"preferLineSuccessor": "优先研发同系载具",
|
||||||
@@ -489,7 +499,7 @@
|
|||||||
"appUpdates": "启动器本体更新",
|
"appUpdates": "启动器本体更新",
|
||||||
"appUpdatesToggle": "启动时检查本体更新",
|
"appUpdatesToggle": "启动时检查本体更新",
|
||||||
"patchPacks": "适配包更新",
|
"patchPacks": "适配包更新",
|
||||||
"patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布在 GitHub 上。",
|
"patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布。",
|
||||||
"updateMirror": "备用更新仓库",
|
"updateMirror": "备用更新仓库",
|
||||||
"updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。",
|
"updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。",
|
||||||
"updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。",
|
"updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。",
|
||||||
@@ -524,11 +534,15 @@
|
|||||||
"reset": "恢复默认"
|
"reset": "恢复默认"
|
||||||
},
|
},
|
||||||
"diagnostics": {
|
"diagnostics": {
|
||||||
|
"recordLogs": "生成运行日志",
|
||||||
|
"recordLogsToggle": "记录启动器、本地服务器和钩子日志",
|
||||||
|
"recordLogsHint": "关闭后停止写入启动器日志、本地服务器流量日志和 wto_ws.log(不影响游戏引擎原生的 .game_logs)。导出日志排查问题前建议重新开启。",
|
||||||
|
"loggingDisabledNotice": "当前已关闭运行日志记录,导出的压缩包仅包含已有历史日志和配置。",
|
||||||
"logs": "日志",
|
"logs": "日志",
|
||||||
"logsHint": "启动器运行日志",
|
"logsHint": "启动器运行日志",
|
||||||
"openLogs": "打开日志文件夹",
|
"openLogs": "打开日志文件夹",
|
||||||
"export": "导出诊断信息",
|
"export": "导出诊断信息",
|
||||||
"exportHint": "导出包含日志、设置和安装记录的 ZIP 文件",
|
"exportHint": "导出包含启动器、本地服务器与游戏日志、设置和安装记录的 ZIP 文件(不含存档)",
|
||||||
"save": "导出…",
|
"save": "导出…",
|
||||||
"saved": "诊断信息已保存到 {{path}}。",
|
"saved": "诊断信息已保存到 {{path}}。",
|
||||||
"serverStatus": "本地服务器状态页",
|
"serverStatus": "本地服务器状态页",
|
||||||
@@ -566,6 +580,12 @@
|
|||||||
"about": {
|
"about": {
|
||||||
"launcher": "启动器 {{version}}",
|
"launcher": "启动器 {{version}}",
|
||||||
"supported": "支持的游戏版本:{{versions}}",
|
"supported": "支持的游戏版本:{{versions}}",
|
||||||
|
"feedback": {
|
||||||
|
"title": "问题反馈",
|
||||||
|
"export": "保存全部日志",
|
||||||
|
"exportHint": "打包启动器、本地服务器及游戏日志为 ZIP 文件以便反馈问题(不含存档)。",
|
||||||
|
"exportButton": "保存日志 ZIP…"
|
||||||
|
},
|
||||||
"pack": {
|
"pack": {
|
||||||
"title": "适配数据",
|
"title": "适配数据",
|
||||||
"current": "当前使用",
|
"current": "当前使用",
|
||||||
@@ -623,7 +643,17 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"statement": "项目信息",
|
"statement": "项目信息",
|
||||||
"statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。"
|
"statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。",
|
||||||
|
"homepage": {
|
||||||
|
"title": "项目主页",
|
||||||
|
"hint": "查看项目介绍、全部版本与社区入口。",
|
||||||
|
"open": "打开主页"
|
||||||
|
},
|
||||||
|
"community": {
|
||||||
|
"discord": "Discord",
|
||||||
|
"discordHint": "开发讨论、日常交流、使用求助与问题反馈。",
|
||||||
|
"openDiscord": "打开 Discord"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"features": {
|
"features": {
|
||||||
"A-Offline startup": "离线启动",
|
"A-Offline startup": "离线启动",
|
||||||
@@ -646,6 +676,7 @@
|
|||||||
"J-Ground arcade and realistic": "陆战(街机、历史)",
|
"J-Ground arcade and realistic": "陆战(街机、历史)",
|
||||||
"J-Air arcade and realistic": "空战(街机、历史)",
|
"J-Air arcade and realistic": "空战(街机、历史)",
|
||||||
"J-Naval arcade and realistic": "海战(街机、历史)",
|
"J-Naval arcade and realistic": "海战(街机、历史)",
|
||||||
|
"E-Crew skills in battle": "战局乘员技能与资格",
|
||||||
"J-Sub-modes": "附加模式(如夜战)",
|
"J-Sub-modes": "附加模式(如夜战)",
|
||||||
"K-AI opponents and teammates": "AI 对手与队友",
|
"K-AI opponents and teammates": "AI 对手与队友",
|
||||||
"K-Spawn score and respawns": "出生点数与重生",
|
"K-Spawn score and respawns": "出生点数与重生",
|
||||||
@@ -659,6 +690,96 @@
|
|||||||
"L-Debriefing": "战后结算",
|
"L-Debriefing": "战后结算",
|
||||||
"L-Battle awards": "战斗嘉奖"
|
"L-Battle awards": "战斗嘉奖"
|
||||||
},
|
},
|
||||||
|
"mods": {
|
||||||
|
"sections": {
|
||||||
|
"list": "模组列表",
|
||||||
|
"presets": "预设与仓库"
|
||||||
|
},
|
||||||
|
"loading": "正在读取模组信息…",
|
||||||
|
"noCopy": "请先安装或选择一个离线客户端,再为它配置模组。",
|
||||||
|
"enabledSummary": "已启用 {{enabled}} / {{total}}",
|
||||||
|
"experimentalChip": "实验功能",
|
||||||
|
"experimentalTitle": "实验期模组接口提示:",
|
||||||
|
"experimentalBody": "离线版当前处于极初期开发阶段(API {{api}})。服务端脚本钩子、内部数据结构及声明式 exe 补丁契约随时可能随本体更新变动且不保证向下兼容;请仅启用来源可信的模组。",
|
||||||
|
"readOnlyNotice": "游戏、本地服务器或维护任务运行期间,模组开关、排序与预设为只读。",
|
||||||
|
"searchPlaceholder": "搜索模组名称、ID 或作者…",
|
||||||
|
"autoSort": "按依赖自动排序",
|
||||||
|
"autoSorted": "已按前置与排序建议重新排列模组顺序。",
|
||||||
|
"refresh": "刷新",
|
||||||
|
"openFolder": "打开模组目录",
|
||||||
|
"openDocs": "开发文档",
|
||||||
|
"discoveryErrorsTitle": "有 {{count}} 个模组目录读取失败:",
|
||||||
|
"blockingIssuesTitle": "存在 {{count}} 项阻塞性模组错误(处理前无法启动):",
|
||||||
|
"issuesTitle": "检测到 {{count}} 项模组提示或冲突:",
|
||||||
|
"severity": {
|
||||||
|
"error": "错误",
|
||||||
|
"warning": "警告",
|
||||||
|
"info": "提示"
|
||||||
|
},
|
||||||
|
"emptyTitle": "当前模组目录里还没有模组。",
|
||||||
|
"emptyHint": "将包含 mod.jsonc 的模组文件夹放入 {{path}},点击「刷新」即可识别。独立涂装、瞄具与单人任务继续沿用游戏原生的 UserSkins / UserSights / UserMissions 目录即可。",
|
||||||
|
"noSearchMatch": "没有匹配当前搜索条件的模组。",
|
||||||
|
"loadOrderHint": "加载顺序:越靠后优先级越高(可拖动或使用上下按钮调整)",
|
||||||
|
"moveUp": "上移",
|
||||||
|
"moveDown": "下移",
|
||||||
|
"showDetails": "详情",
|
||||||
|
"hideDetails": "收起",
|
||||||
|
"errorCount": "{{count}} 错误",
|
||||||
|
"warnCount": "{{count}} 警告",
|
||||||
|
"badges": {
|
||||||
|
"data": "数据/资源",
|
||||||
|
"gui": "界面补丁",
|
||||||
|
"script": "服务端脚本",
|
||||||
|
"exe": "二进制补丁"
|
||||||
|
},
|
||||||
|
"details": {
|
||||||
|
"folder": "目录",
|
||||||
|
"gameVersions": "声明适配版本",
|
||||||
|
"requires": "前置依赖",
|
||||||
|
"conflicts": "已知互斥",
|
||||||
|
"tuning": "服务端数值叠加:{{count}} 份",
|
||||||
|
"serverScript": "含可执行服务端 JS/TS 脚本",
|
||||||
|
"packOps": "客户端数据包操作:{{count}} 项",
|
||||||
|
"addon": "独立 3D 模型/贴图扩展包:{{count}} 个文件",
|
||||||
|
"guiPatches": "界面脚本补丁:{{count}} 项",
|
||||||
|
"exePatches": "声明式 exe 补丁:{{count}} 项",
|
||||||
|
"companionFiles": "附带外置文件:{{count}} 个",
|
||||||
|
"configBlk": "含 config.blk 增量补丁"
|
||||||
|
},
|
||||||
|
"presets": {
|
||||||
|
"heading": "模组序列预设(当前客户端独立保存)",
|
||||||
|
"description": "将当前的启用开关与加载顺序保存为预设,方便在不同玩法配置间一键切换,或导出 JSON 分享给其他玩家。",
|
||||||
|
"quickSwitch": "快速切换模组预设",
|
||||||
|
"customOption": "当前自定义配置",
|
||||||
|
"namePlaceholder": "输入新预设名称,例如:现代载具包",
|
||||||
|
"saveCurrent": "保存为预设",
|
||||||
|
"import": "导入预设…",
|
||||||
|
"empty": "当前客户端尚未保存任何模组预设。",
|
||||||
|
"activeTag": "当前使用",
|
||||||
|
"summary": "启用 {{count}} / 共 {{total}} 个模组",
|
||||||
|
"apply": "应用",
|
||||||
|
"overwrite": "覆盖更新",
|
||||||
|
"export": "导出",
|
||||||
|
"delete": "删除",
|
||||||
|
"saved": "已保存预设「{{name}}」。",
|
||||||
|
"applied": "已切换至预设「{{name}}」。",
|
||||||
|
"updated": "已用当前配置覆盖预设「{{name}}」。",
|
||||||
|
"exported": "预设已导出到:{{path}}",
|
||||||
|
"imported": "已导入模组预设。"
|
||||||
|
},
|
||||||
|
"repo": {
|
||||||
|
"heading": "全局模组仓库位置",
|
||||||
|
"description": "所有客户端共享同一份模组文件仓库(大体积 3D 模型与贴图包通过跨盘目录联接点零拷贝挂载,不重复占用磁盘);每个客户端独立保存自己的开关、排序和预设。",
|
||||||
|
"pathLabel": "当前仓库目录",
|
||||||
|
"defaultNote": "使用启动器默认模组目录",
|
||||||
|
"customNote": "使用自定义模组目录(可放在大容量硬盘或游戏同盘)",
|
||||||
|
"changeFolder": "更改目录…",
|
||||||
|
"resetDefault": "恢复默认目录",
|
||||||
|
"pickTitle": "选择全局模组仓库目录",
|
||||||
|
"updated": "已更新全局模组仓库目录。",
|
||||||
|
"resetDone": "已恢复为默认模组仓库目录。"
|
||||||
|
}
|
||||||
|
},
|
||||||
"errors": {
|
"errors": {
|
||||||
"app_update_unavailable": "当前没有可安装的本体更新。",
|
"app_update_unavailable": "当前没有可安装的本体更新。",
|
||||||
"app_update_busy": "本体更新操作正在进行。",
|
"app_update_busy": "本体更新操作正在进行。",
|
||||||
@@ -682,10 +803,15 @@
|
|||||||
"save_avatar_invalid": "请选择此客户端中可用的头像。",
|
"save_avatar_invalid": "请选择此客户端中可用的头像。",
|
||||||
"save_level_invalid": "请输入此客户端支持的账号等级。",
|
"save_level_invalid": "请输入此客户端支持的账号等级。",
|
||||||
"tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。",
|
"tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。",
|
||||||
|
"mods_read_only": "游戏、本地服务器或维护任务运行期间无法修改模组配置。",
|
||||||
|
"mods_write_failed": "无法保存模组配置,请查看启动器日志。",
|
||||||
|
"mods_preset_invalid": "所选文件不是有效的 WTOffline 模组预设。",
|
||||||
|
"mods_blocking_issues": "当前启用的模组存在缺失前置或互斥冲突,请先在「模组」页面处理后再启动。",
|
||||||
|
"mods_folder_invalid": "所选全局模组目录无效或无法写入。",
|
||||||
"copy_not_found": "所选客户端已不可用。",
|
"copy_not_found": "所选客户端已不可用。",
|
||||||
"copies_write_failed": "无法保存客户端记录。",
|
"copies_write_failed": "无法保存客户端记录。",
|
||||||
"copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。",
|
"copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。",
|
||||||
"decal_source_invalid": "选定的目录缺少有效的贴花缓存。",
|
"decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版目录中的 cache/content(或 cache)。",
|
||||||
"decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。",
|
"decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。",
|
||||||
"maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。",
|
"maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。",
|
||||||
"maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。",
|
"maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。",
|
||||||
@@ -706,12 +832,14 @@
|
|||||||
"launch_steam_confirmation_required": "请在客户端维护中确认 Steam 目录后再启动。",
|
"launch_steam_confirmation_required": "请在客户端维护中确认 Steam 目录后再启动。",
|
||||||
"launch_location": "客户端、原版文件备份或数据目录的位置无效。",
|
"launch_location": "客户端、原版文件备份或数据目录的位置无效。",
|
||||||
"launch_stock_version": "原版文件备份的版本与客户端不一致。",
|
"launch_stock_version": "原版文件备份的版本与客户端不一致。",
|
||||||
|
"launch_stock_missing": "缺少或无法读取原版文件备份(wtoffline\\stock)。请检查安全软件拦截记录,或移除此客户端登记后重新添加。",
|
||||||
"launch_build_failed": "无法生成游戏文件。",
|
"launch_build_failed": "无法生成游戏文件。",
|
||||||
"launch_build_unavailable": "生成游戏文件时发现需要重新确认的不可用补丁。",
|
"launch_build_unavailable": "生成游戏文件时发现需要重新确认的不可用补丁。",
|
||||||
"launch_port_busy": "本地服务器端口已被占用。",
|
"launch_port_busy": "本地服务器端口已被占用。",
|
||||||
"launch_server_failed": "无法启动本地服务器。请查看启动器日志。",
|
"launch_server_failed": "无法启动本地服务器。请查看启动器日志。",
|
||||||
"launch_server_exited": "本地服务器不可用。",
|
"launch_server_exited": "本地服务器不可用。",
|
||||||
"launch_game_failed": "游戏进程无法启动。请查看启动器日志。",
|
"launch_game_failed": "游戏进程无法启动。请查看启动器日志。",
|
||||||
|
"launch_game_files_missing": "启动所需的核心文件缺失或无法访问(可能已被安全软件隔离)。请检查安全软件拦截记录或查看启动器日志。",
|
||||||
"settings_write_failed": "无法保存设置。",
|
"settings_write_failed": "无法保存设置。",
|
||||||
"folder_unreadable": "无法读取文件夹:{{path}}",
|
"folder_unreadable": "无法读取文件夹:{{path}}",
|
||||||
"not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}",
|
"not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}",
|
||||||
@@ -724,8 +852,8 @@
|
|||||||
"missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。",
|
"missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。",
|
||||||
"patch_check_failed": "检查补丁时出错。",
|
"patch_check_failed": "检查补丁时出错。",
|
||||||
"copy_failed": "复制游戏文件失败,已复制的文件已删除。",
|
"copy_failed": "复制游戏文件失败,已复制的文件已删除。",
|
||||||
"hardlink_unavailable": "省空间复制需要已核对的游戏版本,并且目标与原版位于同一磁盘卷。",
|
"hardlink_unavailable": "省空间复制要求目标与原版位于同一磁盘卷,转换已有客户端还要求版本一致。",
|
||||||
"hardlink_no_match": "文件内容与可共用的实测资源不一致。",
|
"hardlink_no_match": "未找到可共用的只读资源包,或文件内容与原版不一致。",
|
||||||
"hardlink_file_changed": "核对或复制过程中有资源文件发生变化。请等待其他文件操作完成后重试。",
|
"hardlink_file_changed": "核对或复制过程中有资源文件发生变化。请等待其他文件操作完成后重试。",
|
||||||
"install_cancelled": "安装已取消,已复制的文件已删除。",
|
"install_cancelled": "安装已取消,已复制的文件已删除。",
|
||||||
"install_busy": "已有安装正在进行。",
|
"install_busy": "已有安装正在进行。",
|
||||||
|
|||||||
@@ -1,20 +1,26 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Notice } from '../../components/Notice.tsx';
|
import { Notice } from '../../components/Notice.tsx';
|
||||||
import { Row } from '../../components/Row.tsx';
|
|
||||||
import { Sheet } from '../../components/Sheet.tsx';
|
import { Sheet } from '../../components/Sheet.tsx';
|
||||||
|
import { ipcInvoke } from '../../ipc.ts';
|
||||||
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
||||||
import { AppUpdateSection } from './AppUpdateSection.tsx';
|
import { AppUpdateSection } from './AppUpdateSection.tsx';
|
||||||
import type { PatchPackState } from '../../shell/usePatchPack.ts';
|
import type { PatchPackState } from '../../shell/usePatchPack.ts';
|
||||||
|
|
||||||
|
const HOMEPAGE_URL = 'https://wto-project.net';
|
||||||
|
const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
|
||||||
|
|
||||||
interface AboutPageProps {
|
interface AboutPageProps {
|
||||||
readonly launcherVersion: string;
|
readonly launcherVersion: string;
|
||||||
readonly supportedVersions: readonly string[];
|
readonly supportedVersions: readonly string[];
|
||||||
readonly patchPack: PatchPackState;
|
readonly patchPack: PatchPackState;
|
||||||
readonly appUpdate: AppUpdateState;
|
readonly appUpdate: AppUpdateState;
|
||||||
|
readonly loggingEnabled: boolean;
|
||||||
|
readonly onError: (error: unknown) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The launcher's version, the game versions it supports, adaptation pack updates, and the project statement. */
|
/** The launcher's version, the game versions it supports, updates, community links, log export, and the project statement. */
|
||||||
export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate }: AboutPageProps) {
|
export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate, loggingEnabled, onError }: AboutPageProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<Sheet title={t('nav.about')}>
|
<Sheet title={t('nav.about')}>
|
||||||
@@ -26,14 +32,97 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
|
|||||||
{t('about.supported', { versions: supportedVersions.join(', ') })}
|
{t('about.supported', { versions: supportedVersions.join(', ') })}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<AppUpdateSection state={appUpdate} />
|
<div className="about-columns">
|
||||||
<PatchPackSection state={patchPack} />
|
<div className="about-column">
|
||||||
<h3 className="section-title section-title-spaced">{t('about.statement')}</h3>
|
<AppUpdateSection state={appUpdate} />
|
||||||
<p className="lead">{t('about.statementBody')}</p>
|
<PatchPackSection state={patchPack} />
|
||||||
|
</div>
|
||||||
|
<div className="about-column">
|
||||||
|
<HomepageSection />
|
||||||
|
<CommunitySection />
|
||||||
|
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
|
||||||
|
<section className="about-card">
|
||||||
|
<h3 className="about-card-title">{t('about.statement')}</h3>
|
||||||
|
<p className="about-card-meta">{t('about.statementBody')}</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</Sheet>
|
</Sheet>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function HomepageSection() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<section className="about-card">
|
||||||
|
<div className="about-card-head">
|
||||||
|
<h3 className="about-card-title">{t('about.homepage.title')}</h3>
|
||||||
|
<div className="about-card-actions">
|
||||||
|
<a className="button" href={HOMEPAGE_URL} target="_blank" rel="noreferrer">
|
||||||
|
{t('about.homepage.open')}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="about-card-meta">{t('about.homepage.hint')}</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommunitySection() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<section className="about-card">
|
||||||
|
<div className="about-card-head">
|
||||||
|
<h3 className="about-card-title">{t('about.community.discord')}</h3>
|
||||||
|
<div className="about-card-actions">
|
||||||
|
<a className="button" href={DISCORD_INVITE_URL} target="_blank" rel="noreferrer">
|
||||||
|
{t('about.community.openDiscord')}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="about-card-meta">{t('about.community.discordHint')}</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function FeedbackLogsSection({ loggingEnabled, onError }: {
|
||||||
|
readonly loggingEnabled: boolean;
|
||||||
|
readonly onError: (error: unknown) => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [exporting, setExporting] = useState(false);
|
||||||
|
const [savedPath, setSavedPath] = useState<string | null>(null);
|
||||||
|
|
||||||
|
async function save(): Promise<void> {
|
||||||
|
setExporting(true);
|
||||||
|
setSavedPath(null);
|
||||||
|
try {
|
||||||
|
const result = await ipcInvoke('app:exportDiagnostics');
|
||||||
|
setSavedPath(result.path);
|
||||||
|
} catch (error) {
|
||||||
|
onError(error);
|
||||||
|
} finally {
|
||||||
|
setExporting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="about-card">
|
||||||
|
<div className="about-card-head">
|
||||||
|
<h3 className="about-card-title">{t('about.feedback.title')}</h3>
|
||||||
|
<div className="about-card-actions">
|
||||||
|
<button type="button" className="button" disabled={exporting} onClick={() => { void save(); }}>
|
||||||
|
{t('about.feedback.exportButton')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="about-card-meta">{t('about.feedback.exportHint')}</p>
|
||||||
|
{!loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
|
||||||
|
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function PatchPackSection({ state }: { readonly state: PatchPackState }) {
|
function PatchPackSection({ state }: { readonly state: PatchPackState }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { active, check, busy } = state;
|
const { active, check, busy } = state;
|
||||||
@@ -45,25 +134,30 @@ function PatchPackSection({ state }: { readonly state: PatchPackState }) {
|
|||||||
? t('about.pack.bundledVersion', { version: active.version })
|
? t('about.pack.bundledVersion', { version: active.version })
|
||||||
: t('about.pack.bundled');
|
: t('about.pack.bundled');
|
||||||
return (
|
return (
|
||||||
<>
|
<section className="about-card">
|
||||||
<h3 className="section-title">{t('about.pack.title')}</h3>
|
<div className="about-card-head">
|
||||||
<Row label={t('about.pack.current')} hint={t('about.pack.currentHint')}>
|
<h3 className="about-card-title">{t('about.pack.title')}</h3>
|
||||||
<span>{current}</span>
|
<div className="about-card-actions">
|
||||||
{active?.source === 'downloaded' && (
|
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
||||||
<button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}>
|
{busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')}
|
||||||
{t('about.pack.useBundled')}
|
|
||||||
</button>
|
</button>
|
||||||
)}
|
{active?.source === 'downloaded' && (
|
||||||
</Row>
|
<button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}>
|
||||||
<Row label={t('about.pack.check')} hint={t('about.pack.checkHint')}>
|
{t('about.pack.useBundled')}
|
||||||
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
</button>
|
||||||
{busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')}
|
)}
|
||||||
</button>
|
</div>
|
||||||
</Row>
|
</div>
|
||||||
|
<p className="about-card-meta">
|
||||||
|
<span className="about-card-label">{t('about.pack.current')}</span>
|
||||||
|
{' · '}
|
||||||
|
{current}
|
||||||
|
</p>
|
||||||
|
<p className="small">{t('about.pack.currentHint')}</p>
|
||||||
{busy === 'applying' && <p className="small">{t('about.pack.applying')}</p>}
|
{busy === 'applying' && <p className="small">{t('about.pack.applying')}</p>}
|
||||||
{state.applyFailure && <Notice tone="error"><p>{t(`about.pack.applyFailed.${state.applyFailure}`)}</p></Notice>}
|
{state.applyFailure && <Notice tone="error"><p>{t(`about.pack.applyFailed.${state.applyFailure}`)}</p></Notice>}
|
||||||
{check && busy !== 'checking' && <CheckResult state={state} />}
|
{check && busy !== 'checking' && <CheckResult state={state} />}
|
||||||
</>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Notice } from '../../components/Notice.tsx';
|
import { Notice } from '../../components/Notice.tsx';
|
||||||
import { ProgressBar } from '../../components/ProgressBar.tsx';
|
import { ProgressBar } from '../../components/ProgressBar.tsx';
|
||||||
import { Row } from '../../components/Row.tsx';
|
|
||||||
import { formatBytes } from '../../format.ts';
|
import { formatBytes } from '../../format.ts';
|
||||||
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
||||||
|
|
||||||
@@ -10,13 +9,16 @@ export function AppUpdateSection({ state }: { readonly state: AppUpdateState })
|
|||||||
if (!state.supported) return null;
|
if (!state.supported) return null;
|
||||||
const { check, busy, progress } = state;
|
const { check, busy, progress } = state;
|
||||||
return (
|
return (
|
||||||
<>
|
<section className="about-card">
|
||||||
<h3 className="section-title">{t('about.update.title')}</h3>
|
<div className="about-card-head">
|
||||||
<Row label={t('about.update.check')}>
|
<h3 className="about-card-title">{t('about.update.title')}</h3>
|
||||||
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
<div className="about-card-actions">
|
||||||
{t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')}
|
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
||||||
</button>
|
{t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')}
|
||||||
</Row>
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="about-card-meta">{t('about.update.check')}</p>
|
||||||
{check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>}
|
{check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>}
|
||||||
{check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
|
{check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
|
||||||
{check?.status === 'available' && busy !== 'checking' && (
|
{check?.status === 'available' && busy !== 'checking' && (
|
||||||
@@ -43,6 +45,6 @@ export function AppUpdateSection({ state }: { readonly state: AppUpdateState })
|
|||||||
)}
|
)}
|
||||||
</Notice>
|
</Notice>
|
||||||
)}
|
)}
|
||||||
</>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,29 +1,24 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import type { IpcInput } from '@shared/ipc/contract.ts';
|
|
||||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||||
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
|
import type { MaintenanceInfo, MaintenanceProgress } from '@shared/schemas/maintenance.ts';
|
||||||
import { ProgressBar } from '../../components/ProgressBar.tsx';
|
import { ProgressBar } from '../../components/ProgressBar.tsx';
|
||||||
import { Sheet } from '../../components/Sheet.tsx';
|
import { Sheet } from '../../components/Sheet.tsx';
|
||||||
import { formatBytes } from '../../format.ts';
|
import { formatBytes } from '../../format.ts';
|
||||||
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
|
import { ipcInvoke } from '../../ipc.ts';
|
||||||
import { CopyMaintenanceActions, CopyRemoval, type CopyRemovalOptions } from './CopyMaintenanceControls.tsx';
|
import { CopyMaintenanceActions, CopyRemoval, type CopyRemovalOptions } from './CopyMaintenanceControls.tsx';
|
||||||
|
import type { CopyMaintenanceState, MaintenanceOperation, MaintenanceOptions } from './useCopyMaintenance.ts';
|
||||||
|
|
||||||
interface CopyMaintenanceProps {
|
interface CopyMaintenanceProps {
|
||||||
readonly record: InstallRecord;
|
readonly record: InstallRecord;
|
||||||
|
readonly maintenance: CopyMaintenanceState;
|
||||||
readonly onError: (error: unknown) => void;
|
readonly onError: (error: unknown) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
type Operation = MaintenanceRequest['operation'];
|
export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanceProps) {
|
||||||
type OperationOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
|
|
||||||
|
|
||||||
export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
|
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [info, setInfo] = useState<MaintenanceInfo | null>(null);
|
const [info, setInfo] = useState<MaintenanceInfo | null>(null);
|
||||||
const [working, setWorking] = useState<Operation | null>(null);
|
|
||||||
const [progress, setProgress] = useState<MaintenanceProgress | null>(null);
|
|
||||||
const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null);
|
const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null);
|
||||||
const [result, setResult] = useState<Operation | 'cancelled' | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
let mounted = true;
|
||||||
@@ -31,29 +26,17 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
|
|||||||
if (mounted) setInfo(value);
|
if (mounted) setInfo(value);
|
||||||
}).catch(onError);
|
}).catch(onError);
|
||||||
return () => { mounted = false; };
|
return () => { mounted = false; };
|
||||||
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, onError]);
|
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, maintenance.revision, onError]);
|
||||||
|
|
||||||
useEffect(() => ipcOn('event:copy-maintenance', (event) => {
|
const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
|
||||||
if (event.id === record.id) setProgress(event);
|
if (operation === 'delete') setRemoval(null);
|
||||||
}), [record.id]);
|
maintenance.run(record.id, operation, options);
|
||||||
|
|
||||||
const run = (operation: Operation, options: OperationOptions = {}): void => {
|
|
||||||
setResult(null);
|
|
||||||
setWorking(operation);
|
|
||||||
setProgress(null);
|
|
||||||
ipcInvoke('copies:maintain', { id: record.id, operation, ...options })
|
|
||||||
.then(() => {
|
|
||||||
setResult(operation);
|
|
||||||
setRemoval(null);
|
|
||||||
})
|
|
||||||
.catch((error: unknown) => {
|
|
||||||
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') setResult('cancelled');
|
|
||||||
else onError(error);
|
|
||||||
})
|
|
||||||
.finally(() => setWorking(null));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const busy = working !== null;
|
const active = maintenance.active;
|
||||||
|
const busy = active !== null;
|
||||||
|
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sheet title={t('copies.sections.maintain')} aside={record.name}>
|
<Sheet title={t('copies.sections.maintain')} aside={record.name}>
|
||||||
<CopyMaintenanceActions
|
<CopyMaintenanceActions
|
||||||
@@ -71,32 +54,25 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
|
|||||||
onOptionsChange={setRemoval}
|
onOptionsChange={setRemoval}
|
||||||
onRemove={(deleteData) => run('delete', { deleteData })}
|
onRemove={(deleteData) => run('delete', { deleteData })}
|
||||||
/>
|
/>
|
||||||
{working && (
|
{active && <MaintenanceStatus progress={active} onCancel={maintenance.cancel} />}
|
||||||
<MaintenanceStatus
|
|
||||||
operation={working}
|
|
||||||
progress={progress}
|
|
||||||
onCancel={() => ipcInvoke('copies:cancelMaintenance').catch(onError)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
|
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
|
||||||
</Sheet>
|
</Sheet>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
interface MaintenanceStatusProps {
|
interface MaintenanceStatusProps {
|
||||||
readonly operation: Operation;
|
readonly progress: MaintenanceProgress;
|
||||||
readonly progress: MaintenanceProgress | null;
|
|
||||||
readonly onCancel: () => void;
|
readonly onCancel: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function MaintenanceStatus({ operation, progress, onCancel }: MaintenanceStatusProps) {
|
function MaintenanceStatus({ progress, onCancel }: MaintenanceStatusProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<div className="maintenance-progress" role="status">
|
<div className="maintenance-progress" role="status">
|
||||||
<p>{t(`copies.maintenance.phase.${progress?.phase ?? 'checking'}`)}</p>
|
<p>{t(`copies.maintenance.phase.${progress.phase}`)}</p>
|
||||||
<ProgressBar value={progress?.doneBytes ?? 0} max={progress?.totalBytes || null} />
|
<ProgressBar value={progress.doneBytes} max={progress.totalBytes || null} />
|
||||||
{progress?.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
|
{progress.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
|
||||||
{(operation === 'update' || operation === 'compact') && progress?.phase !== 'applying' && (
|
{(progress.operation === 'update' || progress.operation === 'compact') && progress.phase !== 'applying' && (
|
||||||
<button type="button" className="button" onClick={onCancel}>
|
<button type="button" className="button" onClick={onCancel}>
|
||||||
{t('wizard.cancel')}
|
{t('wizard.cancel')}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -32,7 +32,9 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSte
|
|||||||
)}
|
)}
|
||||||
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion
|
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion
|
||||||
? t(info.updateAvailable
|
? t(info.updateAvailable
|
||||||
? (record.hardlinkedFiles?.length ? 'copies.maintenance.updateDetaches' : 'copies.maintenance.newVersion')
|
? (record.hardlinkedFiles?.length
|
||||||
|
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
|
||||||
|
: 'copies.maintenance.newVersion')
|
||||||
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
|
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
|
||||||
: t('copies.maintenance.noSource')}>
|
: t('copies.maintenance.noSource')}>
|
||||||
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
|
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import type { IpcInput } from '@shared/ipc/contract.ts';
|
||||||
|
import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
|
||||||
|
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
|
||||||
|
|
||||||
|
export type MaintenanceOperation = MaintenanceRequest['operation'];
|
||||||
|
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
|
||||||
|
|
||||||
|
export interface MaintenanceOutcome {
|
||||||
|
readonly copyId: string;
|
||||||
|
readonly outcome: MaintenanceOperation | 'cancelled';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tracks copy maintenance across tab switches so progress and busy state survive unmounting the maintenance page. */
|
||||||
|
export function useCopyMaintenance(onError: (error: unknown) => void) {
|
||||||
|
const [active, setActive] = useState<MaintenanceProgress | null>(null);
|
||||||
|
const [lastResult, setLastResult] = useState<MaintenanceOutcome | null>(null);
|
||||||
|
const [revision, setRevision] = useState(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
let receivedEvent = false;
|
||||||
|
const dispose = ipcOn('event:copy-maintenance', (event) => {
|
||||||
|
receivedEvent = true;
|
||||||
|
setActive(event);
|
||||||
|
if (event === null) setRevision((value) => value + 1);
|
||||||
|
});
|
||||||
|
ipcInvoke('copies:maintenanceState').then((state) => {
|
||||||
|
if (mounted && !receivedEvent) setActive(state);
|
||||||
|
}).catch(onError);
|
||||||
|
return () => { mounted = false; dispose(); };
|
||||||
|
}, [onError]);
|
||||||
|
|
||||||
|
const run = useCallback((id: string, operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
|
||||||
|
setLastResult(null);
|
||||||
|
setActive({ id, operation, phase: 'checking', doneBytes: 0, totalBytes: 0 });
|
||||||
|
ipcInvoke('copies:maintain', { id, operation, ...options })
|
||||||
|
.then(() => {
|
||||||
|
setLastResult({ copyId: id, outcome: operation });
|
||||||
|
})
|
||||||
|
.catch((error: unknown) => {
|
||||||
|
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') {
|
||||||
|
setLastResult({ copyId: id, outcome: 'cancelled' });
|
||||||
|
} else {
|
||||||
|
onError(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
setActive((current) => (current?.id === id && current.operation === operation ? null : current));
|
||||||
|
});
|
||||||
|
}, [onError]);
|
||||||
|
|
||||||
|
const cancel = useCallback((): void => {
|
||||||
|
ipcInvoke('copies:cancelMaintenance').catch(onError);
|
||||||
|
}, [onError]);
|
||||||
|
|
||||||
|
return { active, lastResult, revision, run, cancel };
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CopyMaintenanceState = ReturnType<typeof useCopyMaintenance>;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { TFunction } from 'i18next';
|
import type { TFunction } from 'i18next';
|
||||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||||
import type { LaunchState } from '@shared/schemas/launch.ts';
|
import { formatExitCode, type LaunchState } from '@shared/schemas/launch.ts';
|
||||||
import type { BarModel } from '../../shell/bar-model.ts';
|
import type { BarModel } from '../../shell/bar-model.ts';
|
||||||
import { missingFeatures } from '../copies/missing-features.ts';
|
import { missingFeatures } from '../copies/missing-features.ts';
|
||||||
|
|
||||||
@@ -24,8 +24,11 @@ export function homeBar(
|
|||||||
const starting = { label: t('launch.starting'), disabled: true };
|
const starting = { label: t('launch.starting'), disabled: true };
|
||||||
const progress = { value: state.filesWritten ?? 0, max: state.filesTotal || null };
|
const progress = { value: state.filesWritten ?? 0, max: state.filesTotal || null };
|
||||||
const { gameExit } = state;
|
const { gameExit } = state;
|
||||||
|
const exitCodeLabel = gameExit
|
||||||
|
? (gameExit.code !== null ? formatExitCode(gameExit.code) : (gameExit.signal ?? t('launch.exitCodeUnknown')))
|
||||||
|
: undefined;
|
||||||
const exitDetail = gameExit && gameExit.code !== 0
|
const exitDetail = gameExit && gameExit.code !== 0
|
||||||
? t('launch.exitDetail', { code: gameExit.code ?? gameExit.signal ?? t('launch.exitCodeUnknown'), path: gameExit.logFolder })
|
? t('launch.exitDetail', { code: exitCodeLabel, path: gameExit.logFolder })
|
||||||
: undefined;
|
: undefined;
|
||||||
switch (state.phase) {
|
switch (state.phase) {
|
||||||
case 'checking':
|
case 'checking':
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import type { DataFolderProblem } from '@shared/schemas/install.ts';
|
||||||
import { FolderField } from '../../components/FolderField.tsx';
|
import { FolderField } from '../../components/FolderField.tsx';
|
||||||
import { Notice } from '../../components/Notice.tsx';
|
import { Notice } from '../../components/Notice.tsx';
|
||||||
import { Row } from '../../components/Row.tsx';
|
import { Row } from '../../components/Row.tsx';
|
||||||
|
|
||||||
interface DataStepProps {
|
interface DataStepProps {
|
||||||
readonly dataPath: string;
|
readonly dataPath: string;
|
||||||
|
readonly dataProblem: DataFolderProblem | null;
|
||||||
readonly decalSource: string | null;
|
readonly decalSource: string | null;
|
||||||
readonly steamDataPath: string | null;
|
readonly steamDataPath: string | null;
|
||||||
readonly steamDataConfirmed: boolean;
|
readonly steamDataConfirmed: boolean;
|
||||||
@@ -15,13 +17,14 @@ interface DataStepProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Step 3: where saves, caches and logs of the offline version are kept. */
|
/** Step 3: where saves, caches and logs of the offline version are kept. */
|
||||||
export function DataStep({ dataPath, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) {
|
export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<p className="lead">{t('data.body')}</p>
|
<p className="lead">{t('data.body')}</p>
|
||||||
<FolderField path={dataPath} dialogTitle={t('data.dialogTitle')} onChosen={onDataPath} onError={onError} />
|
<FolderField path={dataPath} dialogTitle={t('data.dialogTitle')} onChosen={onDataPath} onError={onError} />
|
||||||
{steamDataPath && (
|
{dataProblem && <Notice tone="error">{t(`data.problem.${dataProblem}`)}</Notice>}
|
||||||
|
{!dataProblem && steamDataPath && (
|
||||||
<Notice tone="warning">
|
<Notice tone="warning">
|
||||||
<p>{t('steam.dataWarning')}</p>
|
<p>{t('steam.dataWarning')}</p>
|
||||||
<p className="small">{steamDataPath}</p>
|
<p className="small">{steamDataPath}</p>
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
|
|||||||
{step === 'data' && (
|
{step === 'data' && (
|
||||||
<DataStep
|
<DataStep
|
||||||
dataPath={wizard.dataPath}
|
dataPath={wizard.dataPath}
|
||||||
|
dataProblem={wizard.dataProblem}
|
||||||
steamDataPath={wizard.steamDataPath}
|
steamDataPath={wizard.steamDataPath}
|
||||||
steamDataConfirmed={wizard.steamDataConfirmed}
|
steamDataConfirmed={wizard.steamDataConfirmed}
|
||||||
onSteamDataConfirmed={wizard.setSteamDataConfirmed}
|
onSteamDataConfirmed={wizard.setSteamDataConfirmed}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import type { FolderSize, GameFolderInspection, InstallProgress, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
import type { DataFolderProblem, FolderSize, GameFolderInspection, InstallProgress, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
||||||
import { ipcInvoke, ipcOn } from '../../ipc.ts';
|
import { ipcInvoke, ipcOn } from '../../ipc.ts';
|
||||||
import { useErrorMessage } from '../../useErrorMessage.ts';
|
import { useErrorMessage } from '../../useErrorMessage.ts';
|
||||||
import { checkUsable } from './CheckStep.tsx';
|
import { checkUsable } from './CheckStep.tsx';
|
||||||
@@ -33,7 +33,13 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
|||||||
const [draftId, setDraftId] = useState<string | null>(null);
|
const [draftId, setDraftId] = useState<string | null>(null);
|
||||||
const [name, setName] = useState('');
|
const [name, setName] = useState('');
|
||||||
const [dataPath, setDataPath] = useState('');
|
const [dataPath, setDataPath] = useState('');
|
||||||
const [dataInspection, setDataInspection] = useState<{ picked: string; path: string; inSteam: boolean; confirmed: boolean } | null>(null);
|
const [dataInspection, setDataInspection] = useState<{
|
||||||
|
key: string;
|
||||||
|
path: string;
|
||||||
|
inSteam: boolean;
|
||||||
|
problem: DataFolderProblem | null;
|
||||||
|
confirmed: boolean;
|
||||||
|
} | null>(null);
|
||||||
const [decalSource, setDecalSource] = useState<string | null>(null);
|
const [decalSource, setDecalSource] = useState<string | null>(null);
|
||||||
const [check, setCheck] = useState<PatchCheck | null>(null);
|
const [check, setCheck] = useState<PatchCheck | null>(null);
|
||||||
const [missingAccepted, setMissingAccepted] = useState(false);
|
const [missingAccepted, setMissingAccepted] = useState(false);
|
||||||
@@ -53,22 +59,38 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
|||||||
};
|
};
|
||||||
}, [source, report]);
|
}, [source, report]);
|
||||||
|
|
||||||
|
const plannedCopyPath = choice.method === 'in-place' || choice.method === 'existing'
|
||||||
|
? (source?.path ?? null)
|
||||||
|
: (choice.target?.path ?? null);
|
||||||
|
const plannedSourcePath = choice.method === 'copy' || choice.method === 'hardlink'
|
||||||
|
? (source?.path ?? null)
|
||||||
|
: null;
|
||||||
|
const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null;
|
||||||
|
const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!active || !dataPath) return;
|
if (!active || !dataPath) return;
|
||||||
let current = true;
|
let current = true;
|
||||||
ipcInvoke('install:inspectDataFolder', { path: dataPath })
|
ipcInvoke('install:inspectDataFolder', {
|
||||||
.then(({ path, inSteam }) => {
|
path: dataPath,
|
||||||
|
...(plannedCopyPath ? { copyPath: plannedCopyPath } : {}),
|
||||||
|
...(plannedSourcePath ? { sourcePath: plannedSourcePath } : {}),
|
||||||
|
...(plannedStockSourcePath ? { stockSourcePath: plannedStockSourcePath } : {}),
|
||||||
|
})
|
||||||
|
.then(({ path, inSteam, problem }) => {
|
||||||
if (!current) return;
|
if (!current) return;
|
||||||
setDataInspection((previous) => previous?.picked === dataPath && previous.path === path && previous.inSteam === inSteam
|
setDataInspection((previous) => previous?.key === dataInspectionKey && previous.path === path &&
|
||||||
|
previous.inSteam === inSteam && previous.problem === problem
|
||||||
? previous
|
? previous
|
||||||
: { picked: dataPath, path, inSteam, confirmed: false });
|
: { key: dataInspectionKey, path, inSteam, problem, confirmed: false });
|
||||||
})
|
})
|
||||||
.catch((error: unknown) => current && report(error));
|
.catch((error: unknown) => current && report(error));
|
||||||
return () => { current = false; };
|
return () => { current = false; };
|
||||||
}, [active, dataPath, report]);
|
}, [active, dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath, dataInspectionKey, report]);
|
||||||
|
|
||||||
const dataChecked = dataInspection?.picked === dataPath ? dataInspection : null;
|
const dataChecked = dataInspection?.key === dataInspectionKey ? dataInspection : null;
|
||||||
const dataReady = dataChecked !== null && (!dataChecked.inSteam || dataChecked.confirmed);
|
const dataProblem = dataChecked?.problem ?? null;
|
||||||
|
const dataReady = dataChecked !== null && dataProblem === null && (!dataChecked.inSteam || dataChecked.confirmed);
|
||||||
const setSteamDataConfirmed = (confirmed: boolean): void => {
|
const setSteamDataConfirmed = (confirmed: boolean): void => {
|
||||||
setDataInspection((inspection) => inspection ? { ...inspection, confirmed } : null);
|
setDataInspection((inspection) => inspection ? { ...inspection, confirmed } : null);
|
||||||
};
|
};
|
||||||
@@ -208,7 +230,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn,
|
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn,
|
||||||
steamDataPath: dataChecked?.inSteam ? dataChecked.path : null, steamDataConfirmed: dataChecked?.confirmed ?? false,
|
steamDataPath: dataChecked?.inSteam ? dataChecked.path : null, steamDataConfirmed: dataChecked?.confirmed ?? false,
|
||||||
start, back, next, cancel, report, chooseMode, chooseSource, setStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted,
|
start, back, next, cancel, report, chooseMode, chooseSource, setStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,591 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useState, type DragEvent, type FormEvent } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||||
|
import type { ModIssueView, ModListItem, ModsStateView } from '@shared/schemas/mods.ts';
|
||||||
|
import { Row } from '../../components/Row.tsx';
|
||||||
|
import { Sheet } from '../../components/Sheet.tsx';
|
||||||
|
import { ipcInvoke } from '../../ipc.ts';
|
||||||
|
import type { ModsSection } from '../../shell/navigation.ts';
|
||||||
|
|
||||||
|
const MOD_DOCS_URL = 'https://wto-project.net/mod-docs';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
readonly copy: InstallRecord;
|
||||||
|
readonly section: ModsSection;
|
||||||
|
readonly readOnly: boolean;
|
||||||
|
readonly onError: (error: unknown) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function localized(value: string | Readonly<Record<string, string>> | undefined, language: string): string {
|
||||||
|
if (!value) return '';
|
||||||
|
if (typeof value === 'string') return value;
|
||||||
|
const exact = value[language];
|
||||||
|
if (exact) return exact;
|
||||||
|
const prefix = language.split('-')[0];
|
||||||
|
if (prefix) {
|
||||||
|
const match = Object.entries(value).find(([key]) => key === prefix || key.startsWith(`${prefix}-`));
|
||||||
|
if (match?.[1]) return match[1];
|
||||||
|
}
|
||||||
|
return value.en ?? value['en-US'] ?? Object.values(value)[0] ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ModsPage({ copy, section, readOnly, onError }: Props) {
|
||||||
|
const { t, i18n } = useTranslation();
|
||||||
|
const [state, setState] = useState<ModsStateView | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [query, setQuery] = useState('');
|
||||||
|
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||||
|
const [draggedId, setDraggedId] = useState<string | null>(null);
|
||||||
|
const [presetName, setPresetName] = useState('');
|
||||||
|
const [notice, setNotice] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const load = useCallback(() => {
|
||||||
|
setBusy(true);
|
||||||
|
ipcInvoke('mods:getState', { copyId: copy.id })
|
||||||
|
.then(setState)
|
||||||
|
.catch(onError)
|
||||||
|
.finally(() => setBusy(false));
|
||||||
|
}, [copy.id, onError]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
const sync = (): void => {
|
||||||
|
ipcInvoke('mods:getState', { copyId: copy.id })
|
||||||
|
.then((result) => { if (mounted) setState(result); })
|
||||||
|
.catch(onError);
|
||||||
|
};
|
||||||
|
sync();
|
||||||
|
window.addEventListener('focus', sync);
|
||||||
|
return () => {
|
||||||
|
mounted = false;
|
||||||
|
window.removeEventListener('focus', sync);
|
||||||
|
};
|
||||||
|
}, [copy.id, onError]);
|
||||||
|
|
||||||
|
const runAction = (action: Promise<ModsStateView>, successNotice?: string): void => {
|
||||||
|
setBusy(true);
|
||||||
|
setNotice(null);
|
||||||
|
action
|
||||||
|
.then((next) => {
|
||||||
|
setState(next);
|
||||||
|
if (successNotice) setNotice(successNotice);
|
||||||
|
})
|
||||||
|
.catch(onError)
|
||||||
|
.finally(() => setBusy(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
const issuesByMod = useMemo(() => {
|
||||||
|
const map = new Map<string, ModIssueView[]>();
|
||||||
|
for (const issue of state?.issues ?? []) {
|
||||||
|
const list = map.get(issue.modId) ?? [];
|
||||||
|
list.push(issue);
|
||||||
|
map.set(issue.modId, list);
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}, [state]);
|
||||||
|
|
||||||
|
const title = t(`mods.sections.${section}`);
|
||||||
|
if (!state) {
|
||||||
|
return <Sheet title={title} aside={copy.name}><p className="lead">{t('mods.loading')}</p></Sheet>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const disabled = readOnly || busy;
|
||||||
|
const enabledCount = state.mods.filter((mod) => state.enabled[mod.id] === true).length;
|
||||||
|
|
||||||
|
const toggleMod = (modId: string, nextEnabled: boolean): void => {
|
||||||
|
runAction(ipcInvoke('mods:setEnabled', { copyId: copy.id, modId, enabled: nextEnabled }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const reorder = (nextOrder: string[]): void => {
|
||||||
|
runAction(ipcInvoke('mods:setOrder', { copyId: copy.id, order: nextOrder }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const moveMod = (modId: string, delta: -1 | 1): void => {
|
||||||
|
const idx = state.order.indexOf(modId);
|
||||||
|
const target = idx + delta;
|
||||||
|
if (idx < 0 || target < 0 || target >= state.order.length) return;
|
||||||
|
const next = [...state.order];
|
||||||
|
const [item] = next.splice(idx, 1);
|
||||||
|
next.splice(target, 0, item!);
|
||||||
|
reorder(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDrop = (targetId: string, event: DragEvent<HTMLDivElement>): void => {
|
||||||
|
event.preventDefault();
|
||||||
|
const sourceId = draggedId;
|
||||||
|
setDraggedId(null);
|
||||||
|
if (!sourceId || sourceId === targetId || disabled) return;
|
||||||
|
const from = state.order.indexOf(sourceId);
|
||||||
|
const to = state.order.indexOf(targetId);
|
||||||
|
if (from < 0 || to < 0) return;
|
||||||
|
const next = [...state.order];
|
||||||
|
const [moved] = next.splice(from, 1);
|
||||||
|
next.splice(to, 0, moved!);
|
||||||
|
reorder(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const savePreset = (event: FormEvent<HTMLFormElement>): void => {
|
||||||
|
event.preventDefault();
|
||||||
|
const trimmed = presetName.trim();
|
||||||
|
if (!trimmed) return;
|
||||||
|
runAction(
|
||||||
|
ipcInvoke('mods:savePreset', { copyId: copy.id, name: trimmed }),
|
||||||
|
t('mods.presets.saved', { name: trimmed }),
|
||||||
|
);
|
||||||
|
setPresetName('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const pickCustomFolder = (): void => {
|
||||||
|
ipcInvoke('dialog:pickFolder', { title: t('mods.repo.pickTitle') })
|
||||||
|
.then(({ path }) => {
|
||||||
|
if (!path) return;
|
||||||
|
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path }), t('mods.repo.updated'));
|
||||||
|
})
|
||||||
|
.catch(onError);
|
||||||
|
};
|
||||||
|
|
||||||
|
const resetFolder = (): void => {
|
||||||
|
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path: null }), t('mods.repo.resetDone'));
|
||||||
|
};
|
||||||
|
|
||||||
|
const exportPreset = (presetId: string): void => {
|
||||||
|
setBusy(true);
|
||||||
|
setNotice(null);
|
||||||
|
ipcInvoke('mods:exportPreset', { copyId: copy.id, presetId })
|
||||||
|
.then(({ path }) => {
|
||||||
|
if (path) setNotice(t('mods.presets.exported', { path }));
|
||||||
|
})
|
||||||
|
.catch(onError)
|
||||||
|
.finally(() => setBusy(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
const importPreset = (): void => {
|
||||||
|
setBusy(true);
|
||||||
|
setNotice(null);
|
||||||
|
ipcInvoke('mods:importPreset', { copyId: copy.id })
|
||||||
|
.then(({ imported, state: next }) => {
|
||||||
|
setState(next);
|
||||||
|
if (imported) setNotice(t('mods.presets.imported'));
|
||||||
|
})
|
||||||
|
.catch(onError)
|
||||||
|
.finally(() => setBusy(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
const normalizedQuery = query.trim().toLowerCase();
|
||||||
|
const visibleMods = normalizedQuery
|
||||||
|
? state.mods.filter((mod) => {
|
||||||
|
const displayName = localized(mod.name, i18n.language).toLowerCase();
|
||||||
|
return displayName.includes(normalizedQuery)
|
||||||
|
|| mod.id.toLowerCase().includes(normalizedQuery)
|
||||||
|
|| mod.author.toLowerCase().includes(normalizedQuery);
|
||||||
|
})
|
||||||
|
: state.mods;
|
||||||
|
|
||||||
|
const canDrag = !disabled && normalizedQuery.length === 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sheet
|
||||||
|
title={title}
|
||||||
|
aside={(
|
||||||
|
<span className="mods-aside">
|
||||||
|
<span>{copy.name} · {t('mods.enabledSummary', { enabled: enabledCount, total: state.mods.length })}</span>
|
||||||
|
<span
|
||||||
|
className="mods-exp-chip"
|
||||||
|
tabIndex={0}
|
||||||
|
aria-label={t('mods.experimentalBody', { api: state.apiVersion })}
|
||||||
|
>
|
||||||
|
<span>{t('mods.experimentalChip')}</span>
|
||||||
|
<span className="mods-exp-icon" aria-hidden="true">i</span>
|
||||||
|
<span className="mods-exp-popover" role="tooltip">
|
||||||
|
<strong>{t('mods.experimentalTitle')}</strong>
|
||||||
|
<span>{t('mods.experimentalBody', { api: state.apiVersion })}</span>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{readOnly && (
|
||||||
|
<div className="mods-banner mods-banner-warn" role="status">
|
||||||
|
{t('mods.readOnlyNotice')}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{notice && (
|
||||||
|
<div className="mods-banner mods-banner-ok" role="status">
|
||||||
|
{notice}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{section === 'list' ? (
|
||||||
|
<>
|
||||||
|
<div className="mods-toolbar">
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
className="input mods-search"
|
||||||
|
placeholder={t('mods.searchPlaceholder')}
|
||||||
|
value={query}
|
||||||
|
onChange={(event) => setQuery(event.target.value)}
|
||||||
|
/>
|
||||||
|
{state.presets.length > 0 && (
|
||||||
|
<select
|
||||||
|
className="select mods-preset-select"
|
||||||
|
aria-label={t('mods.presets.quickSwitch')}
|
||||||
|
disabled={disabled}
|
||||||
|
value={state.activePresetId ?? ''}
|
||||||
|
onChange={(event) => {
|
||||||
|
const id = event.target.value;
|
||||||
|
if (id) runAction(ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: id }));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">{t('mods.presets.customOption')}</option>
|
||||||
|
{state.presets.map((preset) => (
|
||||||
|
<option key={preset.id} value={preset.id}>{preset.name}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button"
|
||||||
|
disabled={disabled || state.mods.length < 2}
|
||||||
|
onClick={() => runAction(ipcInvoke('mods:autoSort', { copyId: copy.id }), t('mods.autoSorted'))}
|
||||||
|
>
|
||||||
|
{t('mods.autoSort')}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="button" disabled={busy} onClick={load}>
|
||||||
|
{t('mods.refresh')}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
|
||||||
|
{t('mods.openFolder')}
|
||||||
|
</button>
|
||||||
|
<a className="button" href={MOD_DOCS_URL} target="_blank" rel="noreferrer">
|
||||||
|
{t('mods.openDocs')}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{state.discoveryErrors.length > 0 && (
|
||||||
|
<div className="mods-issues-box mods-issues-error">
|
||||||
|
<div className="mods-issues-title">{t('mods.discoveryErrorsTitle', { count: state.discoveryErrors.length })}</div>
|
||||||
|
<ul>
|
||||||
|
{state.discoveryErrors.map((err) => (
|
||||||
|
<li key={err.folderName}>
|
||||||
|
<code>{err.folderName}</code>: {err.reason}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{state.issues.length > 0 && (
|
||||||
|
<div className={state.hasBlockingErrors ? 'mods-issues-box mods-issues-error' : 'mods-issues-box mods-issues-warn'}>
|
||||||
|
<div className="mods-issues-title">
|
||||||
|
{state.hasBlockingErrors
|
||||||
|
? t('mods.blockingIssuesTitle', { count: state.issues.filter((i) => i.severity === 'error').length })
|
||||||
|
: t('mods.issuesTitle', { count: state.issues.length })}
|
||||||
|
</div>
|
||||||
|
<ul>
|
||||||
|
{state.issues.map((issue, idx) => (
|
||||||
|
<li key={`${issue.modId}-${issue.kind}-${idx}`} className={`mods-issue-${issue.severity}`}>
|
||||||
|
<span className="mods-issue-tag">{t(`mods.severity.${issue.severity}`)}</span>
|
||||||
|
<strong>{issue.modId}</strong>: {issue.detail}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{visibleMods.length === 0 ? (
|
||||||
|
<div className="mods-empty">
|
||||||
|
<p className="lead">{state.mods.length === 0 ? t('mods.emptyTitle') : t('mods.noSearchMatch')}</p>
|
||||||
|
{state.mods.length === 0 && (
|
||||||
|
<>
|
||||||
|
<p className="mods-hint">{t('mods.emptyHint', { path: state.modsDir })}</p>
|
||||||
|
<button type="button" className="button button-primary" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
|
||||||
|
{t('mods.openFolder')}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="mods-list">
|
||||||
|
{visibleMods.map((mod) => {
|
||||||
|
const index = state.order.indexOf(mod.id);
|
||||||
|
const isEnabled = state.enabled[mod.id] === true;
|
||||||
|
const isExpanded = expandedId === mod.id;
|
||||||
|
const modIssues = issuesByMod.get(mod.id) ?? [];
|
||||||
|
return (
|
||||||
|
<ModCard
|
||||||
|
key={mod.id}
|
||||||
|
mod={mod}
|
||||||
|
index={index}
|
||||||
|
total={state.order.length}
|
||||||
|
enabled={isEnabled}
|
||||||
|
expanded={isExpanded}
|
||||||
|
disabled={disabled}
|
||||||
|
canDrag={canDrag}
|
||||||
|
language={i18n.language}
|
||||||
|
issues={modIssues}
|
||||||
|
onToggle={(next) => toggleMod(mod.id, next)}
|
||||||
|
onMove={(delta) => moveMod(mod.id, delta)}
|
||||||
|
onToggleExpand={() => setExpandedId(isExpanded ? null : mod.id)}
|
||||||
|
onDragStart={() => setDraggedId(mod.id)}
|
||||||
|
onDrop={(event) => handleDrop(mod.id, event)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<section className="mods-section">
|
||||||
|
<h3 className="mods-subheading">{t('mods.presets.heading')}</h3>
|
||||||
|
<p className="mods-hint">{t('mods.presets.description')}</p>
|
||||||
|
<form className="mods-preset-form" onSubmit={savePreset}>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="input"
|
||||||
|
maxLength={80}
|
||||||
|
disabled={disabled}
|
||||||
|
placeholder={t('mods.presets.namePlaceholder')}
|
||||||
|
value={presetName}
|
||||||
|
onChange={(event) => setPresetName(event.target.value)}
|
||||||
|
/>
|
||||||
|
<button type="submit" className="button button-primary" disabled={disabled || !presetName.trim()}>
|
||||||
|
{t('mods.presets.saveCurrent')}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="button" disabled={disabled} onClick={importPreset}>
|
||||||
|
{t('mods.presets.import')}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{state.presets.length === 0 ? (
|
||||||
|
<p className="mods-hint">{t('mods.presets.empty')}</p>
|
||||||
|
) : (
|
||||||
|
<div className="mods-preset-list">
|
||||||
|
{state.presets.map((preset) => {
|
||||||
|
const active = state.activePresetId === preset.id;
|
||||||
|
const count = Object.values(preset.enabled).filter(Boolean).length;
|
||||||
|
return (
|
||||||
|
<div key={preset.id} className={active ? 'mods-preset-item mods-preset-active' : 'mods-preset-item'}>
|
||||||
|
<div className="mods-preset-meta">
|
||||||
|
<div className="mods-preset-name">
|
||||||
|
{preset.name}
|
||||||
|
{active && <span className="mods-badge mods-badge-data">{t('mods.presets.activeTag')}</span>}
|
||||||
|
</div>
|
||||||
|
<div className="mods-preset-sub">
|
||||||
|
{t('mods.presets.summary', { count, total: preset.order.length })}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="copy-list-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button button-primary"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => runAction(
|
||||||
|
ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: preset.id }),
|
||||||
|
t('mods.presets.applied', { name: preset.name }),
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{t('mods.presets.apply')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => runAction(
|
||||||
|
ipcInvoke('mods:savePreset', { copyId: copy.id, name: preset.name, overwriteId: preset.id }),
|
||||||
|
t('mods.presets.updated', { name: preset.name }),
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{t('mods.presets.overwrite')}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="button" disabled={busy} onClick={() => exportPreset(preset.id)}>
|
||||||
|
{t('mods.presets.export')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => runAction(ipcInvoke('mods:deletePreset', { copyId: copy.id, presetId: preset.id }))}
|
||||||
|
>
|
||||||
|
{t('mods.presets.delete')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="mods-section">
|
||||||
|
<h3 className="mods-subheading">{t('mods.repo.heading')}</h3>
|
||||||
|
<p className="mods-hint">{t('mods.repo.description')}</p>
|
||||||
|
<Row
|
||||||
|
label={t('mods.repo.pathLabel')}
|
||||||
|
hint={state.isCustomModsDir ? t('mods.repo.customNote') : t('mods.repo.defaultNote')}
|
||||||
|
>
|
||||||
|
<code className="mods-path">{state.modsDir}</code>
|
||||||
|
</Row>
|
||||||
|
<div className="copy-list-actions" style={{ marginTop: 12 }}>
|
||||||
|
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
|
||||||
|
{t('mods.openFolder')}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="button" disabled={disabled} onClick={pickCustomFolder}>
|
||||||
|
{t('mods.repo.changeFolder')}
|
||||||
|
</button>
|
||||||
|
{state.isCustomModsDir && (
|
||||||
|
<button type="button" className="button" disabled={disabled} onClick={resetFolder}>
|
||||||
|
{t('mods.repo.resetDefault')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Sheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ModCardProps {
|
||||||
|
readonly mod: ModListItem;
|
||||||
|
readonly index: number;
|
||||||
|
readonly total: number;
|
||||||
|
readonly enabled: boolean;
|
||||||
|
readonly expanded: boolean;
|
||||||
|
readonly disabled: boolean;
|
||||||
|
readonly canDrag: boolean;
|
||||||
|
readonly language: string;
|
||||||
|
readonly issues: readonly ModIssueView[];
|
||||||
|
readonly onToggle: (next: boolean) => void;
|
||||||
|
readonly onMove: (delta: -1 | 1) => void;
|
||||||
|
readonly onToggleExpand: () => void;
|
||||||
|
readonly onDragStart: () => void;
|
||||||
|
readonly onDrop: (event: DragEvent<HTMLDivElement>) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ModCard({
|
||||||
|
mod,
|
||||||
|
index,
|
||||||
|
total,
|
||||||
|
enabled,
|
||||||
|
expanded,
|
||||||
|
disabled,
|
||||||
|
canDrag,
|
||||||
|
language,
|
||||||
|
issues,
|
||||||
|
onToggle,
|
||||||
|
onMove,
|
||||||
|
onToggleExpand,
|
||||||
|
onDragStart,
|
||||||
|
onDrop,
|
||||||
|
}: ModCardProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const displayName = localized(mod.name, language) || mod.id;
|
||||||
|
const description = localized(mod.description, language);
|
||||||
|
const errorCount = issues.filter((i) => i.severity === 'error').length;
|
||||||
|
const warnCount = issues.filter((i) => i.severity === 'warning').length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`mods-card${enabled ? ' mods-card-enabled' : ''}`}
|
||||||
|
draggable={canDrag}
|
||||||
|
onDragStart={onDragStart}
|
||||||
|
onDragOver={(event) => { if (canDrag) event.preventDefault(); }}
|
||||||
|
onDrop={onDrop}
|
||||||
|
>
|
||||||
|
<div className="mods-card-row">
|
||||||
|
<span className="mods-order-num" title={t('mods.loadOrderHint')}>#{index + 1}</span>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="mods-checkbox"
|
||||||
|
checked={enabled}
|
||||||
|
disabled={disabled}
|
||||||
|
aria-label={displayName}
|
||||||
|
onChange={(event) => onToggle(event.target.checked)}
|
||||||
|
/>
|
||||||
|
<div className="mods-card-main" onClick={onToggleExpand}>
|
||||||
|
<div className="mods-card-title">
|
||||||
|
<span className="mods-name">{displayName}</span>
|
||||||
|
<span className="mods-version">v{mod.version}</span>
|
||||||
|
<span className="mods-author">· {mod.author}</span>
|
||||||
|
<div className="mods-badges">
|
||||||
|
{mod.badges.map((badge) => (
|
||||||
|
<span key={badge} className={`mods-badge mods-badge-${badge}`}>
|
||||||
|
{t(`mods.badges.${badge}`)}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
{errorCount > 0 && <span className="mods-badge mods-badge-error">{t('mods.errorCount', { count: errorCount })}</span>}
|
||||||
|
{warnCount > 0 && <span className="mods-badge mods-badge-warn">{t('mods.warnCount', { count: warnCount })}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{description && <div className="mods-card-desc">{description}</div>}
|
||||||
|
</div>
|
||||||
|
<div className="mods-card-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button mods-move-btn"
|
||||||
|
disabled={disabled || index <= 0}
|
||||||
|
title={t('mods.moveUp')}
|
||||||
|
onClick={() => onMove(-1)}
|
||||||
|
>
|
||||||
|
↑
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button mods-move-btn"
|
||||||
|
disabled={disabled || index < 0 || index >= total - 1}
|
||||||
|
title={t('mods.moveDown')}
|
||||||
|
onClick={() => onMove(1)}
|
||||||
|
>
|
||||||
|
↓
|
||||||
|
</button>
|
||||||
|
<button type="button" className="button" onClick={onToggleExpand}>
|
||||||
|
{expanded ? t('mods.hideDetails') : t('mods.showDetails')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{expanded && (
|
||||||
|
<div className="mods-card-details">
|
||||||
|
<div className="mods-detail-grid">
|
||||||
|
<div><span>ID:</span> <code>{mod.id}</code></div>
|
||||||
|
<div><span>API:</span> <code>{mod.apiVersion}</code></div>
|
||||||
|
<div><span>{t('mods.details.folder')}:</span> <code>{mod.folderName}</code></div>
|
||||||
|
{mod.gameVersions.length > 0 && (
|
||||||
|
<div><span>{t('mods.details.gameVersions')}:</span> <code>{mod.gameVersions.join(', ')}</code></div>
|
||||||
|
)}
|
||||||
|
{mod.requires.length > 0 && (
|
||||||
|
<div><span>{t('mods.details.requires')}:</span> <code>{mod.requires.join(', ')}</code></div>
|
||||||
|
)}
|
||||||
|
{mod.conflicts.length > 0 && (
|
||||||
|
<div><span>{t('mods.details.conflicts')}:</span> <code>{mod.conflicts.join(', ')}</code></div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mods-detail-summary">
|
||||||
|
{mod.serverTuningFiles.length > 0 && (
|
||||||
|
<span>{t('mods.details.tuning', { count: mod.serverTuningFiles.length })}</span>
|
||||||
|
)}
|
||||||
|
{mod.hasServerScript && <span>{t('mods.details.serverScript')}</span>}
|
||||||
|
{mod.packOperations.length > 0 && (
|
||||||
|
<span>{t('mods.details.packOps', { count: mod.packOperations.length })}</span>
|
||||||
|
)}
|
||||||
|
{mod.hasClientAddon && (
|
||||||
|
<span>{t('mods.details.addon', { count: mod.addonFileCount })}</span>
|
||||||
|
)}
|
||||||
|
{mod.guiPatchCount > 0 && (
|
||||||
|
<span>{t('mods.details.guiPatches', { count: mod.guiPatchCount })}</span>
|
||||||
|
)}
|
||||||
|
{mod.exePatchCount > 0 && (
|
||||||
|
<span>{t('mods.details.exePatches', { count: mod.exePatchCount })}</span>
|
||||||
|
)}
|
||||||
|
{mod.clientFileCount > 0 && (
|
||||||
|
<span>{t('mods.details.companionFiles', { count: mod.clientFileCount })}</span>
|
||||||
|
)}
|
||||||
|
{mod.hasConfigBlkPatch && <span>{t('mods.details.configBlk')}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@ interface Props {
|
|||||||
readonly onError: (error: unknown) => void;
|
readonly onError: (error: unknown) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ACTIONS = ['research', 'purchase', 'equipment'] as const;
|
const ACTIONS = ['purchase', 'equipment'] as const;
|
||||||
|
|
||||||
export function SaveResearch({ copyId, userId, readOnly, onError }: Props) {
|
export function SaveResearch({ copyId, userId, readOnly, onError }: Props) {
|
||||||
const { t, i18n } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
|
|||||||
@@ -1,19 +1,25 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import type { Settings } from '@shared/schemas/settings.ts';
|
||||||
import { Row } from '../../components/Row.tsx';
|
import { Row } from '../../components/Row.tsx';
|
||||||
import { Sheet } from '../../components/Sheet.tsx';
|
import { Sheet } from '../../components/Sheet.tsx';
|
||||||
import { ipcInvoke } from '../../ipc.ts';
|
import { ipcInvoke } from '../../ipc.ts';
|
||||||
|
|
||||||
interface DiagnosticsSettingsProps {
|
interface DiagnosticsSettingsProps {
|
||||||
|
readonly settings: Settings;
|
||||||
readonly serverRunning: boolean;
|
readonly serverRunning: boolean;
|
||||||
readonly onError: (error: unknown) => void;
|
readonly onError: (error: unknown) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSettingsProps) {
|
export function DiagnosticsSettings({ settings, onError, serverRunning }: DiagnosticsSettingsProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [exporting, setExporting] = useState(false);
|
const [exporting, setExporting] = useState(false);
|
||||||
const [savedPath, setSavedPath] = useState<string | null>(null);
|
const [savedPath, setSavedPath] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const updateLogging = (loggingEnabled: boolean): void => {
|
||||||
|
ipcInvoke('settings:update', { loggingEnabled }).catch(onError);
|
||||||
|
};
|
||||||
|
|
||||||
async function save(): Promise<void> {
|
async function save(): Promise<void> {
|
||||||
setExporting(true);
|
setExporting(true);
|
||||||
setSavedPath(null);
|
setSavedPath(null);
|
||||||
@@ -29,6 +35,16 @@ export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSetti
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Sheet title={t('settings.sections.diag')}>
|
<Sheet title={t('settings.sections.diag')}>
|
||||||
|
<Row label={t('settings.diagnostics.recordLogs')} hint={t('settings.diagnostics.recordLogsHint')}>
|
||||||
|
<label className="check check-inline">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={settings.loggingEnabled}
|
||||||
|
onChange={(event) => updateLogging(event.target.checked)}
|
||||||
|
/>
|
||||||
|
{t('settings.diagnostics.recordLogsToggle')}
|
||||||
|
</label>
|
||||||
|
</Row>
|
||||||
<Row label={t('settings.diagnostics.logs')} hint={t('settings.diagnostics.logsHint')}>
|
<Row label={t('settings.diagnostics.logs')} hint={t('settings.diagnostics.logsHint')}>
|
||||||
<button type="button" className="button" onClick={() => ipcInvoke('app:openLogsFolder').catch(onError)}>
|
<button type="button" className="button" onClick={() => ipcInvoke('app:openLogsFolder').catch(onError)}>
|
||||||
{t('settings.diagnostics.openLogs')}
|
{t('settings.diagnostics.openLogs')}
|
||||||
@@ -44,6 +60,7 @@ export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSetti
|
|||||||
{t('settings.diagnostics.openStatus')}
|
{t('settings.diagnostics.openStatus')}
|
||||||
</button>
|
</button>
|
||||||
</Row>
|
</Row>
|
||||||
|
{!settings.loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
|
||||||
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
|
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
|
||||||
</Sheet>
|
</Sheet>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ type Field = keyof TuningValues;
|
|||||||
type Draft = Partial<Record<Field, string | boolean>>;
|
type Draft = Partial<Record<Field, string | boolean>>;
|
||||||
const fields = {
|
const fields = {
|
||||||
rewards: ['rewardMultiplierSilverLions', 'rewardMultiplierResearchPoints', 'friendlyKillPenaltyMul'],
|
rewards: ['rewardMultiplierSilverLions', 'rewardMultiplierResearchPoints', 'friendlyKillPenaltyMul'],
|
||||||
battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'tankBotRespawns', 'airBotRespawns', 'strikeUcavSpawnScore'],
|
battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'tankBotRespawns', 'airBotRespawns', 'strikeUcavSpawnScore', 'nuclearEscalationStrategicBombers'],
|
||||||
newProfile: ['silverLions', 'goldenEagles'],
|
newProfile: ['silverLions', 'goldenEagles'],
|
||||||
research: ['preferLineSuccessor', 'autoTargetPick'],
|
research: ['preferLineSuccessor', 'autoTargetPick'],
|
||||||
} as const satisfies Record<TuningSection, readonly Field[]>;
|
} as const satisfies Record<TuningSection, readonly Field[]>;
|
||||||
@@ -70,7 +70,7 @@ export function TuningPage({ copy, section, onError }: Props) {
|
|||||||
const editor = (field: Field): ReactNode => {
|
const editor = (field: Field): ReactNode => {
|
||||||
const active = draft[field] ?? inputValue(field, loaded.effective[field]);
|
const active = draft[field] ?? inputValue(field, loaded.effective[field]);
|
||||||
const label = t(`tuning.fields.${field}`);
|
const label = t(`tuning.fields.${field}`);
|
||||||
if (field === 'preferLineSuccessor') {
|
if (typeof loaded.defaults[field] === 'boolean') {
|
||||||
return <input type="checkbox" aria-label={label} disabled={saving} checked={active === true} onChange={(event) => set(field, event.target.checked)} />;
|
return <input type="checkbox" aria-label={label} disabled={saving} checked={active === true} onChange={(event) => set(field, event.target.checked)} />;
|
||||||
}
|
}
|
||||||
if (field === 'autoTargetPick') {
|
if (field === 'autoTargetPick') {
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* The window's pages and the sections of those that have a section list in the side panel.
|
* The window's pages and the sections of those that have a section list in the side panel.
|
||||||
* Pages for later features (saves, tuning) join this list when they are built.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export const PAGES = ['home', 'saves', 'tuning', 'copies', 'settings', 'about'] as const;
|
export const PAGES = ['home', 'saves', 'tuning', 'mods', 'copies', 'settings', 'about'] as const;
|
||||||
export type PageId = (typeof PAGES)[number];
|
export type PageId = (typeof PAGES)[number];
|
||||||
|
|
||||||
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const;
|
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const;
|
||||||
@@ -12,6 +11,9 @@ export type SaveSection = (typeof SAVE_SECTIONS)[number];
|
|||||||
export const TUNING_SECTIONS = ['rewards', 'battle', 'newProfile', 'research'] as const;
|
export const TUNING_SECTIONS = ['rewards', 'battle', 'newProfile', 'research'] as const;
|
||||||
export type TuningSection = (typeof TUNING_SECTIONS)[number];
|
export type TuningSection = (typeof TUNING_SECTIONS)[number];
|
||||||
|
|
||||||
|
export const MODS_SECTIONS = ['list', 'presets'] as const;
|
||||||
|
export type ModsSection = (typeof MODS_SECTIONS)[number];
|
||||||
|
|
||||||
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
|
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
|
||||||
export type CopySection = (typeof COPY_SECTIONS)[number];
|
export type CopySection = (typeof COPY_SECTIONS)[number];
|
||||||
|
|
||||||
@@ -23,16 +25,25 @@ export interface Route {
|
|||||||
readonly copies: CopySection;
|
readonly copies: CopySection;
|
||||||
readonly saves: SaveSection;
|
readonly saves: SaveSection;
|
||||||
readonly tuning: TuningSection;
|
readonly tuning: TuningSection;
|
||||||
|
readonly mods: ModsSection;
|
||||||
readonly settings: SettingsSection;
|
readonly settings: SettingsSection;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const START_ROUTE: Route = { page: 'home', saves: 'list', tuning: 'rewards', copies: 'list', settings: 'general' };
|
export const START_ROUTE: Route = {
|
||||||
|
page: 'home',
|
||||||
|
saves: 'list',
|
||||||
|
tuning: 'rewards',
|
||||||
|
mods: 'list',
|
||||||
|
copies: 'list',
|
||||||
|
settings: 'general',
|
||||||
|
};
|
||||||
|
|
||||||
/** Where a link points: a page, and for pages with sections, which one. */
|
/** Where a link points: a page, and for pages with sections, which one. */
|
||||||
export type Destination =
|
export type Destination =
|
||||||
| { readonly page: 'home' | 'about' }
|
| { readonly page: 'home' | 'about' }
|
||||||
| { readonly page: 'saves'; readonly section?: SaveSection }
|
| { readonly page: 'saves'; readonly section?: SaveSection }
|
||||||
| { readonly page: 'tuning'; readonly section?: TuningSection }
|
| { readonly page: 'tuning'; readonly section?: TuningSection }
|
||||||
|
| { readonly page: 'mods'; readonly section?: ModsSection }
|
||||||
| { readonly page: 'copies'; readonly section?: CopySection }
|
| { readonly page: 'copies'; readonly section?: CopySection }
|
||||||
| { readonly page: 'settings'; readonly section?: SettingsSection };
|
| { readonly page: 'settings'; readonly section?: SettingsSection };
|
||||||
|
|
||||||
@@ -42,6 +53,8 @@ export function navigate(route: Route, to: Destination): Route {
|
|||||||
return { ...route, page: 'saves', saves: to.section ?? route.saves };
|
return { ...route, page: 'saves', saves: to.section ?? route.saves };
|
||||||
case 'tuning':
|
case 'tuning':
|
||||||
return { ...route, page: 'tuning', tuning: to.section ?? route.tuning };
|
return { ...route, page: 'tuning', tuning: to.section ?? route.tuning };
|
||||||
|
case 'mods':
|
||||||
|
return { ...route, page: 'mods', mods: to.section ?? route.mods };
|
||||||
case 'copies':
|
case 'copies':
|
||||||
return { ...route, page: 'copies', copies: to.section ?? route.copies };
|
return { ...route, page: 'copies', copies: to.section ?? route.copies };
|
||||||
case 'settings':
|
case 'settings':
|
||||||
|
|||||||
@@ -215,9 +215,13 @@
|
|||||||
|
|
||||||
/* ===== Buttons and links ===== */
|
/* ===== Buttons and links ===== */
|
||||||
.button {
|
.button {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
font: 500 14px var(--font-display);
|
font: 500 14px var(--font-display);
|
||||||
letter-spacing: 0.04em;
|
letter-spacing: 0.04em;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
|
text-decoration: none;
|
||||||
padding: 7px 16px;
|
padding: 7px 16px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
|||||||
@@ -371,3 +371,461 @@
|
|||||||
line-height: 1.6;
|
line-height: 1.6;
|
||||||
color: var(--text-dim);
|
color: var(--text-dim);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.about-columns {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 14px;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.about-column {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 14px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.about-card {
|
||||||
|
min-width: 0;
|
||||||
|
padding: 14px 16px;
|
||||||
|
background: rgba(0, 0, 0, 0.14);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
.about-card-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.about-card-title {
|
||||||
|
margin: 0;
|
||||||
|
font: 500 14px var(--font-display);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
color: var(--white);
|
||||||
|
}
|
||||||
|
|
||||||
|
.about-card-actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.about-card-meta {
|
||||||
|
margin: 8px 0 0;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.about-card-label {
|
||||||
|
color: var(--text-dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
.about-card .notice {
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.about-card .notice .button {
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== Mods ===== */
|
||||||
|
.mods-aside {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-exp-chip {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
padding: 2px 7px;
|
||||||
|
font-size: 11.5px;
|
||||||
|
line-height: 1.3;
|
||||||
|
color: rgba(255, 227, 163, 0.9);
|
||||||
|
background: rgba(214, 158, 46, 0.14);
|
||||||
|
border: 1px solid rgba(214, 158, 46, 0.38);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
cursor: help;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-exp-chip:hover,
|
||||||
|
.mods-exp-chip:focus-visible {
|
||||||
|
background: rgba(214, 158, 46, 0.22);
|
||||||
|
border-color: rgba(214, 158, 46, 0.6);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-exp-icon {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 700;
|
||||||
|
font-style: normal;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 1px solid rgba(255, 227, 163, 0.55);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-exp-popover {
|
||||||
|
position: absolute;
|
||||||
|
top: calc(100% + 8px);
|
||||||
|
right: 0;
|
||||||
|
z-index: 40;
|
||||||
|
width: 340px;
|
||||||
|
max-width: min(340px, 70vw);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.5;
|
||||||
|
text-align: left;
|
||||||
|
white-space: normal;
|
||||||
|
color: rgba(255, 244, 218, 0.94);
|
||||||
|
background: rgba(16, 20, 24, 0.97);
|
||||||
|
border: 1px solid rgba(214, 158, 46, 0.5);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
box-shadow: 0 10px 26px rgba(0, 0, 0, 0.55);
|
||||||
|
opacity: 0;
|
||||||
|
visibility: hidden;
|
||||||
|
pointer-events: none;
|
||||||
|
transform: translateY(-2px);
|
||||||
|
transition: opacity 140ms ease, transform 140ms ease, visibility 140ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-exp-chip:hover .mods-exp-popover,
|
||||||
|
.mods-exp-chip:focus-visible .mods-exp-popover {
|
||||||
|
opacity: 1;
|
||||||
|
visibility: visible;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-banner {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 3px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
line-height: 1.5;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-banner-warn {
|
||||||
|
background: rgba(206, 65, 55, 0.16);
|
||||||
|
border-color: rgba(206, 65, 55, 0.5);
|
||||||
|
color: #ffd7d4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-banner-ok {
|
||||||
|
background: rgba(68, 170, 102, 0.16);
|
||||||
|
border-color: rgba(68, 170, 102, 0.5);
|
||||||
|
color: #d7ffe4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-toolbar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-search {
|
||||||
|
flex: 1 1 180px;
|
||||||
|
min-width: 140px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-select {
|
||||||
|
max-width: 210px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-issues-box {
|
||||||
|
padding: 10px 12px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-issues-error {
|
||||||
|
background: rgba(206, 65, 55, 0.15);
|
||||||
|
border-color: rgba(206, 65, 55, 0.55);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-issues-warn {
|
||||||
|
background: rgba(214, 158, 46, 0.13);
|
||||||
|
border-color: rgba(214, 158, 46, 0.45);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-issues-title {
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-issues-box ul {
|
||||||
|
margin: 0;
|
||||||
|
padding-left: 18px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-issue-tag {
|
||||||
|
display: inline-block;
|
||||||
|
margin-right: 6px;
|
||||||
|
padding: 1px 5px;
|
||||||
|
font-size: 11px;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: rgba(255, 255, 255, 0.12);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-empty {
|
||||||
|
padding: 20px 14px;
|
||||||
|
text-align: center;
|
||||||
|
border: 1px dashed var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-hint {
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
line-height: 1.5;
|
||||||
|
margin: 6px 0 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card {
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: rgba(12, 16, 19, 0.62);
|
||||||
|
transition: border-color 120ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-enabled {
|
||||||
|
border-left: 3px solid var(--red);
|
||||||
|
background: rgba(18, 24, 29, 0.78);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-order-num {
|
||||||
|
min-width: 26px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
text-align: right;
|
||||||
|
cursor: grab;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-checkbox {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
flex: none;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-main {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-title {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-name {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--white);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-version,
|
||||||
|
.mods-author {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-desc {
|
||||||
|
margin-top: 3px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badges {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge {
|
||||||
|
padding: 1px 6px;
|
||||||
|
font-size: 11px;
|
||||||
|
border-radius: 2px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.16);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge-data {
|
||||||
|
background: rgba(88, 166, 255, 0.16);
|
||||||
|
color: #b7d7ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge-gui {
|
||||||
|
background: rgba(163, 113, 247, 0.18);
|
||||||
|
color: #dec8ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge-script {
|
||||||
|
background: rgba(214, 158, 46, 0.22);
|
||||||
|
color: #ffe3a3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge-exe {
|
||||||
|
background: rgba(206, 65, 55, 0.28);
|
||||||
|
color: #ffc2be;
|
||||||
|
border-color: rgba(206, 65, 55, 0.55);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge-error {
|
||||||
|
background: rgba(206, 65, 55, 0.35);
|
||||||
|
color: #ffd5d2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge-warn {
|
||||||
|
background: rgba(214, 158, 46, 0.25);
|
||||||
|
color: #ffe8b3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-move-btn {
|
||||||
|
min-width: 28px;
|
||||||
|
padding: 4px 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-details {
|
||||||
|
padding: 10px 12px 12px 48px;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-detail-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||||
|
gap: 4px 12px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-detail-summary {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-detail-summary span {
|
||||||
|
padding: 2px 7px;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: rgba(255, 255, 255, 0.08);
|
||||||
|
color: rgba(255, 255, 255, 0.85);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-section {
|
||||||
|
margin-bottom: 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-subheading {
|
||||||
|
margin: 0 0 4px;
|
||||||
|
font: 600 15px var(--font-display);
|
||||||
|
color: var(--white);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-form {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
margin: 10px 0 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-form .input {
|
||||||
|
flex: 1 1 200px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-item {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: rgba(12, 16, 19, 0.62);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-active {
|
||||||
|
border-left: 3px solid var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-meta {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-name {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--white);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-sub {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-path {
|
||||||
|
font-size: 12px;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
@@ -24,6 +24,11 @@ export const APP_ERROR_CODES = [
|
|||||||
'diagnostics_export_failed',
|
'diagnostics_export_failed',
|
||||||
'copy_not_found',
|
'copy_not_found',
|
||||||
'tuning_invalid',
|
'tuning_invalid',
|
||||||
|
'mods_read_only',
|
||||||
|
'mods_write_failed',
|
||||||
|
'mods_preset_invalid',
|
||||||
|
'mods_blocking_issues',
|
||||||
|
'mods_folder_invalid',
|
||||||
'save_not_found',
|
'save_not_found',
|
||||||
'save_archive_invalid',
|
'save_archive_invalid',
|
||||||
'save_official_invalid',
|
'save_official_invalid',
|
||||||
@@ -59,12 +64,16 @@ export const APP_ERROR_CODES = [
|
|||||||
'launch_steam_confirmation_required',
|
'launch_steam_confirmation_required',
|
||||||
'launch_location',
|
'launch_location',
|
||||||
'launch_stock_version',
|
'launch_stock_version',
|
||||||
|
/** The wtoffline/stock backup executable is missing or unreadable before launch. */
|
||||||
|
'launch_stock_missing',
|
||||||
'launch_build_failed',
|
'launch_build_failed',
|
||||||
'launch_build_unavailable',
|
'launch_build_unavailable',
|
||||||
'launch_port_busy',
|
'launch_port_busy',
|
||||||
'launch_server_failed',
|
'launch_server_failed',
|
||||||
'launch_server_exited',
|
'launch_server_exited',
|
||||||
'launch_game_failed',
|
'launch_game_failed',
|
||||||
|
/** Core files built for the launch (aces.exe, wto_ws.dll, wto_ws.cfg) are missing or unreadable. */
|
||||||
|
'launch_game_files_missing',
|
||||||
/** A folder the player chose does not exist or cannot be read (params: path). */
|
/** A folder the player chose does not exist or cannot be read (params: path). */
|
||||||
'folder_unreadable',
|
'folder_unreadable',
|
||||||
/** The chosen folder lacks the files of a War Thunder installation (params: path). */
|
/** The chosen folder lacks the files of a War Thunder installation (params: path). */
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ export const IPC_CHANNEL_PREFIXES = [
|
|||||||
'copies:',
|
'copies:',
|
||||||
/** Settings shared by the saves of a game copy. */
|
/** Settings shared by the saves of a game copy. */
|
||||||
'tuning:',
|
'tuning:',
|
||||||
|
/** Additive mods repository, per-copy ordering/toggles, and presets. */
|
||||||
|
'mods:',
|
||||||
/** Local account and save management. */
|
/** Local account and save management. */
|
||||||
'saves:',
|
'saves:',
|
||||||
/** Starting and stopping the active copy. */
|
/** Starting and stopping the active copy. */
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
CopiesSchema,
|
CopiesSchema,
|
||||||
CopyIdSchema,
|
CopyIdSchema,
|
||||||
CopyNameSchema,
|
CopyNameSchema,
|
||||||
|
DATA_FOLDER_PROBLEMS,
|
||||||
FolderSizeSchema,
|
FolderSizeSchema,
|
||||||
GameFolderInspectionSchema,
|
GameFolderInspectionSchema,
|
||||||
InstallProgressSchema,
|
InstallProgressSchema,
|
||||||
@@ -16,6 +17,7 @@ import {
|
|||||||
} from '../schemas/install.ts';
|
} from '../schemas/install.ts';
|
||||||
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
|
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
|
||||||
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
|
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
|
||||||
|
import { ModsStateViewSchema } from '../schemas/mods.ts';
|
||||||
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts';
|
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts';
|
||||||
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
|
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
|
||||||
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
|
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
|
||||||
@@ -85,8 +87,17 @@ export const ipcContract = {
|
|||||||
output: TargetFolderInspectionSchema,
|
output: TargetFolderInspectionSchema,
|
||||||
},
|
},
|
||||||
'install:inspectDataFolder': {
|
'install:inspectDataFolder': {
|
||||||
input: z.object({ path: z.string().min(1) }),
|
input: z.object({
|
||||||
output: z.object({ path: z.string(), inSteam: z.boolean() }),
|
path: z.string().min(1),
|
||||||
|
copyPath: z.string().min(1).optional(),
|
||||||
|
sourcePath: z.string().min(1).optional(),
|
||||||
|
stockSourcePath: z.string().min(1).optional(),
|
||||||
|
}),
|
||||||
|
output: z.object({
|
||||||
|
path: z.string(),
|
||||||
|
inSteam: z.boolean(),
|
||||||
|
problem: z.enum(DATA_FOLDER_PROBLEMS).nullable(),
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
'install:measureFolder': {
|
'install:measureFolder': {
|
||||||
input: z.object({ path: z.string().min(1), version: z.string().nullable().optional() }),
|
input: z.object({ path: z.string().min(1), version: z.string().nullable().optional() }),
|
||||||
@@ -144,6 +155,10 @@ export const ipcContract = {
|
|||||||
input: z.object({ id: CopyIdSchema }),
|
input: z.object({ id: CopyIdSchema }),
|
||||||
output: MaintenanceInfoSchema,
|
output: MaintenanceInfoSchema,
|
||||||
},
|
},
|
||||||
|
'copies:maintenanceState': {
|
||||||
|
input: z.void(),
|
||||||
|
output: MaintenanceProgressSchema.nullable(),
|
||||||
|
},
|
||||||
'copies:maintain': {
|
'copies:maintain': {
|
||||||
input: MaintenanceRequestSchema,
|
input: MaintenanceRequestSchema,
|
||||||
output: CopiesSchema,
|
output: CopiesSchema,
|
||||||
@@ -248,6 +263,50 @@ export const ipcContract = {
|
|||||||
input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }),
|
input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }),
|
||||||
output: TuningViewSchema,
|
output: TuningViewSchema,
|
||||||
},
|
},
|
||||||
|
'mods:getState': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:setEnabled': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, modId: z.string().min(1), enabled: z.boolean() }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:setOrder': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, order: z.array(z.string()) }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:autoSort': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:savePreset': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, name: z.string().trim().min(1).max(80), overwriteId: z.string().min(1).optional() }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:applyPreset': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:deletePreset': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:exportPreset': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
|
||||||
|
output: z.object({ path: z.string().nullable() }),
|
||||||
|
},
|
||||||
|
'mods:importPreset': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema }),
|
||||||
|
output: z.object({ imported: z.boolean(), state: ModsStateViewSchema }),
|
||||||
|
},
|
||||||
|
'mods:openFolder': {
|
||||||
|
input: z.void(),
|
||||||
|
output: z.void(),
|
||||||
|
},
|
||||||
|
'mods:setFolder': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, path: z.string().min(1).nullable() }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
'launch:getState': {
|
'launch:getState': {
|
||||||
input: z.void(),
|
input: z.void(),
|
||||||
output: LaunchStateSchema,
|
output: LaunchStateSchema,
|
||||||
@@ -324,7 +383,7 @@ export const ipcEvents = {
|
|||||||
'event:app-update-progress': AppUpdateProgressSchema,
|
'event:app-update-progress': AppUpdateProgressSchema,
|
||||||
'event:launch-state': LaunchStateSchema,
|
'event:launch-state': LaunchStateSchema,
|
||||||
'event:copies-changed': CopiesSchema,
|
'event:copies-changed': CopiesSchema,
|
||||||
'event:copy-maintenance': MaintenanceProgressSchema,
|
'event:copy-maintenance': MaintenanceProgressSchema.nullable(),
|
||||||
/** Another patch set became active (a pack was installed, or the bundled set restored). */
|
/** Another patch set became active (a pack was installed, or the bundled set restored). */
|
||||||
'event:patch-set-changed': ActivePatchSetSchema,
|
'event:patch-set-changed': ActivePatchSetSchema,
|
||||||
} as const;
|
} as const;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
[
|
[
|
||||||
"-forcestart",
|
"-forcestart",
|
||||||
|
"-skip_pkg_validation",
|
||||||
"-nobeac",
|
"-nobeac",
|
||||||
"-crashpad-disable-upload",
|
"-crashpad-disable-upload",
|
||||||
"--nosteam"
|
"--nosteam"
|
||||||
|
|||||||
@@ -9,6 +9,11 @@ export function launcherReleaseFiles(version: string) {
|
|||||||
return { installer: `${base}.exe`, manifest: `${base}.manifest.json`, signature: `${base}.manifest.json.sig` };
|
return { installer: `${base}.exe`, manifest: `${base}.manifest.json`, signature: `${base}.manifest.json.sig` };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function portableLauncherReleaseFiles(version: string) {
|
||||||
|
const base = `wtoffline-launcher-${AppReleaseVersionSchema.parse(version)}-win-x64-portable`;
|
||||||
|
return { archive: `${base}.zip`, manifest: `${base}.manifest.json`, signature: `${base}.manifest.json.sig` };
|
||||||
|
}
|
||||||
|
|
||||||
export const LauncherReleaseManifest = z.strictObject({
|
export const LauncherReleaseManifest = z.strictObject({
|
||||||
kind: z.literal('wto-launcher-release'),
|
kind: z.literal('wto-launcher-release'),
|
||||||
format: z.literal(1),
|
format: z.literal(1),
|
||||||
@@ -19,6 +24,16 @@ export const LauncherReleaseManifest = z.strictObject({
|
|||||||
});
|
});
|
||||||
export type LauncherReleaseManifest = z.output<typeof LauncherReleaseManifest>;
|
export type LauncherReleaseManifest = z.output<typeof LauncherReleaseManifest>;
|
||||||
|
|
||||||
|
export const PortableReleaseManifest = z.strictObject({
|
||||||
|
kind: z.literal('wto-launcher-portable-release'),
|
||||||
|
format: z.literal(1),
|
||||||
|
version: AppReleaseVersionSchema,
|
||||||
|
platform: z.literal('win32-x64'),
|
||||||
|
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
|
||||||
|
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
||||||
|
});
|
||||||
|
export type PortableReleaseManifest = z.output<typeof PortableReleaseManifest>;
|
||||||
|
|
||||||
const AppUpdateReleaseSchema = z.object({
|
const AppUpdateReleaseSchema = z.object({
|
||||||
version: AppReleaseVersionSchema,
|
version: AppReleaseVersionSchema,
|
||||||
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
|
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
|
||||||
|
|||||||
@@ -41,6 +41,15 @@ export const TargetFolderInspectionSchema = z.object({
|
|||||||
});
|
});
|
||||||
export type TargetFolderInspection = z.output<typeof TargetFolderInspectionSchema>;
|
export type TargetFolderInspection = z.output<typeof TargetFolderInspectionSchema>;
|
||||||
|
|
||||||
|
/** Why a folder cannot hold the offline client's saves, caches, and logs. */
|
||||||
|
export const DATA_FOLDER_PROBLEMS = [
|
||||||
|
/** The data folder is the client folder itself, contains it, or lies inside its wtoffline folder. */
|
||||||
|
'overlaps_client',
|
||||||
|
/** The data folder lies inside the stock source folder. */
|
||||||
|
'overlaps_stock',
|
||||||
|
] as const;
|
||||||
|
export type DataFolderProblem = (typeof DATA_FOLDER_PROBLEMS)[number];
|
||||||
|
|
||||||
export const FolderSizeSchema = z.object({
|
export const FolderSizeSchema = z.object({
|
||||||
bytes: z.number(),
|
bytes: z.number(),
|
||||||
files: z.number(),
|
files: z.number(),
|
||||||
|
|||||||
@@ -9,6 +9,12 @@ const GameExitSchema = z.object({
|
|||||||
|
|
||||||
export type GameExit = z.output<typeof GameExitSchema>;
|
export type GameExit = z.output<typeof GameExitSchema>;
|
||||||
|
|
||||||
|
/** Append the unsigned 32-bit hex form for Windows NTSTATUS/HRESULT exit codes. */
|
||||||
|
export function formatExitCode(code: number): string {
|
||||||
|
if (code >= 0 && code <= 0xffff) return String(code);
|
||||||
|
return `${code} (0x${(code >>> 0).toString(16).toUpperCase().padStart(8, '0')})`;
|
||||||
|
}
|
||||||
|
|
||||||
export const LaunchStateSchema = z.object({
|
export const LaunchStateSchema = z.object({
|
||||||
phase: z.enum([
|
phase: z.enum([
|
||||||
'ready', 'checking', 'building', 'starting-server', 'starting-game', 'running',
|
'ready', 'checking', 'building', 'starting-server', 'starting-game', 'running',
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ export const MaintenanceRequestSchema = z.object({
|
|||||||
export const MaintenanceInfoSchema = z.object({
|
export const MaintenanceInfoSchema = z.object({
|
||||||
sourceVersion: z.string().nullable(),
|
sourceVersion: z.string().nullable(),
|
||||||
updateAvailable: z.boolean(),
|
updateAvailable: z.boolean(),
|
||||||
|
updatePreservesSpaceSaving: z.boolean(),
|
||||||
spaceSavingAvailable: z.boolean(),
|
spaceSavingAvailable: z.boolean(),
|
||||||
steamConfirmationRequired: z.boolean(),
|
steamConfirmationRequired: z.boolean(),
|
||||||
steamLocations: z.object({
|
steamLocations: z.object({
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export const ModRiskBadgeSchema = z.enum(['data', 'gui', 'script', 'exe']);
|
||||||
|
export const ModIssueSeveritySchema = z.enum(['error', 'warning', 'info']);
|
||||||
|
export const LocalizedTextSchema = z.union([z.string(), z.record(z.string(), z.string())]);
|
||||||
|
|
||||||
|
export const ModPackOperationSchema = z.object({
|
||||||
|
pack: z.string(),
|
||||||
|
targetPath: z.string(),
|
||||||
|
action: z.enum(['blk-patch', 'csv-patch', 'file']),
|
||||||
|
sourceRelativePath: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ModListItemSchema = z.object({
|
||||||
|
id: z.string(),
|
||||||
|
folderName: z.string(),
|
||||||
|
rootDir: z.string(),
|
||||||
|
name: LocalizedTextSchema,
|
||||||
|
description: LocalizedTextSchema.optional(),
|
||||||
|
version: z.string(),
|
||||||
|
author: z.string(),
|
||||||
|
apiVersion: z.string(),
|
||||||
|
gameVersions: z.array(z.string()),
|
||||||
|
requires: z.array(z.string()),
|
||||||
|
conflicts: z.array(z.string()),
|
||||||
|
loadAfter: z.array(z.string()),
|
||||||
|
loadBefore: z.array(z.string()),
|
||||||
|
badges: z.array(ModRiskBadgeSchema),
|
||||||
|
hasServerScript: z.boolean(),
|
||||||
|
serverTuningFiles: z.array(z.string()),
|
||||||
|
packOperations: z.array(ModPackOperationSchema),
|
||||||
|
guiPatchCount: z.number().int().nonnegative(),
|
||||||
|
exePatchCount: z.number().int().nonnegative(),
|
||||||
|
hasClientAddon: z.boolean(),
|
||||||
|
addonFileCount: z.number().int().nonnegative(),
|
||||||
|
clientFileCount: z.number().int().nonnegative(),
|
||||||
|
hasConfigBlkPatch: z.boolean(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ModDiscoveryErrorSchema = z.object({
|
||||||
|
folderName: z.string(),
|
||||||
|
rootDir: z.string(),
|
||||||
|
reason: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ModIssueSchema = z.object({
|
||||||
|
severity: ModIssueSeveritySchema,
|
||||||
|
kind: z.string(),
|
||||||
|
modId: z.string(),
|
||||||
|
otherModId: z.string().optional(),
|
||||||
|
detail: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ModPresetSchema = z.object({
|
||||||
|
id: z.string().min(1),
|
||||||
|
name: z.string().min(1).max(80),
|
||||||
|
order: z.array(z.string()),
|
||||||
|
enabled: z.record(z.string(), z.boolean()),
|
||||||
|
updatedAt: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ModsStateViewSchema = z.object({
|
||||||
|
modsDir: z.string(),
|
||||||
|
defaultModsDir: z.string(),
|
||||||
|
isCustomModsDir: z.boolean(),
|
||||||
|
apiVersion: z.string(),
|
||||||
|
mods: z.array(ModListItemSchema),
|
||||||
|
discoveryErrors: z.array(ModDiscoveryErrorSchema),
|
||||||
|
order: z.array(z.string()),
|
||||||
|
enabled: z.record(z.string(), z.boolean()),
|
||||||
|
activePresetId: z.string().nullable(),
|
||||||
|
presets: z.array(ModPresetSchema),
|
||||||
|
issues: z.array(ModIssueSchema),
|
||||||
|
hasBlockingErrors: z.boolean(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ModPresetTransferSchema = z.object({
|
||||||
|
format: z.literal(1),
|
||||||
|
name: z.string().min(1).max(80),
|
||||||
|
order: z.array(z.string()),
|
||||||
|
enabled: z.record(z.string(), z.boolean()),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type ModListItem = z.output<typeof ModListItemSchema>;
|
||||||
|
export type ModPresetView = z.output<typeof ModPresetSchema>;
|
||||||
|
export type ModIssueView = z.output<typeof ModIssueSchema>;
|
||||||
|
export type ModsStateView = z.output<typeof ModsStateViewSchema>;
|
||||||
@@ -94,7 +94,7 @@ export const OfficialPreviewSchema = z.object({
|
|||||||
omitted: z.array(z.string()),
|
omitted: z.array(z.string()),
|
||||||
});
|
});
|
||||||
export const ResearchBranchSchema = z.object({ country: z.string().min(1), type: z.string().min(1) });
|
export const ResearchBranchSchema = z.object({ country: z.string().min(1), type: z.string().min(1) });
|
||||||
export const ResearchOperationSchema = z.enum(['research', 'purchase', 'equipment']);
|
export const ResearchOperationSchema = z.enum(['purchase', 'equipment']);
|
||||||
export const SaveResearchSchema = z.object({
|
export const SaveResearchSchema = z.object({
|
||||||
branches: z.array(ResearchBranchSchema),
|
branches: z.array(ResearchBranchSchema),
|
||||||
selected: ResearchBranchSchema.nullable(),
|
selected: ResearchBranchSchema.nullable(),
|
||||||
|
|||||||
@@ -28,6 +28,8 @@ export const SettingsSchema = z.object({
|
|||||||
windowClose: WindowCloseSchema.default('quit'),
|
windowClose: WindowCloseSchema.default('quit'),
|
||||||
afterGameStarts: AfterGameStartsSchema.default('minimize'),
|
afterGameStarts: AfterGameStartsSchema.default('minimize'),
|
||||||
autoSaveBackups: z.boolean().default(true),
|
autoSaveBackups: z.boolean().default(true),
|
||||||
|
/** Write launcher, local server traffic, and wto_ws.log files; does not affect game .game_logs. */
|
||||||
|
loggingEnabled: z.boolean().default(true),
|
||||||
launchPortMode: PortModeSchema.default('auto'),
|
launchPortMode: PortModeSchema.default('auto'),
|
||||||
launchPort: PortSchema.default(27015),
|
launchPort: PortSchema.default(27015),
|
||||||
closeServerOnGameExit: z.boolean().default(true),
|
closeServerOnGameExit: z.boolean().default(true),
|
||||||
@@ -35,6 +37,8 @@ export const SettingsSchema = z.object({
|
|||||||
developerMode: z.boolean().default(true),
|
developerMode: z.boolean().default(true),
|
||||||
labStockPath: LabPathSchema.default(null),
|
labStockPath: LabPathSchema.default(null),
|
||||||
labDataPath: LabPathSchema.default(null),
|
labDataPath: LabPathSchema.default(null),
|
||||||
|
/** Custom global mods repository directory; null uses `<userData>/mods`. */
|
||||||
|
modsFolder: LabPathSchema.default(null),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type Settings = z.output<typeof SettingsSchema>;
|
export type Settings = z.output<typeof SettingsSchema>;
|
||||||
@@ -50,6 +54,7 @@ export const SettingsPatchSchema = z.object({
|
|||||||
windowClose: WindowCloseSchema.optional(),
|
windowClose: WindowCloseSchema.optional(),
|
||||||
afterGameStarts: AfterGameStartsSchema.optional(),
|
afterGameStarts: AfterGameStartsSchema.optional(),
|
||||||
autoSaveBackups: z.boolean().optional(),
|
autoSaveBackups: z.boolean().optional(),
|
||||||
|
loggingEnabled: z.boolean().optional(),
|
||||||
launchPortMode: PortModeSchema.optional(),
|
launchPortMode: PortModeSchema.optional(),
|
||||||
launchPort: PortSchema.optional(),
|
launchPort: PortSchema.optional(),
|
||||||
closeServerOnGameExit: z.boolean().optional(),
|
closeServerOnGameExit: z.boolean().optional(),
|
||||||
@@ -57,6 +62,7 @@ export const SettingsPatchSchema = z.object({
|
|||||||
developerMode: z.boolean().optional(),
|
developerMode: z.boolean().optional(),
|
||||||
labStockPath: LabPathSchema.optional(),
|
labStockPath: LabPathSchema.optional(),
|
||||||
labDataPath: LabPathSchema.optional(),
|
labDataPath: LabPathSchema.optional(),
|
||||||
|
modsFolder: LabPathSchema.optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type SettingsPatch = z.output<typeof SettingsPatchSchema>;
|
export type SettingsPatch = z.output<typeof SettingsPatchSchema>;
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ export const TuningValuesSchema = z.object({
|
|||||||
tankBotRespawns: z.number().int().min(1).max(10),
|
tankBotRespawns: z.number().int().min(1).max(10),
|
||||||
airBotRespawns: z.number().int().min(1).max(10),
|
airBotRespawns: z.number().int().min(1).max(10),
|
||||||
strikeUcavSpawnScore: z.number().int().min(1).max(10000),
|
strikeUcavSpawnScore: z.number().int().min(1).max(10000),
|
||||||
|
nuclearEscalationStrategicBombers: z.boolean(),
|
||||||
silverLions: z.number().int().nonnegative(),
|
silverLions: z.number().int().nonnegative(),
|
||||||
goldenEagles: z.number().int().min(0).max(0x7fffffff),
|
goldenEagles: z.number().int().min(0).max(0x7fffffff),
|
||||||
preferLineSuccessor: z.boolean(),
|
preferLineSuccessor: z.boolean(),
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@wto/blk": "*",
|
"@wto/blk": "*",
|
||||||
"@wto/jsonc": "*",
|
"@wto/jsonc": "*",
|
||||||
|
"@wto/mods": "*",
|
||||||
"@wto/vromfs": "*"
|
"@wto/vromfs": "*"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -22,6 +22,7 @@
|
|||||||
import { randomInt } from 'node:crypto';
|
import { randomInt } from 'node:crypto';
|
||||||
import type {
|
import type {
|
||||||
BattleSpawnRulesData,
|
BattleSpawnRulesData,
|
||||||
|
NuclearCarrierUnit,
|
||||||
RandomSpawnGroup,
|
RandomSpawnGroup,
|
||||||
RandomSpawnUnit,
|
RandomSpawnUnit,
|
||||||
SupportPlanePreset,
|
SupportPlanePreset,
|
||||||
@@ -43,6 +44,8 @@ export interface ExtraBattleSlot {
|
|||||||
/** The modifications enabled when not `allModifications`; the unit is otherwise stock. */
|
/** The modifications enabled when not `allModifications`; the unit is otherwise stock. */
|
||||||
readonly modifications: readonly string[];
|
readonly modifications: readonly string[];
|
||||||
readonly forceWeapon?: string;
|
readonly forceWeapon?: string;
|
||||||
|
/** Restricts the respawn weapon dropdown to these presets when multiple mode presets exist. */
|
||||||
|
readonly allowedWeapons?: readonly string[];
|
||||||
/** The RandomSpawnUnits group the vehicle was drawn from. */
|
/** The RandomSpawnUnits group the vehicle was drawn from. */
|
||||||
readonly groupName?: string;
|
readonly groupName?: string;
|
||||||
}
|
}
|
||||||
@@ -56,7 +59,10 @@ export interface ExtraBattleSlotsInput {
|
|||||||
readonly sessionMaxMrank: number;
|
readonly sessionMaxMrank: number;
|
||||||
readonly vehiclesByName: ReadonlyMap<string, CatalogueVehicle>;
|
readonly vehiclesByName: ReadonlyMap<string, CatalogueVehicle>;
|
||||||
readonly rules: BattleSpawnRulesData;
|
readonly rules: BattleSpawnRulesData;
|
||||||
readonly tuning: Pick<BattleTuning, 'strikeUcavModes' | 'strikeUcavSessionMrankAllowance' | 'strikeUcavSpawnScore'>;
|
readonly tuning: Pick<
|
||||||
|
BattleTuning,
|
||||||
|
'strikeUcavModes' | 'strikeUcavSessionMrankAllowance' | 'strikeUcavSpawnScore' | 'nuclearEscalationStrategicBombers'
|
||||||
|
>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly ExtraBattleSlot[] {
|
export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly ExtraBattleSlot[] {
|
||||||
@@ -68,6 +74,7 @@ export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly E
|
|||||||
if (supportPlane) supportSlots.push(supportPlane);
|
if (supportPlane) supportSlots.push(supportPlane);
|
||||||
const ucav = strikeUcavSlot(input);
|
const ucav = strikeUcavSlot(input);
|
||||||
if (ucav) supportSlots.push(ucav);
|
if (ucav) supportSlots.push(ucav);
|
||||||
|
supportSlots.push(...nuclearEscalationSlots(input));
|
||||||
|
|
||||||
// Keep room for fixed support vehicles while displaying random vehicle groups first.
|
// Keep room for fixed support vehicles while displaying random vehicle groups first.
|
||||||
const slots: ExtraBattleSlot[] = [];
|
const slots: ExtraBattleSlot[] = [];
|
||||||
@@ -118,6 +125,72 @@ function strikeUcavSlot(input: ExtraBattleSlotsInput): ExtraBattleSlot | undefin
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const NUCLEAR_ESCALATION_TAG_PREFIX = 'nuclear_escalation_';
|
||||||
|
const GROUND_RB_SUPPORT_MODE = 'tank_event_in_random_battles_historical';
|
||||||
|
const EASTERN_STRATEGIC_BOMBER_COUNTRIES = new Set(['country_ussr', 'country_china']);
|
||||||
|
|
||||||
|
function nuclearEscalationSlots(input: ExtraBattleSlotsInput): ExtraBattleSlot[] {
|
||||||
|
if (!input.declaration.tag?.startsWith(NUCLEAR_ESCALATION_TAG_PREFIX)) return [];
|
||||||
|
const slots: ExtraBattleSlot[] = [];
|
||||||
|
const tactical = selectTacticalNuclearCarrier(input);
|
||||||
|
if (tactical) {
|
||||||
|
const weaponNames = tactical.weapons.map((weapon) => weapon.name);
|
||||||
|
slots.push({
|
||||||
|
unitName: tactical.unitName,
|
||||||
|
allModifications: true,
|
||||||
|
modifications: [],
|
||||||
|
...(weaponNames.length === 1 ? { forceWeapon: weaponNames[0]! } : { allowedWeapons: weaponNames }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (input.tuning.nuclearEscalationStrategicBombers) {
|
||||||
|
const strategic = selectStrategicNuclearBomber(input.country, input.rules.nuclearEscalationStrategicBombers);
|
||||||
|
if (strategic) {
|
||||||
|
const weapon = strategic.weapons[0];
|
||||||
|
slots.push({
|
||||||
|
unitName: strategic.unitName,
|
||||||
|
allModifications: true,
|
||||||
|
modifications: [],
|
||||||
|
...(weapon ? { forceWeapon: weapon.name } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return slots;
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectTacticalNuclearCarrier(input: ExtraBattleSlotsInput): NuclearCarrierUnit | undefined {
|
||||||
|
const byCountry = input.rules.nuclearEscalationTacticalCarriers.filter((entry) => entry.country === input.country);
|
||||||
|
if (byCountry.length === 0) return undefined;
|
||||||
|
|
||||||
|
// Prefer the stock Ground RB nuclear carrier for the matching rank bracket when it carries
|
||||||
|
// Nuclear Escalation 5 kt / 30 kt presets; otherwise pick the country's closest-mrank carrier.
|
||||||
|
const groundPresets = input.rules.supportPlanes[GROUND_RB_SUPPORT_MODE] ?? [];
|
||||||
|
const bracket = groundPresets.find((p) => input.sessionMaxMrank >= p.minMrank && input.sessionMaxMrank <= p.maxMrank);
|
||||||
|
const preferredUnit = bracket?.units[input.country]?.unitName;
|
||||||
|
if (preferredUnit) {
|
||||||
|
const matched = byCountry.find((entry) => entry.unitName === preferredUnit);
|
||||||
|
if (matched) return matched;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...byCountry].sort((a, b) => {
|
||||||
|
const distA = Math.abs(a.mrank - input.sessionMaxMrank);
|
||||||
|
const distB = Math.abs(b.mrank - input.sessionMaxMrank);
|
||||||
|
if (distA !== distB) return distA - distB;
|
||||||
|
const underA = a.mrank <= input.sessionMaxMrank ? 0 : 1;
|
||||||
|
const underB = b.mrank <= input.sessionMaxMrank ? 0 : 1;
|
||||||
|
if (underA !== underB) return underA - underB;
|
||||||
|
return a.mrank - b.mrank || a.unitName.localeCompare(b.unitName);
|
||||||
|
})[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectStrategicNuclearBomber(
|
||||||
|
country: string,
|
||||||
|
bombers: readonly NuclearCarrierUnit[],
|
||||||
|
): NuclearCarrierUnit | undefined {
|
||||||
|
if (bombers.length === 0) return undefined;
|
||||||
|
const preferredCountry = EASTERN_STRATEGIC_BOMBER_COUNTRIES.has(country) ? 'country_ussr' : 'country_usa';
|
||||||
|
return bombers.find((entry) => entry.country === preferredCountry) ?? bombers[0];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The options of one random group: the group's vehicles inside `randomWindow`, or, when none fits,
|
* The options of one random group: the group's vehicles inside `randomWindow`, or, when none fits,
|
||||||
* those of the highest rank below it. Vehicles already in the lineup are left out (offline
|
* those of the highest rank below it. Vehicles already in the lineup are left out (offline
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-ru
|
|||||||
import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts';
|
import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts';
|
||||||
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||||
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
|
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
|
||||||
import { MISSION_DIFFICULTY, SINGLE_SPAWN } from '../game-modes/mode-definition.ts';
|
import { MISSION_DIFFICULTY, SINGLE_SPAWN, modeMaxRespawns } from '../game-modes/mode-definition.ts';
|
||||||
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
|
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
|
||||||
import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts';
|
import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts';
|
||||||
import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts';
|
import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts';
|
||||||
@@ -37,6 +37,7 @@ export interface EnqueueBattleInput {
|
|||||||
readonly modes?: readonly OfferedGameMode[];
|
readonly modes?: readonly OfferedGameMode[];
|
||||||
readonly country: string;
|
readonly country: string;
|
||||||
readonly slotVehicles: readonly string[];
|
readonly slotVehicles: readonly string[];
|
||||||
|
readonly mrankDeltas: ReadonlyMap<string, number>;
|
||||||
readonly selectedSlot?: BattleCrewSlot;
|
readonly selectedSlot?: BattleCrewSlot;
|
||||||
readonly bannedMissions: ReadonlySet<string>;
|
readonly bannedMissions: ReadonlySet<string>;
|
||||||
readonly dislikedMissions: ReadonlySet<string>;
|
readonly dislikedMissions: ReadonlySet<string>;
|
||||||
@@ -46,10 +47,12 @@ export interface BattleLaunchPlan {
|
|||||||
readonly sessionId: string;
|
readonly sessionId: string;
|
||||||
readonly modeId: number;
|
readonly modeId: number;
|
||||||
readonly modeName: string;
|
readonly modeName: string;
|
||||||
|
readonly modeTag?: string;
|
||||||
readonly economicName: string;
|
readonly economicName: string;
|
||||||
readonly missionName: string;
|
readonly missionName: string;
|
||||||
/** The mission as the game describes it, including the parameters copied into the mission settings. */
|
/** The mission as the game describes it, including the parameters copied into the mission settings. */
|
||||||
readonly mission: MissionHeader;
|
readonly mission: MissionHeader;
|
||||||
|
readonly missionRuleKeys: readonly string[];
|
||||||
readonly missionFile: string;
|
readonly missionFile: string;
|
||||||
readonly missionType: string;
|
readonly missionType: string;
|
||||||
readonly level?: string;
|
readonly level?: string;
|
||||||
@@ -67,6 +70,7 @@ export interface BattleLaunchPlan {
|
|||||||
readonly maxMrank: number;
|
readonly maxMrank: number;
|
||||||
readonly maxPlayers: number;
|
readonly maxPlayers: number;
|
||||||
readonly maxBots: number;
|
readonly maxBots: number;
|
||||||
|
readonly maxRespawns?: number;
|
||||||
readonly tankBotRespawns: number;
|
readonly tankBotRespawns: number;
|
||||||
readonly airBotRespawns: number;
|
readonly airBotRespawns: number;
|
||||||
readonly useTankBots: boolean;
|
readonly useTankBots: boolean;
|
||||||
@@ -82,6 +86,16 @@ export type MatchmakeOutcome =
|
|||||||
| { readonly ok: true; readonly launch: BattleLaunchPlan }
|
| { readonly ok: true; readonly launch: BattleLaunchPlan }
|
||||||
| { readonly ok: false; readonly error: string };
|
| { readonly ok: false; readonly error: string };
|
||||||
|
|
||||||
|
export type MissionPoolFilter = (ctx: {
|
||||||
|
readonly userId: string;
|
||||||
|
readonly modeId: number;
|
||||||
|
readonly modeName: string;
|
||||||
|
readonly economicName: string;
|
||||||
|
readonly minMrank: number;
|
||||||
|
readonly maxMrank: number;
|
||||||
|
readonly missions: readonly MissionHeader[];
|
||||||
|
}) => readonly MissionHeader[];
|
||||||
|
|
||||||
export class BattleMatchmaker {
|
export class BattleMatchmaker {
|
||||||
readonly #gameModes: GameModes;
|
readonly #gameModes: GameModes;
|
||||||
readonly #vehicles: readonly CatalogueVehicle[];
|
readonly #vehicles: readonly CatalogueVehicle[];
|
||||||
@@ -90,6 +104,7 @@ export class BattleMatchmaker {
|
|||||||
readonly #tuning: BattleTuning;
|
readonly #tuning: BattleTuning;
|
||||||
readonly #spawnRules: BattleSpawnRulesData;
|
readonly #spawnRules: BattleSpawnRulesData;
|
||||||
readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>;
|
readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>;
|
||||||
|
readonly #filterMissions: MissionPoolFilter | undefined;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
gameModes: GameModes,
|
gameModes: GameModes,
|
||||||
@@ -98,6 +113,7 @@ export class BattleMatchmaker {
|
|||||||
tuning: BattleTuning,
|
tuning: BattleTuning,
|
||||||
spawnRules: BattleSpawnRulesData,
|
spawnRules: BattleSpawnRulesData,
|
||||||
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
|
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
|
||||||
|
filterMissions?: MissionPoolFilter,
|
||||||
) {
|
) {
|
||||||
this.#gameModes = gameModes;
|
this.#gameModes = gameModes;
|
||||||
this.#vehicles = vehicles;
|
this.#vehicles = vehicles;
|
||||||
@@ -106,6 +122,7 @@ export class BattleMatchmaker {
|
|||||||
this.#tuning = tuning;
|
this.#tuning = tuning;
|
||||||
this.#spawnRules = spawnRules;
|
this.#spawnRules = spawnRules;
|
||||||
this.#aircraftLoadouts = aircraftLoadouts;
|
this.#aircraftLoadouts = aircraftLoadouts;
|
||||||
|
this.#filterMissions = filterMissions;
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
|
enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
|
||||||
@@ -117,19 +134,32 @@ export class BattleMatchmaker {
|
|||||||
(mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0,
|
(mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0,
|
||||||
);
|
);
|
||||||
if (pvpModes.length === 0) return { ok: false, error: 'PVE_NOT_SUPPORTED' };
|
if (pvpModes.length === 0) return { ok: false, error: 'PVE_NOT_SUPPORTED' };
|
||||||
const chosenMode = this.#pickQueuedMode(pvpModes, input.slotVehicles, input.selectedSlot?.unitName);
|
const chosenMode = this.#pickQueuedMode(pvpModes, input);
|
||||||
if (!chosenMode) return { ok: false, error: 'BAD_PARAMS' };
|
if (!chosenMode) return { ok: false, error: 'BAD_PARAMS' };
|
||||||
|
|
||||||
const { declaration } = chosenMode;
|
const { declaration } = chosenMode;
|
||||||
const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName);
|
const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName);
|
||||||
const playerMrank = lineupMrank(
|
const playerMrank = lineupMrank(
|
||||||
activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses,
|
activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses,
|
||||||
|
input.mrankDeltas,
|
||||||
);
|
);
|
||||||
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
|
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
|
||||||
const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity;
|
const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity;
|
||||||
const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank));
|
const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank));
|
||||||
const missions = twoSidedMissionsOf(chosenMode, maxMrank);
|
const rawMissions = twoSidedMissionsOf(chosenMode, maxMrank);
|
||||||
if (missions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
|
if (rawMissions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
|
||||||
|
const filteredMissions = this.#filterMissions
|
||||||
|
? this.#filterMissions({
|
||||||
|
userId: input.userId,
|
||||||
|
modeId: declaration.gameModeId,
|
||||||
|
modeName: declaration.name,
|
||||||
|
economicName: declaration.economicName,
|
||||||
|
minMrank,
|
||||||
|
maxMrank,
|
||||||
|
missions: rawMissions,
|
||||||
|
})
|
||||||
|
: rawMissions;
|
||||||
|
const missions = filteredMissions.length > 0 ? filteredMissions : rawMissions;
|
||||||
const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions);
|
const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions);
|
||||||
const coalitions = selectBattleCoalitions({
|
const coalitions = selectBattleCoalitions({
|
||||||
vehicles: this.#vehicles,
|
vehicles: this.#vehicles,
|
||||||
@@ -158,14 +188,11 @@ export class BattleMatchmaker {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#pickQueuedMode(
|
#pickQueuedMode(candidates: readonly OfferedGameMode[], input: EnqueueBattleInput): OfferedGameMode | undefined {
|
||||||
candidates: readonly OfferedGameMode[],
|
const pool = candidates.filter((mode) => isModeEligibleForLineup(
|
||||||
slotVehicles: readonly string[],
|
mode.declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName, input.mrankDeltas,
|
||||||
selectedSlotVehicle: string | undefined,
|
));
|
||||||
): OfferedGameMode | undefined {
|
if (pool.length === 0) return undefined;
|
||||||
const pool = candidates.filter((mode) =>
|
|
||||||
isModeEligibleForLineup(mode.declaration, slotVehicles, selectedSlotVehicle, this.#vehiclesByName));
|
|
||||||
if (pool.length === 0) return candidates.find((mode) => mode.declaration.multiSlot !== false);
|
|
||||||
const classics = pool.filter((mode) => !mode.declaration.tag);
|
const classics = pool.filter((mode) => !mode.declaration.tag);
|
||||||
const subModes = pool.filter((mode) => Boolean(mode.declaration.tag));
|
const subModes = pool.filter((mode) => Boolean(mode.declaration.tag));
|
||||||
if (subModes.length > 0 && classics.length > 0) {
|
if (subModes.length > 0 && classics.length > 0) {
|
||||||
@@ -190,12 +217,14 @@ export class BattleMatchmaker {
|
|||||||
const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers;
|
const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers;
|
||||||
const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers));
|
const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers));
|
||||||
const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1));
|
const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1));
|
||||||
|
const maxRespawns = modeMaxRespawns(declaration);
|
||||||
const missionLocName = resolveMissionLocName(mission);
|
const missionLocName = resolveMissionLocName(mission);
|
||||||
const environment = declaration.environmentOverride ?? mission.environment;
|
const environment = declaration.environmentOverride ?? mission.environment;
|
||||||
const session = this.#sessions.create({
|
const session = this.#sessions.create({
|
||||||
userId: input.userId,
|
userId: input.userId,
|
||||||
modeId: declaration.gameModeId,
|
modeId: declaration.gameModeId,
|
||||||
modeName: declaration.name,
|
modeName: declaration.name,
|
||||||
|
...(declaration.tag !== undefined ? { modeTag: declaration.tag } : {}),
|
||||||
economicName: declaration.economicName,
|
economicName: declaration.economicName,
|
||||||
difficulty: declaration.difficulty,
|
difficulty: declaration.difficulty,
|
||||||
requiredClass: declaration.requiredClass,
|
requiredClass: declaration.requiredClass,
|
||||||
@@ -222,9 +251,11 @@ export class BattleMatchmaker {
|
|||||||
sessionId: session.sessionId,
|
sessionId: session.sessionId,
|
||||||
modeId: declaration.gameModeId,
|
modeId: declaration.gameModeId,
|
||||||
modeName: declaration.name,
|
modeName: declaration.name,
|
||||||
|
...(declaration.tag !== undefined ? { modeTag: declaration.tag } : {}),
|
||||||
economicName: declaration.economicName,
|
economicName: declaration.economicName,
|
||||||
missionName: mission.name,
|
missionName: mission.name,
|
||||||
mission,
|
mission,
|
||||||
|
missionRuleKeys: declaration.missionRuleKeys ?? [],
|
||||||
missionFile: mission.path,
|
missionFile: mission.path,
|
||||||
missionType: mission.type ?? 'domination',
|
missionType: mission.type ?? 'domination',
|
||||||
...(mission.level !== undefined ? { level: mission.level } : {}),
|
...(mission.level !== undefined ? { level: mission.level } : {}),
|
||||||
@@ -242,6 +273,7 @@ export class BattleMatchmaker {
|
|||||||
maxMrank,
|
maxMrank,
|
||||||
maxPlayers,
|
maxPlayers,
|
||||||
maxBots,
|
maxBots,
|
||||||
|
...(maxRespawns === undefined ? {} : { maxRespawns }),
|
||||||
tankBotRespawns: this.#tuning.tankBotRespawns,
|
tankBotRespawns: this.#tuning.tankBotRespawns,
|
||||||
airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns,
|
airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns,
|
||||||
useTankBots: allowedSet.has('tank'),
|
useTankBots: allowedSet.has('tank'),
|
||||||
|
|||||||
@@ -7,8 +7,8 @@
|
|||||||
* copied here from the mission file, base values first and then the sub-block for the battle's
|
* copied here from the mission file, base values first and then the sub-block for the battle's
|
||||||
* difficulty. `_gameMode` is left to the client, which takes it from its own native constants.
|
* difficulty. `_gameMode` is left to the client, which takes it from its own native constants.
|
||||||
*/
|
*/
|
||||||
import { emptyBlock, ensureBlock, setParam, appendParam, type BlkBlock, type BlkParam, type BlkValue } from '@wto/blk';
|
import { emptyBlock, ensureBlock, findParam, setParam, appendParam, type BlkBlock, type BlkParam, type BlkValue } from '@wto/blk';
|
||||||
import { SINGLE_SPAWN } from '../game-modes/mode-definition.ts';
|
import { UNLIMITED_RESPAWNS } from '../game-modes/mode-definition.ts';
|
||||||
import type { ExtraBattleSlot } from './battle-extra-slots.ts';
|
import type { ExtraBattleSlot } from './battle-extra-slots.ts';
|
||||||
import type { BattleLaunchPlan } from './battle-matchmaker.ts';
|
import type { BattleLaunchPlan } from './battle-matchmaker.ts';
|
||||||
import type { CustomBotsPool } from './battle-ranks.ts';
|
import type { CustomBotsPool } from './battle-ranks.ts';
|
||||||
@@ -23,12 +23,13 @@ const RULE_KEYS: readonly string[] = [
|
|||||||
'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul',
|
'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul',
|
||||||
'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec',
|
'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec',
|
||||||
'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord',
|
'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord',
|
||||||
|
'allowedKillStreaks',
|
||||||
];
|
];
|
||||||
|
|
||||||
/** Game type switches of a versus battle with tickets, capture zones and session rewards. */
|
/** Game type switches of a versus battle with tickets, capture zones and session rewards. */
|
||||||
const VERSUS_SWITCHES: readonly string[] = [
|
const VERSUS_SWITCHES: readonly string[] = [
|
||||||
'gt_versus', 'gt_mp_tickets', 'gt_mp_capture', 'gt_use_wp', 'gt_use_xp', 'gt_use_stats', 'gt_use_unlocks',
|
'gt_versus', 'gt_mp_tickets', 'gt_mp_capture', 'gt_use_wp', 'gt_use_xp', 'gt_use_stats', 'gt_use_unlocks',
|
||||||
'isLimitedAmmo', 'allowUseArtillerySupport', 'isBotsAllowed', 'autoBalance',
|
'allowUseArtillerySupport', 'isBotsAllowed', 'autoBalance',
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -39,6 +40,13 @@ const VERSUS_SWITCHES: readonly string[] = [
|
|||||||
export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<Record<string, number>>): BlkBlock {
|
export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<Record<string, number>>): BlkBlock {
|
||||||
const settings = emptyBlock();
|
const settings = emptyBlock();
|
||||||
copyMissionParams(settings, plan);
|
copyMissionParams(settings, plan);
|
||||||
|
// Enable Ground Arcade air events when the mission allows killstreaks; the LocalMP host preserves
|
||||||
|
// MissionSettings.useKillStreaks across prepare_local_mission (local_mp_air_events.c).
|
||||||
|
const allowedKillStreaks = findParam(settings, 'allowedKillStreaks')?.value;
|
||||||
|
if (plan.modeName === 'tank_event_in_random_battles_arcade'
|
||||||
|
&& allowedKillStreaks?.type === 'bool' && allowedKillStreaks.value) {
|
||||||
|
setParam(settings, 'useKillStreaks', flag(true));
|
||||||
|
}
|
||||||
if (plan.level !== undefined) setParam(settings, 'level', text(plan.level));
|
if (plan.level !== undefined) setParam(settings, 'level', text(plan.level));
|
||||||
if (plan.environment !== undefined) setParam(settings, 'environment', text(plan.environment));
|
if (plan.environment !== undefined) setParam(settings, 'environment', text(plan.environment));
|
||||||
if (plan.weather !== undefined) setParam(settings, 'weather', text(plan.weather));
|
if (plan.weather !== undefined) setParam(settings, 'weather', text(plan.weather));
|
||||||
@@ -60,13 +68,19 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
|
|||||||
setParam(settings, 'symmetricTeams', flag(plan.symmetricTeams));
|
setParam(settings, 'symmetricTeams', flag(plan.symmetricTeams));
|
||||||
setParam(settings, 'gt_mp_solo', flag(false));
|
setParam(settings, 'gt_mp_solo', flag(false));
|
||||||
for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true));
|
for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true));
|
||||||
setParam(settings, 'allowSpare', flag(!plan.selectedSlot));
|
// The native in-flight rearm request and its receiver both require unlimited reserve ammunition.
|
||||||
|
setParam(settings, 'isLimitedAmmo', flag(plan.modeName !== 'air_arcade'));
|
||||||
|
// MissionSettings defaults isLimitedFuel to false, which disables fuel consumption and HUD timers.
|
||||||
|
setParam(settings, 'isLimitedFuel', flag(true));
|
||||||
|
setParam(settings, 'allowSpare', flag(!plan.selectedSlot && plan.maxRespawns !== UNLIMITED_RESPAWNS));
|
||||||
|
if (plan.maxRespawns !== undefined) setParam(settings, 'maxRespawns', integer(plan.maxRespawns));
|
||||||
if (plan.selectedSlot) {
|
if (plan.selectedSlot) {
|
||||||
setParam(settings, 'maxRespawns', integer(SINGLE_SPAWN));
|
|
||||||
setParam(settings, 'ctaInstantDecreaseTicketsWhenNoRespawn', flag(true));
|
setParam(settings, 'ctaInstantDecreaseTicketsWhenNoRespawn', flag(true));
|
||||||
// The native mission loader reads the AI limit at the top level, after its bots.blk default.
|
|
||||||
setParam(settings, 'numBotRespawns', integer(plan.airBotRespawns));
|
|
||||||
}
|
}
|
||||||
|
// MissionSettings::load (2.61.0.37 0x126b1f4..0x126b2e6) reads global config/bots.blk defaults
|
||||||
|
// first, then overrides aircraft and tank AI respawn limits from the mission root, not customBots.
|
||||||
|
setParam(settings, 'numBotRespawns', integer(plan.airBotRespawns));
|
||||||
|
setParam(settings, 'numTankBotRespawns', integer(plan.tankBotRespawns));
|
||||||
setParam(settings, 'useSpawnScore', flag(plan.useSpawnScore));
|
setParam(settings, 'useSpawnScore', flag(plan.useSpawnScore));
|
||||||
setParam(settings, 'useTankBots', flag(plan.useTankBots));
|
setParam(settings, 'useTankBots', flag(plan.useTankBots));
|
||||||
setParam(settings, 'useShipBots', flag(plan.useShipBots));
|
setParam(settings, 'useShipBots', flag(plan.useShipBots));
|
||||||
@@ -88,14 +102,15 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
|
|||||||
}
|
}
|
||||||
|
|
||||||
function copyMissionParams(settings: BlkBlock, plan: BattleLaunchPlan): void {
|
function copyMissionParams(settings: BlkBlock, plan: BattleLaunchPlan): void {
|
||||||
const wanted = new Set([...LOCALIZATION_KEYS, ...RULE_KEYS]);
|
const ruleKeys = new Set([...RULE_KEYS, ...plan.missionRuleKeys]);
|
||||||
|
const wanted = new Set([...LOCALIZATION_KEYS, ...ruleKeys]);
|
||||||
const copy = (params: readonly BlkParam[] | undefined, keys: ReadonlySet<string>): void => {
|
const copy = (params: readonly BlkParam[] | undefined, keys: ReadonlySet<string>): void => {
|
||||||
for (const param of params ?? []) {
|
for (const param of params ?? []) {
|
||||||
if (keys.has(param.name)) setParam(settings, param.name, param.value);
|
if (keys.has(param.name)) setParam(settings, param.name, param.value);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
copy(plan.mission.missionParams, wanted);
|
copy(plan.mission.missionParams, wanted);
|
||||||
copy(plan.mission.difficultyParams[plan.difficulty], new Set(RULE_KEYS));
|
copy(plan.mission.difficultyParams[plan.difficulty], ruleKeys);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Fixed spawn costs of extra slots, read back by the spawn score respondents (customSpawnScore). */
|
/** Fixed spawn costs of extra slots, read back by the spawn score respondents (customSpawnScore). */
|
||||||
@@ -115,6 +130,7 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
|
|||||||
setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam)));
|
setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam)));
|
||||||
setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';')));
|
setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';')));
|
||||||
setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';')));
|
setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';')));
|
||||||
|
if (plan.maxRespawns === UNLIMITED_RESPAWNS) setParam(bots, 'wtoUnlimitedRespawns', text('1'));
|
||||||
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
|
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
|
||||||
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
|
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
|
||||||
setParam(bots, 'numBotRespawnsInVersus', integer(plan.airBotRespawns));
|
setParam(bots, 'numBotRespawnsInVersus', integer(plan.airBotRespawns));
|
||||||
|
|||||||
@@ -95,18 +95,28 @@ export function lineupMrank(
|
|||||||
difficulty: ModeDifficulty,
|
difficulty: ModeDifficulty,
|
||||||
requiredClass: UnitClass,
|
requiredClass: UnitClass,
|
||||||
allowedClasses: readonly UnitClass[],
|
allowedClasses: readonly UnitClass[],
|
||||||
|
mrankDeltas: ReadonlyMap<string, number>,
|
||||||
): number {
|
): number {
|
||||||
const crafts: CraftRankEntry[] = vehicleNames.flatMap((name) => {
|
const crafts: CraftRankEntry[] = vehicleNames.flatMap((name) => {
|
||||||
const vehicle = byName.get(name);
|
const vehicle = byName.get(name);
|
||||||
if (!vehicle) return [];
|
if (!vehicle) return [];
|
||||||
return [{
|
return [{
|
||||||
unitClass: unitClassOfExpClass(vehicle.unitClass),
|
unitClass: unitClassOfExpClass(vehicle.unitClass),
|
||||||
mrank: vehicleMrank(vehicle, difficulty, requiredClass),
|
mrank: lineupVehicleMrank(vehicle, difficulty, requiredClass, mrankDeltas),
|
||||||
}];
|
}];
|
||||||
});
|
});
|
||||||
return maxModeMrank(crafts, requiredClass, allowedClasses);
|
return maxModeMrank(crafts, requiredClass, allowedClasses);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function lineupVehicleMrank(
|
||||||
|
vehicle: CatalogueVehicle,
|
||||||
|
difficulty: ModeDifficulty,
|
||||||
|
requiredClass: UnitClass,
|
||||||
|
mrankDeltas: ReadonlyMap<string, number>,
|
||||||
|
): number {
|
||||||
|
return vehicleMrank(vehicle, difficulty, requiredClass) + (mrankDeltas.get(vehicle.name) ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
export function selectCustomBots(
|
export function selectCustomBots(
|
||||||
vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
|
vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
|
||||||
): CustomBotsPool {
|
): CustomBotsPool {
|
||||||
@@ -203,6 +213,7 @@ export function isModeEligibleForLineup(
|
|||||||
slotVehicles: readonly string[],
|
slotVehicles: readonly string[],
|
||||||
selectedSlotVehicle: string | undefined,
|
selectedSlotVehicle: string | undefined,
|
||||||
byName: ReadonlyMap<string, CatalogueVehicle>,
|
byName: ReadonlyMap<string, CatalogueVehicle>,
|
||||||
|
mrankDeltas: ReadonlyMap<string, number>,
|
||||||
): boolean {
|
): boolean {
|
||||||
if (!declaration.tag && declaration.multiSlot !== false) return true;
|
if (!declaration.tag && declaration.multiSlot !== false) return true;
|
||||||
const active = activeVehiclesForMode(declaration, slotVehicles, selectedSlotVehicle, byName);
|
const active = activeVehiclesForMode(declaration, slotVehicles, selectedSlotVehicle, byName);
|
||||||
@@ -211,7 +222,7 @@ export function isModeEligibleForLineup(
|
|||||||
const matchingCount = active.filter((name) => {
|
const matchingCount = active.filter((name) => {
|
||||||
const vehicle = byName.get(name);
|
const vehicle = byName.get(name);
|
||||||
if (!vehicle || unitClassOfExpClass(vehicle.unitClass) !== declaration.requiredClass) return false;
|
if (!vehicle || unitClassOfExpClass(vehicle.unitClass) !== declaration.requiredClass) return false;
|
||||||
return vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass) >= minMrank;
|
return lineupVehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass, mrankDeltas) >= minMrank;
|
||||||
}).length;
|
}).length;
|
||||||
return matchingCount >= minCrafts;
|
return matchingCount >= minCrafts;
|
||||||
}
|
}
|
||||||
@@ -26,6 +26,7 @@ export interface BattleTuning {
|
|||||||
readonly strikeUcavSpawnScore: number;
|
readonly strikeUcavSpawnScore: number;
|
||||||
readonly tankBotRespawns: number;
|
readonly tankBotRespawns: number;
|
||||||
readonly airBotRespawns: number;
|
readonly airBotRespawns: number;
|
||||||
|
readonly nuclearEscalationStrategicBombers: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function readBattleTuning(reader: TuningReader): BattleTuning {
|
export function readBattleTuning(reader: TuningReader): BattleTuning {
|
||||||
@@ -66,5 +67,6 @@ export function readBattleTuning(reader: TuningReader): BattleTuning {
|
|||||||
strikeUcavSpawnScore: reader.int('strikeUcavSpawnScore', { min: 1, max: 10000 }),
|
strikeUcavSpawnScore: reader.int('strikeUcavSpawnScore', { min: 1, max: 10000 }),
|
||||||
tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }),
|
tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }),
|
||||||
airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }),
|
airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }),
|
||||||
|
nuclearEscalationStrategicBombers: reader.bool('nuclearEscalationStrategicBombers'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -12,6 +12,7 @@ import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue
|
|||||||
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
||||||
import type { ResearchRules } from '../../research/research-rules.ts';
|
import type { ResearchRules } from '../../research/research-rules.ts';
|
||||||
import type { StoreCatalogue } from '../../store/store-catalogue.ts';
|
import type { StoreCatalogue } from '../../store/store-catalogue.ts';
|
||||||
|
import type { TrainingCatalogue } from '../../training/training-completion.ts';
|
||||||
import type { UnlockShop } from '../../unlocks/unlock-purchase.ts';
|
import type { UnlockShop } from '../../unlocks/unlock-purchase.ts';
|
||||||
import type { CharActionHandler } from '../char-action.ts';
|
import type { CharActionHandler } from '../char-action.ts';
|
||||||
import { acceptEula } from './agreement-actions.ts';
|
import { acceptEula } from './agreement-actions.ts';
|
||||||
@@ -61,6 +62,7 @@ import {
|
|||||||
buyWeaponsAction,
|
buyWeaponsAction,
|
||||||
enableModificationsAction,
|
enableModificationsAction,
|
||||||
saveWeaponPresetsAction,
|
saveWeaponPresetsAction,
|
||||||
|
setUnitSelectedMrankAction,
|
||||||
} from './modification-actions.ts';
|
} from './modification-actions.ts';
|
||||||
import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts';
|
import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts';
|
||||||
import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts';
|
import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts';
|
||||||
@@ -93,6 +95,7 @@ export interface ActionDependencies {
|
|||||||
readonly store: StoreCatalogue;
|
readonly store: StoreCatalogue;
|
||||||
readonly inventory: InventoryCatalogue;
|
readonly inventory: InventoryCatalogue;
|
||||||
readonly trophies: TrophyCatalogue;
|
readonly trophies: TrophyCatalogue;
|
||||||
|
readonly training?: TrainingCatalogue;
|
||||||
readonly clans?: ClanActionDependencies;
|
readonly clans?: ClanActionDependencies;
|
||||||
readonly cloudSettings?: CloudSettingsStore;
|
readonly cloudSettings?: CloudSettingsStore;
|
||||||
readonly battle?: BattleActionDependencies;
|
readonly battle?: BattleActionDependencies;
|
||||||
@@ -117,7 +120,7 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH
|
|||||||
['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)],
|
['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)],
|
||||||
['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)],
|
['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)],
|
||||||
['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)],
|
['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)],
|
||||||
['cln_update', clientUpdateAction(deps.profiles, deps.accounts)],
|
['cln_update', clientUpdateAction(deps.profiles, deps.accounts, deps.training)],
|
||||||
['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)],
|
['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)],
|
||||||
['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)],
|
['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)],
|
||||||
['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.crew)],
|
['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.crew)],
|
||||||
@@ -137,6 +140,7 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH
|
|||||||
['cln_buy_weapon', buyWeaponsAction(deps.profiles, deps.accounts, deps.equipment)],
|
['cln_buy_weapon', buyWeaponsAction(deps.profiles, deps.accounts, deps.equipment)],
|
||||||
['cln_save_weapon_presets', saveWeaponPresetsAction(deps.profiles, deps.accounts, deps.equipment)],
|
['cln_save_weapon_presets', saveWeaponPresetsAction(deps.profiles, deps.accounts, deps.equipment)],
|
||||||
['cln_enable_modifications', enableModificationsAction(deps.profiles, deps.accounts, deps.equipment)],
|
['cln_enable_modifications', enableModificationsAction(deps.profiles, deps.accounts, deps.equipment)],
|
||||||
|
['cln_set_unit_selected_mrank', setUnitSelectedMrankAction(deps.profiles, deps.accounts, deps.equipment)],
|
||||||
['cln_upgrade_crew', upgradeCrewAction(deps.profiles, deps.accounts, deps.crew)],
|
['cln_upgrade_crew', upgradeCrewAction(deps.profiles, deps.accounts, deps.crew)],
|
||||||
['cln_purchase_skill_points', purchaseSkillPointsAction(deps.profiles, deps.accounts, deps.crew)],
|
['cln_purchase_skill_points', purchaseSkillPointsAction(deps.profiles, deps.accounts, deps.crew)],
|
||||||
['cln_specialize_crew', specializeCrewAction(deps.profiles, deps.accounts, deps.crew)],
|
['cln_specialize_crew', specializeCrewAction(deps.profiles, deps.accounts, deps.crew)],
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
* settles them into the player's save (battle-settlement.ts) and answers the updated profile,
|
* settles them into the player's save (battle-settlement.ts) and answers the updated profile,
|
||||||
* whose new `EULT_SESSION_RESULT` log carries the debriefing table.
|
* whose new `EULT_SESSION_RESULT` log carries the debriefing table.
|
||||||
*/
|
*/
|
||||||
|
import type { BattleSettlementContext } from '@wto/mods';
|
||||||
import type { AccountStore } from '../../accounts/account-store.ts';
|
import type { AccountStore } from '../../accounts/account-store.ts';
|
||||||
import { parseBattleReport } from '../../battle/battle-report.ts';
|
import { parseBattleReport } from '../../battle/battle-report.ts';
|
||||||
import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
|
import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
|
||||||
@@ -28,6 +29,7 @@ export interface BattleActionDependencies {
|
|||||||
readonly streaks: BattleStreaks;
|
readonly streaks: BattleStreaks;
|
||||||
/** Units whose lives and events are not settled (battle-support-planes.ts). */
|
/** Units whose lives and events are not settled (battle-support-planes.ts). */
|
||||||
readonly supportPlanes: ReadonlySet<string>;
|
readonly supportPlanes: ReadonlySet<string>;
|
||||||
|
readonly onAfterSettle?: (ctx: BattleSettlementContext) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FinishBattleContext {
|
export interface FinishBattleContext {
|
||||||
@@ -62,6 +64,11 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio
|
|||||||
}
|
}
|
||||||
const updated = ctx.profiles.update(account.userId, (profile) => {
|
const updated = ctx.profiles.update(account.userId, (profile) => {
|
||||||
settleBattle(profile, report, session, settlementDeps);
|
settleBattle(profile, report, session, settlementDeps);
|
||||||
|
battle.onAfterSettle?.({
|
||||||
|
userId: account.userId,
|
||||||
|
roomId: session.sessionId,
|
||||||
|
summary: { profile, report, session },
|
||||||
|
});
|
||||||
});
|
});
|
||||||
battle.sessions.markSettled(session.sessionId);
|
battle.sessions.markSettled(session.sessionId);
|
||||||
return { kind: 'data', blk: clientProfile(updated, account) };
|
return { kind: 'data', blk: clientProfile(updated, account) };
|
||||||
|
|||||||
@@ -2,19 +2,48 @@
|
|||||||
* `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`):
|
* `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`):
|
||||||
* triggered by `save_online_single_job` when the client marks seen user logs as disabled
|
* triggered by `save_online_single_job` when the client marks seen user logs as disabled
|
||||||
* (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar
|
* (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar
|
||||||
* auto-repair / auto-refill / auto-buy-modifications and map preferences. Answers the whole
|
* auto-repair / auto-refill / auto-buy-modifications and map preferences. On returning from
|
||||||
* updated profile.
|
* a stock training mission, the client also reports completion in `missionAwards` while
|
||||||
|
* `pveProgress` is empty. Answers the whole updated profile.
|
||||||
*/
|
*/
|
||||||
|
import { findBlock, findParam, type BlkBlock } from '@wto/blk';
|
||||||
import type { AccountStore } from '../../accounts/account-store.ts';
|
import type { AccountStore } from '../../accounts/account-store.ts';
|
||||||
|
import { boolField, stringField } from '../../game-data/datasets/blk-fields.ts';
|
||||||
import { applyClientProfileUpdate } from '../../profile/profile-client-settings.ts';
|
import { applyClientProfileUpdate } from '../../profile/profile-client-settings.ts';
|
||||||
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
||||||
import { ACCEPTED } from '../../research/rule-outcome.ts';
|
import { ACCEPTED } from '../../research/rule-outcome.ts';
|
||||||
|
import type { TrainingCatalogue, TrainingCompletionReport } from '../../training/training-completion.ts';
|
||||||
import type { CharActionHandler } from '../char-action.ts';
|
import type { CharActionHandler } from '../char-action.ts';
|
||||||
import { ruleAction } from './rule-answer.ts';
|
import { ruleAction } from './rule-answer.ts';
|
||||||
|
|
||||||
export function clientUpdateAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
|
export function clientUpdateAction(
|
||||||
return ruleAction(profiles, accounts, (payload) => (profile) => {
|
profiles: PlayerProfiles,
|
||||||
applyClientProfileUpdate(profile, payload);
|
accounts: AccountStore,
|
||||||
return ACCEPTED;
|
training?: TrainingCatalogue,
|
||||||
|
): CharActionHandler {
|
||||||
|
return ruleAction(profiles, accounts, (payload) => {
|
||||||
|
const completion = training ? readTrainingCompletion(payload) : undefined;
|
||||||
|
return (profile) => {
|
||||||
|
applyClientProfileUpdate(profile, payload);
|
||||||
|
if (completion && training) training.applyCompletion(profile, completion);
|
||||||
|
return ACCEPTED;
|
||||||
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function readTrainingCompletion(request: BlkBlock): TrainingCompletionReport | undefined {
|
||||||
|
const awards = findBlock(request, 'missionAwards');
|
||||||
|
if (!awards
|
||||||
|
|| stringField(awards, 'gameModeName') !== 'training'
|
||||||
|
|| boolField(awards, 'success') !== true
|
||||||
|
|| boolField(awards, 'early') !== false
|
||||||
|
|| boolField(awards, 'onlineGame') !== false) return undefined;
|
||||||
|
|
||||||
|
const chapter = stringField(awards, 'chapterName');
|
||||||
|
const mission = stringField(awards, 'missionName');
|
||||||
|
const difficulty = findParam(awards, 'difficulty')?.value;
|
||||||
|
if (!chapter || !mission || difficulty?.type !== 'int'
|
||||||
|
|| (difficulty.value !== 0 && difficulty.value !== 1 && difficulty.value !== 2)) return undefined;
|
||||||
|
|
||||||
|
return { chapter, mission, difficulty: difficulty.value };
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@
|
|||||||
* cln_buy_all_modification: unit:t forceOpen:b cost:i costGold:i
|
* cln_buy_all_modification: unit:t forceOpen:b cost:i costGold:i
|
||||||
* cln_buy_spare_aircrafts: aircraft:t count:i cost:i costGold:i
|
* cln_buy_spare_aircrafts: aircraft:t count:i cost:i costGold:i
|
||||||
* cln_buy_weapon: aircraft:t weapon:t count:i cost:i costGold:i
|
* cln_buy_weapon: aircraft:t weapon:t count:i cost:i costGold:i
|
||||||
|
* cln_set_unit_selected_mrank (scripts/unit/unitmrankselectionstate.nut): unit:t addMrank:i
|
||||||
* cln_enable_modifications (shop_enable_modifications, 0x17a5020 -> 0x29a890; lab round 18):
|
* cln_enable_modifications (shop_enable_modifications, 0x17a5020 -> 0x29a890; lab round 18):
|
||||||
* <vehicle>{ <modification>:b=yes ... } ...
|
* <vehicle>{ <modification>:b=yes ... } ...
|
||||||
*/
|
*/
|
||||||
@@ -16,6 +17,7 @@ import type { AccountStore } from '../../accounts/account-store.ts';
|
|||||||
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
|
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
|
||||||
import { buyAllModifications, buyModification, enableModifications } from '../../modifications/modification-purchase.ts';
|
import { buyAllModifications, buyModification, enableModifications } from '../../modifications/modification-purchase.ts';
|
||||||
import { buySpares } from '../../modifications/spare-purchase.ts';
|
import { buySpares } from '../../modifications/spare-purchase.ts';
|
||||||
|
import { selectVehicleMrankDelta } from '../../modifications/vehicle-mrank-selection.ts';
|
||||||
import { saveWeaponPresets } from '../../modifications/weapon-presets.ts';
|
import { saveWeaponPresets } from '../../modifications/weapon-presets.ts';
|
||||||
import { buyWeapons } from '../../modifications/weapon-purchase.ts';
|
import { buyWeapons } from '../../modifications/weapon-purchase.ts';
|
||||||
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
||||||
@@ -81,6 +83,15 @@ export function saveWeaponPresetsAction(profiles: PlayerProfiles, accounts: Acco
|
|||||||
return ruleAction(profiles, accounts, (payload) => (profile) => saveWeaponPresets(profile, equipment, payload));
|
return ruleAction(profiles, accounts, (payload) => (profile) => saveWeaponPresets(profile, equipment, payload));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function setUnitSelectedMrankAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
|
||||||
|
return ruleAction(profiles, accounts, (payload) => {
|
||||||
|
const vehicle = stringParam(payload, 'unit');
|
||||||
|
const delta = intParam(payload, 'addMrank');
|
||||||
|
if (!vehicle || delta === undefined) return undefined;
|
||||||
|
return (profile) => selectVehicleMrankDelta(profile, equipment, vehicle, delta);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function offeredPrice(payload: BlkBlock) {
|
function offeredPrice(payload: BlkBlock) {
|
||||||
return { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 };
|
return { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 };
|
||||||
}
|
}
|
||||||
@@ -13,6 +13,8 @@
|
|||||||
* default lets the client continue and reveal what it asks for next.
|
* default lets the client continue and reveal what it asks for next.
|
||||||
*/
|
*/
|
||||||
import { emptyBlock } from '@wto/blk';
|
import { emptyBlock } from '@wto/blk';
|
||||||
|
import type { ModCharRequest, ModCharResponse } from '@wto/mods';
|
||||||
|
import type { ServerModRuntime } from '../mods/server-mod-runtime.ts';
|
||||||
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
|
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
|
||||||
import type { CharActionHandler } from './char-action.ts';
|
import type { CharActionHandler } from './char-action.ts';
|
||||||
import { toResponse, type CharAnswer } from './char-answers.ts';
|
import { toResponse, type CharAnswer } from './char-answers.ts';
|
||||||
@@ -23,17 +25,26 @@ const CHAR_HOST = /^char-[a-z0-9-]+\.warthunder\.com$/;
|
|||||||
export class CharService implements Service {
|
export class CharService implements Service {
|
||||||
readonly name = 'char';
|
readonly name = 'char';
|
||||||
readonly #actions: ReadonlyMap<string, CharActionHandler>;
|
readonly #actions: ReadonlyMap<string, CharActionHandler>;
|
||||||
|
readonly #modRuntime: ServerModRuntime | undefined;
|
||||||
|
|
||||||
constructor(actions: ReadonlyMap<string, CharActionHandler>) {
|
constructor(actions: ReadonlyMap<string, CharActionHandler>, modRuntime?: ServerModRuntime) {
|
||||||
this.#actions = actions;
|
this.#actions = actions;
|
||||||
|
this.#modRuntime = modRuntime;
|
||||||
}
|
}
|
||||||
|
|
||||||
accepts(request: ServiceRequest): boolean {
|
accepts(request: ServiceRequest): boolean {
|
||||||
return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost);
|
return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost);
|
||||||
}
|
}
|
||||||
|
|
||||||
handle(request: ServiceRequest): ServiceResponse {
|
handle(request: ServiceRequest): ServiceResponse | Promise<ServiceResponse> {
|
||||||
const action = header(request, 'action') ?? '(no action header)';
|
const action = header(request, 'action') ?? '(no action header)';
|
||||||
|
if (this.#modRuntime?.hasCharOverride(action)) {
|
||||||
|
return this.#handleWithModOverride(action, request);
|
||||||
|
}
|
||||||
|
return this.#handleCore(action, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
#handleCore(action: string, request: ServiceRequest): ServiceResponse {
|
||||||
const payload = decodeRequestPayload(request.body);
|
const payload = decodeRequestPayload(request.body);
|
||||||
const handler = this.#actions.get(action);
|
const handler = this.#actions.get(action);
|
||||||
const answer: CharAnswer = handler
|
const answer: CharAnswer = handler
|
||||||
@@ -56,6 +67,46 @@ export class CharService implements Service {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async #handleWithModOverride(action: string, request: ServiceRequest): Promise<ServiceResponse> {
|
||||||
|
const headers: Record<string, string | undefined> = {};
|
||||||
|
for (const [key, value] of Object.entries(request.headers)) {
|
||||||
|
headers[key] = Array.isArray(value) ? value[0] : value;
|
||||||
|
}
|
||||||
|
const query: Record<string, string> = {};
|
||||||
|
for (const [key, value] of request.query.entries()) query[key] = value;
|
||||||
|
|
||||||
|
const modReq: ModCharRequest = {
|
||||||
|
action,
|
||||||
|
userId: header(request, 'uidhint') ?? '',
|
||||||
|
headers,
|
||||||
|
body: request.body,
|
||||||
|
query,
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await this.#modRuntime!.dispatchCharOverride(action, modReq, async (nextReq): Promise<ModCharResponse> => {
|
||||||
|
const forwarded: ServiceRequest = { ...request, body: nextReq.body };
|
||||||
|
const coreResp = this.#handleCore(nextReq.action, forwarded);
|
||||||
|
return {
|
||||||
|
status: coreResp.status,
|
||||||
|
...(coreResp.headers ? { headers: coreResp.headers } : {}),
|
||||||
|
body: coreResp.body ?? '',
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const responseHeaders: Record<string, string> = { ...(result.headers ?? {}) };
|
||||||
|
if (result.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) {
|
||||||
|
responseHeaders['content-type'] = result.contentType;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
status: result.status ?? 200,
|
||||||
|
headers: responseHeaders,
|
||||||
|
body: result.body,
|
||||||
|
logNotes: {
|
||||||
|
summary: `${action} [mod handler] -> ${result.status ?? 200}`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function header(request: ServiceRequest, name: string): string | undefined {
|
function header(request: ServiceRequest, name: string): string | undefined {
|
||||||
|
|||||||
@@ -14,12 +14,14 @@
|
|||||||
* char.vromfs.bin config/wpcost.blk
|
* char.vromfs.bin config/wpcost.blk
|
||||||
* ucav_*_killstreak{ country:t ... }
|
* ucav_*_killstreak{ country:t ... }
|
||||||
* The strike UCAVs, one per country.
|
* The strike UCAVs, one per country.
|
||||||
|
* *_killstreak / nt_* with weapons.<preset>.totalNuclearYield:i
|
||||||
|
* Tactical (5 kt / 30 kt) and strategic (>= 1000 kt) nuclear carriers for Nuclear Escalation.
|
||||||
* char.vromfs.bin config/warpoints.blk respawn_points / TankHistorical
|
* char.vromfs.bin config/warpoints.blk respawn_points / TankHistorical
|
||||||
* Starting points and unit cost parameters for Ground Realistic Battles.
|
* Starting points and unit cost parameters for Ground Realistic Battles.
|
||||||
*/
|
*/
|
||||||
import type { BlkBlock } from '@wto/blk';
|
import type { BlkBlock } from '@wto/blk';
|
||||||
import { findParam } from '@wto/blk';
|
import { findParam } from '@wto/blk';
|
||||||
import { blockAt, numberField, stringField, stringList } from './blk-fields.ts';
|
import { blockAt, boolField, numberField, stringField, stringList } from './blk-fields.ts';
|
||||||
import type { Dataset } from './dataset.ts';
|
import type { Dataset } from './dataset.ts';
|
||||||
|
|
||||||
export interface SupportPlaneUnit {
|
export interface SupportPlaneUnit {
|
||||||
@@ -43,6 +45,18 @@ export interface StrikeUcav {
|
|||||||
readonly unitName: string;
|
readonly unitName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface NuclearCarrierWeapon {
|
||||||
|
readonly name: string;
|
||||||
|
readonly yieldKt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NuclearCarrierUnit {
|
||||||
|
readonly country: string;
|
||||||
|
readonly unitName: string;
|
||||||
|
readonly mrank: number;
|
||||||
|
readonly weapons: readonly NuclearCarrierWeapon[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface RandomSpawnUnit {
|
export interface RandomSpawnUnit {
|
||||||
readonly unitName: string;
|
readonly unitName: string;
|
||||||
readonly addModifications: readonly string[];
|
readonly addModifications: readonly string[];
|
||||||
@@ -76,22 +90,31 @@ export interface BattleSpawnRulesData {
|
|||||||
/** By event name (`missionSupportPlane` keys are game mode names). */
|
/** By event name (`missionSupportPlane` keys are game mode names). */
|
||||||
readonly supportPlanes: Readonly<Record<string, readonly SupportPlanePreset[]>>;
|
readonly supportPlanes: Readonly<Record<string, readonly SupportPlanePreset[]>>;
|
||||||
readonly strikeUcavs: readonly StrikeUcav[];
|
readonly strikeUcavs: readonly StrikeUcav[];
|
||||||
|
/** Killstreak nuclear carriers carrying 5 kt / 30 kt Nuclear Escalation presets. */
|
||||||
|
readonly nuclearEscalationTacticalCarriers: readonly NuclearCarrierUnit[];
|
||||||
|
/** Megaton-class strategic nuclear bombers (`nt_*` with totalNuclearYield >= 1000 kt). */
|
||||||
|
readonly nuclearEscalationStrategicBombers: readonly NuclearCarrierUnit[];
|
||||||
readonly spawnScore: SpawnScoreRules;
|
readonly spawnScore: SpawnScoreRules;
|
||||||
/** By event economic name, then country. */
|
/** By event economic name, then country. */
|
||||||
readonly randomSpawnUnits: Readonly<Record<string, Readonly<Record<string, readonly RandomSpawnGroup[]>>>>;
|
readonly randomSpawnUnits: Readonly<Record<string, Readonly<Record<string, readonly RandomSpawnGroup[]>>>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const STRIKE_UCAV_PATTERN = /^ucav_.*_killstreak$/;
|
const STRIKE_UCAV_PATTERN = /^ucav_.*_killstreak$/;
|
||||||
|
const KILLSTREAK_PATTERN = /_killstreak$/;
|
||||||
|
const STRATEGIC_BOMBER_PATTERN = /^nt_/;
|
||||||
|
const STRATEGIC_YIELD_MIN_KT = 1000;
|
||||||
|
|
||||||
export const battleSpawnRules: Dataset<BattleSpawnRulesData> = {
|
export const battleSpawnRules: Dataset<BattleSpawnRulesData> = {
|
||||||
id: 'battle-spawn-rules',
|
id: 'battle-spawn-rules',
|
||||||
version: 3,
|
version: 4,
|
||||||
extract: (source) => {
|
extract: (source) => {
|
||||||
const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk');
|
const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk');
|
||||||
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
|
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
|
||||||
return {
|
return {
|
||||||
supportPlanes: extractSupportPlanes(blockAt(gameplay, 'missionSupportPlane')),
|
supportPlanes: extractSupportPlanes(blockAt(gameplay, 'missionSupportPlane')),
|
||||||
strikeUcavs: extractStrikeUcavs(wpcost.blocks),
|
strikeUcavs: extractStrikeUcavs(wpcost.blocks),
|
||||||
|
nuclearEscalationTacticalCarriers: extractNuclearCarriers(wpcost.blocks, 'tactical'),
|
||||||
|
nuclearEscalationStrategicBombers: extractNuclearCarriers(wpcost.blocks, 'strategic'),
|
||||||
spawnScore: extractSpawnScore(blockAt(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'respawn_points')),
|
spawnScore: extractSpawnScore(blockAt(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'respawn_points')),
|
||||||
randomSpawnUnits: extractRandomSpawnUnits(blockAt(gameplay, 'RandomSpawnUnits')),
|
randomSpawnUnits: extractRandomSpawnUnits(blockAt(gameplay, 'RandomSpawnUnits')),
|
||||||
};
|
};
|
||||||
@@ -162,6 +185,38 @@ function extractStrikeUcavs(wpcostBlocks: readonly BlkBlock[]): StrikeUcav[] {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function extractNuclearCarriers(
|
||||||
|
wpcostBlocks: readonly BlkBlock[],
|
||||||
|
kind: 'tactical' | 'strategic',
|
||||||
|
): NuclearCarrierUnit[] {
|
||||||
|
const carriers: NuclearCarrierUnit[] = [];
|
||||||
|
for (const unitBlk of wpcostBlocks) {
|
||||||
|
const country = stringField(unitBlk, 'country') ?? '';
|
||||||
|
if (!country.startsWith('country_')) continue;
|
||||||
|
if (kind === 'tactical' && !KILLSTREAK_PATTERN.test(unitBlk.name)) continue;
|
||||||
|
if (kind === 'strategic' && !STRATEGIC_BOMBER_PATTERN.test(unitBlk.name)) continue;
|
||||||
|
const weaponsBlk = blockAt(unitBlk, 'weapons');
|
||||||
|
if (!weaponsBlk) continue;
|
||||||
|
const weapons: NuclearCarrierWeapon[] = [];
|
||||||
|
for (const weaponBlk of weaponsBlk.blocks) {
|
||||||
|
if (boolField(weaponBlk, 'isWeaponForCustomSlot') === true) continue;
|
||||||
|
if (boolField(weaponBlk, 'hideInGui') === true) continue;
|
||||||
|
if (weaponBlk.name.includes('without_countermeasures')) continue;
|
||||||
|
const yieldKt = numberField(weaponBlk, 'totalNuclearYield') ?? 0;
|
||||||
|
if (yieldKt <= 0) continue;
|
||||||
|
if (kind === 'tactical' && yieldKt >= STRATEGIC_YIELD_MIN_KT) continue;
|
||||||
|
if (kind === 'strategic' && yieldKt < STRATEGIC_YIELD_MIN_KT) continue;
|
||||||
|
weapons.push({ name: weaponBlk.name, yieldKt });
|
||||||
|
}
|
||||||
|
if (weapons.length === 0) continue;
|
||||||
|
weapons.sort((a, b) => a.yieldKt - b.yieldKt || a.name.localeCompare(b.name));
|
||||||
|
const mrank = numberField(unitBlk, 'economicRankHistorical') ?? numberField(unitBlk, 'economicRank') ?? 0;
|
||||||
|
carriers.push({ country, unitName: unitBlk.name, mrank, weapons });
|
||||||
|
}
|
||||||
|
carriers.sort((a, b) => a.country.localeCompare(b.country) || a.mrank - b.mrank || a.unitName.localeCompare(b.unitName));
|
||||||
|
return carriers;
|
||||||
|
}
|
||||||
|
|
||||||
function extractRandomSpawnUnits(
|
function extractRandomSpawnUnits(
|
||||||
root: BlkBlock | undefined,
|
root: BlkBlock | undefined,
|
||||||
): Record<string, Record<string, RandomSpawnGroup[]>> {
|
): Record<string, Record<string, RandomSpawnGroup[]>> {
|
||||||
|
|||||||
@@ -0,0 +1,117 @@
|
|||||||
|
/**
|
||||||
|
* Dataset: stock training missions and their first-completion rewards from char.vromfs.bin:
|
||||||
|
* - config/mislist.blk ("training" block): chapter/mission full names accepted for progress;
|
||||||
|
* - config/pve_awards.blk ("training" block): per-mission decal, shared first-completion unlock,
|
||||||
|
* and per-difficulty Silver Lions rewards (`wpEarnedWinDiff0..2`);
|
||||||
|
* - config/unlocks.blk: decal unlock verification and `oneTimeAwardUnlock` Golden Eagles amount
|
||||||
|
* and mutually exclusive `char_unlocked` conditions.
|
||||||
|
*/
|
||||||
|
import { findParam, type BlkBlock } from '@wto/blk';
|
||||||
|
import { blockAt, boolField, stringField, stringList } from './blk-fields.ts';
|
||||||
|
import type { Dataset, DatasetSource } from './dataset.ts';
|
||||||
|
|
||||||
|
const CHAR_PACK = 'char.vromfs.bin';
|
||||||
|
const MISLIST = 'config/mislist.blk';
|
||||||
|
const PVE_AWARDS = 'config/pve_awards.blk';
|
||||||
|
const UNLOCKS = 'config/unlocks.blk';
|
||||||
|
const TRAINING_SECTION = 'training';
|
||||||
|
|
||||||
|
export interface TrainingFirstCompletionAward {
|
||||||
|
readonly id: string;
|
||||||
|
readonly goldenEagles: number;
|
||||||
|
readonly blockedBy: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TrainingMissionEntry {
|
||||||
|
readonly fullName: string;
|
||||||
|
readonly decal?: string;
|
||||||
|
readonly firstCompletion?: TrainingFirstCompletionAward;
|
||||||
|
/** First-win Silver Lions rewards (`wpEarnedWinDiff0..2`) for arcade, realistic, simulator. */
|
||||||
|
readonly silverLionsByDifficulty: readonly [number, number, number];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TrainingMissionsData {
|
||||||
|
readonly missions: readonly TrainingMissionEntry[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const trainingMissions: Dataset<TrainingMissionsData> = {
|
||||||
|
id: 'training-missions',
|
||||||
|
version: 1,
|
||||||
|
extract(source: DatasetSource): TrainingMissionsData {
|
||||||
|
const misSection = blockAt(source.readBlk(CHAR_PACK, MISLIST), TRAINING_SECTION);
|
||||||
|
if (!misSection) throw new Error(`${MISLIST} has no "${TRAINING_SECTION}" block`);
|
||||||
|
const awardSection = blockAt(source.readBlk(CHAR_PACK, PVE_AWARDS), TRAINING_SECTION);
|
||||||
|
if (!awardSection) throw new Error(`${PVE_AWARDS} has no "${TRAINING_SECTION}" block`);
|
||||||
|
|
||||||
|
const awardsByMission = new Map<string, BlkBlock>(awardSection.blocks.map((entry) => [entry.name, entry]));
|
||||||
|
const unlocksById = new Map<string, BlkBlock>();
|
||||||
|
for (const entry of source.readBlk(CHAR_PACK, UNLOCKS).blocks) {
|
||||||
|
const id = stringField(entry, 'id');
|
||||||
|
if (id) unlocksById.set(id, entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const missions: TrainingMissionEntry[] = [];
|
||||||
|
for (const chapter of misSection.blocks) {
|
||||||
|
for (const mission of stringList(chapter, 'm')) {
|
||||||
|
const fullName = `${chapter.name}/${mission}`;
|
||||||
|
if (seen.has(fullName)) continue;
|
||||||
|
seen.add(fullName);
|
||||||
|
missions.push(buildMissionEntry(fullName, mission, awardsByMission.get(mission), unlocksById));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { missions };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
function buildMissionEntry(
|
||||||
|
fullName: string,
|
||||||
|
mission: string,
|
||||||
|
award: BlkBlock | undefined,
|
||||||
|
unlocks: ReadonlyMap<string, BlkBlock>,
|
||||||
|
): TrainingMissionEntry {
|
||||||
|
const decalId = stringField(award, 'decal');
|
||||||
|
const decal = decalId && stringField(unlocks.get(decalId), 'type') === 'decal' ? decalId : undefined;
|
||||||
|
const firstCompletion = award ? readFirstCompletionAward(award, mission, unlocks) : undefined;
|
||||||
|
return {
|
||||||
|
fullName,
|
||||||
|
...(decal ? { decal } : {}),
|
||||||
|
...(firstCompletion ? { firstCompletion } : {}),
|
||||||
|
silverLionsByDifficulty: [
|
||||||
|
readWinSilverLions(award, 0),
|
||||||
|
readWinSilverLions(award, 1),
|
||||||
|
readWinSilverLions(award, 2),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function readFirstCompletionAward(
|
||||||
|
award: BlkBlock,
|
||||||
|
mission: string,
|
||||||
|
unlocks: ReadonlyMap<string, BlkBlock>,
|
||||||
|
): TrainingFirstCompletionAward | undefined {
|
||||||
|
const id = stringField(award, 'oneTimeAwardUnlock');
|
||||||
|
if (!id) return undefined;
|
||||||
|
const unlock = unlocks.get(id);
|
||||||
|
if (stringField(unlock, 'type') !== 'award') return undefined;
|
||||||
|
const amount = unlock && findParam(unlock, 'amount_gold')?.value;
|
||||||
|
const mode = blockAt(unlock, 'mode');
|
||||||
|
if (amount?.type !== 'int' || amount.value <= 0
|
||||||
|
|| stringField(mode, 'type') !== 'char_mission_list'
|
||||||
|
|| !stringList(mode, 'name').includes(mission)) return undefined;
|
||||||
|
|
||||||
|
const blocked = mode?.blocks.flatMap((condition) =>
|
||||||
|
condition.name === 'condition'
|
||||||
|
&& stringField(condition, 'type') === 'char_unlocked'
|
||||||
|
&& boolField(condition, 'positive') === false
|
||||||
|
? stringList(condition, 'unlock')
|
||||||
|
: []) ?? [];
|
||||||
|
const hideIfEarned = stringField(award, 'hideOneTimeAwardIfUnlockIsOpen');
|
||||||
|
if (hideIfEarned) blocked.push(hideIfEarned);
|
||||||
|
return { id, goldenEagles: amount.value, blockedBy: [...new Set(blocked)] };
|
||||||
|
}
|
||||||
|
|
||||||
|
function readWinSilverLions(award: BlkBlock | undefined, difficulty: 0 | 1 | 2): number {
|
||||||
|
const value = award && findParam(award, `wpEarnedWinDiff${difficulty}`)?.value;
|
||||||
|
return value?.type === 'int' && value.value > 0 ? value.value : 0;
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
* char.vromfs.bin config/wpcost.blk, per vehicle:
|
* char.vromfs.bin config/wpcost.blk, per vehicle:
|
||||||
* needBuyToOpenNextInTier<N>:i researched modifications of tier N needed to open tier N+1
|
* needBuyToOpenNextInTier<N>:i researched modifications of tier N needed to open tier N+1
|
||||||
* modifications{ <name>{ tier:i reqExp:i value:i costGold:i openCostGold:i
|
* modifications{ <name>{ tier:i reqExp:i value:i costGold:i openCostGold:i
|
||||||
* reqModification:t (repeated) maxCount:i ammoCount:i ... } }
|
* reqModification:t (repeated) maxCount:i ammoCount:i addMrank:i ... } }
|
||||||
* Ammunition and expendables are modifications too (tier 0, maxCount, ammoCount).
|
* Ammunition and expendables are modifications too (tier 0, maxCount, ammoCount).
|
||||||
* weapons{ <preset>{ value:i costGold:i maxCount:i reqModification:t ... } }
|
* weapons{ <preset>{ value:i costGold:i maxCount:i reqModification:t ... } }
|
||||||
* Paid presets (bombs, rockets) are bought by the piece, up to maxCount; the rest are free,
|
* Paid presets (bombs, rockets) are bought by the piece, up to maxCount; the rest are free,
|
||||||
@@ -39,6 +39,8 @@ export interface ModificationFacts {
|
|||||||
readonly maxCount: number;
|
readonly maxCount: number;
|
||||||
/** ammoCount present: an ammunition belt or shell type. */
|
/** ammoCount present: an ammunition belt or shell type. */
|
||||||
readonly ammunition: boolean;
|
readonly ammunition: boolean;
|
||||||
|
/** addMrank: selectable matchmaking rank increase unlocked by owning this modification. */
|
||||||
|
readonly addMrank?: number;
|
||||||
/** Initial enabled state when acquired (`turn_it_off` / `isEnabledByDefaultForAddMrank`). */
|
/** Initial enabled state when acquired (`turn_it_off` / `isEnabledByDefaultForAddMrank`). */
|
||||||
readonly defaultEnabled: boolean;
|
readonly defaultEnabled: boolean;
|
||||||
/** Non-bullet `group` name when modifications in the same group are mutually exclusive. */
|
/** Non-bullet `group` name when modifications in the same group are mutually exclusive. */
|
||||||
@@ -78,7 +80,7 @@ interface GlobalModificationMeta {
|
|||||||
|
|
||||||
export const vehicleEquipment: Dataset<readonly VehicleEquipment[]> = {
|
export const vehicleEquipment: Dataset<readonly VehicleEquipment[]> = {
|
||||||
id: 'vehicle-equipment',
|
id: 'vehicle-equipment',
|
||||||
version: 4,
|
version: 5,
|
||||||
extract: (source) => {
|
extract: (source) => {
|
||||||
const modMeta = readGlobalModificationMeta(source.readBlk('char.vromfs.bin', MODIFICATIONS_CONFIG));
|
const modMeta = readGlobalModificationMeta(source.readBlk('char.vromfs.bin', MODIFICATIONS_CONFIG));
|
||||||
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => equipmentOf(vehicle, modMeta));
|
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => equipmentOf(vehicle, modMeta));
|
||||||
@@ -119,6 +121,7 @@ function equipmentOf(vehicle: BlkBlock, modMeta: ReadonlyMap<string, GlobalModif
|
|||||||
|
|
||||||
function modificationOf(modification: BlkBlock, meta: GlobalModificationMeta | undefined): ModificationFacts {
|
function modificationOf(modification: BlkBlock, meta: GlobalModificationMeta | undefined): ModificationFacts {
|
||||||
const ammunition = numberField(modification, 'ammoCount') !== undefined;
|
const ammunition = numberField(modification, 'ammoCount') !== undefined;
|
||||||
|
const addMrank = numberField(modification, 'addMrank');
|
||||||
const defaultEnabled = !(meta?.turnOffByDefault ?? false) && (boolField(modification, 'isEnabledByDefaultForAddMrank') ?? true);
|
const defaultEnabled = !(meta?.turnOffByDefault ?? false) && (boolField(modification, 'isEnabledByDefaultForAddMrank') ?? true);
|
||||||
const group = stringField(modification, 'group') ?? meta?.group;
|
const group = stringField(modification, 'group') ?? meta?.group;
|
||||||
const exclusiveGroup = !ammunition && !(meta?.bulletGroup ?? false) ? group : undefined;
|
const exclusiveGroup = !ammunition && !(meta?.bulletGroup ?? false) ? group : undefined;
|
||||||
@@ -132,6 +135,7 @@ function modificationOf(modification: BlkBlock, meta: GlobalModificationMeta | u
|
|||||||
requires: stringList(modification, 'reqModification'),
|
requires: stringList(modification, 'reqModification'),
|
||||||
maxCount: numberField(modification, 'maxCount') ?? 0,
|
maxCount: numberField(modification, 'maxCount') ?? 0,
|
||||||
ammunition,
|
ammunition,
|
||||||
|
...(addMrank !== undefined ? { addMrank } : {}),
|
||||||
defaultEnabled,
|
defaultEnabled,
|
||||||
...(exclusiveGroup !== undefined ? { exclusiveGroup } : {}),
|
...(exclusiveGroup !== undefined ? { exclusiveGroup } : {}),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -50,6 +50,10 @@ export interface GameModeDeclaration {
|
|||||||
* `true`; `false` for single-slot modes (`air_realistic` and its `small_teams_` sub-mode).
|
* `true`; `false` for single-slot modes (`air_realistic` and its `small_teams_` sub-mode).
|
||||||
*/
|
*/
|
||||||
readonly multiSlot?: boolean;
|
readonly multiSlot?: boolean;
|
||||||
|
/** Stock maxRespawns value when this mode specifies its own respawn count. */
|
||||||
|
readonly maxRespawns?: number;
|
||||||
|
/** Additional scalar settings the local host needs from this mode's missions. */
|
||||||
|
readonly missionRuleKeys?: readonly string[];
|
||||||
/** False for modes whose native weapon rules replace combat presets. Defaults to true. */
|
/** False for modes whose native weapon rules replace combat presets. Defaults to true. */
|
||||||
readonly allowBotAircraftLoadouts?: boolean;
|
readonly allowBotAircraftLoadouts?: boolean;
|
||||||
/** Minimum `mrank` exposed on the parent mode for Night Battles (`scripts/events/eventinfo.nut:134-136`). */
|
/** Minimum `mrank` exposed on the parent mode for Night Battles (`scripts/events/eventinfo.nut:134-136`). */
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
* AB/RB get Enduring Confrontation; Ground AB and Air AB get none);
|
* AB/RB get Enduring Confrontation; Ground AB and Air AB get none);
|
||||||
* - `queueEvent.nut` includes or excludes its `gameModeId` in `match.enqueue` `game_modes_list`.
|
* - `queueEvent.nut` includes or excludes its `gameModeId` in `match.enqueue` `game_modes_list`.
|
||||||
*/
|
*/
|
||||||
|
import { UNLIMITED_RESPAWNS } from '../mode-definition.ts';
|
||||||
import type { GameModeDeclaration } from './game-mode-declaration.ts';
|
import type { GameModeDeclaration } from './game-mode-declaration.ts';
|
||||||
import {
|
import {
|
||||||
AIR_REALISTIC_MISSIONS,
|
AIR_REALISTIC_MISSIONS,
|
||||||
@@ -69,6 +70,15 @@ export const SUB_GAME_MODES: readonly GameModeDeclaration[] = [
|
|||||||
displayType: 'random_battle',
|
displayType: 'random_battle',
|
||||||
allowedCraftMinMrank: { aircraft: MIN_MRANK_NUCLEAR_ESCALATION },
|
allowedCraftMinMrank: { aircraft: MIN_MRANK_NUCLEAR_ESCALATION },
|
||||||
minQueueMrank: MIN_MRANK_NUCLEAR_ESCALATION,
|
minQueueMrank: MIN_MRANK_NUCLEAR_ESCALATION,
|
||||||
|
maxRespawns: UNLIMITED_RESPAWNS,
|
||||||
|
// mission_settings.mission in mis.vromfs.bin gamedata/missions/cta/planes/nuclear_escalation/.
|
||||||
|
missionRuleKeys: [
|
||||||
|
'customHUD', 'nuclearEscalationStage1', 'nuclearEscalationStage2', 'nuclearEscalationStage3',
|
||||||
|
'useSpawnDelay', 'afterRespawnDelaySec', 'overrideMaxActiveUnitsWeight', 'scheduleBasedGmUpdateMaxInterval',
|
||||||
|
'disableFallingTrees', 'alwaysSendAllyGMData', 'isAlwaysShowCollectiveDetectedUnits', 'useAIForCollectiveDetection',
|
||||||
|
'allowToChooseHUDIconPreset', 'showAIKilllog', 'showUnitTooltipOnMap', 'disableMfdForPrevgenConsoles',
|
||||||
|
'clientReplayMaxSizeMb', 'timeToLoseInstantDetection', 'showTacticalMapCellSize',
|
||||||
|
],
|
||||||
requiredClass: 'aircraft',
|
requiredClass: 'aircraft',
|
||||||
allowedClasses: ['aircraft'],
|
allowedClasses: ['aircraft'],
|
||||||
missions: NUCLEAR_ESCALATION_MISSIONS,
|
missions: NUCLEAR_ESCALATION_MISSIONS,
|
||||||
|
|||||||
@@ -41,8 +41,13 @@ export const MISSION_DIFFICULTY: Readonly<Record<ModeDifficulty, string>> = {
|
|||||||
simulator: 'hardcore',
|
simulator: 'hardcore',
|
||||||
};
|
};
|
||||||
|
|
||||||
// globals/missions/respawnCountModes.nut: RESPAWN_COUNT_MODE.SINGLE_SPAWN.
|
// globals/missions/respawnCountModes.nut: RESPAWN_COUNT_MODE.
|
||||||
export const SINGLE_SPAWN = 1;
|
export const SINGLE_SPAWN = 1;
|
||||||
|
export const UNLIMITED_RESPAWNS = -2;
|
||||||
|
|
||||||
|
export function modeMaxRespawns(mode: GameModeDeclaration): number | undefined {
|
||||||
|
return mode.maxRespawns ?? (mode.multiSlot === false ? SINGLE_SPAWN : undefined);
|
||||||
|
}
|
||||||
|
|
||||||
export type ModeDefinition = Readonly<Record<string, unknown>>;
|
export type ModeDefinition = Readonly<Record<string, unknown>>;
|
||||||
|
|
||||||
@@ -50,6 +55,7 @@ export function buildModeDefinition(mode: GameModeDeclaration, missions: readonl
|
|||||||
countries: readonly string[], missionRanks?: MissionRotationRanks): ModeDefinition {
|
countries: readonly string[], missionRanks?: MissionRotationRanks): ModeDefinition {
|
||||||
const minTeamSize = mode.teamSizeOverride?.min ?? 1;
|
const minTeamSize = mode.teamSizeOverride?.min ?? 1;
|
||||||
const maxTeamSize = mode.teamSizeOverride?.max ?? teamSize(mode, missions);
|
const maxTeamSize = mode.teamSizeOverride?.max ?? teamSize(mode, missions);
|
||||||
|
const maxRespawns = modeMaxRespawns(mode);
|
||||||
const team = {
|
const team = {
|
||||||
countries: [...countries],
|
countries: [...countries],
|
||||||
allowedCrafts: mode.allowedClasses.map((unitClass) => {
|
allowedCrafts: mode.allowedClasses.map((unitClass) => {
|
||||||
@@ -83,7 +89,7 @@ export function buildModeDefinition(mode: GameModeDeclaration, missions: readonl
|
|||||||
teamB: structuredClone(team),
|
teamB: structuredClone(team),
|
||||||
mission_decl: {
|
mission_decl: {
|
||||||
difficulty: MISSION_DIFFICULTY[mode.difficulty],
|
difficulty: MISSION_DIFFICULTY[mode.difficulty],
|
||||||
...(mode.multiSlot === false ? { maxRespawns: SINGLE_SPAWN } : {}),
|
...(maxRespawns === undefined ? {} : { maxRespawns }),
|
||||||
missions_list: Object.fromEntries(missions.map((mission) => {
|
missions_list: Object.fromEntries(missions.map((mission) => {
|
||||||
const ranges = missionRanks?.byMission.get(mission.name);
|
const ranges = missionRanks?.byMission.get(mission.name);
|
||||||
return [mission.name, ranges?.length === 1 ? { enableIf: ranges[0] } : {}];
|
return [mission.name, ranges?.length === 1 ? { enableIf: ranges[0] } : {}];
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import type { BlkBlock, BlkValue } from '@wto/blk';
|
|||||||
import type { BannerParams } from '../battle/battle-economy.ts';
|
import type { BannerParams } from '../battle/battle-economy.ts';
|
||||||
import type { BattleLaunchPlan } from '../battle/battle-matchmaker.ts';
|
import type { BattleLaunchPlan } from '../battle/battle-matchmaker.ts';
|
||||||
import { battleMissionSettings } from '../battle/battle-mission-settings.ts';
|
import { battleMissionSettings } from '../battle/battle-mission-settings.ts';
|
||||||
import { SINGLE_SPAWN } from '../game-modes/mode-definition.ts';
|
|
||||||
|
|
||||||
type WireParam = readonly [name: string, type: 't' | 'i' | 'r' | 'b', value: string | number | boolean];
|
type WireParam = readonly [name: string, type: 't' | 'i' | 'r' | 'b', value: string | number | boolean];
|
||||||
|
|
||||||
@@ -52,12 +51,13 @@ export function battleLaunchNotify(
|
|||||||
mission: {
|
mission: {
|
||||||
name: plan.missionName,
|
name: plan.missionName,
|
||||||
difficulty: plan.difficulty,
|
difficulty: plan.difficulty,
|
||||||
...(plan.selectedSlot ? { maxRespawns: SINGLE_SPAWN } : {}),
|
...(plan.maxRespawns === undefined ? {} : { maxRespawns: plan.maxRespawns }),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
battle: {
|
battle: {
|
||||||
sessionId: plan.sessionId,
|
sessionId: plan.sessionId,
|
||||||
modeName: plan.modeName,
|
modeName: plan.modeName,
|
||||||
|
...(plan.modeTag ? { modeTag: plan.modeTag } : {}),
|
||||||
economicName: plan.economicName,
|
economicName: plan.economicName,
|
||||||
country: plan.country,
|
country: plan.country,
|
||||||
missionName: plan.missionName,
|
missionName: plan.missionName,
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
* "strike": time:f the local player's nuclear bomb exploded
|
* "strike": time:f the local player's nuclear bomb exploded
|
||||||
* answer: { streaks: [{ id:s stage:i (-1 = single-stage) stageParam:i wp:i exp:i }] }
|
* answer: { streaks: [{ id:s stage:i (-1 = single-stage) stageParam:i wp:i exp:i }] }
|
||||||
*/
|
*/
|
||||||
|
import type { BattleLiveFactContext } from '@wto/mods';
|
||||||
import type { BattleLiveLogs } from '../battle/battle-live-log.ts';
|
import type { BattleLiveLogs } from '../battle/battle-live-log.ts';
|
||||||
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
|
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
|
||||||
import type { BattleStreaks } from '../battle/battle-streaks.ts';
|
import type { BattleStreaks } from '../battle/battle-streaks.ts';
|
||||||
@@ -23,6 +24,7 @@ export interface BattleLiveDependencies {
|
|||||||
readonly streaks: BattleStreaks;
|
readonly streaks: BattleStreaks;
|
||||||
/** Units whose lives and events earn no awards (battle-support-planes.ts). */
|
/** Units whose lives and events earn no awards (battle-support-planes.ts). */
|
||||||
readonly supportPlanes: ReadonlySet<string>;
|
readonly supportPlanes: ReadonlySet<string>;
|
||||||
|
readonly onLiveFact?: (ctx: BattleLiveFactContext) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string, MatchingRequestHandler]> {
|
export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string, MatchingRequestHandler]> {
|
||||||
@@ -34,6 +36,11 @@ export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string,
|
|||||||
if (!session || session.settled) return { streaks: [] };
|
if (!session || session.settled) return { streaks: [] };
|
||||||
const log = deps.liveLogs.of(session.sessionId);
|
const log = deps.liveLogs.of(session.sessionId);
|
||||||
if (!recordFact(log, p)) return { streaks: [] };
|
if (!recordFact(log, p)) return { streaks: [] };
|
||||||
|
deps.onLiveFact?.({
|
||||||
|
userId: userId!,
|
||||||
|
roomId: session.sessionId,
|
||||||
|
fact: p as Record<string, unknown>,
|
||||||
|
});
|
||||||
const awarded = deps.streaks.evaluate({
|
const awarded = deps.streaks.evaluate({
|
||||||
...withoutSupportPlanes({ events: log.events, lives: log.lives }, deps.supportPlanes),
|
...withoutSupportPlanes({ events: log.events, lives: log.lives }, deps.supportPlanes),
|
||||||
feed: log.feed,
|
feed: log.feed,
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
|
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
|
||||||
* - `match.check_reconnect`
|
* - `match.check_reconnect`
|
||||||
*/
|
*/
|
||||||
|
import type { BattleMatchmakeContext } from '@wto/mods';
|
||||||
import { MAX_BATTLE_CREW_SLOTS } from '../battle/battle-extra-slots.ts';
|
import { MAX_BATTLE_CREW_SLOTS } from '../battle/battle-extra-slots.ts';
|
||||||
import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.ts';
|
import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.ts';
|
||||||
import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts';
|
import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts';
|
||||||
@@ -12,6 +13,7 @@ import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankE
|
|||||||
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
|
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
|
||||||
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
|
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
|
||||||
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
|
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
|
||||||
|
import { vehicleMrankDelta } from '../profile/profile-hangar.ts';
|
||||||
import type { PlayerProfiles } from '../profile/player-profiles.ts';
|
import type { PlayerProfiles } from '../profile/player-profiles.ts';
|
||||||
import { battleLaunchNotify, type BattleLaunchNotify } from './battle-launch-notify.ts';
|
import { battleLaunchNotify, type BattleLaunchNotify } from './battle-launch-notify.ts';
|
||||||
import type { MatchingRequestHandler } from './matching-requests.ts';
|
import type { MatchingRequestHandler } from './matching-requests.ts';
|
||||||
@@ -23,6 +25,7 @@ export interface BattleQueueDependencies {
|
|||||||
readonly sessions: BattleSessionStore;
|
readonly sessions: BattleSessionStore;
|
||||||
readonly economy: BattleEconomy;
|
readonly economy: BattleEconomy;
|
||||||
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
|
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
|
||||||
|
readonly onBeforeMatchmake?: (ctx: BattleMatchmakeContext) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> {
|
export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> {
|
||||||
@@ -84,12 +87,18 @@ function handleEnqueue(
|
|||||||
const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country);
|
const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country);
|
||||||
const idInCountry = playerEntry.selectedSlot;
|
const idInCountry = playerEntry.selectedSlot;
|
||||||
const selectedSlotVehicle = idInCountry === undefined ? undefined : crewSlotVehicleOfCountry(profile, playerEntry.country, idInCountry);
|
const selectedSlotVehicle = idInCountry === undefined ? undefined : crewSlotVehicleOfCountry(profile, playerEntry.country, idInCountry);
|
||||||
|
deps.onBeforeMatchmake?.({
|
||||||
|
userId,
|
||||||
|
eventName: modes[0]!.declaration.name,
|
||||||
|
request: params as Record<string, unknown>,
|
||||||
|
});
|
||||||
const outcome = deps.matchmaker.enqueue({
|
const outcome = deps.matchmaker.enqueue({
|
||||||
userId,
|
userId,
|
||||||
mode: modes[0]!,
|
mode: modes[0]!,
|
||||||
modes,
|
modes,
|
||||||
country: playerEntry.country,
|
country: playerEntry.country,
|
||||||
slotVehicles,
|
slotVehicles,
|
||||||
|
mrankDeltas: new Map(slotVehicles.map((vehicle) => [vehicle, vehicleMrankDelta(profile, vehicle)])),
|
||||||
...(idInCountry !== undefined && selectedSlotVehicle ? { selectedSlot: { idInCountry, unitName: selectedSlotVehicle } } : {}),
|
...(idInCountry !== undefined && selectedSlotVehicle ? { selectedSlot: { idInCountry, unitName: selectedSlotVehicle } } : {}),
|
||||||
bannedMissions: playerEntry.bannedMissions,
|
bannedMissions: playerEntry.bannedMissions,
|
||||||
dislikedMissions: playerEntry.dislikedMissions,
|
dislikedMissions: playerEntry.dislikedMissions,
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import { moduleResearchTarget, setModuleResearchTarget } from '../profile/profil
|
|||||||
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
|
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
|
||||||
import { isCounted, isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts';
|
import { isCounted, isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts';
|
||||||
import { currentModuleStatus } from './module-state.ts';
|
import { currentModuleStatus } from './module-state.ts';
|
||||||
import { ModuleStatus } from './module-status.ts';
|
import { ModuleStatus, vehicleModuleState } from './module-status.ts';
|
||||||
|
|
||||||
export interface ModificationOrder {
|
export interface ModificationOrder {
|
||||||
readonly vehicle: string;
|
readonly vehicle: string;
|
||||||
@@ -48,8 +48,9 @@ export function buyModification(profile: BlkBlock, catalogue: EquipmentCatalogue
|
|||||||
export function buyAllModifications(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, outright: boolean, offered: Price): RuleOutcome {
|
export function buyAllModifications(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, outright: boolean, offered: Price): RuleOutcome {
|
||||||
const equipment = catalogue.vehicle(vehicle);
|
const equipment = catalogue.vehicle(vehicle);
|
||||||
if (!equipment || !ownsVehicle(profile, vehicle)) return refused('BAD_PARAMS');
|
if (!equipment || !ownsVehicle(profile, vehicle)) return refused('BAD_PARAMS');
|
||||||
|
const { statuses } = vehicleModuleState(profile, equipment);
|
||||||
const purchases = equipment.modifications.flatMap((modification) => {
|
const purchases = equipment.modifications.flatMap((modification) => {
|
||||||
const purchase = buyAllEntry(profile, vehicle, modification, catalogue, outright);
|
const purchase = buyAllEntry(profile, vehicle, modification, statuses.get(modification.name), outright);
|
||||||
return purchase ? [{ modification, purchase }] : [];
|
return purchase ? [{ modification, purchase }] : [];
|
||||||
});
|
});
|
||||||
const price = purchases.reduce<Price>((sum, { purchase }) => ({
|
const price = purchases.reduce<Price>((sum, { purchase }) => ({
|
||||||
@@ -114,17 +115,24 @@ function outrightPurchase(profile: BlkBlock, vehicle: string, modification: Modi
|
|||||||
/**
|
/**
|
||||||
* One entry of "buy all", as the client sums it (scripts weaponry/itemInfo.nut getAllModsCost):
|
* One entry of "buy all", as the client sums it (scripts weaponry/itemInfo.nut getAllModsCost):
|
||||||
* skip what is at its maximum; with forceOpen every modification starts at its outright price
|
* skip what is at its maximum; with forceOpen every modification starts at its outright price
|
||||||
* (whatever its status); a buyable one (canBuyMod) with a non-zero price takes its own price
|
* (whatever its status); a buyable or researched one (canBuyMod || isModStatusResearched) with a
|
||||||
* instead, and is skipped altogether when counted or priced in golden eagles.
|
* non-zero price takes its own price instead, and is skipped altogether when counted or priced in
|
||||||
|
* golden eagles.
|
||||||
*/
|
*/
|
||||||
function buyAllEntry(profile: BlkBlock, vehicle: string, modification: ModificationFacts, catalogue: EquipmentCatalogue, outright: boolean): Purchase | undefined {
|
function buyAllEntry(
|
||||||
|
profile: BlkBlock,
|
||||||
|
vehicle: string,
|
||||||
|
modification: ModificationFacts,
|
||||||
|
status: ModuleStatus | undefined,
|
||||||
|
outright: boolean,
|
||||||
|
): Purchase | undefined {
|
||||||
const record = modificationRecord(profile, vehicle, modification.name);
|
const record = modificationRecord(profile, vehicle, modification.name);
|
||||||
const maxAmount = Math.max(1, modification.maxCount);
|
const maxAmount = Math.max(1, modification.maxCount);
|
||||||
if ((record?.count ?? 0) >= maxAmount) return undefined;
|
if ((record?.count ?? 0) >= maxAmount) return undefined;
|
||||||
let purchase: Purchase | undefined;
|
let purchase: Purchase | undefined;
|
||||||
const openPrice = outright && isResearchable(modification) ? outrightPrice(profile, vehicle, modification) : 0;
|
const openPrice = outright && isResearchable(modification) ? outrightPrice(profile, vehicle, modification) : 0;
|
||||||
if (openPrice > 0) purchase = { price: { silverLions: 0, goldenEagles: openPrice }, amount: 1 };
|
if (openPrice > 0) purchase = { price: { silverLions: 0, goldenEagles: openPrice }, amount: 1 };
|
||||||
const buyable = record !== undefined || currentModuleStatus(profile, catalogue, vehicle, modification.name) === ModuleStatus.CAN_BUY;
|
const buyable = record !== undefined || status === ModuleStatus.CAN_BUY || status === ModuleStatus.RESEARCHED;
|
||||||
if (buyable && (modification.silverLions > 0 || modification.goldenEagles > 0)) {
|
if (buyable && (modification.silverLions > 0 || modification.goldenEagles > 0)) {
|
||||||
if (isCounted(modification) || modification.goldenEagles > 0) return undefined;
|
if (isCounted(modification) || modification.goldenEagles > 0) return undefined;
|
||||||
purchase = { price: { silverLions: modification.silverLions, goldenEagles: 0 }, amount: 1 };
|
purchase = { price: { silverLions: modification.silverLions, goldenEagles: 0 }, amount: 1 };
|
||||||
|
|||||||
@@ -10,11 +10,12 @@ import { moduleResearchPoints } from '../profile/profile-module-research.ts';
|
|||||||
import { countsForTier, isResearchable } from './equipment-catalogue.ts';
|
import { countsForTier, isResearchable } from './equipment-catalogue.ts';
|
||||||
import type { ProfileEquipmentIndex } from './profile-equipment-index.ts';
|
import type { ProfileEquipmentIndex } from './profile-equipment-index.ts';
|
||||||
|
|
||||||
/** shopItemConsts ES_ITEM_STATUS_*; the same values as the vehicle statuses. */
|
/** shopItemConsts ES_ITEM_STATUS_* (aces.exe 2.61.0.58 0x17e2894..0x17e294b); same values as VehicleStatus. */
|
||||||
export const ModuleStatus = {
|
export const ModuleStatus = {
|
||||||
LOCKED: 1,
|
LOCKED: 1,
|
||||||
CAN_RESEARCH: 2,
|
CAN_RESEARCH: 2,
|
||||||
CAN_BUY: 8,
|
CAN_BUY: 8,
|
||||||
|
RESEARCHED: 0x40,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type ModuleStatus = (typeof ModuleStatus)[keyof typeof ModuleStatus];
|
export type ModuleStatus = (typeof ModuleStatus)[keyof typeof ModuleStatus];
|
||||||
@@ -32,10 +33,11 @@ export function vehicleModuleState(
|
|||||||
index?: ProfileEquipmentIndex,
|
index?: ProfileEquipmentIndex,
|
||||||
): VehicleModuleState {
|
): VehicleModuleState {
|
||||||
const openTier = openTierOf(profile, equipment, index);
|
const openTier = openTierOf(profile, equipment, index);
|
||||||
|
const byName = new Map(equipment.modifications.map((mod) => [mod.name, mod]));
|
||||||
const statuses = new Map<string, ModuleStatus>();
|
const statuses = new Map<string, ModuleStatus>();
|
||||||
for (const modification of equipment.modifications) {
|
for (const modification of equipment.modifications) {
|
||||||
if (isOwned(profile, equipment.vehicle, modification.name, index)) continue;
|
if (isOwned(profile, equipment.vehicle, modification.name, index)) continue;
|
||||||
statuses.set(modification.name, statusOf(profile, equipment.vehicle, modification, openTier, index));
|
statuses.set(modification.name, statusOf(profile, equipment.vehicle, modification, openTier, byName, index));
|
||||||
}
|
}
|
||||||
return { openTier, statuses };
|
return { openTier, statuses };
|
||||||
}
|
}
|
||||||
@@ -80,16 +82,38 @@ function openTierOf(profile: BlkBlock, equipment: VehicleEquipment, index?: Prof
|
|||||||
return tier;
|
return tier;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function arePrerequisitesResearched(
|
||||||
|
profile: BlkBlock,
|
||||||
|
vehicle: string,
|
||||||
|
requires: readonly string[],
|
||||||
|
byName: ReadonlyMap<string, ModificationFacts>,
|
||||||
|
index?: ProfileEquipmentIndex,
|
||||||
|
): boolean {
|
||||||
|
return requires.every((required) => {
|
||||||
|
if (isOwned(profile, vehicle, required, index)) return true;
|
||||||
|
const mod = byName.get(required);
|
||||||
|
return mod !== undefined && isResearchable(mod) && isModuleResearched(profile, vehicle, mod, index);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function statusOf(
|
function statusOf(
|
||||||
profile: BlkBlock,
|
profile: BlkBlock,
|
||||||
vehicle: string,
|
vehicle: string,
|
||||||
modification: ModificationFacts,
|
modification: ModificationFacts,
|
||||||
openTier: number,
|
openTier: number,
|
||||||
|
byName: ReadonlyMap<string, ModificationFacts>,
|
||||||
index?: ProfileEquipmentIndex,
|
index?: ProfileEquipmentIndex,
|
||||||
): ModuleStatus {
|
): ModuleStatus {
|
||||||
if (isResearchable(modification)) {
|
if (isResearchable(modification)) {
|
||||||
if (modification.tier > openTier) return ModuleStatus.LOCKED;
|
if (modification.tier > openTier) return ModuleStatus.LOCKED;
|
||||||
return isModuleResearched(profile, vehicle, modification, index) ? ModuleStatus.CAN_BUY : ModuleStatus.CAN_RESEARCH;
|
if (isModuleResearched(profile, vehicle, modification, index)) {
|
||||||
|
return arePrerequisitesOwned(profile, vehicle, modification.requires, index)
|
||||||
|
? ModuleStatus.CAN_BUY
|
||||||
|
: ModuleStatus.RESEARCHED;
|
||||||
|
}
|
||||||
|
return arePrerequisitesResearched(profile, vehicle, modification.requires, byName, index)
|
||||||
|
? ModuleStatus.CAN_RESEARCH
|
||||||
|
: ModuleStatus.LOCKED;
|
||||||
}
|
}
|
||||||
return arePrerequisitesOwned(profile, vehicle, modification.requires, index) ? ModuleStatus.CAN_BUY : ModuleStatus.LOCKED;
|
return arePrerequisitesOwned(profile, vehicle, modification.requires, index) ? ModuleStatus.CAN_BUY : ModuleStatus.LOCKED;
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,12 @@
|
|||||||
* carry 30,000+ flat sub-blocks; indexing once drops refresh cost from O(N^2) to O(N).
|
* carry 30,000+ flat sub-blocks; indexing once drops refresh cost from O(N^2) to O(N).
|
||||||
*/
|
*/
|
||||||
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
|
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
|
||||||
import { recordName, type ModificationRecord } from '../profile/profile-modifications.ts';
|
import {
|
||||||
|
allModificationBlocks,
|
||||||
|
MAX_MODIFICATION_BLOCK_ENTRIES,
|
||||||
|
recordName,
|
||||||
|
type ModificationRecord,
|
||||||
|
} from '../profile/profile-modifications.ts';
|
||||||
import type { WeaponRecord } from '../profile/profile-weapons.ts';
|
import type { WeaponRecord } from '../profile/profile-weapons.ts';
|
||||||
|
|
||||||
const HANGAR = 'hangar';
|
const HANGAR = 'hangar';
|
||||||
@@ -21,7 +26,7 @@ export class ProfileEquipmentIndex {
|
|||||||
readonly #weapons = new Map<string, BlkBlock>();
|
readonly #weapons = new Map<string, BlkBlock>();
|
||||||
readonly #modsResearch = new Map<string, BlkBlock>();
|
readonly #modsResearch = new Map<string, BlkBlock>();
|
||||||
readonly #removedResearch = new Set<string>();
|
readonly #removedResearch = new Set<string>();
|
||||||
#modificationsBlock: BlkBlock | undefined;
|
readonly #modificationsBlocks: BlkBlock[];
|
||||||
#weaponsBlock: BlkBlock | undefined;
|
#weaponsBlock: BlkBlock | undefined;
|
||||||
#modsResearchBlock: BlkBlock | undefined;
|
#modsResearchBlock: BlkBlock | undefined;
|
||||||
|
|
||||||
@@ -30,9 +35,9 @@ export class ProfileEquipmentIndex {
|
|||||||
const hangar = findBlock(profile, HANGAR);
|
const hangar = findBlock(profile, HANGAR);
|
||||||
if (hangar) for (const entry of hangar.blocks) this.#hangar.set(entry.name, entry);
|
if (hangar) for (const entry of hangar.blocks) this.#hangar.set(entry.name, entry);
|
||||||
|
|
||||||
this.#modificationsBlock = findBlock(profile, MODIFICATIONS);
|
this.#modificationsBlocks = allModificationBlocks(profile);
|
||||||
if (this.#modificationsBlock) {
|
for (const chunk of this.#modificationsBlocks) {
|
||||||
for (const entry of this.#modificationsBlock.blocks) this.#modifications.set(entry.name, entry);
|
for (const entry of chunk.blocks) this.#modifications.set(entry.name, entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.#weaponsBlock = findBlock(profile, WEAPONS);
|
this.#weaponsBlock = findBlock(profile, WEAPONS);
|
||||||
@@ -103,14 +108,32 @@ export class ProfileEquipmentIndex {
|
|||||||
const key = recordName(vehicle, modification);
|
const key = recordName(vehicle, modification);
|
||||||
let block = this.#modifications.get(key);
|
let block = this.#modifications.get(key);
|
||||||
if (!block) {
|
if (!block) {
|
||||||
this.#modificationsBlock ??= ensureBlock(this.#profile, MODIFICATIONS);
|
|
||||||
block = { name: key, params: [], blocks: [] };
|
block = { name: key, params: [], blocks: [] };
|
||||||
this.#modificationsBlock.blocks.push(block);
|
this.#appendModificationBlock(block);
|
||||||
this.#modifications.set(key, block);
|
this.#modifications.set(key, block);
|
||||||
}
|
}
|
||||||
block.params = orderedModParams(record);
|
block.params = orderedModParams(record);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#appendModificationBlock(entry: BlkBlock): void {
|
||||||
|
for (let index = this.#modificationsBlocks.length - 1; index >= 0; index--) {
|
||||||
|
const chunk = this.#modificationsBlocks[index]!;
|
||||||
|
if (chunk.blocks.length < MAX_MODIFICATION_BLOCK_ENTRIES) {
|
||||||
|
chunk.blocks.push(entry);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const nextChunk: BlkBlock = { name: MODIFICATIONS, params: [], blocks: [entry] };
|
||||||
|
const lastChunk = this.#modificationsBlocks[this.#modificationsBlocks.length - 1];
|
||||||
|
if (lastChunk) {
|
||||||
|
const insertAt = this.#profile.blocks.lastIndexOf(lastChunk) + 1;
|
||||||
|
this.#profile.blocks.splice(insertAt, 0, nextChunk);
|
||||||
|
} else {
|
||||||
|
this.#profile.blocks.push(nextChunk);
|
||||||
|
}
|
||||||
|
this.#modificationsBlocks.push(nextChunk);
|
||||||
|
}
|
||||||
|
|
||||||
weaponRecord(vehicle: string, weapon: string): WeaponRecord | undefined {
|
weaponRecord(vehicle: string, weapon: string): WeaponRecord | undefined {
|
||||||
const block = this.#weapons.get(`${vehicle}_${weapon}`);
|
const block = this.#weapons.get(`${vehicle}_${weapon}`);
|
||||||
if (!block) return undefined;
|
if (!block) return undefined;
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
*/
|
*/
|
||||||
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
|
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
|
||||||
import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts';
|
import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts';
|
||||||
import { recordName } from '../profile/profile-modifications.ts';
|
import { allModificationBlocks, appendModificationEntry, recordName } from '../profile/profile-modifications.ts';
|
||||||
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
|
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
|
||||||
|
|
||||||
export interface SupportPlaneModification {
|
export interface SupportPlaneModification {
|
||||||
@@ -31,7 +31,10 @@ export interface SupportUnitEquipmentGrants {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function supportPlaneModifications(
|
export function supportPlaneModifications(
|
||||||
rules: Pick<BattleSpawnRulesData, 'supportPlanes' | 'strikeUcavs'>,
|
rules: Pick<
|
||||||
|
BattleSpawnRulesData,
|
||||||
|
'supportPlanes' | 'strikeUcavs' | 'nuclearEscalationTacticalCarriers' | 'nuclearEscalationStrategicBombers'
|
||||||
|
>,
|
||||||
catalogue: EquipmentCatalogue,
|
catalogue: EquipmentCatalogue,
|
||||||
): SupportUnitEquipmentGrants {
|
): SupportUnitEquipmentGrants {
|
||||||
const seenMods = new Set<string>();
|
const seenMods = new Set<string>();
|
||||||
@@ -53,21 +56,34 @@ export function supportPlaneModifications(
|
|||||||
weapons.push({ vehicle, weapon, count: Math.max(1, count) });
|
weapons.push({ vehicle, weapon, count: Math.max(1, count) });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const grantWeaponPreset = (unitName: string, weapon: string): void => {
|
||||||
|
const facts = catalogue.weapon(unitName, weapon);
|
||||||
|
addWeapon(unitName, weapon, facts?.maxCount ?? 1);
|
||||||
|
for (const modification of facts?.requires ?? []) addMod(unitName, modification);
|
||||||
|
for (const container of facts?.sumWeapons ?? []) {
|
||||||
|
const containerFacts = catalogue.weapon(unitName, container);
|
||||||
|
addWeapon(unitName, container, containerFacts?.maxCount ?? 1);
|
||||||
|
for (const modification of containerFacts?.requires ?? []) addMod(unitName, modification);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
for (const presets of Object.values(rules.supportPlanes)) {
|
for (const presets of Object.values(rules.supportPlanes)) {
|
||||||
for (const preset of presets) {
|
for (const preset of presets) {
|
||||||
for (const { unitName, weapon } of Object.values(preset.units)) {
|
for (const { unitName, weapon } of Object.values(preset.units)) {
|
||||||
const facts = catalogue.weapon(unitName, weapon);
|
grantWeaponPreset(unitName, weapon);
|
||||||
addWeapon(unitName, weapon, facts?.maxCount ?? 1);
|
|
||||||
for (const modification of facts?.requires ?? []) addMod(unitName, modification);
|
|
||||||
for (const container of facts?.sumWeapons ?? []) {
|
|
||||||
const containerFacts = catalogue.weapon(unitName, container);
|
|
||||||
addWeapon(unitName, container, containerFacts?.maxCount ?? 1);
|
|
||||||
for (const modification of containerFacts?.requires ?? []) addMod(unitName, modification);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const carrier of [
|
||||||
|
...rules.nuclearEscalationTacticalCarriers,
|
||||||
|
...rules.nuclearEscalationStrategicBombers,
|
||||||
|
]) {
|
||||||
|
for (const weapon of carrier.weapons) {
|
||||||
|
grantWeaponPreset(carrier.unitName, weapon.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for (const ucav of rules.strikeUcavs) {
|
for (const ucav of rules.strikeUcavs) {
|
||||||
const vehicle = catalogue.vehicle(ucav.unitName);
|
const vehicle = catalogue.vehicle(ucav.unitName);
|
||||||
if (!vehicle) continue;
|
if (!vehicle) continue;
|
||||||
@@ -82,13 +98,14 @@ export function supportPlaneModifications(
|
|||||||
|
|
||||||
export function grantSupportPlaneModifications(profile: BlkBlock, grants: SupportUnitEquipmentGrants): void {
|
export function grantSupportPlaneModifications(profile: BlkBlock, grants: SupportUnitEquipmentGrants): void {
|
||||||
if (grants.modifications.length > 0) {
|
if (grants.modifications.length > 0) {
|
||||||
let modsBlock = findBlock(profile, 'modifications');
|
const existing = new Set<string>();
|
||||||
const existing = new Set((modsBlock?.blocks ?? []).map((entry) => entry.name));
|
for (const chunk of allModificationBlocks(profile)) {
|
||||||
|
for (const entry of chunk.blocks) existing.add(entry.name);
|
||||||
|
}
|
||||||
for (const { vehicle, modification } of grants.modifications) {
|
for (const { vehicle, modification } of grants.modifications) {
|
||||||
const key = recordName(vehicle, modification);
|
const key = recordName(vehicle, modification);
|
||||||
if (existing.has(key)) continue;
|
if (existing.has(key)) continue;
|
||||||
modsBlock ??= ensureBlock(profile, 'modifications');
|
appendModificationEntry(profile, { name: key, params: [{ name: 'count', value: { type: 'int64', value: 1n } }], blocks: [] });
|
||||||
modsBlock.blocks.push({ name: key, params: [{ name: 'count', value: { type: 'int64', value: 1n } }], blocks: [] });
|
|
||||||
existing.add(key);
|
existing.add(key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import type { BlkBlock } from '@wto/blk';
|
||||||
|
import { ownsVehicle, setVehicleMrankDelta } from '../profile/profile-hangar.ts';
|
||||||
|
import { modificationRecord } from '../profile/profile-modifications.ts';
|
||||||
|
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
|
||||||
|
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
|
||||||
|
|
||||||
|
export function selectVehicleMrankDelta(
|
||||||
|
profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, delta: number,
|
||||||
|
): RuleOutcome {
|
||||||
|
const equipment = catalogue.vehicle(vehicle);
|
||||||
|
if (!equipment || !ownsVehicle(profile, vehicle) || !Number.isInteger(delta) || delta < 0) return refused('BAD_PARAMS');
|
||||||
|
|
||||||
|
// Stock getSelectableAddMranks offers zero and each positive addMrank on an owned modification.
|
||||||
|
if (delta > 0 && !equipment.modifications.some((modification) =>
|
||||||
|
modification.addMrank === delta && (modificationRecord(profile, vehicle, modification.name)?.count ?? 0) > 0)) {
|
||||||
|
return refused('NOT_AVAILABLE');
|
||||||
|
}
|
||||||
|
|
||||||
|
setVehicleMrankDelta(profile, vehicle, delta);
|
||||||
|
return ACCEPTED;
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
/**
|
||||||
|
* HTTP router service that exposes mod-registered routes under `/mods/<modId>/...`
|
||||||
|
* so mods can provide custom APIs or embedded-browser pages without touching core routes.
|
||||||
|
*/
|
||||||
|
import type { ModHttpHandler, ModHttpRequest } from '@wto/mods';
|
||||||
|
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
|
||||||
|
|
||||||
|
export interface RegisteredModHttpRoute {
|
||||||
|
readonly modId: string;
|
||||||
|
/** Full normalized path prefix or exact path under `/mods/<modId>/...`. */
|
||||||
|
readonly pattern: string;
|
||||||
|
readonly isWildcard: boolean;
|
||||||
|
readonly prefix: string;
|
||||||
|
readonly handler: ModHttpHandler;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ModHttpService implements Service {
|
||||||
|
readonly name = 'mods-http';
|
||||||
|
readonly #routes: readonly RegisteredModHttpRoute[];
|
||||||
|
|
||||||
|
constructor(routes: readonly RegisteredModHttpRoute[]) {
|
||||||
|
this.#routes = routes;
|
||||||
|
}
|
||||||
|
|
||||||
|
accepts(request: ServiceRequest): boolean {
|
||||||
|
if (request.originalHost !== undefined) return false;
|
||||||
|
return this.#match(request.path) !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
async handle(request: ServiceRequest): Promise<ServiceResponse> {
|
||||||
|
const matched = this.#match(request.path);
|
||||||
|
if (!matched) {
|
||||||
|
return { status: 404, body: 'mod route not found' };
|
||||||
|
}
|
||||||
|
const headers: Record<string, string | undefined> = {};
|
||||||
|
for (const [key, value] of Object.entries(request.headers)) {
|
||||||
|
headers[key] = Array.isArray(value) ? value[0] : value;
|
||||||
|
}
|
||||||
|
const query: Record<string, string> = {};
|
||||||
|
for (const [key, value] of request.query.entries()) query[key] = value;
|
||||||
|
|
||||||
|
const modReq: ModHttpRequest = {
|
||||||
|
method: request.method,
|
||||||
|
path: request.path,
|
||||||
|
query,
|
||||||
|
headers,
|
||||||
|
body: request.body,
|
||||||
|
};
|
||||||
|
const answer = await matched.handler(modReq);
|
||||||
|
const responseHeaders: Record<string, string> = { ...(answer.headers ?? {}) };
|
||||||
|
if (answer.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) {
|
||||||
|
responseHeaders['content-type'] = answer.contentType;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
status: answer.status ?? 200,
|
||||||
|
headers: responseHeaders,
|
||||||
|
body: answer.body,
|
||||||
|
logNotes: { summary: `mod:${matched.modId} ${request.method} ${request.path}` },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#match(path: string): RegisteredModHttpRoute | undefined {
|
||||||
|
for (const route of this.#routes) {
|
||||||
|
if (route.isWildcard) {
|
||||||
|
if (path.startsWith(route.prefix)) return route;
|
||||||
|
} else if (path === route.pattern) {
|
||||||
|
return route;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildModHttpRoute(modId: string, subPath: string, handler: ModHttpHandler): RegisteredModHttpRoute {
|
||||||
|
const cleaned = subPath.startsWith('/') ? subPath : `/${subPath}`;
|
||||||
|
const full = `/mods/${modId}${cleaned === '/' ? '' : cleaned}`;
|
||||||
|
if (full.endsWith('/*')) {
|
||||||
|
const prefix = full.slice(0, -1); // keeps trailing '/'
|
||||||
|
return { modId, pattern: full, isWildcard: true, prefix, handler };
|
||||||
|
}
|
||||||
|
return { modId, pattern: full, isWildcard: false, prefix: full, handler };
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
/**
|
||||||
|
* Isolated JSON storage for server mods:
|
||||||
|
* - per-player files under `<dataFolder>/saves/<userId>/mods/<safeModId>.json`
|
||||||
|
* - shared mod state under `<dataFolder>/mods-data/<safeModId>.json`
|
||||||
|
*
|
||||||
|
* Keeping mod state outside `profile.blk` guarantees uninstalling a mod never corrupts stock saves.
|
||||||
|
*/
|
||||||
|
import { existsSync, readFileSync, rmSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import type { ModPlayerStorage, ModStorageApi } from '@wto/mods';
|
||||||
|
import { writeFileAtomic } from '../storage/atomic-file.ts';
|
||||||
|
|
||||||
|
export function createModStorage(dataFolder: string, modId: string): ModStorageApi {
|
||||||
|
const safeMod = sanitizeSegment(modId);
|
||||||
|
return {
|
||||||
|
forPlayer(userId: string): ModPlayerStorage {
|
||||||
|
const safeUser = sanitizeSegment(userId);
|
||||||
|
const filePath = join(dataFolder, 'saves', safeUser, 'mods', `${safeMod}.json`);
|
||||||
|
return createJsonFileStorage(filePath);
|
||||||
|
},
|
||||||
|
shared(): ModPlayerStorage {
|
||||||
|
const filePath = join(dataFolder, 'mods-data', `${safeMod}.json`);
|
||||||
|
return createJsonFileStorage(filePath);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createJsonFileStorage(filePath: string): ModPlayerStorage {
|
||||||
|
return {
|
||||||
|
read<T = unknown>(): T | undefined {
|
||||||
|
if (!existsSync(filePath)) return undefined;
|
||||||
|
try {
|
||||||
|
return JSON.parse(readFileSync(filePath, 'utf8')) as T;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
write(value: unknown): void {
|
||||||
|
writeFileAtomic(filePath, JSON.stringify(value, null, 2));
|
||||||
|
},
|
||||||
|
remove(): void {
|
||||||
|
try {
|
||||||
|
rmSync(filePath, { force: true });
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeSegment(raw: string): string {
|
||||||
|
const cleaned = raw.replace(/[^A-Za-z0-9._-]/g, '_');
|
||||||
|
if (!cleaned || cleaned === '.' || cleaned === '..') {
|
||||||
|
throw new Error(`invalid storage path segment "${raw}"`);
|
||||||
|
}
|
||||||
|
return cleaned;
|
||||||
|
}
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
/**
|
||||||
|
* Experimental server-side JS/TS mod runtime.
|
||||||
|
*
|
||||||
|
* Loads each enabled mod's server script entry (`.ts`, `.mjs`, or `.js` via Node 24's built-in
|
||||||
|
* TypeScript stripping and ESM dynamic import), injects an isolated `WtoServerModContext`, and
|
||||||
|
* coordinates lifecycle hooks, profile/battle hooks, char/matching wrappers, and `/mods/<id>/*`
|
||||||
|
* HTTP routes.
|
||||||
|
*/
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { pathToFileURL } from 'node:url';
|
||||||
|
import type { BlkBlock } from '@wto/blk';
|
||||||
|
import {
|
||||||
|
MOD_API_VERSION,
|
||||||
|
type BattleFilterMissionsContext,
|
||||||
|
type BattleLiveFactContext,
|
||||||
|
type BattleMatchmakeContext,
|
||||||
|
type BattleMissionCandidate,
|
||||||
|
type BattleSettlementContext,
|
||||||
|
type DiscoveredMod,
|
||||||
|
type ModCharHandler,
|
||||||
|
type ModCharRequest,
|
||||||
|
type ModCharResponse,
|
||||||
|
type ModCharWrapper,
|
||||||
|
type ModHttpHandler,
|
||||||
|
type ModMatchingHandler,
|
||||||
|
type ModMatchingRequest,
|
||||||
|
type ModMatchingWrapper,
|
||||||
|
type ServerModCataloguesView,
|
||||||
|
type ServerModDatasetsView,
|
||||||
|
type WtoServerMod,
|
||||||
|
type WtoServerModContext,
|
||||||
|
} from '@wto/mods';
|
||||||
|
import type { MatchingRequestHandler, MatchingRequestTable } from '../matching/matching-requests.ts';
|
||||||
|
import { buildModHttpRoute, ModHttpService, type RegisteredModHttpRoute } from './mod-http-service.ts';
|
||||||
|
import { createModStorage } from './mod-storage.ts';
|
||||||
|
|
||||||
|
interface RuntimeInitOptions {
|
||||||
|
readonly mods: readonly DiscoveredMod[];
|
||||||
|
readonly gameFolder: string;
|
||||||
|
readonly dataFolder: string;
|
||||||
|
readonly port: number;
|
||||||
|
readonly report: (line: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ScopedHandler<T> {
|
||||||
|
readonly modId: string;
|
||||||
|
readonly fn: T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ServerModRuntime {
|
||||||
|
readonly #report: (line: string) => void;
|
||||||
|
readonly #loadedModIds: string[] = [];
|
||||||
|
readonly #onDatasetsLoaded: ScopedHandler<(datasets: ServerModDatasetsView) => void | Promise<void>>[] = [];
|
||||||
|
readonly #onCataloguesReady: ScopedHandler<(catalogues: ServerModCataloguesView) => void | Promise<void>>[] = [];
|
||||||
|
readonly #onServerListening: ScopedHandler<(info: { readonly port: number }) => void | Promise<void>>[] = [];
|
||||||
|
readonly #onServerClosing: ScopedHandler<() => void | Promise<void>>[] = [];
|
||||||
|
readonly #onProfileRefresh: ScopedHandler<(profile: BlkBlock, userId: string) => void>[] = [];
|
||||||
|
readonly #onBeforeMatchmake: ScopedHandler<(ctx: BattleMatchmakeContext) => void>[] = [];
|
||||||
|
readonly #onFilterMissions: ScopedHandler<(ctx: BattleFilterMissionsContext) => readonly BattleMissionCandidate[] | void>[] = [];
|
||||||
|
readonly #onLiveFact: ScopedHandler<(ctx: BattleLiveFactContext) => void>[] = [];
|
||||||
|
readonly #onAfterSettle: ScopedHandler<(ctx: BattleSettlementContext) => void>[] = [];
|
||||||
|
readonly #charHandlers = new Map<string, ScopedHandler<ModCharHandler>>();
|
||||||
|
readonly #charWrappers = new Map<string, ScopedHandler<ModCharWrapper>[]>();
|
||||||
|
readonly #matchingHandlers = new Map<string, ScopedHandler<ModMatchingHandler>>();
|
||||||
|
readonly #matchingWrappers = new Map<string, ScopedHandler<ModMatchingWrapper>[]>();
|
||||||
|
readonly #httpRoutes: RegisteredModHttpRoute[] = [];
|
||||||
|
|
||||||
|
private constructor(report: (line: string) => void) {
|
||||||
|
this.#report = report;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async load(options: RuntimeInitOptions): Promise<ServerModRuntime> {
|
||||||
|
const runtime = new ServerModRuntime(options.report);
|
||||||
|
const scriptMods = options.mods.filter((mod) => mod.content.serverEntry !== undefined);
|
||||||
|
if (scriptMods.length === 0) return runtime;
|
||||||
|
|
||||||
|
const cacheBust = Date.now();
|
||||||
|
for (const mod of scriptMods) {
|
||||||
|
const entryRel = mod.content.serverEntry!;
|
||||||
|
const entryAbs = join(mod.rootDir, ...entryRel.split('/'));
|
||||||
|
const modId = mod.manifest.id;
|
||||||
|
const url = `${pathToFileURL(entryAbs).href}?wto_mod=${cacheBust}`;
|
||||||
|
|
||||||
|
let loadedModule: Record<string, unknown>;
|
||||||
|
try {
|
||||||
|
loadedModule = (await import(url)) as Record<string, unknown>;
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(
|
||||||
|
`Failed to load server mod "${modId}" (${entryRel}): ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const modExport = resolveModExport(loadedModule);
|
||||||
|
if (!modExport) {
|
||||||
|
throw new Error(
|
||||||
|
`Server mod "${modId}" (${entryRel}) must export default { setup(ctx) { ... } } or named setup(ctx)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ctx = runtime.#createContext(mod, options);
|
||||||
|
try {
|
||||||
|
await modExport.setup(ctx);
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(
|
||||||
|
`Server mod "${modId}" setup() failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
runtime.#loadedModIds.push(modId);
|
||||||
|
options.report(`mod ${modId}: server script loaded (${entryRel})`);
|
||||||
|
}
|
||||||
|
return runtime;
|
||||||
|
}
|
||||||
|
|
||||||
|
get loadedModIds(): readonly string[] {
|
||||||
|
return this.#loadedModIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
async runDatasetsLoaded(view: ServerModDatasetsView): Promise<void> {
|
||||||
|
for (const { modId, fn } of this.#onDatasetsLoaded) {
|
||||||
|
try {
|
||||||
|
await fn(view);
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Server mod "${modId}" onDatasetsLoaded failed: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async runCataloguesReady(view: ServerModCataloguesView): Promise<void> {
|
||||||
|
for (const { modId, fn } of this.#onCataloguesReady) {
|
||||||
|
try {
|
||||||
|
await fn(view);
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Server mod "${modId}" onCataloguesReady failed: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async runServerListening(port: number): Promise<void> {
|
||||||
|
for (const { modId, fn } of this.#onServerListening) {
|
||||||
|
try {
|
||||||
|
await fn({ port });
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] onServerListening error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async runServerClosing(): Promise<void> {
|
||||||
|
for (const { modId, fn } of [...this.#onServerClosing].reverse()) {
|
||||||
|
try {
|
||||||
|
await fn();
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] onServerClosing error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runProfileRefresh(profile: BlkBlock, userId: string): void {
|
||||||
|
for (const { modId, fn } of this.#onProfileRefresh) {
|
||||||
|
try {
|
||||||
|
fn(profile, userId);
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] profile.onRefresh error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runBattleBeforeMatchmake(ctx: BattleMatchmakeContext): void {
|
||||||
|
for (const { modId, fn } of this.#onBeforeMatchmake) {
|
||||||
|
try {
|
||||||
|
fn(ctx);
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] battle.onBeforeMatchmake error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runBattleFilterMissions<T extends BattleMissionCandidate>(
|
||||||
|
ctx: Omit<BattleFilterMissionsContext, 'missions'> & { readonly missions: readonly T[] },
|
||||||
|
): readonly T[] {
|
||||||
|
if (this.#onFilterMissions.length === 0) return ctx.missions;
|
||||||
|
let current: readonly T[] = ctx.missions;
|
||||||
|
for (const { modId, fn } of this.#onFilterMissions) {
|
||||||
|
try {
|
||||||
|
const next = fn({ ...ctx, missions: current });
|
||||||
|
if (Array.isArray(next)) {
|
||||||
|
const allowed = new Set(next.map((item) => item.name));
|
||||||
|
const filtered = current.filter((item) => allowed.has(item.name));
|
||||||
|
if (filtered.length > 0) {
|
||||||
|
current = filtered;
|
||||||
|
} else {
|
||||||
|
this.#report(`[mod:${modId}] battle.onFilterMissions returned 0 matching candidates for ${ctx.modeName}; keeping previous pool`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] battle.onFilterMissions error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
runBattleLiveFact(ctx: BattleLiveFactContext): void {
|
||||||
|
for (const { modId, fn } of this.#onLiveFact) {
|
||||||
|
try {
|
||||||
|
fn(ctx);
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] battle.onLiveFact error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runBattleAfterSettle(ctx: BattleSettlementContext): void {
|
||||||
|
for (const { modId, fn } of this.#onAfterSettle) {
|
||||||
|
try {
|
||||||
|
fn(ctx);
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] battle.onAfterSettle error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hasCharOverride(action: string): boolean {
|
||||||
|
return this.#charHandlers.has(action) || this.#charWrappers.has(action);
|
||||||
|
}
|
||||||
|
|
||||||
|
async dispatchCharOverride(
|
||||||
|
action: string,
|
||||||
|
request: ModCharRequest,
|
||||||
|
baseDispatch: (req: ModCharRequest) => Promise<ModCharResponse>,
|
||||||
|
): Promise<ModCharResponse> {
|
||||||
|
const custom = this.#charHandlers.get(action);
|
||||||
|
const terminal: (req: ModCharRequest) => Promise<ModCharResponse> = custom
|
||||||
|
? async (req) => await custom.fn(req)
|
||||||
|
: baseDispatch;
|
||||||
|
|
||||||
|
const wrappers = this.#charWrappers.get(action);
|
||||||
|
if (!wrappers || wrappers.length === 0) return terminal(request);
|
||||||
|
|
||||||
|
let chain = terminal;
|
||||||
|
for (let i = wrappers.length - 1; i >= 0; i -= 1) {
|
||||||
|
const wrapper = wrappers[i]!.fn;
|
||||||
|
const next = chain;
|
||||||
|
chain = async (req) => await wrapper(req, next);
|
||||||
|
}
|
||||||
|
return chain(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
applyMatchingRoutes(baseTable: MatchingRequestTable): MatchingRequestTable {
|
||||||
|
if (this.#matchingHandlers.size === 0 && this.#matchingWrappers.size === 0) {
|
||||||
|
return baseTable;
|
||||||
|
}
|
||||||
|
const merged = new Map<string, MatchingRequestHandler>(baseTable);
|
||||||
|
|
||||||
|
for (const [method, custom] of this.#matchingHandlers) {
|
||||||
|
merged.set(method, (request, session) => custom.fn({
|
||||||
|
method,
|
||||||
|
params: request.params,
|
||||||
|
userId: session.authenticatedUserId(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [method, wrappers] of this.#matchingWrappers) {
|
||||||
|
const original = merged.get(method);
|
||||||
|
merged.set(method, (request, session) => {
|
||||||
|
const baseFn = (req: ModMatchingRequest): Record<string, unknown> => (
|
||||||
|
original ? original({ ...request, params: req.params }, session) : {}
|
||||||
|
);
|
||||||
|
let chain = baseFn;
|
||||||
|
for (let i = wrappers.length - 1; i >= 0; i -= 1) {
|
||||||
|
const wrap = wrappers[i]!.fn;
|
||||||
|
const next = chain;
|
||||||
|
chain = (req) => wrap(req, next);
|
||||||
|
}
|
||||||
|
return chain({
|
||||||
|
method,
|
||||||
|
params: request.params,
|
||||||
|
userId: session.authenticatedUserId(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
httpService(): ModHttpService {
|
||||||
|
return new ModHttpService(this.#httpRoutes);
|
||||||
|
}
|
||||||
|
|
||||||
|
#createContext(mod: DiscoveredMod, options: RuntimeInitOptions): WtoServerModContext {
|
||||||
|
const modId = mod.manifest.id;
|
||||||
|
return {
|
||||||
|
apiVersion: MOD_API_VERSION,
|
||||||
|
manifest: mod.manifest,
|
||||||
|
modDir: mod.rootDir,
|
||||||
|
gameFolder: options.gameFolder,
|
||||||
|
dataFolder: options.dataFolder,
|
||||||
|
port: options.port,
|
||||||
|
logger: {
|
||||||
|
info: (message) => options.report(`[mod:${modId}] ${message}`),
|
||||||
|
warn: (message) => options.report(`[mod:${modId}] WARN: ${message}`),
|
||||||
|
error: (message) => options.report(`[mod:${modId}] ERROR: ${message}`),
|
||||||
|
},
|
||||||
|
storage: createModStorage(options.dataFolder, modId),
|
||||||
|
hooks: {
|
||||||
|
onDatasetsLoaded: (fn) => { this.#onDatasetsLoaded.push({ modId, fn }); },
|
||||||
|
onCataloguesReady: (fn) => { this.#onCataloguesReady.push({ modId, fn }); },
|
||||||
|
onServerListening: (fn) => { this.#onServerListening.push({ modId, fn }); },
|
||||||
|
onServerClosing: (fn) => { this.#onServerClosing.push({ modId, fn }); },
|
||||||
|
profile: {
|
||||||
|
onRefresh: (fn) => { this.#onProfileRefresh.push({ modId, fn }); },
|
||||||
|
},
|
||||||
|
battle: {
|
||||||
|
onBeforeMatchmake: (fn) => { this.#onBeforeMatchmake.push({ modId, fn }); },
|
||||||
|
onFilterMissions: (fn) => { this.#onFilterMissions.push({ modId, fn }); },
|
||||||
|
onLiveFact: (fn) => { this.#onLiveFact.push({ modId, fn }); },
|
||||||
|
onAfterSettle: (fn) => { this.#onAfterSettle.push({ modId, fn }); },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
routes: {
|
||||||
|
char: {
|
||||||
|
register: (action, fn) => { this.#charHandlers.set(action, { modId, fn }); },
|
||||||
|
wrap: (action, fn) => {
|
||||||
|
const list = this.#charWrappers.get(action) ?? [];
|
||||||
|
list.push({ modId, fn });
|
||||||
|
this.#charWrappers.set(action, list);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
matching: {
|
||||||
|
register: (method, fn) => { this.#matchingHandlers.set(method, { modId, fn }); },
|
||||||
|
wrap: (method, fn) => {
|
||||||
|
const list = this.#matchingWrappers.get(method) ?? [];
|
||||||
|
list.push({ modId, fn });
|
||||||
|
this.#matchingWrappers.set(method, list);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
http: {
|
||||||
|
register: (subPath: string, handler: ModHttpHandler) => {
|
||||||
|
this.#httpRoutes.push(buildModHttpRoute(modId, subPath, handler));
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveModExport(mod: Record<string, unknown>): WtoServerMod | undefined {
|
||||||
|
const def = mod.default;
|
||||||
|
if (def && typeof def === 'object' && typeof (def as Record<string, unknown>).setup === 'function') {
|
||||||
|
return def as WtoServerMod;
|
||||||
|
}
|
||||||
|
if (typeof def === 'function') {
|
||||||
|
return { setup: def as WtoServerMod['setup'] };
|
||||||
|
}
|
||||||
|
if (typeof mod.setup === 'function') {
|
||||||
|
return { setup: mod.setup as WtoServerMod['setup'] };
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatError(error: unknown): string {
|
||||||
|
return error instanceof Error ? error.stack ?? error.message : String(error);
|
||||||
|
}
|
||||||
@@ -1,19 +1,24 @@
|
|||||||
/**
|
/**
|
||||||
* Owned vehicles in the profile, as in Gaijin's
|
* The profile's hangar has one sub-block per owned vehicle, as in config/default_user.blk.
|
||||||
* config/default_user.blk: one empty sub-block per vehicle the player owns.
|
|
||||||
*
|
*
|
||||||
* hangar{
|
* hangar{
|
||||||
* bf2c_1{
|
* bf2c_1{
|
||||||
* }
|
* }
|
||||||
* }
|
* }
|
||||||
*/
|
*/
|
||||||
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
|
import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
|
||||||
|
import { intField } from './blk-fields.ts';
|
||||||
|
|
||||||
const HANGAR = 'hangar';
|
const HANGAR = 'hangar';
|
||||||
|
const MRANK_DELTA = 'mrankDelta';
|
||||||
|
|
||||||
|
function ownedVehicle(profile: BlkBlock, vehicle: string): BlkBlock | undefined {
|
||||||
|
const hangar = findBlock(profile, HANGAR);
|
||||||
|
return hangar && findBlock(hangar, vehicle);
|
||||||
|
}
|
||||||
|
|
||||||
export function ownsVehicle(profile: BlkBlock, vehicle: string): boolean {
|
export function ownsVehicle(profile: BlkBlock, vehicle: string): boolean {
|
||||||
const hangar = findBlock(profile, HANGAR);
|
return ownedVehicle(profile, vehicle) !== undefined;
|
||||||
return hangar !== undefined && findBlock(hangar, vehicle) !== undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ownedVehicles(profile: BlkBlock): Set<string> {
|
export function ownedVehicles(profile: BlkBlock): Set<string> {
|
||||||
@@ -25,3 +30,13 @@ export function addOwnedVehicle(profile: BlkBlock, vehicle: string): void {
|
|||||||
const hangar = ensureBlock(profile, HANGAR);
|
const hangar = ensureBlock(profile, HANGAR);
|
||||||
if (!hangar.blocks.some((owned) => owned.name === vehicle)) hangar.blocks.push({ name: vehicle, params: [], blocks: [] });
|
if (!hangar.blocks.some((owned) => owned.name === vehicle)) hangar.blocks.push({ name: vehicle, params: [], blocks: [] });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The stock client uses the base rank until it has a non-negative selection. */
|
||||||
|
export function vehicleMrankDelta(profile: BlkBlock, vehicle: string): number {
|
||||||
|
return Math.max(0, intField(ownedVehicle(profile, vehicle), MRANK_DELTA));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setVehicleMrankDelta(profile: BlkBlock, vehicle: string, delta: number): void {
|
||||||
|
const entry = ownedVehicle(profile, vehicle);
|
||||||
|
if (entry) setParam(entry, MRANK_DELTA, { type: 'int', value: delta });
|
||||||
|
}
|
||||||
@@ -17,12 +17,20 @@
|
|||||||
* script function get_mission_progress (0x179c900 -> 0xebad60) looks up. It returns the
|
* script function get_mission_progress (0x179c900 -> 0xebad60) looks up. It returns the
|
||||||
* highest difficulty completed (0, 1, 2), or 3 or more when there is none.
|
* highest difficulty completed (0, 1, 2), or 3 or more when there is none.
|
||||||
*/
|
*/
|
||||||
import { ensureBlock, setParam, type BlkBlock } from '@wto/blk';
|
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
|
||||||
|
|
||||||
const PVE_PROGRESS = 'pveProgress';
|
const PVE_PROGRESS = 'pveProgress';
|
||||||
const MISSIONS = 'missions';
|
const MISSIONS = 'missions';
|
||||||
const DIFFICULTIES = [0, 1, 2] as const;
|
const DIFFICULTIES = [0, 1, 2] as const;
|
||||||
|
|
||||||
|
export function hasCompletedMissionDifficulty(profile: BlkBlock, fullMissionName: string, difficulty: 0 | 1 | 2): boolean {
|
||||||
|
const pve = findBlock(profile, PVE_PROGRESS);
|
||||||
|
const missions = pve && findBlock(pve, MISSIONS);
|
||||||
|
const mission = missions && findBlock(missions, fullMissionName);
|
||||||
|
const flag = mission && findParam(mission, `diff_${difficulty}`)?.value;
|
||||||
|
return flag?.type === 'bool' && flag.value;
|
||||||
|
}
|
||||||
|
|
||||||
/** Record the mission as completed on every difficulty up to and including `highest` (0, 1 or 2). */
|
/** Record the mission as completed on every difficulty up to and including `highest` (0, 1 or 2). */
|
||||||
export function recordMissionCompleted(profile: BlkBlock, fullMissionName: string, highest: 0 | 1 | 2): void {
|
export function recordMissionCompleted(profile: BlkBlock, fullMissionName: string, highest: 0 | 1 | 2): void {
|
||||||
const entry = ensureBlock(ensureBlock(ensureBlock(profile, PVE_PROGRESS), MISSIONS), fullMissionName);
|
const entry = ensureBlock(ensureBlock(ensureBlock(profile, PVE_PROGRESS), MISSIONS), fullMissionName);
|
||||||
|
|||||||
@@ -12,11 +12,19 @@
|
|||||||
* the first one that does not match (aces.exe 0x942740), so a record is always rewritten whole:
|
* the first one that does not match (aces.exe 0x942740), so a record is always rewritten whole:
|
||||||
* wpSpent:i goldSpent:i lastWpCost:i lastGoldCost:i persist:b rpEarned:i enabled:b count:i64 modLevel:i
|
* wpSpent:i goldSpent:i lastWpCost:i lastGoldCost:i persist:b rpEarned:i enabled:b count:i64 modLevel:i
|
||||||
* Absent values are left out; enabled is only written when false (the default is enabled).
|
* Absent values are left out; enabled is only written when false (the default is enabled).
|
||||||
|
*
|
||||||
|
* Dagor's binary DataBlock stores child block counts in a uint16 (65,535 max). Because the full
|
||||||
|
* vehicle catalogue exceeds 65,535 modifications, aces.exe splits modifications across up to 3
|
||||||
|
* sibling top-level `modifications` blocks of at most 65,535 entries each (2.61.0.37 0x938fae..0x9397e6,
|
||||||
|
* 2.61.0.58 0x93ba70 / 0x93bb53). All readers and writers here span every sibling block.
|
||||||
*/
|
*/
|
||||||
import { ensureBlock, findBlock, type BlkBlock, type BlkParam } from '@wto/blk';
|
import type { BlkBlock, BlkParam } from '@wto/blk';
|
||||||
|
|
||||||
const MODIFICATIONS = 'modifications';
|
const MODIFICATIONS = 'modifications';
|
||||||
|
|
||||||
|
/** Maximum entries per `modifications` DataBlock (uint16 child count limit in aces.exe 0x939000 / 0x93ba70). */
|
||||||
|
export const MAX_MODIFICATION_BLOCK_ENTRIES = 0xffff;
|
||||||
|
|
||||||
export interface ModificationRecord {
|
export interface ModificationRecord {
|
||||||
readonly silverLionsSpent: number;
|
readonly silverLionsSpent: number;
|
||||||
readonly goldenEaglesSpent: number;
|
readonly goldenEaglesSpent: number;
|
||||||
@@ -29,9 +37,66 @@ export function recordName(vehicle: string, modification: string): string {
|
|||||||
return `${vehicle}_${modification}`;
|
return `${vehicle}_${modification}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Every top-level `modifications` chunk in the profile, in document order. */
|
||||||
|
export function allModificationBlocks(profile: BlkBlock): BlkBlock[] {
|
||||||
|
return profile.blocks.filter((block) => block.name === MODIFICATIONS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Append a new modification entry to a chunk with spare capacity, opening a sibling chunk when full. */
|
||||||
|
export function appendModificationEntry(profile: BlkBlock, entry: BlkBlock): void {
|
||||||
|
const chunks = allModificationBlocks(profile);
|
||||||
|
for (let index = chunks.length - 1; index >= 0; index--) {
|
||||||
|
const chunk = chunks[index]!;
|
||||||
|
if (chunk.blocks.length < MAX_MODIFICATION_BLOCK_ENTRIES) {
|
||||||
|
chunk.blocks.push(entry);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const nextChunk: BlkBlock = { name: MODIFICATIONS, params: [], blocks: [entry] };
|
||||||
|
const lastChunk = chunks[chunks.length - 1];
|
||||||
|
if (lastChunk) {
|
||||||
|
const insertAt = profile.blocks.lastIndexOf(lastChunk) + 1;
|
||||||
|
profile.blocks.splice(insertAt, 0, nextChunk);
|
||||||
|
} else {
|
||||||
|
profile.blocks.push(nextChunk);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ensure every top-level `modifications` chunk stays within the 65,535-child DataBlock limit. */
|
||||||
|
export function normalizeModificationBlocks(profile: BlkBlock): void {
|
||||||
|
const chunks = allModificationBlocks(profile);
|
||||||
|
if (chunks.length === 0) return;
|
||||||
|
const needsRebalance = chunks.some((chunk) => chunk.blocks.length > MAX_MODIFICATION_BLOCK_ENTRIES)
|
||||||
|
|| (chunks.length > 1 && chunks.some((chunk) => chunk.blocks.length === 0));
|
||||||
|
if (!needsRebalance) return;
|
||||||
|
|
||||||
|
const firstIndex = profile.blocks.findIndex((block) => block.name === MODIFICATIONS);
|
||||||
|
const entries = chunks.flatMap((chunk) => chunk.blocks);
|
||||||
|
profile.blocks = profile.blocks.filter((block) => block.name !== MODIFICATIONS);
|
||||||
|
if (entries.length === 0) return;
|
||||||
|
|
||||||
|
const rebuilt: BlkBlock[] = [];
|
||||||
|
for (let offset = 0; offset < entries.length; offset += MAX_MODIFICATION_BLOCK_ENTRIES) {
|
||||||
|
rebuilt.push({
|
||||||
|
name: MODIFICATIONS,
|
||||||
|
params: [],
|
||||||
|
blocks: entries.slice(offset, offset + MAX_MODIFICATION_BLOCK_ENTRIES),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
profile.blocks.splice(Math.max(0, firstIndex), 0, ...rebuilt);
|
||||||
|
}
|
||||||
|
|
||||||
|
function findModificationEntry(profile: BlkBlock, key: string): BlkBlock | undefined {
|
||||||
|
for (const chunk of profile.blocks) {
|
||||||
|
if (chunk.name !== MODIFICATIONS) continue;
|
||||||
|
const found = chunk.blocks.find((entry) => entry.name === key);
|
||||||
|
if (found) return found;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
export function modificationRecord(profile: BlkBlock, vehicle: string, modification: string): ModificationRecord | undefined {
|
export function modificationRecord(profile: BlkBlock, vehicle: string, modification: string): ModificationRecord | undefined {
|
||||||
const block = findBlock(profile, MODIFICATIONS);
|
const record = findModificationEntry(profile, recordName(vehicle, modification));
|
||||||
const record = block && findBlock(block, recordName(vehicle, modification));
|
|
||||||
if (!record) return undefined;
|
if (!record) return undefined;
|
||||||
return {
|
return {
|
||||||
silverLionsSpent: intOf(record, 'wpSpent'),
|
silverLionsSpent: intOf(record, 'wpSpent'),
|
||||||
@@ -42,12 +107,17 @@ export function modificationRecord(profile: BlkBlock, vehicle: string, modificat
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function ownsModification(profile: BlkBlock, vehicle: string, modification: string): boolean {
|
export function ownsModification(profile: BlkBlock, vehicle: string, modification: string): boolean {
|
||||||
return modificationRecord(profile, vehicle, modification) !== undefined;
|
return findModificationEntry(profile, recordName(vehicle, modification)) !== undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function writeModificationRecord(profile: BlkBlock, vehicle: string, modification: string, record: ModificationRecord): void {
|
export function writeModificationRecord(profile: BlkBlock, vehicle: string, modification: string, record: ModificationRecord): void {
|
||||||
const block = ensureBlock(ensureBlock(profile, MODIFICATIONS), recordName(vehicle, modification));
|
const key = recordName(vehicle, modification);
|
||||||
block.params = orderedParams(record);
|
const existing = findModificationEntry(profile, key);
|
||||||
|
if (existing) {
|
||||||
|
existing.params = orderedParams(record);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
appendModificationEntry(profile, { name: key, params: orderedParams(record), blocks: [] });
|
||||||
}
|
}
|
||||||
|
|
||||||
function orderedParams(record: ModificationRecord): BlkParam[] {
|
function orderedParams(record: ModificationRecord): BlkParam[] {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
* (with the modifications the mission support planes' presets need) and the free repair over time (repair/repair-over-time.ts) kept up to date and persisted on
|
* (with the modifications the mission support planes' presets need) and the free repair over time (repair/repair-over-time.ts) kept up to date and persisted on
|
||||||
* every read or write.
|
* every read or write.
|
||||||
*/
|
*/
|
||||||
|
import type { BlkBlock } from '@wto/blk';
|
||||||
import type { AccountStore } from './accounts/account-store.ts';
|
import type { AccountStore } from './accounts/account-store.ts';
|
||||||
import type { ClanStore } from './clans/clan-store.ts';
|
import type { ClanStore } from './clans/clan-store.ts';
|
||||||
import type { DatasetCache } from './game-data/datasets/dataset-cache.ts';
|
import type { DatasetCache } from './game-data/datasets/dataset-cache.ts';
|
||||||
@@ -50,6 +51,7 @@ export function setUpProfiles(
|
|||||||
tuning: Tuning,
|
tuning: Tuning,
|
||||||
sync?: ProfileSyncContext,
|
sync?: ProfileSyncContext,
|
||||||
vehicles: readonly CatalogueVehicle[] = datasets.load(vehicleCatalogue),
|
vehicles: readonly CatalogueVehicle[] = datasets.load(vehicleCatalogue),
|
||||||
|
onProfileRefresh?: (profile: BlkBlock, userId: string) => void,
|
||||||
): ProfileServices {
|
): ProfileServices {
|
||||||
const startingContent: StartingContent = {
|
const startingContent: StartingContent = {
|
||||||
reserveVehicles: datasets.load(reserveVehicles),
|
reserveVehicles: datasets.load(reserveVehicles),
|
||||||
@@ -70,6 +72,7 @@ export function setUpProfiles(
|
|||||||
removeExpiredItems(profile, serverTimeNow());
|
removeExpiredItems(profile, serverTimeNow());
|
||||||
repairVehiclesOverTime(profile, repair, serverTimeNow());
|
repairVehiclesOverTime(profile, repair, serverTimeNow());
|
||||||
trimUserLogs(profile, tuning.limits.userLogsKept);
|
trimUserLogs(profile, tuning.limits.userLogsKept);
|
||||||
|
onProfileRefresh?.(profile, userId);
|
||||||
});
|
});
|
||||||
return { profiles, research, equipment, repair };
|
return { profiles, research, equipment, repair };
|
||||||
}
|
}
|
||||||
@@ -3,9 +3,9 @@ import { ClanStore } from '../clans/clan-store.ts';
|
|||||||
import { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
|
import { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
|
||||||
import { vehicleCatalogue } from '../game-data/datasets/vehicle-catalogue.ts';
|
import { vehicleCatalogue } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||||
import { GameFiles } from '../game-data/game-files.ts';
|
import { GameFiles } from '../game-data/game-files.ts';
|
||||||
|
import { ProfileEquipmentIndex } from '../modifications/profile-equipment-index.ts';
|
||||||
import { addOwnedVehicle, ownedVehicles } from '../profile/profile-hangar.ts';
|
import { addOwnedVehicle, ownedVehicles } from '../profile/profile-hangar.ts';
|
||||||
import { ownsModification, writeModificationRecord } from '../profile/profile-modifications.ts';
|
import { researchPointsOf } from '../profile/profile-vehicle-research.ts';
|
||||||
import { researchPointsOf, setResearchPoints } from '../profile/profile-vehicle-research.ts';
|
|
||||||
import { setUpProfiles } from '../profiles-setup.ts';
|
import { setUpProfiles } from '../profiles-setup.ts';
|
||||||
import { TechTree } from '../research/tech-tree.ts';
|
import { TechTree } from '../research/tech-tree.ts';
|
||||||
import { loadTuning } from '../tuning/tuning.ts';
|
import { loadTuning } from '../tuning/tuning.ts';
|
||||||
@@ -15,7 +15,7 @@ export interface ResearchBranch {
|
|||||||
readonly country: string;
|
readonly country: string;
|
||||||
readonly type: string;
|
readonly type: string;
|
||||||
}
|
}
|
||||||
export type ResearchOperation = 'research' | 'purchase' | 'equipment';
|
export type ResearchOperation = 'purchase' | 'equipment';
|
||||||
|
|
||||||
function tree(location: SaveLocation) {
|
function tree(location: SaveLocation) {
|
||||||
const gameFiles = new GameFiles(location.gameFolder);
|
const gameFiles = new GameFiles(location.gameFolder);
|
||||||
@@ -52,21 +52,19 @@ export function editSaveResearch(location: SaveLocation, userId: string, branch:
|
|||||||
const { profiles, equipment } = setUpProfiles(location.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
|
const { profiles, equipment } = setUpProfiles(location.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
|
||||||
profiles.update(userId, (profile) => {
|
profiles.update(userId, (profile) => {
|
||||||
const owned = ownedVehicles(profile);
|
const owned = ownedVehicles(profile);
|
||||||
|
const index = operation === 'equipment' ? new ProfileEquipmentIndex(profile) : undefined;
|
||||||
for (const unit of units) {
|
for (const unit of units) {
|
||||||
if (operation === 'research' && unit.kind === 'research' && !owned.has(unit.name)) {
|
|
||||||
setResearchPoints(profile, unit.name, Math.max(researchPointsOf(profile, unit.name), unit.researchPoints));
|
|
||||||
}
|
|
||||||
if (operation === 'purchase' && (unit.kind === 'research' || unit.kind === 'purchase')) {
|
if (operation === 'purchase' && (unit.kind === 'research' || unit.kind === 'purchase')) {
|
||||||
addOwnedVehicle(profile, unit.name);
|
addOwnedVehicle(profile, unit.name);
|
||||||
for (const part of unit.parts) addOwnedVehicle(profile, part);
|
for (const part of unit.parts) addOwnedVehicle(profile, part);
|
||||||
}
|
}
|
||||||
if (operation === 'equipment' && owned.has(unit.name)) {
|
if (index && owned.has(unit.name)) {
|
||||||
const enabledGroups = new Set<string>();
|
const enabledGroups = new Set<string>();
|
||||||
for (const mod of equipment.vehicle(unit.name)?.modifications ?? []) {
|
for (const mod of equipment.vehicle(unit.name)?.modifications ?? []) {
|
||||||
if (mod.name === 'premExpMul' || mod.goldenEagles > 0 || ownsModification(profile, unit.name, mod.name)) continue;
|
if (mod.name === 'premExpMul' || mod.goldenEagles > 0 || index.ownsModification(unit.name, mod.name)) continue;
|
||||||
const enable = mod.defaultEnabled && (!mod.exclusiveGroup || !enabledGroups.has(mod.exclusiveGroup));
|
const enable = mod.defaultEnabled && (!mod.exclusiveGroup || !enabledGroups.has(mod.exclusiveGroup));
|
||||||
if (enable && mod.exclusiveGroup) enabledGroups.add(mod.exclusiveGroup);
|
if (enable && mod.exclusiveGroup) enabledGroups.add(mod.exclusiveGroup);
|
||||||
writeModificationRecord(profile, unit.name, mod.name, {
|
index.writeModificationRecord(unit.name, mod.name, {
|
||||||
silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: enable, count: Math.max(1, mod.maxCount),
|
silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: enable, count: Math.max(1, mod.maxCount),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
import { existsSync, readFileSync } from 'node:fs';
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
|
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
|
||||||
|
import { normalizeModificationBlocks } from '../profile/profile-modifications.ts';
|
||||||
import { writeFileAtomic } from '../storage/atomic-file.ts';
|
import { writeFileAtomic } from '../storage/atomic-file.ts';
|
||||||
import type { SaveUpgrades } from './save-upgrades.ts';
|
import type { SaveUpgrades } from './save-upgrades.ts';
|
||||||
|
|
||||||
@@ -44,6 +45,7 @@ export class SaveStore {
|
|||||||
saveProfile(userId: string, profile: BlkBlock): void {
|
saveProfile(userId: string, profile: BlkBlock): void {
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
const previous = existsSync(this.#infoPath(userId)) ? (JSON.parse(readFileSync(this.#infoPath(userId), 'utf8')) as SaveInfo) : undefined;
|
const previous = existsSync(this.#infoPath(userId)) ? (JSON.parse(readFileSync(this.#infoPath(userId), 'utf8')) as SaveInfo) : undefined;
|
||||||
|
normalizeModificationBlocks(profile);
|
||||||
writeFileAtomic(this.#profilePath(userId), encodeBlk(profile));
|
writeFileAtomic(this.#profilePath(userId), encodeBlk(profile));
|
||||||
const info: SaveInfo = { formatVersion: this.#upgrades.currentFormat, created: previous?.created ?? now, updated: now };
|
const info: SaveInfo = { formatVersion: this.#upgrades.currentFormat, created: previous?.created ?? now, updated: now };
|
||||||
writeFileAtomic(this.#infoPath(userId), JSON.stringify(info, null, 2));
|
writeFileAtomic(this.#infoPath(userId), JSON.stringify(info, null, 2));
|
||||||
|
|||||||
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user