merge: bring main into feat/tank-ai-nav

Takes main's mounted gun traverse limits, capture and hit feedback,
LocalMP air AI sync, mod tech tree insertions and launcher changes.

Conflicts resolved:
- wto_ai_runtime.das: fire update runs before navigation, as on main,
  so a hull-aim request is driven in the same frame; navigation keeps
  the navmesh state and slot arguments of this branch.
- wto_ai_nav_common.das: main's wto_try_hull_aim replaces the old
  limited-traverse pivot and uses this branch's drive command helper
  and stuck-watch reset.
- build.ps1 and local_mp_internal.h: keep both sides' sources and
  declarations.
This commit is contained in:
N0VAN0M4LY committed 2026-12-05 22:14:34 +08:00
commit 77e4806ffc
114 files changed
+4330 -623

No files matched your search

+6 -1
View File
@@ -53,6 +53,8 @@ export interface BattleSettlementDeps {
readonly streaks: BattleStreaks;
readonly items: ItemCatalogue;
readonly repair: RepairRules;
/** Optional hook receiving total base (unboosted) vehicle RP earned in the battle. */
readonly onBattleRpEarned?: ((baseVehicleRp: number, nowSec: number) => void) | undefined;
}
const REPAIR_MODE: Readonly<Record<ModeDifficulty, RepairMode>> = { arcade: 'Arcade', realistic: 'Historical', simulator: 'Simulation' };
@@ -87,12 +89,15 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B
if (crew && vehicle.expTotal > 0) addEarnedSkillPoints(crew, vehicle.expTotal * crewExpMul);
}
const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment);
const research = investBattleRp(profile, rewards.vehicles.map(vehicleRpOf), {
const vehicleRps = rewards.vehicles.map(vehicleRpOf);
const research = investBattleRp(profile, vehicleRps, {
country: session.country,
requiredClass: session.requiredClass,
difficulty,
nowUnixSec: log.timeSec,
}, deps);
const baseVehicleRp = vehicleRps.reduce((sum, vehicle) => sum + Math.max(0, vehicle.noBonusExp), 0);
if (baseVehicleRp > 0) deps.onBattleRpEarned?.(baseVehicleRp, log.timeSec);
recordBoosterUses(profile, boosters.uses, log);
const wager = activeWager(profile, deps.items);
const wagerOutcome = wager && wagerBattle(wager.wager, wager.state, {
+11 -3
View File
@@ -16,12 +16,19 @@ export interface BackupSpawn {
readonly backup: string;
}
/** Strip native model folder prefixes (e.g. "tankModels/cn_type_59" -> "cn_type_59"). */
export function normalizeBackupUnitName(unit: string): string {
const slash = unit.lastIndexOf('/');
return slash >= 0 ? unit.slice(slash + 1) : unit;
}
function receiptKey(session: BattleSession, slot: number): string {
return `${session.sessionId}_${slot}`;
}
export function recordDailyBackupSpawn(profile: BlkBlock, session: BattleSession, spawn: BackupSpawn): boolean {
return spawn.backup === DAILY_BACKUP && session.spareSlots?.get(spawn.slot) === spawn.unit
const unit = normalizeBackupUnitName(spawn.unit);
return spawn.backup === DAILY_BACKUP && session.spareSlots?.get(spawn.slot) === unit
&& recordDailySpare(profile, session.startedAtSec, receiptKey(session, spawn.slot));
}
@@ -32,11 +39,12 @@ export function consumeBattleSpares(
const seenSlots = new Set<number>();
const consumed = new Map<string, number>();
for (const spawn of spawns) {
const { slot, unit, backup } = spawn;
const { slot, backup } = spawn;
const unit = normalizeBackupUnitName(spawn.unit);
if (session.spareSlots?.get(slot) !== unit || seenSlots.has(slot)) continue;
seenSlots.add(slot);
if (backup === DAILY_BACKUP) {
recordDailyBackupSpawn(profile, session, spawn);
recordDailyBackupSpawn(profile, session, { slot, unit, backup });
continue;
}
if (dailySparesLeft(profile, session.startedAtSec) > 0
+11 -1
View File
@@ -13,6 +13,7 @@ import type { BattleEconomy } from '../../battle/battle-economy.ts';
import type { BattleStreaks } from '../../battle/battle-streaks.ts';
import { withoutSupportPlanes } from '../../battle/battle-support-planes.ts';
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { clientProfile } from '../../profile/client-profile.ts';
@@ -41,6 +42,7 @@ export interface FinishBattleContext {
readonly crew: CrewSkillCatalogue;
readonly items: ItemCatalogue;
readonly repair: RepairRules;
readonly clans?: { readonly store: ClanStore } | undefined;
}
export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler {
@@ -67,7 +69,15 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio
// The result log and expenses are written together. A retry can arrive after the profile
// was saved but before the session was marked settled.
if (hasBattleResultLog(profile, session.roomId)) return false;
settleBattle(profile, report, session, settlementDeps);
settleBattle(profile, report, session, {
...settlementDeps,
onBattleRpEarned: ctx.clans
? (baseVehicleRp, nowSec) => {
ctx.clans!.store.recordBattleActivity(account.userId, baseVehicleRp, nowSec);
ctx.clans!.store.syncProfile(profile, account, nowSec);
}
: undefined,
});
battle.onAfterSettle?.({
userId: account.userId,
roomId: session.sessionId,
@@ -2,7 +2,9 @@
* `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
* (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar
* auto-repair / auto-refill / auto-buy-modifications and map preferences. On returning from
* auto-repair / auto-refill / auto-buy-modifications, map preferences, and per-vehicle
* preferences (`hangar/<vehicle>` `lastSkin`, `lastWeapon`, `lastBullets0..5`, and flight
* trims `aileronTrim`/`elevatorTrim`/`rudderTrim`). On returning from
* a stock training mission, the client also reports completion in `missionAwards` while
* `pveProgress` is empty. Answers the whole updated profile.
*/
+16 -3
View File
@@ -8,18 +8,24 @@
*/
import { appendParam, emptyBlock, setParam, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import type { LocalizedText } from '../../game-data/datasets/unit-names.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { serverTimeNow } from '../../profile/server-time.ts';
import type { RuleOutcome } from '../../research/rule-outcome.ts';
import type { StoreCatalogue, StoreProduct } from '../../store/store-catalogue.ts';
import { buyGoldEntitlement } from '../../store/store-purchase.ts';
import { freePaymentLabelForStore } from '../../store/store-tuning.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts';
export function entitlementsPriceEx(store: StoreCatalogue): CharActionHandler {
const table = buildEntitlementsPriceBlk(store.allProducts());
export function entitlementsPriceEx(
store: StoreCatalogue,
freePaymentLabel?: LocalizedText,
): CharActionHandler {
const label = freePaymentLabel ?? freePaymentLabelForStore(store);
const table = buildEntitlementsPriceBlk(store.allProducts(), label);
return () => ({ kind: 'data', blk: table });
}
@@ -42,8 +48,15 @@ export function buyEntitlementAction(profiles: PlayerProfiles, accounts: Account
});
}
function buildEntitlementsPriceBlk(products: readonly StoreProduct[]): BlkBlock {
function buildEntitlementsPriceBlk(
products: readonly StoreProduct[],
freePaymentLabel: LocalizedText,
): BlkBlock {
const root = emptyBlock();
// Top-level string params are ignored by stock blockCount() enumeration and read by the
// free-offline-payment-method GUI patch to localize the no-GJN payment option.
setParam(root, 'wtoFreePaymentLabelZh', { type: 'string', value: freePaymentLabel.zh });
setParam(root, 'wtoFreePaymentLabelEn', { type: 'string', value: freePaymentLabel.en });
for (const product of products) {
const block = emptyBlock(product.id);
setParam(block, 'chapter', { type: 'string', value: product.chapter });
+14 -2
View File
@@ -31,6 +31,14 @@ const OPTIONAL_LOG_STRING_KEYS: ReadonlyArray<keyof Omit<ClanLogEntry, 'id' | 'e
export function toClanInfoBlk(clan: ClanRecord, tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): BlkBlock {
const todayDay = Math.floor(nowSec / 86400);
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, historyDepthDays } = tuning.activity;
// `clanInfoTable.nut:269` passes `nextRewardDayId` straight to `time.buildDateTimeStr`
// (`clanAverageActivityModal.nut:60-62`), which expects a Unix timestamp in seconds.
// `clan_get_clan_info` (`aces.exe` 0x1787130) returns the raw DataBlock, and Squirrel
// `sqDataBlock` (`0x460da35`) pushes `TYPE_INT64` as a 64-bit integer.
const anchorDay = clan.lastRewardDay ?? todayDay;
const candidateNextDay = anchorDay + rewardPeriodDays;
const nextRewardDay = candidateNextDay > todayDay ? candidateNextDay : todayDay + rewardPeriodDays;
const nextRewardSec = nextRewardDay * 86400;
return {
name: '',
params: [
@@ -57,7 +65,7 @@ export function toClanInfoBlk(clan: ClanRecord, tuning: ClanTuning, nowSec = Mat
int('rewardPeriodDays', rewardPeriodDays),
bool('expRewardEnabled', true),
int('historyDepth', historyDepthDays),
int('nextRewardDayId', todayDay + rewardPeriodDays),
int64('nextRewardDayId', BigInt(nextRewardSec)),
],
blocks: [
buildAstatBlock(clan, tuning),
@@ -215,7 +223,7 @@ function statParams(stats: ClanStats): BlkParam[] {
function buildMemberActivityBlock(member: ClanMemberRecord, todayDay: number): BlkBlock {
const periods = member.periods.length > 0
? member.periods
: [{ day: todayDay, activity: member.curActivity, exp: 20000 }];
: (member.curActivity > 0 ? [{ day: todayDay, activity: member.curActivity, exp: 0 }] : []);
return {
name: member.uid,
@@ -248,6 +256,10 @@ function int(name: string, value: number): BlkParam {
return { name, value: { type: 'int', value: Math.trunc(value) } };
}
function int64(name: string, value: bigint): BlkParam {
return { name, value: { type: 'int64', value } };
}
function bool(name: string, value: boolean): BlkParam {
return { name, value: { type: 'bool', value } };
}
+4 -2
View File
@@ -54,13 +54,15 @@ export function addMemberToClan(
): void {
if (clan.members.some((m) => m.uid === uid)) return;
const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), tuning);
const curActivity = Math.min(tuning.activity.maxPerPeriod, tuning.activity.startingActivity);
const periodActivitySum = periods.reduce((s, p) => s + p.activity, 0);
clan.members.push({
uid,
nick,
role,
joinDateSec: nowSec,
curActivity: tuning.activity.maxPerPeriod,
totalActivity: periods.reduce((s, p) => s + p.activity, 0),
curActivity,
totalActivity: periods.length > 0 ? periodActivitySum : curActivity,
earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0),
ratingArc: tuning.playerRating.joiner.arc,
ratingHist: tuning.playerRating.joiner.hist,
+75
View File
@@ -0,0 +1,75 @@
/**
* Squadron (clan) battle season schedule matching `char.vromfs.bin` `config/clan_rewards.blk`
* (`seasons{}`): six bi-monthly UTC seasons per year starting on the 1st of Jan, Mar, May,
* Jul, Sep, and Nov at 00:00:00 UTC.
*
* Wire contract verified in stock `aces.exe` (2.61.0.58):
* - `GameSaveData::onAsyncEconTransComplete` (`0xebc33c..0xebc7b4`) reads four top-level
* profile parameters on every profile-returning char transaction:
* - `clanDuelNextReward:i64` (`0xebc731..0xebc745`, `DataBlock::getInt64`) -> `rewardDay`
* - `clanSeasonStart:i64` (`0xebc755..0xebc769`, `DataBlock::getInt64`) -> `startDay`
* - `clanSeasonOrdinal:i` (`0xebc778..0xebc78c`, `DataBlock::getInt`) -> `ordinalNumber`
* - `clanSeasonInYear:i` (`0xebc79a..0xebc7ae`, `DataBlock::getInt`) -> `numberInYear`
* - `clan_get_current_season_info` (`0x178aff0..0x178b227`) exposes those four fields verbatim.
* - `gui.vromfs.bin` `scripts/clans/clanseasons.nut:45-54` formats the title using
* `unixtime_to_utc_timetbl(info.startDay).year` and `info.numberInYear + 1`
* (`CLAN_SEASON_NUM_IN_YEAR_SHIFT = 1`, yielding Roman numerals `I`..`VI`), and formats the
* end time with `time.buildDateTimeStr(info.rewardDay, false, false)`.
*/
export interface ClanSeasonInfo {
/** UTC 00:00:00 start of the active season as Unix seconds. */
readonly startDaySec: number;
/** UTC 00:00:00 end/reward timestamp of the active season (start of next season) as Unix seconds. */
readonly rewardDaySec: number;
/** Zero-based season index within the UTC year (`0..5`, displayed as `I..VI`). */
readonly numberInYear: number;
/** Monotonic positive ordinal season number across years. */
readonly ordinalNumber: number;
}
/** Season start month/day pairs from `char.vromfs.bin` `config/clan_rewards.blk` `seasons{}`. */
export const CLAN_SEASON_STARTS: ReadonlyArray<{ readonly month: number; readonly day: number }> = [
{ month: 1, day: 1 },
{ month: 3, day: 1 },
{ month: 5, day: 1 },
{ month: 7, day: 1 },
{ month: 9, day: 1 },
{ month: 11, day: 1 },
];
const SEASON_ORDINAL_BASE_YEAR = 2016;
/** Compute the active squadron battle season for a given Unix timestamp in seconds. */
export function currentClanSeason(nowSec = Math.floor(Date.now() / 1000)): ClanSeasonInfo {
const now = new Date(Math.trunc(nowSec) * 1000);
const year = now.getUTCFullYear();
const seasonCount = CLAN_SEASON_STARTS.length;
let activeIndex = 0;
let startSec = Date.UTC(year, CLAN_SEASON_STARTS[0]!.month - 1, CLAN_SEASON_STARTS[0]!.day) / 1000;
for (let i = seasonCount - 1; i >= 0; i--) {
const entry = CLAN_SEASON_STARTS[i]!;
const candidateSec = Date.UTC(year, entry.month - 1, entry.day) / 1000;
if (nowSec >= candidateSec) {
activeIndex = i;
startSec = candidateSec;
break;
}
}
const nextIndex = (activeIndex + 1) % seasonCount;
const nextYear = activeIndex + 1 >= seasonCount ? year + 1 : year;
const nextEntry = CLAN_SEASON_STARTS[nextIndex]!;
const rewardSec = Date.UTC(nextYear, nextEntry.month - 1, nextEntry.day) / 1000;
const ordinalNumber = Math.max(1, (year - SEASON_ORDINAL_BASE_YEAR) * seasonCount + activeIndex + 1);
return {
startDaySec: startSec,
rewardDaySec: rewardSec,
numberInYear: activeIndex,
ordinalNumber,
};
}
+119 -12
View File
@@ -3,25 +3,75 @@
* The directory is written when the server first creates `<data>/clans.json`.
*/
import type { ClanTuning, PresetClan, PresetMember } from './clan-tuning.ts';
import type { ClanActivityPeriodEntry, ClanMemberRecord, ClanRecord } from './clan-types.ts';
import { ClanRole, type ClanActivityPeriodEntry, type ClanMemberRecord, type ClanRecord } from './clan-types.ts';
const SECONDS_PER_DAY = 86400;
export function createDefaultClans(tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] {
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
const createdBase = nowSec - tuning.presetClans.createdDaysAgo * SECONDS_PER_DAY;
return tuning.presetClans.clans.map((spec) => buildSeededClan(spec, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning));
return tuning.presetClans.clans.map((spec, specIndex) =>
buildSeededClan(spec, specIndex, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning));
}
/** The activity periods a member starts with: startingPeriods periods, each with the given activity and the squadron RP it earns. */
export function buildDefaultPeriods(todayDay: number, tuning: ClanTuning, periodActivity = tuning.activity.maxPerPeriod): ClanActivityPeriodEntry[] {
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, startingPeriods } = tuning.activity;
/**
* The activity periods a member starts with: `periodCount` periods (defaulting to
* `activity.startingPeriods`), each with the given activity and the squadron RP it earns.
*/
export function buildDefaultPeriods(
todayDay: number,
tuning: ClanTuning,
periodActivity = tuning.activity.maxPerPeriod,
periodCount = tuning.activity.startingPeriods,
): ClanActivityPeriodEntry[] {
if (periodCount <= 0) return [];
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays } = tuning.activity;
const exp = Math.round((periodActivity / maxPerPeriod) * squadronRpPerFullPeriod);
return Array.from({ length: startingPeriods }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp }));
return Array.from({ length: periodCount }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp }));
}
function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanRecord {
const members = spec.members.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning));
/**
* Idempotently appends deterministic filler NPCs to an existing preset clan whose
* persisted roster is smaller than its configured `targetMemberCount`, without altering
* any existing player or NPC members.
*/
export function backfillPresetClanMembers(
clan: ClanRecord,
spec: PresetClan,
specIndex: number,
todayDay: number,
tuning: ClanTuning,
): boolean {
const targetCount = Math.min(clan.mlimit, spec.targetMemberCount);
if (clan.members.length >= targetCount) return false;
const existingUids = new Set(clan.members.map((m) => m.uid));
const fillerSpecs = buildPresetFillerSpecs(spec, specIndex, tuning);
let added = false;
for (let i = 0; i < fillerSpecs.length && clan.members.length < targetCount; i++) {
const npc = fillerSpecs[i]!;
if (existingUids.has(npc.uid)) continue;
existingUids.add(npc.uid);
const memberIdx = spec.members.length + i;
clan.members.push(buildSeededMember(spec, npc, memberIdx, clan.cdateSec, todayDay, tuning));
added = true;
}
return added;
}
function buildSeededClan(
spec: PresetClan,
specIndex: number,
cdateSec: number,
todayDay: number,
tuning: ClanTuning,
): ClanRecord {
const mlimit = spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal;
const allSpecs: PresetMember[] = [
...spec.members,
...buildPresetFillerSpecs(spec, specIndex, tuning),
].slice(0, mlimit);
const members = allSpecs.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning));
const leader = spec.members[0]!;
return {
id: spec.id,
@@ -35,13 +85,14 @@ function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, t
region: spec.region,
status: 'open',
autoaccept: spec.autoAccept,
mlimit: spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal,
mlimit,
mspent: 0,
cdateSec,
changedByUid: leader.uid,
changedByNick: leader.nick,
changedTimeSec: cdateSec,
regionLastUpdatedSec: 0,
lastRewardDay: todayDay,
stats: { dr_era5_arc: spec.rating.arc, dr_era5_hist: spec.rating.hist, dr_era5_sim: spec.rating.sim, ...tuning.presetClans.stats },
members,
candidates: [],
@@ -55,8 +106,64 @@ function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, t
};
}
function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanMemberRecord {
const periods = buildDefaultPeriods(todayDay, tuning, npc.activity);
function buildPresetFillerSpecs(spec: PresetClan, specIndex: number, tuning: ClanTuning): PresetMember[] {
const mlimit = spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal;
const targetCount = Math.min(mlimit, Math.max(spec.members.length, spec.targetMemberCount));
const needed = targetCount - spec.members.length;
if (needed <= 0) return [];
const filler = tuning.presetClans.fillerMembers;
const clanSlot = presetClanSlot(spec.id, specIndex);
const usedUids = new Set(spec.members.map((m) => m.uid));
const span = Math.max(0, filler.activityMax - filler.activityMin);
const result: PresetMember[] = [];
let ordinal = spec.members.length + 1;
while (result.length < needed) {
const uid = String(filler.uidBase + clanSlot * filler.uidStride + ordinal);
if (usedUids.has(uid)) {
ordinal++;
continue;
}
usedUids.add(uid);
const callsign = filler.callsigns[(clanSlot * 7 + ordinal) % filler.callsigns.length]!;
const title = filler.titles[(clanSlot * 3 + ordinal) % filler.titles.length]!;
const icon = filler.icons[(clanSlot * 5 + ordinal) % filler.icons.length]!;
const unit = filler.units[(clanSlot * 11 + ordinal) % filler.units.length]!;
const activityOffset = span > 0 ? (clanSlot * 13 + ordinal * 17) % (span + 1) : 0;
const activity = Math.min(tuning.activity.maxPerPeriod, filler.activityMin + activityOffset);
result.push({
uid,
nick: `${callsign}_${clanSlot}${String(ordinal).padStart(2, '0')}`,
role: ClanRole.REGULAR,
title,
icon,
unit,
activity,
});
ordinal++;
}
return result;
}
function presetClanSlot(clanId: string, specIndex: number): number {
const parsed = Number(clanId);
if (Number.isSafeInteger(parsed) && parsed > 0) {
const remainder = parsed % 1000;
if (remainder > 0) return remainder;
}
return specIndex + 1;
}
function buildSeededMember(
spec: PresetClan,
npc: PresetMember,
idx: number,
cdateSec: number,
todayDay: number,
tuning: ClanTuning,
): ClanMemberRecord {
const periods = buildDefaultPeriods(todayDay, tuning, npc.activity, tuning.presetClans.npcHistoryPeriods);
const { step, floor } = tuning.presetClans.memberRating;
return {
uid: npc.uid,
@@ -69,7 +176,7 @@ function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cda
npcFrame: '',
npcShowcaseUnit: npc.unit,
curActivity: npc.activity,
totalActivity: periods.reduce((sum, p) => sum + p.activity, 0),
totalActivity: periods.length > 0 ? periods.reduce((sum, p) => sum + p.activity, 0) : npc.activity,
earnedSquadronExp: periods.reduce((sum, p) => sum + p.exp, 0),
ratingArc: Math.max(floor.arc, spec.rating.arc - idx * step.arc),
ratingHist: Math.max(floor.hist, spec.rating.hist - idx * step.hist),
+187 -27
View File
@@ -39,10 +39,12 @@ import {
type MembershipRequestQuery,
} from './clan-membership.ts';
import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts';
import { createDefaultClans } from './clan-seeds.ts';
import { backfillPresetClanMembers, createDefaultClans } from './clan-seeds.ts';
import type { ClanTuning } from './clan-tuning.ts';
import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts';
const SECONDS_PER_DAY = 86400;
export type { LeaderboardQuery };
export class ClanStore {
@@ -51,18 +53,36 @@ export class ClanStore {
readonly tuning: ClanTuning;
#state: StoredClansState;
constructor(dataFolder: string, tuning: ClanTuning) {
constructor(dataFolder: string, tuning: ClanTuning, nowSec = nowSeconds()) {
this.#filePath = join(dataFolder, 'clans.json');
this.tuning = tuning;
this.#state = this.#loadOrSeed();
this.#state = this.#loadOrSeed(nowSec);
}
#loadOrSeed(): StoredClansState {
#loadOrSeed(nowSec: number): StoredClansState {
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
if (existsSync(this.#filePath)) {
const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState;
if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') return parsed;
if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') {
let mutated = false;
for (let i = 0; i < this.tuning.presetClans.clans.length; i++) {
const spec = this.tuning.presetClans.clans[i]!;
const existing = parsed.clans.find((c) => c.id === spec.id);
if (existing && backfillPresetClanMembers(existing, spec, i, todayDay, this.tuning)) {
mutated = true;
}
}
for (const clan of parsed.clans) {
if (clan.lastRewardDay === undefined) {
clan.lastRewardDay = todayDay;
mutated = true;
}
}
if (mutated) this.#save(parsed);
return parsed;
}
}
const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning) };
const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning, nowSec) };
this.#save(seeded);
return seeded;
}
@@ -71,19 +91,7 @@ export class ClanStore {
writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2));
}
#resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined {
return clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(userId)?.clan;
}
byId(clanId: string): ClanRecord | undefined {
return this.#state.clans.find((c) => c.id === clanId);
}
findClan(query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }): ClanRecord | undefined {
return findClanInList(this.#state.clans, query);
}
clanOfUser(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
#findUserClan(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
for (const clan of this.#state.clans) {
const member = clan.members.find((m) => m.uid === userId);
if (member) return { clan, member };
@@ -91,12 +99,147 @@ export class ClanStore {
return undefined;
}
#resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined {
return clanId && clanId !== '-1'
? this.#state.clans.find((c) => c.id === clanId)
: this.#findUserClan(userId)?.clan;
}
/**
* Lazily settles expired activity reward periods for all squadrons using the stock
* client formula (`clanAverageActivityModal.nut:44-54`):
* `myExp = min(min(1, myPercent / clanPercent) * clanActivity, maxClanActivity)`
* Player members' current-period activity resets to 0 for the new period while NPC
* members keep their active roster contribution.
*/
settleExpiredPeriods(nowSec = nowSeconds()): boolean {
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
const {
maxPerPeriod,
squadronRpPerFullPeriod: maxClanActivity,
rewardPeriodDays,
historyDepthDays,
} = this.tuning.activity;
let mutated = false;
for (const clan of this.#state.clans) {
if (clan.lastRewardDay === undefined) {
clan.lastRewardDay = todayDay;
mutated = true;
continue;
}
const elapsedDays = todayDay - clan.lastRewardDay;
if (elapsedDays < rewardPeriodDays) continue;
const anchorDay = clan.lastRewardDay;
const periodsPassed = Math.floor(elapsedDays / rewardPeriodDays);
const settlementDay = anchorDay + rewardPeriodDays;
const nextAnchorDay = anchorDay + periodsPassed * rewardPeriodDays;
const clanActivity = clan.members.reduce((sum, m) => sum + Math.max(0, m.curActivity), 0);
const maxActivity = maxPerPeriod * clan.members.length;
const clanPercent = maxActivity > 0 ? clanActivity / maxActivity : 0;
const minKeptDay = settlementDay - historyDepthDays;
clan.members = clan.members.map((member) => {
const myActivity = Math.max(0, member.curActivity);
const myPercent = maxPerPeriod > 0 ? myActivity / maxPerPeriod : 0;
const myExp = (myPercent > 0 && clanPercent > 0)
? Math.min(maxClanActivity, Math.round(Math.min(1, myPercent / clanPercent) * clanActivity))
: 0;
const pastSettled = member.periods.filter((p) => !(p.exp === 0 && p.day >= anchorDay && p.day <= settlementDay));
const settledEntry = (myActivity > 0 || myExp > 0)
? [{ day: settlementDay, activity: myActivity, exp: myExp }]
: [];
const nextPeriods = [...settledEntry, ...pastSettled].filter((p) => p.day >= minKeptDay);
if (member.isNpc) {
return {
...member,
totalActivity: member.totalActivity + myActivity,
earnedSquadronExp: member.earnedSquadronExp + myExp,
periods: nextPeriods,
};
}
return {
...member,
curActivity: 0,
earnedSquadronExp: member.earnedSquadronExp + myExp,
periods: nextPeriods,
};
});
clan.lastRewardDay = nextAnchorDay;
mutated = true;
}
if (mutated) this.#save();
return mutated;
}
/**
* Accumulates current-period squadron activity from battle base vehicle RP
* (`floor(baseVehicleRp / rpPerActivityPoint)`, capped at `maxPerPeriod`).
* Returns the activity points actually added.
*/
recordBattleActivity(userId: string, baseVehicleRp: number, nowSec = nowSeconds()): number {
this.settleExpiredPeriods(nowSec);
if (!Number.isFinite(baseVehicleRp) || baseVehicleRp <= 0) return 0;
const found = this.#findUserClan(userId);
if (!found) return 0;
const { maxPerPeriod, rpPerActivityPoint } = this.tuning.activity;
const rawGain = Math.floor(baseVehicleRp / rpPerActivityPoint);
if (rawGain <= 0) return 0;
const { clan, member } = found;
const remaining = Math.max(0, maxPerPeriod - member.curActivity);
const added = Math.min(rawGain, remaining);
if (added <= 0) return 0;
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
const periodStartDay = clan.lastRewardDay ?? todayDay;
const nextCurActivity = member.curActivity + added;
const nextTotalActivity = member.totalActivity + added;
const existingInProgressIdx = member.periods.findIndex((p) => p.exp === 0 && p.day >= periodStartDay);
const nextPeriods = existingInProgressIdx >= 0
? member.periods.map((p, idx) => (idx === existingInProgressIdx ? { day: todayDay, activity: nextCurActivity, exp: 0 } : p))
: [{ day: todayDay, activity: nextCurActivity, exp: 0 }, ...member.periods];
const memberIdx = clan.members.findIndex((m) => m.uid === userId);
if (memberIdx < 0) return 0;
clan.members[memberIdx] = {
...member,
curActivity: nextCurActivity,
totalActivity: nextTotalActivity,
periods: nextPeriods,
};
this.#save();
return added;
}
byId(clanId: string, nowSec = nowSeconds()): ClanRecord | undefined {
this.settleExpiredPeriods(nowSec);
return this.#state.clans.find((c) => c.id === clanId);
}
findClan(
query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined },
nowSec = nowSeconds(),
): ClanRecord | undefined {
this.settleExpiredPeriods(nowSec);
return findClanInList(this.#state.clans, query);
}
clanOfUser(userId: string, nowSec = nowSeconds()): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
this.settleExpiredPeriods(nowSec);
return this.#findUserClan(userId);
}
pendingRequestOfUser(userId: string): ClanRecord | undefined {
return this.#state.clans.find((c) => c.candidates.some((cand) => cand.uid === userId));
}
earnedSquadronExpOf(userId: string): number {
return this.clanOfUser(userId)?.member.earnedSquadronExp ?? 0;
earnedSquadronExpOf(userId: string, nowSec = nowSeconds()): number {
return this.clanOfUser(userId, nowSec)?.member.earnedSquadronExp ?? 0;
}
npcMemberByUid(uid: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
@@ -107,8 +250,8 @@ export class ClanStore {
return undefined;
}
syncProfile(profile: BlkBlock, account: Account): void {
const found = this.clanOfUser(account.userId);
syncProfile(profile: BlkBlock, account: Account, nowSec = nowSeconds()): void {
const found = this.clanOfUser(account.userId, nowSec);
if (found) {
const { clan, member } = found;
if (member.nick !== account.nick) {
@@ -131,15 +274,31 @@ export class ClanStore {
}
}
queryLeaderboard(query: LeaderboardQuery): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> {
queryLeaderboard(query: LeaderboardQuery, nowSec = nowSeconds()): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> {
this.settleExpiredPeriods(nowSec);
return queryClanLeaderboard(this.#state.clans, query, this.tuning);
}
createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome {
this.settleExpiredPeriods(nowSec);
const outcome = createClanInState(this.#state, profile, account, economy, this.tuning, input, nowSec);
if (outcome.ok) {
const created = this.#state.clans[0];
if (created) {
created.lastRewardDay = Math.floor(nowSec / SECONDS_PER_DAY);
const founder = created.members[0];
if (founder && founder.uid === account.userId) {
const curActivity = Math.min(this.tuning.activity.maxPerPeriod, this.tuning.activity.startingActivity);
const periodActivitySum = founder.periods.reduce((s, p) => s + p.activity, 0);
created.members[0] = {
...founder,
curActivity,
totalActivity: founder.periods.length > 0 ? periodActivitySum : curActivity,
};
}
}
this.#save();
this.syncProfile(profile, account);
this.syncProfile(profile, account, nowSec);
}
return outcome;
}
@@ -189,10 +348,11 @@ export class ClanStore {
}
requestOrCancelMembership(profile: BlkBlock, account: Account, query: MembershipRequestQuery, nowSec = nowSeconds()): RuleOutcome {
const res = requestOrCancelMembershipInState(this.#state.clans, this.findClan(query), Boolean(this.clanOfUser(account.userId)), account, query, nowSec, this.tuning);
this.settleExpiredPeriods(nowSec);
const res = requestOrCancelMembershipInState(this.#state.clans, findClanInList(this.#state.clans, query), Boolean(this.#findUserClan(account.userId)), account, query, nowSec, this.tuning);
if (res.mutated) {
this.#save();
this.syncProfile(profile, account);
this.syncProfile(profile, account, nowSec);
}
return res.outcome;
}
+46 -1
View File
@@ -26,6 +26,17 @@ export interface PresetMember {
readonly activity: number;
}
export interface PresetFillerMembers {
readonly activityMin: number;
readonly activityMax: number;
readonly uidBase: number;
readonly uidStride: number;
readonly callsigns: readonly string[];
readonly titles: readonly string[];
readonly icons: readonly string[];
readonly units: readonly string[];
}
export interface PresetClan {
readonly id: string;
readonly tag: string;
@@ -37,6 +48,7 @@ export interface PresetClan {
readonly region: string;
readonly autoAccept: boolean;
readonly createdAfterDays: number;
readonly targetMemberCount: number;
readonly rating: ModeTriple;
readonly members: readonly PresetMember[];
}
@@ -47,6 +59,8 @@ export interface ClanTuning {
readonly squadronRpPerFullPeriod: number;
readonly rewardPeriodDays: number;
readonly historyDepthDays: number;
readonly rpPerActivityPoint: number;
readonly startingActivity: number;
readonly startingPeriods: number;
};
readonly memberLimits: { readonly normal: number; readonly battalionInitial: number };
@@ -56,6 +70,8 @@ export interface ClanTuning {
readonly presetClans: {
readonly createdDaysAgo: number;
readonly memberJoinSpacingMinutes: number;
readonly npcHistoryPeriods: number;
readonly fillerMembers: PresetFillerMembers;
readonly stats: PresetClanStats;
readonly memberRating: { readonly step: ModeTriple; readonly floor: ModeTriple };
readonly clans: readonly PresetClan[];
@@ -64,6 +80,7 @@ export interface ClanTuning {
export function readClanTuning(file: TuningReader): ClanTuning {
const activity = file.object('activity');
const maxPerPeriod = activity.int('maxPerPeriod', { min: 1 });
const limits = file.object('memberLimits');
const leaderboard = file.object('leaderboard');
const preset = file.object('presetClans');
@@ -71,10 +88,12 @@ export function readClanTuning(file: TuningReader): ClanTuning {
const rating = preset.object('memberRating');
return {
activity: {
maxPerPeriod: activity.int('maxPerPeriod', { min: 1 }),
maxPerPeriod,
squadronRpPerFullPeriod: activity.int('squadronRpPerFullPeriod', { min: 0 }),
rewardPeriodDays: activity.int('rewardPeriodDays', { min: 1 }),
historyDepthDays: activity.int('historyDepthDays', { min: 1 }),
rpPerActivityPoint: activity.int('rpPerActivityPoint', { min: 1 }),
startingActivity: activity.int('startingActivity', { min: 0, max: maxPerPeriod }),
startingPeriods: activity.int('startingPeriods', { min: 0 }),
},
memberLimits: { normal: limits.int('normal', { min: 1 }), battalionInitial: limits.int('battalionInitial', { min: 1 }) },
@@ -84,6 +103,8 @@ export function readClanTuning(file: TuningReader): ClanTuning {
presetClans: {
createdDaysAgo: preset.int('createdDaysAgo', { min: 0 }),
memberJoinSpacingMinutes: preset.int('memberJoinSpacingMinutes', { min: 0 }),
npcHistoryPeriods: preset.int('npcHistoryPeriods', { min: 0 }),
fillerMembers: readFillerMembers(preset.object('fillerMembers'), maxPerPeriod),
stats: Object.fromEntries(STAT_KEYS.map((key) => [key, stats.int(key, { min: 0 })])) as unknown as PresetClanStats,
memberRating: { step: triple(rating.object('step')), floor: triple(rating.object('floor')) },
clans: preset.list('clans', readPresetClan),
@@ -91,11 +112,34 @@ export function readClanTuning(file: TuningReader): ClanTuning {
};
}
function readFillerMembers(entry: TuningReader, maxPerPeriod: number): PresetFillerMembers {
const activityMin = entry.int('activityMin', { min: 0, max: maxPerPeriod });
const activityMax = entry.int('activityMax', { min: activityMin, max: maxPerPeriod });
const callsigns = entry.stringList('callsigns');
const titles = entry.stringList('titles');
const icons = entry.stringList('icons');
const units = entry.stringList('units');
if (callsigns.length === 0 || titles.length === 0 || icons.length === 0 || units.length === 0) {
throw new TuningError('tuning file clans.jsonc: presetClans.fillerMembers callsigns, titles, icons, and units must be non-empty');
}
return {
activityMin,
activityMax,
uidBase: entry.int('uidBase', { min: 1 }),
uidStride: entry.int('uidStride', { min: 1 }),
callsigns,
titles,
icons,
units,
};
}
function readPresetClan(entry: TuningReader): PresetClan {
const type = entry.string('type');
if (type !== 'normal' && type !== 'battalion') throw new TuningError(`tuning file clans.jsonc: clan type must be normal or battalion (found "${type}")`);
const members = entry.list('members', readPresetMember);
if (members.length === 0) throw new TuningError(`tuning file clans.jsonc: preset clan ${entry.string('id')} needs at least one member (the first is its leader)`);
const rawTarget = entry.has('targetMemberCount') ? entry.int('targetMemberCount', { min: 1 }) : members.length;
return {
id: entry.string('id'),
tag: entry.string('tag'),
@@ -107,6 +151,7 @@ function readPresetClan(entry: TuningReader): PresetClan {
region: entry.string('region'),
autoAccept: entry.bool('autoAccept'),
createdAfterDays: entry.int('createdAfterDays', { min: 0 }),
targetMemberCount: Math.max(members.length, rawTarget),
rating: triple(entry.object('rating')),
members,
};
+2
View File
@@ -171,6 +171,8 @@ export interface ClanRecord {
changedByNick: string;
changedTimeSec: number;
regionLastUpdatedSec: number;
/** UTC day index (floor(unixSec / 86400)) when the current activity reward period started. */
lastRewardDay?: number;
stats: ClanStats;
members: ClanMemberRecord[];
candidates: ClanCandidateRecord[];
@@ -4,8 +4,10 @@
* `extInventory` and pushing `mrpc.generic_notify` (`inventory.changed`) to active game clients.
*/
import { gjnText } from '../store/redeem-codes.ts';
import { DEFAULT_FREE_PAYMENT_LABEL } from '../store/store-tuning.ts';
import type { BlkBlock } from '@wto/blk';
import type { AccountStore } from '../accounts/account-store.ts';
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import { balanceOf } from '../profile/profile-currency.ts';
import { externalInventoryItems } from '../profile/profile-external-inventory.ts';
@@ -36,6 +38,7 @@ export class MarketplaceService implements Service {
readonly #notifyInventoryChanged: () => void;
readonly #maxPerPurchase: number;
readonly #sellFeeRate: number;
readonly #freePaymentLabel: LocalizedText;
constructor(
accounts: AccountStore,
@@ -43,6 +46,7 @@ export class MarketplaceService implements Service {
catalogue: InventoryCatalogue,
notifyInventoryChanged: () => void,
tuning: Pick<MarketplaceTuning, 'maxPerPurchase' | 'sellFeeRate'>,
freePaymentLabel: LocalizedText = DEFAULT_FREE_PAYMENT_LABEL,
) {
this.#accounts = accounts;
this.#profiles = profiles;
@@ -50,6 +54,7 @@ export class MarketplaceService implements Service {
this.#notifyInventoryChanged = notifyInventoryChanged;
this.#maxPerPurchase = tuning.maxPerPurchase;
this.#sellFeeRate = tuning.sellFeeRate;
this.#freePaymentLabel = freePaymentLabel;
}
accepts(request: ServiceRequest): boolean {
@@ -96,6 +101,7 @@ export class MarketplaceService implements Service {
currentUserId: account?.userId ?? '',
balance,
sellFeeRate: this.#sellFeeRate,
freePaymentLabel: this.#freePaymentLabel,
listings,
}, `marketplace state (${account?.userId ?? 'no-account'})`);
}
@@ -158,7 +164,13 @@ export class MarketplaceService implements Service {
});
if (errorReason === 'NOT_ENOUGH_GJN') {
return jsonResponse({ ok: false, message: { zh: 'GJN 不够。可直接点「老福爷付过了」,或在商店的"兑换码"页用 GJN 充值码补充。', en: 'Not enough GJN. Use "老福爷付过了" or a GJN code on the Redeem tab of the store.' } }, `marketplace buy ${itemdefId}: NOMONEY`);
return jsonResponse({
ok: false,
message: {
zh: `GJN 不够。可直接点「${this.#freePaymentLabel.zh}」,或在商店的"兑换码"页用 GJN 充值码补充。`,
en: `Not enough GJN. Use "${this.#freePaymentLabel.en}" or a GJN code on the Redeem tab of the store.`,
},
}, `marketplace buy ${itemdefId}: NOMONEY`);
}
if (errorReason) {
return jsonResponse({ ok: false, message: { zh: '购买失败。', en: 'Purchase failed.' } }, `marketplace buy ${itemdefId}: ${errorReason}`);
@@ -166,15 +178,23 @@ export class MarketplaceService implements Service {
this.#notifyInventoryChanged();
const costSummary = isFree ? 'free' : `${gjnText(listing.gjnCostCents * quantity)} GJN`;
return jsonResponse({ ok: true, message: buySuccessMessage(listing, quantity, isFree) }, `marketplace buy ${itemdefId} x${quantity} (${costSummary})`);
return jsonResponse(
{ ok: true, message: buySuccessMessage(listing, quantity, isFree, this.#freePaymentLabel) },
`marketplace buy ${itemdefId} x${quantity} (${costSummary})`,
);
}
}
function buySuccessMessage(listing: MarketplaceListing, quantity: number, isFree: boolean): { zh: string; en: string } {
function buySuccessMessage(
listing: MarketplaceListing,
quantity: number,
isFree: boolean,
freePaymentLabel: LocalizedText,
): LocalizedText {
return isFree
? {
zh: `老福爷付过了!「${listing.title.zh}」兑换券 ×${quantity} 已放进游戏库存,可在机库的"道具 → 库存"里使用。`,
en: `Paid by 老福爷! ${quantity} × "${listing.title.en}" coupon is in your inventory (Items → Inventory in the hangar).`,
zh: `已通过「${freePaymentLabel.zh}」获得「${listing.title.zh}」兑换券 ×${quantity},已放进游戏库存,可在机库的"道具 → 库存"里使用。`,
en: `Claimed ${quantity} × "${listing.title.en}" coupon via "${freePaymentLabel.en}". It is in your inventory (Items → Inventory in the hangar).`,
}
: {
zh: `已购买「${listing.title.zh}」兑换券 ×${quantity},已放进游戏库存,可在机库的"道具 → 库存"里使用。`,
+8 -4
View File
@@ -9,7 +9,7 @@ const T = {
heldOnly: '只看我的库存', search: '搜索', sortPopular: '人气', sortName: '名称(从 A 到 Z)', sortPriceAsc: '价格(从低到高)', sortPriceDesc: '价格(从高到低)',
catVehicle: '载具', catSkin: '涂装', catAttachable: '装饰挂件', catDecal: '贴花', catUnlock: '头像',
allCountries: '全部国家', allClasses: '全部', rank: '{rank} 级', from: '从', held: '库存 ×{n}', owned: '已拥有',
buy: '购买', freeBuy: '老福爷付过了', sell: '出售', pickAccount: '请先在右上角选择账号', empty: '没有符合条件的物品',
buy: '购买', freeBuy: '直接获取', sell: '出售', pickAccount: '请先在右上角选择账号', empty: '没有符合条件的物品',
buyPrice: '系统售价:<b>{price}</b> GJN', sellPrice: '卖给系统:<b>{price}</b> GJN(扣 {fee}% 手续费)', youHave: '你拥有:<b>{n}</b>',
tradeUnconfirmed: '无法确认交易结果,请先查看余额和库存。',
tagType: '物品类型', tagRarity: '稀有度', tagCountry: '国家', ticker: '离线交易所:按固定价格与系统交易,价格取自官方交易所快照。',
@@ -19,7 +19,7 @@ const T = {
heldOnly: 'Only my inventory', search: 'Search', sortPopular: 'Popular', sortName: 'Name (A to Z)', sortPriceAsc: 'Price (low to high)', sortPriceDesc: 'Price (high to low)',
catVehicle: 'Vehicles', catSkin: 'Camouflages', catAttachable: 'Decorations', catDecal: 'Decals', catUnlock: 'Avatars',
allCountries: 'All countries', allClasses: 'All', rank: 'Rank {rank}', from: 'from', held: 'Owned ×{n}', owned: 'Owned',
buy: 'Buy', freeBuy: '老福爷付过了', sell: 'Sell', pickAccount: 'Pick an account at the top right', empty: 'Nothing matches the filters',
buy: 'Buy', freeBuy: 'Direct Claim', sell: 'Sell', pickAccount: 'Pick an account at the top right', empty: 'Nothing matches the filters',
buyPrice: 'System price: <b>{price}</b> GJN', sellPrice: 'Sell to system: <b>{price}</b> GJN ({fee}% fee)', youHave: 'You own: <b>{n}</b>',
tradeUnconfirmed: 'Could not confirm the trade. Check your balance and inventory.',
tagType: 'Item type', tagRarity: 'Rarity', tagCountry: 'Country', ticker: 'Offline market: fixed-price trades with the system, prices from an official market snapshot.',
@@ -33,7 +33,11 @@ const t = (key, params) => WtoUi.tr(T, key, params);
const $ = (id) => document.getElementById(id);
const wantedItem = WtoUi.query.get('n') || '';
let state = { accounts: [], currentUserId: '', balance: { gjnCents: 0, goldenEagles: 0 }, listings: [] };
let state = { accounts: [], currentUserId: '', balance: { gjnCents: 0, goldenEagles: 0 }, listings: [], freePaymentLabel: null };
function freePaymentLabel() {
return WtoUi.text(state.freePaymentLabel) || t('freeBuy');
}
const activeCats = new Set();
let openedWanted = false;
let tradeNoticeId = 0;
@@ -173,7 +177,7 @@ function fillOrderColumns(detail, listing) {
sellCol.append(sellBtn, html('totals', t('sellPrice', { price: WtoUi.gjn(listing.sellCents), fee })), html('totals', t('youHave', { n: listing.couponCount || 0 })));
const buyBtn = Object.assign(document.createElement('button'), { className: 'big buy', textContent: noAccount ? t('pickAccount') : t('buy'), disabled: noAccount });
buyBtn.onclick = () => trade('/trade.gaijin.net/api/buy', { itemdefId: listing.itemdefId, quantity: 1, payMethod: 'gjn' }, listing);
const freeBtn = Object.assign(document.createElement('button'), { className: 'big free', textContent: t('freeBuy'), disabled: noAccount });
const freeBtn = Object.assign(document.createElement('button'), { className: 'big free', textContent: freePaymentLabel(), disabled: noAccount });
freeBtn.onclick = () => trade('/trade.gaijin.net/api/buy', { itemdefId: listing.itemdefId, quantity: 1, payMethod: 'free' }, listing);
buyCol.append(buyBtn, freeBtn, html('totals', t('buyPrice', { price: WtoUi.gjn(listing.gjnCostCents) })));
}
@@ -12,7 +12,7 @@ import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.
import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts';
import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankEntry } from '../battle/battle-ranks.ts';
import type { BattleSession, BattleSessionStore } from '../battle/battle-session-store.ts';
import { DAILY_BACKUP, recordDailyBackupSpawn } from '../battle/battle-spares.ts';
import { DAILY_BACKUP, normalizeBackupUnitName, recordDailyBackupSpawn } from '../battle/battle-spares.ts';
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
import { dailySparesLeft } from '../profile/profile-daily-spares.ts';
@@ -50,8 +50,9 @@ export function battleQueueRequests(deps: BattleQueueDependencies): Array<[strin
return { error: 'BAD_PARAMS' };
}
const battle = deps.sessions.findForUser(sessionId, userId);
if (!battle || battle.settled || battle.spareSlots?.get(slot) !== unit) return { error: 'BAD_PARAMS' };
deps.profiles.updateWhen(userId, (profile) => recordDailyBackupSpawn(profile, battle, { slot, unit, backup: DAILY_BACKUP }));
const normalizedUnit = normalizeBackupUnitName(unit);
if (!battle || battle.settled || battle.spareSlots?.get(slot) !== normalizedUnit) return { error: 'BAD_PARAMS' };
deps.profiles.updateWhen(userId, (profile) => recordDailyBackupSpawn(profile, battle, { slot, unit: normalizedUnit, backup: DAILY_BACKUP }));
return {};
}],
];
+17 -4
View File
@@ -1,22 +1,30 @@
/**
* The profile as the char service hands it to the client: the saved profile plus the
* account data and server clock the char server attaches on the wire.
* account data, server clock, and active squadron season metadata the char server attaches
* on the wire.
*
* charDrivenNick: the client reads the player's nick from this top-level string when it
* loads a profile (name looked up at aces.exe 2.61.0.37 0x8fe0aa, value stored at 0x91874d).
*
* serverTime:i64: the char server's clock; without it the client
* takes the server time as 0 and every expiry and time limit is wrong.
*
* clanDuelNextReward:i64, clanSeasonStart:i64, clanSeasonOrdinal:i, clanSeasonInYear:i:
* parsed by GameSaveData::onAsyncEconTransComplete (aces.exe 2.61.0.58 0xebc728..0xebc7b4)
* on every profile-returning char response and exposed by clan_get_current_season_info
* (0x178aff0..0x178b227). Without them all fields default to 0, causing the squadron
* leaderboard to display "1970-I" and "1970-01-01".
*/
import { setParam, type BlkBlock } from '@wto/blk';
import type { Account } from '../accounts/account-store.ts';
import { currentClanSeason } from '../clans/clan-season.ts';
import { appearance, DEFAULT_PILOT_ICON } from './profile-appearance.ts';
import { DAILY_SPARES_BLOCK } from './profile-daily-spares.ts';
import { clearStoreCart } from './profile-store-cart.ts';
import { clientHangarSpares } from './profile-vehicle-state.ts';
import { serverTimeNow } from './server-time.ts';
import { serverTimeFromUnixMs } from './server-time.ts';
export function clientProfile(saved: BlkBlock, account: Account): BlkBlock {
export function clientProfile(saved: BlkBlock, account: Account, nowMs = Date.now()): BlkBlock {
// Clone the hangar entries whose spare count has a different wire representation.
const profile: BlkBlock = {
name: saved.name,
@@ -26,8 +34,13 @@ export function clientProfile(saved: BlkBlock, account: Account): BlkBlock {
};
clearStoreCart(profile);
const pilotIcon = appearance(profile).pilotIcon || DEFAULT_PILOT_ICON;
const season = currentClanSeason(Math.floor(nowMs / 1000));
setParam(profile, 'pilotIcon', { type: 'string', value: pilotIcon });
setParam(profile, 'charDrivenNick', { type: 'string', value: account.nick });
setParam(profile, 'serverTime', { type: 'int64', value: serverTimeNow() });
setParam(profile, 'serverTime', { type: 'int64', value: serverTimeFromUnixMs(nowMs) });
setParam(profile, 'clanDuelNextReward', { type: 'int64', value: BigInt(season.rewardDaySec) });
setParam(profile, 'clanSeasonStart', { type: 'int64', value: BigInt(season.startDaySec) });
setParam(profile, 'clanSeasonOrdinal', { type: 'int', value: season.ordinalNumber });
setParam(profile, 'clanSeasonInYear', { type: 'int', value: season.numberInYear });
return profile;
}
@@ -5,7 +5,14 @@
* - hangar toggles `autoRefillWeapons:b`, `autoRepairAircrafts:b`, `autoBuyModifications:b` (0x918ef0);
* - privacy / save metadata `onlineSaveVersion:i`, `allowToBeAddedToContacts:b`, `allowToBeAddedToLB:b` (0x9179d4..0x917a4c);
* - `classinessMarkPriorities:i64` (0x92b2cb);
* - sub-block `mapPreferences` (0x927530 -> 0x9483d0).
* - sub-block `mapPreferences` (0x927530 -> 0x9483d0);
* - per-vehicle `hangar/<vehicle>` client preferences (`AircraftInfo::serialize` mode 0x20/0x80,
* owned vehicles only per the stock chard guard at 0x938081):
* - `lastSkin:t` (2.61.0.37 0x940fbc/0x94111b, 2.61.0.58 0x943a2f/0x943b8e);
* - `lastWeapon:t` (2.61.0.37 0x940ff4/0x941084, 2.61.0.58 0x943a67/0x943af7);
* - `lastBullets0..5:t` (2.61.0.37 0x94078d..0x940914 / 0x940b2c..0x940f8d, 2.61.0.58 0x943200..0x94393e);
* - `aileronTrim:r`, `elevatorTrim:r`, `rudderTrim:r` (2.61.0.37 0x941682..0x941720 / 0x9411e7..0x9412db,
* 2.61.0.58 0x943c7a..0x944119).
*
* Empty shell blocks that `saveOnline` (mode 0x20) also emits (`entitlementsInfo{}`,
* `pveProgress{}`, `weaponPresets{}` — custom weapon presets use `cln_save_weapon_presets`, and
@@ -13,6 +20,7 @@
* state is preserved.
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
import { updateOwnedVehicle } from './profile-hangar.ts';
import { disableUserLogs } from './profile-trophies-log.ts';
const BOOL_SETTINGS = [
@@ -23,6 +31,23 @@ const BOOL_SETTINGS = [
'allowToBeAddedToLB',
] as const;
const VEHICLE_STRING_SETTINGS = [
'lastSkin',
'lastWeapon',
'lastBullets0',
'lastBullets1',
'lastBullets2',
'lastBullets3',
'lastBullets4',
'lastBullets5',
] as const;
const VEHICLE_TRIM_SETTINGS = [
'aileronTrim',
'elevatorTrim',
'rudderTrim',
] as const;
/**
* Whether hangar ammunition/expendable auto-refill is enabled (`EconomicState` +0xe979).
* Defaults to `true` when absent from `profile.blk`, matching `aces.exe` 0x90b6a0 and 0x918ef0.
@@ -57,6 +82,10 @@ export function applyClientProfileUpdate(profile: BlkBlock, request: BlkBlock):
target.blocks = cloned.blocks;
}
for (const vehicle of findBlock(request, 'hangar')?.blocks ?? []) {
applyVehicleClientSettings(profile, vehicle);
}
const userlogs = findBlock(request, 'userlogs');
if (userlogs) {
const idsToDisable = userlogs.blocks
@@ -68,3 +97,16 @@ export function applyClientProfileUpdate(profile: BlkBlock, request: BlkBlock):
if (idsToDisable.length > 0) disableUserLogs(profile, idsToDisable);
}
}
function applyVehicleClientSettings(profile: BlkBlock, vehicle: BlkBlock): void {
updateOwnedVehicle(profile, vehicle.name, (entry) => {
for (const name of VEHICLE_STRING_SETTINGS) {
const param = findParam(vehicle, name)?.value;
if (param?.type === 'string') setParam(entry, name, param);
}
for (const name of VEHICLE_TRIM_SETTINGS) {
const param = findParam(vehicle, name)?.value;
if (param?.type === 'real' && Number.isFinite(param.value)) setParam(entry, name, param);
}
});
}
@@ -31,6 +31,12 @@ export function addOwnedVehicle(profile: BlkBlock, vehicle: string): void {
if (!hangar.blocks.some((owned) => owned.name === vehicle)) hangar.blocks.push({ name: vehicle, params: [], blocks: [] });
}
/** Update an owned vehicle's hangar entry in place; ignores vehicles the player does not own. */
export function updateOwnedVehicle(profile: BlkBlock, vehicle: string, update: (entry: BlkBlock) => void): void {
const entry = ownedVehicle(profile, vehicle);
if (entry) update(entry);
}
/** The stock client uses the base rank until it has a non-negative selection. */
export function vehicleMrankDelta(profile: BlkBlock, vehicle: string): number {
return Math.max(0, intField(ownedVehicle(profile, vehicle), MRANK_DELTA));
+5 -2
View File
@@ -60,6 +60,7 @@ import { Router } from './transport/router.ts';
import { loadOrCreateCredentials } from './transport/tls/tls-certificate.ts';
import { StoreCatalogue } from './store/store-catalogue.ts';
import { StoreService } from './store/store-service.ts';
import { bindStoreFreePaymentLabel } from './store/store-tuning.ts';
import { TrainingCatalogue } from './training/training-completion.ts';
import { TrafficLog } from './traffic-log/traffic-log.ts';
import { loadTuning, type Tuning } from './tuning/tuning.ts';
@@ -235,7 +236,7 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
webUi,
new RegistrationService(accounts),
new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port),
new MarketplaceService(accounts, profiles, catalogues.inventory, notifyInventoryChanged, tuning.marketplace),
new MarketplaceService(accounts, profiles, catalogues.inventory, notifyInventoryChanged, tuning.marketplace, tuning.store.freePaymentLabel),
new InventoryService(accounts, profiles, catalogues.inventory),
new LoginService(accounts),
new CharService(actionTable({
@@ -310,12 +311,14 @@ function loadDomainCatalogues(
localizedUnitNames: UnitNamesMap,
) {
const classicItemDefs = datasets.load(itemCatalogue);
const store = new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames, labels, tuning.store);
bindStoreFreePaymentLabel(store, tuning.store.freePaymentLabel);
return {
crew: new CrewSkillCatalogue(datasets.load(crewSkillData)),
decor: new DecorShop(datasets.load(decorCatalogue)),
unlocks: new UnlockShop(datasets.load(unlockPrices)),
items: new ItemCatalogue(classicItemDefs, tuning.limits.itemPiecesPerPurchase),
store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames, labels, tuning.store),
store,
inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs, tuning),
trophies: new TrophyCatalogue(vehicles, classicItemDefs, tuning.trophies),
training: new TrainingCatalogue(datasets.load(trainingMissions)),
+43
View File
@@ -39,7 +39,27 @@ export interface MultiVehiclePack extends VehiclePackContent {
readonly vehicles: readonly string[];
}
export const DEFAULT_FREE_PAYMENT_LABEL: LocalizedText = {
zh: '直接获取',
en: 'Direct Claim',
};
const MAX_FREE_PAYMENT_LABEL_LENGTH = 64;
const freePaymentLabelsByStore = new WeakMap<object, LocalizedText>();
/** Associate a configured free payment label with a StoreCatalogue instance. */
export function bindStoreFreePaymentLabel(store: object, label: LocalizedText): void {
freePaymentLabelsByStore.set(store, label);
}
/** Return the configured free payment label for a StoreCatalogue instance, falling back to the default. */
export function freePaymentLabelForStore(store: object): LocalizedText {
return freePaymentLabelsByStore.get(store) ?? DEFAULT_FREE_PAYMENT_LABEL;
}
export interface StoreTuning {
/** Localized label for the no-GJN offline payment button in the game dialog, local store, and marketplace. */
readonly freePaymentLabel: LocalizedText;
readonly goldenEaglePacks: readonly GoldenEaglePack[];
readonly silverLionPacks: readonly SilverLionPack[];
readonly premiumForGoldenEagles: readonly PremiumTier[];
@@ -53,6 +73,7 @@ export interface StoreTuning {
}
export function readStoreTuning(file: TuningReader): StoreTuning {
const freePaymentLabel = readFreePaymentLabel(file);
const packs = file.object('vehiclePacks');
const byRank = packs.list('byRank', (entry) => ({ upToRank: entry.int('upToRank', { min: 1 }), ...packContent(entry) }))
.sort((a, b) => a.upToRank - b.upToRank);
@@ -66,6 +87,7 @@ export function readStoreTuning(file: TuningReader): StoreTuning {
validateStoreUniqueness(goldenEaglePacks, silverLionPacks, premiumForGoldenEagles, premiumForGjn, multiVehiclePacks);
return {
freePaymentLabel,
goldenEaglePacks,
silverLionPacks,
premiumForGoldenEagles,
@@ -76,6 +98,27 @@ export function readStoreTuning(file: TuningReader): StoreTuning {
};
}
function readFreePaymentLabel(file: TuningReader): LocalizedText {
const labelObj = file.object('freePaymentLabel');
return {
zh: readFreePaymentLabelPart(labelObj, 'zh'),
en: readFreePaymentLabelPart(labelObj, 'en'),
};
}
function readFreePaymentLabelPart(entry: TuningReader, key: 'zh' | 'en'): string {
const trimmed = entry.string(key).trim();
if (trimmed === '') {
throw new TuningError(`tuning file store.jsonc: freePaymentLabel.${key} must not be blank`);
}
if (trimmed.length > MAX_FREE_PAYMENT_LABEL_LENGTH) {
throw new TuningError(
`tuning file store.jsonc: freePaymentLabel.${key} must be at most ${MAX_FREE_PAYMENT_LABEL_LENGTH} characters`,
);
}
return trimmed;
}
/** The pack content for a vehicle: its own entry over the first rank tier that covers its rank (the last tier above the highest). */
export function vehiclePackContent(tuning: StoreTuning, vehicle: string, rank: number): VehiclePackContent {
const tier = tuning.vehiclePacksByRank.find((entry) => rank <= entry.upToRank) ?? tuning.vehiclePacksByRank[tuning.vehiclePacksByRank.length - 1]!;
+35 -10
View File
@@ -20,6 +20,7 @@ import { describeRedeemCodes, gjnText, redeemStoreCode, type RedeemOutcome } fro
import type { RedeemTuning } from './redeem-tuning.ts';
import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts';
import { buyFreeStoreProduct, buyGjnProduct, buyStoreCart, canBuyGjnProduct, type GjnPurchaseOutcome, type StoreCheckoutOutcome } from './store-purchase.ts';
import { freePaymentLabelForStore } from './store-tuning.ts';
const NO_ACCOUNT: LocalizedText = { zh: '没有找到这个账号,请先在右上角选择账号。', en: 'Account not found. Pick an account at the top right first.' };
@@ -31,12 +32,20 @@ export class StoreWebApi {
readonly #profiles: PlayerProfiles;
readonly #catalogue: StoreCatalogue;
readonly #redeemCodes: RedeemTuning;
readonly #freePaymentLabel: LocalizedText;
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning) {
constructor(
accounts: AccountStore,
profiles: PlayerProfiles,
catalogue: StoreCatalogue,
redeemCodes: RedeemTuning,
freePaymentLabel?: LocalizedText,
) {
this.#accounts = accounts;
this.#profiles = profiles;
this.#catalogue = catalogue;
this.#redeemCodes = redeemCodes;
this.#freePaymentLabel = freePaymentLabel ?? freePaymentLabelForStore(catalogue);
}
/** The answer for /store/api/<name>, or undefined when it is not an API request. */
@@ -64,6 +73,7 @@ export class StoreWebApi {
products,
cartProductIds: profile ? storeCartIds(profile) : [],
redeemHelp: describeRedeemCodes(this.#redeemCodes),
freePaymentLabel: this.#freePaymentLabel,
}, `store web state (${account?.userId ?? 'no account'})`);
}
@@ -94,7 +104,10 @@ export class StoreWebApi {
return true;
});
const modeTag = isFree ? 'free' : 'gjn';
return jsonResponse({ ok: outcome.ok, cartProductIds, message: purchaseMessage(outcome, product, isFree) }, `store web buy ${product.id} (${modeTag}): ${outcome.ok ? 'OK' : outcome.reason}`);
return jsonResponse(
{ ok: outcome.ok, cartProductIds, message: purchaseMessage(outcome, product, isFree, this.#freePaymentLabel) },
`store web buy ${product.id} (${modeTag}): ${outcome.ok ? 'OK' : outcome.reason}`,
);
}
#cart(request: ServiceRequest): ServiceResponse {
@@ -153,7 +166,7 @@ export class StoreWebApi {
return false;
}
const outcome = buyStoreCart(profile, products, payMethod, now);
message = checkoutMessage(outcome, products, payMethod);
message = checkoutMessage(outcome, products, payMethod, this.#freePaymentLabel);
if (!outcome.ok) return false;
clearStoreCart(profile);
cartProductIds = [];
@@ -177,13 +190,18 @@ export class StoreWebApi {
}
}
function purchaseMessage(outcome: GjnPurchaseOutcome, product: StoreProduct, isFree: boolean): LocalizedText {
function purchaseMessage(
outcome: GjnPurchaseOutcome,
product: StoreProduct,
isFree: boolean,
freePaymentLabel: LocalizedText,
): LocalizedText {
const cost = gjnText(product.gjnCostCents ?? 0);
if (outcome.ok) {
return isFree
? {
zh: `老福爷付过了!已直接获得「${product.title.zh}」。关闭商店窗口后机库会自动刷新。`,
en: `Paid by 老福爷! Claimed "${product.title.en}". Close the store window to refresh the hangar.`,
zh: `已通过「${freePaymentLabel.zh}」获得「${product.title.zh}」。关闭商店窗口后机库会自动刷新。`,
en: `Claimed "${product.title.en}" via "${freePaymentLabel.en}". Close the store window to refresh the hangar.`,
}
: {
zh: `已购买「${product.title.zh}」,花费 ${cost} GJN。关闭商店窗口后机库会自动刷新。`,
@@ -191,7 +209,10 @@ function purchaseMessage(outcome: GjnPurchaseOutcome, product: StoreProduct, isF
};
}
if (outcome.reason === 'NOT_ENOUGH_GJN') {
return { zh: `GJN 不够:需要 ${cost} GJN。可直接点「老福爷付过了」,或在"兑换码"页用 GJN 充值码补充。`, en: `Not enough GJN: ${cost} GJN needed. Use "老福爷付过了" or a GJN code on the Redeem tab.` };
return {
zh: `GJN 不够:需要 ${cost} GJN。可直接点「${freePaymentLabel.zh}」,或在"兑换码"页用 GJN 充值码补充。`,
en: `Not enough GJN: ${cost} GJN needed. Use "${freePaymentLabel.en}" or a GJN code on the Redeem tab.`,
};
}
if (outcome.reason === 'ALREADY_BOUGHT') return alreadyBoughtMessage(product);
return { zh: '这个商品现在买不了。', en: 'This product cannot be bought right now.' };
@@ -208,19 +229,23 @@ function checkoutMessage(
outcome: StoreCheckoutOutcome,
products: readonly StoreProduct[],
payMethod: 'gjn' | 'free',
freePaymentLabel: LocalizedText,
): LocalizedText {
if (outcome.ok) {
const count = products.length;
const cost = gjnText(outcome.costCents);
return payMethod === 'free'
? { zh: `老福爷付过了!已领取 ${count} 件商品。关闭商城窗口后机库会自动刷新。`,
en: `Paid by 老福爷! Claimed ${count} items. Close the store to refresh the hangar.` }
? { zh: `已通过「${freePaymentLabel.zh}」领取 ${count} 件商品。关闭商城窗口后机库会自动刷新。`,
en: `Claimed ${count} items via "${freePaymentLabel.en}". Close the store to refresh the hangar.` }
: { zh: `已购买 ${count} 件商品,花费 ${cost} GJN。关闭商城窗口后机库会自动刷新。`,
en: `Bought ${count} items for ${cost} GJN. Close the store to refresh the hangar.` };
}
if (outcome.reason === 'NOT_ENOUGH_GJN') {
const cost = gjnText(outcome.costCents);
return { zh: `购物车共需 ${cost} GJN,当前余额不足。`, en: `Your cart costs ${cost} GJN. Your balance is too low.` };
return {
zh: `购物车共需 ${cost} GJN,当前余额不足。可直接点「${freePaymentLabel.zh}」。`,
en: `Your cart costs ${cost} GJN. Your balance is too low. Use "${freePaymentLabel.en}" instead.`,
};
}
const product = products.find((item) => item.id === outcome.productId);
return outcome.reason === 'ALREADY_BOUGHT' && product ? alreadyBoughtMessage(product) : NO_PRODUCT;
+9 -3
View File
@@ -9,7 +9,7 @@ const T = {
search: '搜索礼包或载具', allCountries: '所有国家', allRanks: '所有等级', rank: '{rank} 级',
sort: '商品排序', sortBest: '最畅销', sortNewest: '最新上架', sortPriceAsc: '价格从低到高', sortPriceDesc: '价格从高到低',
containsEagles: '{n} 金鹰', containsSilver: '{n} 银狮', containsPremium: '{days} 天高级账户',
buy: '购买', freeBuy: '老福爷付过了', owned: '已拥有', pickAccount: '请先选择账号',
buy: '购买', freeBuy: '直接获取', owned: '已拥有', pickAccount: '请先选择账号',
redeem: '兑换', codePlaceholder: '输入兑换码', empty: '没有符合条件的商品',
featured: '推荐礼包', bestSeller: '畅销', viewPack: '查看礼包', related: '更多推荐', packPrice: '礼包价格',
includes: '礼包内容', back: '返回目录', bonusTitle: '高级载具权益',
@@ -31,7 +31,7 @@ const T = {
search: 'Search packs or vehicles', allCountries: 'All nations', allRanks: 'All ranks', rank: 'Rank {rank}',
sort: 'Sort products', sortBest: 'Top sellers', sortNewest: 'Newest', sortPriceAsc: 'Price: low to high', sortPriceDesc: 'Price: high to low',
containsEagles: '{n} Golden Eagles', containsSilver: '{n} Silver Lions', containsPremium: '{days} days of Premium Account',
buy: 'Buy', freeBuy: '老福爷付过了', owned: 'Owned', pickAccount: 'Pick an account first',
buy: 'Buy', freeBuy: 'Direct Claim', owned: 'Owned', pickAccount: 'Pick an account first',
redeem: 'Redeem', codePlaceholder: 'Enter a code', empty: 'Nothing matches the filters',
featured: 'Featured packs', bestSeller: 'Top seller', viewPack: 'View pack', related: 'Explore other packs', packPrice: 'Pack price',
includes: 'Pack contents', back: 'Back to catalog', bonusTitle: 'Premium bonuses',
@@ -53,7 +53,7 @@ const t = (key, params) => WtoUi.tr(T, key, params);
const $ = (id) => document.getElementById(id);
let initialGuid = (WtoUi.query.get('item') || '').toUpperCase();
let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0 }, products: [], cartProductIds: [], redeemHelp: [] };
let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0 }, products: [], cartProductIds: [], redeemHelp: [], freePaymentLabel: null };
let currentTab = 'vehicle-pack';
let detailId = '';
let catalogScroll = 0;
@@ -61,9 +61,14 @@ let loadVersion = 0;
let loading = true;
const checkout = createStoreCheckout(loadState);
function freePaymentLabel() {
return WtoUi.text(state.freePaymentLabel) || t('freeBuy');
}
function applyStaticTexts() {
for (const el of document.querySelectorAll('[data-t]')) el.textContent = t(el.dataset.t);
for (const el of document.querySelectorAll('[data-label]')) el.setAttribute('aria-label', t(el.dataset.label));
$('payFree').textContent = freePaymentLabel();
$('searchInput').placeholder = t('search');
$('codeInput').placeholder = t('codePlaceholder');
$('marketLink').href = WtoUi.pageLink('/trade.gaijin.net/');
@@ -88,6 +93,7 @@ async function loadState(userId) {
return await loadState('');
}
state = next;
$('payFree').textContent = freePaymentLabel();
WtoUi.fillAccountSelect($('accountSelect'), state.accounts, state.activeUserId);
$('gjnVal').textContent = WtoUi.gjn(state.balance.gjnCents);
$('goldVal').textContent = WtoUi.num(state.balance.goldenEagles);