39 Commits
Author SHA1 Message Date
N0VAN0M4LY f6b00bc787 fix(modifications): emit RESEARCHED status and align buy-all pricing
Add ModuleStatus.RESEARCHED (0x40, ES_ITEM_STATUS_RESEARCHED) for modifications that have reached their RP requirement while a reqModification prerequisite is not yet owned, and keep unresearched modifications locked until their prerequisites are researched.

Update buyAllModifications / buyAllEntry to accept both CAN_BUY and RESEARCHED so the server matches client getAllModsCost (canBuyMod || isModStatusResearched) instead of rejecting cln_buy_all_modification with PRICE_CHANGED (shown as Internal character server error).

Verified: root and launcher typecheck, and runtime check against 2.61.0.58 wpcost.blk chained modifications. Pending in-game acceptance.
2026-12-03 06:38:15 +08:00
N0VAN0M4LY 638bc75724 fix(native): filter air enemy damage MPI feed and keep repeat air hits
Hook AcesApp's local MPI proxy dispatch to drop enemy-part-damage messages (0xf104 / 0xf118, captured dynamically) whose recipient_pid does not belong to the local player or watched hero, preventing AI-vs-AI aircraft damage from leaking into the local kill feed.

Remove the mistaken !is_kill gate in hook_dispatch_hit_crit: the 5th argument from Unit::flushOffenderHitAward is a repeat-flush flag rather than a kill flag, which dropped follow-up aircraft hits because fixed-wing units flush exclusively through the timer path. Add a same-team guard to match the severe-damage hook.

Verified: MSVC build.ps1 (0 warnings in project code), check-patches (14/14) and 12/12 native module resolution on 2.61.0.37 and 2.61.0.58. Pending in-game acceptance.
2026-12-03 06:37:58 +08:00
N0VAN0M4LY 02fe867cf1 refactor(launcher): open mod documentation on wto-project.net
Replace the local offline HTML mod docs viewer in the launcher Mods page with a direct link to https://wto-project.net/mod-docs, remove the unused mods:openDocs IPC path and resource entry, and drop build-mod-docs-html.ts from Windows packaging while keeping bundled mod templates intact. Root typecheck, launcher typecheck, and electron-vite build passed.
2026-12-03 06:26:52 +08:00
N0VAN0M4LY 742094ea1e chore(launcher): bump version to 0.1.3 and add release notes 2026-12-03 06:13:23 +08:00
N0VAN0M4LY c8ba395e4f docs(dev-docs): add common implementation pitfalls and PR self-check 2026-12-03 06:13:23 +08:00
N0VAN0M4LYandduduyagame 4e99d2c484 fix(training): persist tutorial completions and grant first-time rewards
On returning from a stock training mission, the client reports the outcome in
cln_update under missionAwards while sending an empty pveProgress block. Because
the local server did not record this completion, the hangar repeated tutorial
prompts after restart and never credited first-completion rewards.

Add a cached training-missions dataset (config/mislist.blk,
config/pve_awards.blk, config/unlocks.blk), pure completion rules in
TrainingCatalogue, and missionAwards parsing in clientUpdateAction. Completed
tutorials now persist pveProgress/missions and grant per-mission decals, the
shared first-basic-tutorial Golden Eagles unlock, and per-difficulty first-win
Silver Lions once per account during cln_update before replying.

Credit to duduyagame for identifying the cln_update missionAwards reporting flow
and stock reward definitions (PR #6).

Checks: root `npm run typecheck` passed; verified training-missions dataset
extraction/caching and TrainingCatalogue idempotency against read-only stock
2.61.0.37 files in a temporary data folder. In-game acceptance pending on an
isolated client copy.

Co-authored-by: duduyagame <[email protected]>
2026-12-03 05:23:18 +08:00
N0VAN0M4LYandduduyagame 42b8275151 fix(battle): write root numBotRespawns and numTankBotRespawns for all modes
MissionSettings::load (2.61.0.37 0x126b1f4..0x126b2e6) initializes AI respawn
limits from global config/bots.blk defaults (numBotRespawnsInMultiSlot=1,
numTankBotRespawnsInMultiSlot=3) and then overrides them from the mission root
fields numBotRespawns and numTankBotRespawns rather than customRules/customBots.

Previously only single-slot modes wrote numBotRespawns at the mission root, so
Air Arcade and other multi-slot modes stayed at 1 aircraft respawn and all modes
ignored tuning.battle.tankBotRespawns. Write both root fields unconditionally
using the per-mode values already resolved by BattleMatchmaker.

Credit to duduyagame for identifying the missing root numBotRespawns in Air
Arcade (PR #7).

Checks: root `npm run typecheck` passed. In-game acceptance pending on an
isolated client copy.

Co-authored-by: duduyagame <[email protected]>
2026-12-03 05:22:40 +08:00
N0VAN0M4LY 594ff5ab54 feat(launcher): add project homepage link to About page
Add a Project homepage card and button pointing to https://wto-project.net on the launcher About page with matching zh-CN and en locale entries. Root typecheck, launcher typecheck, electron-vite build, and locale key parity checks passed.
2026-12-03 04:34:22 +08:00
N0VAN0M4LY 41088d5377 docs(mods): use neutral, self-contained phrasing in mod developer documentation 2026-12-03 03:45:13 +08:00
N0VAN0M4LY d94c8fe687 feat(mods): merge additive mod system, official map selector, and mod-dev-docs
# Conflicts:
#	apps/launcher/src/main/workers/build-worker.ts
#	apps/launcher/src/renderer/src/i18n/locales/en.json
#	apps/launcher/src/renderer/src/i18n/locales/zh-CN.json
2026-12-03 03:43:56 +08:00
N0VAN0M4LY de967dd993 feat(repo): add R2 release staging, download page, and S3 publish script
Add scripts/publish-r2-releases.ts with a zero-dependency SigV4 R2 client and bilingual static index.html generator. Staged launcher releases and adaptation packs are verified against the committed Ed25519 public key and SHA-256 digests before publishing, assets are uploaded ahead of the releases feed with SHA-256 skip checks, and .env*.local is gitignored for local R2 credentials. Verified with root typecheck, local staging, and live R2 upload.
2026-12-03 03:03:14 +08:00
N0VAN0M4LY dc5e637e20 fix(mods): track additive pack overlay folders inside mod templates 2026-12-03 03:02:19 +08:00
N0VAN0M4LY 240ee81712 feat(launcher): use dl.wto-project.net as primary release source with GitHub fallback
Replace the single GitHub repository field in release-channels.jsonc with primary_source (https://dl.wto-project.net) and ordered fallback_sources (GitHub), and update withReleaseSources to walk the deduplicated primary, player mirror, and fallback list while keeping preferred-source downloads and Ed25519 signature verification intact. Verified with root and launcher typecheck and launcher production build.
2026-12-03 03:02:14 +08:00
N0VAN0M4LY 6e65cec4c0 feat(mods): add official map selector mod template and move templates into mod-dev-docs 2026-12-03 03:01:18 +08:00
N0VAN0M4LY aa952e7cca docs(mods): add standalone mod-dev-docs handbook and launcher quick-open button 2026-12-03 02:51:54 +08:00
N0VAN0M4LY 5983e3f3e2 feat(mods): add battle.onFilterMissions hook and per-template bundled seeding 2026-12-03 02:40:38 +08:00
N0VAN0M4LY 662e837ab2 fix(patcher): support regional.vromfs.bin decal and skin indexes on cache import
Modern online War Thunder clients (verified on 2.61.0.58) ship their decal and
skin indexes (dldata/downloadable_decals.blk and dldata/downloadable_skins.blk)
inside cache/binary.<ver>/regional.vromfs.bin rather than downloading
downloadable_decals.<hash>.blk into cache/content/. Requiring
downloadable_decals.<hash>.blk rejected every live 2.61 cache/content folder.

- Accept modern online caches containing cached .ddsx textures alongside a
  sibling binary.<ver>/regional.vromfs.bin (as well as selecting the parent
  cache folder or legacy downloadable_decals.<hash>.blk caches).
- Extract both dldata/downloadable_decals.blk and dldata/downloadable_skins.blk
  into a self-contained .wto-index snapshot on launcher import (excluded from
  the copied game cache/content folder) and embed them into char.vromfs.bin
  during copy build so webdlcontent::init mounts cache/content and resolves
  cached real decals and downloadable skins natively without client patches.
- Log the specific rejection reason in launcher decal import and clarify the
  en/zh-CN prompts.

Verified with root and launcher npm run typecheck, launcher electron-vite
build, and an end-to-end temporary import + char.vromfs.bin build against a
read-only 2.61.0.58 online cache (4,080 decals / 1,930 skins embedded).
In-game acceptance pending on an isolated 2.61.0.58 client copy.
2026-12-03 01:58:28 +08:00
N0VAN0M4LY 8636d0b71d fix(mods): serialize initial example seeding and refresh on window focus 2026-12-03 01:55:20 +08:00
N0VAN0M4LY 97707f533d feat(launcher): bundle example mod templates and seed fresh mods folder once 2026-12-03 01:51:43 +08:00
N0VAN0M4LY ada635ecc7 refactor(launcher): move experimental mod notice to hover tooltip chip 2026-12-03 01:48:47 +08:00
N0VAN0M4LY deffcd6dde feat(saves): merge bulk research and purchase into one launcher action
In the launcher's Saves -> Vehicles & Research page, "Research all" only
filled vehicle RP without purchasing them, requiring players to buy each
vehicle manually in-game while a separate "Grant regular vehicles" button
already added them to the hangar.

Merge the two actions into a single "Research and buy all" (`purchase`) action
alongside "Unlock modifications" (`equipment`), and switch bulk modification
unlocking in save-research.ts to ProfileEquipmentIndex so large saves stay
O(N) and write cleanly across chunked modification blocks.

Verified with root and launcher npm run typecheck, launcher electron-vite
build, and en/zh-CN locale key parity (631 keys).
2026-12-03 01:19:20 +08:00
N0VAN0M4LY 4e72bf3746 fix(profile): split modifications across sibling blocks at 65,535 entries
Dagor's binary DataBlock stores child block counts in a uint16 (65,535 max),
and the full 2.61.0.58 vehicle catalogue contains 76,041 modifications. Writing
all owned modifications into a single `modifications` block caused encodeBlk to
throw BlkFormatError once a save crossed 65,535 entries, preventing saving and
login.

Match aces.exe's native multi-block layout (2.61.0.37 0x938fae..0x9397e6,
2.61.0.58 0x93ba70 / 0x93bb53), which splits modifications across up to 3
sibling top-level `modifications` blocks of at most 65,535 entries each:

- Add allModificationBlocks, appendModificationEntry, and
  normalizeModificationBlocks in profile-modifications.ts and span all chunks
  in modificationRecord, ownsModification, and writeModificationRecord.
- Index and append across sibling chunks in ProfileEquipmentIndex and
  grantSupportPlaneModifications.
- Filter all sibling chunks in prepareTransferredProfile and normalize before
  encoding in SaveStore.saveProfile.

Verified with root npm run typecheck and a 2.61.0.58 temporary save check
encoding, decoding, and filtering >65,535 modifications across sibling chunks.
In-game acceptance pending on an isolated 2.61.0.58 client copy.
2026-12-03 01:18:14 +08:00
N0VAN0M4LY 3aac60c8a3 docs(mods): add bilingual mod authoring guide and runnable example mod templates 2026-12-03 00:41:47 +08:00
N0VAN0M4LY dbc21182a2 feat(launcher): add Mods page, per-client presets, custom repo folder, and launch integration 2026-12-03 00:34:07 +08:00
N0VAN0M4LY 5c09c4e47a fix(battle): enable limited fuel in LocalMP versus battles
MissionSettings initializes isLimitedFuel to false by default (2.61.0.37
0x12620af), leaving LocalMP versus battles with infinite fuel, no fuel
burn weight reduction, and no HUD fuel timer. Set isLimitedFuel=true in
battleMissionSettings across all versus modes to match live behavior.

Verified with root npm run typecheck. In-game acceptance pending on an
isolated 2.61.0.58 client copy.
2026-12-03 00:31:35 +08:00
N0VAN0M4LY dce9b59765 fix(battle): match native modification inversion and bullet belt filtering on spawn
Align battle/pass-spawn-modifications-blk with the native UnitModifications
construction rules verified on 2.61.0.37 and 2.61.0.58:

- Filter effects.bulletMod belts against the spawn request's selected
  bullets0..N so unlocked belts (whose last wpcost.blk entry is usually
  *_stealth) do not overwrite single-belt aircraft guns with non-tracer
  stealth belts.
- Resolve invertEnableLogic (unit BLK overriding config/modifications.blk)
  so spaded vehicles move inverted performance modifications to disabledMods
  instead of applying stock penalties (and arcade double-inversion) in
  LocalMP battles.
- Include unequipped modifications in disabledMods only when they define
  disableModEffects (e.g. stock fire extinguisher / repair kit), keeping
  unequipped normal modifications out of disabledMods.

Verified with full Quirrel bytecode check-gui on 2.61.0.37 and 2.61.0.58
(49 GUI patches across 37 .nut files). In-game acceptance pending on an
isolated 2.61.0.58 client copy.
2026-12-03 00:29:51 +08:00
N0VAN0M4LYandAlem Bek e8122d7c6b fix(battle): restore LocalMP Ground Arcade air events
Copy allowedKillStreaks and set useKillStreaks for Ground Arcade in battle-mission-settings.ts, and add a dedicated dynamic native module (local_mp_air_events) that preserves MissionSettings.useKillStreaks across prepare_local_mission, credits local player AI kills toward native killstreak counters, delivers UnitRespawn (0xf030) to the LocalMP host via shared unit_on_event, and recovers invalid surface poses from gameplay.blk spawnPos parameters for the match rank.

Based on PR #3 by Rivfflot, who diagnosed the LocalMP Ground Arcade air-event gaps and verified the fix in-game; refactored here onto patches/native dynamic resolution for cross-version and MSVC build compatibility.

Checked: root and launcher typecheck, MSVC native/wto-net/build.ps1, native resolution across 2.61.0.37 and 2.61.0.58 (12/12 modules), 2.61.0.58 check-patches (14/14), and temporary 2.61.0.58 copy build all passed. Pending in-game acceptance on the refactored module.

Co-authored-by: Alem Bek <[email protected]>
2026-12-03 00:14:32 +08:00
N0VAN0M4LY aa7a6e7d02 feat(server): add experimental JS/TS mod runtime, hooks, tuning list ops, and isolated mod storage 2026-12-03 00:00:36 +08:00
N0VAN0M4LY fd9d25d346 feat(patcher): support additive mod pack overlays, addon mounts, and protected exe patches 2026-12-02 23:48:34 +08:00
N0VAN0M4LY 8fbaeb4228 feat(mods): add core mod manifest, resolver, BLK/CSV patchers, and server API types 2026-12-02 23:42:26 +08:00
N0VAN0M4LY 4999c7f5a3 fix(native): assign local player squad ID for yellow squad target mark
Pressing ID_SQUAD_TARGET_DESIGNATION ("Set target for squad") checks
MPlayer+0xab0 (squadId) and returns early when it is zero (2.61.0.58
0x1600a4f). The LocalMP host already retains the 0xf10f relay and
0xf142 HUD indicator path (0xcb045c -> 0xcb1646 -> 0xcafffb ->
0x19a65e0), which also requires a non-zero squadId from matchingInfo+0x0.

Set matchingInfo+0x0 (squadId) to 1 for the local player when zero in
hook_mplayer_init_from_matching so MPlayer::initFromMatching (0x59e660
on 2.61.0.37, 0x59f370 on 2.61.0.58) copies it into MPlayer+0xab0 and
restores the yellow squad target marker without extra hooks or exe patches.

Verified with native wto_ws.dll build; pending in-game verification.
2026-12-02 23:16:49 +08:00
N0VAN0M4LY d0e4797fe7 feat(battle): add Nuclear Escalation tactical and strategic nuclear carriers
Connect stage-unlocked nuclear carriers to Air Realistic sub-mode 103
(Nuclear Escalation) and expose a player toggle for stage-3 megaton
strategic bombers:

- Dataset & profile grants: extract tactical killstreak nuclear carriers
  (5 kt / 30 kt Nuclear Escalation presets) and megaton strategic bombers
  (nt_b_52h / nt_tu_95m) from wpcost.blk in battle-spawn-rules (v4), and
  grant their required weapon/modification records in
  support-plane-modifications.ts.
- Server slot selection & tuning: add nuclearEscalationStrategicBombers
  (default true) in tuning/battle.jsonc, battle-tuning.ts, and
  launcher-tuning.ts; add one nation-matched tactical carrier per session
  rank bracket (with allowedWeapons limited to its Nuclear Escalation
  presets) and, when enabled, one stage-3 strategic bomber to
  extraBattleSlots; include modeTag in battle launch notifications.
- GUI patch & launcher UI: add battle/filter-extra-slot-weapons on
  scripts/weaponry/weaponryinfo.nut to filter extra-slot presets by
  allowedWeapons (hiding Ground RB zero-yield presets at stage 0) and to
  fall back to LocalMP launch metadata for GameModeRestrictions; expose
  the strategic bomber toggle in the launcher Battle tuning section.

Verified with root and launcher typechecks, launcher build, full
check-gui on 2.61.0.37 and 2.61.0.58 (49 patches across 37 .nut files),
and slot selection check across all 10 nations on 2.61.0.58 stock data;
pending in-game verification.
2026-12-02 23:03:15 +08:00
N0VAN0M4LY f1ec034994 feat(battle): wire Nuclear Escalation launch and airfield cooldowns
Connect Air Realistic sub-mode 103 (Nuclear Escalation) mission launch
settings and LocalMP respawn/airfield-cooldown handling:

- Server: support mode-level maxRespawns (UNLIMITED_RESPAWNS = -2) and
  per-mode missionRuleKeys so Nuclear Escalation forwards customHUD,
  stage thresholds, useSpawnDelay, afterRespawnDelaySec, and battle
  display flags from the stock missions; reject queues when no candidate
  mode is eligible for the lineup; disable spares and emit
  wtoUnlimitedRespawns for unlimited-respawn modes.
- Native: keep slots usable when wtoUnlimitedRespawns is set and emit
  wtoLocalMpAirfieldSpawn with the unit name and spawn base ID when the
  local player actually enters pilot control.
- GUI patches: track confirmed LocalMP airfield departures in
  scripts/respawn/respawnbases.nut and feed the computed per-base delays
  into scripts/respawn/respawn.nut slot countdowns and spawn checks.

Stage-unlocked dedicated event aircraft allocation by faction and room
BR is not yet wired and remains pending research. Verified with root and
launcher typechecks, check-patches and check-gui on 2.61.0.37 and
2.61.0.58, and native wto_ws.dll build; pending in-game verification.
2026-12-02 21:35:17 +08:00
N0VAN0M4LY 646be7afb9 fix(battle): load player crew skills on LocalMP host
Unit::loadCrew previously skipped reading the player's equipped crew from
the profile whenever Multiplayer+0x60 (host flag) was non-zero, leaving
human players with default skills and no Expert/Ace bonuses. Calling
UnitCrewSkills::initFromSave after Unit::changeAircraft in the native
loadout hook ran too late to affect live vehicle crew state.

Add exe patch battle/load-local-host-player-crew to check both the host
and LocalMP flags (+0x60 and +0x61) in Unit::loadCrew so only non-LocalMP
hosts skip directly to the default crew while preserving the owner check.
Remove the late initFromSave workaround from local_mp_loadout.c (keeping
its native patch sites for compatibility with 0.1.2 hook DLLs) and add
the E-Crew skills in battle feature labels to the launcher locales.

Verified with check-patches on 2.61.0.37 (0x10025dd) and 2.61.0.58
(0x100700d), native wto_ws.dll build, launcher typecheck and build;
pending in-game verification.
2026-12-02 21:33:46 +08:00
N0VAN0M4LY 7bd17c4f74 fix(battle): enable in-flight reload in air arcade
Air arcade battles previously set isLimitedAmmo=true via VERSUS_SWITCHES.
Both the native in-flight rearm request and its host handler require
unlimited reserve ammunition, which prevented airborne reloading in Air AB.

Move isLimitedAmmo out of VERSUS_SWITCHES and set it to false only when
modeName is air_arcade, keeping limited ammunition for all other modes.

Verified with root npm run typecheck; pending in-game verification.
2026-12-02 21:32:42 +08:00
N0VAN0M4LY be772c0cea fix(launcher): keep copy maintenance progress across tab switches 2026-12-02 20:24:30 +08:00
N0VAN0M4LY fa7f68b942 feat(launcher): use two-column About layout and add Discord link 2026-12-02 20:06:51 +08:00
N0VAN0M4LY 899fb5d91b fix(server): persist selectable battle ratings
Validate the selected rank against owned modifications and return the saved profile.

Use the saved rank delta for mode eligibility and room matchmaking.

Verified with typecheck and a local 2.61.0.58 server run using temporary data. In-game acceptance is pending.
2026-12-02 19:55:41 +08:00
N0VAN0M4LY 3f0e08c5b7 docs(repo): add Discord community links to README 2026-12-02 19:19:41 +08:00
194 changed files with 14163 additions and 1919 deletions

No files matched your search

+97
View File
@@ -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.
+5 -1
View File
@@ -1,5 +1,8 @@
# Never commit game files (copyright, size). The build reads them from a game folder. # Never commit game files (copyright, size). The build reads them from a game folder.
*.vromfs.bin *.vromfs.bin
# Allow additive patch directories named after target packs inside mod templates (never binary archives).
!mod-dev-docs/templates/**/client/packs/*.vromfs.bin/
!mod-dev-docs/templates/**/client/packs/ui/*.vromfs.bin/
*.vromfs.bin.orig *.vromfs.bin.orig
aces.exe aces.exe
aces*.exe aces*.exe
@@ -25,10 +28,11 @@ __pycache__/
*.pyc *.pyc
.venv/ .venv/
# Saves, logs, local runtime data # Saves, logs, local runtime data, local secrets
/data/ /data/
/saves/ /saves/
*.log *.log
.env*.local
# Editors / OS # Editors / OS
.vscode/ .vscode/
+12 -4
View File
@@ -2,7 +2,7 @@
<a id="zh-cn"></a> <a id="zh-cn"></a>
简体中文 · [English](#english) 简体中文 · [English](#english) · [Discord](https://discord.gg/P566xWNpEs)
------ ------
@@ -21,6 +21,10 @@ WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线
`patches/versions/` 中每份核对记录对应一个检查通过并在游戏中验证过的客户端版本。补丁和 native 模块按特征码、字符串引用和从代码中读出的值定位,不依赖固定地址,小版本更新后通常仍能命中,但没有核对记录的版本不保证功能正确。 `patches/versions/` 中每份核对记录对应一个检查通过并在游戏中验证过的客户端版本。补丁和 native 模块按特征码、字符串引用和从代码中读出的值定位,不依赖固定地址,小版本更新后通常仍能命中,但没有核对记录的版本不保证功能正确。
## 开发讨论、交流与求助
欢迎加入 [WTOffline Discord 服务器](https://discord.gg/P566xWNpEs),用于日常交流、使用求助、问题反馈、调参分享以及开发和版本适配讨论。
## 功能 ## 功能
| 领域 | 已实现 | | 领域 | 已实现 |
@@ -151,7 +155,7 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
## 开发 ## 开发
开发规范、补丁指南和 PR 自查清单见 [Dev Docs](dev-docs/README.md#zh-cn)。 开发规范、补丁指南和 PR 自查清单见 [Dev Docs](dev-docs/README.md#zh-cn),开发与版本适配讨论欢迎前往 [Discord](https://discord.gg/P566xWNpEs)。
### 环境要求 ### 环境要求
@@ -265,7 +269,7 @@ tools/ wtotools,补丁检查工具(Python)
# WTOffline (English) # WTOffline (English)
[简体中文](#zh-cn) · English [简体中文](#zh-cn) · English · [Discord](https://discord.gg/P566xWNpEs)
WTOffline is a single-player offline project for the Windows client of War Thunder. A local server emulates Gaijin's online services, and the client sends all of its requests to the local machine. The client logs in, loads its profile, enters the hangar, and submits player actions as usual. Game rules, saves, and battle settlement run on the local server, and all allies and opponents are AI. WTOffline is a single-player offline project for the Windows client of War Thunder. A local server emulates Gaijin's online services, and the client sends all of its requests to the local machine. The client logs in, loads its profile, enters the hangar, and submits player actions as usual. Game rules, saves, and battle settlement run on the local server, and all allies and opponents are AI.
@@ -282,6 +286,10 @@ The repository contains source code and patch definitions only. It does not cont
Each check record in `patches/versions/` stands for a client version that passed the checks and was verified in game. Patches and native modules are located by signatures, string references and values read from the code rather than fixed addresses, so they usually still match after a minor update, but correct behavior is not guaranteed for a version without a check record. Each check record in `patches/versions/` stands for a client version that passed the checks and was verified in game. Patches and native modules are located by signatures, string references and values read from the code rather than fixed addresses, so they usually still match after a minor update, but correct behavior is not guaranteed for a version without a check record.
## Community
Join the [WTOffline Discord server](https://discord.gg/P566xWNpEs) for general discussion, troubleshooting, bug reports, and development or patch adaptation discussions.
## Features ## Features
| Area | Implemented | | Area | Implemented |
@@ -412,7 +420,7 @@ To override defaults, create `tuning/<same file name>.jsonc` in the data folder
## Development ## Development
See [Dev Docs](dev-docs/README.md#english) for development rules, patch templates, and the PR checklist. See [Dev Docs](dev-docs/README.md#english) for development rules, patch templates, and the PR checklist, or join [Discord](https://discord.gg/P566xWNpEs) for development and patch adaptation discussions.
### Requirements ### Requirements
+2 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "@wto/launcher", "name": "@wto/launcher",
"productName": "WTOffline Launcher", "productName": "WTOffline Launcher",
"version": "0.1.2", "version": "0.1.3",
"private": true, "private": true,
"description": "Installer and launcher of the War Thunder offline project.", "description": "Installer and launcher of the War Thunder offline project.",
"type": "module", "type": "module",
@@ -14,6 +14,7 @@
}, },
"dependencies": { "dependencies": {
"@fontsource/roboto-condensed": "^5.3.0", "@fontsource/roboto-condensed": "^5.3.0",
"@wto/mods": "*",
"@wto/patcher": "*", "@wto/patcher": "*",
"@wto/server": "*", "@wto/server": "*",
"fflate": "^0.8.2", "fflate": "^0.8.2",
+57 -1
View File
@@ -5,7 +5,7 @@ import { appUpdatesSupported, checkAppUpdate, downloadAppUpdate, installAppUpdat
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts'; import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.ts'; import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.ts';
import { getSettings, updateSettings } from '../services/config/settings-store.ts'; import { getSettings, updateSettings } from '../services/config/settings-store.ts';
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress } from '../services/copies/copy-maintenance.ts'; import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress, maintenanceState } from '../services/copies/copy-maintenance.ts';
import { relocateCopy } from '../services/copies/relocate-copy.ts'; import { relocateCopy } from '../services/copies/relocate-copy.ts';
import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts'; import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts';
import { measureFolder } from '../services/game-folder/folder-size.ts'; import { measureFolder } from '../services/game-folder/folder-size.ts';
@@ -17,6 +17,19 @@ import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesSta
import { readInstalledLab } from '../services/launch/lab-handoff.ts'; import { readInstalledLab } from '../services/launch/lab-handoff.ts';
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts'; import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts'; import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
import {
applyModPreset,
autoSortMods,
deleteModPreset,
exportModPreset,
getModsState,
importModPreset,
openModsFolder,
saveModPreset,
setModEnabled,
setModsFolder,
setModsOrder,
} from '../services/mods/mods-service.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts'; import { resourcePaths } from '../services/resources/resource-paths.ts';
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts'; import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
import { broadcast, handle } from './register.ts'; import { broadcast, handle } from './register.ts';
@@ -135,6 +148,7 @@ export function registerIpcHandlers(): void {
return updated; return updated;
}); });
handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id)); handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id));
handle('copies:maintenanceState', () => maintenanceState());
handle('copies:maintain', async (request) => { handle('copies:maintain', async (request) => {
if (saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy'); if (saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy');
const updated = await hydrateCopiesStatus(await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress))); const updated = await hydrateCopiesStatus(await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress)));
@@ -174,6 +188,48 @@ export function registerIpcHandlers(): void {
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId)); handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch)); handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
const requireModsWritable = (): void => {
if (launchInProgress() || maintenanceInProgress()) throw new AppError('mods_read_only');
};
handle('mods:getState', ({ copyId }) => getModsState(copyId));
handle('mods:setEnabled', ({ copyId, modId, enabled }) => {
requireModsWritable();
return setModEnabled(copyId, modId, enabled);
});
handle('mods:setOrder', ({ copyId, order }) => {
requireModsWritable();
return setModsOrder(copyId, order);
});
handle('mods:autoSort', ({ copyId }) => {
requireModsWritable();
return autoSortMods(copyId);
});
handle('mods:savePreset', ({ copyId, name, overwriteId }) => {
requireModsWritable();
return saveModPreset(copyId, name, overwriteId);
});
handle('mods:applyPreset', ({ copyId, presetId }) => {
requireModsWritable();
return applyModPreset(copyId, presetId);
});
handle('mods:deletePreset', ({ copyId, presetId }) => {
requireModsWritable();
return deleteModPreset(copyId, presetId);
});
handle('mods:exportPreset', ({ copyId, presetId }, sender) =>
exportModPreset(copyId, presetId, BrowserWindow.fromWebContents(sender)));
handle('mods:importPreset', ({ copyId }, sender) => {
requireModsWritable();
return importModPreset(copyId, BrowserWindow.fromWebContents(sender));
});
handle('mods:openFolder', () => openModsFolder());
handle('mods:setFolder', async ({ copyId, path }) => {
requireModsWritable();
const state = await setModsFolder(copyId, path);
broadcast('event:settings-changed', await getSettings());
return state;
});
handle('launch:getState', () => getLaunchState()); handle('launch:getState', () => getLaunchState());
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null)); handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
handle('launch:start', () => { handle('launch:start', () => {
@@ -15,12 +15,20 @@ import { localServerReady } from '../launch/local-server.ts';
import { fileInfo } from './change-copy-files.ts'; import { fileInfo } from './change-copy-files.ts';
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts'; import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
let current: { stop: AbortController; interruptible: boolean } | null = null; let current: {
stop: AbortController;
interruptible: boolean;
progress: MaintenanceProgress;
} | null = null;
export function maintenanceInProgress(): boolean { export function maintenanceInProgress(): boolean {
return current !== null; return current !== null;
} }
export function maintenanceState(): MaintenanceProgress | null {
return current ? { ...current.progress } : null;
}
export function cancelMaintenance(): void { export function cancelMaintenance(): void {
if (current?.interruptible) current.stop.abort(); if (current?.interruptible) current.stop.abort();
} }
@@ -43,18 +51,28 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
export async function maintainCopy( export async function maintainCopy(
request: MaintenanceRequest, request: MaintenanceRequest,
publish: (progress: MaintenanceProgress) => void, publish: (progress: MaintenanceProgress | null) => void,
): Promise<Copies> { ): Promise<Copies> {
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy'); if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
const initial: MaintenanceProgress = {
id: request.id,
operation: request.operation,
phase: 'checking',
doneBytes: 0,
totalBytes: 0,
};
const job = { const job = {
stop: new AbortController(), stop: new AbortController(),
interruptible: request.operation === 'update' || request.operation === 'compact', interruptible: request.operation === 'update' || request.operation === 'compact',
progress: initial,
}; };
current = job; current = job;
const signal = job.stop.signal; const signal = job.stop.signal;
const report: Report = (phase, doneBytes = 0, totalBytes = 0) => { const report: Report = (phase, doneBytes = 0, totalBytes = 0) => {
if (phase === 'applying') job.interruptible = false; if (phase === 'applying') job.interruptible = false;
publish({ id: request.id, operation: request.operation, phase, doneBytes, totalBytes }); const next: MaintenanceProgress = { id: request.id, operation: request.operation, phase, doneBytes, totalBytes };
job.progress = next;
publish(next);
}; };
try { try {
@@ -67,6 +85,7 @@ export async function maintainCopy(
throw new AppError('maintenance_failed'); throw new AppError('maintenance_failed');
} finally { } finally {
current = null; current = null;
publish(null);
} }
} }
@@ -1,7 +1,12 @@
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises'; import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative } from 'node:path'; import { dirname, isAbsolute, join, relative } from 'node:path';
import { isInSteamLibrary, playerDecalCacheProblem } from '@wto/patcher'; import {
isInSteamLibrary,
playerDecalCacheProblem,
resolvePlayerDecalCacheFolder,
writeDecalCacheIndexSnapshot,
} from '@wto/patcher';
import { AppError } from '@shared/errors.ts'; import { AppError } from '@shared/errors.ts';
import type { Copies } from '@shared/schemas/install.ts'; import type { Copies } from '@shared/schemas/install.ts';
import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts'; import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts';
@@ -33,8 +38,13 @@ export async function importDecalCache(
dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false, dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false,
): Promise<string> { ): Promise<string> {
if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid'); if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid');
const source = await realpath(sourcePath).catch(() => null); const rawSource = await realpath(sourcePath).catch(() => null);
if (!source || playerDecalCacheProblem(source)) throw new AppError('decal_source_invalid'); const source = rawSource ? await realpath(resolvePlayerDecalCacheFolder(rawSource)).catch(() => null) : null;
const problem = source ? playerDecalCacheProblem(source) : 'selected folder could not be resolved';
if (!source || problem) {
console.warn('[decals] invalid decal cache source:', sourcePath, '->', problem);
throw new AppError('decal_source_invalid');
}
const root = await cacheRoot(dataPath, steamDataConfirmed); const root = await cacheRoot(dataPath, steamDataConfirmed);
if (copyPathContains(source, root) || copyPathContains(root, source)) { if (copyPathContains(source, root) || copyPathContains(root, source)) {
@@ -56,7 +66,12 @@ export async function importDecalCache(
}, },
}); });
signal?.throwIfAborted(); signal?.throwIfAborted();
if (playerDecalCacheProblem(target)) throw new AppError('decal_source_invalid'); writeDecalCacheIndexSnapshot(source, target);
const copiedProblem = playerDecalCacheProblem(target);
if (copiedProblem) {
console.warn('[decals] copied decal cache failed validation:', copiedProblem);
throw new AppError('decal_source_invalid');
}
return id; return id;
} catch (error) { } catch (error) {
await discardDecalCache(dataPath, id, steamDataConfirmed); await discardDecalCache(dataPath, id, steamDataConfirmed);
@@ -11,6 +11,7 @@ import type { Settings } from '@shared/schemas/settings.ts';
import { getSettings } from '../config/settings-store.ts'; import { getSettings } from '../config/settings-store.ts';
import { decalCachePath } from '../install/decals.ts'; import { decalCachePath } from '../install/decals.ts';
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts'; import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts';
import { resourcePaths } from '../resources/resource-paths.ts'; import { resourcePaths } from '../resources/resource-paths.ts';
import { saveBackup } from '../saves/save-archive.ts'; import { saveBackup } from '../saves/save-archive.ts';
import { buildCopy } from './build-copy.ts'; import { buildCopy } from './build-copy.ts';
@@ -108,7 +109,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 +124,15 @@ async function launch(job: LaunchJob): Promise<void> {
update(job, { phase: 'ready' }); update(job, { phase: 'ready' });
return; return;
} }
const gameExit = await runOrdinaryLaunch(copyPath, dataPath, port, settings, signal, publish); const gameExit = await runOrdinaryLaunch(
copyPath,
dataPath,
port,
settings,
signal,
publish,
{ modsDir, enabledModIds },
);
update(job, { phase: 'game-exited', gameExit }); update(job, { phase: 'game-exited', gameExit });
} }
@@ -134,6 +143,8 @@ interface LaunchPlan {
readonly dataPath: string; readonly dataPath: string;
readonly steamLibraryConfirmed: boolean; readonly steamLibraryConfirmed: boolean;
readonly port: number; readonly port: number;
readonly modsDir: string;
readonly enabledModIds: readonly string[];
} }
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> { async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
@@ -183,13 +194,15 @@ 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 { 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();
@@ -211,6 +224,8 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
...(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,428 @@
import { randomUUID } from 'node:crypto';
import { access, cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
import { isAbsolute, join } from 'node:path';
import { app, BrowserWindow, dialog, shell } from 'electron';
import {
computeAutoSortOrder,
discoverMods,
emptyClientModsConfig,
MOD_API_VERSION,
normalizeClientModsConfig,
resolveModLoadOrder,
type ClientModsConfig,
type DiscoveredMod,
type ModPreset,
} from '@wto/mods';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
import { getSettings, updateSettings } from '../config/settings-store.ts';
import { listCopies } from '../install/install-record.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
const CLIENT_MODS_CONFIG_FILE = 'mods-config.json';
const EXAMPLES_SEEDED_MARKER = '.wto-examples-seeded';
const inFlightSeeds = new Map<string, Promise<void>>();
export function defaultModsFolder(): string {
return join(app.getPath('userData'), 'mods');
}
export async function resolveModsFolder(): Promise<{ readonly modsDir: string; readonly defaultModsDir: string; readonly isCustomModsDir: boolean }> {
const settings = await getSettings();
const defaultModsDir = defaultModsFolder();
const isCustomModsDir = settings.modsFolder !== null;
const modsDir = settings.modsFolder ?? defaultModsDir;
await mkdir(modsDir, { recursive: true });
await seedBundledExampleModsOnce(modsDir);
return { modsDir, defaultModsDir, isCustomModsDir };
}
/**
* Copy newly shipped bundled template mods into the mods folder once each (disabled by default).
* Tracks which template folder names have already been seeded in `.wto-examples-seeded` so
* deleting a bundled template never restores it, while newly added official templates still
* appear for existing users. Serialized per directory to prevent concurrent seeding races.
*/
async function seedBundledExampleModsOnce(modsDir: string): Promise<void> {
const key = modsDir.toLowerCase();
const pending = inFlightSeeds.get(key);
if (pending) {
await pending;
return;
}
const task = (async () => {
const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER);
try {
const templatesRoot = resourcePaths().modTemplates;
if (!(await pathExists(templatesRoot))) return;
const seeded = await readSeededTemplateNames(markerPath, modsDir);
const templates = await readdir(templatesRoot, { withFileTypes: true });
let changed = false;
for (const entry of templates) {
if (!entry.isDirectory()) continue;
if (seeded.has(entry.name)) continue;
const dest = join(modsDir, entry.name);
if (!(await pathExists(dest))) {
await cp(join(templatesRoot, entry.name), dest, { recursive: true });
}
seeded.add(entry.name);
changed = true;
}
if (changed || !(await pathExists(markerPath))) {
await writeFile(markerPath, JSON.stringify({ seeded: [...seeded].sort() }, null, 2) + '\n', 'utf8');
}
} catch (error) {
console.warn('[mods] seeding bundled example mods skipped:', error);
}
})().finally(() => {
inFlightSeeds.delete(key);
});
inFlightSeeds.set(key, task);
await task;
}
async function readSeededTemplateNames(markerPath: string, modsDir: string): Promise<Set<string>> {
if (!(await pathExists(markerPath))) return new Set();
try {
const raw = (await readFile(markerPath, 'utf8')).trim();
if (raw === '1') {
// Legacy marker from initial 2-template version: mark existing folders as already seeded
// so newly added official templates (e.g. official-map-selector) are still delivered once.
const existing = await readdir(modsDir);
const set = new Set(['example-vehicle-tweak', 'example-server-script']);
for (const name of existing) set.add(name);
return set;
}
const parsed = JSON.parse(raw) as { seeded?: unknown };
if (Array.isArray(parsed.seeded)) {
return new Set(parsed.seeded.filter((item): item is string => typeof item === 'string'));
}
} catch { /* ignore */ }
return new Set();
}
async function pathExists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch {
return false;
}
}
export async function openModsFolder(): Promise<void> {
const { modsDir } = await resolveModsFolder();
const failure = await shell.openPath(modsDir);
if (failure) console.warn('[mods] opening the mods folder failed:', modsDir, failure);
}
export async function getModsState(copyId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
return buildModsStateView(copy);
}
export async function setModEnabled(copyId: string, modId: string, enabled: boolean): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const next: ClientModsConfig = {
...current,
activePresetId: null,
enabled: { ...current.enabled, [modId]: enabled },
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function setModsOrder(copyId: string, order: readonly string[]): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const next = normalizeClientModsConfig({ ...current, activePresetId: null, order }, discovered.mods);
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function autoSortMods(copyId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const sortedOrder = computeAutoSortOrder(discovered.mods, current.order);
const next: ClientModsConfig = {
...current,
activePresetId: null,
order: sortedOrder,
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function saveModPreset(copyId: string, name: string, overwriteId?: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const now = new Date().toISOString();
let presets: ModPreset[];
let presetId: string;
if (overwriteId && current.presets.some((preset) => preset.id === overwriteId)) {
presetId = overwriteId;
presets = current.presets.map((preset) => (
preset.id === overwriteId
? { id: preset.id, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now }
: preset
));
} else {
presetId = randomUUID();
presets = [
...current.presets,
{ id: presetId, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now },
];
}
const next: ClientModsConfig = {
...current,
activePresetId: presetId,
presets,
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function applyModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const preset = current.presets.find((item) => item.id === presetId);
if (!preset) throw new AppError('mods_preset_invalid');
const next = normalizeClientModsConfig({
...current,
order: preset.order,
enabled: preset.enabled,
activePresetId: preset.id,
}, discovered.mods);
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function deleteModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const current = await readClientModsConfig(copy.dataPath);
const next: ClientModsConfig = {
...current,
activePresetId: current.activePresetId === presetId ? null : current.activePresetId,
presets: current.presets.filter((preset) => preset.id !== presetId),
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function exportModPreset(
copyId: string,
presetId: string,
window: BrowserWindow | null,
): Promise<{ readonly path: string | null }> {
const copy = await requireCopy(copyId);
const current = await readClientModsConfig(copy.dataPath);
const preset = current.presets.find((item) => item.id === presetId);
if (!preset) throw new AppError('mods_preset_invalid');
const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset';
const dialogOptions = {
defaultPath: `${safeName}.wto-mods-preset.json`,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
};
const choice = window
? await dialog.showSaveDialog(window, dialogOptions)
: await dialog.showSaveDialog(dialogOptions);
if (choice.canceled || !choice.filePath) return { path: null };
const payload = {
format: 1 as const,
name: preset.name,
order: [...preset.order],
enabled: { ...preset.enabled },
};
await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
return { path: choice.filePath };
}
export async function importModPreset(
copyId: string,
window: BrowserWindow | null,
): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> {
const copy = await requireCopy(copyId);
const dialogOptions = {
properties: ['openFile'] as Array<'openFile'>,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
};
const choice = window
? await dialog.showOpenDialog(window, dialogOptions)
: await dialog.showOpenDialog(dialogOptions);
if (choice.canceled || !choice.filePaths[0]) {
return { imported: false, state: await buildModsStateView(copy) };
}
let parsedRaw: unknown;
try {
parsedRaw = JSON.parse(await readFile(choice.filePaths[0], 'utf8')) as unknown;
} catch {
throw new AppError('mods_preset_invalid');
}
const validated = ModPresetTransferSchema.safeParse(parsedRaw);
if (!validated.success) throw new AppError('mods_preset_invalid');
const current = await readClientModsConfig(copy.dataPath);
const newPreset: ModPreset = {
id: randomUUID(),
name: validated.data.name,
order: validated.data.order,
enabled: validated.data.enabled,
updatedAt: new Date().toISOString(),
};
const next: ClientModsConfig = {
...current,
presets: [...current.presets, newPreset],
};
await writeClientModsConfig(copy.dataPath, next);
return { imported: true, state: await buildModsStateView(copy, next) };
}
export async function setModsFolder(copyId: string, folderPath: string | null): Promise<ModsStateView> {
if (folderPath !== null) {
if (!isAbsolute(folderPath)) throw new AppError('mods_folder_invalid');
try {
await mkdir(folderPath, { recursive: true });
const info = await stat(folderPath);
if (!info.isDirectory()) throw new AppError('mods_folder_invalid');
} catch (error) {
if (error instanceof AppError) throw error;
throw new AppError('mods_folder_invalid');
}
}
await updateSettings({ modsFolder: folderPath });
const copy = await requireCopy(copyId);
return buildModsStateView(copy);
}
/** Resolve ordered enabled mods for a launch; rejects when blocking dependency/conflict errors exist. */
export async function resolveEnabledModsForLaunch(
dataPath: string,
gameVersion: string | null,
): Promise<{ readonly modsDir: string; readonly enabledMods: readonly DiscoveredMod[] }> {
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const config = normalizeClientModsConfig(await readClientModsConfig(dataPath), discovered.mods);
const resolved = resolveModLoadOrder(discovered.mods, config, gameVersion);
if (resolved.hasBlockingErrors) {
console.error('[mods] blocking mod issues prevented launch:', resolved.issues.filter((i) => i.severity === 'error'));
throw new AppError('mods_blocking_issues');
}
return { modsDir, enabledMods: resolved.enabledMods };
}
async function buildModsStateView(copy: InstallRecord, preloadedConfig?: ClientModsConfig): Promise<ModsStateView> {
const { modsDir, defaultModsDir, isCustomModsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const rawConfig = preloadedConfig ?? await readClientModsConfig(copy.dataPath);
const config = normalizeClientModsConfig(rawConfig, discovered.mods);
const resolved = resolveModLoadOrder(discovered.mods, config, copy.gameVersion);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const orderedMods: ModListItem[] = config.order
.map((id) => byId.get(id))
.filter((mod): mod is DiscoveredMod => mod !== undefined)
.map(toModListItem);
return {
modsDir,
defaultModsDir,
isCustomModsDir,
apiVersion: MOD_API_VERSION,
mods: orderedMods,
discoveryErrors: [...discovered.errors],
order: [...config.order],
enabled: { ...config.enabled },
activePresetId: config.activePresetId,
presets: config.presets.map((preset) => ({
id: preset.id,
name: preset.name,
order: [...preset.order],
enabled: { ...preset.enabled },
updatedAt: preset.updatedAt,
})),
issues: [...resolved.issues],
hasBlockingErrors: resolved.hasBlockingErrors,
};
}
function toModListItem(mod: DiscoveredMod): ModListItem {
return {
id: mod.manifest.id,
folderName: mod.folderName,
rootDir: mod.rootDir,
name: mod.manifest.name,
...(mod.manifest.description !== undefined ? { description: mod.manifest.description } : {}),
version: mod.manifest.version,
author: mod.manifest.author,
apiVersion: mod.manifest.apiVersion,
gameVersions: [...mod.manifest.gameVersions],
requires: [...mod.manifest.requires],
conflicts: [...mod.manifest.conflicts],
loadAfter: [...mod.manifest.loadAfter],
loadBefore: [...mod.manifest.loadBefore],
badges: [...mod.content.badges],
hasServerScript: mod.content.serverEntry !== undefined,
serverTuningFiles: [...mod.content.serverTuningFiles],
packOperations: [...mod.content.packOperations],
guiPatchCount: mod.content.guiPatchDirs.length,
exePatchCount: mod.content.exePatchDirs.length,
hasClientAddon: mod.content.hasClientAddon,
addonFileCount: mod.content.addonRelativeFiles.length,
clientFileCount: mod.content.clientFiles.length,
hasConfigBlkPatch: mod.content.configBlkPatch !== undefined,
};
}
async function requireCopy(copyId: string): Promise<InstallRecord> {
const copies = await listCopies();
const copy = copies.copies.find((entry) => entry.id === copyId);
if (!copy) throw new AppError('copy_not_found');
return copy;
}
async function readClientModsConfig(dataPath: string): Promise<ClientModsConfig> {
const path = join(dataPath, CLIENT_MODS_CONFIG_FILE);
try {
const raw = await readJsonOr(path, null);
if (!raw || typeof raw !== 'object') return emptyClientModsConfig();
const obj = raw as Partial<ClientModsConfig>;
return {
format: 1,
order: Array.isArray(obj.order) ? obj.order.filter((item): item is string => typeof item === 'string') : [],
enabled: obj.enabled && typeof obj.enabled === 'object' ? { ...obj.enabled } : {},
activePresetId: typeof obj.activePresetId === 'string' ? obj.activePresetId : null,
presets: Array.isArray(obj.presets) ? obj.presets : [],
};
} catch (error) {
console.warn('[mods] unreadable client mods config, using defaults:', path, error);
return emptyClientModsConfig();
}
}
async function writeClientModsConfig(dataPath: string, config: ClientModsConfig): Promise<void> {
try {
await writeJsonAtomic(join(dataPath, CLIENT_MODS_CONFIG_FILE), config);
} catch (error) {
console.error('[mods] writing client mods config failed:', error);
throw new AppError('mods_write_failed');
}
}
@@ -1,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 {
@@ -98,18 +98,35 @@ export function sameReleaseSource(a: ReleaseSource, b: ReleaseSource): boolean {
export async function withReleaseSources<T>( export async function withReleaseSources<T>(
read: (source: ReleaseSource) => Promise<T>, preferred?: ReleaseSource, read: (source: ReleaseSource) => Promise<T>, preferred?: ReleaseSource,
): Promise<T> { ): Promise<T> {
const primary = releaseSource(new URL(`https://github.com/${patchPackTuning().repository}`)); const tuning = patchPackTuning();
const repository = releaseRepositoryUrl((await getSettings()).updateMirrorUrl); const candidates: ReleaseSource[] = [];
const mirror = repository ? releaseSource(repository) : null; const add = (url: URL | null): void => {
if (!mirror || sameReleaseSource(primary, mirror)) return read(primary); if (!url) return;
const [first, second] = preferred && sameReleaseSource(preferred, mirror) ? [mirror, primary] : [primary, mirror]; const source = releaseSource(url);
try { if (!candidates.some((existing) => sameReleaseSource(existing, source))) candidates.push(source);
return await read(first); };
} catch (error) { add(releaseRepositoryUrl(tuning.primarySource));
if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error; add(releaseRepositoryUrl((await getSettings()).updateMirrorUrl));
console.info(`[release-feed] ${first.feed.hostname} was unavailable, trying ${second.feed.hostname}.`); for (const fallback of tuning.fallbackSources) add(releaseRepositoryUrl(fallback));
return read(second); if (candidates.length === 0) throw new FeedUnreachableError('No valid release sources are configured.');
const ordered = preferred
? [preferred, ...candidates.filter((source) => !sameReleaseSource(source, preferred))]
: candidates;
let lastError: unknown;
for (let index = 0; index < ordered.length; index += 1) {
const current = ordered[index]!;
try {
return await read(current);
} catch (error) {
if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error;
lastError = error;
const next = ordered[index + 1];
if (next) console.info(`[release-feed] ${current.feed.hostname} was unavailable, trying ${next.feed.hostname}.`);
}
} }
throw lastError;
} }
function listingFor(source: ReleaseSource): Promise<ReleaseListing> { function listingFor(source: ReleaseSource): Promise<ReleaseListing> {
@@ -17,6 +17,8 @@ export interface ResourcePaths {
readonly networkHookLibrary: string; readonly networkHookLibrary: string;
/** Multi-resolution Windows icon for the window and system tray. */ /** Multi-resolution Windows icon for the window and system tray. */
readonly appIcon: string; readonly appIcon: string;
/** Bundled example mod templates seeded into an empty mods folder on first use. */
readonly modTemplates: string;
} }
export function resourcePaths(): ResourcePaths { export function resourcePaths(): ResourcePaths {
@@ -32,6 +34,7 @@ export function bundledResourcePaths(): ResourcePaths {
patches: join(process.resourcesPath, 'patches'), patches: join(process.resourcesPath, 'patches'),
networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'), networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'),
appIcon: join(process.resourcesPath, 'icon.ico'), appIcon: join(process.resourcesPath, 'icon.ico'),
modTemplates: join(process.resourcesPath, 'mod-templates'),
}; };
} }
// The app path is apps/launcher; the repository is two levels up. // The app path is apps/launcher; the repository is two levels up.
@@ -40,6 +43,7 @@ export function bundledResourcePaths(): ResourcePaths {
patches: join(repository, 'patches'), patches: join(repository, 'patches'),
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'), networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'), appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
modTemplates: join(repository, 'mod-dev-docs', 'templates'),
}; };
} }
@@ -12,6 +12,8 @@ export interface BuildRequest {
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' };
+65 -5
View File
@@ -1,7 +1,21 @@
import { readFileSync, realpathSync } from 'node:fs'; import { readFileSync, realpathSync } from 'node:fs';
import { relative } from 'node:path'; import { relative } from 'node:path';
import type { MessageEvent } from 'electron'; import type { MessageEvent } from 'electron';
import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCacheProblem, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher'; import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
import {
assertWritableCopy,
buildGameCopy,
computeModsBuildFingerprint,
copyPlayerDecalCache,
CORE_BUILD_PACKS,
playerDecalCacheProblem,
prepareOptionalStockPacks,
readPlayerDecalIndexFiles,
readStockGameFiles,
syncExternalModFiles,
writeGameCopy,
type GameCopyFile,
} from '@wto/patcher';
import { multiVehiclePackIds } from '@wto/server'; import { multiVehiclePackIds } from '@wto/server';
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts'; import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
@@ -9,6 +23,9 @@ let prepared: {
readonly request: BuildRequest; readonly request: BuildRequest;
readonly files: readonly GameCopyFile[]; readonly files: readonly GameCopyFile[];
readonly decalCache: string | undefined; readonly decalCache: string | undefined;
readonly enabledMods: readonly DiscoveredMod[];
readonly optionalPacksInBuild: readonly ModdableClientPack[];
readonly fingerprint: string;
} | null = null; } | null = null;
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void { function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
@@ -31,17 +48,41 @@ function importedDecals(path: string | undefined): string | undefined {
return undefined; return undefined;
} }
function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly string[] | undefined): DiscoveredMod[] {
if (!modsDir || !enabledModIds || enabledModIds.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const ordered: DiscoveredMod[] = [];
for (const id of enabledModIds) {
const mod = byId.get(id);
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
ordered.push(mod);
}
return ordered;
}
function build(request: BuildRequest): void { function build(request: BuildRequest): void {
checkBuildLocation(request); checkBuildLocation(request);
const decalCache = importedDecals(request.decalCache); const decalCache = importedDecals(request.decalCache);
const decalIndexFiles = decalCache ? readPlayerDecalIndexFiles(decalCache) : undefined;
const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds);
const touchedPacks = touchedClientPacks(enabledMods);
const optionalPacksInBuild = touchedPacks.filter((pack) => !CORE_BUILD_PACKS.has(pack));
const extraStockPacks = optionalPacksInBuild.length > 0
? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild)
: undefined;
const result = buildGameCopy({ const result = buildGameCopy({
stock: readStockGameFiles(request.stockPath), stock: readStockGameFiles(request.stockPath),
patches: request.patches, patches: request.patches,
networkHookLibrary: readFileSync(request.networkHookLibrary), networkHookLibrary: readFileSync(request.networkHookLibrary),
port: request.port, port: request.port,
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info), multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info, enabledMods),
placeholderDecals: decalCache === undefined, placeholderDecals: decalCache === undefined,
...(decalIndexFiles ? { decalIndexFiles } : {}),
hookLogging: request.hookLogging, hookLogging: request.hookLogging,
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
...(extraStockPacks ? { extraStockPacks } : {}),
}); });
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures]; const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
const accepted = new Set(request.acceptedUnavailable); const accepted = new Set(request.acceptedUnavailable);
@@ -50,7 +91,19 @@ function build(request: BuildRequest): void {
send({ kind: 'failed', error: 'launch_build_unavailable' }); send({ kind: 'failed', error: 'launch_build_unavailable' });
return; return;
} }
prepared = { request, files: result.files, decalCache }; if (result.mods.enabledModIds.length > 0) {
console.info(
`[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` +
`(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` +
`gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` +
`exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`,
);
for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) {
console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`);
}
}
const fingerprint = computeModsBuildFingerprint(enabledMods, request.port, request.patches);
prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint };
send({ kind: 'prepared', total: prepared.files.length }); send({ kind: 'prepared', total: prepared.files.length });
} }
@@ -62,15 +115,22 @@ process.parentPort.on('message', (event: MessageEvent) => {
return; return;
} }
if (!prepared) throw new Error('No build is ready to write.'); if (!prepared) throw new Error('No build is ready to write.');
const { request, files, decalCache } = prepared; const { request, files, decalCache, enabledMods, optionalPacksInBuild, fingerprint } = prepared;
prepared = null; prepared = null;
checkBuildLocation(request); checkBuildLocation(request);
const { copyPath } = request; const { copyPath, stockPath } = request;
if (decalCache) copyPlayerDecalCache(decalCache, copyPath); if (decalCache) copyPlayerDecalCache(decalCache, copyPath);
for (const [index, file] of files.entries()) { for (const [index, file] of files.entries()) {
writeGameCopy(copyPath, [file]); writeGameCopy(copyPath, [file]);
send({ kind: 'progress', written: index + 1, total: files.length, file: file.path }); send({ kind: 'progress', written: index + 1, total: files.length, file: file.path });
} }
const deployResult = syncExternalModFiles(copyPath, stockPath, enabledMods, optionalPacksInBuild, fingerprint);
for (const warning of deployResult.warnings) {
console.warn(`[mods] skipped "${warning.targetRelPath}" from "${warning.modId}": ${warning.reason}`);
}
if (deployResult.restoredOptionalPacks.length > 0) {
console.info(`[mods] restored stock pack(s): ${deployResult.restoredOptionalPacks.join(', ')}`);
}
send({ kind: 'written' }); send({ kind: 'written' });
} catch (error) { } catch (error) {
console.error('[build] preparing the game copy failed:', error); console.error('[build] preparing the game copy failed:', error);
@@ -1,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);
+13 -2
View File
@@ -10,6 +10,7 @@ import { applyLanguage, resolveLanguage } from './i18n/index.ts';
import { ipcInvoke, ipcOn } from './ipc.ts'; import { ipcInvoke, ipcOn } from './ipc.ts';
import { AboutPage } from './pages/about/AboutPage.tsx'; import { AboutPage } from './pages/about/AboutPage.tsx';
import { CopyMaintenance } from './pages/copies/CopyMaintenance.tsx'; import { CopyMaintenance } from './pages/copies/CopyMaintenance.tsx';
import { useCopyMaintenance } from './pages/copies/useCopyMaintenance.ts';
import { CopyList } from './pages/copies/CopyList.tsx'; import { CopyList } from './pages/copies/CopyList.tsx';
import { CopySummary } from './pages/copies/CopySummary.tsx'; import { CopySummary } from './pages/copies/CopySummary.tsx';
import { FeatureStatus } from './pages/copies/FeatureStatus.tsx'; import { FeatureStatus } from './pages/copies/FeatureStatus.tsx';
@@ -21,6 +22,7 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
import { WizardMain } from './pages/install/WizardMain.tsx'; import { WizardMain } from './pages/install/WizardMain.tsx';
import { WizardSide } from './pages/install/WizardSide.tsx'; import { WizardSide } from './pages/install/WizardSide.tsx';
import { wizardBar } from './pages/install/wizard-bar.ts'; import { wizardBar } from './pages/install/wizard-bar.ts';
import { ModsPage } from './pages/mods/ModsPage.tsx';
import { TuningPage } from './pages/tuning/TuningPage.tsx'; import { TuningPage } from './pages/tuning/TuningPage.tsx';
import { SavesPage } from './pages/saves/SavesPage.tsx'; import { SavesPage } from './pages/saves/SavesPage.tsx';
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx'; import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
@@ -31,7 +33,7 @@ import { Background } from './shell/Background.tsx';
import { BottomBar } from './shell/BottomBar.tsx'; import { BottomBar } from './shell/BottomBar.tsx';
import type { BarModel } from './shell/bar-model.ts'; import type { BarModel } from './shell/bar-model.ts';
import { Footer } from './shell/Footer.tsx'; import { Footer } from './shell/Footer.tsx';
import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts'; import { COPY_SECTIONS, MODS_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
import { SubNav } from './shell/SubNav.tsx'; import { SubNav } from './shell/SubNav.tsx';
import { TitleBar } from './shell/TitleBar.tsx'; import { TitleBar } from './shell/TitleBar.tsx';
import { useBackgrounds } from './shell/useBackgrounds.ts'; import { useBackgrounds } from './shell/useBackgrounds.ts';
@@ -68,6 +70,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
// The setting as the window opened: turning it on later does not check right away. // The setting as the window opened: turning it on later does not check right away.
const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report); const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report);
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report); const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
const maintenance = useCopyMaintenance(report);
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions; const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) }); const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) });
@@ -193,6 +196,14 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
: <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>, : <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>,
bar: home, bar: home,
}; };
case 'mods':
return {
side: <SubNav sections={MODS_SECTIONS} active={route.mods} label={(section) => t(`mods.sections.${section}`)} onSelect={(section) => go({ page: 'mods', section })} />,
main: record
? <ModsPage key={record.id} copy={record} section={route.mods} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'server-running', 'stopping'].includes(launch.phase)} onError={report} />
: <Sheet title={t(`mods.sections.${route.mods}`)}><p className="lead">{t('mods.noCopy')}</p></Sheet>,
bar: home,
};
case 'copies': { case 'copies': {
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />; const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
if (route.copies === 'list') { if (route.copies === 'list') {
@@ -223,7 +234,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
}; };
} }
if (route.copies === 'maintain') { if (route.copies === 'maintain') {
return { side, main: <CopyMaintenance key={record.id} record={record} onError={report} />, bar: home }; return { side, main: <CopyMaintenance key={record.id} record={record} maintenance={maintenance} onError={report} />, bar: home };
} }
const main = route.copies === 'features' const main = route.copies === 'features'
? <FeatureStatus record={record} supportedVersions={supported} onError={report} /> ? <FeatureStatus record={record} supportedVersions={supported} onError={report} />
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,13 +1,15 @@
import { useState } from 'react'; import { useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx'; import { Notice } from '../../components/Notice.tsx';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx'; import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts'; import { ipcInvoke } from '../../ipc.ts';
import type { AppUpdateState } from '../../shell/useAppUpdate.ts'; import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
import { AppUpdateSection } from './AppUpdateSection.tsx'; import { AppUpdateSection } from './AppUpdateSection.tsx';
import type { PatchPackState } from '../../shell/usePatchPack.ts'; import type { PatchPackState } from '../../shell/usePatchPack.ts';
const HOMEPAGE_URL = 'https://wto-project.net';
const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
interface AboutPageProps { interface AboutPageProps {
readonly launcherVersion: string; readonly launcherVersion: string;
readonly supportedVersions: readonly string[]; readonly supportedVersions: readonly string[];
@@ -17,7 +19,7 @@ interface AboutPageProps {
readonly onError: (error: unknown) => void; readonly onError: (error: unknown) => void;
} }
/** The launcher's version, the game versions it supports, adaptation pack updates, 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, appUpdate, loggingEnabled, onError }: AboutPageProps) {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
@@ -30,15 +32,59 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
{t('about.supported', { versions: supportedVersions.join(', ') })} {t('about.supported', { versions: supportedVersions.join(', ') })}
</div> </div>
</div> </div>
<AppUpdateSection state={appUpdate} /> <div className="about-columns">
<PatchPackSection state={patchPack} /> <div className="about-column">
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} /> <AppUpdateSection state={appUpdate} />
<h3 className="section-title section-title-spaced">{t('about.statement')}</h3> <PatchPackSection state={patchPack} />
<p className="lead">{t('about.statementBody')}</p> </div>
<div className="about-column">
<HomepageSection />
<CommunitySection />
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
<section className="about-card">
<h3 className="about-card-title">{t('about.statement')}</h3>
<p className="about-card-meta">{t('about.statementBody')}</p>
</section>
</div>
</div>
</Sheet> </Sheet>
); );
} }
function HomepageSection() {
const { t } = useTranslation();
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.homepage.title')}</h3>
<div className="about-card-actions">
<a className="button" href={HOMEPAGE_URL} target="_blank" rel="noreferrer">
{t('about.homepage.open')}
</a>
</div>
</div>
<p className="about-card-meta">{t('about.homepage.hint')}</p>
</section>
);
}
function CommunitySection() {
const { t } = useTranslation();
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.community.discord')}</h3>
<div className="about-card-actions">
<a className="button" href={DISCORD_INVITE_URL} target="_blank" rel="noreferrer">
{t('about.community.openDiscord')}
</a>
</div>
</div>
<p className="about-card-meta">{t('about.community.discordHint')}</p>
</section>
);
}
function FeedbackLogsSection({ loggingEnabled, onError }: { function FeedbackLogsSection({ loggingEnabled, onError }: {
readonly loggingEnabled: boolean; readonly loggingEnabled: boolean;
readonly onError: (error: unknown) => void; readonly onError: (error: unknown) => void;
@@ -61,16 +107,19 @@ function FeedbackLogsSection({ loggingEnabled, onError }: {
} }
return ( return (
<> <section className="about-card">
<h3 className="section-title section-title-spaced">{t('about.feedback.title')}</h3> <div className="about-card-head">
<Row label={t('about.feedback.export')} hint={t('about.feedback.exportHint')}> <h3 className="about-card-title">{t('about.feedback.title')}</h3>
<button type="button" className="button" disabled={exporting} onClick={() => { void save(); }}> <div className="about-card-actions">
{t('about.feedback.exportButton')} <button type="button" className="button" disabled={exporting} onClick={() => { void save(); }}>
</button> {t('about.feedback.exportButton')}
</Row> </button>
</div>
</div>
<p className="about-card-meta">{t('about.feedback.exportHint')}</p>
{!loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>} {!loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>} {savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
</> </section>
); );
} }
@@ -85,25 +134,30 @@ function PatchPackSection({ state }: { readonly state: PatchPackState }) {
? t('about.pack.bundledVersion', { version: active.version }) ? t('about.pack.bundledVersion', { version: active.version })
: t('about.pack.bundled'); : t('about.pack.bundled');
return ( return (
<> <section className="about-card">
<h3 className="section-title">{t('about.pack.title')}</h3> <div className="about-card-head">
<Row label={t('about.pack.current')} hint={t('about.pack.currentHint')}> <h3 className="about-card-title">{t('about.pack.title')}</h3>
<span>{current}</span> <div className="about-card-actions">
{active?.source === 'downloaded' && ( <button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
<button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}> {busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')}
{t('about.pack.useBundled')}
</button> </button>
)} {active?.source === 'downloaded' && (
</Row> <button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}>
<Row label={t('about.pack.check')} hint={t('about.pack.checkHint')}> {t('about.pack.useBundled')}
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}> </button>
{busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')} )}
</button> </div>
</Row> </div>
<p className="about-card-meta">
<span className="about-card-label">{t('about.pack.current')}</span>
{' · '}
{current}
</p>
<p className="small">{t('about.pack.currentHint')}</p>
{busy === 'applying' && <p className="small">{t('about.pack.applying')}</p>} {busy === 'applying' && <p className="small">{t('about.pack.applying')}</p>}
{state.applyFailure && <Notice tone="error"><p>{t(`about.pack.applyFailed.${state.applyFailure}`)}</p></Notice>} {state.applyFailure && <Notice tone="error"><p>{t(`about.pack.applyFailed.${state.applyFailure}`)}</p></Notice>}
{check && busy !== 'checking' && <CheckResult state={state} />} {check && busy !== 'checking' && <CheckResult state={state} />}
</> </section>
); );
} }
@@ -1,7 +1,6 @@
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx'; import { Notice } from '../../components/Notice.tsx';
import { ProgressBar } from '../../components/ProgressBar.tsx'; import { ProgressBar } from '../../components/ProgressBar.tsx';
import { Row } from '../../components/Row.tsx';
import { formatBytes } from '../../format.ts'; import { formatBytes } from '../../format.ts';
import type { AppUpdateState } from '../../shell/useAppUpdate.ts'; import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
@@ -10,13 +9,16 @@ export function AppUpdateSection({ state }: { readonly state: AppUpdateState })
if (!state.supported) return null; if (!state.supported) return null;
const { check, busy, progress } = state; const { check, busy, progress } = state;
return ( return (
<> <section className="about-card">
<h3 className="section-title">{t('about.update.title')}</h3> <div className="about-card-head">
<Row label={t('about.update.check')}> <h3 className="about-card-title">{t('about.update.title')}</h3>
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}> <div className="about-card-actions">
{t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')} <button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
</button> {t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')}
</Row> </button>
</div>
</div>
<p className="about-card-meta">{t('about.update.check')}</p>
{check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>} {check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>}
{check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>} {check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
{check?.status === 'available' && busy !== 'checking' && ( {check?.status === 'available' && busy !== 'checking' && (
@@ -43,6 +45,6 @@ export function AppUpdateSection({ state }: { readonly state: AppUpdateState })
)} )}
</Notice> </Notice>
)} )}
</> </section>
); );
} }
@@ -1,29 +1,24 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import type { IpcInput } from '@shared/ipc/contract.ts';
import type { InstallRecord } from '@shared/schemas/install.ts'; import type { InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts'; import type { MaintenanceInfo, MaintenanceProgress } from '@shared/schemas/maintenance.ts';
import { ProgressBar } from '../../components/ProgressBar.tsx'; import { ProgressBar } from '../../components/ProgressBar.tsx';
import { Sheet } from '../../components/Sheet.tsx'; import { Sheet } from '../../components/Sheet.tsx';
import { formatBytes } from '../../format.ts'; import { formatBytes } from '../../format.ts';
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts'; import { ipcInvoke } from '../../ipc.ts';
import { CopyMaintenanceActions, CopyRemoval, type CopyRemovalOptions } from './CopyMaintenanceControls.tsx'; import { CopyMaintenanceActions, CopyRemoval, type CopyRemovalOptions } from './CopyMaintenanceControls.tsx';
import type { CopyMaintenanceState, MaintenanceOperation, MaintenanceOptions } from './useCopyMaintenance.ts';
interface CopyMaintenanceProps { interface CopyMaintenanceProps {
readonly record: InstallRecord; readonly record: InstallRecord;
readonly maintenance: CopyMaintenanceState;
readonly onError: (error: unknown) => void; readonly onError: (error: unknown) => void;
} }
type Operation = MaintenanceRequest['operation']; export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanceProps) {
type OperationOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const [info, setInfo] = useState<MaintenanceInfo | null>(null); const [info, setInfo] = useState<MaintenanceInfo | null>(null);
const [working, setWorking] = useState<Operation | null>(null);
const [progress, setProgress] = useState<MaintenanceProgress | null>(null);
const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null); const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null);
const [result, setResult] = useState<Operation | 'cancelled' | null>(null);
useEffect(() => { useEffect(() => {
let mounted = true; let mounted = true;
@@ -31,29 +26,17 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
if (mounted) setInfo(value); if (mounted) setInfo(value);
}).catch(onError); }).catch(onError);
return () => { mounted = false; }; return () => { mounted = false; };
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, onError]); }, [record.id, record.gameVersion, record.steamLibraryConfirmation, maintenance.revision, onError]);
useEffect(() => ipcOn('event:copy-maintenance', (event) => { const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
if (event.id === record.id) setProgress(event); if (operation === 'delete') setRemoval(null);
}), [record.id]); maintenance.run(record.id, operation, options);
const run = (operation: Operation, options: OperationOptions = {}): void => {
setResult(null);
setWorking(operation);
setProgress(null);
ipcInvoke('copies:maintain', { id: record.id, operation, ...options })
.then(() => {
setResult(operation);
setRemoval(null);
})
.catch((error: unknown) => {
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') setResult('cancelled');
else onError(error);
})
.finally(() => setWorking(null));
}; };
const busy = working !== null; const active = maintenance.active;
const busy = active !== null;
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
return ( return (
<Sheet title={t('copies.sections.maintain')} aside={record.name}> <Sheet title={t('copies.sections.maintain')} aside={record.name}>
<CopyMaintenanceActions <CopyMaintenanceActions
@@ -71,32 +54,25 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
onOptionsChange={setRemoval} onOptionsChange={setRemoval}
onRemove={(deleteData) => run('delete', { deleteData })} onRemove={(deleteData) => run('delete', { deleteData })}
/> />
{working && ( {active && <MaintenanceStatus progress={active} onCancel={maintenance.cancel} />}
<MaintenanceStatus
operation={working}
progress={progress}
onCancel={() => ipcInvoke('copies:cancelMaintenance').catch(onError)}
/>
)}
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>} {result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
</Sheet> </Sheet>
); );
} }
interface MaintenanceStatusProps { interface MaintenanceStatusProps {
readonly operation: Operation; readonly progress: MaintenanceProgress;
readonly progress: MaintenanceProgress | null;
readonly onCancel: () => void; readonly onCancel: () => void;
} }
function MaintenanceStatus({ operation, progress, onCancel }: MaintenanceStatusProps) { function MaintenanceStatus({ progress, onCancel }: MaintenanceStatusProps) {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<div className="maintenance-progress" role="status"> <div className="maintenance-progress" role="status">
<p>{t(`copies.maintenance.phase.${progress?.phase ?? 'checking'}`)}</p> <p>{t(`copies.maintenance.phase.${progress.phase}`)}</p>
<ProgressBar value={progress?.doneBytes ?? 0} max={progress?.totalBytes || null} /> <ProgressBar value={progress.doneBytes} max={progress.totalBytes || null} />
{progress?.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null} {progress.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
{(operation === 'update' || operation === 'compact') && progress?.phase !== 'applying' && ( {(progress.operation === 'update' || progress.operation === 'compact') && progress.phase !== 'applying' && (
<button type="button" className="button" onClick={onCancel}> <button type="button" className="button" onClick={onCancel}>
{t('wizard.cancel')} {t('wizard.cancel')}
</button> </button>
@@ -0,0 +1,60 @@
import { useCallback, useEffect, useState } from 'react';
import type { IpcInput } from '@shared/ipc/contract.ts';
import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
export type MaintenanceOperation = MaintenanceRequest['operation'];
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
export interface MaintenanceOutcome {
readonly copyId: string;
readonly outcome: MaintenanceOperation | 'cancelled';
}
/** Tracks copy maintenance across tab switches so progress and busy state survive unmounting the maintenance page. */
export function useCopyMaintenance(onError: (error: unknown) => void) {
const [active, setActive] = useState<MaintenanceProgress | null>(null);
const [lastResult, setLastResult] = useState<MaintenanceOutcome | null>(null);
const [revision, setRevision] = useState(0);
useEffect(() => {
let mounted = true;
let receivedEvent = false;
const dispose = ipcOn('event:copy-maintenance', (event) => {
receivedEvent = true;
setActive(event);
if (event === null) setRevision((value) => value + 1);
});
ipcInvoke('copies:maintenanceState').then((state) => {
if (mounted && !receivedEvent) setActive(state);
}).catch(onError);
return () => { mounted = false; dispose(); };
}, [onError]);
const run = useCallback((id: string, operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
setLastResult(null);
setActive({ id, operation, phase: 'checking', doneBytes: 0, totalBytes: 0 });
ipcInvoke('copies:maintain', { id, operation, ...options })
.then(() => {
setLastResult({ copyId: id, outcome: operation });
})
.catch((error: unknown) => {
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') {
setLastResult({ copyId: id, outcome: 'cancelled' });
} else {
onError(error);
}
})
.finally(() => {
setActive((current) => (current?.id === id && current.operation === operation ? null : current));
});
}, [onError]);
const cancel = useCallback((): void => {
ipcInvoke('copies:cancelMaintenance').catch(onError);
}, [onError]);
return { active, lastResult, revision, run, cancel };
}
export type CopyMaintenanceState = ReturnType<typeof useCopyMaintenance>;
@@ -0,0 +1,591 @@
import { useCallback, useEffect, useMemo, useState, type DragEvent, type FormEvent } from 'react';
import { useTranslation } from 'react-i18next';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { ModIssueView, ModListItem, ModsStateView } from '@shared/schemas/mods.ts';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
import type { ModsSection } from '../../shell/navigation.ts';
const MOD_DOCS_URL = 'https://wto-project.net/mod-docs';
interface Props {
readonly copy: InstallRecord;
readonly section: ModsSection;
readonly readOnly: boolean;
readonly onError: (error: unknown) => void;
}
function localized(value: string | Readonly<Record<string, string>> | undefined, language: string): string {
if (!value) return '';
if (typeof value === 'string') return value;
const exact = value[language];
if (exact) return exact;
const prefix = language.split('-')[0];
if (prefix) {
const match = Object.entries(value).find(([key]) => key === prefix || key.startsWith(`${prefix}-`));
if (match?.[1]) return match[1];
}
return value.en ?? value['en-US'] ?? Object.values(value)[0] ?? '';
}
export function ModsPage({ copy, section, readOnly, onError }: Props) {
const { t, i18n } = useTranslation();
const [state, setState] = useState<ModsStateView | null>(null);
const [busy, setBusy] = useState(false);
const [query, setQuery] = useState('');
const [expandedId, setExpandedId] = useState<string | null>(null);
const [draggedId, setDraggedId] = useState<string | null>(null);
const [presetName, setPresetName] = useState('');
const [notice, setNotice] = useState<string | null>(null);
const load = useCallback(() => {
setBusy(true);
ipcInvoke('mods:getState', { copyId: copy.id })
.then(setState)
.catch(onError)
.finally(() => setBusy(false));
}, [copy.id, onError]);
useEffect(() => {
let mounted = true;
const sync = (): void => {
ipcInvoke('mods:getState', { copyId: copy.id })
.then((result) => { if (mounted) setState(result); })
.catch(onError);
};
sync();
window.addEventListener('focus', sync);
return () => {
mounted = false;
window.removeEventListener('focus', sync);
};
}, [copy.id, onError]);
const runAction = (action: Promise<ModsStateView>, successNotice?: string): void => {
setBusy(true);
setNotice(null);
action
.then((next) => {
setState(next);
if (successNotice) setNotice(successNotice);
})
.catch(onError)
.finally(() => setBusy(false));
};
const issuesByMod = useMemo(() => {
const map = new Map<string, ModIssueView[]>();
for (const issue of state?.issues ?? []) {
const list = map.get(issue.modId) ?? [];
list.push(issue);
map.set(issue.modId, list);
}
return map;
}, [state]);
const title = t(`mods.sections.${section}`);
if (!state) {
return <Sheet title={title} aside={copy.name}><p className="lead">{t('mods.loading')}</p></Sheet>;
}
const disabled = readOnly || busy;
const enabledCount = state.mods.filter((mod) => state.enabled[mod.id] === true).length;
const toggleMod = (modId: string, nextEnabled: boolean): void => {
runAction(ipcInvoke('mods:setEnabled', { copyId: copy.id, modId, enabled: nextEnabled }));
};
const reorder = (nextOrder: string[]): void => {
runAction(ipcInvoke('mods:setOrder', { copyId: copy.id, order: nextOrder }));
};
const moveMod = (modId: string, delta: -1 | 1): void => {
const idx = state.order.indexOf(modId);
const target = idx + delta;
if (idx < 0 || target < 0 || target >= state.order.length) return;
const next = [...state.order];
const [item] = next.splice(idx, 1);
next.splice(target, 0, item!);
reorder(next);
};
const handleDrop = (targetId: string, event: DragEvent<HTMLDivElement>): void => {
event.preventDefault();
const sourceId = draggedId;
setDraggedId(null);
if (!sourceId || sourceId === targetId || disabled) return;
const from = state.order.indexOf(sourceId);
const to = state.order.indexOf(targetId);
if (from < 0 || to < 0) return;
const next = [...state.order];
const [moved] = next.splice(from, 1);
next.splice(to, 0, moved!);
reorder(next);
};
const savePreset = (event: FormEvent<HTMLFormElement>): void => {
event.preventDefault();
const trimmed = presetName.trim();
if (!trimmed) return;
runAction(
ipcInvoke('mods:savePreset', { copyId: copy.id, name: trimmed }),
t('mods.presets.saved', { name: trimmed }),
);
setPresetName('');
};
const pickCustomFolder = (): void => {
ipcInvoke('dialog:pickFolder', { title: t('mods.repo.pickTitle') })
.then(({ path }) => {
if (!path) return;
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path }), t('mods.repo.updated'));
})
.catch(onError);
};
const resetFolder = (): void => {
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path: null }), t('mods.repo.resetDone'));
};
const exportPreset = (presetId: string): void => {
setBusy(true);
setNotice(null);
ipcInvoke('mods:exportPreset', { copyId: copy.id, presetId })
.then(({ path }) => {
if (path) setNotice(t('mods.presets.exported', { path }));
})
.catch(onError)
.finally(() => setBusy(false));
};
const importPreset = (): void => {
setBusy(true);
setNotice(null);
ipcInvoke('mods:importPreset', { copyId: copy.id })
.then(({ imported, state: next }) => {
setState(next);
if (imported) setNotice(t('mods.presets.imported'));
})
.catch(onError)
.finally(() => setBusy(false));
};
const normalizedQuery = query.trim().toLowerCase();
const visibleMods = normalizedQuery
? state.mods.filter((mod) => {
const displayName = localized(mod.name, i18n.language).toLowerCase();
return displayName.includes(normalizedQuery)
|| mod.id.toLowerCase().includes(normalizedQuery)
|| mod.author.toLowerCase().includes(normalizedQuery);
})
: state.mods;
const canDrag = !disabled && normalizedQuery.length === 0;
return (
<Sheet
title={title}
aside={(
<span className="mods-aside">
<span>{copy.name} · {t('mods.enabledSummary', { enabled: enabledCount, total: state.mods.length })}</span>
<span
className="mods-exp-chip"
tabIndex={0}
aria-label={t('mods.experimentalBody', { api: state.apiVersion })}
>
<span>{t('mods.experimentalChip')}</span>
<span className="mods-exp-icon" aria-hidden="true">i</span>
<span className="mods-exp-popover" role="tooltip">
<strong>{t('mods.experimentalTitle')}</strong>
<span>{t('mods.experimentalBody', { api: state.apiVersion })}</span>
</span>
</span>
</span>
)}
>
{readOnly && (
<div className="mods-banner mods-banner-warn" role="status">
{t('mods.readOnlyNotice')}
</div>
)}
{notice && (
<div className="mods-banner mods-banner-ok" role="status">
{notice}
</div>
)}
{section === 'list' ? (
<>
<div className="mods-toolbar">
<input
type="search"
className="input mods-search"
placeholder={t('mods.searchPlaceholder')}
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
{state.presets.length > 0 && (
<select
className="select mods-preset-select"
aria-label={t('mods.presets.quickSwitch')}
disabled={disabled}
value={state.activePresetId ?? ''}
onChange={(event) => {
const id = event.target.value;
if (id) runAction(ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: id }));
}}
>
<option value="">{t('mods.presets.customOption')}</option>
{state.presets.map((preset) => (
<option key={preset.id} value={preset.id}>{preset.name}</option>
))}
</select>
)}
<button
type="button"
className="button"
disabled={disabled || state.mods.length < 2}
onClick={() => runAction(ipcInvoke('mods:autoSort', { copyId: copy.id }), t('mods.autoSorted'))}
>
{t('mods.autoSort')}
</button>
<button type="button" className="button" disabled={busy} onClick={load}>
{t('mods.refresh')}
</button>
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
{t('mods.openFolder')}
</button>
<a className="button" href={MOD_DOCS_URL} target="_blank" rel="noreferrer">
{t('mods.openDocs')}
</a>
</div>
{state.discoveryErrors.length > 0 && (
<div className="mods-issues-box mods-issues-error">
<div className="mods-issues-title">{t('mods.discoveryErrorsTitle', { count: state.discoveryErrors.length })}</div>
<ul>
{state.discoveryErrors.map((err) => (
<li key={err.folderName}>
<code>{err.folderName}</code>: {err.reason}
</li>
))}
</ul>
</div>
)}
{state.issues.length > 0 && (
<div className={state.hasBlockingErrors ? 'mods-issues-box mods-issues-error' : 'mods-issues-box mods-issues-warn'}>
<div className="mods-issues-title">
{state.hasBlockingErrors
? t('mods.blockingIssuesTitle', { count: state.issues.filter((i) => i.severity === 'error').length })
: t('mods.issuesTitle', { count: state.issues.length })}
</div>
<ul>
{state.issues.map((issue, idx) => (
<li key={`${issue.modId}-${issue.kind}-${idx}`} className={`mods-issue-${issue.severity}`}>
<span className="mods-issue-tag">{t(`mods.severity.${issue.severity}`)}</span>
<strong>{issue.modId}</strong>: {issue.detail}
</li>
))}
</ul>
</div>
)}
{visibleMods.length === 0 ? (
<div className="mods-empty">
<p className="lead">{state.mods.length === 0 ? t('mods.emptyTitle') : t('mods.noSearchMatch')}</p>
{state.mods.length === 0 && (
<>
<p className="mods-hint">{t('mods.emptyHint', { path: state.modsDir })}</p>
<button type="button" className="button button-primary" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
{t('mods.openFolder')}
</button>
</>
)}
</div>
) : (
<div className="mods-list">
{visibleMods.map((mod) => {
const index = state.order.indexOf(mod.id);
const isEnabled = state.enabled[mod.id] === true;
const isExpanded = expandedId === mod.id;
const modIssues = issuesByMod.get(mod.id) ?? [];
return (
<ModCard
key={mod.id}
mod={mod}
index={index}
total={state.order.length}
enabled={isEnabled}
expanded={isExpanded}
disabled={disabled}
canDrag={canDrag}
language={i18n.language}
issues={modIssues}
onToggle={(next) => toggleMod(mod.id, next)}
onMove={(delta) => moveMod(mod.id, delta)}
onToggleExpand={() => setExpandedId(isExpanded ? null : mod.id)}
onDragStart={() => setDraggedId(mod.id)}
onDrop={(event) => handleDrop(mod.id, event)}
/>
);
})}
</div>
)}
</>
) : (
<>
<section className="mods-section">
<h3 className="mods-subheading">{t('mods.presets.heading')}</h3>
<p className="mods-hint">{t('mods.presets.description')}</p>
<form className="mods-preset-form" onSubmit={savePreset}>
<input
type="text"
className="input"
maxLength={80}
disabled={disabled}
placeholder={t('mods.presets.namePlaceholder')}
value={presetName}
onChange={(event) => setPresetName(event.target.value)}
/>
<button type="submit" className="button button-primary" disabled={disabled || !presetName.trim()}>
{t('mods.presets.saveCurrent')}
</button>
<button type="button" className="button" disabled={disabled} onClick={importPreset}>
{t('mods.presets.import')}
</button>
</form>
{state.presets.length === 0 ? (
<p className="mods-hint">{t('mods.presets.empty')}</p>
) : (
<div className="mods-preset-list">
{state.presets.map((preset) => {
const active = state.activePresetId === preset.id;
const count = Object.values(preset.enabled).filter(Boolean).length;
return (
<div key={preset.id} className={active ? 'mods-preset-item mods-preset-active' : 'mods-preset-item'}>
<div className="mods-preset-meta">
<div className="mods-preset-name">
{preset.name}
{active && <span className="mods-badge mods-badge-data">{t('mods.presets.activeTag')}</span>}
</div>
<div className="mods-preset-sub">
{t('mods.presets.summary', { count, total: preset.order.length })}
</div>
</div>
<div className="copy-list-actions">
<button
type="button"
className="button button-primary"
disabled={disabled}
onClick={() => runAction(
ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: preset.id }),
t('mods.presets.applied', { name: preset.name }),
)}
>
{t('mods.presets.apply')}
</button>
<button
type="button"
className="button"
disabled={disabled}
onClick={() => runAction(
ipcInvoke('mods:savePreset', { copyId: copy.id, name: preset.name, overwriteId: preset.id }),
t('mods.presets.updated', { name: preset.name }),
)}
>
{t('mods.presets.overwrite')}
</button>
<button type="button" className="button" disabled={busy} onClick={() => exportPreset(preset.id)}>
{t('mods.presets.export')}
</button>
<button
type="button"
className="button"
disabled={disabled}
onClick={() => runAction(ipcInvoke('mods:deletePreset', { copyId: copy.id, presetId: preset.id }))}
>
{t('mods.presets.delete')}
</button>
</div>
</div>
);
})}
</div>
)}
</section>
<section className="mods-section">
<h3 className="mods-subheading">{t('mods.repo.heading')}</h3>
<p className="mods-hint">{t('mods.repo.description')}</p>
<Row
label={t('mods.repo.pathLabel')}
hint={state.isCustomModsDir ? t('mods.repo.customNote') : t('mods.repo.defaultNote')}
>
<code className="mods-path">{state.modsDir}</code>
</Row>
<div className="copy-list-actions" style={{ marginTop: 12 }}>
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
{t('mods.openFolder')}
</button>
<button type="button" className="button" disabled={disabled} onClick={pickCustomFolder}>
{t('mods.repo.changeFolder')}
</button>
{state.isCustomModsDir && (
<button type="button" className="button" disabled={disabled} onClick={resetFolder}>
{t('mods.repo.resetDefault')}
</button>
)}
</div>
</section>
</>
)}
</Sheet>
);
}
interface ModCardProps {
readonly mod: ModListItem;
readonly index: number;
readonly total: number;
readonly enabled: boolean;
readonly expanded: boolean;
readonly disabled: boolean;
readonly canDrag: boolean;
readonly language: string;
readonly issues: readonly ModIssueView[];
readonly onToggle: (next: boolean) => void;
readonly onMove: (delta: -1 | 1) => void;
readonly onToggleExpand: () => void;
readonly onDragStart: () => void;
readonly onDrop: (event: DragEvent<HTMLDivElement>) => void;
}
function ModCard({
mod,
index,
total,
enabled,
expanded,
disabled,
canDrag,
language,
issues,
onToggle,
onMove,
onToggleExpand,
onDragStart,
onDrop,
}: ModCardProps) {
const { t } = useTranslation();
const displayName = localized(mod.name, language) || mod.id;
const description = localized(mod.description, language);
const errorCount = issues.filter((i) => i.severity === 'error').length;
const warnCount = issues.filter((i) => i.severity === 'warning').length;
return (
<div
className={`mods-card${enabled ? ' mods-card-enabled' : ''}`}
draggable={canDrag}
onDragStart={onDragStart}
onDragOver={(event) => { if (canDrag) event.preventDefault(); }}
onDrop={onDrop}
>
<div className="mods-card-row">
<span className="mods-order-num" title={t('mods.loadOrderHint')}>#{index + 1}</span>
<input
type="checkbox"
className="mods-checkbox"
checked={enabled}
disabled={disabled}
aria-label={displayName}
onChange={(event) => onToggle(event.target.checked)}
/>
<div className="mods-card-main" onClick={onToggleExpand}>
<div className="mods-card-title">
<span className="mods-name">{displayName}</span>
<span className="mods-version">v{mod.version}</span>
<span className="mods-author">· {mod.author}</span>
<div className="mods-badges">
{mod.badges.map((badge) => (
<span key={badge} className={`mods-badge mods-badge-${badge}`}>
{t(`mods.badges.${badge}`)}
</span>
))}
{errorCount > 0 && <span className="mods-badge mods-badge-error">{t('mods.errorCount', { count: errorCount })}</span>}
{warnCount > 0 && <span className="mods-badge mods-badge-warn">{t('mods.warnCount', { count: warnCount })}</span>}
</div>
</div>
{description && <div className="mods-card-desc">{description}</div>}
</div>
<div className="mods-card-actions">
<button
type="button"
className="button mods-move-btn"
disabled={disabled || index <= 0}
title={t('mods.moveUp')}
onClick={() => onMove(-1)}
>
↑
</button>
<button
type="button"
className="button mods-move-btn"
disabled={disabled || index < 0 || index >= total - 1}
title={t('mods.moveDown')}
onClick={() => onMove(1)}
>
↓
</button>
<button type="button" className="button" onClick={onToggleExpand}>
{expanded ? t('mods.hideDetails') : t('mods.showDetails')}
</button>
</div>
</div>
{expanded && (
<div className="mods-card-details">
<div className="mods-detail-grid">
<div><span>ID:</span> <code>{mod.id}</code></div>
<div><span>API:</span> <code>{mod.apiVersion}</code></div>
<div><span>{t('mods.details.folder')}:</span> <code>{mod.folderName}</code></div>
{mod.gameVersions.length > 0 && (
<div><span>{t('mods.details.gameVersions')}:</span> <code>{mod.gameVersions.join(', ')}</code></div>
)}
{mod.requires.length > 0 && (
<div><span>{t('mods.details.requires')}:</span> <code>{mod.requires.join(', ')}</code></div>
)}
{mod.conflicts.length > 0 && (
<div><span>{t('mods.details.conflicts')}:</span> <code>{mod.conflicts.join(', ')}</code></div>
)}
</div>
<div className="mods-detail-summary">
{mod.serverTuningFiles.length > 0 && (
<span>{t('mods.details.tuning', { count: mod.serverTuningFiles.length })}</span>
)}
{mod.hasServerScript && <span>{t('mods.details.serverScript')}</span>}
{mod.packOperations.length > 0 && (
<span>{t('mods.details.packOps', { count: mod.packOperations.length })}</span>
)}
{mod.hasClientAddon && (
<span>{t('mods.details.addon', { count: mod.addonFileCount })}</span>
)}
{mod.guiPatchCount > 0 && (
<span>{t('mods.details.guiPatches', { count: mod.guiPatchCount })}</span>
)}
{mod.exePatchCount > 0 && (
<span>{t('mods.details.exePatches', { count: mod.exePatchCount })}</span>
)}
{mod.clientFileCount > 0 && (
<span>{t('mods.details.companionFiles', { count: mod.clientFileCount })}</span>
)}
{mod.hasConfigBlkPatch && <span>{t('mods.details.configBlk')}</span>}
</div>
</div>
)}
</div>
);
}
@@ -11,7 +11,7 @@ interface Props {
readonly onError: (error: unknown) => void; readonly onError: (error: unknown) => void;
} }
const ACTIONS = ['research', 'purchase', 'equipment'] as const; const ACTIONS = ['purchase', 'equipment'] as const;
export function SaveResearch({ copyId, userId, readOnly, onError }: Props) { export function SaveResearch({ copyId, userId, readOnly, onError }: Props) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
@@ -11,7 +11,7 @@ type Field = keyof TuningValues;
type Draft = Partial<Record<Field, string | boolean>>; type Draft = Partial<Record<Field, string | boolean>>;
const fields = { const fields = {
rewards: ['rewardMultiplierSilverLions', 'rewardMultiplierResearchPoints', 'friendlyKillPenaltyMul'], rewards: ['rewardMultiplierSilverLions', 'rewardMultiplierResearchPoints', 'friendlyKillPenaltyMul'],
battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'tankBotRespawns', 'airBotRespawns', 'strikeUcavSpawnScore'], battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'tankBotRespawns', 'airBotRespawns', 'strikeUcavSpawnScore', 'nuclearEscalationStrategicBombers'],
newProfile: ['silverLions', 'goldenEagles'], newProfile: ['silverLions', 'goldenEagles'],
research: ['preferLineSuccessor', 'autoTargetPick'], research: ['preferLineSuccessor', 'autoTargetPick'],
} as const satisfies Record<TuningSection, readonly Field[]>; } as const satisfies Record<TuningSection, readonly Field[]>;
@@ -70,7 +70,7 @@ export function TuningPage({ copy, section, onError }: Props) {
const editor = (field: Field): ReactNode => { const editor = (field: Field): ReactNode => {
const active = draft[field] ?? inputValue(field, loaded.effective[field]); const active = draft[field] ?? inputValue(field, loaded.effective[field]);
const label = t(`tuning.fields.${field}`); const label = t(`tuning.fields.${field}`);
if (field === 'preferLineSuccessor') { if (typeof loaded.defaults[field] === 'boolean') {
return <input type="checkbox" aria-label={label} disabled={saving} checked={active === true} onChange={(event) => set(field, event.target.checked)} />; return <input type="checkbox" aria-label={label} disabled={saving} checked={active === true} onChange={(event) => set(field, event.target.checked)} />;
} }
if (field === 'autoTargetPick') { if (field === 'autoTargetPick') {
@@ -1,9 +1,8 @@
/** /**
* The window's pages and the sections of those that have a section list in the side panel. * The window's pages and the sections of those that have a section list in the side panel.
* Pages for later features (saves, tuning) join this list when they are built.
*/ */
export const PAGES = ['home', 'saves', 'tuning', 'copies', 'settings', 'about'] as const; export const PAGES = ['home', 'saves', 'tuning', 'mods', 'copies', 'settings', 'about'] as const;
export type PageId = (typeof PAGES)[number]; export type PageId = (typeof PAGES)[number];
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const; export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const;
@@ -12,6 +11,9 @@ export type SaveSection = (typeof SAVE_SECTIONS)[number];
export const TUNING_SECTIONS = ['rewards', 'battle', 'newProfile', 'research'] as const; export const TUNING_SECTIONS = ['rewards', 'battle', 'newProfile', 'research'] as const;
export type TuningSection = (typeof TUNING_SECTIONS)[number]; export type TuningSection = (typeof TUNING_SECTIONS)[number];
export const MODS_SECTIONS = ['list', 'presets'] as const;
export type ModsSection = (typeof MODS_SECTIONS)[number];
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const; export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
export type CopySection = (typeof COPY_SECTIONS)[number]; export type CopySection = (typeof COPY_SECTIONS)[number];
@@ -23,16 +25,25 @@ export interface Route {
readonly copies: CopySection; readonly copies: CopySection;
readonly saves: SaveSection; readonly saves: SaveSection;
readonly tuning: TuningSection; readonly tuning: TuningSection;
readonly mods: ModsSection;
readonly settings: SettingsSection; readonly settings: SettingsSection;
} }
export const START_ROUTE: Route = { page: 'home', saves: 'list', tuning: 'rewards', copies: 'list', settings: 'general' }; export const START_ROUTE: Route = {
page: 'home',
saves: 'list',
tuning: 'rewards',
mods: 'list',
copies: 'list',
settings: 'general',
};
/** Where a link points: a page, and for pages with sections, which one. */ /** Where a link points: a page, and for pages with sections, which one. */
export type Destination = export type Destination =
| { readonly page: 'home' | 'about' } | { readonly page: 'home' | 'about' }
| { readonly page: 'saves'; readonly section?: SaveSection } | { readonly page: 'saves'; readonly section?: SaveSection }
| { readonly page: 'tuning'; readonly section?: TuningSection } | { readonly page: 'tuning'; readonly section?: TuningSection }
| { readonly page: 'mods'; readonly section?: ModsSection }
| { readonly page: 'copies'; readonly section?: CopySection } | { readonly page: 'copies'; readonly section?: CopySection }
| { readonly page: 'settings'; readonly section?: SettingsSection }; | { readonly page: 'settings'; readonly section?: SettingsSection };
@@ -42,6 +53,8 @@ export function navigate(route: Route, to: Destination): Route {
return { ...route, page: 'saves', saves: to.section ?? route.saves }; return { ...route, page: 'saves', saves: to.section ?? route.saves };
case 'tuning': case 'tuning':
return { ...route, page: 'tuning', tuning: to.section ?? route.tuning }; return { ...route, page: 'tuning', tuning: to.section ?? route.tuning };
case 'mods':
return { ...route, page: 'mods', mods: to.section ?? route.mods };
case 'copies': case 'copies':
return { ...route, page: 'copies', copies: to.section ?? route.copies }; return { ...route, page: 'copies', copies: to.section ?? route.copies };
case 'settings': case 'settings':
@@ -215,9 +215,13 @@
/* ===== Buttons and links ===== */ /* ===== Buttons and links ===== */
.button { .button {
display: inline-flex;
align-items: center;
justify-content: center;
font: 500 14px var(--font-display); font: 500 14px var(--font-display);
letter-spacing: 0.04em; letter-spacing: 0.04em;
text-transform: uppercase; text-transform: uppercase;
text-decoration: none;
padding: 7px 16px; padding: 7px 16px;
cursor: pointer; cursor: pointer;
white-space: nowrap; white-space: nowrap;
@@ -371,3 +371,461 @@
line-height: 1.6; line-height: 1.6;
color: var(--text-dim); color: var(--text-dim);
} }
.about-columns {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
align-items: start;
}
.about-column {
display: flex;
flex-direction: column;
gap: 14px;
min-width: 0;
}
.about-card {
min-width: 0;
padding: 14px 16px;
background: rgba(0, 0, 0, 0.14);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.about-card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
flex-wrap: wrap;
}
.about-card-title {
margin: 0;
font: 500 14px var(--font-display);
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--white);
}
.about-card-actions {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.about-card-meta {
margin: 8px 0 0;
font-size: 13px;
line-height: 1.5;
color: var(--text);
}
.about-card-label {
color: var(--text-dim);
}
.about-card .notice {
margin-top: 10px;
}
.about-card .notice .button {
margin-top: 8px;
}
/* ===== Mods ===== */
.mods-aside {
display: inline-flex;
align-items: center;
gap: 10px;
}
.mods-exp-chip {
position: relative;
display: inline-flex;
align-items: center;
gap: 5px;
padding: 2px 7px;
font-size: 11.5px;
line-height: 1.3;
color: rgba(255, 227, 163, 0.9);
background: rgba(214, 158, 46, 0.14);
border: 1px solid rgba(214, 158, 46, 0.38);
border-radius: var(--radius);
cursor: help;
user-select: none;
}
.mods-exp-chip:hover,
.mods-exp-chip:focus-visible {
background: rgba(214, 158, 46, 0.22);
border-color: rgba(214, 158, 46, 0.6);
outline: none;
}
.mods-exp-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
font-size: 10px;
font-weight: 700;
font-style: normal;
border-radius: 50%;
border: 1px solid rgba(255, 227, 163, 0.55);
}
.mods-exp-popover {
position: absolute;
top: calc(100% + 8px);
right: 0;
z-index: 40;
width: 340px;
max-width: min(340px, 70vw);
display: flex;
flex-direction: column;
gap: 4px;
padding: 10px 12px;
font-size: 12px;
line-height: 1.5;
text-align: left;
white-space: normal;
color: rgba(255, 244, 218, 0.94);
background: rgba(16, 20, 24, 0.97);
border: 1px solid rgba(214, 158, 46, 0.5);
border-radius: var(--radius);
box-shadow: 0 10px 26px rgba(0, 0, 0, 0.55);
opacity: 0;
visibility: hidden;
pointer-events: none;
transform: translateY(-2px);
transition: opacity 140ms ease, transform 140ms ease, visibility 140ms ease;
}
.mods-exp-chip:hover .mods-exp-popover,
.mods-exp-chip:focus-visible .mods-exp-popover {
opacity: 1;
visibility: visible;
transform: translateY(0);
}
.mods-banner {
display: flex;
flex-direction: column;
gap: 3px;
padding: 10px 12px;
margin-bottom: 12px;
font-size: 12.5px;
line-height: 1.5;
border: 1px solid var(--line);
border-radius: var(--radius);
}
.mods-banner-warn {
background: rgba(206, 65, 55, 0.16);
border-color: rgba(206, 65, 55, 0.5);
color: #ffd7d4;
}
.mods-banner-ok {
background: rgba(68, 170, 102, 0.16);
border-color: rgba(68, 170, 102, 0.5);
color: #d7ffe4;
}
.mods-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
.mods-search {
flex: 1 1 180px;
min-width: 140px;
}
.mods-preset-select {
max-width: 210px;
}
.mods-issues-box {
padding: 10px 12px;
margin-bottom: 12px;
font-size: 12.5px;
border-radius: var(--radius);
border: 1px solid var(--line);
}
.mods-issues-error {
background: rgba(206, 65, 55, 0.15);
border-color: rgba(206, 65, 55, 0.55);
}
.mods-issues-warn {
background: rgba(214, 158, 46, 0.13);
border-color: rgba(214, 158, 46, 0.45);
}
.mods-issues-title {
font-weight: 600;
margin-bottom: 6px;
}
.mods-issues-box ul {
margin: 0;
padding-left: 18px;
display: flex;
flex-direction: column;
gap: 4px;
}
.mods-issue-tag {
display: inline-block;
margin-right: 6px;
padding: 1px 5px;
font-size: 11px;
border-radius: 2px;
background: rgba(255, 255, 255, 0.12);
}
.mods-empty {
padding: 20px 14px;
text-align: center;
border: 1px dashed var(--line);
border-radius: var(--radius);
}
.mods-hint {
font-size: 12.5px;
color: var(--text-dim);
line-height: 1.5;
margin: 6px 0 12px;
}
.mods-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.mods-card {
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(12, 16, 19, 0.62);
transition: border-color 120ms ease;
}
.mods-card-enabled {
border-left: 3px solid var(--red);
background: rgba(18, 24, 29, 0.78);
}
.mods-card-row {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
}
.mods-order-num {
min-width: 26px;
font-size: 12px;
color: var(--text-dim);
text-align: right;
cursor: grab;
}
.mods-checkbox {
width: 16px;
height: 16px;
flex: none;
cursor: pointer;
}
.mods-card-main {
flex: 1;
min-width: 0;
cursor: pointer;
}
.mods-card-title {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.mods-name {
font-weight: 600;
color: var(--white);
}
.mods-version,
.mods-author {
font-size: 12px;
color: var(--text-dim);
}
.mods-card-desc {
margin-top: 3px;
font-size: 12px;
color: var(--text-dim);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.mods-badges {
display: inline-flex;
flex-wrap: wrap;
gap: 4px;
}
.mods-badge {
padding: 1px 6px;
font-size: 11px;
border-radius: 2px;
border: 1px solid rgba(255, 255, 255, 0.16);
}
.mods-badge-data {
background: rgba(88, 166, 255, 0.16);
color: #b7d7ff;
}
.mods-badge-gui {
background: rgba(163, 113, 247, 0.18);
color: #dec8ff;
}
.mods-badge-script {
background: rgba(214, 158, 46, 0.22);
color: #ffe3a3;
}
.mods-badge-exe {
background: rgba(206, 65, 55, 0.28);
color: #ffc2be;
border-color: rgba(206, 65, 55, 0.55);
}
.mods-badge-error {
background: rgba(206, 65, 55, 0.35);
color: #ffd5d2;
}
.mods-badge-warn {
background: rgba(214, 158, 46, 0.25);
color: #ffe8b3;
}
.mods-card-actions {
display: flex;
align-items: center;
gap: 4px;
flex: none;
}
.mods-move-btn {
min-width: 28px;
padding: 4px 6px;
}
.mods-card-details {
padding: 10px 12px 12px 48px;
border-top: 1px solid var(--line);
font-size: 12px;
color: var(--text-dim);
}
.mods-detail-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 4px 12px;
margin-bottom: 8px;
}
.mods-detail-summary {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.mods-detail-summary span {
padding: 2px 7px;
border-radius: 2px;
background: rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.85);
}
.mods-section {
margin-bottom: 22px;
}
.mods-subheading {
margin: 0 0 4px;
font: 600 15px var(--font-display);
color: var(--white);
}
.mods-preset-form {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 10px 0 14px;
}
.mods-preset-form .input {
flex: 1 1 200px;
}
.mods-preset-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.mods-preset-item {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(12, 16, 19, 0.62);
}
.mods-preset-active {
border-left: 3px solid var(--red);
}
.mods-preset-meta {
min-width: 0;
}
.mods-preset-name {
display: flex;
align-items: center;
gap: 8px;
font-weight: 600;
color: var(--white);
}
.mods-preset-sub {
font-size: 12px;
color: var(--text-dim);
margin-top: 2px;
}
.mods-path {
font-size: 12px;
word-break: break-all;
}
+5
View File
@@ -24,6 +24,11 @@ export const APP_ERROR_CODES = [
'diagnostics_export_failed', 'diagnostics_export_failed',
'copy_not_found', 'copy_not_found',
'tuning_invalid', 'tuning_invalid',
'mods_read_only',
'mods_write_failed',
'mods_preset_invalid',
'mods_blocking_issues',
'mods_folder_invalid',
'save_not_found', 'save_not_found',
'save_archive_invalid', 'save_archive_invalid',
'save_official_invalid', 'save_official_invalid',
+2
View File
@@ -16,6 +16,8 @@ export const IPC_CHANNEL_PREFIXES = [
'copies:', 'copies:',
/** Settings shared by the saves of a game copy. */ /** Settings shared by the saves of a game copy. */
'tuning:', 'tuning:',
/** Additive mods repository, per-copy ordering/toggles, and presets. */
'mods:',
/** Local account and save management. */ /** Local account and save management. */
'saves:', 'saves:',
/** Starting and stopping the active copy. */ /** Starting and stopping the active copy. */
+50 -1
View File
@@ -17,6 +17,7 @@ import {
} from '../schemas/install.ts'; } from '../schemas/install.ts';
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts'; import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts'; import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
import { ModsStateViewSchema } from '../schemas/mods.ts';
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts'; import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts';
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts'; import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts'; import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
@@ -154,6 +155,10 @@ export const ipcContract = {
input: z.object({ id: CopyIdSchema }), input: z.object({ id: CopyIdSchema }),
output: MaintenanceInfoSchema, output: MaintenanceInfoSchema,
}, },
'copies:maintenanceState': {
input: z.void(),
output: MaintenanceProgressSchema.nullable(),
},
'copies:maintain': { 'copies:maintain': {
input: MaintenanceRequestSchema, input: MaintenanceRequestSchema,
output: CopiesSchema, output: CopiesSchema,
@@ -258,6 +263,50 @@ export const ipcContract = {
input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }), input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }),
output: TuningViewSchema, output: TuningViewSchema,
}, },
'mods:getState': {
input: z.object({ copyId: CopyIdSchema }),
output: ModsStateViewSchema,
},
'mods:setEnabled': {
input: z.object({ copyId: CopyIdSchema, modId: z.string().min(1), enabled: z.boolean() }),
output: ModsStateViewSchema,
},
'mods:setOrder': {
input: z.object({ copyId: CopyIdSchema, order: z.array(z.string()) }),
output: ModsStateViewSchema,
},
'mods:autoSort': {
input: z.object({ copyId: CopyIdSchema }),
output: ModsStateViewSchema,
},
'mods:savePreset': {
input: z.object({ copyId: CopyIdSchema, name: z.string().trim().min(1).max(80), overwriteId: z.string().min(1).optional() }),
output: ModsStateViewSchema,
},
'mods:applyPreset': {
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
output: ModsStateViewSchema,
},
'mods:deletePreset': {
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
output: ModsStateViewSchema,
},
'mods:exportPreset': {
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
output: z.object({ path: z.string().nullable() }),
},
'mods:importPreset': {
input: z.object({ copyId: CopyIdSchema }),
output: z.object({ imported: z.boolean(), state: ModsStateViewSchema }),
},
'mods:openFolder': {
input: z.void(),
output: z.void(),
},
'mods:setFolder': {
input: z.object({ copyId: CopyIdSchema, path: z.string().min(1).nullable() }),
output: ModsStateViewSchema,
},
'launch:getState': { 'launch:getState': {
input: z.void(), input: z.void(),
output: LaunchStateSchema, output: LaunchStateSchema,
@@ -334,7 +383,7 @@ export const ipcEvents = {
'event:app-update-progress': AppUpdateProgressSchema, 'event:app-update-progress': AppUpdateProgressSchema,
'event:launch-state': LaunchStateSchema, 'event:launch-state': LaunchStateSchema,
'event:copies-changed': CopiesSchema, 'event:copies-changed': CopiesSchema,
'event:copy-maintenance': MaintenanceProgressSchema, 'event:copy-maintenance': MaintenanceProgressSchema.nullable(),
/** Another patch set became active (a pack was installed, or the bundled set restored). */ /** Another patch set became active (a pack was installed, or the bundled set restored). */
'event:patch-set-changed': ActivePatchSetSchema, 'event:patch-set-changed': ActivePatchSetSchema,
} as const; } as const;
+87
View File
@@ -0,0 +1,87 @@
import { z } from 'zod';
export const ModRiskBadgeSchema = z.enum(['data', 'gui', 'script', 'exe']);
export const ModIssueSeveritySchema = z.enum(['error', 'warning', 'info']);
export const LocalizedTextSchema = z.union([z.string(), z.record(z.string(), z.string())]);
export const ModPackOperationSchema = z.object({
pack: z.string(),
targetPath: z.string(),
action: z.enum(['blk-patch', 'csv-patch', 'file']),
sourceRelativePath: z.string(),
});
export const ModListItemSchema = z.object({
id: z.string(),
folderName: z.string(),
rootDir: z.string(),
name: LocalizedTextSchema,
description: LocalizedTextSchema.optional(),
version: z.string(),
author: z.string(),
apiVersion: z.string(),
gameVersions: z.array(z.string()),
requires: z.array(z.string()),
conflicts: z.array(z.string()),
loadAfter: z.array(z.string()),
loadBefore: z.array(z.string()),
badges: z.array(ModRiskBadgeSchema),
hasServerScript: z.boolean(),
serverTuningFiles: z.array(z.string()),
packOperations: z.array(ModPackOperationSchema),
guiPatchCount: z.number().int().nonnegative(),
exePatchCount: z.number().int().nonnegative(),
hasClientAddon: z.boolean(),
addonFileCount: z.number().int().nonnegative(),
clientFileCount: z.number().int().nonnegative(),
hasConfigBlkPatch: z.boolean(),
});
export const ModDiscoveryErrorSchema = z.object({
folderName: z.string(),
rootDir: z.string(),
reason: z.string(),
});
export const ModIssueSchema = z.object({
severity: ModIssueSeveritySchema,
kind: z.string(),
modId: z.string(),
otherModId: z.string().optional(),
detail: z.string(),
});
export const ModPresetSchema = z.object({
id: z.string().min(1),
name: z.string().min(1).max(80),
order: z.array(z.string()),
enabled: z.record(z.string(), z.boolean()),
updatedAt: z.string(),
});
export const ModsStateViewSchema = z.object({
modsDir: z.string(),
defaultModsDir: z.string(),
isCustomModsDir: z.boolean(),
apiVersion: z.string(),
mods: z.array(ModListItemSchema),
discoveryErrors: z.array(ModDiscoveryErrorSchema),
order: z.array(z.string()),
enabled: z.record(z.string(), z.boolean()),
activePresetId: z.string().nullable(),
presets: z.array(ModPresetSchema),
issues: z.array(ModIssueSchema),
hasBlockingErrors: z.boolean(),
});
export const ModPresetTransferSchema = z.object({
format: z.literal(1),
name: z.string().min(1).max(80),
order: z.array(z.string()),
enabled: z.record(z.string(), z.boolean()),
});
export type ModListItem = z.output<typeof ModListItemSchema>;
export type ModPresetView = z.output<typeof ModPresetSchema>;
export type ModIssueView = z.output<typeof ModIssueSchema>;
export type ModsStateView = z.output<typeof ModsStateViewSchema>;
+1 -1
View File
@@ -94,7 +94,7 @@ export const OfficialPreviewSchema = z.object({
omitted: z.array(z.string()), omitted: z.array(z.string()),
}); });
export const ResearchBranchSchema = z.object({ country: z.string().min(1), type: z.string().min(1) }); export const ResearchBranchSchema = z.object({ country: z.string().min(1), type: z.string().min(1) });
export const ResearchOperationSchema = z.enum(['research', 'purchase', 'equipment']); export const ResearchOperationSchema = z.enum(['purchase', 'equipment']);
export const SaveResearchSchema = z.object({ export const SaveResearchSchema = z.object({
branches: z.array(ResearchBranchSchema), branches: z.array(ResearchBranchSchema),
selected: ResearchBranchSchema.nullable(), selected: ResearchBranchSchema.nullable(),
@@ -37,6 +37,8 @@ export const SettingsSchema = z.object({
developerMode: z.boolean().default(true), developerMode: z.boolean().default(true),
labStockPath: LabPathSchema.default(null), labStockPath: LabPathSchema.default(null),
labDataPath: LabPathSchema.default(null), labDataPath: LabPathSchema.default(null),
/** Custom global mods repository directory; null uses `<userData>/mods`. */
modsFolder: LabPathSchema.default(null),
}); });
export type Settings = z.output<typeof SettingsSchema>; export type Settings = z.output<typeof SettingsSchema>;
@@ -60,6 +62,7 @@ export const SettingsPatchSchema = z.object({
developerMode: z.boolean().optional(), developerMode: z.boolean().optional(),
labStockPath: LabPathSchema.optional(), labStockPath: LabPathSchema.optional(),
labDataPath: LabPathSchema.optional(), labDataPath: LabPathSchema.optional(),
modsFolder: LabPathSchema.optional(),
}); });
export type SettingsPatch = z.output<typeof SettingsPatchSchema>; export type SettingsPatch = z.output<typeof SettingsPatchSchema>;
@@ -12,6 +12,7 @@ export const TuningValuesSchema = z.object({
tankBotRespawns: z.number().int().min(1).max(10), tankBotRespawns: z.number().int().min(1).max(10),
airBotRespawns: z.number().int().min(1).max(10), airBotRespawns: z.number().int().min(1).max(10),
strikeUcavSpawnScore: z.number().int().min(1).max(10000), strikeUcavSpawnScore: z.number().int().min(1).max(10000),
nuclearEscalationStrategicBombers: z.boolean(),
silverLions: z.number().int().nonnegative(), silverLions: z.number().int().nonnegative(),
goldenEagles: z.number().int().min(0).max(0x7fffffff), goldenEagles: z.number().int().min(0).max(0x7fffffff),
preferLineSuccessor: z.boolean(), preferLineSuccessor: z.boolean(),
+1
View File
@@ -9,6 +9,7 @@
"dependencies": { "dependencies": {
"@wto/blk": "*", "@wto/blk": "*",
"@wto/jsonc": "*", "@wto/jsonc": "*",
"@wto/mods": "*",
"@wto/vromfs": "*" "@wto/vromfs": "*"
} }
} }
+74 -1
View File
@@ -22,6 +22,7 @@
import { randomInt } from 'node:crypto'; import { randomInt } from 'node:crypto';
import type { import type {
BattleSpawnRulesData, BattleSpawnRulesData,
NuclearCarrierUnit,
RandomSpawnGroup, RandomSpawnGroup,
RandomSpawnUnit, RandomSpawnUnit,
SupportPlanePreset, SupportPlanePreset,
@@ -43,6 +44,8 @@ export interface ExtraBattleSlot {
/** The modifications enabled when not `allModifications`; the unit is otherwise stock. */ /** The modifications enabled when not `allModifications`; the unit is otherwise stock. */
readonly modifications: readonly string[]; readonly modifications: readonly string[];
readonly forceWeapon?: string; readonly forceWeapon?: string;
/** Restricts the respawn weapon dropdown to these presets when multiple mode presets exist. */
readonly allowedWeapons?: readonly string[];
/** The RandomSpawnUnits group the vehicle was drawn from. */ /** The RandomSpawnUnits group the vehicle was drawn from. */
readonly groupName?: string; readonly groupName?: string;
} }
@@ -56,7 +59,10 @@ export interface ExtraBattleSlotsInput {
readonly sessionMaxMrank: number; readonly sessionMaxMrank: number;
readonly vehiclesByName: ReadonlyMap<string, CatalogueVehicle>; readonly vehiclesByName: ReadonlyMap<string, CatalogueVehicle>;
readonly rules: BattleSpawnRulesData; readonly rules: BattleSpawnRulesData;
readonly tuning: Pick<BattleTuning, 'strikeUcavModes' | 'strikeUcavSessionMrankAllowance' | 'strikeUcavSpawnScore'>; readonly tuning: Pick<
BattleTuning,
'strikeUcavModes' | 'strikeUcavSessionMrankAllowance' | 'strikeUcavSpawnScore' | 'nuclearEscalationStrategicBombers'
>;
} }
export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly ExtraBattleSlot[] { export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly ExtraBattleSlot[] {
@@ -68,6 +74,7 @@ export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly E
if (supportPlane) supportSlots.push(supportPlane); if (supportPlane) supportSlots.push(supportPlane);
const ucav = strikeUcavSlot(input); const ucav = strikeUcavSlot(input);
if (ucav) supportSlots.push(ucav); if (ucav) supportSlots.push(ucav);
supportSlots.push(...nuclearEscalationSlots(input));
// Keep room for fixed support vehicles while displaying random vehicle groups first. // Keep room for fixed support vehicles while displaying random vehicle groups first.
const slots: ExtraBattleSlot[] = []; const slots: ExtraBattleSlot[] = [];
@@ -118,6 +125,72 @@ function strikeUcavSlot(input: ExtraBattleSlotsInput): ExtraBattleSlot | undefin
}; };
} }
const NUCLEAR_ESCALATION_TAG_PREFIX = 'nuclear_escalation_';
const GROUND_RB_SUPPORT_MODE = 'tank_event_in_random_battles_historical';
const EASTERN_STRATEGIC_BOMBER_COUNTRIES = new Set(['country_ussr', 'country_china']);
function nuclearEscalationSlots(input: ExtraBattleSlotsInput): ExtraBattleSlot[] {
if (!input.declaration.tag?.startsWith(NUCLEAR_ESCALATION_TAG_PREFIX)) return [];
const slots: ExtraBattleSlot[] = [];
const tactical = selectTacticalNuclearCarrier(input);
if (tactical) {
const weaponNames = tactical.weapons.map((weapon) => weapon.name);
slots.push({
unitName: tactical.unitName,
allModifications: true,
modifications: [],
...(weaponNames.length === 1 ? { forceWeapon: weaponNames[0]! } : { allowedWeapons: weaponNames }),
});
}
if (input.tuning.nuclearEscalationStrategicBombers) {
const strategic = selectStrategicNuclearBomber(input.country, input.rules.nuclearEscalationStrategicBombers);
if (strategic) {
const weapon = strategic.weapons[0];
slots.push({
unitName: strategic.unitName,
allModifications: true,
modifications: [],
...(weapon ? { forceWeapon: weapon.name } : {}),
});
}
}
return slots;
}
function selectTacticalNuclearCarrier(input: ExtraBattleSlotsInput): NuclearCarrierUnit | undefined {
const byCountry = input.rules.nuclearEscalationTacticalCarriers.filter((entry) => entry.country === input.country);
if (byCountry.length === 0) return undefined;
// Prefer the stock Ground RB nuclear carrier for the matching rank bracket when it carries
// Nuclear Escalation 5 kt / 30 kt presets; otherwise pick the country's closest-mrank carrier.
const groundPresets = input.rules.supportPlanes[GROUND_RB_SUPPORT_MODE] ?? [];
const bracket = groundPresets.find((p) => input.sessionMaxMrank >= p.minMrank && input.sessionMaxMrank <= p.maxMrank);
const preferredUnit = bracket?.units[input.country]?.unitName;
if (preferredUnit) {
const matched = byCountry.find((entry) => entry.unitName === preferredUnit);
if (matched) return matched;
}
return [...byCountry].sort((a, b) => {
const distA = Math.abs(a.mrank - input.sessionMaxMrank);
const distB = Math.abs(b.mrank - input.sessionMaxMrank);
if (distA !== distB) return distA - distB;
const underA = a.mrank <= input.sessionMaxMrank ? 0 : 1;
const underB = b.mrank <= input.sessionMaxMrank ? 0 : 1;
if (underA !== underB) return underA - underB;
return a.mrank - b.mrank || a.unitName.localeCompare(b.unitName);
})[0];
}
function selectStrategicNuclearBomber(
country: string,
bombers: readonly NuclearCarrierUnit[],
): NuclearCarrierUnit | undefined {
if (bombers.length === 0) return undefined;
const preferredCountry = EASTERN_STRATEGIC_BOMBER_COUNTRIES.has(country) ? 'country_ussr' : 'country_usa';
return bombers.find((entry) => entry.country === preferredCountry) ?? bombers[0];
}
/** /**
* The options of one random group: the group's vehicles inside `randomWindow`, or, when none fits, * The options of one random group: the group's vehicles inside `randomWindow`, or, when none fits,
* those of the highest rank below it. Vehicles already in the lineup are left out (offline * those of the highest rank below it. Vehicles already in the lineup are left out (offline
+44 -12
View File
@@ -10,7 +10,7 @@ import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-ru
import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts'; import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts'; import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { MISSION_DIFFICULTY, SINGLE_SPAWN } from '../game-modes/mode-definition.ts'; import { MISSION_DIFFICULTY, SINGLE_SPAWN, modeMaxRespawns } from '../game-modes/mode-definition.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts'; import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts'; import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts';
import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts'; import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts';
@@ -37,6 +37,7 @@ export interface EnqueueBattleInput {
readonly modes?: readonly OfferedGameMode[]; readonly modes?: readonly OfferedGameMode[];
readonly country: string; readonly country: string;
readonly slotVehicles: readonly string[]; readonly slotVehicles: readonly string[];
readonly mrankDeltas: ReadonlyMap<string, number>;
readonly selectedSlot?: BattleCrewSlot; readonly selectedSlot?: BattleCrewSlot;
readonly bannedMissions: ReadonlySet<string>; readonly bannedMissions: ReadonlySet<string>;
readonly dislikedMissions: ReadonlySet<string>; readonly dislikedMissions: ReadonlySet<string>;
@@ -46,10 +47,12 @@ export interface BattleLaunchPlan {
readonly sessionId: string; readonly sessionId: string;
readonly modeId: number; readonly modeId: number;
readonly modeName: string; readonly modeName: string;
readonly modeTag?: string;
readonly economicName: string; readonly economicName: string;
readonly missionName: string; readonly missionName: string;
/** The mission as the game describes it, including the parameters copied into the mission settings. */ /** The mission as the game describes it, including the parameters copied into the mission settings. */
readonly mission: MissionHeader; readonly mission: MissionHeader;
readonly missionRuleKeys: readonly string[];
readonly missionFile: string; readonly missionFile: string;
readonly missionType: string; readonly missionType: string;
readonly level?: string; readonly level?: string;
@@ -67,6 +70,7 @@ export interface BattleLaunchPlan {
readonly maxMrank: number; readonly maxMrank: number;
readonly maxPlayers: number; readonly maxPlayers: number;
readonly maxBots: number; readonly maxBots: number;
readonly maxRespawns?: number;
readonly tankBotRespawns: number; readonly tankBotRespawns: number;
readonly airBotRespawns: number; readonly airBotRespawns: number;
readonly useTankBots: boolean; readonly useTankBots: boolean;
@@ -82,6 +86,16 @@ export type MatchmakeOutcome =
| { readonly ok: true; readonly launch: BattleLaunchPlan } | { readonly ok: true; readonly launch: BattleLaunchPlan }
| { readonly ok: false; readonly error: string }; | { readonly ok: false; readonly error: string };
export type MissionPoolFilter = (ctx: {
readonly userId: string;
readonly modeId: number;
readonly modeName: string;
readonly economicName: string;
readonly minMrank: number;
readonly maxMrank: number;
readonly missions: readonly MissionHeader[];
}) => readonly MissionHeader[];
export class BattleMatchmaker { export class BattleMatchmaker {
readonly #gameModes: GameModes; readonly #gameModes: GameModes;
readonly #vehicles: readonly CatalogueVehicle[]; readonly #vehicles: readonly CatalogueVehicle[];
@@ -90,6 +104,7 @@ export class BattleMatchmaker {
readonly #tuning: BattleTuning; readonly #tuning: BattleTuning;
readonly #spawnRules: BattleSpawnRulesData; readonly #spawnRules: BattleSpawnRulesData;
readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>; readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>;
readonly #filterMissions: MissionPoolFilter | undefined;
constructor( constructor(
gameModes: GameModes, gameModes: GameModes,
@@ -98,6 +113,7 @@ export class BattleMatchmaker {
tuning: BattleTuning, tuning: BattleTuning,
spawnRules: BattleSpawnRulesData, spawnRules: BattleSpawnRulesData,
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>, aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
filterMissions?: MissionPoolFilter,
) { ) {
this.#gameModes = gameModes; this.#gameModes = gameModes;
this.#vehicles = vehicles; this.#vehicles = vehicles;
@@ -106,6 +122,7 @@ export class BattleMatchmaker {
this.#tuning = tuning; this.#tuning = tuning;
this.#spawnRules = spawnRules; this.#spawnRules = spawnRules;
this.#aircraftLoadouts = aircraftLoadouts; this.#aircraftLoadouts = aircraftLoadouts;
this.#filterMissions = filterMissions;
} }
enqueue(input: EnqueueBattleInput): MatchmakeOutcome { enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
@@ -117,19 +134,32 @@ export class BattleMatchmaker {
(mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0, (mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0,
); );
if (pvpModes.length === 0) return { ok: false, error: 'PVE_NOT_SUPPORTED' }; if (pvpModes.length === 0) return { ok: false, error: 'PVE_NOT_SUPPORTED' };
const chosenMode = this.#pickQueuedMode(pvpModes, input.slotVehicles, input.selectedSlot?.unitName); const chosenMode = this.#pickQueuedMode(pvpModes, input);
if (!chosenMode) return { ok: false, error: 'BAD_PARAMS' }; if (!chosenMode) return { ok: false, error: 'BAD_PARAMS' };
const { declaration } = chosenMode; const { declaration } = chosenMode;
const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName); const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName);
const playerMrank = lineupMrank( const playerMrank = lineupMrank(
activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses, activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses,
input.mrankDeltas,
); );
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank); const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity; const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity;
const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank)); const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank));
const missions = twoSidedMissionsOf(chosenMode, maxMrank); const rawMissions = twoSidedMissionsOf(chosenMode, maxMrank);
if (missions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' }; if (rawMissions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
const filteredMissions = this.#filterMissions
? this.#filterMissions({
userId: input.userId,
modeId: declaration.gameModeId,
modeName: declaration.name,
economicName: declaration.economicName,
minMrank,
maxMrank,
missions: rawMissions,
})
: rawMissions;
const missions = filteredMissions.length > 0 ? filteredMissions : rawMissions;
const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions); const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions);
const coalitions = selectBattleCoalitions({ const coalitions = selectBattleCoalitions({
vehicles: this.#vehicles, vehicles: this.#vehicles,
@@ -158,14 +188,11 @@ export class BattleMatchmaker {
}; };
} }
#pickQueuedMode( #pickQueuedMode(candidates: readonly OfferedGameMode[], input: EnqueueBattleInput): OfferedGameMode | undefined {
candidates: readonly OfferedGameMode[], const pool = candidates.filter((mode) => isModeEligibleForLineup(
slotVehicles: readonly string[], mode.declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName, input.mrankDeltas,
selectedSlotVehicle: string | undefined, ));
): OfferedGameMode | undefined { if (pool.length === 0) return undefined;
const pool = candidates.filter((mode) =>
isModeEligibleForLineup(mode.declaration, slotVehicles, selectedSlotVehicle, this.#vehiclesByName));
if (pool.length === 0) return candidates.find((mode) => mode.declaration.multiSlot !== false);
const classics = pool.filter((mode) => !mode.declaration.tag); const classics = pool.filter((mode) => !mode.declaration.tag);
const subModes = pool.filter((mode) => Boolean(mode.declaration.tag)); const subModes = pool.filter((mode) => Boolean(mode.declaration.tag));
if (subModes.length > 0 && classics.length > 0) { if (subModes.length > 0 && classics.length > 0) {
@@ -190,12 +217,14 @@ export class BattleMatchmaker {
const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers; const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers;
const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers)); const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers));
const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1)); const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1));
const maxRespawns = modeMaxRespawns(declaration);
const missionLocName = resolveMissionLocName(mission); const missionLocName = resolveMissionLocName(mission);
const environment = declaration.environmentOverride ?? mission.environment; const environment = declaration.environmentOverride ?? mission.environment;
const session = this.#sessions.create({ const session = this.#sessions.create({
userId: input.userId, userId: input.userId,
modeId: declaration.gameModeId, modeId: declaration.gameModeId,
modeName: declaration.name, modeName: declaration.name,
...(declaration.tag !== undefined ? { modeTag: declaration.tag } : {}),
economicName: declaration.economicName, economicName: declaration.economicName,
difficulty: declaration.difficulty, difficulty: declaration.difficulty,
requiredClass: declaration.requiredClass, requiredClass: declaration.requiredClass,
@@ -222,9 +251,11 @@ export class BattleMatchmaker {
sessionId: session.sessionId, sessionId: session.sessionId,
modeId: declaration.gameModeId, modeId: declaration.gameModeId,
modeName: declaration.name, modeName: declaration.name,
...(declaration.tag !== undefined ? { modeTag: declaration.tag } : {}),
economicName: declaration.economicName, economicName: declaration.economicName,
missionName: mission.name, missionName: mission.name,
mission, mission,
missionRuleKeys: declaration.missionRuleKeys ?? [],
missionFile: mission.path, missionFile: mission.path,
missionType: mission.type ?? 'domination', missionType: mission.type ?? 'domination',
...(mission.level !== undefined ? { level: mission.level } : {}), ...(mission.level !== undefined ? { level: mission.level } : {}),
@@ -242,6 +273,7 @@ export class BattleMatchmaker {
maxMrank, maxMrank,
maxPlayers, maxPlayers,
maxBots, maxBots,
...(maxRespawns === undefined ? {} : { maxRespawns }),
tankBotRespawns: this.#tuning.tankBotRespawns, tankBotRespawns: this.#tuning.tankBotRespawns,
airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns, airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns,
useTankBots: allowedSet.has('tank'), useTankBots: allowedSet.has('tank'),
@@ -7,8 +7,8 @@
* copied here from the mission file, base values first and then the sub-block for the battle's * copied here from the mission file, base values first and then the sub-block for the battle's
* difficulty. `_gameMode` is left to the client, which takes it from its own native constants. * difficulty. `_gameMode` is left to the client, which takes it from its own native constants.
*/ */
import { emptyBlock, ensureBlock, setParam, appendParam, type BlkBlock, type BlkParam, type BlkValue } from '@wto/blk'; import { emptyBlock, ensureBlock, findParam, setParam, appendParam, type BlkBlock, type BlkParam, type BlkValue } from '@wto/blk';
import { SINGLE_SPAWN } from '../game-modes/mode-definition.ts'; import { UNLIMITED_RESPAWNS } from '../game-modes/mode-definition.ts';
import type { ExtraBattleSlot } from './battle-extra-slots.ts'; import type { ExtraBattleSlot } from './battle-extra-slots.ts';
import type { BattleLaunchPlan } from './battle-matchmaker.ts'; import type { BattleLaunchPlan } from './battle-matchmaker.ts';
import type { CustomBotsPool } from './battle-ranks.ts'; import type { CustomBotsPool } from './battle-ranks.ts';
@@ -23,12 +23,13 @@ const RULE_KEYS: readonly string[] = [
'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul', 'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul',
'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec', 'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec',
'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord', 'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord',
'allowedKillStreaks',
]; ];
/** Game type switches of a versus battle with tickets, capture zones and session rewards. */ /** Game type switches of a versus battle with tickets, capture zones and session rewards. */
const VERSUS_SWITCHES: readonly string[] = [ const VERSUS_SWITCHES: readonly string[] = [
'gt_versus', 'gt_mp_tickets', 'gt_mp_capture', 'gt_use_wp', 'gt_use_xp', 'gt_use_stats', 'gt_use_unlocks', 'gt_versus', 'gt_mp_tickets', 'gt_mp_capture', 'gt_use_wp', 'gt_use_xp', 'gt_use_stats', 'gt_use_unlocks',
'isLimitedAmmo', 'allowUseArtillerySupport', 'isBotsAllowed', 'autoBalance', 'allowUseArtillerySupport', 'isBotsAllowed', 'autoBalance',
]; ];
/** /**
@@ -39,6 +40,13 @@ const VERSUS_SWITCHES: readonly string[] = [
export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<Record<string, number>>): BlkBlock { export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<Record<string, number>>): BlkBlock {
const settings = emptyBlock(); const settings = emptyBlock();
copyMissionParams(settings, plan); copyMissionParams(settings, plan);
// Enable Ground Arcade air events when the mission allows killstreaks; the LocalMP host preserves
// MissionSettings.useKillStreaks across prepare_local_mission (local_mp_air_events.c).
const allowedKillStreaks = findParam(settings, 'allowedKillStreaks')?.value;
if (plan.modeName === 'tank_event_in_random_battles_arcade'
&& allowedKillStreaks?.type === 'bool' && allowedKillStreaks.value) {
setParam(settings, 'useKillStreaks', flag(true));
}
if (plan.level !== undefined) setParam(settings, 'level', text(plan.level)); if (plan.level !== undefined) setParam(settings, 'level', text(plan.level));
if (plan.environment !== undefined) setParam(settings, 'environment', text(plan.environment)); if (plan.environment !== undefined) setParam(settings, 'environment', text(plan.environment));
if (plan.weather !== undefined) setParam(settings, 'weather', text(plan.weather)); if (plan.weather !== undefined) setParam(settings, 'weather', text(plan.weather));
@@ -60,13 +68,19 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
setParam(settings, 'symmetricTeams', flag(plan.symmetricTeams)); setParam(settings, 'symmetricTeams', flag(plan.symmetricTeams));
setParam(settings, 'gt_mp_solo', flag(false)); setParam(settings, 'gt_mp_solo', flag(false));
for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true)); for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true));
setParam(settings, 'allowSpare', flag(!plan.selectedSlot)); // The native in-flight rearm request and its receiver both require unlimited reserve ammunition.
setParam(settings, 'isLimitedAmmo', flag(plan.modeName !== 'air_arcade'));
// MissionSettings defaults isLimitedFuel to false, which disables fuel consumption and HUD timers.
setParam(settings, 'isLimitedFuel', flag(true));
setParam(settings, 'allowSpare', flag(!plan.selectedSlot && plan.maxRespawns !== UNLIMITED_RESPAWNS));
if (plan.maxRespawns !== undefined) setParam(settings, 'maxRespawns', integer(plan.maxRespawns));
if (plan.selectedSlot) { if (plan.selectedSlot) {
setParam(settings, 'maxRespawns', integer(SINGLE_SPAWN));
setParam(settings, 'ctaInstantDecreaseTicketsWhenNoRespawn', flag(true)); setParam(settings, 'ctaInstantDecreaseTicketsWhenNoRespawn', flag(true));
// The native mission loader reads the AI limit at the top level, after its bots.blk default.
setParam(settings, 'numBotRespawns', integer(plan.airBotRespawns));
} }
// MissionSettings::load (2.61.0.37 0x126b1f4..0x126b2e6) reads global config/bots.blk defaults
// first, then overrides aircraft and tank AI respawn limits from the mission root, not customBots.
setParam(settings, 'numBotRespawns', integer(plan.airBotRespawns));
setParam(settings, 'numTankBotRespawns', integer(plan.tankBotRespawns));
setParam(settings, 'useSpawnScore', flag(plan.useSpawnScore)); setParam(settings, 'useSpawnScore', flag(plan.useSpawnScore));
setParam(settings, 'useTankBots', flag(plan.useTankBots)); setParam(settings, 'useTankBots', flag(plan.useTankBots));
setParam(settings, 'useShipBots', flag(plan.useShipBots)); setParam(settings, 'useShipBots', flag(plan.useShipBots));
@@ -88,14 +102,15 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
} }
function copyMissionParams(settings: BlkBlock, plan: BattleLaunchPlan): void { function copyMissionParams(settings: BlkBlock, plan: BattleLaunchPlan): void {
const wanted = new Set([...LOCALIZATION_KEYS, ...RULE_KEYS]); const ruleKeys = new Set([...RULE_KEYS, ...plan.missionRuleKeys]);
const wanted = new Set([...LOCALIZATION_KEYS, ...ruleKeys]);
const copy = (params: readonly BlkParam[] | undefined, keys: ReadonlySet<string>): void => { const copy = (params: readonly BlkParam[] | undefined, keys: ReadonlySet<string>): void => {
for (const param of params ?? []) { for (const param of params ?? []) {
if (keys.has(param.name)) setParam(settings, param.name, param.value); if (keys.has(param.name)) setParam(settings, param.name, param.value);
} }
}; };
copy(plan.mission.missionParams, wanted); copy(plan.mission.missionParams, wanted);
copy(plan.mission.difficultyParams[plan.difficulty], new Set(RULE_KEYS)); copy(plan.mission.difficultyParams[plan.difficulty], ruleKeys);
} }
/** Fixed spawn costs of extra slots, read back by the spawn score respondents (customSpawnScore). */ /** Fixed spawn costs of extra slots, read back by the spawn score respondents (customSpawnScore). */
@@ -115,6 +130,7 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam))); setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam)));
setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';'))); setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';')));
setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';'))); setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';')));
if (plan.maxRespawns === UNLIMITED_RESPAWNS) setParam(bots, 'wtoUnlimitedRespawns', text('1'));
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns)); setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns)); setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
setParam(bots, 'numBotRespawnsInVersus', integer(plan.airBotRespawns)); setParam(bots, 'numBotRespawnsInVersus', integer(plan.airBotRespawns));
+13 -2
View File
@@ -95,18 +95,28 @@ export function lineupMrank(
difficulty: ModeDifficulty, difficulty: ModeDifficulty,
requiredClass: UnitClass, requiredClass: UnitClass,
allowedClasses: readonly UnitClass[], allowedClasses: readonly UnitClass[],
mrankDeltas: ReadonlyMap<string, number>,
): number { ): number {
const crafts: CraftRankEntry[] = vehicleNames.flatMap((name) => { const crafts: CraftRankEntry[] = vehicleNames.flatMap((name) => {
const vehicle = byName.get(name); const vehicle = byName.get(name);
if (!vehicle) return []; if (!vehicle) return [];
return [{ return [{
unitClass: unitClassOfExpClass(vehicle.unitClass), unitClass: unitClassOfExpClass(vehicle.unitClass),
mrank: vehicleMrank(vehicle, difficulty, requiredClass), mrank: lineupVehicleMrank(vehicle, difficulty, requiredClass, mrankDeltas),
}]; }];
}); });
return maxModeMrank(crafts, requiredClass, allowedClasses); return maxModeMrank(crafts, requiredClass, allowedClasses);
} }
function lineupVehicleMrank(
vehicle: CatalogueVehicle,
difficulty: ModeDifficulty,
requiredClass: UnitClass,
mrankDeltas: ReadonlyMap<string, number>,
): number {
return vehicleMrank(vehicle, difficulty, requiredClass) + (mrankDeltas.get(vehicle.name) ?? 0);
}
export function selectCustomBots( export function selectCustomBots(
vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>, vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
): CustomBotsPool { ): CustomBotsPool {
@@ -203,6 +213,7 @@ export function isModeEligibleForLineup(
slotVehicles: readonly string[], slotVehicles: readonly string[],
selectedSlotVehicle: string | undefined, selectedSlotVehicle: string | undefined,
byName: ReadonlyMap<string, CatalogueVehicle>, byName: ReadonlyMap<string, CatalogueVehicle>,
mrankDeltas: ReadonlyMap<string, number>,
): boolean { ): boolean {
if (!declaration.tag && declaration.multiSlot !== false) return true; if (!declaration.tag && declaration.multiSlot !== false) return true;
const active = activeVehiclesForMode(declaration, slotVehicles, selectedSlotVehicle, byName); const active = activeVehiclesForMode(declaration, slotVehicles, selectedSlotVehicle, byName);
@@ -211,7 +222,7 @@ export function isModeEligibleForLineup(
const matchingCount = active.filter((name) => { const matchingCount = active.filter((name) => {
const vehicle = byName.get(name); const vehicle = byName.get(name);
if (!vehicle || unitClassOfExpClass(vehicle.unitClass) !== declaration.requiredClass) return false; if (!vehicle || unitClassOfExpClass(vehicle.unitClass) !== declaration.requiredClass) return false;
return vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass) >= minMrank; return lineupVehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass, mrankDeltas) >= minMrank;
}).length; }).length;
return matchingCount >= minCrafts; return matchingCount >= minCrafts;
} }
+2
View File
@@ -26,6 +26,7 @@ export interface BattleTuning {
readonly strikeUcavSpawnScore: number; readonly strikeUcavSpawnScore: number;
readonly tankBotRespawns: number; readonly tankBotRespawns: number;
readonly airBotRespawns: number; readonly airBotRespawns: number;
readonly nuclearEscalationStrategicBombers: boolean;
} }
export function readBattleTuning(reader: TuningReader): BattleTuning { export function readBattleTuning(reader: TuningReader): BattleTuning {
@@ -66,5 +67,6 @@ export function readBattleTuning(reader: TuningReader): BattleTuning {
strikeUcavSpawnScore: reader.int('strikeUcavSpawnScore', { min: 1, max: 10000 }), strikeUcavSpawnScore: reader.int('strikeUcavSpawnScore', { min: 1, max: 10000 }),
tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }), tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }),
airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }), airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }),
nuclearEscalationStrategicBombers: reader.bool('nuclearEscalationStrategicBombers'),
}; };
} }
+5 -1
View File
@@ -12,6 +12,7 @@ import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue
import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { ResearchRules } from '../../research/research-rules.ts'; import type { ResearchRules } from '../../research/research-rules.ts';
import type { StoreCatalogue } from '../../store/store-catalogue.ts'; import type { StoreCatalogue } from '../../store/store-catalogue.ts';
import type { TrainingCatalogue } from '../../training/training-completion.ts';
import type { UnlockShop } from '../../unlocks/unlock-purchase.ts'; import type { UnlockShop } from '../../unlocks/unlock-purchase.ts';
import type { CharActionHandler } from '../char-action.ts'; import type { CharActionHandler } from '../char-action.ts';
import { acceptEula } from './agreement-actions.ts'; import { acceptEula } from './agreement-actions.ts';
@@ -61,6 +62,7 @@ import {
buyWeaponsAction, buyWeaponsAction,
enableModificationsAction, enableModificationsAction,
saveWeaponPresetsAction, saveWeaponPresetsAction,
setUnitSelectedMrankAction,
} from './modification-actions.ts'; } from './modification-actions.ts';
import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts'; import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts';
import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts'; import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts';
@@ -93,6 +95,7 @@ export interface ActionDependencies {
readonly store: StoreCatalogue; readonly store: StoreCatalogue;
readonly inventory: InventoryCatalogue; readonly inventory: InventoryCatalogue;
readonly trophies: TrophyCatalogue; readonly trophies: TrophyCatalogue;
readonly training?: TrainingCatalogue;
readonly clans?: ClanActionDependencies; readonly clans?: ClanActionDependencies;
readonly cloudSettings?: CloudSettingsStore; readonly cloudSettings?: CloudSettingsStore;
readonly battle?: BattleActionDependencies; readonly battle?: BattleActionDependencies;
@@ -117,7 +120,7 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH
['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)], ['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)],
['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)], ['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)],
['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)], ['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)],
['cln_update', clientUpdateAction(deps.profiles, deps.accounts)], ['cln_update', clientUpdateAction(deps.profiles, deps.accounts, deps.training)],
['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)], ['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)],
['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)], ['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)],
['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.crew)], ['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.crew)],
@@ -137,6 +140,7 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH
['cln_buy_weapon', buyWeaponsAction(deps.profiles, deps.accounts, deps.equipment)], ['cln_buy_weapon', buyWeaponsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_save_weapon_presets', saveWeaponPresetsAction(deps.profiles, deps.accounts, deps.equipment)], ['cln_save_weapon_presets', saveWeaponPresetsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_enable_modifications', enableModificationsAction(deps.profiles, deps.accounts, deps.equipment)], ['cln_enable_modifications', enableModificationsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_set_unit_selected_mrank', setUnitSelectedMrankAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_upgrade_crew', upgradeCrewAction(deps.profiles, deps.accounts, deps.crew)], ['cln_upgrade_crew', upgradeCrewAction(deps.profiles, deps.accounts, deps.crew)],
['cln_purchase_skill_points', purchaseSkillPointsAction(deps.profiles, deps.accounts, deps.crew)], ['cln_purchase_skill_points', purchaseSkillPointsAction(deps.profiles, deps.accounts, deps.crew)],
['cln_specialize_crew', specializeCrewAction(deps.profiles, deps.accounts, deps.crew)], ['cln_specialize_crew', specializeCrewAction(deps.profiles, deps.accounts, deps.crew)],
@@ -3,6 +3,7 @@
* settles them into the player's save (battle-settlement.ts) and answers the updated profile, * settles them into the player's save (battle-settlement.ts) and answers the updated profile,
* whose new `EULT_SESSION_RESULT` log carries the debriefing table. * whose new `EULT_SESSION_RESULT` log carries the debriefing table.
*/ */
import type { BattleSettlementContext } from '@wto/mods';
import type { AccountStore } from '../../accounts/account-store.ts'; import type { AccountStore } from '../../accounts/account-store.ts';
import { parseBattleReport } from '../../battle/battle-report.ts'; import { parseBattleReport } from '../../battle/battle-report.ts';
import type { BattleSessionStore } from '../../battle/battle-session-store.ts'; import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
@@ -28,6 +29,7 @@ export interface BattleActionDependencies {
readonly streaks: BattleStreaks; readonly streaks: BattleStreaks;
/** Units whose lives and events are not settled (battle-support-planes.ts). */ /** Units whose lives and events are not settled (battle-support-planes.ts). */
readonly supportPlanes: ReadonlySet<string>; readonly supportPlanes: ReadonlySet<string>;
readonly onAfterSettle?: (ctx: BattleSettlementContext) => void;
} }
export interface FinishBattleContext { export interface FinishBattleContext {
@@ -62,6 +64,11 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio
} }
const updated = ctx.profiles.update(account.userId, (profile) => { const updated = ctx.profiles.update(account.userId, (profile) => {
settleBattle(profile, report, session, settlementDeps); settleBattle(profile, report, session, settlementDeps);
battle.onAfterSettle?.({
userId: account.userId,
roomId: session.sessionId,
summary: { profile, report, session },
});
}); });
battle.sessions.markSettled(session.sessionId); battle.sessions.markSettled(session.sessionId);
return { kind: 'data', blk: clientProfile(updated, account) }; return { kind: 'data', blk: clientProfile(updated, account) };
@@ -2,19 +2,48 @@
* `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`): * `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`):
* triggered by `save_online_single_job` when the client marks seen user logs as disabled * triggered by `save_online_single_job` when the client marks seen user logs as disabled
* (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar * (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar
* auto-repair / auto-refill / auto-buy-modifications and map preferences. Answers the whole * auto-repair / auto-refill / auto-buy-modifications and map preferences. On returning from
* updated profile. * a stock training mission, the client also reports completion in `missionAwards` while
* `pveProgress` is empty. Answers the whole updated profile.
*/ */
import { findBlock, findParam, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts'; import type { AccountStore } from '../../accounts/account-store.ts';
import { boolField, stringField } from '../../game-data/datasets/blk-fields.ts';
import { applyClientProfileUpdate } from '../../profile/profile-client-settings.ts'; import { applyClientProfileUpdate } from '../../profile/profile-client-settings.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { ACCEPTED } from '../../research/rule-outcome.ts'; import { ACCEPTED } from '../../research/rule-outcome.ts';
import type { TrainingCatalogue, TrainingCompletionReport } from '../../training/training-completion.ts';
import type { CharActionHandler } from '../char-action.ts'; import type { CharActionHandler } from '../char-action.ts';
import { ruleAction } from './rule-answer.ts'; import { ruleAction } from './rule-answer.ts';
export function clientUpdateAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { export function clientUpdateAction(
return ruleAction(profiles, accounts, (payload) => (profile) => { profiles: PlayerProfiles,
applyClientProfileUpdate(profile, payload); accounts: AccountStore,
return ACCEPTED; training?: TrainingCatalogue,
): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const completion = training ? readTrainingCompletion(payload) : undefined;
return (profile) => {
applyClientProfileUpdate(profile, payload);
if (completion && training) training.applyCompletion(profile, completion);
return ACCEPTED;
};
}); });
} }
function readTrainingCompletion(request: BlkBlock): TrainingCompletionReport | undefined {
const awards = findBlock(request, 'missionAwards');
if (!awards
|| stringField(awards, 'gameModeName') !== 'training'
|| boolField(awards, 'success') !== true
|| boolField(awards, 'early') !== false
|| boolField(awards, 'onlineGame') !== false) return undefined;
const chapter = stringField(awards, 'chapterName');
const mission = stringField(awards, 'missionName');
const difficulty = findParam(awards, 'difficulty')?.value;
if (!chapter || !mission || difficulty?.type !== 'int'
|| (difficulty.value !== 0 && difficulty.value !== 1 && difficulty.value !== 2)) return undefined;
return { chapter, mission, difficulty: difficulty.value };
}
@@ -8,6 +8,7 @@
* cln_buy_all_modification: unit:t forceOpen:b cost:i costGold:i * cln_buy_all_modification: unit:t forceOpen:b cost:i costGold:i
* cln_buy_spare_aircrafts: aircraft:t count:i cost:i costGold:i * cln_buy_spare_aircrafts: aircraft:t count:i cost:i costGold:i
* cln_buy_weapon: aircraft:t weapon:t count:i cost:i costGold:i * cln_buy_weapon: aircraft:t weapon:t count:i cost:i costGold:i
* cln_set_unit_selected_mrank (scripts/unit/unitmrankselectionstate.nut): unit:t addMrank:i
* cln_enable_modifications (shop_enable_modifications, 0x17a5020 -> 0x29a890; lab round 18): * cln_enable_modifications (shop_enable_modifications, 0x17a5020 -> 0x29a890; lab round 18):
* <vehicle>{ <modification>:b=yes ... } ... * <vehicle>{ <modification>:b=yes ... } ...
*/ */
@@ -16,6 +17,7 @@ import type { AccountStore } from '../../accounts/account-store.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts'; import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { buyAllModifications, buyModification, enableModifications } from '../../modifications/modification-purchase.ts'; import { buyAllModifications, buyModification, enableModifications } from '../../modifications/modification-purchase.ts';
import { buySpares } from '../../modifications/spare-purchase.ts'; import { buySpares } from '../../modifications/spare-purchase.ts';
import { selectVehicleMrankDelta } from '../../modifications/vehicle-mrank-selection.ts';
import { saveWeaponPresets } from '../../modifications/weapon-presets.ts'; import { saveWeaponPresets } from '../../modifications/weapon-presets.ts';
import { buyWeapons } from '../../modifications/weapon-purchase.ts'; import { buyWeapons } from '../../modifications/weapon-purchase.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts';
@@ -81,6 +83,15 @@ export function saveWeaponPresetsAction(profiles: PlayerProfiles, accounts: Acco
return ruleAction(profiles, accounts, (payload) => (profile) => saveWeaponPresets(profile, equipment, payload)); return ruleAction(profiles, accounts, (payload) => (profile) => saveWeaponPresets(profile, equipment, payload));
} }
export function setUnitSelectedMrankAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
const delta = intParam(payload, 'addMrank');
if (!vehicle || delta === undefined) return undefined;
return (profile) => selectVehicleMrankDelta(profile, equipment, vehicle, delta);
});
}
function offeredPrice(payload: BlkBlock) { function offeredPrice(payload: BlkBlock) {
return { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 }; return { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 };
} }
+53 -2
View File
@@ -13,6 +13,8 @@
* default lets the client continue and reveal what it asks for next. * default lets the client continue and reveal what it asks for next.
*/ */
import { emptyBlock } from '@wto/blk'; import { emptyBlock } from '@wto/blk';
import type { ModCharRequest, ModCharResponse } from '@wto/mods';
import type { ServerModRuntime } from '../mods/server-mod-runtime.ts';
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts'; import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
import type { CharActionHandler } from './char-action.ts'; import type { CharActionHandler } from './char-action.ts';
import { toResponse, type CharAnswer } from './char-answers.ts'; import { toResponse, type CharAnswer } from './char-answers.ts';
@@ -23,17 +25,26 @@ const CHAR_HOST = /^char-[a-z0-9-]+\.warthunder\.com$/;
export class CharService implements Service { export class CharService implements Service {
readonly name = 'char'; readonly name = 'char';
readonly #actions: ReadonlyMap<string, CharActionHandler>; readonly #actions: ReadonlyMap<string, CharActionHandler>;
readonly #modRuntime: ServerModRuntime | undefined;
constructor(actions: ReadonlyMap<string, CharActionHandler>) { constructor(actions: ReadonlyMap<string, CharActionHandler>, modRuntime?: ServerModRuntime) {
this.#actions = actions; this.#actions = actions;
this.#modRuntime = modRuntime;
} }
accepts(request: ServiceRequest): boolean { accepts(request: ServiceRequest): boolean {
return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost); return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost);
} }
handle(request: ServiceRequest): ServiceResponse { handle(request: ServiceRequest): ServiceResponse | Promise<ServiceResponse> {
const action = header(request, 'action') ?? '(no action header)'; const action = header(request, 'action') ?? '(no action header)';
if (this.#modRuntime?.hasCharOverride(action)) {
return this.#handleWithModOverride(action, request);
}
return this.#handleCore(action, request);
}
#handleCore(action: string, request: ServiceRequest): ServiceResponse {
const payload = decodeRequestPayload(request.body); const payload = decodeRequestPayload(request.body);
const handler = this.#actions.get(action); const handler = this.#actions.get(action);
const answer: CharAnswer = handler const answer: CharAnswer = handler
@@ -56,6 +67,46 @@ export class CharService implements Service {
}, },
}; };
} }
async #handleWithModOverride(action: string, request: ServiceRequest): Promise<ServiceResponse> {
const headers: Record<string, string | undefined> = {};
for (const [key, value] of Object.entries(request.headers)) {
headers[key] = Array.isArray(value) ? value[0] : value;
}
const query: Record<string, string> = {};
for (const [key, value] of request.query.entries()) query[key] = value;
const modReq: ModCharRequest = {
action,
userId: header(request, 'uidhint') ?? '',
headers,
body: request.body,
query,
};
const result = await this.#modRuntime!.dispatchCharOverride(action, modReq, async (nextReq): Promise<ModCharResponse> => {
const forwarded: ServiceRequest = { ...request, body: nextReq.body };
const coreResp = this.#handleCore(nextReq.action, forwarded);
return {
status: coreResp.status,
...(coreResp.headers ? { headers: coreResp.headers } : {}),
body: coreResp.body ?? '',
};
});
const responseHeaders: Record<string, string> = { ...(result.headers ?? {}) };
if (result.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) {
responseHeaders['content-type'] = result.contentType;
}
return {
status: result.status ?? 200,
headers: responseHeaders,
body: result.body,
logNotes: {
summary: `${action} [mod handler] -> ${result.status ?? 200}`,
},
};
}
} }
function header(request: ServiceRequest, name: string): string | undefined { function header(request: ServiceRequest, name: string): string | undefined {
@@ -14,12 +14,14 @@
* char.vromfs.bin config/wpcost.blk * char.vromfs.bin config/wpcost.blk
* ucav_*_killstreak{ country:t ... } * ucav_*_killstreak{ country:t ... }
* The strike UCAVs, one per country. * The strike UCAVs, one per country.
* *_killstreak / nt_* with weapons.<preset>.totalNuclearYield:i
* Tactical (5 kt / 30 kt) and strategic (>= 1000 kt) nuclear carriers for Nuclear Escalation.
* char.vromfs.bin config/warpoints.blk respawn_points / TankHistorical * char.vromfs.bin config/warpoints.blk respawn_points / TankHistorical
* Starting points and unit cost parameters for Ground Realistic Battles. * Starting points and unit cost parameters for Ground Realistic Battles.
*/ */
import type { BlkBlock } from '@wto/blk'; import type { BlkBlock } from '@wto/blk';
import { findParam } from '@wto/blk'; import { findParam } from '@wto/blk';
import { blockAt, numberField, stringField, stringList } from './blk-fields.ts'; import { blockAt, boolField, numberField, stringField, stringList } from './blk-fields.ts';
import type { Dataset } from './dataset.ts'; import type { Dataset } from './dataset.ts';
export interface SupportPlaneUnit { export interface SupportPlaneUnit {
@@ -43,6 +45,18 @@ export interface StrikeUcav {
readonly unitName: string; readonly unitName: string;
} }
export interface NuclearCarrierWeapon {
readonly name: string;
readonly yieldKt: number;
}
export interface NuclearCarrierUnit {
readonly country: string;
readonly unitName: string;
readonly mrank: number;
readonly weapons: readonly NuclearCarrierWeapon[];
}
export interface RandomSpawnUnit { export interface RandomSpawnUnit {
readonly unitName: string; readonly unitName: string;
readonly addModifications: readonly string[]; readonly addModifications: readonly string[];
@@ -76,22 +90,31 @@ export interface BattleSpawnRulesData {
/** By event name (`missionSupportPlane` keys are game mode names). */ /** By event name (`missionSupportPlane` keys are game mode names). */
readonly supportPlanes: Readonly<Record<string, readonly SupportPlanePreset[]>>; readonly supportPlanes: Readonly<Record<string, readonly SupportPlanePreset[]>>;
readonly strikeUcavs: readonly StrikeUcav[]; readonly strikeUcavs: readonly StrikeUcav[];
/** Killstreak nuclear carriers carrying 5 kt / 30 kt Nuclear Escalation presets. */
readonly nuclearEscalationTacticalCarriers: readonly NuclearCarrierUnit[];
/** Megaton-class strategic nuclear bombers (`nt_*` with totalNuclearYield >= 1000 kt). */
readonly nuclearEscalationStrategicBombers: readonly NuclearCarrierUnit[];
readonly spawnScore: SpawnScoreRules; readonly spawnScore: SpawnScoreRules;
/** By event economic name, then country. */ /** By event economic name, then country. */
readonly randomSpawnUnits: Readonly<Record<string, Readonly<Record<string, readonly RandomSpawnGroup[]>>>>; readonly randomSpawnUnits: Readonly<Record<string, Readonly<Record<string, readonly RandomSpawnGroup[]>>>>;
} }
const STRIKE_UCAV_PATTERN = /^ucav_.*_killstreak$/; const STRIKE_UCAV_PATTERN = /^ucav_.*_killstreak$/;
const KILLSTREAK_PATTERN = /_killstreak$/;
const STRATEGIC_BOMBER_PATTERN = /^nt_/;
const STRATEGIC_YIELD_MIN_KT = 1000;
export const battleSpawnRules: Dataset<BattleSpawnRulesData> = { export const battleSpawnRules: Dataset<BattleSpawnRulesData> = {
id: 'battle-spawn-rules', id: 'battle-spawn-rules',
version: 3, version: 4,
extract: (source) => { extract: (source) => {
const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk'); const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk');
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk'); const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
return { return {
supportPlanes: extractSupportPlanes(blockAt(gameplay, 'missionSupportPlane')), supportPlanes: extractSupportPlanes(blockAt(gameplay, 'missionSupportPlane')),
strikeUcavs: extractStrikeUcavs(wpcost.blocks), strikeUcavs: extractStrikeUcavs(wpcost.blocks),
nuclearEscalationTacticalCarriers: extractNuclearCarriers(wpcost.blocks, 'tactical'),
nuclearEscalationStrategicBombers: extractNuclearCarriers(wpcost.blocks, 'strategic'),
spawnScore: extractSpawnScore(blockAt(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'respawn_points')), spawnScore: extractSpawnScore(blockAt(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'respawn_points')),
randomSpawnUnits: extractRandomSpawnUnits(blockAt(gameplay, 'RandomSpawnUnits')), randomSpawnUnits: extractRandomSpawnUnits(blockAt(gameplay, 'RandomSpawnUnits')),
}; };
@@ -162,6 +185,38 @@ function extractStrikeUcavs(wpcostBlocks: readonly BlkBlock[]): StrikeUcav[] {
}); });
} }
function extractNuclearCarriers(
wpcostBlocks: readonly BlkBlock[],
kind: 'tactical' | 'strategic',
): NuclearCarrierUnit[] {
const carriers: NuclearCarrierUnit[] = [];
for (const unitBlk of wpcostBlocks) {
const country = stringField(unitBlk, 'country') ?? '';
if (!country.startsWith('country_')) continue;
if (kind === 'tactical' && !KILLSTREAK_PATTERN.test(unitBlk.name)) continue;
if (kind === 'strategic' && !STRATEGIC_BOMBER_PATTERN.test(unitBlk.name)) continue;
const weaponsBlk = blockAt(unitBlk, 'weapons');
if (!weaponsBlk) continue;
const weapons: NuclearCarrierWeapon[] = [];
for (const weaponBlk of weaponsBlk.blocks) {
if (boolField(weaponBlk, 'isWeaponForCustomSlot') === true) continue;
if (boolField(weaponBlk, 'hideInGui') === true) continue;
if (weaponBlk.name.includes('without_countermeasures')) continue;
const yieldKt = numberField(weaponBlk, 'totalNuclearYield') ?? 0;
if (yieldKt <= 0) continue;
if (kind === 'tactical' && yieldKt >= STRATEGIC_YIELD_MIN_KT) continue;
if (kind === 'strategic' && yieldKt < STRATEGIC_YIELD_MIN_KT) continue;
weapons.push({ name: weaponBlk.name, yieldKt });
}
if (weapons.length === 0) continue;
weapons.sort((a, b) => a.yieldKt - b.yieldKt || a.name.localeCompare(b.name));
const mrank = numberField(unitBlk, 'economicRankHistorical') ?? numberField(unitBlk, 'economicRank') ?? 0;
carriers.push({ country, unitName: unitBlk.name, mrank, weapons });
}
carriers.sort((a, b) => a.country.localeCompare(b.country) || a.mrank - b.mrank || a.unitName.localeCompare(b.unitName));
return carriers;
}
function extractRandomSpawnUnits( function extractRandomSpawnUnits(
root: BlkBlock | undefined, root: BlkBlock | undefined,
): Record<string, Record<string, RandomSpawnGroup[]>> { ): Record<string, Record<string, RandomSpawnGroup[]>> {
@@ -0,0 +1,117 @@
/**
* Dataset: stock training missions and their first-completion rewards from char.vromfs.bin:
* - config/mislist.blk ("training" block): chapter/mission full names accepted for progress;
* - config/pve_awards.blk ("training" block): per-mission decal, shared first-completion unlock,
* and per-difficulty Silver Lions rewards (`wpEarnedWinDiff0..2`);
* - config/unlocks.blk: decal unlock verification and `oneTimeAwardUnlock` Golden Eagles amount
* and mutually exclusive `char_unlocked` conditions.
*/
import { findParam, type BlkBlock } from '@wto/blk';
import { blockAt, boolField, stringField, stringList } from './blk-fields.ts';
import type { Dataset, DatasetSource } from './dataset.ts';
const CHAR_PACK = 'char.vromfs.bin';
const MISLIST = 'config/mislist.blk';
const PVE_AWARDS = 'config/pve_awards.blk';
const UNLOCKS = 'config/unlocks.blk';
const TRAINING_SECTION = 'training';
export interface TrainingFirstCompletionAward {
readonly id: string;
readonly goldenEagles: number;
readonly blockedBy: readonly string[];
}
export interface TrainingMissionEntry {
readonly fullName: string;
readonly decal?: string;
readonly firstCompletion?: TrainingFirstCompletionAward;
/** First-win Silver Lions rewards (`wpEarnedWinDiff0..2`) for arcade, realistic, simulator. */
readonly silverLionsByDifficulty: readonly [number, number, number];
}
export interface TrainingMissionsData {
readonly missions: readonly TrainingMissionEntry[];
}
export const trainingMissions: Dataset<TrainingMissionsData> = {
id: 'training-missions',
version: 1,
extract(source: DatasetSource): TrainingMissionsData {
const misSection = blockAt(source.readBlk(CHAR_PACK, MISLIST), TRAINING_SECTION);
if (!misSection) throw new Error(`${MISLIST} has no "${TRAINING_SECTION}" block`);
const awardSection = blockAt(source.readBlk(CHAR_PACK, PVE_AWARDS), TRAINING_SECTION);
if (!awardSection) throw new Error(`${PVE_AWARDS} has no "${TRAINING_SECTION}" block`);
const awardsByMission = new Map<string, BlkBlock>(awardSection.blocks.map((entry) => [entry.name, entry]));
const unlocksById = new Map<string, BlkBlock>();
for (const entry of source.readBlk(CHAR_PACK, UNLOCKS).blocks) {
const id = stringField(entry, 'id');
if (id) unlocksById.set(id, entry);
}
const seen = new Set<string>();
const missions: TrainingMissionEntry[] = [];
for (const chapter of misSection.blocks) {
for (const mission of stringList(chapter, 'm')) {
const fullName = `${chapter.name}/${mission}`;
if (seen.has(fullName)) continue;
seen.add(fullName);
missions.push(buildMissionEntry(fullName, mission, awardsByMission.get(mission), unlocksById));
}
}
return { missions };
},
};
function buildMissionEntry(
fullName: string,
mission: string,
award: BlkBlock | undefined,
unlocks: ReadonlyMap<string, BlkBlock>,
): TrainingMissionEntry {
const decalId = stringField(award, 'decal');
const decal = decalId && stringField(unlocks.get(decalId), 'type') === 'decal' ? decalId : undefined;
const firstCompletion = award ? readFirstCompletionAward(award, mission, unlocks) : undefined;
return {
fullName,
...(decal ? { decal } : {}),
...(firstCompletion ? { firstCompletion } : {}),
silverLionsByDifficulty: [
readWinSilverLions(award, 0),
readWinSilverLions(award, 1),
readWinSilverLions(award, 2),
],
};
}
function readFirstCompletionAward(
award: BlkBlock,
mission: string,
unlocks: ReadonlyMap<string, BlkBlock>,
): TrainingFirstCompletionAward | undefined {
const id = stringField(award, 'oneTimeAwardUnlock');
if (!id) return undefined;
const unlock = unlocks.get(id);
if (stringField(unlock, 'type') !== 'award') return undefined;
const amount = unlock && findParam(unlock, 'amount_gold')?.value;
const mode = blockAt(unlock, 'mode');
if (amount?.type !== 'int' || amount.value <= 0
|| stringField(mode, 'type') !== 'char_mission_list'
|| !stringList(mode, 'name').includes(mission)) return undefined;
const blocked = mode?.blocks.flatMap((condition) =>
condition.name === 'condition'
&& stringField(condition, 'type') === 'char_unlocked'
&& boolField(condition, 'positive') === false
? stringList(condition, 'unlock')
: []) ?? [];
const hideIfEarned = stringField(award, 'hideOneTimeAwardIfUnlockIsOpen');
if (hideIfEarned) blocked.push(hideIfEarned);
return { id, goldenEagles: amount.value, blockedBy: [...new Set(blocked)] };
}
function readWinSilverLions(award: BlkBlock | undefined, difficulty: 0 | 1 | 2): number {
const value = award && findParam(award, `wpEarnedWinDiff${difficulty}`)?.value;
return value?.type === 'int' && value.value > 0 ? value.value : 0;
}
@@ -5,7 +5,7 @@
* char.vromfs.bin config/wpcost.blk, per vehicle: * char.vromfs.bin config/wpcost.blk, per vehicle:
* needBuyToOpenNextInTier<N>:i researched modifications of tier N needed to open tier N+1 * needBuyToOpenNextInTier<N>:i researched modifications of tier N needed to open tier N+1
* modifications{ <name>{ tier:i reqExp:i value:i costGold:i openCostGold:i * modifications{ <name>{ tier:i reqExp:i value:i costGold:i openCostGold:i
* reqModification:t (repeated) maxCount:i ammoCount:i ... } } * reqModification:t (repeated) maxCount:i ammoCount:i addMrank:i ... } }
* Ammunition and expendables are modifications too (tier 0, maxCount, ammoCount). * Ammunition and expendables are modifications too (tier 0, maxCount, ammoCount).
* weapons{ <preset>{ value:i costGold:i maxCount:i reqModification:t ... } } * weapons{ <preset>{ value:i costGold:i maxCount:i reqModification:t ... } }
* Paid presets (bombs, rockets) are bought by the piece, up to maxCount; the rest are free, * Paid presets (bombs, rockets) are bought by the piece, up to maxCount; the rest are free,
@@ -39,6 +39,8 @@ export interface ModificationFacts {
readonly maxCount: number; readonly maxCount: number;
/** ammoCount present: an ammunition belt or shell type. */ /** ammoCount present: an ammunition belt or shell type. */
readonly ammunition: boolean; readonly ammunition: boolean;
/** addMrank: selectable matchmaking rank increase unlocked by owning this modification. */
readonly addMrank?: number;
/** Initial enabled state when acquired (`turn_it_off` / `isEnabledByDefaultForAddMrank`). */ /** Initial enabled state when acquired (`turn_it_off` / `isEnabledByDefaultForAddMrank`). */
readonly defaultEnabled: boolean; readonly defaultEnabled: boolean;
/** Non-bullet `group` name when modifications in the same group are mutually exclusive. */ /** Non-bullet `group` name when modifications in the same group are mutually exclusive. */
@@ -78,7 +80,7 @@ interface GlobalModificationMeta {
export const vehicleEquipment: Dataset<readonly VehicleEquipment[]> = { export const vehicleEquipment: Dataset<readonly VehicleEquipment[]> = {
id: 'vehicle-equipment', id: 'vehicle-equipment',
version: 4, version: 5,
extract: (source) => { extract: (source) => {
const modMeta = readGlobalModificationMeta(source.readBlk('char.vromfs.bin', MODIFICATIONS_CONFIG)); const modMeta = readGlobalModificationMeta(source.readBlk('char.vromfs.bin', MODIFICATIONS_CONFIG));
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => equipmentOf(vehicle, modMeta)); return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => equipmentOf(vehicle, modMeta));
@@ -119,6 +121,7 @@ function equipmentOf(vehicle: BlkBlock, modMeta: ReadonlyMap<string, GlobalModif
function modificationOf(modification: BlkBlock, meta: GlobalModificationMeta | undefined): ModificationFacts { function modificationOf(modification: BlkBlock, meta: GlobalModificationMeta | undefined): ModificationFacts {
const ammunition = numberField(modification, 'ammoCount') !== undefined; const ammunition = numberField(modification, 'ammoCount') !== undefined;
const addMrank = numberField(modification, 'addMrank');
const defaultEnabled = !(meta?.turnOffByDefault ?? false) && (boolField(modification, 'isEnabledByDefaultForAddMrank') ?? true); const defaultEnabled = !(meta?.turnOffByDefault ?? false) && (boolField(modification, 'isEnabledByDefaultForAddMrank') ?? true);
const group = stringField(modification, 'group') ?? meta?.group; const group = stringField(modification, 'group') ?? meta?.group;
const exclusiveGroup = !ammunition && !(meta?.bulletGroup ?? false) ? group : undefined; const exclusiveGroup = !ammunition && !(meta?.bulletGroup ?? false) ? group : undefined;
@@ -132,6 +135,7 @@ function modificationOf(modification: BlkBlock, meta: GlobalModificationMeta | u
requires: stringList(modification, 'reqModification'), requires: stringList(modification, 'reqModification'),
maxCount: numberField(modification, 'maxCount') ?? 0, maxCount: numberField(modification, 'maxCount') ?? 0,
ammunition, ammunition,
...(addMrank !== undefined ? { addMrank } : {}),
defaultEnabled, defaultEnabled,
...(exclusiveGroup !== undefined ? { exclusiveGroup } : {}), ...(exclusiveGroup !== undefined ? { exclusiveGroup } : {}),
}; };
@@ -50,6 +50,10 @@ export interface GameModeDeclaration {
* `true`; `false` for single-slot modes (`air_realistic` and its `small_teams_` sub-mode). * `true`; `false` for single-slot modes (`air_realistic` and its `small_teams_` sub-mode).
*/ */
readonly multiSlot?: boolean; readonly multiSlot?: boolean;
/** Stock maxRespawns value when this mode specifies its own respawn count. */
readonly maxRespawns?: number;
/** Additional scalar settings the local host needs from this mode's missions. */
readonly missionRuleKeys?: readonly string[];
/** False for modes whose native weapon rules replace combat presets. Defaults to true. */ /** False for modes whose native weapon rules replace combat presets. Defaults to true. */
readonly allowBotAircraftLoadouts?: boolean; readonly allowBotAircraftLoadouts?: boolean;
/** Minimum `mrank` exposed on the parent mode for Night Battles (`scripts/events/eventinfo.nut:134-136`). */ /** Minimum `mrank` exposed on the parent mode for Night Battles (`scripts/events/eventinfo.nut:134-136`). */
@@ -11,6 +11,7 @@
* AB/RB get Enduring Confrontation; Ground AB and Air AB get none); * AB/RB get Enduring Confrontation; Ground AB and Air AB get none);
* - `queueEvent.nut` includes or excludes its `gameModeId` in `match.enqueue` `game_modes_list`. * - `queueEvent.nut` includes or excludes its `gameModeId` in `match.enqueue` `game_modes_list`.
*/ */
import { UNLIMITED_RESPAWNS } from '../mode-definition.ts';
import type { GameModeDeclaration } from './game-mode-declaration.ts'; import type { GameModeDeclaration } from './game-mode-declaration.ts';
import { import {
AIR_REALISTIC_MISSIONS, AIR_REALISTIC_MISSIONS,
@@ -69,6 +70,15 @@ export const SUB_GAME_MODES: readonly GameModeDeclaration[] = [
displayType: 'random_battle', displayType: 'random_battle',
allowedCraftMinMrank: { aircraft: MIN_MRANK_NUCLEAR_ESCALATION }, allowedCraftMinMrank: { aircraft: MIN_MRANK_NUCLEAR_ESCALATION },
minQueueMrank: MIN_MRANK_NUCLEAR_ESCALATION, minQueueMrank: MIN_MRANK_NUCLEAR_ESCALATION,
maxRespawns: UNLIMITED_RESPAWNS,
// mission_settings.mission in mis.vromfs.bin gamedata/missions/cta/planes/nuclear_escalation/.
missionRuleKeys: [
'customHUD', 'nuclearEscalationStage1', 'nuclearEscalationStage2', 'nuclearEscalationStage3',
'useSpawnDelay', 'afterRespawnDelaySec', 'overrideMaxActiveUnitsWeight', 'scheduleBasedGmUpdateMaxInterval',
'disableFallingTrees', 'alwaysSendAllyGMData', 'isAlwaysShowCollectiveDetectedUnits', 'useAIForCollectiveDetection',
'allowToChooseHUDIconPreset', 'showAIKilllog', 'showUnitTooltipOnMap', 'disableMfdForPrevgenConsoles',
'clientReplayMaxSizeMb', 'timeToLoseInstantDetection', 'showTacticalMapCellSize',
],
requiredClass: 'aircraft', requiredClass: 'aircraft',
allowedClasses: ['aircraft'], allowedClasses: ['aircraft'],
missions: NUCLEAR_ESCALATION_MISSIONS, missions: NUCLEAR_ESCALATION_MISSIONS,
@@ -41,8 +41,13 @@ export const MISSION_DIFFICULTY: Readonly<Record<ModeDifficulty, string>> = {
simulator: 'hardcore', simulator: 'hardcore',
}; };
// globals/missions/respawnCountModes.nut: RESPAWN_COUNT_MODE.SINGLE_SPAWN. // globals/missions/respawnCountModes.nut: RESPAWN_COUNT_MODE.
export const SINGLE_SPAWN = 1; export const SINGLE_SPAWN = 1;
export const UNLIMITED_RESPAWNS = -2;
export function modeMaxRespawns(mode: GameModeDeclaration): number | undefined {
return mode.maxRespawns ?? (mode.multiSlot === false ? SINGLE_SPAWN : undefined);
}
export type ModeDefinition = Readonly<Record<string, unknown>>; export type ModeDefinition = Readonly<Record<string, unknown>>;
@@ -50,6 +55,7 @@ export function buildModeDefinition(mode: GameModeDeclaration, missions: readonl
countries: readonly string[], missionRanks?: MissionRotationRanks): ModeDefinition { countries: readonly string[], missionRanks?: MissionRotationRanks): ModeDefinition {
const minTeamSize = mode.teamSizeOverride?.min ?? 1; const minTeamSize = mode.teamSizeOverride?.min ?? 1;
const maxTeamSize = mode.teamSizeOverride?.max ?? teamSize(mode, missions); const maxTeamSize = mode.teamSizeOverride?.max ?? teamSize(mode, missions);
const maxRespawns = modeMaxRespawns(mode);
const team = { const team = {
countries: [...countries], countries: [...countries],
allowedCrafts: mode.allowedClasses.map((unitClass) => { allowedCrafts: mode.allowedClasses.map((unitClass) => {
@@ -83,7 +89,7 @@ export function buildModeDefinition(mode: GameModeDeclaration, missions: readonl
teamB: structuredClone(team), teamB: structuredClone(team),
mission_decl: { mission_decl: {
difficulty: MISSION_DIFFICULTY[mode.difficulty], difficulty: MISSION_DIFFICULTY[mode.difficulty],
...(mode.multiSlot === false ? { maxRespawns: SINGLE_SPAWN } : {}), ...(maxRespawns === undefined ? {} : { maxRespawns }),
missions_list: Object.fromEntries(missions.map((mission) => { missions_list: Object.fromEntries(missions.map((mission) => {
const ranges = missionRanks?.byMission.get(mission.name); const ranges = missionRanks?.byMission.get(mission.name);
return [mission.name, ranges?.length === 1 ? { enableIf: ranges[0] } : {}]; return [mission.name, ranges?.length === 1 ? { enableIf: ranges[0] } : {}];
@@ -16,7 +16,6 @@ import type { BlkBlock, BlkValue } from '@wto/blk';
import type { BannerParams } from '../battle/battle-economy.ts'; import type { BannerParams } from '../battle/battle-economy.ts';
import type { BattleLaunchPlan } from '../battle/battle-matchmaker.ts'; import type { BattleLaunchPlan } from '../battle/battle-matchmaker.ts';
import { battleMissionSettings } from '../battle/battle-mission-settings.ts'; import { battleMissionSettings } from '../battle/battle-mission-settings.ts';
import { SINGLE_SPAWN } from '../game-modes/mode-definition.ts';
type WireParam = readonly [name: string, type: 't' | 'i' | 'r' | 'b', value: string | number | boolean]; type WireParam = readonly [name: string, type: 't' | 'i' | 'r' | 'b', value: string | number | boolean];
@@ -52,12 +51,13 @@ export function battleLaunchNotify(
mission: { mission: {
name: plan.missionName, name: plan.missionName,
difficulty: plan.difficulty, difficulty: plan.difficulty,
...(plan.selectedSlot ? { maxRespawns: SINGLE_SPAWN } : {}), ...(plan.maxRespawns === undefined ? {} : { maxRespawns: plan.maxRespawns }),
}, },
}, },
battle: { battle: {
sessionId: plan.sessionId, sessionId: plan.sessionId,
modeName: plan.modeName, modeName: plan.modeName,
...(plan.modeTag ? { modeTag: plan.modeTag } : {}),
economicName: plan.economicName, economicName: plan.economicName,
country: plan.country, country: plan.country,
missionName: plan.missionName, missionName: plan.missionName,
@@ -11,6 +11,7 @@
* "strike": time:f the local player's nuclear bomb exploded * "strike": time:f the local player's nuclear bomb exploded
* answer: { streaks: [{ id:s stage:i (-1 = single-stage) stageParam:i wp:i exp:i }] } * answer: { streaks: [{ id:s stage:i (-1 = single-stage) stageParam:i wp:i exp:i }] }
*/ */
import type { BattleLiveFactContext } from '@wto/mods';
import type { BattleLiveLogs } from '../battle/battle-live-log.ts'; import type { BattleLiveLogs } from '../battle/battle-live-log.ts';
import type { BattleSessionStore } from '../battle/battle-session-store.ts'; import type { BattleSessionStore } from '../battle/battle-session-store.ts';
import type { BattleStreaks } from '../battle/battle-streaks.ts'; import type { BattleStreaks } from '../battle/battle-streaks.ts';
@@ -23,6 +24,7 @@ export interface BattleLiveDependencies {
readonly streaks: BattleStreaks; readonly streaks: BattleStreaks;
/** Units whose lives and events earn no awards (battle-support-planes.ts). */ /** Units whose lives and events earn no awards (battle-support-planes.ts). */
readonly supportPlanes: ReadonlySet<string>; readonly supportPlanes: ReadonlySet<string>;
readonly onLiveFact?: (ctx: BattleLiveFactContext) => void;
} }
export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string, MatchingRequestHandler]> { export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string, MatchingRequestHandler]> {
@@ -34,6 +36,11 @@ export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string,
if (!session || session.settled) return { streaks: [] }; if (!session || session.settled) return { streaks: [] };
const log = deps.liveLogs.of(session.sessionId); const log = deps.liveLogs.of(session.sessionId);
if (!recordFact(log, p)) return { streaks: [] }; if (!recordFact(log, p)) return { streaks: [] };
deps.onLiveFact?.({
userId: userId!,
roomId: session.sessionId,
fact: p as Record<string, unknown>,
});
const awarded = deps.streaks.evaluate({ const awarded = deps.streaks.evaluate({
...withoutSupportPlanes({ events: log.events, lives: log.lives }, deps.supportPlanes), ...withoutSupportPlanes({ events: log.events, lives: log.lives }, deps.supportPlanes),
feed: log.feed, feed: log.feed,
@@ -5,6 +5,7 @@
* - `match.leave_queue` (scripts/queue/queuestate.nut:28) * - `match.leave_queue` (scripts/queue/queuestate.nut:28)
* - `match.check_reconnect` * - `match.check_reconnect`
*/ */
import type { BattleMatchmakeContext } from '@wto/mods';
import { MAX_BATTLE_CREW_SLOTS } from '../battle/battle-extra-slots.ts'; import { MAX_BATTLE_CREW_SLOTS } from '../battle/battle-extra-slots.ts';
import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.ts'; import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.ts';
import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts'; import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts';
@@ -12,6 +13,7 @@ import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankE
import type { BattleSessionStore } from '../battle/battle-session-store.ts'; import type { BattleSessionStore } from '../battle/battle-session-store.ts';
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts'; import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts'; import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
import { vehicleMrankDelta } from '../profile/profile-hangar.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts'; import type { PlayerProfiles } from '../profile/player-profiles.ts';
import { battleLaunchNotify, type BattleLaunchNotify } from './battle-launch-notify.ts'; import { battleLaunchNotify, type BattleLaunchNotify } from './battle-launch-notify.ts';
import type { MatchingRequestHandler } from './matching-requests.ts'; import type { MatchingRequestHandler } from './matching-requests.ts';
@@ -23,6 +25,7 @@ export interface BattleQueueDependencies {
readonly sessions: BattleSessionStore; readonly sessions: BattleSessionStore;
readonly economy: BattleEconomy; readonly economy: BattleEconomy;
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void; readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
readonly onBeforeMatchmake?: (ctx: BattleMatchmakeContext) => void;
} }
export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> { export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> {
@@ -84,12 +87,18 @@ function handleEnqueue(
const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country); const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country);
const idInCountry = playerEntry.selectedSlot; const idInCountry = playerEntry.selectedSlot;
const selectedSlotVehicle = idInCountry === undefined ? undefined : crewSlotVehicleOfCountry(profile, playerEntry.country, idInCountry); const selectedSlotVehicle = idInCountry === undefined ? undefined : crewSlotVehicleOfCountry(profile, playerEntry.country, idInCountry);
deps.onBeforeMatchmake?.({
userId,
eventName: modes[0]!.declaration.name,
request: params as Record<string, unknown>,
});
const outcome = deps.matchmaker.enqueue({ const outcome = deps.matchmaker.enqueue({
userId, userId,
mode: modes[0]!, mode: modes[0]!,
modes, modes,
country: playerEntry.country, country: playerEntry.country,
slotVehicles, slotVehicles,
mrankDeltas: new Map(slotVehicles.map((vehicle) => [vehicle, vehicleMrankDelta(profile, vehicle)])),
...(idInCountry !== undefined && selectedSlotVehicle ? { selectedSlot: { idInCountry, unitName: selectedSlotVehicle } } : {}), ...(idInCountry !== undefined && selectedSlotVehicle ? { selectedSlot: { idInCountry, unitName: selectedSlotVehicle } } : {}),
bannedMissions: playerEntry.bannedMissions, bannedMissions: playerEntry.bannedMissions,
dislikedMissions: playerEntry.dislikedMissions, dislikedMissions: playerEntry.dislikedMissions,
@@ -21,7 +21,7 @@ import { moduleResearchTarget, setModuleResearchTarget } from '../profile/profil
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import { isCounted, isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts'; import { isCounted, isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts';
import { currentModuleStatus } from './module-state.ts'; import { currentModuleStatus } from './module-state.ts';
import { ModuleStatus } from './module-status.ts'; import { ModuleStatus, vehicleModuleState } from './module-status.ts';
export interface ModificationOrder { export interface ModificationOrder {
readonly vehicle: string; readonly vehicle: string;
@@ -48,8 +48,9 @@ export function buyModification(profile: BlkBlock, catalogue: EquipmentCatalogue
export function buyAllModifications(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, outright: boolean, offered: Price): RuleOutcome { export function buyAllModifications(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, outright: boolean, offered: Price): RuleOutcome {
const equipment = catalogue.vehicle(vehicle); const equipment = catalogue.vehicle(vehicle);
if (!equipment || !ownsVehicle(profile, vehicle)) return refused('BAD_PARAMS'); if (!equipment || !ownsVehicle(profile, vehicle)) return refused('BAD_PARAMS');
const { statuses } = vehicleModuleState(profile, equipment);
const purchases = equipment.modifications.flatMap((modification) => { const purchases = equipment.modifications.flatMap((modification) => {
const purchase = buyAllEntry(profile, vehicle, modification, catalogue, outright); const purchase = buyAllEntry(profile, vehicle, modification, statuses.get(modification.name), outright);
return purchase ? [{ modification, purchase }] : []; return purchase ? [{ modification, purchase }] : [];
}); });
const price = purchases.reduce<Price>((sum, { purchase }) => ({ const price = purchases.reduce<Price>((sum, { purchase }) => ({
@@ -114,17 +115,24 @@ function outrightPurchase(profile: BlkBlock, vehicle: string, modification: Modi
/** /**
* One entry of "buy all", as the client sums it (scripts weaponry/itemInfo.nut getAllModsCost): * One entry of "buy all", as the client sums it (scripts weaponry/itemInfo.nut getAllModsCost):
* skip what is at its maximum; with forceOpen every modification starts at its outright price * skip what is at its maximum; with forceOpen every modification starts at its outright price
* (whatever its status); a buyable one (canBuyMod) with a non-zero price takes its own price * (whatever its status); a buyable or researched one (canBuyMod || isModStatusResearched) with a
* instead, and is skipped altogether when counted or priced in golden eagles. * non-zero price takes its own price instead, and is skipped altogether when counted or priced in
* golden eagles.
*/ */
function buyAllEntry(profile: BlkBlock, vehicle: string, modification: ModificationFacts, catalogue: EquipmentCatalogue, outright: boolean): Purchase | undefined { function buyAllEntry(
profile: BlkBlock,
vehicle: string,
modification: ModificationFacts,
status: ModuleStatus | undefined,
outright: boolean,
): Purchase | undefined {
const record = modificationRecord(profile, vehicle, modification.name); const record = modificationRecord(profile, vehicle, modification.name);
const maxAmount = Math.max(1, modification.maxCount); const maxAmount = Math.max(1, modification.maxCount);
if ((record?.count ?? 0) >= maxAmount) return undefined; if ((record?.count ?? 0) >= maxAmount) return undefined;
let purchase: Purchase | undefined; let purchase: Purchase | undefined;
const openPrice = outright && isResearchable(modification) ? outrightPrice(profile, vehicle, modification) : 0; const openPrice = outright && isResearchable(modification) ? outrightPrice(profile, vehicle, modification) : 0;
if (openPrice > 0) purchase = { price: { silverLions: 0, goldenEagles: openPrice }, amount: 1 }; if (openPrice > 0) purchase = { price: { silverLions: 0, goldenEagles: openPrice }, amount: 1 };
const buyable = record !== undefined || currentModuleStatus(profile, catalogue, vehicle, modification.name) === ModuleStatus.CAN_BUY; const buyable = record !== undefined || status === ModuleStatus.CAN_BUY || status === ModuleStatus.RESEARCHED;
if (buyable && (modification.silverLions > 0 || modification.goldenEagles > 0)) { if (buyable && (modification.silverLions > 0 || modification.goldenEagles > 0)) {
if (isCounted(modification) || modification.goldenEagles > 0) return undefined; if (isCounted(modification) || modification.goldenEagles > 0) return undefined;
purchase = { price: { silverLions: modification.silverLions, goldenEagles: 0 }, amount: 1 }; purchase = { price: { silverLions: modification.silverLions, goldenEagles: 0 }, amount: 1 };
+27 -3
View File
@@ -10,11 +10,12 @@ import { moduleResearchPoints } from '../profile/profile-module-research.ts';
import { countsForTier, isResearchable } from './equipment-catalogue.ts'; import { countsForTier, isResearchable } from './equipment-catalogue.ts';
import type { ProfileEquipmentIndex } from './profile-equipment-index.ts'; import type { ProfileEquipmentIndex } from './profile-equipment-index.ts';
/** shopItemConsts ES_ITEM_STATUS_*; the same values as the vehicle statuses. */ /** shopItemConsts ES_ITEM_STATUS_* (aces.exe 2.61.0.58 0x17e2894..0x17e294b); same values as VehicleStatus. */
export const ModuleStatus = { export const ModuleStatus = {
LOCKED: 1, LOCKED: 1,
CAN_RESEARCH: 2, CAN_RESEARCH: 2,
CAN_BUY: 8, CAN_BUY: 8,
RESEARCHED: 0x40,
} as const; } as const;
export type ModuleStatus = (typeof ModuleStatus)[keyof typeof ModuleStatus]; export type ModuleStatus = (typeof ModuleStatus)[keyof typeof ModuleStatus];
@@ -32,10 +33,11 @@ export function vehicleModuleState(
index?: ProfileEquipmentIndex, index?: ProfileEquipmentIndex,
): VehicleModuleState { ): VehicleModuleState {
const openTier = openTierOf(profile, equipment, index); const openTier = openTierOf(profile, equipment, index);
const byName = new Map(equipment.modifications.map((mod) => [mod.name, mod]));
const statuses = new Map<string, ModuleStatus>(); const statuses = new Map<string, ModuleStatus>();
for (const modification of equipment.modifications) { for (const modification of equipment.modifications) {
if (isOwned(profile, equipment.vehicle, modification.name, index)) continue; if (isOwned(profile, equipment.vehicle, modification.name, index)) continue;
statuses.set(modification.name, statusOf(profile, equipment.vehicle, modification, openTier, index)); statuses.set(modification.name, statusOf(profile, equipment.vehicle, modification, openTier, byName, index));
} }
return { openTier, statuses }; return { openTier, statuses };
} }
@@ -80,16 +82,38 @@ function openTierOf(profile: BlkBlock, equipment: VehicleEquipment, index?: Prof
return tier; return tier;
} }
function arePrerequisitesResearched(
profile: BlkBlock,
vehicle: string,
requires: readonly string[],
byName: ReadonlyMap<string, ModificationFacts>,
index?: ProfileEquipmentIndex,
): boolean {
return requires.every((required) => {
if (isOwned(profile, vehicle, required, index)) return true;
const mod = byName.get(required);
return mod !== undefined && isResearchable(mod) && isModuleResearched(profile, vehicle, mod, index);
});
}
function statusOf( function statusOf(
profile: BlkBlock, profile: BlkBlock,
vehicle: string, vehicle: string,
modification: ModificationFacts, modification: ModificationFacts,
openTier: number, openTier: number,
byName: ReadonlyMap<string, ModificationFacts>,
index?: ProfileEquipmentIndex, index?: ProfileEquipmentIndex,
): ModuleStatus { ): ModuleStatus {
if (isResearchable(modification)) { if (isResearchable(modification)) {
if (modification.tier > openTier) return ModuleStatus.LOCKED; if (modification.tier > openTier) return ModuleStatus.LOCKED;
return isModuleResearched(profile, vehicle, modification, index) ? ModuleStatus.CAN_BUY : ModuleStatus.CAN_RESEARCH; if (isModuleResearched(profile, vehicle, modification, index)) {
return arePrerequisitesOwned(profile, vehicle, modification.requires, index)
? ModuleStatus.CAN_BUY
: ModuleStatus.RESEARCHED;
}
return arePrerequisitesResearched(profile, vehicle, modification.requires, byName, index)
? ModuleStatus.CAN_RESEARCH
: ModuleStatus.LOCKED;
} }
return arePrerequisitesOwned(profile, vehicle, modification.requires, index) ? ModuleStatus.CAN_BUY : ModuleStatus.LOCKED; return arePrerequisitesOwned(profile, vehicle, modification.requires, index) ? ModuleStatus.CAN_BUY : ModuleStatus.LOCKED;
} }
@@ -4,7 +4,12 @@
* carry 30,000+ flat sub-blocks; indexing once drops refresh cost from O(N^2) to O(N). * carry 30,000+ flat sub-blocks; indexing once drops refresh cost from O(N^2) to O(N).
*/ */
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
import { recordName, type ModificationRecord } from '../profile/profile-modifications.ts'; import {
allModificationBlocks,
MAX_MODIFICATION_BLOCK_ENTRIES,
recordName,
type ModificationRecord,
} from '../profile/profile-modifications.ts';
import type { WeaponRecord } from '../profile/profile-weapons.ts'; import type { WeaponRecord } from '../profile/profile-weapons.ts';
const HANGAR = 'hangar'; const HANGAR = 'hangar';
@@ -21,7 +26,7 @@ export class ProfileEquipmentIndex {
readonly #weapons = new Map<string, BlkBlock>(); readonly #weapons = new Map<string, BlkBlock>();
readonly #modsResearch = new Map<string, BlkBlock>(); readonly #modsResearch = new Map<string, BlkBlock>();
readonly #removedResearch = new Set<string>(); readonly #removedResearch = new Set<string>();
#modificationsBlock: BlkBlock | undefined; readonly #modificationsBlocks: BlkBlock[];
#weaponsBlock: BlkBlock | undefined; #weaponsBlock: BlkBlock | undefined;
#modsResearchBlock: BlkBlock | undefined; #modsResearchBlock: BlkBlock | undefined;
@@ -30,9 +35,9 @@ export class ProfileEquipmentIndex {
const hangar = findBlock(profile, HANGAR); const hangar = findBlock(profile, HANGAR);
if (hangar) for (const entry of hangar.blocks) this.#hangar.set(entry.name, entry); if (hangar) for (const entry of hangar.blocks) this.#hangar.set(entry.name, entry);
this.#modificationsBlock = findBlock(profile, MODIFICATIONS); this.#modificationsBlocks = allModificationBlocks(profile);
if (this.#modificationsBlock) { for (const chunk of this.#modificationsBlocks) {
for (const entry of this.#modificationsBlock.blocks) this.#modifications.set(entry.name, entry); for (const entry of chunk.blocks) this.#modifications.set(entry.name, entry);
} }
this.#weaponsBlock = findBlock(profile, WEAPONS); this.#weaponsBlock = findBlock(profile, WEAPONS);
@@ -103,14 +108,32 @@ export class ProfileEquipmentIndex {
const key = recordName(vehicle, modification); const key = recordName(vehicle, modification);
let block = this.#modifications.get(key); let block = this.#modifications.get(key);
if (!block) { if (!block) {
this.#modificationsBlock ??= ensureBlock(this.#profile, MODIFICATIONS);
block = { name: key, params: [], blocks: [] }; block = { name: key, params: [], blocks: [] };
this.#modificationsBlock.blocks.push(block); this.#appendModificationBlock(block);
this.#modifications.set(key, block); this.#modifications.set(key, block);
} }
block.params = orderedModParams(record); block.params = orderedModParams(record);
} }
#appendModificationBlock(entry: BlkBlock): void {
for (let index = this.#modificationsBlocks.length - 1; index >= 0; index--) {
const chunk = this.#modificationsBlocks[index]!;
if (chunk.blocks.length < MAX_MODIFICATION_BLOCK_ENTRIES) {
chunk.blocks.push(entry);
return;
}
}
const nextChunk: BlkBlock = { name: MODIFICATIONS, params: [], blocks: [entry] };
const lastChunk = this.#modificationsBlocks[this.#modificationsBlocks.length - 1];
if (lastChunk) {
const insertAt = this.#profile.blocks.lastIndexOf(lastChunk) + 1;
this.#profile.blocks.splice(insertAt, 0, nextChunk);
} else {
this.#profile.blocks.push(nextChunk);
}
this.#modificationsBlocks.push(nextChunk);
}
weaponRecord(vehicle: string, weapon: string): WeaponRecord | undefined { weaponRecord(vehicle: string, weapon: string): WeaponRecord | undefined {
const block = this.#weapons.get(`${vehicle}_${weapon}`); const block = this.#weapons.get(`${vehicle}_${weapon}`);
if (!block) return undefined; if (!block) return undefined;
@@ -11,7 +11,7 @@
*/ */
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk'; import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts'; import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts';
import { recordName } from '../profile/profile-modifications.ts'; import { allModificationBlocks, appendModificationEntry, recordName } from '../profile/profile-modifications.ts';
import type { EquipmentCatalogue } from './equipment-catalogue.ts'; import type { EquipmentCatalogue } from './equipment-catalogue.ts';
export interface SupportPlaneModification { export interface SupportPlaneModification {
@@ -31,7 +31,10 @@ export interface SupportUnitEquipmentGrants {
} }
export function supportPlaneModifications( export function supportPlaneModifications(
rules: Pick<BattleSpawnRulesData, 'supportPlanes' | 'strikeUcavs'>, rules: Pick<
BattleSpawnRulesData,
'supportPlanes' | 'strikeUcavs' | 'nuclearEscalationTacticalCarriers' | 'nuclearEscalationStrategicBombers'
>,
catalogue: EquipmentCatalogue, catalogue: EquipmentCatalogue,
): SupportUnitEquipmentGrants { ): SupportUnitEquipmentGrants {
const seenMods = new Set<string>(); const seenMods = new Set<string>();
@@ -53,21 +56,34 @@ export function supportPlaneModifications(
weapons.push({ vehicle, weapon, count: Math.max(1, count) }); weapons.push({ vehicle, weapon, count: Math.max(1, count) });
}; };
const grantWeaponPreset = (unitName: string, weapon: string): void => {
const facts = catalogue.weapon(unitName, weapon);
addWeapon(unitName, weapon, facts?.maxCount ?? 1);
for (const modification of facts?.requires ?? []) addMod(unitName, modification);
for (const container of facts?.sumWeapons ?? []) {
const containerFacts = catalogue.weapon(unitName, container);
addWeapon(unitName, container, containerFacts?.maxCount ?? 1);
for (const modification of containerFacts?.requires ?? []) addMod(unitName, modification);
}
};
for (const presets of Object.values(rules.supportPlanes)) { for (const presets of Object.values(rules.supportPlanes)) {
for (const preset of presets) { for (const preset of presets) {
for (const { unitName, weapon } of Object.values(preset.units)) { for (const { unitName, weapon } of Object.values(preset.units)) {
const facts = catalogue.weapon(unitName, weapon); grantWeaponPreset(unitName, weapon);
addWeapon(unitName, weapon, facts?.maxCount ?? 1);
for (const modification of facts?.requires ?? []) addMod(unitName, modification);
for (const container of facts?.sumWeapons ?? []) {
const containerFacts = catalogue.weapon(unitName, container);
addWeapon(unitName, container, containerFacts?.maxCount ?? 1);
for (const modification of containerFacts?.requires ?? []) addMod(unitName, modification);
}
} }
} }
} }
for (const carrier of [
...rules.nuclearEscalationTacticalCarriers,
...rules.nuclearEscalationStrategicBombers,
]) {
for (const weapon of carrier.weapons) {
grantWeaponPreset(carrier.unitName, weapon.name);
}
}
for (const ucav of rules.strikeUcavs) { for (const ucav of rules.strikeUcavs) {
const vehicle = catalogue.vehicle(ucav.unitName); const vehicle = catalogue.vehicle(ucav.unitName);
if (!vehicle) continue; if (!vehicle) continue;
@@ -82,13 +98,14 @@ export function supportPlaneModifications(
export function grantSupportPlaneModifications(profile: BlkBlock, grants: SupportUnitEquipmentGrants): void { export function grantSupportPlaneModifications(profile: BlkBlock, grants: SupportUnitEquipmentGrants): void {
if (grants.modifications.length > 0) { if (grants.modifications.length > 0) {
let modsBlock = findBlock(profile, 'modifications'); const existing = new Set<string>();
const existing = new Set((modsBlock?.blocks ?? []).map((entry) => entry.name)); for (const chunk of allModificationBlocks(profile)) {
for (const entry of chunk.blocks) existing.add(entry.name);
}
for (const { vehicle, modification } of grants.modifications) { for (const { vehicle, modification } of grants.modifications) {
const key = recordName(vehicle, modification); const key = recordName(vehicle, modification);
if (existing.has(key)) continue; if (existing.has(key)) continue;
modsBlock ??= ensureBlock(profile, 'modifications'); appendModificationEntry(profile, { name: key, params: [{ name: 'count', value: { type: 'int64', value: 1n } }], blocks: [] });
modsBlock.blocks.push({ name: key, params: [{ name: 'count', value: { type: 'int64', value: 1n } }], blocks: [] });
existing.add(key); existing.add(key);
} }
} }
@@ -0,0 +1,21 @@
import type { BlkBlock } from '@wto/blk';
import { ownsVehicle, setVehicleMrankDelta } from '../profile/profile-hangar.ts';
import { modificationRecord } from '../profile/profile-modifications.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
export function selectVehicleMrankDelta(
profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, delta: number,
): RuleOutcome {
const equipment = catalogue.vehicle(vehicle);
if (!equipment || !ownsVehicle(profile, vehicle) || !Number.isInteger(delta) || delta < 0) return refused('BAD_PARAMS');
// Stock getSelectableAddMranks offers zero and each positive addMrank on an owned modification.
if (delta > 0 && !equipment.modifications.some((modification) =>
modification.addMrank === delta && (modificationRecord(profile, vehicle, modification.name)?.count ?? 0) > 0)) {
return refused('NOT_AVAILABLE');
}
setVehicleMrankDelta(profile, vehicle, delta);
return ACCEPTED;
}
+82
View File
@@ -0,0 +1,82 @@
/**
* HTTP router service that exposes mod-registered routes under `/mods/<modId>/...`
* so mods can provide custom APIs or embedded-browser pages without touching core routes.
*/
import type { ModHttpHandler, ModHttpRequest } from '@wto/mods';
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
export interface RegisteredModHttpRoute {
readonly modId: string;
/** Full normalized path prefix or exact path under `/mods/<modId>/...`. */
readonly pattern: string;
readonly isWildcard: boolean;
readonly prefix: string;
readonly handler: ModHttpHandler;
}
export class ModHttpService implements Service {
readonly name = 'mods-http';
readonly #routes: readonly RegisteredModHttpRoute[];
constructor(routes: readonly RegisteredModHttpRoute[]) {
this.#routes = routes;
}
accepts(request: ServiceRequest): boolean {
if (request.originalHost !== undefined) return false;
return this.#match(request.path) !== undefined;
}
async handle(request: ServiceRequest): Promise<ServiceResponse> {
const matched = this.#match(request.path);
if (!matched) {
return { status: 404, body: 'mod route not found' };
}
const headers: Record<string, string | undefined> = {};
for (const [key, value] of Object.entries(request.headers)) {
headers[key] = Array.isArray(value) ? value[0] : value;
}
const query: Record<string, string> = {};
for (const [key, value] of request.query.entries()) query[key] = value;
const modReq: ModHttpRequest = {
method: request.method,
path: request.path,
query,
headers,
body: request.body,
};
const answer = await matched.handler(modReq);
const responseHeaders: Record<string, string> = { ...(answer.headers ?? {}) };
if (answer.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) {
responseHeaders['content-type'] = answer.contentType;
}
return {
status: answer.status ?? 200,
headers: responseHeaders,
body: answer.body,
logNotes: { summary: `mod:${matched.modId} ${request.method} ${request.path}` },
};
}
#match(path: string): RegisteredModHttpRoute | undefined {
for (const route of this.#routes) {
if (route.isWildcard) {
if (path.startsWith(route.prefix)) return route;
} else if (path === route.pattern) {
return route;
}
}
return undefined;
}
}
export function buildModHttpRoute(modId: string, subPath: string, handler: ModHttpHandler): RegisteredModHttpRoute {
const cleaned = subPath.startsWith('/') ? subPath : `/${subPath}`;
const full = `/mods/${modId}${cleaned === '/' ? '' : cleaned}`;
if (full.endsWith('/*')) {
const prefix = full.slice(0, -1); // keeps trailing '/'
return { modId, pattern: full, isWildcard: true, prefix, handler };
}
return { modId, pattern: full, isWildcard: false, prefix: full, handler };
}
+55
View File
@@ -0,0 +1,55 @@
/**
* Isolated JSON storage for server mods:
* - per-player files under `<dataFolder>/saves/<userId>/mods/<safeModId>.json`
* - shared mod state under `<dataFolder>/mods-data/<safeModId>.json`
*
* Keeping mod state outside `profile.blk` guarantees uninstalling a mod never corrupts stock saves.
*/
import { existsSync, readFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import type { ModPlayerStorage, ModStorageApi } from '@wto/mods';
import { writeFileAtomic } from '../storage/atomic-file.ts';
export function createModStorage(dataFolder: string, modId: string): ModStorageApi {
const safeMod = sanitizeSegment(modId);
return {
forPlayer(userId: string): ModPlayerStorage {
const safeUser = sanitizeSegment(userId);
const filePath = join(dataFolder, 'saves', safeUser, 'mods', `${safeMod}.json`);
return createJsonFileStorage(filePath);
},
shared(): ModPlayerStorage {
const filePath = join(dataFolder, 'mods-data', `${safeMod}.json`);
return createJsonFileStorage(filePath);
},
};
}
function createJsonFileStorage(filePath: string): ModPlayerStorage {
return {
read<T = unknown>(): T | undefined {
if (!existsSync(filePath)) return undefined;
try {
return JSON.parse(readFileSync(filePath, 'utf8')) as T;
} catch {
return undefined;
}
},
write(value: unknown): void {
writeFileAtomic(filePath, JSON.stringify(value, null, 2));
},
remove(): void {
try {
rmSync(filePath, { force: true });
} catch { /* ignore */ }
},
};
}
function sanitizeSegment(raw: string): string {
const cleaned = raw.replace(/[^A-Za-z0-9._-]/g, '_');
if (!cleaned || cleaned === '.' || cleaned === '..') {
throw new Error(`invalid storage path segment "${raw}"`);
}
return cleaned;
}
+362
View File
@@ -0,0 +1,362 @@
/**
* Experimental server-side JS/TS mod runtime.
*
* Loads each enabled mod's server script entry (`.ts`, `.mjs`, or `.js` via Node 24's built-in
* TypeScript stripping and ESM dynamic import), injects an isolated `WtoServerModContext`, and
* coordinates lifecycle hooks, profile/battle hooks, char/matching wrappers, and `/mods/<id>/*`
* HTTP routes.
*/
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import type { BlkBlock } from '@wto/blk';
import {
MOD_API_VERSION,
type BattleFilterMissionsContext,
type BattleLiveFactContext,
type BattleMatchmakeContext,
type BattleMissionCandidate,
type BattleSettlementContext,
type DiscoveredMod,
type ModCharHandler,
type ModCharRequest,
type ModCharResponse,
type ModCharWrapper,
type ModHttpHandler,
type ModMatchingHandler,
type ModMatchingRequest,
type ModMatchingWrapper,
type ServerModCataloguesView,
type ServerModDatasetsView,
type WtoServerMod,
type WtoServerModContext,
} from '@wto/mods';
import type { MatchingRequestHandler, MatchingRequestTable } from '../matching/matching-requests.ts';
import { buildModHttpRoute, ModHttpService, type RegisteredModHttpRoute } from './mod-http-service.ts';
import { createModStorage } from './mod-storage.ts';
interface RuntimeInitOptions {
readonly mods: readonly DiscoveredMod[];
readonly gameFolder: string;
readonly dataFolder: string;
readonly port: number;
readonly report: (line: string) => void;
}
interface ScopedHandler<T> {
readonly modId: string;
readonly fn: T;
}
export class ServerModRuntime {
readonly #report: (line: string) => void;
readonly #loadedModIds: string[] = [];
readonly #onDatasetsLoaded: ScopedHandler<(datasets: ServerModDatasetsView) => void | Promise<void>>[] = [];
readonly #onCataloguesReady: ScopedHandler<(catalogues: ServerModCataloguesView) => void | Promise<void>>[] = [];
readonly #onServerListening: ScopedHandler<(info: { readonly port: number }) => void | Promise<void>>[] = [];
readonly #onServerClosing: ScopedHandler<() => void | Promise<void>>[] = [];
readonly #onProfileRefresh: ScopedHandler<(profile: BlkBlock, userId: string) => void>[] = [];
readonly #onBeforeMatchmake: ScopedHandler<(ctx: BattleMatchmakeContext) => void>[] = [];
readonly #onFilterMissions: ScopedHandler<(ctx: BattleFilterMissionsContext) => readonly BattleMissionCandidate[] | void>[] = [];
readonly #onLiveFact: ScopedHandler<(ctx: BattleLiveFactContext) => void>[] = [];
readonly #onAfterSettle: ScopedHandler<(ctx: BattleSettlementContext) => void>[] = [];
readonly #charHandlers = new Map<string, ScopedHandler<ModCharHandler>>();
readonly #charWrappers = new Map<string, ScopedHandler<ModCharWrapper>[]>();
readonly #matchingHandlers = new Map<string, ScopedHandler<ModMatchingHandler>>();
readonly #matchingWrappers = new Map<string, ScopedHandler<ModMatchingWrapper>[]>();
readonly #httpRoutes: RegisteredModHttpRoute[] = [];
private constructor(report: (line: string) => void) {
this.#report = report;
}
static async load(options: RuntimeInitOptions): Promise<ServerModRuntime> {
const runtime = new ServerModRuntime(options.report);
const scriptMods = options.mods.filter((mod) => mod.content.serverEntry !== undefined);
if (scriptMods.length === 0) return runtime;
const cacheBust = Date.now();
for (const mod of scriptMods) {
const entryRel = mod.content.serverEntry!;
const entryAbs = join(mod.rootDir, ...entryRel.split('/'));
const modId = mod.manifest.id;
const url = `${pathToFileURL(entryAbs).href}?wto_mod=${cacheBust}`;
let loadedModule: Record<string, unknown>;
try {
loadedModule = (await import(url)) as Record<string, unknown>;
} catch (error) {
throw new Error(
`Failed to load server mod "${modId}" (${entryRel}): ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
);
}
const modExport = resolveModExport(loadedModule);
if (!modExport) {
throw new Error(
`Server mod "${modId}" (${entryRel}) must export default { setup(ctx) { ... } } or named setup(ctx)`,
);
}
const ctx = runtime.#createContext(mod, options);
try {
await modExport.setup(ctx);
} catch (error) {
throw new Error(
`Server mod "${modId}" setup() failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
);
}
runtime.#loadedModIds.push(modId);
options.report(`mod ${modId}: server script loaded (${entryRel})`);
}
return runtime;
}
get loadedModIds(): readonly string[] {
return this.#loadedModIds;
}
async runDatasetsLoaded(view: ServerModDatasetsView): Promise<void> {
for (const { modId, fn } of this.#onDatasetsLoaded) {
try {
await fn(view);
} catch (error) {
throw new Error(`Server mod "${modId}" onDatasetsLoaded failed: ${formatError(error)}`);
}
}
}
async runCataloguesReady(view: ServerModCataloguesView): Promise<void> {
for (const { modId, fn } of this.#onCataloguesReady) {
try {
await fn(view);
} catch (error) {
throw new Error(`Server mod "${modId}" onCataloguesReady failed: ${formatError(error)}`);
}
}
}
async runServerListening(port: number): Promise<void> {
for (const { modId, fn } of this.#onServerListening) {
try {
await fn({ port });
} catch (error) {
this.#report(`[mod:${modId}] onServerListening error: ${formatError(error)}`);
}
}
}
async runServerClosing(): Promise<void> {
for (const { modId, fn } of [...this.#onServerClosing].reverse()) {
try {
await fn();
} catch (error) {
this.#report(`[mod:${modId}] onServerClosing error: ${formatError(error)}`);
}
}
}
runProfileRefresh(profile: BlkBlock, userId: string): void {
for (const { modId, fn } of this.#onProfileRefresh) {
try {
fn(profile, userId);
} catch (error) {
this.#report(`[mod:${modId}] profile.onRefresh error: ${formatError(error)}`);
}
}
}
runBattleBeforeMatchmake(ctx: BattleMatchmakeContext): void {
for (const { modId, fn } of this.#onBeforeMatchmake) {
try {
fn(ctx);
} catch (error) {
this.#report(`[mod:${modId}] battle.onBeforeMatchmake error: ${formatError(error)}`);
}
}
}
runBattleFilterMissions<T extends BattleMissionCandidate>(
ctx: Omit<BattleFilterMissionsContext, 'missions'> & { readonly missions: readonly T[] },
): readonly T[] {
if (this.#onFilterMissions.length === 0) return ctx.missions;
let current: readonly T[] = ctx.missions;
for (const { modId, fn } of this.#onFilterMissions) {
try {
const next = fn({ ...ctx, missions: current });
if (Array.isArray(next)) {
const allowed = new Set(next.map((item) => item.name));
const filtered = current.filter((item) => allowed.has(item.name));
if (filtered.length > 0) {
current = filtered;
} else {
this.#report(`[mod:${modId}] battle.onFilterMissions returned 0 matching candidates for ${ctx.modeName}; keeping previous pool`);
}
}
} catch (error) {
this.#report(`[mod:${modId}] battle.onFilterMissions error: ${formatError(error)}`);
}
}
return current;
}
runBattleLiveFact(ctx: BattleLiveFactContext): void {
for (const { modId, fn } of this.#onLiveFact) {
try {
fn(ctx);
} catch (error) {
this.#report(`[mod:${modId}] battle.onLiveFact error: ${formatError(error)}`);
}
}
}
runBattleAfterSettle(ctx: BattleSettlementContext): void {
for (const { modId, fn } of this.#onAfterSettle) {
try {
fn(ctx);
} catch (error) {
this.#report(`[mod:${modId}] battle.onAfterSettle error: ${formatError(error)}`);
}
}
}
hasCharOverride(action: string): boolean {
return this.#charHandlers.has(action) || this.#charWrappers.has(action);
}
async dispatchCharOverride(
action: string,
request: ModCharRequest,
baseDispatch: (req: ModCharRequest) => Promise<ModCharResponse>,
): Promise<ModCharResponse> {
const custom = this.#charHandlers.get(action);
const terminal: (req: ModCharRequest) => Promise<ModCharResponse> = custom
? async (req) => await custom.fn(req)
: baseDispatch;
const wrappers = this.#charWrappers.get(action);
if (!wrappers || wrappers.length === 0) return terminal(request);
let chain = terminal;
for (let i = wrappers.length - 1; i >= 0; i -= 1) {
const wrapper = wrappers[i]!.fn;
const next = chain;
chain = async (req) => await wrapper(req, next);
}
return chain(request);
}
applyMatchingRoutes(baseTable: MatchingRequestTable): MatchingRequestTable {
if (this.#matchingHandlers.size === 0 && this.#matchingWrappers.size === 0) {
return baseTable;
}
const merged = new Map<string, MatchingRequestHandler>(baseTable);
for (const [method, custom] of this.#matchingHandlers) {
merged.set(method, (request, session) => custom.fn({
method,
params: request.params,
userId: session.authenticatedUserId(),
}));
}
for (const [method, wrappers] of this.#matchingWrappers) {
const original = merged.get(method);
merged.set(method, (request, session) => {
const baseFn = (req: ModMatchingRequest): Record<string, unknown> => (
original ? original({ ...request, params: req.params }, session) : {}
);
let chain = baseFn;
for (let i = wrappers.length - 1; i >= 0; i -= 1) {
const wrap = wrappers[i]!.fn;
const next = chain;
chain = (req) => wrap(req, next);
}
return chain({
method,
params: request.params,
userId: session.authenticatedUserId(),
});
});
}
return merged;
}
httpService(): ModHttpService {
return new ModHttpService(this.#httpRoutes);
}
#createContext(mod: DiscoveredMod, options: RuntimeInitOptions): WtoServerModContext {
const modId = mod.manifest.id;
return {
apiVersion: MOD_API_VERSION,
manifest: mod.manifest,
modDir: mod.rootDir,
gameFolder: options.gameFolder,
dataFolder: options.dataFolder,
port: options.port,
logger: {
info: (message) => options.report(`[mod:${modId}] ${message}`),
warn: (message) => options.report(`[mod:${modId}] WARN: ${message}`),
error: (message) => options.report(`[mod:${modId}] ERROR: ${message}`),
},
storage: createModStorage(options.dataFolder, modId),
hooks: {
onDatasetsLoaded: (fn) => { this.#onDatasetsLoaded.push({ modId, fn }); },
onCataloguesReady: (fn) => { this.#onCataloguesReady.push({ modId, fn }); },
onServerListening: (fn) => { this.#onServerListening.push({ modId, fn }); },
onServerClosing: (fn) => { this.#onServerClosing.push({ modId, fn }); },
profile: {
onRefresh: (fn) => { this.#onProfileRefresh.push({ modId, fn }); },
},
battle: {
onBeforeMatchmake: (fn) => { this.#onBeforeMatchmake.push({ modId, fn }); },
onFilterMissions: (fn) => { this.#onFilterMissions.push({ modId, fn }); },
onLiveFact: (fn) => { this.#onLiveFact.push({ modId, fn }); },
onAfterSettle: (fn) => { this.#onAfterSettle.push({ modId, fn }); },
},
},
routes: {
char: {
register: (action, fn) => { this.#charHandlers.set(action, { modId, fn }); },
wrap: (action, fn) => {
const list = this.#charWrappers.get(action) ?? [];
list.push({ modId, fn });
this.#charWrappers.set(action, list);
},
},
matching: {
register: (method, fn) => { this.#matchingHandlers.set(method, { modId, fn }); },
wrap: (method, fn) => {
const list = this.#matchingWrappers.get(method) ?? [];
list.push({ modId, fn });
this.#matchingWrappers.set(method, list);
},
},
http: {
register: (subPath: string, handler: ModHttpHandler) => {
this.#httpRoutes.push(buildModHttpRoute(modId, subPath, handler));
},
},
},
};
}
}
function resolveModExport(mod: Record<string, unknown>): WtoServerMod | undefined {
const def = mod.default;
if (def && typeof def === 'object' && typeof (def as Record<string, unknown>).setup === 'function') {
return def as WtoServerMod;
}
if (typeof def === 'function') {
return { setup: def as WtoServerMod['setup'] };
}
if (typeof mod.setup === 'function') {
return { setup: mod.setup as WtoServerMod['setup'] };
}
return undefined;
}
function formatError(error: unknown): string {
return error instanceof Error ? error.stack ?? error.message : String(error);
}
+20 -5
View File
@@ -1,19 +1,24 @@
/** /**
* Owned vehicles in the profile, as in Gaijin's * The profile's hangar has one sub-block per owned vehicle, as in config/default_user.blk.
* config/default_user.blk: one empty sub-block per vehicle the player owns.
* *
* hangar{ * hangar{
* bf2c_1{ * bf2c_1{
* } * }
* } * }
*/ */
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk'; import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
import { intField } from './blk-fields.ts';
const HANGAR = 'hangar'; const HANGAR = 'hangar';
const MRANK_DELTA = 'mrankDelta';
function ownedVehicle(profile: BlkBlock, vehicle: string): BlkBlock | undefined {
const hangar = findBlock(profile, HANGAR);
return hangar && findBlock(hangar, vehicle);
}
export function ownsVehicle(profile: BlkBlock, vehicle: string): boolean { export function ownsVehicle(profile: BlkBlock, vehicle: string): boolean {
const hangar = findBlock(profile, HANGAR); return ownedVehicle(profile, vehicle) !== undefined;
return hangar !== undefined && findBlock(hangar, vehicle) !== undefined;
} }
export function ownedVehicles(profile: BlkBlock): Set<string> { export function ownedVehicles(profile: BlkBlock): Set<string> {
@@ -25,3 +30,13 @@ export function addOwnedVehicle(profile: BlkBlock, vehicle: string): void {
const hangar = ensureBlock(profile, HANGAR); const hangar = ensureBlock(profile, HANGAR);
if (!hangar.blocks.some((owned) => owned.name === vehicle)) hangar.blocks.push({ name: vehicle, params: [], blocks: [] }); if (!hangar.blocks.some((owned) => owned.name === vehicle)) hangar.blocks.push({ name: vehicle, params: [], blocks: [] });
} }
/** The stock client uses the base rank until it has a non-negative selection. */
export function vehicleMrankDelta(profile: BlkBlock, vehicle: string): number {
return Math.max(0, intField(ownedVehicle(profile, vehicle), MRANK_DELTA));
}
export function setVehicleMrankDelta(profile: BlkBlock, vehicle: string, delta: number): void {
const entry = ownedVehicle(profile, vehicle);
if (entry) setParam(entry, MRANK_DELTA, { type: 'int', value: delta });
}
@@ -17,12 +17,20 @@
* script function get_mission_progress (0x179c900 -> 0xebad60) looks up. It returns the * script function get_mission_progress (0x179c900 -> 0xebad60) looks up. It returns the
* highest difficulty completed (0, 1, 2), or 3 or more when there is none. * highest difficulty completed (0, 1, 2), or 3 or more when there is none.
*/ */
import { ensureBlock, setParam, type BlkBlock } from '@wto/blk'; import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const PVE_PROGRESS = 'pveProgress'; const PVE_PROGRESS = 'pveProgress';
const MISSIONS = 'missions'; const MISSIONS = 'missions';
const DIFFICULTIES = [0, 1, 2] as const; const DIFFICULTIES = [0, 1, 2] as const;
export function hasCompletedMissionDifficulty(profile: BlkBlock, fullMissionName: string, difficulty: 0 | 1 | 2): boolean {
const pve = findBlock(profile, PVE_PROGRESS);
const missions = pve && findBlock(pve, MISSIONS);
const mission = missions && findBlock(missions, fullMissionName);
const flag = mission && findParam(mission, `diff_${difficulty}`)?.value;
return flag?.type === 'bool' && flag.value;
}
/** Record the mission as completed on every difficulty up to and including `highest` (0, 1 or 2). */ /** Record the mission as completed on every difficulty up to and including `highest` (0, 1 or 2). */
export function recordMissionCompleted(profile: BlkBlock, fullMissionName: string, highest: 0 | 1 | 2): void { export function recordMissionCompleted(profile: BlkBlock, fullMissionName: string, highest: 0 | 1 | 2): void {
const entry = ensureBlock(ensureBlock(ensureBlock(profile, PVE_PROGRESS), MISSIONS), fullMissionName); const entry = ensureBlock(ensureBlock(ensureBlock(profile, PVE_PROGRESS), MISSIONS), fullMissionName);
@@ -12,11 +12,19 @@
* the first one that does not match (aces.exe 0x942740), so a record is always rewritten whole: * the first one that does not match (aces.exe 0x942740), so a record is always rewritten whole:
* wpSpent:i goldSpent:i lastWpCost:i lastGoldCost:i persist:b rpEarned:i enabled:b count:i64 modLevel:i * wpSpent:i goldSpent:i lastWpCost:i lastGoldCost:i persist:b rpEarned:i enabled:b count:i64 modLevel:i
* Absent values are left out; enabled is only written when false (the default is enabled). * Absent values are left out; enabled is only written when false (the default is enabled).
*
* Dagor's binary DataBlock stores child block counts in a uint16 (65,535 max). Because the full
* vehicle catalogue exceeds 65,535 modifications, aces.exe splits modifications across up to 3
* sibling top-level `modifications` blocks of at most 65,535 entries each (2.61.0.37 0x938fae..0x9397e6,
* 2.61.0.58 0x93ba70 / 0x93bb53). All readers and writers here span every sibling block.
*/ */
import { ensureBlock, findBlock, type BlkBlock, type BlkParam } from '@wto/blk'; import type { BlkBlock, BlkParam } from '@wto/blk';
const MODIFICATIONS = 'modifications'; const MODIFICATIONS = 'modifications';
/** Maximum entries per `modifications` DataBlock (uint16 child count limit in aces.exe 0x939000 / 0x93ba70). */
export const MAX_MODIFICATION_BLOCK_ENTRIES = 0xffff;
export interface ModificationRecord { export interface ModificationRecord {
readonly silverLionsSpent: number; readonly silverLionsSpent: number;
readonly goldenEaglesSpent: number; readonly goldenEaglesSpent: number;
@@ -29,9 +37,66 @@ export function recordName(vehicle: string, modification: string): string {
return `${vehicle}_${modification}`; return `${vehicle}_${modification}`;
} }
/** Every top-level `modifications` chunk in the profile, in document order. */
export function allModificationBlocks(profile: BlkBlock): BlkBlock[] {
return profile.blocks.filter((block) => block.name === MODIFICATIONS);
}
/** Append a new modification entry to a chunk with spare capacity, opening a sibling chunk when full. */
export function appendModificationEntry(profile: BlkBlock, entry: BlkBlock): void {
const chunks = allModificationBlocks(profile);
for (let index = chunks.length - 1; index >= 0; index--) {
const chunk = chunks[index]!;
if (chunk.blocks.length < MAX_MODIFICATION_BLOCK_ENTRIES) {
chunk.blocks.push(entry);
return;
}
}
const nextChunk: BlkBlock = { name: MODIFICATIONS, params: [], blocks: [entry] };
const lastChunk = chunks[chunks.length - 1];
if (lastChunk) {
const insertAt = profile.blocks.lastIndexOf(lastChunk) + 1;
profile.blocks.splice(insertAt, 0, nextChunk);
} else {
profile.blocks.push(nextChunk);
}
}
/** Ensure every top-level `modifications` chunk stays within the 65,535-child DataBlock limit. */
export function normalizeModificationBlocks(profile: BlkBlock): void {
const chunks = allModificationBlocks(profile);
if (chunks.length === 0) return;
const needsRebalance = chunks.some((chunk) => chunk.blocks.length > MAX_MODIFICATION_BLOCK_ENTRIES)
|| (chunks.length > 1 && chunks.some((chunk) => chunk.blocks.length === 0));
if (!needsRebalance) return;
const firstIndex = profile.blocks.findIndex((block) => block.name === MODIFICATIONS);
const entries = chunks.flatMap((chunk) => chunk.blocks);
profile.blocks = profile.blocks.filter((block) => block.name !== MODIFICATIONS);
if (entries.length === 0) return;
const rebuilt: BlkBlock[] = [];
for (let offset = 0; offset < entries.length; offset += MAX_MODIFICATION_BLOCK_ENTRIES) {
rebuilt.push({
name: MODIFICATIONS,
params: [],
blocks: entries.slice(offset, offset + MAX_MODIFICATION_BLOCK_ENTRIES),
});
}
profile.blocks.splice(Math.max(0, firstIndex), 0, ...rebuilt);
}
function findModificationEntry(profile: BlkBlock, key: string): BlkBlock | undefined {
for (const chunk of profile.blocks) {
if (chunk.name !== MODIFICATIONS) continue;
const found = chunk.blocks.find((entry) => entry.name === key);
if (found) return found;
}
return undefined;
}
export function modificationRecord(profile: BlkBlock, vehicle: string, modification: string): ModificationRecord | undefined { export function modificationRecord(profile: BlkBlock, vehicle: string, modification: string): ModificationRecord | undefined {
const block = findBlock(profile, MODIFICATIONS); const record = findModificationEntry(profile, recordName(vehicle, modification));
const record = block && findBlock(block, recordName(vehicle, modification));
if (!record) return undefined; if (!record) return undefined;
return { return {
silverLionsSpent: intOf(record, 'wpSpent'), silverLionsSpent: intOf(record, 'wpSpent'),
@@ -42,12 +107,17 @@ export function modificationRecord(profile: BlkBlock, vehicle: string, modificat
} }
export function ownsModification(profile: BlkBlock, vehicle: string, modification: string): boolean { export function ownsModification(profile: BlkBlock, vehicle: string, modification: string): boolean {
return modificationRecord(profile, vehicle, modification) !== undefined; return findModificationEntry(profile, recordName(vehicle, modification)) !== undefined;
} }
export function writeModificationRecord(profile: BlkBlock, vehicle: string, modification: string, record: ModificationRecord): void { export function writeModificationRecord(profile: BlkBlock, vehicle: string, modification: string, record: ModificationRecord): void {
const block = ensureBlock(ensureBlock(profile, MODIFICATIONS), recordName(vehicle, modification)); const key = recordName(vehicle, modification);
block.params = orderedParams(record); const existing = findModificationEntry(profile, key);
if (existing) {
existing.params = orderedParams(record);
return;
}
appendModificationEntry(profile, { name: key, params: orderedParams(record), blocks: [] });
} }
function orderedParams(record: ModificationRecord): BlkParam[] { function orderedParams(record: ModificationRecord): BlkParam[] {
+3
View File
@@ -5,6 +5,7 @@
* (with the modifications the mission support planes' presets need) and the free repair over time (repair/repair-over-time.ts) kept up to date and persisted on * (with the modifications the mission support planes' presets need) and the free repair over time (repair/repair-over-time.ts) kept up to date and persisted on
* every read or write. * every read or write.
*/ */
import type { BlkBlock } from '@wto/blk';
import type { AccountStore } from './accounts/account-store.ts'; import type { AccountStore } from './accounts/account-store.ts';
import type { ClanStore } from './clans/clan-store.ts'; import type { ClanStore } from './clans/clan-store.ts';
import type { DatasetCache } from './game-data/datasets/dataset-cache.ts'; import type { DatasetCache } from './game-data/datasets/dataset-cache.ts';
@@ -50,6 +51,7 @@ export function setUpProfiles(
tuning: Tuning, tuning: Tuning,
sync?: ProfileSyncContext, sync?: ProfileSyncContext,
vehicles: readonly CatalogueVehicle[] = datasets.load(vehicleCatalogue), vehicles: readonly CatalogueVehicle[] = datasets.load(vehicleCatalogue),
onProfileRefresh?: (profile: BlkBlock, userId: string) => void,
): ProfileServices { ): ProfileServices {
const startingContent: StartingContent = { const startingContent: StartingContent = {
reserveVehicles: datasets.load(reserveVehicles), reserveVehicles: datasets.load(reserveVehicles),
@@ -70,6 +72,7 @@ export function setUpProfiles(
removeExpiredItems(profile, serverTimeNow()); removeExpiredItems(profile, serverTimeNow());
repairVehiclesOverTime(profile, repair, serverTimeNow()); repairVehiclesOverTime(profile, repair, serverTimeNow());
trimUserLogs(profile, tuning.limits.userLogsKept); trimUserLogs(profile, tuning.limits.userLogsKept);
onProfileRefresh?.(profile, userId);
}); });
return { profiles, research, equipment, repair }; return { profiles, research, equipment, repair };
} }
+7 -9
View File
@@ -3,9 +3,9 @@ import { ClanStore } from '../clans/clan-store.ts';
import { DatasetCache } from '../game-data/datasets/dataset-cache.ts'; import { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
import { vehicleCatalogue } from '../game-data/datasets/vehicle-catalogue.ts'; import { vehicleCatalogue } from '../game-data/datasets/vehicle-catalogue.ts';
import { GameFiles } from '../game-data/game-files.ts'; import { GameFiles } from '../game-data/game-files.ts';
import { ProfileEquipmentIndex } from '../modifications/profile-equipment-index.ts';
import { addOwnedVehicle, ownedVehicles } from '../profile/profile-hangar.ts'; import { addOwnedVehicle, ownedVehicles } from '../profile/profile-hangar.ts';
import { ownsModification, writeModificationRecord } from '../profile/profile-modifications.ts'; import { researchPointsOf } from '../profile/profile-vehicle-research.ts';
import { researchPointsOf, setResearchPoints } from '../profile/profile-vehicle-research.ts';
import { setUpProfiles } from '../profiles-setup.ts'; import { setUpProfiles } from '../profiles-setup.ts';
import { TechTree } from '../research/tech-tree.ts'; import { TechTree } from '../research/tech-tree.ts';
import { loadTuning } from '../tuning/tuning.ts'; import { loadTuning } from '../tuning/tuning.ts';
@@ -15,7 +15,7 @@ export interface ResearchBranch {
readonly country: string; readonly country: string;
readonly type: string; readonly type: string;
} }
export type ResearchOperation = 'research' | 'purchase' | 'equipment'; export type ResearchOperation = 'purchase' | 'equipment';
function tree(location: SaveLocation) { function tree(location: SaveLocation) {
const gameFiles = new GameFiles(location.gameFolder); const gameFiles = new GameFiles(location.gameFolder);
@@ -52,21 +52,19 @@ export function editSaveResearch(location: SaveLocation, userId: string, branch:
const { profiles, equipment } = setUpProfiles(location.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles); const { profiles, equipment } = setUpProfiles(location.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
profiles.update(userId, (profile) => { profiles.update(userId, (profile) => {
const owned = ownedVehicles(profile); const owned = ownedVehicles(profile);
const index = operation === 'equipment' ? new ProfileEquipmentIndex(profile) : undefined;
for (const unit of units) { for (const unit of units) {
if (operation === 'research' && unit.kind === 'research' && !owned.has(unit.name)) {
setResearchPoints(profile, unit.name, Math.max(researchPointsOf(profile, unit.name), unit.researchPoints));
}
if (operation === 'purchase' && (unit.kind === 'research' || unit.kind === 'purchase')) { if (operation === 'purchase' && (unit.kind === 'research' || unit.kind === 'purchase')) {
addOwnedVehicle(profile, unit.name); addOwnedVehicle(profile, unit.name);
for (const part of unit.parts) addOwnedVehicle(profile, part); for (const part of unit.parts) addOwnedVehicle(profile, part);
} }
if (operation === 'equipment' && owned.has(unit.name)) { if (index && owned.has(unit.name)) {
const enabledGroups = new Set<string>(); const enabledGroups = new Set<string>();
for (const mod of equipment.vehicle(unit.name)?.modifications ?? []) { for (const mod of equipment.vehicle(unit.name)?.modifications ?? []) {
if (mod.name === 'premExpMul' || mod.goldenEagles > 0 || ownsModification(profile, unit.name, mod.name)) continue; if (mod.name === 'premExpMul' || mod.goldenEagles > 0 || index.ownsModification(unit.name, mod.name)) continue;
const enable = mod.defaultEnabled && (!mod.exclusiveGroup || !enabledGroups.has(mod.exclusiveGroup)); const enable = mod.defaultEnabled && (!mod.exclusiveGroup || !enabledGroups.has(mod.exclusiveGroup));
if (enable && mod.exclusiveGroup) enabledGroups.add(mod.exclusiveGroup); if (enable && mod.exclusiveGroup) enabledGroups.add(mod.exclusiveGroup);
writeModificationRecord(profile, unit.name, mod.name, { index.writeModificationRecord(unit.name, mod.name, {
silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: enable, count: Math.max(1, mod.maxCount), silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: enable, count: Math.max(1, mod.maxCount),
}); });
} }
+2
View File
@@ -11,6 +11,7 @@
import { existsSync, readFileSync } from 'node:fs'; import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path'; import { join } from 'node:path';
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk'; import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
import { normalizeModificationBlocks } from '../profile/profile-modifications.ts';
import { writeFileAtomic } from '../storage/atomic-file.ts'; import { writeFileAtomic } from '../storage/atomic-file.ts';
import type { SaveUpgrades } from './save-upgrades.ts'; import type { SaveUpgrades } from './save-upgrades.ts';
@@ -44,6 +45,7 @@ export class SaveStore {
saveProfile(userId: string, profile: BlkBlock): void { saveProfile(userId: string, profile: BlkBlock): void {
const now = new Date().toISOString(); const now = new Date().toISOString();
const previous = existsSync(this.#infoPath(userId)) ? (JSON.parse(readFileSync(this.#infoPath(userId), 'utf8')) as SaveInfo) : undefined; const previous = existsSync(this.#infoPath(userId)) ? (JSON.parse(readFileSync(this.#infoPath(userId), 'utf8')) as SaveInfo) : undefined;
normalizeModificationBlocks(profile);
writeFileAtomic(this.#profilePath(userId), encodeBlk(profile)); writeFileAtomic(this.#profilePath(userId), encodeBlk(profile));
const info: SaveInfo = { formatVersion: this.#upgrades.currentFormat, created: previous?.created ?? now, updated: now }; const info: SaveInfo = { formatVersion: this.#upgrades.currentFormat, created: previous?.created ?? now, updated: now };
writeFileAtomic(this.#infoPath(userId), JSON.stringify(info, null, 2)); writeFileAtomic(this.#infoPath(userId), JSON.stringify(info, null, 2));
+7 -3
View File
@@ -10,7 +10,7 @@ import { InventoryCatalogue } from '../inventory/itemdef-catalogue.ts';
import { intField, stringField } from '../profile/blk-fields.ts'; import { intField, stringField } from '../profile/blk-fields.ts';
import { allCrews } from '../profile/profile-crews.ts'; import { allCrews } from '../profile/profile-crews.ts';
import { ACTIVE_LISTS } from '../profile/profile-items.ts'; import { ACTIVE_LISTS } from '../profile/profile-items.ts';
import { recordName } from '../profile/profile-modifications.ts'; import { normalizeModificationBlocks, recordName } from '../profile/profile-modifications.ts';
import { loadTuning } from '../tuning/tuning.ts'; import { loadTuning } from '../tuning/tuning.ts';
import type { SaveLocation } from './save-editor.ts'; import type { SaveLocation } from './save-editor.ts';
@@ -38,9 +38,13 @@ export function prepareTransferredProfile(location: SaveLocation, bytes: Uint8Ar
['modifications', modifications], ['modsResearch', modifications], ['weapons', weapons], ['modifications', modifications], ['modsResearch', modifications], ['weapons', weapons],
] as const; ] as const;
for (const [key, allowed] of blockKeys) { for (const [key, allowed] of blockKeys) {
const collection = findBlock(profile, key); for (const collection of profile.blocks) {
if (collection) collection.blocks = collection.blocks.filter((entry) => allowed.has(entry.name)); if (collection.name === key) {
collection.blocks = collection.blocks.filter((entry) => allowed.has(entry.name));
}
}
} }
normalizeModificationBlocks(profile);
for (const crew of allCrews(profile)) { for (const crew of allCrews(profile)) {
const aircraft = findBlock(crew, 'aircrafts'); const aircraft = findBlock(crew, 'aircrafts');
if (aircraft) { if (aircraft) {
+161 -35
View File
@@ -1,8 +1,9 @@
/** /**
* Assemble the local server: data layer, save layer, rules, * Assemble the local server: data layer, save layer, rules, experimental additive mod runtime,
* protocol-layer services, and the single loopback listening port. * protocol-layer services, and the single loopback listening port.
*/ */
import type { Server } from 'node:net'; import type { Server } from 'node:net';
import type { DiscoveredMod, ServerModDatasetsView } from '@wto/mods';
import { AccountStore } from './accounts/account-store.ts'; import { AccountStore } from './accounts/account-store.ts';
import { RegistrationService } from './accounts/registration-service.ts'; import { RegistrationService } from './accounts/registration-service.ts';
import { BattleEconomy } from './battle/battle-economy.ts'; import { BattleEconomy } from './battle/battle-economy.ts';
@@ -16,7 +17,7 @@ import { CloudSettingsStore } from './cloud-settings/cloud-settings-store.ts';
import { CrewSkillCatalogue } from './crew/crew-skill-rules.ts'; import { CrewSkillCatalogue } from './crew/crew-skill-rules.ts';
import { DecorShop } from './decor/decor-purchase.ts'; import { DecorShop } from './decor/decor-purchase.ts';
import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts'; import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts';
import { battleEconomy } from './game-data/datasets/battle-economy.ts'; import { battleEconomy, type BattleEconomyData } from './game-data/datasets/battle-economy.ts';
import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts'; import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts';
import { researchEfficiency } from './game-data/datasets/research-efficiency.ts'; import { researchEfficiency } from './game-data/datasets/research-efficiency.ts';
import { ResearchEfficiency } from './research/research-efficiency.ts'; import { ResearchEfficiency } from './research/research-efficiency.ts';
@@ -31,11 +32,12 @@ import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts';
import { externalItemSources } from './game-data/datasets/external-item-sources.ts'; import { externalItemSources } from './game-data/datasets/external-item-sources.ts';
import { flightModelPresets } from './game-data/datasets/flight-model-presets.ts'; import { flightModelPresets } from './game-data/datasets/flight-model-presets.ts';
import { itemCatalogue } from './game-data/datasets/item-catalogue.ts'; import { itemCatalogue } from './game-data/datasets/item-catalogue.ts';
import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.ts'; import { multiplayerMissions, type MultiplayerMissions } from './game-data/datasets/multiplayer-missions.ts';
import { shopCountries } from './game-data/datasets/shop-countries.ts'; import { shopCountries } from './game-data/datasets/shop-countries.ts';
import { storeBundles } from './game-data/datasets/store-bundles.ts'; import { storeBundles } from './game-data/datasets/store-bundles.ts';
import { trainingMissions } from './game-data/datasets/training-missions.ts';
import { uiLabels, type UiLabels } from './game-data/datasets/ui-labels.ts'; import { uiLabels, type UiLabels } from './game-data/datasets/ui-labels.ts';
import { unitNames } from './game-data/datasets/unit-names.ts'; import { unitNames, type UnitNamesMap } from './game-data/datasets/unit-names.ts';
import { unlockPrices } from './game-data/datasets/unlock-prices.ts'; import { unlockPrices } from './game-data/datasets/unlock-prices.ts';
import { vehicleCatalogue, type CatalogueVehicle } from './game-data/datasets/vehicle-catalogue.ts'; import { vehicleCatalogue, type CatalogueVehicle } from './game-data/datasets/vehicle-catalogue.ts';
import { webIcons } from './game-data/datasets/web-icons.ts'; import { webIcons } from './game-data/datasets/web-icons.ts';
@@ -49,12 +51,14 @@ import { ItemCatalogue } from './items/item-catalogue.ts';
import { LoginService } from './login/login-service.ts'; import { LoginService } from './login/login-service.ts';
import { matchingRequests } from './matching/matching-requests.ts'; import { matchingRequests } from './matching/matching-requests.ts';
import type { MatchingService } from './matching/matching-service.ts'; import type { MatchingService } from './matching/matching-service.ts';
import { ServerModRuntime } from './mods/server-mod-runtime.ts';
import { setUpProfiles } from './profiles-setup.ts'; import { setUpProfiles } from './profiles-setup.ts';
import { createPortListener } from './transport/port-listener.ts'; import { createPortListener } from './transport/port-listener.ts';
import { Router } from './transport/router.ts'; import { Router } from './transport/router.ts';
import { loadOrCreateCredentials } from './transport/tls/tls-certificate.ts'; import { loadOrCreateCredentials } from './transport/tls/tls-certificate.ts';
import { StoreCatalogue } from './store/store-catalogue.ts'; import { StoreCatalogue } from './store/store-catalogue.ts';
import { StoreService } from './store/store-service.ts'; import { StoreService } from './store/store-service.ts';
import { TrainingCatalogue } from './training/training-completion.ts';
import { TrafficLog } from './traffic-log/traffic-log.ts'; import { TrafficLog } from './traffic-log/traffic-log.ts';
import { loadTuning, type Tuning } from './tuning/tuning.ts'; import { loadTuning, type Tuning } from './tuning/tuning.ts';
import { UnlockShop } from './unlocks/unlock-purchase.ts'; import { UnlockShop } from './unlocks/unlock-purchase.ts';
@@ -67,39 +71,100 @@ export interface ServerOptions {
/** Accounts, saves and logs. */ /** Accounts, saves and logs. */
readonly dataFolder: string; readonly dataFolder: string;
readonly port: number; readonly port: number;
/** Start-up progress lines (static data extraction, game modes). */ /** Start-up progress lines (static data extraction, game modes, mod loading). */
readonly report?: (line: string) => void; readonly report?: (line: string) => void;
/** Whether to write traffic logs under `<dataFolder>/logs`; defaults to true. */ /** Whether to write traffic logs under `<dataFolder>/logs`; defaults to true. */
readonly loggingEnabled?: boolean; readonly loggingEnabled?: boolean;
/** Ordered list of enabled additive mods to load for this session. */
readonly mods?: readonly DiscoveredMod[];
} }
export const LOOPBACK = '127.0.0.1'; export const LOOPBACK = '127.0.0.1';
export interface RunningServer { export interface RunningServer {
readonly logFolder: string; readonly logFolder: string;
readonly loadedModIds: readonly string[];
close(): Promise<void>; close(): Promise<void>;
} }
export async function startServer(options: ServerOptions): Promise<RunningServer> { export async function startServer(options: ServerOptions): Promise<RunningServer> {
const report = options.report ?? (() => {}); const report = options.report ?? (() => {});
const enabledMods = options.mods ?? [];
const modRuntime = await ServerModRuntime.load({
mods: enabledMods,
gameFolder: options.gameFolder,
dataFolder: options.dataFolder,
port: options.port,
report,
});
const gameFiles = new GameFiles(options.gameFolder); const gameFiles = new GameFiles(options.gameFolder);
// Static data and stores first, before the port opens. // Static data and stores first, before the port opens.
const datasets = new DatasetCache(options.dataFolder, gameFiles, report); const datasets = new DatasetCache(options.dataFolder, gameFiles, report);
const tuning = loadTuning(options.dataFolder, report); const tuning = loadTuning(options.dataFolder, report, enabledMods);
const mutableDatasets = new Map<string, unknown>();
const vehiclesList: CatalogueVehicle[] = [...datasets.load(vehicleCatalogue)];
const rawMissions = datasets.load(multiplayerMissions);
const missionsObj: MultiplayerMissions = {
categories: [...rawMissions.categories],
missions: { ...rawMissions.missions },
};
const spawnRulesObj = datasets.load(battleSpawnRules);
const economyDataObj: BattleEconomyData = { ...datasets.load(battleEconomy), vehicles: { ...datasets.load(battleEconomy).vehicles } };
const labelsObj: UiLabels = { ...datasets.load(uiLabels) };
const localizedUnitNamesObj: UnitNamesMap = { ...datasets.load(unitNames) };
mutableDatasets.set('vehicle-catalogue', vehiclesList);
mutableDatasets.set('multiplayer-missions', missionsObj);
mutableDatasets.set('battle-spawn-rules', spawnRulesObj);
mutableDatasets.set('battle-economy', economyDataObj);
mutableDatasets.set('ui-labels', labelsObj);
mutableDatasets.set('unit-names', localizedUnitNamesObj);
const datasetsView: ServerModDatasetsView = {
vehicles: vehiclesList,
battleEconomy: economyDataObj as unknown as Record<string, unknown>,
battleSpawnRules: spawnRulesObj,
multiplayerMissions: missionsObj as unknown as Record<string, unknown>,
uiLabels: labelsObj as unknown as Record<string, unknown>,
unitNames: localizedUnitNamesObj as unknown as Record<string, unknown>,
get: <T = unknown>(id: string) => mutableDatasets.get(id) as T | undefined,
set: (id: string, value: unknown) => { mutableDatasets.set(id, value); },
};
await modRuntime.runDatasetsLoaded(datasetsView);
const vehicles = (mutableDatasets.get('vehicle-catalogue') as readonly CatalogueVehicle[]) ?? vehiclesList;
const missions = (mutableDatasets.get('multiplayer-missions') as MultiplayerMissions) ?? missionsObj;
const spawnRules = (mutableDatasets.get('battle-spawn-rules') as typeof spawnRulesObj) ?? spawnRulesObj;
const economyData = (mutableDatasets.get('battle-economy') as BattleEconomyData) ?? economyDataObj;
const labels = (mutableDatasets.get('ui-labels') as UiLabels) ?? labelsObj;
const localizedUnitNames = (mutableDatasets.get('unit-names') as UnitNamesMap) ?? localizedUnitNamesObj;
const gameModes = new GameModes( const gameModes = new GameModes(
datasets.load(multiplayerMissions), datasets.load(shopCountries), report, tuning.battle.fixedAirRealisticMaxMrank, missions, datasets.load(shopCountries), report, tuning.battle.fixedAirRealisticMaxMrank,
); );
const accounts = new AccountStore(options.dataFolder); const accounts = new AccountStore(options.dataFolder);
const clans = new ClanStore(options.dataFolder, tuning.clans); const clans = new ClanStore(options.dataFolder, tuning.clans);
const cloudSettings = new CloudSettingsStore(options.dataFolder); const cloudSettings = new CloudSettingsStore(options.dataFolder);
const vehicles = datasets.load(vehicleCatalogue);
const spawnRules = datasets.load(battleSpawnRules);
const economyData = datasets.load(battleEconomy);
const efficiencyData = datasets.load(researchEfficiency); const efficiencyData = datasets.load(researchEfficiency);
const streakDefinitions = datasets.load(battleStreaks); const streakDefinitions = datasets.load(battleStreaks);
const labels = datasets.load(uiLabels); const { profiles, research, equipment, repair } = setUpProfiles(
const { profiles, research, equipment, repair } = setUpProfiles(options.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles); options.dataFolder,
const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(datasets, tuning, vehicles, labels); gameFiles,
datasets,
tuning,
{ accounts, clans },
vehicles,
(profile, userId) => modRuntime.runProfileRefresh(profile, userId),
);
const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(
datasets,
tuning,
vehicles,
labels,
localizedUnitNames,
);
const storeProducts = catalogues.store.allProducts(); const storeProducts = catalogues.store.allProducts();
const artwork = new GameArtwork(options.gameFolder, { const artwork = new GameArtwork(options.gameFolder, {
vehicles: storeProducts.flatMap((product) => product.vehicles?.map((vehicle) => vehicle.name) ?? []), vehicles: storeProducts.flatMap((product) => product.vehicles?.map((vehicle) => vehicle.name) ?? []),
@@ -112,8 +177,19 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
let matching: MatchingService | undefined; let matching: MatchingService | undefined;
const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' }); const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' });
const notifyUser = (userId: string, eventName: string, payload: Record<string, unknown>) => {
matching?.notifyUser(userId, eventName, payload);
};
const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept); const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept);
const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules, botAircraftLoadouts); const battleMatchmaker = new BattleMatchmaker(
gameModes,
vehicles,
battleSessions,
tuning.battle,
spawnRules,
botAircraftLoadouts,
(ctx) => modRuntime.runBattleFilterMissions(ctx),
);
const economy = new BattleEconomy( const economy = new BattleEconomy(
economyData, economyData,
tuning.battleEconomy, tuning.battleEconomy,
@@ -124,7 +200,31 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
const streaks = new BattleStreaks(streakDefinitions, vehicles, economy); const streaks = new BattleStreaks(streakDefinitions, vehicles, economy);
const supportPlanes = supportPlaneUnits(spawnRules); const supportPlanes = supportPlaneUnits(spawnRules);
await modRuntime.runCataloguesReady({
tuning: tuning as unknown as Readonly<Record<string, unknown>>,
gameModes,
profiles,
accounts,
research,
equipment,
repair,
store: catalogues.store,
inventory: catalogues.inventory,
trophies: catalogues.trophies,
items: catalogues.items,
crew: catalogues.crew,
decor: catalogues.decor,
unlocks: catalogues.unlocks,
clans,
battleMatchmaker,
battleEconomy: economy,
battleStreaks: streaks,
notifyInventoryChanged,
notifyUser,
});
const router = new Router([ const router = new Router([
modRuntime.httpService(),
webUi, webUi,
new RegistrationService(accounts), new RegistrationService(accounts),
new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port), new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port),
@@ -140,44 +240,69 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
...catalogues, ...catalogues,
clans: { store: clans, economy: squadronEconomy }, clans: { store: clans, economy: squadronEconomy },
cloudSettings, cloudSettings,
battle: { sessions: battleSessions, economy, efficiency: new ResearchEfficiency(efficiencyData, research.techTree), streaks, supportPlanes }, battle: {
sessions: battleSessions,
economy,
efficiency: new ResearchEfficiency(efficiencyData, research.techTree),
streaks,
supportPlanes,
onAfterSettle: (ctx) => modRuntime.runBattleAfterSettle(ctx),
},
notifyInventoryChanged, notifyInventoryChanged,
})), }), modRuntime),
new DownloadableContentService(), new DownloadableContentService(),
]); ]);
const log = new TrafficLog(options.dataFolder, options.loggingEnabled ?? true); const log = new TrafficLog(options.dataFolder, options.loggingEnabled ?? true);
const matchingTable = modRuntime.applyMatchingRoutes(matchingRequests({
gameModes,
accounts,
battle: {
gameModes,
profiles,
matchmaker: battleMatchmaker,
sessions: battleSessions,
economy,
notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload),
onBeforeMatchmake: (ctx) => modRuntime.runBattleBeforeMatchmake(ctx),
},
battleLive: {
sessions: battleSessions,
liveLogs: new BattleLiveLogs(tuning.limits.battleSessionsKept),
streaks,
supportPlanes,
onLiveFact: (ctx) => modRuntime.runBattleLiveFact(ctx),
},
}));
const listener = createPortListener( const listener = createPortListener(
router, router,
matchingRequests({ matchingTable,
gameModes,
accounts,
battle: {
gameModes,
profiles,
matchmaker: battleMatchmaker,
sessions: battleSessions,
economy,
notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload),
},
battleLive: { sessions: battleSessions, liveLogs: new BattleLiveLogs(tuning.limits.battleSessionsKept), streaks, supportPlanes },
}),
log, log,
loadOrCreateCredentials(options.dataFolder), loadOrCreateCredentials(options.dataFolder),
); );
matching = listener.matching; matching = listener.matching;
await listen(listener.server, options.port); await listen(listener.server, options.port);
await modRuntime.runServerListening(options.port);
return { return {
logFolder: log.folder, logFolder: log.folder,
close: () => new Promise((resolve) => { loadedModIds: modRuntime.loadedModIds,
listener.server.close(() => resolve()); close: async () => {
listener.destroyConnections(); await modRuntime.runServerClosing();
}), await new Promise<void>((resolve) => {
listener.server.close(() => resolve());
listener.destroyConnections();
});
},
}; };
} }
function loadDomainCatalogues(datasets: DatasetCache, tuning: Tuning, vehicles: readonly CatalogueVehicle[], labels: UiLabels) { function loadDomainCatalogues(
datasets: DatasetCache,
tuning: Tuning,
vehicles: readonly CatalogueVehicle[],
labels: UiLabels,
localizedUnitNames: UnitNamesMap,
) {
const classicItemDefs = datasets.load(itemCatalogue); const classicItemDefs = datasets.load(itemCatalogue);
const localizedUnitNames = datasets.load(unitNames);
return { return {
crew: new CrewSkillCatalogue(datasets.load(crewSkillData)), crew: new CrewSkillCatalogue(datasets.load(crewSkillData)),
decor: new DecorShop(datasets.load(decorCatalogue)), decor: new DecorShop(datasets.load(decorCatalogue)),
@@ -186,6 +311,7 @@ function loadDomainCatalogues(datasets: DatasetCache, tuning: Tuning, vehicles:
store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames, labels, tuning.store), store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames, labels, tuning.store),
inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs, tuning), inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs, tuning),
trophies: new TrophyCatalogue(vehicles, classicItemDefs, tuning.trophies), trophies: new TrophyCatalogue(vehicles, classicItemDefs, tuning.trophies),
training: new TrainingCatalogue(datasets.load(trainingMissions)),
clanEconomy: datasets.load(clanEconomy), clanEconomy: datasets.load(clanEconomy),
}; };
} }
+7 -2
View File
@@ -6,9 +6,14 @@
* `bundles/guid` registers a GUID for its id, so the build must register every pack this server * `bundles/guid` registers a GUID for its id, so the build must register every pack this server
* will sell from the same data folder. * will sell from the same data folder.
*/ */
import type { DiscoveredMod } from '@wto/mods';
import { tuningFiles } from '../tuning/tuning-loader.ts'; import { tuningFiles } from '../tuning/tuning-loader.ts';
import { readStoreTuning } from './store-tuning.ts'; import { readStoreTuning } from './store-tuning.ts';
export function multiVehiclePackIds(dataFolder: string, report: (line: string) => void): string[] { export function multiVehiclePackIds(
return readStoreTuning(tuningFiles(dataFolder, report).read('store')).multiVehiclePacks.map((pack) => pack.id); dataFolder: string,
report: (line: string) => void,
mods: readonly DiscoveredMod[] = [],
): string[] {
return readStoreTuning(tuningFiles(dataFolder, report, undefined, mods).read('store')).multiVehiclePacks.map((pack) => pack.id);
} }
@@ -0,0 +1,73 @@
/**
* Rules for completing stock training missions reported by `cln_update` (`missionAwards`):
* persists `pveProgress/missions` completion flags and grants first-completion rewards
* (decal unlock/resource, shared first-basic-tutorial Golden Eagles unlock, and per-difficulty
* first-win Silver Lions) once per account.
*/
import type { BlkBlock } from '@wto/blk';
import type { TrainingMissionEntry, TrainingMissionsData } from '../game-data/datasets/training-missions.ts';
import { addGoldenEagles, addSilverLions } from '../profile/profile-currency.ts';
import { hasCompletedMissionDifficulty, recordMissionCompleted } from '../profile/profile-mission-progress.ts';
import { addResource, ownsResource } from '../profile/profile-resources.ts';
import { addUnlock, earnedUnlocks } from '../profile/profile-unlocks.ts';
export type TrainingDifficulty = 0 | 1 | 2;
export interface TrainingCompletionReport {
readonly chapter: string;
readonly mission: string;
readonly difficulty: TrainingDifficulty;
}
const DIFFICULTIES: readonly TrainingDifficulty[] = [0, 1, 2];
export class TrainingCatalogue {
readonly #byFullName: ReadonlyMap<string, TrainingMissionEntry>;
constructor(data: TrainingMissionsData) {
this.#byFullName = new Map(data.missions.map((entry) => [entry.fullName, entry]));
}
/**
* Persist a completed training mission and grant its one-time rewards. Repeated reports keep
* existing completion flags intact without paying any reward twice.
*/
applyCompletion(profile: BlkBlock, report: TrainingCompletionReport): void {
const entry = this.#byFullName.get(`${report.chapter}/${report.mission}`);
if (!entry) return;
let silverLions = 0;
for (const difficulty of DIFFICULTIES) {
if (difficulty <= report.difficulty && !hasCompletedMissionDifficulty(profile, entry.fullName, difficulty)) {
silverLions += entry.silverLionsByDifficulty[difficulty];
}
}
recordMissionCompleted(profile, entry.fullName, report.difficulty);
if (silverLions > 0) addSilverLions(profile, silverLions);
grantMissionUnlocks(profile, entry);
}
}
function grantMissionUnlocks(profile: BlkBlock, entry: TrainingMissionEntry): void {
if (!entry.decal && !entry.firstCompletion) return;
const earned = earnedUnlocks(profile);
const grantUnlock = (id: string): void => {
if (earned.has(id)) return;
addUnlock(profile, id);
earned.add(id);
};
if (entry.decal) {
grantUnlock(entry.decal);
if (!ownsResource(profile, entry.decal)) {
addResource(profile, entry.decal, { silverLions: 0, goldenEagles: 0 });
}
}
const first = entry.firstCompletion;
if (first && !earned.has(first.id) && !first.blockedBy.some((id) => earned.has(id))) {
addGoldenEagles(profile, first.goldenEagles);
grantUnlock(first.id);
}
}
@@ -25,6 +25,7 @@ function values(files: TuningFiles) {
tankBotRespawns: battle.tankBotRespawns, tankBotRespawns: battle.tankBotRespawns,
airBotRespawns: battle.airBotRespawns, airBotRespawns: battle.airBotRespawns,
strikeUcavSpawnScore: battle.strikeUcavSpawnScore, strikeUcavSpawnScore: battle.strikeUcavSpawnScore,
nuclearEscalationStrategicBombers: battle.nuclearEscalationStrategicBombers,
silverLions: newProfile.silverLions, silverLions: newProfile.silverLions,
goldenEagles: newProfile.goldenEagles, goldenEagles: newProfile.goldenEagles,
preferLineSuccessor: research.preferLineSuccessor, preferLineSuccessor: research.preferLineSuccessor,
@@ -46,6 +47,7 @@ const fileOf = {
tankBotRespawns: 'battle', tankBotRespawns: 'battle',
airBotRespawns: 'battle', airBotRespawns: 'battle',
strikeUcavSpawnScore: 'battle', strikeUcavSpawnScore: 'battle',
nuclearEscalationStrategicBombers: 'battle',
silverLions: 'new-profile', silverLions: 'new-profile',
goldenEagles: 'new-profile', goldenEagles: 'new-profile',
preferLineSuccessor: 'research', preferLineSuccessor: 'research',
+30 -20
View File
@@ -1,16 +1,21 @@
/** /**
* Load one tuning file: the defaults shipped in * Load one tuning file with multi-layer overrides:
* apps/server/tuning/<name>.jsonc, with <data folder>/tuning/<name>.jsonc laid * shipped defaults (`apps/server/tuning/<name>.jsonc`)
* over them field by field when the player or a developer put one there. Objects merge key * -> each enabled mod's `<server.tuning>/<name>.jsonc` in load order
* by key; any other value (numbers, texts, lists) in the override replaces the default. * -> player overrides (`<dataFolder>/tuning/<name>.jsonc`).
*
* Objects merge key by key; plain lists replace the base list; `{ "$listOps": [...] }`
* performs additive append/prepend/upsertBy/removeBy operations across layers.
*/ */
import { existsSync, readFileSync } from 'node:fs'; import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path'; import { join } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { parseJsonc } from '@wto/jsonc'; import { parseJsonc } from '@wto/jsonc';
import { mergeTuningLayer, type DiscoveredMod } from '@wto/mods';
import { TuningError, TuningReader } from './tuning-reader.ts'; import { TuningError, TuningReader } from './tuning-reader.ts';
const DEFAULTS_FOLDER = fileURLToPath(new URL('../../tuning/', import.meta.url)); const DEFAULTS_FOLDER = fileURLToPath(new URL('../../tuning/', import.meta.url));
const DEFAULT_MOD_TUNING_DIR = 'server/tuning';
export interface TuningFiles { export interface TuningFiles {
/** The merged content of <name>.jsonc, ready for typed reads. */ /** The merged content of <name>.jsonc, ready for typed reads. */
@@ -21,19 +26,35 @@ export function tuningFiles(
dataFolder: string | null, dataFolder: string | null,
report: (line: string) => void, report: (line: string) => void,
proposed?: ReadonlyMap<string, Record<string, unknown>>, proposed?: ReadonlyMap<string, Record<string, unknown>>,
mods: readonly DiscoveredMod[] = [],
): TuningFiles { ): TuningFiles {
const overridesFolder = dataFolder === null ? null : join(dataFolder, 'tuning'); const overridesFolder = dataFolder === null ? null : join(dataFolder, 'tuning');
return { return {
read(name: string): TuningReader { read(name: string): TuningReader {
const fileName = `${name}.jsonc`; const fileName = `${name}.jsonc`;
const defaults = parseFile(join(DEFAULTS_FOLDER, fileName)); let merged = parseFile(join(DEFAULTS_FOLDER, fileName));
for (const mod of mods) {
const modTuningDir = mod.manifest.server?.tuning ?? DEFAULT_MOD_TUNING_DIR;
const modFilePath = join(mod.rootDir, ...modTuningDir.split('/'), fileName);
if (!existsSync(modFilePath)) continue;
report(`tuning ${fileName}: applying mod "${mod.manifest.id}" overrides`);
try {
merged = mergeTuningLayer(merged, parseFile(modFilePath));
} catch (error) {
throw new TuningError(
`mod "${mod.manifest.id}" tuning ${fileName} merge failed: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
const candidate = proposed?.get(name); const candidate = proposed?.get(name);
if (candidate) return new TuningReader(fileName, mergeOverride(defaults, candidate)); if (candidate) return new TuningReader(fileName, mergeTuningLayer(merged, candidate));
if (overridesFolder === null) return new TuningReader(fileName, defaults); if (overridesFolder === null) return new TuningReader(fileName, merged);
const overridePath = join(overridesFolder, fileName); const overridePath = join(overridesFolder, fileName);
if (!existsSync(overridePath)) return new TuningReader(fileName, defaults); if (!existsSync(overridePath)) return new TuningReader(fileName, merged);
report(`tuning ${fileName}: using overrides from ${overridePath}`); report(`tuning ${fileName}: using overrides from ${overridePath}`);
return new TuningReader(fileName, mergeOverride(defaults, parseFile(overridePath))); return new TuningReader(fileName, mergeTuningLayer(merged, parseFile(overridePath)));
}, },
}; };
} }
@@ -45,14 +66,3 @@ function parseFile(path: string): unknown {
throw new TuningError(`tuning file ${path} cannot be read: ${error instanceof Error ? error.message : String(error)}`); throw new TuningError(`tuning file ${path} cannot be read: ${error instanceof Error ? error.message : String(error)}`);
} }
} }
function mergeOverride(base: unknown, override: unknown): unknown {
if (!isObject(base) || !isObject(override)) return override;
const merged: Record<string, unknown> = { ...base };
for (const [key, value] of Object.entries(override)) merged[key] = key in base ? mergeOverride(base[key], value) : value;
return merged;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+7 -2
View File
@@ -13,6 +13,7 @@ import { readNewProfileTuning, type NewProfileTuning } from '../profile/new-prof
import { readResearchTuning, type ResearchTuning } from '../research/research-tuning.ts'; import { readResearchTuning, type ResearchTuning } from '../research/research-tuning.ts';
import { readRedeemTuning, type RedeemTuning } from '../store/redeem-tuning.ts'; import { readRedeemTuning, type RedeemTuning } from '../store/redeem-tuning.ts';
import { readStoreTuning, type StoreTuning } from '../store/store-tuning.ts'; import { readStoreTuning, type StoreTuning } from '../store/store-tuning.ts';
import type { DiscoveredMod } from '@wto/mods';
import { readLimitsTuning, type LimitsTuning } from './limits-tuning.ts'; import { readLimitsTuning, type LimitsTuning } from './limits-tuning.ts';
import { tuningFiles } from './tuning-loader.ts'; import { tuningFiles } from './tuning-loader.ts';
@@ -31,8 +32,12 @@ export interface Tuning {
readonly limits: LimitsTuning; readonly limits: LimitsTuning;
} }
export function loadTuning(dataFolder: string, report: (line: string) => void): Tuning { export function loadTuning(
const files = tuningFiles(dataFolder, report); dataFolder: string,
report: (line: string) => void,
mods: readonly DiscoveredMod[] = [],
): Tuning {
const files = tuningFiles(dataFolder, report, undefined, mods);
return { return {
store: readStoreTuning(files.read('store')), store: readStoreTuning(files.read('store')),
redeemCodes: readRedeemTuning(files.read('redeem-codes')), redeemCodes: readRedeemTuning(files.read('redeem-codes')),
+6 -1
View File
@@ -47,5 +47,10 @@
// AI bot respawn limits per battle in multi-slot versus modes. // AI bot respawn limits per battle in multi-slot versus modes.
"tankBotRespawns": 3, "tankBotRespawns": 3,
"airBotRespawns": 2 "airBotRespawns": 2,
// Offer a stage-3 megaton strategic bomber (B-52H / Tu-95M) alongside the tactical nuclear
// carrier in Air RB Nuclear Escalation (sub-mode 103). Disable to use tactical 5 kt / 30 kt
// carriers only, matching the regular live rotation.
"nuclearEscalationStrategicBombers": true
} }
+2
View File
@@ -12,6 +12,7 @@
| 改游戏规则、档案或本地服务 | [apps/server](../apps/server) | | 改游戏规则、档案或本地服务 | [apps/server](../apps/server) |
| 改游戏副本的构建或补丁检查 | [packages/patcher](../packages/patcher)、[scripts](../scripts)、[tools](../tools) | | 改游戏副本的构建或补丁检查 | [packages/patcher](../packages/patcher)、[scripts](../scripts)、[tools](../tools) |
| 写客户端补丁或适配新的游戏版本 | [补丁指南](patches.md#zh-cn)和[补丁集](../patches) | | 写客户端补丁或适配新的游戏版本 | [补丁指南](patches.md#zh-cn)和[补丁集](../patches) |
| 制作添加式模组(实验期) | [模组开发文档(mod-dev-docs)](../mod-dev-docs/README.md) |
提交前按[自查清单](contributing.md#zh-cn)整理依据、运行适用的[检查命令](contributing.md#checks),并把检查结果和实机步骤写进 [PR 模板](templates/pull-request.md)。 提交前按[自查清单](contributing.md#zh-cn)整理依据、运行适用的[检查命令](contributing.md#checks),并把检查结果和实机步骤写进 [PR 模板](templates/pull-request.md)。
@@ -27,5 +28,6 @@ Start with a stock client you own and use it as a read-only source. Install the
| Change game rules, saves, or local services | [apps/server](../apps/server) | | Change game rules, saves, or local services | [apps/server](../apps/server) |
| Change the game copy build or patch checks | [packages/patcher](../packages/patcher), [scripts](../scripts), [tools](../tools) | | Change the game copy build or patch checks | [packages/patcher](../packages/patcher), [scripts](../scripts), [tools](../tools) |
| Write a client patch or adapt a new game build | [Patch guide](patches.md#english) and the [patch set](../patches) | | Write a client patch or adapt a new game build | [Patch guide](patches.md#english) and the [patch set](../patches) |
| Author additive mods (experimental) | [Mod development docs (mod-dev-docs)](../mod-dev-docs/README.md#english) |
Before submitting, follow the [review checklist](contributing.md#english), run the applicable [checks](contributing.md#checks), and record the results and in-game steps in the [PR template](templates/pull-request.md). Before submitting, follow the [review checklist](contributing.md#english), run the applicable [checks](contributing.md#checks), and record the results and in-game steps in the [PR template](templates/pull-request.md).
+2
View File
@@ -9,6 +9,7 @@
- 改动只解决一个目标。实现、配置、补丁说明和相关开发文档一致。提交标题用英文 `type(scope): description`,scope 用小写模块名,仓库级改动用 `repo`。破坏兼容时用 `type(scope)!: description`,并在 `BREAKING CHANGE:` 脚注说明影响和处理方式。正文交代原因、依据和验证结果,代码注释也用英文。联署留给实际协作的开发者。 - 改动只解决一个目标。实现、配置、补丁说明和相关开发文档一致。提交标题用英文 `type(scope): description`,scope 用小写模块名,仓库级改动用 `repo`。破坏兼容时用 `type(scope)!: description`,并在 `BREAKING CHANGE:` 脚注说明影响和处理方式。正文交代原因、依据和验证结果,代码注释也用英文。联署留给实际协作的开发者。
- 游戏行为的判断有目标版本和一手出处。新动作写清客户端怎样发请求、怎样读取应答。客户端改动登记到对应补丁或构建模块,并说明为何需要。涉及新数值时,按[三类数值规则](development-rules.md#数值和数据来源)检查来源、配置和校验。 - 游戏行为的判断有目标版本和一手出处。新动作写清客户端怎样发请求、怎样读取应答。客户端改动登记到对应补丁或构建模块,并说明为何需要。涉及新数值时,按[三类数值规则](development-rules.md#数值和数据来源)检查来源、配置和校验。
- 检查模块职责、依赖方向和重复逻辑。涉及账号、余额和档案时,检查错误输入、写盘顺序,以及多个账号之间的数据隔离。选择奖品或其他数据项时,按明确规则排序和筛选。 - 检查模块职责、依赖方向和重复逻辑。涉及账号、余额和档案时,检查错误输入、写盘顺序,以及多个账号之间的数据隔离。选择奖品或其他数据项时,按明确规则排序和筛选。
- 若借助 AI 助手编写代码,提交前请人工逐行对照 [常见实现陷阱与工程红线](development-rules.md#常见实现陷阱与工程红线含-ai-辅助开发对照):确认没有硬编码偏移/地址、没有写死原版数据或魔法数字、没有越层修改或夹带无关改动,并且每一条写进 PR 的检查命令都在本机真实运行过。
- 只做类型、补丁、构建和可运行检查。功能验收由人使用隔离副本在游戏里做。注明实际执行过的命令、对应版本和结果。还要实机核对时写出入口、操作和预期现象。商城或交易所改动覆盖内置浏览器打开、相关操作和关窗后的档案刷新。 - 只做类型、补丁、构建和可运行检查。功能验收由人使用隔离副本在游戏里做。注明实际执行过的命令、对应版本和结果。还要实机核对时写出入口、操作和预期现象。商城或交易所改动覆盖内置浏览器打开、相关操作和关窗后的档案刷新。
- 提交前看一遍差异,确认来源、路径、记录和玩家数据可以分享。用 [PR 模板](templates/pull-request.md) 提供复核所需的信息。 - 提交前看一遍差异,确认来源、路径、记录和玩家数据可以分享。用 [PR 模板](templates/pull-request.md) 提供复核所需的信息。
@@ -21,6 +22,7 @@
- Keep one purpose per change. Update the affected implementation, configuration, patch notes, and developer docs together. Use English `type(scope): description` commit subjects with a lowercase module scope or `repo` for repository-wide changes. For a breaking change, use `type(scope)!: description` and a `BREAKING CHANGE:` footer that explains the impact and what to do. Explain the reason, evidence, and verification in the commit body. Use English comments and reserve co-author credits for developers who actually collaborated. - Keep one purpose per change. Update the affected implementation, configuration, patch notes, and developer docs together. Use English `type(scope): description` commit subjects with a lowercase module scope or `repo` for repository-wide changes. For a breaking change, use `type(scope)!: description` and a `BREAKING CHANGE:` footer that explains the impact and what to do. Explain the reason, evidence, and verification in the commit body. Use English comments and reserve co-author credits for developers who actually collaborated.
- Cite the target build and primary evidence for game behavior. For new actions, explain how the client sends the request and consumes the reply. Register client edits in their patch or build module and explain why they are needed. For new values, check the source, tuning, and validation using the [three kinds of values](development-rules.md#data-and-tuning). - Cite the target build and primary evidence for game behavior. For new actions, explain how the client sends the request and consumes the reply. Register client edits in their patch or build module and explain why they are needed. For new values, check the source, tuning, and validation using the [three kinds of values](development-rules.md#data-and-tuning).
- Check module responsibilities, dependency direction, and reuse. For accounts, currency, and saves, check bad inputs, when updates reach disk, and separation between accounts. Use explicit ordering and selection rules for prize pools and other lists. - Check module responsibilities, dependency direction, and reuse. For accounts, currency, and saves, check bad inputs, when updates reach disk, and separation between accounts. Use explicit ordering and selection rules for prize pools and other lists.
- When using AI tools to draft code, review the diff line by line against [common implementation pitfalls](development-rules.md#common-implementation-pitfalls-especially-with-ai-assisted-prs): confirm there are no hardcoded addresses/offsets, no copied stock numbers or magic constants, no layer violations or unrelated edits, and that every check reported in the PR was actually executed.
- Limit automated checks to type, patch, build, and startup checks. Functional acceptance is performed by a person in an isolated game copy. Report the commands actually run, the client builds, and the results. For pending in-game checks, give the entry point, action, and expected result. Store and marketplace changes cover opening the embedded browser, the affected action, and the profile refresh on close. - Limit automated checks to type, patch, build, and startup checks. Functional acceptance is performed by a person in an isolated game copy. Report the commands actually run, the client builds, and the results. For pending in-game checks, give the entry point, action, and expected result. Store and marketplace changes cover opening the embedded browser, the affected action, and the profile refresh on close.
- Review the diff for shareable sources, paths, records, and player data. Use the [PR template](templates/pull-request.md) to provide enough detail for review. - Review the diff for shareable sources, paths, records, and player data. Use the [PR template](templates/pull-request.md) to provide enough detail for review.
+28
View File
@@ -23,6 +23,20 @@
本地服务器每次启动加载数值配置。数据目录下的同名 `tuning/*.jsonc` 可逐键覆盖默认对象。数字、字符串和列表整体替换。 本地服务器每次启动加载数值配置。数据目录下的同名 `tuning/*.jsonc` 可逐键覆盖默认对象。数字、字符串和列表整体替换。
## 常见实现陷阱与工程红线(含 AI 辅助开发对照)
欢迎借助 AI 助手阅读反汇编、排查日志和定位根因。实际提交改动时,请按下列正反对照逐条收口实现,确保补丁在后续小版本更新与长期维护中依然健壮:
| 维度 | 推荐做法 | 避免做法 |
| --- | --- | --- |
| 定位与偏移 | exe 补丁与 native 模块一律通过 `patches/exe/`、`patches/native/` 的 `signature`、`string_ref`、`within` 动态捕获地址、跳转目标和结构体偏移 | 在 C/TS 代码中硬编码 RVA、结构体偏移、函数地址或 `_ReturnAddress` |
| 改动分层 | 先核对服务端协议、任务根字段与原版配置能否解决;协议层、规则层、存档层、数据层职责分离,修改档案先写盘再回复 | 用客户端硬补丁绕开本该由本地服务器解决的问题,或在协议处理器里堆砌业务规则、先回成功再写盘 |
| 静态数据与数值 | 游戏文件已有的载具、任务、奖励、出生点等一律通过缓存 `datasets/` 从玩家原版文件读取;离线自定参数进 `apps/server/tuning/*.jsonc` 并做启动校验 | 在代码里手抄原版数值、写死兜底坐标或散落魔法数字 |
| 复用与粒度 | 复用 `local_mp_core` 等公共站点与现有模块;共享库 `packages/*` 通过参数收配置;文件接近 300 行、函数接近 50 行时拆分职责 | 重复挂钩同一原生函数、让 `packages/*` 反向读取 `apps/*`、把多类职责塞进单个大文件或大函数 |
| 编译器与运行环境 | Native C 代码严格兼容 MSVC(`native/wto-net/build.ps1` 0 警告);TS 代码兼容 Node 24 原生类型剥离(`erasableSyntaxOnly`) | 引入 GCC 专属扩展或未在 MSVC 编译核对的 C 语法 |
| 校验与验收 | 按改动执行对应的 `typecheck`、`check-patches`、完整 `check-gui`(Quirrel 字节码检查)与临时副本构建,如实记录未实机项 | 只靠单测或静态推演就宣称已验证通过;跳过 `check-gui`;在未实机验收前提交 `patches/versions/*.jsonc` |
| 范围与协作规范 | 一笔 PR 专注单一目标,使用英文约定式提交与英文代码注释,只保留实际人类协作者的 `Co-authored-by` | 夹带无关格式化/重构、写入个人本机路径或把 AI 助手署名为 `Co-authored-by` |
## 本地开发与材料 ## 本地开发与材料
- 游戏只在专用副本和隔离环境里启动。启动前验证断网限制、本地服务、Steam 和账号身份,以及文件、注册表、机器标识、反作弊和崩溃上报的隔离。需要观察启动行为时,在一次性环境里核对前后变化。原版来源只读,通过离线副本启动并使用本地账号。 - 游戏只在专用副本和隔离环境里启动。启动前验证断网限制、本地服务、Steam 和账号身份,以及文件、注册表、机器标识、反作弊和崩溃上报的隔离。需要观察启动行为时,在一次性环境里核对前后变化。原版来源只读,通过离线副本启动并使用本地账号。
@@ -52,6 +66,20 @@ Use game data and official material as the first sources for economic defaults.
At startup, the server can load a same-named `tuning/*.jsonc` file from the data directory. Object keys merge. Numbers, strings, and arrays are replaced as a whole. At startup, the server can load a same-named `tuning/*.jsonc` file from the data directory. Object keys merge. Numbers, strings, and arrays are replaced as a whole.
## Common implementation pitfalls (especially with AI-assisted PRs)
Using AI tools to inspect binaries, trace logs, and pinpoint root causes is welcome. Before opening a PR, verify the implementation itself against these engineering guardrails so changes stay maintainable across game updates:
| Area | Preferred practice | Avoid |
| --- | --- | --- |
| Locating & offsets | Resolve addresses, jump targets, and struct offsets dynamically via `signature`, `string_ref`, or `within` captures in `patches/exe/` and `patches/native/` | Hardcoding RVAs, struct offsets, raw function pointers, or `_ReturnAddress` checks in C or TypeScript |
| Layering | Solve in the local server or stock config first; separate protocol, rules, persistence, and datasets, and write saves to disk before returning success | Adding client workarounds for server-solvable issues, mixing game rules into protocol handlers, or replying before persistence |
| Static data & tuning | Extract stock vehicle, mission, reward, and spawn data from player archives via cached `datasets/`; put offline defaults in `apps/server/tuning/*.jsonc` with startup validation | Copying stock numbers into source code, hardcoding fallback coordinates, or scattering magic constants |
| Reuse & modularity | Reuse shared native sites (`local_mp_core`) and existing helpers; pass paths/config into `packages/*`; split files near 300 lines or functions near 50 lines | Registering duplicate hooks for the same symbol, reading `apps/*` from `packages/*`, or growing monolithic handlers |
| Toolchains | Keep native C code cleanly buildable with MSVC (`native/wto-net/build.ps1`, zero warnings) and TS compatible with Node 24 erasable syntax | Relying on GCC-only extensions or submitting C changes without an MSVC build |
| Verification | Run the matching `typecheck`, `check-patches`, full `check-gui` (Quirrel bytecode check), and temporary copy build; clearly mark pending in-game checks | Relying on mock/unit tests as proof of in-game correctness, skipping `check-gui`, or committing `patches/versions/*.jsonc` before live acceptance |
| Scope & hygiene | Keep each PR focused on one change, use English conventional commits and English comments, and reserve `Co-authored-by` for human collaborators | Mixing unrelated refactors, leaking local paths, or attributing AI tools in `Co-authored-by` |
## Local development and contributions ## Local development and contributions
- Launch the game in a dedicated copy and isolated environment. Before launch, verify the network restrictions, local service, and isolation of Steam identity, accounts, files, registry, machine identifiers, anti-cheat, and crash reporting. Observe before and after effects in a disposable environment when needed. Use a read-only stock source and a local account, and launch from the offline copy. - Launch the game in a dedicated copy and isolated environment. Before launch, verify the network restrictions, local service, and isolation of Steam identity, accounts, files, registry, machine identifiers, anti-cheat, and crash reporting. Observe before and after effects in a disposable environment when needed. Use a read-only stock source and a local account, and launch from the offline copy.
+8
View File
@@ -12,6 +12,14 @@
<!-- List the affected builds and any change to patch variants or version records. --> <!-- List the affected builds and any change to patch variants or version records. -->
## Self-check
- [ ] No hardcoded addresses, RVAs, struct offsets, or `_ReturnAddress` checks (dynamic `patches/` captures used instead)
- [ ] No hardcoded stock game numbers or magic defaults (read from stock archives via `datasets/` or placed in `tuning/*.jsonc`)
- [ ] Layer boundaries preserved (protocol / rules / persistence / datasets; `packages/*` does not read `apps/*`)
- [ ] Scope is focused on one goal, code comments and commit messages are in English, and no unrelated files were modified
- [ ] Every command listed in **Checks run** was actually executed (including `check-gui` for `patches/gui/` and MSVC `build.ps1` for `native/`)
## Checks run ## Checks run
| Command or check | Client build if relevant | Result | | Command or check | Client build if relevant | Result |
+49
View File
@@ -0,0 +1,49 @@
# WTOffline 模组开发文档 / Mod Development Documentation
简体中文 · [English](#english)
> **实验期声明(API `0.1-experimental`)**
> WTOffline 当前处于极初期开发阶段。服务端脚本接口、内部数据结构、钩子契约及声明式 `exe` 补丁格式均可能随本体开发随时调整,**现阶段不承诺向后兼容**。模组作者使用服务端脚本或客户端二进制补丁时,请做好跟随本体更新维护的准备。
---
## 中文文档目录(`zh-CN/`)
| 章节 | 内容概览 |
| --- | --- |
| [01 · 快速入门与清单规范](zh-CN/01-quick-start.md) | 5 分钟做出第一个模组、目录结构、`mod.jsonc` 全字段表、依赖/互斥/排序、风险徽标与启动器调试 |
| [02 · 客户端数据包与 BLK 增量补丁](zh-CN/02-client-packs-and-blk.md) | 8 个可叠加 `.vromfs.bin` 包、BLK 补丁全部 7 种操作(含 `cloneBlock`)、13 种 BLK 类型写法、文本 `.blk` 自动编译、CSV 词条合并、`config.blk` 补丁 |
| [03 · 添加全新 3D 模型与贴图载具](zh-CN/03-custom-3d-vehicles.md) | `client/addon/res/`(`.grp` + `.dxp.bin`)跨盘 NTFS Junction 零拷贝挂载、挂进科技树/经济/图标/译名、原生涂装瞄具边界说明 |
| [04 · 客户端 GUI 补丁与声明式 EXE 补丁](zh-CN/04-client-gui-and-exe.md) | 增量 GUI 脚本补丁、新增原生 DaGui 弹窗、`sq.exe` Quirrel 完整字节码检查、声明式 `exe` 补丁与核心隔离保护红线 |
| [05 · 服务端零代码数值叠加(Tuning)](zh-CN/05-server-tuning.md) | 12 份 `server/tuning/*.jsonc` 说明、多层合并顺序、`$listOps` 列表增量操作(`append` / `prepend` / `upsertBy` / `removeBy`) |
| [06 · 服务端 JS/TS 脚本完整接口手册](zh-CN/06-server-scripting-api.md) | Node 24 原生 TS 语法要求、`WtoServerModContext`、独立存档区 `storage`、全部生命周期与对局钩子(含 `onFilterMissions`)、`char` / `matching` / `http` 路由与完整范例 |
| [07 · 排错、日志与最佳实践](zh-CN/07-troubleshooting-and-faq.md) | 定位 `launcher.log` 与本地服务器日志、冲突分析、防止损坏玩家存档、跨盘与非 NTFS 磁盘行为说明 |
### 自带官方模组模板(`templates/`)
以下 3 个模组会随 WTOffline 启动器自动分发到玩家首次初始化的全局 `mods/` 目录(默认关闭,勾选即用),可直接对照源码学习或复制改造:
| 模板目录 | 定位 | 演示的核心能力 |
| --- | --- | --- |
| `templates/example-vehicle-tweak/` | 零代码数据与本地化示例 | `server/tuning/battle.jsonc` + `wpcost.blk.patch.jsonc` + `lang/units.csv.patch.csv` |
| `templates/example-server-script/` | 服务端脚本最小示例 | `server/index.ts`、`onDatasetsLoaded`、`profile.onRefresh`、独立存档区、自定义 `/mods/<id>/status` 路由 |
| `templates/official-map-selector/` | 实用全栈官方模组 | 模式选择 UI 按钮补丁 + 原生 DaGui 小地图网格弹窗 + 多语言词条 + 自定义匹配 RPC + 独立存档 + `battle.onFilterMissions` 白/黑名单选图 |
---
<a id="english"></a>
## English Documentation (`en/`)
> **Experimental Notice (API `0.1-experimental`)**
> WTOffline is in early development. Server script APIs, internal data structures, hook contracts, and declarative `exe` patch formats may change without backwards compatibility across releases. Authors using server scripts or binary patches should be ready to update alongside core releases.
| Chapter | Topics |
| --- | --- |
| [01 · Quick Start & Manifest](en/01-quick-start.md) | Build your first mod in 5 minutes, folder layout, full `mod.jsonc` schema, dependencies/conflicts/ordering, risk badges |
| [02 · Client Packs & BLK Patching](en/02-client-packs-and-blk.md) | 8 overlayable `.vromfs.bin` packs, all 7 BLK patch ops (including `cloneBlock`), all 13 BLK types, auto text-BLK compilation, CSV merging, `config.blk` patches |
| [03 · Custom 3D Vehicle Models](en/03-custom-3d-vehicles.md) | `client/addon/res/` (`.grp` + `.dxp.bin`) cross-drive zero-copy NTFS Junction mounting, tech tree/economy/icons/localization wiring, native skins/sights boundary |
| [04 · Client GUI & Declarative EXE Patches](en/04-client-gui-and-exe.md) | Incremental GUI script patches, adding standalone native DaGui modals, full Quirrel bytecode checks (`sq.exe`), declarative `exe` patches & core isolation lock |
| [05 · Server Code-Free Tuning Overlays](en/05-server-tuning.md) | All 12 `server/tuning/*.jsonc` files, multi-layer precedence, `$listOps` (`append`, `prepend`, `upsertBy`, `removeBy`) |
| [06 · Server JS/TS Scripting API Reference](en/06-server-scripting-api.md) | Node 24 erasable TypeScript rules, `WtoServerModContext`, isolated `storage`, all lifecycle & battle hooks (including `onFilterMissions`), `char` / `matching` / `http` routes |
| [07 · Troubleshooting & FAQ](en/07-troubleshooting-and-faq.md) | Reading logs, diagnosing conflicts, keeping player saves clean, cross-drive and exFAT fallback behavior |
+105
View File
@@ -0,0 +1,105 @@
# 01 · Quick Start & Manifest Reference
> **Target Spec**: `format: 1` · `api_version: "0.1-experimental"` (experimental; subject to breaking changes)
## 1. Additive Mod Architecture
WTOffline uses a **stackable, additive** mod architecture. Mods supply incremental patches and added files rather than replacing full `.vromfs.bin` archives:
1. Before launching the game, the launcher starts from clean stock backups (`wtoffline/stock/`), applies core offline patches first, then layers every enabled mod's client patches and added files in the order shown on the **Mods** page;
2. Large 3D model and texture addons mount across drives with zero copying via **Windows NTFS Directory Junctions**;
3. The local server extracts static data from the overlaid packs, layers `server/tuning/*.jsonc` in the same order, and loads `server/index.ts` scripts;
4. Disabling a mod or switching presets cleanly unmounts junctions and restores stock packs.
- **Global repository**: defaults to `%APPDATA%\WTOffline Launcher\mods` (configurable to any drive under **Mods › Presets & repository**).
- **Per-client configuration**: toggles, load order, and presets live in each client's `<dataPath>/mods-config.json`.
---
## 2. Build Your First Mod in 5 Minutes
1. Open **Mods › Open mods folder** in the launcher.
2. Create a folder `my-first-mod` containing `mod.jsonc`:
```jsonc
{
"format": 1,
"id": "demo.my-first-mod",
"name": { "en": "My First Mod", "zh-CN": "我的第一个模组" },
"version": "0.1.0",
"author": "YourName",
"description": "Doubles Silver Lions and Research Points battle rewards.",
"api_version": "0.1-experimental",
"game_versions": ["2.61.0.*"]
}
```
3. Create `my-first-mod/server/tuning/battle.jsonc`:
```jsonc
{
"rewardMultiplierSilverLions": 2.0,
"rewardMultiplierResearchPoints": 2.0
}
```
4. Return to the launcher (the Mods page refreshes automatically on focus), enable your mod, and click **Launch**.
---
## 3. Standard Folder Layout
Create only the folders your mod actually needs:
```text
<mod-folder>/
├─ mod.jsonc # Required: manifest
├─ server/ # Optional: server extensions
│ ├─ tuning/ # *.jsonc tuning overlays
│ └─ index.ts (or index.mjs / .js) # server script entry
└─ client/ # Optional: client extensions
├─ packs/ # .vromfs.bin additive overlays
│ ├─ char.vromfs.bin/
│ ├─ aces.vromfs.bin/
│ ├─ gui.vromfs.bin/
│ ├─ lang.vromfs.bin/
│ ├─ mis.vromfs.bin/
│ ├─ game.vromfs.bin/
│ ├─ ui/atlases.vromfs.bin/
│ └─ ui/images.vromfs.bin/
├─ addon/ # 3D model & texture pack (res/*.grp, res/*.dxp.bin)
├─ gui-patches/ # declarative GUI script patches
├─ exe-patches/ # declarative exe patches
├─ files/ # optional companion skins/sights/sounds/missions
└─ config-blk.patch.jsonc # optional root config.blk patch
```
---
## 4. `mod.jsonc` Schema Reference
Unknown fields are rejected by strict validation.
| Field | Required | Type | Description |
| --- | --- | --- | --- |
| `format` | Yes | `1` | Manifest format version (currently `1`) |
| `id` | Yes | `string` | Globally unique ID matching `/^[a-z0-9][a-z0-9._-]{0,63}$/` |
| `name` | Yes | `string \| { [lang]: string }` | Display name (plain string or locale map) |
| `version` | Yes | `string` | Mod version (SemVer recommended) |
| `author` | Yes | `string` | Author or team name |
| `description` | No | `string \| { [lang]: string }` | Short description |
| `api_version` | Yes | `string` | Target API tag, currently `"0.1-experimental"` |
| `game_versions` | No | `string[]` | Game version wildcards (e.g. `["2.61.0.*"]`); mismatch warns only |
| `requires` | No | `string[]` | Required dependency mod IDs (blocking error if missing/disabled) |
| `conflicts` | No | `string[]` | Incompatible mod IDs (blocking error if both enabled) |
| `load_after` | No | `string[]` | Recommended load-order predecessors (used by Auto-sort) |
| `load_before` | No | `string[]` | Recommended load-order successors |
| `server` | No | `{ entry?: string, tuning?: string }` | Custom relative paths for server script entry and tuning folder |
---
## 5. Load Order, Risk Badges & Conflict Detection
- **Priority**: items lower in the list load later and take higher priority.
- **Risk badges**: automatically inferred as `data`, `gui`, `script`, and `exe`.
- **Conflict checks**: missing/disabled dependencies and declared conflicts block launching; whole-file overrides warn; shared BLK/CSV/tuning overlays report informational merge notices.
@@ -0,0 +1,53 @@
# 02 · Client Packs & BLK Incremental Patching
## 1. Supported `.vromfs.bin` Packs
Place overlays under `client/packs/<pack-path>/`:
- **Always rebuilt from stock**: `char.vromfs.bin`, `aces.vromfs.bin`, `gui.vromfs.bin`
- **On-demand backup & restore**: `lang.vromfs.bin`, `mis.vromfs.bin`, `game.vromfs.bin`, `ui/atlases.vromfs.bin`, `ui/images.vromfs.bin`
Because the local server extracts static datasets directly from the overlaid packs on startup, vehicles added or edited in `shop.blk` and `wpcost.blk` automatically flow into research trees, prices, modifications, AI pools, and offline store bundle GUIDs.
---
## 2. File Handling Rules
1. **`<target>.patch.jsonc`** — Type-preserving structured BLK patch applied to `<target>` inside the pack.
2. **`<target>.patch.csv`** — Semicolon-separated localization CSV merger keyed by column 0.
3. **Any other file** — Added or replaced directly. Plain text `.blk` files are compiled to binary BLK automatically before packing.
---
## 3. BLK Patch Operations (`*.blk.patch.jsonc`)
Every patch file has `{ "ops": [...] }`. Path segments support indexed sibling selectors such as `"range[2]"` (zero-based).
- **`setParam`**: `{ "op": "setParam", "path": [...], "name": "...", "value": ..., "createBlocks": false }`
- **`addParam`**: appends a repeated parameter without removing existing entries (ideal for `slaveUnit`, `folder`, `aircraftGift`).
- **`removeParam`**: removes all matching params by `name` (or only those matching optional `value`).
- **`upsertBlock`**: finds or creates a block along `path` and merges `block.params` and `block.blocks`.
- **`addBlock`**: inserts a new child block (`before` / `after` sibling anchor optional).
- **`removeBlock`**: deletes the block at `path`.
- **`cloneBlock`**: deep-clones an existing block (`from`) into `toParent` under `newName`, optionally applying nested `ops` rooted at the cloned block (fastest way to derive a modded vehicle in `wpcost.blk`).
### Explicit BLK Types
Use `{ "type": "<blkType>", "value": <val> }` whenever an exact Dagor BLK type is needed:
`string`, `int`, `real`, `bool`, `int64`, `point2`, `point3`, `point4`, `ipoint2`, `ipoint3`, `ipoint4`, `color` (`[r,g,b,a]` or packed `0xAARRGGBB`), `matrix` (12 reals).
---
## 4. Localization CSV Patches (`*.csv.patch.csv`)
```csv
"<ID|readonly|noverify>";"<English>";"<Chinese>";"<HChinese>"
"my_custom_tank_shop";"M1A2 Mod";"M1A2 魔改型";"M1A2 魔改型"
```
Existing keys update only the supplied non-empty language columns; new keys are appended cleanly.
---
## 5. Root `config.blk` Patches (`client/config-blk.patch.jsonc`)
Uses the exact same BLK patch format against `<copy>/config.blk`. The launcher backs up the stock `config.blk` automatically and restores it when no enabled mod patches it.
+33
View File
@@ -0,0 +1,33 @@
# 03 · Adding Custom 3D Vehicle Models & Textures
## 1. How 3D Asset Mounting Works
Verified directly against 2.61.0.x `aces.exe` (`dlContent.cpp`) and `config/settings.blk`:
- Any addon path under `/pkg_user/` skips the `res/grp_hdr.vromfs.bin` check and directly scans `<addon>/res/` for all `.grp` (3D geometry/skeleton/collision) and `.dxp.bin` (DDSx texture) archives;
- If a mod ships a compiled CDK `res/grp_hdr.vromfs.bin`, the patcher mounts it under `content/pkg_wto_<modId>` so the native `grp_hdr` loader handles it;
- The patcher automatically registers all enabled mod addon folders in `aces.vromfs.bin` `config/settings.blk` (`addons`, `addons_no_check`, `addonsWithBasePath`).
### Cross-Drive Zero-Copy Mounting
Each mod's `client/addon/` is mounted into `<copy>/content/pkg_user/<safeModId>` via a **Windows NTFS Directory Junction**:
- Works across drives (e.g. `mods/` on C: or D:, client on J:);
- Requires no administrator privileges;
- Uses 0 extra bytes and mounts/unmounts in ~1 ms without touching source files in `mods/`.
---
## 2. 6-Step Checklist for a Custom 3D Vehicle
1. **`client/addon/res/<unit>.grp` + `<unit>.dxp.bin`**: 3D model and textures exported via War Thunder CDK;
2. **`client/packs/aces.vromfs.bin/gamedata/units/.../<unit>.blk`**: vehicle FM/DM/weapons (plain text BLK compiles automatically);
3. **`client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc`**: economy, BR, modifications (use `cloneBlock` from a similar stock vehicle);
4. **`client/packs/char.vromfs.bin/config/shop.blk.patch.jsonc`** & **`unittags.blk.patch.jsonc`**: tech tree slot and unit tags;
5. **`client/packs/lang.vromfs.bin/lang/units.csv.patch.csv`**: localized names (`_shop`, `_0`, `_1`, `_2`);
6. **`client/packs/ui/atlases.vromfs.bin/gameuiskin/<lowercase_unit>_ico.svg`** & optional **`ui/images.vromfs.bin/units/<unit>.ddsx`**: silhouette icon (used in tech tree and local web store) and statcard image.
---
## 3. Native Skins, Sights & Companion Files Boundary
- Standalone user skins (`UserSkins/`), sights (`UserSights/`), and missions (`UserMissions/`) continue to use the game's native folders and are never managed or deleted by the launcher.
- Large overhaul/vehicle mods may optionally bundle companion skins, sights, or sound banks under `client/files/`. Exclusive subdirectories under `UserSkins/`, `UserSights/`, and `UserMissions/` mount via cross-drive Junctions; any target colliding with a player-owned native file is skipped with a warning and never overwritten.
+33
View File
@@ -0,0 +1,33 @@
# 04 · Client GUI Patches & Declarative EXE Patches
> **Experimental Notice**: GUI script patches and declarative `exe` patches depend on target client builds and may need updates after game or core patches.
---
## 1. Extending Client UI (Recommended Pattern)
1. Place new standalone `.nut`, `.tpl`, and `.css` files under `client/packs/gui.vromfs.bin/` (keep paths lowercase to match stock archive conventions);
2. Place minimal entry-point edits under `client/gui-patches/<patch-name>/` using `patch.jsonc` + `find.nut` / `replace.nut` fragments.
Core offline GUI patches always run first; mod GUI patches apply afterward in load order. Every `find` snippet must match uniquely once or the patch is skipped safely. `{{LOCAL_ENDPOINT}}` in replacement text expands to `127.0.0.1:<port>`.
### Mandatory Quirrel Bytecode Check
Before shipping any new or patched `.nut` script, compile the complete resulting script with `compilestring` via `sq.exe` to catch lexical scope conflicts, reserved keywords (such as `base`), and forward references that would otherwise hang login at "Loading":
```powershell
& "build\quirrel-cli\bin\Release\sq.exe" -e "local f = compilestring(readfile('your_script.nut'), 'your_script.nut'); println('OK')"
```
---
## 2. Declarative EXE Patches (`client/exe-patches/`)
Mods reuse WTOffline's `@wto/exepatch` format (`patch.jsonc` with `id`, `title`, `features`, `requires`, and `variants` using `signature`, `string_ref`, or `within` locators). **Never distribute modified `aces.exe` binaries.**
### Core Isolation Lock (Hard Security Boundary)
1. Core offline and isolation patches are planned first and their byte ranges are locked;
2. Any mod `exe` patch whose write range overlaps a protected core patch is **rejected** (`overlaps protected core patch`);
3. Overlapping patches between two mods reject the later patch with the conflicting mod ID;
4. Unmatched patterns on another game build are skipped cleanly and logged without breaking the core build.
+31
View File
@@ -0,0 +1,31 @@
# 05 · Server Code-Free Tuning Overlays
The local server stores all offline-defined economy, battle, store, marketplace, chest, redeem-code, clan, and limit values in **12 `.jsonc` tuning files**. Mods can overlay any of them under `server/tuning/<name>.jsonc` without writing code.
## 1. Merge Precedence
1. Shipped defaults (`apps/server/tuning/<name>.jsonc`)
2. Enabled mods' `server/tuning/<name>.jsonc` in load order
3. Player overrides (`<dataFolder>/tuning/<name>.jsonc`, highest priority)
## 2. All 12 Tuning Files
`battle.jsonc`, `battle-economy.jsonc`, `store.jsonc`, `marketplace.jsonc`, `trophies.jsonc`, `supply-chests.jsonc`, `recycling.jsonc`, `redeem-codes.jsonc`, `new-profile.jsonc`, `research.jsonc`, `clans.jsonc`, `limits.jsonc`.
## 3. Additive List Operations (`$listOps`)
Objects merge recursively by key; plain arrays replace the previous array. To stack items across multiple mods without clobbering, wrap list edits in `{ "$listOps": [...] }`:
```jsonc
{
"multiVehiclePacks": {
"$listOps": [
{ "op": "append", "items": [{ "id": "mod_duo_pack", "priceGjn": 49.99, "vehicles": ["us_m2a4"] }] },
{ "op": "upsertBy", "key": "id", "item": { "id": "wto_pack_two_fronts", "priceGjn": 19.99 } },
{ "op": "removeBy", "key": "id", "value": "some_pack_id" }
]
}
}
```
Supported ops: `append`, `prepend`, `upsertBy`, `removeBy`.
@@ -0,0 +1,40 @@
# 06 · Server JS/TS Scripting API Reference
> **Experimental Warning (API `0.1-experimental`)**: All server script contracts, internal catalogue classes, and hook shapes are unstable and may change across releases without backwards compatibility.
## 1. Runtime & TypeScript Rules
Server scripts run inside Electron 43's bundled **Node.js 24** with built-in TypeScript type stripping (`erasableSyntaxOnly` syntax: no `enum`, `namespace`, or parameter properties). Pre-bundled `.mjs` / `.js` files are also supported.
Default entry lookup order: `server/index.ts` → `server/index.mjs` → `server/index.js` (or explicit `server.entry` in `mod.jsonc`).
```ts
export default {
async setup(ctx) {
ctx.logger.info('mod initialized');
},
};
```
Full TypeScript definitions live in `packages/mods/src/server-api.ts`.
## 2. `WtoServerModContext`
- `apiVersion`, `manifest`, `modDir`, `gameFolder`, `dataFolder`, `port`
- `logger`: `{ info(msg), warn(msg), error(msg) }` (prefixed with `[mod:<id>]`)
- `storage`:
- `storage.forPlayer(userId)` → atomic JSON file under `<dataFolder>/saves/<userId>/mods/<modId>.json` (never mutate stock `profile.blk` with custom keys)
- `storage.shared()` → `<dataFolder>/mods-data/<modId>.json`
- `hooks`:
- `onDatasetsLoaded(datasets)` — inspect/mutate `vehicles`, `battleEconomy`, `battleSpawnRules`, `multiplayerMissions`, `uiLabels`, `unitNames`, or `get(id)` / `set(id, value)`
- `onCataloguesReady(catalogues)` — access `tuning`, `gameModes`, `profiles`, `accounts`, `research`, `equipment`, `repair`, `store`, `inventory`, `trophies`, `items`, `crew`, `decor`, `unlocks`, `clans`, `battleMatchmaker`, `battleEconomy`, `battleStreaks`, `notifyInventoryChanged()`, `notifyUser(userId, eventName, payload)`
- `onServerListening({ port })` / `onServerClosing()`
- `profile.onRefresh(profile, userId)`
- `battle.onBeforeMatchmake({ userId, eventName, request })`
- `battle.onFilterMissions({ userId, modeId, modeName, economicName, minMrank, maxMrank, missions })` — return a filtered/reordered subset of candidate missions (empty results safely fall back to the prior pool)
- `battle.onLiveFact({ userId, roomId, fact })`
- `battle.onAfterSettle({ userId, roomId, summary })`
- `routes`:
- `routes.char.register(action, handler)` / `routes.char.wrap(action, wrapper)`
- `routes.matching.register(method, handler)` / `routes.matching.wrap(method, wrapper)` (callable from client Quirrel via `matchingApiFunc`)
- `routes.http.register(subPath, handler)` — automatically namespaced under `/mods/<modId>/...` (supports exact paths and `/*` wildcards)
@@ -0,0 +1,21 @@
# 07 · Troubleshooting & Best Practices
## 1. Where to Check Logs
Open **Settings › Diagnostics › Open logs folder** or **About › Export diagnostics**:
- **`launcher.log`**: filter `[build]` for pack/GUI/exe patch reports, `[mods]` for Junction mount and native-file conflict warnings, and `[mod:<id>]` for server script logs and stack traces.
- **`<copy>/.game_logs/*.clog`**: client Quirrel runtime errors and `[PACK]` / `pkg_user` asset loading logs.
## 2. Common Issues
- **Discovery error in Mods page**: check `mod.jsonc` JSON syntax, unknown keys, `id` format, and `server.entry` path.
- **Blocking errors on Launch**: enable missing `requires` dependencies or disable one of two mutually conflicting mods.
- **Node TS syntax error**: avoid `enum`/`namespace`/parameter properties in raw `.ts`, or bundle to `.mjs`.
- **`overlaps protected core patch`**: mod `exe` patch collided with a locked core isolation patch; choose a non-overlapping site.
- **Client hangs at "Loading"**: run full `sq.exe` `compilestring` bytecode checks on all modified/added `.nut` files.
## 3. Cross-Drive & Non-NTFS Behavior
- NTFS drives mount `client/addon/` and exclusive `UserSkins/`/`UserSights/`/`UserMissions/` folders via cross-drive **NTFS Directory Junctions** (no admin required, 0 extra space).
- Flat shared files (`sound/mod/*.bank`) try file symlink → same-drive hardlink → size/mtime cached copy.
- exFAT drives automatically fall back to incremental cached copies.
@@ -0,0 +1,19 @@
// Example experimental server-side TypeScript mod.
// Demonstrates dataset/catalogue hooks, per-account isolated storage, and a custom HTTP endpoint.
{
"format": 1,
"id": "example.server-script",
"name": {
"zh-CN": "示例:服务端 TS 脚本钩子",
"en": "Example: Server TS Script Hooks"
},
"version": "0.1.0",
"author": "WTOffline",
"description": {
"zh-CN": "演示实验期服务端 TypeScript 钩子、独立存档区与自定义 /mods/<id>/status 网页接口。",
"en": "Demonstrates experimental server TypeScript hooks, isolated mod storage, and a custom /mods/<id>/status HTTP route."
},
"api_version": "0.1-experimental",
"game_versions": ["2.61.0.*"],
"load_after": ["example.vehicle-tweak"]
}
@@ -0,0 +1,60 @@
/**
* Example server-side TypeScript mod (erasable TypeScript syntax, runs directly on Electron's Node 24).
*
* EXPERIMENTAL: Internal server contracts and hook shapes may change across WTOffline releases.
*/
interface ModState {
refreshes: number;
lastUpdated: string;
}
export default {
setup(ctx: {
readonly apiVersion: string;
readonly manifest: { readonly id: string; readonly version: string };
readonly logger: { info(msg: string): void };
readonly storage: {
forPlayer(userId: string): { read<T>(): T | undefined; write(value: unknown): void };
};
readonly hooks: {
onDatasetsLoaded(fn: (datasets: { readonly vehicles: unknown[] }) => void): void;
onServerListening(fn: (info: { readonly port: number }) => void): void;
readonly profile: {
onRefresh(fn: (profile: unknown, userId: string) => void): void;
};
};
readonly routes: {
readonly http: {
register(subPath: string, fn: () => { status: number; contentType: string; body: string }): void;
};
};
}) {
let vehicleCount = 0;
ctx.hooks.onDatasetsLoaded((datasets) => {
vehicleCount = datasets.vehicles.length;
ctx.logger.info(`observed ${vehicleCount} vehicles in merged dataset`);
});
ctx.hooks.profile.onRefresh((_profile, userId) => {
const store = ctx.storage.forPlayer(userId);
const prev = store.read<ModState>() ?? { refreshes: 0, lastUpdated: '' };
store.write({ refreshes: prev.refreshes + 1, lastUpdated: new Date().toISOString() });
});
ctx.hooks.onServerListening(({ port }) => {
ctx.logger.info(`custom status endpoint ready at http://127.0.0.1:${port}/mods/${ctx.manifest.id}/status`);
});
ctx.routes.http.register('/status', () => ({
status: 200,
contentType: 'application/json; charset=utf-8',
body: JSON.stringify({
modId: ctx.manifest.id,
version: ctx.manifest.version,
apiVersion: ctx.apiVersion,
vehicleCount,
}),
}));
},
};
@@ -0,0 +1,12 @@
// Incremental BLK patch applied to char.vromfs.bin config/wpcost.blk.
// Only touches the target vehicle block so other mods editing different vehicles stack cleanly.
{
"ops": [
{
"op": "setParam",
"path": ["us_m2a4"],
"name": "rewardMulHistorical",
"value": { "type": "real", "value": 1.2 }
}
]
}
@@ -0,0 +1,2 @@
"<ID|readonly|noverify>";"<English>";"<Chinese>";"<HChinese>"
"us_m2a4_shop";"M2A4 (Modded)";"M2A4(模组示例)";"M2A4(模組示例)"
1 <ID|readonly|noverify> <English> <Chinese> <HChinese>
2 us_m2a4_shop M2A4 (Modded) M2A4(模组示例) M2A4(模組示例)
@@ -0,0 +1,18 @@
// Example additive data mod: adjusts battle rewards via server tuning, patches a stock
// vehicle's economy block in char.vromfs.bin, and updates a localization label in lang.vromfs.bin.
{
"format": 1,
"id": "example.vehicle-tweak",
"name": {
"zh-CN": "示例:载具数值与收益微调",
"en": "Example: Vehicle & Economy Tweak"
},
"version": "0.1.0",
"author": "WTOffline",
"description": {
"zh-CN": "演示零代码叠加:修改对局收益倍率、增量修补 wpcost.blk 与本地化词条。",
"en": "Demonstrates code-free stacking: battle reward tuning, incremental wpcost.blk patching, and localization CSV merging."
},
"api_version": "0.1-experimental",
"game_versions": ["2.61.0.*"]
}
@@ -0,0 +1,5 @@
// Server tuning overlay: multiplies Silver Lions and Research Points rewards by 1.5x.
{
"rewardMultiplierSilverLions": 1.5,
"rewardMultiplierResearchPoints": 1.5
}
@@ -0,0 +1 @@
@import "missions\mapPreferences.css"
@@ -0,0 +1,20 @@
// Register the Custom Map Pool Selector DaGui stylesheet in the root CSS manifest.
{
"id": "official-map-selector/register-css",
"title": "Include wtomapselector.css in gui/css.css",
"features": [
"Custom Map Pool Selector"
],
"variants": [
{
"written_for": "2.61.0.58",
"file": "gui/css.css",
"edits": [
{
"find": "find-css.css",
"replace": "replace-css.css"
}
]
}
]
}
@@ -0,0 +1,2 @@
@import "missions\mapPreferences.css"
@import "missions\wtomapselector.css"
@@ -0,0 +1,4 @@
function updateButtons() {
let wikiLinkBtn = showObjById("wiki_link", hasFeature("AllowExternalLink"), this.scene)
wikiLinkBtn.link = getCurCircuitOverride("wikiMatchmakerURL", loc("url/wiki_matchmaker"))
}
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff. Show more