refactor(repo)!: move apps, shared packages, and patch definitions

Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:

  apps/server        the local server (was packages/local-service),
                     package @wto/server
  packages/patcher   builds the game copy (was packages/build),
                     package @wto/patcher
  patches/exe        exe patch definitions (was exe-patches)
  patches/gui        GUI script patches (was gui-patches)

Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".

The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.

The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.


Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.

BREAKING CHANGE: Use @wto/server and @wto/patcher from the new workspace paths. Run the development build with scripts/build-game-copy.ts and pass --data.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 03:20:54 +08:00
1 parent 9c813ccf7d
commit 930ea07630
476 files changed
+275 -251

No files matched your search

@@ -0,0 +1,37 @@
/**
* Picking a research target for a branch that has none.
*
* The stock game never leaves a country and vehicle type without a vehicle in research while
* one can be researched: the char server sets the target itself, and the client only asks the
* player to confirm it (aces.exe 2.61.0.37 0x17a45e0 shop_get_countries_list_with_autoset_units
* returns {country, unit = currUnit, prevUnit}; scripts/researches/researchActions.nut
* checkNonApprovedResearches opens scripts/shop/shopCheckResearch.nut, which keeps a target
* that is still being researched). Which vehicle the server picks is not in the client, so the
* pick is offline tuning (tuning/research.jsonc autoTargetPick).
*/
import type { AutoTargetPick, ResearchTuning } from './research-tuning.ts';
import type { TreeVehicle } from './tech-tree.ts';
/** The vehicle to research among the branch's researchable candidates; undefined when there are none. */
export function pickResearchTarget(
candidates: readonly TreeVehicle[],
tuning: ResearchTuning,
previousUnitName: string = '',
): TreeVehicle | undefined {
if (tuning.preferLineSuccessor && previousUnitName) {
const successors = candidates.filter((vehicle) => vehicle.requires === previousUnitName);
if (successors.length > 0) return [...successors].sort(ORDERS[tuning.autoTargetPick])[0];
}
return [...candidates].sort(ORDERS[tuning.autoTargetPick])[0];
}
type Order = (a: TreeVehicle, b: TreeVehicle) => number;
const byTree: Order = (a, b) => a.treeOrder - b.treeOrder;
const byPointsThenTree: Order = (a, b) => a.researchPoints - b.researchPoints || byTree(a, b);
const ORDERS: Readonly<Record<AutoTargetPick, Order>> = {
highestRank: (a, b) => b.rank - a.rank || byPointsThenTree(a, b),
lowestRank: (a, b) => a.rank - b.rank || byPointsThenTree(a, b),
treeOrder: byTree,
};
@@ -0,0 +1,23 @@
/**
* Buying a crew slot (cln_buy_slot, implementation notes).
*
* The price of a country's next slot is config/rank.blk crew_slots slot<N>, N being the
* number of crews the country has, as the client shows it (get_crew_slot_cost, aces.exe
* 2.61.0.37 0x90eaa0). Without a slot<N> there is nothing more to buy. The new crew is empty
* and numbered after every existing crew.
*/
import type { BlkBlock } from '@wto/blk';
import { addCrew, crewCountOf } from '../profile/profile-crews.ts';
import { canAfford, pay } from '../profile/profile-currency.ts';
import type { ResearchRules } from './research-rules.ts';
import { ACCEPTED, refused, type RuleOutcome } from './rule-outcome.ts';
export function buyCrewSlot(profile: BlkBlock, rules: ResearchRules, country: string): RuleOutcome {
if (!rules.techTree.hasCountry(country)) return refused('BAD_PARAMS');
const price = rules.crewSlotPrices[crewCountOf(profile, country)];
if (!price) return refused('NOT_AVAILABLE');
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
addCrew(profile, country);
return ACCEPTED;
}
+42
View File
@@ -0,0 +1,42 @@
/**
* Opening ranks.
*
* rank.blk needBuyToOpenNextInEra gives, per country, how many vehicles of rank k a vehicle
* type must own before rank k+1 opens: the name with the type first
* ("needBuyToOpenNextInEraTank3"), then without it ("needBuyToOpenNextInEra3"); neither means
* no requirement (scripts/unit/unitInfo.nut getUnitsNeedBuyToOpenNextInEra returns -1, which
* leaves nothing to buy). Owned vehicles count whatever their kind, at exactly that rank, as
* the stock tech tree counts them (scripts/shop/shop.nut updateBoughtVehiclesCount). Rank k+1
* is open when every rank up to k has enough; rank I is always open.
*/
import type { BlkBlock } from '@wto/blk';
import type { EraRequirements } from '../game-data/datasets/rank-settings.ts';
import { openRanksUpTo } from '../profile/profile-eras.ts';
import type { TechTree } from './tech-tree.ts';
import type { VehicleType } from './vehicle-types.ts';
/** Open every rank the owned vehicles allow; ranks never close. Returns whether anything changed. */
export function openEarnedRanks(profile: BlkBlock, owned: ReadonlySet<string>, techTree: TechTree, requirements: EraRequirements): boolean {
const ownedByRank = new Map<string, number>();
for (const vehicle of techTree.all()) {
if (!owned.has(vehicle.name)) continue;
const key = rankKey(vehicle.country, vehicle.type, vehicle.rank);
ownedByRank.set(key, (ownedByRank.get(key) ?? 0) + 1);
}
let changed = false;
for (const { country, type, highestRank } of techTree.branches()) {
let open = 1;
while (open < highestRank && (ownedByRank.get(rankKey(country, type, open)) ?? 0) >= vehiclesNeeded(requirements, country, type, open)) open++;
if (openRanksUpTo(profile, country, type, open)) changed = true;
}
return changed;
}
function vehiclesNeeded(requirements: EraRequirements, country: string, type: VehicleType, rank: number): number {
const forCountry = requirements[country];
return forCountry?.[`needBuyToOpenNextInEra${type}${rank}`] ?? forCountry?.[`needBuyToOpenNextInEra${rank}`] ?? 0;
}
function rankKey(country: string, type: VehicleType, rank: number): string {
return `${country}/${type}/${rank}`;
}
@@ -0,0 +1,101 @@
/**
* How much of a battle's vehicle Research Points reaches the researched vehicle (game data:
* game-data/datasets/research-efficiency.ts; rules from the official wiki "Research Points"
* https://wiki.warthunder.com/Research_Points and the news "Following the Roadmap: Vehicle
* Research Bonuses", 2024-09-24, whose numbers match rank.blk):
*
* - Rank difference: researching a vehicle N ranks above or below the one played costs
* expPenaltyPercentForHigherRank<N> / expPenaltyPercentForLowerRank<N> percent. A premium
* vehicle researching lower-ranked vehicles has no penalty (the older wiki "Research Points"
* page says so; the current page does not mention it, so this is kept but unconfirmed).
* - Predecessor: playing the vehicle directly before the researched one (its reqAir) adds
* expBonusPercentForChildForMode<diffCode> percent and overrides the rank penalty.
* - Vehicle Research Bonus: once the player owns a "top" vehicle of a vehicle type in any nation,
* every nation's research of that type gets ExpNewNationBonus[type][rank of the researched
* vehicle] percent of the base Research Points, for expNewNationBonusDailyBattleCount battles per
* nation and type per day (00:00 GMT). A top vehicle is researchable (not premium, pack, event,
* squadron or hidden), ends a research line (the first vehicle when the line ends in a group),
* sits at the tree's highest rank and is at most two battle rating steps below the tree's
* highest battle rating. Not modelled: the exclusion of vehicles "considered new" (the game files
* carry no release dates).
*/
import type { ResearchEfficiencyData } from '../game-data/datasets/research-efficiency.ts';
import type { EconomyDifficulty } from '../game-data/datasets/battle-economy.ts';
import { isPremiumKind, type TechTree, type TreeVehicle } from './tech-tree.ts';
/** The client's diffCode of each difficulty (scripts/airinfo.nut reads the child bonus with it). */
const DIFF_CODE: Readonly<Record<EconomyDifficulty, number>> = { arcade: 0, historical: 1, simulation: 2 };
/** Battle rating steps a top vehicle may sit below its tree's highest battle rating. */
const TOP_VEHICLE_MRANK_STEPS = 2;
export interface ResearchEfficiencyTerms {
readonly childBonusPercent: number;
readonly rankDiffPenaltyPercent: number;
}
export class ResearchEfficiency {
readonly #data: ResearchEfficiencyData;
readonly #tree: TechTree;
readonly #topVehicles: ReadonlySet<string>;
constructor(data: ResearchEfficiencyData, tree: TechTree) {
this.#data = data;
this.#tree = tree;
this.#topVehicles = topVehiclesOf(data.lineEnds, tree);
}
get dailyBonusBattles(): number {
return this.#data.nationBonusDailyBattles;
}
/** Predecessor bonus or rank penalty of RP earned in `played` and invested into `researched`. */
termsFor(played: TreeVehicle, researched: TreeVehicle, difficulty: EconomyDifficulty): ResearchEfficiencyTerms {
if (researched.requires === played.name) {
return { childBonusPercent: this.#data.childBonusPercent[DIFF_CODE[difficulty]] ?? 0, rankDiffPenaltyPercent: 0 };
}
const diff = researched.rank - played.rank;
if (diff < 0 && isPremiumKind(played.kind)) return { childBonusPercent: 0, rankDiffPenaltyPercent: 0 };
const series = diff >= 0 ? this.#data.higherRankPenaltyPercent : this.#data.lowerRankPenaltyPercent;
const percent = series[Math.min(Math.abs(diff), series.length - 1)] ?? 0;
return { childBonusPercent: 0, rankDiffPenaltyPercent: percent };
}
/** The Vehicle Research Bonus percent for researching `researched`, given the vehicles the player owns. */
nationBonusPercent(researched: TreeVehicle, owned: ReadonlySet<string>): number {
const hasTop = [...this.#topVehicles].some((name) => owned.has(name) && this.#tree.vehicle(name)?.type === researched.type);
if (!hasTop) return 0;
return this.#data.nationBonusPercent[researched.type]?.[researched.rank] ?? 0;
}
}
function topVehiclesOf(lineEnds: readonly string[], tree: TechTree): Set<string> {
const highestRank = new Map(tree.branches().map((branch) => [`${branch.country}/${branch.type}`, branch.highestRank]));
const highestMrank = new Map<string, number>();
for (const vehicle of tree.all()) {
if (!vehicle.inTechTree || vehicle.kind === 'hidden' || vehicle.kind === 'part') continue;
const key = `${vehicle.country}/${vehicle.type}`;
highestMrank.set(key, Math.max(highestMrank.get(key) ?? 0, maxMrank(vehicle)));
}
const top = new Set<string>();
for (const name of lineEnds) {
const vehicle = tree.vehicle(name);
if (!vehicle || vehicle.kind !== 'research') continue;
const key = `${vehicle.country}/${vehicle.type}`;
if (vehicle.rank !== highestRank.get(key)) continue;
if (maxMrank(vehicle) < (highestMrank.get(key) ?? 0) - TOP_VEHICLE_MRANK_STEPS) continue;
top.add(name);
}
return top;
}
/** The highest economic rank of a vehicle over the game modes ("maximum BR among all game modes"). */
function maxMrank(vehicle: TreeVehicle): number {
return Math.max(
vehicle.economicRankArcade,
vehicle.economicRankHistorical,
vehicle.economicRankSimulation,
vehicle.economicRankTankHistorical ?? 0,
vehicle.economicRankTankSimulation ?? 0,
);
}
@@ -0,0 +1,111 @@
/**
* Choosing what to research and putting research points into a vehicle (implementation notes
* sections 1.2, 4.3 and 5).
*
* - Choosing a research target (cln_set_researchable) makes a researchable vehicle the
* target of its country and type and closes the "research finished" prompt.
* - Dismissing that prompt (cln_reset_researchable) only closes it.
* - Converting free research points (cln_convert_exp) costs the points and golden eagles:
* one golden eagle per researchPointsPerGoldenEagle points, rounded up. The stock window
* (scripts/convertExp/convertExpHandler.nut) never asks for more than the vehicle still
* needs; more is cut down to that.
* - Spending banked excess research points (cln_move_exp_to_unit) puts the branch's
* researchUnits/<country>/exp<Type> into the chosen vehicle, up to what it still needs.
* - When a vehicle's research points reach what it needs and it is the target, the target is
* cleared and the vehicle recorded as just finished, which makes the client offer the next
* research (research-state.ts).
*/
import type { BlkBlock } from '@wto/blk';
import { balanceOf, pay } from '../profile/profile-currency.ts';
import { freeResearchPoints, spendFreeResearchPoints } from '../profile/profile-research-points.ts';
import {
branchExcessRp,
researchTarget,
setBranchExcessRp,
setFinishedResearch,
setResearchTarget,
} from '../profile/profile-research-targets.ts';
import { researchPointsOf, setResearchPoints } from '../profile/profile-vehicle-research.ts';
import type { ResearchRules } from './research-rules.ts';
import { currentStatus } from './research-state.ts';
import { ACCEPTED, refused, type RuleOutcome } from './rule-outcome.ts';
import type { TreeVehicle } from './tech-tree.ts';
import { VehicleStatus } from './vehicle-status.ts';
import { vehicleTypeById } from './vehicle-types.ts';
export function chooseResearchTarget(
profile: BlkBlock,
rules: ResearchRules,
vehicleName: string,
typeId: number,
): RuleOutcome {
const vehicle = rules.techTree.vehicle(vehicleName);
if (!vehicle || vehicleTypeById(typeId) !== vehicle.type) return refused('BAD_PARAMS');
if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE');
setResearchTarget(profile, vehicle.country, vehicle.type, vehicle.name);
setFinishedResearch(profile, vehicle.country, vehicle.type, '');
return ACCEPTED;
}
export function dismissFinishedResearch(
profile: BlkBlock,
rules: ResearchRules,
country: string,
typeId: number,
): RuleOutcome {
const type = vehicleTypeById(typeId);
if (!type || !rules.techTree.hasCountry(country)) return refused('BAD_PARAMS');
setFinishedResearch(profile, country, type, '');
return ACCEPTED;
}
export function convertFreeResearchPoints(
profile: BlkBlock,
rules: ResearchRules,
vehicleName: string,
requested: number,
): RuleOutcome {
const vehicle = rules.techTree.vehicle(vehicleName);
if (!vehicle || !Number.isSafeInteger(requested) || requested <= 0) return refused('BAD_PARAMS');
if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE');
const amount = Math.min(requested, vehicle.researchPoints - researchPointsOf(profile, vehicle.name));
const goldenEagles = Math.ceil(amount / rules.researchPointsPerGoldenEagle);
if (freeResearchPoints(profile) < amount) return refused('NOT_ENOUGH_RESEARCH_POINTS');
if (balanceOf(profile).goldenEagles < goldenEagles) return refused('NOT_ENOUGH_MONEY');
pay(profile, { silverLions: 0, goldenEagles });
spendFreeResearchPoints(profile, amount);
addResearchPoints(profile, vehicle, amount);
return ACCEPTED;
}
export function moveExcessExpToUnit(profile: BlkBlock, rules: ResearchRules, vehicleName: string): RuleOutcome {
const vehicle = rules.techTree.vehicle(vehicleName);
if (!vehicle) return refused('BAD_PARAMS');
if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE');
const available = branchExcessRp(profile, vehicle.country, vehicle.type);
const before = researchPointsOf(profile, vehicle.name);
const needed = Math.max(0, vehicle.researchPoints - before);
const moved = Math.min(available, needed);
if (moved <= 0) return ACCEPTED;
const remaining = available - moved;
setBranchExcessRp(profile, vehicle.country, vehicle.type, remaining);
setResearchPoints(profile, vehicle.name, before + moved);
if (before + moved >= vehicle.researchPoints) {
setResearchTarget(profile, vehicle.country, vehicle.type, '');
setFinishedResearch(profile, vehicle.country, vehicle.type, remaining > 0 ? '' : vehicle.name);
} else {
setResearchTarget(profile, vehicle.country, vehicle.type, vehicle.name);
setFinishedResearch(profile, vehicle.country, vehicle.type, '');
}
return ACCEPTED;
}
export function addResearchPoints(profile: BlkBlock, vehicle: TreeVehicle, amount: number): void {
const before = researchPointsOf(profile, vehicle.name);
setResearchPoints(profile, vehicle.name, before + amount);
const finished = before < vehicle.researchPoints && before + amount >= vehicle.researchPoints;
if (finished && researchTarget(profile, vehicle.country, vehicle.type) === vehicle.name) {
setResearchTarget(profile, vehicle.country, vehicle.type, '');
setFinishedResearch(profile, vehicle.country, vehicle.type, vehicle.name);
}
}
@@ -0,0 +1,35 @@
/**
* Static facts used by vehicle research and purchase rules, loaded once at startup from game
* files (implementation notes; implementation notes).
*/
import type { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
import { crewSlotPrices, eraRequirements, type CrewSlotPrices, type EraRequirements } from '../game-data/datasets/rank-settings.ts';
import { researchPointsPerGoldenEagle } from '../game-data/datasets/research-point-rate.ts';
import { vehicleCatalogue, type CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import { vehicleUnlocks, type UnlockDefinition } from '../game-data/datasets/vehicle-unlocks.ts';
import type { ResearchTuning } from './research-tuning.ts';
import { TechTree } from './tech-tree.ts';
export interface ResearchRules {
readonly techTree: TechTree;
readonly eraRequirements: EraRequirements;
readonly vehicleUnlocks: readonly UnlockDefinition[];
readonly crewSlotPrices: CrewSlotPrices;
readonly researchPointsPerGoldenEagle: number;
readonly researchTuning: ResearchTuning;
}
export function loadResearchRules(
datasets: DatasetCache,
researchTuning: ResearchTuning,
vehicles: readonly CatalogueVehicle[] = datasets.load(vehicleCatalogue),
): ResearchRules {
return {
techTree: new TechTree(vehicles),
eraRequirements: datasets.load(eraRequirements),
vehicleUnlocks: datasets.load(vehicleUnlocks),
crewSlotPrices: datasets.load(crewSlotPrices),
researchPointsPerGoldenEagle: datasets.load(researchPointsPerGoldenEagle),
researchTuning,
};
}
+113
View File
@@ -0,0 +1,113 @@
/**
* Bringing the research state of a profile up to date. The char
* server keeps it current online; the local server does it whenever a profile is handed out
* or changed (profile/player-profiles.ts), so the state always follows from the facts:
* owned vehicles, research points, earned unlocks, banked excess research points.
*
* 1. Open ranks and earn unlocks until neither changes anything (an unlock can give a vehicle,
* a vehicle can open a rank, a rank can earn an unlock).
* 2. Write every vehicle's status into unitResearch: owned vehicles have no entry, locked
* vehicles only keep one while they hold research points.
* 3. Keep every branch researching while it can: a target that is no
* longer researchable (bought, researched, ...) is cleared, and a new one is picked by
* auto-research-target.ts when the branch has just finished a vehicle (prevUnit set: the
* stock scripts then open the "choose the next research" window, ShopCheckResearch, from
* scripts/researches/researchActions.nut checkNonApprovedResearches) or has no banked
* exp<Branch>. With banked RP and nothing just finished it stays empty, so the player chooses
* where the RP goes (cln_move_exp_to_unit). A branch with nothing left to research has its
* banked RP cleared.
*/
import type { BlkBlock } from '@wto/blk';
import { ownedVehicles } from '../profile/profile-hangar.ts';
import {
branchExcessRp,
finishedResearch,
researchTarget,
setBranchExcessRp,
setResearchTarget,
} from '../profile/profile-research-targets.ts';
import { earnedUnlocks } from '../profile/profile-unlocks.ts';
import { removeVehicleResearch, researchPointsOf, setVehicleStatus } from '../profile/profile-vehicle-research.ts';
import { pickResearchTarget } from './auto-research-target.ts';
import { openEarnedRanks } from './era-progress.ts';
import type { ResearchRules } from './research-rules.ts';
import type { TreeVehicle } from './tech-tree.ts';
import { VehicleStatus, vehicleStatuses } from './vehicle-status.ts';
import { earnVehicleUnlocks } from './vehicle-unlock-rules.ts';
const MAX_ROUNDS = 16;
export function refreshResearchState(profile: BlkBlock, rules: ResearchRules): void {
const owned = ownedVehicles(profile);
const earned = earnedUnlocks(profile);
for (let round = 0; round < MAX_ROUNDS; round++) {
const ranksChanged = openEarnedRanks(profile, owned, rules.techTree, rules.eraRequirements);
const unlocksChanged = earnVehicleUnlocks(profile, { earned, owned }, rules.vehicleUnlocks, rules.techTree);
if (!ranksChanged && !unlocksChanged) break;
}
const statuses = vehicleStatuses({ profile, owned, earnedUnlocks: earned, techTree: rules.techTree });
for (const vehicle of rules.techTree.all()) {
const status = statuses.get(vehicle.name);
if (status === undefined || (status === VehicleStatus.LOCKED && researchPointsOf(profile, vehicle.name) === 0)) {
removeVehicleResearch(profile, vehicle.name);
} else {
setVehicleStatus(profile, vehicle.name, status);
}
}
const candidates = researchCandidates(rules, statuses);
const unresearchedBranches = branchesWithUnresearchedTreeVehicles(rules, statuses);
for (const { country, type } of rules.techTree.branches()) {
const key = `${country}/${type}`;
if (!unresearchedBranches.has(key)) {
setBranchExcessRp(profile, country, type, 0);
}
const target = researchTarget(profile, country, type);
if (target && statuses.get(target) === VehicleStatus.CAN_RESEARCH) continue;
if (target) setResearchTarget(profile, country, type, '');
const prev = finishedResearch(profile, country, type);
const excess = branchExcessRp(profile, country, type);
if (prev !== '' || excess === 0) {
const next = pickResearchTarget(candidates.get(key) ?? [], rules.researchTuning, target || prev);
setResearchTarget(profile, country, type, next?.name ?? '');
}
}
}
function researchCandidates(rules: ResearchRules, statuses: ReadonlyMap<string, VehicleStatus>): Map<string, TreeVehicle[]> {
const byBranch = new Map<string, TreeVehicle[]>();
for (const vehicle of rules.techTree.all()) {
if (vehicle.kind !== 'research' || statuses.get(vehicle.name) !== VehicleStatus.CAN_RESEARCH) continue;
const key = `${vehicle.country}/${vehicle.type}`;
const list = byBranch.get(key);
if (list) list.push(vehicle);
else byBranch.set(key, [vehicle]);
}
return byBranch;
}
function branchesWithUnresearchedTreeVehicles(
rules: ResearchRules,
statuses: ReadonlyMap<string, VehicleStatus>,
): Set<string> {
const branches = new Set<string>();
for (const vehicle of rules.techTree.all()) {
if (vehicle.kind !== 'research') continue;
const status = statuses.get(vehicle.name);
if (status === VehicleStatus.CAN_RESEARCH || status === VehicleStatus.LOCKED) {
branches.add(`${vehicle.country}/${vehicle.type}`);
}
}
return branches;
}
export function currentStatus(profile: BlkBlock, rules: ResearchRules, vehicle: string): VehicleStatus | undefined {
return vehicleStatuses({
profile,
owned: ownedVehicles(profile),
earnedUnlocks: earnedUnlocks(profile),
techTree: rules.techTree,
}).get(vehicle);
}
@@ -0,0 +1,21 @@
/** Typed content of tuning/research.jsonc: research rules the offline version decides itself. */
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
export const AUTO_TARGET_PICKS = ['lowestRank', 'highestRank', 'treeOrder'] as const;
export type AutoTargetPick = (typeof AUTO_TARGET_PICKS)[number];
export interface ResearchTuning {
/** Whether finishing or buying the current target prefers its direct tech-tree successor first. */
readonly preferLineSuccessor: boolean;
/** Which researchable vehicle becomes the target when there is no line successor (or on a new save). */
readonly autoTargetPick: AutoTargetPick;
}
export function readResearchTuning(file: TuningReader): ResearchTuning {
const preferLineSuccessor = file.bool('preferLineSuccessor');
const pick = file.string('autoTargetPick');
if (!(AUTO_TARGET_PICKS as readonly string[]).includes(pick)) {
throw new TuningError(`tuning file research.jsonc: autoTargetPick must be one of ${AUTO_TARGET_PICKS.join(', ')} (found ${JSON.stringify(pick)})`);
}
return { preferLineSuccessor, autoTargetPick: pick as AutoTargetPick };
}
+21
View File
@@ -0,0 +1,21 @@
/** What a research or purchase rule says about a player's request. */
export type Refusal =
/** The request names something that does not exist or does not fit (unknown vehicle, wrong type ...). */
| 'BAD_PARAMS'
/** The vehicle's status does not allow it (locked, not researchable, already owned ...). */
| 'NOT_AVAILABLE'
/** The price the client offered is not the current price. */
| 'PRICE_CHANGED'
| 'NOT_ENOUGH_MONEY'
| 'NOT_ENOUGH_RESEARCH_POINTS'
/** A crew does not have the skill points the upgrade costs. */
| 'NOT_ENOUGH_SKILL_POINTS';
export type RuleOutcome = { readonly ok: true } | { readonly ok: false; readonly refusal: Refusal };
export const ACCEPTED: RuleOutcome = { ok: true };
export function refused(refusal: Refusal): RuleOutcome {
return { ok: false, refusal };
}
@@ -0,0 +1,116 @@
/**
* Squadron vehicle (`researchType:t="clanVehicle"`) research and Golden-Eagle early purchase
* rules (implementation notes; aces.exe 0xec0b70..0xec0c6f; scripts/unit/unitActions.nut).
*/
import type { BlkBlock } from '@wto/blk';
import { canAfford, pay, type Price } from '../profile/profile-currency.ts';
import { addOwnedVehicle } from '../profile/profile-hangar.ts';
import {
availableSquadronRp,
setSquadronResearchTarget,
spendSquadronRp,
squadronResearchOf,
} from '../profile/profile-clan.ts';
import { researchPointsOf, setResearchPoints } from '../profile/profile-vehicle-research.ts';
import { currentStatus } from './research-state.ts';
import type { ResearchRules } from './research-rules.ts';
import { ACCEPTED, refused, type RuleOutcome } from './rule-outcome.ts';
import type { TreeVehicle } from './tech-tree.ts';
import { VehicleStatus } from './vehicle-status.ts';
/**
* Exact Golden-Eagle early purchase cost calculated by `clan_get_unit_open_cost_gold`
* (aces.exe 0x177dee0 -> 0xec0b70..0xec0c6f).
*/
export function squadronUnitOpenCostGold(profile: BlkBlock, vehicle: TreeVehicle): number {
if (vehicle.researchPoints <= 0 || vehicle.openCostGold <= 0) return 0;
const curExp = Math.min(researchPointsOf(profile, vehicle.name), vehicle.researchPoints);
const remainingExp = vehicle.researchPoints - curExp;
const scaled = Math.floor((remainingExp * vehicle.openCostGold) / vehicle.researchPoints);
return Math.max(vehicle.minOpenCostGold, scaled);
}
/** `cln_set_research_clan_unit`: select a squadron vehicle for research (and optionally auto-invest RP). */
export function chooseSquadronResearchTarget(
profile: BlkBlock,
rules: ResearchRules,
unitName: string,
autoFlush: boolean,
clanActivityEarnedExp = 0,
): RuleOutcome {
const vehicle = rules.techTree.vehicle(unitName);
if (!vehicle || vehicle.kind !== 'squadron') return refused('BAD_PARAMS');
if (currentStatus(profile, rules, unitName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE');
setSquadronResearchTarget(profile, vehicle.name);
if (autoFlush) {
investAvailableSquadronRp(profile, vehicle, clanActivityEarnedExp);
}
return ACCEPTED;
}
/** `cln_flush_clan_exp_to_unit`: invest available squadron RP into the currently selected squadron vehicle. */
export function flushSquadronExpToUnit(
profile: BlkBlock,
rules: ResearchRules,
clanActivityEarnedExp = 0,
): RuleOutcome {
const { researchUnitName } = squadronResearchOf(profile);
if (!researchUnitName) return ACCEPTED;
const vehicle = rules.techTree.vehicle(researchUnitName);
if (!vehicle || vehicle.kind !== 'squadron') {
setSquadronResearchTarget(profile, '');
return ACCEPTED;
}
if (currentStatus(profile, rules, vehicle.name) !== VehicleStatus.CAN_RESEARCH) {
setSquadronResearchTarget(profile, '');
return ACCEPTED;
}
investAvailableSquadronRp(profile, vehicle, clanActivityEarnedExp);
return ACCEPTED;
}
/** `cln_buy_not_researched_clans_unit`: buy an unresearched squadron vehicle directly with Golden Eagles. */
export function buyNotResearchedSquadronUnit(
profile: BlkBlock,
rules: ResearchRules,
unitName: string,
offered: Price,
): RuleOutcome {
const vehicle = rules.techTree.vehicle(unitName);
if (!vehicle || vehicle.kind !== 'squadron') return refused('BAD_PARAMS');
if (currentStatus(profile, rules, unitName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE');
const expectedGold = squadronUnitOpenCostGold(profile, vehicle);
if (expectedGold <= 0) return refused('NOT_AVAILABLE');
if (offered.silverLions !== 0 || offered.goldenEagles !== expectedGold) return refused('PRICE_CHANGED');
const price: Price = { silverLions: 0, goldenEagles: expectedGold };
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
addOwnedVehicle(profile, vehicle.name);
for (const part of vehicle.parts) addOwnedVehicle(profile, part);
if (squadronResearchOf(profile).researchUnitName === vehicle.name) {
setSquadronResearchTarget(profile, '');
}
return ACCEPTED;
}
function investAvailableSquadronRp(profile: BlkBlock, vehicle: TreeVehicle, clanActivityEarnedExp: number): void {
const available = availableSquadronRp(profile, clanActivityEarnedExp);
if (available <= 0) return;
const curExp = researchPointsOf(profile, vehicle.name);
const needed = Math.max(0, vehicle.researchPoints - curExp);
const invest = Math.min(available, needed);
if (invest <= 0) return;
spendSquadronRp(profile, invest);
setResearchPoints(profile, vehicle.name, curExp + invest);
if (curExp + invest >= vehicle.researchPoints) {
setSquadronResearchTarget(profile, '');
}
}
+89
View File
@@ -0,0 +1,89 @@
/**
* The vehicles as research and purchase see them: the catalogue (game-data vehicle-catalogue)
* with each vehicle's type and how it is obtained.
*
* Kinds, checked in this order:
* part the separate part of a split vehicle; comes with its main vehicle
* hidden shop.blk showOnlyWhenBought: event and promotion prizes, mission copies,
* drones, ship floatplanes; the stock UI only shows them to players who own
* them, so they are not offered
* squadron researchType clanVehicle: researched with squadron research points or bought
* early for golden eagles (feature-inventory I, later); no rank requirement
* gift gift:t: packs and marketplace vehicles; the stock scripts never offer them
* for silver lions or golden eagles (scripts/unit/unitShopInfo.nut
* canBuyUnitEvenNotInShop); the local shop gives them (feature-inventory G, later)
* event event:t (feature-inventory G, later)
* premium costGold > 0 or premPackAir (the scripts' isUnitSpecial): bought for golden
* eagles without research, rank or previous vehicle
* research reqExp > 0: researched, then bought
* purchase no reqExp: bought without research (helicopters that start a branch, free
* vehicles unlocked by an achievement, reserve vehicles)
*/
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import { vehicleTypeOfClass, type VehicleType } from './vehicle-types.ts';
export type VehicleKind = 'part' | 'hidden' | 'squadron' | 'gift' | 'event' | 'premium' | 'research' | 'purchase';
export interface TreeVehicle extends CatalogueVehicle {
readonly type: VehicleType;
readonly kind: VehicleKind;
}
const SQUADRON_RESEARCH = 'clanVehicle';
export class TechTree {
readonly #vehicles: ReadonlyMap<string, TreeVehicle>;
constructor(catalogue: readonly CatalogueVehicle[]) {
const parts = new Set(catalogue.filter((vehicle) => vehicle.inTechTree).flatMap((vehicle) => vehicle.parts));
const vehicles = new Map<string, TreeVehicle>();
for (const vehicle of catalogue) {
const type = vehicleTypeOfClass(vehicle.unitClass);
// Without a type or country the client's status function locks the vehicle (0x911750, 0x961dd0).
if (type && vehicle.country) vehicles.set(vehicle.name, { ...vehicle, type, kind: kindOf(vehicle, parts) });
}
this.#vehicles = vehicles;
}
vehicle(name: string): TreeVehicle | undefined {
return this.#vehicles.get(name);
}
/** Every vehicle with a type and country, in the tech tree or not. */
all(): Iterable<TreeVehicle> {
return this.#vehicles.values();
}
/** The countries and vehicle types that have vehicles in the tech tree, with their highest rank. */
branches(): { country: string; type: VehicleType; highestRank: number }[] {
const highest = new Map<string, { country: string; type: VehicleType; highestRank: number }>();
for (const vehicle of this.#vehicles.values()) {
if (!vehicle.inTechTree) continue;
const key = `${vehicle.country}/${vehicle.type}`;
const known = highest.get(key);
if (!known) highest.set(key, { country: vehicle.country, type: vehicle.type, highestRank: vehicle.rank });
else known.highestRank = Math.max(known.highestRank, vehicle.rank);
}
return [...highest.values()];
}
hasCountry(country: string): boolean {
for (const vehicle of this.#vehicles.values()) if (vehicle.inTechTree && vehicle.country === country) return true;
return false;
}
}
function kindOf(vehicle: CatalogueVehicle, parts: ReadonlySet<string>): VehicleKind {
if (parts.has(vehicle.name)) return 'part';
if (vehicle.onlyShownWhenOwned) return 'hidden';
if (vehicle.researchType === SQUADRON_RESEARCH) return 'squadron';
if (vehicle.gift) return 'gift';
if (vehicle.event) return 'event';
if (vehicle.goldenEagles > 0 || vehicle.premiumPack) return 'premium';
return vehicle.researchPoints > 0 ? 'research' : 'purchase';
}
/** Premium-like vehicles for unlock conditions that count "premium" vehicles separately (unlocks.blk premium:b). */
export function isPremiumKind(kind: VehicleKind): boolean {
return kind === 'premium' || kind === 'gift' || kind === 'event';
}
@@ -0,0 +1,33 @@
/**
* Buying a vehicle (cln_buy_aircraft, implementation notes).
*
* The vehicle must be buyable (status "can buy"). Its price is config/wpcost.blk value
* (silver lions) and costGold (golden eagles), less the best active personal discount: the
* client prices it the same way (wp_get_cost / wp_get_cost_gold, aces.exe 2.61.0.37 0x9158a0;
* implementation notes; the price table itself has no discounts). The client sends the price
* it showed; a different one is refused, as when a discount ended online. A purchase made with
* a discount counts against that discount item. The parts of a split vehicle come with it.
*/
import type { BlkBlock } from '@wto/blk';
import { discountedPrice, recordDiscountUse, vehicleDiscount } from '../items/personal-discounts.ts';
import { canAfford, pay, type Price } from '../profile/profile-currency.ts';
import { addOwnedVehicle } from '../profile/profile-hangar.ts';
import { currentStatus } from './research-state.ts';
import type { ResearchRules } from './research-rules.ts';
import { ACCEPTED, refused, type RuleOutcome } from './rule-outcome.ts';
import { VehicleStatus } from './vehicle-status.ts';
export function buyVehicle(profile: BlkBlock, rules: ResearchRules, vehicleName: string, offered: Price): RuleOutcome {
const vehicle = rules.techTree.vehicle(vehicleName);
if (!vehicle) return refused('BAD_PARAMS');
if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_BUY) return refused('NOT_AVAILABLE');
const discount = vehicleDiscount(profile, vehicle);
const price = discountedPrice({ silverLions: vehicle.silverLions, goldenEagles: vehicle.goldenEagles }, discount.percent);
if (offered.silverLions !== price.silverLions || offered.goldenEagles !== price.goldenEagles) return refused('PRICE_CHANGED');
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
if (discount.uid !== undefined) recordDiscountUse(profile, discount.uid);
addOwnedVehicle(profile, vehicle.name);
for (const part of vehicle.parts) addOwnedVehicle(profile, part);
return ACCEPTED;
}
@@ -0,0 +1,79 @@
/**
* The status of each vehicle the player does not own, in
* the order of the stock explanation of why a vehicle cannot be bought or researched
* (gui.vromfs.bin scripts/unit/unitInfoTexts.nut getCantBuyUnitReason):
*
* not in the tech tree, part, hidden, gift, event locked
* reqUnlock not earned locked
* premium can buy
* rank not open (squadron vehicles have no rank gate) locked
* research points reached (or none needed):
* previous vehicle owned, or none can buy
* otherwise researched ("buy the previous first")
* not reached:
* previous vehicle researched or owned, or none can research
* otherwise locked
*
* "In research" is not a status the server gives: the client shows a researchable vehicle
* that way when it is the research target (aces.exe 2.61.0.37 0xebf7a0).
*/
import type { BlkBlock } from '@wto/blk';
import { openRank } from '../profile/profile-eras.ts';
import { researchPointsOf } from '../profile/profile-vehicle-research.ts';
import type { TechTree, TreeVehicle } from './tech-tree.ts';
/** Values of shop_unit_research_status (registered from aces.exe 0x17dbc20). */
export const VehicleStatus = {
LOCKED: 1,
CAN_RESEARCH: 2,
CAN_BUY: 8,
RESEARCHED: 0x40,
} as const;
export type VehicleStatus = (typeof VehicleStatus)[keyof typeof VehicleStatus];
const UNAVAILABLE_KINDS = new Set(['part', 'hidden', 'gift', 'event']);
export interface StatusInputs {
readonly profile: BlkBlock;
readonly owned: ReadonlySet<string>;
readonly earnedUnlocks: ReadonlySet<string>;
readonly techTree: TechTree;
}
/** Status of every vehicle the player does not own. */
export function vehicleStatuses(inputs: StatusInputs): Map<string, VehicleStatus> {
const statuses = new Map<string, VehicleStatus>();
const statusOf = (vehicle: TreeVehicle): VehicleStatus => {
let status = statuses.get(vehicle.name);
if (status === undefined) {
// Locked while being worked out, so a loop in the previous-vehicle data cannot recurse forever.
statuses.set(vehicle.name, VehicleStatus.LOCKED);
status = computeStatus(vehicle, inputs, statusOfName);
statuses.set(vehicle.name, status);
}
return status;
};
const statusOfName = (name: string): VehicleStatus | 'owned' | undefined => {
if (inputs.owned.has(name)) return 'owned';
const vehicle = inputs.techTree.vehicle(name);
return vehicle && statusOf(vehicle);
};
for (const vehicle of inputs.techTree.all()) if (!inputs.owned.has(vehicle.name)) statusOf(vehicle);
return statuses;
}
function computeStatus(vehicle: TreeVehicle, inputs: StatusInputs, statusOfName: (name: string) => VehicleStatus | 'owned' | undefined): VehicleStatus {
if (!vehicle.inTechTree || UNAVAILABLE_KINDS.has(vehicle.kind)) return VehicleStatus.LOCKED;
if (vehicle.requiredUnlock && !inputs.earnedUnlocks.has(vehicle.requiredUnlock)) return VehicleStatus.LOCKED;
if (vehicle.kind === 'premium') return VehicleStatus.CAN_BUY;
// getCantBuyUnitReason skips the rank check for squadron vehicles.
if (vehicle.kind !== 'squadron' && openRank(inputs.profile, vehicle.country, vehicle.type) < vehicle.rank) return VehicleStatus.LOCKED;
const previous = vehicle.requires === undefined ? 'owned' : statusOfName(vehicle.requires);
if (isResearched(vehicle, inputs.profile)) return previous === 'owned' ? VehicleStatus.CAN_BUY : VehicleStatus.RESEARCHED;
const previousResearched = previous === 'owned' || previous === VehicleStatus.CAN_BUY || previous === VehicleStatus.RESEARCHED;
return previousResearched ? VehicleStatus.CAN_RESEARCH : VehicleStatus.LOCKED;
}
export function isResearched(vehicle: TreeVehicle, profile: BlkBlock): boolean {
return researchPointsOf(profile, vehicle.name) >= vehicle.researchPoints;
}
+56
View File
@@ -0,0 +1,56 @@
/**
* Vehicle types as the client numbers and names them.
*
* Numbers: the ES unit type the scripts send (getEsUnitType; cln_set_researchable "type").
* Names: the table at aces.exe 2.61.0.37 0x72b6d98 / 0x72b6d58, used in the profile's
* parameter names (eras "<type>_<country>", researchUnits "currUnit<type>"). The type of a
* vehicle comes from its wpcost.blk unitClass, mapped as EconomicState::getUnitType does
* (0x911750, class table 0x72b6338).
*/
export const VEHICLE_TYPES = ['Aircraft', 'Tank', 'Ship', 'Helicopter', 'Boat', 'Human', 'Transport'] as const;
export type VehicleType = (typeof VEHICLE_TYPES)[number];
const TYPE_OF_CLASS: Readonly<Record<string, VehicleType>> = {
exp_fighter: 'Aircraft',
exp_bomber: 'Aircraft',
exp_assault: 'Aircraft',
exp_tank: 'Tank',
exp_heavy_tank: 'Tank',
exp_tank_destroyer: 'Tank',
exp_SPAA: 'Tank',
exp_ship: 'Ship',
exp_destroyer: 'Ship',
exp_cruiser: 'Ship',
exp_torpedo_boat: 'Boat',
exp_gun_boat: 'Boat',
exp_torpedo_gun_boat: 'Boat',
exp_submarine_chaser: 'Boat',
exp_naval_ferry_barge: 'Boat',
exp_helicopter: 'Helicopter',
exp_human: 'Human',
exp_transport: 'Transport',
};
/** The tech-tree branches of config/shop.blk, as the stock scripts pair them (scripts/unit/unitTypesList.nut armyId). */
const TYPE_OF_BRANCH: Readonly<Record<string, VehicleType>> = {
aviation: 'Aircraft',
army: 'Tank',
ships: 'Ship',
helicopters: 'Helicopter',
boats: 'Boat',
};
export function vehicleTypeOfClass(unitClass: string): VehicleType | undefined {
return TYPE_OF_CLASS[unitClass];
}
export function vehicleTypeOfBranch(branch: string): VehicleType {
const type = TYPE_OF_BRANCH[branch];
if (!type) throw new Error(`unknown tech-tree branch: ${branch}`);
return type;
}
export function vehicleTypeById(id: number): VehicleType | undefined {
return VEHICLE_TYPES[id];
}
@@ -0,0 +1,90 @@
/**
* Earning the unlocks vehicles depend on. The char server checks
* these conditions and records the unlock; an unlock of type "aircraft" also gives the
* vehicle of the same name.
*
* char_unlocks at least num of the listed unlocks are earned
* char_aircrafts_in_era the player owns at least num vehicles of the country (if given)
* whose class is listed, at rank era or above (exactly era with
* rankExactly); premium and squadron vehicles only count with
* premium:b=yes / clanUnits:b=yes
* char_player_era the country has rank era open for the class
* Other condition types, and modes with extra condition{} blocks (first battle, logins ...),
* are left to the features they belong to and count as not met.
*
* Unlock classes: "tank", "ship", "boat", "helicopter", and "aircraft" for aircraft and
* helicopters ("aircraft_only" is the aircraft alone). That "aircraft" includes helicopters
* is inferred from the separate "aircraft_only" class.
*/
import type { BlkBlock } from '@wto/blk';
import { VEHICLE_UNLOCK_TYPE, type UnlockDefinition, type UnlockMode } from '../game-data/datasets/vehicle-unlocks.ts';
import { openRank } from '../profile/profile-eras.ts';
import { addOwnedVehicle } from '../profile/profile-hangar.ts';
import { addUnlock } from '../profile/profile-unlocks.ts';
import { isPremiumKind, type TechTree } from './tech-tree.ts';
import type { VehicleType } from './vehicle-types.ts';
const TYPES_OF_UNLOCK_CLASS: Readonly<Record<string, readonly VehicleType[]>> = {
aircraft: ['Aircraft', 'Helicopter'],
aircraft_only: ['Aircraft'],
helicopter: ['Helicopter'],
tank: ['Tank'],
ship: ['Ship'],
boat: ['Boat'],
};
export interface UnlockState {
readonly earned: Set<string>;
readonly owned: Set<string>;
}
/** Earn every unlock whose condition holds; returns whether anything changed. */
export function earnVehicleUnlocks(profile: BlkBlock, state: UnlockState, definitions: readonly UnlockDefinition[], techTree: TechTree): boolean {
let changed = false;
for (const definition of definitions) {
if (state.earned.has(definition.id) || !definition.modes.some((mode) => modeHolds(mode, profile, state, techTree))) continue;
addUnlock(profile, definition.id);
state.earned.add(definition.id);
if (definition.type === VEHICLE_UNLOCK_TYPE && techTree.vehicle(definition.id) && !state.owned.has(definition.id)) {
addOwnedVehicle(profile, definition.id);
state.owned.add(definition.id);
}
changed = true;
}
return changed;
}
function modeHolds(mode: UnlockMode, profile: BlkBlock, state: UnlockState, techTree: TechTree): boolean {
if (mode.hasOtherConditions) return false;
switch (mode.type) {
case 'char_unlocks':
return mode.unlocks.filter((unlock) => state.earned.has(unlock)).length >= (mode.num ?? mode.unlocks.length);
case 'char_aircrafts_in_era':
return ownedInEra(mode, state.owned, techTree) >= (mode.num ?? 1);
case 'char_player_era':
return mode.country !== undefined && mode.era !== undefined
&& typesOf(mode).some((type) => openRank(profile, mode.country!, type) >= mode.era!);
default:
return false;
}
}
function ownedInEra(mode: UnlockMode, owned: ReadonlySet<string>, techTree: TechTree): number {
const types = new Set(typesOf(mode));
const era = mode.era ?? 1;
let count = 0;
for (const name of owned) {
const vehicle = techTree.vehicle(name);
if (!vehicle || !types.has(vehicle.type)) continue;
if (mode.country !== undefined && vehicle.country !== mode.country) continue;
if (mode.rankExactly ? vehicle.rank !== era : vehicle.rank < era) continue;
if (!mode.premium && isPremiumKind(vehicle.kind)) continue;
if (!mode.clanUnits && vehicle.kind === 'squadron') continue;
count++;
}
return count;
}
function typesOf(mode: UnlockMode): VehicleType[] {
return mode.unitClasses.flatMap((unitClass) => TYPES_OF_UNLOCK_CLASS[unitClass] ?? []);
}