63 Commits
Author SHA1 Message Date
N0VAN0M4LY 37cbcd806f docs(mods): align handbook chapters with .patch.blk and UI image format notes 2026-12-04 02:52:47 +08:00
N0VAN0M4LY 0af4183cb1 merge(ground-ai): merge feat/tank-ai phase 1 into main 2026-12-04 02:50:48 +08:00
N0VAN0M4LY 65363ce9de feat(mods): support Dagor-style BLK patches and include compilation
Add native-style *.blk.patch.blk and client/config-blk.patch.blk incremental patching alongside compile-time include/includeOnce and Dagor @-directive expansion (@override, @override-last, @replace, @delete, @delete-last, @delete-all, @clone, @clone-last, @inherit, @after, @before, indexed paths, unquoted @ syntax, triple-quoted strings, packed hex colors, and CDK #/develop/gameBase/ paths) while preserving full *.blk.patch.jsonc backwards compatibility.
2026-12-04 02:36:16 +08:00
N0VAN0M4LY 69d95df88e fix(hud): correct LocalMP damage feedback
Use the stock effective-hit flag to award normal hits and show ineffective hits without rewards. Route enemy parts feedback by the actual attacker or recipient and the active spectator state.

Verified both TypeScript projects, the native DLL build, and patch and Quirrel checks on 2.61.0.37, 2.61.0.58, and 2.61.0.60. Built fresh 2.61.0.58 and 2.61.0.60 copies. In-game verification is pending.
2026-12-04 02:35:47 +08:00
N0VAN0M4LY b3f9ff589c fix(ground-ai): short-circuit driveToPos instead of skipping setBehaviorTree
Skipping Unit::setBehaviorTree left unit->behTree null on LocalMP bot tanks, which prevented VehiclePhysActor from applying producedCT to appliedCT (100% dead_echo in sinai_Conq1). Hook driveToPos::update (.37 0x861370, .58 0x863a90) instead and return ER_SUCCESS (1) when the ground AI script is ready, keeping the BehTree initialized while completely suppressing stock tankBot driving. Verified MSVC build (0 warnings) and .37/.58 native module resolution (0 failures).
2026-12-04 01:54:14 +08:00
N0VAN0M4LY 85532cd930 feat(ground-ai)!: disable stock tankBot globally when AI script loads
Replace per-bot mid-battle movement handback to stock AI with a clean
binary startup gate:

- Locate Unit::setBehaviorTree (ground_ai_set_beh_tree: .37 0x4e89b0,
  .58 0x4e8f60) in patches/native/local_mp_ground_ai.jsonc and hook it
  in native/wto-net/src/local_mp_ground_ai.c.
- Announce readiness from [init] in wto_ai_runtime.das via
  wtoGroundAiScriptReady once the ground AI scripts finish compiling
  cleanly with custom movement enabled. When announced, hook_set_beh_tree
  suppresses attaching "tankBot" to LocalMP bot tanks and keeps their
  MoveSystem.inactive pinned to 1 for the life of the vehicle, ending
  all tug-of-war (external_inactive_reset) with stock AI.
- If scripts fail to compile, are missing, or mode is "stock" / "fire",
  ownMovement stays 0 and stock tankBot runs untouched.
- Remove per-bot handback, timeout release, and the now-obsolete
  navigation.returnToStockOnFailure config plumbing; on genuine script
  failure a bot halts in place and logs DRIVE_FAIL instead of silently
  switching to stock. Also initialize newly spawned bot ticks to run on
  frame 0 to eliminate spawn-frame invalid_drive_cmd noise.

Verified MSVC build of wto_ws.dll (0 warnings in project C sources), root
and launcher type checks, native module resolution on both 2.61.0.37 and
2.61.0.58 (0 failures), isolated 2.61.0.58 startup confirming 12/12
LocalMP modules installed, wto_ai_runtime.das loaded in 213 ms (0 compile
errors), and "ground AI script ready (ownMovement=1; stock tankBot
disabled)" in wto_ws.log.

BREAKING CHANGE: removes navigation.returnToStockOnFailure from
tuning/ground-ai.jsonc; stock tankBot is now controlled strictly by
whether the custom ground AI script loaded with custom movement enabled.
2026-12-04 01:06:04 +08:00
N0VAN0M4LY 651b023d2a fix(launcher): preserve skipped files during game updates
Reuse source scan exclusions during stale-file cleanup so updates preserve user content and tool files copied by earlier installers.

Verified with root and launcher typechecks and an update run against temporary folders.
2026-12-04 00:47:29 +08:00
N0VAN0M4LY 1d3e47b082 feat(launcher): allow changing the online update source
Let registered clients set or replace their online installation source
from the maintenance page. Validate the source and persist its path
before refreshing the available update status.

Verified launcher and workspace type checks, a launcher build, and an
incremental update of a registered client using local game snapshots.
2026-12-04 00:11:55 +08:00
N0VAN0M4LY ac35c25851 feat(ground-ai): add ready-rack dual-ammo bot spawn loadouts and shell switching
Select realistic ready-rack dual-shell loadouts for AI tanks on the local
server, inject them natively on bot spawn, and switch between anti-armor
and soft-target shells in battle:

- Add the loadout section to tuning/ground-ai.jsonc (lowReadyRackThreshold,
  topUpAmmoCount, primaryAmmoPct, secondaryMinRounds,
  penetrationCompareDistM), validated in ground-ai-tuning.ts.
- Add the tank-bot-ammo v2 dataset (apps/server/src/game-data/datasets/
  tank-bot-ammo.ts) reading primary cannon weapon name, capacity,
  firstStage/autoLoad shell ready-rack counts (excluding separate charges),
  and selectable shell modifications (using Lanz-Odermatt kinetic fields,
  cumulativeDamage, armorpower, and transitive reqModification chains).
- Add selectBotTankLoadouts (apps/server/src/battle/bot-tank-loadouts.ts):
  carry ready-rack count when >= 15 (top up to 22 when smaller or absent,
  clamped to gun capacity), skip SPAA/belt autocannons, pick highest-tier
  APFSDS/anti-armor primary (~80%) plus HE/HESH/HEAT secondary (~20%, min
  3 rounds) when available, and attach required addModification entries and
  per-tank wtoAmmo_<unit> strings to customBots when mode != stock.
- Hook Unit::changeAircraft (already located dynamically on .37 and .58) in
  native/wto-net/src/local_mp_loadout.c to assign the 24-byte
  ChangeUnitReflection.bullets entries via bullet_vec_assign for LocalMP
  bot spawns (async == 0, non-local bot MPlayer), leaving player spawns
  untouched.
- Track soft-target vs anti-armor shell classes in wto_ai_specs_common.das
  and write gun.nextBulletType in wto_ai_fire_common.das to queue HE/HESH
  against light/narrow targets and APFSDS/AP against MBTs/heavy armor.

Verified MSVC build of wto_ws.dll (0 warnings in project C sources), root
and launcher type checks, 14/14 check-patches on 2.61.0.58, 12/12 LocalMP
module installation, clean daScript load (wto_ai_runtime.das loaded in
211 ms, 0 compile errors), and real 2.61.0.58 loadout selection on
cn_ztz_96a (18 APFSDS + 4 HE), germ_leopard_2a4 (12 DM23 + 3 HEATFS),
ussr_t_80bvm (22 3BM60 + 6 HE), us_m1a2_abrams (14 M829A2 + 4 HEAT-MP),
ussr_t_34_1941 (18 APHEBC + 4 HE), and ussr_zsu_23_4 (stock belt kept).
Live battle acceptance begins in Step 9.
2026-12-03 19:25:04 +08:00
N0VAN0M4LY d5008baeff feat(ground-ai): add navmesh flank lanes, rally staging, recall, and air-aware SPAA
Complete the team commander layer with validated flank routes, coordinated
rally launches, dynamic cap recall, and air-threat-responsive SPAA:

- Add flank, rally, and recall parameters to the commander section of
  tuning/ground-ai.jsonc (flankMaxLengthRatio, flankMinSeparationM,
  rallyProgressFrac, rallyWaitSec, rallyMinFrac, rallyRadiusM,
  recallSafeHoldSec), validated in ground-ai-tuning.ts and compiled into
  WTO_AI_CMD_* constants.
- Add wto_ai_lanes_common.das:
  - Lazily build and cache per-(team, cap) center and left/right flank
    lanes using two-segment navmesh find_path_ex; reject flanks exceeding
    1.6x center path length or closer than 45 m to the center midpoint.
  - Stage offensive groups at the 40% rally point along their lane and
    launch once 2/3 of the group arrives or 25 s elapse, resetting on cap
    ownership flips.
  - Track enemy ground count and contested state on friendly caps,
    holding recall active until safe for 15 s; track enemy aircraft
    presence for team SPAA intel.
- Split mode planners and recall demand overrides into
  wto_ai_commander_plans_common.das; pull (enemies + 1) nearest support
  or reserve bots to defend contested friendly caps while always keeping
  at least one offensive assault bot.
- Update wto_ai_commander_anchors_common.das so SPAA follows behind the
  actual Assault group centroid and checks upward open-sky clearance when
  enemy aircraft are active.
- Wire WtoTaskOrder lane/relay/rally fields into wto_ai_route_common.das
  (replacing unvalidated wing relays and preserving corridor turning
  corners), wto_ai_tactics_common.das (rally staging hold), and
  wto_ai_runtime.das (1 s rally release check).

Verified root and launcher type checks, isolated 2.61.0.58 build (27
ground AI modules packed), and clean in-engine daScript compilation/load
(wto_ai_runtime.das loaded in 183 ms, 0 compile errors). Live battle
acceptance deferred until the full pipeline is wired.
2026-12-03 18:46:53 +08:00
N0VAN0M4LY 45ff082a36 feat(ground-ai): add sample-based lead estimation, exit watch, and bounded bias
Replace direct reads of true enemy velocity with an own-sight sample
estimator, add 2-5 s last-seen exit watching, and sample bounded aiming
bias once per shooting opportunity:

- Add the estimation section to tuning/ground-ai.jsonc (watchMinSec,
  watchMaxSec, velSampleMinSpanSec, velStableSpanSec, velJumpResetMps,
  baseAimSigmaM, leadErrorFrac, maxBiasM), validated in
  ground-ai-tuning.ts and compiled into WTO_AI_EST_* constants.
- Add wto_ai_estimate_common.das:
  - Maintain a 6-sample timestamped ring buffer from each bot's own
    visual sightings; compute smoothed observed velocity and convergence
    quality, dropping quality and re-seeding bias on sudden braking/turns
    or target switches.
  - On LOS loss from an active ground engagement, freeze watchPos at the
    last-seen exit point, clear observed velocity, and draw one random
    2-5 s watch duration; stationary overwatch/defend bots hold their
    post while watching, whereas pushing/retreating bots keep moving
    while keeping their turret on the exit.
  - Compute lead from observed velocity and loaded-shell flight time,
    sampling one bounded bias vector per shooting opportunity (target,
    shot count, state, 12 m position cell) that narrows as observation
    quality improves and still passes the single fire-permission gate.

Verified root and launcher type checks, isolated 2.61.0.58 build (25
ground AI modules packed), and clean in-engine daScript compilation/load
(wto_ai_runtime.das loaded in 184 ms, 0 compile errors). Live battle
acceptance deferred until the full pipeline is wired.
2026-12-03 18:23:12 +08:00
N0VAN0M4LY 80113bdd2e feat(ground-ai): add cover reload, stalemate reposition, and damage repair
Complete the single-vehicle tactical loop for reload survival, stalemate
breaking, and vehicle damage repair:

- Add cover, reload, hull-angle, stalemate, reposition, and repair-cover
  parameters to tuning/ground-ai.jsonc, validated in ground-ai-tuning.ts
  and compiled into WTO_AI_SM_* constants.
- Add wto_ai_cover_common.das: continuously record the last hard-concealed
  hull position before peeking, and evaluate 9 cover candidates around
  the tank (with enemy-clearance scoring when searching for a repair
  cover).
- Add wto_ai_tactics_actions_common.das and wire wto_ai_tactics_common.das:
  - Damage retreat & repair (plan 6.1): when gun is inoperable while
    mobile, retreat to an enemy-free cover and send
    EventRepairSystemRequestRepair(repair=true) once safe; when engine or
    tracks immobilize the chassis, halt in place, request repair, and keep
    gun self-defense active; stay halted while
    repair_system_remaining_repair_time > 0.
  - 3-way reload action: pull back into remembered/nearby cover (up to 6 s
    budget, uninterrupted by flashes/new orders) -> zigzag advance at
    +/-18 deg when pushing without cover -> angle hull front +/-15 deg
    when side-exposed >30 deg with pivot room.
  - Stalemate reposition: confirm outgoing effective damage via
    EventUnitDamage (uint(hpFixed) < uint(prevHpFixed)) and enemy death;
    trigger lateral reposition after 2 no-effect shots, 2 no-shot halts,
    or 12 s cumulative halt time, unlocking short-halt only after 20 m
    progress or reaching the new position.
- Split periodic telemetry out of wto_ai_runtime.das into
  wto_ai_diag_common.das to keep every module under 300 lines.

Verified root and launcher type checks, isolated 2.61.0.58 build (24
ground AI modules packed), and clean in-engine daScript compilation/load
(wto_ai_runtime.das loaded in 228 ms, 0 compile errors). Live battle
acceptance deferred until the full pipeline is wired.
2026-12-03 18:14:43 +08:00
N0VAN0M4LY 314bdfe68e feat(ground-ai): add hull state machine and two-beat turn driving
Replace the legacy tactics posture heuristics with an explicit per-bot
hull state machine driven by WtoTaskOrder and the 100/300/800 m distance
tiers, and fix chassis steering bugs:

- Add the stateMachine section to tuning/ground-ai.jsonc (preaimAngleDeg,
  shortHaltMaxSec, shortHaltCooldownSec, turnLaunchSpeedMps), validated in
  ground-ai-tuning.ts and compiled into WTO_AI_SM_* constants.
- Replace WTO_POSTURE_* with the unified WTO_STATE_* hull state enum in
  wto_ai_types_common.das and decouple wto_perceive_update into
  wto_ai_runtime.das so perception runs independently of hull tactics.
- Rewrite wto_ai_tactics_common.das as a priority-arbitrated state
  machine: safety/SPAA -> ridge withdrawal -> active SHORT_HALT budget
  (3 s limit with cooldown on timeout) -> crowd dispersion -> distance-tier
  combat (RUN_AND_GUN <=100 m and high-urgency 100-300 m slow-move-fire;
  PREAIM keeping the hull moving while gun reloads or turret error >8 deg;
  SHORT_HALT only when ready and permitted by order.maxStopRangeM / 800 m
  4 s window; RELOAD_ADVANCE when reloading away from cover) -> MARCH.
  Log every state transition with reason, distance and speed.
- Fix the inverted neutral-pivot condition in wto_ai_drive_common.das,
  add 2nd-gear straight-launch before full steering when turning with
  open front clearance, and use full throttle when accelerating to target
  speed so the automatic gearbox upshifts cleanly.

Verified root and launcher type checks, isolated 2.61.0.58 build (21
ground AI modules packed), and clean in-engine daScript compilation/load
(wto_ai_runtime.das loaded in 195 ms, 0 compile errors). Live battle
acceptance deferred until the full pipeline is wired.
2026-12-03 17:47:10 +08:00
N0VAN0M4LY 9229045042 feat(ground-ai): add exposure perception and single ballistic fire gate
Replace the old foliage-ignoring LOS check and 45 m pre-fire ray with
separate vision/hard-occlusion queries, exposure-integrated spotting, and
a single fire-permission gate for every ground weapon:

- Add perception and fire-gate distance/ballistics/budget parameters to
  tuning/ground-ai.jsonc, validated in ground-ai-tuning.ts and compiled
  into wto_ai_config_common.das.
- Extract wto_ai_combat_types_common.das and add wto_ai_sight_common.das:
  visual checks use smoke occluders, ETF_ALL with aimRay material,
  traceTransparencyRayRIGenNormalized foliage transparency, and vehicle/
  wreck checks; hard-occlusion checks test terrain/structures plus both
  ETF_RI and ETF_RI_PHYS without skipping soft foliage, plus swept
  sphere_cast and wreck/vehicle bounds along the full shot distance.
- Rewrite wto_ai_perceive_common.das with per-target exposure integration
  (fast/normal/far fill times and occlusion decay), 4-point visibility
  sampling with continuous >=2-point LOS tracking for the 800 m 4-second
  window, frozen last-seen coordinates with zeroed velocity on LOS loss,
  and impact-time hit direction (no live offender lookup).
- Record per-shell ballistics profiles (speed, Cx, mass, ballisticCaliber)
  in wto_ai_specs_common.das and sync the currently loaded shell from
  gun.chosenBulletType / bulletSets at runtime.
- Add wto_ai_fire_gate_common.das as the sole ground trigger exit: checks
  visual lock, weapon readiness, distance-tier measured chassis speed
  limits (100/300/800 m), 800 m 4-second window, aim settle, per-frame
  check budget, straight muzzle hard-ray, drag-integrated ballistic arc
  sweep, predicted friendly corridor, and every barrel in the primary
  trigger group. Confirm real shot departure from loaded ammo/readiness,
  remove the pure-launcher stock bypass and add_unit_for_target leak, and
  log exact deny/shot reasons.

Verified root and launcher type checks, isolated 2.61.0.58 build (21
ground AI modules packed), and clean in-engine daScript compilation/load
(wto_ai_runtime.das loaded in 186 ms, 0 compile errors). Live battle
acceptance deferred until the full pipeline is wired.
2026-12-03 17:34:59 +08:00
N0VAN0M4LY 7e5eb99696 feat(ground-ai): add task order, mode-aware commander v1, and world fixes
Replace the per-bot greedy cap scorer (wto_ai_macro_common.das) with a
whole-team commander and explicit task order contract, and fix the world,
spec, and navigation bugs found during the codebase audit:

- Classify ground battle modes (bttl, conq, dom) in multiplayer-missions
  v5 from mislist.blk categories (with suffix fallback for event maps) and
  emit wtoGroundMode in customRules/customBots.
- Add the commander section to tuning/ground-ai.jsonc with range and sum
  validation, compiled into WTO_AI_CMD_* constants.
- Split zone/mode/spawn refresh into wto_ai_world_zones_common.das and fix
  four world snapshot bugs: stop double-recording deaths in wreck scans
  and deduplicate with a ring cursor, refresh units before spawn fallback
  while retrying real respawn points, fall back battleCenter to spawns
  when capCount is 0, and relax cap radius clamping to 10..180 m.
- Fix limited-traverse yaw overwrite in wto_ai_specs_common.das and
  compute pivot turn angle against wishDir in wto_ai_nav_common.das.
- Introduce WtoTaskOrder (wto_ai_order_common.das) and whole-team
  commander v1 (wto_ai_commander_common.das +
  wto_ai_commander_anchors_common.das): mode-aware role quotas (Bttl,
  Conq, Dom), deterministic distance + vehicle-suitability matching,
  20-second role hysteresis, separate total-assigned vs cap-insider
  counters, frontline-relative SPAA anchors, EventZoneCaptured immediate
  rebalance, and per-team WTO_AI|CMD telemetry.

Verified root and launcher type checks, multiplayer-missions v5 dataset
extraction (1140 missions with Bttl/Conq/Dom classification), isolated
2.61.0.58 build (18 ground AI modules packed), and clean in-engine
daScript compilation/load (wto_ai_runtime.das loaded in 155 ms, 0 compile
errors). Live battle tuning and acceptance deferred until the full
pipeline is wired.
2026-12-03 17:20:17 +08:00
N0VAN0M4LY 73bae4785f fix(ground-ai): harden drive ownership, teardown and failure switch
Address two issues found in the first isolated 2.61.0.58 live runs and add
a test switch to disable silent fallback to stock movement:

- Add navigation.returnToStockOnFailure in tuning/ground-ai.jsonc (default
  true), compiled into WTO_AI_NAV_RETURN_TO_STOCK and written to wto_ws.cfg
  as ground_ai_return_to_stock=0 when disabled. When false, failed or
  timed-out bots keep stock movement paused, brake in place and log the
  failure once instead of silently handing control back to stock tankBot.
- Allow holdMs=0 release actions even after local_mp_is_host() flips false
  during mission unload, add eid=0 bulk release on wto_reset_runtime(), and
  match slots by eid rather than live owner lookup so match exit cleans up
  the native control table immediately.
- Stop releasing drive ownership when a vehicle is immobilized by damage or
  repair; brake in place and pause the echo watchdog instead, avoiding the
  1-second release/re-acquire flapping observed during combat. Log exact
  release reasons and back off for 1 second if MoveSystem.inactive is
  cleared externally.

Verified MSVC build of wto_ws.dll (0 warnings in project C sources), root
and launcher type checks, 14/14 check-patches on 2.61.0.58, and a temporary
2.61.0.58 game copy build confirming ground_ai_return_to_stock=0 in
wto_ws.cfg and 15 packed daScript modules. Live battle re-check pending.
2026-12-03 16:47:44 +08:00
N0VAN0M4LY 89242e91f0 feat(ground-ai): default to the full custom ground AI
Stock tankBot only drives each bot to a capture point, so the custom AI is the intended player default. Stock mode stays available for troubleshooting, and per-vehicle control still returns to stock movement on failure. Verified the shipped tuning loads with mode full.
2026-12-03 16:09:36 +08:00
N0VAN0M4LY 5e521295a3 feat(ground-ai)!: replace layer switches with complete modes
Ground AI layers could be enabled in any combination, including ones the
scripts cannot run (fire control without perception disabled stock aiming
and never fired). The configuration now selects one of four complete modes:
stock, fire (stock movement, custom fire permission), drive (custom orders
and driving, stock firing) and full. The build derives the compiled layer
constants from the mode, and an unknown mode is rejected at load time.

The offline tank class weights for the AI bot pool move from code into
tuning/ground-ai.jsonc (lineupWeights). They apply only when a custom mode
is active; stock mode keeps the stock weight of 1 for every vehicle.

Verified root and launcher type checks, mode-to-constant compilation for
all four modes, rejection of an unknown mode, bot pool weights in stock and
custom modes, and temporary 2.61.0.58 game copy builds in full mode (15
script modules packed) and stock mode (no game pack written).

BREAKING CHANGE: ground-ai.jsonc drops "enabled" and "layers". Override
files set "mode" to "stock", "fire", "drive" or "full" instead.
2026-12-03 16:05:03 +08:00
N0VAN0M4LY 885e3bbb5d feat(ground-ai): return bot movement control on failure
Grant custom physics control per LocalMP bot and let the native layer release it when the script stops renewing control. Verified both TypeScript checks, the MSVC build, native resolution and check-patches on .37 and .58, and isolated .58 script loading.
2026-12-03 14:24:32 +08:00
N0VAN0M4LY bb680c6abd fix(patcher): retain stock tank AI movement
Keep the original behavior tree installed and validate the optional script entry and dependencies after mod overlays. Verified stock tree bytes and the enable/disable rebuild on 2.61.0.58.
2026-12-03 14:24:32 +08:00
N0VAN0M4LY 975a28441a feat(ground-ai): implement modular zero-heap tank AI daScript layers
Add 14 modular daScript files under game-ai/ground covering per-vehicle
DataBlock specs, foliage-filtered terrain and cliff crest lookahead,
flat world snapshots, anti-clustering telemetry and active dispersion,
cap-insider-bounded macro scheduling, sticky 6-channel perception,
ridge snipe/reverse withdraw tactics, wide-projected NavMesh routing,
bidirectional forward/reverse DWA local planning, closed-loop
VehiclePhys chassis control, and settled ballistic fire control.
2026-12-03 12:12:17 +08:00
N0VAN0M4LY 4ac3484f56 feat(patcher,server): wire ground AI tuning, bot weights, and pack build
Add ground-ai.jsonc tuning validation, realistic tank class weights for
customBots pools, on-demand game.vromfs.bin / ailist.blk injection in
@wto/patcher, and launcher/CLI build integration while keeping all
ground AI layers disabled by default in shipped configuration.
2026-12-03 12:07:30 +08:00
N0VAN0M4LY a2fdcc1f15 docs(mods): fix schema errors and expand bilingual mod handbook to full parity
Fix store.jsonc vehiclePacks nesting and gjn field name, matchingApiFunc callback argument order, and DaGui CSS @import/lowercase rules; add stock archive inspection steps, BR-to-mrank table, cloned vehicle walkthrough, tuning field reference, and official-map-selector full-stack trace while bringing en/01..07.md to full 1:1 parity with zh-CN/.
2026-12-03 11:25:54 +08:00
N0VAN0M4LY e79866b96e docs(dev-docs): rewrite bilingual developer handbook with real code and byte walkthroughs
Expand dev-docs with a plain-language glossary, accurate single-port server flow, real apps/server directory map and cln_set_researchable trace, un-elided 57-byte EXE patch anatomy, 6-file Native C wiring guide, real Good vs. Bad code comparisons, AI constraint prompt, and traffic-log debugging steps at 1:1 zh-CN/en parity.
2026-12-03 11:25:53 +08:00
N0VAN0M4LY e2ac4fa744 fix(launcher): use original-fs for copy and guard nested launcher folders
Electron patches node:fs to treat any .asar file on disk as a virtual
archive directory. When a player's War Thunder source directory contains
an .asar file (for example from a leftover portable launcher folder
previously unpacked inside the game folder), createReadStream fails with
ENOENT and aborts full-copy installation.

Changes:
- Add rawFs() helper using Electron's original-fs (with node:fs fallback)
  and use it across copy-game.ts and change-copy-files.ts for directory
  scans, streaming copies, timestamp preservation, rollback and cleanup.
- Preserve the first non-cancellation worker error in copyPlannedFiles so
  sibling AbortError rejections do not mask the real filesystem or
  hardlink error.
- Skip nested subfolders containing WTOffline Launcher.exe during
  planCopy, and reject copy installation upfront with
  launcher_inside_source when the packaged launcher itself runs from
  inside the selected source game directory (with en and zh-CN messages).

Verification:
- Root and launcher typecheck passed.
- Launcher electron-vite build passed.
- en.json and zh-CN.json key parity check passed (720 keys).
- Verified in Electron that patched node:fs reproduces ENOENT on
  default_app.asar while original-fs copies and cleans it up cleanly.
- Packaged installer end-to-end verification pending.
2026-12-03 10:40:49 +08:00
N0VAN0M4LY 01bafb6db7 fix(launcher): detach portable updater via Start-Process on Windows
Spawning powershell.exe directly with Node detached: true sets DETACHED_PROCESS (no console), causing Windows PowerShell 5.1 ConsoleHost to exit silently with code 0 before running -File. Spawning without detached lets it run, but Electron tears down attached children on app.quit(). Launch the apply script via a short hidden PowerShell Start-Process helper before quitting, properly quoting paths with spaces or non-ASCII characters, and clean up staged files if launching fails.
2026-12-03 07:48:44 +08:00
N0VAN0M4LY 18637cf1ff fix(launcher): skip user skins, sights, CDK, and launcher log folders when copying game
Exclude UserSkins and UserSights from stock client scans as player data folders (matching UserMissions and keeping them protected from symlink redirection during launch), and skip WarThunderCDK plus official launcher/updater log and obsolete folders when copying, sizing, or incrementally updating from a stock installation.

Verified: root typecheck, launcher typecheck, and launcher electron-vite build pass; runtime copy test pending.
2026-12-03 07:24:54 +08:00
N0VAN0M4LY 10427912e2 feat(launcher): display rendered markdown release notes in a modal
Keep the About page launcher update notice compact by showing only the available version, package size, and action buttons, with a compact button to open a scrollable release notes dialog when notes are present. Render GFM Markdown safely into React elements via marked.lexer without injecting raw HTML, and raise the release notes cap from 1,600 chars to 64 KiB so full bilingual notes are preserved.
2026-12-03 07:18:31 +08:00
N0VAN0M4LY 214f9d7f4b fix(launcher): use original-fs in portable updater and drop default_app.asar
Electron patches node:fs to treat .asar archives as virtual directories, so portable update verification failed on staged resources/default_app.asar and recursive cleanup could leave staging folders behind. Switch staging lstat and cleanup rm in portable-update.ts to original-fs (falling back to node:fs outside Electron), strip unused resources/default_app.asar during packaging so already-released 0.1.2/0.1.3 portable builds can update cleanly to future releases, and include portable-update.log in exported diagnostics.
2026-12-03 07:18:14 +08:00
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
247 changed files with 25309 additions and 673 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/
+3 -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,10 +14,12 @@
}, },
"dependencies": { "dependencies": {
"@fontsource/roboto-condensed": "^5.3.0", "@fontsource/roboto-condensed": "^5.3.0",
"@wto/mods": "*",
"@wto/patcher": "*", "@wto/patcher": "*",
"@wto/server": "*", "@wto/server": "*",
"fflate": "^0.8.2", "fflate": "^0.8.2",
"i18next": "^26.3.6", "i18next": "^26.3.6",
"marked": "^18.4.0",
"react": "^19.2.8", "react": "^19.2.8",
"react-dom": "^19.2.8", "react-dom": "^19.2.8",
"react-i18next": "^17.0.10", "react-i18next": "^17.0.10",
+55
View File
@@ -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';
@@ -175,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', () => {
@@ -22,7 +22,9 @@ import {
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset, FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
} from '../patch-pack/release-assets.ts'; } from '../patch-pack/release-assets.ts';
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts'; import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
import { isPortableLauncher, launchPortableUpdater, preparePortableInstall } from './portable-update.ts'; import {
cleanupPreparedPortableInstall, isPortableLauncher, launchPortableUpdater, preparePortableInstall,
} from './portable-update.ts';
type UpdateMode = 'installer' | 'portable'; type UpdateMode = 'installer' | 'portable';
@@ -215,7 +217,12 @@ export function installAppUpdate(version: string, launcherBusy: () => boolean):
try { try {
if (offer.mode === 'portable') { if (offer.mode === 'portable') {
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot()); const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
launchPortableUpdater(prepared); try {
await launchPortableUpdater(prepared);
} catch (launchError) {
await cleanupPreparedPortableInstall(prepared);
throw launchError;
}
app.quit(); app.quit();
return; return;
} }
@@ -7,21 +7,35 @@
* only obsolete files listed in the previous portable inventory (never touching unrelated user * only obsolete files listed in the previous portable inventory (never touching unrelated user
* files in the same folder), and restarts the updated executable. * files in the same folder), and restarts the updated executable.
*/ */
import { execFile, spawn } from 'node:child_process'; import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
import * as nodeFs from 'node:fs';
import { existsSync } from 'node:fs'; import { existsSync } from 'node:fs';
import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { promisify } from 'node:util'; import { promisify } from 'node:util';
import { z } from 'zod'; import { z } from 'zod';
const execute = promisify(execFile); const execute = promisify(execFile);
const require = createRequire(import.meta.url);
export const PORTABLE_MARKER_FILE = 'portable-mode'; export const PORTABLE_MARKER_FILE = 'portable-mode';
export const PORTABLE_FILES_MANIFEST = 'portable-files.json'; export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
export const PORTABLE_UPDATE_LOG_FILENAME = 'portable-update.log';
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe'; const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe'; const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
// Electron patches node:fs to expose .asar archives as virtual directories, which makes
// lstat().isFile() return false and recursive rm() fail on staged .asar files.
function rawFsPromises(): typeof nodeFs.promises {
try {
return (require('original-fs') as typeof nodeFs).promises;
} catch {
return nodeFs.promises;
}
}
const PortableInventorySchema = z.object({ const PortableInventorySchema = z.object({
format: z.literal(1), format: z.literal(1),
version: z.string().min(1), version: z.string().min(1),
@@ -216,6 +230,7 @@ export async function preparePortableInstall(
): Promise<PreparedPortableUpdate> { ): Promise<PreparedPortableUpdate> {
await assertWritableFolder(installDir); await assertWritableFolder(installDir);
await mkdir(updatesRoot, { recursive: true }); await mkdir(updatesRoot, { recursive: true });
const rawFs = rawFsPromises();
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`); const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
await mkdir(stagingDir, { recursive: true }); await mkdir(stagingDir, { recursive: true });
try { try {
@@ -238,7 +253,7 @@ export async function preparePortableInstall(
} }
for (const rel of newFiles) { for (const rel of newFiles) {
const stagedPath = resolveInside(stagingDir, rel); const stagedPath = resolveInside(stagingDir, rel);
const stats = await lstat(stagedPath); const stats = await rawFs.lstat(stagedPath);
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`); if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
} }
@@ -254,7 +269,7 @@ export async function preparePortableInstall(
installDir: resolve(installDir), installDir: resolve(installDir),
stagingDir, stagingDir,
archivePath, archivePath,
logPath: join(updatesRoot, 'portable-update.log'), logPath: join(updatesRoot, PORTABLE_UPDATE_LOG_FILENAME),
executable: LAUNCHER_EXECUTABLE, executable: LAUNCHER_EXECUTABLE,
newFiles, newFiles,
staleFiles, staleFiles,
@@ -263,21 +278,46 @@ export async function preparePortableInstall(
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8'); await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
return { scriptPath, planPath, stagingDir }; return { scriptPath, planPath, stagingDir };
} catch (error) { } catch (error) {
await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined); await rawFs.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
throw error; throw error;
} }
} }
export function launchPortableUpdater(prepared: PreparedPortableUpdate): void { export async function cleanupPreparedPortableInstall(prepared: PreparedPortableUpdate): Promise<void> {
const child = spawn('powershell.exe', [ const rawFs = rawFsPromises();
'-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass', await rawFs.rm(prepared.stagingDir, { recursive: true, force: true }).catch(() => undefined);
'-File', prepared.scriptPath, prepared.planPath, await rm(prepared.planPath, { force: true }).catch(() => undefined);
], { }
cwd: dirname(prepared.scriptPath),
detached: true, /**
stdio: 'ignore', * Launch the portable apply script in a hidden PowerShell process that survives Electron exit.
windowsHide: true, *
shell: false, * On Windows, spawning powershell.exe directly with Node's `detached: true` sets DETACHED_PROCESS
}); * (no console), causing Windows PowerShell 5.1 ConsoleHost to exit silently with code 0 before
child.unref(); * running `-File`. Spawning without `detached` lets PowerShell run, but Electron tears down
* attached children on `app.quit()`. Using a short hidden PowerShell helper with `Start-Process`
* gives the updater its own hidden console and cleanly detaches it before the launcher quits.
*/
export async function launchPortableUpdater(prepared: PreparedPortableUpdate): Promise<void> {
const workDir = dirname(prepared.scriptPath);
const launcherPath = join(workDir, `launch-portable-${randomUUID()}.ps1`);
const script = [
'param([string]$ScriptPath, [string]$PlanPath, [string]$WorkDir)',
"$ErrorActionPreference = 'Stop'",
'$argsList = @(',
" '-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',",
' \'-File\', "`"$ScriptPath`"", "`"$PlanPath`""',
')',
"Start-Process -FilePath 'powershell.exe' -WorkingDirectory $WorkDir -WindowStyle Hidden -ArgumentList $argsList",
].join('\r\n');
// UTF-8 BOM ensures Windows PowerShell 5.1 decodes non-ASCII paths properly.
await writeFile(launcherPath, `\uFEFF${script}\r\n`, 'utf8');
try {
await execute('powershell.exe', [
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
'-File', launcherPath, prepared.scriptPath, prepared.planPath, workDir,
], { cwd: workDir, windowsHide: true, timeout: 30_000 });
} finally {
await rm(launcherPath, { force: true }).catch(() => undefined);
}
} }
@@ -1,10 +1,11 @@
import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';
import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path'; import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path';
import { rawFs } from '../../util/raw-fs.ts';
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts'; import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
export async function fileInfo(path: string) { export async function fileInfo(path: string) {
const fsPromises = rawFs().promises;
try { try {
return await lstat(path); return await fsPromises.lstat(path);
} catch (error) { } catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
return null; return null;
@@ -28,7 +29,8 @@ export async function changeCopyFiles<T>(
prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>, prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>,
recordChange: () => Promise<T>, recordChange: () => Promise<T>,
): Promise<T> { ): Promise<T> {
const work = await mkdtemp(join(dirname(root), '.wto-copy-')); const fsPromises = rawFs().promises;
const work = await fsPromises.mkdtemp(join(dirname(root), '.wto-copy-'));
const incoming = join(work, 'new'); const incoming = join(work, 'new');
const backups = join(work, 'old'); const backups = join(work, 'old');
const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = []; const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = [];
@@ -44,14 +46,14 @@ export async function changeCopyFiles<T>(
const entry = { target, saved: null as string | null, replaced: false }; const entry = { target, saved: null as string | null, replaced: false };
if (old) { if (old) {
const saved = join(backups, path); const saved = join(backups, path);
await mkdir(dirname(saved), { recursive: true }); await fsPromises.mkdir(dirname(saved), { recursive: true });
await rename(target, saved); await fsPromises.rename(target, saved);
entry.saved = saved; entry.saved = saved;
} }
changes.push(entry); changes.push(entry);
if (add) { if (add) {
await mkdir(dirname(target), { recursive: true }); await fsPromises.mkdir(dirname(target), { recursive: true });
await rename(join(incoming, path), target); await fsPromises.rename(join(incoming, path), target);
entry.replaced = true; entry.replaced = true;
} }
} }
@@ -60,8 +62,8 @@ export async function changeCopyFiles<T>(
} catch (error) { } catch (error) {
for (const { target, saved, replaced } of changes.reverse()) { for (const { target, saved, replaced } of changes.reverse()) {
try { try {
if (replaced) await rm(target, { force: true }); if (replaced) await fsPromises.rm(target, { force: true });
if (saved) await rename(saved, target); if (saved) await fsPromises.rename(saved, target);
} catch (rollbackError) { } catch (rollbackError) {
keepBackups = true; keepBackups = true;
console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError); console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError);
@@ -70,7 +72,7 @@ export async function changeCopyFiles<T>(
throw error; throw error;
} finally { } finally {
if (!keepBackups && relative(dirname(root), dirname(work)) === '') { if (!keepBackups && relative(dirname(root), dirname(work)) === '') {
await rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error)); await fsPromises.rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error));
} }
} }
} }
@@ -7,7 +7,7 @@ import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schema
import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts'; import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts'; import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { sameVolume } from '../game-folder/inspect-target-folder.ts'; import { sameVolume } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts'; import { copyPlannedFiles, isInSkippedSourceFolder, planCopy, type CopyPlan } from '../install/copy-game.ts';
import { import {
fileHash, fileHash,
linkVerifiedResource, linkVerifiedResource,
@@ -21,20 +21,10 @@ import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } fro
import { checkPatches } from '../install/patch-check.ts'; import { checkPatches } from '../install/patch-check.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts'; import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts'; import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
import { readSource } from './copy-source.ts';
export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void; export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
if (!record.sourcePath) return null;
try {
const game = await inspectGameFolder(record.sourcePath);
return game.missingFiles.length > 0 ? null : game;
} catch (error) {
if (error instanceof AppError) return null;
throw error;
}
}
export function isNewer(source: GameFolderInspection | null, version: string | null): boolean { export function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
return !!source?.version && !!version && compareVersions(source.version, version) > 0; return !!source?.version && !!version && compareVersions(source.version, version) > 0;
} }
@@ -67,7 +57,10 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
const linked = record.hardlinkedFiles ?? []; const linked = record.hardlinkedFiles ?? [];
const linkedPaths = new Set(linked.map(key)); const linkedPaths = new Set(linked.map(key));
const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root); const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root);
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name))); // Older installs may have tracked files in folders that source scans now skip.
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter(
(name) => !found.has(key(name)) && !isInSkippedSourceFolder(name),
);
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles( const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal, game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
); );
@@ -13,7 +13,8 @@ import { gameProcessRunning, launchInProgress } from '../launch/launch-controlle
import { readInstalledLab } from '../launch/lab-handoff.ts'; import { readInstalledLab } from '../launch/lab-handoff.ts';
import { localServerReady } from '../launch/local-server.ts'; import { localServerReady } from '../launch/local-server.ts';
import { fileInfo } from './change-copy-files.ts'; import { fileInfo } from './change-copy-files.ts';
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts'; import { compactCopy, convertibleCopy, isNewer, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
import { readSource, setCopySource } from './copy-source.ts';
let current: { let current: {
stop: AbortController; stop: AbortController;
@@ -92,6 +93,8 @@ export async function maintainCopy(
async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> { async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> {
const { id, operation, steamLocations } = request; const { id, operation, steamLocations } = request;
const record = await requireCopy(id); const record = await requireCopy(id);
if (operation === 'set-source') return setCopySource(record, request.sourcePath);
const root = await checkedRoot(record); const root = await checkedRoot(record);
const dataPath = await canonicalCopyPath(record.dataPath); const dataPath = await canonicalCopyPath(record.dataPath);
const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath); const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath);
@@ -0,0 +1,52 @@
import { isAbsolute, join } from 'node:path';
import { AppError } from '@shared/errors.ts';
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { canonicalCopyPath, copyPathContains, updateCopyRecord } from '../install/install-record.ts';
import { fileInfo } from './change-copy-files.ts';
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
if (!record.sourcePath) return null;
try {
return await inspectSource(record, record.sourcePath);
} catch (error) {
if (error instanceof AppError) return null;
throw error;
}
}
export async function setCopySource(record: InstallRecord, path: string | undefined): Promise<Copies> {
const source = await inspectSource(record, path);
return updateCopyRecord(record.id, (latest) => {
if (latest.copyPath !== record.copyPath || latest.dataPath !== record.dataPath) {
throw new AppError('maintenance_location');
}
return { ...latest, sourcePath: source.resolvedPath };
});
}
async function inspectSource(record: InstallRecord, path: string | undefined): Promise<GameFolderInspection> {
if (!path || !isAbsolute(path)) throw new AppError('maintenance_source_invalid');
const [game, copyPath, dataPath] = await Promise.all([
inspectGameFolder(path), canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath),
]);
const source = game.resolvedPath;
const overlapsCopy = copyPathContains(source, copyPath) || copyPathContains(copyPath, source);
if (overlapsCopy || copyPathContains(source, dataPath)) {
throw new AppError('maintenance_source_overlap');
}
if (game.missingFiles.length || !game.version || game.hasOfflineBackup || game.needsStockSource) {
throw new AppError('maintenance_source_invalid');
}
// Verify that the directory has game resources beyond the four files used for patching.
const [content, languages, missions] = await Promise.all([
fileInfo(join(source, 'content')),
fileInfo(join(source, 'lang.vromfs.bin')),
fileInfo(join(source, 'mis.vromfs.bin')),
]);
if (!content?.isDirectory() || !languages?.isFile() || !missions?.isFile()) {
throw new AppError('maintenance_source_invalid');
}
return { ...game, path: source };
}
@@ -7,6 +7,7 @@ import { zipSync } from 'fflate';
import { GAME_FILES } from '@wto/patcher'; import { GAME_FILES } from '@wto/patcher';
import { AppError } from '@shared/errors.ts'; import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts'; import type { InstallRecord } from '@shared/schemas/install.ts';
import { PORTABLE_UPDATE_LOG_FILENAME } from '../app-update/portable-update.ts';
import { getSettings } from '../config/settings-store.ts'; import { getSettings } from '../config/settings-store.ts';
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts'; import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts'; import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
@@ -58,6 +59,11 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name)); await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name));
} }
} }
await addFile(
files,
`launcher-logs/${PORTABLE_UPDATE_LOG_FILENAME}`,
join(userData, 'launcher-updates', PORTABLE_UPDATE_LOG_FILENAME),
);
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]); const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath; const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
if (dataPath) await addServerLogs(files, dataPath); if (dataPath) await addServerLogs(files, dataPath);
@@ -1,9 +1,9 @@
import { createReadStream, createWriteStream, type BigIntStats } from 'node:fs'; import type { BigIntStats, Dirent } from 'node:fs';
import { lstat, mkdir, readdir, rm, utimes } from 'node:fs/promises'; import { join, normalize, relative, sep } from 'node:path';
import { join, relative } from 'node:path';
import { Transform } from 'node:stream'; import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises'; import { pipeline } from 'node:stream/promises';
import { AppError } from '@shared/errors.ts'; import { AppError } from '@shared/errors.ts';
import { rawFs } from '../../util/raw-fs.ts';
import { linkVerifiedResource, sameResource } from './hardlink-files.ts'; import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
/** /**
@@ -12,14 +12,45 @@ import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
*/ */
/** /**
* Top-level folders of an installation that hold what the game produced while the player played * Top-level folders of an installation that hold player-generated data or user content from
* online, not the game itself: logs, the web content cache, replays, screenshots and the player's * playing online, not the stock client itself: logs, the web content cache, replays, screenshots,
* own missions. The offline copy does not take the online game's data (working rules 18); the * and user missions, skins and sights. The offline copy does not take the online game's data; the
* game creates these folders again when it needs them. * game creates these folders again when it needs them.
*/ */
export const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']); export const PLAYER_DATA_FOLDERS = new Set([
/** Top-level folders ignored when scanning a stock source, including any stray offline backup directory. */ '.game_logs',
const SKIPPED_SOURCE_FOLDERS = new Set([...PLAYER_DATA_FOLDERS, 'wtoffline']); 'cache',
'replays',
'screenshots',
'usermissions',
'userskins',
'usersights',
]);
/**
* Top-level folders ignored when scanning a stock source in addition to player data:
* official launcher/updater logs and obsolete files, the War Thunder CDK toolkit, and any stray
* offline backup directory.
*/
const SKIPPED_SOURCE_FOLDERS = new Set([
...PLAYER_DATA_FOLDERS,
'.gaijin_updater_logs',
'.launcher_log',
'.obsolete',
'.start_app_logs',
'warthundercdk',
'wtoffline',
]);
const LAUNCHER_EXECUTABLE_LOWER = 'wtoffline launcher.exe';
/** Whether a relative path starts with a top-level entry excluded from source scans. */
export function isInSkippedSourceFolder(relativePath: string): boolean {
const [topLevel = ''] = normalize(relativePath).split(sep, 1);
return SKIPPED_SOURCE_FOLDERS.has(topLevel.toLowerCase());
}
function isLauncherFolder(entries: readonly Dirent[]): boolean {
return entries.some((entry) => entry.isFile() && entry.name.toLowerCase() === LAUNCHER_EXECUTABLE_LOWER);
}
interface CopyEntry { interface CopyEntry {
readonly relativePath: string; readonly relativePath: string;
@@ -40,20 +71,26 @@ export interface CopyProgress {
/** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */ /** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */
export async function planCopy(source: string): Promise<CopyPlan> { export async function planCopy(source: string): Promise<CopyPlan> {
const fsPromises = rawFs().promises;
const files: CopyEntry[] = []; const files: CopyEntry[] = [];
const folders: string[] = []; const folders: string[] = [];
let totalBytes = 0; let totalBytes = 0;
const pending = [source]; const pending = [source];
while (pending.length) { while (pending.length) {
const folder = pending.pop()!; const folder = pending.pop()!;
for (const entry of await readdir(folder, { withFileTypes: true })) { const entries = await fsPromises.readdir(folder, { withFileTypes: true });
if (folder !== source) {
// Skip any WTOffline Launcher folder that was previously extracted inside the game directory.
if (isLauncherFolder(entries)) continue;
folders.push(relative(source, folder));
}
for (const entry of entries) {
const path = join(folder, entry.name); const path = join(folder, entry.name);
if (folder === source && SKIPPED_SOURCE_FOLDERS.has(entry.name.toLowerCase())) continue; if (folder === source && isInSkippedSourceFolder(entry.name)) continue;
if (entry.isDirectory()) { if (entry.isDirectory()) {
folders.push(relative(source, path));
pending.push(path); pending.push(path);
} else if (entry.isFile()) { } else if (entry.isFile()) {
const { size, mtimeMs } = await lstat(path); const { size, mtimeMs } = await fsPromises.lstat(path);
files.push({ relativePath: relative(source, path), bytes: size, modifiedAt: mtimeMs }); files.push({ relativePath: relative(source, path), bytes: size, modifiedAt: mtimeMs });
totalBytes += size; totalBytes += size;
} }
@@ -78,8 +115,10 @@ export async function copyPlannedFiles(
onProgress: (progress: CopyProgress) => void, onProgress: (progress: CopyProgress) => void,
hardlinks?: ReadonlyMap<string, BigIntStats>, hardlinks?: ReadonlyMap<string, BigIntStats>,
): Promise<void> { ): Promise<void> {
await mkdir(target, { recursive: true }); const fs = rawFs();
for (const folder of plan.folders) await mkdir(join(target, folder), { recursive: true }); const fsPromises = fs.promises;
await fsPromises.mkdir(target, { recursive: true });
for (const folder of plan.folders) await fsPromises.mkdir(join(target, folder), { recursive: true });
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined; const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
let next = 0; let next = 0;
let doneBytes = 0; let doneBytes = 0;
@@ -95,6 +134,8 @@ export async function copyPlannedFiles(
// caller cleaning up after an error never races a copy still writing. // caller cleaning up after an error never races a copy still writing.
const stop = new AbortController(); const stop = new AbortController();
const stopSignal = AbortSignal.any([signal, stop.signal]); const stopSignal = AbortSignal.any([signal, stop.signal]);
let firstError: unknown = null;
let hasError = false;
const copyNext = async (): Promise<void> => { const copyNext = async (): Promise<void> => {
try { try {
while (next < plan.files.length) { while (next < plan.files.length) {
@@ -109,30 +150,35 @@ export async function copyPlannedFiles(
doneBytes += file.bytes; doneBytes += file.bytes;
} else { } else {
await pipeline( await pipeline(
createReadStream(from), fs.createReadStream(from),
countBytes(), countBytes(),
// 'wx': fail instead of overwriting a file that is already there. // 'wx': fail instead of overwriting a file that is already there.
createWriteStream(to, { flags: 'wx' }), fs.createWriteStream(to, { flags: 'wx' }),
{ signal: stopSignal }, { signal: stopSignal },
); );
const modified = new Date(file.modifiedAt); const modified = new Date(file.modifiedAt);
await utimes(to, modified, modified); await fsPromises.utimes(to, modified, modified);
} }
doneFiles += 1; doneFiles += 1;
onProgress({ doneBytes, doneFiles }); onProgress({ doneBytes, doneFiles });
} }
} catch (error) { } catch (error) {
if (!hasError && !stop.signal.aborted && !signal.aborted) {
hasError = true;
firstError = error;
}
stop.abort(error); stop.abort(error);
throw error; throw error;
} }
}; };
const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext)); const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext));
if (hasError) throw firstError;
const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected'); const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');
if (failed) throw failed.reason; if (failed) throw failed.reason;
if (linkedTargets) { if (linkedTargets) {
for (const [path, stamp] of linkedTargets) { for (const [path, stamp] of linkedTargets) {
signal.throwIfAborted(); signal.throwIfAborted();
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed'); if (!sameResource(stamp, await fsPromises.lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
} }
} }
} }
@@ -142,9 +188,10 @@ export async function copyPlannedFiles(
* when the copy started, so everything in it came from the copy. * when the copy started, so everything in it came from the copy.
*/ */
export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise<void> { export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise<void> {
const fsPromises = rawFs().promises;
if (!targetExisted) { if (!targetExisted) {
await rm(target, { recursive: true, force: true }); await fsPromises.rm(target, { recursive: true, force: true });
return; return;
} }
for (const entry of await readdir(target)) await rm(join(target, entry), { recursive: true, force: true }); for (const entry of await fsPromises.readdir(target)) await fsPromises.rm(join(target, entry), { recursive: true, force: true });
} }
@@ -1,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);
@@ -1,6 +1,7 @@
import type { BigIntStats } from 'node:fs'; import type { BigIntStats } from 'node:fs';
import { access, mkdir } from 'node:fs/promises'; import { access, mkdir } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative } from 'node:path'; import { dirname, isAbsolute, join, relative } from 'node:path';
import { app } from 'electron';
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher'; import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts'; import { AppError } from '@shared/errors.ts';
import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts'; import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
@@ -140,6 +141,12 @@ async function inspectInstallation(request: InstallRequest) {
const [copyPath, dataPath, sourcePath] = await Promise.all([ const [copyPath, dataPath, sourcePath] = await Promise.all([
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder), canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
]); ]);
if (request.method === 'copy' && app.isPackaged) {
const launcherDir = await canonicalCopyPath(dirname(process.execPath));
if (copyPathContains(sourcePath, launcherDir)) {
throw new AppError('launcher_inside_source');
}
}
await requireAvailableCopy(request.id, copyPath, dataPath); await requireAvailableCopy(request.id, copyPath, dataPath);
const dataProblem = dataFolderProblem( const dataProblem = dataFolderProblem(
dataPath, dataPath,
@@ -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 {
@@ -62,6 +62,7 @@ export class ReleasePageLimitError extends Error {
} }
const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }; const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
const MAX_RELEASE_NOTES_CHARS = 64 * 1024;
const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() }); const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() });
const LauncherReleaseEntry = z.object({ const LauncherReleaseEntry = z.object({
draft: z.literal(false), draft: z.literal(false),
@@ -98,18 +99,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> {
@@ -248,7 +266,7 @@ function launcherRelease(entry: Record<string, unknown>, version: string, source
return { return {
source, source,
version, version,
notes: body?.trim().slice(0, 1600) ?? '', notes: body?.trim().slice(0, MAX_RELEASE_NOTES_CHARS) ?? '',
installer, installer,
manifest, manifest,
signature, signature,
@@ -17,6 +17,10 @@ export interface ResourcePaths {
readonly networkHookLibrary: string; readonly networkHookLibrary: string;
/** Multi-resolution Windows icon for the window and system tray. */ /** Multi-resolution Windows icon for the window and system tray. */
readonly appIcon: string; readonly appIcon: string;
/** Bundled example mod templates seeded into an empty mods folder on first use. */
readonly modTemplates: string;
/** Modular ground AI daScript sources injected into `game.vromfs.bin` when active. */
readonly groundAiScripts: string;
} }
export function resourcePaths(): ResourcePaths { export function resourcePaths(): ResourcePaths {
@@ -32,6 +36,8 @@ export function bundledResourcePaths(): ResourcePaths {
patches: join(process.resourcesPath, 'patches'), patches: join(process.resourcesPath, 'patches'),
networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'), networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'),
appIcon: join(process.resourcesPath, 'icon.ico'), appIcon: join(process.resourcesPath, 'icon.ico'),
modTemplates: join(process.resourcesPath, 'mod-templates'),
groundAiScripts: join(process.resourcesPath, 'game-ai', 'ground'),
}; };
} }
// 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 +46,8 @@ export function bundledResourcePaths(): ResourcePaths {
patches: join(repository, 'patches'), patches: join(repository, 'patches'),
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'), networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'), appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
modTemplates: join(repository, 'mod-dev-docs', 'templates'),
groundAiScripts: join(repository, 'game-ai', 'ground'),
}; };
} }
+23
View File
@@ -0,0 +1,23 @@
import * as nodeFs from 'node:fs';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
let cached: typeof nodeFs | null = null;
/**
* Return Node's unpatched fs module inside Electron.
*
* Electron patches `node:fs` to treat any `.asar` file anywhere on disk as a virtual archive
* directory, which breaks streaming reads, stats and recursive cleanup when copying or managing
* player folders that happen to contain an `.asar` file. Falls back to `node:fs` outside Electron.
*/
export function rawFs(): typeof nodeFs {
if (cached) return cached;
try {
cached = require('original-fs') as typeof nodeFs;
} catch {
cached = nodeFs;
}
return cached;
}
@@ -9,9 +9,12 @@ export interface BuildRequest {
readonly port: number; readonly port: number;
readonly patches: string; readonly patches: string;
readonly networkHookLibrary: string; readonly networkHookLibrary: string;
readonly groundAiScripts: string;
readonly 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' };
+85 -6
View File
@@ -1,14 +1,34 @@
import { readFileSync, realpathSync } from 'node:fs'; import { readFileSync, realpathSync } from 'node:fs';
import { relative } from 'node:path'; import { relative } from 'node:path';
import type { MessageEvent } from 'electron'; import type { MessageEvent } from 'electron';
import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCacheProblem, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher'; import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
import { multiVehiclePackIds } from '@wto/server'; import {
assertWritableCopy,
buildGameCopy,
computeModsBuildFingerprint,
copyPlayerDecalCache,
CORE_BUILD_PACKS,
GAME_PACK_FILE,
isGroundAiActive,
playerDecalCacheProblem,
prepareOptionalStockPacks,
readPlayerDecalIndexFiles,
readStockGameFiles,
syncExternalModFiles,
writeGameCopy,
type GameCopyBuild,
type GameCopyFile,
} from '@wto/patcher';
import { loadGroundAiTuning, multiVehiclePackIds } from '@wto/server';
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts'; import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
let prepared: { let prepared: {
readonly request: BuildRequest; readonly request: BuildRequest;
readonly files: readonly GameCopyFile[]; readonly files: readonly GameCopyFile[];
readonly decalCache: string | undefined; readonly decalCache: string | undefined;
readonly enabledMods: readonly DiscoveredMod[];
readonly optionalPacksInBuild: readonly ModdableClientPack[];
readonly fingerprint: string;
} | null = null; } | null = null;
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void { function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
@@ -31,17 +51,63 @@ function importedDecals(path: string | undefined): string | undefined {
return undefined; return undefined;
} }
function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly string[] | undefined): DiscoveredMod[] {
if (!modsDir || !enabledModIds || enabledModIds.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const ordered: DiscoveredMod[] = [];
for (const id of enabledModIds) {
const mod = byId.get(id);
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
ordered.push(mod);
}
return ordered;
}
function logModBuildSummary(result: GameCopyBuild): void {
if (result.gamePack) {
console.info(`[build] injected ${result.gamePack.modules.length} ground AI module(s) into ${result.gamePack.archiveFolder}`);
}
if (result.mods.enabledModIds.length === 0) return;
console.info(
`[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` +
`(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` +
`gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` +
`exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`,
);
for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) {
console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`);
}
}
function build(request: BuildRequest): void { function build(request: BuildRequest): void {
checkBuildLocation(request); checkBuildLocation(request);
const decalCache = importedDecals(request.decalCache); const decalCache = importedDecals(request.decalCache);
const decalIndexFiles = decalCache ? readPlayerDecalIndexFiles(decalCache) : undefined;
const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds);
const groundAiConfig = loadGroundAiTuning(request.dataPath, console.info, enabledMods);
const groundAiActive = isGroundAiActive(groundAiConfig);
const touchedSet = new Set<ModdableClientPack>(
touchedClientPacks(enabledMods).filter((pack) => !CORE_BUILD_PACKS.has(pack)),
);
if (groundAiActive) touchedSet.add(GAME_PACK_FILE);
const optionalPacksInBuild = [...touchedSet];
const extraStockPacks = optionalPacksInBuild.length > 0
? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild)
: undefined;
const result = buildGameCopy({ const result = buildGameCopy({
stock: readStockGameFiles(request.stockPath), stock: readStockGameFiles(request.stockPath),
patches: request.patches, patches: request.patches,
networkHookLibrary: readFileSync(request.networkHookLibrary), networkHookLibrary: readFileSync(request.networkHookLibrary),
port: request.port, port: request.port,
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info), multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info, enabledMods),
placeholderDecals: decalCache === undefined, placeholderDecals: decalCache === undefined,
...(decalIndexFiles ? { decalIndexFiles } : {}),
hookLogging: request.hookLogging, hookLogging: request.hookLogging,
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
...(extraStockPacks ? { extraStockPacks } : {}),
groundAi: { scriptsFolder: request.groundAiScripts, config: groundAiConfig },
}); });
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures]; const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
const accepted = new Set(request.acceptedUnavailable); const accepted = new Set(request.acceptedUnavailable);
@@ -50,7 +116,13 @@ function build(request: BuildRequest): void {
send({ kind: 'failed', error: 'launch_build_unavailable' }); send({ kind: 'failed', error: 'launch_build_unavailable' });
return; return;
} }
prepared = { request, files: result.files, decalCache }; logModBuildSummary(result);
const fingerprint = computeModsBuildFingerprint(
enabledMods,
request.port,
`${request.patches}|groundAi=${JSON.stringify(groundAiConfig)}`,
);
prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint };
send({ kind: 'prepared', total: prepared.files.length }); send({ kind: 'prepared', total: prepared.files.length });
} }
@@ -62,15 +134,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);
+10 -1
View File
@@ -22,6 +22,7 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
import { WizardMain } from './pages/install/WizardMain.tsx'; import { WizardMain } from './pages/install/WizardMain.tsx';
import { WizardSide } from './pages/install/WizardSide.tsx'; import { WizardSide } from './pages/install/WizardSide.tsx';
import { wizardBar } from './pages/install/wizard-bar.ts'; import { wizardBar } from './pages/install/wizard-bar.ts';
import { ModsPage } from './pages/mods/ModsPage.tsx';
import { TuningPage } from './pages/tuning/TuningPage.tsx'; import { TuningPage } from './pages/tuning/TuningPage.tsx';
import { SavesPage } from './pages/saves/SavesPage.tsx'; import { SavesPage } from './pages/saves/SavesPage.tsx';
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx'; import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
@@ -32,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';
@@ -195,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') {
@@ -0,0 +1,152 @@
import { createElement, Fragment, useMemo, type ReactNode } from 'react';
import { marked, type Token, type Tokens } from 'marked';
const SAFE_EXTERNAL_URL = /^https?:\/\//i;
const HTML_COMMENT = /^<!--[\s\S]*?-->$/;
function isSafeExternalUrl(href: string | undefined): href is string {
return typeof href === 'string' && SAFE_EXTERNAL_URL.test(href.trim());
}
function renderInline(tokens: readonly Token[], keyPrefix: string): ReactNode {
return tokens.map((token, index) => renderInlineToken(token, `${keyPrefix}-${index}`));
}
function renderInlineToken(token: Token, key: string): ReactNode {
switch (token.type) {
case 'text': {
const textToken = token as Tokens.Text;
if (textToken.tokens?.length) return <Fragment key={key}>{renderInline(textToken.tokens, key)}</Fragment>;
return <Fragment key={key}>{textToken.text}</Fragment>;
}
case 'escape':
return <Fragment key={key}>{(token as Tokens.Escape).text}</Fragment>;
case 'strong':
return <strong key={key}>{renderInline((token as Tokens.Strong).tokens, key)}</strong>;
case 'em':
return <em key={key}>{renderInline((token as Tokens.Em).tokens, key)}</em>;
case 'del':
return <del key={key}>{renderInline((token as Tokens.Del).tokens, key)}</del>;
case 'codespan':
return <code key={key}>{(token as Tokens.Codespan).text}</code>;
case 'br':
return <br key={key} />;
case 'link': {
const link = token as Tokens.Link;
const content = link.tokens.length ? renderInline(link.tokens, key) : link.text;
if (!isSafeExternalUrl(link.href)) return <Fragment key={key}>{content}</Fragment>;
return (
<a key={key} href={link.href} title={link.title ?? undefined} target="_blank" rel="noreferrer">
{content}
</a>
);
}
case 'image':
return <Fragment key={key}>{(token as Tokens.Image).text}</Fragment>;
case 'html': {
const raw = (token as Tokens.HTML).text.trim();
if (!raw || HTML_COMMENT.test(raw)) return null;
return <Fragment key={key}>{raw}</Fragment>;
}
default:
return 'raw' in token && typeof token.raw === 'string' ? <Fragment key={key}>{token.raw}</Fragment> : null;
}
}
function renderTable(table: Tokens.Table, key: string): ReactNode {
return (
<div key={key} className="markdown-table-wrap">
<table>
<thead>
<tr>
{table.header.map((cell, column) => (
<th key={`${key}-h-${column}`} style={cell.align ? { textAlign: cell.align } : undefined}>
{renderInline(cell.tokens, `${key}-h-${column}`)}
</th>
))}
</tr>
</thead>
<tbody>
{table.rows.map((row, rowIndex) => (
<tr key={`${key}-r-${rowIndex}`}>
{row.map((cell, column) => (
<td key={`${key}-r-${rowIndex}-${column}`} style={cell.align ? { textAlign: cell.align } : undefined}>
{renderInline(cell.tokens, `${key}-r-${rowIndex}-${column}`)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
}
function renderListItem(item: Tokens.ListItem, key: string): ReactNode {
return (
<li key={key}>
{item.task && <input type="checkbox" checked={Boolean(item.checked)} disabled readOnly className="markdown-task" />}
{renderBlocks(item.tokens, key)}
</li>
);
}
function renderBlock(token: Token, key: string): ReactNode {
switch (token.type) {
case 'space':
case 'def':
case 'checkbox':
return null;
case 'heading': {
const heading = token as Tokens.Heading;
const level = Math.min(6, Math.max(1, heading.depth));
return createElement(`h${level}`, { key }, renderInline(heading.tokens, key));
}
case 'paragraph':
return <p key={key}>{renderInline((token as Tokens.Paragraph).tokens, key)}</p>;
case 'text': {
const textToken = token as Tokens.Text;
if (textToken.tokens?.length) return <Fragment key={key}>{renderInline(textToken.tokens, key)}</Fragment>;
return <Fragment key={key}>{textToken.text}</Fragment>;
}
case 'blockquote':
return <blockquote key={key}>{renderBlocks((token as Tokens.Blockquote).tokens, key)}</blockquote>;
case 'list': {
const list = token as Tokens.List;
const items = list.items.map((item, index) => renderListItem(item, `${key}-i-${index}`));
if (list.ordered) {
return <ol key={key} start={typeof list.start === 'number' && list.start !== 1 ? list.start : undefined}>{items}</ol>;
}
return <ul key={key}>{items}</ul>;
}
case 'code':
return (
<pre key={key}>
<code>{(token as Tokens.Code).text}</code>
</pre>
);
case 'hr':
return <hr key={key} />;
case 'table':
return renderTable(token as Tokens.Table, key);
case 'html': {
const raw = (token as Tokens.HTML).text.trim();
if (!raw || HTML_COMMENT.test(raw)) return null;
return <p key={key}>{raw}</p>;
}
default:
return 'raw' in token && typeof token.raw === 'string' && token.raw.trim()
? <p key={key}>{token.raw}</p>
: null;
}
}
function renderBlocks(tokens: readonly Token[], keyPrefix: string): ReactNode {
return tokens.map((token, index) => renderBlock(token, `${keyPrefix}-${index}`));
}
/** Safe React renderer for GFM Markdown without injecting raw HTML. */
export function MarkdownContent({ markdown }: { readonly markdown: string }) {
const tokens = useMemo(() => marked.lexer(markdown, { gfm: true, breaks: false }), [markdown]);
return <div className="markdown-body">{renderBlocks(tokens, 'md')}</div>;
}
@@ -7,6 +7,7 @@
"home": "Home", "home": "Home",
"saves": "Saves", "saves": "Saves",
"tuning": "Tuning", "tuning": "Tuning",
"mods": "Mods",
"copies": "Clients", "copies": "Clients",
"settings": "Settings", "settings": "Settings",
"about": "About" "about": "About"
@@ -96,7 +97,7 @@
}, },
"decals": { "decals": {
"source": "Decal source", "source": "Decal source",
"hint": "Import the online game's cache/content folder. The client uses placeholder decals when no cache is available.", "hint": "Import the online game's cache/content (or cache) folder for cached decals and downloadable skins. Placeholder decals are used when no cache is available.",
"choose": "Choose decal cache…", "choose": "Choose decal cache…",
"useDefault": "Use placeholder decals", "useDefault": "Use placeholder decals",
"importing": "Importing decal cache", "importing": "Importing decal cache",
@@ -230,11 +231,18 @@
"missingFolder": "Folder missing", "missingFolder": "Folder missing",
"relocate": "Relocate…", "relocate": "Relocate…",
"relocateDialogTitle": "Select the moved client folder", "relocateDialogTitle": "Select the moved client folder",
"list": { "current": "Current", "select": "Set as current" }, "list": {
"current": "Current",
"select": "Set as current"
},
"none": "The offline edition is not installed yet.", "none": "The offline edition is not installed yet.",
"maintenance": { "maintenance": {
"update": "Update from online installation", "update": "Update from online installation",
"updateAction": "Update client", "updateAction": "Update client",
"setSource": "Set source…",
"changeSource": "Change source…",
"chooseSource": "Choose the online installation folder",
"sourceNotSet": "No online installation source is configured.",
"newVersion": "Version {{version}} is available from the installation source.", "newVersion": "Version {{version}} is available from the installation source.",
"updateKeepsSpaceSaving": "Version {{version}} is available. Updating continues sharing read-only resource archives with the source.", "updateKeepsSpaceSaving": "Version {{version}} is available. Updating continues sharing read-only resource archives with the source.",
"updateDetaches": "Version {{version}} is available. Because the client and source are on different volumes, updating copies shared resources into independent files and requires additional space.", "updateDetaches": "Version {{version}} is available. Because the client and source are on different volumes, updating copies shared resources into independent files and requires additional space.",
@@ -267,6 +275,7 @@
}, },
"result": { "result": {
"confirm-steam": "Steam locations confirmed.", "confirm-steam": "Steam locations confirmed.",
"set-source": "Online installation source saved.",
"check": "Patch check complete.", "check": "Patch check complete.",
"repair": "Original files restored.", "repair": "Original files restored.",
"update": "Client updated.", "update": "Client updated.",
@@ -341,8 +350,7 @@
"country": "Country", "country": "Country",
"type": "Vehicle type", "type": "Vehicle type",
"actions": "Bulk actions", "actions": "Bulk actions",
"research": "Research all", "purchase": "Research and buy all",
"purchase": "Grant regular vehicles",
"equipment": "Unlock modifications", "equipment": "Unlock modifications",
"empty": "This client has no eligible research branches.", "empty": "This client has no eligible research branches.",
"rank": "Rank {{rank}}", "rank": "Rank {{rank}}",
@@ -436,7 +444,8 @@
"premiumDays": "Premium account days", "premiumDays": "Premium account days",
"avatar": "Avatar", "avatar": "Avatar",
"avatarUnavailable": "Avatar unavailable", "avatarUnavailable": "Avatar unavailable",
"level": "Account level",␍ "apply": "Save changes", "level": "Account level",
"apply": "Save changes",
"saved": "Changes saved.", "saved": "Changes saved.",
"noBattles": "The save has no recorded battles.", "noBattles": "The save has no recorded battles.",
"win": "Victory", "win": "Victory",
@@ -463,6 +472,7 @@
"tankBotRespawns": "AI tank respawns", "tankBotRespawns": "AI tank respawns",
"airBotRespawns": "AI aircraft respawns", "airBotRespawns": "AI aircraft respawns",
"strikeUcavSpawnScore": "Strike UCAV spawn points", "strikeUcavSpawnScore": "Strike UCAV spawn points",
"nuclearEscalationStrategicBombers": "Nuclear Escalation stage-3 strategic bombers (B-52H / Tu-95M)",
"silverLions": "Starting Silver Lions", "silverLions": "Starting Silver Lions",
"goldenEagles": "Starting Golden Eagles", "goldenEagles": "Starting Golden Eagles",
"preferLineSuccessor": "Prefer the next vehicle in the line", "preferLineSuccessor": "Prefer the next vehicle in the line",
@@ -494,7 +504,7 @@
"appUpdates": "Launcher updates", "appUpdates": "Launcher updates",
"appUpdatesToggle": "Check for launcher updates at start", "appUpdatesToggle": "Check for launcher updates at start",
"patchPacks": "Adaptation pack updates", "patchPacks": "Adaptation pack updates",
"patchPacksHint": "After a game update, the patches for the new version are released on GitHub as an adaptation pack.", "patchPacksHint": "After a game update, patches for the new version are released as an adaptation pack.",
"updateMirror": "Update mirror repository", "updateMirror": "Update mirror repository",
"updateMirrorHint": "Enter an HTTPS mirror with a GitHub-compatible releases list. It is used if the primary source is unreachable. Leave blank to disable it.", "updateMirrorHint": "Enter an HTTPS mirror with a GitHub-compatible releases list. It is used if the primary source is unreachable. Leave blank to disable it.",
"updateMirrorInvalid": "Enter a valid HTTPS repository address or leave the field blank.", "updateMirrorInvalid": "Enter a valid HTTPS repository address or leave the field blank.",
@@ -629,6 +639,9 @@
"download": "Download update", "download": "Download update",
"install": "Quit and install", "install": "Quit and install",
"installing": "Opening the installer…", "installing": "Opening the installer…",
"viewNotes": "Release notes",
"notesTitle": "Release notes — v{{version}}",
"closeNotes": "Close",
"errors": { "errors": {
"network": "The update source could not be reached.", "network": "The update source could not be reached.",
"page_limit": "Could not confirm whether a newer version is available.", "page_limit": "Could not confirm whether a newer version is available.",
@@ -639,6 +652,11 @@
}, },
"statement": "Project information", "statement": "Project information",
"statementBody": "WTOffline is a noncommercial hobby project independent of Gaijin. Running it requires your own War Thunder base game files.", "statementBody": "WTOffline is a noncommercial hobby project independent of Gaijin. Running it requires your own War Thunder base game files.",
"homepage": {
"title": "Project homepage",
"hint": "Project overview, release catalog, and community links.",
"open": "Open homepage"
},
"community": { "community": {
"discord": "Discord", "discord": "Discord",
"discordHint": "Development discussion, general chat, troubleshooting, and bug reports.", "discordHint": "Development discussion, general chat, troubleshooting, and bug reports.",
@@ -666,6 +684,7 @@
"J-Ground arcade and realistic": "Ground battles (arcade, realistic)", "J-Ground arcade and realistic": "Ground battles (arcade, realistic)",
"J-Air arcade and realistic": "Air battles (arcade, realistic)", "J-Air arcade and realistic": "Air battles (arcade, realistic)",
"J-Naval arcade and realistic": "Naval battles (arcade, realistic)", "J-Naval arcade and realistic": "Naval battles (arcade, realistic)",
"E-Crew skills in battle": "Crew skills and qualifications in battle",
"J-Sub-modes": "Additional modes (such as night battles)", "J-Sub-modes": "Additional modes (such as night battles)",
"K-AI opponents and teammates": "AI opponents and allies", "K-AI opponents and teammates": "AI opponents and allies",
"K-Spawn score and respawns": "Spawn points and respawning", "K-Spawn score and respawns": "Spawn points and respawning",
@@ -679,6 +698,96 @@
"L-Debriefing": "Battle results", "L-Debriefing": "Battle results",
"L-Battle awards": "Battle awards" "L-Battle awards": "Battle awards"
}, },
"mods": {
"sections": {
"list": "Mod list",
"presets": "Presets & repository"
},
"loading": "Loading mods…",
"noCopy": "Install or select an offline client first to configure its mods.",
"enabledSummary": "{{enabled}} / {{total}} enabled",
"experimentalChip": "Experimental",
"experimentalTitle": "Experimental mod API notice:",
"experimentalBody": "WTOffline is in early development (API {{api}}). Server script hooks, internal data structures, and declarative exe patch contracts may change at any time without backwards compatibility; only enable mods from trusted sources.",
"readOnlyNotice": "Mod toggles, load order, and presets are read-only while the game, local server, or maintenance is running.",
"searchPlaceholder": "Filter by mod name, ID, or author…",
"autoSort": "Auto-sort by dependencies",
"autoSorted": "Reordered mods based on dependencies and load-order hints.",
"refresh": "Refresh",
"openFolder": "Open mods folder",
"openDocs": "Mod docs",
"discoveryErrorsTitle": "{{count}} mod folder(s) could not be loaded:",
"blockingIssuesTitle": "{{count}} blocking mod error(s) prevent launching:",
"issuesTitle": "{{count}} mod notice(s) or overlap(s):",
"severity": {
"error": "Error",
"warning": "Warning",
"info": "Info"
},
"emptyTitle": "No mods found in the global mods folder yet.",
"emptyHint": "Place mod folders containing mod.jsonc into {{path}}, then click Refresh. Standalone skins, sights, and user missions continue to work directly via the game's native UserSkins / UserSights / UserMissions folders.",
"noSearchMatch": "No mods match the current search filter.",
"loadOrderHint": "Load order: lower items load later and take higher priority (drag or use arrows)",
"moveUp": "Move up",
"moveDown": "Move down",
"showDetails": "Details",
"hideDetails": "Hide",
"errorCount": "{{count}} error",
"warnCount": "{{count}} warn",
"badges": {
"data": "Data / Assets",
"gui": "GUI Patch",
"script": "Server Script",
"exe": "Exe Patch"
},
"details": {
"folder": "Folder",
"gameVersions": "Declared game versions",
"requires": "Requires",
"conflicts": "Conflicts",
"tuning": "Server tuning overlays: {{count}}",
"serverScript": "Executable server JS/TS script",
"packOps": "Client pack operations: {{count}}",
"addon": "3D model / texture addon: {{count}} file(s)",
"guiPatches": "GUI script patches: {{count}}",
"exePatches": "Declarative exe patches: {{count}}",
"companionFiles": "Companion files: {{count}}",
"configBlk": "Includes config.blk patch"
},
"presets": {
"heading": "Mod presets (saved per client)",
"description": "Save the current mod toggles and load order as named presets for quick switching or JSON export/import.",
"quickSwitch": "Switch mod preset",
"customOption": "Custom active selection",
"namePlaceholder": "New preset name, e.g. Modern Vehicles",
"saveCurrent": "Save preset",
"import": "Import preset…",
"empty": "No presets saved for this client yet.",
"activeTag": "Active",
"summary": "{{count}} enabled / {{total}} tracked",
"apply": "Apply",
"overwrite": "Update",
"export": "Export",
"delete": "Delete",
"saved": "Saved preset \"{{name}}\".",
"applied": "Applied preset \"{{name}}\".",
"updated": "Updated preset \"{{name}}\" with current setup.",
"exported": "Exported preset to: {{path}}",
"imported": "Imported mod preset."
},
"repo": {
"heading": "Global mods repository",
"description": "All clients share one mod folder (large 3D model and texture addons mount across drives via NTFS Junctions with zero copying), while each client keeps its own toggles, load order, and presets.",
"pathLabel": "Repository folder",
"defaultNote": "Using launcher default mods folder",
"customNote": "Using custom mods folder (can live on a larger drive or the same drive as your client)",
"changeFolder": "Change folder…",
"resetDefault": "Reset to default",
"pickTitle": "Select global mods repository folder",
"updated": "Updated global mods repository folder.",
"resetDone": "Reset to default mods repository folder."
}
},
"errors": { "errors": {
"app_update_unavailable": "There is no launcher update available to install.", "app_update_unavailable": "There is no launcher update available to install.",
"app_update_busy": "A launcher update operation is already in progress.", "app_update_busy": "A launcher update operation is already in progress.",
@@ -702,14 +811,21 @@
"save_avatar_invalid": "Select an avatar available in this client.", "save_avatar_invalid": "Select an avatar available in this client.",
"save_level_invalid": "Enter a level supported by this client.", "save_level_invalid": "Enter a level supported by this client.",
"tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.", "tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.",
"mods_read_only": "Mods cannot be changed while the game, local server, or maintenance is running.",
"mods_write_failed": "The mod configuration could not be saved. See the launcher log.",
"mods_preset_invalid": "The selected file is not a valid WTOffline mod preset.",
"mods_blocking_issues": "Enabled mods have missing dependencies or conflicts. Resolve them on the Mods page before launching.",
"mods_folder_invalid": "The selected global mods folder is invalid or not writable.",
"copy_not_found": "The selected client is no longer available.", "copy_not_found": "The selected client is no longer available.",
"copies_write_failed": "The client registry could not be saved.", "copies_write_failed": "The client registry could not be saved.",
"copy_location_in_use": "The client or data location overlaps an existing client.", "copy_location_in_use": "The client or data location overlaps an existing client.",
"decal_source_invalid": "The selected folder does not contain a usable decal cache.", "decal_source_invalid": "The selected folder does not contain a usable decal cache. Log into the online hangar once to populate it, then choose cache/content (or cache).",
"decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.", "decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.",
"maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.", "maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.",
"maintenance_location": "The operation would affect files outside the registered client or data folder.", "maintenance_location": "The operation would affect files outside the registered client or data folder.",
"maintenance_no_update": "A newer version is unavailable at the installation source.", "maintenance_no_update": "A newer version is unavailable at the installation source.",
"maintenance_source_invalid": "Choose a complete online game installation folder.",
"maintenance_source_overlap": "The online installation source must be separate from the offline client and its data folder.",
"maintenance_cancelled": "The client update was cancelled.", "maintenance_cancelled": "The client update was cancelled.",
"maintenance_failed": "Client maintenance failed. See the launcher log.", "maintenance_failed": "Client maintenance failed. See the launcher log.",
"maintenance_source_changed": "The installation source changed during the update. Retry once its update is complete.", "maintenance_source_changed": "The installation source changed during the update. Retry once its update is complete.",
@@ -745,6 +861,7 @@
"essential_patches_unavailable": "Patches required by the offline edition do not apply to this game version. Installation is not possible: {{patches}}", "essential_patches_unavailable": "Patches required by the offline edition do not apply to this game version. Installation is not possible: {{patches}}",
"missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.", "missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.",
"patch_check_failed": "An error occurred while checking patches.", "patch_check_failed": "An error occurred while checking patches.",
"launcher_inside_source": "WTOffline Launcher is currently inside the selected War Thunder folder. Move the launcher to a separate folder outside the game directory, then retry.",
"copy_failed": "Copying the game files failed. The copied files have been deleted.", "copy_failed": "Copying the game files failed. The copied files have been deleted.",
"hardlink_unavailable": "Space-saving copying requires the destination and source to be on the same volume, and converting an existing client also requires matching versions.", "hardlink_unavailable": "Space-saving copying requires the destination and source to be on the same volume, and converting an existing client also requires matching versions.",
"hardlink_no_match": "No matching read-only resource archives were found, or their contents differ from the source.", "hardlink_no_match": "No matching read-only resource archives were found, or their contents differ from the source.",
@@ -7,6 +7,7 @@
"home": "首页", "home": "首页",
"saves": "存档", "saves": "存档",
"tuning": "数值", "tuning": "数值",
"mods": "模组",
"copies": "客户端", "copies": "客户端",
"settings": "设置", "settings": "设置",
"about": "关于" "about": "关于"
@@ -96,7 +97,7 @@
}, },
"decals": { "decals": {
"source": "贴花来源", "source": "贴花来源",
"hint": "可导入在线版游戏的 cache/content。未导入时使用占位贴花。", "hint": "可导入在线版游戏的 cache/content(或 cache),同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。",
"choose": "选择贴花缓存…", "choose": "选择贴花缓存…",
"useDefault": "使用占位贴花", "useDefault": "使用占位贴花",
"importing": "正在导入贴花缓存", "importing": "正在导入贴花缓存",
@@ -230,11 +231,18 @@
"missingFolder": "目录不存在", "missingFolder": "目录不存在",
"relocate": "重新定位…", "relocate": "重新定位…",
"relocateDialogTitle": "选择挪动后的客户端文件夹", "relocateDialogTitle": "选择挪动后的客户端文件夹",
"list": { "current": "当前", "select": "设为当前" }, "list": {
"current": "当前",
"select": "设为当前"
},
"none": "尚未安装离线版。", "none": "尚未安装离线版。",
"maintenance": { "maintenance": {
"update": "从在线版更新", "update": "从在线版更新",
"updateAction": "更新客户端", "updateAction": "更新客户端",
"setSource": "设置来源…",
"changeSource": "更换来源…",
"chooseSource": "选择在线版安装目录",
"sourceNotSet": "尚未设置在线版安装来源。",
"newVersion": "安装来源已更新至 {{version}}。", "newVersion": "安装来源已更新至 {{version}}。",
"updateKeepsSpaceSaving": "安装来源中有新版本 {{version}}。更新时会继续与原版共用只读资源包。", "updateKeepsSpaceSaving": "安装来源中有新版本 {{version}}。更新时会继续与原版共用只读资源包。",
"updateDetaches": "安装来源中有新版本 {{version}}。当前与安装来源不在同一磁盘卷,更新会把共享资源复制为独立文件,需要额外空间。", "updateDetaches": "安装来源中有新版本 {{version}}。当前与安装来源不在同一磁盘卷,更新会把共享资源复制为独立文件,需要额外空间。",
@@ -267,6 +275,7 @@
}, },
"result": { "result": {
"confirm-steam": "已确认 Steam 目录。", "confirm-steam": "已确认 Steam 目录。",
"set-source": "在线版安装来源已保存。",
"check": "补丁检查已完成。", "check": "补丁检查已完成。",
"repair": "原版文件已还原。", "repair": "原版文件已还原。",
"update": "客户端已更新。", "update": "客户端已更新。",
@@ -341,8 +350,7 @@
"country": "国家", "country": "国家",
"type": "兵种", "type": "兵种",
"actions": "批量操作", "actions": "批量操作",
"research": "全部研发", "purchase": "全部研发并购买",
"purchase": "获得常规载具",
"equipment": "解锁改装件", "equipment": "解锁改装件",
"empty": "此客户端没有可编辑的研发分支。", "empty": "此客户端没有可编辑的研发分支。",
"rank": "等级 {{rank}}", "rank": "等级 {{rank}}",
@@ -436,7 +444,8 @@
"premiumDays": "高级账户剩余天数", "premiumDays": "高级账户剩余天数",
"avatar": "头像", "avatar": "头像",
"avatarUnavailable": "头像不可用", "avatarUnavailable": "头像不可用",
"level": "账号等级",␍ "apply": "保存更改", "level": "账号等级",
"apply": "保存更改",
"saved": "更改已保存。", "saved": "更改已保存。",
"noBattles": "此存档没有对局记录。", "noBattles": "此存档没有对局记录。",
"win": "胜利", "win": "胜利",
@@ -463,6 +472,7 @@
"tankBotRespawns": "AI 坦克重生次数", "tankBotRespawns": "AI 坦克重生次数",
"airBotRespawns": "AI 飞机重生次数", "airBotRespawns": "AI 飞机重生次数",
"strikeUcavSpawnScore": "打击无人机所需出生点数", "strikeUcavSpawnScore": "打击无人机所需出生点数",
"nuclearEscalationStrategicBombers": "核战冲突启用第 3 阶段战略核轰炸机(B-52H / Tu-95M)",
"silverLions": "初始银狮", "silverLions": "初始银狮",
"goldenEagles": "初始金鹰", "goldenEagles": "初始金鹰",
"preferLineSuccessor": "优先研发同系载具", "preferLineSuccessor": "优先研发同系载具",
@@ -494,7 +504,7 @@
"appUpdates": "启动器本体更新", "appUpdates": "启动器本体更新",
"appUpdatesToggle": "启动时检查本体更新", "appUpdatesToggle": "启动时检查本体更新",
"patchPacks": "适配包更新", "patchPacks": "适配包更新",
"patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布在 GitHub 上。", "patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布。",
"updateMirror": "备用更新仓库", "updateMirror": "备用更新仓库",
"updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。", "updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。",
"updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。", "updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。",
@@ -629,6 +639,9 @@
"download": "下载更新", "download": "下载更新",
"install": "退出并安装", "install": "退出并安装",
"installing": "正在打开安装包…", "installing": "正在打开安装包…",
"viewNotes": "查看更新说明",
"notesTitle": "版本 {{version}} 更新说明",
"closeNotes": "关闭",
"errors": { "errors": {
"network": "暂时无法访问更新源。", "network": "暂时无法访问更新源。",
"page_limit": "无法确认是否有新版本。", "page_limit": "无法确认是否有新版本。",
@@ -639,6 +652,11 @@
}, },
"statement": "项目信息", "statement": "项目信息",
"statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。", "statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。",
"homepage": {
"title": "项目主页",
"hint": "查看项目介绍、全部版本与社区入口。",
"open": "打开主页"
},
"community": { "community": {
"discord": "Discord", "discord": "Discord",
"discordHint": "开发讨论、日常交流、使用求助与问题反馈。", "discordHint": "开发讨论、日常交流、使用求助与问题反馈。",
@@ -666,6 +684,7 @@
"J-Ground arcade and realistic": "陆战(街机、历史)", "J-Ground arcade and realistic": "陆战(街机、历史)",
"J-Air arcade and realistic": "空战(街机、历史)", "J-Air arcade and realistic": "空战(街机、历史)",
"J-Naval arcade and realistic": "海战(街机、历史)", "J-Naval arcade and realistic": "海战(街机、历史)",
"E-Crew skills in battle": "战局乘员技能与资格",
"J-Sub-modes": "附加模式(如夜战)", "J-Sub-modes": "附加模式(如夜战)",
"K-AI opponents and teammates": "AI 对手与队友", "K-AI opponents and teammates": "AI 对手与队友",
"K-Spawn score and respawns": "出生点数与重生", "K-Spawn score and respawns": "出生点数与重生",
@@ -679,6 +698,96 @@
"L-Debriefing": "战后结算", "L-Debriefing": "战后结算",
"L-Battle awards": "战斗嘉奖" "L-Battle awards": "战斗嘉奖"
}, },
"mods": {
"sections": {
"list": "模组列表",
"presets": "预设与仓库"
},
"loading": "正在读取模组信息…",
"noCopy": "请先安装或选择一个离线客户端,再为它配置模组。",
"enabledSummary": "已启用 {{enabled}} / {{total}}",
"experimentalChip": "实验功能",
"experimentalTitle": "实验期模组接口提示:",
"experimentalBody": "离线版当前处于极初期开发阶段(API {{api}})。服务端脚本钩子、内部数据结构及声明式 exe 补丁契约随时可能随本体更新变动且不保证向下兼容;请仅启用来源可信的模组。",
"readOnlyNotice": "游戏、本地服务器或维护任务运行期间,模组开关、排序与预设为只读。",
"searchPlaceholder": "搜索模组名称、ID 或作者…",
"autoSort": "按依赖自动排序",
"autoSorted": "已按前置与排序建议重新排列模组顺序。",
"refresh": "刷新",
"openFolder": "打开模组目录",
"openDocs": "开发文档",
"discoveryErrorsTitle": "有 {{count}} 个模组目录读取失败:",
"blockingIssuesTitle": "存在 {{count}} 项阻塞性模组错误(处理前无法启动):",
"issuesTitle": "检测到 {{count}} 项模组提示或冲突:",
"severity": {
"error": "错误",
"warning": "警告",
"info": "提示"
},
"emptyTitle": "当前模组目录里还没有模组。",
"emptyHint": "将包含 mod.jsonc 的模组文件夹放入 {{path}},点击「刷新」即可识别。独立涂装、瞄具与单人任务继续沿用游戏原生的 UserSkins / UserSights / UserMissions 目录即可。",
"noSearchMatch": "没有匹配当前搜索条件的模组。",
"loadOrderHint": "加载顺序:越靠后优先级越高(可拖动或使用上下按钮调整)",
"moveUp": "上移",
"moveDown": "下移",
"showDetails": "详情",
"hideDetails": "收起",
"errorCount": "{{count}} 错误",
"warnCount": "{{count}} 警告",
"badges": {
"data": "数据/资源",
"gui": "界面补丁",
"script": "服务端脚本",
"exe": "二进制补丁"
},
"details": {
"folder": "目录",
"gameVersions": "声明适配版本",
"requires": "前置依赖",
"conflicts": "已知互斥",
"tuning": "服务端数值叠加:{{count}} 份",
"serverScript": "含可执行服务端 JS/TS 脚本",
"packOps": "客户端数据包操作:{{count}} 项",
"addon": "独立 3D 模型/贴图扩展包:{{count}} 个文件",
"guiPatches": "界面脚本补丁:{{count}} 项",
"exePatches": "声明式 exe 补丁:{{count}} 项",
"companionFiles": "附带外置文件:{{count}} 个",
"configBlk": "含 config.blk 增量补丁"
},
"presets": {
"heading": "模组序列预设(当前客户端独立保存)",
"description": "将当前的启用开关与加载顺序保存为预设,方便在不同玩法配置间一键切换,或导出 JSON 分享给其他玩家。",
"quickSwitch": "快速切换模组预设",
"customOption": "当前自定义配置",
"namePlaceholder": "输入新预设名称,例如:现代载具包",
"saveCurrent": "保存为预设",
"import": "导入预设…",
"empty": "当前客户端尚未保存任何模组预设。",
"activeTag": "当前使用",
"summary": "启用 {{count}} / 共 {{total}} 个模组",
"apply": "应用",
"overwrite": "覆盖更新",
"export": "导出",
"delete": "删除",
"saved": "已保存预设「{{name}}」。",
"applied": "已切换至预设「{{name}}」。",
"updated": "已用当前配置覆盖预设「{{name}}」。",
"exported": "预设已导出到:{{path}}",
"imported": "已导入模组预设。"
},
"repo": {
"heading": "全局模组仓库位置",
"description": "所有客户端共享同一份模组文件仓库(大体积 3D 模型与贴图包通过跨盘目录联接点零拷贝挂载,不重复占用磁盘);每个客户端独立保存自己的开关、排序和预设。",
"pathLabel": "当前仓库目录",
"defaultNote": "使用启动器默认模组目录",
"customNote": "使用自定义模组目录(可放在大容量硬盘或游戏同盘)",
"changeFolder": "更改目录…",
"resetDefault": "恢复默认目录",
"pickTitle": "选择全局模组仓库目录",
"updated": "已更新全局模组仓库目录。",
"resetDone": "已恢复为默认模组仓库目录。"
}
},
"errors": { "errors": {
"app_update_unavailable": "当前没有可安装的本体更新。", "app_update_unavailable": "当前没有可安装的本体更新。",
"app_update_busy": "本体更新操作正在进行。", "app_update_busy": "本体更新操作正在进行。",
@@ -702,14 +811,21 @@
"save_avatar_invalid": "请选择此客户端中可用的头像。", "save_avatar_invalid": "请选择此客户端中可用的头像。",
"save_level_invalid": "请输入此客户端支持的账号等级。", "save_level_invalid": "请输入此客户端支持的账号等级。",
"tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。", "tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。",
"mods_read_only": "游戏、本地服务器或维护任务运行期间无法修改模组配置。",
"mods_write_failed": "无法保存模组配置,请查看启动器日志。",
"mods_preset_invalid": "所选文件不是有效的 WTOffline 模组预设。",
"mods_blocking_issues": "当前启用的模组存在缺失前置或互斥冲突,请先在「模组」页面处理后再启动。",
"mods_folder_invalid": "所选全局模组目录无效或无法写入。",
"copy_not_found": "所选客户端已不可用。", "copy_not_found": "所选客户端已不可用。",
"copies_write_failed": "无法保存客户端记录。", "copies_write_failed": "无法保存客户端记录。",
"copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。", "copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。",
"decal_source_invalid": "选定的目录缺少有效的贴花缓存。", "decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版目录中的 cache/content(或 cache)。",
"decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。", "decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。",
"maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。", "maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。",
"maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。", "maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。",
"maintenance_no_update": "安装来源没有可用的新版本。", "maintenance_no_update": "安装来源没有可用的新版本。",
"maintenance_source_invalid": "请选择完整的在线版游戏安装目录。",
"maintenance_source_overlap": "在线版安装来源必须与离线客户端和数据目录分开。",
"maintenance_cancelled": "客户端更新已取消。", "maintenance_cancelled": "客户端更新已取消。",
"maintenance_failed": "客户端维护失败。请查看启动器日志。", "maintenance_failed": "客户端维护失败。请查看启动器日志。",
"maintenance_source_changed": "安装来源在更新过程中发生变化。请在在线版更新完成后重试。", "maintenance_source_changed": "安装来源在更新过程中发生变化。请在在线版更新完成后重试。",
@@ -745,6 +861,7 @@
"essential_patches_unavailable": "此游戏版本缺少离线版运行所必需的补丁,无法安装:{{patches}}", "essential_patches_unavailable": "此游戏版本缺少离线版运行所必需的补丁,无法安装:{{patches}}",
"missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。", "missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。",
"patch_check_failed": "检查补丁时出错。", "patch_check_failed": "检查补丁时出错。",
"launcher_inside_source": "启动器当前位于所选的战争雷霆游戏目录内。请先把启动器移动到游戏目录之外的独立文件夹,然后再试。",
"copy_failed": "复制游戏文件失败,已复制的文件已删除。", "copy_failed": "复制游戏文件失败,已复制的文件已删除。",
"hardlink_unavailable": "省空间复制要求目标与原版位于同一磁盘卷,转换已有客户端还要求版本一致。", "hardlink_unavailable": "省空间复制要求目标与原版位于同一磁盘卷,转换已有客户端还要求版本一致。",
"hardlink_no_match": "未找到可共用的只读资源包,或文件内容与原版不一致。", "hardlink_no_match": "未找到可共用的只读资源包,或文件内容与原版不一致。",
@@ -7,6 +7,7 @@ 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'; const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
interface AboutPageProps { interface AboutPageProps {
@@ -37,6 +38,7 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
<PatchPackSection state={patchPack} /> <PatchPackSection state={patchPack} />
</div> </div>
<div className="about-column"> <div className="about-column">
<HomepageSection />
<CommunitySection /> <CommunitySection />
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} /> <FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
<section className="about-card"> <section className="about-card">
@@ -49,6 +51,23 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
); );
} }
function HomepageSection() {
const { t } = useTranslation();
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.homepage.title')}</h3>
<div className="about-card-actions">
<a className="button" href={HOMEPAGE_URL} target="_blank" rel="noreferrer">
{t('about.homepage.open')}
</a>
</div>
</div>
<p className="about-card-meta">{t('about.homepage.hint')}</p>
</section>
);
}
function CommunitySection() { function CommunitySection() {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
@@ -1,13 +1,19 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx'; import { Notice } from '../../components/Notice.tsx';
import { ProgressBar } from '../../components/ProgressBar.tsx'; import { ProgressBar } from '../../components/ProgressBar.tsx';
import { formatBytes } from '../../format.ts'; import { formatBytes } from '../../format.ts';
import type { AppUpdateState } from '../../shell/useAppUpdate.ts'; import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
import { ReleaseNotesModal } from './ReleaseNotesModal.tsx';
export function AppUpdateSection({ state }: { readonly state: AppUpdateState }) { export function AppUpdateSection({ state }: { readonly state: AppUpdateState }) {
const { t } = useTranslation(); const { t } = useTranslation();
const [notesOpen, setNotesOpen] = useState(false);
if (!state.supported) return null; if (!state.supported) return null;
const { check, busy, progress } = state; const { check, busy, progress } = state;
const available = check?.status === 'available' && busy !== 'checking' ? check : null;
const notes = available?.release.notes.trim() ?? '';
return ( return (
<section className="about-card"> <section className="about-card">
<div className="about-card-head"> <div className="about-card-head">
@@ -21,30 +27,46 @@ export function AppUpdateSection({ state }: { readonly state: AppUpdateState })
<p className="about-card-meta">{t('about.update.check')}</p> <p className="about-card-meta">{t('about.update.check')}</p>
{check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>} {check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>}
{check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>} {check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
{check?.status === 'available' && busy !== 'checking' && ( {available && (
<Notice tone="info"> <Notice tone="info">
<p>{t('about.update.available', { version: check.release.version, size: formatBytes(check.release.size) })}</p> <p>{t('about.update.available', { version: available.release.version, size: formatBytes(available.release.size) })}</p>
{check.release.notes && <p className="small update-notes">{check.release.notes}</p>} {busy === 'downloading' && (
{busy === 'downloading' ? (
<> <>
<p>{t('about.update.downloading')}</p> <p>{t('about.update.downloading')}</p>
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} /> <ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
</> </>
) : ( )}
<button {(busy !== 'downloading' || notes) && (
type="button" <div className="update-actions">
className="button button-primary" {busy !== 'downloading' && (
disabled={busy !== null} <button
onClick={() => { type="button"
if (check.ready) state.install(check.release.version); className="button button-primary"
else state.download(check.release.version); disabled={busy !== null}
}} onClick={() => {
> if (available.ready) state.install(available.release.version);
{t(busy === 'installing' ? 'about.update.installing' : check.ready ? 'about.update.install' : 'about.update.download')} else state.download(available.release.version);
</button> }}
>
{t(busy === 'installing' ? 'about.update.installing' : available.ready ? 'about.update.install' : 'about.update.download')}
</button>
)}
{notes && (
<button type="button" className="button button-compact" onClick={() => setNotesOpen(true)}>
{t('about.update.viewNotes')}
</button>
)}
</div>
)} )}
</Notice> </Notice>
)} )}
{notesOpen && available && notes && (
<ReleaseNotesModal
version={available.release.version}
notes={notes}
onClose={() => setNotesOpen(false)}
/>
)}
</section> </section>
); );
} }
@@ -0,0 +1,57 @@
import { useEffect, useId } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import { MarkdownContent } from '../../components/MarkdownContent.tsx';
interface ReleaseNotesModalProps {
readonly version: string;
readonly notes: string;
readonly onClose: () => void;
}
/** Standalone dialog displaying rendered Markdown release notes for an available launcher update. */
export function ReleaseNotesModal({ version, notes, onClose }: ReleaseNotesModalProps) {
const { t } = useTranslation();
const titleId = useId();
useEffect(() => {
const onKeyDown = (event: KeyboardEvent): void => {
if (event.key === 'Escape') onClose();
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [onClose]);
return createPortal(
<div
className="modal-backdrop"
role="presentation"
onClick={(event) => {
if (event.target === event.currentTarget) onClose();
}}
>
<div className="modal-dialog" role="dialog" aria-modal="true" aria-labelledby={titleId}>
<header className="modal-head">
<h3 id={titleId} className="modal-title">{t('about.update.notesTitle', { version })}</h3>
<button
type="button"
className="modal-close"
aria-label={t('about.update.closeNotes')}
onClick={onClose}
>
×
</button>
</header>
<div className="modal-body">
<MarkdownContent markdown={notes} />
</div>
<footer className="modal-foot">
<button type="button" className="button" onClick={onClose}>
{t('about.update.closeNotes')}
</button>
</footer>
</div>
</div>,
document.body,
);
}
@@ -22,17 +22,24 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
useEffect(() => { useEffect(() => {
let mounted = true; let mounted = true;
setInfo(null);
ipcInvoke('copies:maintenanceInfo', { id: record.id }).then((value) => { ipcInvoke('copies:maintenanceInfo', { id: record.id }).then((value) => {
if (mounted) setInfo(value); if (mounted) setInfo(value);
}).catch(onError); }).catch(onError);
return () => { mounted = false; }; return () => { mounted = false; };
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, maintenance.revision, onError]); }, [record.id, record.gameVersion, record.sourcePath, record.steamLibraryConfirmation, maintenance.revision, onError]);
const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => { const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
if (operation === 'delete') setRemoval(null); if (operation === 'delete') setRemoval(null);
maintenance.run(record.id, operation, options); maintenance.run(record.id, operation, options);
}; };
const chooseUpdateSource = (): void => {
ipcInvoke('dialog:pickFolder', { title: t('copies.maintenance.chooseSource') }).then(({ path }) => {
if (path) run('set-source', { sourcePath: path });
}).catch(onError);
};
const active = maintenance.active; const active = maintenance.active;
const busy = active !== null; const busy = active !== null;
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null; const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
@@ -44,6 +51,7 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
info={info} info={info}
busy={busy} busy={busy}
onRun={run} onRun={run}
onChooseSource={chooseUpdateSource}
onConfirmSteam={(steamLocations) => run('confirm-steam', { steamLocations })} onConfirmSteam={(steamLocations) => run('confirm-steam', { steamLocations })}
/> />
<CopyRemoval <CopyRemoval
@@ -12,12 +12,20 @@ interface CopyMaintenanceControlsProps {
interface CopyMaintenanceActionsProps extends CopyMaintenanceControlsProps { interface CopyMaintenanceActionsProps extends CopyMaintenanceControlsProps {
readonly onRun: (operation: 'update' | 'compact' | 'check' | 'repair') => void; readonly onRun: (operation: 'update' | 'compact' | 'check' | 'repair') => void;
readonly onChooseSource: () => void;
readonly onConfirmSteam: (locations: NonNullable<MaintenanceRequest['steamLocations']>) => void; readonly onConfirmSteam: (locations: NonNullable<MaintenanceRequest['steamLocations']>) => void;
} }
export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSteam }: CopyMaintenanceActionsProps) { export function CopyMaintenanceActions({ record, info, busy, onRun, onChooseSource, onConfirmSteam }: CopyMaintenanceActionsProps) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const steam = info?.steamLocations; const steam = info?.steamLocations;
const updateHint = info?.sourceVersion
? t(info.updateAvailable
? (record.hardlinkedFiles?.length
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
: 'copies.maintenance.newVersion')
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
: t(record.sourcePath ? (info ? 'copies.maintenance.noSource' : 'copies.maintenance.phase.checking') : 'copies.maintenance.sourceNotSet');
return ( return (
<> <>
{info?.steamConfirmationRequired && steam && ( {info?.steamConfirmationRequired && steam && (
@@ -30,13 +38,10 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSte
</button> </button>
</Notice> </Notice>
)} )}
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion <Row label={t('copies.maintenance.update')} hint={record.sourcePath ? <>{record.sourcePath}<br />{updateHint}</> : updateHint}>
? t(info.updateAvailable <button type="button" className="button" disabled={busy} onClick={onChooseSource}>
? (record.hardlinkedFiles?.length {t(record.sourcePath ? 'copies.maintenance.changeSource' : 'copies.maintenance.setSource')}
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches') </button>
: 'copies.maintenance.newVersion')
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
: t('copies.maintenance.noSource')}>
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'} <button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
disabled={busy || !info?.updateAvailable} onClick={() => onRun('update')}> disabled={busy || !info?.updateAvailable} onClick={() => onRun('update')}>
{t('copies.maintenance.updateAction')} {t('copies.maintenance.updateAction')}
@@ -4,7 +4,7 @@ import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/ma
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts'; import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
export type MaintenanceOperation = MaintenanceRequest['operation']; export type MaintenanceOperation = MaintenanceRequest['operation'];
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>; export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations' | 'sourcePath'>;
export interface MaintenanceOutcome { export interface MaintenanceOutcome {
readonly copyId: string; readonly copyId: string;
@@ -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':
@@ -252,6 +252,11 @@
background: var(--red); background: var(--red);
} }
.button-compact {
font-size: 13px;
padding: 5px 12px;
}
.link { .link {
font: inherit; font: inherit;
color: var(--white); color: var(--white);
@@ -481,3 +486,245 @@
left: 100%; left: 100%;
} }
} }
/* ===== Modal dialog & Markdown content ===== */
.modal-backdrop {
position: fixed;
inset: 0;
z-index: 40;
display: flex;
align-items: center;
justify-content: center;
padding: 28px;
background: rgba(7, 10, 12, 0.72);
}
.modal-dialog {
width: min(760px, 100%);
max-height: min(600px, 100%);
display: flex;
flex-direction: column;
overflow: hidden;
background: var(--sheet);
border: 1px solid var(--line-strong);
border-radius: var(--radius);
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.65);
}
.modal-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 14px 12px 20px;
background: linear-gradient(180deg, #343a40, #2b3136);
border-bottom: 1px solid #000;
}
.modal-title {
margin: 0;
font: 500 18px var(--font-display);
color: var(--white);
letter-spacing: 0.02em;
}
.modal-close {
flex: none;
width: 28px;
height: 28px;
display: grid;
place-items: center;
padding: 0;
border: 0;
border-radius: var(--radius);
background: none;
color: var(--text-dim);
font-size: 20px;
line-height: 1;
cursor: pointer;
}
.modal-close:hover {
color: var(--white);
background: rgba(255, 255, 255, 0.1);
}
.modal-body {
flex: 1;
min-height: 0;
overflow: auto;
padding: 18px 22px 22px;
user-select: text;
}
.modal-foot {
display: flex;
justify-content: flex-end;
gap: 10px;
padding: 10px 20px;
border-top: 1px solid var(--line);
background: rgba(0, 0, 0, 0.17);
}
.markdown-body {
font-size: 13.5px;
line-height: 1.65;
color: var(--text);
overflow-wrap: anywhere;
}
.markdown-body > :first-child {
margin-top: 0;
}
.markdown-body > :last-child {
margin-bottom: 0;
}
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
margin: 18px 0 8px;
font-family: var(--font-display);
font-weight: 500;
color: var(--white);
line-height: 1.3;
}
.markdown-body h1 {
font-size: 20px;
padding-bottom: 6px;
border-bottom: 1px solid var(--line);
}
.markdown-body h2 {
font-size: 17px;
padding-bottom: 5px;
border-bottom: 1px solid var(--line);
}
.markdown-body h3 {
font-size: 15px;
}
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
font-size: 14px;
color: var(--text);
}
.markdown-body p {
margin: 0 0 10px;
}
.markdown-body strong {
color: var(--white);
font-weight: 600;
}
.markdown-body ul,
.markdown-body ol {
margin: 6px 0 10px;
padding-left: 22px;
}
.markdown-body li {
margin: 4px 0;
}
.markdown-body li > ul,
.markdown-body li > ol {
margin: 4px 0;
}
.markdown-body li > p {
margin: 0 0 4px;
}
.markdown-body li > p:last-child {
margin-bottom: 0;
}
.markdown-body code {
padding: 1px 5px;
font-family: var(--font-mono);
font-size: 12.5px;
color: #e6eff2;
background: rgba(0, 0, 0, 0.34);
border: 1px solid var(--line-soft);
border-radius: 2px;
}
.markdown-body pre {
margin: 10px 0;
padding: 10px 12px;
overflow: auto;
background: rgba(0, 0, 0, 0.38);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.markdown-body pre code {
padding: 0;
background: none;
border: 0;
font-size: 12.5px;
line-height: 1.5;
}
.markdown-body blockquote {
margin: 10px 0;
padding: 6px 12px;
color: var(--text-dim);
background: rgba(255, 255, 255, 0.03);
border-left: 3px solid var(--line-strong);
}
.markdown-body hr {
margin: 16px 0;
border: 0;
border-top: 1px solid var(--line);
}
.markdown-body a {
color: #7feaf2;
text-decoration: none;
border-bottom: 1px solid rgba(127, 234, 242, 0.35);
}
.markdown-body a:hover {
color: var(--white);
border-bottom-color: var(--white);
}
.markdown-table-wrap {
margin: 10px 0;
overflow-x: auto;
}
.markdown-body table {
width: 100%;
border-collapse: collapse;
font-size: 12.5px;
}
.markdown-body th,
.markdown-body td {
padding: 6px 10px;
border: 1px solid var(--line);
text-align: left;
}
.markdown-body th {
color: var(--white);
background: rgba(255, 255, 255, 0.05);
}
.markdown-task {
margin-right: 6px;
vertical-align: middle;
}
+400 -3
View File
@@ -344,9 +344,12 @@
} }
/* ===== About ===== */ /* ===== About ===== */
.update-notes { .update-actions {
white-space: pre-line; display: flex;
overflow-wrap: anywhere; align-items: center;
gap: 8px;
flex-wrap: wrap;
margin-top: 10px;
} }
.about-head { .about-head {
@@ -435,3 +438,397 @@
.about-card .notice .button { .about-card .notice .button {
margin-top: 8px; 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;
}
+9
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',
@@ -40,6 +45,8 @@ export const APP_ERROR_CODES = [
'maintenance_busy', 'maintenance_busy',
'maintenance_location', 'maintenance_location',
'maintenance_no_update', 'maintenance_no_update',
'maintenance_source_invalid',
'maintenance_source_overlap',
'maintenance_cancelled', 'maintenance_cancelled',
'maintenance_failed', 'maintenance_failed',
'maintenance_source_changed', 'maintenance_source_changed',
@@ -89,6 +96,8 @@ export const APP_ERROR_CODES = [
'missing_features_not_accepted', 'missing_features_not_accepted',
/** Working out which patches fit failed; the details are in the log. */ /** Working out which patches fit failed; the details are in the log. */
'patch_check_failed', 'patch_check_failed',
/** The packaged launcher itself sits inside the selected stock War Thunder folder. */
'launcher_inside_source',
/** Copying the game failed; what was copied has been removed. */ /** Copying the game failed; what was copied has been removed. */
'copy_failed', 'copy_failed',
'hardlink_unavailable', 'hardlink_unavailable',
+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. */
+45
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';
@@ -262,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,
+1 -1
View File
@@ -150,7 +150,7 @@ export type InstallProgress = z.output<typeof InstallProgressSchema>;
export const InstallRecordSchema = z.object({ export const InstallRecordSchema = z.object({
id: CopyIdSchema, id: CopyIdSchema,
name: CopyNameSchema, name: CopyNameSchema,
/** Recorded only for a separate source copied during installation. */ /** Separate online installation used as the read-only update source. */
sourcePath: z.string().min(1).nullable(), sourcePath: z.string().min(1).nullable(),
method: z.enum(INSTALL_METHODS), method: z.enum(INSTALL_METHODS),
copyPath: z.string(), copyPath: z.string(),
@@ -1,11 +1,12 @@
import { z } from 'zod'; import { z } from 'zod';
import { CopyIdSchema } from './install.ts'; import { CopyIdSchema } from './install.ts';
export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'compact', 'delete', 'confirm-steam']); export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'compact', 'delete', 'confirm-steam', 'set-source']);
export const MaintenanceRequestSchema = z.object({ export const MaintenanceRequestSchema = z.object({
id: CopyIdSchema, id: CopyIdSchema,
operation: MaintenanceOperationSchema, operation: MaintenanceOperationSchema,
deleteData: z.boolean().default(false), deleteData: z.boolean().default(false),
sourcePath: z.string().min(1).optional(),
steamLocations: z.object({ steamLocations: z.object({
copyPath: z.string().min(1), copyPath: z.string().min(1),
dataPath: z.string().min(1), dataPath: z.string().min(1),
+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
+46 -5
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';
@@ -19,11 +19,13 @@ import {
isModeEligibleForLineup, isModeEligibleForLineup,
lineupMrank, lineupMrank,
selectCustomBots, selectCustomBots,
type TankLineupWeights,
type CustomBotsPool, type CustomBotsPool,
} from './battle-ranks.ts'; } from './battle-ranks.ts';
import type { BattleSessionStore } from './battle-session-store.ts'; import type { BattleSessionStore } from './battle-session-store.ts';
import { battleSpawnScore, type BattleSpawnScore } from './battle-spawn-score.ts'; import { battleSpawnScore, type BattleSpawnScore } from './battle-spawn-score.ts';
import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts'; import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
import type { BotTankLoadout } from './bot-tank-loadouts.ts';
import type { BattleTuning } from './battle-tuning.ts'; import type { BattleTuning } from './battle-tuning.ts';
export interface BattleCrewSlot { export interface BattleCrewSlot {
@@ -47,10 +49,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;
@@ -68,6 +72,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;
@@ -83,6 +88,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[];
@@ -91,6 +106,9 @@ 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 #tankWeights: TankLineupWeights | undefined;
readonly #tankLoadouts: ReadonlyMap<string, BotTankLoadout> | undefined;
readonly #filterMissions: MissionPoolFilter | undefined;
constructor( constructor(
gameModes: GameModes, gameModes: GameModes,
@@ -99,6 +117,9 @@ export class BattleMatchmaker {
tuning: BattleTuning, tuning: BattleTuning,
spawnRules: BattleSpawnRulesData, spawnRules: BattleSpawnRulesData,
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>, aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
tankWeights: TankLineupWeights | undefined,
tankLoadouts?: ReadonlyMap<string, BotTankLoadout>,
filterMissions?: MissionPoolFilter,
) { ) {
this.#gameModes = gameModes; this.#gameModes = gameModes;
this.#vehicles = vehicles; this.#vehicles = vehicles;
@@ -107,6 +128,9 @@ export class BattleMatchmaker {
this.#tuning = tuning; this.#tuning = tuning;
this.#spawnRules = spawnRules; this.#spawnRules = spawnRules;
this.#aircraftLoadouts = aircraftLoadouts; this.#aircraftLoadouts = aircraftLoadouts;
this.#tankWeights = tankWeights;
this.#tankLoadouts = tankLoadouts;
this.#filterMissions = filterMissions;
} }
enqueue(input: EnqueueBattleInput): MatchmakeOutcome { enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
@@ -130,8 +154,20 @@ export class BattleMatchmaker {
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,
@@ -153,7 +189,7 @@ export class BattleMatchmaker {
minMrank, minMrank,
maxMrank, maxMrank,
limitPerType: this.#tuning.botPoolLimitPerType, limitPerType: this.#tuning.botPoolLimitPerType,
}, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts); }, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts, this.#tankWeights, this.#tankLoadouts);
return { return {
ok: true, ok: true,
launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots), launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots),
@@ -164,7 +200,7 @@ export class BattleMatchmaker {
const pool = candidates.filter((mode) => isModeEligibleForLineup( const pool = candidates.filter((mode) => isModeEligibleForLineup(
mode.declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName, input.mrankDeltas, mode.declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName, input.mrankDeltas,
)); ));
if (pool.length === 0) return candidates.find((mode) => mode.declaration.multiSlot !== false); if (pool.length === 0) return undefined;
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) {
@@ -189,12 +225,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,
@@ -221,9 +259,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 } : {}),
@@ -241,6 +281,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,6 +23,7 @@ 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. */
@@ -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));
@@ -62,13 +70,17 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true)); for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true));
// The native in-flight rearm request and its receiver both require unlimited reserve ammunition. // The native in-flight rearm request and its receiver both require unlimited reserve ammunition.
setParam(settings, 'isLimitedAmmo', flag(plan.modeName !== 'air_arcade')); setParam(settings, 'isLimitedAmmo', flag(plan.modeName !== 'air_arcade'));
setParam(settings, 'allowSpare', flag(!plan.selectedSlot)); // 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));
@@ -90,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). */
@@ -117,6 +130,8 @@ 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.mission.groundMode !== undefined) setParam(bots, 'wtoGroundMode', text(plan.mission.groundMode));
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));
@@ -126,6 +141,7 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
poolBlock('allowedAircrafts', 'aircraft', plan.customBots.aircrafts), poolBlock('allowedAircrafts', 'aircraft', plan.customBots.aircrafts),
poolBlock('allowedShips', 'ship', plan.customBots.ships), poolBlock('allowedShips', 'ship', plan.customBots.ships),
); );
addTankAmmoParams(bots, plan.customBots.tanks);
return bots; return bots;
} }
@@ -141,11 +157,26 @@ function poolBlock(name: string, entryName: string, entries: CustomBotsPool['tan
setParam(ensureBlock(block, 'preset'), 'name', text(loadout.preset)); setParam(ensureBlock(block, 'preset'), 'name', text(loadout.preset));
for (const modification of loadout.modifications) appendParam(block, 'addModification', text(modification)); for (const modification of loadout.modifications) appendParam(block, 'addModification', text(modification));
} }
if (entry.tankLoadout !== undefined) {
for (const modification of entry.tankLoadout.modifications) appendParam(block, 'addModification', text(modification));
}
pool.blocks.push(block); pool.blocks.push(block);
} }
return pool; return pool;
} }
/** Per-tank bot ammo strings (`weapon|mod0:count0|mod1:count1`) read by local_mp_loadout.c. */
function addTankAmmoParams(bots: BlkBlock, entries: CustomBotsPool['tanks']): void {
const seen = new Set<string>();
for (const entry of entries) {
const loadout = entry.tankLoadout;
if (!loadout || loadout.bullets.length === 0 || seen.has(entry.name)) continue;
seen.add(entry.name);
const parts = [loadout.weaponName, ...loadout.bullets.slice(0, 2).map((s) => `${s.modName}:${s.count}`)];
setParam(bots, `wtoAmmo_${entry.name}`, text(parts.join('|')));
}
}
function text(value: string): BlkValue { function text(value: string): BlkValue {
return { type: 'string', value }; return { type: 'string', value };
} }
+39 -4
View File
@@ -10,6 +10,7 @@ import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.t
import type { GameModeDeclaration, ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts'; import type { GameModeDeclaration, ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
import { vehicleTypeById, vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts'; import { vehicleTypeById, vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts';
import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts'; import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
import type { BotTankLoadout } from './bot-tank-loadouts.ts';
const COUNTRY_PREFIX = 'country_'; const COUNTRY_PREFIX = 'country_';
@@ -23,6 +24,7 @@ export interface BotPoolEntry {
readonly country: string; readonly country: string;
readonly weight: number; readonly weight: number;
readonly aircraftLoadout?: BotAircraftLoadout; readonly aircraftLoadout?: BotAircraftLoadout;
readonly tankLoadout?: BotTankLoadout;
} }
export interface CustomBotsPool { export interface CustomBotsPool {
@@ -31,6 +33,16 @@ export interface CustomBotsPool {
readonly ships: readonly BotPoolEntry[]; readonly ships: readonly BotPoolEntry[];
} }
/** Offline tank pool weights by vehicle class (`tuning/ground-ai.jsonc` `lineupWeights`). */
export interface TankLineupWeights {
readonly spaa: number;
readonly lightTank: number;
readonly tankDestroyer: number;
readonly heavyTank: number;
readonly mediumTank: number;
readonly other: number;
}
export interface BotPoolQuery { export interface BotPoolQuery {
readonly difficulty: ModeDifficulty; readonly difficulty: ModeDifficulty;
readonly requiredClass: UnitClass; readonly requiredClass: UnitClass;
@@ -117,14 +129,25 @@ function lineupVehicleMrank(
return vehicleMrank(vehicle, difficulty, requiredClass) + (mrankDeltas.get(vehicle.name) ?? 0); return vehicleMrank(vehicle, difficulty, requiredClass) + (mrankDeltas.get(vehicle.name) ?? 0);
} }
/**
* Without `tankWeights` every pool entry keeps the stock weight of 1.
*/
export function selectCustomBots( export function selectCustomBots(
vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>, vehicles: readonly CatalogueVehicle[],
query: BotPoolQuery,
aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
tankWeights?: TankLineupWeights,
tankLoadouts?: ReadonlyMap<string, BotTankLoadout>,
): CustomBotsPool { ): CustomBotsPool {
const allowed = new Set(query.allowedClasses); const allowed = new Set(query.allowedClasses);
const orderedCountries = [...new Set(query.countries.map((c) => (c.startsWith(COUNTRY_PREFIX) ? c : `${COUNTRY_PREFIX}${c}`)))]; const orderedCountries = [...new Set(query.countries.map((c) => (c.startsWith(COUNTRY_PREFIX) ? c : `${COUNTRY_PREFIX}${c}`)))];
const aircrafts = allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : []; const aircrafts = allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : [];
const rawTanks = allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query, tankWeights) : [];
return { return {
tanks: allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query) : [], tanks: tankLoadouts ? rawTanks.map((entry) => {
const tankLoadout = tankLoadouts.get(entry.name);
return tankLoadout === undefined ? entry : { ...entry, tankLoadout };
}) : rawTanks,
aircrafts: query.requiredClass === 'aircraft' && aircraftLoadouts ? aircrafts.map((entry) => { aircrafts: query.requiredClass === 'aircraft' && aircraftLoadouts ? aircrafts.map((entry) => {
const aircraftLoadout = aircraftLoadouts.get(entry.name); const aircraftLoadout = aircraftLoadouts.get(entry.name);
return aircraftLoadout === undefined ? entry : { ...entry, aircraftLoadout }; return aircraftLoadout === undefined ? entry : { ...entry, aircraftLoadout };
@@ -138,6 +161,7 @@ function pickCategoryPool(
orderedCountries: readonly string[], orderedCountries: readonly string[],
category: 'tank' | 'aircraft' | 'ship', category: 'tank' | 'aircraft' | 'ship',
query: BotPoolQuery, query: BotPoolQuery,
tankWeights?: TankLineupWeights,
): BotPoolEntry[] { ): BotPoolEntry[] {
const countrySet = new Set(orderedCountries); const countrySet = new Set(orderedCountries);
const eligible = vehicles.filter((vehicle) => const eligible = vehicles.filter((vehicle) =>
@@ -161,13 +185,14 @@ function pickCategoryPool(
return mrank >= query.minMrank && mrank <= query.maxMrank; return mrank >= query.minMrank && mrank <= query.maxMrank;
}); });
const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType); const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType);
return roundRobinByCountry(source, orderedCountries, query.limitPerType); return roundRobinByCountry(source, orderedCountries, query.limitPerType, (vehicle) => tankPoolWeight(vehicle, tankWeights));
} }
function roundRobinByCountry( function roundRobinByCountry(
vehicles: readonly CatalogueVehicle[], vehicles: readonly CatalogueVehicle[],
orderedCountries: readonly string[], orderedCountries: readonly string[],
limit: number, limit: number,
weightOf: (vehicle: CatalogueVehicle) => number,
): BotPoolEntry[] { ): BotPoolEntry[] {
const buckets = new Map<string, CatalogueVehicle[]>(orderedCountries.map((country) => [country, []])); const buckets = new Map<string, CatalogueVehicle[]>(orderedCountries.map((country) => [country, []]));
for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle); for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle);
@@ -177,7 +202,7 @@ function roundRobinByCountry(
for (const country of orderedCountries) { for (const country of orderedCountries) {
const vehicle = buckets.get(country)?.[index]; const vehicle = buckets.get(country)?.[index];
if (!vehicle) continue; if (!vehicle) continue;
out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: 1 }); out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: weightOf(vehicle) });
added = true; added = true;
if (out.length >= limit) break; if (out.length >= limit) break;
} }
@@ -186,6 +211,16 @@ function roundRobinByCountry(
return out; return out;
} }
function tankPoolWeight(vehicle: CatalogueVehicle, weights: TankLineupWeights | undefined): number {
if (weights === undefined) return 1;
if (vehicle.unitClass === 'exp_SPAA') return weights.spaa;
if (vehicle.isLightTank) return weights.lightTank;
if (vehicle.unitClass === 'exp_tank_destroyer') return weights.tankDestroyer;
if (vehicle.unitClass === 'exp_heavy_tank') return weights.heavyTank;
if (vehicle.unitClass === 'exp_tank') return weights.mediumTank;
return weights.other;
}
function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined { function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined {
if (type === 'Tank') return 'tank'; if (type === 'Tank') return 'tank';
if (type === 'Aircraft') return 'aircraft'; if (type === 'Aircraft') return 'aircraft';
+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'),
}; };
} }
+135
View File
@@ -0,0 +1,135 @@
/**
* Offline AI tank spawn ammunition selector:
* - Total carried rounds follow the vehicle's first-stage / autoloader ready rack, topped up
* when below the configured threshold (clamped to main gun capacity).
* - Primary shell prefers legal APFSDS, otherwise ranks anti-armor shells by 500 m penetration.
* - Secondary shell carries a small share of HE / HEAT / HESH when available for soft targets.
*/
import type { GroundAiLoadoutConfig } from '@wto/patcher';
import type { TankAmmoProfile, TankBotAmmoData, TankShellChoice } from '../game-data/datasets/tank-bot-ammo.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import { vehicleTypeOfClass } from '../research/vehicle-types.ts';
export interface BotTankBulletSlot {
readonly modName: string;
readonly count: number;
}
export interface BotTankLoadout {
readonly weaponName: string;
readonly bullets: readonly BotTankBulletSlot[];
readonly modifications: readonly string[];
}
export function selectBotTankLoadouts(
vehicles: readonly CatalogueVehicle[],
ammoData: TankBotAmmoData,
config: GroundAiLoadoutConfig,
): ReadonlyMap<string, BotTankLoadout> {
const result = new Map<string, BotTankLoadout>();
for (const vehicle of vehicles) {
if (vehicleTypeOfClass(vehicle.unitClass) !== 'Tank' || vehicle.unitClass === 'exp_SPAA') continue;
const profile = ammoData[vehicle.name];
if (!profile || profile.isBelt || profile.maxBullets <= 0) continue;
const loadout = chooseTankLoadout(profile, config);
if (loadout !== undefined) result.set(vehicle.name, loadout);
}
return result;
}
function chooseTankLoadout(profile: TankAmmoProfile, config: GroundAiLoadoutConfig): BotTankLoadout | undefined {
const combatShells = profile.shells.filter((shell) => !isNonCombatShell(shell.bulletType));
if (combatShells.length === 0) return undefined;
const primary = pickPrimaryShell(combatShells);
if (!primary) return undefined;
const totalRounds = computeCarriedRounds(profile, config);
if (totalRounds <= 0) return undefined;
const secondary = pickSecondaryShell(combatShells, primary);
const bullets = splitRounds(primary, secondary, totalRounds, config);
const modSet = new Set<string>();
for (const chosen of [primary, ...(bullets.length > 1 && secondary ? [secondary] : [])]) {
if (chosen.modName) modSet.add(chosen.modName);
for (const req of chosen.requires) modSet.add(req);
}
return {
weaponName: profile.weaponName,
bullets,
modifications: [...modSet].sort(),
};
}
function computeCarriedRounds(profile: TankAmmoProfile, config: GroundAiLoadoutConfig): number {
const want = profile.readyRack >= config.lowReadyRackThreshold
? profile.readyRack
: config.topUpAmmoCount;
return Math.max(1, Math.min(want, profile.maxBullets));
}
function pickPrimaryShell(shells: readonly TankShellChoice[]): TankShellChoice | undefined {
const ranked = [...shells].sort((a, b) => compareAntiArmor(a, b));
return ranked[0];
}
function compareAntiArmor(a: TankShellChoice, b: TankShellChoice): number {
const tierA = antiArmorTier(a.bulletType);
const tierB = antiArmorTier(b.bulletType);
if (tierA !== tierB) return tierB - tierA;
const scoreA = a.pen500Mm + (isApheFamily(a.bulletType) ? 12 : 0);
const scoreB = b.pen500Mm + (isApheFamily(b.bulletType) ? 12 : 0);
if (scoreA !== scoreB) return scoreB - scoreA;
if (a.speedMps !== b.speedMps) return b.speedMps - a.speedMps;
return a.modName.localeCompare(b.modName);
}
function antiArmorTier(bulletType: string): number {
if (bulletType.includes('apds_fs')) return 5;
if (bulletType.includes('atgm')) return 4;
if (bulletType.includes('apds')) return 3;
if (bulletType.includes('heat') || isApheFamily(bulletType) || bulletType.startsWith('ap')) return 2;
if (bulletType.includes('hesh')) return 1;
return 0;
}
function pickSecondaryShell(shells: readonly TankShellChoice[], primary: TankShellChoice): TankShellChoice | undefined {
const candidates = shells.filter((shell) => shell.modName !== primary.modName && isSoftTargetShell(shell.bulletType));
if (candidates.length === 0) return undefined;
return [...candidates].sort((a, b) => {
const heA = a.bulletType.includes('he_frag') ? 2 : (a.bulletType.includes('hesh') ? 1 : 0);
const heB = b.bulletType.includes('he_frag') ? 2 : (b.bulletType.includes('hesh') ? 1 : 0);
if (heA !== heB) return heB - heA;
if (a.speedMps !== b.speedMps) return b.speedMps - a.speedMps;
return a.modName.localeCompare(b.modName);
})[0];
}
function splitRounds(
primary: TankShellChoice,
secondary: TankShellChoice | undefined,
totalRounds: number,
config: GroundAiLoadoutConfig,
): BotTankBulletSlot[] {
if (!secondary || config.primaryAmmoPct >= 100 || config.secondaryMinRounds <= 0 || totalRounds < config.secondaryMinRounds * 2 + 2) {
return [{ modName: primary.modName, count: totalRounds }];
}
const wantSec = Math.round((totalRounds * (100 - config.primaryAmmoPct)) / 100);
const secCount = Math.min(totalRounds - 1, Math.max(config.secondaryMinRounds, wantSec));
const priCount = totalRounds - secCount;
return [
{ modName: primary.modName, count: priCount },
{ modName: secondary.modName, count: secCount },
];
}
function isNonCombatShell(bulletType: string): boolean {
return bulletType.includes('smoke') || bulletType.includes('practice') || bulletType.includes('shrapnel');
}
function isSoftTargetShell(bulletType: string): boolean {
return bulletType.includes('he_frag') || bulletType.includes('hesh') || bulletType.includes('heat');
}
function isApheFamily(bulletType: string): boolean {
return bulletType.includes('aphe') || bulletType.includes('apcbc') || bulletType.includes('apbc');
}
+3 -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';
@@ -94,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;
@@ -118,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)],
@@ -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 };
}
+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 {
+23 -2
View File
@@ -7,24 +7,45 @@
* will start the service the same way. Stops on Ctrl+C. * will start the service the same way. Stops on Ctrl+C.
*/ */
import { parseArgs } from 'node:util'; import { parseArgs } from 'node:util';
import { discoverMods, type DiscoveredMod } from '@wto/mods';
import { LOOPBACK, startServer } from './server.ts'; import { LOOPBACK, startServer } from './server.ts';
function resolveCliMods(modsDir: string | undefined, modIds: readonly string[] | undefined): DiscoveredMod[] {
if (!modsDir || !modIds || modIds.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
return modIds.map((id) => {
const mod = byId.get(id);
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
return mod;
});
}
async function main(): Promise<number> { async function main(): Promise<number> {
const { values } = parseArgs({ const { values } = parseArgs({
options: { options: {
game: { type: 'string' }, game: { type: 'string' },
data: { type: 'string' }, data: { type: 'string' },
port: { type: 'string' }, port: { type: 'string' },
'mods-dir': { type: 'string' },
mod: { type: 'string', multiple: true },
}, },
}); });
const port = Number(values.port); const port = Number(values.port);
if (!values.game || !values.data || !Number.isInteger(port) || port < 1 || port > 65535) { if (!values.game || !values.data || !Number.isInteger(port) || port < 1 || port > 65535) {
console.error('usage: cli.ts --game <game folder> --data <data folder> --port <n>'); console.error('usage: cli.ts --game <game folder> --data <data folder> --port <n> [--mods-dir <dir> --mod <id>...]');
return 2; return 2;
} }
let service; let service;
try { try {
service = await startServer({ gameFolder: values.game, dataFolder: values.data, port, report: (line) => console.log(line) }); const mods = resolveCliMods(values['mods-dir'], values.mod);
service = await startServer({
gameFolder: values.game,
dataFolder: values.data,
port,
report: (line) => console.log(line),
...(mods.length > 0 ? { mods } : {}),
});
} catch (error) { } catch (error) {
const code = (error as NodeJS.ErrnoException).code; const code = (error as NodeJS.ErrnoException).code;
console.error(code === 'EADDRINUSE' ? `port ${port} is already in use; choose another port` : String(error)); console.error(code === 'EADDRINUSE' ? `port ${port} is already in use; choose another port` : String(error));
@@ -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[]>> {
@@ -41,9 +41,13 @@ interface AirfieldLayoutData {
readonly airfieldLayoutProblem?: string; readonly airfieldLayoutProblem?: string;
} }
export type GroundBattleMode = 'bttl' | 'conq' | 'dom';
export interface MissionHeader extends AirfieldLayoutData { export interface MissionHeader extends AirfieldLayoutData {
readonly name: string; readonly name: string;
readonly path: string; readonly path: string;
/** Ground mission tactical layout derived from mislist category (or suffix fallback for events). */
readonly groundMode?: GroundBattleMode;
readonly level?: string; readonly level?: string;
readonly type?: string; readonly type?: string;
readonly environment?: string; readonly environment?: string;
@@ -72,7 +76,7 @@ export interface MultiplayerMissions {
export const multiplayerMissions: Dataset<MultiplayerMissions> = { export const multiplayerMissions: Dataset<MultiplayerMissions> = {
id: 'multiplayer-missions', id: 'multiplayer-missions',
version: 4, version: 5,
extract(source: DatasetSource): MultiplayerMissions { extract(source: DatasetSource): MultiplayerMissions {
const section = blockAt(source.readBlk('char.vromfs.bin', MISSION_LIST), MULTIPLAYER_SECTION); const section = blockAt(source.readBlk('char.vromfs.bin', MISSION_LIST), MULTIPLAYER_SECTION);
if (!section) throw new Error(`${MISSION_LIST} has no "${MULTIPLAYER_SECTION}" block`); if (!section) throw new Error(`${MISSION_LIST} has no "${MULTIPLAYER_SECTION}" block`);
@@ -82,6 +86,7 @@ export const multiplayerMissions: Dataset<MultiplayerMissions> = {
missions: stringList(block, 'm'), missions: stringList(block, 'm'),
})); }));
const groundModeByMission = indexGroundModes(categories);
const paths = source.listFiles('mis.vromfs.bin'); const paths = source.listFiles('mis.vromfs.bin');
const pathByName = missionPathsByLowerName(paths); const pathByName = missionPathsByLowerName(paths);
const knownPaths = new Set(paths); const knownPaths = new Set(paths);
@@ -94,12 +99,34 @@ export const multiplayerMissions: Dataset<MultiplayerMissions> = {
const document = source.readBlk('mis.vromfs.bin', path); const document = source.readBlk('mis.vromfs.bin', path);
const airfields = path.startsWith(AIR_HISTORICAL_MISSION_FOLDER) const airfields = path.startsWith(AIR_HISTORICAL_MISSION_FOLDER)
? readAirfieldLayouts(source, document, knownPaths, airfieldsByPath) : { airfieldLayouts: [] }; ? readAirfieldLayouts(source, document, knownPaths, airfieldsByPath) : { airfieldLayouts: [] };
missions[name] = readHeader(name, path, document, airfields); const groundMode = groundModeByMission.get(name) ?? groundModeFromName(name);
missions[name] = readHeader(name, path, document, airfields, groundMode);
} }
return { categories, missions }; return { categories, missions };
}, },
}; };
function indexGroundModes(categories: readonly MissionCategory[]): Map<string, GroundBattleMode> {
const byName = new Map<string, GroundBattleMode>();
for (const category of categories) {
const mode: GroundBattleMode | undefined =
category.name === 'air_ground_Bttl' ? 'bttl'
: category.name === 'air_ground_Conq' ? 'conq'
: category.name === 'air_ground_Dom' ? 'dom'
: undefined;
if (!mode) continue;
for (const name of category.missions) if (!byName.has(name)) byName.set(name, mode);
}
return byName;
}
function groundModeFromName(name: string): GroundBattleMode | undefined {
if (/_Bttl\d*$/i.test(name)) return 'bttl';
if (/_Conq\d*$/i.test(name)) return 'conq';
if (/_Dom\d*$/i.test(name)) return 'dom';
return undefined;
}
function missionPathsByLowerName(paths: readonly string[]): Map<string, string> { function missionPathsByLowerName(paths: readonly string[]): Map<string, string> {
const byName = new Map<string, string>(); const byName = new Map<string, string>();
const repeated = new Set<string>(); const repeated = new Set<string>();
@@ -114,11 +141,12 @@ function missionPathsByLowerName(paths: readonly string[]): Map<string, string>
} }
function readHeader( function readHeader(
name: string, path: string, document: BlkBlock, airfields: AirfieldLayoutData, name: string, path: string, document: BlkBlock, airfields: AirfieldLayoutData, groundMode?: GroundBattleMode,
): MissionHeader { ): MissionHeader {
const settings = blockAt(document, 'mission_settings'); const settings = blockAt(document, 'mission_settings');
const mission = blockAt(settings, 'mission'); const mission = blockAt(settings, 'mission');
const optional = { const optional = {
groundMode,
level: stringField(mission, 'level'), level: stringField(mission, 'level'),
type: stringField(mission, 'type'), type: stringField(mission, 'type'),
environment: stringField(mission, 'environment'), environment: stringField(mission, 'environment'),
@@ -0,0 +1,244 @@
/**
* Dataset: primary cannon weapon name, capacity, first-stage/autoloader ready-rack count,
* and selectable ammunition groups (with penetration and prerequisite modifications) for
* every ground tank model in `aces.vromfs.bin` + `char.vromfs.bin`.
*/
import { findBlock, type BlkBlock } from '@wto/blk';
import type { Dataset, DatasetSource } from './dataset.ts';
import { boolField, numberField, stringField, stringList } from './blk-fields.ts';
const VEHICLE_ECONOMY = 'config/wpcost.blk';
const MODIFICATIONS_CONFIG = 'config/modifications.blk';
const TANK_MODELS_PREFIX = 'gamedata/units/tankmodels/';
export interface TankShellChoice {
/** Modification name expected by ChangeUnitReflection.bullets[i] (`""` for stock default). */
readonly modName: string;
readonly bulletType: string;
readonly speedMps: number;
/** Estimated normal penetration at 500 m (mm) for deterministic ranking. */
readonly pen500Mm: number;
/** Transitive prerequisite modifications needed to unlock this shell. */
readonly requires: readonly string[];
}
export interface TankAmmoProfile {
readonly weaponName: string;
readonly maxBullets: number;
readonly isBelt: boolean;
/** Total firstStage / autoLoad / ammoLoadedInGun shell slots (excluding separate charges). */
readonly readyRack: number;
readonly shells: readonly TankShellChoice[];
}
export type TankBotAmmoData = Readonly<Record<string, TankAmmoProfile>>;
interface GlobalModInfo {
readonly bulletMod?: string;
readonly requires: readonly string[];
}
interface WeaponBulletMeta {
readonly bulletType: string;
readonly speedMps: number;
readonly pen500Mm: number;
}
export const tankBotAmmo: Dataset<TankBotAmmoData> = {
id: 'tank-bot-ammo',
version: 2,
extract(source: DatasetSource): TankBotAmmoData {
const globalMods = readGlobalModInfo(source.readBlk('char.vromfs.bin', MODIFICATIONS_CONFIG));
const wpcost = source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY);
const acesPaths = new Set(source.listFiles('aces.vromfs.bin').map((p) => p.toLowerCase()));
const weaponCache = new Map<string, { isBelt: boolean; defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> }>();
const out: Record<string, TankAmmoProfile> = {};
for (const vehicleBlk of wpcost.blocks) {
const unitPath = `${TANK_MODELS_PREFIX}${vehicleBlk.name.toLowerCase()}.blk`;
if (!acesPaths.has(unitPath)) continue;
const profile = extractTankProfile(source, acesPaths, weaponCache, globalMods, vehicleBlk, unitPath);
if (profile !== undefined) out[vehicleBlk.name] = profile;
}
return out;
},
};
function readGlobalModInfo(root: BlkBlock): ReadonlyMap<string, GlobalModInfo> {
const mods = findBlock(root, 'modifications');
const map = new Map<string, GlobalModInfo>();
for (const entry of mods?.blocks ?? []) {
const effects = findBlock(entry, 'effects');
const bulletMod = stringField(effects, 'additiveBulletMod') ?? stringField(effects, 'bulletMod');
map.set(entry.name, {
...(bulletMod !== undefined ? { bulletMod } : {}),
requires: stringList(entry, 'reqModification'),
});
}
return map;
}
function extractTankProfile(
source: DatasetSource,
acesPaths: ReadonlySet<string>,
weaponCache: Map<string, { isBelt: boolean; defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> }>,
globalMods: ReadonlyMap<string, GlobalModInfo>,
wpcostVehicle: BlkBlock,
unitPath: string,
): TankAmmoProfile | undefined {
const unitBlk = source.readBlk('aces.vromfs.bin', unitPath);
const mainWeapon = findMainGunBlock(unitBlk);
if (!mainWeapon) return undefined;
const rawBlkPath = stringField(mainWeapon, 'blk');
const maxBullets = Math.trunc(numberField(mainWeapon, 'bullets') ?? 0);
if (!rawBlkPath || maxBullets <= 0) return undefined;
const lowerBlkPath = rawBlkPath.toLowerCase();
if (!acesPaths.has(lowerBlkPath)) return undefined;
const weaponName = basenameWithoutExt(rawBlkPath);
const weaponMeta = loadWeaponMeta(source, weaponCache, lowerBlkPath);
const readyRack = countReadyRackShells(unitBlk, stringField(mainWeapon, 'trigger') ?? 'gunner0');
const shells = collectSelectableShells(wpcostVehicle, unitBlk, globalMods, weaponMeta);
if (shells.length === 0) return undefined;
return { weaponName, maxBullets, isBelt: weaponMeta.isBelt, readyRack, shells };
}
function findMainGunBlock(unitBlk: BlkBlock): BlkBlock | undefined {
const common = findBlock(unitBlk, 'commonWeapons');
if (!common) return undefined;
return common.blocks.find((block) =>
stringField(block, 'trigger') === 'gunner0'
&& !(stringField(block, 'blk') ?? '').toLowerCase().includes('dummy_weapon'));
}
function countReadyRackShells(unitBlk: BlkBlock, mainTrigger: string): number {
const stowages = findBlock(unitBlk, 'ammoStowages');
if (!stowages) return 0;
let total = 0;
for (const stow of stowages.blocks) {
const triggers = stringList(stow, 'weaponTrigger');
if (triggers.length > 0 && !triggers.includes(mainTrigger)) continue;
for (const cluster of stow.blocks) {
if (cluster.name !== 'shells') continue;
const isReady = boolField(cluster, 'firstStage') === true
|| boolField(cluster, 'autoLoad') === true
|| boolField(cluster, 'ammoLoadedInGun') === true;
if (!isReady) continue;
for (const slot of cluster.blocks) total += Math.max(0, Math.trunc(numberField(slot, 'count') ?? 0));
}
}
return total;
}
function loadWeaponMeta(
source: DatasetSource,
cache: Map<string, { isBelt: boolean; defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> }>,
lowerPath: string,
) {
const cached = cache.get(lowerPath);
if (cached) return cached;
const blk = source.readBlk('aces.vromfs.bin', lowerPath);
const isBelt = boolField(blk, 'isBulletBelt') === true;
const defaultBlock = findBlock(blk, 'bullet');
const defaultBullet = defaultBlock ? parseBulletMeta(defaultBlock) : undefined;
const sets = new Map<string, WeaponBulletMeta>();
for (const child of blk.blocks) {
if (child.name === 'bullet') continue;
const subBullet = findBlock(child, 'bullet');
if (!subBullet) continue;
const meta = parseBulletMeta(subBullet);
if (meta) sets.set(child.name, meta);
}
const entry = { isBelt, ...(defaultBullet ? { defaultBullet } : {}), sets };
cache.set(lowerPath, entry);
return entry;
}
function parseBulletMeta(bullet: BlkBlock): WeaponBulletMeta | undefined {
const bulletType = (stringField(bullet, 'bulletType') ?? '').toLowerCase();
if (!bulletType) return undefined;
const speedMps = numberField(bullet, 'speed') ?? 0;
const pen500Mm = estimatePen500Mm(bullet, bulletType, speedMps);
return { bulletType, speedMps, pen500Mm };
}
function estimatePen500Mm(bullet: BlkBlock, bulletType: string, speedMps: number): number {
const cum = numberField(findBlock(bullet, 'cumulativeDamage'), 'armorPower');
const apBlock = findBlock(bullet, 'armorpower');
const ap500 = numberField(apBlock, 'ArmorPower500m') ?? numberField(apBlock, 'ArmorPower0m') ?? 0;
if (bulletType.includes('apds_fs')) {
const dmgBlock = findBlock(bullet, 'damage');
const kinetic = dmgBlock ? findBlock(dmgBlock, 'kinetic') : undefined;
const workLen = numberField(kinetic, 'lanzOdermattWorkingLength')
?? numberField(kinetic, 'WorkingLength')
?? numberField(kinetic, 'Length')
?? 0;
const density = numberField(kinetic, 'lanzOdermattDensity') ?? numberField(kinetic, 'Density') ?? 17000;
if (workLen > 0) return Math.max(ap500, Math.round(workLen * Math.sqrt(density / 7850) * (speedMps / 1700) * 0.85));
return Math.max(ap500, Math.round(speedMps * 0.24));
}
if (cum !== undefined && cum > ap500) return cum;
if (ap500 > 0) return ap500;
const mass = numberField(bullet, 'mass') ?? 0;
const cal = numberField(bullet, 'damageCaliber') ?? numberField(bullet, 'caliber') ?? 0;
if (mass > 0 && cal > 0 && speedMps > 100 && !bulletType.includes('he_') && !bulletType.includes('smoke')) {
return Math.round(0.0022 * Math.pow(mass, 0.55) * Math.pow(speedMps, 1.43) / Math.pow(cal * 1000, 0.65));
}
return 0;
}
function collectSelectableShells(
wpcostVehicle: BlkBlock,
unitBlk: BlkBlock,
globalMods: ReadonlyMap<string, GlobalModInfo>,
weaponMeta: { defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> },
): TankShellChoice[] {
const out: TankShellChoice[] = [];
if (weaponMeta.defaultBullet) {
out.push({ modName: '', ...weaponMeta.defaultBullet, requires: [] });
}
const wpModsBlock = findBlock(wpcostVehicle, 'modifications');
const unitModsBlock = findBlock(unitBlk, 'modifications');
const reqMap = new Map<string, readonly string[]>();
for (const mod of wpModsBlock?.blocks ?? []) reqMap.set(mod.name, stringList(mod, 'reqModification'));
for (const mod of wpModsBlock?.blocks ?? []) {
if (numberField(mod, 'ammoCount') === undefined) continue;
const unitMod = unitModsBlock ? findBlock(unitModsBlock, mod.name) : undefined;
const unitModEffects = unitMod ? findBlock(unitMod, 'effects') : undefined;
const setName = stringField(unitModEffects, 'additiveBulletMod')
?? stringField(unitModEffects, 'bulletMod')
?? globalMods.get(mod.name)?.bulletMod
?? mod.name;
const meta = weaponMeta.sets.get(setName);
if (!meta) continue;
out.push({
modName: mod.name,
...meta,
requires: collectTransitiveReqs(mod.name, reqMap, globalMods),
});
}
return out;
}
function collectTransitiveReqs(
modName: string,
reqMap: ReadonlyMap<string, readonly string[]>,
globalMods: ReadonlyMap<string, GlobalModInfo>,
): string[] {
const seen = new Set<string>();
const queue = [...(reqMap.get(modName) ?? []), ...(globalMods.get(modName)?.requires ?? [])];
while (queue.length > 0) {
const next = queue.pop()!;
if (!next || next === modName || seen.has(next)) continue;
seen.add(next);
for (const parent of reqMap.get(next) ?? []) queue.push(parent);
}
return [...seen].sort();
}
function basenameWithoutExt(path: string): string {
const slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
const file = slash >= 0 ? path.slice(slash + 1) : path;
return file.endsWith('.blk') ? file.slice(0, -4) : file;
}
@@ -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;
}
@@ -27,11 +27,14 @@ import type { Dataset } from './dataset.ts';
import { shopEntriesByName } from './shop-tree.ts'; import { shopEntriesByName } from './shop-tree.ts';
const VEHICLE_ECONOMY = 'config/wpcost.blk'; const VEHICLE_ECONOMY = 'config/wpcost.blk';
const UNIT_TAGS = 'config/unittags.blk';
export interface CatalogueVehicle { export interface CatalogueVehicle {
readonly name: string; readonly name: string;
readonly country: string; readonly country: string;
readonly unitClass: string; readonly unitClass: string;
/** True when config/unittags.blk tags the vehicle with type_light_tank. */
readonly isLightTank?: boolean;
readonly rank: number; readonly rank: number;
/** wpcost.blk reqAir; absent when empty or missing. */ /** wpcost.blk reqAir; absent when empty or missing. */
readonly requires?: string; readonly requires?: string;
@@ -70,15 +73,27 @@ export interface CatalogueVehicle {
export const vehicleCatalogue: Dataset<readonly CatalogueVehicle[]> = { export const vehicleCatalogue: Dataset<readonly CatalogueVehicle[]> = {
id: 'vehicle-catalogue', id: 'vehicle-catalogue',
version: 6, version: 7,
extract: (source) => { extract: (source) => {
const shopEntries = shopEntriesByName(source); const shopEntries = shopEntriesByName(source);
const treeOrder = new Map([...shopEntries.keys()].map((name, index) => [name, index])); const treeOrder = new Map([...shopEntries.keys()].map((name, index) => [name, index]));
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => catalogueVehicle(vehicle, shopEntries.get(vehicle.name), treeOrder.get(vehicle.name) ?? -1)); const lightTanks = lightTankNames(source.readBlk('char.vromfs.bin', UNIT_TAGS));
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) =>
catalogueVehicle(vehicle, shopEntries.get(vehicle.name), treeOrder.get(vehicle.name) ?? -1, lightTanks.has(vehicle.name)),
);
}, },
}; };
function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, treeOrder: number): CatalogueVehicle { function lightTankNames(unitTagsRoot: BlkBlock): ReadonlySet<string> {
const names = new Set<string>();
for (const unit of unitTagsRoot.blocks) {
const tags = unit.blocks.find((block) => block.name === 'tags');
if (tags && boolField(tags, 'type_light_tank') === true) names.add(unit.name);
}
return names;
}
function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, treeOrder: number, isLightTank: boolean): CatalogueVehicle {
const requires = stringField(vehicle, 'reqAir'); const requires = stringField(vehicle, 'reqAir');
const researchType = stringField(vehicle, 'researchType'); const researchType = stringField(vehicle, 'researchType');
const requiredUnlock = stringField(shopEntry, 'reqUnlock'); const requiredUnlock = stringField(shopEntry, 'reqUnlock');
@@ -90,6 +105,7 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, tr
name: vehicle.name, name: vehicle.name,
country: stringField(vehicle, 'country') ?? '', country: stringField(vehicle, 'country') ?? '',
unitClass: stringField(vehicle, 'unitClass') ?? '', unitClass: stringField(vehicle, 'unitClass') ?? '',
...(isLightTank ? { isLightTank: true } : {}),
rank: numberField(vehicle, 'rank') ?? 0, rank: numberField(vehicle, 'rank') ?? 0,
...(requires ? { requires } : {}), ...(requires ? { requires } : {}),
researchPoints: numberField(vehicle, 'reqExp') ?? 0, researchPoints: numberField(vehicle, 'reqExp') ?? 0,
@@ -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] } : {}];
+1
View File
@@ -11,5 +11,6 @@ export { editSaveAccount, editSaveCurrencies, listSaveSummaries, readSaveDetails
export { listSaveAvatars, readSaveAvatar } from './saves/save-avatars.ts'; export { listSaveAvatars, readSaveAvatar } from './saves/save-avatars.ts';
export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts'; export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts';
export { prepareTransferredProfile } from './saves/transferred-profile.ts'; export { prepareTransferredProfile } from './saves/transferred-profile.ts';
export { loadGroundAiTuning, type GroundAiTuning } from './tuning/ground-ai-tuning.ts';
export { readLauncherTuning, writeLauncherTuning, type LauncherTuningPatch } from './tuning/launcher-tuning.ts'; export { readLauncherTuning, writeLauncherTuning, type LauncherTuningPatch } from './tuning/launcher-tuning.ts';
export { multiVehiclePackIds } from './store/store-pack-ids.ts'; export { multiVehiclePackIds } from './store/store-pack-ids.ts';
@@ -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';
@@ -24,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]> {
@@ -85,6 +87,11 @@ 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]!,
@@ -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);
} }
} }
+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);
}
@@ -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) {
+168 -35
View File
@@ -1,14 +1,16 @@
/** /**
* 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';
import { BattleMatchmaker } from './battle/battle-matchmaker.ts'; import { BattleMatchmaker } from './battle/battle-matchmaker.ts';
import { BattleSessionStore } from './battle/battle-session-store.ts'; import { BattleSessionStore } from './battle/battle-session-store.ts';
import { selectBotAircraftLoadouts } from './battle/bot-aircraft-loadouts.ts'; import { selectBotAircraftLoadouts } from './battle/bot-aircraft-loadouts.ts';
import { selectBotTankLoadouts } from './battle/bot-tank-loadouts.ts';
import { actionTable } from './char/actions/action-table.ts'; import { actionTable } from './char/actions/action-table.ts';
import { CharService } from './char/char-service.ts'; import { CharService } from './char/char-service.ts';
import { ClanStore } from './clans/clan-store.ts'; import { ClanStore } from './clans/clan-store.ts';
@@ -16,7 +18,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';
@@ -30,12 +32,14 @@ import { DatasetCache } from './game-data/datasets/dataset-cache.ts';
import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts'; 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 { tankBotAmmo } from './game-data/datasets/tank-bot-ammo.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 +53,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 +73,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) ?? []),
@@ -108,12 +175,28 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
}, report); }, report);
const webUi = new WebUiService(datasets.load(webIcons), labels, options.dataFolder, artwork); const webUi = new WebUiService(datasets.load(webIcons), labels, options.dataFolder, artwork);
const botAircraftLoadouts = selectBotAircraftLoadouts(vehicles, datasets.load(flightModelPresets), equipment); const botAircraftLoadouts = selectBotAircraftLoadouts(vehicles, datasets.load(flightModelPresets), equipment);
const botTankLoadouts = tuning.groundAi.mode === 'stock'
? undefined
: selectBotTankLoadouts(vehicles, datasets.load(tankBotAmmo), tuning.groundAi.loadout);
gameFiles.releasePacks(); gameFiles.releasePacks();
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,
tuning.groundAi.mode === 'stock' ? undefined : tuning.groundAi.lineupWeights,
botTankLoadouts,
(ctx) => modRuntime.runBattleFilterMissions(ctx),
);
const economy = new BattleEconomy( const economy = new BattleEconomy(
economyData, economyData,
tuning.battleEconomy, tuning.battleEconomy,
@@ -124,7 +207,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 +247,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 +318,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);
}
}
+302
View File
@@ -0,0 +1,302 @@
/**
* Typed, range-validated reader for `tuning/ground-ai.jsonc`.
*/
import type { DiscoveredMod } from '@wto/mods';
import { GROUND_AI_MODES, type GroundAiConfig, type GroundAiMode } from '@wto/patcher';
import type { TankLineupWeights } from '../battle/battle-ranks.ts';
import { tuningFiles } from './tuning-loader.ts';
import { TuningError, type TuningReader } from './tuning-reader.ts';
export interface GroundAiTuning extends GroundAiConfig {
/** Tank pool weights by class, used only when a custom ground AI mode is active. */
readonly lineupWeights: TankLineupWeights;
}
const DRIVE_MODES = new Set(['vehicle_phys', 'movesys']);
export function loadGroundAiTuning(
dataFolder: string | null,
report: (line: string) => void,
mods: readonly DiscoveredMod[] = [],
): GroundAiTuning {
return readGroundAiTuning(tuningFiles(dataFolder, report, undefined, mods).read('ground-ai'));
}
export function readGroundAiTuning(reader: TuningReader): GroundAiTuning {
const cadence = reader.object('cadence');
const diag = reader.object('diagnostics');
return {
mode: readMode(reader),
loadout: readLoadoutSection(reader.object('loadout')),
lineupWeights: readLineupWeights(reader.object('lineupWeights')),
cadence: {
maxBots: cadence.int('maxBots', { min: 1, max: 64 }),
macroTickSec: cadence.number('macroTickSec', { min: 0.1, max: 5 }),
tacticsTickSec: cadence.number('tacticsTickSec', { min: 0.05, max: 2 }),
navTickSec: cadence.number('navTickSec', { min: 0.05, max: 2 }),
},
commander: readCommanderSection(reader.object('commander')),
macro: readMacroSection(reader.object('macro')),
crowd: readCrowdSection(reader.object('crowd')),
terrain: readTerrainSection(reader.object('terrain')),
navigation: readNavigationSection(reader.object('navigation')),
perception: readPerceptionSection(reader.object('perception')),
stateMachine: readStateMachineSection(reader.object('stateMachine')),
tactics: readTacticsSection(reader.object('tactics')),
estimation: readEstimationSection(reader.object('estimation')),
fireControl: readFireControlSection(reader.object('fireControl')),
diagnostics: {
telemetry: diag.bool('telemetry'),
telemetryIntervalSec: diag.number('telemetryIntervalSec', { min: 0.5, max: 60 }),
},
};
}
function readMode(reader: TuningReader): GroundAiMode {
const mode = reader.string('mode');
const known = GROUND_AI_MODES.find((candidate) => candidate === mode);
if (known === undefined) {
throw new TuningError(`tuning file ground-ai.jsonc: mode must be one of ${GROUND_AI_MODES.map((m) => `"${m}"`).join(', ')} (found "${mode}")`);
}
return known;
}
function readLoadoutSection(loadout: TuningReader): GroundAiTuning['loadout'] {
return {
lowReadyRackThreshold: loadout.int('lowReadyRackThreshold', { min: 1, max: 60 }),
topUpAmmoCount: loadout.int('topUpAmmoCount', { min: 4, max: 80 }),
primaryAmmoPct: loadout.int('primaryAmmoPct', { min: 50, max: 100 }),
secondaryMinRounds: loadout.int('secondaryMinRounds', { min: 0, max: 20 }),
penetrationCompareDistM: loadout.int('penetrationCompareDistM', { min: 100, max: 2000 }),
};
}
function readLineupWeights(weights: TuningReader): TankLineupWeights {
const range = { min: 0.01, max: 10 };
return {
spaa: weights.number('spaa', range),
lightTank: weights.number('lightTank', range),
tankDestroyer: weights.number('tankDestroyer', range),
heavyTank: weights.number('heavyTank', range),
mediumTank: weights.number('mediumTank', range),
other: weights.number('other', range),
};
}
function readCommanderSection(cmd: TuningReader): GroundAiTuning['commander'] {
const pct = { min: 0, max: 100 };
const bttlAssaultPct = cmd.int('bttlAssaultPct', pct);
const bttlFlankPct = cmd.int('bttlFlankPct', pct);
const bttlOverwatchPct = cmd.int('bttlOverwatchPct', pct);
if (bttlAssaultPct + bttlFlankPct + bttlOverwatchPct > 100) {
throw new TuningError('tuning file ground-ai.jsonc: commander Bttl percentages must sum to <= 100');
}
const conqAssaultPct = cmd.int('conqAssaultPct', pct);
const conqFlankPct = cmd.int('conqFlankPct', pct);
if (conqAssaultPct + conqFlankPct > 100) {
throw new TuningError('tuning file ground-ai.jsonc: commander Conq assault + flank percentages must sum to <= 100');
}
const conqHoldDefendPct = cmd.int('conqHoldDefendPct', pct);
const conqHoldOverwatchPct = cmd.int('conqHoldOverwatchPct', pct);
if (conqHoldDefendPct + conqHoldOverwatchPct > 100) {
throw new TuningError('tuning file ground-ai.jsonc: commander Conq hold percentages must sum to <= 100');
}
return {
rebalanceSec: cmd.number('rebalanceSec', { min: 1.0, max: 30.0 }),
roleHoldSec: cmd.number('roleHoldSec', { min: 0.0, max: 120.0 }),
bttlAssaultPct,
bttlFlankPct,
bttlOverwatchPct,
conqAssaultPct,
conqFlankPct,
conqHoldDefendPct,
conqHoldOverwatchPct,
domAssaultPct: cmd.int('domAssaultPct', pct),
domMaxDefendersPerCap: cmd.int('domMaxDefendersPerCap', { min: 0, max: 4 }),
overwatchStandOffM: cmd.number('overwatchStandOffM', { min: 25.0, max: 350.0 }),
flankStandOffM: cmd.number('flankStandOffM', { min: 25.0, max: 300.0 }),
spaaFollowOffsetM: cmd.number('spaaFollowOffsetM', { min: 40.0, max: 500.0 }),
flankMaxLengthRatio: cmd.number('flankMaxLengthRatio', { min: 1.05, max: 3.0 }),
flankMinSeparationM: cmd.number('flankMinSeparationM', { min: 15.0, max: 200.0 }),
rallyProgressFrac: cmd.number('rallyProgressFrac', { min: 0.1, max: 0.75 }),
rallyWaitSec: cmd.number('rallyWaitSec', { min: 3.0, max: 60.0 }),
rallyMinFrac: cmd.number('rallyMinFrac', { min: 0.25, max: 1.0 }),
rallyRadiusM: cmd.number('rallyRadiusM', { min: 15.0, max: 140.0 }),
recallSafeHoldSec: cmd.number('recallSafeHoldSec', { min: 3.0, max: 60.0 }),
};
}
function readMacroSection(macro: TuningReader): GroundAiTuning['macro'] {
const recaptureMinBots = macro.int('recaptureMinBots', { min: 1, max: 8 });
const recaptureMaxBots = macro.int('recaptureMaxBots', { min: 1, max: 12 });
if (recaptureMaxBots < recaptureMinBots) {
throw new TuningError('tuning file ground-ai.jsonc: macro.recaptureMaxBots must be >= macro.recaptureMinBots');
}
return {
openingSplitSec: macro.number('openingSplitSec', { min: 0, max: 180 }),
capMaxInsiders: macro.int('capMaxInsiders', { min: 1, max: 8 }),
recaptureMinBots,
recaptureMaxBots,
capStickyBonusM: macro.number('capStickyBonusM', { min: 0, max: 800 }),
deathZoneRadiusM: macro.number('deathZoneRadiusM', { min: 10, max: 250 }),
deathZoneTtlSec: macro.number('deathZoneTtlSec', { min: 5, max: 300 }),
deathZoneMinKills: macro.int('deathZoneMinKills', { min: 1, max: 16 }),
spaaRearOffsetM: macro.number('spaaRearOffsetM', { min: 40, max: 600 }),
spaaRelocateSec: macro.number('spaaRelocateSec', { min: 5, max: 180 }),
enemySpawnAvoidM: macro.number('enemySpawnAvoidM', { min: 60, max: 600 }),
};
}
function readCrowdSection(crowd: TuningReader): GroundAiTuning['crowd'] {
return {
personalSpaceM: crowd.number('personalSpaceM', { min: 6, max: 40 }),
clusterRadiusM: crowd.number('clusterRadiusM', { min: 12, max: 80 }),
clusterMaxAllies: crowd.int('clusterMaxAllies', { min: 1, max: 10 }),
disperseStepM: crowd.number('disperseStepM', { min: 8, max: 65 }),
disperseHoldSec: crowd.number('disperseHoldSec', { min: 1, max: 15 }),
};
}
function readTerrainSection(terrain: TuningReader): GroundAiTuning['terrain'] {
return {
maxClimbSlopeDeg: terrain.number('maxClimbSlopeDeg', { min: 10, max: 42 }),
maxDropSlopeDeg: terrain.number('maxDropSlopeDeg', { min: 8, max: 40 }),
maxWaterDepthM: terrain.number('maxWaterDepthM', { min: 0.2, max: 2.5 }),
collisionMarginM: terrain.number('collisionMarginM', { min: 0.05, max: 2.0 }),
crestLookaheadM: terrain.number('crestLookaheadM', { min: 8, max: 80 }),
ridgeMaxDwellSec: terrain.number('ridgeMaxDwellSec', { min: 2, max: 60 }),
ridgeMaxShots: terrain.int('ridgeMaxShots', { min: 1, max: 10 }),
};
}
function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation'] {
const driveMode = nav.string('driveMode');
if (!DRIVE_MODES.has(driveMode)) {
throw new TuningError(`tuning file ground-ai.jsonc: navigation.driveMode must be "vehicle_phys" or "movesys" (found "${driveMode}")`);
}
const steerSign = nav.number('steerSign', { min: -1, max: 1 });
if (steerSign !== 1 && steerSign !== -1) {
throw new TuningError('tuning file ground-ai.jsonc: navigation.steerSign must be 1 or -1');
}
return {
driveMode,
maxPhysBots: nav.int('maxPhysBots', { min: 0, max: 64 }),
steerSign,
deadEchoSec: nav.number('deadEchoSec', { min: 0.3, max: 10 }),
controlTimeoutSec: nav.number('controlTimeoutSec', { min: 0.3, max: 10 }),
cornerBrakeAccel: nav.number('cornerBrakeAccel', { min: 0.5, max: 8 }),
pivotAngleDeg: nav.number('pivotAngleDeg', { min: 25, max: 150 }),
stuckWindowSec: nav.number('stuckWindowSec', { min: 1, max: 15 }),
stuckMinMoveM: nav.number('stuckMinMoveM', { min: 0.5, max: 10 }),
unstickReverseSec: nav.number('unstickReverseSec', { min: 0.8, max: 10 }),
tacticalReverseDistM: nav.number('tacticalReverseDistM', { min: 10, max: 90 }),
tacticalReverseMaxSec: nav.number('tacticalReverseMaxSec', { min: 2, max: 25 }),
};
}
function readPerceptionSection(perc: TuningReader): GroundAiTuning['perception'] {
return {
foliageTransparency: perc.number('foliageTransparency', { min: 0.001, max: 1.0 }),
nearSpotRangeM: perc.number('nearSpotRangeM', { min: 20, max: 250 }),
firingSpotRangeM: perc.number('firingSpotRangeM', { min: 150, max: 1500 }),
fastSpotSec: perc.number('fastSpotSec', { min: 0.05, max: 1.5 }),
normalSpotSec: perc.number('normalSpotSec', { min: 0.1, max: 3.0 }),
farSpotSec: perc.number('farSpotSec', { min: 0.3, max: 6.0 }),
decayPerSec: perc.number('decayPerSec', { min: 0.2, max: 10.0 }),
frontConeHalfDeg: perc.number('frontConeHalfDeg', { min: 10, max: 90 }),
peripheralCloseM: perc.number('peripheralCloseM', { min: 30, max: 250 }),
};
}
function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine'] {
const coverMinDistM = sm.number('coverMinDistM', { min: 2.0, max: 30.0 });
const coverMaxDistM = sm.number('coverMaxDistM', { min: 6.0, max: 80.0 });
if (coverMaxDistM <= coverMinDistM) {
throw new TuningError('tuning file ground-ai.jsonc: stateMachine.coverMaxDistM must be > coverMinDistM');
}
return {
preaimAngleDeg: sm.number('preaimAngleDeg', { min: 1.0, max: 30.0 }),
shortHaltMaxSec: sm.number('shortHaltMaxSec', { min: 0.5, max: 12.0 }),
shortHaltCooldownSec: sm.number('shortHaltCooldownSec', { min: 0.5, max: 20.0 }),
turnLaunchSpeedMps: sm.number('turnLaunchSpeedMps', { min: 0.5, max: 6.0 }),
coverMinDistM,
coverMaxDistM,
coverRetreatBudgetSec: sm.number('coverRetreatBudgetSec', { min: 1.5, max: 20.0 }),
reloadAdvanceAngleDeg: sm.number('reloadAdvanceAngleDeg', { min: 0.0, max: 45.0 }),
hullAngleTriggerDeg: sm.number('hullAngleTriggerDeg', { min: 15.0, max: 75.0 }),
hullAngleTargetDeg: sm.number('hullAngleTargetDeg', { min: 0.0, max: 35.0 }),
maxTotalHaltSec: sm.number('maxTotalHaltSec', { min: 3.0, max: 40.0 }),
stalemateMissShots: sm.int('stalemateMissShots', { min: 1, max: 8 }),
stalemateNoShotHalts: sm.int('stalemateNoShotHalts', { min: 1, max: 6 }),
repositionMinMoveM: sm.number('repositionMinMoveM', { min: 5.0, max: 80.0 }),
repositionStepM: sm.number('repositionStepM', { min: 15.0, max: 120.0 }),
repairSafeEnemyDistM: sm.number('repairSafeEnemyDistM', { min: 30.0, max: 400.0 }),
};
}
function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] {
return {
visionRangeM: tactics.number('visionRangeM', { min: 200, max: 3500 }),
visionFovDeg: tactics.number('visionFovDeg', { min: 40, max: 180 }),
peripheralRangeM: tactics.number('peripheralRangeM', { min: 30, max: 800 }),
engineAudioRangeM: tactics.number('engineAudioRangeM', { min: 10, max: 250 }),
shotAudioRangeM: tactics.number('shotAudioRangeM', { min: 50, max: 1200 }),
radioShareRangeM: tactics.number('radioShareRangeM', { min: 50, max: 1500 }),
memoryTtlSec: tactics.number('memoryTtlSec', { min: 1, max: 45 }),
targetStickinessSec: tactics.number('targetStickinessSec', { min: 0.5, max: 20 }),
peekCooldownSec: tactics.number('peekCooldownSec', { min: 1, max: 30 }),
};
}
function readEstimationSection(est: TuningReader): GroundAiTuning['estimation'] {
const watchMinSec = est.number('watchMinSec', { min: 0.5, max: 10.0 });
const watchMaxSec = est.number('watchMaxSec', { min: 1.0, max: 15.0 });
if (watchMaxSec < watchMinSec) {
throw new TuningError('tuning file ground-ai.jsonc: estimation.watchMaxSec must be >= watchMinSec');
}
const velSampleMinSpanSec = est.number('velSampleMinSpanSec', { min: 0.05, max: 2.0 });
const velStableSpanSec = est.number('velStableSpanSec', { min: 0.2, max: 6.0 });
if (velStableSpanSec <= velSampleMinSpanSec) {
throw new TuningError('tuning file ground-ai.jsonc: estimation.velStableSpanSec must be > velSampleMinSpanSec');
}
return {
watchMinSec,
watchMaxSec,
velSampleMinSpanSec,
velStableSpanSec,
velJumpResetMps: est.number('velJumpResetMps', { min: 1.0, max: 20.0 }),
baseAimSigmaM: est.number('baseAimSigmaM', { min: 0.0, max: 2.0 }),
leadErrorFrac: est.number('leadErrorFrac', { min: 0.0, max: 1.0 }),
maxBiasM: est.number('maxBiasM', { min: 0.0, max: 6.0 }),
};
}
function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl'] {
const closeRangeM = fc.number('closeRangeM', { min: 30, max: 250 });
const midRangeM = fc.number('midRangeM', { min: 100, max: 600 });
const longRangeM = fc.number('longRangeM', { min: 300, max: 1500 });
if (midRangeM <= closeRangeM || longRangeM <= midRangeM) {
throw new TuningError('tuning file ground-ai.jsonc: fireControl ranges must satisfy closeRangeM < midRangeM < longRangeM');
}
return {
maxEngageRangeM: fc.number('maxEngageRangeM', { min: 150, max: 3000 }),
closeRangeM,
midRangeM,
longRangeM,
midSlowSpeedRatio: fc.number('midSlowSpeedRatio', { min: 0.1, max: 1.0 }),
midSlowMaxMps: fc.number('midSlowMaxMps', { min: 1.0, max: 15.0 }),
stopSpeedMaxMps: fc.number('stopSpeedMaxMps', { min: 0.1, max: 2.0 }),
longRangeWindowSec: fc.number('longRangeWindowSec', { min: 1.0, max: 15.0 }),
baseAlignDeg: fc.number('baseAlignDeg', { min: 0.1, max: 3.0 }),
closeHitRadiusM: fc.number('closeHitRadiusM', { min: 0.25, max: 2.2 }),
barrelSettleDegSec: fc.number('barrelSettleDegSec', { min: 0.2, max: 12.0 }),
closeSettleHoldSec: fc.number('closeSettleHoldSec', { min: 0.02, max: 0.5 }),
settleHoldSec: fc.number('settleHoldSec', { min: 0.05, max: 1.5 }),
unstabilizedStopSpeedMps: fc.number('unstabilizedStopSpeedMps', { min: 0.1, max: 3.0 }),
stabilizedCreepSpeedMps: fc.number('stabilizedCreepSpeedMps', { min: 1.5, max: 15.0 }),
friendlyCorridorM: fc.number('friendlyCorridorM', { min: 1.0, max: 10.0 }),
ballisticStepMaxM: fc.number('ballisticStepMaxM', { min: 5.0, max: 80.0 }),
ballisticSweepRadiusM: fc.number('ballisticSweepRadiusM', { min: 0.02, max: 0.5 }),
maxPreFireChecksPerTick: fc.int('maxPreFireChecksPerTick', { min: 1, max: 16 }),
};
}
@@ -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);
}
+10 -2
View File
@@ -13,6 +13,8 @@ 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 { readGroundAiTuning, type GroundAiTuning } from './ground-ai-tuning.ts';
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';
@@ -28,11 +30,16 @@ export interface Tuning {
readonly clans: ClanTuning; readonly clans: ClanTuning;
readonly battle: BattleTuning; readonly battle: BattleTuning;
readonly battleEconomy: BattleEconomyTuning; readonly battleEconomy: BattleEconomyTuning;
readonly groundAi: GroundAiTuning;
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')),
@@ -45,6 +52,7 @@ export function loadTuning(dataFolder: string, report: (line: string) => void):
clans: readClanTuning(files.read('clans')), clans: readClanTuning(files.read('clans')),
battle: readBattleTuning(files.read('battle')), battle: readBattleTuning(files.read('battle')),
battleEconomy: readBattleEconomyTuning(files.read('battle-economy')), battleEconomy: readBattleEconomyTuning(files.read('battle-economy')),
groundAi: readGroundAiTuning(files.read('ground-ai')),
limits: readLimitsTuning(files.read('limits')), limits: readLimitsTuning(files.read('limits')),
}; };
} }
+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
} }
+196
View File
@@ -0,0 +1,196 @@
// Ground battle AI configuration.
// Per-client overrides live in <dataDir>/tuning/ground-ai.jsonc. The game copy build compiles the
// layer settings into game/wtoai/wto_ai_config_common.das; the local server reads lineupWeights.
{
// "full": every custom layer (default).
// "fire": stock movement and destinations, custom perception and fire permission.
// "drive": custom team orders and driving, stock aiming and firing (debugging).
// "stock": stock AI only, no scripts packed, stock lineup weights (troubleshooting).
"mode": "full",
// AI tank spawn ammunition selection (offline values; ignored in "stock" mode).
// Carries first-stage / autoloader ready-rack capacity, topped up when below threshold,
// split between best anti-armor primary (APFSDS preferred) and HE/HEAT secondary when available.
"loadout": {
"lowReadyRackThreshold": 15,
"topUpAmmoCount": 22,
"primaryAmmoPct": 80,
"secondaryMinRounds": 3,
"penetrationCompareDistM": 500
},
// Relative pick weights of AI tank classes in a battle's bot pool. Offline values; ignored in
// "stock" mode, where every vehicle keeps the stock weight of 1.
"lineupWeights": {
"spaa": 0.12,
"lightTank": 0.45,
"tankDestroyer": 0.55,
"heavyTank": 0.85,
"mediumTank": 1.15,
"other": 1.0
},
"cadence": {
"maxBots": 64,
"macroTickSec": 0.5,
"tacticsTickSec": 0.25,
"navTickSec": 0.2
},
// Team commander role quotas and timing (offline values).
"commander": {
"rebalanceSec": 5.0,
"roleHoldSec": 20.0,
"bttlAssaultPct": 45,
"bttlFlankPct": 15,
"bttlOverwatchPct": 20,
"conqAssaultPct": 50,
"conqFlankPct": 20,
"conqHoldDefendPct": 30,
"conqHoldOverwatchPct": 30,
"domAssaultPct": 70,
"domMaxDefendersPerCap": 1,
"overwatchStandOffM": 95.0,
"flankStandOffM": 75.0,
"spaaFollowOffsetM": 160.0,
"flankMaxLengthRatio": 1.6,
"flankMinSeparationM": 45.0,
"rallyProgressFrac": 0.40,
"rallyWaitSec": 25.0,
"rallyMinFrac": 0.66,
"rallyRadiusM": 55.0,
"recallSafeHoldSec": 15.0
},
"macro": {
"openingSplitSec": 40.0,
"capMaxInsiders": 2,
"recaptureMinBots": 2,
"recaptureMaxBots": 4,
"capStickyBonusM": 165.0,
"deathZoneRadiusM": 55.0,
"deathZoneTtlSec": 60.0,
"deathZoneMinKills": 3,
"spaaRearOffsetM": 185.0,
"spaaRelocateSec": 28.0,
"enemySpawnAvoidM": 180.0
},
"crowd": {
"personalSpaceM": 14.0,
"clusterRadiusM": 28.0,
"clusterMaxAllies": 2,
"disperseStepM": 24.0,
"disperseHoldSec": 4.2
},
"terrain": {
"maxClimbSlopeDeg": 25.0,
"maxDropSlopeDeg": 20.0,
"maxWaterDepthM": 0.6,
"collisionMarginM": 0.3,
"crestLookaheadM": 28.0,
"ridgeMaxDwellSec": 10.0,
"ridgeMaxShots": 2
},
"navigation": {
// "vehicle_phys" uses custom inputs with native ownership. "movesys" keeps stock movement.
"driveMode": "vehicle_phys",
"maxPhysBots": 64,
"steerSign": 1.0,
"deadEchoSec": 1.2,
"controlTimeoutSec": 1.0,
"cornerBrakeAccel": 1.75,
"pivotAngleDeg": 75.0,
"stuckWindowSec": 3.6,
"stuckMinMoveM": 2.0,
"unstickReverseSec": 3.0,
"tacticalReverseDistM": 34.0,
"tacticalReverseMaxSec": 9.5
},
// Exposure-based visual perception (offline values; foliageTransparency matches stock infantry AI).
"perception": {
"foliageTransparency": 0.01,
"nearSpotRangeM": 90.0,
"firingSpotRangeM": 650.0,
"fastSpotSec": 0.25,
"normalSpotSec": 0.60,
"farSpotSec": 1.45,
"decayPerSec": 1.5,
"frontConeHalfDeg": 30.0,
"peripheralCloseM": 100.0
},
// Per-bot hull state machine timings and thresholds (offline values).
"stateMachine": {
"preaimAngleDeg": 8.0,
"shortHaltMaxSec": 3.0,
"shortHaltCooldownSec": 4.0,
"turnLaunchSpeedMps": 2.1,
"coverMinDistM": 6.0,
"coverMaxDistM": 24.0,
"coverRetreatBudgetSec": 6.0,
"reloadAdvanceAngleDeg": 18.0,
"hullAngleTriggerDeg": 30.0,
"hullAngleTargetDeg": 15.0,
"maxTotalHaltSec": 12.0,
"stalemateMissShots": 2,
"stalemateNoShotHalts": 2,
"repositionMinMoveM": 20.0,
"repositionStepM": 48.0,
"repairSafeEnemyDistM": 140.0
},
"tactics": {
"visionRangeM": 1250.0,
"visionFovDeg": 115.0,
"peripheralRangeM": 230.0,
"engineAudioRangeM": 65.0,
"shotAudioRangeM": 380.0,
"radioShareRangeM": 450.0,
"memoryTtlSec": 12.0,
"targetStickinessSec": 4.5,
"peekCooldownSec": 6.0
},
// Target velocity estimation from own visual samples, last-seen watch, and bounded shot bias.
"estimation": {
"watchMinSec": 2.0,
"watchMaxSec": 5.0,
"velSampleMinSpanSec": 0.25,
"velStableSpanSec": 1.2,
"velJumpResetMps": 4.5,
"baseAimSigmaM": 0.28,
"leadErrorFrac": 0.26,
"maxBiasM": 2.2
},
"fireControl": {
"maxEngageRangeM": 1250.0,
"closeRangeM": 100.0,
"midRangeM": 300.0,
"longRangeM": 800.0,
"midSlowSpeedRatio": 0.45,
"midSlowMaxMps": 5.5,
"stopSpeedMaxMps": 0.45,
"longRangeWindowSec": 4.0,
"baseAlignDeg": 0.42,
"closeHitRadiusM": 0.85,
"barrelSettleDegSec": 1.8,
"closeSettleHoldSec": 0.08,
"settleHoldSec": 0.20,
"unstabilizedStopSpeedMps": 0.45,
"stabilizedCreepSpeedMps": 5.5,
"friendlyCorridorM": 3.2,
"ballisticStepMaxM": 25.0,
"ballisticSweepRadiusM": 0.12,
"maxPreFireChecksPerTick": 2
},
"diagnostics": {
"telemetry": false,
"telemetryIntervalSec": 5.0
}
}
+231 -19
View File
@@ -1,31 +1,243 @@
# Dev Docs # WTOffline Developer Documentation / 开发者文档
<a id="zh-cn"></a> <a id="zh-cn"></a>
简体中文 · [English](#english) 简体中文 · [English](#english) · [在线文档站](https://wto-project.net/dev-docs)
这是 WTOffline 的开发与贡献入口。请先准备一份自己持有的原版客户端,只读使用,并从 [主 README 的开发章节](../README.md#开发)安装工具和依赖。要启动游戏验证时,另备一份 Steam 游戏库之外的离线副本和独立的数据目录,先按[开发规范](development-rules.md#zh-cn)核实隔离。 欢迎参与 WTOffline 开发。本目录面向**项目贡献者、客户端新版本适配者,以及使用 AI 编程工具辅助逆向定位与编写代码的协作者**。无论你之前是否接触过 Dagor 引擎或《战争雷霆》客户端内部结构,都可以按本指南一步步上手。
| 要做的事 | 从这里开始 | > **如果你只是想制作载具属性魔改、自定义地图池、全新 3D 载具模型或服务端脚本模组**:你完全不需要修改 WTOffline 核心源码,请直接阅读 [模组开发文档(mod-dev-docs)](../mod-dev-docs/README.md) 或访问 [在线模组文档](https://wto-project.net/mod-docs)。
| --- | --- |
| 改启动器或安装流程 | [apps/launcher](../apps/launcher) |
| 改游戏规则、档案或本地服务 | [apps/server](../apps/server) |
| 改游戏副本的构建或补丁检查 | [packages/patcher](../packages/patcher)、[scripts](../scripts)、[tools](../tools) |
| 写客户端补丁或适配新的游戏版本 | [补丁指南](patches.md#zh-cn)和[补丁集](../patches) |
提交前按[自查清单](contributing.md#zh-cn)整理依据、运行适用的[检查命令](contributing.md#checks),并把检查结果和实机步骤写进 [PR 模板](templates/pull-request.md)。 ---
## 第一次来,建议按什么顺序读?
不要一上来就啃二进制补丁字段或反汇编地址。按下面三步顺读,大约 15–20 分钟就能建立完整的全局认知:
1. **[开发理念、架构分层与工程规范](development-rules.md#zh-cn)**(**必读第一站**):搞清楚启动器、单端口本地模拟服务器(`apps/server`)与进程内网络/对局桥接库(`wto_ws.dll`)是如何协同工作的;顺着一个真实的 `cln_set_researchable` 动作看懂服务端四层代码怎么流转;掌握「三类数值放哪里」「好代码 vs 坏代码」真实对比,以及可直接复制给 AI 编程助手的工程约束提示词。
2. **[补丁编写与新版本适配指南](patches.md#zh-cn)**:当确认本地服务器与原版配置确实无法解决问题、必须修改客户端时,按这篇手把手教程拆包查看原版文件、用 `tools/re/cli.py` 反汇编定位,并对照完整无省略的 GUI(`patches/gui/`)、EXE(`patches/exe/`)和 Native(`patches/native/` + `native/wto-net/`)真实案例编写跨版本自适应补丁。
3. **[环境搭建、流量调试与提交自查](contributing.md#zh-cn)**:配齐本地开发环境,学会直接阅读 `<数据目录>/logs/` 下自动解码的明文 BLK 流量日志快速抓 Bug,按改动类型运行对应的必跑检查命令,并对照 [PR 模板](templates/pull-request.md) 提交高质量改动。
---
<a id="glossary-zh"></a>
## 核心概念与术语词典
在阅读后续文档或翻阅源码时,你会频繁遇到以下专有名词。这里用大白话一次性讲透:
### 1. `vromfs.bin`(Dagor 虚拟只读归档包)
《战争雷霆》不会把成千上万个零散脚本和配置文件直接摊在硬盘上,而是打包进若干个 `.vromfs.bin` 归档文件中。它在结构上分两层:外层是带简单异或混淆的 Zstandard(zstd)压缩容器、内部镜像 MD5 与末尾 256 字节签名;内层是文件表(全小写相对路径、偏移量、可选 SHA-1 摘要,以及可选的共享键名表 `nm` 与 `.dict` 压缩字典)。项目中的 `@wto/vromfs`(`readArchive` / `getFile` / `putFile` / `writeArchive`)负责无损读写这些归档包。
不同归档包各司其职,查数据时按下面这张表找最快:
| 归档包路径(相对于游戏根目录) | 里面装什么核心内容 | WTOffline 哪里会用到它 |
| --- | --- | --- |
| `char.vromfs.bin` | 科技树排布(`config/shop.blk`)、载具价格/研发点/修车费/改装件(`config/wpcost.blk`)、全局经济与分房公式(`config/warpoints.blk`、`config/rank.blk`)、初始档案模板(`config/default_user.blk`)、任务列表与成就解锁(`config/mislist.blk`、`config/pve_awards.blk`、`config/unlocks.blk`)、涂装/贴花/挂件/道具定义(`config/skins.blk`、`config/decals.blk`、`config/attachable.blk`、`config/items.blk`)以及 `config/network.blk` | `packages/patcher` 构建副本时改写服务地址与隐藏载具可见性;`apps/server` 启动时从中提取绝大部分静态经济与科技树数据集 |
| `aces.vromfs.bin` | 局内玩法与连杀支援规则(`config/gameplay.blk`)、界面与礼包 GUID 映射(`config/gui.blk`)、工坊配方(`config/workshop.blk`)以及全部载具的气动/损伤/武器预设模型(`gamedata/flightmodels/…`、`gamedata/units/…`) | `packages/patcher` 写入本地商店礼包 GUID;`apps/server` 提取对局出生规则、礼包映射与载具武器预设 |
| `gui.vromfs.bin` | 客户端全部机库、弹窗、商店、战后结算与 HUD 界面的 Quirrel 脚本(`scripts/**/*.nut`)与布局模板(`.blk` / `.css`) | `patches/gui/` 在构建副本时对少数客户端界面脚本做精确片段替换 |
| `mis.vromfs.bin` | 多人对战与单人任务的地图逻辑、出生点区域、战区与胜利条件定义(`gamedata/missions/**/*.blk`) | `apps/server` 启动时扫描提取多人任务目录(`multiplayer-missions` 数据集),用于匹配开局 |
| `lang.vromfs.bin` | 分号分隔的多语言本地化词条表(`lang/units.csv`、`lang/menu.csv`、`lang/unlocks_achievements.csv` 等) | `apps/server` 提取载具、国家与物品的多语言显示名称,供本地网页商店、交易所和启动器展示 |
| `ui/atlases.vromfs.bin` | 科技树载具剪影与阵营国旗等矢量图标(`gameuiskin/*.svg`) | `apps/server` 按需提取金币车/礼包车/市场车图标与国旗(`web-icons` 数据集)供游戏内嵌网页商店渲染 |
| `ui/images.vromfs.bin` | 界面位图插画、礼包封面与飞行员头像贴图(`images/**`) | `apps/server` 为内嵌网页商店展示商品封面,并为启动器存档页渲染玩家头像 |
### 2. `BLK` / `DataBlock`(Dagor 树状键值与块数据格式)
`BLK`(引擎 C++ 类名为 `DataBlock`)是贯穿整个游戏的通用配置与通信载体,结构类似「带严格值类型的树状 JSON」:每个节点既可以挂载带类型的参数(如整数 `:i`、浮点 `:r`、字符串 `:t`、布尔 `:b`、三维向量 `:p3`、矩阵 `:m` 等),也可以嵌套任意多层同名或异名子块。在 WTOffline 中你会见到它的四种形态,全部由 `@wto/blk`(`decodeBlk`、`encodeBlk`、`formatBlkText`、`parseBlkText`)统一处理:
- **归档包内的紧凑二进制 BLK**:`char.vromfs.bin` 与 `aces.vromfs.bin` 里的 `.blk` 通常将键名抽离到包内共享键名表 `nm`(甚至配合 `.dict` 字典做二次 zstd 压缩),解码时需传入 `SharedNameContext`;
- **`char` 协议单包二进制 BLK**:HTTP 响应体首字节带压缩标记(例如 `0x69` 即 `'i'` 表示未压缩二进制 BLK,另有 zlib / zstd 标记),后面紧跟自包含二进制 BLK;
- **`PBBD` 批处理流**:客户端上传云端键位与设置(`cln_bulk_set_gblk`)时使用的多段二进制容器(魔数 `"PBBD"`),每段内嵌独立 BLK 块;
- **本地存档自包含二进制 BLK**:`<数据目录>/saves/<userId>/profile.blk` 直接用 `encodeBlk()` 落盘,完整保留每个字段的原始值类型,避免整数与浮点数混淆导致客户端解析异常。
### 3. 本地模拟的四大 Gaijin 后端服务
原版联网客户端并不是只跟一台服务器通信,而是同时访问多套职责不同的后端服务。`apps/server` 在本机 `127.0.0.1:<端口>` 上把这四大核心服务全部接管并模拟:
- **`yuplay2`(登录与权益服务,`login/`、`store/`)**:处理客户端启动时的账号密码表单登录(`POST /login.php`),签发本地会话凭据与 `userId`,并提供商店礼包与激活码相关的 Web 接口;
- **`char`(角色档案服务器 Character Server,`char/`)**:机库阶段最核心的请求入口(原域名 `char-*.warthunder.com`)。客户端通过 HTTP 请求头 `action` 指明动作名(如 `cln_get_user_stat`、`cln_buy_aircraft`、`cln_set_researchable`、`cln_update`),通过 `uidhint` 指明当前账号,请求与响应主体以二进制 BLK 为主,负责完整玩家档案下发、科技树研发、买车买改装、乘员组训练、联队、云端键位设置及战后经济结算;
- **`matching`(匹配与开局二进制长连接服务,`matching/`)**:基于 TCP 的自定义二进制长连接协议(首字节固定为 `0x01`,9 字节包头 + LZ4 压缩负载,握手后启用流加密)。负责向客户端下发可用游戏模式列表、接收排队与小队状态,并在匹配成功时向客户端下发完整的对局启动参数(地图、天气、AI 名单、自定义计分参数等);
- **`inventory`(外部物品库与交易所服务,`inventory/`)**:模拟 `inventory-proxy-*.gaijin.net/char` 接口(动作名如 `GetInventory`、`GetItemDefsClient`、`GetItemPrices`、`GetItemDefChances`、`ExchangeItems`)。与 `char` 不同,客户端 `charsq` 模块直接将响应解析为 UTF-8 JSON,且要求关键响应附带 RSA 内容签名;用于驱动补给箱开箱、载具兑换券、工坊合成与本地模拟交易所。
### 4. `LocalMP`(为什么既要有 `apps/server`,又必须有 `wto_ws.dll`?)
初看代码库时最容易产生的疑问是:**既然已经用 Node.js 写了本地服务器 `apps/server`,为什么还要用 C 写一个 `native/wto-net/`(编译为 `wto_ws.dll`)注入进游戏进程?**
原因在于《战争雷霆》客户端与专用对局服务器(Dedicated Server)的代码裁剪边界:
- 原版零售客户端 `aces.exe` 内部其实保留了一套名为 **`LocalMP`(本地多人主机,`mp_is_host == 1 && mp_is_local_mp == 1`)** 的局内会话模式,能够在本机直接跑完整的物理引擎、弹道解算、损伤模型与 AI 驾驶逻辑,因此 WTOffline 不需要重写整套游戏物理服务器;
- **但是**,Gaijin 在编译零售版 `aces.exe` 时,把原本只在云端专用对局服务器上运行的大量「对局裁判(Host Referee)」处理逻辑裁掉了——包括:**响应玩家选车与挂载弹药并生成实体、允许 `BotSystem` 刷出 AI 载具、判定击杀/助攻/占点并往记分牌加分、陆战街机连杀空中支援事件生成、核弹落地直接判胜,以及过滤本不该发给受害者之外玩家的炮管/炮闩受损提示**;
- 因此两套组件分工明确、缺一不可:**`apps/server` 负责对局之外的一切**(登录、机库养成、商店市场、排队拼装任务配置、战后发银狮/研发点与存档持久化);而 **`wto_ws.dll` 在对局进行期间通过 MinHook 挂载在 `aces.exe` 进程内**,一方面把所有硬编码外网 Socket 连接重定向回 `127.0.0.1`,另一方面通过 `local_mp_*` 模块把被客户端裁掉的局内主机裁判逻辑原原本本补齐。
### 5. `Quirrel (.nut)` 与 `sq.exe` 字节码编译器
`gui.vromfs.bin` 中的 `.nut` 文件使用的是 Gaijin 基于 Squirrel 深度定制的强词法作用域脚本语言 **[Quirrel](https://quirrel.io/)**。客户端在玩家点击登录、进入机库前会一次性编译加载大批 `.nut` 脚本。
为什么修改 `patches/gui/` 后**不能只靠肉眼或普通语法树(AST)检查**,而需要用对应提交版本的原生编译器 `sq.exe` 跑 `wtotools check-gui`?因为 Quirrel 的 `compilestring` 字节码编译阶段会执行严格的词法绑定检查:
- 如果你在 `replace.nut` 里声明了一个 `local` 变量,恰好与该文件顶部 `from ... import *` 通配导入的某个全局常量重名;
- 或者在函数尚未定义/绑定前做了前向调用;
- 或者把 Quirrel 保留字(最典型的坑是 `base`)当成了普通变量名;
普通语法检查器都会放行,但真进游戏时 Quirrel 虚拟机就会直接中断模块加载,导致客户端**永远卡死在登录后的「正在加载…」转圈界面**。`wtotools check-gui` 会在内存中打上所有 GUI 补丁并逐个调用 `sq.exe` 编译字节码,把这类致命隐患在提交前 100% 拦住。
### 6. `RVA`、虚拟地址(`VA`)与进程运行时指针
在看 `patches/exe/`、`patches/native/` 或使用逆向工具时,务必分清这三种地址表示:
- **`VA`(Virtual Address,静态虚拟地址)**:Ghidra 或 IDA 打开 64 位 Windows 程序 `aces.exe` 时,默认镜像基址(`ImageBase`)是 `0x140000000`,因此反编译器里显示的函数地址往往长这样:`0x1412657a0`;
- **`RVA`(Relative Virtual Address,相对虚拟地址)**:减去镜像基址后的纯偏移,即 **`RVA = VA - ImageBase`**(例如 `0x1412657a0 - 0x140000000 = 0x12657a0`)。因为 Windows 的 ASLR(地址空间布局随机化)每次启动游戏都会把 `aces.exe` 加载到不同的内存基址,**仓库内所有补丁注释、`tools/re/cli.py` 参数以及生成的 `win64/wto_ws.cfg` 一律使用 RVA**;
- **运行时绝对指针(Runtime Pointer)**:游戏启动后,`wto_ws.dll`(见 `native/wto-net/src/local_mp_values.c`)通过 `(uint8_t *)GetModuleHandleW(NULL) + rva` 把 `wto_ws.cfg` 里的 RVA 换算成当次进程内的真实内存地址存入 `g_lmp`。
### 7. `features` 功能标签与三条「核心安全锁」(`ESSENTIAL_FEATURES`)
每个 `patches/exe/**/patch.jsonc`、`patches/gui/**/patch.jsonc` 和 `patches/native/*.jsonc` 都包含一个 `features` 字符串数组,标签以功能分组字母 `A-`..`K-` 开头(例如 `"G-Store"`、`"K-AI opponents and teammates"`、`"K-Kill, assist and capture scoring"`)。当游戏刚发布小版本更新、个别非关键补丁暂时失配时,启动器依靠这些标签清晰告知玩家「当前版本哪一项具体子功能暂不可用」,其余功能仍可正常游玩。
但其中有 **3 个定义在 `packages/patcher/src/essential-features.ts`(`ESSENTIAL_FEATURES`)中的硬阻断安全标签**例外:
1. **`A-Offline startup`**:离线副本能否启动的根基(例如跳过修改后 `.vromfs.bin` 的官方签名校验);
2. **`A-Isolation from the official game`**:与官方正版客户端的完全隔离(将用户配置存档改到独立 `WTOffline` 目录、注册表改到 `Software\WTOffline`、剥离反作弊启动器与崩溃上报);
3. **`A-No Gaijin connections`**:彻底阻断连向 Gaijin 官方服务器(例如将导入表 `WS2_32.dll` 替换为 `wto_ws.dll` 并在加载时强制挂载网络重定向钩子)。
只要带有上述任一标签的补丁未能成功定位和应用,`blockingFailures()` 就会**终止副本构建与启动**,防止离线客户端触碰玩家的线上正版数据或直连官方服务器,从而保护玩家的线上账号安全。
---
## 按你想做的事,直接定位代码目录
| 你想做什么 | 具体源码子目录 | 对口参考章节 |
| --- | --- | --- |
| 新增或修复机库动作路由(买车、研发、乘员、联队、贴花、战后结算等 `char` 接口) | `apps/server/src/char/actions/`(协议适配)+ `apps/server/src/<领域>/`(纯业务规则,如 `research/`、`modifications/`、`crew/`、`battle/`) | [架构分层与真实动作追踪](development-rules.md#server-layers-zh) |
| 修改玩家档案字段读写、新号初始资产或存档落盘格式 | `apps/server/src/profile/`、`apps/server/src/saves/`、`apps/server/src/storage/` | [存档层与原子写盘规范](development-rules.md#walkthrough-zh) |
| 从游戏原版数据包提取新的载具/经济/任务/本地化静态数据 | `apps/server/src/game-data/datasets/` | [三类数值与缓存数据集](development-rules.md#values-zh) |
| 调整离线版默认倍率、商店定价、补给箱权重、AI 重生数或上限参数 | `apps/server/tuning/*.jsonc` + `apps/server/src/tuning/` + 各领域 `*-tuning.ts` | [三类数值放哪里](development-rules.md#values-zh) |
| 修改本地内嵌网页商店、模拟交易所或服务器脚本模组运行时 | `apps/server/src/store/`、`apps/server/src/inventory/`、`apps/server/src/web-ui/`、`apps/server/src/mods/` | [服务器目录全景图](development-rules.md#server-layers-zh) |
| 修改桌面启动器界面、安装向导、存档管理页、模组管理页或更新器 | `apps/launcher/src/` | [检查命令清单](contributing.md#checks) |
| 修改离线副本构建管线、归档包改写、BLK 编解码、EXE 补丁引擎或模组加载器 | `packages/patcher/`、`packages/blk/`、`packages/vromfs/`、`packages/exepatch/`、`packages/mods/` | [仓库级单向依赖约定](development-rules.md#workspace-rule-zh) |
| 修改游戏内界面弹窗、按钮或结算页脚本(Quirrel `.nut`) | `patches/gui/<领域>/<名称>/` | [GUI 补丁完整范例](patches.md#gui-patches-zh) |
| 修改 `aces.exe` 机器码分支或只读常量字符串 | `patches/exe/<领域>/<名称>/` | [EXE 补丁 57 字节逐指令拆解](patches.md#exe-patches-zh) |
| 编写或修复 `wto_ws.dll` 局内 `LocalMP` 原生裁判钩子 | `patches/native/<模块>.jsonc` + `native/wto-net/src/` | [Native 模块 6 文件串联教程](patches.md#native-modules-zh) |
| 协助适配刚发布的《战争雷霆》客户端小版本更新 | `patches/versions/`、`scripts/record-game-version.ts` | [适配新版本客户端四步流程](patches.md#adapt-version-zh) |
---
<a id="english"></a> <a id="english"></a>
[简体中文](#zh-cn) · English [简体中文](#zh-cn) · English · [Online Docs](https://wto-project.net/dev-docs)
Start with a stock client you own and use it as a read-only source. Install the tools and dependencies listed in the [main README](../README.md#development). To launch the game for verification, prepare an offline copy outside the Steam library and a separate data directory, then verify isolation using the [development rules](development-rules.md#english). Welcome to WTOffline development. This directory is written for **project contributors, client build adapters, and collaborators using AI coding assistants to reverse-engineer, investigate, and fix issues**. Even if you have never worked with the Dagor Engine or War Thunder internals before, these guides walk you through every layer from first principles.
| Task | Start here | > **Just want to create vehicle stat tweaks, custom map pools, standalone 3D vehicles, or server script mods?** You do not need to modify WTOffline's core source code at all—head straight to the [Mod Development Docs (`mod-dev-docs`)](../mod-dev-docs/README.md#english) or the [online Mod Docs](https://wto-project.net/mod-docs).
| --- | --- |
| Change the launcher or installer | [apps/launcher](../apps/launcher) |
| 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) |
| Write a client patch or adapt a new game build | [Patch guide](patches.md#english) and the [patch set](../patches) |
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). ---
## Recommended Reading Order
Do not jump straight into raw byte patterns or disassembly offsets on your first visit. Reading the three core guides in this order builds the full mental model in 15–20 minutes:
1. **[Design Philosophy, Architecture & Engineering Rules](development-rules.md#english)** (**Start here**): Understand how the launcher, single-port local server (`apps/server`), and in-process Winsock/LocalMP bridge (`wto_ws.dll`) fit together; trace one real `cln_set_researchable` request end-to-end across all four server layers; learn where the three categories of numbers belong; review four real Good vs. Bad code comparisons; and grab the copy-paste prompt block for AI coding assistants.
2. **[Patch Authoring & Version Adaptation Guide](patches.md#english)**: Once you have confirmed that the local server and stock configuration genuinely cannot solve an issue, follow step-by-step instructions to unpack stock archives, disassemble `aces.exe` with `tools/re/cli.py`, and study un-elided real patches across `patches/gui/`, `patches/exe/`, and `patches/native/` + `native/wto-net/`.
3. **[Environment Setup, Traffic Debugging & PR Guide](contributing.md#english)**: Set up the Windows x64 toolchain, inspect auto-decoded readable BLK payloads under `<data-dir>/logs/` to pinpoint bugs in minutes, run the required verification commands for your change type, and fill out the [PR template](templates/pull-request.md).
---
<a id="glossary-en"></a>
## Core Concepts & Glossary
You will encounter these War Thunder and WTOffline terms throughout the codebase and documentation. Here is what each one means in plain language:
### 1. `vromfs.bin` (Dagor Virtual Read-Only File System Archive)
Instead of shipping tens of thousands of loose scripts and config files on disk, War Thunder bundles them into `.vromfs.bin` archives. Each archive has two layers: an outer container (Zstandard compression with lightweight XOR obfuscation, an MD5 digest of the inner image, and a 256-byte signature tail) and an inner image (a lowercase relative path table, byte offsets, optional SHA-1 digests, plus an optional shared name map `nm` and `.dict` zstd dictionary). `@wto/vromfs` (`readArchive`, `getFile`, `putFile`, `writeArchive`) reads and repacks these archives losslessly.
Use this lookup table whenever you need to find where a stock script, config, or asset lives:
| Archive path (relative to game root) | What it stores | How WTOffline uses it |
| --- | --- | --- |
| `char.vromfs.bin` | Tech-tree layout (`config/shop.blk`), per-vehicle prices, RP, repair costs, and modifications (`config/wpcost.blk`), global economy and BR formulas (`config/warpoints.blk`, `config/rank.blk`), new-account profile template (`config/default_user.blk`), mission lists and unlock definitions (`config/mislist.blk`, `config/pve_awards.blk`, `config/unlocks.blk`), camos/decals/decorators/classic items (`config/skins.blk`, `config/decals.blk`, `config/attachable.blk`, `config/items.blk`), and `config/network.blk` | `packages/patcher` rewrites backend URLs and hidden-vehicle visibility during copy builds; `apps/server` extracts most economy, tech-tree, unlock, and mission datasets from it at startup |
| `aces.vromfs.bin` | Match gameplay and killstreak rules (`config/gameplay.blk`), UI config and store bundle GUID mappings (`config/gui.blk`), workshop recipes (`config/workshop.blk`), and all vehicle flight/damage/weapon preset files (`gamedata/flightmodels/…`, `gamedata/units/…`) | `packages/patcher` injects offline store bundle GUIDs; `apps/server` extracts spawn rules, bundle mappings, and weapon presets |
| `gui.vromfs.bin` | All in-game hangar, modal, store, debriefing, and HUD Quirrel scripts (`scripts/**/*.nut`) and layout templates (`.blk` / `.css`) | `patches/gui/` applies minimal surgical text replacements to UI scripts when building the offline copy |
| `mis.vromfs.bin` | Multiplayer and single-player mission logic, spawn zones, capture points, and victory rules (`gamedata/missions/**/*.blk`) | `apps/server` scans it at startup (`multiplayer-missions` dataset) to build matchmaking mission definitions |
| `lang.vromfs.bin` | Semicolon-separated localization CSV tables (`lang/units.csv`, `lang/menu.csv`, `lang/unlocks_achievements.csv`, etc.) | `apps/server` extracts localized vehicle, country, and item names for the in-game web store, marketplace, and launcher |
| `ui/atlases.vromfs.bin` | Tech-tree vehicle silhouettes and country flags in SVG format (`gameuiskin/*.svg`) | `apps/server` extracts icons for gift/premium/market vehicles and flags (`web-icons` dataset) for the local web store and marketplace |
| `ui/images.vromfs.bin` | UI raster artwork, bundle cover images, and pilot avatar textures (`images/**`) | `apps/server` serves store/marketplace item artwork and renders player profile icons for the launcher's saves page |
### 2. `BLK` / `DataBlock` (Dagor Typed Hierarchical Data Format)
`BLK` (named `DataBlock` in Dagor Engine C++ code) is the typed tree format used everywhere in War Thunder for configs, network payloads, and player profiles. Think of it as a tree of named blocks and typed key-value parameters (`:i` integers, `:r` floats, `:t` strings, `:b` booleans, `:p3` 3D vectors, `:m` matrices, etc.). You will encounter four binary/wire representations in WTOffline, all handled by `@wto/blk` (`decodeBlk`, `encodeBlk`, `formatBlkText`, `parseBlkText`):
- **Slimmed binary BLK inside `.vromfs.bin`**: `.blk` files inside `char.vromfs.bin` and `aces.vromfs.bin` strip repeated key names into the archive's shared name map `nm` (and may compress payloads with an archive `.dict` zstd dictionary), decoded by passing `SharedNameContext` to `decodeBlk`;
- **Framed binary BLK on `char` HTTP exchanges**: Single-document HTTP payloads prefixed with a 1-byte compression marker (e.g., `0x69` / `'i'` for uncompressed binary BLK, or zlib/zstd markers);
- **`PBBD` batch streams**: Multi-chunk binary streams (magic `"PBBD"`) used by `online_storage` (`cln_bulk_set_gblk`) when uploading keybindings and cloud settings, where each chunk carries an embedded BLK block;
- **Self-contained binary BLK on disk**: Player profiles saved at `<data>/saves/<userId>/profile.blk` via `encodeBlk()`, preserving every parameter's exact scalar/vector type so the game client never misinterprets ints as floats or vice versa.
### 3. The Four Gaijin Backend Services Emulated Locally
A live War Thunder client talks to several distinct backend services rather than a single monolithic API. `apps/server` emulates all four locally on a single `127.0.0.1:<port>` listener:
- **`yuplay2` (Login & Entitlement APIs, `login/`, `store/`)**: Handles form-encoded credential sign-in (`POST /login.php`), issues local session tokens and `userId`s, and serves store/redeem-code web endpoints;
- **`char` (Character Server, `char/`)**: The primary hangar RPC service (`char-*.warthunder.com`). Requests specify the operation via the `action` HTTP header (such as `cln_get_user_stat`, `cln_buy_aircraft`, `cln_set_researchable`, `cln_update`) and identify the player via `uidhint`, exchanging binary BLK payloads for full profile sync, tech-tree research, vehicle/modification/crew purchases, squadrons, cloud settings, and post-battle settlement;
- **`matching` (Binary Matchmaking & Session RPC, `matching/`)**: A persistent binary TCP protocol (first byte `0x01`, 9-byte header + LZ4-compressed frame, stream-encrypted after handshake) that serves game-mode lists, manages queues and squad state, and dispatches complete battle launch configurations (map, weather, AI bot rosters, `customScoreParams`, etc.);
- **`inventory` (External Inventory & Marketplace Service, `inventory/`)**: Emulates `inventory-proxy-*.gaijin.net/char` (`GetInventory`, `GetItemDefsClient`, `GetItemPrices`, `GetItemDefChances`, `ExchangeItems`). Unlike `char`, the client's `charsq` subsystem parses raw HTTP bodies directly as UTF-8 JSON and verifies RSA content signatures—powering supply chests, vehicle coupons, workshop crafting, and the simulated marketplace.
### 4. `LocalMP` (Why WTOffline Needs Both `apps/server` AND `wto_ws.dll`)
A natural question for newcomers is: **If `apps/server` already emulates Gaijin's backend in TypeScript, why do we also compile `native/wto-net/` into `wto_ws.dll` and load it inside `aces.exe`?**
The answer comes down to what Gaijin kept vs. stripped in the retail game client:
- Retail `aces.exe` still contains an in-process **`LocalMP` session mode (`mp_is_host == 1 && mp_is_local_mp == 1`)** capable of running full physics, ballistics, damage models, and AI piloting/driving locally—meaning WTOffline does not have to reimplement a Dedicated Server physics engine from scratch;
- **However**, when building retail `aces.exe`, Gaijin compiled out many **Dedicated Server battle referee handlers** that normally run only in the cloud during live matches: **spawning player vehicles and weapon loadouts on selection, granting `BotSystem` permission to spawn AI vehicles, awarding kill/assist/capture scoreboard points, running Ground Arcade killstreak air events, triggering nuclear instant victories, and filtering barrel/breech/part-damage HUD notices so enemy hits are not misdelivered to the local player**;
- Consequently, the two halves have a crisp boundary: **`apps/server` owns everything before and after a battle** (login, hangar progression, economy, store/market, matchmaking setup, post-battle Silver Lions/RP settlement, and atomic save persistence), while **`wto_ws.dll` hooks `aces.exe` in-process via MinHook**—redirecting hardcoded outbound Winsock traffic to `127.0.0.1` and restoring stripped host-side referee logic **during** live `LocalMP` battles via modular `local_mp_*` bridges.
### 5. `Quirrel (.nut)` & the `sq.exe` Bytecode Compiler
UI scripts inside `gui.vromfs.bin` (`.nut` files) are written in **[Quirrel](https://quirrel.io/)**, Gaijin's Squirrel-derived scripting language with strict lexical scoping. When logging into the hangar, the client preloads and compiles UI script modules en masse.
Why is running `wtotools check-gui` with the matching `sq.exe` compiler mandatory whenever you touch `patches/gui/`, instead of eyeballing diffs or running an AST-only syntax check? Because Quirrel's `compilestring` bytecode compiler enforces lexical binding rules that AST parsers ignore:
- Declaring a `local` identifier that collides with a constant imported via `from ... import *` at the top of the file;
- Referencing an unbound local/module function before its declaration;
- Using a Quirrel reserved keyword (most notoriously `base`) as a variable name.
Any of those mistakes looks syntactically innocent on paper, yet aborts module compilation inside the game client and **freezes login indefinitely on the `"Loading..."` spinner**. `wtotools check-gui` applies every GUI patch in memory and compiles each modified `.nut` file to Quirrel bytecode via `sq.exe`, catching 100% of lexical and constant-binding errors before commit.
### 6. `RVA` vs. Virtual Address (`VA`) vs. Runtime Pointer
Keep these three address forms straight whenever you read disassembly or write `patches/`:
- **`VA` (Virtual Address)**: When you open 64-bit `aces.exe` in Ghidra or IDA, the default PE `ImageBase` is `0x140000000`, so addresses appear as `0x1412657a0`;
- **`RVA` (Relative Virtual Address)**: Offset from the image base, i.e., **`RVA = VA - ImageBase`** (`0x1412657a0 - 0x140000000 = 0x12657a0`). Because Windows ASLR loads `aces.exe` at a fresh random base address on every launch, **every `patches/` comment, `tools/re/cli.py` argument, and `win64/wto_ws.cfg` entry uses RVAs exclusively**;
- **Runtime Pointer**: When the game starts, `wto_ws.dll` (`native/wto-net/src/local_mp_values.c`) adds the live module base `(uint8_t *)GetModuleHandleW(NULL) + rva` and stores the resulting process pointer in `g_lmp`.
### 7. `features` Tags & the Three Essential Safety Locks (`ESSENTIAL_FEATURES`)
Every definition in `patches/exe/**/patch.jsonc`, `patches/gui/**/patch.jsonc`, and `patches/native/*.jsonc` lists one or more `features` tags prefixed by inventory category (`A-` through `K-`, such as `"G-Store"`, `"K-AI opponents and teammates"`, or `"K-Kill, assist and capture scoring"`). If a minor client update breaks an optional patch, the launcher uses these tags to show the player exactly which non-essential gameplay feature is degraded while still letting them play.
Three tags defined in `packages/patcher/src/essential-features.ts` (`ESSENTIAL_FEATURES`) are **hard-blocking safety locks**:
1. **`A-Offline startup`**: Required for the offline copy to boot at all (e.g., bypassing `.vromfs.bin` pack signature checks so modified archives load);
2. **`A-Isolation from the official game`**: Keeps the offline copy completely separate from the official client (redirecting user saves/settings to `WTOffline`, registry keys to `Software\WTOffline`, and disabling the anti-cheat launcher and crash reporter);
3. **`A-No Gaijin connections`**: Guarantees zero traffic reaches Gaijin's live servers (e.g., rewriting the PE import descriptor from `WS2_32.dll` to `wto_ws.dll` and enforcing Winsock redirection hooks on attach).
If **any** patch carrying one of these three tags fails to resolve, `blockingFailures()` immediately aborts copy installation and launch—protecting the player's official online installation and account from ever being touched.
---
## Jump Straight to Your Task
| What you want to do | Specific codebase directories | Primary reference |
| --- | --- | --- |
| Add or fix hangar actions (research, purchases, crews, squadrons, decals, post-battle settlement, etc.) | `apps/server/src/char/actions/` (wire handlers) + `apps/server/src/<domain>/` (pure rules: `research/`, `modifications/`, `crew/`, `battle/`, etc.) | [Server Layers & Action Walkthrough](development-rules.md#server-layers-en) |
| Change player profile fields, new-account defaults, or save persistence / format upgrades | `apps/server/src/profile/`, `apps/server/src/saves/`, `apps/server/src/storage/` | [Persistence & Atomic Writes](development-rules.md#walkthrough-en) |
| Extract new static vehicle, economy, mission, or localization data from stock archives | `apps/server/src/game-data/datasets/` | [Three Categories of Values](development-rules.md#values-en) |
| Adjust offline reward multipliers, store prices, supply-chest weights, AI respawn counts, or limits | `apps/server/tuning/*.jsonc` + `apps/server/src/tuning/` + `<domain>/*-tuning.ts` | [Three Categories of Values](development-rules.md#values-en) |
| Work on the in-game web store, simulated marketplace, or server script mod runtime | `apps/server/src/store/`, `apps/server/src/inventory/`, `apps/server/src/web-ui/`, `apps/server/src/mods/` | [Server Directory Map](development-rules.md#server-layers-en) |
| Change the desktop launcher UI, install wizard, saves manager, mods page, or auto-updater | `apps/launcher/src/` | [Required Check Commands](contributing.md#checks-en) |
| Modify copy building, archive patching, BLK/vromfs codecs, EXE patch engine, or mod loader | `packages/patcher/`, `packages/blk/`, `packages/vromfs/`, `packages/exepatch/`, `packages/mods/` | [Workspace Dependency Rule](development-rules.md#workspace-rule-en) |
| Patch in-game UI modals, buttons, or debriefing Quirrel scripts (`.nut`) | `patches/gui/<domain>/<name>/` | [GUI Patches Full Example](patches.md#gui-patches-en) |
| Patch machine instructions or constant `.rdata` strings in `aces.exe` | `patches/exe/<domain>/<name>/` | [EXE Patch 57-Byte Anatomy](patches.md#exe-patches-en) |
| Write or fix `wto_ws.dll` in-process `LocalMP` battle host hooks | `patches/native/<module>.jsonc` + `native/wto-net/src/` | [Native Modules 6-File Wiring](patches.md#native-modules-en) |
| Adapt WTOffline to a newly released minor War Thunder client build | `patches/versions/`, `scripts/record-game-version.ts` | [Adapting a New Client Build](patches.md#adapt-version-en) |
+254 -46
View File
@@ -1,79 +1,122 @@
# Contributing # 环境搭建、流量调试与提交指南 / Contributing Guide
<a id="zh-cn"></a> <a id="zh-cn"></a>
简体中文 · [English](#english) · [返回 Dev Docs](README.md#zh-cn) 简体中文 · [English](#english) · [返回 Dev Docs](README.md#zh-cn)
## 提交前自查 这篇指南带你从零搭好本地开发环境、用内置的自动解码流量日志快速定位机库与对局问题,并在发起 Pull Request 前跑通对应的真实工程检查。
- 改动只解决一个目标。实现、配置、补丁说明和相关开发文档一致。提交标题用英文 `type(scope): description`,scope 用小写模块名,仓库级改动用 `repo`。破坏兼容时用 `type(scope)!: description`,并在 `BREAKING CHANGE:` 脚注说明影响和处理方式。正文交代原因、依据和验证结果,代码注释也用英文。联署留给实际协作的开发者。 ---
- 游戏行为的判断有目标版本和一手出处。新动作写清客户端怎样发请求、怎样读取应答。客户端改动登记到对应补丁或构建模块,并说明为何需要。涉及新数值时,按[三类数值规则](development-rules.md#数值和数据来源)检查来源、配置和校验。
- 检查模块职责、依赖方向和重复逻辑。涉及账号、余额和档案时,检查错误输入、写盘顺序,以及多个账号之间的数据隔离。选择奖品或其他数据项时,按明确规则排序和筛选。
- 只做类型、补丁、构建和可运行检查。功能验收由人使用隔离副本在游戏里做。注明实际执行过的命令、对应版本和结果。还要实机核对时写出入口、操作和预期现象。商城或交易所改动覆盖内置浏览器打开、相关操作和关窗后的档案刷新。
- 提交前看一遍差异,确认来源、路径、记录和玩家数据可以分享。用 [PR 模板](templates/pull-request.md) 提供复核所需的信息。
<a id="english"></a> ## 1. 开发环境准备
[简体中文](#zh-cn) · English · [Dev Docs](README.md#english) 你需要一台 **Windows x64** 电脑,并安装以下基础工具:
## Review before submitting 1. **Node.js 24+**:仓库内的 CLI 脚本与 `apps/server` 直接以 Node 24 原生类型剥离模式运行 `.ts` 源码(Node 20/22 旧版本会因 `.ts` 扩展名或模块解析报错)。
2. **Visual Studio 2022 或 Build Tools(勾选「使用 C++ 的桌面开发」x64 工具链与 CMake)**:用于通过 `cl.exe` 编译 `native/wto-net/`(生成 `wto_ws.dll`),以及一次性编译 Quirrel 字节码检查器 `sq.exe`。
3. **Python 3.12+**:用于运行补丁校验器 `wtotools`、静态逆向工具 `tools/re/cli.py` 与客户端 `.clog` 日志解密命令。
4. **一份玩家本人合法持有的官方原版客户端(严格保持只读)**,以及在 Steam 游戏库目录之外单独准备的**离线副本目录**与**本地服务器数据目录**。
- 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).
- 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. ```powershell
- 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. # 1. 安装工作区依赖
- 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. npm install
# 2. 编译进程内网络重定向与 LocalMP 桥接库 -> build\native\wto_ws.dll
powershell -NoProfile -File .\native\wto-net\build.ps1
# 3. 下载桌面启动器所需的 Electron 二进制运行时
node node_modules/electron/install.js
# 4. 初始化 Python 虚拟环境并安装本地补丁/逆向工具包 wtotools
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e ./tools
```
如果你想脱离桌面启动器,直接从命令行快速构建一份离线副本并以前台模式启动本地服务器查看实时输出(注意:**`--game` 在构建时传只读原版目录、启动服务器时传离线副本目录,两条命令的 `--data` 与 `--port` 必须完全一致**):
```powershell
node scripts/build-game-copy.ts --game "<原版目录>" --out "<离线副本目录>" --data "<独立数据目录>" --port 27015
node apps/server/src/cli.ts --game "<离线副本目录>" --data "<独立数据目录>" --port 27015
```
---
<a id="debugging-zh"></a>
## 2. 怎么调试与查日志(排查 Bug 最快的路径)
排查机库动作报错、购买失败、匹配卡住或对局计分异常时,**千万不要靠盲猜客户端发了什么包**。WTOffline 在四处关键节点都留有可直接阅读的诊断日志:
### 2.1 本地服务器流量日志:`<数据目录>/logs/<启动时间戳>/`(第一站!)
每次启动 `apps/server`,`TrafficLog`(`apps/server/src/traffic-log/traffic-log.ts`)都会在 `<数据目录>/logs/` 下新建一个带 ISO 时间戳的会话文件夹,里面包含两部分:
1. **`requests.jsonl`(全量请求索引流)**
每行是一条 JSON 记录,按全局递增序号 `id` 记录每一次 HTTP 交互(`kind: "http"`)、每一条匹配服双向消息(`kind: "matching"`)、被拒绝的 WebSocket 升级请求(`kind: "websocket"`)以及连接开关事件:
- **一秒定位未实现接口**:直接在 `requests.jsonl` 中搜索 `"unhandled":true`(或看终端输出末尾带 `[UNHANDLED]` 标记的行),就能立刻抓出客户端刚发了哪个尚未挂载处理器的 `char` 动作、`yuplay2` 路径或 `matching` 消息!
- 每条记录中的 `files` 字段直接指明该次请求与响应对应的负载文件名。
2. **`bodies/` 子目录(自动解码的可读明文负载!)**
每个序号 `id`(补零至 6 位,如 `000042`)按需生成以下文件:
- `000042.req.bin` / `000042.resp.bin`:原始线上传输字节(登录表单中的密码字段会自动脱敏);
- **`000042.req.txt` / `000042.resp.txt`**:**自动解包并格式化好的可读明文 BLK 文本**(无论是带 `0x69` / zlib / zstd 标记的 `char` 二进制 BLK,还是 `cln_bulk_set_gblk` 上传的 `PBBD` 多段批处理流,都会自动转成缩进清晰的文本 BLK!)或 UTF-8 JSON 文本——你无需手写任何解包脚本,直接用编辑器打开 `.txt` 就能看清每一个字段与类型;
- **`000042.matching-in.json` / `000042.matching-out.json`**:解密并解压后的匹配长连接双向 RPC 消息(`in` 为客户端发来,`out` 为本地服务器下发)。
### 2.2 其余三类配套诊断日志
- **进程内钩子与 `LocalMP` 日志:`<离线副本目录>/win64/wto_ws.log`**
由 `wto_ws.dll` 每次启动游戏时重写。记录本地服务器端口号、每一次域名拦截与 Socket 连接重定向结果、`wto_ws.cfg` 与当前 `aces.exe` 的 PE 头校验结果,以及 **11 个 `local_mp_*` 模块中哪些成功安装、哪些因缺少 `wto_ws.cfg` 键值被优雅跳过**(并打印缺失的具体键名)。排查局内不刷 AI、选车无响应、记分牌为 0 或连杀飞机异常时先看这里。
- **游戏引擎客户端日志:`<离线副本目录>/.game_logs/*.clog`**
Dagor 引擎原生日志,记录 Quirrel 脚本编译/运行期报错、进机库卡死在「正在加载…」的具体栈信息、任务脚本报错与资源缺失。由于 `.clog` 是二进制异或加密格式,直接用 `tools/re/cli.py` 解密成纯文本再查阅:
```powershell
.\.venv\Scripts\python.exe tools\re\cli.py decrypt-clog "<离线副本目录>\.game_logs\<最新文件>.clog" --out "<临时目录>\game.clog.txt"
```
- **桌面启动器日志:`launcher.log`**
在启动器界面打开「设置 → 诊断 → 打开日志目录」即可查看,记录副本构建、补丁包校验、子进程启停与更新器状态。
---
<a id="checks"></a> <a id="checks"></a>
## 检查命令 / Check commands ## 3. 提交前必跑的工程检查命令(按改动范围对照执行)
在仓库根目录执行适用于本次改动的命令。尖括号内的占位内容换成自己的实际值。所有游戏输入文件用只读原版来源,构建输出用单独目录。 WTOffline **不要求也不提倡编写庞大的模拟(Mock)单元测试套件**,而是要求你按实际触碰的代码目录,跑通下面对应的**真实编译器、补丁字节核对与 Quirrel 字节码检查**;最终交互体验则在独立隔离副本中进游戏实机验收。
Run the applicable commands from the repository root. Replace placeholders in angle brackets with your own values. Use read-only stock inputs and a separate build output directory. | 你修改了哪里 | 提交前必须跑通的检查 |
| 改动 / Change | 检查 / Check |
| --- | --- | | --- | --- |
| 共用库或本地服务器 / Shared packages or local server | 根目录类型检查,必要时用独立数据目录确认服务器能启动<br>Root type check and server startup with separate data when applicable | | 共享库 `packages/*`、本地服务器 `apps/server` 或 `scripts/*` | 根目录 `npm run typecheck`;若动了服务端启动逻辑或 `tuning/*.jsonc`,用临时数据目录启动一次 `apps/server/src/cli.ts` 确认数据集提取与配置校验零报错 |
| 启动器 / Launcher | 启动器的类型检查和构建<br>Launcher type check and build | | 桌面启动器 `apps/launcher` | 启动器 `typecheck` + `electron-vite build`;若增改了界面多语言词条,确认 `en.json` 与 `zh-CN.json` 键名完全对齐 |
| exe 补丁 / Exe patch | `check-patches` 核对定位、原字节和源码<br>Verify matches, original bytes, and the patch source with `check-patches` | | `patches/exe/`(任何 `patch.jsonc`) | `wtotools check-patches`(验证特征码唯一命中、`expect_original` 匹配,且 `asm`/`data` 编译结果与 `bytes` 逐字节一致) |
| 修改 `patch.jsonc` 或 GUI 片段 / Edits to `patch.jsonc` or GUI fragments | 完整 `check-gui` 检查所有 GUI 补丁的命中、词法作用域和字节码编译<br>Run the full `check-gui` location, lexical scope, and bytecode checks | | `patches/gui/`(任何 `patch.jsonc` 或 `.nut` 片段) | **完整** `wtotools check-gui`(调用 `sq.exe` 执行 `compilestring` 词法作用域与字节码编译检查) + 临时副本构建确认 `gui-patch-definition.ts` Schema 无未知键报错 |
| Native 或构建流程 / Native or copy build | Native 改动先编译 DLL,再用临时输出目录构建,核对定位和可用性<br>Build the DLL for native changes, then check locations and availability with a temporary copy build | | `native/wto-net/` 或 `patches/native/` | MSVC `native\wto-net\build.ps1`(`/W4` **零警告**)+ 临时目录 `scripts/build-game-copy.ts` 确认所有原生站点全部解析就绪 |
| 版本适配 / New client build | 生成版本核对记录,完成适用的补丁和构建检查,再走实机验收<br>Generate a version record, run the applicable checks, then perform in-game acceptance | | 适配客户端新版本(`patches/versions/`) | `scripts/record-game-version.ts` + 上述全部适用检查 + **在隔离副本中实机登录进机库并完成 `LocalMP` 对局验收后**,方可提交 `patches/versions/<版本号>.jsonc` |
常用检查命令汇总(均在仓库根目录执行,将尖括号替换为你的本地路径):
```powershell ```powershell
# TypeScript / launcher # 1. TypeScript 类型与语法剥离约束检查(校验 .ts 后缀、import type、erasableSyntaxOnly 等)
npm run typecheck npm run typecheck
npm run typecheck --workspace "@wto/launcher" npm run typecheck --workspace "@wto/launcher"
npm run build --workspace "@wto/launcher" npm run build --workspace "@wto/launcher"
# Patch tool setup # 2. EXE 与 GUI 补丁核对(输入源必须是只读原版客户端目录!)
python -m venv .venv .\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<原版目录>\win64\aces.exe"
.\.venv\Scripts\python.exe -m pip install -e ./tools .\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<原版目录>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
# Patch verification # 3. Native DLL 编译(MSVC /W4 零警告)与完整离线副本试构建
.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<stock-client-dir>\win64\aces.exe"
.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-client-dir>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
# Native build and copy build check
powershell -NoProfile -File .\native\wto-net\build.ps1 powershell -NoProfile -File .\native\wto-net\build.ps1
node scripts/build-game-copy.ts --game "<stock-client-dir>" --out "<temporary-output-dir>" --data "<separate-data-dir>" --port <port> node scripts/build-game-copy.ts --game "<原版目录>" --out "<临时副本目录>" --data "<临时数据目录>" --port 27015
# Version adaptation # 4. 客户端版本适配记录核对
node scripts/record-game-version.ts --game "<stock-client-dir>" node scripts/record-game-version.ts --game "<原版目录>"
``` ```
实际启动时,离线副本需要包含完整游戏文件,本地服务器与副本构建使用同一端口和数据目录。版本记录命令会写入 `patches/versions/`,按[补丁指南](patches.md#核对版本与提交)核对后再提交。[服务器启动命令](../README.md#构建副本并启动服务器)
For an actual launch, use a full offline copy and match the server's port and data directory to the copy build. The record generator writes to `patches/versions/`. Follow the [patch guide](patches.md#check-versions-and-submit) before committing a record. [Server startup command](../README.md#build-the-copy-and-start-the-server)
<a id="quirrel"></a> <a id="quirrel"></a>
## 构建 Quirrel 编译器 / Build the Quirrel compiler ### 一次性编译 Quirrel 字节码检查器 `sq.exe`(注意 `--sq` 路径参数!)
GUI 检查使用 `sq.exe` 调用 `compilestring`,检查词法作用域和字节码编译。成功时会报告所有改动脚本都编译通过。以下步骤使用 Visual Studio 2022 的 x64 C++ 工具和 CMake 3.31。将实际编译器路径传给 `check-gui --sq`。[Quirrel 源码版本](https://github.com/GaijinEntertainment/quirrel/tree/19f17df9b6ee43c91ef5c635fd45970ec76c5dbe) `check-gui` 需要调用与《战争雷霆》客户端同代的官方 Quirrel 编译器(固定在 [Quirrel 仓库提交 `19f17df9b6ee43c91ef5c635fd45970ec76c5dbe`](https://github.com/GaijinEntertainment/quirrel/tree/19f17df9b6ee43c91ef5c635fd45970ec76c5dbe))。使用 Visual Studio 2022 C++ 工具链与 CMake 编译一次即可长期复用:
The GUI checker uses `sq.exe` and `compilestring` to check lexical scope and compile bytecode. A passing run reports successful compilation for all changed scripts. These steps use the Visual Studio 2022 x64 C++ tools and CMake 3.31. Pass the path to your compiler to `check-gui --sq`. [Quirrel source revision](https://github.com/GaijinEntertainment/quirrel/tree/19f17df9b6ee43c91ef5c635fd45970ec76c5dbe)
```powershell ```powershell
git clone https://github.com/GaijinEntertainment/quirrel.git build/quirrel-source git clone https://github.com/GaijinEntertainment/quirrel.git build/quirrel-source
@@ -81,3 +124,168 @@ git -C build/quirrel-source checkout --detach 19f17df9b6ee43c91ef5c635fd45970ec7
cmake -S build/quirrel-source -B build/quirrel-cli -G "Visual Studio 17 2022" -A x64 cmake -S build/quirrel-source -B build/quirrel-cli -G "Visual Studio 17 2022" -A x64
cmake --build build/quirrel-cli --config Release --target sq cmake --build build/quirrel-cli --config Release --target sq
``` ```
> **关于 `--sq` 参数的重要说明**:`wtotools check-gui` 在不传 `--sq` 时的默认查找路径是 `build/quirrel-check/sq.exe`(见 `tools/src/wtotools/cli/gui_commands.py`),而上面这条 Visual Studio CMake 多配置构建命令会把可执行文件生成在 **`build\quirrel-cli\bin\Release\sq.exe`**。因此运行 `check-gui` 时请像上方命令一样显式传入 `--sq "build\quirrel-cli\bin\Release\sq.exe"`(或者手动把生成的 `sq.exe` 复制一份到 `build\quirrel-check\sq.exe`)。
---
## 4. 提交消息规范与 PR 自查清单
- **一笔 PR 只聚焦一个清晰目标**:不要在修某个结算 Bug 的 PR 里顺手重排无关目录或大面积格式化其他文件。
- **全英文约定式提交(Conventional Commits)与英文注释**:
- 提交标题格式:`type(scope): concise summary`(例如 `fix(battle): credit Ground Arcade air event kills from AI victims`、`feat(launcher): show missing optional patch features`;仓库级工程或文档改动用 `repo` 或 `docs`);
- 若包含破坏性变更,在 `scope` 后加 `!` 并在正文末尾附上 `BREAKING CHANGE:` 说明;
- 代码注释、补丁顶部三行说明、补丁 `title` 与 Git 提交消息正文统一使用英文;
- `Co-authored-by` 尾注仅用于署名实际参与协作的人类开发者,不要填写 AI 模型或编程工具。
- **发起 PR 前最后 5 项自检**:
1. 对照 [开发规范第 4 节](development-rules.md#good-vs-bad-zh):零硬编码 RVA/结构体偏移/`_ReturnAddress()`、零手抄游戏静态数值、零越层 I/O;
2. 核对语法与 Schema 细节:TS 相对导入全部带 `.ts` 后缀且遵守 `erasableSyntaxOnly`;补丁 JSONC 无多余未知键(特别是 `patches/gui/**/patch.jsonc` 未误写 `requires`);带尾随立即数的 `rel32` 捕获已显式填写 `"end"`;
3. 涉及货币、研发、库存或存档改动时,确认所有修改均通过 `PlayerProfiles` / `SaveStore` **先完成原子写盘再向客户端返回响应**,且多账号目录严格隔离;
4. 通读一遍 `git diff`,确认没有带入任何本机个人路径、原版游戏文件、解包产物、测试存档或未脱敏日志;
5. 完整填写 [PR 模板](templates/pull-request.md),如实列出实际运行过的命令与输出结论,并把「已在隔离副本实机验收的界面步骤」与「尚待维护者实机验收的步骤」明确区分开。
---
<a id="english"></a>
[简体中文](#zh-cn) · English · [Back to Dev Docs](README.md#english)
This guide walks you through setting up a Windows x64 development environment, diagnosing bugs rapidly with auto-decoded local traffic logs, and running the required verification checks before opening a Pull Request.
---
## 1. Environment Setup
You need a **Windows x64** machine with:
1. **Node.js 24+**: Repository CLI scripts and `apps/server` execute `.ts` files directly via Node 24's native type-stripping (older Node 20/22 releases will fail on `.ts` import specifiers).
2. **Visual Studio 2022 or Build Tools (with "Desktop development with C++" x64 tools & CMake)**: Used by `native/wto-net/build.ps1` (`cl.exe`) to build `wto_ws.dll` and once to compile the Quirrel bytecode checker `sq.exe`.
3. **Python 3.12+**: Used for the patch verifier (`wtotools`), static disassembler (`tools/re/cli.py`), and `.clog` log decryptor.
4. **Your own legitimate stock War Thunder installation (kept strictly read-only)**, plus a separate **offline copy folder** and **server data folder** located outside any Steam library directory.
After cloning the repository, bootstrap everything from the repo root:
```powershell
# 1. Install npm workspace dependencies
npm install
# 2. Compile the Winsock redirector & LocalMP host bridge -> build\native\wto_ws.dll
powershell -NoProfile -File .\native\wto-net\build.ps1
# 3. Download the Electron runtime binary for the desktop launcher
node node_modules/electron/install.js
# 4. Create the Python virtual environment and install `wtotools` in editable mode
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e ./tools
```
To build an offline game copy and run the local server directly from the terminal without the desktop launcher (note: pass the **read-only stock folder** to `build-game-copy.ts --game`, pass the **offline copy folder** to `cli.ts --game`, and keep `--data` and `--port` identical across both commands):
```powershell
node scripts/build-game-copy.ts --game "<stock-dir>" --out "<copy-dir>" --data "<data-dir>" --port 27015
node apps/server/src/cli.ts --game "<copy-dir>" --data "<data-dir>" --port 27015
```
---
<a id="debugging-en"></a>
## 2. Traffic Log Debugging & Diagnostic Logs
Never guess what payload the game client sent or why a hangar action failed—WTOffline records human-readable diagnostics across four log locations:
### 2.1 Local Server Traffic Logs: `<data-dir>/logs/<ISO-timestamp>/` (Check Here First!)
Every time `apps/server` starts, `TrafficLog` (`apps/server/src/traffic-log/traffic-log.ts`) creates a timestamped session folder under `<data-dir>/logs/` containing:
1. **`requests.jsonl` (Indexed Exchange Log)**
One JSON line per HTTP request/response (`kind: "http"`), matching message (`kind: "matching"`), refused WebSocket upgrade (`kind: "websocket"`), or TCP connection open/close, numbered sequentially by `id`:
- **Spot missing endpoints instantly**: Search `requests.jsonl` for `"unhandled":true` (or look for `[UNHANDLED]` in the server console) to immediately see any unimplemented `char` action, `yuplay2` endpoint, or `matching` RPC!
- Each entry's `files` object points directly to its corresponding payload files inside `bodies/`.
2. **`bodies/` Subdirectory (Auto-Decoded Readable BLK & JSON Payloads!)**
Numbered by zero-padded sequence ID (e.g., `000042.*`):
- `000042.req.bin` / `000042.resp.bin`: Raw wire bytes (with sign-in passwords automatically redacted);
- **`000042.req.txt` / `000042.resp.txt`**: **Automatically unpacked and formatted readable BLK text** (covering `0x69`/zlib/zstd-framed `char` binary BLK payloads as well as multi-chunk `PBBD` streams on `cln_bulk_set_gblk`!) or UTF-8 JSON/form text—open any `.txt` file directly in your editor to inspect exact block trees and parameter types without manual decoding;
- **`000042.matching-in.json` / `000042.matching-out.json`**: Decrypted, LZ4-decompressed inbound (`in`) and outbound (`out`) `matching` binary RPC messages.
### 2.2 The Other Three Diagnostic Logs
- **Native Hook & `LocalMP` Log: `<copy-dir>/win64/wto_ws.log`**
Rewritten on every client launch by `wto_ws.dll`. Logs the active local port, every locally answered hostname and redirected/refused socket, whether `wto_ws.cfg` matched the running `aces.exe` PE `TimeDateStamp` / `SizeOfImage`, and **which of the 11 `local_mp_*` modules installed vs. were skipped** (naming the exact missing `wto_ws.cfg` key when skipped), plus live battle referee events.
- **Dagor Client Log: `<copy-dir>/.game_logs/*.clog`**
Records Quirrel script compilation/runtime errors, exact call stacks behind `"Loading..."` login hangs, mission errors, and missing assets. Because `.clog` files are XOR-encrypted binary logs, decrypt them to plain text with `tools/re/cli.py`:
```powershell
.\.venv\Scripts\python.exe tools\re\cli.py decrypt-clog "<copy-dir>\.game_logs\<latest>.clog" --out "<temp-dir>\game.clog.txt"
```
- **Desktop Launcher Log: `launcher.log`**
Accessible from Launcher **Settings -> Diagnostics -> Open log folder**, covering copy builds, patch-pack checks, server process lifecycle, and updater activity.
---
<a id="checks-en"></a>
## 3. Required Checks Before Submitting
WTOffline **does not require or encourage large mock unit test suites**. Instead, run the real compiler, binary-patch, and Quirrel bytecode verifiers matching the files you touched, followed by live acceptance in an isolated game copy:
| What you changed | Required checks before opening a PR |
| --- | --- |
| `packages/*`, `apps/server`, or `scripts/*` | Root `npm run typecheck`; if you touched server startup or `tuning/*.jsonc`, boot `apps/server/src/cli.ts` against a temporary data folder to confirm clean dataset extraction and tuning validation |
| `apps/launcher` | Launcher `typecheck` + `electron-vite build`; if you edited UI strings, verify `en.json` and `zh-CN.json` locale key parity |
| `patches/exe/` (any `patch.jsonc`) | `wtotools check-patches` (verifies unique signature hits, `expect_original` bytes, and exact byte-for-byte agreement between `asm`/`data` and `bytes`) |
| `patches/gui/` (any `patch.jsonc` or `.nut` fragment) | **Full** `wtotools check-gui` using `sq.exe` `compilestring` (required) + a temporary copy build to confirm zero unknown schema keys in `gui-patch-definition.ts` |
| `native/wto-net/` or `patches/native/` | MSVC `native\wto-net\build.ps1` (`/W4`, **zero warnings**) + temporary `scripts/build-game-copy.ts` run confirming every native module resolves cleanly |
| Adapting a new client build (`patches/versions/`) | `scripts/record-game-version.ts` + all applicable checks above + **live in-game verification in an isolated copy (hangar login + `LocalMP` battle)** before committing `patches/versions/<version>.jsonc` |
Complete command reference (run from the repository root, substituting bracketed paths):
```powershell
# 1. TypeScript typecheck & Node 24 erasable-syntax checks (.ts extensions, import type, etc.)
npm run typecheck
npm run typecheck --workspace "@wto/launcher"
npm run build --workspace "@wto/launcher"
# 2. EXE & GUI patch verification (always point at your READ-ONLY stock folder!)
.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<stock-dir>\win64\aces.exe"
.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-dir>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
# 3. Native DLL build (MSVC /W4 zero warnings) & temporary offline copy build
powershell -NoProfile -File .\native\wto-net\build.ps1
node scripts/build-game-copy.ts --game "<stock-dir>" --out "<temp-copy-dir>" --data "<temp-data-dir>" --port 27015
# 4. Client build compatibility record
node scripts/record-game-version.ts --game "<stock-dir>"
```
<a id="quirrel-en"></a>
### One-Time Build of the Quirrel Bytecode Compiler `sq.exe` (Note the `--sq` Flag!)
`check-gui` requires the official Quirrel compiler pinned to the revision matching War Thunder's client VM ([Quirrel commit `19f17df9b6ee43c91ef5c635fd45970ec76c5dbe`](https://github.com/GaijinEntertainment/quirrel/tree/19f17df9b6ee43c91ef5c635fd45970ec76c5dbe)). Build it once with Visual Studio 2022 C++ tools and CMake:
```powershell
git clone https://github.com/GaijinEntertainment/quirrel.git build/quirrel-source
git -C build/quirrel-source checkout --detach 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe
cmake -S build/quirrel-source -B build/quirrel-cli -G "Visual Studio 17 2022" -A x64
cmake --build build/quirrel-cli --config Release --target sq
```
> **Important note on `--sq`**: `wtotools check-gui` defaults `--sq` to `build/quirrel-check/sq.exe` (`tools/src/wtotools/cli/gui_commands.py`), whereas the multi-config Visual Studio CMake build above outputs **`build\quirrel-cli\bin\Release\sq.exe`**. Always pass `--sq "build\quirrel-cli\bin\Release\sq.exe"` explicitly as shown in the command block above (or copy `sq.exe` to `build\quirrel-check\sq.exe`).
---
## 4. Commit Conventions & Pre-PR Checklist
- **One focused goal per PR**: Avoid mixing unrelated refactors or repo-wide formatting into a bugfix or feature PR.
- **English Conventional Commits & English code comments**:
- Format commit titles as `type(scope): concise summary` (e.g., `fix(battle): credit Ground Arcade air event kills from AI victims`, `feat(launcher): show missing optional patch features`; use `repo` or `docs` for repository-level or documentation changes);
- Mark breaking changes with `!` after the scope and a `BREAKING CHANGE:` footer;
- Write all code comments, 3-line patch header comments, patch `title` fields, and commit bodies in English;
- Reserve `Co-authored-by` trailers strictly for human collaborators—never list AI models or coding tools.
- **Final 5-point self-check before opening a PR**:
1. Check against [Development Rules — Section 4](development-rules.md#good-vs-bad-en): zero hardcoded RVAs, struct offsets, or `_ReturnAddress()` checks; zero hardcoded stock game numbers; zero cross-layer I/O;
2. Verify syntax & schema discipline: explicit `.ts` extensions on relative imports, `import type` for types, no `enum`/`namespace`/parameter properties; strict patch JSONC keys (no `requires` in `patches/gui/**/patch.jsonc`, explicit `"end"` on `rel32` captures with trailing immediates);
3. For currency, research, inventory, or profile mutations, verify changes persist atomically via `PlayerProfiles` / `SaveStore` **before** replying to the client, with strict per-account isolation;
4. Review `git diff` to ensure zero personal machine paths, copyrighted game files, extracted stock scripts, personal saves, or unredacted logs slipped in;
5. Fill out the [PR template](templates/pull-request.md) completely, recording exact commands run and clearly separating observed in-game checks from pending in-game acceptance steps.
+576 -36
View File
@@ -1,59 +1,599 @@
# Development rules # 开发理念、架构分层与工程规范 / Development Rules
<a id="zh-cn"></a> <a id="zh-cn"></a>
简体中文 · [English](#english) · [返回 Dev Docs](README.md#zh-cn) 简体中文 · [English](#english) · [返回 Dev Docs](README.md#zh-cn)
## 实现位置 这篇文档不只罗列「能做什么、不能做什么」,而是先把 **WTOffline 为什么这样分层、客户端与本地服务器各自承担什么角色** 彻底讲透。只要底层运行模型在脑子里立住了,项目里的每一条工程规范都是自然而然的推论。
- 开工前明确玩家会看到什么变化和准备改的范围。涉及玩法或架构取舍,先和维护者对齐。先查目标版本的游戏文件、原版界面脚本和官方公开源码,记录版本、文件或函数以及支持结论的事实。把推测标为推测。需要读写游戏格式时,先评估已有工具的许可、维护情况和版本适用性。[DagorEngine 源码](https://github.com/GaijinEntertainment/DagorEngine) ---
- 客户端沿用原有流程,由本地服务器按协议回应。先看服务器或游戏自带配置能否解决。确实需要改客户端时,注明对应功能、原有行为和更小的改动为什么不够。界面脚本进 `patches/gui/`,数据包配置改动归 `packages/patcher/`,其他补丁按[补丁指南](patches.md#zh-cn)登记。
- 服务端按领域分模块。协议层处理请求和应答格式,规则层处理游戏规则,存档层负责持久化,数据层只提取游戏文件中的事实。修改档案的动作写盘成功后再回复。无法识别账号、缺必填参数或余额不足时,明确拒绝。初期开发用新存档验收,无需增加旧存档迁移。
- 应用通过参数把配置和路径交给共享库。按职责拆文件、函数和类,复用现有逻辑和常量。文件接近 300 行或函数接近 50 行就检查是否该拆分。商城与交易所的 HTML、CSS、JS 使用独立文件并复用[网页模块](../apps/server/src/web-ui)。
## 数值和数据来源 <a id="architecture-zh"></a>
| 数值类别 | 做法 | ## 1. 先建立全景图:WTOffline 到底是怎么跑起来的?
| --- | --- |
| 协议规定的值,如包头长度和消息类型 | 保留在代码中,注明版本和出处。 |
| 游戏文件已有的值,如车价、改装件价格 | 启动时从玩家的游戏文件读取。缺少必需值时报告具体字段并停止,避免悄悄代入编造的默认值。 |
| 离线版决定的值,如奖励、价格、权重、倍率、等级门槛、数量上限 | 写进对应模块的 `tuning/`。服务端默认值位于 [apps/server/tuning](../apps/server/tuning),启动时校验类型、范围和必填字段。 |
经济数值先查游戏数据和官方资料。商城以官方美元价作为 GJN 标价依据。官方资料缺项时,沿用已有出处的参考数据,或说明它属于离线设计。配置注释或 PR 记录出处、单位和取值规则,具体数值以配置为准。展示给玩家的数字也从同一数据来源生成。 WTOffline 采用与《逃离塔科夫》单机版(SPT)一脉相承的本地模拟架构:**不推翻重写游戏引擎,而是让原版客户端相信自己正连着完整的线上后端,把它的全部网络请求收口到本机 `127.0.0.1` 的模拟服务器,并仅在进程内补齐客户端被裁剪掉的局内主机裁判函数。**
本地服务器每次启动加载数值配置。数据目录下的同名 `tuning/*.jsonc` 可逐键覆盖默认对象。数字、字符串和列表整体替换。 ```text
玩家在启动器点击「启动游戏」
│
├─ 1. 桌面启动器(apps/launcher)调用构建引擎(packages/patcher)
│ └─ 以「严格只读」方式读取玩家的官方原版客户端目录,向独立离线副本目录生成:
│ ├─ char.vromfs.bin / aces.vromfs.bin:改写 network.blk 服务地址 -> 127.0.0.1:<端口>,注入本地商店礼包 GUID
│ ├─ gui.vromfs.bin:应用 patches/gui/(仅修补本地服务器无法覆盖的极少数界面脚本点)
│ ├─ win64/aces.exe:应用 patches/exe/(跳过包验签、隔离存档与注册表、禁用反作弊、把导入表 WS2_32.dll 改为 wto_ws.dll)
│ └─ win64/wto_ws.dll + win64/wto_ws.cfg:按 patches/native/*.jsonc 动态解析函数 RVA 与结构体偏移写入配置文件
│
├─ 2. 本地模拟服务器(apps/server,仅绑定 127.0.0.1:<端口> 单端口监听)
│ ├─ 启动阶段:通过 DatasetCache 从游戏归档包提取静态事实(科技树、价格、改装件、任务、多语言词条),加载 tuning/*.jsonc
│ └─ 运行阶段:port-listener.ts 按每个 TCP 连接的首批字节自动分流多协议:
│ ├─ 首字节 0x01 ──▶ MatchingService(9 字节头 + LZ4 压缩帧,握手后流加密)
│ ├─ 明文 PASS/NICK/USER/CAP/PING ──▶ IrcServer(机库与小队聊天)
│ ├─ 首字节 0x16(TLS ClientHello) ──▶ 本地证书 TLSSocket 解密后再二次分流至 IrcServer 或 HTTP
│ └─ 其余全部明文连接 ──▶ HTTP 服务器(yuplay2 登录、char 二进制 BLK 档案、inventory 签名 JSON、内嵌网页商店)
│ (注:HTTP WebSocket upgrade 请求会被记录日志后直接 socket.destroy() 拒绝)
│
└─ 3. 隔离离线副本(win64/aces.exe + win64/wto_ws.dll)
├─ 进程加载时(DllMain):wto_ws.dll 通过 wto_ws.def 把全部 Winsock 导出(含序号导出)转发至系统 ws2_32.dll,
│ 同时用 MinHook 挂钩系统 ws2_32.dll 的域名解析与连接函数;若任一网络钩子安装失败,DllMain 直接返回 FALSE 终止启动!
├─ 机库阶段:登录、拉取档案、科技树研发、买车买改装、乘员训练、开箱、逛商店,全部走原版协议由 apps/server 处理并原子落盘
└─ 对局阶段:MatchingService 下发任务参数使客户端以 LocalMP 本地主机开局;
wto_ws.dll 校验 PE 指纹匹配后启用 local_mp_* 模块,在进程内补齐选车出生、AI 刷出、击杀助攻占点计分、
陆战街机空中支援、核弹判胜与受损提示过滤;战后由客户端经 cln_update 回传 apps/server 结算银狮/研发点并落盘
```
## 本地开发与材料 ### 1.1 单端口多协议分流细节(`apps/server/src/transport/`)
- 游戏只在专用副本和隔离环境里启动。启动前验证断网限制、本地服务、Steam 和账号身份,以及文件、注册表、机器标识、反作弊和崩溃上报的隔离。需要观察启动行为时,在一次性环境里核对前后变化。原版来源只读,通过离线副本启动并使用本地账号。 客户端内部既有读取 `config/network.blk` 的模块,也有把域名、端口甚至 `https://` 写死在二进制常量里的模块。为了不占用一串本地端口,本地服务器在 `apps/server/src/transport/port-listener.ts` 中用**单个 TCP 监听端口**接住所有流量,在 `socket.once('data', ...)` 窥探首批字节后原样退回缓冲区(`socket.unshift`)并精准派发:
- 商城和交易所通过游戏内置浏览器访问本地服务。改动时核对该客户端内置浏览器支持的语法,沿用游戏语言和游戏文件中的本地化文字。包括浏览器子进程在内都要检查网络和缓存位置。
- 提交材料使用自己的代码和最小改动片段。游戏文件、解包产物和玩家数据留在本机。PR 使用可公开复核的出处和已清理的日志节选。 1. **匹配二进制协议(首字节 `0x01`)**:匹配 `startsMatchingPacket(first)` 后交由 `MatchingService` 处理(9 字节小端包头 + LZ4 数据块,见 `matching/matching-frame.ts`);
2. **明文 IRC 握手**:首行以 `PASS`、`NICK`、`USER`、`CAP` 或 `PING` 开头时交由 `IrcServer` 处理;
3. **TLS 加密连接(首字节 `0x16`)**:使用本地动态生成的自签名证书建立 `TLSSocket` 解密,再窥探解密后的首包字节——若是 TLS 承载的 IRC 握手则交由 `IrcServer`,否则派发给 HTTP 服务器;
4. **常规 HTTP 连接**:其余连接直接进入 `http-listener.ts` 的 `createHttpServer`,由 `Router` 按原始目标域名(`originalHost`)和路径分发给 `login`、`char`、`inventory`、`store`、`downloadable-content` 等服务。注意:**WTOffline 不使用 WebSocket**——客户端偶然发起的 HTTP `upgrade` 请求会在 `http-listener.ts` 中记入流量日志(`WebSocket ... (refused)`)并立即调用 `socket.destroy()` 断开。
### 1.2 `wto_ws.dll` 是如何在零外联风险下接管网络的?
在 `patches/exe/online/network-hook-library/patch.jsonc` 中,补丁将 `aces.exe` 只读数据段(`.rdata`)导入描述符引用的字符串 `"WS2_32.dll\0"`(`57 53 32 5f 33 32 2e 64 6c 6c 00`,共 **11 字节**)原位替换为等长的 `"wto_ws.dll\0"`(`77 74 6f 5f 77 73 2e 64 6c 6c 00`,同样 **11 字节**):
- Windows 加载器启动 `aces.exe` 时会自动加载同目录下的 `win64/wto_ws.dll`,由 `native/wto-net/src/wto_ws.def` 将客户端导入的全部 Winsock API(包含 31 个按 `@序号` 导入的函数)无缝转发给系统 `ws2_32.dll`;
- 在 `native/wto-net/src/dll_main.c` 的 `DllMain(DLL_PROCESS_ATTACH)` 中,DLL 读取同目录 `wto_ws.cfg`,通过 MinHook 直接挂钩系统 `ws2_32.dll` 本身的域名解析与连接/数据报函数(这样进程内**所有模块**的网络调用都会经过重定向,而不只是主程序);
- **安全熔断**:如果 `MH_Initialize`、`install_resolver_hooks`、`install_connection_hooks` 或 `MH_ApplyQueued` 中任何一步失败,`DllMain` 会记录日志并直接返回 `FALSE`,让 Windows 加载器中止启动游戏进程,避免游戏在未挂钩状态下连接外网。
### 1.3 基本设计原则
> **遇到功能缺失或 Bug 时,先评估能否在 `apps/server` 或通过下发原版配置字段解决。**
> 能通过修正服务端协议响应、补齐下发给客户端的任务 BLK 字段、或读取原版静态配置解决的问题,优先在服务端解决,不新增 `.nut` 界面脚本或 `aces.exe` / `wto_ws.dll` 客户端补丁。客户端补丁留给原版客户端确实缺少对应通路的场景——因为游戏每次小版本更新都会重排二进制代码,而服务端协议与配置字段跨版本稳定得多。
---
<a id="2-代码地图与分层边界"></a>
<a id="workspace-rule-zh"></a>
## 2. 仓库依赖约定与 `apps/server` 真实代码地图
### 2.1 仓库级单向依赖约定
```text
apps/launcher ──┐
├──▶ packages/* (@wto/blk · @wto/vromfs · @wto/jsonc · @wto/exepatch · @wto/patcher · @wto/mods)
apps/server ──┘
```
- **依赖方向单向朝下**:应用层 `apps/*` 可以导入共享包 `packages/*`(开发脚本 `scripts/*` 可组合两者),`packages/*` 不应反向导入、引用或硬编码读取 `apps/*` 下的代码或配置文件。
- 当共享包需要补丁集目录、数据目录、端口或礼包列表时,一律由上层调用方通过函数参数显式传入。
<a id="server-layers-zh"></a>
### 2.2 本地服务器 `apps/server/src/` 四层目录全景图
注意:**`apps/server/src/` 下并没有一个笼统的 `rules/` 文件夹**——业务规则是按游戏业务领域拆分成独立目录的。动手写代码前请对照下面这张真实目录表放对位置:
| 职责分层 | `apps/server/src/` 下的真实子目录 | 这一层负责什么 | 应避免放在这一层的内容 |
| --- | --- | --- | --- |
| **1. 传输与协议层**(Transport & Protocol) | `transport/`(单端口分流、HTTP 路由、TLS 证书)、`traffic-log/`(流量落盘)、`login/`(`yuplay2` 登录与会话凭据)、`char/`(含 `char-service.ts`、`pbbd-stream.ts`、`char/actions/*-actions.ts` 与路由总表 `char/actions/action-table.ts`)、`matching/`(LZ4 帧、流加密与排队 RPC)、`inventory/`(外部物品库与 RSA 内容签名)、`store/`(礼包与激活码路由)、`chat/`(IRC 服务端)、`cloud-settings/`、`downloadable-content/`、`web-ui/`(内嵌商店/市场页面渲染)、`mods/`(服务端模组运行时) | 解码线上传输格式(表单、JSON、压缩标记二进制 BLK、`PBBD` 流、LZ4 帧),提取并校验请求参数,调用对应领域规则,再把结果编码回客户端期待的原版响应格式 | 避免在 `*-actions.ts` 里堆砌几百行扣钱、算研发点或改档案树的业务逻辑;不要绕过 `PlayerProfiles` / `SaveStore` 直接读写磁盘文件 |
| **2. 领域规则层**(Domain Rules) | `battle/`(开局配置与战后经济结算)、`research/`(科技树状态、选定研发、自由研发点兑换)、`modifications/`(改装件、弹链、备用载具、自定义挂载)、`crew/`(乘员组槽位与技能加点)、`items/`(加成卡、赌注、折扣券)、`repair/`(战损折算与免费修车时间)、`clans/`(联队管理与联队载具研发)、`decor/`(涂装、贴花、3D 挂件)、`unlocks/`(成就、头衔、阶段解锁)、`player-card/`(头像、资料卡展柜)、`training/`(新手教程首通奖励)、`game-modes/` | **纯业务逻辑**:接收内存中的档案 `BlkBlock`、已加载的静态数据集与可调参数,校验前置条件,计算并更新档案状态,返回明确的成功或拒绝错误码(如 `RuleOutcome`) | **零网络、零磁盘 I/O**:不导入 `node:http`、`node:net` 或 `node:fs`,也不要感知外层是 HTTP 还是匹配长连接 |
| **3. 档案与持久化层**(Profile & Persistence) | `profile/`(`player-profiles.ts` 及按领域拆分的 `profile-*.ts` 档案节点读写器、派生状态刷新器)、`saves/`(`save-store.ts` 账号存档读写、`save-upgrades.ts` 版本演进)、`accounts/`(本地多账号密码与隔离)、`storage/`(`atomic-file.ts` 原子落盘) | 封装档案 BLK 树的底层字段读写,管理多账号目录隔离(`<data>/saves/<userId>/`),维护存档 `formatVersion`,并通过临时文件 + `fsync` + 原子重命名保证断电不坏档 | 不掺杂具体购买价格或研发公式;**任何修改档案的动作必须在磁盘原子写入完成后才能向客户端返回成功响应** |
| **4. 静态数据集与可调配置层**(Datasets & Tuning) | `game-data/`(`game-files.ts`、`game-pack.ts`、`datasets/*.ts`、`datasets/dataset-cache.ts`)、仓库默认配置 `apps/server/tuning/*.jsonc` + 加载校验器 `src/tuning/`(`tuning-loader.ts`、`tuning-reader.ts`、`limits-tuning.ts`、`launcher-tuning.ts`)+ 各领域 `<领域>/*-tuning.ts` | 启动时从玩家原版 `.vromfs.bin` 提取静态事实并按包时间戳 + 内部文件 SHA-1 缓存到 `<data>/cache/datasets/`;按「仓库默认 → 已启用模组 → 玩家 `<data>/tuning/` 覆盖」三层合并 JSONC 并做严格类型与范围校验 | 不要凭空编造原版数据;必填字段缺失时应明确报错停止启动,避免用隐式假默认值掩盖问题 |
**模块粒度与复用准则**:
- 当单个源文件接近 **300 行** 或单个函数接近 **50 行** 时,主动检查是否把协议拆包、档案树遍历和业务公式塞进了同一个文件,及时按上表拆开;
- 动手前先搜现有公共基础设施(如 `char/actions/rule-answer.ts`、`profile/profile-*.ts`、`modifications/equipment-catalogue.ts`、`web-ui/` 公共组件、`native` 侧的 `local_mp_core`),尽量复用而不是重复实现。
---
<a id="walkthrough-zh"></a>
### 2.3 跟着真实代码走一遍:`cln_set_researchable` 是怎么穿透四层的?
光看分层表还不够直观。下面我们顺着玩家在科技树点击「研发此载具」时触发的真实动作 **`cln_set_researchable`**,逐文件看一遍标准请求流(你在写任何新 `char` 动作时直接照这个模板写即可):
1. **客户端发包 → 协议入口解码(`apps/server/src/char/char-service.ts`)**
客户端向 `char-*.warthunder.com` 发送 HTTP POST,请求头带 `action: cln_set_researchable` 与 `uidhint: <userId>`,请求体是带压缩标记的二进制 BLK(包含 `unit:t = "us_m4a1_1942_sherman"` 与 `type:i = 0`)。`CharService.#handleCore` 调用 `decodeRequestPayload(request.body)`(`char/char-payload.ts`)把二进制负载解码为 `BlkBlock`(同时生成可读文本供流量日志记录),然后从 `char/actions/action-table.ts` 注册表里查出对应的处理器 `setResearchable`。
2. **协议动作适配与参数提取(`apps/server/src/char/actions/research-actions.ts`)**
`setResearchable` 本身只有十几行:它使用公共包装器 `ruleAction`(`char/actions/rule-answer.ts`),通过 `stringParam(payload, 'unit')` 和 `intParam(payload, 'type')`(`char/actions/payload-params.ts`)做基础类型提取。如果缺字段就返回 `undefined`(由 `ruleAction` 统一回 `!ERROR:BAD_PARAMS`);参数齐全则返回一个闭包:
`(profile) => chooseResearchTarget(profile, rules, vehicle, type)`。
3. **加载档案与执行纯领域规则(`apps/server/src/research/research-progress.ts`)**
`ruleAction` 校验完账号后调用 `profiles.updateWhen(account.userId, ...)`(`profile/player-profiles.ts`),由 `SaveStore.loadProfile` 从 `<data>/saves/<userId>/profile.blk` 读出当前档案并交给纯规则函数 `chooseResearchTarget`:
- 先从启动期提取好的科技树数据集 `rules.techTree.vehicle(vehicleName)` 查找该载具并核对 `typeId`;
- 调用 `currentStatus(profile, rules, vehicleName)` 确认该载具在玩家当前档案下确实处于 `VehicleStatus.CAN_RESEARCH` 状态;若尚未解锁前置车或已拥有,则返回 `refused('NOT_AVAILABLE')`(`{ ok: false, refusal: 'NOT_AVAILABLE' }`),`updateWhen` 看到 `false` **不触碰磁盘**,`ruleAction` 向客户端回复纯文本 `!ERROR:NOT_AVAILABLE`;
- 校验通过后,调用 `profile/profile-research-targets.ts` 的访问器写入新研发目标、清空刚完成研发弹窗标记,返回 `ACCEPTED`(`{ ok: true }`)。
4. **先原子落盘,再回包给客户端(`profile/player-profiles.ts` → `saves/save-store.ts` → `storage/atomic-file.ts`)**
`updateWhen` 收到 `true` 后,先运行 `#refresh(profile, userId)` 同步档案内的派生状态(解锁阶段、头衔、联队同步等),随即调用 `SaveStore.saveProfile(userId, profile)`。`saveProfile` 使用 `writeFileAtomic` 先在同目录写出临时文件 `profile.blk.<pid>.<rand>.tmp`、调用 `fsyncSync(fd)` 刷入物理磁盘、再原位 `renameSync` 覆盖目标文件并更新 `save.json`。**只有在磁盘写入彻底成功后**,`ruleAction` 才调用 `clientProfile(profile, account)` 组装客户端视图,由 `toResponse`(`char/char-answers.ts`)加上 `0x69` 标记编码成二进制 BLK 返回 HTTP 200。
### 2.4 存档结构演进规则(`saves/save-upgrades.ts`)
- **领域规则只面向「当前最新版」存档结构编程**:避免在 `research/`、`modifications/`、`battle/` 等业务代码里散落兼容旧测试字段的 `if/else` 分支;
- 当正式版本演进确实改变了 `profile.blk` 的存储结构时,统一在档案升级链(`saves/save-upgrades.ts` 的 `SaveUpgrades`)中追加一步升级函数(`steps[n]` 负责把 `formatVersion` 从 `n + 1` 原地升级到 `n + 2`)。`SaveStore.loadProfile` 打开旧版存档时会按顺序跑完升级步骤并立即以最新 `formatVersion` 原子回写磁盘。仍在同一分支开发调试、尚未发布的草稿改动无需写迁移代码。
---
<a id="values-zh"></a>
## 3. 三类数值放哪里(保持边界清晰)
在代码审查中,最常见的返工原因就是把不同性质的数字混写在了业务逻辑里。写下任何一个字面量前,先问它属于下面哪一类:
| 数值类别 | 典型例子 | 唯一正确的存放位置 | 常见错误示范 |
| --- | --- | --- | --- |
| **① 协议与引擎固定常量** | 匹配/局内消息号(如 `LMP_MPI_MSG_UNIT_RESPAWN = 0xf030u`)、`PBBD` 魔数(`0x44424250`)、Dagor 容器布局(`dag::Vector` 偏移、`FastNameMap` 移位)、状态位掩码 | 定义为具名常量放在对应协议或头文件中,并用**英文注释写明一手来源**(目标客户端版本号 + RVA,或 [DagorEngine 公开源码](https://github.com/GaijinEntertainment/DagorEngine) 文件路径) | 在函数中间裸写 `if (msgId == 61488)` 或 `if (status == 64)` 且没有任何来源注释 |
| **② 原版游戏包里本来就有的静态事实** | 载具购买银狮/金鹰价、研发点需求、分房权重、维修费、改装件树、多人地图列表、新手教程首通奖励、连杀支援出生高度/距离/速度 | 在 `apps/server/src/game-data/datasets/` 编写 `Dataset<T>`,服务启动时经 `DatasetCache` 从玩家原版 `.vromfs.bin` 动态读取并缓存在 `<data>/cache/datasets/<id>.json`;若原版文件缺失必填块/字段,直接 `throw new Error(...)` 明确报错停止 | 把某一个客户端版本的载具表、奖励金额或出生坐标手抄成 TS/C 常量表;或者读不到原版字段时悄悄 `?? 10000` 填个假默认值蒙混过关 |
| **③ 离线版自己决定的可调参数** | 银狮/研发点收益倍率、新账号初始货币、本地商店礼包定价、补给箱掉落权重、AI 机器人重生次数、单次请求数量上限、玩法开关 | 仓库默认值放进 `apps/server/tuning/<领域>.jsonc`,在对应 `<领域>/*-tuning.ts` 用 `TuningReader` 做启动期类型与上下界校验;运行期由 `tuning-loader.ts` 自动按「仓库默认 → 已启用模组覆盖 → 玩家 `<data>/tuning/<领域>.jsonc` 覆盖」合并 | 把 `const RP_MULTIPLIER = 3.0` 或硬上限直接写死在结算函数内部,导致玩家和模组作者无法通过 `tuning/` 调参 |
---
<a id="4-好代码-vs-坏代码4-组最常见的真实对比"></a>
<a id="good-vs-bad-zh"></a>
## 4. 好代码 vs 坏代码:4 组来自真实仓库的代码对比
下面所有正面代码全部取自仓库内的真实文件与真实符号,提交前请逐条对照自查。
### 对比 1:Native C 钩子 —— `g_lmp` 动态捕获与外层作用域标志 vs 硬编码偏移与 `_ReturnAddress()`
客户端只要发一个小版本更新(例如 `2.61.0.37` → `2.61.0.58`),函数 RVA 会整体漂移,C++ 类成员偏移也会随着字段增删而移动(例如 `gameplay` 里的连杀规则表偏移就会跨版本变化)。
```c
// ❌ 坏写法:硬编码 RVA、硬编码结构体偏移 +0x3798、用 _ReturnAddress() 猜调用栈
// 只要游戏发一个小补丁,轻则功能静默失效,重则当场非法内存访问崩溃!
static void __fastcall bad_hook_send_unit_respawn(uint8_t *unit, const void *spawn)
{
uintptr_t base = (uintptr_t)GetModuleHandleW(NULL);
if ((uintptr_t)_ReturnAddress() != base + 0x1281280)
return;
const uint8_t *gameplay = *(const uint8_t *const *)(base + 0x7bad2f0);
const uint8_t *rules = *(const uint8_t *const *)(gameplay + 0x3798);
/* ... */
}
```
```c
// ✅ 好写法(真实代码:native/wto-net/src/local_mp_air_events.c + local_mp_offsets.h + local_mp_values.h):
// 1. 所有函数地址与结构体偏移均在 patches/native/local_mp_air_events.jsonc 动态捕获写入 wto_ws.cfg,
// 运行时由 local_mp_values.c 填入全局 extern LmpValues g_lmp(LMP_GP_OFF_KS_RULES 展开为 g_lmp.gp_ks_rules);
// 2. 用外层函数钩子 + 线程局部标志(__declspec(thread))精确界定调用上下文,彻底告别脆弱的 _ReturnAddress()。
static SwitchPlayerUnitFn orig_switch_player_unit;
static __declspec(thread) int g_in_air_event_switch;
static void __fastcall hook_switch_player_unit(void *event_mgr, void *participant, uint8_t to_air)
{
int previous = g_in_air_event_switch;
if (to_air != 0 && ground_arcade_air_events_enabled())
g_in_air_event_switch = 1;
orig_switch_player_unit(event_mgr, participant, to_air);
g_in_air_event_switch = previous;
}
// 读取连杀规则表时全部走 g_lmp 动态解析值,跨小版本自动适配:
const uint8_t *gameplay = g_lmp.gameplay ? *(const uint8_t *const *)g_lmp.gameplay : NULL;
const uint8_t *rules = *(const uint8_t *const *)(gameplay + LMP_GP_OFF_KS_RULES);
uint32_t rule_count = *(const uint32_t *)(gameplay + LMP_GP_OFF_KS_RULE_COUNT);
```
### 对比 2:原版静态数据 —— `DatasetCache` 提取与纯领域目录消费 vs 在业务里手抄常量表
```ts
// ❌ 坏写法:把某一个版本的新手教程首通银狮/金鹰奖励硬编码成服务端字典
const TUTORIAL_REWARDS: Record<string, { silverLions: number; goldenEagles: number }> = {
'tutorialB_fighter': { silverLions: 5000, goldenEagles: 100 },
'tutorialB_assaulter': { silverLions: 5000, goldenEagles: 0 },
};
```
```ts
// ✅ 好写法(真实代码:apps/server/src/game-data/datasets/training-missions.ts
// + apps/server/src/training/training-completion.ts):
// 1. 在 datasets/ 定义带版本号的 Dataset,从玩家原版 char.vromfs.bin 的
// config/mislist.blk、config/pve_awards.blk、config/unlocks.blk 提取真实配置;缺失必填块立即抛错。
export const trainingMissions: Dataset<TrainingMissionsData> = {
id: 'training-missions',
version: 1,
extract(source: DatasetSource): TrainingMissionsData {
const misSection = blockAt(source.readBlk('char.vromfs.bin', 'config/mislist.blk'), 'training');
if (!misSection) throw new Error('config/mislist.blk has no "training" block');
const awardSection = blockAt(source.readBlk('char.vromfs.bin', 'config/pve_awards.blk'), 'training');
if (!awardSection) throw new Error('config/pve_awards.blk has no "training" block');
// ... 组装 missions 列表并返回纯数据对象
return { missions };
},
};
// 2. 启动时通过 DatasetCache 加载(包未变直接命中缓存),交由纯领域类 TrainingCatalogue 执行幂等发奖:
const trainingCatalogue = new TrainingCatalogue(datasets.load(trainingMissions));
trainingCatalogue.applyCompletion(profile, { chapter, mission, difficulty });
```
### 对比 3:找准修复层级与严格遵守工具链语法(MSVC C 与 Node 24 原生 TS)
**(A)先查原版读取逻辑,别急着动刀写客户端补丁**
- ❌ **坏思路**:发现多载具出击模式下 AI 机器人死一次就不再重生,立刻去反汇编 `BotSystem` 准备写 `patches/exe/` 强改内存计数器。
- ✅ **好思路**:先看 `MissionSettings::load` 是怎么读任务配置的——结果发现原版客户端本来就会读取任务 BLK 根节点的 `numBotRespawns` 与 `numTankBotRespawns`,只是服务端组装匹配开局配置时漏填了这两个根字段。在 `apps/server` 补上几行配置下发即可解决,**零客户端补丁、跨版本永久免疫失效**。
**(B)MSVC C 编译规范与 Node 24 原生 TypeScript 语法规范**
- **Native C(`native/wto-net/`)**:由 `native/wto-net/build.ps1` 调用 Visual Studio `cl.exe` 以 `/W4` 编译,要求**零编译警告**。校验自定义结构体大小与成员偏移时使用 `<windows.h>` 的编译期断言 `C_ASSERT(sizeof(LocalMpAirSpawn) == 0x48);`,线程局部存储使用 `__declspec(thread)`,内存对齐使用 `__declspec(align(16))`;避免使用 `__attribute__((...))`、零长数组、可变长数组(VLA)或 `void *` 算术运算等 GCC/Clang 专属扩展。
- **TypeScript(`tsconfig.json`)**:Node.js 24 直接剥离类型运行 `.ts` 源码,仓库开启了 `erasableSyntaxOnly: true`、`verbatimModuleSyntax: true`、`allowImportingTsExtensions: true` 与 `exactOptionalPropertyTypes: true`:
```ts
// ❌ 坏写法:省略 .ts 后缀、值导入混用纯类型、使用 enum 或构造函数参数属性(Node 24 类型剥离与 tsc 均会报错!)
import { SaveStore, SaveUpgrades } from '../saves/save-store';
export enum ResearchState { Locked = 0, Available = 1 }
export class Handler {
constructor(private readonly saves: SaveStore) {}
}
```
```ts
// ✅ 好写法:相对路径一律写明 .ts 扩展名;纯类型必须用 import type;用 as const 对象或联合类型代替 enum;用 #私有字段
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import type { SaveUpgrades } from './save-upgrades.ts';
export const VehicleStatus = {
CAN_RESEARCH: 2,
OWNED: 4,
} as const;
```
### 对比 4:工程验证 —— 跑真实工具链检查 vs 写几百行假 Mock 单元测试
- ❌ **坏写法**:改了 `patches/gui/` 只肉眼扫一眼 `.nut` 缩进,或者自己造一套模拟客户端行为的 300 行 Mock 单测跑绿就宣称「测试全部通过」——结果真进游戏时因为 Quirrel 词法作用域冲突卡死在登录界面,或者 `patch.jsonc` 多写了一个非法键在构建副本时直接抛 `DefinitionError`。
- ✅ **好写法**:按改动范围老老实实运行真实检查工具(`npm run typecheck`、`wtotools check-patches`、带 `sq.exe` 的完整 `wtotools check-gui`、`native\wto-net\build.ps1`、`scripts/build-game-copy.ts`),并在 PR 描述中**如实把「已在命令行跑过的检查」与「尚待在隔离副本进游戏实机验收的步骤」分开写清楚**。
---
<a id="ai-guide-zh"></a>
## 5. 使用 AI 编程助手协作指南(含一键复制约束提示词)
我们非常鼓励你使用 Claude Code、Codex、Cursor 等 AI 工具协助阅读反汇编、梳理 `.nut` 界面调用链、核对 BLK 字段以及快速定位协议差异。
但 AI 如果事先不知道 WTOffline 的工程边界,很容易顺手写出硬编码 RVA、在 `patches/gui/**/patch.jsonc` 里误加 `requires` 字段、漏写 `.ts` 导入后缀、用 `enum` 语法或生成一大堆无意义的 Mock 测试。**在让 AI 动手修改任何文件之前,请先把下面这段完整提示词发给它**:
```text
我正在为 WTOffline 仓库开发改动。在编写或修改代码前,请遵循以下项目规范(写任何符号、结构体字段、CLI 参数前先读取仓库真实源文件核实):
1. 修复层级优先顺序:先查原版一手依据(玩家只读原版 .vromfs.bin、gui.vromfs.bin 里的 .nut 脚本、DagorEngine 公开源码)。凡是能在本地服务器(apps/server)协议响应、任务配置字段或静态数据集里解决的问题,不要新增 patches/gui/、patches/exe/ 或 native/wto-net/ 客户端补丁。
2. 动态定位,不硬编码地址与偏移:不要在 C 或 TS 代码里写死 exe 函数地址、RVA、C++ 结构体偏移或 _ReturnAddress() 调用栈判断。所有原生地址与偏移通过 patches/exe/ 或 patches/native/*.jsonc 的 signature / string_ref / within 动态捕获写入 wto_ws.cfg,C 侧通过 extern LmpValues g_lmp(local_mp_values.h / local_mp_offsets.h)读取,并用外层钩子 + __declspec(thread) 标志替代返回地址检查。带尾随立即数的 rip-relative 指令捕获 rel32 时需显式指定 "end"(指令总字节长度)。
3. 三类数值严格归位:原版游戏自带数值(载具价格、研发点、奖励、任务、出生参数)必须通过 apps/server/src/game-data/datasets/(DatasetCache)从原版归档提取,缺必填字段直接抛错;离线版自定参数与开关统一放入 apps/server/tuning/*.jsonc 并在对应 *-tuning.ts 做启动校验;协议/引擎常量写英文注释注明客户端版本 RVA 或 DagorEngine 源码路径。
4. 分层与依赖方向:packages/* 不导入或读取 apps/*。apps/server/src/ 内区分传输协议层(char/actions/ 等)、领域规则层(research/、battle/、modifications/ 等纯逻辑目录,无 rules/ 目录,零网络零磁盘 I/O)、档案持久化层(profile/、saves/、storage/atomic-file.ts —— 改档动作先原子写盘成功再回包);存档兼容升级统一通过 saves/save-upgrades.ts 的 formatVersion 步骤处理,不在业务规则里散落旧版兼容分支。单文件接近 300 行或函数接近 50 行时主动拆分。
5. 严格语法与 Schema 约束:
- TypeScript 运行在 Node 24 原生类型剥离模式(erasableSyntaxOnly + verbatimModuleSyntax + allowImportingTsExtensions):所有相对导入必须带显式 `.ts` 后缀,纯类型必须用 `import type`,禁止使用 `enum`、`namespace` 和构造函数参数属性。
- Native C 必须通过 MSVC `native/wto-net/build.ps1`(/W4 零警告),使用 `C_ASSERT` 做编译期布局检查,禁止 GCC 扩展;新增 `.c` 文件需同步加入 `build.ps1` 的 `$sources`。
- 补丁 JSONC 严格校检未知键:特别是 `patches/gui/**/patch.jsonc` 顶层只允许 `id`、`title`、`features`、`variants`(不要写 `requires`,否则会抛出 DefinitionError)。
6. 真实工具验证:不要编写庞大的模拟(mock)单元测试套件。按改动运行真实检查命令(`npm run typecheck`、`wtotools check-patches`、带 `--sq` 的完整 `wtotools check-gui`、`native/wto-net/build.ps1`、`scripts/build-game-copy.ts`),并如实区分已跑过的命令与待隔离副本实机验收项。
7. 提交规范:一笔 PR 只聚焦单一目标;代码注释、补丁 `title`/头部三行说明与约定式提交消息统一使用英文;不把 AI 写入 Co-authored-by;在隔离副本实机进游戏验收前不提交 `patches/versions/*.jsonc`。
```
---
<a id="isolation-zh"></a>
## 6. 隔离安全与资产边界
1. **官方原版客户端目录保持只读**:无论是拆包查 `.blk`、跑 `tools/re/cli.py` 反汇编、`wtotools` 核对补丁还是构建游戏副本,原版目录都只作为只读输入源,不要向 Steam 或官方启动器安装目录写入、覆盖或残留文件。
2. **仅在独立隔离副本中运行测试**:实机运行客户端必须在 Steam 库目录之外的独立离线副本中进行,并确保三大核心安全锁(`ESSENTIAL_FEATURES`)全部生效——所有联网请求经 `wto_ws.dll` 收口至 `127.0.0.1`、本地配置落入独立 `WTOffline` 用户目录与 `Software\WTOffline` 注册表路径、反作弊与崩溃上报已剥离,且只使用离线本地账号登录。
3. **代码仓库不包含受版权保护资产与隐私信息**:不要将 `.vromfs.bin`、`aces.exe`、解包出的原版 `.nut` / `.blk` 完整文件、真实玩家存档、本机绝对路径或未脱敏日志提交进 Git 仓库。
---
<a id="english"></a> <a id="english"></a>
[简体中文](#zh-cn) · English · [Dev Docs](README.md#english) [简体中文](#zh-cn) · English · [Back to Dev Docs](README.md#english)
## Where changes belong Rather than handing you a dry list of dos and don'ts, this guide first explains **how WTOffline actually works under the hood and why its layers are separated the way they are**. Once that architecture clicks, every engineering rule follows naturally.
- State the player-visible result and the intended scope before starting. Discuss gameplay or architectural changes with maintainers. Check the target build, stock UI scripts, and official public source. Record the version, file or symbol, and the evidence for the behavior. Mark any inference as such. For game formats, look for existing tools and review their licensing, maintenance, and version support. [DagorEngine source](https://github.com/GaijinEntertainment/DagorEngine) ---
- Keep the client's normal flow by responding from the local server. Check the server and stock configuration first. When a client change is necessary, document the feature, the stock behavior, and why a lighter change is insufficient. Put UI edits in `patches/gui/` and archive configuration edits in `packages/patcher/`. See the [patch guide](patches.md#english) for the other patch types.
- Keep protocol encoding, game rules, persistence, and game data extraction in their own layers. Persist a save change before returning success. Reject unknown accounts, missing required inputs, and insufficient balances. During early development, use fresh saves for acceptance and omit legacy migrations.
- Pass configuration and paths from applications into shared packages. Reuse existing logic and constants. Review files near 300 lines or functions near 50 lines for responsibilities that can be split. Store shop and marketplace HTML, CSS, and JavaScript in separate files and reuse the [web UI module](../apps/server/src/web-ui).
## Data and tuning <a id="architecture-en"></a>
| Kind of value | Where it belongs | ## 1. End-to-End Architecture: How WTOffline Works
| --- | --- |
| Protocol constants such as header sizes and message types | Keep them in code with the source and relevant version. |
| Values already in the game files such as vehicle and modification prices | Read them from the player's game files at startup. Report the field and stop if a required value is missing. |
| Offline defaults such as rewards, prices, weights, multipliers, rank thresholds, and limits | Put them in the module's `tuning/` directory. Server defaults are in [apps/server/tuning](../apps/server/tuning) and are validated at startup. |
Use game data and official material as the first sources for economic defaults. The local store uses official USD prices as the basis for GJN prices. For gaps, use reference data with a recorded source or document the offline design choice. Put the source, unit, and reasoning in a comment or the PR. Read the exact values and any player-facing numbers from the configuration. WTOffline uses the same core philosophy as Single Player Tarkov (SPT): **do not rewrite the game engine—keep the retail client running its native code paths, redirect all network traffic to a local emulation server on `127.0.0.1`, and hook `aces.exe` in-process only where retail builds stripped Dedicated Server battle handlers.**
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. ```text
Player clicks "Launch" in the Launcher
│
├─ 1. Desktop Launcher (apps/launcher) invokes Copy Builder (packages/patcher)
│ └─ Reads the player's official stock install STRICTLY READ-ONLY and writes an isolated copy:
│ ├─ char.vromfs.bin / aces.vromfs.bin: rewrite network.blk endpoints -> 127.0.0.1:<port>, inject store bundle GUIDs
│ ├─ gui.vromfs.bin: apply patches/gui/ (surgical UI script edits only where server responses cannot suffice)
│ ├─ win64/aces.exe: apply patches/exe/ (bypass pack signature checks, isolate user dir & registry, disable anti-cheat,
│ │ rewrite PE import name "WS2_32.dll\0" -> "wto_ws.dll\0")
│ └─ win64/wto_ws.dll + win64/wto_ws.cfg: resolve patches/native/*.jsonc RVAs & struct offsets into wto_ws.cfg
│
├─ 2. Local Emulation Server (apps/server, bound strictly to 127.0.0.1:<port>)
│ ├─ Startup: DatasetCache extracts static facts from stock .vromfs.bin archives; tuning-loader merges tuning/*.jsonc
│ └─ Runtime: transport/port-listener.ts peeks at the first bytes of every TCP socket on that single port:
│ ├─ First byte 0x01 ──▶ MatchingService (9-byte header + LZ4 frames, encrypted after handshake)
│ ├─ Plaintext PASS/NICK/USER/CAP/PING ──▶ IrcServer (hangar & squad chat)
│ ├─ First byte 0x16 (TLS ClientHello) ──▶ Local-cert TLSSocket decrypts, then routes to IrcServer or HTTP
│ └─ Everything else ──▶ HTTP server (yuplay2 login, char binary BLK RPC, signed inventory JSON, web store)
│ (Note: HTTP WebSocket `upgrade` requests are logged and explicitly refused via socket.destroy()!)
│
└─ 3. Isolated Offline Client Copy (win64/aces.exe + win64/wto_ws.dll)
├─ Process attach (DllMain): wto_ws.dll forwards all Winsock exports (including 31 ordinal imports) via wto_ws.def
│ to system ws2_32.dll and installs MinHook detours on ws2_32's resolver/connect APIs; if ANY network hook fails,
│ DllMain returns FALSE so Windows immediately aborts launch before a single packet can go online!
├─ Hangar phase: sign-in, profile load, tech-tree research, purchases, crews, chests, and store all run over stock
│ protocols against apps/server with atomic disk persistence
└─ Battle phase: MatchingService launches a LocalMP host session; after verifying PE headers against wto_ws.cfg,
wto_ws.dll activates local_mp_* modules to restore stripped host handlers (vehicle/loadout spawn, AI bot spawn,
kill/assist/capture scoring, Ground Arcade air events, nuclear instant win, damage-notice filtering), and post-battle
results return to apps/server via cln_update for reward settlement and save persistence
```
## Local development and contributions ### 1.1 Single-Port Protocol Multiplexing (`apps/server/src/transport/`)
- 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. Because some client subsystems read URLs from `config/network.blk` while others use compiled-in hostnames, ports, and `https://` URLs, `apps/server/src/transport/port-listener.ts` multiplexes every protocol over **one `127.0.0.1` TCP port**. On each incoming connection, `socket.once('data', ...)` inspects the initial bytes, pushes them back with `socket.unshift(first)`, and hands the socket to the matching protocol handler:
- The store and marketplace use the game's embedded browser and the local service. Check the browser features supported by the target build and reuse the game's language and localized data. Include the browser subprocess when checking network access and cache paths.
- Submit your own code and the smallest fragments needed for a patch. Keep game files, extracted assets, and player data local. Use sources that reviewers can access and redact any log excerpts. 1. **Matching binary RPC (`first[0] === 0x01`)**: Matched by `startsMatchingPacket(first)` (`matching/matching-frame.ts` — 9-byte little-endian header + LZ4 block) and handed to `MatchingService`;
2. **Plaintext IRC handshake**: Connections starting with `PASS`, `NICK`, `USER`, `CAP`, or `PING` (`startsIrcHandshake`) go straight to `IrcServer`;
3. **TLS ClientHello (`first[0] === 0x16`)**: Wrapped in a `TLSSocket` using the local certificate, after which the first decrypted bytes are inspected again—routing TLS-wrapped IRC handshakes to `IrcServer` and all other decrypted streams to the HTTP server;
4. **Plaintext HTTP**: All remaining connections go to `createHttpServer` (`transport/http-listener.ts`), where `Router` dispatches requests by `originalHost` and path across `login`, `char`, `inventory`, `store`, `downloadable-content`, etc. **Note on WebSockets**: WTOffline does **not** use WebSockets—any HTTP `upgrade` request hits `server.on('upgrade', ...)` in `http-listener.ts`, which logs `WebSocket <host><path> (refused)` in the traffic log and immediately closes the socket with `socket.destroy()`.
### 1.2 How `wto_ws.dll` Intercepts All Outbound Traffic Safely
`patches/exe/online/network-hook-library/patch.jsonc` locates the 11-byte import descriptor name `"WS2_32.dll\0"` (`57 53 32 5f 33 32 2e 64 6c 6c 00`) in `aces.exe`'s `.rdata` section and overwrites it in place with `"wto_ws.dll\0"` (`77 74 6f 5f 77 73 2e 64 6c 6c 00`, also **11 bytes**):
- When Windows loads `aces.exe`, it loads `win64/wto_ws.dll` instead of `WS2_32.dll`. `native/wto-net/src/wto_ws.def` forwards every imported Winsock symbol (preserving exact `@ordinal` numbers for all 31 ordinal-imported functions) to the operating system's `ws2_32.dll`;
- Inside `DllMain` (`native/wto-net/src/dll_main.c`), `wto_ws.dll` loads `wto_ws.cfg` and uses MinHook to hook the name-resolution, `connect`, and datagram functions inside the system's `ws2_32.dll` itself—so network calls from **every module** in the process pass through local redirection, not just calls made directly by `aces.exe`;
- **Hard fail-closed guarantee**: If `MH_Initialize`, `install_resolver_hooks()`, `install_connection_hooks()`, or `MH_ApplyQueued()` fails for any reason, `DllMain` logs the failure and **returns `FALSE`**, causing the Windows loader to abort process startup immediately rather than risking an unhooked online connection.
### 1.3 The Golden Priority Rule
> **Before touching any client file, always ask: "Can `apps/server` or stock mission/config fields solve this?"**
> If a bug or feature can be implemented by returning the right server payload, populating a stock BLK field in the mission launch config, or extracting stock archive data, **never add a `.nut`, `aces.exe`, or `wto_ws.dll` patch**. Client patches are strictly a last resort when retail `aces.exe` or `gui.vromfs.bin` genuinely lacks the path—because minor game updates frequently shift binary code while wire protocols and BLK schemas remain stable across builds.
---
<a id="2-code-map-and-layer-boundaries"></a>
<a id="workspace-rule-en"></a>
## 2. Workspace Dependency Rule & Real `apps/server` Directory Map
### 2.1 One-Way Workspace Dependency Rule
```text
apps/launcher ──┐
├──▶ packages/* (@wto/blk · @wto/vromfs · @wto/jsonc · @wto/exepatch · @wto/patcher · @wto/mods)
apps/server ──┘
```
- **Dependencies flow strictly downward**: `apps/*` may import from `packages/*` (and developer CLI scripts under `scripts/*` may compose both), **but `packages/*` must never import from, reference, or hardcode paths into `apps/*`**.
- Whenever a shared package needs a patch directory, data folder, port number, or bundle list, pass it explicitly as a function parameter from the caller.
<a id="server-layers-en"></a>
### 2.2 Complete `apps/server/src/` Four-Layer Directory Map
Note that **there is NO monolithic `rules/` folder in `apps/server/src/`**—domain rules live in dedicated per-domain directories. Use this map to place every file in the right layer:
| Layer | Real directories under `apps/server/src/` | What belongs here | What must NOT go here |
| --- | --- | --- | --- |
| **1. Transport & Protocol** | `transport/` (single-port listener, HTTP router, TLS cert), `traffic-log/` (JSONL + decoded body logger), `login/` (`yuplay2` sign-in & session tokens), `char/` (`char-service.ts`, `pbbd-stream.ts`, `char/actions/*-actions.ts`, and `char/actions/action-table.ts`), `matching/` (LZ4 framing, stream cipher, queue/battle RPC), `inventory/` (external inventory & RSA content signing), `store/` (bundle & redeem-code endpoints), `chat/` (IRC server), `cloud-settings/`, `downloadable-content/`, `web-ui/` (in-game store & market HTML/CSS), `mods/` (server mod runtime) | Decode wire payloads (HTML forms, JSON, marker-prefixed binary BLK, `PBBD` streams, LZ4 packets), validate request parameters, invoke domain rules, and serialize results back into stock wire formats | Do not write multi-hundred-line currency, research, or profile-mutation logic inside `*-actions.ts`; never read or write save files directly bypassing `PlayerProfiles` / `SaveStore` |
| **2. Domain Rules** | `battle/` (mission setup & post-battle economy settlement), `research/` (tech-tree state, target selection, free-RP conversion), `modifications/` (modules, ammo belts, spares, custom weapon presets), `crew/` (slots & skill progression), `items/` (boosters, wagers, discounts), `repair/` (battle damage & timed free repair), `clans/` (squadrons & squadron vehicle RP), `decor/` (skins, decals, 3D attachables), `unlocks/` (streaks, titles, progression unlocks), `player-card/` (pilot icons & showcases), `training/` (tutorial completion rewards), `game-modes/` | **Pure domain logic**: take an in-memory profile `BlkBlock`, loaded datasets, and validated tuning; verify preconditions; mutate or compute the next state; return an explicit `RuleOutcome` (`ACCEPTED` or `refused('CODE')`) | **Zero network or filesystem I/O**: never import `node:http`, `node:net`, or `node:fs`, and keep domain logic agnostic of HTTP headers or sockets |
| **3. Profile & Persistence** | `profile/` (`player-profiles.ts` plus focused `profile-*.ts` BLK accessors and derived-state refresh), `saves/` (`save-store.ts` & `save-upgrades.ts` `formatVersion`), `accounts/` (multi-account credentials & isolation), `storage/` (`atomic-file.ts` `writeFileAtomic`) | Encapsulate typed `BlkBlock` profile accessors, isolate per-account saves under `<data>/saves/<userId>/`, run ordered `formatVersion` upgrades, and guarantee crash-safe writes via temp file + `fsync` + atomic rename | Do not embed shop pricing or research formulas here; **every profile mutation must finish writing to disk before replying to the client** |
| **4. Datasets & Tuning** | `game-data/` (`game-files.ts`, `game-pack.ts`, `datasets/*.ts`, `datasets/dataset-cache.ts`), shipped defaults in `apps/server/tuning/*.jsonc` + loader/validators in `src/tuning/` (`tuning-loader.ts`, `tuning-reader.ts`, `limits-tuning.ts`, `launcher-tuning.ts`) + per-domain `<domain>/*-tuning.ts` | Extract static facts from stock `.vromfs.bin` archives at startup (cached in `<data>/cache/datasets/<id>.json` by pack size/mtime and inner file SHA-1 digests), and merge/validate JSONC tuning across shipped defaults -> enabled mods -> player `<data>/tuning/` overrides | Never invent stock game numbers; if a required stock block or field is missing, throw an explicit error at startup instead of silently substituting a fake default |
**File granularity & reuse**:
- When a file approaches **300 lines** or a function approaches **50 lines**, check whether wire parsing, BLK tree traversal, and domain rules have been mixed together and split them cleanly along the table above;
- Reuse existing building blocks (`char/actions/rule-answer.ts`, `profile/profile-*.ts`, `modifications/equipment-catalogue.ts`, shared `web-ui/` helpers, and `local_mp_core` in C) instead of duplicating helpers.
---
<a id="walkthrough-en"></a>
### 2.3 End-to-End Walkthrough of One Real Action: `cln_set_researchable`
To see how those four layers collaborate in practice, let's trace what happens when a player clicks **"Research"** on a vehicle in the tech tree and the client sends **`cln_set_researchable`** (use this exact pattern whenever you add a new profile-mutating `char` action):
1. **Wire Arrival & Payload Decoding (`apps/server/src/char/char-service.ts`)**
The client sends an HTTP POST to `char-*.warthunder.com` with headers `action: cln_set_researchable` and `uidhint: <userId>`, carrying a marker-prefixed binary BLK body (`unit:t = "us_m4a1_1942_sherman"`, `type:i = 0`). `CharService.#handleCore` calls `decodeRequestPayload(request.body)` (`char/char-payload.ts`) to decode the `BlkBlock` (and format readable BLK text for the traffic log), then looks up `'cln_set_researchable'` in `char/actions/action-table.ts` to invoke `setResearchable`.
2. **Protocol Adapter & Parameter Extraction (`apps/server/src/char/actions/research-actions.ts`)**
`setResearchable` is a thin 14-line adapter built on `ruleAction` (`char/actions/rule-answer.ts`). It extracts `unit` and `type` (or `mod` for module research) using `stringParam` and `intParam` (`char/actions/payload-params.ts`). Missing parameters return `undefined` (which `ruleAction` turns into `!ERROR:BAD_PARAMS`); valid parameters return a pure rule closure:
`(profile) => chooseResearchTarget(profile, rules, vehicle, type)`.
3. **Profile Load & Pure Domain Rule (`apps/server/src/research/research-progress.ts`)**
After resolving the account via `withAccount`, `ruleAction` calls `profiles.updateWhen(account.userId, ...)` (`profile/player-profiles.ts`), which loads `<data>/saves/<userId>/profile.blk` through `SaveStore.loadProfile` and passes the `BlkBlock` into `chooseResearchTarget`:
- Looks up the vehicle in the startup-extracted tech-tree dataset via `rules.techTree.vehicle(vehicleName)` and verifies `vehicleTypeById(typeId) === vehicle.type`;
- Verifies `currentStatus(profile, rules, vehicleName) === VehicleStatus.CAN_RESEARCH`. If the vehicle is locked or already owned, it returns `refused('NOT_AVAILABLE')` (`{ ok: false, refusal: 'NOT_AVAILABLE' }`)—causing `updateWhen` to return `undefined` **without touching the disk** and `ruleAction` to reply `!ERROR:NOT_AVAILABLE`;
- Otherwise, updates the active target and clears any pending finished-research prompt via `profile/profile-research-targets.ts`, returning `ACCEPTED` (`{ ok: true }`).
4. **Atomic Disk Persistence BEFORE Replying (`profile/player-profiles.ts` -> `saves/save-store.ts` -> `storage/atomic-file.ts`)**
When the closure accepts, `PlayerProfiles.updateWhen` runs `#refresh(profile, userId)` to bring derived profile state (unlocked ranks, statuses, clan sync, earned unlocks) up to date, then calls `SaveStore.saveProfile(userId, profile)`. `saveProfile` calls `writeFileAtomic` (`storage/atomic-file.ts`), which writes `profile.blk.<pid>.<rand>.tmp`, flushes hardware buffers via `fsyncSync(fd)`, and atomically `renameSync`s it over `profile.blk` (with Windows transient-lock retries) before updating `save.json`. **Only after both atomic writes succeed** does `ruleAction` project `clientProfile(profile, account)` and `toResponse` (`char/char-answers.ts`) send HTTP 200 (`0x69` uncompressed marker + binary BLK) back to `aces.exe`.
### 2.4 Save Schema Upgrades (`saves/save-upgrades.ts`)
- **Domain rules always target only the current profile schema**: never scatter ad-hoc legacy compatibility branches (`if (oldFieldExists) ...`) across `research/`, `modifications/`, or `battle/`.
- When a release changes what `profile.blk` stores, append an ordered `SaveUpgrade` step to `SaveUpgrades` (`saves/save-upgrades.ts`, where `steps[n]` transforms a `formatVersion` `n + 1` profile into `n + 2` in place, bumping `currentFormat`). When `SaveStore.loadProfile` opens a save from an earlier release, it runs the missing steps in order and immediately persists the upgraded profile at `currentFormat`. Unreleased work-in-progress structures on a development branch do not need migration shims.
---
<a id="values-en"></a>
## 3. Three Categories of Values (Keep Boundaries Clear)
Every number or constant in WTOffline belongs to exactly one of three categories:
| Category | Concrete examples | Where it MUST live | Anti-pattern to avoid |
| --- | --- | --- | --- |
| **1. Protocol & engine constants** | Wire/MPI message IDs (`LMP_MPI_MSG_UNIT_RESPAWN = 0xf030u`), `PBBD` magic (`0x44424250`), Dagor container layouts (`dag::Vector` offsets, `FastNameMap` shifts), bitmasks | Named constants in the relevant protocol module or header, with an **English comment citing the primary source** (client version + RVA, or [DagorEngine open-source](https://github.com/GaijinEntertainment/DagorEngine) file path) | Bare magic numbers like `if (msgId == 61488)` or `if (st == 64)` with zero provenance comment |
| **2. Stock game facts** | Vehicle SL/GE prices, RP requirements, battle ratings, repair costs, modification trees, mission lists, tutorial first-win rewards, killstreak spawn altitude/distance/speed | Extracted from the player's read-only `.vromfs.bin` archives at startup via `apps/server/src/game-data/datasets/` (`Dataset<T>`) and cached in `<data>/cache/datasets/<id>.json` by `DatasetCache`. Throw an explicit `Error` if a required block/field is missing | Copying a table of vehicle costs, tutorial rewards, or spawn coordinates from one client build into TS/C code, or silently falling back to `?? 10000` when a lookup fails |
| **3. Offline tuning & defaults** | SL/RP reward multipliers, new-profile starting balances, local store bundle prices, supply-chest drop weights, AI bot respawn counts, request caps, gameplay toggles | Shipped defaults in `apps/server/tuning/<domain>.jsonc`, validated for type and bounds at startup via `TuningReader` in `<domain>/*-tuning.ts`, and merged by `tuning-loader.ts` across shipped defaults -> enabled mod overrides -> player `<data>/tuning/<domain>.jsonc` overrides | Hardcoding `const RP_MULTIPLIER = 3.0` or arbitrary caps inside a settlement function where players and mods cannot override them |
---
<a id="4-good-vs-bad-code-patterns-real-pitfalls"></a>
<a id="good-vs-bad-en"></a>
## 4. Good vs. Bad Code: 4 Real Codebase Comparisons
Every "✅ Good" snippet below uses the exact symbols and files from this repository. Check your changes against all four before opening a PR.
### Comparison 1: Native C Hooks — `g_lmp` Dynamic Captures & Scoped TLS Flags vs. Hardcoded Offsets & `_ReturnAddress()`
Whenever War Thunder ships a minor patch (e.g., `2.61.0.37` -> `2.61.0.58`), function RVAs shift across `.text` and C++ class member offsets move whenever fields are added or reordered.
```c
// ❌ BAD: Hardcoded RVAs, hardcoded struct offset (+0x3798), and brittle _ReturnAddress() caller check.
// The very next minor game update will silently break the feature or crash the client!
static void __fastcall bad_hook_send_unit_respawn(uint8_t *unit, const void *spawn)
{
uintptr_t base = (uintptr_t)GetModuleHandleW(NULL);
if ((uintptr_t)_ReturnAddress() != base + 0x1281280)
return;
const uint8_t *gameplay = *(const uint8_t *const *)(base + 0x7bad2f0);
const uint8_t *rules = *(const uint8_t *const *)(gameplay + 0x3798);
/* ... */
}
```
```c
// ✅ GOOD (Real code: native/wto-net/src/local_mp_air_events.c + local_mp_offsets.h + local_mp_values.h):
// 1. Every RVA and struct offset is dynamically captured in patches/native/local_mp_air_events.jsonc,
// written to wto_ws.cfg, and loaded into extern LmpValues g_lmp (LMP_GP_OFF_KS_RULES -> g_lmp.gp_ks_rules);
// 2. An outer detour + thread-local flag (__declspec(thread)) scopes the call cleanly without _ReturnAddress().
static SwitchPlayerUnitFn orig_switch_player_unit;
static __declspec(thread) int g_in_air_event_switch;
static void __fastcall hook_switch_player_unit(void *event_mgr, void *participant, uint8_t to_air)
{
int previous = g_in_air_event_switch;
if (to_air != 0 && ground_arcade_air_events_enabled())
g_in_air_event_switch = 1;
orig_switch_player_unit(event_mgr, participant, to_air);
g_in_air_event_switch = previous;
}
// Struct offsets come from g_lmp, surviving minor client updates automatically:
const uint8_t *gameplay = g_lmp.gameplay ? *(const uint8_t *const *)g_lmp.gameplay : NULL;
const uint8_t *rules = *(const uint8_t *const *)(gameplay + LMP_GP_OFF_KS_RULES);
uint32_t rule_count = *(const uint32_t *)(gameplay + LMP_GP_OFF_KS_RULE_COUNT);
```
### Comparison 2: Stock Game Data — `DatasetCache` Extraction + Pure Catalogue vs. Hardcoded TS Maps
```ts
// ❌ BAD: Hardcoding tutorial mission rewards from one client build directly in server code
const TUTORIAL_REWARDS: Record<string, { silverLions: number; goldenEagles: number }> = {
'tutorialB_fighter': { silverLions: 5000, goldenEagles: 100 },
'tutorialB_assaulter': { silverLions: 5000, goldenEagles: 0 },
};
```
```ts
// ✅ GOOD (Real code: apps/server/src/game-data/datasets/training-missions.ts
// + apps/server/src/training/training-completion.ts):
// 1. Define a versioned Dataset<T> that extracts stock data from char.vromfs.bin
// (config/mislist.blk, config/pve_awards.blk, config/unlocks.blk) and throws if required blocks are missing.
export const trainingMissions: Dataset<TrainingMissionsData> = {
id: 'training-missions',
version: 1,
extract(source: DatasetSource): TrainingMissionsData {
const misSection = blockAt(source.readBlk('char.vromfs.bin', 'config/mislist.blk'), 'training');
if (!misSection) throw new Error('config/mislist.blk has no "training" block');
const awardSection = blockAt(source.readBlk('char.vromfs.bin', 'config/pve_awards.blk'), 'training');
if (!awardSection) throw new Error('config/pve_awards.blk has no "training" block');
// ... build and return { missions }
return { missions };
},
};
// 2. Load through DatasetCache at startup and pass pure data into TrainingCatalogue:
const trainingCatalogue = new TrainingCatalogue(datasets.load(trainingMissions));
trainingCatalogue.applyCompletion(profile, { chapter, mission, difficulty });
```
### Comparison 3: Fixing at the Right Layer & Toolchain Discipline (MSVC C & Node 24 TypeScript)
**(A) Check stock loader fields before writing a client patch**
- ❌ **Bad instinct**: Notice AI bots only respawn once in multi-slot Air Arcade battles and immediately start reversing `BotSystem` to write an `aces.exe` memory patch.
- ✅ **Good engineering**: Inspect `MissionSettings::load` first and discover that the stock client already reads `numBotRespawns` and `numTankBotRespawns` from the mission root `DataBlock`—the local server simply omitted those two root parameters when assembling multi-slot missions. Adding them in `apps/server` fixes the issue in 5 lines with **zero client patches** and permanent cross-version stability.
**(B) MSVC C rules & Node 24 native TypeScript rules**
- **Native C (`native/wto-net/`)**: Compiled by Visual Studio `cl.exe` via `native/wto-net/build.ps1` with `/W4` and **zero warnings**. Verify stack/wire struct layouts at compile time with `C_ASSERT(sizeof(LocalMpAirSpawn) == 0x48);`, use `__declspec(thread)` for TLS and `__declspec(align(16))` for alignment, and **never use GCC/Clang extensions** (`__attribute__`, VLAs, zero-length arrays, or `void *` pointer arithmetic).
- **TypeScript (`tsconfig.json`)**: Executed directly by Node.js 24 native type-stripping with `erasableSyntaxOnly: true`, `verbatimModuleSyntax: true`, `allowImportingTsExtensions: true`, and `exactOptionalPropertyTypes: true`:
```ts
// ❌ BAD: Extensionless relative import, value-importing a type, using `enum`, and constructor parameter properties
import { SaveStore, SaveUpgrades } from '../saves/save-store';
export enum ResearchState { Locked = 0, Available = 1 }
export class Handler {
constructor(private readonly saves: SaveStore) {}
}
```
```ts
// ✅ GOOD: Explicit `.ts` extension on all relative imports, `import type` for types, `as const` objects instead of `enum`, and `#private` fields
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import type { SaveUpgrades } from './save-upgrades.ts';
export const VehicleStatus = {
CAN_RESEARCH: 2,
OWNED: 4,
} as const;
```
### Comparison 4: Real Verification vs. Mock Test Suites
- ❌ **Bad practice**: Editing `patches/gui/` and only eyeballing indentation—or writing 300 lines of mock unit tests that simulate fake server/client calls—and declaring the change "fully tested", only for login to hang forever on a Quirrel `from ... import *` scope collision or `loadGuiPatches` to throw `DefinitionError` on an unknown JSONC key.
- ✅ **Good practice**: Run the real verification tools matching your change (`npm run typecheck`, `wtotools check-patches`, full `wtotools check-gui` with `sq.exe`, MSVC `native\wto-net\build.ps1`, `scripts/build-game-copy.ts`), and **honestly separate executed CLI checks from pending in-game acceptance steps** in your PR description.
---
<a id="ai-guide-en"></a>
## 5. Working Effectively with AI Coding Assistants (Copy-Paste Prompt Block)
Using AI assistants (Claude Code, Codex, Cursor, etc.) to read disassembly, trace `.nut` UI call chains, inspect BLK schemas, and pinpoint protocol mismatches is warmly welcomed.
However, without explicit project context, AI tools frequently invent hardcoded RVAs, add an invalid `requires` field to `patches/gui/**/patch.jsonc`, omit `.ts` import extensions, write `enum` declarations, or generate bloated mock test suites. **Paste the constraint block below into your AI session before asking it to write or edit code**:
```text
I am preparing a change for the WTOffline repository. Before writing any code, always read the real source files to verify symbols, struct fields, and CLI flags, and follow these engineering rules strictly:
1. Layer priority: Ground every change in primary sources (read-only stock .vromfs.bin archives, gui.vromfs.bin .nut scripts, DagorEngine open-source code). Solve issues in apps/server protocol answers, mission BLK fields, or stock datasets before adding any client patch under patches/gui/, patches/exe/, or native/wto-net/.
2. Zero hardcoded addresses or offsets: Never hardcode function RVAs, global addresses, C++ struct offsets, or _ReturnAddress() caller checks in C or TS. Capture all native symbols and offsets dynamically via patches/exe/ or patches/native/*.jsonc (signature / string_ref / within) into wto_ws.cfg, read them in C exclusively through `extern LmpValues g_lmp` (local_mp_values.h / local_mp_offsets.h), and replace caller checks with an outer hook + `__declspec(thread)` flag. When capturing a `rel32` from an instruction that has trailing immediate bytes after disp32, always pass `"end"` set to the full instruction byte length.
3. Three value categories: Extract stock game numbers (vehicle prices, RP, rewards, missions, spawn params) from stock archives via `apps/server/src/game-data/datasets/` (`DatasetCache`), throwing explicitly if required fields are missing. Put offline defaults/multipliers/toggles in `apps/server/tuning/*.jsonc` validated via `*-tuning.ts`. Keep protocol/engine constants in code with English comments citing the client build RVA or DagorEngine source path.
4. Layer & dependency rules: `packages/*` must never import or read from `apps/*`. Inside `apps/server/src/`, keep transport/protocol (`char/actions/`, etc.), pure domain rules (`research/`, `battle/`, `modifications/`, etc. — note there is NO `rules/` folder; zero network/disk I/O in domain modules), and profile/persistence (`profile/`, `saves/`, `storage/atomic-file.ts` — always persist atomically to disk BEFORE replying) cleanly separated. Handle save schema evolution only via `formatVersion` steps in `saves/save-upgrades.ts`, never ad-hoc legacy branches in domain rules. Split files near 300 lines or functions near 50 lines.
5. Strict toolchain & schema rules:
- TypeScript runs on Node 24 native type-stripping (`erasableSyntaxOnly`, `verbatimModuleSyntax`, `allowImportingTsExtensions`): include explicit `.ts` extensions on all relative imports, use `import type` for type-only imports, and never use `enum`, `namespace`, or constructor parameter properties.
- Native C must compile cleanly with MSVC `native/wto-net/build.ps1` (`/W4`, zero warnings), using `C_ASSERT` for layout checks and zero GCC extensions; register any new `.c` file in `build.ps1`'s `$sources` list.
- Patch JSONC files reject unknown keys: in particular, `patches/gui/**/patch.jsonc` allows ONLY `id`, `title`, `features`, and `variants` at top level (adding `requires` throws `DefinitionError`!).
6. Real verification: Do not add large mock unit test suites. Run the applicable real checks (`npm run typecheck`, `wtotools check-patches`, full `wtotools check-gui` with `--sq`, `native/wto-net/build.ps1`, `scripts/build-game-copy.ts`) and clearly separate executed CLI checks from pending isolated in-game acceptance steps.
7. PR hygiene: Keep one focused goal per PR; write code comments, patch `title`/3-line header comments, and conventional commit messages in English; never list AI tools in `Co-authored-by`; and never commit `patches/versions/*.jsonc` before live in-game verification in an isolated copy.
```
---
<a id="isolation-en"></a>
## 6. Isolation & Asset Boundaries (Non-Negotiable)
1. **Keep the official stock installation strictly read-only**: Unpacking archives, running `tools/re/cli.py`, checking patches with `wtotools`, and building game copies must only ever read the stock client folder—**never write, modify, or drop files inside a Steam or official launcher installation**.
2. **Test exclusively in an isolated offline copy**: Run the patched client only from a separate directory outside your Steam library, with all three `ESSENTIAL_FEATURES` safety locks active—all network calls redirected to `127.0.0.1` by `wto_ws.dll`, user files isolated under `WTOffline`, registry state under `Software\WTOffline`, anti-cheat and crash reporting disabled, and signed in only with a local offline account.
3. **Zero copyrighted assets or private data in Git**: Never commit `.vromfs.bin` packs, `aces.exe`, full extracted stock `.nut` / `.blk` files, personal player saves, machine-specific paths, or unredacted logs to the repository.
+943 -44
View File
File diff suppressed because it is too large. Load diff
+18 -7
View File
@@ -1,23 +1,34 @@
## Change ## Change
<!-- Describe the player-visible result and the scope of this PR. --> <!-- Describe the player-visible result and the single focused goal of this PR. -->
## Reason and evidence ## Reason and evidence
<!-- Give the target client build and the relevant game file, script, or official source. --> <!-- Give the target client build (e.g. 2.61.0.37) and cite the primary source: stock archive file, .nut script, RVA, or DagorEngine source path. -->
<!-- For a client patch, explain why the local service or game configuration is insufficient. --> <!-- For any client patch (patches/gui, patches/exe, native/wto-net), explain why apps/server or stock BLK configuration cannot solve it. -->
<!-- For tuning changes, record the source and unit of the new defaults. --> <!-- For tuning changes (apps/server/tuning/*.jsonc), record the rationale, bounds, and units of the new defaults. -->
## Client compatibility ## Client compatibility
<!-- List the affected builds and any change to patch variants or version records. --> <!-- List the tested/affected client builds and any added patch variants or patches/versions/<version>.jsonc updates. -->
<!-- Reminder: never commit patches/versions/<version>.jsonc until live isolated in-game acceptance is complete. -->
## Self-check
- [ ] No hardcoded addresses, RVAs, C++ struct offsets, or `_ReturnAddress()` checks (all native values resolved dynamically into `g_lmp` via `patches/`, with explicit `"end"` on `rel32` captures that have trailing immediate bytes)
- [ ] No hardcoded stock game numbers or silent fallback defaults (extracted from stock archives via `game-data/datasets/` or validated in `tuning/*.jsonc`)
- [ ] Layer & persistence rules preserved (`packages/*` never imports `apps/*`; domain modules stay free of network/disk I/O; profile mutations persist atomically via `PlayerProfiles` / `SaveStore` before replying)
- [ ] Toolchain & schema rules met (explicit `.ts` extensions on relative imports, `import type` for types, no `enum`/`namespace`/parameter properties; strict patch JSONC keys—e.g., no `requires` in `patches/gui/**/patch.jsonc`; new `.c` files added to `native/wto-net/build.ps1`)
- [ ] Focused on one goal, English comments / patch `title` / conventional commit message used, no AI `Co-authored-by` trailers, and no personal paths, game assets, or unredacted logs in `git diff`
- [ ] Every command listed in **Checks run** was actually executed (including `wtotools check-gui --sq ...` for `patches/gui/` and MSVC `native/wto-net/build.ps1` with zero warnings for `native/`)
## Checks run ## Checks run
| Command or check | Client build if relevant | Result | | Command or check | Client build (if relevant) | Result |
| --- | --- | --- | | --- | --- | --- |
| | | | | | | |
## In-game acceptance ## In-game acceptance
<!-- Give the screen or entry point, the action, and the expected result. Record what was observed or mark the check pending. --> <!-- Give the exact screen or entry point, the action to perform, and the expected result in an isolated offline copy. -->
<!-- Clearly state what was observed in-game, or explicitly mark steps that are still pending live verification. -->
Loaded 100 of 247 files, more files were not shown because too many files have changed in this diff. Show more