Compare commits
124
Commits
7bd17c4f74
...
v0.1.6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2867063e1 | ||
|
|
887a8262db | ||
|
|
036a479aab | ||
|
|
9ba92f289d | ||
|
|
aaae2e4187 | ||
|
|
d73221092d | ||
|
|
b56c5eaf58 | ||
|
|
710c8ecaaa | ||
|
|
b276e686b0 | ||
|
|
894dd0363d | ||
|
|
d58ba9fb9b | ||
|
|
f8bd79042b | ||
|
|
5786fee63b | ||
|
|
0b841ce2a2 | ||
|
|
038d897b1e | ||
|
|
ee7bb12092 | ||
|
|
ee360a5042 | ||
|
|
4e658cae9c | ||
|
|
1590a2fea9 | ||
|
|
4136021c8c | ||
|
|
264c5c59b8 | ||
|
|
77e4806ffc | ||
|
|
58fde2030c | ||
|
|
413bd55c54 | ||
|
|
470fc3746d | ||
|
|
f86ab99c17 | ||
|
|
0843fde6ff | ||
|
|
ba947fe5b6 | ||
|
|
39a77c04cb | ||
|
|
e0a344708d | ||
|
|
21ab1084a6 | ||
|
|
f932ef096f | ||
|
|
d40623cd47 | ||
|
|
ebc36aef99 | ||
|
|
dddcdde62c | ||
|
|
fe29b5fe9c | ||
|
|
647eff35fe | ||
|
|
ed5296e0b8 | ||
|
|
c3cf4e3707 | ||
|
|
49264b0326 | ||
|
|
29736870ac | ||
|
|
9e6e13895e | ||
|
|
12a573a333 | ||
|
|
429c5eec12 | ||
|
|
b3211b89cd | ||
|
|
8f1d175d55 | ||
|
|
48f01b533e | ||
|
|
6f2d9f639b | ||
|
|
f2e73c1cfe | ||
|
|
bc35cc89ab | ||
|
|
4191d59168 | ||
|
|
842ee23fa4 | ||
|
|
8c7d4a44a4 | ||
|
|
688406bb76 | ||
|
|
0167c3ea7d | ||
|
|
3282320fb7 | ||
|
|
6d0abf9caf | ||
|
|
194417a388 | ||
|
|
480496ca93 | ||
|
|
428b2d3601 | ||
|
|
2d3287937f | ||
|
|
37cbcd806f | ||
|
|
0af4183cb1 | ||
|
|
65363ce9de | ||
|
|
69d95df88e | ||
|
|
b3f9ff589c | ||
|
|
85532cd930 | ||
|
|
651b023d2a | ||
|
|
1d3e47b082 | ||
|
|
ac35c25851 | ||
|
|
d5008baeff | ||
|
|
45ff082a36 | ||
|
|
80113bdd2e | ||
|
|
314bdfe68e | ||
|
|
9229045042 | ||
|
|
7e5eb99696 | ||
|
|
73bae4785f | ||
|
|
89242e91f0 | ||
|
|
5e521295a3 | ||
|
|
885e3bbb5d | ||
|
|
bb680c6abd | ||
|
|
975a28441a | ||
|
|
4ac3484f56 | ||
|
|
a2fdcc1f15 | ||
|
|
e79866b96e | ||
|
|
e2ac4fa744 | ||
|
|
01bafb6db7 | ||
|
|
18637cf1ff | ||
|
|
10427912e2 | ||
|
|
214f9d7f4b | ||
|
|
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 |
No files matched your search
@@ -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.
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
## 简体中文
|
||||||
|
|
||||||
|
`v0.1.4` 带来**实验性新版陆战 AI(第一阶段)**、启动器全新**「Bot 参数」调参页(含陆战 AI 出车权重)**、**Dagor 风格 `.blk.patch.blk` 模组补丁引擎**,以及多项对局伤害反馈、改装件批量购买与启动器便携更新修复。
|
||||||
|
|
||||||
|
### 该下载哪一个文件?
|
||||||
|
|
||||||
|
- **绝大多数玩家**:下载 **`wtoffline-launcher-0.1.4-win-x64.exe`**,下载后直接安装即可(覆盖安装保留全部存档与配置)。
|
||||||
|
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.4-win-x64-portable.zip`**,解压到任意目录后运行其中的启动器即可。
|
||||||
|
|
||||||
|
### 重点新功能
|
||||||
|
|
||||||
|
- **实验性新版陆战 AI(第一阶段,默认启用)。**
|
||||||
|
- 引入全新的模块化陆战 AI 架构:包含整队指挥层与任务单(按坚守 / 征服 / 制霸模式分配进攻、侧翼、架枪与防空角色,支持分路包抄、集结出发、占点回防与防空阵位)、曝光积分视觉感知与唯一弹道开火许可门(含植被透光、硬遮挡弹道扫掠与友军走廊防误伤)、单车车体状态机(短停射击预算、掩体装填回缩、摆角、僵持换位与受损维修)、本车目击测速提前量与失联守出口,以及按待发架容量配置主/副双弹种出生装弹与局内自动切弹。
|
||||||
|
- 当前为第一阶段实验版本,默认以完整模式(`full`)运行并持续调优中;若遇到寻路或行为异常,可随时在启动器「数值 → Bot 参数」切回「原版 AI(`stock`)」。
|
||||||
|
- 移动射击的车速上限随距离缩短而提高。车辆会主动减速,持续无法开火时可短停争取一炮,瞄准也改为按跟踪目标的误差判断。同步更新了出车权重、感知、占点与车体动作的默认参数。
|
||||||
|
- **启动器新增「数值 → Bot 参数」页面。**
|
||||||
|
- 统一集中管理陆战 AI 模式切换、AI 坦克 / 飞机重生次数、每类载具候选池上限、**陆战 AI 出车权重**(中坦 / 主战、重坦、坦歼、轻坦、防空车、其他)与出生携弹策略。
|
||||||
|
- 同时以折叠分组开放全部陆战 AI 进阶参数(指挥配额、占点宏观、状态机、视觉感知、测速偏差、火控开火门、机动寻路、编队避让与地形约束),支持参数校验与一键恢复默认值。
|
||||||
|
- **模组系统新增 Dagor 风格 `.blk.patch.blk` 与 `include` 编译支持。**
|
||||||
|
- 支持原生风格的 `*.blk.patch.blk` 与 `client/config-blk.patch.blk` 增量补丁、编译期 `include` / `includeOnce` 展开,以及 Dagor `@` 指令(`@override`、`@replace`、`@delete`、`@clone`、`@inherit`、`@after`、`@before` 等),同时完全保留 `*.blk.patch.jsonc` 兼容。
|
||||||
|
- 同步重写并补齐中英双语开发者手册(`dev-docs/`)与模组制作手册(`mod-dev-docs/`)。
|
||||||
|
|
||||||
|
### 修复与改进
|
||||||
|
|
||||||
|
- **对局伤害反馈与改装件**:
|
||||||
|
- 修复空战右下角敌机部件受损播报串台(仅显示本机及观战目标,不再混入 AI 互打记录)以及空战持续命中时重复普通命中丢失的问题;
|
||||||
|
- 修正普通命中与跳弹等引擎判定无效命中的奖励分类,并修正右侧部件受损反馈的攻击者与收件人归属;
|
||||||
|
- 修复机库一键「购买所有已研发改装件」时因前置依赖状态与价格核算不一致报「角色服务器内部错误」的问题。
|
||||||
|
- **对局奖励与备用载具**
|
||||||
|
- 空战街机可因伤害或摧毁敌方小基地获得个人分,摧毁奖励也会列入战后明细。
|
||||||
|
- 修复重生界面中已购买的单车备用载具显示。每日免费出击、单车备用和通用备用按实际成功出击结算。
|
||||||
|
- 修复部分任务单位击杀被误计为首杀的问题,并加固助攻事件处理。
|
||||||
|
- **启动器维护、便携版更新与界面**:
|
||||||
|
- 客户端维护页新增「设置 / 更换在线版安装来源」,方便在线版移动目录后继续一键增量更新;
|
||||||
|
- 复制安装与「从在线版更新」自动跳过并保留玩家自定义内容目录(`UserSkins`、`UserSights`、`WarThunderCDK` 与启动器日志),避免更新覆盖自制涂装或瞄具;
|
||||||
|
- 复制安装与增量更新会跳过下载不完整的超清材质包(UHQ)。已有离线客户端遇到残缺材质包时,启动器会在启动前提示处理。
|
||||||
|
- 修复便携版原地更新在 Windows 下的文件复制、Electron `.asar` 检查冲突与进程分离重启问题,并防止客户端或数据目录嵌套于启动器安装目录内;
|
||||||
|
- 更新日志改为支持 Markdown 排版的弹窗展示。
|
||||||
|
|
||||||
|
### 社区交流与反馈
|
||||||
|
|
||||||
|
欢迎加入 WTOffline 官方 Discord 服务器,反馈新版陆战 AI 实机体验、分享你的 Bot 调参或自制模组,并关注最新客户端适配进度:
|
||||||
|
|
||||||
|
- **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`,并支持按特征码自动适配后续小版本(已在 `2.61.0.60` 通过静态与构建核对)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
`v0.1.4` introduces the **experimental Ground AI Rebuild (Phase 1)**, a new **Bot parameters** page in the launcher (including **ground AI vehicle class weights**), **Dagor-style `.blk.patch.blk` mod patching**, and a set of battle damage feedback, bulk modification purchase, and portable updater fixes.
|
||||||
|
|
||||||
|
### Which file should I download?
|
||||||
|
|
||||||
|
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.4-win-x64.exe`** — the standard Windows installer with built-in automatic update checks (safe to install over previous versions; preserves all saves and tuning).
|
||||||
|
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.4-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
- **Experimental Ground AI Rebuild (Phase 1, enabled by default).**
|
||||||
|
- Introduces a modular custom ground AI architecture: a team commander & task orders (mode-aware Assault / Flank / Overwatch / SPAA role quotas for Battle, Conquest, and Domination with flank lanes, rally staging, cap recall, and air-aware SPAA positioning), exposure-based visual perception and a single ballistic fire gate (foliage transparency, hard-cover ballistic sweeps, and friendly-fire corridor protection), a hull state machine (short-halt budget, cover reload retreat, angling, stalemate repositioning, and damage repair), sample-based velocity lead estimation with last-seen exit watch, and ready-rack dual-ammo bot spawn loadouts with automatic shell switching.
|
||||||
|
- Ships in `full` mode by default for testing and live tuning; if you run into pathing or behavior issues, you can switch back to **Stock AI (`stock`)** anytime under **Tuning → Bot parameters**.
|
||||||
|
- The speed limit for firing on the move rises as targets get closer. Bots slow down and can briefly stop when they cannot fire while moving. Aim stability now uses tracking error. Vehicle weights, perception, capture assignments, and hull behavior also have updated defaults.
|
||||||
|
- **New "Tuning → Bot parameters" page in the launcher.**
|
||||||
|
- Brings together ground AI mode selection, AI tank / aircraft respawn limits, per-type AI pool cap, **ground AI vehicle class weights** (Medium/MBT, Heavy, TD, Light, SPAA, Other), and spawn ammunition rules in one place.
|
||||||
|
- Exposes all advanced ground AI tuning sections in collapsible groups (commander, macro, state machine, perception, tactics, estimation, fire control, navigation, crowd, terrain, and runtime cadence/diagnostics) with validation and one-click section reset.
|
||||||
|
- **Dagor-style `.blk.patch.blk` & compile-time `include` support for mods.**
|
||||||
|
- Supports native-style `*.blk.patch.blk` and `client/config-blk.patch.blk` incremental patching, `include` / `includeOnce` expansion, and Dagor `@`-directives (`@override`, `@replace`, `@delete`, `@clone`, `@inherit`, `@after`, `@before`, etc.) while maintaining full backwards compatibility with `*.blk.patch.jsonc`.
|
||||||
|
- Rewrote and expanded both the bilingual Developer Handbook (`dev-docs/`) and Mod Developer Handbook (`mod-dev-docs/`).
|
||||||
|
|
||||||
|
### Fixes and improvements
|
||||||
|
|
||||||
|
- **Battle feedback & modifications**:
|
||||||
|
- Fixed Air battle bottom-right enemy part damage feed bleed-through from AI-vs-AI fights (now filtered to the local player or spectated unit) and stopped dropping repeated normal hits on aircraft.
|
||||||
|
- Corrected normal hit vs. ineffective hit (e.g., ricochet) award classification and right-side component damage feedback ownership.
|
||||||
|
- Fixed "Internal character server error" when clicking **Buy all researched modifications** by emitting native `RESEARCHED` status for prerequisite chains and aligning bulk pricing.
|
||||||
|
- **Battle rewards and backups**
|
||||||
|
- Damaging or destroying enemy mini-bases in Air Arcade now awards personal score. Base destruction rewards appear in the post-battle breakdown.
|
||||||
|
- Fixed how purchased vehicle backups appear in the respawn screen. Daily free spawns, vehicle backups, and universal backups are accounted for after a confirmed spawn.
|
||||||
|
- Fixed some mission-unit kills being counted as the first player kill and tightened assist event handling.
|
||||||
|
- **Launcher maintenance, portable updater & UI**:
|
||||||
|
- Added support for setting or changing the online client update source on the client maintenance page.
|
||||||
|
- Skipped and preserved player-created folders (`UserSkins`, `UserSights`, `WarThunderCDK`, and launcher logs) when copying or updating from the online client.
|
||||||
|
- Copy installs and incremental updates skip incomplete Ultra High Quality (UHQ) texture packs. The launcher flags incomplete packs in existing offline installations before starting the client.
|
||||||
|
- Fixed portable in-place updates on Windows (`original-fs`, removing unused `default_app.asar`, detached `Start-Process` relaunch) and guarded against nested launcher/data directories.
|
||||||
|
- Rendered launcher release notes in a dedicated Markdown modal.
|
||||||
|
|
||||||
|
### Community & Feedback
|
||||||
|
|
||||||
|
Join the official WTOffline Discord server to share feedback on the new ground AI, post custom Bot tuning presets or 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 (static and build checks pass on `2.61.0.60`).
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
## 简体中文
|
||||||
|
|
||||||
|
`v0.1.5` 是一次集中维护与修复版本,重点解决 **空战坠机后偶发崩溃(`0xC0000374`)**、**备用载具无法出击与扣减失效**、**单车涂装/挂载/弹链与配平未保存**、**联队时间与 20,000 研发点上限异常**、**贴花缓存缺失导致大面积无法显示**,以及 **启动器客户端移除防误删与安装体验改进**。
|
||||||
|
|
||||||
|
### 该下载哪一个文件?
|
||||||
|
|
||||||
|
- **绝大多数玩家(推荐)**:下载 **`wtoffline-launcher-0.1.5-win-x64.exe`**,直接覆盖安装即可(保留全部存档与配置)。
|
||||||
|
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.5-win-x64-portable.zip`**,解压到任意目录后运行其中的启动器即可。
|
||||||
|
|
||||||
|
### 重点修复
|
||||||
|
|
||||||
|
- **对局与战斗**:
|
||||||
|
- 修复空战与核战冲突中飞机坠毁后 0.1–4 秒内偶发堆损坏崩溃(`0xC0000374`)的问题:新增原生模块 `local_mp_air_ai_sync`,在本地主机下串行化 AI 飞机队列扩容操作,同时保留多核并行物理更新;
|
||||||
|
- 修复战局内选择备用载具后无法点击出击,以及陆战 / 海战载具因内部路径前缀导致备用载具结算扣减失效、未修车槽位被误拦的问题;
|
||||||
|
- 修复新版陆战 AI 在单人试驾中错误接管靶车的问题,限定仅在多人对局中运行。
|
||||||
|
- **档案、联队与商店**:
|
||||||
|
- 修复载具涂装、挂载预设、弹链选择以及试飞配平(副翼 / 升降舵 / 方向舵)在重启后未保存的问题(感谢 `duduyagame`);
|
||||||
|
- 修复联队活跃度下次结算时间与排行榜赛季时间显示为 1970 年的问题;预置普通联队补齐 58–60 名 NPC 成员以恢复 20,000 周期研发点上限,接通对局活跃度累计与 3 天周期结算,并在 `tuning/clans.jsonc` 开放初始周期与初始活跃度配置(默认 `0`);
|
||||||
|
- 解除部分联动促销载具(`bf-109c_1_promo`、`us_m4_sherman_promo`、`jp_destroyer_hatsuzuki`)的跨平台促销锁定,支持在科技树直接订购;
|
||||||
|
- 免扣款支付按钮默认名称改为「直接获取」(`Direct Claim`),并可在 `tuning/store.jsonc`(`freePaymentLabel`)中自定义,同步热生效于游戏内支付弹窗、内置商城和内置交易所。
|
||||||
|
- **贴花缓存与涂装索引**:
|
||||||
|
- 修复从在线版导入贴花缓存时因部分 `.ddsx` 文件尚未缓存而导致贴花大面积读取失败的问题:构建时自动按实际缓存文件过滤索引、自动补齐缺失 LOD、未缓存标准贴花回退内置占位图并丢弃残缺涂装;
|
||||||
|
- 支持直接选择游戏根目录识别贴花缓存,安装向导可自动探测并预填在线版贴花缓存,客户端详情页新增一键从在线版来源导入贴花缓存。
|
||||||
|
|
||||||
|
### 启动器改进
|
||||||
|
|
||||||
|
- **更安全的客户端移除与还原流程**:
|
||||||
|
- 彻底拆分「从列表移除客户端」与「删除磁盘文件」,默认均不勾选;坏记录或已移动目录可直接安全移出列表;
|
||||||
|
- 新增 `wtoffline/client.json` 来源标记,仅允许对明确标记为独立副本 / 硬链接副本、非 Steam 且不与其他客户端来源目录重叠的目录执行删除;原地安装或无标记目录提供原子「还原原版文件并清理离线补丁」与「打开所在文件夹」入口。
|
||||||
|
- **安装进度与对话框体验**:
|
||||||
|
- 省空间复制进度条拆分展示实际写入字节与硬链接共享字节,并补充 Windows 资源管理器属性会重复统计硬链接空间的说明;
|
||||||
|
- 启动器所有分类文件 / 目录选择与导出对话框自动记住上次路径,并在原路径不存在时回退至最近的现存父目录。
|
||||||
|
|
||||||
|
### 社区交流与反馈
|
||||||
|
|
||||||
|
欢迎加入 WTOffline 官方 Discord 服务器反馈问题、分享调参配置或自制模组,并关注最新客户端适配进度:
|
||||||
|
|
||||||
|
- **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`,并支持按特征码自动适配后续小版本(已在 `2.61.0.60` 通过静态与构建核对)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
`v0.1.5` is a maintenance and bug-fix release addressing the **Air battle post-crash heap corruption (`0xC0000374`)**, **backup vehicle respawn and accounting issues**, **vehicle camouflage/loadout/trim persistence**, **squadron timestamps and 20,000 RP cap**, **decal cache missing-file failures**, and **safer launcher client removal and installation UX**.
|
||||||
|
|
||||||
|
### Which file should I download?
|
||||||
|
|
||||||
|
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.5-win-x64.exe`** — the standard Windows installer with built-in automatic update checks (safe to install over previous versions; preserves all saves and tuning).
|
||||||
|
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.5-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
|
||||||
|
|
||||||
|
### Key Fixes
|
||||||
|
|
||||||
|
- **Battles & gameplay**:
|
||||||
|
- Fixed intermittent heap corruption crashes (`0xC0000374`) 0.1–4 seconds after aircraft crashes in Air battles and Nuclear Escalation via a new native module (`local_mp_air_ai_sync`) that serializes `TeamAiManager::addToUnsortedPlanes` on the local host while keeping multi-threaded aircraft updates intact.
|
||||||
|
- Fixed backup vehicles failing to respawn in LocalMP battles, normalized ground/naval unit path prefixes so backup deductions match correctly after battle, and stopped unrepaired crew slots from blocking backup spawns.
|
||||||
|
- Restricted the custom ground AI runtime to multiplayer battles so it no longer takes over target vehicles in single-player test drives.
|
||||||
|
- **Profile, squadrons & store**:
|
||||||
|
- Persisted per-vehicle camouflage, weapon preset, ammo belt selections, and test-flight trim preferences across restarts (thanks to `duduyagame`).
|
||||||
|
- Fixed 1970 timestamps for squadron activity rewards and leaderboard seasons, backfilled preset normal squadrons to 58–60 NPC members to restore the 20,000 RP period cap, wired battle RP into 3-day squadron activity cycles, and made initial periods/activity configurable in `tuning/clans.jsonc` (defaulting to `0`).
|
||||||
|
- Stripped cross-promotion locks from promo gift vehicles (`bf-109c_1_promo`, `us_m4_sherman_promo`, `jp_destroyer_hatsuzuki`) so they can be ordered directly from the tech tree.
|
||||||
|
- Changed the default free offline payment button label to **Direct Claim** (Chinese: 「直接获取」) and made it tunable via `tuning/store.jsonc` (`freePaymentLabel`) across the in-game payment dialog, local store, and local marketplace.
|
||||||
|
- **Decal & skin cache**:
|
||||||
|
- Fixed widespread decal load failures when importing partially cached online `cache/content` folders by filtering against locally present `.ddsx` files, repairing single-LOD hits, falling back uncached stock decals to built-in placeholders, and dropping incomplete downloadable skins.
|
||||||
|
- Added support for picking a game root folder directly, auto-detecting decal cache in the install wizard, and one-click import from the recorded online source in client details.
|
||||||
|
|
||||||
|
### Launcher Improvements
|
||||||
|
|
||||||
|
- **Safer client removal & stock restore**:
|
||||||
|
- Separated removing a client from the launcher list from deleting files on disk (both unchecked by default), allowing broken or missing entries to be removed cleanly.
|
||||||
|
- Added a `wtoffline/client.json` origin marker so disk deletion is only permitted for verified copy/hardlink clients outside Steam that do not overlap any registered source folder, plus an atomic **Restore stock files & clean offline patches** flow and **Open folder** action for in-place or unmarked directories.
|
||||||
|
- **Install progress & file pickers**:
|
||||||
|
- Split actual disk-copied bytes from hardlinked shared bytes in space-saving install progress, with a note explaining that Windows Explorer properties double-count hardlinked space.
|
||||||
|
- Remembered the last selected directory per category across all file/folder picker and export dialogs with automatic parent fallback.
|
||||||
|
|
||||||
|
### Community & Feedback
|
||||||
|
|
||||||
|
Join the official WTOffline Discord server to report issues, share custom tuning presets or 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 (static and build checks pass on `2.61.0.60`).
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
## 简体中文
|
||||||
|
|
||||||
|
V0.1.6 改进了陆战 AI 的驾驶和交战,加入空战全真无间断作战、陆战全真和空陆守卫模式。启动器新增乘员组编辑和独立的地图适配包更新入口。
|
||||||
|
|
||||||
|
### 陆战 AI 与地图适配包
|
||||||
|
|
||||||
|
- AI **按车宽选择行驶路线**,同队坦克尽量分路推进。遇到停着的车辆或残骸时会尝试绕行,反复受阻时会后退并重新规划路线。
|
||||||
|
- AI **记住敌人上次出现的位置**,优先盯住近处或正在攻击自己的威胁。射击时综合考虑视线、炮口方向和命中机会,必要时减速、短停或转动车体。固定主炮也会借助车体转向进入射界。
|
||||||
|
- **首个地图适配包** `2026.12.06` 基于 Steam `2.61.0.64` 制作,覆盖 57 张陆战地图,下载约 541 MB。地图包单独分发,发布后可在启动器「关于 → 地图适配包」检查更新并安装。缺少对应地图数据时默认沿用原版寻路。
|
||||||
|
|
||||||
|
### 对局与结算
|
||||||
|
|
||||||
|
- **空战全真**采用 15 个原版无间断作战(EC)任务,支持无限重生。**陆战全真**使用出生点数(SP)出击。
|
||||||
|
- **空战和陆战守卫**可进入离线对局,按编队权重选择任务。陆战守卫的敌方进攻波次由原版任务 AI 控制,友方守卫使用新版 AI。
|
||||||
|
- 修复核战冲突等无限重生模式的 AI 重生规则,以及玩家无限重生时被误要求支付银狮的问题。
|
||||||
|
- 空战历史和全真中的敌方小基地伤害与摧毁现在计入个人分和战果收益。陆战占点给实际参与完成占领的玩家计分,并纳入银狮和研发点结算。
|
||||||
|
- 修复陆战命中标记、换弹种提示和右侧部件受损提示混入与玩家无关的事件。修复自定义陆战 AI 坦克行驶时缺少发动机声的问题。
|
||||||
|
|
||||||
|
### 启动器与模组
|
||||||
|
|
||||||
|
- 游戏退出后,可在「存档 → 乘员组」按国家开放、关闭或重新开放槽位,按兵种预览并调整技能等级。关闭前会自动备份,重新开放时可恢复该组的技能、训练和专精。
|
||||||
|
- 多个模组现在可在同一段科技树研发线上插入载具。启动器按模组加载顺序串接,并同步显示的连线与实际研发前置条件。
|
||||||
|
|
||||||
|
### 下载与兼容性
|
||||||
|
|
||||||
|
- **安装版** `wtoffline-launcher-0.1.6-win-x64.exe` 可覆盖安装。**便携版** `wtoffline-launcher-0.1.6-win-x64-portable.zip` 解压后即可使用。
|
||||||
|
- 已登记核对的客户端版本为 `2.61.0.37`、`2.61.0.43`、`2.61.0.55`、`2.61.0.58` 和 `2.61.0.64`。建议使用 `2.61.0.64` 搭配首个地图适配包。
|
||||||
|
- 此版本会自动把旧存档升级到格式 4。如需继续用旧版启动器,请保留升级前的存档备份。
|
||||||
|
- 首批地图的寻路已通过加载检查,部分路线仍需局内复核。全真、守卫、乘员组和发动机声修复仍待实机验收。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
V0.1.6 improves ground AI driving and combat, adds Air Simulator Enduring Confrontation, Ground Simulator and Air and Ground Assault, and gives the launcher a crew editor and a separate map pack updater.
|
||||||
|
|
||||||
|
### Ground AI and map packs
|
||||||
|
|
||||||
|
- **Driving and detours** use routes that fit each vehicle's width. Bots on the same team spread out where possible. They try to go around stopped vehicles and wrecks, and back up and replan after repeated blockages.
|
||||||
|
- **Spotting, aiming and firing** account for the last place a target was seen, nearby threats and incoming fire. Bots consider visibility, gun alignment and the chance of hitting. They can slow down, stop briefly or turn the hull, including to bring fixed guns on target.
|
||||||
|
- **The first map pack** (`2026.12.06`) covers 57 ground maps from Steam client `2.61.0.64` and is about 541 MB to download. The launcher lists it separately under **About → Map Adaptation Pack** when it is available. By default, battles use stock pathfinding when a map has no pack data.
|
||||||
|
|
||||||
|
### Battles and rewards
|
||||||
|
|
||||||
|
- **Air Simulator** uses 15 stock Enduring Confrontation missions with unlimited respawns. **Ground Simulator** uses Spawn Points.
|
||||||
|
- **Air and Ground Assault** can be played offline, with missions selected for the lineup's battle rating. In Ground Assault, stock mission AI controls the attacking waves and the new ground AI controls friendly defenders.
|
||||||
|
- Fixed bot respawns in unlimited-respawn modes such as Nuclear Escalation and removed unintended Silver Lion respawn charges in those modes.
|
||||||
|
- Damaging and destroying enemy mini-bases in Air Realistic and Simulator now counts toward personal score and battle rewards. Players who complete a ground capture receive score and credit toward Silver Lion and research rewards.
|
||||||
|
- Fixed ground hit markers, shell-change prompts and part-damage notices showing events unrelated to the player. Restored engine sound for ground AI tanks under custom driving control.
|
||||||
|
|
||||||
|
### Launcher and mods
|
||||||
|
|
||||||
|
- With the game closed, use **Saves → Crews** to open, close or reopen crew slots by nation, and preview and adjust skill levels by vehicle type. Closing a slot creates a backup. Reopening can restore its skills, training and qualifications.
|
||||||
|
- Multiple mods can insert vehicles into the same tech-tree link. The launcher composes the additions in mod load order and updates both the visible links and the research prerequisites.
|
||||||
|
|
||||||
|
### Downloads and compatibility
|
||||||
|
|
||||||
|
- **Installer** `wtoffline-launcher-0.1.6-win-x64.exe` can be installed over a previous version. **Portable** `wtoffline-launcher-0.1.6-win-x64-portable.zip` runs after extraction.
|
||||||
|
- Recorded client versions are `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, `2.61.0.58` and `2.61.0.64`. We recommend `2.61.0.64` with the first map pack.
|
||||||
|
- Existing saves upgrade automatically to format 4. Keep a pre-upgrade backup if you need to use an older launcher.
|
||||||
|
- The first set of maps passed loading checks. Some routes still need in-game checks, along with Simulator and Assault modes, the crew editor, and the engine audio fix.
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
# 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 the three
|
|
||||||
# signed files (installer, manifest, signature); a release missing any of them breaks the check
|
|
||||||
# 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:
|
|
||||||
# - push a tag: git tag v0.1.0 && git push origin v0.1.0
|
|
||||||
# - from the Actions page (Run workflow), giving the version; the tag is created on the chosen
|
|
||||||
# branch's latest commit.
|
|
||||||
# The release note comes from .github/release-notes/v<version>.md. The signing key comes from the
|
|
||||||
# repository secret PATCH_SIGNING_KEY (the same Ed25519 key used for adaptation packs).
|
|
||||||
name: Launcher release
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags: ['v*']
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
version:
|
|
||||||
description: 'Launcher version, e.g. 0.1.0 (must match apps/launcher/package.json)'
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
draft:
|
|
||||||
description: 'Keep the release as a draft for editing before publication'
|
|
||||||
type: boolean
|
|
||||||
default: true
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
release:
|
|
||||||
runs-on: windows-latest
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
shell: bash
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: 24
|
|
||||||
cache: npm
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: Download the Electron runtime
|
|
||||||
run: node node_modules/electron/install.js
|
|
||||||
|
|
||||||
- name: Resolve and verify the version
|
|
||||||
run: |
|
|
||||||
if [ "${{ github.event_name }}" = 'workflow_dispatch' ]; then
|
|
||||||
VERSION="${{ inputs.version }}"
|
|
||||||
else
|
|
||||||
VERSION="${GITHUB_REF_NAME#v}"
|
|
||||||
fi
|
|
||||||
PKG_VERSION=$(node -p "require('./apps/launcher/package.json').version")
|
|
||||||
if [ "$VERSION" != "$PKG_VERSION" ]; then
|
|
||||||
echo "Version $VERSION does not match apps/launcher/package.json ($PKG_VERSION)" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "VERSION=$VERSION" >> "$GITHUB_ENV"
|
|
||||||
|
|
||||||
- name: Typecheck
|
|
||||||
run: |
|
|
||||||
npm run typecheck
|
|
||||||
npm run typecheck --workspace "@wto/launcher"
|
|
||||||
|
|
||||||
- name: Build and package the Windows installer and portable archive
|
|
||||||
run: npm --workspace "@wto/launcher" run package:win
|
|
||||||
|
|
||||||
- name: Sign the release
|
|
||||||
env:
|
|
||||||
PATCH_SIGNING_KEY: ${{ secrets.PATCH_SIGNING_KEY }}
|
|
||||||
run: node scripts/sign-launcher-release.ts
|
|
||||||
|
|
||||||
- name: Create the release
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ github.token }}
|
|
||||||
run: |
|
|
||||||
flags=(--draft)
|
|
||||||
if [ "${{ github.event_name }}" = 'workflow_dispatch' ] && [ "${{ inputs.draft }}" = 'false' ]; then
|
|
||||||
flags=()
|
|
||||||
fi
|
|
||||||
gh release create "v$VERSION" \
|
|
||||||
"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.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[@]}" \
|
|
||||||
--title "WTOffline Launcher $VERSION" \
|
|
||||||
--notes-file ".github/release-notes/v$VERSION.md" \
|
|
||||||
--target "$GITHUB_SHA"
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
# Release an adaptation pack (packages/patcher/src/patch-pack/): pack and sign patches/ and publish
|
|
||||||
# it as a GitHub prerelease tagged patches-<version>, where the launcher looks for it.
|
|
||||||
#
|
|
||||||
# Start it either way:
|
|
||||||
# - push a tag: git tag patches-2026.11.29 && git push origin patches-2026.11.29
|
|
||||||
# - from the Actions page (Run workflow), giving the version; the tag is created on the chosen
|
|
||||||
# branch's latest commit.
|
|
||||||
# The signing key comes from the repository secret PATCH_SIGNING_KEY
|
|
||||||
# (scripts/generate-patch-signing-key.ts).
|
|
||||||
name: Adaptation pack
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags: ['patches-*']
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
version:
|
|
||||||
description: 'Pack version, YYYY.MM.DD or YYYY.MM.DD.N'
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
draft:
|
|
||||||
description: 'Keep the signed prerelease as a draft for editing before publication'
|
|
||||||
type: boolean
|
|
||||||
default: false
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
release:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
env:
|
|
||||||
# Packing needs no Electron binary.
|
|
||||||
ELECTRON_SKIP_BINARY_DOWNLOAD: '1'
|
|
||||||
VERSION: ${{ github.event_name == 'workflow_dispatch' && inputs.version || '' }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: 24
|
|
||||||
cache: npm
|
|
||||||
|
|
||||||
- run: npm ci
|
|
||||||
|
|
||||||
- name: Pack and sign
|
|
||||||
env:
|
|
||||||
PATCH_SIGNING_KEY: ${{ secrets.PATCH_SIGNING_KEY }}
|
|
||||||
run: |
|
|
||||||
if [ -n "$VERSION" ]; then
|
|
||||||
node scripts/build-patch-pack.ts --version "$VERSION" --out dist
|
|
||||||
else
|
|
||||||
# The version comes from the pushed tag (GITHUB_REF_NAME).
|
|
||||||
node scripts/build-patch-pack.ts --out dist
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Create the prerelease
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ github.token }}
|
|
||||||
DRAFT: ${{ inputs.draft || false }}
|
|
||||||
run: |
|
|
||||||
manifest=$(ls dist/*.manifest.json)
|
|
||||||
field() { node -e "const m=JSON.parse(require('fs').readFileSync(process.argv[1],'utf8'));const v=m[process.argv[2]];process.stdout.write(Array.isArray(v)?v.join(', '):String(v))" "$manifest" "$1"; }
|
|
||||||
version=$(field version)
|
|
||||||
printf 'Adaptation pack %s.\n\nChecked game versions: %s\nNeeds offline version %s or newer.\n' \
|
|
||||||
"$version" "$(field game_versions)" "$(field min_app_version)" > dist/notes.md
|
|
||||||
release_flags=(--prerelease)
|
|
||||||
if [ "$DRAFT" = 'true' ]; then
|
|
||||||
release_flags+=(--draft)
|
|
||||||
fi
|
|
||||||
gh release create "patches-$version" \
|
|
||||||
"dist/wtoffline-patches-$version.zip" \
|
|
||||||
"dist/wtoffline-patches-$version.zip.sig" \
|
|
||||||
"dist/wtoffline-patches-$version.manifest.json" \
|
|
||||||
"${release_flags[@]}" \
|
|
||||||
--title "Adaptation pack $version" \
|
|
||||||
--notes-file dist/notes.md \
|
|
||||||
--target "$GITHUB_SHA"
|
|
||||||
+6
-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
|
||||||
@@ -15,6 +18,7 @@ aces*.exe
|
|||||||
/apps/launcher/out/
|
/apps/launcher/out/
|
||||||
**/dist/
|
**/dist/
|
||||||
**/unpacked/
|
**/unpacked/
|
||||||
|
tools/navgen/extract/target/
|
||||||
|
|
||||||
# Node
|
# Node
|
||||||
node_modules/
|
node_modules/
|
||||||
@@ -25,10 +29,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/
|
||||||
|
|||||||
@@ -8,6 +8,8 @@
|
|||||||
|
|
||||||
WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线项目。本地服务器模拟 Gaijin 的线上服务,客户端的所有请求都发到本机。客户端照常登录、读取档案、进入机库、提交玩家操作,游戏规则、存档和对局结算都在本地服务器上完成,对手和队友全部是 AI。
|
WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线项目。本地服务器模拟 Gaijin 的线上服务,客户端的所有请求都发到本机。客户端照常登录、读取档案、进入机库、提交玩家操作,游戏规则、存档和对局结算都在本地服务器上完成,对手和队友全部是 AI。
|
||||||
|
|
||||||
|
> **项目定位**:WTOffline 是为了方便玩家离线游玩的**单机**《战争雷霆》项目。为保持项目边界清晰、避免争议,项目组**不会提供也不会制作包括局域网联机在内的任何形式联机功能**。
|
||||||
|
|
||||||
仓库只包含源码和补丁定义,不包含任何游戏文件。构建时从玩家本机的原版安装读取文件,生成一份独立的游戏副本。
|
仓库只包含源码和补丁定义,不包含任何游戏文件。构建时从玩家本机的原版安装读取文件,生成一份独立的游戏副本。
|
||||||
|
|
||||||
## 状态
|
## 状态
|
||||||
@@ -41,7 +43,7 @@ WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线
|
|||||||
| 战后 | 结算页、战斗历史、个人统计、战斗奖章、加成道具与合同结算、修理费与自动修理 |
|
| 战后 | 结算页、战斗历史、个人统计、战斗奖章、加成道具与合同结算、修理费与自动修理 |
|
||||||
| 回放 | 录制与回放,回放中切换到 AI 视角 |
|
| 回放 | 录制与回放,回放中切换到 AI 视角 |
|
||||||
|
|
||||||
尚未实现:全真模式、自定义战斗、单人任务与动态战役、世界大战、战令、成就进度和称号获取、排行榜。好友、组队等多人社交功能不适用,只保证界面不报错。
|
尚未实现:全真模式、自定义战斗、单人任务与动态战役、世界大战、战令、成就进度和称号获取、排行榜。本项目仅面向单人离线游玩,不制作包括局域网联机在内的任何联机功能;好友、组队等多人社交功能不适用,只保证界面不报错。
|
||||||
|
|
||||||
AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不足。
|
AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不足。
|
||||||
|
|
||||||
@@ -261,7 +263,7 @@ tools/ wtotools,补丁检查工具(Python)
|
|||||||
|
|
||||||
## 声明
|
## 声明
|
||||||
|
|
||||||
本项目是同人爱好项目,与 Gaijin Entertainment 没有任何关联,也未获其认可。War Thunder 及相关名称和素材归其各自所有者所有。仓库不分发任何游戏文件,使用者需要自行拥有合法的游戏客户端。
|
本项目是面向单人离线游玩的非商业同人爱好项目,项目组不会主动制作包括局域网联机在内的任何联机功能。本项目与 Gaijin Entertainment 没有任何关联,也未获其认可。War Thunder 及相关名称和素材归其各自所有者所有。仓库不分发任何游戏文件,使用者需要自行拥有合法的游戏客户端。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -273,6 +275,8 @@ tools/ wtotools,补丁检查工具(Python)
|
|||||||
|
|
||||||
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.
|
||||||
|
|
||||||
|
> **Project scope**: WTOffline is a **single-player offline** War Thunder project built to make offline play convenient for players. The project team **will not develop or provided any kind of multiplayer or networking features, including LAN multiplayer**.
|
||||||
|
|
||||||
The repository contains source code and patch definitions only. It does not contain any game files. The build reads files from the player's own installation and produces a separate game copy.
|
The repository contains source code and patch definitions only. It does not contain any game files. The build reads files from the player's own installation and produces a separate game copy.
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
@@ -306,7 +310,7 @@ Join the [WTOffline Discord server](https://discord.gg/P566xWNpEs) for general d
|
|||||||
| After battle | Debriefing, battle history, personal statistics, battle awards, booster and contract settlement, repair costs and auto-repair |
|
| After battle | Debriefing, battle history, personal statistics, battle awards, booster and contract settlement, repair costs and auto-repair |
|
||||||
| Replays | Recording and playback, switching to AI vehicles during playback |
|
| Replays | Recording and playback, switching to AI vehicles during playback |
|
||||||
|
|
||||||
Not yet implemented: Simulator modes, custom battles, single missions and dynamic campaigns, World War, the battle pass, achievement progress and title unlocks, leaderboards. Social multiplayer features such as friends and squads do not apply; the interface is only kept from breaking.
|
Not yet implemented: Simulator modes, custom battles, single missions and dynamic campaigns, World War, the battle pass, achievement progress and title unlocks, leaderboards. This project is strictly for single-player offline play and will not develop any multiplayer features (including LAN multiplayer); social multiplayer features such as friends and squads do not apply and are only kept from breaking the interface.
|
||||||
|
|
||||||
AI driving, pathfinding, and tactics come from the game's built-in AI and still have clear shortcomings.
|
AI driving, pathfinding, and tactics come from the game's built-in AI and still have clear shortcomings.
|
||||||
|
|
||||||
@@ -526,4 +530,4 @@ This project is released under the [GNU Affero General Public License v3.0](LICE
|
|||||||
|
|
||||||
## Disclaimer
|
## Disclaimer
|
||||||
|
|
||||||
This is a non-commercial fan project. It is not affiliated with or endorsed by Gaijin Entertainment. War Thunder and related names and assets belong to their respective owners. The repository does not distribute any game files; you need your own legitimate copy of the game client.
|
This is a non-commercial fan project built strictly for single-player offline play; the project team will not actively develop any multiplayer features, including LAN multiplayer. It is not affiliated with or endorsed by Gaijin Entertainment. War Thunder and related names and assets belong to their respective owners. The repository does not distribute any game files; you need your own legitimate copy of the game client.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
lab.local.json
|
||||||
|
.cache/
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>WTOffline AI Lab</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"mapsDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/maps",
|
||||||
|
"geoDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/work",
|
||||||
|
"logsDir": "J:/GAME/WTLab/client-2.61.0.58/.game_logs",
|
||||||
|
"python": "J:/GAME/WTOfflineProject/.venv/Scripts/python.exe"
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"name": "@wto/ai-lab",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "Ground AI lab: replay viewer for battle traces and simulator runs.",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"typecheck": "tsc --noEmit -p tsconfig.json"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@wto/ground-sim": "*",
|
||||||
|
"react": "^19.2.8",
|
||||||
|
"react-dom": "^19.2.8",
|
||||||
|
"three": "^0.187.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/react": "^19.2.17",
|
||||||
|
"@types/react-dom": "^19.2.3",
|
||||||
|
"@types/three": "^0.187.0",
|
||||||
|
"@vitejs/plugin-react": "^5.2.0",
|
||||||
|
"vite": "^7.3.6"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
/**
|
||||||
|
* Dev-server API of the AI lab (local only):
|
||||||
|
* GET /api/maps levels that have a navigation pack in mapsDir
|
||||||
|
* GET /api/maps/file?name= a pack or POI file of mapsDir
|
||||||
|
* GET /api/logs game logs (.clog) in logsDir, newest first
|
||||||
|
* GET /api/logs/text?name= a log decrypted with wtotools (cached until the log changes)
|
||||||
|
* GET /api/scene?name= the 3D map (.wtoscene) of a level, built from its .wtogeo in geoDir
|
||||||
|
* (cached until the geometry changes)
|
||||||
|
* Paths come from lab.local.json next to this app (see lab.local.example.json).
|
||||||
|
*/
|
||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
||||||
|
import type { ServerResponse } from 'node:http';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { buildMapScene, encodeMapScene, readGeo } from '@wto/ground-sim';
|
||||||
|
import type { Connect, Plugin } from 'vite';
|
||||||
|
|
||||||
|
interface LabConfig {
|
||||||
|
readonly mapsDir: string;
|
||||||
|
/** Where the navigation bake left the levels' .wtogeo geometry. */
|
||||||
|
readonly geoDir: string;
|
||||||
|
readonly logsDir: string;
|
||||||
|
readonly python: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const APP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const CACHE_DIR = path.join(APP_DIR, '.cache');
|
||||||
|
const SAFE_NAME = /^[\w.-]+$/;
|
||||||
|
|
||||||
|
function loadConfig(): LabConfig {
|
||||||
|
const file = path.join(APP_DIR, 'lab.local.json');
|
||||||
|
const raw = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>) : {};
|
||||||
|
const str = (key: string, fallback: string): string => (typeof raw[key] === 'string' ? (raw[key] as string) : fallback);
|
||||||
|
const mapsDir = str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps'));
|
||||||
|
return {
|
||||||
|
mapsDir,
|
||||||
|
geoDir: str('geoDir', path.join(mapsDir, '..', 'work')),
|
||||||
|
logsDir: str('logsDir', ''),
|
||||||
|
python: str('python', 'python'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendJson(res: ServerResponse, status: number, body: unknown): void {
|
||||||
|
res.statusCode = status;
|
||||||
|
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||||
|
res.end(JSON.stringify(body));
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendFile(res: ServerResponse, file: string, type: string): void {
|
||||||
|
res.statusCode = 200;
|
||||||
|
res.setHeader('Content-Type', type);
|
||||||
|
createReadStream(file).pipe(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
function listMaps(cfg: LabConfig): { level: string; pois: boolean; scene: boolean }[] {
|
||||||
|
if (!existsSync(cfg.mapsDir)) return [];
|
||||||
|
return readdirSync(cfg.mapsDir)
|
||||||
|
.filter((f) => f.endsWith('.wtonav'))
|
||||||
|
.map((f) => {
|
||||||
|
const level = f.slice(0, -'.wtonav'.length);
|
||||||
|
return {
|
||||||
|
level,
|
||||||
|
pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)),
|
||||||
|
scene: existsSync(path.join(cfg.geoDir, `${level}.wtogeo`)),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function listLogs(cfg: LabConfig): { name: string; size: number; mtime: number }[] {
|
||||||
|
if (cfg.logsDir === '' || !existsSync(cfg.logsDir)) return [];
|
||||||
|
return readdirSync(cfg.logsDir)
|
||||||
|
.filter((f) => f.endsWith('.clog'))
|
||||||
|
.map((name) => {
|
||||||
|
const st = statSync(path.join(cfg.logsDir, name));
|
||||||
|
return { name, size: st.size, mtime: st.mtimeMs };
|
||||||
|
})
|
||||||
|
.sort((a, b) => b.mtime - a.mtime);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Decrypts `name` into the cache unless the cached text is newer than the log. */
|
||||||
|
function decryptLog(cfg: LabConfig, name: string): Promise<string> {
|
||||||
|
const source = path.join(cfg.logsDir, name);
|
||||||
|
const out = path.join(CACHE_DIR, `${name}.txt`);
|
||||||
|
mkdirSync(CACHE_DIR, { recursive: true });
|
||||||
|
if (existsSync(out) && statSync(out).mtimeMs >= statSync(source).mtimeMs) return Promise.resolve(out);
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
execFile(cfg.python, ['-m', 'wtotools.cli', 'decrypt-clog', source, '--out', out], { timeout: 180_000 }, (err, _stdout, stderr) => {
|
||||||
|
if (err !== null) reject(new Error(`decrypt-clog failed: ${stderr || err.message}`));
|
||||||
|
else resolve(out);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Builds the level's 3D map into the cache unless the cached one is newer than its geometry. */
|
||||||
|
function sceneFile(cfg: LabConfig, level: string): string | undefined {
|
||||||
|
const geo = path.join(cfg.geoDir, `${level}.wtogeo`);
|
||||||
|
if (!existsSync(geo)) return undefined;
|
||||||
|
const out = path.join(CACHE_DIR, `${level}.wtoscene`);
|
||||||
|
if (existsSync(out) && statSync(out).mtimeMs >= statSync(geo).mtimeMs) return out;
|
||||||
|
mkdirSync(CACHE_DIR, { recursive: true });
|
||||||
|
writeFileSync(out, encodeMapScene(buildMapScene(readGeo(readFileSync(geo)))));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handle(cfg: LabConfig, url: URL, res: ServerResponse): Promise<boolean> {
|
||||||
|
const name = url.searchParams.get('name') ?? '';
|
||||||
|
if (url.pathname === '/api/maps') { sendJson(res, 200, listMaps(cfg)); return true; }
|
||||||
|
if (url.pathname === '/api/logs') { sendJson(res, 200, listLogs(cfg)); return true; }
|
||||||
|
const known = ['/api/maps/file', '/api/logs/text', '/api/scene'];
|
||||||
|
if (!known.includes(url.pathname)) return false;
|
||||||
|
if (!SAFE_NAME.test(name)) { sendJson(res, 400, { error: 'bad file name' }); return true; }
|
||||||
|
if (url.pathname === '/api/scene') {
|
||||||
|
const file = sceneFile(cfg, name);
|
||||||
|
if (file === undefined) sendJson(res, 404, { error: `no ${name}.wtogeo in ${cfg.geoDir}` });
|
||||||
|
else sendFile(res, file, 'application/octet-stream');
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (url.pathname === '/api/maps/file') {
|
||||||
|
const file = path.join(cfg.mapsDir, name);
|
||||||
|
if (!existsSync(file)) sendJson(res, 404, { error: `no ${name} in ${cfg.mapsDir}` });
|
||||||
|
else sendFile(res, file, name.endsWith('.json') ? 'application/json' : 'application/octet-stream');
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!name.endsWith('.clog') || !existsSync(path.join(cfg.logsDir, name))) {
|
||||||
|
sendJson(res, 404, { error: `no log ${name}` });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
sendFile(res, await decryptLog(cfg, name), 'text/plain; charset=utf-8');
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function labApi(): Plugin {
|
||||||
|
return {
|
||||||
|
name: 'wto-ai-lab-api',
|
||||||
|
configureServer(server) {
|
||||||
|
const middleware: Connect.NextHandleFunction = (req, res, next) => {
|
||||||
|
const url = new URL(req.url ?? '/', 'http://localhost');
|
||||||
|
if (!url.pathname.startsWith('/api/')) { next(); return; }
|
||||||
|
handle(loadConfig(), url, res)
|
||||||
|
.then((handled) => { if (!handled) sendJson(res, 404, { error: 'unknown endpoint' }); })
|
||||||
|
.catch((err: unknown) => sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) }));
|
||||||
|
};
|
||||||
|
server.middlewares.use(middleware);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
/** AI lab replay viewer: pick a game log, a battle in it, and play it back on the map. */
|
||||||
|
import type { TraceBattle } from '@wto/ground-sim';
|
||||||
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
|
import { fetchLogs, fetchMaps, loadLog, loadMap, type LogEntry, type MapData, type MapEntry } from './data.ts';
|
||||||
|
import { sceneAt } from './frames.ts';
|
||||||
|
import { Inspector } from './Inspector.tsx';
|
||||||
|
import { Map3D, type MapLook } from './Map3D.tsx';
|
||||||
|
import { buildMapLayer } from './mapLayer.ts';
|
||||||
|
import type { ViewMode } from './three/cameraRig.ts';
|
||||||
|
import type { Layers } from './three/overlays.ts';
|
||||||
|
import { Timeline } from './Timeline.tsx';
|
||||||
|
|
||||||
|
const LAYER_LABELS: Readonly<Record<keyof Layers, string>> = {
|
||||||
|
goals: '目标点', links: '目标连线', cones: '炮塔视野', labels: '标签', events: '开火与受击',
|
||||||
|
};
|
||||||
|
|
||||||
|
const VIEW_LABELS: Readonly<Record<ViewMode, string>> = { top: '俯视', free: '自由', follow: '跟随选中车', gun: '炮口视角' };
|
||||||
|
|
||||||
|
function logLabel(l: LogEntry): string {
|
||||||
|
const when = new Date(l.mtime).toLocaleString();
|
||||||
|
return `${l.name}(${(l.size / 1e6).toFixed(1)} MB,${when})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function App(): React.JSX.Element {
|
||||||
|
const [maps, setMaps] = useState<MapEntry[]>([]);
|
||||||
|
const [logs, setLogs] = useState<LogEntry[]>([]);
|
||||||
|
const [logName, setLogName] = useState('');
|
||||||
|
const [battles, setBattles] = useState<TraceBattle[]>([]);
|
||||||
|
const [battleIdx, setBattleIdx] = useState(0);
|
||||||
|
const [mapData, setMapData] = useState<MapData | undefined>(undefined);
|
||||||
|
const [exposure, setExposure] = useState(false);
|
||||||
|
const [covers, setCovers] = useState(false);
|
||||||
|
const [look, setLook] = useState<MapLook>({ view: 'top', navImage: true, objects: true, crushable: true });
|
||||||
|
const [layers, setLayers] = useState<Layers>({ goals: true, links: true, cones: false, labels: false, events: true });
|
||||||
|
const [t, setT] = useState(0);
|
||||||
|
const [playing, setPlaying] = useState(false);
|
||||||
|
const [speed, setSpeed] = useState(4);
|
||||||
|
const [selected, setSelected] = useState<string | undefined>(undefined);
|
||||||
|
const [status, setStatus] = useState('');
|
||||||
|
|
||||||
|
const refreshLogs = (): void => { fetchLogs().then(setLogs).catch((e: unknown) => setStatus(String(e))); };
|
||||||
|
useEffect(() => {
|
||||||
|
fetchMaps().then(setMaps).catch((e: unknown) => setStatus(String(e)));
|
||||||
|
refreshLogs();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const openLog = (name: string): void => {
|
||||||
|
setLogName(name);
|
||||||
|
setPlaying(false);
|
||||||
|
setStatus('正在解密和读取日志…');
|
||||||
|
loadLog(name).then((list) => {
|
||||||
|
setBattles(list);
|
||||||
|
// The longest battle that has bots in its trace; a battle left right after loading has none.
|
||||||
|
let pick = list.length - 1;
|
||||||
|
let best = 0;
|
||||||
|
list.forEach((b, i) => {
|
||||||
|
const withBots = b.frames.filter((f) => f.bots.size > 0).length;
|
||||||
|
if (withBots > best) { best = withBots; pick = i; }
|
||||||
|
});
|
||||||
|
setBattleIdx(Math.max(0, pick));
|
||||||
|
setStatus(list.length === 0 ? '这份日志里没有对局。' : '');
|
||||||
|
}).catch((e: unknown) => setStatus(String(e)));
|
||||||
|
};
|
||||||
|
|
||||||
|
const battle = battles[battleIdx];
|
||||||
|
const level = battle?.level;
|
||||||
|
useEffect(() => {
|
||||||
|
setT(battle?.startT ?? 0);
|
||||||
|
setSelected(undefined);
|
||||||
|
}, [battle]);
|
||||||
|
useEffect(() => {
|
||||||
|
const entry = maps.find((m) => m.level === level);
|
||||||
|
setMapData(undefined);
|
||||||
|
if (entry === undefined) return;
|
||||||
|
loadMap(entry).then(setMapData).catch((e: unknown) => setStatus(String(e)));
|
||||||
|
}, [level, maps]);
|
||||||
|
|
||||||
|
const mapLayer = useMemo(
|
||||||
|
() => (mapData === undefined ? undefined : buildMapLayer(mapData.pack, { tier: 1, exposure, covers })),
|
||||||
|
[mapData, exposure, covers],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!playing || battle === undefined) return;
|
||||||
|
let last = performance.now();
|
||||||
|
let handle = requestAnimationFrame(function step(now) {
|
||||||
|
const dt = (now - last) / 1000;
|
||||||
|
last = now;
|
||||||
|
setT((cur) => {
|
||||||
|
const next = cur + dt * speed;
|
||||||
|
if (next >= battle.endT) { setPlaying(false); return battle.endT; }
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
handle = requestAnimationFrame(step);
|
||||||
|
});
|
||||||
|
return () => cancelAnimationFrame(handle);
|
||||||
|
}, [playing, speed, battle]);
|
||||||
|
|
||||||
|
const scene = useMemo(() => (battle === undefined ? undefined : sceneAt(battle, t)), [battle, t]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="app">
|
||||||
|
<header>
|
||||||
|
<select value={logName} onChange={(e) => openLog(e.target.value)}>
|
||||||
|
<option value="">选择游戏日志…</option>
|
||||||
|
{logs.map((l) => <option key={l.name} value={l.name}>{logLabel(l)}</option>)}
|
||||||
|
</select>
|
||||||
|
<button type="button" onClick={refreshLogs}>刷新</button>
|
||||||
|
{battles.length > 1 && (
|
||||||
|
<select value={battleIdx} onChange={(e) => setBattleIdx(Number(e.target.value))}>
|
||||||
|
{battles.map((b, i) => (
|
||||||
|
<option key={i} value={i}>{`第 ${i + 1} 局 ${b.level ?? '未知地图'}(${b.frames.length} 帧)`}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
{(Object.keys(LAYER_LABELS) as (keyof Layers)[]).map((k) => (
|
||||||
|
<label key={k}>
|
||||||
|
<input type="checkbox" checked={layers[k]} onChange={(e) => setLayers({ ...layers, [k]: e.target.checked })} />
|
||||||
|
{LAYER_LABELS[k]}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
<select value={look.view} onChange={(e) => setLook({ ...look, view: e.target.value as ViewMode })}>
|
||||||
|
{(Object.keys(VIEW_LABELS) as ViewMode[]).map((v) => <option key={v} value={v}>{VIEW_LABELS[v]}</option>)}
|
||||||
|
</select>
|
||||||
|
<label><input type="checkbox" checked={look.navImage} onChange={(e) => setLook({ ...look, navImage: e.target.checked })} />导航网格</label>
|
||||||
|
<label><input type="checkbox" checked={look.objects} onChange={(e) => setLook({ ...look, objects: e.target.checked })} />物体</label>
|
||||||
|
<label><input type="checkbox" checked={look.crushable} onChange={(e) => setLook({ ...look, crushable: e.target.checked })} />可碾压物</label>
|
||||||
|
<label><input type="checkbox" checked={exposure} onChange={(e) => setExposure(e.target.checked)} />暴露度</label>
|
||||||
|
<label><input type="checkbox" checked={covers} onChange={(e) => setCovers(e.target.checked)} />掩体点</label>
|
||||||
|
{status !== '' && <span className="status">{status}</span>}
|
||||||
|
{battle !== undefined && battle.frames.length === 0 && <span className="status">这一局没有轨迹(游戏里没开 diagnostics.trace)。</span>}
|
||||||
|
</header>
|
||||||
|
<main>
|
||||||
|
<Map3D mapScene={mapData?.scene} nav={mapLayer} battle={battle} scene={scene} selected={selected}
|
||||||
|
layers={layers} look={look} onSelect={setSelected} />
|
||||||
|
{battle !== undefined && <Inspector battle={battle} scene={scene} selected={selected} />}
|
||||||
|
</main>
|
||||||
|
{battle !== undefined && (
|
||||||
|
<Timeline battle={battle} t={t} playing={playing} speed={speed} selected={selected}
|
||||||
|
onSeek={setT} onPlaying={setPlaying} onSpeed={setSpeed} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
/** Details of the selected vehicle at the current time, its recent log events, and the legends. */
|
||||||
|
import type { TraceBattle, TraceEvent } from '@wto/ground-sim';
|
||||||
|
import { eventsBetween, type SceneAt } from './frames.ts';
|
||||||
|
import {
|
||||||
|
BEHAVIOR_COLORS, BEHAVIOR_ZH, CLASS_ZH, COMMAND_ZH, DENY_COLORS, DENY_ZH, LANE_ZH, LOOK_COLORS, LOOK_ZH,
|
||||||
|
STATE_ZH, URGENCY_ZH, zh,
|
||||||
|
} from './labels.ts';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
readonly battle: TraceBattle;
|
||||||
|
readonly scene: SceneAt | undefined;
|
||||||
|
readonly selected: string | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const RECENT_SEC = 20;
|
||||||
|
|
||||||
|
function angleDiff(a: number, b: number): number {
|
||||||
|
return Math.abs(((((a - b) % 360) + 540) % 360) - 180);
|
||||||
|
}
|
||||||
|
|
||||||
|
function involves(e: TraceEvent, eid: string): boolean {
|
||||||
|
return e.eid === eid || e.fields['tgt'] === eid || e.fields['off'] === eid || e.fields['target'] === eid;
|
||||||
|
}
|
||||||
|
|
||||||
|
function eventText(e: TraceEvent): string {
|
||||||
|
return Object.entries(e.fields)
|
||||||
|
.filter(([k]) => k !== 't' && k !== 'eid')
|
||||||
|
.map(([k, v]) => `${k}=${v}`)
|
||||||
|
.join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function Legend({ names, colors }: { names: readonly string[]; colors: readonly string[] }): React.JSX.Element {
|
||||||
|
return (
|
||||||
|
<div className="legend">
|
||||||
|
{names.map((n, i) => (
|
||||||
|
<span key={n}><i style={{ background: colors[i] ?? '#444' }} />{n}</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Row({ k, v }: { k: string; v: string }): React.JSX.Element {
|
||||||
|
return <tr><th>{k}</th><td>{v}</td></tr>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Inspector({ battle, scene, selected }: Props): React.JSX.Element {
|
||||||
|
const u = selected !== undefined ? scene?.units.get(selected) : undefined;
|
||||||
|
const b = u?.bot;
|
||||||
|
const recent = selected !== undefined && scene !== undefined
|
||||||
|
? eventsBetween(battle, scene.t - RECENT_SEC, scene.t).filter((e) => involves(e, selected)).reverse()
|
||||||
|
: [];
|
||||||
|
return (
|
||||||
|
<aside className="inspector">
|
||||||
|
{u === undefined && <p className="hint">点击地图上的车辆查看详情。白框是玩家,黄色虚线是炮塔想看的方向,白线是实际炮管。</p>}
|
||||||
|
{u !== undefined && (
|
||||||
|
<table>
|
||||||
|
<tbody>
|
||||||
|
<Row k="编号" v={`${u.unit.eid}(${u.unit.army} 队,${u.unit.human ? '玩家' : u.unit.bot ? 'AI' : '原版 AI'})`} />
|
||||||
|
<Row k="存活" v={u.unit.alive ? '是' : '否'} />
|
||||||
|
<Row k="车速" v={`${u.unit.speed.toFixed(1)} m/s`} />
|
||||||
|
{b !== undefined && <>
|
||||||
|
<Row k="车型" v={zh(CLASS_ZH, b.vehicleClass)} />
|
||||||
|
<Row k="任务" v={b.hasOrder ? `${zh(COMMAND_ZH, b.command)},紧迫度${zh(URGENCY_ZH, b.urgency)},点 ${b.capIdx},${zh(LANE_ZH, b.lane)}` : '无'} />
|
||||||
|
<Row k="行为" v={`${zh(BEHAVIOR_ZH, b.behavior)}(分数 ${b.behaviorScore.toFixed(2)})`} />
|
||||||
|
<Row k="状态" v={zh(STATE_ZH, b.state)} />
|
||||||
|
<Row k="车速 期望/实际" v={`${b.wantSpeed.toFixed(1)} / ${b.forwardSpeed.toFixed(1)} m/s${b.reverseTravel ? ',倒车跟路' : ''}`} />
|
||||||
|
<Row k="感知目标" v={b.target === '0' ? '无' : `${b.target}${b.targetInSight ? '(可见)' : '(不可见)'}`} />
|
||||||
|
<Row k="威胁表" v={`${b.threatCount} 项,最高 ${b.topThreat},最高可见 ${b.topVisibleThreat}`} />
|
||||||
|
<Row k="炮塔依据" v={`${zh(LOOK_ZH, b.lookReason)}${b.lookAt !== '0' ? ` → ${b.lookAt}` : ''}`} />
|
||||||
|
<Row k="炮塔偏差" v={b.gunYaw === undefined ? '—' : `离想看的方向 ${angleDiff(b.gunYaw, b.wishYaw).toFixed(0)}°,离车头 ${angleDiff(b.gunYaw, u.yaw).toFixed(0)}°`} />
|
||||||
|
<Row k="主炮" v={b.reloading ? '装填中' : b.gunReady ? '就绪' : '未就绪'} />
|
||||||
|
<Row k="开火判定" v={`${zh(DENY_ZH, b.deny)},命中概率 ${(b.hitProb * 100).toFixed(0)}% / 门槛 ${(b.threshold * 100).toFixed(0)}%`} />
|
||||||
|
<Row k="扳机要求车速" v={b.requestedSpeed >= 99 ? '不限' : `${b.requestedSpeed.toFixed(1)} m/s`} />
|
||||||
|
</>}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
{recent.length > 0 && (
|
||||||
|
<div className="events">
|
||||||
|
<h4>最近 {RECENT_SEC} 秒的日志</h4>
|
||||||
|
{recent.map((e, i) => (
|
||||||
|
<div key={`${e.t}-${i}`}><b>{e.t.toFixed(1)}</b> {e.kind} <span>{eventText(e)}</span></div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<h4>行为</h4>
|
||||||
|
<Legend names={BEHAVIOR_ZH} colors={BEHAVIOR_COLORS} />
|
||||||
|
<h4>拒绝开火</h4>
|
||||||
|
<Legend names={DENY_ZH} colors={DENY_COLORS} />
|
||||||
|
<h4>炮塔依据</h4>
|
||||||
|
<Legend names={LOOK_ZH} colors={LOOK_COLORS} />
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
/**
|
||||||
|
* The battle in 3D: terrain and object collision shapes of the level, vehicles as simple shapes,
|
||||||
|
* and the replay's lines and markers. Left drag pans, right drag turns (except top-down), wheel
|
||||||
|
* zooms; a click on a vehicle selects it.
|
||||||
|
*/
|
||||||
|
import { BEHAVIOR_NAMES, type MapScene, type TraceBattle } from '@wto/ground-sim';
|
||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import { AmbientLight, Color, DirectionalLight, HemisphereLight, Raycaster, Scene, Vector2, WebGLRenderer } from 'three';
|
||||||
|
import { CSS2DRenderer } from 'three/addons/renderers/CSS2DRenderer.js';
|
||||||
|
import type { SceneAt, UnitAt } from './frames.ts';
|
||||||
|
import type { MapLayer } from './mapLayer.ts';
|
||||||
|
import { CameraRig, type ViewMode } from './three/cameraRig.ts';
|
||||||
|
import { buildMapMeshes, setTerrainImage, type MapMeshes } from './three/mapMeshes.ts';
|
||||||
|
import { Overlays, type Layers } from './three/overlays.ts';
|
||||||
|
import { TankPool } from './three/tanks.ts';
|
||||||
|
|
||||||
|
export interface MapLook {
|
||||||
|
readonly view: ViewMode;
|
||||||
|
/** Drape the navigation mesh image over the terrain instead of height colours. */
|
||||||
|
readonly navImage: boolean;
|
||||||
|
readonly objects: boolean;
|
||||||
|
readonly crushable: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
readonly mapScene: MapScene | undefined;
|
||||||
|
readonly nav: MapLayer | undefined;
|
||||||
|
readonly battle: TraceBattle | undefined;
|
||||||
|
readonly scene: SceneAt | undefined;
|
||||||
|
readonly selected: string | undefined;
|
||||||
|
readonly layers: Layers;
|
||||||
|
readonly look: MapLook;
|
||||||
|
readonly onSelect: (eid: string | undefined) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface World {
|
||||||
|
readonly renderer: WebGLRenderer;
|
||||||
|
readonly labels: CSS2DRenderer;
|
||||||
|
readonly scene: Scene;
|
||||||
|
readonly rig: CameraRig;
|
||||||
|
map: MapMeshes | undefined;
|
||||||
|
tanks: TankPool;
|
||||||
|
overlays: Overlays;
|
||||||
|
selected: string | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CRUSHABLE_KIND = 3;
|
||||||
|
const CLICK_PX = 4;
|
||||||
|
|
||||||
|
function labelOf(u: UnitAt): string {
|
||||||
|
const name = u.bot !== undefined ? (BEHAVIOR_NAMES[u.bot.behavior] ?? '?') : u.unit.human ? 'player' : '';
|
||||||
|
return `${u.unit.eid.replace(/^0x/, '')} ${name}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createWorld(host: HTMLDivElement): World {
|
||||||
|
const renderer = new WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true });
|
||||||
|
renderer.setPixelRatio(window.devicePixelRatio);
|
||||||
|
host.appendChild(renderer.domElement);
|
||||||
|
const labels = new CSS2DRenderer();
|
||||||
|
labels.domElement.className = 'labels3d';
|
||||||
|
host.appendChild(labels.domElement);
|
||||||
|
const scene = new Scene();
|
||||||
|
scene.background = new Color(0x0b0c0d);
|
||||||
|
scene.add(new HemisphereLight(0xdfe8ff, 0x3a3326, 1.4), new AmbientLight(0xffffff, 0.25));
|
||||||
|
const sun = new DirectionalLight(0xffffff, 1.6);
|
||||||
|
sun.position.set(0.5, 1, 0.3);
|
||||||
|
scene.add(sun);
|
||||||
|
const tanks = new TankPool(undefined);
|
||||||
|
const overlays = new Overlays(tanks);
|
||||||
|
scene.add(tanks.group, overlays.group);
|
||||||
|
return { renderer, labels, scene, rig: new CameraRig(renderer.domElement), map: undefined, tanks, overlays, selected: undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
function replaceMap(w: World, mapScene: MapScene | undefined, nav: MapLayer | undefined): void {
|
||||||
|
if (w.map !== undefined) { w.scene.remove(w.map.group); w.map.dispose(); }
|
||||||
|
w.scene.remove(w.tanks.group, w.overlays.group);
|
||||||
|
w.tanks.dispose();
|
||||||
|
w.overlays.dispose();
|
||||||
|
w.map = mapScene === undefined ? undefined : buildMapMeshes(mapScene, nav);
|
||||||
|
w.tanks = new TankPool(mapScene?.terrain);
|
||||||
|
w.overlays = new Overlays(w.tanks);
|
||||||
|
if (w.map !== undefined) w.scene.add(w.map.group);
|
||||||
|
w.scene.add(w.tanks.group, w.overlays.group);
|
||||||
|
if (mapScene !== undefined) {
|
||||||
|
const t = mapScene.terrain;
|
||||||
|
let sum = 0;
|
||||||
|
for (const h of t.heights) sum += h;
|
||||||
|
w.rig.fit(mapScene.boundsMin[0], mapScene.boundsMin[1], mapScene.boundsMax[0], mapScene.boundsMax[1], sum / Math.max(1, t.heights.length));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Map3D({ mapScene, nav, battle, scene, selected, layers, look, onSelect }: Props): React.JSX.Element {
|
||||||
|
const hostRef = useRef<HTMLDivElement>(null);
|
||||||
|
const worldRef = useRef<World | undefined>(undefined);
|
||||||
|
const onSelectRef = useRef(onSelect);
|
||||||
|
onSelectRef.current = onSelect;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const host = hostRef.current;
|
||||||
|
if (host === null) return;
|
||||||
|
const w = createWorld(host);
|
||||||
|
worldRef.current = w;
|
||||||
|
const resize = (): void => {
|
||||||
|
const r = host.getBoundingClientRect();
|
||||||
|
w.renderer.setSize(r.width, r.height);
|
||||||
|
w.labels.setSize(r.width, r.height);
|
||||||
|
w.rig.resize(r.width, r.height);
|
||||||
|
};
|
||||||
|
const obs = new ResizeObserver(resize);
|
||||||
|
obs.observe(host);
|
||||||
|
resize();
|
||||||
|
w.renderer.setAnimationLoop(() => {
|
||||||
|
w.rig.tick(w.selected === undefined ? undefined : w.tanks.get(w.selected));
|
||||||
|
w.renderer.render(w.scene, w.rig.camera);
|
||||||
|
w.labels.render(w.scene, w.rig.camera);
|
||||||
|
});
|
||||||
|
const down = new Vector2();
|
||||||
|
const el = w.renderer.domElement;
|
||||||
|
const onDown = (e: PointerEvent): void => { down.set(e.clientX, e.clientY); };
|
||||||
|
const onUp = (e: PointerEvent): void => {
|
||||||
|
if (e.button !== 0 || Math.hypot(e.clientX - down.x, e.clientY - down.y) > CLICK_PX) return;
|
||||||
|
const r = el.getBoundingClientRect();
|
||||||
|
const ray = new Raycaster();
|
||||||
|
ray.setFromCamera(new Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), w.rig.camera);
|
||||||
|
const hit = ray.intersectObjects(w.tanks.pickables(), false)[0];
|
||||||
|
onSelectRef.current(hit?.object.userData['eid'] as string | undefined);
|
||||||
|
};
|
||||||
|
el.addEventListener('pointerdown', onDown);
|
||||||
|
el.addEventListener('pointerup', onUp);
|
||||||
|
return () => {
|
||||||
|
obs.disconnect();
|
||||||
|
el.removeEventListener('pointerdown', onDown);
|
||||||
|
el.removeEventListener('pointerup', onUp);
|
||||||
|
w.renderer.setAnimationLoop(null);
|
||||||
|
replaceMap(w, undefined, undefined);
|
||||||
|
w.rig.dispose();
|
||||||
|
w.renderer.dispose();
|
||||||
|
host.replaceChildren();
|
||||||
|
worldRef.current = undefined;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const w = worldRef.current;
|
||||||
|
if (w !== undefined) replaceMap(w, mapScene, nav);
|
||||||
|
// The navigation image is applied by the effect below; only a new level rebuilds the map.
|
||||||
|
}, [mapScene]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const w = worldRef.current;
|
||||||
|
if (w?.map !== undefined) setTerrainImage(w.map, look.navImage ? nav : undefined);
|
||||||
|
}, [nav, look.navImage, mapScene]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const w = worldRef.current;
|
||||||
|
if (w?.map === undefined) return;
|
||||||
|
w.map.kinds.forEach((g, k) => { g.visible = look.objects && (k !== CRUSHABLE_KIND || look.crushable); });
|
||||||
|
}, [look.objects, look.crushable, mapScene]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
worldRef.current?.rig.setMode(look.view);
|
||||||
|
}, [look.view]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const w = worldRef.current;
|
||||||
|
if (w === undefined) return;
|
||||||
|
w.selected = selected;
|
||||||
|
w.rig.refollow();
|
||||||
|
}, [selected]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const w = worldRef.current;
|
||||||
|
if (w === undefined || battle === undefined || scene === undefined) return;
|
||||||
|
w.tanks.update(scene.units, selected, (u) => (layers.labels && u.unit.alive ? labelOf(u) : undefined));
|
||||||
|
w.overlays.update(battle, scene, layers);
|
||||||
|
}, [battle, scene, selected, layers, mapScene]);
|
||||||
|
|
||||||
|
return <div ref={hostRef} className="map3d" />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
/**
|
||||||
|
* Playback controls and, for the selected bot, three strips over the whole battle: its behavior,
|
||||||
|
* the reason it did not fire, and why its turret pointed where it did. Click a strip to seek.
|
||||||
|
*/
|
||||||
|
import type { TraceBattle } from '@wto/ground-sim';
|
||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import { BEHAVIOR_COLORS, DENY_COLORS, LOOK_COLORS } from './labels.ts';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
readonly battle: TraceBattle;
|
||||||
|
readonly t: number;
|
||||||
|
readonly playing: boolean;
|
||||||
|
readonly speed: number;
|
||||||
|
readonly selected: string | undefined;
|
||||||
|
readonly onSeek: (t: number) => void;
|
||||||
|
readonly onPlaying: (playing: boolean) => void;
|
||||||
|
readonly onSpeed: (speed: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SPEEDS = [0.5, 1, 2, 4, 8, 16];
|
||||||
|
const STRIP_H = 10;
|
||||||
|
|
||||||
|
function drawStrips(canvas: HTMLCanvasElement, battle: TraceBattle, eid: string | undefined, t: number): void {
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
if (ctx === null) return;
|
||||||
|
const w = canvas.width;
|
||||||
|
const span = Math.max(1, battle.endT - battle.startT);
|
||||||
|
ctx.fillStyle = '#16181a';
|
||||||
|
ctx.fillRect(0, 0, w, canvas.height);
|
||||||
|
if (eid !== undefined) {
|
||||||
|
const frames = battle.frames;
|
||||||
|
for (let i = 0; i < frames.length; i++) {
|
||||||
|
const f = frames[i];
|
||||||
|
const bot = f?.bots.get(eid);
|
||||||
|
if (f === undefined || bot === undefined) continue;
|
||||||
|
const x0 = ((f.t - battle.startT) / span) * w;
|
||||||
|
const x1 = (((frames[i + 1]?.t ?? f.t + 0.5) - battle.startT) / span) * w;
|
||||||
|
const bw = Math.max(1, x1 - x0);
|
||||||
|
ctx.fillStyle = BEHAVIOR_COLORS[bot.behavior] ?? '#444';
|
||||||
|
ctx.fillRect(x0, 0, bw, STRIP_H);
|
||||||
|
ctx.fillStyle = DENY_COLORS[bot.deny] ?? '#444';
|
||||||
|
ctx.fillRect(x0, STRIP_H + 2, bw, STRIP_H);
|
||||||
|
ctx.fillStyle = LOOK_COLORS[bot.lookReason] ?? '#444';
|
||||||
|
ctx.fillRect(x0, 2 * (STRIP_H + 2), bw, STRIP_H);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const cx = ((t - battle.startT) / span) * w;
|
||||||
|
ctx.fillStyle = '#fff';
|
||||||
|
ctx.fillRect(cx - 1, 0, 2, canvas.height);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Timeline({ battle, t, playing, speed, selected, onSeek, onPlaying, onSpeed }: Props): React.JSX.Element {
|
||||||
|
const stripRef = useRef<HTMLCanvasElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
const c = stripRef.current;
|
||||||
|
if (c === null) return;
|
||||||
|
c.width = Math.max(1, Math.floor(c.getBoundingClientRect().width));
|
||||||
|
drawStrips(c, battle, selected, t);
|
||||||
|
}, [battle, selected, t]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="timeline">
|
||||||
|
<div className="controls">
|
||||||
|
<button type="button" onClick={() => onPlaying(!playing)}>{playing ? '暂停' : '播放'}</button>
|
||||||
|
<select value={speed} onChange={(e) => onSpeed(Number(e.target.value))}>
|
||||||
|
{SPEEDS.map((s) => <option key={s} value={s}>{s}×</option>)}
|
||||||
|
</select>
|
||||||
|
<span className="time">{t.toFixed(1)} s / {battle.endT.toFixed(0)} s</span>
|
||||||
|
<input
|
||||||
|
type="range" min={battle.startT} max={battle.endT} step={0.1} value={t}
|
||||||
|
onChange={(e) => onSeek(Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="strip-labels"><span>行为</span><span>拒绝开火</span><span>炮塔依据</span></div>
|
||||||
|
<canvas
|
||||||
|
ref={stripRef}
|
||||||
|
className="strips"
|
||||||
|
height={3 * (STRIP_H + 2)}
|
||||||
|
onClick={(e) => {
|
||||||
|
const w = e.currentTarget.width;
|
||||||
|
onSeek(battle.startT + (e.nativeEvent.offsetX / w) * (battle.endT - battle.startT));
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
/** Loading maps and logs through the lab's dev-server API (server/lab-api.ts). */
|
||||||
|
import {
|
||||||
|
decodeMapScene, parsePois, parseTraceLog, readNavPack, type MapPois, type MapScene, type NavPack, type TraceBattle,
|
||||||
|
} from '@wto/ground-sim';
|
||||||
|
|
||||||
|
export interface LogEntry {
|
||||||
|
readonly name: string;
|
||||||
|
readonly size: number;
|
||||||
|
readonly mtime: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MapEntry {
|
||||||
|
readonly level: string;
|
||||||
|
readonly pois: boolean;
|
||||||
|
/** The level's geometry is there, so it has a 3D map. */
|
||||||
|
readonly scene: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MapData {
|
||||||
|
readonly pack: NavPack;
|
||||||
|
readonly pois: MapPois | undefined;
|
||||||
|
readonly scene: MapScene | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function get(url: string): Promise<Response> {
|
||||||
|
const res = await fetch(url);
|
||||||
|
if (!res.ok) {
|
||||||
|
const body = await res.text();
|
||||||
|
throw new Error(`${url}: ${res.status} ${body}`);
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchMaps(): Promise<MapEntry[]> {
|
||||||
|
return (await (await get('/api/maps')).json()) as MapEntry[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchLogs(): Promise<LogEntry[]> {
|
||||||
|
return (await (await get('/api/logs')).json()) as LogEntry[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadLog(name: string): Promise<TraceBattle[]> {
|
||||||
|
const text = await (await get(`/api/logs/text?name=${encodeURIComponent(name)}`)).text();
|
||||||
|
return parseTraceLog(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadMap(entry: MapEntry): Promise<MapData> {
|
||||||
|
const bytes = new Uint8Array(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.wtonav`)}`)).arrayBuffer());
|
||||||
|
const pois = entry.pois
|
||||||
|
? parsePois(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.pois.json`)}`)).text())
|
||||||
|
: undefined;
|
||||||
|
const scene = entry.scene
|
||||||
|
? decodeMapScene(new Uint8Array(await (await get(`/api/scene?name=${encodeURIComponent(entry.level)}`)).arrayBuffer()))
|
||||||
|
: undefined;
|
||||||
|
return { pack: readNavPack(bytes), pois, scene };
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
/** Looking up the battle state at any time between two trace samples. */
|
||||||
|
import type { BotSample, CapSample, TraceBattle, TraceEvent, UnitSample } from '@wto/ground-sim';
|
||||||
|
|
||||||
|
export interface UnitAt {
|
||||||
|
readonly unit: UnitSample;
|
||||||
|
/** Interpolated position, hull heading, pitch and roll. */
|
||||||
|
readonly x: number;
|
||||||
|
readonly y: number;
|
||||||
|
readonly z: number;
|
||||||
|
readonly yaw: number;
|
||||||
|
readonly hullPitch: number;
|
||||||
|
readonly hullRoll: number;
|
||||||
|
/** Interpolated gun world yaw and pitch; from the bot line, or the hull, when the unit line has none. */
|
||||||
|
readonly gunYaw: number;
|
||||||
|
readonly gunPitch: number;
|
||||||
|
/** Decision state of the sample at or before the time; undefined for players. */
|
||||||
|
readonly bot: BotSample | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SceneAt {
|
||||||
|
readonly t: number;
|
||||||
|
readonly units: Map<string, UnitAt>;
|
||||||
|
readonly caps: CapSample[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Index of the last frame at or before `t` (-1 before the first). */
|
||||||
|
export function frameIndexAt(battle: TraceBattle, t: number): number {
|
||||||
|
let lo = 0;
|
||||||
|
let hi = battle.frames.length - 1;
|
||||||
|
let found = -1;
|
||||||
|
while (lo <= hi) {
|
||||||
|
const mid = (lo + hi) >> 1;
|
||||||
|
if ((battle.frames[mid]?.t ?? Infinity) <= t) { found = mid; lo = mid + 1; } else hi = mid - 1;
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
function lerpYaw(a: number, b: number, k: number): number {
|
||||||
|
const d = ((((b - a) % 360) + 540) % 360) - 180;
|
||||||
|
return a + d * k;
|
||||||
|
}
|
||||||
|
|
||||||
|
function lerp(a: number, b: number | undefined, k: number): number {
|
||||||
|
return a + ((b ?? a) - a) * k;
|
||||||
|
}
|
||||||
|
|
||||||
|
function gunOf(u: UnitSample, bot: BotSample | undefined): [number, number] {
|
||||||
|
return [u.gunYaw ?? bot?.gunYaw ?? u.yaw, u.gunPitch ?? 0];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sceneAt(battle: TraceBattle, t: number): SceneAt {
|
||||||
|
const i = Math.max(0, frameIndexAt(battle, t));
|
||||||
|
const a = battle.frames[i];
|
||||||
|
const b = battle.frames[i + 1];
|
||||||
|
const units = new Map<string, UnitAt>();
|
||||||
|
if (a === undefined) return { t, units, caps: [] };
|
||||||
|
const k = b !== undefined && b.t > a.t ? Math.min(1, Math.max(0, (t - a.t) / (b.t - a.t))) : 0;
|
||||||
|
for (const [eid, ua] of a.units) {
|
||||||
|
const ub = b?.units.get(eid);
|
||||||
|
const move = ub !== undefined && ua.alive && ub.alive ? k : 0;
|
||||||
|
const bot = a.bots.get(eid);
|
||||||
|
const [gyA, gpA] = gunOf(ua, bot);
|
||||||
|
const [gyB, gpB] = ub !== undefined ? gunOf(ub, b?.bots.get(eid)) : [gyA, gpA];
|
||||||
|
units.set(eid, {
|
||||||
|
unit: ua,
|
||||||
|
x: lerp(ua.x, ub?.x, move),
|
||||||
|
y: lerp(ua.y, ub?.y, move),
|
||||||
|
z: lerp(ua.z, ub?.z, move),
|
||||||
|
yaw: lerpYaw(ua.yaw, ub?.yaw ?? ua.yaw, move),
|
||||||
|
hullPitch: lerp(ua.hullPitch ?? 0, ub?.hullPitch, move),
|
||||||
|
hullRoll: lerp(ua.hullRoll ?? 0, ub?.hullRoll, move),
|
||||||
|
gunYaw: lerpYaw(gyA, gyB, move),
|
||||||
|
gunPitch: lerp(gpA, gpB, move),
|
||||||
|
bot,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { t, units, caps: a.caps };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Events with time in [from, to], from the sorted event list. */
|
||||||
|
export function eventsBetween(battle: TraceBattle, from: number, to: number): TraceEvent[] {
|
||||||
|
let lo = 0;
|
||||||
|
let hi = battle.events.length;
|
||||||
|
while (lo < hi) {
|
||||||
|
const mid = (lo + hi) >> 1;
|
||||||
|
if ((battle.events[mid]?.t ?? Infinity) < from) lo = mid + 1; else hi = mid;
|
||||||
|
}
|
||||||
|
const out: TraceEvent[] = [];
|
||||||
|
for (let i = lo; i < battle.events.length; i++) {
|
||||||
|
const e = battle.events[i];
|
||||||
|
if (e === undefined || e.t > to) break;
|
||||||
|
out.push(e);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
/** Chinese display names for the trace codes (the codes themselves are in @wto/ground-sim). */
|
||||||
|
|
||||||
|
export const BEHAVIOR_ZH = ['推进', '交战推进', '短停', '回掩体', '换位', '守位', '疏散', '撤回', '维修'] as const;
|
||||||
|
|
||||||
|
export const BEHAVIOR_COLORS = ['#6c8ebf', '#e0884a', '#e5d34a', '#8fbf6c', '#b07cc6', '#5fb8b0', '#9a9a9a', '#c65f5f', '#7a5a3a'] as const;
|
||||||
|
|
||||||
|
export const STATE_ZH: Readonly<Record<number, string>> = {
|
||||||
|
0: '行军', 1: '行进交战', 3: '短停', 4: '退入掩体', 5: '掩体装填', 7: '原地守位', 8: '换位',
|
||||||
|
9: '失能', 10: '疏散', 11: '坡脊撤回',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const DENY_ZH = [
|
||||||
|
'放行', '无目标', '炮未就绪', '命中概率不足', '远距窗口不足', '瞄准误差', '等待炮管稳定', '检查预算',
|
||||||
|
'炮口有硬物', '弹道有硬物', '友军', '多炮检查', '射界外', '点射间歇',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export const DENY_COLORS = [
|
||||||
|
'#4caf50', '#333', '#666', '#e53935', '#8e24aa', '#fb8c00', '#fdd835', '#90a4ae',
|
||||||
|
'#6d4c41', '#795548', '#03a9f4', '#9e9e9e', '#d81b60', '#26a69a',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export const LOOK_ZH = ['—', '交战目标', '威胁', '目标消失处', '记忆位置', '线索', '扫视'] as const;
|
||||||
|
|
||||||
|
export const LOOK_COLORS = ['#333', '#e53935', '#fb8c00', '#fdd835', '#8e24aa', '#03a9f4', '#607d8b'] as const;
|
||||||
|
|
||||||
|
export const COMMAND_ZH = ['主攻', '侧翼', '架枪', '防守', '预备', '防空'] as const;
|
||||||
|
|
||||||
|
export const URGENCY_ZH = ['低', '中', '高'] as const;
|
||||||
|
|
||||||
|
export const LANE_ZH = ['中路', '左翼', '右翼'] as const;
|
||||||
|
|
||||||
|
export const CLASS_ZH = ['中坦', '轻坦', '重坦', '歼击车', '防空'] as const;
|
||||||
|
|
||||||
|
export function zh(names: readonly string[] | Readonly<Record<number, string>>, code: number): string {
|
||||||
|
const name = Array.isArray(names) ? names[code] : (names as Readonly<Record<number, string>>)[code];
|
||||||
|
return name ?? String(code);
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { StrictMode } from 'react';
|
||||||
|
import { createRoot } from 'react-dom/client';
|
||||||
|
import { App } from './App.tsx';
|
||||||
|
import './style.css';
|
||||||
|
|
||||||
|
const root = document.getElementById('root');
|
||||||
|
if (root !== null) createRoot(root).render(<StrictMode><App /></StrictMode>);
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
/**
|
||||||
|
* The navigation image draped over the 3D terrain, drawn once into an offscreen canvas: walkable polygons of one mesh tier coloured
|
||||||
|
* by surface, optionally the tactical grid's exposure and the baked cover points.
|
||||||
|
*/
|
||||||
|
import { NAV_AREA_NAMES, type NavPack } from '@wto/ground-sim';
|
||||||
|
|
||||||
|
export interface MapLayer {
|
||||||
|
readonly canvas: HTMLCanvasElement;
|
||||||
|
/** World x of the canvas's left edge and world z of its top edge. */
|
||||||
|
readonly x0: number;
|
||||||
|
readonly z1: number;
|
||||||
|
readonly pxPerM: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MapLayerOptions {
|
||||||
|
readonly tier: number;
|
||||||
|
readonly exposure: boolean;
|
||||||
|
readonly covers: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AREA_COLORS: Readonly<Record<string, string>> = {
|
||||||
|
road: '#77786a', bridge: '#a0a090', ground: '#3d4a33', rough: '#5a4d34', forest: '#29402a',
|
||||||
|
crushable: '#4f5f35', shallowWater: '#35607a', chokepoint: '#7a6a35', exposed: '#5f5f33',
|
||||||
|
deepWater: '#1d3a66', noGo: '#3a2626',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function buildMapLayer(pack: NavPack, opts: MapLayerOptions): MapLayer {
|
||||||
|
const [x0, , z0] = pack.header.bmin;
|
||||||
|
const [x1, , z1] = pack.header.bmax;
|
||||||
|
const pxPerM = Math.min(2, 4096 / Math.max(x1 - x0, z1 - z0));
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
canvas.width = Math.ceil((x1 - x0) * pxPerM);
|
||||||
|
canvas.height = Math.ceil((z1 - z0) * pxPerM);
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
if (ctx === null) return { canvas, x0, z1, pxPerM };
|
||||||
|
// Off the mesh (buildings, steep or blocked ground) when draped over the 3D terrain.
|
||||||
|
ctx.fillStyle = '#55584f';
|
||||||
|
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||||
|
const tier = pack.tiers[opts.tier] ?? pack.tiers[1];
|
||||||
|
if (tier !== undefined) {
|
||||||
|
for (let area = 1; area < NAV_AREA_NAMES.length; area++) {
|
||||||
|
ctx.beginPath();
|
||||||
|
for (let i = 0; i < tier.polyCount; i++) {
|
||||||
|
if (tier.areas[i] !== area) continue;
|
||||||
|
const ring = tier.rings[i];
|
||||||
|
if (ring === undefined) continue;
|
||||||
|
for (let k = 0; k < ring.length; k += 2) {
|
||||||
|
const px = ((ring[k] ?? 0) - x0) * pxPerM;
|
||||||
|
const py = (z1 - (ring[k + 1] ?? 0)) * pxPerM;
|
||||||
|
if (k === 0) ctx.moveTo(px, py);
|
||||||
|
else ctx.lineTo(px, py);
|
||||||
|
}
|
||||||
|
ctx.closePath();
|
||||||
|
}
|
||||||
|
ctx.fillStyle = AREA_COLORS[NAV_AREA_NAMES[area] ?? ''] ?? '#444';
|
||||||
|
ctx.fill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (opts.exposure) drawExposure(ctx, pack, x0, z1, pxPerM);
|
||||||
|
if (opts.covers) drawCovers(ctx, pack, x0, z1, pxPerM);
|
||||||
|
return { canvas, x0, z1, pxPerM };
|
||||||
|
}
|
||||||
|
|
||||||
|
function drawExposure(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void {
|
||||||
|
const g = pack.tactical;
|
||||||
|
const cell = g.cellM * pxPerM;
|
||||||
|
for (let r = 0; r < g.rows; r++) {
|
||||||
|
for (let c = 0; c < g.cols; c++) {
|
||||||
|
const e = g.exposure[r * g.cols + c] ?? 0;
|
||||||
|
if (e < 16) continue;
|
||||||
|
ctx.fillStyle = `rgba(255, 80, 40, ${(e / 255) * 0.45})`;
|
||||||
|
const wx = g.origin[0] + c * g.cellM;
|
||||||
|
const wz = g.origin[1] + r * g.cellM;
|
||||||
|
ctx.fillRect((wx - x0) * pxPerM, (z1 - wz - g.cellM) * pxPerM, cell, cell);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function drawCovers(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void {
|
||||||
|
for (const cv of pack.covers) {
|
||||||
|
const px = (cv.pos[0] - x0) * pxPerM;
|
||||||
|
const py = (z1 - cv.pos[2]) * pxPerM;
|
||||||
|
ctx.strokeStyle = cv.kind === 1 ? 'rgba(120, 220, 255, 0.8)' : 'rgba(255, 230, 120, 0.8)';
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(px, py);
|
||||||
|
ctx.lineTo(px + cv.coverDir[0] * 6 * pxPerM, py - cv.coverDir[1] * 6 * pxPerM);
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
* { box-sizing: border-box; }
|
||||||
|
html, body, #root { margin: 0; height: 100%; background: #0b0c0d; color: #ddd; font: 13px/1.4 system-ui, 'Microsoft YaHei', sans-serif; }
|
||||||
|
.app { display: flex; flex-direction: column; height: 100%; }
|
||||||
|
header { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding: 6px 10px; background: #16181a; border-bottom: 1px solid #2a2d30; }
|
||||||
|
header select { max-width: 420px; }
|
||||||
|
header label { display: inline-flex; align-items: center; gap: 3px; }
|
||||||
|
.status { color: #ffb74d; }
|
||||||
|
main { flex: 1; display: flex; min-height: 0; }
|
||||||
|
.map3d { flex: 1; min-width: 0; height: 100%; position: relative; overflow: hidden; }
|
||||||
|
.map3d canvas { display: block; }
|
||||||
|
.labels3d { position: absolute; inset: 0; pointer-events: none; }
|
||||||
|
.tank-label { color: rgba(255,255,255,0.9); font-size: 11px; text-shadow: 0 0 3px #000; white-space: nowrap; }
|
||||||
|
.tank-label.human { color: #ffe14a; }
|
||||||
|
.inspector { width: 360px; overflow-y: auto; padding: 8px 10px; background: #121416; border-left: 1px solid #2a2d30; }
|
||||||
|
.inspector table { width: 100%; border-collapse: collapse; }
|
||||||
|
.inspector th { text-align: left; color: #999; font-weight: normal; padding: 2px 8px 2px 0; white-space: nowrap; vertical-align: top; }
|
||||||
|
.inspector td { padding: 2px 0; }
|
||||||
|
.inspector h4 { margin: 12px 0 4px; color: #aaa; font-weight: normal; }
|
||||||
|
.hint { color: #999; }
|
||||||
|
.events { font-size: 12px; }
|
||||||
|
.events div { padding: 1px 0; border-bottom: 1px solid #1d2023; word-break: break-all; }
|
||||||
|
.events span { color: #999; }
|
||||||
|
.legend { display: flex; flex-wrap: wrap; gap: 4px 10px; font-size: 12px; }
|
||||||
|
.legend i { display: inline-block; width: 10px; height: 10px; margin-right: 3px; vertical-align: -1px; }
|
||||||
|
.timeline { padding: 6px 10px; background: #16181a; border-top: 1px solid #2a2d30; }
|
||||||
|
.controls { display: flex; gap: 8px; align-items: center; }
|
||||||
|
.controls input[type='range'] { flex: 1; }
|
||||||
|
.time { min-width: 120px; font-variant-numeric: tabular-nums; }
|
||||||
|
.strip-labels { display: flex; gap: 12px; font-size: 11px; color: #888; margin-top: 4px; }
|
||||||
|
canvas.strips { width: 100%; height: 36px; display: block; cursor: pointer; }
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
/**
|
||||||
|
* The 3D view's cameras: a top-down orthographic map view (world +z up the screen, like the old
|
||||||
|
* flat map), a free perspective view, a view that follows the selected vehicle, and a view out of
|
||||||
|
* its muzzle along the barrel.
|
||||||
|
*/
|
||||||
|
import { OrthographicCamera, PerspectiveCamera, Quaternion, Vector3, type Camera } from 'three';
|
||||||
|
import { MapControls } from 'three/addons/controls/MapControls.js';
|
||||||
|
import type { Tank } from './tanks.ts';
|
||||||
|
|
||||||
|
export type ViewMode = 'top' | 'free' | 'follow' | 'gun';
|
||||||
|
|
||||||
|
const TOP_HEIGHT = 3000;
|
||||||
|
/** Top-down camera sits this far south of its target, so the controls keep north up. */
|
||||||
|
const TOP_SOUTH = 0.01;
|
||||||
|
const FREE_MAX_POLAR = Math.PI * 0.49;
|
||||||
|
|
||||||
|
export class CameraRig {
|
||||||
|
readonly persp = new PerspectiveCamera(50, 1, 0.5, 20000);
|
||||||
|
readonly ortho = new OrthographicCamera(-1, 1, 1, -1, 1, 10000);
|
||||||
|
readonly controls: MapControls;
|
||||||
|
private mode: ViewMode = 'top';
|
||||||
|
private aspect = 1;
|
||||||
|
private readonly lastFollow = new Vector3();
|
||||||
|
private following = false;
|
||||||
|
|
||||||
|
constructor(dom: HTMLElement) {
|
||||||
|
this.controls = new MapControls(this.ortho, dom);
|
||||||
|
this.controls.enableDamping = true;
|
||||||
|
this.controls.dampingFactor = 0.15;
|
||||||
|
this.controls.screenSpacePanning = true;
|
||||||
|
this.limitTilt();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Top-down stays straight down; the other views may tilt down to just above the horizon. */
|
||||||
|
private limitTilt(): void {
|
||||||
|
this.controls.maxPolarAngle = this.mode === 'top' ? 0 : FREE_MAX_POLAR;
|
||||||
|
}
|
||||||
|
|
||||||
|
get camera(): Camera {
|
||||||
|
return this.mode === 'top' ? this.ortho : this.persp;
|
||||||
|
}
|
||||||
|
|
||||||
|
resize(w: number, h: number): void {
|
||||||
|
this.aspect = w / Math.max(1, h);
|
||||||
|
this.persp.aspect = this.aspect;
|
||||||
|
this.persp.updateProjectionMatrix();
|
||||||
|
const half = (this.ortho.top - this.ortho.bottom) / 2;
|
||||||
|
this.ortho.left = -half * this.aspect;
|
||||||
|
this.ortho.right = half * this.aspect;
|
||||||
|
this.ortho.updateProjectionMatrix();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Frames the world rectangle (x, z) in both cameras. */
|
||||||
|
fit(minX: number, minZ: number, maxX: number, maxZ: number, groundY: number): void {
|
||||||
|
const cx = (minX + maxX) / 2;
|
||||||
|
const cz = -(minZ + maxZ) / 2;
|
||||||
|
const half = (Math.max((maxX - minX) / this.aspect, maxZ - minZ) / 2) * 1.05;
|
||||||
|
Object.assign(this.ortho, { left: -half * this.aspect, right: half * this.aspect, top: half, bottom: -half, zoom: 1 });
|
||||||
|
this.ortho.updateProjectionMatrix();
|
||||||
|
this.ortho.position.set(cx, groundY + TOP_HEIGHT, cz + TOP_SOUTH);
|
||||||
|
this.persp.position.set(cx, groundY + half * 0.9, cz + half * 1.1);
|
||||||
|
this.controls.target.set(cx, groundY, cz);
|
||||||
|
this.ortho.lookAt(this.controls.target);
|
||||||
|
this.persp.lookAt(this.controls.target);
|
||||||
|
this.controls.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
setMode(mode: ViewMode): void {
|
||||||
|
if (mode === this.mode) return;
|
||||||
|
const target = this.controls.target.clone();
|
||||||
|
if (this.mode === 'top' && mode !== 'gun') {
|
||||||
|
const span = (this.ortho.top - this.ortho.bottom) / this.ortho.zoom;
|
||||||
|
this.persp.position.set(target.x, target.y + span * 0.6, target.z + span * 0.6);
|
||||||
|
}
|
||||||
|
if (mode === 'top') this.ortho.position.set(target.x, target.y + TOP_HEIGHT, target.z + TOP_SOUTH);
|
||||||
|
this.mode = mode;
|
||||||
|
this.limitTilt();
|
||||||
|
this.following = false;
|
||||||
|
this.controls.object = this.camera;
|
||||||
|
this.controls.enableRotate = mode !== 'top';
|
||||||
|
this.controls.enabled = mode !== 'gun';
|
||||||
|
this.camera.lookAt(target);
|
||||||
|
this.controls.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The next follow frame starts over around the (newly) selected vehicle. */
|
||||||
|
refollow(): void {
|
||||||
|
this.following = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Per frame: keeps the followed vehicle centred, or puts the camera at the muzzle. */
|
||||||
|
tick(tank: Tank | undefined): void {
|
||||||
|
if (this.mode === 'follow' && tank !== undefined && tank.root.visible) {
|
||||||
|
const at = tank.root.position;
|
||||||
|
if (!this.following) {
|
||||||
|
this.controls.target.copy(at);
|
||||||
|
this.persp.position.set(at.x - 25, at.y + 15, at.z + 25);
|
||||||
|
this.following = true;
|
||||||
|
} else {
|
||||||
|
const d = at.clone().sub(this.lastFollow);
|
||||||
|
this.controls.target.add(d);
|
||||||
|
this.persp.position.add(d);
|
||||||
|
}
|
||||||
|
this.lastFollow.copy(at);
|
||||||
|
} else if (this.mode === 'gun' && tank !== undefined && tank.root.visible) {
|
||||||
|
const q = tank.barrel.getWorldQuaternion(new Quaternion());
|
||||||
|
const dir = new Vector3(1, 0, 0).applyQuaternion(q);
|
||||||
|
const tip = tank.barrel.getWorldPosition(new Vector3()).addScaledVector(dir, tank.length * 0.8);
|
||||||
|
this.persp.position.copy(tip);
|
||||||
|
this.persp.lookAt(tip.clone().add(dir));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.controls.enabled) this.controls.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
this.controls.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
/**
|
||||||
|
* Game world to three.js: Dagor is left-handed with Y up, three.js right-handed, so world z is
|
||||||
|
* mirrored (three z = -world z). A world heading (degrees of atan2(z, x)) then becomes the same
|
||||||
|
* angle of rotation about three's +Y, and a model's local +X is its front, +Y up, -Z its left.
|
||||||
|
*/
|
||||||
|
import { Vector3 } from 'three';
|
||||||
|
|
||||||
|
export const DEG = Math.PI / 180;
|
||||||
|
|
||||||
|
export function toThree(x: number, y: number, z: number, out: Vector3 = new Vector3()): Vector3 {
|
||||||
|
return out.set(x, y, -z);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Three.js direction of a world heading and pitch, in degrees. */
|
||||||
|
export function dirOf(yawDeg: number, pitchDeg: number, out: Vector3 = new Vector3()): Vector3 {
|
||||||
|
const c = Math.cos(pitchDeg * DEG);
|
||||||
|
return out.set(Math.cos(yawDeg * DEG) * c, Math.sin(pitchDeg * DEG), -Math.sin(yawDeg * DEG) * c);
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
/**
|
||||||
|
* The static 3D map: lit terrain (coloured by height, or draped with the navigation mesh image),
|
||||||
|
* the collision shapes of placed objects coloured by kind, and the water plane.
|
||||||
|
*/
|
||||||
|
import type { MapScene, SceneTerrain } from '@wto/ground-sim';
|
||||||
|
import {
|
||||||
|
BufferAttribute, BufferGeometry, CanvasTexture, Color, DoubleSide, Group, Mesh, MeshLambertMaterial,
|
||||||
|
PlaneGeometry, SRGBColorSpace, type Material,
|
||||||
|
} from 'three';
|
||||||
|
import type { MapLayer } from '../mapLayer.ts';
|
||||||
|
|
||||||
|
/** Colour and opacity per SCENE_KIND_NAMES entry. */
|
||||||
|
const KIND_LOOK: readonly (readonly [number, number])[] = [
|
||||||
|
[0xb9b2a3, 1], [0x7d7a74, 1], [0x9a7b55, 1], [0xe09a4a, 0.4], [0x4f8a3c, 1], [0x6f8aa0, 1],
|
||||||
|
];
|
||||||
|
|
||||||
|
const LOW = new Color(0x3c4a32);
|
||||||
|
const HIGH = new Color(0x9b9171);
|
||||||
|
|
||||||
|
export interface MapMeshes {
|
||||||
|
readonly group: Group;
|
||||||
|
readonly terrain: Mesh<BufferGeometry, MeshLambertMaterial>;
|
||||||
|
/** Objects per scene kind, to switch kinds on and off. */
|
||||||
|
readonly kinds: Group[];
|
||||||
|
dispose(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function terrainGeometry(t: SceneTerrain, nav: MapLayer | undefined): BufferGeometry {
|
||||||
|
const n = t.cols * t.rows;
|
||||||
|
const pos = new Float32Array(n * 3);
|
||||||
|
const col = new Float32Array(n * 3);
|
||||||
|
const uv = new Float32Array(n * 2);
|
||||||
|
let lo = Infinity;
|
||||||
|
let hi = -Infinity;
|
||||||
|
for (const h of t.heights) { lo = Math.min(lo, h); hi = Math.max(hi, h); }
|
||||||
|
const c = new Color();
|
||||||
|
const navW = nav === undefined ? 1 : nav.canvas.width / nav.pxPerM;
|
||||||
|
const navH = nav === undefined ? 1 : nav.canvas.height / nav.pxPerM;
|
||||||
|
for (let r = 0; r < t.rows; r++) {
|
||||||
|
for (let k = 0; k < t.cols; k++) {
|
||||||
|
const i = r * t.cols + k;
|
||||||
|
const x = t.origin[0] + k * t.cellM;
|
||||||
|
const z = t.origin[1] + r * t.cellM;
|
||||||
|
const h = t.heights[i] ?? 0;
|
||||||
|
pos.set([x, h, -z], i * 3);
|
||||||
|
c.lerpColors(LOW, HIGH, hi > lo ? (h - lo) / (hi - lo) : 0);
|
||||||
|
col.set([c.r, c.g, c.b], i * 3);
|
||||||
|
if (nav !== undefined) uv.set([(x - nav.x0) / navW, (z - (nav.z1 - navH)) / navH], i * 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const idx = new Uint32Array((t.cols - 1) * (t.rows - 1) * 6);
|
||||||
|
let at = 0;
|
||||||
|
for (let r = 0; r + 1 < t.rows; r++) {
|
||||||
|
for (let k = 0; k + 1 < t.cols; k++) {
|
||||||
|
const i = r * t.cols + k;
|
||||||
|
idx.set([i, i + 1, i + t.cols, i + 1, i + t.cols + 1, i + t.cols], at);
|
||||||
|
at += 6;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const g = new BufferGeometry();
|
||||||
|
g.setAttribute('position', new BufferAttribute(pos, 3));
|
||||||
|
g.setAttribute('color', new BufferAttribute(col, 3));
|
||||||
|
g.setAttribute('uv', new BufferAttribute(uv, 2));
|
||||||
|
g.setIndex(new BufferAttribute(idx, 1));
|
||||||
|
g.computeVertexNormals();
|
||||||
|
return g;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drapes the navigation image over the terrain, or goes back to height colours. */
|
||||||
|
export function setTerrainImage(m: MapMeshes, nav: MapLayer | undefined): void {
|
||||||
|
const mat = m.terrain.material;
|
||||||
|
mat.map?.dispose();
|
||||||
|
if (nav === undefined) {
|
||||||
|
mat.map = null;
|
||||||
|
mat.vertexColors = true;
|
||||||
|
} else {
|
||||||
|
const tex = new CanvasTexture(nav.canvas);
|
||||||
|
tex.colorSpace = SRGBColorSpace;
|
||||||
|
tex.anisotropy = 8;
|
||||||
|
mat.map = tex;
|
||||||
|
mat.vertexColors = false;
|
||||||
|
}
|
||||||
|
mat.needsUpdate = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function objectKinds(scene: MapScene, materials: Material[]): Group[] {
|
||||||
|
const kinds = KIND_LOOK.map(() => new Group());
|
||||||
|
const mats = KIND_LOOK.map(([color, opacity]) => new MeshLambertMaterial({
|
||||||
|
color, flatShading: true, side: DoubleSide, transparent: opacity < 1, opacity, depthWrite: opacity >= 1,
|
||||||
|
}));
|
||||||
|
materials.push(...mats);
|
||||||
|
for (const m of scene.meshes) {
|
||||||
|
const g = new BufferGeometry();
|
||||||
|
const pos = new Float32Array(m.positions);
|
||||||
|
for (let i = 2; i < pos.length; i += 3) pos[i] = -(pos[i] ?? 0);
|
||||||
|
g.setAttribute('position', new BufferAttribute(pos, 3));
|
||||||
|
g.setIndex(new BufferAttribute(m.indices, 1));
|
||||||
|
g.computeBoundingSphere();
|
||||||
|
const mat = mats[m.kind] ?? mats[0];
|
||||||
|
if (mat !== undefined) kinds[m.kind]?.add(new Mesh(g, mat));
|
||||||
|
}
|
||||||
|
return kinds;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildMapMeshes(scene: MapScene, nav: MapLayer | undefined): MapMeshes {
|
||||||
|
const group = new Group();
|
||||||
|
const materials: Material[] = [];
|
||||||
|
const terrainMat = new MeshLambertMaterial({ vertexColors: true });
|
||||||
|
materials.push(terrainMat);
|
||||||
|
const terrain = new Mesh(terrainGeometry(scene.terrain, nav), terrainMat);
|
||||||
|
group.add(terrain);
|
||||||
|
const kinds = objectKinds(scene, materials);
|
||||||
|
for (const k of kinds) group.add(k);
|
||||||
|
if (scene.waterLevel !== undefined) {
|
||||||
|
const w = scene.boundsMax[0] - scene.boundsMin[0];
|
||||||
|
const d = scene.boundsMax[1] - scene.boundsMin[1];
|
||||||
|
const waterMat = new MeshLambertMaterial({ color: 0x2d5f8a, transparent: true, opacity: 0.55, depthWrite: false });
|
||||||
|
materials.push(waterMat);
|
||||||
|
const water = new Mesh(new PlaneGeometry(w, d), waterMat);
|
||||||
|
water.rotation.x = -Math.PI / 2;
|
||||||
|
water.position.set(scene.boundsMin[0] + w / 2, scene.waterLevel, -(scene.boundsMin[1] + d / 2));
|
||||||
|
group.add(water);
|
||||||
|
}
|
||||||
|
const meshes: MapMeshes = {
|
||||||
|
group, terrain, kinds,
|
||||||
|
dispose() {
|
||||||
|
group.traverse((o) => { if (o instanceof Mesh) (o.geometry as BufferGeometry).dispose(); });
|
||||||
|
terrainMat.map?.dispose();
|
||||||
|
for (const m of materials) m.dispose();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if (nav !== undefined) setTerrainImage(meshes, nav);
|
||||||
|
return meshes;
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
/**
|
||||||
|
* What is drawn over the map for one moment, rebuilt every update: goal, target and look lines,
|
||||||
|
* the gun's view cone, recent shots and hits, deaths so far, and the capture zones.
|
||||||
|
*/
|
||||||
|
import type { TraceBattle } from '@wto/ground-sim';
|
||||||
|
import {
|
||||||
|
AdditiveBlending, BufferAttribute, BufferGeometry, Color, DoubleSide, Group, LineBasicMaterial,
|
||||||
|
LineSegments, Mesh, MeshBasicMaterial, Points, PointsMaterial,
|
||||||
|
} from 'three';
|
||||||
|
import { eventsBetween, type SceneAt, type UnitAt } from '../frames.ts';
|
||||||
|
import { DEG } from './coords.ts';
|
||||||
|
import { ARMY_HEX, type TankPool } from './tanks.ts';
|
||||||
|
|
||||||
|
export interface Layers {
|
||||||
|
readonly goals: boolean;
|
||||||
|
readonly links: boolean;
|
||||||
|
readonly cones: boolean;
|
||||||
|
readonly labels: boolean;
|
||||||
|
readonly events: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const GUN_FOV_HALF_DEG = 30;
|
||||||
|
const CONE_M = 120;
|
||||||
|
const CONE_STEPS = 12;
|
||||||
|
const EVENT_WINDOW_SEC = 2;
|
||||||
|
const CAP_STEPS = 64;
|
||||||
|
const WISH_M = 25;
|
||||||
|
|
||||||
|
/** Line segments with per-vertex colour, refilled from scratch on every update. */
|
||||||
|
class Lines {
|
||||||
|
readonly obj: LineSegments;
|
||||||
|
private pos: number[] = [];
|
||||||
|
private col: number[] = [];
|
||||||
|
|
||||||
|
constructor(opacity: number, additive = false) {
|
||||||
|
const mat = new LineBasicMaterial({ vertexColors: true, transparent: true, opacity, depthTest: !additive });
|
||||||
|
if (additive) mat.blending = AdditiveBlending;
|
||||||
|
this.obj = new LineSegments(new BufferGeometry(), mat);
|
||||||
|
this.obj.frustumCulled = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
add(ax: number, ay: number, az: number, bx: number, by: number, bz: number, c: Color): void {
|
||||||
|
this.pos.push(ax, ay, -az, bx, by, -bz);
|
||||||
|
this.col.push(c.r, c.g, c.b, c.r, c.g, c.b);
|
||||||
|
}
|
||||||
|
|
||||||
|
flush(): void {
|
||||||
|
const g = this.obj.geometry;
|
||||||
|
g.setAttribute('position', new BufferAttribute(Float32Array.from(this.pos), 3));
|
||||||
|
g.setAttribute('color', new BufferAttribute(Float32Array.from(this.col), 3));
|
||||||
|
g.computeBoundingSphere();
|
||||||
|
this.pos = [];
|
||||||
|
this.col = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const C = {
|
||||||
|
goal: new Color(0x9aa4ad), target: new Color(0xff4646), targetLost: new Color(0x803030),
|
||||||
|
look: new Color(0xffa028), wish: new Color(0xffe14a), shot: new Color(0xffff78), dead1: new Color(ARMY_HEX[1]),
|
||||||
|
dead2: new Color(ARMY_HEX[2]), cap: new Color(0xdddddd),
|
||||||
|
};
|
||||||
|
|
||||||
|
export class Overlays {
|
||||||
|
readonly group = new Group();
|
||||||
|
private readonly faint = new Lines(0.35);
|
||||||
|
private readonly bold = new Lines(0.9);
|
||||||
|
private readonly shots = new Lines(1, true);
|
||||||
|
private readonly cones: Mesh;
|
||||||
|
private readonly hits: Points;
|
||||||
|
|
||||||
|
constructor(private readonly tanks: TankPool) {
|
||||||
|
this.cones = new Mesh(new BufferGeometry(), new MeshBasicMaterial({
|
||||||
|
color: 0xffffc8, transparent: true, opacity: 0.08, side: DoubleSide, depthWrite: false,
|
||||||
|
}));
|
||||||
|
this.cones.frustumCulled = false;
|
||||||
|
this.hits = new Points(new BufferGeometry(), new PointsMaterial({ size: 6, sizeAttenuation: false, vertexColors: true }));
|
||||||
|
this.hits.frustumCulled = false;
|
||||||
|
this.group.add(this.faint.obj, this.bold.obj, this.shots.obj, this.cones, this.hits);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Height where lines leave a vehicle: its turret top. */
|
||||||
|
private eye(u: UnitAt): number {
|
||||||
|
return this.tanks.groundY(u.x, u.y, u.z) + (this.tanks.get(u.unit.eid)?.eyeY ?? 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
update(battle: TraceBattle, scene: SceneAt, layers: Layers): void {
|
||||||
|
const cone: number[] = [];
|
||||||
|
for (const u of scene.units.values()) this.botLines(u, scene, layers, cone);
|
||||||
|
if (layers.events) this.events(battle, scene);
|
||||||
|
this.deaths(battle, scene.t);
|
||||||
|
this.caps(scene);
|
||||||
|
const g = this.cones.geometry;
|
||||||
|
g.setAttribute('position', new BufferAttribute(Float32Array.from(cone), 3));
|
||||||
|
this.faint.flush();
|
||||||
|
this.bold.flush();
|
||||||
|
this.shots.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
private botLines(u: UnitAt, scene: SceneAt, layers: Layers, cone: number[]): void {
|
||||||
|
const bot = u.bot;
|
||||||
|
if (bot === undefined || !u.unit.alive) return;
|
||||||
|
const y = this.eye(u);
|
||||||
|
if (layers.goals && bot.hasOrder) this.faint.add(u.x, y, u.z, bot.goalX, this.tanks.terrainY(bot.goalX, bot.goalZ) + 1, bot.goalZ, C.goal);
|
||||||
|
const wy = bot.wishYaw * DEG;
|
||||||
|
this.bold.add(u.x, y, u.z, u.x + Math.cos(wy) * WISH_M, y, u.z + Math.sin(wy) * WISH_M, C.wish);
|
||||||
|
if (layers.cones) {
|
||||||
|
for (let i = 0; i < CONE_STEPS; i++) {
|
||||||
|
const a = (u.gunYaw - GUN_FOV_HALF_DEG + (2 * GUN_FOV_HALF_DEG * i) / CONE_STEPS) * DEG;
|
||||||
|
const b = (u.gunYaw - GUN_FOV_HALF_DEG + (2 * GUN_FOV_HALF_DEG * (i + 1)) / CONE_STEPS) * DEG;
|
||||||
|
cone.push(u.x, y, -u.z, u.x + Math.cos(a) * CONE_M, y, -(u.z + Math.sin(a) * CONE_M),
|
||||||
|
u.x + Math.cos(b) * CONE_M, y, -(u.z + Math.sin(b) * CONE_M));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!layers.links) return;
|
||||||
|
const target = scene.units.get(bot.target);
|
||||||
|
if (target !== undefined && bot.target !== '0') {
|
||||||
|
(bot.targetInSight ? this.bold : this.faint).add(u.x, y, u.z, target.x, this.eye(target), target.z,
|
||||||
|
bot.targetInSight ? C.target : C.targetLost);
|
||||||
|
}
|
||||||
|
const look = scene.units.get(bot.lookAt);
|
||||||
|
if (look !== undefined && bot.lookAt !== bot.target) this.bold.add(u.x, y, u.z, look.x, this.eye(look), look.z, C.look);
|
||||||
|
}
|
||||||
|
|
||||||
|
private events(battle: TraceBattle, scene: SceneAt): void {
|
||||||
|
const pos: number[] = [];
|
||||||
|
const col: number[] = [];
|
||||||
|
const c = new Color();
|
||||||
|
for (const e of eventsBetween(battle, scene.t - EVENT_WINDOW_SEC, scene.t)) {
|
||||||
|
const fade = 1 - (scene.t - e.t) / EVENT_WINDOW_SEC;
|
||||||
|
if (e.kind === 'SHOT' && e.eid !== undefined) {
|
||||||
|
const from = scene.units.get(e.eid);
|
||||||
|
const to = scene.units.get(e.fields['tgt'] ?? '');
|
||||||
|
if (from === undefined || to === undefined) continue;
|
||||||
|
this.shots.add(from.x, this.eye(from), from.z, to.x, this.eye(to) - 1, to.z, c.copy(C.shot).multiplyScalar(fade));
|
||||||
|
} else if (e.kind === 'HIT') {
|
||||||
|
const x = Number(e.fields['x']);
|
||||||
|
const z = Number(e.fields['z']);
|
||||||
|
pos.push(x, this.tanks.terrainY(x, z) + 1.5, -z);
|
||||||
|
c.set(e.fields['drop'] === '1' ? 0xff3c3c : 0xc8c8c8).multiplyScalar(fade);
|
||||||
|
col.push(c.r, c.g, c.b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.hits.geometry.setAttribute('position', new BufferAttribute(Float32Array.from(pos), 3));
|
||||||
|
this.hits.geometry.setAttribute('color', new BufferAttribute(Float32Array.from(col), 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
private deaths(battle: TraceBattle, t: number): void {
|
||||||
|
for (const e of eventsBetween(battle, battle.startT, t)) {
|
||||||
|
if (e.kind !== 'DEATH') continue;
|
||||||
|
const x = Number(e.fields['x']);
|
||||||
|
const z = Number(e.fields['z']);
|
||||||
|
const y = this.tanks.terrainY(x, z) + 0.5;
|
||||||
|
const c = e.fields['army'] === '1' ? C.dead1 : C.dead2;
|
||||||
|
this.faint.add(x - 4, y, z - 4, x + 4, y, z + 4, c);
|
||||||
|
this.faint.add(x - 4, y, z + 4, x + 4, y, z - 4, c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private caps(scene: SceneAt): void {
|
||||||
|
for (const cap of scene.caps) {
|
||||||
|
const c = new Color(ARMY_HEX[cap.owner] ?? C.cap.getHex());
|
||||||
|
for (let i = 0; i < CAP_STEPS; i++) {
|
||||||
|
const a = (i / CAP_STEPS) * Math.PI * 2;
|
||||||
|
const b = ((i + 1) / CAP_STEPS) * Math.PI * 2;
|
||||||
|
const ax = cap.x + Math.cos(a) * cap.r;
|
||||||
|
const az = cap.z + Math.sin(a) * cap.r;
|
||||||
|
const bx = cap.x + Math.cos(b) * cap.r;
|
||||||
|
const bz = cap.z + Math.sin(b) * cap.r;
|
||||||
|
this.bold.add(ax, this.tanks.terrainY(ax, az) + 0.8, az, bx, this.tanks.terrainY(bx, bz) + 0.8, bz, c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
this.group.traverse((o) => {
|
||||||
|
if (o instanceof Mesh || o instanceof LineSegments || o instanceof Points) {
|
||||||
|
o.geometry.dispose();
|
||||||
|
(o.material as { dispose(): void }).dispose();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
/**
|
||||||
|
* Every vehicle as simple shapes: a hull box tilted by the hull's pitch and roll, a turret box
|
||||||
|
* turned to the gun's heading, and a barrel at the gun's pitch. Sizes come from the bot's vehicle
|
||||||
|
* class (players: light or medium).
|
||||||
|
*/
|
||||||
|
import { sceneHeightAt, type SceneTerrain } from '@wto/ground-sim';
|
||||||
|
import {
|
||||||
|
BoxGeometry, Color, CylinderGeometry, Group, Mesh, MeshLambertMaterial, type Object3D,
|
||||||
|
} from 'three';
|
||||||
|
import { CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
|
||||||
|
import type { UnitAt } from '../frames.ts';
|
||||||
|
import { DEG } from './coords.ts';
|
||||||
|
|
||||||
|
/** Length, width, hull height per vehicle class (medium, light, heavy, tank destroyer, SPAA). */
|
||||||
|
const SIZES: readonly (readonly [number, number, number])[] = [
|
||||||
|
[7, 3.4, 1.3], [6, 3, 1.1], [7.6, 3.6, 1.4], [7, 3.3, 1.2], [6.5, 3.1, 1.2],
|
||||||
|
];
|
||||||
|
|
||||||
|
export const ARMY_HEX: Readonly<Record<number, number>> = { 1: 0x4aa3ff, 2: 0xff5c5c };
|
||||||
|
const DEAD = new Color(0x4a4a4a);
|
||||||
|
const SELECTED = new Color(0x6a5200);
|
||||||
|
const NONE = new Color(0);
|
||||||
|
|
||||||
|
/** A trace height further than this from the terrain is kept (bridge, building, platform). */
|
||||||
|
const OFF_GROUND_M = 1.5;
|
||||||
|
|
||||||
|
export interface Tank {
|
||||||
|
readonly root: Group;
|
||||||
|
readonly turret: Group;
|
||||||
|
readonly barrel: Group;
|
||||||
|
readonly label: CSS2DObject;
|
||||||
|
readonly mats: MeshLambertMaterial[];
|
||||||
|
/** Turret top above the hull origin, where lines and the gun camera start. */
|
||||||
|
readonly eyeY: number;
|
||||||
|
readonly length: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sizeOf(u: UnitAt): readonly [number, number, number] {
|
||||||
|
const cls = u.bot?.vehicleClass ?? (u.unit.light ? 1 : 0);
|
||||||
|
return SIZES[cls] ?? SIZES[0] ?? [7, 3.4, 1.3];
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeTank(u: UnitAt): Tank {
|
||||||
|
const [len, wid, hh] = sizeOf(u);
|
||||||
|
const hullMat = new MeshLambertMaterial();
|
||||||
|
const turretMat = new MeshLambertMaterial();
|
||||||
|
const root = new Group();
|
||||||
|
root.rotation.order = 'YZX';
|
||||||
|
const hull = new Mesh(new BoxGeometry(len, hh, wid), hullMat);
|
||||||
|
hull.position.y = hh / 2;
|
||||||
|
const turret = new Group();
|
||||||
|
turret.position.set(-len * 0.05, hh, 0);
|
||||||
|
const tw = wid * 0.7;
|
||||||
|
const th = hh * 0.65;
|
||||||
|
const turretBox = new Mesh(new BoxGeometry(len * 0.48, th, tw), turretMat);
|
||||||
|
turretBox.position.y = th / 2;
|
||||||
|
const barrel = new Group();
|
||||||
|
barrel.position.set(len * 0.2, th * 0.55, 0);
|
||||||
|
const tube = new Mesh(new CylinderGeometry(0.09, 0.11, len * 0.75, 8), turretMat);
|
||||||
|
tube.rotation.z = -Math.PI / 2;
|
||||||
|
tube.position.x = len * 0.375;
|
||||||
|
barrel.add(tube);
|
||||||
|
turret.add(turretBox, barrel);
|
||||||
|
root.add(hull, turret);
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.className = 'tank-label';
|
||||||
|
const label = new CSS2DObject(div);
|
||||||
|
label.position.y = hh + th + 2.5;
|
||||||
|
root.add(label);
|
||||||
|
for (const m of [hull, turretBox, tube]) m.userData['eid'] = u.unit.eid;
|
||||||
|
return { root, turret, barrel, label, mats: [hullMat, turretMat], eyeY: hh + th, length: len };
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TankPool {
|
||||||
|
readonly group = new Group();
|
||||||
|
private readonly tanks = new Map<string, Tank>();
|
||||||
|
|
||||||
|
constructor(private readonly terrain: SceneTerrain | undefined) {}
|
||||||
|
|
||||||
|
get(eid: string): Tank | undefined {
|
||||||
|
return this.tanks.get(eid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Meshes to pick with a ray. */
|
||||||
|
pickables(): Object3D[] {
|
||||||
|
const out: Object3D[] = [];
|
||||||
|
for (const t of this.tanks.values()) if (t.root.visible) t.root.traverse((o) => { if (o instanceof Mesh) out.push(o); });
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
terrainY(x: number, z: number): number {
|
||||||
|
return this.terrain === undefined ? 0 : sceneHeightAt(this.terrain, x, z);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ground height for the vehicle: the terrain unless the trace puts it clearly above or below. */
|
||||||
|
groundY(x: number, y: number, z: number): number {
|
||||||
|
if (this.terrain === undefined) return y;
|
||||||
|
const g = sceneHeightAt(this.terrain, x, z);
|
||||||
|
return Math.abs(y - g) <= OFF_GROUND_M ? g : y;
|
||||||
|
}
|
||||||
|
|
||||||
|
update(units: ReadonlyMap<string, UnitAt>, selected: string | undefined, labels: (u: UnitAt) => string | undefined): void {
|
||||||
|
for (const [eid, t] of this.tanks) if (!units.has(eid)) t.root.visible = false;
|
||||||
|
for (const u of units.values()) {
|
||||||
|
let t = this.tanks.get(u.unit.eid);
|
||||||
|
if (t === undefined) {
|
||||||
|
t = makeTank(u);
|
||||||
|
this.tanks.set(u.unit.eid, t);
|
||||||
|
this.group.add(t.root);
|
||||||
|
}
|
||||||
|
this.place(t, u, u.unit.eid === selected, labels(u));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private place(t: Tank, u: UnitAt, selected: boolean, label: string | undefined): void {
|
||||||
|
t.root.visible = true;
|
||||||
|
t.root.position.set(u.x, this.groundY(u.x, u.y, u.z), -u.z);
|
||||||
|
t.root.rotation.set(u.hullRoll * DEG, u.yaw * DEG, u.hullPitch * DEG);
|
||||||
|
const rel = ((((u.gunYaw - u.yaw) % 360) + 540) % 360) - 180;
|
||||||
|
t.turret.rotation.y = rel * DEG;
|
||||||
|
const hullSlope = u.hullPitch * Math.cos(rel * DEG) + u.hullRoll * Math.sin(rel * DEG);
|
||||||
|
t.barrel.rotation.z = (u.gunPitch - hullSlope) * DEG;
|
||||||
|
const base = u.unit.alive ? new Color(ARMY_HEX[u.unit.army] ?? 0xcccccc) : DEAD;
|
||||||
|
t.mats.forEach((m, i) => {
|
||||||
|
m.color.copy(base).multiplyScalar(i === 0 ? 1 : 0.8);
|
||||||
|
m.emissive.copy(selected ? SELECTED : NONE);
|
||||||
|
});
|
||||||
|
t.label.visible = label !== undefined;
|
||||||
|
if (label !== undefined) t.label.element.textContent = label;
|
||||||
|
if (u.unit.human) t.label.element.classList.add('human');
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
for (const t of this.tanks.values()) {
|
||||||
|
t.root.traverse((o) => { if (o instanceof Mesh) o.geometry.dispose(); });
|
||||||
|
for (const m of t.mats) m.dispose();
|
||||||
|
t.label.element.remove();
|
||||||
|
}
|
||||||
|
this.tanks.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
// The lab is a Vite page plus its dev-server API (server/), so it has its own settings and stays
|
||||||
|
// out of the root typecheck, like the launcher.
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2023",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||||
|
"types": ["node"],
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"strict": true,
|
||||||
|
"noUncheckedIndexedAccess": true,
|
||||||
|
"noImplicitOverride": true,
|
||||||
|
"exactOptionalPropertyTypes": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"useDefineForClassFields": true
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts", "src/**/*.tsx", "server/**/*.ts", "vite.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
import { defineConfig } from 'vite';
|
||||||
|
import { labApi } from './server/lab-api.ts';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react(), labApi()],
|
||||||
|
server: { host: '127.0.0.1', port: 47180, strictPort: false },
|
||||||
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@wto/launcher",
|
"name": "@wto/launcher",
|
||||||
"productName": "WTOffline Launcher",
|
"productName": "WTOffline Launcher",
|
||||||
"version": "0.1.2",
|
"version": "0.1.6",
|
||||||
"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,10 +14,12 @@
|
|||||||
},
|
},
|
||||||
"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",
|
||||||
"i18next": "^26.3.6",
|
"i18next": "^26.3.6",
|
||||||
|
"marked": "^18.4.0",
|
||||||
"react": "^19.2.8",
|
"react": "^19.2.8",
|
||||||
"react-dom": "^19.2.8",
|
"react-dom": "^19.2.8",
|
||||||
"react-i18next": "^17.0.10",
|
"react-i18next": "^17.0.10",
|
||||||
|
|||||||
@@ -11,14 +11,30 @@ import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagn
|
|||||||
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, detectDecalCacheSource } from '../services/install/decals.ts';
|
||||||
import { cancelInstall, checkGameFolder, dataFolderProblem, 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 { activeMapNav, applyMapNavUpdate, checkMapNavUpdate, useLocalMapNav } from '../services/map-nav/map-nav-update.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 { changeSaveCrew, getSaveCrews, previewSaveCrew } from '../services/saves/manage-save-crews.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 { rememberDialogPath, resolveDialogDefaultPath } from '../util/dialog-paths.ts';
|
||||||
import { broadcast, handle } from './register.ts';
|
import { broadcast, handle } from './register.ts';
|
||||||
|
|
||||||
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
|
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
|
||||||
@@ -55,11 +71,18 @@ export function registerIpcHandlers(): void {
|
|||||||
BrowserWindow.fromWebContents(sender)?.close();
|
BrowserWindow.fromWebContents(sender)?.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
handle('dialog:pickFolder', async ({ title }, sender) => {
|
handle('dialog:pickFolder', async ({ title, defaultPath }, sender) => {
|
||||||
const window = BrowserWindow.fromWebContents(sender);
|
const window = BrowserWindow.fromWebContents(sender);
|
||||||
const options = { properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>, ...(title ? { title } : {}) };
|
const resolvedDefaultPath = await resolveDialogDefaultPath('folder', defaultPath);
|
||||||
|
const options = {
|
||||||
|
properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>,
|
||||||
|
...(title ? { title } : {}),
|
||||||
|
...(resolvedDefaultPath ? { defaultPath: resolvedDefaultPath } : {}),
|
||||||
|
};
|
||||||
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
|
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
|
||||||
return { path: result.canceled ? null : (result.filePaths[0] ?? null) };
|
const chosen = result.canceled ? null : (result.filePaths[0] ?? null);
|
||||||
|
if (chosen) await rememberDialogPath('folder', chosen);
|
||||||
|
return { path: chosen };
|
||||||
});
|
});
|
||||||
|
|
||||||
handle('install:prepareCopy', () => createCopyDraft());
|
handle('install:prepareCopy', () => createCopyDraft());
|
||||||
@@ -143,6 +166,7 @@ export function registerIpcHandlers(): void {
|
|||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
handle('copies:cancelMaintenance', () => cancelMaintenance());
|
handle('copies:cancelMaintenance', () => cancelMaintenance());
|
||||||
|
handle('decals:detectSource', async ({ path }) => ({ path: await detectDecalCacheSource(path) }));
|
||||||
|
|
||||||
handle('saves:list', ({ copyId }) => getSaveList(copyId));
|
handle('saves:list', ({ copyId }) => getSaveList(copyId));
|
||||||
handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId));
|
handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId));
|
||||||
@@ -171,10 +195,55 @@ export function registerIpcHandlers(): void {
|
|||||||
|
|
||||||
handle('saves:research', ({ copyId, userId, branch }) => getSaveResearch(copyId, userId, branch));
|
handle('saves:research', ({ copyId, userId, branch }) => getSaveResearch(copyId, userId, branch));
|
||||||
handle('saves:editResearch', ({ copyId, userId, branch, action }) => changeSaveResearch(copyId, userId, branch, action));
|
handle('saves:editResearch', ({ copyId, userId, branch, action }) => changeSaveResearch(copyId, userId, branch, action));
|
||||||
|
handle('saves:crews', ({ copyId, userId, country }) => getSaveCrews(copyId, userId, country));
|
||||||
|
handle('saves:previewCrew', ({ copyId, userId, country, edit }) => previewSaveCrew(copyId, userId, country, edit));
|
||||||
|
handle('saves:editCrew', ({ copyId, userId, country, edit, token }) => changeSaveCrew(copyId, userId, country, edit, token));
|
||||||
|
|
||||||
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', () => {
|
||||||
@@ -201,6 +270,11 @@ export function registerIpcHandlers(): void {
|
|||||||
});
|
});
|
||||||
|
|
||||||
handle('updates:check', () => checkAppUpdate());
|
handle('updates:check', () => checkAppUpdate());
|
||||||
|
handle('map-nav:active', () => activeMapNav());
|
||||||
|
handle('map-nav:check', () => checkMapNavUpdate());
|
||||||
|
handle('map-nav:apply', ({ version }) => applyMapNavUpdate(version, (progress) =>
|
||||||
|
broadcast('event:map-nav-progress', progress)));
|
||||||
|
handle('map-nav:deactivate', () => useLocalMapNav());
|
||||||
handle('updates:download', ({ version }) => downloadAppUpdate(version, (progress) => broadcast('event:app-update-progress', progress)));
|
handle('updates:download', ({ version }) => downloadAppUpdate(version, (progress) => broadcast('event:app-update-progress', progress)));
|
||||||
handle('updates:install', ({ version }) => installAppUpdate(version, () =>
|
handle('updates:install', ({ version }) => installAppUpdate(version, () =>
|
||||||
launchInProgress() || installationInProgress() || maintenanceInProgress() || saveWriteInProgress() || decalImportInProgress()));
|
launchInProgress() || installationInProgress() || maintenanceInProgress() || saveWriteInProgress() || decalImportInProgress()));
|
||||||
|
|||||||
@@ -1,11 +1,6 @@
|
|||||||
import { spawn } from 'node:child_process';
|
import { spawn } from 'node:child_process';
|
||||||
import { createHash } from 'node:crypto';
|
|
||||||
import { once } from 'node:events';
|
import { once } from 'node:events';
|
||||||
import { createWriteStream } from 'node:fs';
|
|
||||||
import { mkdir, rename, unlink } from 'node:fs/promises';
|
|
||||||
import { dirname, join } from 'node:path';
|
import { dirname, join } from 'node:path';
|
||||||
import { Transform } from 'node:stream';
|
|
||||||
import { pipeline } from 'node:stream/promises';
|
|
||||||
import { app } from 'electron';
|
import { app } from 'electron';
|
||||||
import { compareAppVersions, packSigningPublicKey, PatchPackError, patchPackTuning, verifyEd25519 } from '@wto/patcher';
|
import { compareAppVersions, packSigningPublicKey, PatchPackError, patchPackTuning, verifyEd25519 } from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
@@ -19,10 +14,12 @@ import {
|
|||||||
newestProjectRelease, projectReleaseVersion, ReleasePageLimitError, sameReleaseSource, withReleaseSources, type LauncherRelease,
|
newestProjectRelease, projectReleaseVersion, ReleasePageLimitError, sameReleaseSource, withReleaseSources, type LauncherRelease,
|
||||||
} from '../patch-pack/release-feed.ts';
|
} from '../patch-pack/release-feed.ts';
|
||||||
import {
|
import {
|
||||||
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
|
FeedUnreachableError, readReleaseAsset, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, stageReleaseAsset,
|
||||||
} from '../patch-pack/release-assets.ts';
|
} from '../patch-pack/release-assets.ts';
|
||||||
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
|
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
|
||||||
import { isPortableLauncher, launchPortableUpdater, preparePortableInstall } from './portable-update.ts';
|
import {
|
||||||
|
cleanupPreparedPortableInstall, isPortableLauncher, launchPortableUpdater, preparePortableInstall,
|
||||||
|
} from './portable-update.ts';
|
||||||
|
|
||||||
type UpdateMode = 'installer' | 'portable';
|
type UpdateMode = 'installer' | 'portable';
|
||||||
|
|
||||||
@@ -150,7 +147,7 @@ export function downloadAppUpdate(
|
|||||||
? offer.release : await projectReleaseVersion('launcher', version, source);
|
? offer.release : await projectReleaseVersion('launcher', version, source);
|
||||||
const assetUrl = offer.mode === 'portable' ? release.portable?.archive : release.installer;
|
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}.`);
|
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);
|
await stageReleaseAsset(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) {
|
||||||
@@ -160,50 +157,6 @@ export function downloadAppUpdate(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function stageArtifact(
|
|
||||||
assetUrl: URL, source: LauncherRelease['source'], manifest: LauncherReleaseManifest | PortableReleaseManifest, target: string,
|
|
||||||
report: (progress: AppUpdateProgress) => void,
|
|
||||||
): Promise<void> {
|
|
||||||
const partial = `${target}.partial`;
|
|
||||||
const deadline = AbortSignal.timeout(30 * 60_000);
|
|
||||||
let size = 0;
|
|
||||||
let reportedAt = 0;
|
|
||||||
const hash = createHash('sha256');
|
|
||||||
try {
|
|
||||||
await mkdir(dirname(target), { recursive: true });
|
|
||||||
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
|
||||||
if (error.code !== 'ENOENT') throw error;
|
|
||||||
});
|
|
||||||
const response = await requestReleaseAsset(assetUrl, deadline, source);
|
|
||||||
const monitor = new Transform({
|
|
||||||
transform(chunk: Buffer, _encoding, done) {
|
|
||||||
size += chunk.length;
|
|
||||||
if (size > manifest.size) {
|
|
||||||
done(new Error('The download is larger than the signed release size.'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
hash.update(chunk);
|
|
||||||
if (size === manifest.size || Date.now() - reportedAt >= 200) {
|
|
||||||
reportedAt = Date.now();
|
|
||||||
report({ received: size, total: manifest.size });
|
|
||||||
}
|
|
||||||
done(null, chunk);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline });
|
|
||||||
if (size !== manifest.size) throw new FeedUnreachableError('The update download is incomplete.');
|
|
||||||
if (hash.digest('hex') !== manifest.sha256) throw new Error('The update download does not match the signed release.');
|
|
||||||
await rename(partial, target);
|
|
||||||
} catch (error) {
|
|
||||||
if (deadline.aborted) throw new FeedUnreachableError('The update download timed out.', { cause: error });
|
|
||||||
throw error;
|
|
||||||
} finally {
|
|
||||||
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
|
||||||
if (error.code !== 'ENOENT') console.warn('[app-update] removing a partial download failed:', error);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function installAppUpdate(version: string, launcherBusy: () => boolean): Promise<void> {
|
export function installAppUpdate(version: string, launcherBusy: () => boolean): Promise<void> {
|
||||||
return exclusively(async () => {
|
return exclusively(async () => {
|
||||||
const offer = selectedOffer(version);
|
const offer = selectedOffer(version);
|
||||||
@@ -215,7 +168,12 @@ export function installAppUpdate(version: string, launcherBusy: () => boolean):
|
|||||||
try {
|
try {
|
||||||
if (offer.mode === 'portable') {
|
if (offer.mode === 'portable') {
|
||||||
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
|
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
|
||||||
launchPortableUpdater(prepared);
|
try {
|
||||||
|
await launchPortableUpdater(prepared);
|
||||||
|
} catch (launchError) {
|
||||||
|
await cleanupPreparedPortableInstall(prepared);
|
||||||
|
throw launchError;
|
||||||
|
}
|
||||||
app.quit();
|
app.quit();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,21 +7,35 @@
|
|||||||
* only obsolete files listed in the previous portable inventory (never touching unrelated user
|
* only obsolete files listed in the previous portable inventory (never touching unrelated user
|
||||||
* files in the same folder), and restarts the updated executable.
|
* files in the same folder), and restarts the updated executable.
|
||||||
*/
|
*/
|
||||||
import { execFile, spawn } from 'node:child_process';
|
import { execFile } from 'node:child_process';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import * as nodeFs from 'node:fs';
|
||||||
import { existsSync } from 'node:fs';
|
import { existsSync } from 'node:fs';
|
||||||
import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
||||||
import { promisify } from 'node:util';
|
import { promisify } from 'node:util';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
const execute = promisify(execFile);
|
const execute = promisify(execFile);
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
|
||||||
export const PORTABLE_MARKER_FILE = 'portable-mode';
|
export const PORTABLE_MARKER_FILE = 'portable-mode';
|
||||||
export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
|
export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
|
||||||
|
export const PORTABLE_UPDATE_LOG_FILENAME = 'portable-update.log';
|
||||||
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
|
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
|
||||||
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
|
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
|
||||||
|
|
||||||
|
// Electron patches node:fs to expose .asar archives as virtual directories, which makes
|
||||||
|
// lstat().isFile() return false and recursive rm() fail on staged .asar files.
|
||||||
|
function rawFsPromises(): typeof nodeFs.promises {
|
||||||
|
try {
|
||||||
|
return (require('original-fs') as typeof nodeFs).promises;
|
||||||
|
} catch {
|
||||||
|
return nodeFs.promises;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const PortableInventorySchema = z.object({
|
const PortableInventorySchema = z.object({
|
||||||
format: z.literal(1),
|
format: z.literal(1),
|
||||||
version: z.string().min(1),
|
version: z.string().min(1),
|
||||||
@@ -216,6 +230,7 @@ export async function preparePortableInstall(
|
|||||||
): Promise<PreparedPortableUpdate> {
|
): Promise<PreparedPortableUpdate> {
|
||||||
await assertWritableFolder(installDir);
|
await assertWritableFolder(installDir);
|
||||||
await mkdir(updatesRoot, { recursive: true });
|
await mkdir(updatesRoot, { recursive: true });
|
||||||
|
const rawFs = rawFsPromises();
|
||||||
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
|
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
|
||||||
await mkdir(stagingDir, { recursive: true });
|
await mkdir(stagingDir, { recursive: true });
|
||||||
try {
|
try {
|
||||||
@@ -238,7 +253,7 @@ export async function preparePortableInstall(
|
|||||||
}
|
}
|
||||||
for (const rel of newFiles) {
|
for (const rel of newFiles) {
|
||||||
const stagedPath = resolveInside(stagingDir, rel);
|
const stagedPath = resolveInside(stagingDir, rel);
|
||||||
const stats = await lstat(stagedPath);
|
const stats = await rawFs.lstat(stagedPath);
|
||||||
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
|
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,7 +269,7 @@ export async function preparePortableInstall(
|
|||||||
installDir: resolve(installDir),
|
installDir: resolve(installDir),
|
||||||
stagingDir,
|
stagingDir,
|
||||||
archivePath,
|
archivePath,
|
||||||
logPath: join(updatesRoot, 'portable-update.log'),
|
logPath: join(updatesRoot, PORTABLE_UPDATE_LOG_FILENAME),
|
||||||
executable: LAUNCHER_EXECUTABLE,
|
executable: LAUNCHER_EXECUTABLE,
|
||||||
newFiles,
|
newFiles,
|
||||||
staleFiles,
|
staleFiles,
|
||||||
@@ -263,21 +278,46 @@ export async function preparePortableInstall(
|
|||||||
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
|
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
|
||||||
return { scriptPath, planPath, stagingDir };
|
return { scriptPath, planPath, stagingDir };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
|
await rawFs.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function launchPortableUpdater(prepared: PreparedPortableUpdate): void {
|
export async function cleanupPreparedPortableInstall(prepared: PreparedPortableUpdate): Promise<void> {
|
||||||
const child = spawn('powershell.exe', [
|
const rawFs = rawFsPromises();
|
||||||
'-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',
|
await rawFs.rm(prepared.stagingDir, { recursive: true, force: true }).catch(() => undefined);
|
||||||
'-File', prepared.scriptPath, prepared.planPath,
|
await rm(prepared.planPath, { force: true }).catch(() => undefined);
|
||||||
], {
|
}
|
||||||
cwd: dirname(prepared.scriptPath),
|
|
||||||
detached: true,
|
/**
|
||||||
stdio: 'ignore',
|
* Launch the portable apply script in a hidden PowerShell process that survives Electron exit.
|
||||||
windowsHide: true,
|
*
|
||||||
shell: false,
|
* On Windows, spawning powershell.exe directly with Node's `detached: true` sets DETACHED_PROCESS
|
||||||
});
|
* (no console), causing Windows PowerShell 5.1 ConsoleHost to exit silently with code 0 before
|
||||||
child.unref();
|
* running `-File`. Spawning without `detached` lets PowerShell run, but Electron tears down
|
||||||
|
* attached children on `app.quit()`. Using a short hidden PowerShell helper with `Start-Process`
|
||||||
|
* gives the updater its own hidden console and cleanly detaches it before the launcher quits.
|
||||||
|
*/
|
||||||
|
export async function launchPortableUpdater(prepared: PreparedPortableUpdate): Promise<void> {
|
||||||
|
const workDir = dirname(prepared.scriptPath);
|
||||||
|
const launcherPath = join(workDir, `launch-portable-${randomUUID()}.ps1`);
|
||||||
|
const script = [
|
||||||
|
'param([string]$ScriptPath, [string]$PlanPath, [string]$WorkDir)',
|
||||||
|
"$ErrorActionPreference = 'Stop'",
|
||||||
|
'$argsList = @(',
|
||||||
|
" '-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',",
|
||||||
|
' \'-File\', "`"$ScriptPath`"", "`"$PlanPath`""',
|
||||||
|
')',
|
||||||
|
"Start-Process -FilePath 'powershell.exe' -WorkingDirectory $WorkDir -WindowStyle Hidden -ArgumentList $argsList",
|
||||||
|
].join('\r\n');
|
||||||
|
// UTF-8 BOM ensures Windows PowerShell 5.1 decodes non-ASCII paths properly.
|
||||||
|
await writeFile(launcherPath, `\uFEFF${script}\r\n`, 'utf8');
|
||||||
|
try {
|
||||||
|
await execute('powershell.exe', [
|
||||||
|
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
|
||||||
|
'-File', launcherPath, prepared.scriptPath, prepared.planPath, workDir,
|
||||||
|
], { cwd: workDir, windowsHide: true, timeout: 30_000 });
|
||||||
|
} finally {
|
||||||
|
await rm(launcherPath, { force: true }).catch(() => undefined);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';
|
|
||||||
import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path';
|
import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path';
|
||||||
|
import { rawFs } from '../../util/raw-fs.ts';
|
||||||
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
|
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
|
||||||
|
|
||||||
export async function fileInfo(path: string) {
|
export async function fileInfo(path: string) {
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
try {
|
try {
|
||||||
return await lstat(path);
|
return await fsPromises.lstat(path);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||||
return null;
|
return null;
|
||||||
@@ -28,7 +29,8 @@ export async function changeCopyFiles<T>(
|
|||||||
prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>,
|
prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>,
|
||||||
recordChange: () => Promise<T>,
|
recordChange: () => Promise<T>,
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
const work = await mkdtemp(join(dirname(root), '.wto-copy-'));
|
const fsPromises = rawFs().promises;
|
||||||
|
const work = await fsPromises.mkdtemp(join(dirname(root), '.wto-copy-'));
|
||||||
const incoming = join(work, 'new');
|
const incoming = join(work, 'new');
|
||||||
const backups = join(work, 'old');
|
const backups = join(work, 'old');
|
||||||
const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = [];
|
const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = [];
|
||||||
@@ -44,14 +46,14 @@ export async function changeCopyFiles<T>(
|
|||||||
const entry = { target, saved: null as string | null, replaced: false };
|
const entry = { target, saved: null as string | null, replaced: false };
|
||||||
if (old) {
|
if (old) {
|
||||||
const saved = join(backups, path);
|
const saved = join(backups, path);
|
||||||
await mkdir(dirname(saved), { recursive: true });
|
await fsPromises.mkdir(dirname(saved), { recursive: true });
|
||||||
await rename(target, saved);
|
await fsPromises.rename(target, saved);
|
||||||
entry.saved = saved;
|
entry.saved = saved;
|
||||||
}
|
}
|
||||||
changes.push(entry);
|
changes.push(entry);
|
||||||
if (add) {
|
if (add) {
|
||||||
await mkdir(dirname(target), { recursive: true });
|
await fsPromises.mkdir(dirname(target), { recursive: true });
|
||||||
await rename(join(incoming, path), target);
|
await fsPromises.rename(join(incoming, path), target);
|
||||||
entry.replaced = true;
|
entry.replaced = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -60,8 +62,8 @@ export async function changeCopyFiles<T>(
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
for (const { target, saved, replaced } of changes.reverse()) {
|
for (const { target, saved, replaced } of changes.reverse()) {
|
||||||
try {
|
try {
|
||||||
if (replaced) await rm(target, { force: true });
|
if (replaced) await fsPromises.rm(target, { force: true });
|
||||||
if (saved) await rename(saved, target);
|
if (saved) await fsPromises.rename(saved, target);
|
||||||
} catch (rollbackError) {
|
} catch (rollbackError) {
|
||||||
keepBackups = true;
|
keepBackups = true;
|
||||||
console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError);
|
console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError);
|
||||||
@@ -70,7 +72,7 @@ export async function changeCopyFiles<T>(
|
|||||||
throw error;
|
throw error;
|
||||||
} finally {
|
} finally {
|
||||||
if (!keepBackups && relative(dirname(root), dirname(work)) === '') {
|
if (!keepBackups && relative(dirname(root), dirname(work)) === '') {
|
||||||
await rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error));
|
await fsPromises.rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,8 @@ import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schema
|
|||||||
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 { readClientMarker, writeClientMarker } from '../install/client-marker.ts';
|
||||||
|
import { copyPlannedFiles, isInSkippedSourceFolder, planCopy, type CopyPlan } from '../install/copy-game.ts';
|
||||||
import {
|
import {
|
||||||
fileHash,
|
fileHash,
|
||||||
linkVerifiedResource,
|
linkVerifiedResource,
|
||||||
@@ -21,20 +22,10 @@ import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } fro
|
|||||||
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';
|
||||||
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
|
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
|
||||||
|
import { readSource } from './copy-source.ts';
|
||||||
|
|
||||||
export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
|
export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
|
||||||
|
|
||||||
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
|
|
||||||
if (!record.sourcePath) return null;
|
|
||||||
try {
|
|
||||||
const game = await inspectGameFolder(record.sourcePath);
|
|
||||||
return game.missingFiles.length > 0 ? null : game;
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AppError) return null;
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
|
export function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
|
||||||
return !!source?.version && !!version && compareVersions(source.version, version) > 0;
|
return !!source?.version && !!version && compareVersions(source.version, version) > 0;
|
||||||
}
|
}
|
||||||
@@ -67,7 +58,10 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
|
|||||||
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 preserveHardlinks = await updatePreservesSpaceSaving(record, game, root);
|
||||||
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
|
// Older installs may have tracked files in folders that source scans now skip.
|
||||||
|
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter(
|
||||||
|
(name) => !found.has(key(name)) && !isInSkippedSourceFolder(name),
|
||||||
|
);
|
||||||
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
|
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
|
||||||
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
|
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
|
||||||
);
|
);
|
||||||
@@ -76,7 +70,7 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
|
|||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
const check = await checkPatches(game.path, record.dataPath);
|
const check = await checkPatches(game.path, record.dataPath);
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
return changeCopyFiles(root, async (incoming) => {
|
const updated = await changeCopyFiles(root, async (incoming) => {
|
||||||
report('copying', 0, copy.totalBytes);
|
report('copying', 0, copy.totalBytes);
|
||||||
let lastReport = 0;
|
let lastReport = 0;
|
||||||
await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => {
|
await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => {
|
||||||
@@ -111,6 +105,13 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
|
|||||||
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
|
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
|
||||||
...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}),
|
...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}),
|
||||||
})));
|
})));
|
||||||
|
if (!preserveHardlinks && linked.length > 0) {
|
||||||
|
const marker = await readClientMarker(root);
|
||||||
|
if (marker?.origin === 'hardlink' || (marker === null && record.method === 'copy')) {
|
||||||
|
await writeClientMarker(root, 'copy');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface UpdateFilePlan {
|
interface UpdateFilePlan {
|
||||||
@@ -195,7 +196,7 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
|
|||||||
const total = candidates.reduce((bytes, file) => bytes + file.bytes, 0);
|
const total = candidates.reduce((bytes, file) => bytes + file.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) => {
|
const updated = await changeCopyFiles(root, async (incoming) => {
|
||||||
const replacements: string[] = [];
|
const replacements: string[] = [];
|
||||||
const unchanged = new Map<string, BigIntStats>();
|
const unchanged = new Map<string, BigIntStats>();
|
||||||
let checked = 0;
|
let checked = 0;
|
||||||
@@ -232,6 +233,8 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
|
|||||||
report('applying', total, total);
|
report('applying', total, total);
|
||||||
return { replace: replacements, remove: [] };
|
return { replace: replacements, remove: [] };
|
||||||
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
|
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
|
||||||
|
await writeClientMarker(root, 'hardlink');
|
||||||
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function canShareVolume(sourcePath: string, root: string): Promise<boolean> {
|
async function canShareVolume(sourcePath: string, root: string): Promise<boolean> {
|
||||||
|
|||||||
@@ -1,19 +1,28 @@
|
|||||||
import { readdir, rm } from 'node:fs/promises';
|
import { isAbsolute, relative } from 'node:path';
|
||||||
import { isAbsolute, join, parse, relative } from 'node:path';
|
|
||||||
import { app } from 'electron';
|
|
||||||
import { isInSteamLibrary } from '@wto/patcher';
|
import { isInSteamLibrary } from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import type { Copies, InstallRecord } from '@shared/schemas/install.ts';
|
import type { Copies, InstallRecord } from '@shared/schemas/install.ts';
|
||||||
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
|
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
|
||||||
|
import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts';
|
||||||
import { installationInProgress } from '../install/install-game.ts';
|
import { installationInProgress } from '../install/install-game.ts';
|
||||||
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts';
|
import { canonicalCopyPath, listCopies, steamLibraryNeedsConfirmation, 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 { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
|
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
|
||||||
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 { compactCopy, convertibleCopy, isNewer, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
|
||||||
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
|
import {
|
||||||
|
canDeleteCopyFiles,
|
||||||
|
canRestoreStock,
|
||||||
|
checkedRoot,
|
||||||
|
failLocation,
|
||||||
|
removeCopy,
|
||||||
|
resolveClientOrigin,
|
||||||
|
withCanonicalSources,
|
||||||
|
} from './copy-removal.ts';
|
||||||
|
import { readSource, setCopySource } from './copy-source.ts';
|
||||||
|
|
||||||
|
export { canDeleteCopyFiles, canRestoreStock, resolveClientOrigin } from './copy-removal.ts';
|
||||||
|
|
||||||
let current: {
|
let current: {
|
||||||
stop: AbortController;
|
stop: AbortController;
|
||||||
@@ -34,9 +43,23 @@ export function cancelMaintenance(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
|
export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
|
||||||
const record = await requireCopy(id);
|
const registry = await listCopies();
|
||||||
const source = await readSource(record);
|
const record = registry.copies.find((copy) => copy.id === id);
|
||||||
const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]);
|
if (!record) throw new AppError('copy_not_found');
|
||||||
|
const [source, copyPath, dataPath, canonicalCopies] = await Promise.all([
|
||||||
|
readSource(record),
|
||||||
|
canonicalCopyPath(record.copyPath),
|
||||||
|
canonicalCopyPath(record.dataPath),
|
||||||
|
withCanonicalSources(registry.copies),
|
||||||
|
]);
|
||||||
|
const [diskMarker, hasHardlinkedResources, canRestoreAndRemove] = await Promise.all([
|
||||||
|
readClientMarker(copyPath),
|
||||||
|
detectHardlinkedResources(copyPath),
|
||||||
|
canRestoreStock(record, copyPath),
|
||||||
|
]);
|
||||||
|
const clientOrigin = resolveClientOrigin(record, diskMarker);
|
||||||
|
const canDeleteFiles = canDeleteCopyFiles(record, copyPath, clientOrigin, registry.copies) &&
|
||||||
|
canDeleteCopyFiles(record, copyPath, clientOrigin, canonicalCopies);
|
||||||
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath);
|
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath);
|
||||||
const dataInSteam = isInSteamLibrary(record.dataPath) || isInSteamLibrary(dataPath);
|
const dataInSteam = isInSteamLibrary(record.dataPath) || isInSteamLibrary(dataPath);
|
||||||
return {
|
return {
|
||||||
@@ -46,6 +69,10 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
|
|||||||
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,
|
||||||
|
clientOrigin,
|
||||||
|
hasHardlinkedResources,
|
||||||
|
canDeleteFiles,
|
||||||
|
canRestoreAndRemove,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,13 +119,28 @@ export async function maintainCopy(
|
|||||||
async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> {
|
async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> {
|
||||||
const { id, operation, steamLocations } = request;
|
const { id, operation, steamLocations } = request;
|
||||||
const record = await requireCopy(id);
|
const record = await requireCopy(id);
|
||||||
|
if (operation === 'set-source') return setCopySource(record, request.sourcePath);
|
||||||
|
if (operation === 'delete') {
|
||||||
|
return removeCopy(
|
||||||
|
record,
|
||||||
|
{
|
||||||
|
deleteFiles: request.deleteFiles === true,
|
||||||
|
restoreStock: request.restoreStock === true,
|
||||||
|
deleteData: request.deleteData === true,
|
||||||
|
},
|
||||||
|
signal,
|
||||||
|
report,
|
||||||
|
labServerUses,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const root = await checkedRoot(record);
|
const root = await checkedRoot(record);
|
||||||
const dataPath = await canonicalCopyPath(record.dataPath);
|
const dataPath = await canonicalCopyPath(record.dataPath);
|
||||||
const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath);
|
const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath);
|
||||||
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
|
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
|
|
||||||
if (operation !== 'confirm-steam' && operation !== 'delete' && needsConfirmation) {
|
if (operation !== 'confirm-steam' && needsConfirmation) {
|
||||||
throw new AppError('launch_steam_confirmation_required');
|
throw new AppError('launch_steam_confirmation_required');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,9 +162,6 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign
|
|||||||
return updateFromSource(record, root, signal, report);
|
return updateFromSource(record, root, signal, report);
|
||||||
case 'compact':
|
case 'compact':
|
||||||
return compactCopy(record, root, signal, report);
|
return compactCopy(record, root, signal, report);
|
||||||
case 'delete':
|
|
||||||
report('applying');
|
|
||||||
return remove(record, root, request.deleteData);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,42 +171,6 @@ 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> {
|
|
||||||
const root = await safeFolder(record.copyPath, true);
|
|
||||||
const backup = await canonicalCopyPath(record.stockBackupPath);
|
|
||||||
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) {
|
|
||||||
const source = await canonicalCopyPath(record.sourcePath);
|
|
||||||
if (copyPathContains(source, root) || copyPathContains(root, source)) {
|
|
||||||
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return root;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function safeFolder(path: string, steamAllowed = false): Promise<string> {
|
|
||||||
const root = await canonicalCopyPath(path);
|
|
||||||
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) ||
|
|
||||||
copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) {
|
|
||||||
failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath });
|
|
||||||
}
|
|
||||||
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) {
|
|
||||||
failLocation('folder_is_symlink', { path, root });
|
|
||||||
}
|
|
||||||
return root;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function labServerUses(root: string): Promise<boolean> {
|
async function labServerUses(root: string): Promise<boolean> {
|
||||||
const lab = await readInstalledLab().catch(() => null);
|
const lab = await readInstalledLab().catch(() => null);
|
||||||
if (!lab || relative(lab.copyPath, root) !== '') return false;
|
if (!lab || relative(lab.copyPath, root) !== '') return false;
|
||||||
@@ -180,38 +183,3 @@ async function recordCheck(record: InstallRecord, folder: string): Promise<Copie
|
|||||||
...copy, unavailablePatches: check.unavailable, lastCheckedAt: new Date().toISOString(),
|
...copy, unavailablePatches: check.unavailable, lastCheckedAt: new Date().toISOString(),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
|
|
||||||
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) {
|
|
||||||
if (deleteData) failLocation('delete_data_blocked_in_steam', { copyPath: record.copyPath, root });
|
|
||||||
return removeCopyRecord(record.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = deleteData ? await safeFolder(record.dataPath) : await canonicalCopyPath(record.dataPath);
|
|
||||||
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
|
|
||||||
if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) ||
|
|
||||||
(relative(data, root) !== '' && copyPathContains(data, root)))) {
|
|
||||||
failLocation('delete_data_overlaps_source_or_copy', { root, data, source });
|
|
||||||
}
|
|
||||||
if (!deleteData && copyPathContains(root, data)) {
|
|
||||||
await removeExcept(root, data);
|
|
||||||
} else {
|
|
||||||
await rm(root, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
if (deleteData && !copyPathContains(root, data)) await rm(data, { recursive: true, force: true });
|
|
||||||
return removeCopyRecord(record.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Keep the data folder in place when it was chosen inside this copy. */
|
|
||||||
async function removeExcept(folder: string, kept: string): Promise<void> {
|
|
||||||
if (relative(folder, kept) === '' || !(await fileInfo(folder))) return;
|
|
||||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
|
||||||
const path = join(folder, entry.name);
|
|
||||||
if (copyPathContains(path, kept)) {
|
|
||||||
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
|
|
||||||
await removeExcept(path, kept);
|
|
||||||
} else {
|
|
||||||
await rm(path, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
import { constants } from 'node:fs';
|
||||||
|
import { dirname, isAbsolute, join, parse, relative, resolve } from 'node:path';
|
||||||
|
import { app } from 'electron';
|
||||||
|
import { GAME_FILES, isInSteamLibrary } from '@wto/patcher';
|
||||||
|
import { AppError } from '@shared/errors.ts';
|
||||||
|
import type { ClientOrigin, Copies, InstallRecord } from '@shared/schemas/install.ts';
|
||||||
|
import { rawFs } from '../../util/raw-fs.ts';
|
||||||
|
import { readClientMarker, type ClientMarker } from '../install/client-marker.ts';
|
||||||
|
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord } from '../install/install-record.ts';
|
||||||
|
import { requireStockBackupLocation, STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
||||||
|
import { gameProcessRunning } from '../launch/launch-controller.ts';
|
||||||
|
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
|
||||||
|
import type { Report } from './copy-file-maintenance.ts';
|
||||||
|
|
||||||
|
const OFFLINE_HOOK_FILES = ['wto_ws.dll', 'wto_ws.cfg', 'wto_ws.log'] as const;
|
||||||
|
|
||||||
|
export interface RemoveCopyOptions {
|
||||||
|
readonly deleteFiles: boolean;
|
||||||
|
readonly restoreStock: boolean;
|
||||||
|
readonly deleteData: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function failLocation(reason: string, details: Record<string, unknown>): never {
|
||||||
|
console.warn('[copies] maintenance_location:', reason, details);
|
||||||
|
throw new AppError('maintenance_location');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the effective client origin by preferring a valid on-disk marker while
|
||||||
|
* keeping in-place registrations conservatively locked as `in-place`.
|
||||||
|
*/
|
||||||
|
export function resolveClientOrigin(
|
||||||
|
record: InstallRecord,
|
||||||
|
diskMarker: ClientMarker | null,
|
||||||
|
): ClientOrigin | null {
|
||||||
|
if (record.method === 'in-place') return 'in-place';
|
||||||
|
if (diskMarker) return diskMarker.origin;
|
||||||
|
if (record.method === 'copy') return record.hardlinkedFiles?.length ? 'hardlink' : 'copy';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Only launcher-created copies or existing folders carrying a valid copy/hardlink marker
|
||||||
|
* outside any Steam library and disjoint from every registered copy's sourcePath may be deleted.
|
||||||
|
*/
|
||||||
|
export function canDeleteCopyFiles(
|
||||||
|
record: InstallRecord,
|
||||||
|
root: string,
|
||||||
|
effectiveOrigin: ClientOrigin | null,
|
||||||
|
allCopies: readonly InstallRecord[] = [],
|
||||||
|
): boolean {
|
||||||
|
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) return false;
|
||||||
|
if (effectiveOrigin !== 'copy' && effectiveOrigin !== 'hardlink') return false;
|
||||||
|
const normalizedRoot = resolve(root);
|
||||||
|
const normalizedCopyPath = resolve(record.copyPath);
|
||||||
|
const sources = record.sourcePath
|
||||||
|
? [record.sourcePath, ...allCopies.map((copy) => copy.sourcePath)]
|
||||||
|
: allCopies.map((copy) => copy.sourcePath);
|
||||||
|
for (const candidate of sources) {
|
||||||
|
if (!candidate) continue;
|
||||||
|
const source = resolve(candidate);
|
||||||
|
if (pathsOverlap(normalizedRoot, source) || pathsOverlap(normalizedCopyPath, source)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Check that `record` has a safe root and all four original core files readable in wtoffline/stock. */
|
||||||
|
export async function canRestoreStock(record: InstallRecord, root: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const safeRoot = await checkedRoot(record);
|
||||||
|
const canonicalRoot = await canonicalCopyPath(root);
|
||||||
|
if (relative(safeRoot, canonicalRoot) !== '') return false;
|
||||||
|
const backup = await requireStockBackupLocation(safeRoot);
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
|
for (const file of Object.values(GAME_FILES)) {
|
||||||
|
const stockFile = join(backup, file);
|
||||||
|
const info = await fileInfo(stockFile);
|
||||||
|
if (!info?.isFile()) return false;
|
||||||
|
await fsPromises.access(stockFile, constants.R_OK);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve every copy's `sourcePath` through symlinks/junctions for overlap checks. */
|
||||||
|
export async function withCanonicalSources(copies: readonly InstallRecord[]): Promise<InstallRecord[]> {
|
||||||
|
return Promise.all(copies.map(async (copy) => (
|
||||||
|
copy.sourcePath ? { ...copy, sourcePath: await canonicalCopyPath(copy.sourcePath) } : copy
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkedRoot(record: InstallRecord): Promise<string> {
|
||||||
|
const root = await safeFolder(record.copyPath, true);
|
||||||
|
const backup = await canonicalCopyPath(record.stockBackupPath);
|
||||||
|
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) {
|
||||||
|
const source = await canonicalCopyPath(record.sourcePath);
|
||||||
|
if (pathsOverlap(source, root)) {
|
||||||
|
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function safeFolder(path: string, steamAllowed = false): Promise<string> {
|
||||||
|
const root = await canonicalCopyPath(path);
|
||||||
|
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) ||
|
||||||
|
copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) {
|
||||||
|
failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath });
|
||||||
|
}
|
||||||
|
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) {
|
||||||
|
failLocation('folder_is_symlink', { path, root });
|
||||||
|
}
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removeCopy(
|
||||||
|
record: InstallRecord,
|
||||||
|
options: RemoveCopyOptions,
|
||||||
|
signal: AbortSignal,
|
||||||
|
report: Report,
|
||||||
|
labServerUses: (root: string) => Promise<boolean>,
|
||||||
|
): Promise<Copies> {
|
||||||
|
const { deleteFiles, restoreStock, deleteData } = options;
|
||||||
|
if (deleteFiles && restoreStock) {
|
||||||
|
failLocation('delete_files_and_restore_stock_conflict', { id: record.id });
|
||||||
|
}
|
||||||
|
|
||||||
|
const canonicalRoot = await canonicalCopyPath(record.copyPath);
|
||||||
|
if (await gameProcessRunning(signal) || await labServerUses(canonicalRoot)) {
|
||||||
|
throw new AppError('maintenance_busy');
|
||||||
|
}
|
||||||
|
signal.throwIfAborted();
|
||||||
|
|
||||||
|
// Pure list removal touches no files on disk and skips copyPath/stockBackup checks
|
||||||
|
// so missing, moved, or damaged client registrations can always be removed safely.
|
||||||
|
if (!deleteFiles && !deleteData && !restoreStock) {
|
||||||
|
report('applying');
|
||||||
|
return removeCopyRecord(record.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(canonicalRoot);
|
||||||
|
if ((deleteFiles || deleteData) && copyInSteam) {
|
||||||
|
failLocation(deleteFiles ? 'delete_files_blocked_in_steam' : 'delete_data_blocked_in_steam', {
|
||||||
|
method: record.method,
|
||||||
|
copyPath: record.copyPath,
|
||||||
|
root: canonicalRoot,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let root = canonicalRoot;
|
||||||
|
if (deleteFiles) {
|
||||||
|
const allCopies = (await listCopies()).copies;
|
||||||
|
const canonicalCopies = await withCanonicalSources(allCopies);
|
||||||
|
const initialOrigin = resolveClientOrigin(record, await readClientMarker(canonicalRoot));
|
||||||
|
if (!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, allCopies) ||
|
||||||
|
!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, canonicalCopies)) {
|
||||||
|
failLocation('delete_files_blocked', { method: record.method, origin: initialOrigin, copyPath: record.copyPath, root: canonicalRoot });
|
||||||
|
}
|
||||||
|
root = await checkedRoot(record);
|
||||||
|
const verifiedOrigin = resolveClientOrigin(record, await readClientMarker(root));
|
||||||
|
if (!canDeleteCopyFiles(record, root, verifiedOrigin, allCopies) ||
|
||||||
|
!canDeleteCopyFiles(record, root, verifiedOrigin, canonicalCopies)) {
|
||||||
|
failLocation('delete_files_blocked', { method: record.method, origin: verifiedOrigin, copyPath: record.copyPath, root });
|
||||||
|
}
|
||||||
|
} else if (restoreStock) {
|
||||||
|
root = await checkedRoot(record);
|
||||||
|
if (!(await canRestoreStock(record, root))) {
|
||||||
|
failLocation('restore_stock_unavailable', { copyPath: record.copyPath, root, stockBackupPath: record.stockBackupPath });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = deleteData ? await safeFolder(record.dataPath, false) : await canonicalCopyPath(record.dataPath);
|
||||||
|
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
|
||||||
|
const stockBackup = await canonicalCopyPath(record.stockBackupPath);
|
||||||
|
if (deleteData) {
|
||||||
|
const rawRoot = resolve(record.copyPath);
|
||||||
|
const overlapsSource = source !== null && pathsOverlap(data, source);
|
||||||
|
const containsCopy = deleteFiles
|
||||||
|
? relative(data, root) !== '' && copyPathContains(data, root)
|
||||||
|
: copyPathContains(data, root) || copyPathContains(data, rawRoot) || copyPathContains(data, stockBackup);
|
||||||
|
if (overlapsSource || containsCopy) {
|
||||||
|
failLocation('delete_data_overlaps_source_or_copy', { root, data, source, stockBackup, deleteFiles, restoreStock });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
report('applying');
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
|
if (restoreStock) {
|
||||||
|
await restoreStockAndCleanOfflineFiles(root, data, deleteData);
|
||||||
|
} else if (deleteFiles) {
|
||||||
|
if (!deleteData && copyPathContains(root, data)) {
|
||||||
|
await removeExcept(root, data);
|
||||||
|
} else {
|
||||||
|
await fsPromises.rm(root, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (deleteData && (!deleteFiles || !copyPathContains(root, data))) {
|
||||||
|
await fsPromises.rm(data, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
return removeCopyRecord(record.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomically restore the four stock core files from `wtoffline/stock`, then remove
|
||||||
|
* only launcher-created hook files and the `wtoffline` folder without touching base game files.
|
||||||
|
*/
|
||||||
|
async function restoreStockAndCleanOfflineFiles(root: string, data: string, deleteData: boolean): Promise<void> {
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
|
const backup = await requireStockBackupLocation(root);
|
||||||
|
await changeCopyFiles(root, async (incoming) => {
|
||||||
|
const files = Object.values(GAME_FILES);
|
||||||
|
for (const file of files) {
|
||||||
|
const sourceFile = join(backup, file);
|
||||||
|
if (!(await fileInfo(sourceFile))?.isFile()) {
|
||||||
|
failLocation('stock_backup_source_missing', { root, file, sourceFile });
|
||||||
|
}
|
||||||
|
const targetFile = join(incoming, file);
|
||||||
|
await fsPromises.mkdir(dirname(targetFile), { recursive: true });
|
||||||
|
await fsPromises.copyFile(sourceFile, targetFile);
|
||||||
|
}
|
||||||
|
return { replace: files, remove: [] };
|
||||||
|
}, async () => undefined);
|
||||||
|
|
||||||
|
const exeDir = dirname(GAME_FILES.executable);
|
||||||
|
for (const name of OFFLINE_HOOK_FILES) {
|
||||||
|
const hookFile = await stagedPath(root, join(exeDir, name));
|
||||||
|
const info = await fileInfo(hookFile);
|
||||||
|
if (info && !info.isDirectory()) {
|
||||||
|
await fsPromises.rm(hookFile, { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const wtofflineFolder = await stagedPath(root, dirname(STOCK_BACKUP_FOLDER));
|
||||||
|
const wtofflineInfo = await fileInfo(wtofflineFolder);
|
||||||
|
if (wtofflineInfo?.isDirectory()) {
|
||||||
|
if (!deleteData && copyPathContains(wtofflineFolder, data)) {
|
||||||
|
await removeExcept(wtofflineFolder, data);
|
||||||
|
} else {
|
||||||
|
await fsPromises.rm(wtofflineFolder, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function pathsOverlap(left: string, right: string): boolean {
|
||||||
|
return copyPathContains(left, right) || copyPathContains(right, left);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep the data folder in place when it was chosen inside this copy. */
|
||||||
|
async function removeExcept(folder: string, kept: string): Promise<void> {
|
||||||
|
if (relative(folder, kept) === '' || !(await fileInfo(folder))) return;
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
|
for (const entry of await fsPromises.readdir(folder, { withFileTypes: true })) {
|
||||||
|
const path = join(folder, entry.name);
|
||||||
|
if (copyPathContains(path, kept)) {
|
||||||
|
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
|
||||||
|
await removeExcept(path, kept);
|
||||||
|
} else {
|
||||||
|
await fsPromises.rm(path, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { isAbsolute, join } from 'node:path';
|
||||||
|
import { AppError } from '@shared/errors.ts';
|
||||||
|
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
|
||||||
|
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||||
|
import { canonicalCopyPath, copyPathContains, updateCopyRecord } from '../install/install-record.ts';
|
||||||
|
import { fileInfo } from './change-copy-files.ts';
|
||||||
|
|
||||||
|
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
|
||||||
|
if (!record.sourcePath) return null;
|
||||||
|
try {
|
||||||
|
return await inspectSource(record, record.sourcePath);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AppError) return null;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setCopySource(record: InstallRecord, path: string | undefined): Promise<Copies> {
|
||||||
|
const source = await inspectSource(record, path);
|
||||||
|
return updateCopyRecord(record.id, (latest) => {
|
||||||
|
if (latest.copyPath !== record.copyPath || latest.dataPath !== record.dataPath) {
|
||||||
|
throw new AppError('maintenance_location');
|
||||||
|
}
|
||||||
|
return { ...latest, sourcePath: source.resolvedPath };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function inspectSource(record: InstallRecord, path: string | undefined): Promise<GameFolderInspection> {
|
||||||
|
if (!path || !isAbsolute(path)) throw new AppError('maintenance_source_invalid');
|
||||||
|
const [game, copyPath, dataPath] = await Promise.all([
|
||||||
|
inspectGameFolder(path), canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath),
|
||||||
|
]);
|
||||||
|
const source = game.resolvedPath;
|
||||||
|
const overlapsCopy = copyPathContains(source, copyPath) || copyPathContains(copyPath, source);
|
||||||
|
if (overlapsCopy || copyPathContains(source, dataPath)) {
|
||||||
|
throw new AppError('maintenance_source_overlap');
|
||||||
|
}
|
||||||
|
if (game.missingFiles.length || !game.version || game.hasOfflineBackup || game.needsStockSource) {
|
||||||
|
throw new AppError('maintenance_source_invalid');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify that the directory has game resources beyond the four files used for patching.
|
||||||
|
const [content, languages, missions] = await Promise.all([
|
||||||
|
fileInfo(join(source, 'content')),
|
||||||
|
fileInfo(join(source, 'lang.vromfs.bin')),
|
||||||
|
fileInfo(join(source, 'mis.vromfs.bin')),
|
||||||
|
]);
|
||||||
|
if (!content?.isDirectory() || !languages?.isFile() || !missions?.isFile()) {
|
||||||
|
throw new AppError('maintenance_source_invalid');
|
||||||
|
}
|
||||||
|
return { ...game, path: source };
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import { zipSync } from 'fflate';
|
|||||||
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 type { InstallRecord } from '@shared/schemas/install.ts';
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||||
|
import { PORTABLE_UPDATE_LOG_FILENAME } from '../app-update/portable-update.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';
|
||||||
@@ -58,6 +59,11 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
|
|||||||
await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name));
|
await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
await addFile(
|
||||||
|
files,
|
||||||
|
`launcher-logs/${PORTABLE_UPDATE_LOG_FILENAME}`,
|
||||||
|
join(userData, 'launcher-updates', PORTABLE_UPDATE_LOG_FILENAME),
|
||||||
|
);
|
||||||
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);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { dirname, join } from 'node:path';
|
|||||||
import { executableVersion, GAME_FILES, isInSteamLibrary, recordedGameVersions } from '@wto/patcher';
|
import { executableVersion, GAME_FILES, isInSteamLibrary, recordedGameVersions } from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import type { GameFolderInspection } from '@shared/schemas/install.ts';
|
import type { GameFolderInspection } from '@shared/schemas/install.ts';
|
||||||
|
import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts';
|
||||||
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
||||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||||
|
|
||||||
@@ -61,6 +62,10 @@ export async function inspectGameFolder(path: string): Promise<GameFolderInspect
|
|||||||
needsStockSource = hasMarkerFile || liveExePatched;
|
needsStockSource = hasMarkerFile || liveExePatched;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const [clientMarker, hasHardlinkedResources] = await Promise.all([
|
||||||
|
readClientMarker(resolved),
|
||||||
|
detectHardlinkedResources(resolved),
|
||||||
|
]);
|
||||||
return {
|
return {
|
||||||
path,
|
path,
|
||||||
resolvedPath: resolved,
|
resolvedPath: resolved,
|
||||||
@@ -70,6 +75,8 @@ export async function inspectGameFolder(path: string): Promise<GameFolderInspect
|
|||||||
inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(resolved),
|
inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(resolved),
|
||||||
hasOfflineBackup,
|
hasOfflineBackup,
|
||||||
needsStockSource,
|
needsStockSource,
|
||||||
|
clientOrigin: clientMarker?.origin ?? null,
|
||||||
|
hasHardlinkedResources,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import { join } from 'node:path';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { hardlinkResourceRules, isHardlinkableResource } from '@wto/patcher';
|
||||||
|
import { ClientOriginSchema, type ClientOrigin } from '@shared/schemas/install.ts';
|
||||||
|
import { writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||||
|
import { rawFs } from '../../util/raw-fs.ts';
|
||||||
|
|
||||||
|
/** Relative path of the self-describing client identity marker inside a client folder. */
|
||||||
|
export const CLIENT_MARKER_FILE = join('wtoffline', 'client.json');
|
||||||
|
|
||||||
|
export const ClientMarkerSchema = z.object({
|
||||||
|
format: z.literal(1),
|
||||||
|
origin: ClientOriginSchema,
|
||||||
|
createdBy: z.literal('wtoffline-launcher'),
|
||||||
|
createdAt: z.string().min(1),
|
||||||
|
updatedAt: z.string().min(1).optional(),
|
||||||
|
});
|
||||||
|
export type ClientMarker = z.output<typeof ClientMarkerSchema>;
|
||||||
|
|
||||||
|
/** Cap on qualifying resource files inspected when sampling for hard links. */
|
||||||
|
const MAX_RESOURCE_SAMPLES = 64;
|
||||||
|
|
||||||
|
export function clientMarkerPath(copyFolder: string): string {
|
||||||
|
return join(copyFolder, CLIENT_MARKER_FILE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Safely read and validate `<copyFolder>/wtoffline/client.json`.
|
||||||
|
* Returns `null` when missing, unreadable, malformed, or schema-invalid without throwing.
|
||||||
|
*/
|
||||||
|
export async function readClientMarker(copyFolder: string): Promise<ClientMarker | null> {
|
||||||
|
try {
|
||||||
|
const text = await rawFs().promises.readFile(clientMarkerPath(copyFolder), 'utf8');
|
||||||
|
const parsed = ClientMarkerSchema.safeParse(JSON.parse(text) as unknown);
|
||||||
|
return parsed.success ? parsed.data : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomically write `<copyFolder>/wtoffline/client.json`.
|
||||||
|
* Preserves `createdAt` and records `updatedAt` when updating an existing valid marker.
|
||||||
|
*/
|
||||||
|
export async function writeClientMarker(copyFolder: string, origin: ClientOrigin): Promise<ClientMarker> {
|
||||||
|
const existing = await readClientMarker(copyFolder);
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const marker: ClientMarker = existing
|
||||||
|
? {
|
||||||
|
format: 1,
|
||||||
|
origin,
|
||||||
|
createdBy: 'wtoffline-launcher',
|
||||||
|
createdAt: existing.createdAt,
|
||||||
|
updatedAt: now,
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
format: 1,
|
||||||
|
origin,
|
||||||
|
createdBy: 'wtoffline-launcher',
|
||||||
|
createdAt: now,
|
||||||
|
};
|
||||||
|
await writeJsonAtomic(clientMarkerPath(copyFolder), marker);
|
||||||
|
return marker;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lightweight probe for hard-linked read-only resource packs under allowed content directories.
|
||||||
|
* Returns `true` as soon as a single qualifying resource reports `nlink >= 2`, or `false` on
|
||||||
|
* missing/unreadable directories or when no sampled resource is hard-linked.
|
||||||
|
*/
|
||||||
|
export async function detectHardlinkedResources(copyFolder: string): Promise<boolean> {
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
|
const rules = hardlinkResourceRules();
|
||||||
|
const queue: Array<{ absDir: string; relDir: string }> = rules.allowedDirectories.map((dir) => {
|
||||||
|
const clean = dir.replace(/\/+$/, '');
|
||||||
|
return { absDir: join(copyFolder, clean), relDir: clean };
|
||||||
|
});
|
||||||
|
let sampled = 0;
|
||||||
|
|
||||||
|
while (queue.length > 0 && sampled < MAX_RESOURCE_SAMPLES) {
|
||||||
|
const current = queue.shift()!;
|
||||||
|
let entries;
|
||||||
|
try {
|
||||||
|
entries = await fsPromises.readdir(current.absDir, { withFileTypes: true });
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (entry.isSymbolicLink()) continue;
|
||||||
|
const absPath = join(current.absDir, entry.name);
|
||||||
|
const relPath = `${current.relDir}/${entry.name}`;
|
||||||
|
if (entry.isDirectory()) {
|
||||||
|
queue.push({ absDir: absPath, relDir: relPath });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!entry.isFile()) continue;
|
||||||
|
|
||||||
|
const lower = entry.name.toLowerCase();
|
||||||
|
if (!rules.allowedExtensions.some((ext) => lower.endsWith(ext))) continue;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const stats = await fsPromises.lstat(absPath);
|
||||||
|
if (!stats.isFile() || !isHardlinkableResource(relPath, stats.size)) continue;
|
||||||
|
if (stats.nlink >= 2) return true;
|
||||||
|
sampled += 1;
|
||||||
|
if (sampled >= MAX_RESOURCE_SAMPLES) return false;
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
import { createReadStream, createWriteStream, type BigIntStats } from 'node:fs';
|
import type { BigIntStats, Dirent } from 'node:fs';
|
||||||
import { lstat, mkdir, readdir, rm, utimes } from 'node:fs/promises';
|
import { join, normalize, relative, sep } from 'node:path';
|
||||||
import { join, relative } from 'node:path';
|
|
||||||
import { Transform } from 'node:stream';
|
import { Transform } from 'node:stream';
|
||||||
import { pipeline } from 'node:stream/promises';
|
import { pipeline } from 'node:stream/promises';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
|
import { rawFs } from '../../util/raw-fs.ts';
|
||||||
import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
|
import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
|
||||||
|
import { findIncompleteUhqPacks, isPathInUhqPacks } from './uhq-packages.ts';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Copy a War Thunder installation into a new or empty folder (install method "copy"). The stock
|
* Copy a War Thunder installation into a new or empty folder (install method "copy"). The stock
|
||||||
@@ -12,14 +13,45 @@ import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Top-level folders of an installation that hold what the game produced while the player played
|
* Top-level folders of an installation that hold player-generated data or user content from
|
||||||
* online, not the game itself: logs, the web content cache, replays, screenshots and the player's
|
* playing online, not the stock client itself: logs, the web content cache, replays, screenshots,
|
||||||
* own missions. The offline copy does not take the online game's data (working rules 18); the
|
* and user missions, skins and sights. The offline copy does not take the online game's data; the
|
||||||
* 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([
|
||||||
/** Top-level folders ignored when scanning a stock source, including any stray offline backup directory. */
|
'.game_logs',
|
||||||
const SKIPPED_SOURCE_FOLDERS = new Set([...PLAYER_DATA_FOLDERS, 'wtoffline']);
|
'cache',
|
||||||
|
'replays',
|
||||||
|
'screenshots',
|
||||||
|
'usermissions',
|
||||||
|
'userskins',
|
||||||
|
'usersights',
|
||||||
|
]);
|
||||||
|
/**
|
||||||
|
* Top-level folders ignored when scanning a stock source in addition to player data:
|
||||||
|
* official launcher/updater logs and obsolete files, the War Thunder CDK toolkit, and any stray
|
||||||
|
* offline backup directory.
|
||||||
|
*/
|
||||||
|
const SKIPPED_SOURCE_FOLDERS = new Set([
|
||||||
|
...PLAYER_DATA_FOLDERS,
|
||||||
|
'.gaijin_updater_logs',
|
||||||
|
'.launcher_log',
|
||||||
|
'.obsolete',
|
||||||
|
'.start_app_logs',
|
||||||
|
'warthundercdk',
|
||||||
|
'wtoffline',
|
||||||
|
]);
|
||||||
|
const LAUNCHER_EXECUTABLE_LOWER = 'wtoffline launcher.exe';
|
||||||
|
|
||||||
|
/** Whether a relative path starts with a top-level entry excluded from source scans. */
|
||||||
|
export function isInSkippedSourceFolder(relativePath: string): boolean {
|
||||||
|
const [topLevel = ''] = normalize(relativePath).split(sep, 1);
|
||||||
|
return SKIPPED_SOURCE_FOLDERS.has(topLevel.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLauncherFolder(entries: readonly Dirent[]): boolean {
|
||||||
|
return entries.some((entry) => entry.isFile() && entry.name.toLowerCase() === LAUNCHER_EXECUTABLE_LOWER);
|
||||||
|
}
|
||||||
|
|
||||||
interface CopyEntry {
|
interface CopyEntry {
|
||||||
readonly relativePath: string;
|
readonly relativePath: string;
|
||||||
@@ -36,25 +68,44 @@ export interface CopyPlan {
|
|||||||
export interface CopyProgress {
|
export interface CopyProgress {
|
||||||
readonly doneBytes: number;
|
readonly doneBytes: number;
|
||||||
readonly doneFiles: number;
|
readonly doneFiles: number;
|
||||||
|
/** Bytes actually written to disk so far (excludes hard-linked files). */
|
||||||
|
readonly copiedBytes: number;
|
||||||
|
/** Bytes shared via hard links so far (occupies no extra disk space). */
|
||||||
|
readonly linkedBytes: number;
|
||||||
|
/** Number of hard-linked files created so far. */
|
||||||
|
readonly linkedFiles: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */
|
/** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */
|
||||||
export async function planCopy(source: string): Promise<CopyPlan> {
|
export async function planCopy(source: string): Promise<CopyPlan> {
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
|
const incompleteUhq = await findIncompleteUhqPacks(source);
|
||||||
|
const skippedUhq = new Set(incompleteUhq);
|
||||||
|
if (incompleteUhq.length > 0) {
|
||||||
|
console.warn(`[install] skipping incomplete optional UHQ pack(s) in ${source}: ${incompleteUhq.join(', ')}`);
|
||||||
|
}
|
||||||
const files: CopyEntry[] = [];
|
const files: CopyEntry[] = [];
|
||||||
const folders: string[] = [];
|
const folders: string[] = [];
|
||||||
let totalBytes = 0;
|
let totalBytes = 0;
|
||||||
const pending = [source];
|
const pending = [source];
|
||||||
while (pending.length) {
|
while (pending.length) {
|
||||||
const folder = pending.pop()!;
|
const folder = pending.pop()!;
|
||||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
const entries = await fsPromises.readdir(folder, { withFileTypes: true });
|
||||||
|
if (folder !== source) {
|
||||||
|
// Skip any WTOffline Launcher folder that was previously extracted inside the game directory.
|
||||||
|
if (isLauncherFolder(entries)) continue;
|
||||||
|
folders.push(relative(source, folder));
|
||||||
|
}
|
||||||
|
for (const entry of entries) {
|
||||||
const path = join(folder, entry.name);
|
const path = join(folder, entry.name);
|
||||||
if (folder === source && SKIPPED_SOURCE_FOLDERS.has(entry.name.toLowerCase())) continue;
|
if (folder === source && isInSkippedSourceFolder(entry.name)) continue;
|
||||||
|
const relPath = relative(source, path);
|
||||||
|
if (isPathInUhqPacks(relPath, skippedUhq)) continue;
|
||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
folders.push(relative(source, path));
|
|
||||||
pending.push(path);
|
pending.push(path);
|
||||||
} else if (entry.isFile()) {
|
} else if (entry.isFile()) {
|
||||||
const { size, mtimeMs } = await lstat(path);
|
const { size, mtimeMs } = await fsPromises.lstat(path);
|
||||||
files.push({ relativePath: relative(source, path), bytes: size, modifiedAt: mtimeMs });
|
files.push({ relativePath: relPath, bytes: size, modifiedAt: mtimeMs });
|
||||||
totalBytes += size;
|
totalBytes += size;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -78,16 +129,25 @@ export async function copyPlannedFiles(
|
|||||||
onProgress: (progress: CopyProgress) => void,
|
onProgress: (progress: CopyProgress) => void,
|
||||||
hardlinks?: ReadonlyMap<string, BigIntStats>,
|
hardlinks?: ReadonlyMap<string, BigIntStats>,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await mkdir(target, { recursive: true });
|
const fs = rawFs();
|
||||||
for (const folder of plan.folders) await mkdir(join(target, folder), { recursive: true });
|
const fsPromises = fs.promises;
|
||||||
|
await fsPromises.mkdir(target, { recursive: true });
|
||||||
|
for (const folder of plan.folders) await fsPromises.mkdir(join(target, folder), { recursive: true });
|
||||||
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
|
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
|
||||||
let next = 0;
|
let next = 0;
|
||||||
let doneBytes = 0;
|
let copiedBytes = 0;
|
||||||
|
let linkedBytes = 0;
|
||||||
|
let linkedFiles = 0;
|
||||||
let doneFiles = 0;
|
let doneFiles = 0;
|
||||||
|
const emitProgress = (): void => {
|
||||||
|
// Keep doneBytes aligned with actual bytes written to disk so hard-linked files
|
||||||
|
// do not inflate copy progress.
|
||||||
|
onProgress({ doneBytes: copiedBytes, doneFiles, copiedBytes, linkedBytes, linkedFiles });
|
||||||
|
};
|
||||||
const countBytes = (): Transform => new Transform({
|
const countBytes = (): Transform => new Transform({
|
||||||
transform(chunk: Buffer, _encoding, callback) {
|
transform(chunk: Buffer, _encoding, callback) {
|
||||||
doneBytes += chunk.length;
|
copiedBytes += chunk.length;
|
||||||
onProgress({ doneBytes, doneFiles });
|
emitProgress();
|
||||||
callback(null, chunk);
|
callback(null, chunk);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -95,6 +155,8 @@ export async function copyPlannedFiles(
|
|||||||
// caller cleaning up after an error never races a copy still writing.
|
// caller cleaning up after an error never races a copy still writing.
|
||||||
const stop = new AbortController();
|
const stop = new AbortController();
|
||||||
const stopSignal = AbortSignal.any([signal, stop.signal]);
|
const stopSignal = AbortSignal.any([signal, stop.signal]);
|
||||||
|
let firstError: unknown = null;
|
||||||
|
let hasError = false;
|
||||||
const copyNext = async (): Promise<void> => {
|
const copyNext = async (): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
while (next < plan.files.length) {
|
while (next < plan.files.length) {
|
||||||
@@ -106,33 +168,39 @@ export async function copyPlannedFiles(
|
|||||||
if (verified) {
|
if (verified) {
|
||||||
const linked = await linkVerifiedResource(from, to, verified);
|
const linked = await linkVerifiedResource(from, to, verified);
|
||||||
linkedTargets?.set(to, linked);
|
linkedTargets?.set(to, linked);
|
||||||
doneBytes += file.bytes;
|
linkedBytes += file.bytes;
|
||||||
|
linkedFiles += 1;
|
||||||
} else {
|
} else {
|
||||||
await pipeline(
|
await pipeline(
|
||||||
createReadStream(from),
|
fs.createReadStream(from),
|
||||||
countBytes(),
|
countBytes(),
|
||||||
// 'wx': fail instead of overwriting a file that is already there.
|
// 'wx': fail instead of overwriting a file that is already there.
|
||||||
createWriteStream(to, { flags: 'wx' }),
|
fs.createWriteStream(to, { flags: 'wx' }),
|
||||||
{ signal: stopSignal },
|
{ signal: stopSignal },
|
||||||
);
|
);
|
||||||
const modified = new Date(file.modifiedAt);
|
const modified = new Date(file.modifiedAt);
|
||||||
await utimes(to, modified, modified);
|
await fsPromises.utimes(to, modified, modified);
|
||||||
}
|
}
|
||||||
doneFiles += 1;
|
doneFiles += 1;
|
||||||
onProgress({ doneBytes, doneFiles });
|
emitProgress();
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (!hasError && !stop.signal.aborted && !signal.aborted) {
|
||||||
|
hasError = true;
|
||||||
|
firstError = error;
|
||||||
|
}
|
||||||
stop.abort(error);
|
stop.abort(error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext));
|
const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext));
|
||||||
|
if (hasError) throw firstError;
|
||||||
const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');
|
const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');
|
||||||
if (failed) throw failed.reason;
|
if (failed) throw failed.reason;
|
||||||
if (linkedTargets) {
|
if (linkedTargets) {
|
||||||
for (const [path, stamp] of linkedTargets) {
|
for (const [path, stamp] of linkedTargets) {
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
|
if (!sameResource(stamp, await fsPromises.lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -142,9 +210,10 @@ export async function copyPlannedFiles(
|
|||||||
* when the copy started, so everything in it came from the copy.
|
* when the copy started, so everything in it came from the copy.
|
||||||
*/
|
*/
|
||||||
export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise<void> {
|
export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise<void> {
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
if (!targetExisted) {
|
if (!targetExisted) {
|
||||||
await rm(target, { recursive: true, force: true });
|
await fsPromises.rm(target, { recursive: true, force: true });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (const entry of await readdir(target)) await rm(join(target, entry), { recursive: true, force: true });
|
for (const entry of await fsPromises.readdir(target)) await fsPromises.rm(join(target, entry), { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,31 @@
|
|||||||
import { readdir } from 'node:fs/promises';
|
import { readdir } from 'node:fs/promises';
|
||||||
import { join } from 'node:path';
|
import { dirname, join } from 'node:path';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
|
import type { DataFolderProblem } from '@shared/schemas/install.ts';
|
||||||
|
import { copyPathContains } from './install-record.ts';
|
||||||
|
import { STOCK_BACKUP_FOLDER } from './stock-backup.ts';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
|
|
||||||
/** A data tree must keep the server's saves, logs and caches inside the selected folder. */
|
/** A data tree must keep the server's saves, logs and caches inside the selected folder. */
|
||||||
export async function requireUnredirectedData(root: string): Promise<void> {
|
export async function requireUnredirectedData(root: string): Promise<void> {
|
||||||
|
|||||||
@@ -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';
|
||||||
@@ -17,6 +22,25 @@ export function decalCachePath(dataPath: string, cacheId: string): string {
|
|||||||
return join(dataPath, CACHE_FOLDER, cacheId);
|
return join(dataPath, CACHE_FOLDER, cacheId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read-only check whether a player-chosen or registered folder contains a usable decal cache
|
||||||
|
* (<game>, <game>/cache, or <game>/cache/content). Returns the canonical cache/content path when
|
||||||
|
* valid, or null when absent, invalid, or unreadable.
|
||||||
|
*/
|
||||||
|
export async function detectDecalCacheSource(folderPath: string): Promise<string | null> {
|
||||||
|
if (!folderPath || !isAbsolute(folderPath)) return null;
|
||||||
|
try {
|
||||||
|
const rawSource = await realpath(folderPath).catch(() => null);
|
||||||
|
if (!rawSource) return null;
|
||||||
|
const resolved = resolvePlayerDecalCacheFolder(rawSource);
|
||||||
|
const canonical = await realpath(resolved).catch(() => null);
|
||||||
|
if (!canonical) return null;
|
||||||
|
return playerDecalCacheProblem(canonical) === undefined ? canonical : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise<string> {
|
async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise<string> {
|
||||||
if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed');
|
if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed');
|
||||||
const data = await canonicalCopyPath(dataPath);
|
const data = await canonicalCopyPath(dataPath);
|
||||||
@@ -33,8 +57,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 +85,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);
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
import { createHash } from 'node:crypto';
|
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 { join } from 'node:path';
|
||||||
|
import { isHardlinkableResource } from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
|
import type { InstallProgress } from '@shared/schemas/install.ts';
|
||||||
|
import type { CopyPlan } from './copy-game.ts';
|
||||||
|
|
||||||
export type ResourceMatchResult =
|
export type ResourceMatchResult =
|
||||||
| { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
|
| { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
|
||||||
@@ -83,3 +87,27 @@ function sameIdentityAndContents(left: BigIntStats, right: BigIntStats): boolean
|
|||||||
return right.isFile() && left.dev === right.dev && left.ino === right.ino &&
|
return right.isFile() && left.dev === right.dev && left.ino === right.ino &&
|
||||||
left.size === right.size && left.mtimeNs === right.mtimeNs;
|
left.size === right.size && left.mtimeNs === right.mtimeNs;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Collect and stat every eligible read-only resource pack in `plan` before hard-linking. */
|
||||||
|
export async function prepareHardlinks(
|
||||||
|
source: string,
|
||||||
|
plan: CopyPlan,
|
||||||
|
signal: AbortSignal,
|
||||||
|
report: (progress: InstallProgress) => void,
|
||||||
|
): Promise<ReadonlyMap<string, BigIntStats>> {
|
||||||
|
const candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
|
||||||
|
const totalBytes = candidates.reduce((total, file) => total + file.bytes, 0);
|
||||||
|
const links = new Map<string, BigIntStats>();
|
||||||
|
let doneBytes = 0;
|
||||||
|
let doneFiles = 0;
|
||||||
|
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
||||||
|
for (const file of candidates) {
|
||||||
|
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
|
||||||
|
if (verified) links.set(file.relativePath, verified);
|
||||||
|
doneBytes += file.bytes;
|
||||||
|
doneFiles += 1;
|
||||||
|
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
||||||
|
}
|
||||||
|
if (!links.size) throw new AppError('hardlink_no_match');
|
||||||
|
return links;
|
||||||
|
}
|
||||||
@@ -1,18 +1,21 @@
|
|||||||
import type { BigIntStats } from 'node:fs';
|
|
||||||
import { access, mkdir } from 'node:fs/promises';
|
import { access, mkdir } from 'node:fs/promises';
|
||||||
import { dirname, isAbsolute, join, relative } from 'node:path';
|
import { dirname, isAbsolute, relative } from 'node:path';
|
||||||
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
|
import { app } from 'electron';
|
||||||
|
import { isInSteamLibrary } from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
import type { ClientOrigin, 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 { readClientMarker, writeClientMarker } from './client-marker.ts';
|
||||||
import { requireUnredirectedData } from './data-location.ts';
|
import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts';
|
||||||
|
import { dataFolderProblem, requireUnredirectedData } from './data-location.ts';
|
||||||
import { discardDecalCache, importDecalCache } from './decals.ts';
|
import { discardDecalCache, importDecalCache } from './decals.ts';
|
||||||
import { statHardlinkResource } from './hardlink-files.ts';
|
import { prepareHardlinks } 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, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation, STOCK_BACKUP_FOLDER } from './stock-backup.ts';
|
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation } from './stock-backup.ts';
|
||||||
|
|
||||||
|
export { dataFolderProblem } from './data-location.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,
|
||||||
@@ -100,6 +103,16 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
|||||||
? await refreshStockBackup(copyPath)
|
? await refreshStockBackup(copyPath)
|
||||||
: await backUpStockFiles(copyPath);
|
: await backUpStockFiles(copyPath);
|
||||||
|
|
||||||
|
// Record launcher-created client origin on disk; never overwrite or fabricate a marker for existing folders.
|
||||||
|
let detectedOrigin: ClientOrigin | undefined;
|
||||||
|
if (request.method === 'copy') {
|
||||||
|
await writeClientMarker(copyPath, useHardLinks ? 'hardlink' : 'copy');
|
||||||
|
} else if (request.method === 'in-place') {
|
||||||
|
await writeClientMarker(copyPath, 'in-place');
|
||||||
|
} else {
|
||||||
|
detectedOrigin = (await readClientMarker(copyPath))?.origin;
|
||||||
|
}
|
||||||
|
|
||||||
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||||
const record: InstallRecord = {
|
const record: InstallRecord = {
|
||||||
id: request.id,
|
id: request.id,
|
||||||
@@ -115,6 +128,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
|||||||
installedAt: new Date().toISOString(),
|
installedAt: new Date().toISOString(),
|
||||||
lastCheckedAt: new Date().toISOString(),
|
lastCheckedAt: new Date().toISOString(),
|
||||||
...(decalCacheId ? { decalCacheId } : {}),
|
...(decalCacheId ? { decalCacheId } : {}),
|
||||||
|
...(detectedOrigin ? { detectedOrigin } : {}),
|
||||||
...copied,
|
...copied,
|
||||||
};
|
};
|
||||||
await writeInstallRecord(record);
|
await writeInstallRecord(record);
|
||||||
@@ -140,6 +154,12 @@ async function inspectInstallation(request: InstallRequest) {
|
|||||||
const [copyPath, dataPath, sourcePath] = await Promise.all([
|
const [copyPath, dataPath, sourcePath] = await Promise.all([
|
||||||
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
|
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
|
||||||
]);
|
]);
|
||||||
|
if (request.method === 'copy' && app.isPackaged) {
|
||||||
|
const launcherDir = await canonicalCopyPath(dirname(process.execPath));
|
||||||
|
if (copyPathContains(sourcePath, launcherDir)) {
|
||||||
|
throw new AppError('launcher_inside_source');
|
||||||
|
}
|
||||||
|
}
|
||||||
await requireAvailableCopy(request.id, copyPath, dataPath);
|
await requireAvailableCopy(request.id, copyPath, dataPath);
|
||||||
const dataProblem = dataFolderProblem(
|
const dataProblem = dataFolderProblem(
|
||||||
dataPath,
|
dataPath,
|
||||||
@@ -169,28 +189,6 @@ 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');
|
||||||
@@ -212,8 +210,10 @@ async function copyGame(
|
|||||||
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 = useHardLinks ? await prepareHardlinks(source, 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 linkTotalBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0;
|
||||||
const neededBytes = plan.totalBytes - linkedBytes + SPARE_BYTES;
|
const linkTotalFiles = hardlinks ? hardlinks.size : 0;
|
||||||
|
const copyTotalBytes = Math.max(0, plan.totalBytes - linkTotalBytes);
|
||||||
|
const neededBytes = copyTotalBytes + SPARE_BYTES;
|
||||||
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) {
|
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) {
|
||||||
throw new AppError('hardlink_file_changed');
|
throw new AppError('hardlink_file_changed');
|
||||||
}
|
}
|
||||||
@@ -222,11 +222,26 @@ async function copyGame(
|
|||||||
throw new AppError('not_enough_space', { neededGb: gigabytes(neededBytes), freeGb: gigabytes(available) });
|
throw new AppError('not_enough_space', { neededGb: gigabytes(neededBytes), freeGb: gigabytes(available) });
|
||||||
}
|
}
|
||||||
const targetExisted = await exists(target);
|
const targetExisted = await exists(target);
|
||||||
const totals = { totalBytes: plan.totalBytes, totalFiles: plan.files.length };
|
// Track actual disk-copy bytes in doneBytes/totalBytes so hard-linked resource archives
|
||||||
report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals });
|
// do not inflate the progress bar or cause sudden jumps when links are created.
|
||||||
|
const totals = {
|
||||||
|
totalBytes: copyTotalBytes > 0 ? copyTotalBytes : plan.files.length,
|
||||||
|
totalFiles: plan.files.length,
|
||||||
|
copyTotalBytes,
|
||||||
|
...(hardlinks ? { linkTotalBytes, linkTotalFiles } : {}),
|
||||||
|
};
|
||||||
|
const toProgress = (done: { doneFiles: number; copiedBytes: number; linkedBytes: number; linkedFiles: number }): InstallProgress => ({
|
||||||
|
phase: 'copying',
|
||||||
|
doneBytes: copyTotalBytes > 0 ? done.copiedBytes : done.doneFiles,
|
||||||
|
doneFiles: done.doneFiles,
|
||||||
|
copiedBytes: done.copiedBytes,
|
||||||
|
...(hardlinks ? { linkedBytes: done.linkedBytes, linkedFiles: done.linkedFiles } : {}),
|
||||||
|
...totals,
|
||||||
|
});
|
||||||
|
report(toProgress({ doneFiles: 0, copiedBytes: 0, linkedBytes: 0, linkedFiles: 0 }));
|
||||||
try {
|
try {
|
||||||
await copyPlannedFiles(source, target, plan, signal,
|
await copyPlannedFiles(source, target, plan, signal,
|
||||||
(done) => report({ phase: 'copying', ...done, ...totals }), hardlinks);
|
(done) => report(toProgress(done)), hardlinks);
|
||||||
if (hardlinks && (await inspectGameFolder(source)).version !== sourceVersion) 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),
|
||||||
@@ -241,29 +256,6 @@ async function copyGame(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function prepareHardlinks(
|
|
||||||
source: string,
|
|
||||||
plan: CopyPlan,
|
|
||||||
signal: AbortSignal,
|
|
||||||
report: (progress: InstallProgress) => void,
|
|
||||||
): Promise<ReadonlyMap<string, BigIntStats>> {
|
|
||||||
const candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
|
|
||||||
const totalBytes = candidates.reduce((total, file) => total + file.bytes, 0);
|
|
||||||
const links = new Map<string, BigIntStats>();
|
|
||||||
let doneBytes = 0;
|
|
||||||
let doneFiles = 0;
|
|
||||||
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
|
||||||
for (const file of candidates) {
|
|
||||||
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
|
|
||||||
if (verified) links.set(file.relativePath, verified);
|
|
||||||
doneBytes += file.bytes;
|
|
||||||
doneFiles += 1;
|
|
||||||
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
|
||||||
}
|
|
||||||
if (!links.size) throw new AppError('hardlink_no_match');
|
|
||||||
return links;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function requireGameFolder(path: string) {
|
async function requireGameFolder(path: string) {
|
||||||
const game = await inspectGameFolder(path);
|
const game = await inspectGameFolder(path);
|
||||||
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path });
|
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path });
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { join, normalize } from 'node:path';
|
||||||
|
import { rawFs } from '../../util/raw-fs.ts';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detection of incomplete optional UHQ texture packs (`uhq_vehicles`, `uhq_aircraft`,
|
||||||
|
* `uhq_environment`, etc.) inside a War Thunder folder.
|
||||||
|
*
|
||||||
|
* War Thunder writes `content/pkg_<name>.rq2` when an optional pack is requested and only writes
|
||||||
|
* `content/pkg_<name>.ver` once its download finishes (`PACKAGE_STATUS_OK`). However, at startup
|
||||||
|
* `aces.exe` mounts `content.hq/<name>/res/grp_hdr.vromfs.bin` without requiring the `.ver` file,
|
||||||
|
* registering every `.dxp.bin` listed in the header and crashing later with fatal error 81110007
|
||||||
|
* (`Can't open TexPack`) if any texture pack is missing.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const UHQ_PACK_PATTERN = /^uhq_[a-z0-9_]+$/i;
|
||||||
|
const UHQ_RQ2_PATTERN = /^pkg_(uhq_[a-z0-9_]+)\.rq2$/i;
|
||||||
|
const UHQ_VER_PATTERN = /^pkg_(uhq_[a-z0-9_]+)\.ver$/i;
|
||||||
|
|
||||||
|
export interface IncompleteUhqPack {
|
||||||
|
readonly name: string;
|
||||||
|
readonly hasHeader: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inspects `root` for optional UHQ packs that are incomplete:
|
||||||
|
* - `content/pkg_<name>.rq2` exists without `content/pkg_<name>.ver` (`PACKAGE_STATUS_REQUESTED`), or
|
||||||
|
* - `content.hq/<name>/res/grp_hdr.vromfs.bin` exists with no `.dxp.bin` texture packs beside it.
|
||||||
|
*/
|
||||||
|
export async function inspectIncompleteUhqPacks(root: string): Promise<IncompleteUhqPack[]> {
|
||||||
|
const rq2Packs = new Set<string>();
|
||||||
|
const verPacks = new Set<string>();
|
||||||
|
const candidates = new Set<string>();
|
||||||
|
|
||||||
|
for (const name of await readDirNames(join(root, 'content'))) {
|
||||||
|
const rq2 = UHQ_RQ2_PATTERN.exec(name);
|
||||||
|
if (rq2) {
|
||||||
|
const pack = rq2[1]!.toLowerCase();
|
||||||
|
rq2Packs.add(pack);
|
||||||
|
candidates.add(pack);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const ver = UHQ_VER_PATTERN.exec(name);
|
||||||
|
if (ver) verPacks.add(ver[1]!.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const name of await readDirNames(join(root, 'content.hq'))) {
|
||||||
|
if (UHQ_PACK_PATTERN.test(name)) candidates.add(name.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
const incomplete: IncompleteUhqPack[] = [];
|
||||||
|
for (const pack of [...candidates].sort()) {
|
||||||
|
const resDir = join(root, 'content.hq', pack, 'res');
|
||||||
|
const resFiles = await readDirNames(resDir);
|
||||||
|
const hasHeader = resFiles.some((file) => file.toLowerCase() === 'grp_hdr.vromfs.bin');
|
||||||
|
const hasDxp = resFiles.some((file) => file.toLowerCase().endsWith('.dxp.bin'));
|
||||||
|
const requestedWithoutVer = rq2Packs.has(pack) && !verPacks.has(pack);
|
||||||
|
const emptyHeaderOnly = hasHeader && !hasDxp;
|
||||||
|
if (requestedWithoutVer || emptyHeaderOnly) {
|
||||||
|
incomplete.push({ name: pack, hasHeader });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return incomplete;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Names of all incomplete optional UHQ packs in `root`. */
|
||||||
|
export async function findIncompleteUhqPacks(root: string): Promise<string[]> {
|
||||||
|
return (await inspectIncompleteUhqPacks(root)).map((pack) => pack.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Names of incomplete optional UHQ packs in `root` whose `grp_hdr.vromfs.bin` is present,
|
||||||
|
* which causes `aces.exe` to mount the pack and fail with 81110007 when streaming textures.
|
||||||
|
*/
|
||||||
|
export async function findBlockingIncompleteUhqPacks(root: string): Promise<string[]> {
|
||||||
|
return (await inspectIncompleteUhqPacks(root))
|
||||||
|
.filter((pack) => pack.hasHeader)
|
||||||
|
.map((pack) => pack.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether `relativePath` (relative to the War Thunder root) belongs to any UHQ pack in `packs`:
|
||||||
|
* `content.hq/<pack>/...`, `patch/content.hq/<pack>/...`, or `content/pkg_<pack>.rq2`.
|
||||||
|
*/
|
||||||
|
export function isPathInUhqPacks(relativePath: string, packs: ReadonlySet<string>): boolean {
|
||||||
|
if (packs.size === 0) return false;
|
||||||
|
const parts = normalize(relativePath).replace(/\\/g, '/').toLowerCase().split('/').filter(Boolean);
|
||||||
|
if (parts.length >= 2 && parts[0] === 'content.hq') return packs.has(parts[1]!);
|
||||||
|
if (parts.length >= 3 && parts[0] === 'patch' && parts[1] === 'content.hq') return packs.has(parts[2]!);
|
||||||
|
if (parts.length === 2 && parts[0] === 'content') {
|
||||||
|
const rq2 = UHQ_RQ2_PATTERN.exec(parts[1]!);
|
||||||
|
return rq2 !== null && packs.has(rq2[1]!);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readDirNames(folder: string): Promise<string[]> {
|
||||||
|
try {
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
|
await fsPromises.access(folder);
|
||||||
|
return await fsPromises.readdir(folder);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,7 +11,10 @@ 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 { findBlockingIncompleteUhqPacks } from '../install/uhq-packages.ts';
|
||||||
|
import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts';
|
||||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||||
|
import { selectedMapNavPack } from '../map-nav/map-nav-store.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';
|
||||||
import { gameProcessRunning } from './game-process.ts';
|
import { gameProcessRunning } from './game-process.ts';
|
||||||
@@ -67,9 +70,13 @@ export function startLaunch(report: LaunchJob['report']): LaunchState {
|
|||||||
case 'launch_server_exited':
|
case 'launch_server_exited':
|
||||||
update(job, { phase: 'server-exited', ...context });
|
update(job, { phase: 'server-exited', ...context });
|
||||||
break;
|
break;
|
||||||
default:
|
default: {
|
||||||
update(job, { phase: 'failed', error: code, ...context });
|
const errorParams = error instanceof AppError && Object.keys(error.params).length > 0
|
||||||
|
? { errorParams: { ...error.params } }
|
||||||
|
: {};
|
||||||
|
update(job, { phase: 'failed', error: code, ...errorParams, ...context });
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}).finally(() => {
|
}).finally(() => {
|
||||||
if (active === job) active = null;
|
if (active === job) active = null;
|
||||||
@@ -108,7 +115,7 @@ 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);
|
await buildForLaunch(job, record, plan, settings);
|
||||||
|
|
||||||
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
|
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
|
||||||
@@ -123,7 +130,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 +149,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> {
|
||||||
@@ -183,13 +200,20 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
|
|||||||
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 incompleteUhq = await findBlockingIncompleteUhqPacks(copyPath);
|
||||||
|
if (incompleteUhq.length > 0) {
|
||||||
|
console.warn(`[launch] incomplete optional UHQ pack(s) detected in ${copyPath}: ${incompleteUhq.join(', ')}`);
|
||||||
|
throw new AppError('launch_incomplete_uhq_packs', { packs: incompleteUhq.join(', ') });
|
||||||
|
}
|
||||||
|
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, settings: Settings): 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 (settings.autoSaveBackups) {
|
if (settings.autoSaveBackups) {
|
||||||
for (const { userId } of new AccountStore(dataPath).all()) {
|
for (const { userId } of new AccountStore(dataPath).all()) {
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
@@ -199,6 +223,7 @@ 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();
|
const buildStart = Date.now();
|
||||||
|
const mapNavFolder = selectedMapNavPack(dataPath)?.folder;
|
||||||
let writtenFiles = 0;
|
let writtenFiles = 0;
|
||||||
await buildCopy({
|
await buildCopy({
|
||||||
kind: 'build',
|
kind: 'build',
|
||||||
@@ -208,9 +233,12 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
|
|||||||
port,
|
port,
|
||||||
steamLibraryConfirmed,
|
steamLibraryConfirmed,
|
||||||
...resourcePaths(),
|
...resourcePaths(),
|
||||||
|
...(mapNavFolder === undefined ? {} : { mapNavFolder }),
|
||||||
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
|
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
|
||||||
hookLogging: settings.loggingEnabled,
|
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;
|
writtenFiles = filesWritten;
|
||||||
if (!signal.aborted) update(job, {
|
if (!signal.aborted) update(job, {
|
||||||
|
|||||||
@@ -33,13 +33,22 @@ 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, loggingEnabled = true }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
|
{ gameFolder, dataFolder, port, loggingEnabled = true, modsDir, enabledModIds }: StartLocalServerOptions, signal: AbortSignal,
|
||||||
): Promise<LocalServer> {
|
): Promise<LocalServer> {
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
|
const workerArgs = [gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'];
|
||||||
|
if (modsDir && enabledModIds && enabledModIds.length > 0) {
|
||||||
|
workerArgs.push(modsDir, JSON.stringify(enabledModIds));
|
||||||
|
}
|
||||||
const worker = utilityProcess.fork(
|
const worker = utilityProcess.fork(
|
||||||
join(import.meta.dirname, 'server-worker.js'),
|
join(import.meta.dirname, 'server-worker.js'),
|
||||||
[gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'],
|
workerArgs,
|
||||||
{
|
{
|
||||||
serviceName: 'WTOffline local server',
|
serviceName: 'WTOffline local server',
|
||||||
stdio: 'pipe',
|
stdio: 'pipe',
|
||||||
|
|||||||
@@ -45,12 +45,19 @@ 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(
|
const server = await startLocalServer(
|
||||||
{ gameFolder: copyPath, dataFolder: dataPath, port, loggingEnabled: settings.loggingEnabled },
|
{
|
||||||
|
gameFolder: copyPath,
|
||||||
|
dataFolder: dataPath,
|
||||||
|
port,
|
||||||
|
loggingEnabled: settings.loggingEnabled,
|
||||||
|
...(mods && mods.enabledModIds.length > 0 ? { modsDir: mods.modsDir, enabledModIds: mods.enabledModIds } : {}),
|
||||||
|
},
|
||||||
signal,
|
signal,
|
||||||
);
|
);
|
||||||
const stop = new AbortController();
|
const stop = new AbortController();
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
import { readFile, writeFile } from 'node:fs/promises';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { promisify } from 'node:util';
|
||||||
|
import { PatchPackError } from '@wto/patcher';
|
||||||
|
import { MapNavManifestSchema, type MapNavManifest } from '@shared/schemas/map-nav-pack.ts';
|
||||||
|
import { installerDigest } from '../app-update/installer-integrity.ts';
|
||||||
|
import { RELEASE_MANIFEST_MAX_BYTES } from '../patch-pack/release-assets.ts';
|
||||||
|
|
||||||
|
const execute = promisify(execFile);
|
||||||
|
|
||||||
|
/** Compare the exact maps written by the installer with the signed release manifest. */
|
||||||
|
export async function verifyMapNavFolder(folder: string, manifest: MapNavManifest): Promise<void> {
|
||||||
|
const stored = MapNavManifestSchema.parse(JSON.parse(await readFile(join(folder, 'manifest.json'), 'utf8')));
|
||||||
|
if (JSON.stringify(stored) !== JSON.stringify(MapNavManifestSchema.parse(manifest))) {
|
||||||
|
throw new PatchPackError('contents', 'The map pack manifest does not match the signed release.');
|
||||||
|
}
|
||||||
|
for (const entry of manifest.maps) {
|
||||||
|
const digest = await installerDigest(join(folder, 'maps', entry.level + '.wtonav'), entry.size);
|
||||||
|
if (digest.size !== entry.size || digest.sha256 !== entry.sha256) {
|
||||||
|
throw new PatchPackError('contents', 'The map file does not match the signed release: ' + entry.level);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The ZIP is already verified. Extract only the exact file names and sizes the manifest promises. */
|
||||||
|
export async function extractMapNavArchive(zip: string, staging: string, manifest: MapNavManifest): Promise<string> {
|
||||||
|
const folder = join(staging, 'map-nav');
|
||||||
|
const index = join(staging, 'expected-maps.json');
|
||||||
|
const script = join(staging, 'extract-maps.ps1');
|
||||||
|
const expected = manifest.maps.map(({ level, size }) => ({ name: 'map-nav/maps/' + level + '.wtonav', size }));
|
||||||
|
await writeFile(index, JSON.stringify(expected));
|
||||||
|
await writeFile(script, '\uFEFF' + EXTRACTION_SCRIPT.join('\r\n'), 'utf8');
|
||||||
|
await execute('powershell.exe', [
|
||||||
|
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script,
|
||||||
|
zip, staging, index, String(RELEASE_MANIFEST_MAX_BYTES),
|
||||||
|
], { windowsHide: true, timeout: 180_000 });
|
||||||
|
await verifyMapNavFolder(folder, manifest);
|
||||||
|
return folder;
|
||||||
|
}
|
||||||
|
|
||||||
|
const EXTRACTION_SCRIPT = [
|
||||||
|
'param([string]$ZipPath, [string]$Root, [string]$IndexPath, [long]$ManifestLimit)',
|
||||||
|
"$ErrorActionPreference = 'Stop'",
|
||||||
|
'Add-Type -AssemblyName System.IO.Compression.FileSystem',
|
||||||
|
'$expected = [System.Collections.Generic.Dictionary[string,long]]::new([StringComparer]::Ordinal)',
|
||||||
|
'foreach ($item in (Get-Content -LiteralPath $IndexPath -Raw -Encoding UTF8 | ConvertFrom-Json)) { $expected.Add($item.name, $item.size) }',
|
||||||
|
'$seenManifest = $false',
|
||||||
|
'$zip = [System.IO.Compression.ZipFile]::OpenRead($ZipPath)',
|
||||||
|
'try {',
|
||||||
|
' [System.IO.Directory]::CreateDirectory((Join-Path $Root "map-nav/maps")) | Out-Null',
|
||||||
|
' foreach ($entry in $zip.Entries) {',
|
||||||
|
' $name = $entry.FullName',
|
||||||
|
' if ($entry.Length -eq 0 -and ($name -ceq "map-nav/" -or $name -ceq "map-nav/maps/")) { continue }',
|
||||||
|
' if (!$seenManifest -and $name -ceq "map-nav/manifest.json" -and $entry.Length -le $ManifestLimit) {',
|
||||||
|
' $seenManifest = $true',
|
||||||
|
' } else {',
|
||||||
|
' if (!$expected.ContainsKey($name) -or $entry.Length -ne $expected[$name]) { throw "Unexpected map pack entry: $name" }',
|
||||||
|
' [void]$expected.Remove($name)',
|
||||||
|
' }',
|
||||||
|
' [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, (Join-Path $Root $name), $false)',
|
||||||
|
' }',
|
||||||
|
' if (!$seenManifest -or $expected.Count -gt 0) { throw "The map pack is incomplete." }',
|
||||||
|
'} finally { $zip.Dispose() }',
|
||||||
|
];
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import { readFileSync, readdirSync } from 'node:fs';
|
||||||
|
import { mkdir, rename, rm } from 'node:fs/promises';
|
||||||
|
import { dirname, join } from 'node:path';
|
||||||
|
import { app } from 'electron';
|
||||||
|
import { compareAppVersions } from '@wto/patcher';
|
||||||
|
import {
|
||||||
|
MAP_NAV_FORMAT, MapNavManifestSchema, MapNavVersionSchema, type ActiveMapNav, type MapNavManifest,
|
||||||
|
} from '@shared/schemas/map-nav-pack.ts';
|
||||||
|
import { writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||||
|
import { bundledResourcePaths } from '../resources/resource-paths.ts';
|
||||||
|
|
||||||
|
interface MapNavPack {
|
||||||
|
readonly folder: string;
|
||||||
|
readonly info: NonNullable<ActiveMapNav>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapNavStoreFolder(): string {
|
||||||
|
return join(app.getPath('userData'), 'map-nav');
|
||||||
|
}
|
||||||
|
|
||||||
|
function activeFile(): string {
|
||||||
|
return join(mapNavStoreFolder(), 'active.json');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function needsMapNavLauncherUpdate(manifest: MapNavManifest): boolean {
|
||||||
|
return manifest.format !== MAP_NAV_FORMAT || compareAppVersions(app.getVersion(), manifest.minAppVersion) < 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readManifest(folder: string): MapNavManifest | null {
|
||||||
|
try {
|
||||||
|
return MapNavManifestSchema.parse(JSON.parse(readFileSync(join(dirname(folder), 'manifest.json'), 'utf8')));
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') console.warn('[map-nav] could not read the pack manifest:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function foundPack(folder: string, source: NonNullable<ActiveMapNav>['source']): MapNavPack | null {
|
||||||
|
let maps: string[];
|
||||||
|
try {
|
||||||
|
maps = readdirSync(folder, { withFileTypes: true })
|
||||||
|
.filter((file) => (file.isFile() || file.isSymbolicLink()) && file.name.endsWith('.wtonav'))
|
||||||
|
.map((file) => file.name);
|
||||||
|
} catch (error) {
|
||||||
|
if (!['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) {
|
||||||
|
console.warn('[map-nav] could not read the maps folder:', error);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (maps.length === 0) return null;
|
||||||
|
const manifest = readManifest(folder);
|
||||||
|
if (manifest && needsMapNavLauncherUpdate(manifest)) return null;
|
||||||
|
return {
|
||||||
|
folder,
|
||||||
|
info: { source, version: manifest?.version ?? null, gameVersions: manifest?.gameVersions ?? [], mapCount: maps.length },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function downloadedPack(): MapNavPack | null {
|
||||||
|
try {
|
||||||
|
const active = JSON.parse(readFileSync(activeFile(), 'utf8')) as { version?: unknown };
|
||||||
|
const version = MapNavVersionSchema.parse(active.version);
|
||||||
|
const pack = foundPack(join(mapNavStoreFolder(), version, 'maps'), 'downloaded');
|
||||||
|
return pack?.info.version === version ? pack : null;
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') console.warn('[map-nav] the active pack is unusable:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function selectedMapNavPack(dataPath: string | null): MapNavPack | null {
|
||||||
|
return downloadedPack() ??
|
||||||
|
(dataPath ? foundPack(join(dataPath, 'map-nav', 'maps'), 'local') : null) ??
|
||||||
|
foundPack(bundledResourcePaths().bundledMapNavFolder, 'bundled');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Commit a verified map directory, then switch the pointer used by new launches. */
|
||||||
|
export async function activateMapNavPack(version: string, stagedFolder?: string): Promise<void> {
|
||||||
|
const store = mapNavStoreFolder();
|
||||||
|
if (stagedFolder !== undefined) {
|
||||||
|
await mkdir(store, { recursive: true });
|
||||||
|
await rename(stagedFolder, join(store, version));
|
||||||
|
}
|
||||||
|
await writeJsonAtomic(activeFile(), { version });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deactivateMapNavPack(): Promise<void> {
|
||||||
|
await rm(activeFile(), { force: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
import { lstat, mkdir, mkdtemp, realpath, rm } from 'node:fs/promises';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { app } from 'electron';
|
||||||
|
import {
|
||||||
|
comparePackVersions, packSigningPublicKey, PatchPackError, patchPackTuning, verifyEd25519,
|
||||||
|
} from '@wto/patcher';
|
||||||
|
import { AppError } from '@shared/errors.ts';
|
||||||
|
import type { AppUpdateProgress } from '@shared/schemas/app-update.ts';
|
||||||
|
import {
|
||||||
|
MapNavReleaseManifestSchema, mapNavSignaturePayload, type ActiveMapNav, type MapNavApplyResult,
|
||||||
|
type MapNavCheck, type MapNavReleaseManifest,
|
||||||
|
} from '@shared/schemas/map-nav-pack.ts';
|
||||||
|
import { getSettings } from '../config/settings-store.ts';
|
||||||
|
import { readInstallRecord } from '../install/install-record.ts';
|
||||||
|
import { packUpdateProblem } from '../patch-pack/pack-update.ts';
|
||||||
|
import {
|
||||||
|
readReleaseAsset, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, stageReleaseAsset,
|
||||||
|
} from '../patch-pack/release-assets.ts';
|
||||||
|
import {
|
||||||
|
newestProjectRelease, projectReleaseVersion, withReleaseSources, type PackReleaseFiles,
|
||||||
|
} from '../patch-pack/release-feed.ts';
|
||||||
|
import { extractMapNavArchive, verifyMapNavFolder } from './map-nav-archive.ts';
|
||||||
|
import {
|
||||||
|
activateMapNavPack, deactivateMapNavPack, mapNavStoreFolder, needsMapNavLauncherUpdate, selectedMapNavPack,
|
||||||
|
} from './map-nav-store.ts';
|
||||||
|
|
||||||
|
let updating = false;
|
||||||
|
|
||||||
|
async function duringMapNavUpdate<T>(update: () => Promise<T>): Promise<T> {
|
||||||
|
if (updating) throw new AppError('map_nav_update_busy');
|
||||||
|
updating = true;
|
||||||
|
try {
|
||||||
|
return await update();
|
||||||
|
} finally {
|
||||||
|
updating = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function activeMapNav(): Promise<ActiveMapNav> {
|
||||||
|
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
||||||
|
const useLab = !app.isPackaged && settings.developerMode;
|
||||||
|
const dataPath = (useLab ? settings.labDataPath : null) ?? record?.dataPath ?? null;
|
||||||
|
return selectedMapNavPack(dataPath)?.info ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNewer(version: string, active: ActiveMapNav): boolean {
|
||||||
|
return !active?.version || comparePackVersions(version, active.version) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signedManifest(files: PackReleaseFiles, key: string): Promise<MapNavReleaseManifest> {
|
||||||
|
const signal = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
|
||||||
|
const [bytes, signature] = await Promise.all([
|
||||||
|
readReleaseAsset(files.manifestUrl, RELEASE_MANIFEST_MAX_BYTES, signal, files.source),
|
||||||
|
readReleaseAsset(files.signatureUrl, RELEASE_SIGNATURE_MAX_BYTES, signal, files.source),
|
||||||
|
]);
|
||||||
|
const decoder = new TextDecoder('utf-8', { fatal: true });
|
||||||
|
if (!verifyEd25519(mapNavSignaturePayload(bytes), decoder.decode(signature), key)) {
|
||||||
|
throw new PatchPackError('signature', 'The map pack manifest signature does not match.');
|
||||||
|
}
|
||||||
|
const manifest = MapNavReleaseManifestSchema.parse(JSON.parse(decoder.decode(bytes)));
|
||||||
|
if (manifest.version !== files.version) throw new PatchPackError('contents', 'The signed map pack version does not match the release.');
|
||||||
|
return manifest;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkMapNavUpdate(): Promise<MapNavCheck> {
|
||||||
|
const active = await activeMapNav();
|
||||||
|
const key = packSigningPublicKey();
|
||||||
|
if (!key) return { status: 'failed', active, latest: null, problem: 'no_signing_key' };
|
||||||
|
try {
|
||||||
|
const offer = await withReleaseSources(async (source) => {
|
||||||
|
const files = await newestProjectRelease('mapNav', active?.version ?? null, source);
|
||||||
|
return files ? { files, manifest: await signedManifest(files, key) } : null;
|
||||||
|
});
|
||||||
|
if (!offer) return { status: 'up_to_date', active, latest: null, problem: null };
|
||||||
|
const { files, manifest } = offer;
|
||||||
|
const latest = {
|
||||||
|
version: manifest.version, gameVersions: manifest.gameVersions, minAppVersion: manifest.minAppVersion,
|
||||||
|
publishedAt: files.publishedAt, mapCount: manifest.maps.length, size: manifest.archive.size,
|
||||||
|
};
|
||||||
|
const status = !isNewer(manifest.version, active) ? 'up_to_date'
|
||||||
|
: needsMapNavLauncherUpdate(manifest) ? 'needs_app_update' : 'available';
|
||||||
|
return { status, active, latest, problem: null };
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[map-nav] update check failed:', error);
|
||||||
|
return { status: 'failed', active, latest: null, problem: packUpdateProblem(error) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function installMapNav(
|
||||||
|
files: PackReleaseFiles, manifest: MapNavReleaseManifest, report: (progress: AppUpdateProgress) => void,
|
||||||
|
): Promise<void> {
|
||||||
|
const root = mapNavStoreFolder();
|
||||||
|
const installed = join(root, manifest.version);
|
||||||
|
const existing = await lstat(installed).catch((error: NodeJS.ErrnoException) => {
|
||||||
|
if (error.code !== 'ENOENT') throw error;
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
if (!existing.isDirectory()) throw new PatchPackError('contents', 'The destination for this map pack is not a directory.');
|
||||||
|
await verifyMapNavFolder(installed, manifest);
|
||||||
|
await activateMapNavPack(manifest.version);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await mkdir(root, { recursive: true });
|
||||||
|
const staging = await mkdtemp(join(await realpath(root), '.map-nav-install-'));
|
||||||
|
try {
|
||||||
|
const zip = join(staging, 'maps.zip');
|
||||||
|
await stageReleaseAsset(files.zipUrl, files.source, manifest.archive, zip, report);
|
||||||
|
const folder = await extractMapNavArchive(zip, staging, manifest);
|
||||||
|
await activateMapNavPack(manifest.version, folder);
|
||||||
|
} finally {
|
||||||
|
await rm(staging, { recursive: true, force: true }).catch((error: unknown) =>
|
||||||
|
console.warn('[map-nav] could not remove the installation staging directory:', error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyMapNavUpdate(version: string, report: (progress: AppUpdateProgress) => void): Promise<MapNavApplyResult> {
|
||||||
|
return duringMapNavUpdate(async () => {
|
||||||
|
const key = packSigningPublicKey();
|
||||||
|
if (!key) return { ok: false, problem: 'no_signing_key' };
|
||||||
|
if (!isNewer(version, await activeMapNav())) return { ok: false, problem: 'up_to_date' };
|
||||||
|
try {
|
||||||
|
const installed = await withReleaseSources(async (source) => {
|
||||||
|
const files = await projectReleaseVersion('mapNav', version, source);
|
||||||
|
const manifest = await signedManifest(files, key);
|
||||||
|
if (needsMapNavLauncherUpdate(manifest)) return false;
|
||||||
|
await installMapNav(files, manifest, report);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
if (!installed) return { ok: false, problem: 'needs_app_update' };
|
||||||
|
return { ok: true, active: await activeMapNav() };
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[map-nav] update failed:', error);
|
||||||
|
return { ok: false, problem: packUpdateProblem(error) };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useLocalMapNav(): Promise<ActiveMapNav> {
|
||||||
|
return duringMapNavUpdate(async () => {
|
||||||
|
await deactivateMapNavPack();
|
||||||
|
return activeMapNav();
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,436 @@
|
|||||||
|
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 { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.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 defaultDir = await resolveDialogDefaultPath('mod-preset');
|
||||||
|
const fileName = `${safeName}.wto-mods-preset.json`;
|
||||||
|
const dialogOptions = {
|
||||||
|
defaultPath: defaultDir ? join(defaultDir, fileName) : fileName,
|
||||||
|
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');
|
||||||
|
await rememberDialogPath('mod-preset', choice.filePath);
|
||||||
|
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 defaultPath = await resolveDialogDefaultPath('mod-preset');
|
||||||
|
const dialogOptions = {
|
||||||
|
properties: ['openFile'] as Array<'openFile'>,
|
||||||
|
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
|
||||||
|
...(defaultPath ? { defaultPath } : {}),
|
||||||
|
};
|
||||||
|
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) };
|
||||||
|
}
|
||||||
|
await rememberDialogPath('mod-preset', choice.filePaths[0]);
|
||||||
|
|
||||||
|
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 });
|
||||||
|
if (folderPath !== null) await rememberDialogPath('mods-folder', 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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -42,7 +42,7 @@ export async function checkPackUpdate(): Promise<PackCheck> {
|
|||||||
return { status, active, latest: release(found), problem: null };
|
return { status, active, latest: release(found), problem: null };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('[patch-pack] update check failed:', error);
|
console.warn('[patch-pack] update check failed:', error);
|
||||||
return { status: 'failed', active, latest: null, problem: problemOf(error) };
|
return { status: 'failed', active, latest: null, problem: packUpdateProblem(error) };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,7 +69,7 @@ export async function applyPackUpdate(version: string): Promise<PackApplyResult>
|
|||||||
return { ok: true, active: activePatchSet() };
|
return { ok: true, active: activePatchSet() };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('[patch-pack] update failed:', error);
|
console.warn('[patch-pack] update failed:', error);
|
||||||
return { ok: false, problem: problemOf(error) };
|
return { ok: false, problem: packUpdateProblem(error) };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,7 +110,7 @@ function isNewer(candidate: string, active: string | null): boolean {
|
|||||||
return active === null || comparePackVersions(candidate, active) > 0;
|
return active === null || comparePackVersions(candidate, active) > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
function problemOf(error: unknown): PackProblem {
|
export function packUpdateProblem(error: unknown): PackProblem {
|
||||||
if (error instanceof ReleasePageLimitError) return 'page_limit';
|
if (error instanceof ReleasePageLimitError) return 'page_limit';
|
||||||
if (error instanceof FeedUnreachableError) return 'network';
|
if (error instanceof FeedUnreachableError) return 'network';
|
||||||
if (error instanceof PatchPackError) {
|
if (error instanceof PatchPackError) {
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
import type { Readable } from 'node:stream';
|
import { createHash } from 'node:crypto';
|
||||||
|
import { createWriteStream } from 'node:fs';
|
||||||
|
import { mkdir, rename, unlink } from 'node:fs/promises';
|
||||||
|
import { dirname } from 'node:path';
|
||||||
|
import { Transform, type Readable } from 'node:stream';
|
||||||
|
import { pipeline } from 'node:stream/promises';
|
||||||
import { net, type IncomingMessage } from 'electron';
|
import { net, type IncomingMessage } from 'electron';
|
||||||
import { PatchPackError } from '@wto/patcher';
|
import { PatchPackError } from '@wto/patcher';
|
||||||
import type { ReleaseSource } from './release-feed.ts';
|
import type { ReleaseSource } from './release-feed.ts';
|
||||||
@@ -85,3 +90,50 @@ export async function readReleaseAsset(
|
|||||||
}
|
}
|
||||||
return Buffer.concat(chunks);
|
return Buffer.concat(chunks);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Stream a large, signed asset to disk and install the file only after its size and hash match. */
|
||||||
|
export async function stageReleaseAsset(
|
||||||
|
url: URL, source: ReleaseSource, file: { readonly size: number; readonly sha256: string }, target: string,
|
||||||
|
report: (progress: { received: number; total: number }) => void,
|
||||||
|
): Promise<void> {
|
||||||
|
const partial = target + '.partial';
|
||||||
|
const deadline = AbortSignal.timeout(30 * 60_000);
|
||||||
|
const hash = createHash('sha256');
|
||||||
|
let received = 0;
|
||||||
|
let reportedAt = 0;
|
||||||
|
try {
|
||||||
|
await mkdir(dirname(target), { recursive: true });
|
||||||
|
await removePartial(partial);
|
||||||
|
const response = await requestReleaseAsset(url, deadline, source);
|
||||||
|
const monitor = new Transform({
|
||||||
|
transform(chunk: Buffer, _encoding, done) {
|
||||||
|
received += chunk.length;
|
||||||
|
if (received > file.size) {
|
||||||
|
done(new PatchPackError('size', 'The download is larger than its signed size.'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hash.update(chunk);
|
||||||
|
if (received === file.size || Date.now() - reportedAt >= 200) {
|
||||||
|
reportedAt = Date.now();
|
||||||
|
report({ received, total: file.size });
|
||||||
|
}
|
||||||
|
done(null, chunk);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline });
|
||||||
|
if (received !== file.size) throw new FeedUnreachableError('The update download is incomplete.');
|
||||||
|
if (hash.digest('hex') !== file.sha256) throw new PatchPackError('signature', 'The download does not match the signed release.');
|
||||||
|
await rename(partial, target);
|
||||||
|
} catch (error) {
|
||||||
|
if (deadline.aborted) throw new FeedUnreachableError('The update download timed out.', { cause: error });
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
await removePartial(partial).catch((error: unknown) => console.warn('[release-assets] removing a partial download failed:', error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removePartial(path: string): Promise<void> {
|
||||||
|
await unlink(path).catch((error: NodeJS.ErrnoException) => {
|
||||||
|
if (error.code !== 'ENOENT') throw error;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* 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 {
|
||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
} from '@wto/patcher';
|
} from '@wto/patcher';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { AppReleaseVersionSchema, launcherReleaseFiles, portableLauncherReleaseFiles } from '@shared/schemas/app-update.ts';
|
import { AppReleaseVersionSchema, launcherReleaseFiles, portableLauncherReleaseFiles } from '@shared/schemas/app-update.ts';
|
||||||
|
import { MAP_NAV_TAG_PREFIX, MapNavVersionSchema, mapNavReleaseFiles } from '@shared/schemas/map-nav-pack.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';
|
||||||
@@ -45,6 +46,7 @@ export interface PackReleaseFiles {
|
|||||||
interface ReleaseByChannel {
|
interface ReleaseByChannel {
|
||||||
launcher: LauncherRelease;
|
launcher: LauncherRelease;
|
||||||
pack: PackReleaseFiles;
|
pack: PackReleaseFiles;
|
||||||
|
mapNav: PackReleaseFiles;
|
||||||
}
|
}
|
||||||
|
|
||||||
type ReleaseChannel = keyof ReleaseByChannel;
|
type ReleaseChannel = keyof ReleaseByChannel;
|
||||||
@@ -62,6 +64,7 @@ export class ReleasePageLimitError extends Error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
|
const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
|
||||||
|
const MAX_RELEASE_NOTES_CHARS = 64 * 1024;
|
||||||
const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() });
|
const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() });
|
||||||
const LauncherReleaseEntry = z.object({
|
const LauncherReleaseEntry = z.object({
|
||||||
draft: z.literal(false),
|
draft: z.literal(false),
|
||||||
@@ -98,18 +101,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> {
|
||||||
@@ -152,7 +172,7 @@ export async function projectReleaseVersion<Channel extends ReleaseChannel>(
|
|||||||
|
|
||||||
async function readProjectReleases(source: ReleaseSource): Promise<ReleaseListing> {
|
async function readProjectReleases(source: ReleaseSource): Promise<ReleaseListing> {
|
||||||
const tuning = patchPackTuning();
|
const tuning = patchPackTuning();
|
||||||
const versions: ReleaseVersions = { launcher: new Map(), pack: new Map() };
|
const versions: ReleaseVersions = { launcher: new Map(), pack: new Map(), mapNav: new Map() };
|
||||||
const incomplete: Partial<Record<ReleaseChannel, string>> = {};
|
const incomplete: Partial<Record<ReleaseChannel, string>> = {};
|
||||||
const url = new URL(source.feed);
|
const url = new URL(source.feed);
|
||||||
url.searchParams.set('per_page', String(tuning.releasePageSize));
|
url.searchParams.set('per_page', String(tuning.releasePageSize));
|
||||||
@@ -204,11 +224,16 @@ function collectReleases(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const version = packVersionOfTag(tag);
|
const mapNav = tag.startsWith(MAP_NAV_TAG_PREFIX);
|
||||||
|
const channel = mapNav ? 'mapNav' : 'pack';
|
||||||
|
const version = mapNav ? MapNavVersionSchema.safeParse(tag.slice(MAP_NAV_TAG_PREFIX.length)).data : packVersionOfTag(tag);
|
||||||
if (!version) continue;
|
if (!version) continue;
|
||||||
const pack = packRelease(release, version, tag, source);
|
const pack = packRelease(release, version, tag, source, mapNav ? mapNavReleaseFiles(version) : packFileNames(version));
|
||||||
if (pack) versions.pack.set(pack.version, pack);
|
if (pack) versions[channel].set(pack.version, pack);
|
||||||
else if (!incomplete.pack || comparePackVersions(version, incomplete.pack) > 0) incomplete.pack = version;
|
else {
|
||||||
|
const partial = incomplete[channel];
|
||||||
|
if (!partial || comparePackVersions(version, partial) > 0) incomplete[channel] = version;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,7 +273,7 @@ function launcherRelease(entry: Record<string, unknown>, version: string, source
|
|||||||
return {
|
return {
|
||||||
source,
|
source,
|
||||||
version,
|
version,
|
||||||
notes: body?.trim().slice(0, 1600) ?? '',
|
notes: body?.trim().slice(0, MAX_RELEASE_NOTES_CHARS) ?? '',
|
||||||
installer,
|
installer,
|
||||||
manifest,
|
manifest,
|
||||||
signature,
|
signature,
|
||||||
@@ -256,10 +281,12 @@ function launcherRelease(entry: Record<string, unknown>, version: string, source
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
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,
|
||||||
|
names: ReturnType<typeof packFileNames>,
|
||||||
|
): PackReleaseFiles | null {
|
||||||
if (!Array.isArray(release['assets'])) return null;
|
if (!Array.isArray(release['assets'])) return null;
|
||||||
const urls = assetUrls(release['assets'], tag, source);
|
const urls = assetUrls(release['assets'], tag, source);
|
||||||
const names = packFileNames(version);
|
|
||||||
const zipUrl = urls.get(names.zip);
|
const zipUrl = urls.get(names.zip);
|
||||||
const signatureUrl = urls.get(names.signature);
|
const signatureUrl = urls.get(names.signature);
|
||||||
const manifestUrl = urls.get(names.manifest);
|
const manifestUrl = urls.get(names.manifest);
|
||||||
|
|||||||
@@ -17,6 +17,12 @@ 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;
|
||||||
|
/** Modular ground AI daScript sources injected into `game.vromfs.bin` when active. */
|
||||||
|
readonly groundAiScripts: string;
|
||||||
|
/** Location of the baseline navigation maps, when included with the launcher. */
|
||||||
|
readonly bundledMapNavFolder: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resourcePaths(): ResourcePaths {
|
export function resourcePaths(): ResourcePaths {
|
||||||
@@ -32,6 +38,9 @@ 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'),
|
||||||
|
groundAiScripts: join(process.resourcesPath, 'game-ai', 'ground'),
|
||||||
|
bundledMapNavFolder: join(process.resourcesPath, 'map-nav', 'maps'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// 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 +49,9 @@ 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'),
|
||||||
|
groundAiScripts: join(repository, 'game-ai', 'ground'),
|
||||||
|
bundledMapNavFolder: join(repository, 'build', 'map-nav', 'maps'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { AppError } from '@shared/errors.ts';
|
||||||
|
import type { SaveCrewEdit, SaveCrewPreview, SaveCrewView } from '@shared/schemas/crew-saves.ts';
|
||||||
|
import { offlineClientCacheFolders, requireSaveCopy, runSaveTask, saveLocation, writeSave } from './manage-saves.ts';
|
||||||
|
import { captureSave, restoreDirectory, saveBackup } from './save-archive.ts';
|
||||||
|
|
||||||
|
export async function getSaveCrews(copyId: string, userId: string, country: string | undefined): Promise<SaveCrewView> {
|
||||||
|
const copy = await requireSaveCopy(copyId);
|
||||||
|
return await runSaveTask({ operation: 'readCrews', ...saveLocation(copy), userId, country }) as SaveCrewView;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function previewSaveCrew(copyId: string, userId: string, country: string, edit: SaveCrewEdit): Promise<SaveCrewPreview> {
|
||||||
|
const copy = await requireSaveCopy(copyId);
|
||||||
|
return await runSaveTask({ operation: 'previewCrew', ...saveLocation(copy), userId, country, edit }) as SaveCrewPreview;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function changeSaveCrew(copyId: string, userId: string, country: string, edit: SaveCrewEdit, token: string): Promise<SaveCrewView> {
|
||||||
|
return writeSave(async () => {
|
||||||
|
const copy = await requireSaveCopy(copyId);
|
||||||
|
const before = await captureSave(copy, userId);
|
||||||
|
const cacheFolders = edit.action === 'close' ? await offlineClientCacheFolders(userId) : [];
|
||||||
|
if (edit.action === 'close') await saveBackup(copy, userId, 'crew', before);
|
||||||
|
try {
|
||||||
|
return await runSaveTask({ operation: 'editCrew', ...saveLocation(copy), userId, country, edit, token, cacheFolders }) as SaveCrewView;
|
||||||
|
} catch (error) {
|
||||||
|
const refused = error instanceof AppError && ['save_not_found', 'save_crew_invalid', 'save_crew_slot_limit', 'save_crew_stale'].includes(error.code);
|
||||||
|
if (!refused) await restoreDirectory(copy, userId, before);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import { AppError } from '@shared/errors.ts';
|
|||||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||||
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, OnlineDataSource, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts';
|
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, OnlineDataSource, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts';
|
||||||
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
|
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
|
||||||
|
import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts';
|
||||||
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
|
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
|
||||||
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
|
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
|
||||||
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
|
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
|
||||||
@@ -14,6 +15,8 @@ import { localServerReady } from '../launch/local-server.ts';
|
|||||||
import { forwardProcessOutput } from '../launch/process-output.ts';
|
import { forwardProcessOutput } from '../launch/process-output.ts';
|
||||||
import { archivedBackup, backupList, captureSave, changeSaveFolder, readArchive, restoreDirectory, saveBackup, writeArchive, type SaveArchive } from './save-archive.ts';
|
import { archivedBackup, backupList, captureSave, changeSaveFolder, readArchive, restoreDirectory, saveBackup, writeArchive, type SaveArchive } from './save-archive.ts';
|
||||||
|
|
||||||
|
export { location as saveLocation, offlineClientCacheFolders, requireCopy as requireSaveCopy, run as runSaveTask, write as writeSave };
|
||||||
|
|
||||||
let writing = false;
|
let writing = false;
|
||||||
|
|
||||||
export function saveWriteInProgress(): boolean {
|
export function saveWriteInProgress(): boolean {
|
||||||
@@ -95,15 +98,27 @@ export async function setSaveCurrencies(copyId: string, userId: string, values:
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function pickSaveArchive(window: BrowserWindow | null): Promise<{ path: string | null }> {
|
export async function pickSaveArchive(window: BrowserWindow | null): Promise<{ path: string | null }> {
|
||||||
const options = { properties: ['openFile' as const], filters: [{ name: 'ZIP', extensions: ['zip'] }] };
|
const defaultPath = await resolveDialogDefaultPath('save-archive');
|
||||||
|
const options = {
|
||||||
|
properties: ['openFile' as const],
|
||||||
|
filters: [{ name: 'ZIP', extensions: ['zip'] }],
|
||||||
|
...(defaultPath ? { defaultPath } : {}),
|
||||||
|
};
|
||||||
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
|
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
|
||||||
return { path: result.canceled ? null : result.filePaths[0] ?? null };
|
const chosen = result.canceled ? null : (result.filePaths[0] ?? null);
|
||||||
|
if (chosen) await rememberDialogPath('save-archive', chosen);
|
||||||
|
return { path: chosen };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function exportSave(copyId: string, userId: string, window: BrowserWindow | null): Promise<{ path: string | null }> {
|
export async function exportSave(copyId: string, userId: string, window: BrowserWindow | null): Promise<{ path: string | null }> {
|
||||||
const copy = await requireCopy(copyId);
|
const copy = await requireCopy(copyId);
|
||||||
await getSaveDetails(copyId, userId);
|
await getSaveDetails(copyId, userId);
|
||||||
const options = { defaultPath: `WTOffline-save-${userId}.zip`, filters: [{ name: 'ZIP', extensions: ['zip'] }] };
|
const defaultDir = await resolveDialogDefaultPath('save-archive');
|
||||||
|
const fileName = `WTOffline-save-${userId}.zip`;
|
||||||
|
const options = {
|
||||||
|
defaultPath: defaultDir ? join(defaultDir, fileName) : fileName,
|
||||||
|
filters: [{ name: 'ZIP', extensions: ['zip'] }],
|
||||||
|
};
|
||||||
const result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options);
|
const result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options);
|
||||||
if (result.canceled || !result.filePath) return { path: null };
|
if (result.canceled || !result.filePath) return { path: null };
|
||||||
try {
|
try {
|
||||||
@@ -113,6 +128,7 @@ export async function exportSave(copyId: string, userId: string, window: Browser
|
|||||||
console.error('[saves] could not export the save:', error);
|
console.error('[saves] could not export the save:', error);
|
||||||
throw new AppError('save_operation_failed');
|
throw new AppError('save_operation_failed');
|
||||||
}
|
}
|
||||||
|
await rememberDialogPath('save-archive', result.filePath);
|
||||||
return { path: result.filePath };
|
return { path: result.filePath };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,8 +193,18 @@ export async function restoreSaveBackup(copyId: string, userId: string, name: st
|
|||||||
await getSaveDetails(copyId, userId);
|
await getSaveDetails(copyId, userId);
|
||||||
const archive = await archivedBackup(copy, userId, name);
|
const archive = await archivedBackup(copy, userId, name);
|
||||||
await validateProfile(archive, copy);
|
await validateProfile(archive, copy);
|
||||||
await saveBackup(copy, userId, 'restore');
|
const before = await captureSave(copy, userId);
|
||||||
|
const cacheFolders = name.split('.')[1] === 'crew' ? await offlineClientCacheFolders(userId) : undefined;
|
||||||
|
await saveBackup(copy, userId, 'restore', before);
|
||||||
await restoreDirectory(copy, userId, archive);
|
await restoreDirectory(copy, userId, archive);
|
||||||
|
if (cacheFolders) {
|
||||||
|
try {
|
||||||
|
await run({ operation: 'syncRestoredCrewPresets', ...location(copy), userId, cacheFolders });
|
||||||
|
} catch (error) {
|
||||||
|
await restoreDirectory(copy, userId, before);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
return getSaveDetails(copyId, userId);
|
return getSaveDetails(copyId, userId);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -275,9 +301,16 @@ export async function copyOnlineData(copyId: string, userId: string, accountId:
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function pickOfficialBackups(window: BrowserWindow | null): Promise<string[]> {
|
export async function pickOfficialBackups(window: BrowserWindow | null): Promise<string[]> {
|
||||||
const options = { properties: ['openFile' as const, 'multiSelections' as const], filters: [{ name: 'BLK', extensions: ['blk'] }] };
|
const defaultPath = await resolveDialogDefaultPath('official-backups');
|
||||||
|
const options = {
|
||||||
|
properties: ['openFile' as const, 'multiSelections' as const],
|
||||||
|
filters: [{ name: 'BLK', extensions: ['blk'] }],
|
||||||
|
...(defaultPath ? { defaultPath } : {}),
|
||||||
|
};
|
||||||
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
|
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
|
||||||
return result.canceled ? [] : result.filePaths;
|
if (result.canceled || result.filePaths.length === 0) return [];
|
||||||
|
if (result.filePaths[0]) await rememberDialogPath('official-backups', result.filePaths[0]);
|
||||||
|
return result.filePaths;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function previewSelectedBackups(
|
export async function previewSelectedBackups(
|
||||||
|
|||||||
@@ -178,11 +178,11 @@ export async function backupList(copy: InstallRecord, userId: string): Promise<S
|
|||||||
return backups;
|
return backups;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function saveBackup(copy: InstallRecord, userId: string, type: SaveBackup['type']): Promise<void> {
|
export async function saveBackup(copy: InstallRecord, userId: string, type: SaveBackup['type'], archive?: SaveArchive): Promise<void> {
|
||||||
const root = await backupFolder(copy, userId);
|
const root = await backupFolder(copy, userId);
|
||||||
await mkdir(root, { recursive: true });
|
await mkdir(root, { recursive: true });
|
||||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||||
await writeArchive(join(root, `${stamp}.${type}.${randomUUID()}.zip`), await captureSave(copy, userId));
|
await writeArchive(join(root, `${stamp}.${type}.${randomUUID()}.zip`), archive ?? await captureSave(copy, userId));
|
||||||
if (type === 'launch') {
|
if (type === 'launch') {
|
||||||
const older = (await backupList(copy, userId)).filter((backup) => backup.type === 'launch').slice(10);
|
const older = (await backupList(copy, userId)).filter((backup) => backup.type === 'launch').slice(10);
|
||||||
for (const backup of older) await rm(join(root, backup.name), { force: true });
|
for (const backup of older) await rm(join(root, backup.name), { force: true });
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
import { stat } from 'node:fs/promises';
|
||||||
|
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
||||||
|
import { readJsonOr, writeJsonAtomic } from './atomic-json.ts';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remembers the last directory chosen in native open/save dialogs, keyed by dialog category,
|
||||||
|
* persisted to `<userData>/dialog-paths.json`. Read/write errors are swallowed so dialog
|
||||||
|
* behavior is never disrupted.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type DialogPathCategory =
|
||||||
|
| 'folder'
|
||||||
|
| 'save-archive'
|
||||||
|
| 'official-backups'
|
||||||
|
| 'mods-folder'
|
||||||
|
| 'mod-preset';
|
||||||
|
|
||||||
|
export interface DialogPathStore {
|
||||||
|
resolveDialogDefaultPath(
|
||||||
|
category: DialogPathCategory,
|
||||||
|
explicitPath?: string | null,
|
||||||
|
): Promise<string | undefined>;
|
||||||
|
rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DIALOG_PATHS_FILENAME = 'dialog-paths.json';
|
||||||
|
const LAST_KEY = 'last';
|
||||||
|
const MAX_ANCESTOR_STEPS = 128;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve `candidate` to an existing directory:
|
||||||
|
* - If it is an existing directory, return its normalized path.
|
||||||
|
* - If it is an existing file or does not exist, walk up to the nearest existing ancestor directory.
|
||||||
|
* - Return `undefined` when no existing ancestor directory can be reached.
|
||||||
|
*/
|
||||||
|
export async function resolveExistingDirectory(candidate: string | null | undefined): Promise<string | undefined> {
|
||||||
|
if (!candidate) return undefined;
|
||||||
|
const trimmed = candidate.trim();
|
||||||
|
if (!trimmed || !isAbsolute(trimmed)) return undefined;
|
||||||
|
|
||||||
|
let current = resolve(trimmed);
|
||||||
|
for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) {
|
||||||
|
try {
|
||||||
|
const info = await stat(current);
|
||||||
|
if (info.isDirectory()) return current;
|
||||||
|
} catch {
|
||||||
|
// Missing or inaccessible path; continue walking toward the filesystem root.
|
||||||
|
}
|
||||||
|
const parent = dirname(current);
|
||||||
|
if (parent === current) return undefined;
|
||||||
|
current = parent;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Create a dialog-path store backed by the JSON file path returned by `resolveStorePath`. */
|
||||||
|
export function createDialogPathStore(
|
||||||
|
resolveStorePath: () => Promise<string | null> | string | null,
|
||||||
|
): DialogPathStore {
|
||||||
|
let cached: Map<string, string> | null = null;
|
||||||
|
let loading: Promise<Map<string, string>> | null = null;
|
||||||
|
let pending: Promise<void> = Promise.resolve();
|
||||||
|
|
||||||
|
async function loadMap(): Promise<Map<string, string>> {
|
||||||
|
if (cached) return cached;
|
||||||
|
if (loading) return loading;
|
||||||
|
|
||||||
|
loading = (async () => {
|
||||||
|
const map = new Map<string, string>();
|
||||||
|
const storePath = await resolveStorePath();
|
||||||
|
if (storePath) {
|
||||||
|
try {
|
||||||
|
const raw = await readJsonOr(storePath, null);
|
||||||
|
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
||||||
|
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
|
||||||
|
if (typeof value === 'string' && value.trim().length > 0) {
|
||||||
|
map.set(key, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[dialog-paths] failed to read dialog paths:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cached = map;
|
||||||
|
return map;
|
||||||
|
})().finally(() => {
|
||||||
|
loading = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
return loading;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
async resolveDialogDefaultPath(
|
||||||
|
category: DialogPathCategory,
|
||||||
|
explicitPath?: string | null,
|
||||||
|
): Promise<string | undefined> {
|
||||||
|
try {
|
||||||
|
const explicitDir = await resolveExistingDirectory(explicitPath);
|
||||||
|
if (explicitDir) return explicitDir;
|
||||||
|
|
||||||
|
const map = await loadMap();
|
||||||
|
const categoryPath = map.get(category);
|
||||||
|
if (categoryPath) {
|
||||||
|
const resolved = await resolveExistingDirectory(categoryPath);
|
||||||
|
if (resolved) return resolved;
|
||||||
|
}
|
||||||
|
|
||||||
|
const lastPath = map.get(LAST_KEY);
|
||||||
|
if (lastPath && lastPath !== categoryPath) {
|
||||||
|
const resolved = await resolveExistingDirectory(lastPath);
|
||||||
|
if (resolved) return resolved;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[dialog-paths] failed to resolve default dialog path:', error);
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
},
|
||||||
|
|
||||||
|
async rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void> {
|
||||||
|
const dir = await resolveExistingDirectory(selectedPath);
|
||||||
|
if (!dir) return;
|
||||||
|
|
||||||
|
const operation = pending.then(async () => {
|
||||||
|
const map = await loadMap();
|
||||||
|
if (map.get(category) === dir && map.get(LAST_KEY) === dir) return;
|
||||||
|
|
||||||
|
map.set(category, dir);
|
||||||
|
map.set(LAST_KEY, dir);
|
||||||
|
|
||||||
|
const storePath = await resolveStorePath();
|
||||||
|
if (!storePath) return;
|
||||||
|
try {
|
||||||
|
await writeJsonAtomic(storePath, Object.fromEntries(map));
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[dialog-paths] failed to save dialog paths:', error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
pending = operation.then(() => undefined, () => undefined);
|
||||||
|
await operation;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function defaultStorePath(): Promise<string | null> {
|
||||||
|
try {
|
||||||
|
const mod = await import('electron') as {
|
||||||
|
readonly app?: { getPath?: (name: 'userData') => string };
|
||||||
|
readonly default?: { app?: { getPath?: (name: 'userData') => string } };
|
||||||
|
};
|
||||||
|
const electronApp = mod.app ?? mod.default?.app;
|
||||||
|
if (typeof electronApp?.getPath !== 'function') return null;
|
||||||
|
return join(electronApp.getPath('userData'), DIALOG_PATHS_FILENAME);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultStore = createDialogPathStore(defaultStorePath);
|
||||||
|
|
||||||
|
export function resolveDialogDefaultPath(
|
||||||
|
category: DialogPathCategory,
|
||||||
|
explicitPath?: string | null,
|
||||||
|
): Promise<string | undefined> {
|
||||||
|
return defaultStore.resolveDialogDefaultPath(category, explicitPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void> {
|
||||||
|
return defaultStore.rememberDialogPath(category, selectedPath);
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import * as nodeFs from 'node:fs';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
|
||||||
|
let cached: typeof nodeFs | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return Node's unpatched fs module inside Electron.
|
||||||
|
*
|
||||||
|
* Electron patches `node:fs` to treat any `.asar` file anywhere on disk as a virtual archive
|
||||||
|
* directory, which breaks streaming reads, stats and recursive cleanup when copying or managing
|
||||||
|
* player folders that happen to contain an `.asar` file. Falls back to `node:fs` outside Electron.
|
||||||
|
*/
|
||||||
|
export function rawFs(): typeof nodeFs {
|
||||||
|
if (cached) return cached;
|
||||||
|
try {
|
||||||
|
cached = require('original-fs') as typeof nodeFs;
|
||||||
|
} catch {
|
||||||
|
cached = nodeFs;
|
||||||
|
}
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
@@ -9,9 +9,13 @@ export interface BuildRequest {
|
|||||||
readonly port: number;
|
readonly port: number;
|
||||||
readonly patches: string;
|
readonly patches: string;
|
||||||
readonly networkHookLibrary: string;
|
readonly networkHookLibrary: string;
|
||||||
|
readonly groundAiScripts: string;
|
||||||
|
readonly mapNavFolder?: string;
|
||||||
readonly decalCache?: string;
|
readonly decalCache?: string;
|
||||||
readonly hookLogging: boolean;
|
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,14 +1,34 @@
|
|||||||
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 { multiVehiclePackIds } from '@wto/server';
|
import {
|
||||||
|
assertWritableCopy,
|
||||||
|
buildGameCopy,
|
||||||
|
computeModsBuildFingerprint,
|
||||||
|
copyPlayerDecalCache,
|
||||||
|
CORE_BUILD_PACKS,
|
||||||
|
GAME_PACK_FILE,
|
||||||
|
isGroundAiActive,
|
||||||
|
playerDecalCacheProblem,
|
||||||
|
prepareOptionalStockPacks,
|
||||||
|
readPlayerDecalIndexFiles,
|
||||||
|
readStockGameFiles,
|
||||||
|
syncExternalModFiles,
|
||||||
|
writeGameCopy,
|
||||||
|
type GameCopyBuild,
|
||||||
|
type GameCopyFile,
|
||||||
|
} from '@wto/patcher';
|
||||||
|
import { loadGroundAiTuning, multiVehiclePackIds } from '@wto/server';
|
||||||
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
|
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
|
||||||
|
|
||||||
let prepared: {
|
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,17 +51,64 @@ 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 logModBuildSummary(result: GameCopyBuild): void {
|
||||||
|
if (result.gamePack) {
|
||||||
|
console.info(`[build] injected ${result.gamePack.modules.length} ground AI module(s) into ${result.gamePack.archiveFolder}`);
|
||||||
|
}
|
||||||
|
if (result.mods.enabledModIds.length === 0) return;
|
||||||
|
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}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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 groundAiConfig = loadGroundAiTuning(request.dataPath, console.info, enabledMods);
|
||||||
|
const groundAiActive = isGroundAiActive(groundAiConfig);
|
||||||
|
const touchedSet = new Set<ModdableClientPack>(
|
||||||
|
touchedClientPacks(enabledMods).filter((pack) => !CORE_BUILD_PACKS.has(pack)),
|
||||||
|
);
|
||||||
|
if (groundAiActive) touchedSet.add(GAME_PACK_FILE);
|
||||||
|
const optionalPacksInBuild = [...touchedSet];
|
||||||
|
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,
|
hookLogging: request.hookLogging,
|
||||||
|
...(request.mapNavFolder === undefined ? {} : { mapNavFolder: request.mapNavFolder }),
|
||||||
|
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
|
||||||
|
...(extraStockPacks ? { extraStockPacks } : {}),
|
||||||
|
groundAi: { scriptsFolder: request.groundAiScripts, config: groundAiConfig },
|
||||||
});
|
});
|
||||||
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);
|
||||||
@@ -50,7 +117,13 @@ 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 };
|
logModBuildSummary(result);
|
||||||
|
const fingerprint = computeModsBuildFingerprint(
|
||||||
|
enabledMods,
|
||||||
|
request.port,
|
||||||
|
`${request.patches}|groundAi=${JSON.stringify(groundAiConfig)}`,
|
||||||
|
);
|
||||||
|
prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint };
|
||||||
send({ kind: 'prepared', total: prepared.files.length });
|
send({ kind: 'prepared', total: prepared.files.length });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,15 +135,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,4 +1,5 @@
|
|||||||
import type { AppErrorCode } from '@shared/errors.ts';
|
import type { AppErrorCode } from '@shared/errors.ts';
|
||||||
|
import type { SaveCrewEdit, SaveCrewPreview, SaveCrewView } from '@shared/schemas/crew-saves.ts';
|
||||||
import type { AccountEdits, SaveAvatarChoices, CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts';
|
import type { AccountEdits, SaveAvatarChoices, CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts';
|
||||||
|
|
||||||
interface Location {
|
interface Location {
|
||||||
@@ -23,9 +24,13 @@ export type SaveTask = Location & (
|
|||||||
}
|
}
|
||||||
| { readonly operation: 'readResearch'; readonly userId: string; readonly branch?: ResearchBranch }
|
| { readonly operation: 'readResearch'; readonly userId: string; readonly branch?: ResearchBranch }
|
||||||
| { readonly operation: 'editResearch'; readonly userId: string; readonly branch: ResearchBranch; readonly action: ResearchOperation }
|
| { readonly operation: 'editResearch'; readonly userId: string; readonly branch: ResearchBranch; readonly action: ResearchOperation }
|
||||||
|
| { readonly operation: 'readCrews'; readonly userId: string; readonly country: string | undefined }
|
||||||
|
| { readonly operation: 'previewCrew'; readonly userId: string; readonly country: string; readonly edit: SaveCrewEdit }
|
||||||
|
| { readonly operation: 'editCrew'; readonly userId: string; readonly country: string; readonly edit: SaveCrewEdit; readonly token: string; readonly cacheFolders: readonly string[] }
|
||||||
|
| { readonly operation: 'syncRestoredCrewPresets'; readonly userId: string; readonly cacheFolders: readonly string[] }
|
||||||
| { readonly operation: 'remove'; readonly userId: string }
|
| { readonly operation: 'remove'; readonly userId: string }
|
||||||
| { readonly operation: 'filter'; readonly profile: Uint8Array; readonly filter: boolean }
|
| { readonly operation: 'filter'; readonly profile: Uint8Array; readonly filter: boolean }
|
||||||
| { readonly operation: 'create'; readonly login: string; readonly password: string; readonly nick: string }
|
| { readonly operation: 'create'; readonly login: string; readonly password: string; readonly nick: string }
|
||||||
);
|
);
|
||||||
export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | { userId: string } | Uint8Array | SaveAvatarChoices | string | null;
|
export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | SaveCrewView | SaveCrewPreview | { userId: string } | Uint8Array | SaveAvatarChoices | string | null;
|
||||||
export type SaveReply = { ok: true; result: SaveResult } | { ok: false; error: AppErrorCode };
|
export type SaveReply = { ok: true; result: SaveResult } | { ok: false; error: AppErrorCode };
|
||||||
@@ -1,7 +1,12 @@
|
|||||||
import type { MessageEvent } from 'electron';
|
import type { MessageEvent } from 'electron';
|
||||||
import { AccountStore, editSaveAccount, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveAvatars, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveAvatar, readSaveDetails, readSaveResearch } from '@wto/server';
|
import { AccountStore, editSaveAccount, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveAvatars, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveAvatar, readSaveDetails, readSaveResearch } from '@wto/server';
|
||||||
|
import { editSaveCrew, previewSaveCrewEdit, readSaveCrews, syncRestoredCrewPresets } from '@wto/server';
|
||||||
import type { SaveTask, SaveReply } from './save-protocol.ts';
|
import type { SaveTask, SaveReply } from './save-protocol.ts';
|
||||||
|
|
||||||
|
const CREW_ERRORS = {
|
||||||
|
'not-found': 'save_not_found', invalid: 'save_crew_invalid', 'slot-limit': 'save_crew_slot_limit', stale: 'save_crew_stale',
|
||||||
|
} as const;
|
||||||
|
|
||||||
function execute(task: SaveTask): SaveReply {
|
function execute(task: SaveTask): SaveReply {
|
||||||
switch (task.operation) {
|
switch (task.operation) {
|
||||||
case 'list':
|
case 'list':
|
||||||
@@ -37,6 +42,23 @@ function execute(task: SaveTask): SaveReply {
|
|||||||
const result = editSaveResearch(task, task.userId, task.branch, task.action);
|
const result = editSaveResearch(task, task.userId, task.branch, task.action);
|
||||||
return result ? { ok: true, result } : { ok: false, error: 'save_operation_failed' };
|
return result ? { ok: true, result } : { ok: false, error: 'save_operation_failed' };
|
||||||
}
|
}
|
||||||
|
case 'readCrews': {
|
||||||
|
const result = readSaveCrews(task, task.userId, task.country);
|
||||||
|
return result ? { ok: true, result } : { ok: false, error: 'save_not_found' };
|
||||||
|
}
|
||||||
|
case 'previewCrew': {
|
||||||
|
const result = previewSaveCrewEdit(task, task.userId, task.country, task.edit);
|
||||||
|
if ('preview' in result && result.preview) return { ok: true, result: result.preview };
|
||||||
|
return { ok: false, error: CREW_ERRORS[result.error ?? 'invalid'] };
|
||||||
|
}
|
||||||
|
case 'editCrew': {
|
||||||
|
const result = editSaveCrew(task, task.userId, task.country, task.edit, task.token, task.cacheFolders);
|
||||||
|
if ('view' in result && result.view) return { ok: true, result: result.view };
|
||||||
|
return { ok: false, error: CREW_ERRORS[result.error ?? 'invalid'] };
|
||||||
|
}
|
||||||
|
case 'syncRestoredCrewPresets':
|
||||||
|
syncRestoredCrewPresets(task.dataFolder, task.userId, task.cacheFolders);
|
||||||
|
return { ok: true, result: null };
|
||||||
case 'remove':
|
case 'remove':
|
||||||
return new AccountStore(task.dataFolder).remove(task.userId)
|
return new AccountStore(task.dataFolder).remove(task.userId)
|
||||||
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
|
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
|
||||||
|
|||||||
@@ -1,16 +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, loggingFlag] = 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 loggingEnabled = loggingFlag !== '0';
|
const loggingEnabled = loggingFlag !== '0';
|
||||||
const server = await startServer({ gameFolder, dataFolder, port, loggingEnabled, report: console.info });
|
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.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);
|
||||||
|
|||||||
@@ -22,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';
|
||||||
@@ -32,11 +33,12 @@ 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';
|
||||||
import { useAppUpdate } from './shell/useAppUpdate.ts';
|
import { useAppUpdate } from './shell/useAppUpdate.ts';
|
||||||
|
import { useMapNavPack } from './shell/useMapNavPack.ts';
|
||||||
import { usePatchPack } from './shell/usePatchPack.ts';
|
import { usePatchPack } from './shell/usePatchPack.ts';
|
||||||
import { useErrorMessage } from './useErrorMessage.ts';
|
import { useErrorMessage } from './useErrorMessage.ts';
|
||||||
|
|
||||||
@@ -68,6 +70,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
|||||||
const [route, setRoute] = useState<Route>(START_ROUTE);
|
const [route, setRoute] = useState<Route>(START_ROUTE);
|
||||||
// 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 mapNavPack = useMapNavPack(initialSettings.checkPatchPacksOnStart, report);
|
||||||
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
|
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
|
||||||
const maintenance = useCopyMaintenance(report);
|
const maintenance = useCopyMaintenance(report);
|
||||||
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
|
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
|
||||||
@@ -158,6 +161,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
|||||||
launcherVersion={info.version}
|
launcherVersion={info.version}
|
||||||
supportedVersions={supported}
|
supportedVersions={supported}
|
||||||
patchPack={patchPack}
|
patchPack={patchPack}
|
||||||
|
mapNavPack={mapNavPack}
|
||||||
appUpdate={appUpdate}
|
appUpdate={appUpdate}
|
||||||
loggingEnabled={settings.loggingEnabled}
|
loggingEnabled={settings.loggingEnabled}
|
||||||
onError={report}
|
onError={report}
|
||||||
@@ -195,6 +199,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') {
|
||||||
|
|||||||
@@ -5,16 +5,22 @@ interface FolderFieldProps {
|
|||||||
readonly path: string | null;
|
readonly path: string | null;
|
||||||
/** Title of the folder dialog. */
|
/** Title of the folder dialog. */
|
||||||
readonly dialogTitle: string;
|
readonly dialogTitle: string;
|
||||||
|
/** Optional starting directory when no path is chosen yet. */
|
||||||
|
readonly defaultPath?: string | null | undefined;
|
||||||
readonly disabled?: boolean;
|
readonly disabled?: boolean;
|
||||||
readonly onChosen: (path: string) => void;
|
readonly onChosen: (path: string) => void;
|
||||||
readonly onError: (error: unknown) => void;
|
readonly onError: (error: unknown) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A chosen folder and the button that opens the folder dialog. */
|
/** A chosen folder and the button that opens the folder dialog. */
|
||||||
export function FolderField({ path, dialogTitle, disabled = false, onChosen, onError }: FolderFieldProps) {
|
export function FolderField({ path, dialogTitle, defaultPath, disabled = false, onChosen, onError }: FolderFieldProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const choose = (): void => {
|
const choose = (): void => {
|
||||||
ipcInvoke('dialog:pickFolder', { title: dialogTitle })
|
const startPath = path ?? defaultPath;
|
||||||
|
ipcInvoke('dialog:pickFolder', {
|
||||||
|
title: dialogTitle,
|
||||||
|
...(startPath ? { defaultPath: startPath } : {}),
|
||||||
|
})
|
||||||
.then(({ path: chosen }) => {
|
.then(({ path: chosen }) => {
|
||||||
if (chosen) onChosen(chosen);
|
if (chosen) onChosen(chosen);
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import { createElement, Fragment, useMemo, type ReactNode } from 'react';
|
||||||
|
import { marked, type Token, type Tokens } from 'marked';
|
||||||
|
|
||||||
|
const SAFE_EXTERNAL_URL = /^https?:\/\//i;
|
||||||
|
const HTML_COMMENT = /^<!--[\s\S]*?-->$/;
|
||||||
|
|
||||||
|
function isSafeExternalUrl(href: string | undefined): href is string {
|
||||||
|
return typeof href === 'string' && SAFE_EXTERNAL_URL.test(href.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderInline(tokens: readonly Token[], keyPrefix: string): ReactNode {
|
||||||
|
return tokens.map((token, index) => renderInlineToken(token, `${keyPrefix}-${index}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderInlineToken(token: Token, key: string): ReactNode {
|
||||||
|
switch (token.type) {
|
||||||
|
case 'text': {
|
||||||
|
const textToken = token as Tokens.Text;
|
||||||
|
if (textToken.tokens?.length) return <Fragment key={key}>{renderInline(textToken.tokens, key)}</Fragment>;
|
||||||
|
return <Fragment key={key}>{textToken.text}</Fragment>;
|
||||||
|
}
|
||||||
|
case 'escape':
|
||||||
|
return <Fragment key={key}>{(token as Tokens.Escape).text}</Fragment>;
|
||||||
|
case 'strong':
|
||||||
|
return <strong key={key}>{renderInline((token as Tokens.Strong).tokens, key)}</strong>;
|
||||||
|
case 'em':
|
||||||
|
return <em key={key}>{renderInline((token as Tokens.Em).tokens, key)}</em>;
|
||||||
|
case 'del':
|
||||||
|
return <del key={key}>{renderInline((token as Tokens.Del).tokens, key)}</del>;
|
||||||
|
case 'codespan':
|
||||||
|
return <code key={key}>{(token as Tokens.Codespan).text}</code>;
|
||||||
|
case 'br':
|
||||||
|
return <br key={key} />;
|
||||||
|
case 'link': {
|
||||||
|
const link = token as Tokens.Link;
|
||||||
|
const content = link.tokens.length ? renderInline(link.tokens, key) : link.text;
|
||||||
|
if (!isSafeExternalUrl(link.href)) return <Fragment key={key}>{content}</Fragment>;
|
||||||
|
return (
|
||||||
|
<a key={key} href={link.href} title={link.title ?? undefined} target="_blank" rel="noreferrer">
|
||||||
|
{content}
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
case 'image':
|
||||||
|
return <Fragment key={key}>{(token as Tokens.Image).text}</Fragment>;
|
||||||
|
case 'html': {
|
||||||
|
const raw = (token as Tokens.HTML).text.trim();
|
||||||
|
if (!raw || HTML_COMMENT.test(raw)) return null;
|
||||||
|
return <Fragment key={key}>{raw}</Fragment>;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return 'raw' in token && typeof token.raw === 'string' ? <Fragment key={key}>{token.raw}</Fragment> : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTable(table: Tokens.Table, key: string): ReactNode {
|
||||||
|
return (
|
||||||
|
<div key={key} className="markdown-table-wrap">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
{table.header.map((cell, column) => (
|
||||||
|
<th key={`${key}-h-${column}`} style={cell.align ? { textAlign: cell.align } : undefined}>
|
||||||
|
{renderInline(cell.tokens, `${key}-h-${column}`)}
|
||||||
|
</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{table.rows.map((row, rowIndex) => (
|
||||||
|
<tr key={`${key}-r-${rowIndex}`}>
|
||||||
|
{row.map((cell, column) => (
|
||||||
|
<td key={`${key}-r-${rowIndex}-${column}`} style={cell.align ? { textAlign: cell.align } : undefined}>
|
||||||
|
{renderInline(cell.tokens, `${key}-r-${rowIndex}-${column}`)}
|
||||||
|
</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderListItem(item: Tokens.ListItem, key: string): ReactNode {
|
||||||
|
return (
|
||||||
|
<li key={key}>
|
||||||
|
{item.task && <input type="checkbox" checked={Boolean(item.checked)} disabled readOnly className="markdown-task" />}
|
||||||
|
{renderBlocks(item.tokens, key)}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderBlock(token: Token, key: string): ReactNode {
|
||||||
|
switch (token.type) {
|
||||||
|
case 'space':
|
||||||
|
case 'def':
|
||||||
|
case 'checkbox':
|
||||||
|
return null;
|
||||||
|
case 'heading': {
|
||||||
|
const heading = token as Tokens.Heading;
|
||||||
|
const level = Math.min(6, Math.max(1, heading.depth));
|
||||||
|
return createElement(`h${level}`, { key }, renderInline(heading.tokens, key));
|
||||||
|
}
|
||||||
|
case 'paragraph':
|
||||||
|
return <p key={key}>{renderInline((token as Tokens.Paragraph).tokens, key)}</p>;
|
||||||
|
case 'text': {
|
||||||
|
const textToken = token as Tokens.Text;
|
||||||
|
if (textToken.tokens?.length) return <Fragment key={key}>{renderInline(textToken.tokens, key)}</Fragment>;
|
||||||
|
return <Fragment key={key}>{textToken.text}</Fragment>;
|
||||||
|
}
|
||||||
|
case 'blockquote':
|
||||||
|
return <blockquote key={key}>{renderBlocks((token as Tokens.Blockquote).tokens, key)}</blockquote>;
|
||||||
|
case 'list': {
|
||||||
|
const list = token as Tokens.List;
|
||||||
|
const items = list.items.map((item, index) => renderListItem(item, `${key}-i-${index}`));
|
||||||
|
if (list.ordered) {
|
||||||
|
return <ol key={key} start={typeof list.start === 'number' && list.start !== 1 ? list.start : undefined}>{items}</ol>;
|
||||||
|
}
|
||||||
|
return <ul key={key}>{items}</ul>;
|
||||||
|
}
|
||||||
|
case 'code':
|
||||||
|
return (
|
||||||
|
<pre key={key}>
|
||||||
|
<code>{(token as Tokens.Code).text}</code>
|
||||||
|
</pre>
|
||||||
|
);
|
||||||
|
case 'hr':
|
||||||
|
return <hr key={key} />;
|
||||||
|
case 'table':
|
||||||
|
return renderTable(token as Tokens.Table, key);
|
||||||
|
case 'html': {
|
||||||
|
const raw = (token as Tokens.HTML).text.trim();
|
||||||
|
if (!raw || HTML_COMMENT.test(raw)) return null;
|
||||||
|
return <p key={key}>{raw}</p>;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return 'raw' in token && typeof token.raw === 'string' && token.raw.trim()
|
||||||
|
? <p key={key}>{token.raw}</p>
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderBlocks(tokens: readonly Token[], keyPrefix: string): ReactNode {
|
||||||
|
return tokens.map((token, index) => renderBlock(token, `${keyPrefix}-${index}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Safe React renderer for GFM Markdown without injecting raw HTML. */
|
||||||
|
export function MarkdownContent({ markdown }: { readonly markdown: string }) {
|
||||||
|
const tokens = useMemo(() => marked.lexer(markdown, { gfm: true, breaks: false }), [markdown]);
|
||||||
|
return <div className="markdown-body">{renderBlocks(tokens, 'md')}</div>;
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -6,20 +6,24 @@ 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';
|
||||||
|
import type { MapNavPackState } from '../../shell/useMapNavPack.ts';
|
||||||
|
import { MapNavPackSection } from './MapNavPackSection.tsx';
|
||||||
|
|
||||||
|
const HOMEPAGE_URL = 'https://wto-project.net';
|
||||||
const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
|
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 mapNavPack: MapNavPackState;
|
||||||
readonly appUpdate: AppUpdateState;
|
readonly appUpdate: AppUpdateState;
|
||||||
readonly loggingEnabled: boolean;
|
readonly loggingEnabled: boolean;
|
||||||
readonly onError: (error: unknown) => void;
|
readonly onError: (error: unknown) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The launcher's version, the game versions it supports, updates, community links, log export, 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, loggingEnabled, onError }: AboutPageProps) {
|
export function AboutPage({ launcherVersion, supportedVersions, patchPack, mapNavPack, appUpdate, loggingEnabled, onError }: AboutPageProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<Sheet title={t('nav.about')}>
|
<Sheet title={t('nav.about')}>
|
||||||
@@ -35,8 +39,10 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
|
|||||||
<div className="about-column">
|
<div className="about-column">
|
||||||
<AppUpdateSection state={appUpdate} />
|
<AppUpdateSection state={appUpdate} />
|
||||||
<PatchPackSection state={patchPack} />
|
<PatchPackSection state={patchPack} />
|
||||||
|
<MapNavPackSection state={mapNavPack} />
|
||||||
</div>
|
</div>
|
||||||
<div className="about-column">
|
<div className="about-column">
|
||||||
|
<HomepageSection />
|
||||||
<CommunitySection />
|
<CommunitySection />
|
||||||
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
|
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
|
||||||
<section className="about-card">
|
<section className="about-card">
|
||||||
@@ -49,6 +55,23 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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() {
|
function CommunitySection() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,13 +1,19 @@
|
|||||||
|
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 { ProgressBar } from '../../components/ProgressBar.tsx';
|
import { ProgressBar } from '../../components/ProgressBar.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';
|
||||||
|
import { ReleaseNotesModal } from './ReleaseNotesModal.tsx';
|
||||||
|
|
||||||
export function AppUpdateSection({ state }: { readonly state: AppUpdateState }) {
|
export function AppUpdateSection({ state }: { readonly state: AppUpdateState }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const [notesOpen, setNotesOpen] = useState(false);
|
||||||
if (!state.supported) return null;
|
if (!state.supported) return null;
|
||||||
const { check, busy, progress } = state;
|
const { check, busy, progress } = state;
|
||||||
|
const available = check?.status === 'available' && busy !== 'checking' ? check : null;
|
||||||
|
const notes = available?.release.notes.trim() ?? '';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="about-card">
|
<section className="about-card">
|
||||||
<div className="about-card-head">
|
<div className="about-card-head">
|
||||||
@@ -21,30 +27,46 @@ export function AppUpdateSection({ state }: { readonly state: AppUpdateState })
|
|||||||
<p className="about-card-meta">{t('about.update.check')}</p>
|
<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' && (
|
{available && (
|
||||||
<Notice tone="info">
|
<Notice tone="info">
|
||||||
<p>{t('about.update.available', { version: check.release.version, size: formatBytes(check.release.size) })}</p>
|
<p>{t('about.update.available', { version: available.release.version, size: formatBytes(available.release.size) })}</p>
|
||||||
{check.release.notes && <p className="small update-notes">{check.release.notes}</p>}
|
{busy === 'downloading' && (
|
||||||
{busy === 'downloading' ? (
|
|
||||||
<>
|
<>
|
||||||
<p>{t('about.update.downloading')}</p>
|
<p>{t('about.update.downloading')}</p>
|
||||||
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
|
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
|
||||||
</>
|
</>
|
||||||
) : (
|
)}
|
||||||
<button
|
{(busy !== 'downloading' || notes) && (
|
||||||
type="button"
|
<div className="update-actions">
|
||||||
className="button button-primary"
|
{busy !== 'downloading' && (
|
||||||
disabled={busy !== null}
|
<button
|
||||||
onClick={() => {
|
type="button"
|
||||||
if (check.ready) state.install(check.release.version);
|
className="button button-primary"
|
||||||
else state.download(check.release.version);
|
disabled={busy !== null}
|
||||||
}}
|
onClick={() => {
|
||||||
>
|
if (available.ready) state.install(available.release.version);
|
||||||
{t(busy === 'installing' ? 'about.update.installing' : check.ready ? 'about.update.install' : 'about.update.download')}
|
else state.download(available.release.version);
|
||||||
</button>
|
}}
|
||||||
|
>
|
||||||
|
{t(busy === 'installing' ? 'about.update.installing' : available.ready ? 'about.update.install' : 'about.update.download')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{notes && (
|
||||||
|
<button type="button" className="button button-compact" onClick={() => setNotesOpen(true)}>
|
||||||
|
{t('about.update.viewNotes')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</Notice>
|
</Notice>
|
||||||
)}
|
)}
|
||||||
|
{notesOpen && available && notes && (
|
||||||
|
<ReleaseNotesModal
|
||||||
|
version={available.release.version}
|
||||||
|
notes={notes}
|
||||||
|
onClose={() => setNotesOpen(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Notice } from '../../components/Notice.tsx';
|
||||||
|
import { ProgressBar } from '../../components/ProgressBar.tsx';
|
||||||
|
import { formatBytes } from '../../format.ts';
|
||||||
|
import type { MapNavPackState } from '../../shell/useMapNavPack.ts';
|
||||||
|
|
||||||
|
export function MapNavPackSection({ state }: { readonly state: MapNavPackState }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { active, busy, check, progress } = state;
|
||||||
|
const latest = check?.latest;
|
||||||
|
return (
|
||||||
|
<section className="about-card">
|
||||||
|
<div className="about-card-head">
|
||||||
|
<h3 className="about-card-title">{t('about.mapNav.title')}</h3>
|
||||||
|
<div className="about-card-actions">
|
||||||
|
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
||||||
|
{t(busy === 'checking' ? 'about.pack.checking' : 'about.pack.checkButton')}
|
||||||
|
</button>
|
||||||
|
{active?.source === 'downloaded' && (
|
||||||
|
<button type="button" className="button" disabled={busy !== null} onClick={state.deactivate}>
|
||||||
|
{t('about.mapNav.deactivate')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="about-card-meta">
|
||||||
|
<span className="about-card-label">{t('about.pack.current')}</span>
|
||||||
|
{' · '}
|
||||||
|
{active === undefined ? '…' : active === null ? t('about.mapNav.missing') : [
|
||||||
|
t('about.mapNav.source.' + active.source), active.version,
|
||||||
|
t('about.mapNav.mapCount', { count: active.mapCount }),
|
||||||
|
].filter(Boolean).join(' · ')}
|
||||||
|
</p>
|
||||||
|
<p className="small">{t('about.mapNav.hint')}</p>
|
||||||
|
{busy === 'applying' && (
|
||||||
|
<div role="status">
|
||||||
|
<p className="small">
|
||||||
|
{t(progress?.total && progress.received >= progress.total ? 'about.mapNav.installing' : 'about.mapNav.downloading')}
|
||||||
|
</p>
|
||||||
|
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{state.failure && <Notice tone="error"><p>{t('about.pack.applyFailed.' + state.failure)}</p></Notice>}
|
||||||
|
{busy !== 'checking' && check?.status === 'failed' && (
|
||||||
|
<Notice tone="error"><p>{t('about.pack.checkFailed.' + (check.problem ?? 'contents'))}</p></Notice>
|
||||||
|
)}
|
||||||
|
{busy !== 'checking' && check?.status === 'up_to_date' && (
|
||||||
|
<Notice tone="info"><p>{latest ? t('about.mapNav.upToDate', { version: latest.version }) : t('about.mapNav.noneReleased')}</p></Notice>
|
||||||
|
)}
|
||||||
|
{busy !== 'checking' && check?.status === 'needs_app_update' && latest && (
|
||||||
|
<Notice tone="warning"><p>{t('about.pack.needsAppUpdate', { version: latest.version, app: latest.minAppVersion })}</p></Notice>
|
||||||
|
)}
|
||||||
|
{busy !== 'checking' && check?.status === 'available' && latest && (
|
||||||
|
<Notice tone="info">
|
||||||
|
<p>{t('about.mapNav.available', { version: latest.version, count: latest.mapCount, size: formatBytes(latest.size) })}</p>
|
||||||
|
<p className="small">{t('about.mapNav.compatible', { versions: latest.gameVersions.join(', ') })}</p>
|
||||||
|
{busy !== 'applying' && (
|
||||||
|
<button type="button" className="button button-primary" disabled={busy !== null} onClick={() => state.apply(latest.version)}>
|
||||||
|
{t('about.pack.apply', { version: latest.version })}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</Notice>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { useEffect, useId } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { MarkdownContent } from '../../components/MarkdownContent.tsx';
|
||||||
|
|
||||||
|
interface ReleaseNotesModalProps {
|
||||||
|
readonly version: string;
|
||||||
|
readonly notes: string;
|
||||||
|
readonly onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Standalone dialog displaying rendered Markdown release notes for an available launcher update. */
|
||||||
|
export function ReleaseNotesModal({ version, notes, onClose }: ReleaseNotesModalProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const titleId = useId();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onKeyDown = (event: KeyboardEvent): void => {
|
||||||
|
if (event.key === 'Escape') onClose();
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKeyDown);
|
||||||
|
return () => window.removeEventListener('keydown', onKeyDown);
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div
|
||||||
|
className="modal-backdrop"
|
||||||
|
role="presentation"
|
||||||
|
onClick={(event) => {
|
||||||
|
if (event.target === event.currentTarget) onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="modal-dialog" role="dialog" aria-modal="true" aria-labelledby={titleId}>
|
||||||
|
<header className="modal-head">
|
||||||
|
<h3 id={titleId} className="modal-title">{t('about.update.notesTitle', { version })}</h3>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="modal-close"
|
||||||
|
aria-label={t('about.update.closeNotes')}
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
<div className="modal-body">
|
||||||
|
<MarkdownContent markdown={notes} />
|
||||||
|
</div>
|
||||||
|
<footer className="modal-foot">
|
||||||
|
<button type="button" className="button" onClick={onClose}>
|
||||||
|
{t('about.update.closeNotes')}
|
||||||
|
</button>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -20,19 +20,30 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
|
|||||||
const [info, setInfo] = useState<MaintenanceInfo | null>(null);
|
const [info, setInfo] = useState<MaintenanceInfo | null>(null);
|
||||||
const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null);
|
const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setRemoval(null);
|
||||||
|
}, [record.id]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
let mounted = true;
|
||||||
|
setInfo(null);
|
||||||
ipcInvoke('copies:maintenanceInfo', { id: record.id }).then((value) => {
|
ipcInvoke('copies:maintenanceInfo', { id: record.id }).then((value) => {
|
||||||
if (mounted) setInfo(value);
|
if (mounted) setInfo(value);
|
||||||
}).catch(onError);
|
}).catch(onError);
|
||||||
return () => { mounted = false; };
|
return () => { mounted = false; };
|
||||||
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, maintenance.revision, onError]);
|
}, [record.id, record.gameVersion, record.sourcePath, record.steamLibraryConfirmation, maintenance.revision, onError]);
|
||||||
|
|
||||||
const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
|
const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
|
||||||
if (operation === 'delete') setRemoval(null);
|
if (operation === 'delete') setRemoval(null);
|
||||||
maintenance.run(record.id, operation, options);
|
maintenance.run(record.id, operation, options);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const chooseUpdateSource = (): void => {
|
||||||
|
ipcInvoke('dialog:pickFolder', { title: t('copies.maintenance.chooseSource') }).then(({ path }) => {
|
||||||
|
if (path) run('set-source', { sourcePath: path });
|
||||||
|
}).catch(onError);
|
||||||
|
};
|
||||||
|
|
||||||
const active = maintenance.active;
|
const active = maintenance.active;
|
||||||
const busy = active !== null;
|
const busy = active !== null;
|
||||||
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
|
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
|
||||||
@@ -44,6 +55,7 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
|
|||||||
info={info}
|
info={info}
|
||||||
busy={busy}
|
busy={busy}
|
||||||
onRun={run}
|
onRun={run}
|
||||||
|
onChooseSource={chooseUpdateSource}
|
||||||
onConfirmSteam={(steamLocations) => run('confirm-steam', { steamLocations })}
|
onConfirmSteam={(steamLocations) => run('confirm-steam', { steamLocations })}
|
||||||
/>
|
/>
|
||||||
<CopyRemoval
|
<CopyRemoval
|
||||||
@@ -52,7 +64,8 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
|
|||||||
busy={busy}
|
busy={busy}
|
||||||
options={removal}
|
options={removal}
|
||||||
onOptionsChange={setRemoval}
|
onOptionsChange={setRemoval}
|
||||||
onRemove={(deleteData) => run('delete', { deleteData })}
|
onRemove={(options) => run('delete', options)}
|
||||||
|
onOpenFolder={() => { ipcInvoke('app:openFolder', { path: record.copyPath }).catch(onError); }}
|
||||||
/>
|
/>
|
||||||
{active && <MaintenanceStatus progress={active} onCancel={maintenance.cancel} />}
|
{active && <MaintenanceStatus progress={active} onCancel={maintenance.cancel} />}
|
||||||
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
|
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
|
||||||
|
|||||||
@@ -12,12 +12,20 @@ interface CopyMaintenanceControlsProps {
|
|||||||
|
|
||||||
interface CopyMaintenanceActionsProps extends CopyMaintenanceControlsProps {
|
interface CopyMaintenanceActionsProps extends CopyMaintenanceControlsProps {
|
||||||
readonly onRun: (operation: 'update' | 'compact' | 'check' | 'repair') => void;
|
readonly onRun: (operation: 'update' | 'compact' | 'check' | 'repair') => void;
|
||||||
|
readonly onChooseSource: () => void;
|
||||||
readonly onConfirmSteam: (locations: NonNullable<MaintenanceRequest['steamLocations']>) => void;
|
readonly onConfirmSteam: (locations: NonNullable<MaintenanceRequest['steamLocations']>) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSteam }: CopyMaintenanceActionsProps) {
|
export function CopyMaintenanceActions({ record, info, busy, onRun, onChooseSource, onConfirmSteam }: CopyMaintenanceActionsProps) {
|
||||||
const { t, i18n } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
const steam = info?.steamLocations;
|
const steam = info?.steamLocations;
|
||||||
|
const updateHint = info?.sourceVersion
|
||||||
|
? t(info.updateAvailable
|
||||||
|
? (record.hardlinkedFiles?.length
|
||||||
|
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
|
||||||
|
: 'copies.maintenance.newVersion')
|
||||||
|
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
|
||||||
|
: t(record.sourcePath ? (info ? 'copies.maintenance.noSource' : 'copies.maintenance.phase.checking') : 'copies.maintenance.sourceNotSet');
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{info?.steamConfirmationRequired && steam && (
|
{info?.steamConfirmationRequired && steam && (
|
||||||
@@ -30,13 +38,10 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSte
|
|||||||
</button>
|
</button>
|
||||||
</Notice>
|
</Notice>
|
||||||
)}
|
)}
|
||||||
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion
|
<Row label={t('copies.maintenance.update')} hint={record.sourcePath ? <>{record.sourcePath}<br />{updateHint}</> : updateHint}>
|
||||||
? t(info.updateAvailable
|
<button type="button" className="button" disabled={busy} onClick={onChooseSource}>
|
||||||
? (record.hardlinkedFiles?.length
|
{t(record.sourcePath ? 'copies.maintenance.changeSource' : 'copies.maintenance.setSource')}
|
||||||
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
|
</button>
|
||||||
: 'copies.maintenance.newVersion')
|
|
||||||
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
|
|
||||||
: t('copies.maintenance.noSource')}>
|
|
||||||
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
|
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
|
||||||
disabled={busy || !info?.updateAvailable} onClick={() => onRun('update')}>
|
disabled={busy || !info?.updateAvailable} onClick={() => onRun('update')}>
|
||||||
{t('copies.maintenance.updateAction')}
|
{t('copies.maintenance.updateAction')}
|
||||||
@@ -64,44 +69,112 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSte
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface CopyRemovalOptions {
|
export interface CopyRemovalOptions {
|
||||||
|
readonly deleteFiles: boolean;
|
||||||
|
readonly restoreStock: boolean;
|
||||||
readonly deleteData: boolean;
|
readonly deleteData: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CopyRemovalProps extends CopyMaintenanceControlsProps {
|
interface CopyRemovalProps extends CopyMaintenanceControlsProps {
|
||||||
readonly options: CopyRemovalOptions | null;
|
readonly options: CopyRemovalOptions | null;
|
||||||
readonly onOptionsChange: (options: CopyRemovalOptions | null) => void;
|
readonly onOptionsChange: (options: CopyRemovalOptions | null) => void;
|
||||||
readonly onRemove: (deleteData: boolean) => void;
|
readonly onRemove: (options: CopyRemovalOptions) => void;
|
||||||
|
readonly onOpenFolder: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove }: CopyRemovalProps) {
|
function clientOriginNoteKey(info: MaintenanceInfo): string {
|
||||||
|
if (info.clientOrigin === 'copy') return 'copies.maintenance.originCopy';
|
||||||
|
if (info.clientOrigin === 'hardlink') return 'copies.maintenance.originHardlink';
|
||||||
|
if (info.clientOrigin === 'in-place') return 'copies.maintenance.originInPlace';
|
||||||
|
return info.hasHardlinkedResources
|
||||||
|
? 'copies.maintenance.originUnknownHardlinked'
|
||||||
|
: 'copies.maintenance.originUnknown';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove, onOpenFolder }: CopyRemovalProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const steam = info?.steamLocations;
|
const steam = info?.steamLocations;
|
||||||
const unlinkOnly = steam?.copyInSteam === true;
|
const copyInSteam = steam?.copyInSteam === true;
|
||||||
const canDeleteData = !unlinkOnly && !steam?.dataInSteam;
|
const dataInSteam = steam?.dataInSteam === true;
|
||||||
const action = t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.confirm');
|
const canDeleteFiles = info?.canDeleteFiles === true;
|
||||||
|
const isHardlinkCopy = info?.clientOrigin === 'hardlink';
|
||||||
|
const canRestoreAndRemove = info !== null && !canDeleteFiles && info.canRestoreAndRemove;
|
||||||
|
const canDeleteData = info !== null && !copyInSteam && !dataInSteam;
|
||||||
|
const willDeleteFiles = canDeleteFiles && options?.deleteFiles === true;
|
||||||
|
const willRestoreStock = canRestoreAndRemove && options?.restoreStock === true;
|
||||||
|
const willDeleteData = canDeleteData && options?.deleteData === true;
|
||||||
|
const action = t(
|
||||||
|
willDeleteFiles || willDeleteData
|
||||||
|
? 'copies.maintenance.confirmDelete'
|
||||||
|
: willRestoreStock
|
||||||
|
? 'copies.maintenance.confirmRestore'
|
||||||
|
: 'copies.maintenance.confirmRemove',
|
||||||
|
);
|
||||||
|
const rowHint = copyInSteam
|
||||||
|
? t('copies.maintenance.removeSteamHint')
|
||||||
|
: canDeleteFiles
|
||||||
|
? t('copies.maintenance.removeCopyHint')
|
||||||
|
: canRestoreAndRemove
|
||||||
|
? t('copies.maintenance.removeRestoreHint')
|
||||||
|
: t('copies.maintenance.removeUnlinkHint');
|
||||||
|
const confirmNotice = copyInSteam
|
||||||
|
? t('copies.maintenance.removeSteamNotice', { path: steam?.copyPath ?? record.copyPath })
|
||||||
|
: canDeleteFiles
|
||||||
|
? t('copies.maintenance.removeCopyNotice', { path: record.copyPath })
|
||||||
|
: t('copies.maintenance.removeListOnlyNotice', { path: record.copyPath });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Row label={t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.delete')}
|
<Row label={t('copies.maintenance.remove')} hint={rowHint}>
|
||||||
hint={t(unlinkOnly ? 'copies.maintenance.unlinkHint' : 'copies.maintenance.deleteHint')}>
|
<button type="button" className="button" disabled={busy}
|
||||||
<button type="button" className="button" disabled={busy || !info}
|
onClick={() => onOptionsChange({ deleteFiles: false, restoreStock: false, deleteData: false })}>
|
||||||
onClick={() => onOptionsChange({ deleteData: false })}>
|
{t('copies.maintenance.removeAction')}
|
||||||
{t(unlinkOnly ? 'copies.maintenance.unlinkAction' : 'copies.maintenance.deleteAction')}
|
|
||||||
</button>
|
</button>
|
||||||
</Row>
|
</Row>
|
||||||
{options && (
|
{options && (
|
||||||
<section className="maintenance-confirm" role="group" aria-label={action}>
|
<section className="maintenance-confirm" role="group" aria-label={action}>
|
||||||
<p>{t(unlinkOnly ? 'copies.maintenance.unlinkLocation' : 'copies.maintenance.deleteLocation', { path: steam?.copyPath ?? record.copyPath })}</p>
|
<p>{confirmNotice}</p>
|
||||||
|
{info && <p className="small">{t(clientOriginNoteKey(info))}</p>}
|
||||||
|
{canDeleteFiles && (
|
||||||
|
<>
|
||||||
|
<label className="check">
|
||||||
|
<input type="checkbox" checked={options.deleteFiles} disabled={busy}
|
||||||
|
onChange={(event) => onOptionsChange({ ...options, deleteFiles: event.target.checked, restoreStock: false })} />
|
||||||
|
{t('copies.maintenance.deleteFiles', { path: record.copyPath })}
|
||||||
|
</label>
|
||||||
|
{isHardlinkCopy && <p className="small">{t('copies.maintenance.deleteHardlinkHint')}</p>}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{willDeleteFiles && (
|
||||||
|
<Notice tone="warning">
|
||||||
|
<p>{t(isHardlinkCopy ? 'copies.maintenance.deleteHardlinkWarning' : 'copies.maintenance.deleteFilesWarning', { path: record.copyPath })}</p>
|
||||||
|
</Notice>
|
||||||
|
)}
|
||||||
|
{canRestoreAndRemove && (
|
||||||
|
<>
|
||||||
|
<label className="check">
|
||||||
|
<input type="checkbox" checked={options.restoreStock} disabled={busy}
|
||||||
|
onChange={(event) => onOptionsChange({ ...options, restoreStock: event.target.checked, deleteFiles: false })} />
|
||||||
|
{t('copies.maintenance.restoreStock')}
|
||||||
|
</label>
|
||||||
|
<p className="small">{t('copies.maintenance.restoreStockHint')}</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
{canDeleteData && (
|
{canDeleteData && (
|
||||||
<label className="check">
|
<label className="check">
|
||||||
<input type="checkbox" checked={options.deleteData} disabled={busy}
|
<input type="checkbox" checked={options.deleteData} disabled={busy}
|
||||||
onChange={(event) => onOptionsChange({ deleteData: event.target.checked })} />
|
onChange={(event) => onOptionsChange({ ...options, deleteData: event.target.checked })} />
|
||||||
{t('copies.maintenance.deleteData', { path: record.dataPath })}
|
{t('copies.maintenance.deleteData', { path: record.dataPath })}
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
<div className="copy-list-actions">
|
<div className="copy-list-actions">
|
||||||
|
{!canDeleteFiles && (
|
||||||
|
<button type="button" className="button" disabled={busy || record.folderMissing === true} onClick={onOpenFolder}>
|
||||||
|
{t('copies.maintenance.openFolder')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button type="button" className="button" disabled={busy} onClick={() => onOptionsChange(null)}>{t('wizard.cancel')}</button>
|
<button type="button" className="button" disabled={busy} onClick={() => onOptionsChange(null)}>{t('wizard.cancel')}</button>
|
||||||
<button type="button" className="button button-primary" disabled={busy} onClick={() => onRemove(canDeleteData && options.deleteData)}>
|
<button type="button" className="button button-primary" disabled={busy}
|
||||||
|
onClick={() => onRemove({ deleteFiles: willDeleteFiles, restoreStock: willRestoreStock, deleteData: willDeleteData })}>
|
||||||
{action}
|
{action}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -20,13 +20,46 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc
|
|||||||
const { t, i18n } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
const [name, setName] = useState(record.name);
|
const [name, setName] = useState(record.name);
|
||||||
const [importing, setImporting] = useState(false);
|
const [importing, setImporting] = useState(false);
|
||||||
|
const [detectedSourceDecals, setDetectedSourceDecals] = useState<string | null>(null);
|
||||||
useEffect(() => setName(record.name), [record.id, record.name]);
|
useEffect(() => setName(record.name), [record.id, record.name]);
|
||||||
|
// Read-only probe of the copy's registered online source for a usable decal cache.
|
||||||
|
useEffect(() => {
|
||||||
|
setDetectedSourceDecals(null);
|
||||||
|
if (!record.sourcePath) return;
|
||||||
|
let current = true;
|
||||||
|
ipcInvoke('decals:detectSource', { path: record.sourcePath })
|
||||||
|
.then(({ path }) => {
|
||||||
|
if (current) setDetectedSourceDecals(path);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (current) setDetectedSourceDecals(null);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
current = false;
|
||||||
|
};
|
||||||
|
}, [record.id, record.sourcePath]);
|
||||||
const missing = missingFeatures(record).length;
|
const missing = missingFeatures(record).length;
|
||||||
const verified = isVerified(record.gameVersion, supportedVersions);
|
const verified = isVerified(record.gameVersion, supportedVersions);
|
||||||
|
const importFromSource = async (): Promise<void> => {
|
||||||
|
if (!detectedSourceDecals) return;
|
||||||
|
setImporting(true);
|
||||||
|
try {
|
||||||
|
await ipcInvoke('copies:setDecalSource', { id: record.id, path: detectedSourceDecals });
|
||||||
|
} catch (error) {
|
||||||
|
onError(error);
|
||||||
|
} finally {
|
||||||
|
setImporting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
const applyDecals = async (chooseFolder: boolean): Promise<void> => {
|
const applyDecals = async (chooseFolder: boolean): Promise<void> => {
|
||||||
setImporting(true);
|
setImporting(true);
|
||||||
try {
|
try {
|
||||||
const path = chooseFolder ? (await ipcInvoke('dialog:pickFolder', { title: t('decals.choose') })).path : null;
|
const path = chooseFolder
|
||||||
|
? (await ipcInvoke('dialog:pickFolder', {
|
||||||
|
title: t('decals.choose'),
|
||||||
|
...(record.sourcePath ? { defaultPath: record.sourcePath } : {}),
|
||||||
|
})).path
|
||||||
|
: null;
|
||||||
if (chooseFolder && path === null) return;
|
if (chooseFolder && path === null) return;
|
||||||
await ipcInvoke('copies:setDecalSource', { id: record.id, path });
|
await ipcInvoke('copies:setDecalSource', { id: record.id, path });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -71,6 +104,11 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc
|
|||||||
<Row label={t('copies.summary.data')} hint={t('copies.summary.dataHint')}>{folder(record.dataPath)}</Row>
|
<Row label={t('copies.summary.data')} hint={t('copies.summary.dataHint')}>{folder(record.dataPath)}</Row>
|
||||||
<Row label={t('decals.source')} hint={t('decals.hint')}>
|
<Row label={t('decals.source')} hint={t('decals.hint')}>
|
||||||
<span>{t(importing ? 'decals.importing' : record.decalCacheId ? 'decals.imported' : 'decals.default')}</span>
|
<span>{t(importing ? 'decals.importing' : record.decalCacheId ? 'decals.imported' : 'decals.default')}</span>
|
||||||
|
{detectedSourceDecals && (
|
||||||
|
<button type="button" className="button" disabled={importing} onClick={() => { void importFromSource(); }}>
|
||||||
|
{t('decals.importFromSource')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button type="button" className="button" disabled={importing} onClick={() => { void applyDecals(true); }}>
|
<button type="button" className="button" disabled={importing} onClick={() => { void applyDecals(true); }}>
|
||||||
{t('decals.choose')}
|
{t('decals.choose')}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/ma
|
|||||||
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
|
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
|
||||||
|
|
||||||
export type MaintenanceOperation = MaintenanceRequest['operation'];
|
export type MaintenanceOperation = MaintenanceRequest['operation'];
|
||||||
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
|
export type MaintenanceOptions = Pick<
|
||||||
|
IpcInput<'copies:maintain'>,
|
||||||
|
'deleteFiles' | 'restoreStock' | 'deleteData' | 'steamLocations' | 'sourcePath'
|
||||||
|
>;
|
||||||
|
|
||||||
export interface MaintenanceOutcome {
|
export interface MaintenanceOutcome {
|
||||||
readonly copyId: string;
|
readonly copyId: string;
|
||||||
|
|||||||
@@ -80,8 +80,10 @@ export function homeBar(
|
|||||||
detail: t('launch.versionDetail', { version: state.actualVersion ?? t('source.versionUnknown') }),
|
detail: t('launch.versionDetail', { version: state.actualVersion ?? t('source.versionUnknown') }),
|
||||||
primary: { label: t('launch.check'), onClick: actions.checkVersion },
|
primary: { label: t('launch.check'), onClick: actions.checkVersion },
|
||||||
};
|
};
|
||||||
case 'failed':
|
case 'failed': {
|
||||||
return { tone: 'bad', title: t(`errors.${state.error ?? 'launch_failed'}`), primary: retry };
|
const key = `errors.${state.error ?? 'launch_failed'}` as const;
|
||||||
|
return { tone: 'bad', title: state.errorParams ? t(key, state.errorParams) : t(key), primary: retry };
|
||||||
|
}
|
||||||
case 'ready':
|
case 'ready':
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ interface DataStepProps {
|
|||||||
readonly dataPath: string;
|
readonly dataPath: string;
|
||||||
readonly dataProblem: DataFolderProblem | null;
|
readonly dataProblem: DataFolderProblem | null;
|
||||||
readonly decalSource: string | null;
|
readonly decalSource: string | null;
|
||||||
|
readonly decalAutoDetected: boolean;
|
||||||
|
readonly defaultDecalPath?: string | null | undefined;
|
||||||
readonly steamDataPath: string | null;
|
readonly steamDataPath: string | null;
|
||||||
readonly steamDataConfirmed: boolean;
|
readonly steamDataConfirmed: boolean;
|
||||||
readonly onSteamDataConfirmed: (confirmed: boolean) => void;
|
readonly onSteamDataConfirmed: (confirmed: boolean) => void;
|
||||||
@@ -17,7 +19,19 @@ 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, dataProblem, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) {
|
export function DataStep({
|
||||||
|
dataPath,
|
||||||
|
dataProblem,
|
||||||
|
decalSource,
|
||||||
|
decalAutoDetected,
|
||||||
|
defaultDecalPath,
|
||||||
|
steamDataPath,
|
||||||
|
steamDataConfirmed,
|
||||||
|
onSteamDataConfirmed,
|
||||||
|
onDataPath,
|
||||||
|
onDecalSource,
|
||||||
|
onError,
|
||||||
|
}: DataStepProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -35,9 +49,16 @@ export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, st
|
|||||||
</Notice>
|
</Notice>
|
||||||
)}
|
)}
|
||||||
<Row label={t('decals.source')} hint={t('decals.hint')}>
|
<Row label={t('decals.source')} hint={t('decals.hint')}>
|
||||||
<FolderField path={decalSource} dialogTitle={t('decals.choose')} onChosen={onDecalSource} onError={onError} />
|
<FolderField
|
||||||
|
path={decalSource}
|
||||||
|
defaultPath={defaultDecalPath}
|
||||||
|
dialogTitle={t('decals.choose')}
|
||||||
|
onChosen={onDecalSource}
|
||||||
|
onError={onError}
|
||||||
|
/>
|
||||||
{decalSource && <button type="button" className="button" onClick={() => onDecalSource(null)}>{t('decals.useDefault')}</button>}
|
{decalSource && <button type="button" className="button" onClick={() => onDecalSource(null)}>{t('decals.useDefault')}</button>}
|
||||||
</Row>
|
</Row>
|
||||||
|
{decalAutoDetected && decalSource && <Notice tone="info">{t('decals.autoDetectedNotice')}</Notice>}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -89,6 +89,14 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me
|
|||||||
: t('method.spaceSavingPending')}
|
: t('method.spaceSavingPending')}
|
||||||
onSelect={() => choose('hardlink')}
|
onSelect={() => choose('hardlink')}
|
||||||
>
|
>
|
||||||
|
{sourceSize && savingAvailable && (
|
||||||
|
<p className="small">
|
||||||
|
{t('method.spaceSavingBreakdown', {
|
||||||
|
copy: formatBytes(bytesToCopy(sourceSize, 'hardlink')),
|
||||||
|
shared: formatBytes(sourceSize.linkableBytes ?? 0),
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
{targetPicker}
|
{targetPicker}
|
||||||
</Choice>
|
</Choice>
|
||||||
<Choice
|
<Choice
|
||||||
|
|||||||
@@ -19,6 +19,27 @@ export function ProgressStep({ progress, useHardLinks, importDecals }: {
|
|||||||
const current = phases.indexOf(phase);
|
const current = phases.indexOf(phase);
|
||||||
const tracking = (phase === 'copying' || phase === 'verifying') && progress !== null;
|
const tracking = (phase === 'copying' || phase === 'verifying') && progress !== null;
|
||||||
const caption = phase === 'verifying' ? 'progress.verified' : useHardLinks ? 'progress.prepared' : 'progress.copied';
|
const caption = phase === 'verifying' ? 'progress.verified' : useHardLinks ? 'progress.prepared' : 'progress.copied';
|
||||||
|
const hardlinkStats = phase === 'copying'
|
||||||
|
&& useHardLinks
|
||||||
|
&& progress !== null
|
||||||
|
&& progress.copiedBytes !== undefined
|
||||||
|
&& progress.copyTotalBytes !== undefined
|
||||||
|
&& progress.linkedBytes !== undefined
|
||||||
|
&& progress.linkTotalBytes !== undefined
|
||||||
|
&& progress.linkedFiles !== undefined
|
||||||
|
&& progress.linkTotalFiles !== undefined
|
||||||
|
&& progress.linkTotalFiles > 0
|
||||||
|
? {
|
||||||
|
copiedBytes: progress.copiedBytes,
|
||||||
|
copyTotalBytes: progress.copyTotalBytes,
|
||||||
|
linkedBytes: progress.linkedBytes,
|
||||||
|
linkTotalBytes: progress.linkTotalBytes,
|
||||||
|
linkedFiles: progress.linkedFiles,
|
||||||
|
linkTotalFiles: progress.linkTotalFiles,
|
||||||
|
copiedFiles: Math.max(0, progress.doneFiles - progress.linkedFiles),
|
||||||
|
copyTotalFiles: Math.max(0, progress.totalFiles - progress.linkTotalFiles),
|
||||||
|
}
|
||||||
|
: null;
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{phases.map((name, position) => {
|
{phases.map((name, position) => {
|
||||||
@@ -32,14 +53,35 @@ export function ProgressStep({ progress, useHardLinks, importDecals }: {
|
|||||||
})}
|
})}
|
||||||
<ProgressBar value={tracking ? progress.doneBytes : 0} max={tracking ? progress.totalBytes : null} large />
|
<ProgressBar value={tracking ? progress.doneBytes : 0} max={tracking ? progress.totalBytes : null} large />
|
||||||
{tracking && (
|
{tracking && (
|
||||||
<div className="progress-caption">
|
hardlinkStats ? (
|
||||||
{t(caption, {
|
<>
|
||||||
done: formatBytes(progress.doneBytes),
|
<div className="progress-caption">
|
||||||
total: formatBytes(progress.totalBytes),
|
{t('progress.copiedActual', {
|
||||||
doneFiles: progress.doneFiles.toLocaleString(),
|
copied: formatBytes(hardlinkStats.copiedBytes),
|
||||||
totalFiles: progress.totalFiles.toLocaleString(),
|
copyTotal: formatBytes(hardlinkStats.copyTotalBytes),
|
||||||
})}
|
copiedFiles: hardlinkStats.copiedFiles.toLocaleString(),
|
||||||
</div>
|
copyTotalFiles: hardlinkStats.copyTotalFiles.toLocaleString(),
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<div className="progress-caption">
|
||||||
|
{t('progress.linkedShared', {
|
||||||
|
linked: formatBytes(hardlinkStats.linkedBytes),
|
||||||
|
linkTotal: formatBytes(hardlinkStats.linkTotalBytes),
|
||||||
|
linkedFiles: hardlinkStats.linkedFiles.toLocaleString(),
|
||||||
|
linkTotalFiles: hardlinkStats.linkTotalFiles.toLocaleString(),
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="progress-caption">
|
||||||
|
{t(caption, {
|
||||||
|
done: formatBytes(progress.doneBytes),
|
||||||
|
total: formatBytes(progress.totalBytes),
|
||||||
|
doneFiles: progress.doneFiles.toLocaleString(),
|
||||||
|
totalFiles: progress.totalFiles.toLocaleString(),
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -44,6 +44,8 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
|
|||||||
steamDataConfirmed={wizard.steamDataConfirmed}
|
steamDataConfirmed={wizard.steamDataConfirmed}
|
||||||
onSteamDataConfirmed={wizard.setSteamDataConfirmed}
|
onSteamDataConfirmed={wizard.setSteamDataConfirmed}
|
||||||
decalSource={wizard.decalSource}
|
decalSource={wizard.decalSource}
|
||||||
|
decalAutoDetected={wizard.decalAutoDetected}
|
||||||
|
defaultDecalPath={wizard.decalProbePath}
|
||||||
onDataPath={wizard.setDataPath}
|
onDataPath={wizard.setDataPath}
|
||||||
onDecalSource={wizard.setDecalSource}
|
onDecalSource={wizard.setDecalSource}
|
||||||
onError={wizard.report}
|
onError={wizard.report}
|
||||||
|
|||||||
@@ -40,7 +40,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
|||||||
problem: DataFolderProblem | null;
|
problem: DataFolderProblem | null;
|
||||||
confirmed: boolean;
|
confirmed: boolean;
|
||||||
} | null>(null);
|
} | null>(null);
|
||||||
const [decalSource, setDecalSource] = useState<string | null>(null);
|
const [decalSource, setDecalSourceState] = useState<string | null>(null);
|
||||||
|
const [decalAutoDetected, setDecalAutoDetected] = useState(false);
|
||||||
|
const [decalManuallyEdited, setDecalManuallyEdited] = useState(false);
|
||||||
const [check, setCheck] = useState<PatchCheck | null>(null);
|
const [check, setCheck] = useState<PatchCheck | null>(null);
|
||||||
const [missingAccepted, setMissingAccepted] = useState(false);
|
const [missingAccepted, setMissingAccepted] = useState(false);
|
||||||
const [progress, setProgress] = useState<InstallProgress | null>(null);
|
const [progress, setProgress] = useState<InstallProgress | null>(null);
|
||||||
@@ -66,8 +68,34 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
|||||||
? (source?.path ?? null)
|
? (source?.path ?? null)
|
||||||
: null;
|
: null;
|
||||||
const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null;
|
const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null;
|
||||||
|
const decalProbePath = stockSource?.path ?? source?.path ?? null;
|
||||||
const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]);
|
const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]);
|
||||||
|
|
||||||
|
// Read-only probe of the player-selected source folder for a usable decal cache.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active || !decalProbePath || decalManuallyEdited) return;
|
||||||
|
let current = true;
|
||||||
|
ipcInvoke('decals:detectSource', { path: decalProbePath })
|
||||||
|
.then(({ path }) => {
|
||||||
|
if (!current) return;
|
||||||
|
if (path) {
|
||||||
|
setDecalSourceState(path);
|
||||||
|
setDecalAutoDetected(true);
|
||||||
|
} else {
|
||||||
|
setDecalSourceState(null);
|
||||||
|
setDecalAutoDetected(false);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!current) return;
|
||||||
|
setDecalSourceState(null);
|
||||||
|
setDecalAutoDetected(false);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
current = false;
|
||||||
|
};
|
||||||
|
}, [active, decalProbePath, decalManuallyEdited]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!active || !dataPath) return;
|
if (!active || !dataPath) return;
|
||||||
let current = true;
|
let current = true;
|
||||||
@@ -119,6 +147,12 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
|||||||
|
|
||||||
useEffect(() => ipcOn('event:install-progress', setProgress), []);
|
useEffect(() => ipcOn('event:install-progress', setProgress), []);
|
||||||
|
|
||||||
|
const resetDecals = (): void => {
|
||||||
|
setDecalSourceState(null);
|
||||||
|
setDecalAutoDetected(false);
|
||||||
|
setDecalManuallyEdited(false);
|
||||||
|
};
|
||||||
|
|
||||||
const start = (): void => {
|
const start = (): void => {
|
||||||
clear();
|
clear();
|
||||||
setMode('new');
|
setMode('new');
|
||||||
@@ -130,7 +164,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
|||||||
setDraftId(null);
|
setDraftId(null);
|
||||||
setDataPath('');
|
setDataPath('');
|
||||||
setDataInspection(null);
|
setDataInspection(null);
|
||||||
setDecalSource(null);
|
resetDecals();
|
||||||
setActive(true);
|
setActive(true);
|
||||||
ipcInvoke('install:prepareCopy').then(({ id, dataPath: folder }) => {
|
ipcInvoke('install:prepareCopy').then(({ id, dataPath: folder }) => {
|
||||||
setDraftId(id);
|
setDraftId(id);
|
||||||
@@ -145,11 +179,13 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
|||||||
setStockSource(null);
|
setStockSource(null);
|
||||||
setChoice(nextMode === 'existing' ? { method: 'existing', target: null, steamConfirmed: false } : NO_CHOICE);
|
setChoice(nextMode === 'existing' ? { method: 'existing', target: null, steamConfirmed: false } : NO_CHOICE);
|
||||||
setName('');
|
setName('');
|
||||||
|
resetDecals();
|
||||||
};
|
};
|
||||||
|
|
||||||
const chooseSource = (found: GameFolderInspection | null): void => {
|
const chooseSource = (found: GameFolderInspection | null): void => {
|
||||||
setSource(found);
|
setSource(found);
|
||||||
setStockSource(null);
|
setStockSource(null);
|
||||||
|
resetDecals();
|
||||||
const isExisting = mode === 'existing' || found?.hasOfflineBackup || found?.needsStockSource;
|
const isExisting = mode === 'existing' || found?.hasOfflineBackup || found?.needsStockSource;
|
||||||
const defaultMethod = isExisting ? 'existing' : 'copy';
|
const defaultMethod = isExisting ? 'existing' : 'copy';
|
||||||
setChoice({ method: defaultMethod, target: null, steamConfirmed: false });
|
setChoice({ method: defaultMethod, target: null, steamConfirmed: false });
|
||||||
@@ -166,6 +202,17 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const chooseStockSource = (found: GameFolderInspection | null): void => {
|
||||||
|
setStockSource(found);
|
||||||
|
resetDecals();
|
||||||
|
};
|
||||||
|
|
||||||
|
const setDecalSource = (path: string | null): void => {
|
||||||
|
setDecalSourceState(path);
|
||||||
|
setDecalAutoDetected(false);
|
||||||
|
setDecalManuallyEdited(true);
|
||||||
|
};
|
||||||
|
|
||||||
const install = (): void => {
|
const install = (): void => {
|
||||||
if (!sourceUsable(source, stockSource) || !draftId || !dataReady) return;
|
if (!sourceUsable(source, stockSource) || !draftId || !dataReady) return;
|
||||||
const directFolder = choice.method === 'in-place' || choice.method === 'existing';
|
const directFolder = choice.method === 'in-place' || choice.method === 'existing';
|
||||||
@@ -230,9 +277,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn,
|
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, decalAutoDetected, decalProbePath, 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: chooseStockSource, 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import type { SaveCrewEdit, SaveCrewPreview } from '@shared/schemas/crew-saves.ts';
|
||||||
|
|
||||||
|
export interface PendingCrewChange {
|
||||||
|
readonly edit: SaveCrewEdit;
|
||||||
|
readonly preview: SaveCrewPreview;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
readonly pending: PendingCrewChange;
|
||||||
|
readonly disabled: boolean;
|
||||||
|
readonly busy: boolean;
|
||||||
|
readonly onApply: () => void;
|
||||||
|
readonly onCancel: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SaveCrewChangePreview({ pending, disabled, busy, onApply, onCancel }: Props) {
|
||||||
|
const { t, i18n } = useTranslation();
|
||||||
|
const { edit, preview } = pending;
|
||||||
|
const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
||||||
|
const format = new Intl.NumberFormat(i18n.language);
|
||||||
|
const vehicle = preview.vehicle[language];
|
||||||
|
const restored = preview.restoredVehicle[language];
|
||||||
|
const levels = preview.levels.filter(({ type, before, after }) => (edit.action === 'level' && type === edit.type) || before !== after);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="maintenance-confirm" aria-live="polite">
|
||||||
|
{edit.action === 'close' && <p>{t('saves.crews.confirmClose')}</p>}
|
||||||
|
{edit.action === 'close' && vehicle && <p>{t('saves.crews.removeVehicle', { vehicle })}</p>}
|
||||||
|
{edit.action === 'open' && <p>{restored ? t('saves.crews.confirmRestoreVehicle', { vehicle: restored }) : t('saves.crews.confirmOpen')}</p>}
|
||||||
|
{edit.action === 'add' && <p>{t('saves.crews.confirmAdd')}</p>}
|
||||||
|
{edit.action === 'level' && <p>{t('saves.crews.previewLevel', { target: format.format(edit.target) })}</p>}
|
||||||
|
{levels.length > 0 && <ul>{levels.map(({ type, before, after }) => (
|
||||||
|
<li key={type}>{t('saves.crews.levelChange', { type: t(`saves.crews.types.${type}`), before: format.format(before), after: format.format(after) })}</li>
|
||||||
|
))}</ul>}
|
||||||
|
{preview.presets.length > 0 && (
|
||||||
|
<>
|
||||||
|
<p>{t('saves.crews.affectedPresets')}</p>
|
||||||
|
<ul>{preview.presets.map(({ index, title, vehicle: assignment, empty }) => (
|
||||||
|
<li key={index}>
|
||||||
|
{title || t('saves.crews.preset', { number: index + 1 })}
|
||||||
|
{assignment[language] && ` · ${assignment[language]}`}
|
||||||
|
{empty && ` · ${t('saves.crews.emptyPreset')}`}
|
||||||
|
</li>
|
||||||
|
))}</ul>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{!preview.changed && <p>{t('saves.crews.noChange')}</p>}
|
||||||
|
<div className="copy-list-actions">
|
||||||
|
<button type="button" className="button" disabled={busy} onClick={onCancel}>{t('wizard.cancel')}</button>
|
||||||
|
<button type="button" className="button button-primary" disabled={disabled || !preview.changed} onClick={onApply}>{t('saves.apply')}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { useState, type FormEvent } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import type { SaveCrewEdit, SaveCrewView } from '@shared/schemas/crew-saves.ts';
|
||||||
|
import { Row } from '../../components/Row.tsx';
|
||||||
|
|
||||||
|
type Level = SaveCrewView['crews'][number]['levels'][number];
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
readonly crewId: number;
|
||||||
|
readonly levels: readonly Level[];
|
||||||
|
readonly disabled: boolean;
|
||||||
|
readonly onPreview: (edit: SaveCrewEdit) => void;
|
||||||
|
readonly onChange: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SaveCrewLevelEditor({ crewId, levels, disabled, onPreview, onChange }: Props) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [type, setType] = useState(levels[0]?.type);
|
||||||
|
const [target, setTarget] = useState<string | null>(null);
|
||||||
|
const range = levels.find((level) => level.type === type);
|
||||||
|
if (!range) return null;
|
||||||
|
|
||||||
|
function submit(event: FormEvent<HTMLFormElement>): void {
|
||||||
|
event.preventDefault();
|
||||||
|
const value = Number(target);
|
||||||
|
if (!disabled && range && target?.trim() && Number.isFinite(value)) {
|
||||||
|
onPreview({ action: 'level', crewId, type: range.type, target: value });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={submit}>
|
||||||
|
<Row label={t('saves.crews.target')} hint={t('saves.crews.levelRange', { min: range.min, max: range.max })}>
|
||||||
|
<select className="select" aria-label={t('saves.crews.type')} value={range.type} disabled={disabled} onChange={(event) => {
|
||||||
|
setType(levels.find(({ type: value }) => value === event.target.value)?.type);
|
||||||
|
setTarget(null);
|
||||||
|
onChange();
|
||||||
|
}}>
|
||||||
|
{levels.map(({ type: value }) => <option key={value} value={value}>{t(`saves.crews.types.${value}`)}</option>)}
|
||||||
|
</select>
|
||||||
|
<input className="input" type="number" aria-label={t('saves.crews.target')} disabled={disabled} required step="any"
|
||||||
|
min={range.min} max={range.max} value={target ?? String(range.level)} onChange={(event) => { setTarget(event.target.value); onChange(); }} />
|
||||||
|
<button type="submit" className="button" disabled={disabled || target === null || !target.trim() || Number(target) === range.level}>
|
||||||
|
{t('saves.crews.preview')}
|
||||||
|
</button>
|
||||||
|
</Row>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import type { SaveCrewEdit, SaveCrewView } from '@shared/schemas/crew-saves.ts';
|
||||||
|
import { Row } from '../../components/Row.tsx';
|
||||||
|
import { ipcInvoke } from '../../ipc.ts';
|
||||||
|
import { SaveCrewChangePreview, type PendingCrewChange } from './SaveCrewChangePreview.tsx';
|
||||||
|
import { SaveCrewLevelEditor } from './SaveCrewLevelEditor.tsx';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
readonly copyId: string;
|
||||||
|
readonly userId: string;
|
||||||
|
readonly readOnly: boolean;
|
||||||
|
readonly onError: (error: unknown) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function useCrewPanel({ copyId, userId, readOnly, onError }: Props) {
|
||||||
|
const [view, setView] = useState<SaveCrewView | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [loadFailed, setLoadFailed] = useState(false);
|
||||||
|
const [saved, setSaved] = useState(false);
|
||||||
|
const [pending, setPending] = useState<PendingCrewChange | null>(null);
|
||||||
|
const keys = { copyId, userId };
|
||||||
|
const disabled = busy || readOnly;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
ipcInvoke('saves:crews', { copyId, userId }).then((next) => {
|
||||||
|
if (mounted) setView(next);
|
||||||
|
}).catch((error: unknown) => {
|
||||||
|
if (mounted) {
|
||||||
|
setLoadFailed(true);
|
||||||
|
onError(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return () => { mounted = false; };
|
||||||
|
}, [copyId, userId, onError]);
|
||||||
|
|
||||||
|
function run(action: () => Promise<void>): void {
|
||||||
|
setBusy(true);
|
||||||
|
setSaved(false);
|
||||||
|
setPending(null);
|
||||||
|
action().catch(onError).finally(() => setBusy(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
function preview(edit: SaveCrewEdit): void {
|
||||||
|
const country = view?.selected;
|
||||||
|
if (!country || disabled) return;
|
||||||
|
run(async () => setPending({ edit, preview: await ipcInvoke('saves:previewCrew', { ...keys, country, edit }) }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function apply(onApplied: () => void): void {
|
||||||
|
const country = view?.selected;
|
||||||
|
if (!pending || !country || disabled) return;
|
||||||
|
run(async () => {
|
||||||
|
setView(await ipcInvoke('saves:editCrew', { ...keys, country, edit: pending.edit, token: pending.preview.token }));
|
||||||
|
setSaved(true);
|
||||||
|
onApplied();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
view, busy, disabled, loadFailed, saved, pending, preview, apply,
|
||||||
|
cancel: () => setPending(null),
|
||||||
|
chooseCountry: (country: string) => run(async () => setView(await ipcInvoke('saves:crews', { ...keys, country }))),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SaveCrews(props: Props) {
|
||||||
|
const { t, i18n } = useTranslation();
|
||||||
|
const { view, busy, disabled, loadFailed, saved, pending, chooseCountry, preview, apply, cancel } = useCrewPanel(props);
|
||||||
|
const [editing, setEditing] = useState<number | null>(null);
|
||||||
|
const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
||||||
|
const format = new Intl.NumberFormat(i18n.language);
|
||||||
|
|
||||||
|
if (!view) return <p className="lead">{t(loadFailed ? 'saves.crews.loadFailed' : 'saves.loading')}</p>;
|
||||||
|
if (!view.selected) return <p className="lead">{t('saves.crews.noCountries')}</p>;
|
||||||
|
const confirmation = pending && <SaveCrewChangePreview pending={pending} disabled={disabled} busy={busy} onApply={() => apply(() => setEditing(null))} onCancel={cancel} />;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Row label={t('saves.tree.country')}>
|
||||||
|
<select className="select" aria-label={t('saves.tree.country')} value={view.selected} disabled={busy} onChange={(event) => {
|
||||||
|
setEditing(null);
|
||||||
|
chooseCountry(event.target.value);
|
||||||
|
}}>
|
||||||
|
{view.countries.map(({ id, name }) => <option value={id} key={id}>{name[language]}</option>)}
|
||||||
|
</select>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('saves.crews.slots', { open: view.activeCount, max: view.max })} hint={t('saves.crews.minimum', { count: view.min })}>
|
||||||
|
<button type="button" className="button" disabled={disabled || !view.canAdd} onClick={() => preview({ action: 'add' })}>{t('saves.crews.add')}</button>
|
||||||
|
</Row>
|
||||||
|
{props.readOnly && <p className="small">{t('saves.readOnly')}</p>}
|
||||||
|
{saved && <p className="small" role="status">{t('saves.crews.saved')}</p>}
|
||||||
|
{pending?.edit.action === 'add' && confirmation}
|
||||||
|
<div className="save-crews-list">
|
||||||
|
{view.crews.map((crew, index) => (
|
||||||
|
<div key={crew.id}>
|
||||||
|
<Row label={t('saves.crews.group', { number: index + 1 })} hint={crew.vehicle[language] || t('saves.crews.noVehicle')}>
|
||||||
|
<span>{t(crew.open ? 'saves.crews.opened' : 'saves.crews.closed')}</span>
|
||||||
|
<span className="small">{crew.levels.map(({ type, level }) => `${t(`saves.crews.types.${type}`)} ${format.format(level)}`).join(' · ')}</span>
|
||||||
|
<button type="button" className="button" disabled={disabled || !crew.canToggle} onClick={() => preview({ action: crew.open ? 'close' : 'open', crewId: crew.id })}>
|
||||||
|
{t(crew.open ? 'saves.crews.close' : 'saves.crews.open')}
|
||||||
|
</button>
|
||||||
|
{crew.levels.length > 0 && <button type="button" className="button" disabled={disabled} aria-expanded={editing === crew.id} onClick={() => {
|
||||||
|
setEditing(editing === crew.id ? null : crew.id);
|
||||||
|
cancel();
|
||||||
|
}}>{t('saves.crews.editLevel')}</button>}
|
||||||
|
</Row>
|
||||||
|
{editing === crew.id && <SaveCrewLevelEditor crewId={crew.id} levels={crew.levels} disabled={disabled} onPreview={preview} onChange={cancel} />}
|
||||||
|
{pending?.edit.action !== 'add' && pending?.preview.crewId === crew.id && confirmation}
|
||||||
|
</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();
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { OfficialSaveImport } from './OfficialSaveImport.tsx';
|
|||||||
import { SaveAvatarField } from './SaveAvatarField.tsx';
|
import { SaveAvatarField } from './SaveAvatarField.tsx';
|
||||||
import { SaveResearch } from './SaveResearch.tsx';
|
import { SaveResearch } from './SaveResearch.tsx';
|
||||||
import { SaveBackups } from './SaveBackups.tsx';
|
import { SaveBackups } from './SaveBackups.tsx';
|
||||||
|
import { SaveCrews } from './SaveCrews.tsx';
|
||||||
|
|
||||||
interface SavesPageProps {
|
interface SavesPageProps {
|
||||||
readonly copy: InstallRecord;
|
readonly copy: InstallRecord;
|
||||||
@@ -314,6 +315,7 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
|||||||
)}
|
)}
|
||||||
{section === 'backup' && <SaveBackups key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} onRestored={updateDetails} />}
|
{section === 'backup' && <SaveBackups key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} onRestored={updateDetails} />}
|
||||||
{section === 'vehicles' && <SaveResearch key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} />}
|
{section === 'vehicles' && <SaveResearch key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} />}
|
||||||
|
{section === 'crews' && <SaveCrews key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} />}
|
||||||
</Sheet>
|
</Sheet>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
import { useState, type FormEvent, type ReactNode } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import {
|
||||||
|
GROUND_AI_DRIVE_MODES,
|
||||||
|
GROUND_AI_MODES,
|
||||||
|
TuningPatchSchema,
|
||||||
|
type GroundAiTuningValues,
|
||||||
|
type TuningPatch,
|
||||||
|
type TuningView,
|
||||||
|
} from '@shared/schemas/tuning.ts';
|
||||||
|
import { Row } from '../../components/Row.tsx';
|
||||||
|
import {
|
||||||
|
ALL_BOT_FIELDS,
|
||||||
|
BOT_TUNING_GROUPS,
|
||||||
|
readBotFieldValue,
|
||||||
|
type BotFieldSpec,
|
||||||
|
} from './bot-tuning-fields.ts';
|
||||||
|
|
||||||
|
type DraftMap = Record<string, string | boolean>;
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
readonly data: TuningView;
|
||||||
|
readonly saving: boolean;
|
||||||
|
readonly onSave: (patch: TuningPatch) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toInputValue(value: string | number | boolean): string | boolean {
|
||||||
|
return typeof value === 'boolean' ? value : String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeSection<T extends Record<string, unknown>>(
|
||||||
|
base: T,
|
||||||
|
patch: { readonly [K in keyof T]?: T[K] | undefined } | undefined,
|
||||||
|
): T {
|
||||||
|
if (!patch) return base;
|
||||||
|
const next: Record<string, unknown> = { ...base };
|
||||||
|
for (const [key, value] of Object.entries(patch)) {
|
||||||
|
if (value !== undefined) next[key] = value;
|
||||||
|
}
|
||||||
|
return next as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasValidCrossFieldRules(effective: GroundAiTuningValues, patch: TuningPatch['groundAi']): boolean {
|
||||||
|
if (!patch) return true;
|
||||||
|
const cmd = mergeSection(effective.commander, patch.commander);
|
||||||
|
if (cmd.bttlAssaultPct + cmd.bttlFlankPct + cmd.bttlOverwatchPct > 100) return false;
|
||||||
|
if (cmd.conqAssaultPct + cmd.conqFlankPct > 100) return false;
|
||||||
|
if (cmd.conqHoldDefendPct + cmd.conqHoldOverwatchPct > 100) return false;
|
||||||
|
const macro = mergeSection(effective.macro, patch.macro);
|
||||||
|
if (macro.recaptureMaxBots < macro.recaptureMinBots) return false;
|
||||||
|
const sm = mergeSection(effective.stateMachine, patch.stateMachine);
|
||||||
|
if (sm.coverMaxDistM <= sm.coverMinDistM) return false;
|
||||||
|
const est = mergeSection(effective.estimation, patch.estimation);
|
||||||
|
if (est.watchMaxSec < est.watchMinSec || est.velStableSpanSec <= est.velSampleMinSpanSec) return false;
|
||||||
|
const fc = mergeSection(effective.fireControl, patch.fireControl);
|
||||||
|
if (fc.midRangeM <= fc.closeRangeM || fc.longRangeM <= fc.midRangeM) return false;
|
||||||
|
return fc.minFireThreshold <= fc.fireThreshold;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BotTuningPanel({ data, saving, onSave }: Props) {
|
||||||
|
const { t, i18n } = useTranslation();
|
||||||
|
const [draft, setDraft] = useState<DraftMap>({});
|
||||||
|
const [message, setMessage] = useState<'invalid' | 'saved' | null>(null);
|
||||||
|
const [openGroups, setOpenGroups] = useState<Record<string, boolean>>(() =>
|
||||||
|
Object.fromEntries(BOT_TUNING_GROUPS.map((group) => [group.id, group.defaultOpen])),
|
||||||
|
);
|
||||||
|
|
||||||
|
const format = new Intl.NumberFormat(i18n.language);
|
||||||
|
const activeMode = String(draft['groundAi.mode'] ?? data.effective.groundAi.mode);
|
||||||
|
const allOpen = BOT_TUNING_GROUPS.every((group) => openGroups[group.id]);
|
||||||
|
|
||||||
|
const set = (id: string, value: string | boolean): void => {
|
||||||
|
setMessage(null);
|
||||||
|
setDraft((previous) => ({ ...previous, [id]: value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleAllGroups = (): void => {
|
||||||
|
const nextState = !allOpen;
|
||||||
|
setOpenGroups(Object.fromEntries(BOT_TUNING_GROUPS.map((group) => [group.id, nextState])));
|
||||||
|
};
|
||||||
|
|
||||||
|
const reset = (): void => {
|
||||||
|
setMessage(null);
|
||||||
|
setDraft(Object.fromEntries(
|
||||||
|
ALL_BOT_FIELDS.map((spec) => [spec.id, toInputValue(readBotFieldValue(data.defaults, spec))]),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
const fieldLabel = (spec: BotFieldSpec): string => {
|
||||||
|
if (spec.kind === 'flatInt') return t(`tuning.fields.${spec.id}`);
|
||||||
|
if (spec.kind === 'groundAiMode') return t('tuning.botFields.mode');
|
||||||
|
return t(`tuning.botFields.${spec.section}.${spec.field}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaultLabel = (spec: BotFieldSpec): string => {
|
||||||
|
const value = readBotFieldValue(data.defaults, spec);
|
||||||
|
if (spec.kind === 'groundAiMode') return t(`tuning.botModes.${value}`);
|
||||||
|
if (spec.kind === 'driveMode') return t(`tuning.botDriveModes.${value}`);
|
||||||
|
if (spec.kind === 'steerSign') return value === 1 ? t('tuning.botSteer.normal') : t('tuning.botSteer.inverted');
|
||||||
|
if (typeof value === 'boolean') return t(value ? 'tuning.on' : 'tuning.off');
|
||||||
|
const formatted = format.format(Number(value));
|
||||||
|
const unit = 'unit' in spec && spec.unit ? ` ${spec.unit}` : '';
|
||||||
|
return `${formatted}${unit}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderEditor = (spec: BotFieldSpec): ReactNode => {
|
||||||
|
const active = draft[spec.id] ?? toInputValue(readBotFieldValue(data.effective, spec));
|
||||||
|
const label = fieldLabel(spec);
|
||||||
|
|
||||||
|
if (spec.kind === 'bool') {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
aria-label={label}
|
||||||
|
disabled={saving}
|
||||||
|
checked={active === true}
|
||||||
|
onChange={(event) => set(spec.id, event.target.checked)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (spec.kind === 'groundAiMode') {
|
||||||
|
return (
|
||||||
|
<select
|
||||||
|
className="select"
|
||||||
|
aria-label={label}
|
||||||
|
disabled={saving}
|
||||||
|
value={String(active)}
|
||||||
|
onChange={(event) => set(spec.id, event.target.value)}
|
||||||
|
>
|
||||||
|
{GROUND_AI_MODES.map((mode) => (
|
||||||
|
<option key={mode} value={mode}>{t(`tuning.botModes.${mode}`)}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (spec.kind === 'driveMode') {
|
||||||
|
return (
|
||||||
|
<select
|
||||||
|
className="select"
|
||||||
|
aria-label={label}
|
||||||
|
disabled={saving}
|
||||||
|
value={String(active)}
|
||||||
|
onChange={(event) => set(spec.id, event.target.value)}
|
||||||
|
>
|
||||||
|
{GROUND_AI_DRIVE_MODES.map((mode) => (
|
||||||
|
<option key={mode} value={mode}>{t(`tuning.botDriveModes.${mode}`)}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (spec.kind === 'steerSign') {
|
||||||
|
return (
|
||||||
|
<select
|
||||||
|
className="select"
|
||||||
|
aria-label={label}
|
||||||
|
disabled={saving}
|
||||||
|
value={String(active)}
|
||||||
|
onChange={(event) => set(spec.id, event.target.value)}
|
||||||
|
>
|
||||||
|
<option value="1">{t('tuning.botSteer.normal')}</option>
|
||||||
|
<option value="-1">{t('tuning.botSteer.inverted')}</option>
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const isInt = spec.kind === 'int' || spec.kind === 'flatInt';
|
||||||
|
const unit = 'unit' in spec ? spec.unit : undefined;
|
||||||
|
return (
|
||||||
|
<div className="copy-list-actions">
|
||||||
|
<input
|
||||||
|
className="input"
|
||||||
|
aria-label={label}
|
||||||
|
type="number"
|
||||||
|
min={spec.min}
|
||||||
|
max={spec.max}
|
||||||
|
step={isInt ? '1' : 'any'}
|
||||||
|
value={String(active)}
|
||||||
|
disabled={saving}
|
||||||
|
onChange={(event) => set(spec.id, event.target.value)}
|
||||||
|
/>
|
||||||
|
{unit && <span>{unit}</span>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const submit = (event: FormEvent<HTMLFormElement>): void => {
|
||||||
|
event.preventDefault();
|
||||||
|
const rawPatch: Record<string, unknown> = {};
|
||||||
|
const groundAiPatch: Record<string, unknown> = {};
|
||||||
|
|
||||||
|
for (const spec of ALL_BOT_FIELDS) {
|
||||||
|
if (!(spec.id in draft)) continue;
|
||||||
|
const raw = draft[spec.id];
|
||||||
|
if (spec.kind === 'flatInt') {
|
||||||
|
rawPatch[spec.id] = raw === '' ? NaN : Number(raw);
|
||||||
|
} else if (spec.kind === 'groundAiMode') {
|
||||||
|
groundAiPatch['mode'] = raw;
|
||||||
|
} else {
|
||||||
|
const parsed = spec.kind === 'bool' || spec.kind === 'driveMode'
|
||||||
|
? raw
|
||||||
|
: (raw === '' ? NaN : Number(raw));
|
||||||
|
const sectionObj = (groundAiPatch[spec.section] as Record<string, unknown> | undefined) ?? {};
|
||||||
|
sectionObj[spec.field] = parsed;
|
||||||
|
groundAiPatch[spec.section] = sectionObj;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Object.keys(groundAiPatch).length > 0) rawPatch['groundAi'] = groundAiPatch;
|
||||||
|
|
||||||
|
const result = TuningPatchSchema.safeParse(rawPatch);
|
||||||
|
if (!result.success || !hasValidCrossFieldRules(data.effective.groundAi, result.data.groundAi)) {
|
||||||
|
setMessage('invalid');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setMessage(null);
|
||||||
|
onSave(result.data).then(() => {
|
||||||
|
setDraft({});
|
||||||
|
setMessage('saved');
|
||||||
|
}).catch(() => undefined);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={submit}>
|
||||||
|
<div className="tuning-toolbar">
|
||||||
|
<p className="small">{t('tuning.botModeHint')}</p>
|
||||||
|
<button type="button" className="button" onClick={toggleAllGroups}>
|
||||||
|
{t(allOpen ? 'tuning.collapseAll' : 'tuning.expandAll')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{activeMode === 'stock' && (
|
||||||
|
<p className="notice">{t('tuning.botStockNotice')}</p>
|
||||||
|
)}
|
||||||
|
{BOT_TUNING_GROUPS.map((group) => (
|
||||||
|
<details
|
||||||
|
key={group.id}
|
||||||
|
className="tuning-group"
|
||||||
|
open={openGroups[group.id]}
|
||||||
|
onToggle={(event) => {
|
||||||
|
const isOpen = event.currentTarget.open;
|
||||||
|
setOpenGroups((prev) => (prev[group.id] === isOpen ? prev : { ...prev, [group.id]: isOpen }));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<summary className="tuning-group-summary">
|
||||||
|
<span>{t(`tuning.botGroups.${group.id}`)}</span>
|
||||||
|
<small>{t(`tuning.botGroupHints.${group.id}`)}</small>
|
||||||
|
</summary>
|
||||||
|
<div className="tuning-group-body">
|
||||||
|
{group.fields.map((spec) => (
|
||||||
|
<Row
|
||||||
|
key={spec.id}
|
||||||
|
label={fieldLabel(spec)}
|
||||||
|
hint={t('tuning.default', { value: defaultLabel(spec) })}
|
||||||
|
>
|
||||||
|
{renderEditor(spec)}
|
||||||
|
</Row>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
))}
|
||||||
|
<div className="copy-list-actions tuning-actions">
|
||||||
|
<button type="button" className="button" disabled={saving} onClick={reset}>{t('tuning.reset')}</button>
|
||||||
|
<button type="submit" className="button button-primary" disabled={saving || Object.keys(draft).length === 0}>
|
||||||
|
{t('saves.apply')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{message && <p className="small" role={message === 'invalid' ? 'alert' : 'status'}>{t(`tuning.${message}`)}</p>}
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,20 +1,22 @@
|
|||||||
import { useEffect, useState, type FormEvent, type ReactNode } from 'react';
|
import { useEffect, useState, type FormEvent, type ReactNode } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||||
import { AUTO_TARGET_PICKS, TuningPatchSchema, type TuningValues, type TuningView } from '@shared/schemas/tuning.ts';
|
import { AUTO_TARGET_PICKS, TuningPatchSchema, type TuningPatch, type TuningValues, type TuningView } from '@shared/schemas/tuning.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';
|
||||||
import type { TuningSection } from '../../shell/navigation.ts';
|
import type { TuningSection } from '../../shell/navigation.ts';
|
||||||
|
import { BotTuningPanel } from './BotTuningPanel.tsx';
|
||||||
|
|
||||||
type Field = keyof TuningValues;
|
type SimpleSection = Exclude<TuningSection, 'bots'>;
|
||||||
|
type Field = Exclude<keyof TuningValues, 'groundAi'>;
|
||||||
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', '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<SimpleSection, readonly Field[]>;
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
readonly copy: InstallRecord;
|
readonly copy: InstallRecord;
|
||||||
@@ -34,7 +36,6 @@ export function TuningPage({ copy, section, onError }: Props) {
|
|||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [message, setMessage] = useState<'invalid' | 'saved' | null>(null);
|
const [message, setMessage] = useState<'invalid' | 'saved' | null>(null);
|
||||||
const title = t(`tuning.sections.${section}`);
|
const title = t(`tuning.sections.${section}`);
|
||||||
const sectionFields: readonly Field[] = fields[section];
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
let mounted = true;
|
||||||
@@ -46,6 +47,30 @@ export function TuningPage({ copy, section, onError }: Props) {
|
|||||||
|
|
||||||
if (!data) return <Sheet title={title} aside={copy.name}><p className="lead">{t('tuning.loading')}</p></Sheet>;
|
if (!data) return <Sheet title={title} aside={copy.name}><p className="lead">{t('tuning.loading')}</p></Sheet>;
|
||||||
const loaded = data;
|
const loaded = data;
|
||||||
|
|
||||||
|
const savePatch = async (patch: TuningPatch): Promise<void> => {
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const next = await ipcInvoke('tuning:update', { copyId: copy.id, patch });
|
||||||
|
setData(next);
|
||||||
|
} catch (error) {
|
||||||
|
onError(error);
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (section === 'bots') {
|
||||||
|
return (
|
||||||
|
<Sheet title={title} aside={copy.name} foot={t('tuning.nextLaunch')}>
|
||||||
|
<p className="small">{t('tuning.shared')}</p>
|
||||||
|
<BotTuningPanel data={loaded} saving={saving} onSave={savePatch} />
|
||||||
|
</Sheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sectionFields: readonly Field[] = fields[section];
|
||||||
const format = new Intl.NumberFormat(i18n.language);
|
const format = new Intl.NumberFormat(i18n.language);
|
||||||
const set = (field: Field, value: string | boolean): void => {
|
const set = (field: Field, value: string | boolean): void => {
|
||||||
setMessage(null);
|
setMessage(null);
|
||||||
@@ -70,7 +95,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') {
|
||||||
@@ -110,13 +135,11 @@ export function TuningPage({ copy, section, onError }: Props) {
|
|||||||
setMessage('invalid');
|
setMessage('invalid');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setSaving(true);
|
|
||||||
setMessage(null);
|
setMessage(null);
|
||||||
ipcInvoke('tuning:update', { copyId: copy.id, patch: result.data }).then((next) => {
|
savePatch(result.data).then(() => {
|
||||||
setData(next);
|
|
||||||
setDraft({});
|
setDraft({});
|
||||||
setMessage('saved');
|
setMessage('saved');
|
||||||
}).catch(onError).finally(() => setSaving(false));
|
}).catch(() => undefined);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -0,0 +1,482 @@
|
|||||||
|
import type { GroundAiTuningValues, TuningValues } from '@shared/schemas/tuning.ts';
|
||||||
|
|
||||||
|
export type FlatBotFieldKey = 'tankBotRespawns' | 'airBotRespawns' | 'botPoolLimitPerType';
|
||||||
|
export type GroundAiSectionKey = Exclude<keyof GroundAiTuningValues, 'mode'>;
|
||||||
|
|
||||||
|
export type BotFieldSpec =
|
||||||
|
| {
|
||||||
|
readonly id: FlatBotFieldKey;
|
||||||
|
readonly kind: 'flatInt';
|
||||||
|
readonly min: number;
|
||||||
|
readonly max: number;
|
||||||
|
readonly unit?: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
readonly id: 'groundAi.mode';
|
||||||
|
readonly kind: 'groundAiMode';
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
readonly id: `groundAi.${GroundAiSectionKey}.${string}`;
|
||||||
|
readonly section: GroundAiSectionKey;
|
||||||
|
readonly field: string;
|
||||||
|
readonly kind: 'int' | 'number' | 'bool' | 'driveMode' | 'steerSign';
|
||||||
|
readonly min?: number;
|
||||||
|
readonly max?: number;
|
||||||
|
readonly unit?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface BotTuningGroup {
|
||||||
|
readonly id: string;
|
||||||
|
readonly defaultOpen: boolean;
|
||||||
|
readonly customOnly?: boolean;
|
||||||
|
readonly fields: readonly BotFieldSpec[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function num(
|
||||||
|
section: GroundAiSectionKey,
|
||||||
|
field: string,
|
||||||
|
min: number,
|
||||||
|
max: number,
|
||||||
|
unit?: string,
|
||||||
|
): BotFieldSpec {
|
||||||
|
return {
|
||||||
|
id: `groundAi.${section}.${field}`,
|
||||||
|
section,
|
||||||
|
field,
|
||||||
|
kind: 'number',
|
||||||
|
min,
|
||||||
|
max,
|
||||||
|
...(unit ? { unit } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function int(
|
||||||
|
section: GroundAiSectionKey,
|
||||||
|
field: string,
|
||||||
|
min: number,
|
||||||
|
max: number,
|
||||||
|
unit?: string,
|
||||||
|
): BotFieldSpec {
|
||||||
|
return {
|
||||||
|
id: `groundAi.${section}.${field}`,
|
||||||
|
section,
|
||||||
|
field,
|
||||||
|
kind: 'int',
|
||||||
|
min,
|
||||||
|
max,
|
||||||
|
...(unit ? { unit } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Surfaces of the baked navigation mesh, in the order of tuning/ground-ai.jsonc navCosts*. */
|
||||||
|
const NAV_COST_FIELDS = ['road', 'bridge', 'ground', 'rough', 'forest', 'crushable', 'shallowWater', 'chokepoint'] as const;
|
||||||
|
|
||||||
|
export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
|
||||||
|
{
|
||||||
|
id: 'general',
|
||||||
|
defaultOpen: true,
|
||||||
|
fields: [
|
||||||
|
{ id: 'groundAi.mode', kind: 'groundAiMode' },
|
||||||
|
{ id: 'tankBotRespawns', kind: 'flatInt', min: 1, max: 10 },
|
||||||
|
{ id: 'airBotRespawns', kind: 'flatInt', min: 1, max: 10 },
|
||||||
|
{ id: 'botPoolLimitPerType', kind: 'flatInt', min: 4, max: 200 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'lineupWeights',
|
||||||
|
defaultOpen: true,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('lineupWeights', 'mediumTank', 0.01, 10),
|
||||||
|
num('lineupWeights', 'heavyTank', 0.01, 10),
|
||||||
|
num('lineupWeights', 'tankDestroyer', 0.01, 10),
|
||||||
|
num('lineupWeights', 'lightTank', 0.01, 10),
|
||||||
|
num('lineupWeights', 'spaa', 0.01, 10),
|
||||||
|
num('lineupWeights', 'other', 0.01, 10),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'loadout',
|
||||||
|
defaultOpen: true,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
int('loadout', 'lowReadyRackThreshold', 1, 60),
|
||||||
|
int('loadout', 'topUpAmmoCount', 4, 80),
|
||||||
|
int('loadout', 'primaryAmmoPct', 50, 100, '%'),
|
||||||
|
int('loadout', 'secondaryMinRounds', 0, 20),
|
||||||
|
int('loadout', 'penetrationCompareDistM', 100, 2000, 'm'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'commander',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('commander', 'rebalanceSec', 1, 30, 's'),
|
||||||
|
num('commander', 'roleHoldSec', 0, 120, 's'),
|
||||||
|
int('commander', 'bttlAssaultPct', 0, 100, '%'),
|
||||||
|
int('commander', 'bttlFlankPct', 0, 100, '%'),
|
||||||
|
int('commander', 'bttlOverwatchPct', 0, 100, '%'),
|
||||||
|
int('commander', 'conqAssaultPct', 0, 100, '%'),
|
||||||
|
int('commander', 'conqFlankPct', 0, 100, '%'),
|
||||||
|
int('commander', 'conqHoldDefendPct', 0, 100, '%'),
|
||||||
|
int('commander', 'conqHoldOverwatchPct', 0, 100, '%'),
|
||||||
|
int('commander', 'domAssaultPct', 0, 100, '%'),
|
||||||
|
int('commander', 'domMaxDefendersPerCap', 0, 4),
|
||||||
|
num('commander', 'overwatchStandOffM', 25, 350, 'm'),
|
||||||
|
num('commander', 'flankStandOffM', 25, 300, 'm'),
|
||||||
|
num('commander', 'spaaFollowOffsetM', 40, 500, 'm'),
|
||||||
|
num('commander', 'flankMaxLengthRatio', 1.05, 3),
|
||||||
|
num('commander', 'flankMinSeparationM', 15, 200, 'm'),
|
||||||
|
num('commander', 'rallyProgressFrac', 0.1, 0.75),
|
||||||
|
num('commander', 'rallyWaitSec', 3, 60, 's'),
|
||||||
|
num('commander', 'rallyMinFrac', 0.25, 1),
|
||||||
|
num('commander', 'rallyRadiusM', 15, 140, 'm'),
|
||||||
|
num('commander', 'recallSafeHoldSec', 3, 60, 's'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'macro',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('macro', 'openingSplitSec', 0, 180, 's'),
|
||||||
|
int('macro', 'capMaxInsiders', 1, 8),
|
||||||
|
int('macro', 'recaptureMinBots', 1, 8),
|
||||||
|
int('macro', 'recaptureMaxBots', 1, 12),
|
||||||
|
num('macro', 'capStickyBonusM', 0, 800, 'm'),
|
||||||
|
num('macro', 'deathZoneRadiusM', 10, 250, 'm'),
|
||||||
|
num('macro', 'deathZoneTtlSec', 5, 300, 's'),
|
||||||
|
int('macro', 'deathZoneMinKills', 1, 16),
|
||||||
|
num('macro', 'spaaRearOffsetM', 40, 600, 'm'),
|
||||||
|
num('macro', 'spaaRelocateSec', 5, 180, 's'),
|
||||||
|
num('macro', 'enemySpawnAvoidM', 60, 600, 'm'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'stateMachine',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('stateMachine', 'shortHaltMaxSec', 0.5, 12, 's'),
|
||||||
|
num('stateMachine', 'shortHaltCooldownSec', 0.5, 20, 's'),
|
||||||
|
num('stateMachine', 'turnLaunchSpeedMps', 0.5, 6, 'm/s'),
|
||||||
|
num('stateMachine', 'coverMinDistM', 2, 30, 'm'),
|
||||||
|
num('stateMachine', 'coverMaxDistM', 6, 80, 'm'),
|
||||||
|
num('stateMachine', 'coverRetreatBudgetSec', 1.5, 20, 's'),
|
||||||
|
num('stateMachine', 'maxTotalHaltSec', 3, 40, 's'),
|
||||||
|
int('stateMachine', 'stalemateMissShots', 1, 8),
|
||||||
|
int('stateMachine', 'stalemateNoShotHalts', 1, 6),
|
||||||
|
num('stateMachine', 'repositionMinMoveM', 5, 80, 'm'),
|
||||||
|
num('stateMachine', 'repositionStepM', 15, 120, 'm'),
|
||||||
|
num('stateMachine', 'repairSafeEnemyDistM', 30, 400, 'm'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'perception',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('perception', 'foliageTransparency', 0.001, 1),
|
||||||
|
num('perception', 'nearSpotRangeM', 20, 250, 'm'),
|
||||||
|
num('perception', 'firingSpotRangeM', 150, 1500, 'm'),
|
||||||
|
num('perception', 'fastSpotSec', 0.05, 1.5, 's'),
|
||||||
|
num('perception', 'normalSpotSec', 0.1, 3, 's'),
|
||||||
|
num('perception', 'farSpotSec', 0.3, 6, 's'),
|
||||||
|
num('perception', 'decayPerSec', 0.2, 10),
|
||||||
|
num('perception', 'gunFovHalfDeg', 5, 90, '°'),
|
||||||
|
num('perception', 'nearAwareM', 30, 400, 'm'),
|
||||||
|
num('perception', 'nearArcDeg', 90, 360, '°'),
|
||||||
|
num('perception', 'midAwareM', 100, 1500, 'm'),
|
||||||
|
num('perception', 'nearSpotMul', 1, 5),
|
||||||
|
num('perception', 'midSpotMul', 1, 6),
|
||||||
|
num('perception', 'lookAroundSec', 2, 60, 's'),
|
||||||
|
num('perception', 'lookAroundHoldSec', 0.2, 5, 's'),
|
||||||
|
num('perception', 'discoverScore', 0.05, 0.95),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'tactics',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('tactics', 'visionRangeM', 200, 3500, 'm'),
|
||||||
|
num('tactics', 'engineAudioRangeM', 10, 250, 'm'),
|
||||||
|
num('tactics', 'shotAudioRangeM', 50, 1200, 'm'),
|
||||||
|
num('tactics', 'radioShareRangeM', 50, 1500, 'm'),
|
||||||
|
num('tactics', 'memoryTtlSec', 1, 45, 's'),
|
||||||
|
num('tactics', 'targetStickinessSec', 0.5, 20, 's'),
|
||||||
|
num('tactics', 'peekCooldownSec', 1, 30, 's'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'estimation',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('estimation', 'watchMinSec', 0.5, 10, 's'),
|
||||||
|
num('estimation', 'watchMaxSec', 1, 15, 's'),
|
||||||
|
num('estimation', 'velSampleMinSpanSec', 0.05, 2, 's'),
|
||||||
|
num('estimation', 'velStableSpanSec', 0.2, 6, 's'),
|
||||||
|
num('estimation', 'velJumpResetMps', 1, 20, 'm/s'),
|
||||||
|
num('estimation', 'baseAimSigmaM', 0, 2, 'm'),
|
||||||
|
num('estimation', 'leadErrorFrac', 0, 1),
|
||||||
|
num('estimation', 'maxBiasM', 0, 6, 'm'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'threat',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('threat', 'rangeScaleM', 50, 3000, 'm'),
|
||||||
|
num('threat', 'discoveredMul', 0, 1),
|
||||||
|
num('threat', 'aimConeDeg', 5, 90, '°'),
|
||||||
|
num('threat', 'notAimingMul', 0, 1),
|
||||||
|
num('threat', 'unseenMul', 0, 1),
|
||||||
|
num('threat', 'hitMemorySec', 0, 60, 's'),
|
||||||
|
num('threat', 'hitMul', 1, 5),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'turret',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('turret', 'minDwellSec', 0, 5, 's'),
|
||||||
|
num('turret', 'switchMargin', 0, 3),
|
||||||
|
num('turret', 'scanArcDeg', 0, 180, '°'),
|
||||||
|
num('turret', 'scanPeriodSec', 1, 30, 's'),
|
||||||
|
num('turret', 'fixedMountYawSpanDeg', 0, 180, '°'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'behavior',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('behavior', 'scoreIntervalSec', 0.1, 3, 's'),
|
||||||
|
num('behavior', 'advanceHoldSec', 0, 10, 's'),
|
||||||
|
num('behavior', 'engageHoldSec', 0, 10, 's'),
|
||||||
|
num('behavior', 'haltHoldSec', 0, 10, 's'),
|
||||||
|
num('behavior', 'coverHoldSec', 0, 10, 's'),
|
||||||
|
num('behavior', 'repositionHoldSec', 0, 10, 's'),
|
||||||
|
num('behavior', 'postHoldSec', 0, 10, 's'),
|
||||||
|
num('behavior', 'disperseHoldSec', 0, 10, 's'),
|
||||||
|
num('behavior', 'targetValueWeight', 0, 1),
|
||||||
|
num('behavior', 'nearThreatHaltBonus', 0, 1),
|
||||||
|
num('behavior', 'switchMargin', 0, 1),
|
||||||
|
num('behavior', 'advanceScore', 0, 1),
|
||||||
|
num('behavior', 'engageScore', 0, 1),
|
||||||
|
num('behavior', 'urgencyWeight', 0, 1),
|
||||||
|
num('behavior', 'haltScore', 0, 1),
|
||||||
|
num('behavior', 'crossfirePenalty', 0, 1),
|
||||||
|
num('behavior', 'coverScore', 0, 1),
|
||||||
|
num('behavior', 'coverDangerWeight', 0, 1),
|
||||||
|
num('behavior', 'coverOffensivePenalty', 0, 1),
|
||||||
|
num('behavior', 'coverRetrySec', 0.5, 30, 's'),
|
||||||
|
num('behavior', 'repositionScore', 0, 1),
|
||||||
|
num('behavior', 'holdScore', 0, 1),
|
||||||
|
num('behavior', 'disperseScore', 0, 1),
|
||||||
|
num('behavior', 'urgentSpeedKeep', 0, 1),
|
||||||
|
num('behavior', 'hullAngleDeg', 0, 45, '°'),
|
||||||
|
num('behavior', 'faceToleranceDeg', 3, 60, '°'),
|
||||||
|
num('behavior', 'faceMinDanger', 0, 2),
|
||||||
|
num('behavior', 'reverseTravelAngleDeg', 60, 180, '°'),
|
||||||
|
num('behavior', 'reverseMaxTurnDistM', 0, 200, 'm'),
|
||||||
|
num('behavior', 'reverseMinSpeedMps', 0.5, 10, 'm/s'),
|
||||||
|
num('behavior', 'reverseHoldSec', 0, 20, 's'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'fireControl',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('fireControl', 'maxEngageRangeM', 150, 3000, 'm'),
|
||||||
|
num('fireControl', 'closeRangeM', 30, 250, 'm'),
|
||||||
|
num('fireControl', 'midRangeM', 100, 600, 'm'),
|
||||||
|
num('fireControl', 'longRangeM', 300, 1500, 'm'),
|
||||||
|
num('fireControl', 'stopSpeedMaxMps', 0.1, 2, 'm/s'),
|
||||||
|
num('fireControl', 'longRangeWindowSec', 1, 15, 's'),
|
||||||
|
num('fireControl', 'baseAlignDeg', 0.1, 3, '°'),
|
||||||
|
num('fireControl', 'barrelSettleDegSec', 0.2, 12, '°/s'),
|
||||||
|
num('fireControl', 'closeSettleHoldSec', 0.02, 0.5, 's'),
|
||||||
|
num('fireControl', 'settleHoldSec', 0.05, 1.5, 's'),
|
||||||
|
num('fireControl', 'aimErrorDeg', 0.01, 2, '°'),
|
||||||
|
num('fireControl', 'moveErrDegPerMps', 0, 3, '°'),
|
||||||
|
num('fireControl', 'turnErrDegPerDegSec', 0, 0.5),
|
||||||
|
num('fireControl', 'stabErrFactor', 0.02, 1),
|
||||||
|
num('fireControl', 'targetHalfHeightM', 0.3, 2, 'm'),
|
||||||
|
num('fireControl', 'fireThreshold', 0.05, 0.95),
|
||||||
|
num('fireControl', 'minFireThreshold', 0.01, 0.9),
|
||||||
|
num('fireControl', 'aimingThresholdBonus', 0, 0.5),
|
||||||
|
num('fireControl', 'closeThresholdBonus', 0, 0.5),
|
||||||
|
num('fireControl', 'enemyReloadThresholdBonus', 0, 0.5),
|
||||||
|
num('fireControl', 'enemyReloadSec', 0, 15, 's'),
|
||||||
|
num('fireControl', 'fleetingThresholdBonus', 0, 0.5),
|
||||||
|
num('fireControl', 'fleetingLateralMps', 0.5, 15, 'm/s'),
|
||||||
|
num('fireControl', 'fleetingLookAheadSec', 0.1, 2, 's'),
|
||||||
|
num('fireControl', 'reloadThresholdPenalty', 0, 0.5),
|
||||||
|
num('fireControl', 'longReloadSec', 1, 60, 's'),
|
||||||
|
int('fireControl', 'lowAmmoRounds', 1, 60),
|
||||||
|
num('fireControl', 'lowAmmoThresholdPenalty', 0, 0.5),
|
||||||
|
num('fireControl', 'aimSkill', 0, 1),
|
||||||
|
num('fireControl', 'autocannonMinShotsPerSec', 0.5, 30),
|
||||||
|
num('fireControl', 'retreatThresholdPenalty', 0, 0.6),
|
||||||
|
num('fireControl', 'minShotIntervalSec', 0.1, 5, 's'),
|
||||||
|
num('fireControl', 'autocannonAimSlack', 1, 10),
|
||||||
|
num('fireControl', 'burstSec', 0.2, 6, 's'),
|
||||||
|
num('fireControl', 'burstPauseSec', 0, 5, 's'),
|
||||||
|
num('fireControl', 'autocannonReloadDetectSec', 0.1, 3, 's'),
|
||||||
|
{ id: 'groundAi.fireControl.auxWeapons', section: 'fireControl', field: 'auxWeapons', kind: 'bool' },
|
||||||
|
num('fireControl', 'auxMaxRangeM', 30, 1500, 'm'),
|
||||||
|
{ id: 'groundAi.fireControl.auxFireAtArmor', section: 'fireControl', field: 'auxFireAtArmor', kind: 'bool' },
|
||||||
|
num('fireControl', 'friendlyCorridorM', 1, 10, 'm'),
|
||||||
|
num('fireControl', 'ballisticStepMaxM', 5, 80, 'm'),
|
||||||
|
num('fireControl', 'ballisticSweepRadiusM', 0.02, 0.5, 'm'),
|
||||||
|
int('fireControl', 'maxPreFireChecksPerTick', 1, 16),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'navigation',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
{ id: 'groundAi.navigation.driveMode', section: 'navigation', field: 'driveMode', kind: 'driveMode' },
|
||||||
|
int('navigation', 'maxPhysBots', 0, 64),
|
||||||
|
{ id: 'groundAi.navigation.steerSign', section: 'navigation', field: 'steerSign', kind: 'steerSign' },
|
||||||
|
num('navigation', 'deadEchoSec', 0.3, 10, 's'),
|
||||||
|
num('navigation', 'controlTimeoutSec', 0.3, 10, 's'),
|
||||||
|
num('navigation', 'movingFireSpeedRampMps', 0.2, 5, 'm/s'),
|
||||||
|
num('navigation', 'pivotAngleDeg', 25, 150, '°'),
|
||||||
|
num('navigation', 'tacticalReverseDistM', 10, 90, 'm'),
|
||||||
|
num('navigation', 'tacticalReverseMaxSec', 2, 25, 's'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'navEngine',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
{ id: 'groundAi.navEngine.enabled', section: 'navEngine', field: 'enabled', kind: 'bool' },
|
||||||
|
{ id: 'groundAi.navEngine.allowFallback', section: 'navEngine', field: 'allowFallback', kind: 'bool' },
|
||||||
|
num('navEngine', 'snapRadiusM', 2, 40, 'm'),
|
||||||
|
num('navEngine', 'goalSnapRadiusM', 5, 150, 'm'),
|
||||||
|
num('navEngine', 'pathBudgetMsPerFrame', 0.05, 5, 'ms'),
|
||||||
|
num('navEngine', 'trafficCostPerPath', 0, 3),
|
||||||
|
num('navEngine', 'trafficCostMaxMul', 1, 10),
|
||||||
|
num('navEngine', 'trafficHoldSec', 0, 120, 's'),
|
||||||
|
num('navEngine', 'cornerOffsetM', 0, 5, 'm'),
|
||||||
|
...NAV_COST_FIELDS.map((field) => num('navCostsTracked', field, 0.1, 20)),
|
||||||
|
...NAV_COST_FIELDS.map((field) => num('navCostsWheeled', field, 0.1, 20)),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'pathFollow',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('pathFollow', 'replanIntervalSec', 1, 15, 's'),
|
||||||
|
num('pathFollow', 'replanGoalMoveM', 3, 80, 'm'),
|
||||||
|
num('pathFollow', 'offCorridorReplanM', 3, 60, 'm'),
|
||||||
|
num('pathFollow', 'lookaheadTimeSec', 0.3, 5, 's'),
|
||||||
|
num('pathFollow', 'trackedLookaheadMinM', 2, 40, 'm'),
|
||||||
|
num('pathFollow', 'trackedLookaheadMaxM', 4, 60, 'm'),
|
||||||
|
num('pathFollow', 'wheeledLookaheadMinM', 2, 40, 'm'),
|
||||||
|
num('pathFollow', 'wheeledLookaheadMaxM', 4, 60, 'm'),
|
||||||
|
num('pathFollow', 'cornerAngleDeg', 10, 120, '°'),
|
||||||
|
num('pathFollow', 'cornerLateralAccelMps2', 0.5, 10, 'm/s²'),
|
||||||
|
num('pathFollow', 'cornerBrakeDecelMps2', 0.5, 10, 'm/s²'),
|
||||||
|
num('pathFollow', 'arriveRadiusM', 1, 20, 'm'),
|
||||||
|
num('pathFollow', 'arriveMinSpeedMps', 0.3, 6, 'm/s'),
|
||||||
|
num('pathFollow', 'narrowWallMarginM', 0.2, 6, 'm'),
|
||||||
|
num('pathFollow', 'narrowSpeedMps', 1, 15, 'm/s'),
|
||||||
|
num('pathFollow', 'bumperRayM', 2, 20, 'm'),
|
||||||
|
num('pathFollow', 'bumperStopM', 0.3, 6, 'm'),
|
||||||
|
num('pathFollow', 'bumperBlockSec', 0.2, 5, 's'),
|
||||||
|
num('pathFollow', 'trafficTtcSec', 0.5, 8, 's'),
|
||||||
|
num('pathFollow', 'yieldWaitMaxSec', 0.5, 15, 's'),
|
||||||
|
num('pathFollow', 'stationarySpeedMps', 0.2, 4, 'm/s'),
|
||||||
|
num('pathFollow', 'passMarginM', 0.2, 4, 'm'),
|
||||||
|
num('pathFollow', 'passSpeedMps', 1, 12, 'm/s'),
|
||||||
|
num('pathFollow', 'blockWaitSec', 0.5, 15, 's'),
|
||||||
|
num('pathFollow', 'blockTtlSec', 3, 120, 's'),
|
||||||
|
num('pathFollow', 'contactGapM', 0.2, 3, 'm'),
|
||||||
|
num('pathFollow', 'contactReverseSec', 0.3, 5, 's'),
|
||||||
|
num('pathFollow', 'contactRepeatSec', 3, 120, 's'),
|
||||||
|
num('pathFollow', 'stuckWindowSec', 1, 15, 's'),
|
||||||
|
num('pathFollow', 'stuckMinProgressM', 0.2, 10, 'm'),
|
||||||
|
num('pathFollow', 'unstickReverseM', 2, 25, 'm'),
|
||||||
|
num('pathFollow', 'unstickReverseSec', 0.8, 10, 's'),
|
||||||
|
num('pathFollow', 'unstickRepeatSec', 2, 60, 's'),
|
||||||
|
int('pathFollow', 'unstickMaxAttempts', 1, 10),
|
||||||
|
num('pathFollow', 'jamRadiusM', 2, 50, 'm'),
|
||||||
|
num('pathFollow', 'jamCostMul', 1, 50),
|
||||||
|
num('pathFollow', 'jamTtlSec', 5, 600, 's'),
|
||||||
|
num('pathFollow', 'giveUpRadiusM', 3, 50, 'm'),
|
||||||
|
num('pathFollow', 'giveUpCostMul', 1, 200),
|
||||||
|
num('pathFollow', 'rubbleRadiusM', 1, 40, 'm'),
|
||||||
|
num('pathFollow', 'rubbleCostMul', 1, 50),
|
||||||
|
num('pathFollow', 'rubbleTtlSec', 5, 600, 's'),
|
||||||
|
num('pathFollow', 'wreckRadiusM', 1, 40, 'm'),
|
||||||
|
num('pathFollow', 'wreckCostMul', 1, 50),
|
||||||
|
num('pathFollow', 'wreckTtlSec', 5, 600, 's'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'crowd',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('crowd', 'personalSpaceM', 6, 40, 'm'),
|
||||||
|
num('crowd', 'clusterRadiusM', 12, 80, 'm'),
|
||||||
|
int('crowd', 'clusterMaxAllies', 1, 10),
|
||||||
|
num('crowd', 'disperseStepM', 8, 65, 'm'),
|
||||||
|
num('crowd', 'disperseHoldSec', 1, 15, 's'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'terrain',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('terrain', 'maxClimbSlopeDeg', 10, 42, '°'),
|
||||||
|
num('terrain', 'maxDropSlopeDeg', 8, 40, '°'),
|
||||||
|
num('terrain', 'maxWaterDepthM', 0.2, 2.5, 'm'),
|
||||||
|
num('terrain', 'collisionMarginM', 0.05, 2, 'm'),
|
||||||
|
num('terrain', 'crestLookaheadM', 8, 80, 'm'),
|
||||||
|
num('terrain', 'ridgeMaxDwellSec', 2, 60, 's'),
|
||||||
|
int('terrain', 'ridgeMaxShots', 1, 10),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'runtime',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
int('cadence', 'maxBots', 1, 64),
|
||||||
|
num('cadence', 'macroTickSec', 0.1, 5, 's'),
|
||||||
|
num('cadence', 'tacticsTickSec', 0.05, 2, 's'),
|
||||||
|
num('cadence', 'navTickSec', 0.05, 2, 's'),
|
||||||
|
{ id: 'groundAi.diagnostics.telemetry', section: 'diagnostics', field: 'telemetry', kind: 'bool' },
|
||||||
|
num('diagnostics', 'telemetryIntervalSec', 0.5, 60, 's'),
|
||||||
|
{ id: 'groundAi.diagnostics.battleStats', section: 'diagnostics', field: 'battleStats', kind: 'bool' },
|
||||||
|
num('diagnostics', 'statsLogIntervalSec', 10, 600, 's'),
|
||||||
|
num('diagnostics', 'statsSampleSec', 0.2, 5, 's'),
|
||||||
|
num('diagnostics', 'statsSampleRangeM', 50, 1000, 'm'),
|
||||||
|
num('diagnostics', 'statsRearArcDeg', 30, 180, '°'),
|
||||||
|
{ id: 'groundAi.diagnostics.trace', section: 'diagnostics', field: 'trace', kind: 'bool' },
|
||||||
|
num('diagnostics', 'traceIntervalSec', 0.1, 5, 's'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export const ALL_BOT_FIELDS: readonly BotFieldSpec[] = BOT_TUNING_GROUPS.flatMap((group) => group.fields);
|
||||||
|
|
||||||
|
export function readBotFieldValue(values: TuningValues, spec: BotFieldSpec): string | number | boolean {
|
||||||
|
if (spec.kind === 'flatInt') return values[spec.id];
|
||||||
|
if (spec.kind === 'groundAiMode') return values.groundAi.mode;
|
||||||
|
const section = values.groundAi[spec.section] as Record<string, string | number | boolean>;
|
||||||
|
return section[spec.field]!;
|
||||||
|
}
|
||||||
@@ -1,17 +1,19 @@
|
|||||||
/**
|
/**
|
||||||
* 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', 'crews', 'official', 'backup'] as const;
|
||||||
export type SaveSection = (typeof SAVE_SECTIONS)[number];
|
export type SaveSection = (typeof SAVE_SECTIONS)[number];
|
||||||
|
|
||||||
export const TUNING_SECTIONS = ['rewards', 'battle', 'newProfile', 'research'] as const;
|
export const TUNING_SECTIONS = ['rewards', 'battle', 'bots', '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':
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import type { AppUpdateProgress } from '@shared/schemas/app-update.ts';
|
||||||
|
import type { ActiveMapNav, MapNavCheck } from '@shared/schemas/map-nav-pack.ts';
|
||||||
|
import { ipcInvoke, ipcOn } from '../ipc.ts';
|
||||||
|
import type { PackFailure } from './usePatchPack.ts';
|
||||||
|
|
||||||
|
export function useMapNavPack(checkOnStart: boolean, onError: (error: unknown) => void) {
|
||||||
|
const [active, setActive] = useState<ActiveMapNav>();
|
||||||
|
const [check, setCheck] = useState<MapNavCheck | null>(null);
|
||||||
|
const [busy, setBusy] = useState<'checking' | 'applying' | 'deactivating' | null>(null);
|
||||||
|
const [progress, setProgress] = useState<AppUpdateProgress | null>(null);
|
||||||
|
const [failure, setFailure] = useState<PackFailure | null>(null);
|
||||||
|
const startChecked = useRef(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const refresh = (): void => { ipcInvoke('map-nav:active').then(setActive).catch(onError); };
|
||||||
|
refresh();
|
||||||
|
window.addEventListener('focus', refresh);
|
||||||
|
const disposeCopies = ipcOn('event:copies-changed', refresh);
|
||||||
|
const disposeProgress = ipcOn('event:map-nav-progress', setProgress);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('focus', refresh);
|
||||||
|
disposeCopies();
|
||||||
|
disposeProgress();
|
||||||
|
};
|
||||||
|
}, [onError]);
|
||||||
|
|
||||||
|
const checkNow = useCallback((): void => {
|
||||||
|
setBusy('checking');
|
||||||
|
setFailure(null);
|
||||||
|
ipcInvoke('map-nav:check')
|
||||||
|
.then((result) => {
|
||||||
|
setCheck(result);
|
||||||
|
setActive(result.active);
|
||||||
|
})
|
||||||
|
.catch(onError)
|
||||||
|
.finally(() => setBusy(null));
|
||||||
|
}, [onError]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!checkOnStart || startChecked.current) return;
|
||||||
|
startChecked.current = true;
|
||||||
|
checkNow();
|
||||||
|
}, [checkOnStart, checkNow]);
|
||||||
|
|
||||||
|
function apply(version: string): void {
|
||||||
|
setBusy('applying');
|
||||||
|
setProgress(null);
|
||||||
|
setFailure(null);
|
||||||
|
ipcInvoke('map-nav:apply', { version })
|
||||||
|
.then((result) => {
|
||||||
|
if (!result.ok) {
|
||||||
|
setFailure(result.problem);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setActive(result.active);
|
||||||
|
setCheck((previous) => previous ? { ...previous, status: 'up_to_date', active: result.active } : null);
|
||||||
|
})
|
||||||
|
.catch(onError)
|
||||||
|
.finally(() => setBusy(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
function deactivate(): void {
|
||||||
|
setBusy('deactivating');
|
||||||
|
setFailure(null);
|
||||||
|
ipcInvoke('map-nav:deactivate')
|
||||||
|
.then((result) => {
|
||||||
|
setActive(result);
|
||||||
|
setCheck(null);
|
||||||
|
})
|
||||||
|
.catch(onError)
|
||||||
|
.finally(() => setBusy(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
return { active, check, busy, progress, failure, checkNow, apply, deactivate };
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MapNavPackState = ReturnType<typeof useMapNavPack>;
|
||||||
@@ -252,6 +252,11 @@
|
|||||||
background: var(--red);
|
background: var(--red);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.button-compact {
|
||||||
|
font-size: 13px;
|
||||||
|
padding: 5px 12px;
|
||||||
|
}
|
||||||
|
|
||||||
.link {
|
.link {
|
||||||
font: inherit;
|
font: inherit;
|
||||||
color: var(--white);
|
color: var(--white);
|
||||||
@@ -481,3 +486,245 @@
|
|||||||
left: 100%;
|
left: 100%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ===== Modal dialog & Markdown content ===== */
|
||||||
|
.modal-backdrop {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 40;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 28px;
|
||||||
|
background: rgba(7, 10, 12, 0.72);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-dialog {
|
||||||
|
width: min(760px, 100%);
|
||||||
|
max-height: min(600px, 100%);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--sheet);
|
||||||
|
border: 1px solid var(--line-strong);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.65);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 12px 14px 12px 20px;
|
||||||
|
background: linear-gradient(180deg, #343a40, #2b3136);
|
||||||
|
border-bottom: 1px solid #000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-title {
|
||||||
|
margin: 0;
|
||||||
|
font: 500 18px var(--font-display);
|
||||||
|
color: var(--white);
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-close {
|
||||||
|
flex: none;
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
padding: 0;
|
||||||
|
border: 0;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: none;
|
||||||
|
color: var(--text-dim);
|
||||||
|
font-size: 20px;
|
||||||
|
line-height: 1;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-close:hover {
|
||||||
|
color: var(--white);
|
||||||
|
background: rgba(255, 255, 255, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-body {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
overflow: auto;
|
||||||
|
padding: 18px 22px 22px;
|
||||||
|
user-select: text;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-foot {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 20px;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
background: rgba(0, 0, 0, 0.17);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body {
|
||||||
|
font-size: 13.5px;
|
||||||
|
line-height: 1.65;
|
||||||
|
color: var(--text);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body > :first-child {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body > :last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body h1,
|
||||||
|
.markdown-body h2,
|
||||||
|
.markdown-body h3,
|
||||||
|
.markdown-body h4,
|
||||||
|
.markdown-body h5,
|
||||||
|
.markdown-body h6 {
|
||||||
|
margin: 18px 0 8px;
|
||||||
|
font-family: var(--font-display);
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--white);
|
||||||
|
line-height: 1.3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body h1 {
|
||||||
|
font-size: 20px;
|
||||||
|
padding-bottom: 6px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body h2 {
|
||||||
|
font-size: 17px;
|
||||||
|
padding-bottom: 5px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body h3 {
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body h4,
|
||||||
|
.markdown-body h5,
|
||||||
|
.markdown-body h6 {
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body p {
|
||||||
|
margin: 0 0 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body strong {
|
||||||
|
color: var(--white);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body ul,
|
||||||
|
.markdown-body ol {
|
||||||
|
margin: 6px 0 10px;
|
||||||
|
padding-left: 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body li {
|
||||||
|
margin: 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body li > ul,
|
||||||
|
.markdown-body li > ol {
|
||||||
|
margin: 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body li > p {
|
||||||
|
margin: 0 0 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body li > p:last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body code {
|
||||||
|
padding: 1px 5px;
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: #e6eff2;
|
||||||
|
background: rgba(0, 0, 0, 0.34);
|
||||||
|
border: 1px solid var(--line-soft);
|
||||||
|
border-radius: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body pre {
|
||||||
|
margin: 10px 0;
|
||||||
|
padding: 10px 12px;
|
||||||
|
overflow: auto;
|
||||||
|
background: rgba(0, 0, 0, 0.38);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body pre code {
|
||||||
|
padding: 0;
|
||||||
|
background: none;
|
||||||
|
border: 0;
|
||||||
|
font-size: 12.5px;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body blockquote {
|
||||||
|
margin: 10px 0;
|
||||||
|
padding: 6px 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
background: rgba(255, 255, 255, 0.03);
|
||||||
|
border-left: 3px solid var(--line-strong);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body hr {
|
||||||
|
margin: 16px 0;
|
||||||
|
border: 0;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body a {
|
||||||
|
color: #7feaf2;
|
||||||
|
text-decoration: none;
|
||||||
|
border-bottom: 1px solid rgba(127, 234, 242, 0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body a:hover {
|
||||||
|
color: var(--white);
|
||||||
|
border-bottom-color: var(--white);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-table-wrap {
|
||||||
|
margin: 10px 0;
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: 12.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body th,
|
||||||
|
.markdown-body td {
|
||||||
|
padding: 6px 10px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body th {
|
||||||
|
color: var(--white);
|
||||||
|
background: rgba(255, 255, 255, 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-task {
|
||||||
|
margin-right: 6px;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
Loaded 100 of 498 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user