diff --git a/gui-patches/online-shop/bypass-external-sso-for-local-urls/patch.json b/gui-patches/online-shop/bypass-external-sso-for-local-urls/patch.json index 274a2b3..919b4ff 100644 --- a/gui-patches/online-shop/bypass-external-sso-for-local-urls/patch.json +++ b/gui-patches/online-shop/bypass-external-sso-for-local-urls/patch.json @@ -4,19 +4,19 @@ "file": "scripts/onlineshop/url.nut", "program_behaviour": { - "stock": "打开带 auto_login 标签的链接(如 inventoryClient.nut 的 getMarketplaceBaseUrl())时,scripts/onlineshop/url.nut 调用原生 SsoLoggedUrlAction(yu_sessionProc.cpp:951),把目标地址包装进写死的 https://login.gaijin.net/sso/LoginByStoken 链接后交给系统默认浏览器。", - "patched": "当目标链接指向本次启动的本地服务地址(://:)时,shouldLogin 取 false,让系统默认浏览器直接打开本地网页(/store、/trade.gaijin.net 等)。" + "stock": "打开带 auto_login 标签的链接(如 inventoryClient.nut 的 getMarketplaceBaseUrl())时,scripts/onlineshop/url.nut 调用原生 SsoLoggedUrlAction(yu_sessionProc.cpp:951),把目标地址包装进写死的 https://login.gaijin.net/sso/LoginByStoken 链接,再按 openUrlImpl 的判断交给游戏内置浏览器(PC 非 Steam 下就是内置浏览器,implementation notes 第 9 节)打开。", + "patched": "当目标链接指向本次启动的本地服务地址(://:)时,shouldLogin 取 false,内置浏览器直接打开本地网页(/store、/trade.gaijin.net 等)。" }, "derivation": { - "requirement": "功能清单 G「礼包商店」「市场」与 A「不连 Gaijin」。玩家在游戏内点击「在交易所中查找」或顶栏「交易所」时,必须在默认浏览器直接打开本地交易所页面,且浏览器不访问 login.gaijin.net。", - "cause": "yu_sessionProc.cpp:951 的 SsoLoggedUrlAction 硬编码拼接 https://login.gaijin.net/sso/LoginByStoken(YuSession::setOptionStringSync 无覆盖该域名的选项),再调用 shell_launch() 启动外部浏览器;外部浏览器进程不加载游戏的 wto_ws.dll,会直接连向真实 Gaijin 登录服务器。", + "requirement": "功能清单 G「礼包商店」「市场」与 A「不连 Gaijin」。玩家在游戏内点击「在交易所中查找」或顶栏「交易所」时,必须在内置浏览器里直接打开本地交易所页面,且浏览器不访问 login.gaijin.net。", + "cause": "yu_sessionProc.cpp:951 的 SsoLoggedUrlAction 硬编码拼接 https://login.gaijin.net/sso/LoginByStoken(YuSession::setOptionStringSync 无覆盖该域名的选项),再交给内置浏览器打开;内置浏览器 cefprocess.exe 是独立进程,不加载游戏的 wto_ws.dll,会直接连向真实 Gaijin 登录服务器。", "lighter_options_ruled_out": [ "在 network.blk 去掉 marketplaceURL 的 auto_login:auto_login 不在 network.blk 配置值里,而是由 scripts/inventory/inventoryClient.nut 的 getMarketplaceBaseUrl() 在脚本里前置拼接。", - "让本地登录服务的 get_short_token 返回错误以触发回退分支:url.nut 为配合 SSO 参数对 notAuthUrl 做了 Base64 编码,SsoLoggedUrlAction 失败回调会把这段 Base64 字符串原样传给 shell_launch(),Windows 无法作为 URL 打开。" + "让本地登录服务的 get_short_token 返回错误以触发回退分支:url.nut 为配合 SSO 参数对 notAuthUrl 做了 Base64 编码,SsoLoggedUrlAction 失败回调会把这段 Base64 字符串原样当作地址打开,打不开。" ], "conclusion": "在 gui.vromfs.bin 的 scripts/onlineshop/url.nut 单点为 shouldLogin 增加本地服务地址排除条件(仅对包含 ://<本地地址>:<端口> 的链接跳过 auto_login)。", - "if_not_applied": "在机库点击交易所或市场载具「在交易所中查找」时,系统浏览器会跳转到真实 https://login.gaijin.net/sso/LoginByStoken,无法打开本地交易所且产生外网请求。" + "if_not_applied": "在机库点击交易所或市场载具「在交易所中查找」时,内置浏览器会跳转到真实 https://login.gaijin.net/sso/LoginByStoken,无法打开本地交易所且产生外网请求。" }, "features": ["A-不连 Gaijin", "G-礼包商店", "G-市场"], diff --git a/packages/build/src/network/redirect-network-config.ts b/packages/build/src/network/redirect-network-config.ts index 06ce31a..e82311d 100644 --- a/packages/build/src/network/redirect-network-config.ts +++ b/packages/build/src/network/redirect-network-config.ts @@ -27,8 +27,10 @@ export function redirectNetworkConfig(root: BlkBlock, endpoint: LocalEndpoint): function configureEnvironment(environment: BlkBlock, endpoint: LocalEndpoint): void { setParam(environment, 'enableSslCertCheck', { type: 'bool', value: false }); - // Open the local web store directly without SSO redirection to login.gaijin.net. - setParam(environment, 'webstoreURL', { type: 'string', value: `http://${endpoint.host}:${endpoint.port}/store` }); + // The local store page. The stock value carries URL tags; here only + // auto_local, so scripts/onlineShop/url.nut adds ?skin_lang= and opens it in + // the built-in browser. No auto_login: that goes through Gaijin's login.gaijin.net. + setParam(environment, 'webstoreURL', { type: 'string', value: `auto_local http://${endpoint.host}:${endpoint.port}/store` }); const login = ensureBlock(environment, 'yuplay'); for (const [key, value] of loginOverrides(endpoint)) setParam(login, key, { type: 'string', value }); } diff --git a/packages/local-service/src/char/actions/clan-actions.ts b/packages/local-service/src/char/actions/clan-actions.ts index defefa9..d801a31 100644 --- a/packages/local-service/src/char/actions/clan-actions.ts +++ b/packages/local-service/src/char/actions/clan-actions.ts @@ -62,7 +62,7 @@ export function clanGetAction(accounts: AccountStore, clans: ClanStore): CharAct ? clans.clanOfUser(account.userId)?.clan : clans.findClan({ clanId, clanName, clanTag }); if (!clan) return { kind: 'error', code: 'CLAN_NOT_FOUND' }; - return { kind: 'data', blk: toClanInfoBlk(clan) }; + return { kind: 'data', blk: toClanInfoBlk(clan, clans.tuning) }; }); } @@ -77,7 +77,7 @@ export function clanGetLeaderboardAction(clans: ClanStore): CharActionHandler { filterNotFull: headerOrPayloadBool(context, 'filterNotFull') ?? false, filterAutoAccept: headerOrPayloadBool(context, 'filterAutoAccept') ?? false, }); - return { kind: 'data', blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos)) } }; + return { kind: 'data', blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos, clans.tuning)) } }; }; } @@ -93,7 +93,7 @@ export function clanFindByPrefixAction(clans: ClanStore): CharActionHandler { filterNotFull: headerOrPayloadBool(context, 'filterNotFull') ?? false, filterAutoAccept: headerOrPayloadBool(context, 'filterAutoAccept') ?? false, }); - return { kind: 'data', blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos)) } }; + return { kind: 'data', blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos, clans.tuning)) } }; }; } @@ -105,7 +105,7 @@ export function clansListShortInfoAction(clans: ClanStore): CharActionHandler { .map((p) => (p.value as { type: 'string'; value: string }).value); const blocks = requestedIds.flatMap((id) => { const clan = clans.byId(id); - return clan ? [toClanShortInfoBlk(clan)] : []; + return clan ? [toClanShortInfoBlk(clan, clans.tuning)] : []; }); return { kind: 'data', blk: { name: '', params: [], blocks } }; }; diff --git a/packages/local-service/src/clans/clan-blk.ts b/packages/local-service/src/clans/clan-blk.ts index 4bc6102..aa78a01 100644 --- a/packages/local-service/src/clans/clan-blk.ts +++ b/packages/local-service/src/clans/clan-blk.ts @@ -7,11 +7,8 @@ * - `cln_clan_get_log` paginated clan event log (`clanRequests.nut`) */ import type { BlkBlock, BlkParam } from '@wto/blk'; +import type { ClanTuning } from './clan-tuning.ts'; import { - HISTORY_DEPTH_DAYS, - MAX_ACTIVITY_PER_PERIOD, - MAX_CLAN_ACTIVITY, - REWARD_PERIOD_DAYS, totalPeriodActivityOf, type ClanLogEntry, type ClanMemberRecord, @@ -31,8 +28,9 @@ const OPTIONAL_LOG_STRING_KEYS: ReadonlyArray s + p.activity, 0), earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0), - ratingArc: 1500, - ratingHist: 1500, - ratingSim: 1500, + ratingArc: tuning.playerRating.founder.arc, + ratingHist: tuning.playerRating.founder.hist, + ratingSim: tuning.playerRating.founder.sim, periods, }; const desc = input.type === 'normal' ? input.desc : ''; @@ -272,7 +273,7 @@ function buildCreatedClanRecord( id, name, tag, lastPaidTag: tag, type: input.type, slogan: input.slogan, desc, announcement: input.announcement, region: input.region, status: 'open', autoaccept: true, - mlimit: input.type === 'battalion' ? BATTALION_INITIAL_MEMBER_LIMIT : NORMAL_CLAN_MEMBER_LIMIT, + mlimit: input.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal, mspent: 0, cdateSec: nowSec, changedByUid: account.userId, changedByNick: account.nick, changedTimeSec: nowSec, regionLastUpdatedSec: input.region ? nowSec : 0, diff --git a/packages/local-service/src/clans/clan-membership.ts b/packages/local-service/src/clans/clan-membership.ts index ff8a1fd..011563f 100644 --- a/packages/local-service/src/clans/clan-membership.ts +++ b/packages/local-service/src/clans/clan-membership.ts @@ -2,13 +2,13 @@ * Squadron membership, candidate moderation, role changes, blacklist, and event-log helpers *. */ +import type { ClanTuning } from './clan-tuning.ts'; import type { Account } from '../accounts/account-store.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; import { buildDefaultPeriods } from './clan-seeds.ts'; import { ClanRole, isAssignableClanRole, - MAX_ACTIVITY_PER_PERIOD, roleNameOf, type ClanLogEntry, type ClanRecord, @@ -51,20 +51,21 @@ export function addMemberToClan( initiatorUid: string, initiatorNick: string, nowSec: number, + tuning: ClanTuning, ): void { if (clan.members.some((m) => m.uid === uid)) return; - const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), MAX_ACTIVITY_PER_PERIOD); + const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), tuning); clan.members.push({ uid, nick, role, joinDateSec: nowSec, - curActivity: MAX_ACTIVITY_PER_PERIOD, + curActivity: tuning.activity.maxPerPeriod, totalActivity: periods.reduce((s, p) => s + p.activity, 0), earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0), - ratingArc: 1450, - ratingHist: 1500, - ratingSim: 1400, + ratingArc: tuning.playerRating.joiner.arc, + ratingHist: tuning.playerRating.joiner.hist, + ratingSim: tuning.playerRating.joiner.sim, periods, }); appendClanLog(clan, { @@ -85,6 +86,7 @@ export function requestOrCancelMembershipInState( account: Account, query: MembershipRequestQuery, nowSec: number, + tuning: ClanTuning, ): { readonly outcome: RuleOutcome; readonly mutated: boolean } { if (query.cancel || (!query.clanId && !query.clanName && !query.clanTag) || query.clanId === '-1') { clearCandidateEverywhere(clans, account.userId); @@ -100,7 +102,7 @@ export function requestOrCancelMembershipInState( clearCandidateEverywhere(clans, account.userId); if (targetClan.autoaccept) { - addMemberToClan(targetClan, account.userId, account.nick, ClanRole.REGULAR, account.userId, account.nick, nowSec); + addMemberToClan(targetClan, account.userId, account.nick, ClanRole.REGULAR, account.userId, account.nick, nowSec, tuning); } else { targetClan.candidates.push({ uid: account.userId, @@ -145,6 +147,7 @@ export function acceptCandidateOnClan( targetNick: string, role: number, nowSec: number, + tuning: ClanTuning, ): boolean { if (!clan || !hasClanOfficerRight(clan, initiator.userId) || clan.members.length >= clan.mlimit) return false; const cand = clan.candidates.find((c) => c.uid === targetUid); @@ -152,7 +155,7 @@ export function acceptCandidateOnClan( if (allClans.some((c) => c.members.some((m) => m.uid === targetUid))) return false; const assignedRole = isAssignableClanRole(clan.type, role) ? role : ClanRole.REGULAR; clearCandidateEverywhere(allClans, targetUid); - addMemberToClan(clan, targetUid, cand.nick || targetNick, assignedRole, initiator.userId, initiator.nick, nowSec); + addMemberToClan(clan, targetUid, cand.nick || targetNick, assignedRole, initiator.userId, initiator.nick, nowSec, tuning); return true; } diff --git a/packages/local-service/src/clans/clan-queries.ts b/packages/local-service/src/clans/clan-queries.ts index f6f14ad..e7325e4 100644 --- a/packages/local-service/src/clans/clan-queries.ts +++ b/packages/local-service/src/clans/clan-queries.ts @@ -2,6 +2,7 @@ * Read-only search and leaderboard queries over the local squadron directory *. */ +import type { ClanTuning } from './clan-tuning.ts'; import { stripClanDecorators } from './clan-lifecycle.ts'; import { totalPeriodActivityOf, type ClanRecord } from './clan-types.ts'; @@ -40,8 +41,9 @@ export function findClanInList( export function queryClanLeaderboard( clans: readonly ClanRecord[], query: LeaderboardQuery, + tuning: ClanTuning, ): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> { - const sorted = [...clans].sort((a, b) => metricOf(b, query.sortField) - metricOf(a, query.sortField)); + const sorted = [...clans].sort((a, b) => metricOf(b, query.sortField, tuning) - metricOf(a, query.sortField, tuning)); const withPos = sorted.map((clan, index) => ({ clan, pos: index })); if (query.clanId && query.clanId !== '-1') return withPos.filter((entry) => entry.clan.id === query.clanId); @@ -63,11 +65,11 @@ export function queryClanLeaderboard( return filtered.slice(start, start + count); } -function metricOf(clan: ClanRecord, sortField: string): number { +function metricOf(clan: ClanRecord, sortField: string, tuning: ClanTuning): number { switch (sortField) { case 'activity': case 'clan_activity_by_periods': - return totalPeriodActivityOf(clan); + return totalPeriodActivityOf(clan, tuning); case 'members_cnt': return clan.members.length; case 'dr_era5_arc': diff --git a/packages/local-service/src/clans/clan-seeds.ts b/packages/local-service/src/clans/clan-seeds.ts index 6cdd521..32609d9 100644 --- a/packages/local-service/src/clans/clan-seeds.ts +++ b/packages/local-service/src/clans/clan-seeds.ts @@ -1,175 +1,29 @@ /** - * Default offline squadron directory seeded on first creation of `/clans.json` - * (implementation notes section I; implementation notes). + * The preset squadron directory written on first creation of `/clans.json` + * (implementation notes section I; implementation notes), and the activity periods a member + * starts with. Both are tuning (tuning/clans.jsonc). */ -import { - BATTALION_INITIAL_MEMBER_LIMIT, - ClanRole, - MAX_ACTIVITY_PER_PERIOD, - MAX_CLAN_ACTIVITY, - NORMAL_CLAN_MEMBER_LIMIT, - REWARD_PERIOD_DAYS, - type ClanActivityPeriodEntry, - type ClanMemberRecord, - type ClanRecord, -} from './clan-types.ts'; +import type { ClanTuning, PresetClan, PresetMember } from './clan-tuning.ts'; +import type { ClanActivityPeriodEntry, ClanMemberRecord, ClanRecord } from './clan-types.ts'; -interface NpcSpec { - readonly uid: string; - readonly nick: string; - readonly role: number; - readonly title: string; - readonly icon: string; - readonly unit: string; - readonly activity: number; +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)); } -interface SeedSpec { - readonly id: string; - readonly tag: string; - readonly name: string; - readonly type: 'normal' | 'battalion'; - readonly slogan: string; - readonly desc: string; - readonly announcement: string; - readonly region: string; - readonly autoaccept: boolean; - readonly mlimit: number; - readonly dayOffset: number; - readonly eloArc: number; - readonly eloHist: number; - readonly eloSim: number; - readonly npcs: readonly NpcSpec[]; +/** 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; + const exp = Math.round((periodActivity / maxPerPeriod) * squadronRpPerFullPeriod); + return Array.from({ length: startingPeriods }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp })); } -const SEED_SPECS: readonly SeedSpec[] = [ - { - id: '500001', - tag: '[WTOF]', - name: 'War Thunder Offline Guard', - type: 'normal', - slogan: '离线天空与钢铁防线 · 自由研发全部联队载具', - desc: 'War Thunder Offline 官方预置主力联队。开启自动审批,加入即可获得完整联队活跃度与联队研发点支持。', - announcement: '欢迎加入 [WTOF]!可在联队页面右上角点击「联队载具」或「活跃度」查看研发进度。', - region: 'CN / Global', - autoaccept: true, - mlimit: NORMAL_CLAN_MEMBER_LIMIT, - dayOffset: 0, - eloArc: 1840, - eloHist: 2150, - eloSim: 1620, - npcs: [ - { uid: '900001001', nick: 'Lin_Wei', role: ClanRole.LEADER, title: 'title_marshall', icon: 'cardicon_28', unit: 'cn_ztz_99a', activity: MAX_ACTIVITY_PER_PERIOD }, - { uid: '900001002', nick: 'Elena_Valkyrie', role: ClanRole.DEPUTY, title: 'title_ace', icon: 'cardicon_fem_01', unit: 'su_27sm', activity: MAX_ACTIVITY_PER_PERIOD }, - { uid: '900001003', nick: 'iron_tiger_88', role: ClanRole.OFFICER, title: 'title_tank_destroyer', icon: 'cardicon_14', unit: 'germ_leopard_2a7v', activity: MAX_ACTIVITY_PER_PERIOD }, - { uid: '900001004', nick: 'Tomcat_Actual', role: ClanRole.OFFICER, title: 'title_jet_powered', icon: 'cardicon_07', unit: 'f_14b', activity: 345 }, - { uid: '900001005', nick: 'Kuroshio_DD', role: ClanRole.SERGEANT, title: 'title_sea_wolf', icon: 'cardicon_19', unit: 'jp_destroyer_shimakaze', activity: 330 }, - { uid: '900001006', nick: 'Northern_Fox', role: ClanRole.REGULAR, title: 'title_sniper', icon: 'cardicon_11', unit: 'sw_strv_122b_plus', activity: 310 }, - ], - }, - { - id: '500002', - tag: '=PLAF=', - name: 'Red Falcon Aviation Wing', - type: 'normal', - slogan: '鹰击长空 · 现代喷气空战与陆空协同联队', - desc: '专注于高阶喷气机与现代主战坦克联合作战的离线联队,支持自动入队与高活跃度加成。', - announcement: '本期联队研发推荐:F-16A OCU、苏-33、豹 2PL、M1A1 AIM。', - region: 'Asia', - autoaccept: true, - mlimit: NORMAL_CLAN_MEMBER_LIMIT, - dayOffset: 12, - eloArc: 1690, - eloHist: 2040, - eloSim: 1780, - npcs: [ - { uid: '900002001', nick: 'SkyDragon_J20', role: ClanRole.LEADER, title: 'title_ace', icon: 'cardicon_25', unit: 'j_11a', activity: MAX_ACTIVITY_PER_PERIOD }, - { uid: '900002002', nick: 'Thunderbolt_CN', role: ClanRole.DEPUTY, title: 'title_pilot', icon: 'cardicon_09', unit: 'jh_7a', activity: MAX_ACTIVITY_PER_PERIOD }, - { uid: '900002003', nick: 'SteelWall_99', role: ClanRole.OFFICER, title: 'title_unstoppable', icon: 'cardicon_16', unit: 'cn_vt_4a1', activity: 350 }, - { uid: '900002004', nick: 'NightHawk_04', role: ClanRole.REGULAR, title: 'title_eagle', icon: 'cardicon_05', unit: 'f_15j_kai', activity: 300 }, - ], - }, - { - id: '500003', - tag: '-1STG-', - name: '1st Armored Guards Division', - type: 'normal', - slogan: 'Steel & Fire — Heavy Armor Historical Squadron', - desc: 'Classic and modern armored warfare squadron. Open auto-accept recruitment for all tank commanders.', - announcement: 'Squadron vehicles ready for research at full 20,000 RP per period.', - region: 'EU / Global', - autoaccept: true, - mlimit: NORMAL_CLAN_MEMBER_LIMIT, - dayOffset: 24, - eloArc: 1920, - eloHist: 1980, - eloSim: 1510, - npcs: [ - { uid: '900003001', nick: 'Kommissar_KVs', role: ClanRole.LEADER, title: 'title_hero', icon: 'cardicon_22', unit: 'ussr_t_90m', activity: MAX_ACTIVITY_PER_PERIOD }, - { uid: '900003002', nick: 'PanzerMeyer_IV', role: ClanRole.OFFICER, title: 'title_tankman', icon: 'cardicon_12', unit: 'germ_pzkpfw_VI_ausf_h1_tiger', activity: 340 }, - { uid: '900003003', nick: 'DesertRat_UK', role: ClanRole.REGULAR, title: 'title_conqueror', icon: 'cardicon_18', unit: 'uk_challenger_2_black_night', activity: 290 }, - ], - }, - { - id: '500004', - tag: '^82AB^', - name: '82nd Combined Task Force', - type: 'normal', - slogan: 'All The Way — Air, Ground & Naval Task Force', - desc: '需要审批模式的示例联队(用于测试发送与撤回入队申请流程)。若想立即加入联队,请选择 [WTOF]、=PLAF= 或 -1STG-。', - announcement: 'Manual application review enabled for testing request/cancel workflow.', - region: 'NA', - autoaccept: false, - mlimit: NORMAL_CLAN_MEMBER_LIMIT, - dayOffset: 35, - eloArc: 1550, - eloHist: 1760, - eloSim: 1490, - npcs: [ - { uid: '900004001', nick: 'Major_Winters', role: ClanRole.LEADER, title: 'title_brother_in_arms', icon: 'cardicon_03', unit: 'us_m1a2_sep2_abrams', activity: MAX_ACTIVITY_PER_PERIOD }, - { uid: '900004002', nick: 'Mustang_Lead', role: ClanRole.OFFICER, title: 'title_ace', icon: 'cardicon_08', unit: 'p-51d-30_usaaf_korea', activity: 315 }, - ], - }, - { - id: '500005', - tag: '**RCON**', - name: 'Reconnaissance Battalion Alpha', - type: 'battalion', - slogan: '轻量级战术分队 · 侦察与快速反应', - desc: '战斗群(Battalion)类型预置联队,开启自动加入,支持体验战斗群架构与联队扩编。', - announcement: '轻装侦察分队常驻开放。', - region: 'Global', - autoaccept: true, - mlimit: BATTALION_INITIAL_MEMBER_LIMIT, - dayOffset: 48, - eloArc: 1410, - eloHist: 1610, - eloSim: 1320, - npcs: [ - { uid: '900005001', nick: 'Ghost_Scout', role: ClanRole.LEADER, title: 'title_scout', icon: 'cardicon_15', unit: 'us_hstvl', activity: MAX_ACTIVITY_PER_PERIOD }, - { uid: '900005002', nick: 'Lynx_Spotter', role: ClanRole.REGULAR, title: 'title_sniper', icon: 'cardicon_20', unit: 'it_centauro_rgo_120', activity: 280 }, - ], - }, -]; - -export function createDefaultClans(nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] { - const todayDay = Math.floor(nowSec / 86400); - const createdBase = nowSec - 180 * 86400; - return SEED_SPECS.map((spec) => buildSeededClan(spec, createdBase + spec.dayOffset * 86400, todayDay)); -} - -export function buildDefaultPeriods(todayDay: number, periodActivity = MAX_ACTIVITY_PER_PERIOD): ClanActivityPeriodEntry[] { - const expPerPeriod = Math.round((periodActivity / MAX_ACTIVITY_PER_PERIOD) * MAX_CLAN_ACTIVITY); - return [0, 1, 2].map((idx) => ({ - day: todayDay - idx * REWARD_PERIOD_DAYS, - activity: periodActivity, - exp: expPerPeriod, - })); -} - -function buildSeededClan(spec: SeedSpec, cdateSec: number, todayDay: number): ClanRecord { - const members = spec.npcs.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay)); - const leader = spec.npcs[0]!; +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)); + const leader = spec.members[0]!; return { id: spec.id, name: spec.name, @@ -181,21 +35,15 @@ function buildSeededClan(spec: SeedSpec, cdateSec: number, todayDay: number): Cl announcement: spec.announcement, region: spec.region, status: 'open', - autoaccept: spec.autoaccept, - mlimit: spec.mlimit, + autoaccept: spec.autoAccept, + mlimit: spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal, mspent: 0, cdateSec, changedByUid: leader.uid, changedByNick: leader.nick, changedTimeSec: cdateSec, regionLastUpdatedSec: 0, - stats: { - dr_era5_arc: spec.eloArc, dr_era5_hist: spec.eloHist, dr_era5_sim: spec.eloSim, - akills_arc: 4280, akills_hist: 6150, akills_sim: 1420, - gkills_arc: 7890, gkills_hist: 11240, gkills_sim: 2680, - deaths_arc: 5120, deaths_hist: 6890, deaths_sim: 1950, - ftime_arc: 18400, ftime_hist: 32600, ftime_sim: 8900, - }, + stats: { dr_era5_arc: spec.rating.arc, dr_era5_hist: spec.rating.hist, dr_era5_sim: spec.rating.sim, ...tuning.presetClans.stats }, members, candidates: [], blacklist: [], @@ -208,13 +56,14 @@ function buildSeededClan(spec: SeedSpec, cdateSec: number, todayDay: number): Cl }; } -function buildSeededMember(spec: SeedSpec, npc: NpcSpec, idx: number, cdateSec: number, todayDay: number): ClanMemberRecord { - const periods = buildDefaultPeriods(todayDay, npc.activity); +function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanMemberRecord { + const periods = buildDefaultPeriods(todayDay, tuning, npc.activity); + const { step, floor } = tuning.presetClans.memberRating; return { uid: npc.uid, nick: npc.nick, role: npc.role, - joinDateSec: cdateSec + idx * 3600, + joinDateSec: cdateSec + idx * tuning.presetClans.memberJoinSpacingMinutes * 60, isNpc: true, npcTitle: npc.title, npcPilotIcon: npc.icon, @@ -223,9 +72,9 @@ function buildSeededMember(spec: SeedSpec, npc: NpcSpec, idx: number, cdateSec: curActivity: npc.activity, totalActivity: periods.reduce((sum, p) => sum + p.activity, 0), earnedSquadronExp: periods.reduce((sum, p) => sum + p.exp, 0), - ratingArc: Math.max(800, spec.eloArc - idx * 45), - ratingHist: Math.max(850, spec.eloHist - idx * 50), - ratingSim: Math.max(700, spec.eloSim - idx * 40), + ratingArc: Math.max(floor.arc, spec.rating.arc - idx * step.arc), + ratingHist: Math.max(floor.hist, spec.rating.hist - idx * step.hist), + ratingSim: Math.max(floor.sim, spec.rating.sim - idx * step.sim), periods, }; } diff --git a/packages/local-service/src/clans/clan-store.ts b/packages/local-service/src/clans/clan-store.ts index 3fec216..b6ce635 100644 --- a/packages/local-service/src/clans/clan-store.ts +++ b/packages/local-service/src/clans/clan-store.ts @@ -40,16 +40,20 @@ import { } from './clan-membership.ts'; import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts'; import { createDefaultClans } from './clan-seeds.ts'; +import type { ClanTuning } from './clan-tuning.ts'; import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts'; export type { LeaderboardQuery }; export class ClanStore { readonly #filePath: string; + /** tuning/clans.jsonc; the clan actions serialize clan info with it too. */ + readonly tuning: ClanTuning; #state: StoredClansState; - constructor(dataFolder: string) { + constructor(dataFolder: string, tuning: ClanTuning) { this.#filePath = join(dataFolder, 'clans.json'); + this.tuning = tuning; this.#state = this.#loadOrSeed(); } @@ -58,7 +62,7 @@ export class ClanStore { const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState; if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') return parsed; } - const seeded: StoredClansState = { nextClanId: 600001, clans: createDefaultClans() }; + const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning) }; this.#save(seeded); return seeded; } @@ -128,11 +132,11 @@ export class ClanStore { } queryLeaderboard(query: LeaderboardQuery): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> { - return queryClanLeaderboard(this.#state.clans, query); + return queryClanLeaderboard(this.#state.clans, query, this.tuning); } createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome { - const outcome = createClanInState(this.#state, profile, account, economy, input, nowSec); + const outcome = createClanInState(this.#state, profile, account, economy, this.tuning, input, nowSec); if (outcome.ok) { this.#save(); this.syncProfile(profile, account); @@ -157,7 +161,7 @@ export class ClanStore { input: { readonly tag: string; readonly desc: string; readonly announcement: string }, nowSec = nowSeconds(), ): RuleOutcome { - const outcome = upgradeClanToNormalInState(this.#state.clans, this.#resolveClan(clanId, account.userId), profile, account, economy, input, nowSec); + const outcome = upgradeClanToNormalInState(this.#state.clans, this.#resolveClan(clanId, account.userId), profile, account, economy, this.tuning, input, nowSec); if (outcome.ok) { this.#save(); this.syncProfile(profile, account); @@ -185,7 +189,7 @@ 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); + const res = requestOrCancelMembershipInState(this.#state.clans, this.findClan(query), Boolean(this.clanOfUser(account.userId)), account, query, nowSec, this.tuning); if (res.mutated) { this.#save(); this.syncProfile(profile, account); @@ -213,7 +217,7 @@ export class ClanStore { } acceptCandidate(initiator: Account, clanId: string | undefined, targetUid: string, targetNick: string, role: number, nowSec = nowSeconds()): boolean { - if (!acceptCandidateOnClan(this.#state.clans, this.#resolveClan(clanId, initiator.userId), initiator, targetUid, targetNick, role, nowSec)) return false; + if (!acceptCandidateOnClan(this.#state.clans, this.#resolveClan(clanId, initiator.userId), initiator, targetUid, targetNick, role, nowSec, this.tuning)) return false; this.#save(); return true; } diff --git a/packages/local-service/src/clans/clan-tuning.ts b/packages/local-service/src/clans/clan-tuning.ts new file mode 100644 index 0000000..8a2e063 --- /dev/null +++ b/packages/local-service/src/clans/clan-tuning.ts @@ -0,0 +1,132 @@ +/** Typed content of tuning/clans.jsonc. */ +import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts'; +import { roleCodeFromString, type ClanStats } from './clan-types.ts'; + +/** The clan statistics a preset clan starts with; the per-mode ratings (dr_era5_*) come from each clan's rating. */ +export type PresetClanStats = Omit; + +const STAT_KEYS: readonly (keyof PresetClanStats)[] = [ + 'akills_arc', 'akills_hist', 'akills_sim', 'gkills_arc', 'gkills_hist', 'gkills_sim', + 'deaths_arc', 'deaths_hist', 'deaths_sim', 'ftime_arc', 'ftime_hist', 'ftime_sim', +]; + +export interface ModeTriple { + readonly arc: number; + readonly hist: number; + readonly sim: number; +} + +export interface PresetMember { + readonly uid: string; + readonly nick: string; + readonly role: number; + readonly title: string; + readonly icon: string; + readonly unit: string; + readonly activity: number; +} + +export interface PresetClan { + readonly id: string; + readonly tag: string; + readonly name: string; + readonly type: 'normal' | 'battalion'; + readonly slogan: string; + readonly desc: string; + readonly announcement: string; + readonly region: string; + readonly autoAccept: boolean; + readonly createdAfterDays: number; + readonly rating: ModeTriple; + readonly members: readonly PresetMember[]; +} + +export interface ClanTuning { + readonly activity: { + readonly maxPerPeriod: number; + readonly squadronRpPerFullPeriod: number; + readonly rewardPeriodDays: number; + readonly historyDepthDays: number; + readonly startingPeriods: number; + }; + readonly memberLimits: { readonly normal: number; readonly battalionInitial: number }; + readonly leaderboard: { readonly activityMultiplier: number; readonly maxActivity: number }; + readonly firstNewClanId: number; + readonly playerRating: { readonly founder: ModeTriple; readonly joiner: ModeTriple }; + readonly presetClans: { + readonly createdDaysAgo: number; + readonly memberJoinSpacingMinutes: number; + readonly stats: PresetClanStats; + readonly memberRating: { readonly step: ModeTriple; readonly floor: ModeTriple }; + readonly clans: readonly PresetClan[]; + }; +} + +export function readClanTuning(file: TuningReader): ClanTuning { + const activity = file.object('activity'); + const limits = file.object('memberLimits'); + const leaderboard = file.object('leaderboard'); + const preset = file.object('presetClans'); + const stats = preset.object('stats'); + const rating = preset.object('memberRating'); + return { + activity: { + maxPerPeriod: activity.int('maxPerPeriod', { min: 1 }), + squadronRpPerFullPeriod: activity.int('squadronRpPerFullPeriod', { min: 0 }), + rewardPeriodDays: activity.int('rewardPeriodDays', { min: 1 }), + historyDepthDays: activity.int('historyDepthDays', { min: 1 }), + startingPeriods: activity.int('startingPeriods', { min: 0 }), + }, + memberLimits: { normal: limits.int('normal', { min: 1 }), battalionInitial: limits.int('battalionInitial', { min: 1 }) }, + leaderboard: { activityMultiplier: leaderboard.number('activityMultiplier', { min: 0 }), maxActivity: leaderboard.int('maxActivity', { min: 0 }) }, + firstNewClanId: file.int('firstNewClanId', { min: 1 }), + playerRating: { founder: triple(file.object('playerRating').object('founder')), joiner: triple(file.object('playerRating').object('joiner')) }, + presetClans: { + createdDaysAgo: preset.int('createdDaysAgo', { min: 0 }), + memberJoinSpacingMinutes: preset.int('memberJoinSpacingMinutes', { min: 0 }), + 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), + }, + }; +} + +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)`); + return { + id: entry.string('id'), + tag: entry.string('tag'), + name: entry.string('name'), + type, + slogan: entry.string('slogan'), + desc: entry.string('desc'), + announcement: entry.string('announcement'), + region: entry.string('region'), + autoAccept: entry.bool('autoAccept'), + createdAfterDays: entry.int('createdAfterDays', { min: 0 }), + rating: triple(entry.object('rating')), + members, + }; +} + +function readPresetMember(member: TuningReader): PresetMember { + const roleName = member.string('role'); + const role = roleCodeFromString(roleName); + if (role === undefined) throw new TuningError(`tuning file clans.jsonc: unknown member role "${roleName}"`); + return { + uid: member.string('uid'), + nick: member.string('nick'), + role, + title: member.string('title'), + icon: member.string('icon'), + unit: member.string('unit'), + activity: member.int('activity', { min: 0 }), + }; +} + +function triple(entry: TuningReader): ModeTriple { + return { arc: entry.int('arc'), hist: entry.int('hist'), sim: entry.int('sim') }; +} diff --git a/packages/local-service/src/clans/clan-types.ts b/packages/local-service/src/clans/clan-types.ts index aa66ceb..1800d6d 100644 --- a/packages/local-service/src/clans/clan-types.ts +++ b/packages/local-service/src/clans/clan-types.ts @@ -2,16 +2,10 @@ * Types, binary enum constants, and shared squadron domain constants *. */ +import type { ClanTuning } from './clan-tuning.ts'; import type { BlkBlock } from '@wto/blk'; import type { ClanKind } from '../profile/profile-clan.ts'; -export const MAX_ACTIVITY_PER_PERIOD = 360; -export const MAX_CLAN_ACTIVITY = 20_000; -export const REWARD_PERIOD_DAYS = 3; -export const HISTORY_DEPTH_DAYS = 14; -export const NORMAL_CLAN_MEMBER_LIMIT = 128; -export const BATTALION_INITIAL_MEMBER_LIMIT = 10; - /** Exact `ECMR_*` role codes registered at aces.exe 0x2986a0..0x298802 (table 0x7ba87e8). */ export const ClanRole = { LEADER: 1, @@ -67,9 +61,10 @@ export function isAssignableClanRole(clanType: ClanKind, role: number): boolean || role === ClanRole.REGULAR; } -export function totalPeriodActivityOf(clan: ClanRecord): number { +/** The period activity shown on the leaderboard (tuning/clans.jsonc leaderboard). */ +export function totalPeriodActivityOf(clan: ClanRecord, tuning: ClanTuning): number { const sum = clan.members.reduce((acc, m) => acc + m.curActivity, 0); - return Math.min(MAX_CLAN_ACTIVITY * 5, sum * 10); + return Math.min(tuning.leaderboard.maxActivity, Math.round(sum * tuning.leaderboard.activityMultiplier)); } export interface ClanStats { diff --git a/packages/local-service/src/game-data/datasets/clan-economy.ts b/packages/local-service/src/game-data/datasets/clan-economy.ts index 29b48d7..3438774 100644 --- a/packages/local-service/src/game-data/datasets/clan-economy.ts +++ b/packages/local-service/src/game-data/datasets/clan-economy.ts @@ -33,37 +33,43 @@ export interface ClanEconomy { export const clanEconomy: Dataset = { id: 'clan-economy', - version: 2, + version: 3, extract: (source) => { const wp = source.readBlk('char.vromfs.bin', WARPOINTS); + const required = (key: string): number => { + const value = numberField(wp, key); + if (value === undefined) throw new Error(`${WARPOINTS} has no ${key}; this game build differs from the verified ones`); + return value; + }; + // scripts/clans/clanType.nut reads these costs as `blk?[name] ?? 0`; 2.61.0.37 has no + // clanCreateWPCost, costWPPrimaryInfo or costWPSecondaryInfo, so they are 0 there too. + const clientDefaultZero = (key: string): number => numberField(wp, key) ?? 0; return { - normalCreateGold: numberField(wp, 'clanCreateGoldCost') ?? 2500, - normalCreateSilver: numberField(wp, 'clanCreateWPCost') ?? 0, - normalPrimaryEditGold: numberField(wp, 'costGoldPrimaryInfo') ?? 2500, - normalPrimaryEditSilver: numberField(wp, 'costWPPrimaryInfo') ?? 0, - normalSecondaryEditGold: numberField(wp, 'costGoldSecondaryInfo') ?? 0, - normalSecondaryEditSilver: numberField(wp, 'costWPSecondaryInfo') ?? 0, - battalionCreateGold: numberField(wp, 'battalionCreateGoldCost') ?? 0, - battalionCreateSilver: numberField(wp, 'battalionCreateWPCost') ?? 1_000_000, - battalionPrimaryEditGold: numberField(wp, 'battalionCostGoldPrimaryInfo') ?? 0, - battalionPrimaryEditSilver: numberField(wp, 'battalionCostWPPrimaryInfo') ?? 1_000_000, - battalionSecondaryEditGold: numberField(wp, 'battalionCostGoldSecondaryInfo') ?? 0, - battalionSecondaryEditSilver: numberField(wp, 'battalionCostWPSecondaryInfo') ?? 0, - battalionMembersUpgradeGold: numberField(wp, 'battalionMembersUpgradeCost') ?? 225, - battalionMembersUpgradeStep: numberField(wp, 'battalionMembersUpgradeStep') ?? 10, - battalionMembersUpgradeLimit: numberField(wp, 'battalionMembersUpgradeLimit') ?? 110, - upgradeBattalionToNormalGold: numberField(wp, 'clanUpgradeCostGoldBattalionToNormal') ?? 2500, - upgradeBattalionToNormalSilver: numberField(wp, 'clanUpgradeCostWPBattalionToNormal') ?? 0, - normalFreeDecorators: readDecorList(findBlock(wp, 'clanTagDecorators'), ['--', '..', '==', '^^', '[]']), - battalionFreeDecorators: readDecorList(findBlock(wp, 'battalionTagDecorators'), ['**']), + normalCreateGold: required('clanCreateGoldCost'), + normalCreateSilver: clientDefaultZero('clanCreateWPCost'), + normalPrimaryEditGold: clientDefaultZero('costGoldPrimaryInfo'), + normalPrimaryEditSilver: clientDefaultZero('costWPPrimaryInfo'), + normalSecondaryEditGold: required('costGoldSecondaryInfo'), + normalSecondaryEditSilver: clientDefaultZero('costWPSecondaryInfo'), + battalionCreateGold: required('battalionCreateGoldCost'), + battalionCreateSilver: clientDefaultZero('battalionCreateWPCost'), + battalionPrimaryEditGold: clientDefaultZero('battalionCostGoldPrimaryInfo'), + battalionPrimaryEditSilver: required('battalionCostWPPrimaryInfo'), + battalionSecondaryEditGold: required('battalionCostGoldSecondaryInfo'), + battalionSecondaryEditSilver: required('battalionCostWPSecondaryInfo'), + battalionMembersUpgradeGold: required('battalionMembersUpgradeCost'), + battalionMembersUpgradeStep: required('battalionMembersUpgradeStep'), + battalionMembersUpgradeLimit: required('battalionMembersUpgradeLimit'), + upgradeBattalionToNormalGold: required('clanUpgradeCostGoldBattalionToNormal'), + upgradeBattalionToNormalSilver: clientDefaultZero('clanUpgradeCostWPBattalionToNormal'), + normalFreeDecorators: readDecorList(wp, 'clanTagDecorators'), + battalionFreeDecorators: readDecorList(wp, 'battalionTagDecorators'), }; }, }; -function readDecorList(block: BlkBlock | undefined, fallback: readonly string[]): readonly string[] { - if (!block) return fallback; - const values = block.params - .filter((p) => p.name === 'decor' && p.value.type === 'string') - .map((p) => (p.value as { type: 'string'; value: string }).value); - return values.length > 0 ? values : fallback; +function readDecorList(wp: BlkBlock, blockName: string): readonly string[] { + const block = findBlock(wp, blockName); + if (!block) throw new Error(`${WARPOINTS} has no ${blockName}; this game build differs from the verified ones`); + return block.params.flatMap((p) => (p.name === 'decor' && p.value.type === 'string' ? [p.value.value] : [])); } diff --git a/packages/local-service/src/game-data/datasets/shop-countries.ts b/packages/local-service/src/game-data/datasets/shop-countries.ts index db49b51..b865b78 100644 --- a/packages/local-service/src/game-data/datasets/shop-countries.ts +++ b/packages/local-service/src/game-data/datasets/shop-countries.ts @@ -6,11 +6,10 @@ * scripts/shop/shopCountriesList.nut, updateShopCountriesList). */ import type { Dataset } from './dataset.ts'; - -const SHOP = 'config/shop.blk'; +import { shopCountryNames } from './shop-tree.ts'; export const shopCountries: Dataset = { id: 'shop-countries', version: 1, - extract: (source) => source.readBlk('char.vromfs.bin', SHOP).blocks.map((block) => block.name), + extract: shopCountryNames, }; diff --git a/packages/local-service/src/game-data/datasets/shop-tree.ts b/packages/local-service/src/game-data/datasets/shop-tree.ts new file mode 100644 index 0000000..fc8d0d8 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/shop-tree.ts @@ -0,0 +1,27 @@ +/** + * Walk char.vromfs.bin config/shop.blk: one top-level block per country, below it branches, + * columns, groups and vehicles. Shared by the datasets that need the + * per-vehicle shop entries. + */ +import type { BlkBlock } from '@wto/blk'; +import type { DatasetSource } from './dataset.ts'; + +export const SHOP = 'config/shop.blk'; + +/** Every shop entry by name; the first entry wins when a name repeats. Non-vehicle entries are included and simply never looked up. */ +export function shopEntriesByName(source: DatasetSource): Map { + const entries = new Map(); + for (const country of source.readBlk('char.vromfs.bin', SHOP).blocks) { + for (const entry of entriesBelow(country)) if (!entries.has(entry.name)) entries.set(entry.name, entry); + } + return entries; +} + +/** The countries in tech-tree order (the top-level block names). */ +export function shopCountryNames(source: DatasetSource): string[] { + return source.readBlk('char.vromfs.bin', SHOP).blocks.map((block) => block.name); +} + +function entriesBelow(block: BlkBlock): BlkBlock[] { + return block.blocks.flatMap((child) => [child, ...entriesBelow(child)]); +} diff --git a/packages/local-service/src/game-data/datasets/ui-labels.ts b/packages/local-service/src/game-data/datasets/ui-labels.ts new file mode 100644 index 0000000..0792a7e --- /dev/null +++ b/packages/local-service/src/game-data/datasets/ui-labels.ts @@ -0,0 +1,25 @@ +/** + * Dataset: the game's own names for countries and vehicle types, from lang.vromfs.bin + * lang/menu.csv, for the local web pages: + * country_usa, country_germany, ... country names + * mainmenu/type_aircraft, mainmenu/type_tank, ... vehicle type names + */ +import type { Dataset } from './dataset.ts'; +import { parseLocalizedCsvMap, type LocalizedCsvText } from './lang-csv.ts'; + +const MENU_CSV = 'lang/menu.csv'; +const KEY_PREFIXES = ['country_', 'mainmenu/type_']; + +export type UiLabels = Readonly>; + +export const uiLabels: Dataset = { + id: 'ui-labels', + version: 1, + extract: (source) => { + const labels: Record = {}; + for (const [key, text] of parseLocalizedCsvMap(source.readText('lang.vromfs.bin', MENU_CSV))) { + if (KEY_PREFIXES.some((prefix) => key.startsWith(prefix))) labels[key] = text; + } + return labels; + }, +}; diff --git a/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts b/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts index 38ccc0c..4c44bdb 100644 --- a/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts +++ b/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts @@ -25,9 +25,9 @@ import type { BlkBlock } from '@wto/blk'; import { boolField, numberField, stringField } from './blk-fields.ts'; import type { Dataset } from './dataset.ts'; +import { shopEntriesByName } from './shop-tree.ts'; const VEHICLE_ECONOMY = 'config/wpcost.blk'; -const SHOP = 'config/shop.blk'; export interface CatalogueVehicle { readonly name: string; @@ -64,10 +64,7 @@ export const vehicleCatalogue: Dataset = { id: 'vehicle-catalogue', version: 4, extract: (source) => { - const shopEntries = new Map(); - for (const country of source.readBlk('char.vromfs.bin', SHOP).blocks) { - for (const entry of entriesBelow(country)) if (!shopEntries.has(entry.name)) shopEntries.set(entry.name, entry); - } + const shopEntries = shopEntriesByName(source); return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => catalogueVehicle(vehicle, shopEntries.get(vehicle.name))); }, }; @@ -99,8 +96,3 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined): C minOpenCostGold: numberField(vehicle, 'minOpenCostGold') ?? 0, }; } - -/** Every block below a country: branches, columns, groups and vehicles (non-vehicles have no wpcost entry and are never looked up). */ -function entriesBelow(block: BlkBlock): BlkBlock[] { - return block.blocks.flatMap((child) => [child, ...entriesBelow(child)]); -} diff --git a/packages/local-service/src/game-data/datasets/web-icons.ts b/packages/local-service/src/game-data/datasets/web-icons.ts new file mode 100644 index 0000000..b36a0a2 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/web-icons.ts @@ -0,0 +1,53 @@ +/** + * Dataset: the game's own SVG icons that the local web pages (store and marketplace, shown in + * the in-game browser; implementation notes) display, taken from the player's + * ui/atlases.vromfs.bin so nothing of Gaijin's is shipped with the service (local verification): + * gameuiskin/_ico.svg the tech-tree silhouette of a vehicle + * gameuiskin/.svg a country flag (country_usa, ...) + * + * All 3349 vehicle icons together are about 26 MB, so only the vehicles the stock game sells + * for real money are kept: gift vehicles (wpcost.blk gift:t, the store's packs) and + * marketplace vehicles (shop.blk marketplaceItemdefId). + */ +import { numberField, stringField } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; +import { shopCountryNames, shopEntriesByName } from './shop-tree.ts'; + +const ATLASES = 'ui/atlases.vromfs.bin'; +const VEHICLE_ECONOMY = 'config/wpcost.blk'; +const ICON_FOLDER = 'gameuiskin/'; + +export interface WebIcons { + /** Vehicle name -> SVG text. */ + readonly vehicles: Readonly>; + /** Country (country_usa, ...) -> SVG text. */ + readonly flags: Readonly>; +} + +export const webIcons: Dataset = { + id: 'web-icons', + version: 1, + extract: (source) => { + const available = new Set(source.listFiles(ATLASES)); + const readIcon = (name: string): string | undefined => { + const path = `${ICON_FOLDER}${name}.svg`; + return available.has(path) ? source.readText(ATLASES, path) : undefined; + }; + + const shopEntries = shopEntriesByName(source); + const vehicles: Record = {}; + for (const vehicle of source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks) { + const soldForMoney = stringField(vehicle, 'gift') !== undefined + || numberField(shopEntries.get(vehicle.name), 'marketplaceItemdefId') !== undefined; + const icon = soldForMoney ? readIcon(`${vehicle.name}_ico`) : undefined; + if (icon) vehicles[vehicle.name] = icon; + } + + const flags: Record = {}; + for (const country of shopCountryNames(source)) { + const flag = readIcon(country); + if (flag) flags[country] = flag; + } + return { vehicles, flags }; + }, +}; diff --git a/packages/local-service/src/game-data/game-files.ts b/packages/local-service/src/game-data/game-files.ts index 43dbb8e..a3963cc 100644 --- a/packages/local-service/src/game-data/game-files.ts +++ b/packages/local-service/src/game-data/game-files.ts @@ -7,7 +7,13 @@ import type { BlkBlock } from '@wto/blk'; import { GamePack } from './game-pack.ts'; /** The data packs the local service reads (file names in the game folder). */ -export type GamePackName = 'char.vromfs.bin' | 'mis.vromfs.bin' | 'aces.vromfs.bin' | 'gui.vromfs.bin' | 'lang.vromfs.bin'; +export type GamePackName = + | 'char.vromfs.bin' + | 'mis.vromfs.bin' + | 'aces.vromfs.bin' + | 'gui.vromfs.bin' + | 'lang.vromfs.bin' + | 'ui/atlases.vromfs.bin'; /** What identifies one version of a pack file cheaply (implementation notes, first check). */ export interface PackStamp { diff --git a/packages/local-service/src/inventory/chest-defs.ts b/packages/local-service/src/inventory/chest-defs.ts index 114df28..46f4b19 100644 --- a/packages/local-service/src/inventory/chest-defs.ts +++ b/packages/local-service/src/inventory/chest-defs.ts @@ -1,8 +1,8 @@ /** - * External Silver-Lion supply chests (`910001`, `910002`) and their keyless open generators - * (`910101`, `910102`), using deterministic rank-and-country prize selection. + * External Silver-Lion supply chests and their keyless open generators (implementation notes sections + * 6-8). Which chests exist, their prices and prizes are tuning (tuning/supply-chests.jsonc); + * prize groups resolve deterministically against the game data. */ -import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; import { makeLocalizedItemDef, @@ -12,11 +12,7 @@ import { type GeneratorDrop, type LocalizedItemDef, } from './itemdef-types.ts'; - -export const TACTICAL_CHEST_ID = 910001; -export const COLLECTOR_CHEST_ID = 910002; -const TACTICAL_CHEST_GEN_ID = 910101; -const COLLECTOR_CHEST_GEN_ID = 910102; +import type { ChestPrizeSpec, SupplyChestSpec, SupplyChestTuning } from './supply-chest-tuning.ts'; export interface SupplyChestSources { readonly wrappersByPart: ReadonlyMap; @@ -33,64 +29,30 @@ export interface SupplyChestBuildResult { readonly generators: readonly GeneratorDefinition[]; } -export function buildSupplyChests(sources: SupplyChestSources): SupplyChestBuildResult { - const commonWrappers = [ - ...(sources.wrappersByPart.get(299000) ?? []).slice(0, 3), - ...(sources.wrappersByPart.get(299001) ?? []).slice(0, 5), - ...(sources.wrappersByPart.get(299003) ?? []).slice(0, 2), - ]; - const midTierVehicles = pickAcrossCountries(sources.sortedMarketVehicles.filter((v) => v.rank <= 4), 6).map((v) => v.marketplaceItemdefId!); - const highTierVehicles = pickAcrossCountries(sources.sortedMarketVehicles.filter((v) => v.rank >= 5), 10).map((v) => v.marketplaceItemdefId!); - - const tactical = buildTacticalChest(commonWrappers, sources, midTierVehicles); - const collector = buildCollectorChest(commonWrappers, sources, highTierVehicles.length ? highTierVehicles : midTierVehicles); +export function buildSupplyChests(sources: SupplyChestSources, tuning: SupplyChestTuning): SupplyChestBuildResult { + const pairs = tuning.chests.map((spec) => createChestPair(spec, spec.prizes.flatMap((prize) => resolveDrops(prize, sources)), tuning.maxPerPurchase)); return { - defs: [...tactical.defs, ...collector.defs], - prices: [tactical.price, collector.price], - generators: [tactical.generator, collector.generator], + defs: pairs.flatMap((pair) => pair.defs), + prices: pairs.map((pair) => pair.price), + generators: pairs.map((pair) => pair.generator), }; } -function buildTacticalChest(commonWrappers: readonly number[], sources: SupplyChestSources, vehicleIds: readonly number[]) { - const decors = [...sources.skinCouponIds.slice(0, 3), ...sources.decalCouponIds.slice(0, 2), ...sources.attachableCouponIds.slice(0, 3)]; - return createChestPair({ - chestId: TACTICAL_CHEST_ID, - genId: TACTICAL_CHEST_GEN_ID, - silverLions: 60_000, - quality: 2, - icon: '!#ui/images/chests/items_box2.avif', - title: { en: 'Tactical Supply Chest', zh: '战术物资补给箱' }, - desc: { - en: 'Silver-Lion supply chest containing boosters, universal backups, decorator coupons, and Rank I-IV vehicle coupons.', - zh: '银狮物资补给箱:内含加成卡、通用备用载具、涂装/贴花/挂件券及 I~IV 级市场载具兑换券(点击可查看各项精确掉率)。', - }, - drops: [ - ...commonWrappers.map((itemdefId) => ({ itemdefId, weight: 80 })), - ...decors.map((itemdefId) => ({ itemdefId, weight: 18 })), - ...vehicleIds.map((itemdefId) => ({ itemdefId, weight: 4 })), - ], - }); -} - -function buildCollectorChest(commonWrappers: readonly number[], sources: SupplyChestSources, vehicleIds: readonly number[]) { - const decors = [...sources.skinCouponIds.slice(3, 8), ...sources.decalCouponIds.slice(2, 4), ...sources.attachableCouponIds.slice(3, 8)]; - return createChestPair({ - chestId: COLLECTOR_CHEST_ID, - genId: COLLECTOR_CHEST_GEN_ID, - silverLions: 250_000, - quality: 4, - icon: '!#ui/images/chests/items_box3.avif', - title: { en: "Collector's Supply Chest", zh: '典藏收藏家补给箱' }, - desc: { - en: 'High-tier Silver-Lion supply chest with elevated drop rates for Rank V+ marketplace vehicle and decorator coupons.', - zh: '高阶银狮补给箱:大幅提升 V 级以上稀有市场载具兑换券与 3D 装饰挂件/涂装券的掉落概率。', - }, - drops: [ - ...commonWrappers.slice(0, 5).map((itemdefId) => ({ itemdefId, weight: 45 })), - ...decors.map((itemdefId) => ({ itemdefId, weight: 22 })), - ...vehicleIds.map((itemdefId) => ({ itemdefId, weight: 12 })), - ], - }); +/** Turn one prize group of the tuning file into concrete drops. */ +function resolveDrops(prize: ChestPrizeSpec, sources: SupplyChestSources): GeneratorDrop[] { + const drops = (ids: readonly number[]) => ids.map((itemdefId) => ({ itemdefId, weight: prize.weightEach })); + switch (prize.kind) { + case 'classicItems': + return drops((sources.wrappersByPart.get(prize.recyclePart) ?? []).slice(0, prize.pick)); + case 'coupons': { + const ids = prize.couponKind === 'skin' ? sources.skinCouponIds : prize.couponKind === 'decal' ? sources.decalCouponIds : sources.attachableCouponIds; + return drops(ids.slice(prize.skip, prize.skip + prize.pick)); + } + case 'marketVehicles': { + const inRange = sources.sortedMarketVehicles.filter((v) => v.rank >= prize.minRank && v.rank <= prize.maxRank); + return drops(pickAcrossCountries(inRange, prize.pick).map((v) => v.marketplaceItemdefId!)); + } + } } /** @@ -118,51 +80,42 @@ export function pickAcrossCountries(sorted: readonly CatalogueVehicle[], limit: return picked; } -function createChestPair(spec: { - readonly chestId: number; - readonly genId: number; - readonly silverLions: number; - readonly quality: number; - readonly icon: string; - readonly title: LocalizedText; - readonly desc: LocalizedText; - readonly drops: readonly GeneratorDrop[]; -}): { +function createChestPair(spec: SupplyChestSpec, drops: readonly GeneratorDrop[], maxPerPurchase: number): { readonly defs: readonly LocalizedItemDef[]; readonly price: ExternalItemPrice; readonly generator: GeneratorDefinition; } { - const color = QUALITY_COLORS[spec.quality] ?? '45aacc'; - const chestDef = makeLocalizedItemDef(spec.chestId, { + const color = QUALITY_COLORS[spec.quality] ?? ''; + const chestDef = makeLocalizedItemDef(spec.id, { type: 'item', marketable: false, item_quality: spec.quality, name_color: color, - used_to_create: `${spec.genId}x1`, - tags: 'type:chest;showChances:yes;allowToBuyAmount:10;isAllowSkipOpeningAnim:yes;hideMarketablePropDesc:yes', + used_to_create: `${spec.openerId}x1`, + tags: `type:chest;showChances:yes;allowToBuyAmount:${maxPerPurchase};isAllowSkipOpeningAnim:yes;hideMarketablePropDesc:yes`, icon_url: spec.icon, - }, spec.title, spec.desc); + }, spec.title, spec.description); - const genDef = makeLocalizedItemDef(spec.genId, { + const genDef = makeLocalizedItemDef(spec.openerId, { type: 'generator', marketable: false, item_quality: spec.quality, name_color: color, - exchange: `${spec.chestId}x1`, - bundle: spec.drops.map((d) => `${d.itemdefId}x1`).join(';'), + exchange: `${spec.id}x1`, + bundle: drops.map((d) => `${d.itemdefId}x1`).join(';'), tags: 'devItem:yes', icon_url: spec.icon, }, spec.title, { en: '', zh: '' }); return { defs: [chestDef, genDef], - price: { itemdefId: spec.chestId, silverLions: spec.silverLions, goldenEagles: 0 }, + price: { itemdefId: spec.id, silverLions: spec.silverLions, goldenEagles: 0 }, generator: { - itemdefId: spec.genId, + itemdefId: spec.openerId, isChestGenerator: true, - chestItemdefId: spec.chestId, - recipes: [{ components: [{ itemdefId: spec.chestId, quantity: 1 }] }], - drops: spec.drops, + chestItemdefId: spec.id, + recipes: [{ components: [{ itemdefId: spec.id, quantity: 1 }] }], + drops, }, }; } diff --git a/packages/local-service/src/inventory/coupons/cosmetic-coupons.ts b/packages/local-service/src/inventory/coupons/cosmetic-coupons.ts index 5edc01c..761a9b5 100644 --- a/packages/local-service/src/inventory/coupons/cosmetic-coupons.ts +++ b/packages/local-service/src/inventory/coupons/cosmetic-coupons.ts @@ -14,9 +14,7 @@ import { type LocalizedItemDef, type MarketplaceListing, } from '../itemdef-types.ts'; - -export const DECOR_COUPON_GJN = { skin: 5, decal: 3, attachable: 8 } as const; -export const UNLOCK_COUPON_GJN = 6; +import type { MarketplaceTuning } from '../marketplace-tuning.ts'; const ICON_BY_KIND = { skin: '!#ui/gameuiskin#item_type_skin.svg', @@ -41,7 +39,7 @@ export interface CosmeticCouponBuildResult { readonly workshopStubs: readonly LocalizedItemDef[]; } -export function buildCosmeticCoupons(sources: ExternalItemSources): CosmeticCouponBuildResult { +export function buildCosmeticCoupons(sources: ExternalItemSources, tuning: MarketplaceTuning): CosmeticCouponBuildResult { const defs: LocalizedItemDef[] = []; const coupons: Array = []; const listings: MarketplaceListing[] = []; @@ -51,7 +49,7 @@ export function buildCosmeticCoupons(sources: ExternalItemSources): CosmeticCoup const sortedDecors = [...sources.decorCoupons].sort((a, b) => a.itemdefId - b.itemdefId); for (const decor of sortedDecors) { - const built = buildSingleDecorCoupon(decor); + const built = buildSingleDecorCoupon(decor, tuning); defs.push(built.def); coupons.push([decor.itemdefId, built.action]); listings.push(built.listing); @@ -62,7 +60,7 @@ export function buildCosmeticCoupons(sources: ExternalItemSources): CosmeticCoup const sortedUnlocks = [...sources.unlockCoupons].sort((a, b) => a.itemdefId - b.itemdefId); for (const unlock of sortedUnlocks) { - const built = buildSingleUnlockCoupon(unlock); + const built = buildSingleUnlockCoupon(unlock, tuning); defs.push(built.def); coupons.push([unlock.itemdefId, built.action]); listings.push(built.listing); @@ -81,13 +79,13 @@ export function buildCosmeticCoupons(sources: ExternalItemSources): CosmeticCoup return { defs, coupons, listings, skinCouponIds, decalCouponIds, attachableCouponIds, workshopStubs }; } -function buildSingleDecorCoupon(decor: MarketplaceDecorCoupon): { +function buildSingleDecorCoupon(decor: MarketplaceDecorCoupon, tuning: MarketplaceTuning): { readonly def: LocalizedItemDef; readonly action: CouponAction; readonly listing: MarketplaceListing; } { - const quality = decor.kind === 'attachable' ? 3 : 2; - const color = QUALITY_COLORS[quality] ?? '45aacc'; + const { gjnCents, quality } = tuning.cosmeticCoupons[decor.kind]; + const color = QUALITY_COLORS[quality] ?? ''; const hashName = `${decor.kind}_${decor.itemdefId}`; const def = makeLocalizedItemDef(decor.itemdefId, { type: 'item', @@ -107,7 +105,7 @@ function buildSingleDecorCoupon(decor: MarketplaceDecorCoupon): { itemdefId: decor.itemdefId, marketHashName: hashName, category: decor.kind, - gjnCost: DECOR_COUPON_GJN[decor.kind], + gjnCostCents: gjnCents, quality, nameColor: color, title: decor.name, @@ -117,13 +115,13 @@ function buildSingleDecorCoupon(decor: MarketplaceDecorCoupon): { return { def, action, listing }; } -function buildSingleUnlockCoupon(unlock: MarketplaceUnlockCoupon): { +function buildSingleUnlockCoupon(unlock: MarketplaceUnlockCoupon, tuning: MarketplaceTuning): { readonly def: LocalizedItemDef; readonly action: CouponAction; readonly listing: MarketplaceListing; } { - const quality = 3; - const color = QUALITY_COLORS[quality] ?? '5599ff'; + const { gjnCents, quality } = tuning.cosmeticCoupons.unlock; + const color = QUALITY_COLORS[quality] ?? ''; const hashName = `unlock_${unlock.itemdefId}`; const def = makeLocalizedItemDef(unlock.itemdefId, { type: 'item', @@ -143,7 +141,7 @@ function buildSingleUnlockCoupon(unlock: MarketplaceUnlockCoupon): { itemdefId: unlock.itemdefId, marketHashName: hashName, category: 'unlock', - gjnCost: UNLOCK_COUPON_GJN, + gjnCostCents: gjnCents, quality, nameColor: color, title: unlock.name, diff --git a/packages/local-service/src/inventory/coupons/vehicle-coupons.ts b/packages/local-service/src/inventory/coupons/vehicle-coupons.ts index 1abff7b..a731551 100644 --- a/packages/local-service/src/inventory/coupons/vehicle-coupons.ts +++ b/packages/local-service/src/inventory/coupons/vehicle-coupons.ts @@ -12,17 +12,7 @@ import { type LocalizedItemDef, type MarketplaceListing, } from '../itemdef-types.ts'; - -export const MARKET_VEHICLE_GJN_BY_RANK: Readonly> = { - 1: 8, - 2: 14, - 3: 22, - 4: 35, - 5: 48, - 6: 59, - 7: 69, - 8: 75, -}; +import { vehicleCouponPrice, type MarketplaceTuning } from '../marketplace-tuning.ts'; export interface VehicleCouponBuildResult { readonly defs: readonly LocalizedItemDef[]; @@ -35,6 +25,7 @@ export interface VehicleCouponBuildResult { export function buildVehicleCoupons( vehicles: readonly CatalogueVehicle[], unitNames: Readonly>, + tuning: MarketplaceTuning, ): VehicleCouponBuildResult { const defs: LocalizedItemDef[] = []; const coupons: Array = []; @@ -47,9 +38,8 @@ export function buildVehicleCoupons( for (const vehicle of sortedVehicles) { const id = vehicle.marketplaceItemdefId!; const unitTitle = unitNames[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name }; - const quality = vehicle.rank >= 6 ? 4 : vehicle.rank >= 4 ? 3 : 2; - const color = QUALITY_COLORS[quality] ?? '45aacc'; - const gjnCost = MARKET_VEHICLE_GJN_BY_RANK[vehicle.rank] ?? 45; + const { gjnCents: gjnCostCents, quality } = vehicleCouponPrice(tuning, vehicle.name, vehicle.rank); + const color = QUALITY_COLORS[quality] ?? ''; const tagType = unitClassTag(vehicle.unitClass); defs.push(makeLocalizedItemDef(id, { @@ -71,7 +61,7 @@ export function buildVehicleCoupons( itemdefId: id, marketHashName: vehicle.name, category: 'vehicle', - gjnCost, + gjnCostCents, quality, nameColor: color, title: unitTitle, diff --git a/packages/local-service/src/inventory/inventory-rules.ts b/packages/local-service/src/inventory/inventory-rules.ts index 20da8d5..4d5d0b1 100644 --- a/packages/local-service/src/inventory/inventory-rules.ts +++ b/packages/local-service/src/inventory/inventory-rules.ts @@ -6,7 +6,7 @@ import type { BlkBlock, BlkParam } from '@wto/blk'; import type { ItemCatalogue } from '../items/item-catalogue.ts'; import { grantItem } from '../items/item-grants.ts'; -import { balanceOf, canAfford, pay, payGjn } from '../profile/profile-currency.ts'; +import { balanceOf, canAfford, pay, payGjnCents } from '../profile/profile-currency.ts'; import { consumeExternalItem, externalItemByUid, @@ -252,10 +252,10 @@ export function buyMarketplaceCoupon( if (!listing || !Number.isSafeInteger(quantity) || quantity < 1 || quantity > 20) { return { ok: false, reason: 'NOT_FOUND' }; } - const totalCost = listing.gjnCost * quantity; - if (balanceOf(profile).gjn < totalCost) return { ok: false, reason: 'NOT_ENOUGH_GJN' }; + const totalCost = listing.gjnCostCents * quantity; + if (balanceOf(profile).gjnCents < totalCost) return { ok: false, reason: 'NOT_ENOUGH_GJN' }; - payGjn(profile, totalCost); + payGjnCents(profile, totalCost); const item = grantExternalItem(profile, itemdefId, quantity); return { ok: true, item }; } diff --git a/packages/local-service/src/inventory/itemdef-catalogue.ts b/packages/local-service/src/inventory/itemdef-catalogue.ts index e5e9e48..60bad6d 100644 --- a/packages/local-service/src/inventory/itemdef-catalogue.ts +++ b/packages/local-service/src/inventory/itemdef-catalogue.ts @@ -7,7 +7,10 @@ import type { ExternalItemSources } from '../game-data/datasets/external-item-so import type { ItemDefinition } from '../game-data/datasets/item-catalogue.ts'; import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; -import { buildSupplyChests, COLLECTOR_CHEST_ID, TACTICAL_CHEST_ID } from './chest-defs.ts'; +import { buildSupplyChests } from './chest-defs.ts'; +import type { MarketplaceTuning } from './marketplace-tuning.ts'; +import type { RecyclingTuning } from './recycling-tuning.ts'; +import type { SupplyChestTuning } from './supply-chest-tuning.ts'; import { buildCosmeticCoupons } from './coupons/cosmetic-coupons.ts'; import { buildVehicleCoupons } from './coupons/vehicle-coupons.ts'; import { @@ -22,9 +25,15 @@ import { } from './itemdef-types.ts'; import { buildRecyclingDefs } from './recycling-defs.ts'; -export { COLLECTOR_CHEST_ID, TACTICAL_CHEST_ID }; export type { ExternalItemPrice, GeneratorDefinition, GeneratorRecipe }; +/** The tuning the external inventory is generated with. */ +export interface InventoryTuning { + readonly marketplace: MarketplaceTuning; + readonly supplyChests: SupplyChestTuning; + readonly recycling: RecyclingTuning; +} + export class InventoryCatalogue { readonly #defs = new Map(); readonly #coupons = new Map(); @@ -38,17 +47,18 @@ export class InventoryCatalogue { unitNames: Readonly>, sources: ExternalItemSources, classicItems: readonly ItemDefinition[], + tuning: InventoryTuning, ) { - const vehicleCoupons = buildVehicleCoupons(vehicles, unitNames); - const cosmeticCoupons = buildCosmeticCoupons(sources); - const recycling = buildRecyclingDefs(classicItems); + const vehicleCoupons = buildVehicleCoupons(vehicles, unitNames, tuning.marketplace); + const cosmeticCoupons = buildCosmeticCoupons(sources, tuning.marketplace); + const recycling = buildRecyclingDefs(classicItems, tuning.recycling); const chests = buildSupplyChests({ wrappersByPart: recycling.wrappersByPart, skinCouponIds: cosmeticCoupons.skinCouponIds, decalCouponIds: cosmeticCoupons.decalCouponIds, attachableCouponIds: cosmeticCoupons.attachableCouponIds, sortedMarketVehicles: vehicleCoupons.sortedVehicles, - }); + }, tuning.supplyChests); for (const def of [...vehicleCoupons.defs, ...cosmeticCoupons.defs, ...recycling.defs, ...chests.defs]) { this.#defs.set(def.itemdefId, def); diff --git a/packages/local-service/src/inventory/itemdef-types.ts b/packages/local-service/src/inventory/itemdef-types.ts index 2e0c167..3426111 100644 --- a/packages/local-service/src/inventory/itemdef-types.ts +++ b/packages/local-service/src/inventory/itemdef-types.ts @@ -67,7 +67,7 @@ export interface MarketplaceListing { readonly itemdefId: number; readonly marketHashName: string; readonly category: MarketplaceCategory; - readonly gjnCost: number; + readonly gjnCostCents: number; readonly quality: number; readonly nameColor: string; readonly title: LocalizedText; diff --git a/packages/local-service/src/inventory/marketplace-service.ts b/packages/local-service/src/inventory/marketplace-service.ts index 926317c..da4d5d9 100644 --- a/packages/local-service/src/inventory/marketplace-service.ts +++ b/packages/local-service/src/inventory/marketplace-service.ts @@ -4,6 +4,7 @@ * (vehicles, skins, decals, attachables, pilot/unlocks) with GJN, depositing coupons into * `extInventory` and pushing `mrpc.generic_notify` (`inventory.changed`) to active game clients. */ +import { gjnText } from '../store/redeem-codes.ts'; import type { BlkBlock } from '@wto/blk'; import type { AccountStore } from '../accounts/account-store.ts'; import type { PlayerProfiles } from '../profile/player-profiles.ts'; @@ -32,17 +33,20 @@ export class MarketplaceService implements Service { readonly #profiles: PlayerProfiles; readonly #catalogue: InventoryCatalogue; readonly #notifyInventoryChanged: () => void; + readonly #maxPerPurchase: number; constructor( accounts: AccountStore, profiles: PlayerProfiles, catalogue: InventoryCatalogue, notifyInventoryChanged: () => void, + maxPerPurchase: number, ) { this.#accounts = accounts; this.#profiles = profiles; this.#catalogue = catalogue; this.#notifyInventoryChanged = notifyInventoryChanged; + this.#maxPerPurchase = maxPerPurchase; } accepts(request: ServiceRequest): boolean { @@ -66,7 +70,7 @@ export class MarketplaceService implements Service { #state(request: ServiceRequest): ServiceResponse { const account = selectWebViewAccount(this.#accounts, request.query.get('userId')); const profile = account ? this.#profiles.profileOf(account.userId) : undefined; - const balance = profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjn: 0 }; + const balance = profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjnCents: 0 }; const heldCounts = new Map(); if (profile) { @@ -94,17 +98,17 @@ export class MarketplaceService implements Service { const body = parseJsonBody(request.body); const account = requireWebActionAccount(this.#accounts, body.userId); if (!account) { - return jsonResponse({ ok: false, message: '未找到指定账号,请先在游戏客户端登录并在页面右上角选择账号。' }, 'marketplace buy: unknown account'); + return jsonResponse({ ok: false, message: { zh: '没有找到这个账号,请先在右上角选择账号。', en: 'Account not found. Pick an account at the top right first.' } }, 'marketplace buy: unknown account'); } const itemdefId = Number(body.itemdefId ?? 0); const rawQuantity = body.quantity === undefined ? 1 : Number(body.quantity); - if (!Number.isSafeInteger(itemdefId) || itemdefId <= 0 || !Number.isSafeInteger(rawQuantity) || rawQuantity < 1 || rawQuantity > 20) { - return jsonResponse({ ok: false, message: '请求参数无效(每次购买数量需为 1~20 的整数)。' }, 'marketplace buy: bad params'); + if (!Number.isSafeInteger(itemdefId) || itemdefId <= 0 || !Number.isSafeInteger(rawQuantity) || rawQuantity < 1 || rawQuantity > this.#maxPerPurchase) { + return jsonResponse({ ok: false, message: { zh: `请求无效:每次购买 1~${this.#maxPerPurchase} 张。`, en: `Invalid request: buy 1 to ${this.#maxPerPurchase} coupons at a time.` } }, 'marketplace buy: bad params'); } const quantity = rawQuantity; const listing = this.#catalogue.marketplaceListing(itemdefId); - if (!listing) return jsonResponse({ ok: false, message: '未找到该兑换券商品。' }, `marketplace buy: unknown ${itemdefId}`); + if (!listing) return jsonResponse({ ok: false, message: { zh: '没有找到这张兑换券。', en: 'Coupon not found.' } }, `marketplace buy: unknown ${itemdefId}`); let errorReason: 'NOT_FOUND' | 'NOT_ENOUGH_GJN' | undefined; this.#profiles.updateWhen(account.userId, (saved) => { @@ -117,17 +121,20 @@ export class MarketplaceService implements Service { }); if (errorReason === 'NOT_ENOUGH_GJN') { - return jsonResponse({ ok: false, message: 'GJN 余额不足(可通过存档修改器或商店兑换码补充 GJN)。' }, `marketplace buy ${itemdefId}: NOMONEY`); + return jsonResponse({ ok: false, message: { zh: 'GJN 不够。可以在商店的"兑换码"页用 GJN 充值码补充。', en: 'Not enough GJN. A GJN code on the Redeem tab of the store adds more.' } }, `marketplace buy ${itemdefId}: NOMONEY`); } if (errorReason) { - return jsonResponse({ ok: false, message: '购买失败。' }, `marketplace buy ${itemdefId}: ${errorReason}`); + return jsonResponse({ ok: false, message: { zh: '购买失败。', en: 'Purchase failed.' } }, `marketplace buy ${itemdefId}: ${errorReason}`); } this.#notifyInventoryChanged(); return jsonResponse({ ok: true, - message: `已购买「${listing.title.zh}」兑换券 x${quantity}!已同步至游戏库存,可在机库【道具 → 库存】中使用兑换。`, - }, `marketplace buy ${itemdefId} x${quantity} (${listing.gjnCost * quantity} GJN)`); + message: { + zh: `已购买「${listing.title.zh}」兑换券 ×${quantity},已放进游戏库存,可在机库的"道具 → 库存"里使用。`, + en: `Bought ${quantity} × "${listing.title.en}" coupon. It is in your inventory (Items → Inventory in the hangar).`, + }, + }, `marketplace buy ${itemdefId} x${quantity} (${gjnText(listing.gjnCostCents * quantity)} GJN)`); } } diff --git a/packages/local-service/src/inventory/marketplace-tuning.ts b/packages/local-service/src/inventory/marketplace-tuning.ts new file mode 100644 index 0000000..ca7013d --- /dev/null +++ b/packages/local-service/src/inventory/marketplace-tuning.ts @@ -0,0 +1,59 @@ +/** Typed content of tuning/marketplace.jsonc. */ +import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts'; + +export type CosmeticCouponKind = 'skin' | 'decal' | 'attachable' | 'unlock'; + +export interface CouponPrice { + readonly gjnCents: number; + readonly quality: number; +} + +interface RankTier { + readonly upToRank: number; + readonly value: T; +} + +export interface MarketplaceTuning { + readonly maxPerPurchase: number; + readonly vehiclePriceByVehicle: ReadonlyMap; + readonly vehiclePriceByRank: readonly RankTier[]; + readonly vehicleQualityByRank: readonly RankTier[]; + readonly cosmeticCoupons: Readonly>; +} + +const COSMETIC_KINDS: readonly CosmeticCouponKind[] = ['skin', 'decal', 'attachable', 'unlock']; + +export function readMarketplaceTuning(file: TuningReader): MarketplaceTuning { + const vehicles = file.object('vehicleCoupons'); + const prices = vehicles.object('byVehicle'); + const cosmetic = file.object('cosmeticCoupons'); + return { + maxPerPurchase: file.int('maxPerPurchase', { min: 1 }), + vehiclePriceByVehicle: new Map(prices.keys().map((name) => [name, prices.money(name, { min: 0.01 })])), + vehiclePriceByRank: rankTiers(vehicles, 'byRank', (entry) => entry.money('gjn', { min: 0.01 })), + vehicleQualityByRank: rankTiers(vehicles, 'qualityByRank', (entry) => entry.int('quality', { min: 1, max: 5 })), + cosmeticCoupons: Object.fromEntries(COSMETIC_KINDS.map((kind) => { + const entry = cosmetic.object(kind); + return [kind, { gjnCents: entry.money('gjn', { min: 0.01 }), quality: entry.int('quality', { min: 1, max: 5 }) }]; + })) as Record, + }; +} + +/** A vehicle coupon's price in GJN hundredths and its quality. */ +export function vehicleCouponPrice(tuning: MarketplaceTuning, vehicle: string, rank: number): CouponPrice { + return { + gjnCents: tuning.vehiclePriceByVehicle.get(vehicle) ?? forRank(tuning.vehiclePriceByRank, rank), + quality: forRank(tuning.vehicleQualityByRank, rank), + }; +} + +function rankTiers(file: TuningReader, key: string, read: (entry: TuningReader) => T): RankTier[] { + const tiers = file.list(key, (entry) => ({ upToRank: entry.int('upToRank', { min: 1 }), value: read(entry) })).sort((a, b) => a.upToRank - b.upToRank); + if (tiers.length === 0) throw new TuningError(`tuning file marketplace.jsonc: vehicleCoupons.${key} must have at least one tier`); + return tiers; +} + +/** The first tier whose upToRank covers the rank; the last tier above the highest. */ +function forRank(tiers: readonly RankTier[], rank: number): T { + return (tiers.find((tier) => rank <= tier.upToRank) ?? tiers[tiers.length - 1]!).value; +} diff --git a/packages/local-service/src/inventory/recycling-defs.ts b/packages/local-service/src/inventory/recycling-defs.ts index 43bc571..cee20c4 100644 --- a/packages/local-service/src/inventory/recycling-defs.ts +++ b/packages/local-service/src/inventory/recycling-defs.ts @@ -1,9 +1,9 @@ /** - * Classic-item `autoConsume` wrappers (`810001+`), recycled craft fragments (`299000..299004`), - * and re-synthesis generators (`299020..299024`, `299030`; implementation notes). + * Classic-item `autoConsume` wrappers (`810001+`), recycled craft fragments and re-synthesis + * generators. The fragments are the distinct recycleItemResult + * values of config/items.blk; the recipes are tuning (tuning/recycling.jsonc). */ import type { ItemDefinition } from '../game-data/datasets/item-catalogue.ts'; -import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; import { makeLocalizedItemDef, type CouponAction, @@ -12,18 +12,11 @@ import { type GeneratorRecipe, type LocalizedItemDef, } from './itemdef-types.ts'; +import type { RecyclingTuning } from './recycling-tuning.ts'; -export const RECYCLE_PART_IDS = [299000, 299001, 299002, 299003, 299004] as const; const RECYCLE_SINGLE_OFFSET = 20; const RECYCLE_GENERIC_GENERATOR_ID = 299030; - -const PART_NAMES: Readonly> = { - 299000: { en: 'Spare Supply Fragment', zh: '备用载具回收组件' }, - 299001: { en: 'Booster Fragment', zh: '加成卡回收组件' }, - 299002: { en: 'Coupon Fragment', zh: '折扣券回收组件' }, - 299003: { en: 'Order Fragment', zh: '任务令回收组件' }, - 299004: { en: 'Wager Fragment', zh: '合同回收组件' }, -}; +const FIRST_WRAPPER_ID = 810001; export interface RecyclingBuildResult { readonly defs: readonly LocalizedItemDef[]; @@ -32,28 +25,31 @@ export interface RecyclingBuildResult { readonly wrappersByPart: ReadonlyMap; } -export function buildRecyclingDefs(classicItems: readonly ItemDefinition[]): RecyclingBuildResult { +export function buildRecyclingDefs(classicItems: readonly ItemDefinition[], tuning: RecyclingTuning): RecyclingBuildResult { const defs: LocalizedItemDef[] = []; const coupons: Array = []; const generators: GeneratorDefinition[] = []; - const wrappersByPart = buildClassicWrappers(classicItems, defs, coupons); + const partIds = [...new Set(classicItems.flatMap((item) => (item.recycleItemResult === undefined ? [] : [item.recycleItemResult])))].sort((a, b) => a - b); + const wrappersByPart = buildClassicWrappers(classicItems, partIds, tuning, defs, coupons); const allWrappers = [...new Set([...wrappersByPart.values()].flat())]; - for (const partId of RECYCLE_PART_IDS) { - registerSinglePartSynthesizer(partId, wrappersByPart.get(partId) ?? allWrappers, defs, generators); + for (const partId of partIds) { + registerSinglePartSynthesizer(partId, wrappersByPart.get(partId) ?? allWrappers, tuning, defs, generators); } - registerMixedSynthesizer(allWrappers, defs, generators); + registerMixedSynthesizer(partIds, allWrappers, defs, generators); return { defs, coupons, generators, wrappersByPart }; } function registerSinglePartSynthesizer( partId: number, pool: readonly number[], + tuning: RecyclingTuning, defs: LocalizedItemDef[], generators: GeneratorDefinition[], ): void { const singleGenId = partId + RECYCLE_SINGLE_OFFSET; - const title = PART_NAMES[partId] ?? { en: `Recycled Part #${partId}`, zh: `回收组件 #${partId}` }; + const title = tuning.partNames.get(partId) ?? { en: `Recycled Part #${partId}`, zh: `回收组件 #${partId}` }; + const needed = tuning.partsPerItem; defs.push(makeLocalizedItemDef(partId, { type: 'item', marketable: false, @@ -62,14 +58,14 @@ function registerSinglePartSynthesizer( tags: 'type:craft_part;hideMarketablePropDesc:yes', icon_url: '!#ui/gameuiskin#item_type_craftpart.svg', }, title, { - en: 'Obtained by recycling classic items; 2 fragments craft a new random tactical item.', - zh: '回收经典道具所得;每 2 个组件可重新合成 1 件随机道具。', + en: `Obtained by recycling classic items; ${needed} fragments craft a new random item.`, + zh: `回收经典道具所得;每 ${needed} 个组件可重新合成 1 件随机道具。`, })); defs.push(makeLocalizedItemDef(singleGenId, { type: 'generator', marketable: false, item_quality: 1, - exchange: `${partId}x2`, + exchange: `${partId}x${needed}`, bundle: pool.map((id) => `${id}x1`).join(';'), tags: 'devItem:yes', icon_url: '!#ui/gameuiskin#item_type_craftpart.svg', @@ -77,17 +73,18 @@ function registerSinglePartSynthesizer( generators.push({ itemdefId: singleGenId, isChestGenerator: false, - recipes: [{ components: [{ itemdefId: partId, quantity: 2 }] }], + recipes: [{ components: [{ itemdefId: partId, quantity: needed }] }], drops: pool.map((id): GeneratorDrop => ({ itemdefId: id, weight: 10 })), }); } function registerMixedSynthesizer( + partIds: readonly number[], allWrappers: readonly number[], defs: LocalizedItemDef[], generators: GeneratorDefinition[], ): void { - const { pairRecipes, pairStrings } = buildPairRecipes(); + const { pairRecipes, pairStrings } = buildPairRecipes(partIds); defs.push(makeLocalizedItemDef(RECYCLE_GENERIC_GENERATOR_ID, { type: 'generator', marketable: false, @@ -107,11 +104,13 @@ function registerMixedSynthesizer( function buildClassicWrappers( classicItems: readonly ItemDefinition[], + partIds: readonly number[], + tuning: RecyclingTuning, defs: LocalizedItemDef[], coupons: Array, ): ReadonlyMap { const byRecyclePart = new Map(); - for (const partId of RECYCLE_PART_IDS) byRecyclePart.set(partId, []); + for (const partId of partIds) byRecyclePart.set(partId, []); // Sort deterministically by item id so wrapper IDs and drop pools do not depend on BLK order. const sortedPermanent = classicItems @@ -120,18 +119,19 @@ function buildClassicWrappers( const preferredByPart = new Map(); for (const item of sortedPermanent) { - const partId = item.recycleItemResult ?? 299001; + const partId = item.recycleItemResult; + if (partId === undefined) continue; let bucket = preferredByPart.get(partId); if (!bucket) preferredByPart.set(partId, bucket = []); - if (bucket.length < 8) bucket.push(item); + if (bucket.length < tuning.itemsPerPart) bucket.push(item); } - let nextWrapperId = 810001; - for (const partId of RECYCLE_PART_IDS) { + let nextWrapperId = FIRST_WRAPPER_ID; + for (const partId of partIds) { const targetList = byRecyclePart.get(partId) ?? []; for (const def of preferredByPart.get(partId) ?? []) { const wrapperId = nextWrapperId++; - const count = def.name === 'item_universal_spare' ? 3 : 1; + const count = tuning.piecesPerItem.get(def.name) ?? 1; defs.push(makeLocalizedItemDef(wrapperId, { type: 'item', marketable: false, @@ -146,20 +146,20 @@ function buildClassicWrappers( byRecyclePart.set(partId, targetList); } - const fallbackPool = [...(byRecyclePart.get(299000) ?? []), ...(byRecyclePart.get(299001) ?? [])]; - for (const partId of RECYCLE_PART_IDS) { + const fallbackPool = tuning.fallbackParts.flatMap((partId) => byRecyclePart.get(partId) ?? []); + for (const partId of partIds) { if ((byRecyclePart.get(partId)?.length ?? 0) === 0) byRecyclePart.set(partId, fallbackPool); } return byRecyclePart; } -function buildPairRecipes(): { readonly pairRecipes: readonly GeneratorRecipe[]; readonly pairStrings: readonly string[] } { +function buildPairRecipes(partIds: readonly number[]): { readonly pairRecipes: readonly GeneratorRecipe[]; readonly pairStrings: readonly string[] } { const pairRecipes: GeneratorRecipe[] = []; const pairStrings: string[] = []; - for (let i = 0; i < RECYCLE_PART_IDS.length; i += 1) { - for (let j = i + 1; j < RECYCLE_PART_IDS.length; j += 1) { - const a = RECYCLE_PART_IDS[i]!; - const b = RECYCLE_PART_IDS[j]!; + for (let i = 0; i < partIds.length; i += 1) { + for (let j = i + 1; j < partIds.length; j += 1) { + const a = partIds[i]!; + const b = partIds[j]!; pairRecipes.push({ components: [{ itemdefId: a, quantity: 1 }, { itemdefId: b, quantity: 1 }] }); pairStrings.push(`${a}x1,${b}x1`); } diff --git a/packages/local-service/src/inventory/recycling-tuning.ts b/packages/local-service/src/inventory/recycling-tuning.ts new file mode 100644 index 0000000..fd6d5fa --- /dev/null +++ b/packages/local-service/src/inventory/recycling-tuning.ts @@ -0,0 +1,29 @@ +/** Typed content of tuning/recycling.jsonc. */ +import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; +import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts'; + +export interface RecyclingTuning { + readonly partNames: ReadonlyMap; + readonly partsPerItem: number; + readonly itemsPerPart: number; + readonly piecesPerItem: ReadonlyMap; + readonly fallbackParts: readonly number[]; +} + +export function readRecyclingTuning(file: TuningReader): RecyclingTuning { + const pieces = file.object('piecesPerItem'); + const names = file.table('partNames', (entry) => ({ zh: entry.string('zh'), en: entry.string('en') })); + return { + partNames: new Map([...names].map(([id, name]) => [partId(id), name])), + partsPerItem: file.int('partsPerItem', { min: 1 }), + itemsPerPart: file.int('itemsPerPart', { min: 1 }), + piecesPerItem: new Map(pieces.keys().map((item) => [item, pieces.int(item, { min: 1 })])), + fallbackParts: file.intList('fallbackParts', { min: 1 }), + }; +} + +function partId(text: string): number { + const id = Number(text); + if (!Number.isSafeInteger(id) || id <= 0) throw new TuningError(`tuning file recycling.jsonc: partNames key "${text}" must be a part number`); + return id; +} diff --git a/packages/local-service/src/inventory/supply-chest-tuning.ts b/packages/local-service/src/inventory/supply-chest-tuning.ts new file mode 100644 index 0000000..7a3feb1 --- /dev/null +++ b/packages/local-service/src/inventory/supply-chest-tuning.ts @@ -0,0 +1,65 @@ +/** Typed content of tuning/supply-chests.jsonc. */ +import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; +import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts'; + +export type ChestPrizeSpec = + | { readonly kind: 'classicItems'; readonly recyclePart: number; readonly pick: number; readonly weightEach: number } + | { readonly kind: 'coupons'; readonly couponKind: 'skin' | 'decal' | 'attachable'; readonly skip: number; readonly pick: number; readonly weightEach: number } + | { readonly kind: 'marketVehicles'; readonly minRank: number; readonly maxRank: number; readonly pick: number; readonly weightEach: number }; + +export interface SupplyChestSpec { + readonly id: number; + readonly openerId: number; + readonly silverLions: number; + readonly quality: number; + readonly icon: string; + readonly title: LocalizedText; + readonly description: LocalizedText; + readonly prizes: readonly ChestPrizeSpec[]; +} + +export interface SupplyChestTuning { + readonly maxPerPurchase: number; + readonly chests: readonly SupplyChestSpec[]; +} + +const COUPON_KINDS = ['skin', 'decal', 'attachable'] as const; + +export function readSupplyChestTuning(file: TuningReader): SupplyChestTuning { + return { + maxPerPurchase: file.int('maxPerPurchase', { min: 1 }), + chests: file.list('chests', (entry) => ({ + id: entry.int('id', { min: 1 }), + openerId: entry.int('openerId', { min: 1 }), + silverLions: entry.int('silverLions', { min: 1 }), + quality: entry.int('quality', { min: 1, max: 5 }), + icon: entry.string('icon'), + title: localized(entry.object('title')), + description: localized(entry.object('description')), + prizes: entry.list('prizes', readPrize), + })), + }; +} + +function readPrize(entry: TuningReader): ChestPrizeSpec { + const weightEach = entry.number('weightEach', { min: 0 }); + if (entry.has('classicItems')) { + const group = entry.object('classicItems'); + return { kind: 'classicItems', recyclePart: group.int('recyclePart', { min: 1 }), pick: group.int('pick', { min: 1 }), weightEach }; + } + if (entry.has('coupons')) { + const group = entry.object('coupons'); + const couponKind = group.string('kind'); + if (!(COUPON_KINDS as readonly string[]).includes(couponKind)) throw new TuningError(`tuning file supply-chests.jsonc: coupons.kind must be one of ${COUPON_KINDS.join(', ')} (found "${couponKind}")`); + return { kind: 'coupons', couponKind: couponKind as (typeof COUPON_KINDS)[number], skip: group.int('skip', { min: 0 }), pick: group.int('pick', { min: 1 }), weightEach }; + } + if (entry.has('marketVehicles')) { + const group = entry.object('marketVehicles'); + return { kind: 'marketVehicles', minRank: group.int('minRank', { min: 1 }), maxRank: group.int('maxRank', { min: 1 }), pick: group.int('pick', { min: 1 }), weightEach }; + } + throw new TuningError(`tuning file supply-chests.jsonc: a prize needs one of classicItems, coupons, marketVehicles (found ${JSON.stringify(entry.keys())})`); +} + +function localized(entry: TuningReader): LocalizedText { + return { zh: entry.string('zh'), en: entry.string('en') }; +} diff --git a/packages/local-service/src/inventory/trophy-catalogue.ts b/packages/local-service/src/inventory/trophy-catalogue.ts index 3e589d1..6b59deb 100644 --- a/packages/local-service/src/inventory/trophy-catalogue.ts +++ b/packages/local-service/src/inventory/trophy-catalogue.ts @@ -18,6 +18,7 @@ import type { ServerTime } from '../profile/server-time.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; import { pickAcrossCountries } from './chest-defs.ts'; import { pickWeighted } from './inventory-rules.ts'; +import type { GroupWeight, SupplyTrophySpec, TrophyPrizeSpec, TrophyTuning } from './trophy-tuning.ts'; export type TrophyPrize = | { readonly kind: 'warpoints'; readonly amount: number; readonly weight: number } @@ -38,40 +39,18 @@ export interface TrophyDefinition { readonly prizes: readonly TrophyPrize[]; } -export const DIRECT_UNIT_GOLD_BY_RANK: Readonly> = { - 1: 850, - 2: 1450, - 3: 2600, - 4: 4880, - 5: 6980, - 6: 8380, - 7: 9650, - 8: 10900, -}; - export class TrophyCatalogue { readonly #trophies: readonly TrophyDefinition[]; readonly #byId = new Map(); - constructor(vehicles: readonly CatalogueVehicle[], classicItems: readonly ItemDefinition[]) { - const boosterIds = classicItems - .filter((item) => item.type === 'rateBooster' && item.expiresAt === undefined) - .map((item) => item.name) - .sort((a, b) => a.localeCompare(b)) - .slice(0, 6); - const hasUniversalSpare = classicItems.some((item) => item.name === 'item_universal_spare'); - - const sortedEventVehicles = vehicles + constructor(vehicles: readonly CatalogueVehicle[], classicItems: readonly ItemDefinition[], tuning: TrophyTuning) { + const eventVehicles = vehicles .filter((v) => v.event && !v.marketplaceItemdefId && !v.onlyShownWhenOwned && v.inTechTree) .sort((a, b) => (a.rank - b.rank) || a.country.localeCompare(b.country) || a.name.localeCompare(b.name)); - - const silverUnits = pickAcrossCountries(sortedEventVehicles.filter((v) => v.rank <= 3), 4); - const veteranUnits = pickAcrossCountries(sortedEventVehicles.filter((v) => v.rank >= 4), 6); - + const pools: PrizePools = { eventVehicles, classicItems }; this.#trophies = [ - buildSilverSupplyTrophy(silverUnits, boosterIds, hasUniversalSpare), - buildVeteranSupplyTrophy(veteranUnits.length ? veteranUnits : silverUnits, boosterIds, hasUniversalSpare), - ...sortedEventVehicles.map(buildDirectUnitTrophy), + ...tuning.supplyTrophies.map((spec) => supplyTrophy(spec, pools)), + ...eventVehicles.map((vehicle) => directVehicleTrophy(vehicle, tuning.directVehicleGoldenEagles)), ]; for (const trophy of this.#trophies) this.#byId.set(trophy.id, trophy); } @@ -85,54 +64,67 @@ export class TrophyCatalogue { } } -function buildSilverSupplyTrophy(units: readonly CatalogueVehicle[], boosterIds: readonly string[], hasSpare: boolean): TrophyDefinition { +interface PrizePools { + /** Event vehicles not sold on the marketplace, sorted by (rank, country, name). */ + readonly eventVehicles: readonly CatalogueVehicle[]; + readonly classicItems: readonly ItemDefinition[]; +} + +function supplyTrophy(spec: SupplyTrophySpec, pools: PrizePools): TrophyDefinition { return { - id: 'wto_silver_supply_trophy', - iconStyle: 'small_wooden_box', - silverLions: 50_000, - goldenEagles: 0, + id: spec.id, + iconStyle: spec.iconStyle, + silverLions: spec.silverLions, + goldenEagles: spec.goldenEagles, showChances: true, repeatable: true, instantOpening: false, numTotal: 0, - prizes: [ - ...units.map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight: 2 })), - { kind: 'warpoints', amount: 250_000, weight: 8 }, - { kind: 'warpoints', amount: 75_000, weight: 20 }, - { kind: 'warpoints', amount: 25_000, weight: 35 }, - ...(hasSpare ? [{ kind: 'item', itemName: 'item_universal_spare', count: 3, weight: 25 } as const] : []), - ...boosterIds.map((itemName): TrophyPrize => ({ kind: 'item', itemName, count: 1, weight: 20 })), - ], + prizes: spec.prizes.flatMap((prize) => resolvePrize(spec.id, prize, pools)), }; } -function buildVeteranSupplyTrophy(units: readonly CatalogueVehicle[], boosterIds: readonly string[], hasSpare: boolean): TrophyDefinition { - return { - id: 'wto_veteran_supply_trophy', - iconStyle: 'big_chest', - silverLions: 150_000, - goldenEagles: 0, - showChances: true, - repeatable: true, - instantOpening: false, - numTotal: 0, - prizes: [ - ...units.map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight: 4 })), - { kind: 'gold', amount: 150, weight: 10 }, - { kind: 'warpoints', amount: 500_000, weight: 12 }, - { kind: 'warpoints', amount: 120_000, weight: 28 }, - ...(hasSpare ? [{ kind: 'item', itemName: 'item_universal_spare', count: 5, weight: 30 } as const] : []), - ...boosterIds.slice(0, 4).map((itemName): TrophyPrize => ({ kind: 'item', itemName, count: 1, weight: 22 })), - ], - }; +/** Turn one prize entry of the tuning file into concrete prizes. */ +function resolvePrize(trophyId: string, spec: TrophyPrizeSpec, pools: PrizePools): TrophyPrize[] { + switch (spec.kind) { + case 'silverLions': + return [{ kind: 'warpoints', amount: spec.amount, weight: spec.weight }]; + case 'goldenEagles': + return [{ kind: 'gold', amount: spec.amount, weight: spec.weight }]; + case 'item': + if (!pools.classicItems.some((item) => item.name === spec.item)) { + throw new Error(`tuning file trophies.jsonc: ${trophyId} names item ${spec.item}, which config/items.blk of this game version does not have`); + } + return [{ kind: 'item', itemName: spec.item, count: spec.count, weight: spec.weight }]; + case 'itemsOfType': { + const names = pools.classicItems + .filter((item) => item.type === spec.itemType && item.expiresAt === undefined) + .map((item) => item.name) + .sort((a, b) => a.localeCompare(b)) + .slice(0, spec.pick); + const weight = weightEach(spec.weight, names.length); + return names.map((itemName): TrophyPrize => ({ kind: 'item', itemName, count: spec.count, weight })); + } + case 'eventVehicles': { + const inRange = pools.eventVehicles.filter((v) => v.rank >= spec.minRank && v.rank <= spec.maxRank); + const picked = pickAcrossCountries(inRange, spec.pick); + const weight = weightEach(spec.weight, picked.length); + return picked.map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight })); + } + } } -function buildDirectUnitTrophy(vehicle: CatalogueVehicle): TrophyDefinition { +function weightEach(weight: GroupWeight, count: number): number { + if ('each' in weight) return weight.each; + return count > 0 ? weight.total / count : 0; +} + +function directVehicleTrophy(vehicle: CatalogueVehicle, goldenEagles: number): TrophyDefinition { return { id: `wto_prize_unit_${vehicle.name}`, iconStyle: 'ammo_box', silverLions: 0, - goldenEagles: DIRECT_UNIT_GOLD_BY_RANK[vehicle.rank] ?? 6090, + goldenEagles, showChances: false, repeatable: false, instantOpening: true, diff --git a/packages/local-service/src/inventory/trophy-tuning.ts b/packages/local-service/src/inventory/trophy-tuning.ts new file mode 100644 index 0000000..07d1310 --- /dev/null +++ b/packages/local-service/src/inventory/trophy-tuning.ts @@ -0,0 +1,65 @@ +/** Typed content of tuning/trophies.jsonc. */ +import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts'; + +/** How the weight of a prize group is given: each prize's own, or the group's, split evenly. */ +export type GroupWeight = { readonly each: number } | { readonly total: number }; + +export type TrophyPrizeSpec = + | { readonly kind: 'silverLions'; readonly amount: number; readonly weight: number } + | { readonly kind: 'goldenEagles'; readonly amount: number; readonly weight: number } + | { readonly kind: 'item'; readonly item: string; readonly count: number; readonly weight: number } + | { readonly kind: 'itemsOfType'; readonly itemType: string; readonly pick: number; readonly count: number; readonly weight: GroupWeight } + | { readonly kind: 'eventVehicles'; readonly minRank: number; readonly maxRank: number; readonly pick: number; readonly weight: GroupWeight }; + +export interface SupplyTrophySpec { + readonly id: string; + readonly iconStyle: string; + readonly silverLions: number; + readonly goldenEagles: number; + readonly prizes: readonly TrophyPrizeSpec[]; +} + +export interface TrophyTuning { + readonly supplyTrophies: readonly SupplyTrophySpec[]; + readonly directVehicleGoldenEagles: number; +} + +export function readTrophyTuning(file: TuningReader): TrophyTuning { + return { + supplyTrophies: file.list('supplyTrophies', (entry) => ({ + id: entry.string('id'), + iconStyle: entry.string('iconStyle'), + silverLions: entry.int('silverLions', { min: 0 }), + goldenEagles: entry.int('goldenEagles', { min: 0 }), + prizes: entry.list('prizes', readPrize), + })), + directVehicleGoldenEagles: file.object('directVehicles').int('goldenEagles', { min: 1 }), + }; +} + +function readPrize(entry: TuningReader): TrophyPrizeSpec { + const weight = () => entry.number('weight', { min: 0 }); + if (entry.has('silverLions')) return { kind: 'silverLions', amount: entry.int('silverLions', { min: 1 }), weight: weight() }; + if (entry.has('goldenEagles')) return { kind: 'goldenEagles', amount: entry.int('goldenEagles', { min: 1 }), weight: weight() }; + if (entry.has('item')) return { kind: 'item', item: entry.string('item'), count: entry.int('count', { min: 1 }), weight: weight() }; + if (entry.has('itemsOfType')) { + return { kind: 'itemsOfType', itemType: entry.string('itemsOfType'), pick: entry.int('pick', { min: 1 }), count: entry.int('count', { min: 1 }), weight: groupWeight(entry) }; + } + if (entry.has('eventVehicles')) { + const vehicles = entry.object('eventVehicles'); + return { + kind: 'eventVehicles', + minRank: vehicles.int('minRank', { min: 1 }), + maxRank: vehicles.int('maxRank', { min: 1 }), + pick: vehicles.int('pick', { min: 1 }), + weight: groupWeight(entry), + }; + } + throw new TuningError(`tuning file trophies.jsonc: a prize needs one of silverLions, goldenEagles, item, itemsOfType, eventVehicles (found ${JSON.stringify(entry.keys())})`); +} + +function groupWeight(entry: TuningReader): GroupWeight { + if (entry.has('weightEach')) return { each: entry.number('weightEach', { min: 0 }) }; + if (entry.has('weightTotal')) return { total: entry.number('weightTotal', { min: 0 }) }; + throw new TuningError(`tuning file trophies.jsonc: a prize group needs weightEach or weightTotal (found ${JSON.stringify(entry.keys())})`); +} diff --git a/packages/local-service/src/inventory/web/app.js b/packages/local-service/src/inventory/web/app.js index f3665d0..fcc333c 100644 --- a/packages/local-service/src/inventory/web/app.js +++ b/packages/local-service/src/inventory/web/app.js @@ -1,138 +1,146 @@ -const COUNTRY_LABELS = { - country_usa: '美国', country_germany: '德国', country_ussr: '苏联', country_britain: '英国', - country_japan: '日本', country_china: '中国', country_italy: '意大利', country_france: '法国', - country_sweden: '瑞典', country_israel: '以色列' +// Local marketplace page, shown in the game's built-in browser. +// The game opens it as ?a=[&viewitem&n=] (inventoryClient.nut). +'use strict'; + +const T = { + zh: { + title: 'WTOffline 本地交易所', hint: '买到的兑换券直接进游戏库存(机库 → 道具 → 库存)', toStore: '前往商店', + eagles: '金鹰', lions: '银狮', + catAll: '全部', catVehicle: '载具券', catSkin: '涂装券', catAttachable: '挂件券', catDecal: '贴花券', catUnlock: '头像与解锁券', + search: '搜索名称或编号', allCountries: '全部国家', allClasses: '全部兵种', rank: '{rank} 级', + held: '库存 ×{n}', activated: '已拥有', buy: '购买', pickAccount: '请先选择账号', empty: '没有符合条件的兑换券', + }, + en: { + title: 'WTOffline Marketplace', hint: 'Coupons go straight to your inventory (Items → Inventory in the hangar)', toStore: 'Go to Store', + eagles: 'Golden Eagles', lions: 'Silver Lions', + catAll: 'All', catVehicle: 'Vehicles', catSkin: 'Camouflages', catAttachable: 'Decorations', catDecal: 'Decals', catUnlock: 'Icons and unlocks', + search: 'Search name or id', allCountries: 'All nations', allClasses: 'All types', rank: 'Rank {rank}', + held: 'In inventory ×{n}', activated: 'Owned', buy: 'Buy', pickAccount: 'Pick an account first', empty: 'Nothing matches the filters', + }, }; +// Vehicle class of a listing -> the game's own type name (lang/menu.csv). +const CLASS_LABELS = { + aircraft: 'mainmenu/type_aircraft', helicopter: 'mainmenu/type_helicopter', tank: 'mainmenu/type_tank', + ship: 'mainmenu/type_ship_only', boat: 'mainmenu/type_boat_only', +}; +const ROMAN = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X']; +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: { gjn: 0, goldenEagles: 0, silverLions: 0 }, listings: [] }; +let state = { accounts: [], currentUserId: '', balance: { gjnCents: 0, goldenEagles: 0, silverLions: 0 }, listings: [] }; let activeCat = 'all'; -const initialParams = new URLSearchParams(location.search); -const targetHash = initialParams.get('n') || ''; -if (targetHash) { - document.getElementById('searchInput').value = targetHash; -} -function showToast(msg, ok) { - const el = document.getElementById('toast'); - el.textContent = msg; - el.className = ok ? 'ok' : 'err'; +function applyStaticTexts() { + for (const el of document.querySelectorAll('[data-t]')) el.textContent = t(el.dataset.t); + $('searchInput').placeholder = t('search'); + $('searchInput').value = wantedItem; + $('storeLink').href = WtoUi.pageLink('/store'); + const classSelect = $('classFilter'); + classSelect.appendChild(new Option(t('allClasses'), '')); + for (const [unitClass, key] of Object.entries(CLASS_LABELS)) classSelect.appendChild(new Option(WtoUi.label(key), unitClass)); } async function loadState(userId) { - const q = userId ? '?userId=' + encodeURIComponent(userId) : ''; - const res = await fetch('/trade.gaijin.net/api/state' + q); - state = await res.json(); - renderHeader(); - populateCountries(); + state = await WtoUi.getJson('/trade.gaijin.net/api/state' + (userId ? '?userId=' + encodeURIComponent(userId) : '')); + if (userId && !state.currentUserId) return loadState(''); + if (state.currentUserId) WtoUi.saveAccount(state.currentUserId); + WtoUi.fillAccountSelect($('accountSelect'), state.accounts, state.currentUserId); + $('gjnVal').textContent = WtoUi.gjn(state.balance.gjnCents); + $('goldVal').textContent = WtoUi.num(state.balance.goldenEagles); + $('silverVal').textContent = WtoUi.num(state.balance.silverLions); + renderCountries(); renderGrid(); } -function renderHeader() { - const sel = document.getElementById('accountSelect'); - sel.innerHTML = ''; - for (const acc of state.accounts) { - const opt = document.createElement('option'); - opt.value = acc.userId; - opt.textContent = acc.nick + ' (' + acc.login + ')'; - if (acc.userId === state.currentUserId) opt.selected = true; - sel.appendChild(opt); +function renderCountries() { + const select = $('countryFilter'); + const previous = select.value; + select.innerHTML = ''; + select.appendChild(new Option(t('allCountries'), '')); + for (const country of [...new Set(state.listings.map((l) => l.country).filter(Boolean))]) { + select.appendChild(new Option(WtoUi.label(country), country, false, country === previous)); } - document.getElementById('balGjn').textContent = state.balance.gjn.toLocaleString(); - document.getElementById('balGold').textContent = state.balance.goldenEagles.toLocaleString(); - document.getElementById('balSilver').textContent = state.balance.silverLions.toLocaleString(); } -function populateCountries() { - const sel = document.getElementById('countryFilter'); - const prev = sel.value; - const countries = [...new Set(state.listings.map(l => l.country).filter(Boolean))]; - sel.innerHTML = ''; - for (const c of countries) { - const opt = document.createElement('option'); - opt.value = c; - opt.textContent = COUNTRY_LABELS[c] || c; - if (c === prev) opt.selected = true; - sel.appendChild(opt); - } +function matches(listing) { + const country = $('countryFilter').value; + const unitClass = $('classFilter').value; + const query = $('searchInput').value.trim().toLowerCase(); + if (activeCat !== 'all' && listing.category !== activeCat) return false; + if (country && listing.country !== country) return false; + if (unitClass && listing.unitClass !== unitClass) return false; + return !query || [listing.title.zh, listing.title.en, listing.marketHashName, String(listing.itemdefId)].some((s) => s.toLowerCase().includes(query)); } function renderGrid() { - const grid = document.getElementById('grid'); - const country = document.getElementById('countryFilter').value; - const unitClass = document.getElementById('classFilter').value; - const q = document.getElementById('searchInput').value.trim().toLowerCase(); - - const filtered = state.listings.filter(item => { - if (activeCat !== 'all' && item.category !== activeCat) return false; - if (country && item.country !== country) return false; - if (unitClass && item.unitClass !== unitClass) return false; - if (q) { - const hay = (item.title.zh + ' ' + item.title.en + ' ' + item.marketHashName + ' ' + item.itemdefId).toLowerCase(); - if (!hay.includes(q)) return false; - } - return true; - }); - + const grid = $('grid'); grid.innerHTML = ''; - for (const item of filtered) { - const card = document.createElement('div'); - card.className = 'card' + (targetHash && item.marketHashName === targetHash ? ' highlight' : ''); - const titleColor = item.nameColor ? '#' + item.nameColor : '#e6edf5'; - const badges = []; - if (item.country) badges.push('' + (COUNTRY_LABELS[item.country] || item.country) + ''); - if (item.rank) badges.push('' + item.rank + ' 级'); - badges.push('#' + item.itemdefId + ''); - if (item.couponCount > 0) badges.push('库存持有 x' + item.couponCount + ''); - if (item.alreadyActivated) badges.push('已激活拥有'); - - card.innerHTML = - '
' + - '

' + escapeHtml(item.title.zh) + '

' + - '
' + escapeHtml(item.title.en) + ' · ' + escapeHtml(item.subtitle.zh) + '
' + - '
' + badges.join('') + '
' + - '
' + - '
' + - '' + item.gjnCost + ' GJN' + - '' + - '
'; - const btn = card.querySelector('button'); - if (!state.currentUserId) { - btn.textContent = '请先登录游戏'; - btn.disabled = true; - } else { - btn.textContent = '购买兑换券'; - btn.addEventListener('click', () => buyCoupon(item.itemdefId)); - } - grid.appendChild(card); - } + const listings = state.listings.filter(matches); + if (listings.length === 0) grid.innerHTML = '
' + WtoUi.escapeHtml(t('empty')) + '
'; + for (const listing of listings) grid.appendChild(listingCard(listing)); } -async function buyCoupon(itemdefId) { - const res = await fetch('/trade.gaijin.net/api/buy', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ userId: state.currentUserId, itemdefId, quantity: 1 }) - }); - const data = await res.json(); - showToast(data.message, data.ok); - if (data.ok) await loadState(state.currentUserId); +function listingCard(listing) { + const card = document.createElement('div'); + card.className = 'card' + (wantedItem && listing.marketHashName === wantedItem ? ' highlight' : ''); + const head = document.createElement('div'); + head.className = 'card-head'; + if (listing.category === 'vehicle') head.appendChild(WtoUi.iconImg('vehicle', listing.targetKey, 'vehicle-icon')); + const titles = document.createElement('div'); + titles.innerHTML = '

'; + const title = titles.querySelector('.card-title'); + title.textContent = WtoUi.text(listing.title); + if (listing.nameColor) title.style.setProperty('--quality', '#' + listing.nameColor); + const sub = titles.querySelector('.card-sub'); + if (listing.country) sub.appendChild(WtoUi.iconImg('flag', listing.country, 'flag')); + const parts = []; + if (listing.country) parts.push(WtoUi.label(listing.country)); + if (listing.rank) parts.push(t('rank', { rank: ROMAN[listing.rank] || listing.rank })); + if (!parts.length) parts.push(WtoUi.text(listing.subtitle)); + sub.appendChild(document.createTextNode(parts.join(' · '))); + head.appendChild(titles); + card.appendChild(head); + + const badges = document.createElement('div'); + badges.className = 'badges'; + const badge = (text, owned) => badges.appendChild(Object.assign(document.createElement('span'), { className: 'badge' + (owned ? ' owned' : ''), textContent: text })); + badge('#' + listing.itemdefId, false); + if (listing.couponCount > 0) badge(t('held', { n: listing.couponCount }), true); + if (listing.alreadyActivated) badge(t('activated'), true); + card.appendChild(badges); + + const foot = document.createElement('div'); + foot.className = 'card-foot'; + foot.innerHTML = ''; + foot.querySelector('.price').textContent = WtoUi.gjn(listing.gjnCostCents) + ' GJN'; + const button = foot.querySelector('button'); + button.textContent = state.currentUserId ? t('buy') : t('pickAccount'); + button.disabled = !state.currentUserId; + button.onclick = () => buy(listing.itemdefId); + card.appendChild(foot); + return card; } -function escapeHtml(str) { - return String(str).replace(/[&<>"']/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch])); +async function buy(itemdefId) { + const result = await WtoUi.postJson('/trade.gaijin.net/api/buy', { userId: state.currentUserId, itemdefId, quantity: 1 }); + WtoUi.showNotice($('notice'), WtoUi.text(result.message), result.ok); + if (result.ok) await loadState(state.currentUserId); } -document.getElementById('tabs').addEventListener('click', e => { - const btn = e.target.closest('.tab'); - if (!btn) return; - for (const el of document.querySelectorAll('.tab')) el.classList.remove('active'); - btn.classList.add('active'); - activeCat = btn.dataset.cat; +$('tabs').onclick = (event) => { + const tab = event.target.closest('.tab'); + if (!tab) return; + for (const other of document.querySelectorAll('.tab')) other.classList.toggle('active', other === tab); + activeCat = tab.dataset.cat; renderGrid(); -}); -document.getElementById('accountSelect').addEventListener('change', e => loadState(e.target.value)); -document.getElementById('countryFilter').addEventListener('change', renderGrid); -document.getElementById('classFilter').addEventListener('change', renderGrid); -document.getElementById('searchInput').addEventListener('input', renderGrid); +}; +$('accountSelect').onchange = (event) => loadState(event.target.value); +$('countryFilter').onchange = renderGrid; +$('classFilter').onchange = renderGrid; +$('searchInput').oninput = renderGrid; -loadState(''); +WtoUi.loadLabels().then(() => { + applyStaticTexts(); + return loadState(WtoUi.savedAccount()); +}); diff --git a/packages/local-service/src/inventory/web/index.html b/packages/local-service/src/inventory/web/index.html index 810ea1f..1c72090 100644 --- a/packages/local-service/src/inventory/web/index.html +++ b/packages/local-service/src/inventory/web/index.html @@ -1,49 +1,44 @@ - + - War Thunder Offline — 本地 GJN 交易所 + WTOffline + -
+
-

War Thunder Offline 本地交易所 (GJN Market)

-

购买的兑换券直接存入玩家外部库存并实时推送至游戏(机库 → 道具 → 库存中可直接使用兑换)

+
+
- 前往礼包与金鹰商店 - -
GJN 余额:0 GJN
-
金鹰:0
-
银狮:0
+ + + GJN0 + 0 + 0
-
+
- - - - - - + + + + + +
- - - + + +
+ diff --git a/packages/local-service/src/inventory/web/styles.css b/packages/local-service/src/inventory/web/styles.css index 88f0752..c52fc87 100644 --- a/packages/local-service/src/inventory/web/styles.css +++ b/packages/local-service/src/inventory/web/styles.css @@ -1,109 +1,2 @@ -:root { - --bg: #0f141b; - --panel: #17202b; - --panel-alt: #1e2a38; - --border: #2c3d52; - --text: #e6edf5; - --muted: #93a4b8; - --gjn: #4cd964; - --accent: #3b82f6; -} -* { box-sizing: border-box; } -body { - margin: 0; - font-family: "Segoe UI", "Microsoft YaHei", sans-serif; - background: var(--bg); - color: var(--text); -} -header { - position: sticky; - top: 0; - z-index: 10; - background: rgba(15, 20, 27, 0.96); - border-bottom: 1px solid var(--border); - padding: 14px 24px; - display: flex; - flex-wrap: wrap; - gap: 16px; - align-items: center; - justify-content: space-between; -} -.brand h1 { margin: 0; font-size: 19px; letter-spacing: 0.4px; } -.brand p { margin: 3px 0 0; font-size: 12px; color: var(--muted); } -.wallet { - display: flex; - flex-wrap: wrap; - gap: 12px; - align-items: center; -} -.pill { - background: var(--panel-alt); - border: 1px solid var(--border); - border-radius: 6px; - padding: 6px 12px; - font-size: 13px; -} -.pill strong.gjn { color: var(--gjn); font-size: 15px; } -select, input, button { - font-family: inherit; - font-size: 13px; - border-radius: 6px; - border: 1px solid var(--border); - background: var(--panel); - color: var(--text); - padding: 7px 11px; -} -button { - cursor: pointer; - background: var(--accent); - border-color: #2563eb; - font-weight: 600; -} -button:hover:not(:disabled) { filter: brightness(1.1); } -button:disabled { opacity: 0.45; cursor: not-allowed; } -main { max-width: 1320px; margin: 0 auto; padding: 20px 24px 60px; } -.tabs { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 14px; } -.tab { background: var(--panel); border: 1px solid var(--border); color: var(--muted); } -.tab.active { background: var(--accent); border-color: #2563eb; color: #fff; } -.filters { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 16px; } -.filters input { min-width: 250px; } -#toast { - display: none; - margin-bottom: 14px; - padding: 10px 14px; - border-radius: 6px; - font-size: 13px; - border: 1px solid var(--border); -} -#toast.ok { display: block; background: rgba(22, 163, 74, 0.18); border-color: #16a34a; color: #86efac; } -#toast.err { display: block; background: rgba(239, 68, 68, 0.18); border-color: #ef4444; color: #fca5a5; } -.grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(275px, 1fr)); - gap: 12px; -} -.card { - background: var(--panel); - border: 1px solid var(--border); - border-radius: 8px; - padding: 14px; - display: flex; - flex-direction: column; - justify-content: space-between; - gap: 10px; -} -.card.highlight { border-color: var(--gjn); box-shadow: 0 0 0 1px var(--gjn); } -.card h3 { margin: 0 0 4px; font-size: 15px; } -.meta { font-size: 12px; color: var(--muted); } -.badges { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 6px; } -.badge { font-size: 11px; padding: 2px 7px; border-radius: 4px; background: var(--panel-alt); color: var(--muted); } -.badge.owned { background: rgba(76, 217, 100, 0.16); color: var(--gjn); } -.card-foot { - display: flex; - align-items: center; - justify-content: space-between; - padding-top: 8px; - border-top: 1px solid rgba(255, 255, 255, 0.06); -} -.price { font-weight: 700; font-size: 15px; color: var(--gjn); } -.link-btn { text-decoration: none; color: var(--muted); font-size: 13px; padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; } +/* Marketplace page only; the shared layout is /_wto/ui/common.css. */ +.card-title.quality { color: var(--quality, var(--text)); } diff --git a/packages/local-service/src/items/item-catalogue.ts b/packages/local-service/src/items/item-catalogue.ts index 8014d42..88417d4 100644 --- a/packages/local-service/src/items/item-catalogue.ts +++ b/packages/local-service/src/items/item-catalogue.ts @@ -13,8 +13,11 @@ export const ITEM_TYPES = ['rateBooster', 'personalDiscounts', 'wager', 'mission export class ItemCatalogue { readonly #items: ReadonlyMap; + /** The most pieces one cln_buy_item may ask for (tuning/limits.jsonc). */ + readonly maxPiecesPerPurchase: number; - constructor(definitions: readonly ItemDefinition[]) { + constructor(definitions: readonly ItemDefinition[], maxPiecesPerPurchase: number) { + this.maxPiecesPerPurchase = maxPiecesPerPurchase; const known = new Set(ITEM_TYPES); this.#items = new Map(definitions.filter((item) => known.has(item.type)).map((item) => [item.name, item])); } diff --git a/packages/local-service/src/items/item-purchase.ts b/packages/local-service/src/items/item-purchase.ts index 56b8de6..e3dd7a8 100644 --- a/packages/local-service/src/items/item-purchase.ts +++ b/packages/local-service/src/items/item-purchase.ts @@ -13,11 +13,9 @@ import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts import { isForSale, type ItemCatalogue } from './item-catalogue.ts'; import { grantItem } from './item-grants.ts'; -const MAX_PIECES = 1000; - export function buyItem(profile: BlkBlock, catalogue: ItemCatalogue, name: string, pieces: number, offered: Price, now: ServerTime): RuleOutcome { const item = catalogue.item(name); - if (!item || pieces < 1 || pieces > MAX_PIECES) return refused('BAD_PARAMS'); + if (!item || pieces < 1 || pieces > catalogue.maxPiecesPerPurchase) return refused('BAD_PARAMS'); if (!isForSale(item)) return refused('NOT_AVAILABLE'); const price: Price = { silverLions: item.silverLions * pieces, goldenEagles: item.goldenEagles * pieces }; if (price.silverLions !== offered.silverLions || price.goldenEagles !== offered.goldenEagles) return refused('PRICE_CHANGED'); diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index 63e3088..9dbf23c 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -25,6 +25,10 @@ import { Router } from './server/router.ts'; import { loadOrCreateCredentials } from './server/tls/tls-certificate.ts'; import { StoreService } from './store/store-service.ts'; import { TrafficLog } from './traffic-log/traffic-log.ts'; +import { loadTuning } from './tuning/tuning.ts'; +import { uiLabels } from './game-data/datasets/ui-labels.ts'; +import { webIcons } from './game-data/datasets/web-icons.ts'; +import { WebUiService } from './web-ui/web-ui-service.ts'; export interface LocalServiceOptions { /** The player's game folder; its data packs are read, never written. */ @@ -50,17 +54,20 @@ export async function startLocalService(options: LocalServiceOptions): Promise matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' }); const router = new Router([ - new StoreService(accounts, profiles, research.store), - new MarketplaceService(accounts, profiles, research.inventory, notifyInventoryChanged), + webUi, + new StoreService(accounts, profiles, research.store, tuning.redeemCodes), + new MarketplaceService(accounts, profiles, research.inventory, notifyInventoryChanged, tuning.marketplace.maxPerPurchase), new InventoryService(accounts, profiles, research.inventory), new LoginService(accounts), new CharService(actionTable({ profiles, accounts, research, clans, cloudSettings, notifyInventoryChanged })), diff --git a/packages/local-service/src/profile/new-profile-tuning.ts b/packages/local-service/src/profile/new-profile-tuning.ts new file mode 100644 index 0000000..809072f --- /dev/null +++ b/packages/local-service/src/profile/new-profile-tuning.ts @@ -0,0 +1,17 @@ +/** Typed content of tuning/new-profile.jsonc: a new save's starting money (local verification). */ +import type { TuningReader } from '../tuning/tuning-reader.ts'; +import type { Balance } from './profile-currency.ts'; + +export interface NewProfileTuning { + readonly startingBalance: Balance; +} + +export function readNewProfileTuning(file: TuningReader): NewProfileTuning { + return { + startingBalance: { + silverLions: file.int('silverLions', { min: 0 }), + goldenEagles: file.int('goldenEagles', { min: 0, max: 0x7fffffff }), + gjnCents: file.money('gjn', { min: 0 }), + }, + }; +} diff --git a/packages/local-service/src/profile/new-profile.ts b/packages/local-service/src/profile/new-profile.ts index e694796..79fa5c9 100644 --- a/packages/local-service/src/profile/new-profile.ts +++ b/packages/local-service/src/profile/new-profile.ts @@ -1,20 +1,17 @@ /** * A new account's profile: Gaijin's own new-account template from the player's game files * (config/default_user.blk), plus the offline starting content (starting-content.ts) and the - * starting money. A new account online starts with 150,000 silver lions and 500 golden - * eagles (local verification); the template has none. + * starting money (tuning/new-profile.jsonc; local verification), which the template does not have. */ import type { BlkBlock } from '@wto/blk'; -import { setGjn, setGoldenEagles, setSilverLions, type Balance } from './profile-currency.ts'; +import { setGjnCents, setGoldenEagles, setSilverLions } from './profile-currency.ts'; import { applyStartingContent, type StartingContent } from './starting-content.ts'; -export const STARTING_BALANCE: Balance = { silverLions: 150_000, goldenEagles: 500, gjn: 0 }; - export function newProfile(template: BlkBlock, content: StartingContent): BlkBlock { const profile = structuredClone(template); applyStartingContent(profile, content); - setSilverLions(profile, STARTING_BALANCE.silverLions); - setGoldenEagles(profile, STARTING_BALANCE.goldenEagles); - setGjn(profile, STARTING_BALANCE.gjn); + setSilverLions(profile, content.startingBalance.silverLions); + setGoldenEagles(profile, content.startingBalance.goldenEagles); + setGjnCents(profile, content.startingBalance.gjnCents); return profile; } diff --git a/packages/local-service/src/profile/profile-currency.ts b/packages/local-service/src/profile/profile-currency.ts index 3e4de2e..94af8c6 100644 --- a/packages/local-service/src/profile/profile-currency.ts +++ b/packages/local-service/src/profile/profile-currency.ts @@ -5,8 +5,9 @@ * warpointsPos:i64 silver lions earned in total * warpointsNeg:i64 silver lions spent in total * goldBalance:i golden eagles (read and written as a 32-bit integer, 0x91b570 / 0x91b5cb) - * gjnBalance:i64 GJN balance for the offline store and market (implementation notes; - * ignored by the client when loading a profile) + * gjnBalanceCents:i64 GJN balance in hundredths (GJN prices have two decimals, like the USD + * price they equal); offline store and market only (implementation notes section + * 5.1), the client ignores it * * The silver lion balance is warpointsPos - warpointsNeg; setting it keeps the amount spent * and adjusts the amount earned. @@ -17,20 +18,21 @@ import { intField } from './blk-fields.ts'; const EARNED = 'warpointsPos'; const SPENT = 'warpointsNeg'; const GOLD = 'goldBalance'; -const GJN = 'gjnBalance'; +const GJN = 'gjnBalanceCents'; const MAX_GOLD = 0x7fffffff; export interface Balance { readonly silverLions: number; readonly goldenEagles: number; - readonly gjn: number; + /** GJN in hundredths. */ + readonly gjnCents: number; } export function balanceOf(profile: BlkBlock): Balance { return { silverLions: intField(profile, EARNED) - intField(profile, SPENT), goldenEagles: intField(profile, GOLD), - gjn: intField(profile, GJN), + gjnCents: intField(profile, GJN), }; } @@ -44,7 +46,7 @@ export function setGoldenEagles(profile: BlkBlock, amount: number): void { setParam(profile, GOLD, { type: 'int', value: amount }); } -export function setGjn(profile: BlkBlock, amount: number): void { +export function setGjnCents(profile: BlkBlock, amount: number): void { requireAmount(amount, Number.MAX_SAFE_INTEGER); setParam(profile, GJN, { type: 'int64', value: BigInt(amount) }); } @@ -60,11 +62,16 @@ export function addSilverLions(profile: BlkBlock, amount: number): void { setParam(profile, EARNED, { type: 'int64', value: BigInt(intField(profile, EARNED) + amount) }); } -export function payGjn(profile: BlkBlock, amount: number): void { +export function addGjnCents(profile: BlkBlock, amount: number): void { + requireAmount(amount, Number.MAX_SAFE_INTEGER); + setGjnCents(profile, intField(profile, GJN) + amount); +} + +export function payGjnCents(profile: BlkBlock, amount: number): void { requireAmount(amount, Number.MAX_SAFE_INTEGER); const current = intField(profile, GJN); if (current < amount) throw new RangeError('the player cannot afford this GJN price'); - setGjn(profile, current - amount); + setGjnCents(profile, current - amount); } /** A price in the two in-game currencies. */ diff --git a/packages/local-service/src/profile/profile-trophies-log.ts b/packages/local-service/src/profile/profile-trophies-log.ts index 50b2ca6..8f0ec60 100644 --- a/packages/local-service/src/profile/profile-trophies-log.ts +++ b/packages/local-service/src/profile/profile-trophies-log.ts @@ -9,7 +9,6 @@ import { intField } from './blk-fields.ts'; const TROPHIES = 'trophies'; const USERLOGS = 'userlogs'; -const MAX_USERLOGS = 80; export const EULT_OPEN_TROPHY = 30; export const EULT_BUY_TROPHY = 20; @@ -50,8 +49,11 @@ export function appendUserLog(profile: BlkBlock, entry: NewUserLogEntry): string blocks: [...(entry.bodyBlocks ?? [])], }], }); - if (logs.blocks.length > MAX_USERLOGS) { - logs.blocks.splice(0, logs.blocks.length - MAX_USERLOGS); - } return idHex; } + +/** Keep only the newest `keep` user logs (tuning/limits.jsonc userLogsKept); run on every profile refresh. */ +export function trimUserLogs(profile: BlkBlock, keep: number): void { + const logs = findBlock(profile, USERLOGS); + if (logs && logs.blocks.length > keep) logs.blocks.splice(0, logs.blocks.length - keep); +} diff --git a/packages/local-service/src/profile/starting-content.ts b/packages/local-service/src/profile/starting-content.ts index cd5048f..440f4dc 100644 --- a/packages/local-service/src/profile/starting-content.ts +++ b/packages/local-service/src/profile/starting-content.ts @@ -21,6 +21,7 @@ * Applying it again changes nothing, so it also brings older saves up to date * (profile-upgrades.ts). The starting money is only for new accounts (new-profile.ts). */ +import type { Balance } from './profile-currency.ts'; import type { BlkBlock } from '@wto/blk'; import type { ReserveVehicle } from '../game-data/datasets/reserve-vehicles.ts'; import type { ShopBranches } from '../game-data/datasets/shop-branches.ts'; @@ -36,6 +37,8 @@ const FIRST_RANK = 1; export interface StartingContent { readonly reserveVehicles: readonly ReserveVehicle[]; readonly branches: ShopBranches; + /** Starting money (tuning/new-profile.jsonc). */ + readonly startingBalance: Balance; } export function applyStartingContent(profile: BlkBlock, content: StartingContent): void { diff --git a/packages/local-service/src/profiles-setup.ts b/packages/local-service/src/profiles-setup.ts index a260285..eec4cce 100644 --- a/packages/local-service/src/profiles-setup.ts +++ b/packages/local-service/src/profiles-setup.ts @@ -11,6 +11,7 @@ import { reserveVehicles } from './game-data/datasets/reserve-vehicles.ts'; import { shopBranches } from './game-data/datasets/shop-branches.ts'; import type { GameFiles } from './game-data/game-files.ts'; import { removeExpiredItems } from './items/item-expiry.ts'; +import { trimUserLogs } from './profile/profile-trophies-log.ts'; import { refreshModuleState } from './modifications/module-state.ts'; import { PlayerProfiles } from './profile/player-profiles.ts'; import { profileUpgrades } from './profile/profile-upgrades.ts'; @@ -19,6 +20,7 @@ import type { StartingContent } from './profile/starting-content.ts'; import { loadResearchRules, type ResearchRules } from './research/research-rules.ts'; import { refreshResearchState } from './research/research-state.ts'; import { SaveStore } from './saves/save-store.ts'; +import type { Tuning } from './tuning/tuning.ts'; export interface ProfileServices { readonly profiles: PlayerProfiles; @@ -34,13 +36,15 @@ export function setUpProfiles( dataFolder: string, gameFiles: GameFiles, datasets: DatasetCache, + tuning: Tuning, sync?: ProfileSyncContext, ): ProfileServices { const startingContent: StartingContent = { reserveVehicles: datasets.load(reserveVehicles), branches: datasets.load(shopBranches), + startingBalance: tuning.newProfile.startingBalance, }; - const research = loadResearchRules(datasets); + const research = loadResearchRules(datasets, tuning); const saves = new SaveStore(dataFolder, profileUpgrades(startingContent)); const profiles = new PlayerProfiles(saves, gameFiles, startingContent, (profile, userId) => { const account = sync?.accounts.byUserId(userId); @@ -48,6 +52,7 @@ export function setUpProfiles( refreshResearchState(profile, research); refreshModuleState(profile, research.equipment); removeExpiredItems(profile, serverTimeNow()); + trimUserLogs(profile, tuning.limits.userLogsKept); }); return { profiles, research }; } diff --git a/packages/local-service/src/research/research-rules.ts b/packages/local-service/src/research/research-rules.ts index 7fdafdd..560f211 100644 --- a/packages/local-service/src/research/research-rules.ts +++ b/packages/local-service/src/research/research-rules.ts @@ -24,6 +24,7 @@ import { InventoryCatalogue } from '../inventory/itemdef-catalogue.ts'; import { TrophyCatalogue } from '../inventory/trophy-catalogue.ts'; import { ItemCatalogue } from '../items/item-catalogue.ts'; import { StoreCatalogue } from '../store/store-catalogue.ts'; +import type { Tuning } from '../tuning/tuning.ts'; import { TechTree } from './tech-tree.ts'; export interface ResearchRules { @@ -52,7 +53,7 @@ export interface ResearchRules { readonly clanEconomy: ClanEconomy; } -export function loadResearchRules(datasets: DatasetCache): ResearchRules { +export function loadResearchRules(datasets: DatasetCache, tuning: Tuning): ResearchRules { const vehicles = datasets.load(vehicleCatalogue); const classicItemDefs = datasets.load(itemCatalogue); const localizedUnitNames = datasets.load(unitNames); @@ -66,10 +67,10 @@ export function loadResearchRules(datasets: DatasetCache): ResearchRules { decor: new DecorShop(datasets.load(decorCatalogue)), crew: new CrewSkillCatalogue(datasets.load(crewSkillData)), unlocks: new UnlockShop(datasets.load(unlockPrices)), - items: new ItemCatalogue(classicItemDefs), - store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames), - inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs), - trophies: new TrophyCatalogue(vehicles, classicItemDefs), + items: new ItemCatalogue(classicItemDefs, tuning.limits.itemPiecesPerPurchase), + store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames, tuning.store), + inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs, tuning), + trophies: new TrophyCatalogue(vehicles, classicItemDefs, tuning.trophies), clanEconomy: datasets.load(clanEconomy), }; } diff --git a/packages/local-service/src/save-cli.ts b/packages/local-service/src/save-cli.ts index d77bcb1..e0566a4 100644 --- a/packages/local-service/src/save-cli.ts +++ b/packages/local-service/src/save-cli.ts @@ -14,13 +14,15 @@ import type { ItemDefinition } from './game-data/datasets/item-catalogue.ts'; import { GameFiles } from './game-data/game-files.ts'; import { grantItem } from './items/item-grants.ts'; import { availableSquadronRp, clanMembershipOf, setAvailableSquadronRp } from './profile/profile-clan.ts'; -import { balanceOf, setGjn, setGoldenEagles, setSilverLions } from './profile/profile-currency.ts'; +import { balanceOf, setGjnCents, setGoldenEagles, setSilverLions } from './profile/profile-currency.ts'; import { remainingPremiumDays } from './profile/profile-entitlements.ts'; import { externalInventoryItems, grantExternalItem } from './profile/profile-external-inventory.ts'; import { ownedItems } from './profile/profile-items.ts'; import { freeResearchPoints, setFreeResearchPoints } from './profile/profile-research-points.ts'; import { serverTimeNow } from './profile/server-time.ts'; import { setUpProfiles } from './profiles-setup.ts'; +import { gjnText } from './store/redeem-codes.ts'; +import { loadTuning } from './tuning/tuning.ts'; import type { ResearchRules } from './research/research-rules.ts'; import type { BlkBlock } from '@wto/blk'; @@ -66,10 +68,11 @@ function main(): number { return 1; } - const clans = new ClanStore(values.data); + const tuning = loadTuning(values.data, console.log); + const clans = new ClanStore(values.data, tuning.clans); const gameFiles = new GameFiles(values.game); const datasets = new DatasetCache(values.data, gameFiles, () => {}); - const { profiles, research } = setUpProfiles(values.data, gameFiles, datasets, { accounts, clans }); + const { profiles, research } = setUpProfiles(values.data, gameFiles, datasets, tuning, { accounts, clans }); const edits = parseRequestedEdits(values, research); if (!edits) return 2; @@ -90,11 +93,11 @@ function parseRequestedEdits( ): ParsedEdits | undefined { const silver = optionalAmount(values.silver as string | undefined); const gold = optionalAmount(values.gold as string | undefined); - const gjn = optionalAmount(values.gjn as string | undefined); + const gjn = optionalGjnCents(values.gjn as string | undefined); const freeRp = optionalAmount(values['free-rp'] as string | undefined); const squadronRp = optionalAmount(values['squadron-rp'] as string | undefined); if (silver === null || gold === null || gjn === null || freeRp === null || squadronRp === null) { - console.error('--silver, --gold, --gjn, --free-rp and --squadron-rp take a whole number of 0 or more'); + console.error('--silver, --gold, --free-rp and --squadron-rp take a whole number of 0 or more; --gjn an amount of 0 or more with at most two decimals'); return undefined; } @@ -129,7 +132,7 @@ function parseRequestedEdits( function applyEdits(saved: BlkBlock, edits: ParsedEdits, clanEarned: number, now: bigint): void { if (edits.silver !== undefined) setSilverLions(saved, edits.silver); if (edits.gold !== undefined) setGoldenEagles(saved, edits.gold); - if (edits.gjn !== undefined) setGjn(saved, edits.gjn); + if (edits.gjn !== undefined) setGjnCents(saved, edits.gjn); if (edits.freeRp !== undefined) setFreeResearchPoints(saved, edits.freeRp); if (edits.squadronRp !== undefined) setAvailableSquadronRp(saved, edits.squadronRp, clanEarned); for (const gift of edits.gifts) grantItem(saved, gift.item, gift.pieces, now); @@ -143,13 +146,20 @@ function printSaveSummary(account: Account, profile: BlkBlock, clanEarned: numbe const sqRp = availableSquadronRp(profile, clanEarned); const clanInfo = clanMembershipOf(profile); const clanNote = clanInfo.clanId !== '-1' ? `, clan: ${clanInfo.clanTag} ${clanInfo.clanName}` : ''; - console.log(`${account.login} (${account.userId}): ${balance.silverLions} silver lions, ${balance.goldenEagles} golden eagles, ${balance.gjn} GJN, ${freeResearchPoints(profile)} free research points, ${sqRp} squadron RP${premiumNote}${clanNote}`); + console.log(`${account.login} (${account.userId}): ${balance.silverLions} silver lions, ${balance.goldenEagles} golden eagles, ${gjnText(balance.gjnCents)} GJN, ${freeResearchPoints(profile)} free research points, ${sqRp} squadron RP${premiumNote}${clanNote}`); const items = ownedItems(profile); if (items.length) console.log(`items: ${items.map((item) => `${item.id} x${item.count}`).join(', ')}`); const extItems = externalInventoryItems(profile); if (extItems.length) console.log(`extInventory: ${extItems.map((item) => `#${item.itemDefId} x${item.quantity}`).join(', ')}`); } +/** --gjn: GJN with at most two decimals, returned in hundredths. */ +function optionalGjnCents(text: string | undefined): number | undefined | null { + if (text === undefined) return undefined; + const match = /^(\d+)(?:\.(\d{1,2}))?$/.exec(text); + return match ? Number(match[1]) * 100 + Number((match[2] ?? '').padEnd(2, '0')) : null; +} + function optionalAmount(text: string | undefined): number | undefined | null { if (text === undefined) return undefined; return /^\d+$/.test(text) && Number.isSafeInteger(Number(text)) ? Number(text) : null; diff --git a/packages/local-service/src/store/redeem-codes.ts b/packages/local-service/src/store/redeem-codes.ts index cbe3918..ed0b0c3 100644 --- a/packages/local-service/src/store/redeem-codes.ts +++ b/packages/local-service/src/store/redeem-codes.ts @@ -1,86 +1,102 @@ /** - * Redeem & offline cheat codes (implementation notes section G; implementation notes; - * local verification): - * - PREMIUM-D / WTO-PREM-D / PREM-D / VIP-D (1..3650 days): adds days of Premium Account; - * - WTO-GJN- / GJN- (1..1000000): offline player cheat code adding GJN; - * - WTO-STARTER (once per save): grants 7 days of Premium Account, 1,000 Golden Eagles and 100 GJN. + * Redeem codes and offline cheat codes (implementation notes section G; implementation notes section + * 5.3; local verification). Which codes exist and what they grant is tuning + * (tuning/redeem-codes.jsonc); the texts shown to the player are built from those values. */ import type { BlkBlock } from '@wto/blk'; import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; -import { addGoldenEagles, balanceOf, setGjn } from '../profile/profile-currency.ts'; +import { addGjnCents, addGoldenEagles, addSilverLions } from '../profile/profile-currency.ts'; import { extendPremiumAccount, hasEntitlement, recordEntitlementPurchase } from '../profile/profile-entitlements.ts'; - -const STARTER_ENTITLEMENT = 'wto_redeem_starter'; +import type { CodeReward, PatternCodeTuning, RedeemTuning } from './redeem-tuning.ts'; export type RedeemOutcome = | { readonly ok: true; readonly message: LocalizedText } | { readonly ok: false; readonly reason: 'INVALID_CODE' | 'ALREADY_REDEEMED'; readonly message: LocalizedText }; -export function redeemStoreCode(profile: BlkBlock, rawCode: string, nowFiletime: bigint): RedeemOutcome { +export function redeemStoreCode(profile: BlkBlock, rawCode: string, nowFiletime: bigint, tuning: RedeemTuning): RedeemOutcome { const code = rawCode.trim().toUpperCase(); - if (!code) { - return { ok: false, reason: 'INVALID_CODE', message: { en: 'Enter a redeem code.', zh: '请输入兑换码。' } }; - } + if (!code) return { ok: false, reason: 'INVALID_CODE', message: { en: 'Enter a redeem code.', zh: '请输入兑换码。' } }; - if (code === 'WTO-STARTER') return redeemStarterCode(profile, nowFiletime); + const fixed = tuning.fixedCodes.get(code); + if (fixed) return redeemFixedCode(profile, code, fixed, nowFiletime); - const premiumMatch = /^(?:PREMIUM|WTO-PREM|PREM|VIP)-(\d{1,4})D$/.exec(code); - if (premiumMatch) { - const days = Number(premiumMatch[1]); - if (days >= 1 && days <= 3_650) { - extendPremiumAccount(profile, days, nowFiletime); - return { - ok: true, - message: { - en: `Redeemed ${code}: +${days} days of Premium Account.`, - zh: `兑换成功:高级账户增加 ${days} 天。`, - }, - }; - } - } + const days = patternAmount(code, tuning.premiumDays, 'D'); + if (days !== undefined) return grant(profile, code, { ...NOTHING, premiumDays: days }, nowFiletime); - const gjnMatch = /^(?:WTO-GJN|GJN)-(\d{1,7})$/.exec(code); - if (gjnMatch) { - const amount = Number(gjnMatch[1]); - if (amount >= 1 && amount <= 1_000_000) { - setGjn(profile, balanceOf(profile).gjn + amount); - return { - ok: true, - message: { - en: `Redeemed ${code}: +${amount.toLocaleString('en-US')} GJN.`, - zh: `兑换成功:GJN 增加 ${amount.toLocaleString('en-US')}。`, - }, - }; - } - } + const gjn = patternAmount(code, tuning.gjn, ''); + if (gjn !== undefined) return grant(profile, code, { ...NOTHING, gjnCents: gjn * 100 }, nowFiletime); + const examples = [...tuning.premiumDays.examples, ...tuning.gjn.examples, ...tuning.fixedCodes.keys()]; return { ok: false, reason: 'INVALID_CODE', - message: { - en: 'Unknown redeem code. Examples: PREMIUM-7D, PREMIUM-30D, WTO-PREM-90D, WTO-GJN-100, WTO-STARTER.', - zh: '无效的兑换码。可用示例:PREMIUM-7D、PREMIUM-30D、WTO-PREM-90D、WTO-GJN-100、WTO-STARTER。', - }, + message: { en: `Unknown redeem code. Examples: ${examples.join(', ')}.`, zh: `无效的兑换码。可用示例:${examples.join('、')}。` }, }; } -function redeemStarterCode(profile: BlkBlock, nowFiletime: bigint): RedeemOutcome { - if (hasEntitlement(profile, STARTER_ENTITLEMENT, nowFiletime)) { - return { - ok: false, - reason: 'ALREADY_REDEEMED', - message: { en: 'This starter code has already been redeemed on this save.', zh: '当前存档已使用过该新手礼包兑换码。' }, - }; - } - recordEntitlementPurchase(profile, STARTER_ENTITLEMENT); - extendPremiumAccount(profile, 7, nowFiletime); - addGoldenEagles(profile, 1_000); - setGjn(profile, balanceOf(profile).gjn + 100); - return { - ok: true, - message: { - en: 'Redeemed WTO-STARTER: +7d Premium Account, +1,000 Golden Eagles, +100 GJN.', - zh: '兑换成功:高级账户 +7 天、金鹰 +1,000、GJN +100。', +/** One line per kind of code, for the store page. */ +export function describeRedeemCodes(tuning: RedeemTuning): LocalizedText[] { + const premiumForm = `${tuning.premiumDays.prefixes[0]}-D`; + const gjnForm = `${tuning.gjn.prefixes[0]}-`; + return [ + { + zh: `高级账户天数:${tuning.premiumDays.examples.join('、')}(或任意 ${premiumForm},最多 ${tuning.premiumDays.max} 天)`, + en: `Premium Account days: ${tuning.premiumDays.examples.join(', ')} (or any ${premiumForm}, up to ${tuning.premiumDays.max} days)`, }, - }; + { + zh: `GJN 充值作弊码:${tuning.gjn.examples.join('、')}(或任意 ${gjnForm},最多 ${tuning.gjn.max.toLocaleString('en-US')})`, + en: `GJN cheat code: ${tuning.gjn.examples.join(', ')} (or any ${gjnForm}, up to ${tuning.gjn.max.toLocaleString('en-US')})`, + }, + ...[...tuning.fixedCodes].map(([code, reward]) => { + const text = rewardText(reward); + return { zh: `${code}(每个存档一次):${text.zh}`, en: `${code} (once per save): ${text.en}` }; + }), + ]; +} + +const NOTHING: CodeReward = { premiumDays: 0, goldenEagles: 0, silverLions: 0, gjnCents: 0 }; + +/** The amount in "-" when the code has that form and the amount is in range. */ +function patternAmount(code: string, pattern: PatternCodeTuning, suffix: string): number | undefined { + for (const prefix of pattern.prefixes) { + if (!code.startsWith(`${prefix}-`) || !code.endsWith(suffix)) continue; + const digits = code.slice(prefix.length + 1, code.length - suffix.length); + if (!/^\d+$/.test(digits)) continue; + const amount = Number(digits); + if (amount >= 1 && amount <= pattern.max) return amount; + } + return undefined; +} + +function redeemFixedCode(profile: BlkBlock, code: string, reward: CodeReward, nowFiletime: bigint): RedeemOutcome { + const marker = `wto_redeem_${code.toLowerCase().replace(/-/g, '_')}`; + if (hasEntitlement(profile, marker, nowFiletime)) { + return { ok: false, reason: 'ALREADY_REDEEMED', message: { en: `${code} has already been redeemed on this save.`, zh: `当前存档已经用过 ${code}。` } }; + } + recordEntitlementPurchase(profile, marker); + return grant(profile, code, reward, nowFiletime); +} + +function grant(profile: BlkBlock, code: string, reward: CodeReward, nowFiletime: bigint): RedeemOutcome { + if (reward.premiumDays) extendPremiumAccount(profile, reward.premiumDays, nowFiletime); + if (reward.goldenEagles) addGoldenEagles(profile, reward.goldenEagles); + if (reward.silverLions) addSilverLions(profile, reward.silverLions); + if (reward.gjnCents) addGjnCents(profile, reward.gjnCents); + const text = rewardText(reward); + return { ok: true, message: { en: `Redeemed ${code}: ${text.en}.`, zh: `兑换成功(${code}):${text.zh}。` } }; +} + +function rewardText(reward: CodeReward): LocalizedText { + const parts: LocalizedText[] = []; + const n = (value: number) => value.toLocaleString('en-US'); + if (reward.premiumDays) parts.push({ zh: `高级账户 +${reward.premiumDays} 天`, en: `+${reward.premiumDays} days of Premium Account` }); + if (reward.goldenEagles) parts.push({ zh: `金鹰 +${n(reward.goldenEagles)}`, en: `+${n(reward.goldenEagles)} Golden Eagles` }); + if (reward.silverLions) parts.push({ zh: `银狮 +${n(reward.silverLions)}`, en: `+${n(reward.silverLions)} Silver Lions` }); + if (reward.gjnCents) parts.push({ zh: `GJN +${gjnText(reward.gjnCents)}`, en: `+${gjnText(reward.gjnCents)} GJN` }); + return { zh: parts.map((part) => part.zh).join('、'), en: parts.map((part) => part.en).join(', ') }; +} + +/** A GJN amount in hundredths as the player reads it: 100 -> "1", 1299 -> "12.99". */ +export function gjnText(cents: number): string { + return (cents / 100).toLocaleString('en-US', { minimumFractionDigits: cents % 100 ? 2 : 0, maximumFractionDigits: 2 }); } diff --git a/packages/local-service/src/store/redeem-tuning.ts b/packages/local-service/src/store/redeem-tuning.ts new file mode 100644 index 0000000..d67fe9e --- /dev/null +++ b/packages/local-service/src/store/redeem-tuning.ts @@ -0,0 +1,48 @@ +/** Typed content of tuning/redeem-codes.jsonc (implementation notes; local verification). */ +import type { TuningReader } from '../tuning/tuning-reader.ts'; + +export interface PatternCodeTuning { + readonly prefixes: readonly string[]; + readonly max: number; + readonly examples: readonly string[]; +} + +/** What a code grants; every amount is 0 or more. */ +export interface CodeReward { + readonly premiumDays: number; + readonly goldenEagles: number; + readonly silverLions: number; + /** GJN in hundredths. */ + readonly gjnCents: number; +} + +export interface RedeemTuning { + readonly premiumDays: PatternCodeTuning; + readonly gjn: PatternCodeTuning; + /** Upper-case code -> reward; each can be used once per save. */ + readonly fixedCodes: ReadonlyMap; +} + +export function readRedeemTuning(file: TuningReader): RedeemTuning { + const premium = file.object('premiumDays'); + const gjn = file.object('gjn'); + return { + premiumDays: { prefixes: upper(premium.stringList('prefixes')), max: premium.int('maxDays', { min: 1 }), examples: premium.stringList('examples') }, + gjn: { prefixes: upper(gjn.stringList('prefixes')), max: gjn.int('maxAmount', { min: 1 }), examples: gjn.stringList('examples') }, + fixedCodes: new Map([...file.table('fixedCodes', readReward)].map(([code, reward]) => [code.toUpperCase(), reward])), + }; +} + +function readReward(entry: TuningReader): CodeReward { + const amount = (key: string) => (entry.has(key) ? entry.int(key, { min: 0 }) : 0); + return { + premiumDays: amount('premiumDays'), + goldenEagles: amount('goldenEagles'), + silverLions: amount('silverLions'), + gjnCents: entry.has('gjn') ? entry.money('gjn', { min: 0 }) : 0, + }; +} + +function upper(values: readonly string[]): string[] { + return values.map((value) => value.toUpperCase()); +} diff --git a/packages/local-service/src/store/store-catalogue.ts b/packages/local-service/src/store/store-catalogue.ts index a70928e..afca538 100644 --- a/packages/local-service/src/store/store-catalogue.ts +++ b/packages/local-service/src/store/store-catalogue.ts @@ -1,7 +1,8 @@ /** * Local store catalogue: Golden Eagles packs, Silver Lions * packs, Premium Account durations (both Golden Eagles and GJN), and one vehicle pack per - * gift vehicle in the tech tree. + * gift vehicle in the tech tree. What is sold and for how much is tuning (tuning/store.jsonc); + * which vehicles get a pack follows the game data (isPackVehicle). * * Pure domain catalogue: protocol-layer DataBlock serialization for `cln_get_entitlements_price_ex` * lives in `char/actions/store-actions.ts`. @@ -9,6 +10,7 @@ import type { StoreBundleGuids } from '../game-data/datasets/store-bundles.ts'; import type { LocalizedText, UnitNamesMap } from '../game-data/datasets/unit-names.ts'; import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; +import { vehiclePackContent, type StoreTuning } from './store-tuning.ts'; export type StoreProductKind = 'eagles' | 'warpoints' | 'premium-gold' | 'premium-gjn' | 'vehicle-pack'; @@ -22,7 +24,7 @@ export interface StoreProduct { /** Price in Golden Eagles (in-game purchase via cln_buy_entitlement). */ readonly goldCost?: number; /** Price in GJN (onlinePurchase via item_purchase.php or the local web store). */ - readonly gjnCost?: number; + readonly gjnCostCents?: number; /** Golden Eagles granted on purchase. */ readonly goldIncome?: number; /** Silver Lions granted on purchase. */ @@ -33,69 +35,17 @@ export interface StoreProduct { readonly vehicle?: CatalogueVehicle; } -const EAGLES_PACKS: ReadonlyArray<{ readonly id: string; readonly gold: number; readonly gjn: number }> = [ - { id: 'eagles150', gold: 150, gjn: 1 }, - { id: 'eagles500', gold: 500, gjn: 3 }, - { id: 'eagles1000', gold: 1_000, gjn: 6 }, - { id: 'eagles2500', gold: 2_500, gjn: 14 }, - { id: 'eagles5000', gold: 5_000, gjn: 25 }, - { id: 'eagles10000', gold: 10_000, gjn: 50 }, - { id: 'eagles15000', gold: 15_000, gjn: 72 }, - { id: 'eagles20000', gold: 20_000, gjn: 95 }, - { id: 'eagles25000', gold: 25_000, gjn: 115 }, -]; - -const SILVER_LIONS_PACKS: ReadonlyArray<{ readonly id: string; readonly silver: number; readonly goldCost: number }> = [ - { id: 'warpoints1k', silver: 1_000, goldCost: 3 }, - { id: 'warpoints10k', silver: 10_000, goldCost: 30 }, - { id: 'warpoints50k', silver: 50_000, goldCost: 120 }, - { id: 'warpoints120k', silver: 120_000, goldCost: 300 }, - { id: 'warpoints630k', silver: 630_000, goldCost: 1_500 }, - { id: 'warpoints1300k', silver: 1_300_000, goldCost: 3_000 }, -]; - -const PREMIUM_GOLD_TIERS: ReadonlyArray<{ readonly id: string; readonly days: number; readonly goldCost: number }> = [ - { id: 'prem_1d', days: 1, goldCost: 190 }, - { id: 'prem_7d', days: 7, goldCost: 690 }, - { id: 'prem_15d', days: 15, goldCost: 1_190 }, - { id: 'prem_30d', days: 30, goldCost: 1_900 }, - { id: 'prem_90d', days: 90, goldCost: 4_900 }, - { id: 'prem_365d', days: 365, goldCost: 14_900 }, -]; - -const PREMIUM_GJN_TIERS: ReadonlyArray<{ readonly id: string; readonly days: number; readonly gjn: number }> = [ - { id: 'wto_prem_20d', days: 20, gjn: 8 }, - { id: 'wto_prem_60d', days: 60, gjn: 20 }, - { id: 'wto_prem_180d', days: 180, gjn: 40 }, -]; - -interface PackTier { - readonly gjn: number; - readonly bonusGold: number; - readonly bonusDays: number; -} - -function packTierForRank(rank: number): PackTier { - if (rank <= 2) return { gjn: 15, bonusGold: 1_000, bonusDays: 7 }; - if (rank === 3) return { gjn: 25, bonusGold: 1_000, bonusDays: 7 }; - if (rank === 4) return { gjn: 35, bonusGold: 1_000, bonusDays: 7 }; - if (rank === 5) return { gjn: 50, bonusGold: 2_000, bonusDays: 15 }; - if (rank === 6) return { gjn: 60, bonusGold: 2_000, bonusDays: 15 }; - if (rank === 7) return { gjn: 70, bonusGold: 2_500, bonusDays: 20 }; - return { gjn: 75, bonusGold: 3_000, bonusDays: 30 }; -} - export class StoreCatalogue { readonly #byId = new Map(); readonly #byGuid = new Map(); - constructor(vehicles: readonly CatalogueVehicle[], bundleGuids: StoreBundleGuids, names: UnitNamesMap) { + constructor(vehicles: readonly CatalogueVehicle[], bundleGuids: StoreBundleGuids, names: UnitNamesMap, tuning: StoreTuning) { const products: StoreProduct[] = [ - ...buildEaglesProducts(bundleGuids), - ...buildSilverProducts(), - ...buildPremiumGoldProducts(), - ...buildPremiumGjnProducts(bundleGuids), - ...buildVehiclePackProducts(vehicles, names), + ...buildEaglesProducts(tuning, bundleGuids), + ...buildSilverProducts(tuning), + ...buildPremiumGoldProducts(tuning), + ...buildPremiumGjnProducts(tuning, bundleGuids), + ...buildVehiclePackProducts(tuning, vehicles, names), ]; for (const product of products) { @@ -117,45 +67,45 @@ export class StoreCatalogue { } } -function buildEaglesProducts(bundleGuids: StoreBundleGuids): StoreProduct[] { - return EAGLES_PACKS.map((pack) => { +function buildEaglesProducts(tuning: StoreTuning, bundleGuids: StoreBundleGuids): StoreProduct[] { + return tuning.goldenEaglePacks.map((pack) => { const guid = bundleGuids[pack.id]; return { id: pack.id, kind: 'eagles', chapter: 'eagles', - title: { en: `${pack.gold.toLocaleString('en-US')} Golden Eagles`, zh: `${pack.gold.toLocaleString('en-US')} 金鹰` }, + title: { en: `${pack.goldenEagles.toLocaleString('en-US')} Golden Eagles`, zh: `${pack.goldenEagles.toLocaleString('en-US')} 金鹰` }, ...(guid ? { guid } : {}), - gjnCost: pack.gjn, - goldIncome: pack.gold, + gjnCostCents: pack.gjnCents, + goldIncome: pack.goldenEagles, }; }); } -function buildSilverProducts(): StoreProduct[] { - return SILVER_LIONS_PACKS.map((pack) => ({ +function buildSilverProducts(tuning: StoreTuning): StoreProduct[] { + return tuning.silverLionPacks.map((pack) => ({ id: pack.id, kind: 'warpoints', chapter: 'warpoints', - title: { en: `${pack.silver.toLocaleString('en-US')} Silver Lions`, zh: `${pack.silver.toLocaleString('en-US')} 银狮` }, - goldCost: pack.goldCost, - silverIncome: pack.silver, + title: { en: `${pack.silverLions.toLocaleString('en-US')} Silver Lions`, zh: `${pack.silverLions.toLocaleString('en-US')} 银狮` }, + goldCost: pack.goldenEagles, + silverIncome: pack.silverLions, })); } -function buildPremiumGoldProducts(): StoreProduct[] { - return PREMIUM_GOLD_TIERS.map((tier) => ({ +function buildPremiumGoldProducts(tuning: StoreTuning): StoreProduct[] { + return tuning.premiumForGoldenEagles.map((tier) => ({ id: tier.id, kind: 'premium-gold', chapter: 'premium', title: { en: `Premium Account (${tier.days}d)`, zh: `高级账户(${tier.days} 天)` }, - goldCost: tier.goldCost, + goldCost: tier.price, premiumDays: tier.days, })); } -function buildPremiumGjnProducts(bundleGuids: StoreBundleGuids): StoreProduct[] { - return PREMIUM_GJN_TIERS.map((tier) => { +function buildPremiumGjnProducts(tuning: StoreTuning, bundleGuids: StoreBundleGuids): StoreProduct[] { + return tuning.premiumForGjn.map((tier) => { const guid = bundleGuids[tier.id]; return { id: tier.id, @@ -163,24 +113,24 @@ function buildPremiumGjnProducts(bundleGuids: StoreBundleGuids): StoreProduct[] chapter: 'premium', title: { en: `Premium Account (${tier.days}d)`, zh: `高级账户(${tier.days} 天)` }, ...(guid ? { guid } : {}), - gjnCost: tier.gjn, + gjnCostCents: tier.price, premiumDays: tier.days, }; }); } -function buildVehiclePackProducts(vehicles: readonly CatalogueVehicle[], names: UnitNamesMap): StoreProduct[] { +function buildVehiclePackProducts(tuning: StoreTuning, vehicles: readonly CatalogueVehicle[], names: UnitNamesMap): StoreProduct[] { return vehicles.filter(isPackVehicle).map((vehicle) => { - const tier = packTierForRank(vehicle.rank); + const content = vehiclePackContent(tuning, vehicle.name, vehicle.rank); const unitLabel = names[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name }; return { id: `wto_pack_${vehicle.name}`, kind: 'vehicle-pack', chapter: 'bonuses', title: { en: `${unitLabel.en} Pack`, zh: `${unitLabel.zh} 礼包` }, - gjnCost: tier.gjn, - goldIncome: tier.bonusGold, - premiumDays: tier.bonusDays, + gjnCostCents: content.gjnCents, + ...(content.goldenEagles ? { goldIncome: content.goldenEagles } : {}), + ...(content.premiumDays ? { premiumDays: content.premiumDays } : {}), vehicle, }; }); diff --git a/packages/local-service/src/store/store-purchase.ts b/packages/local-service/src/store/store-purchase.ts index 20db566..45be408 100644 --- a/packages/local-service/src/store/store-purchase.ts +++ b/packages/local-service/src/store/store-purchase.ts @@ -6,7 +6,7 @@ * bought through item_purchase.php or the local web store. */ import type { BlkBlock } from '@wto/blk'; -import { addGoldenEagles, addSilverLions, balanceOf, canAfford, pay, payGjn } from '../profile/profile-currency.ts'; +import { addGoldenEagles, addSilverLions, balanceOf, canAfford, pay, payGjnCents } from '../profile/profile-currency.ts'; import { extendPremiumAccount, hasEntitlement, recordEntitlementPurchase } from '../profile/profile-entitlements.ts'; import { addOwnedVehicle, ownsVehicle } from '../profile/profile-hangar.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; @@ -37,7 +37,7 @@ export type GjnPurchaseOutcome = | { readonly ok: false; readonly reason: 'NOT_FOUND' | 'ALREADY_BOUGHT' | 'NOT_ENOUGH_GJN' }; export function canBuyGjnProduct(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): boolean { - if (product.gjnCost === undefined) return false; + if (product.gjnCostCents === undefined) return false; if (product.kind === 'vehicle-pack' && product.vehicle) { return !ownsVehicle(profile, product.vehicle.name) && !hasEntitlement(profile, product.id, nowFiletime); } @@ -45,15 +45,15 @@ export function canBuyGjnProduct(profile: BlkBlock, product: StoreProduct, nowFi } export function buyGjnProduct(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): GjnPurchaseOutcome { - if (product.gjnCost === undefined) return { ok: false, reason: 'NOT_FOUND' }; + if (product.gjnCostCents === undefined) return { ok: false, reason: 'NOT_FOUND' }; if (product.kind === 'vehicle-pack' && product.vehicle) { if (ownsVehicle(profile, product.vehicle.name) || hasEntitlement(profile, product.id, nowFiletime)) { return { ok: false, reason: 'ALREADY_BOUGHT' }; } } - if (balanceOf(profile).gjn < product.gjnCost) return { ok: false, reason: 'NOT_ENOUGH_GJN' }; + if (balanceOf(profile).gjnCents < product.gjnCostCents) return { ok: false, reason: 'NOT_ENOUGH_GJN' }; - payGjn(profile, product.gjnCost); + payGjnCents(profile, product.gjnCostCents); grantProductRewards(profile, product, nowFiletime); return { ok: true }; } diff --git a/packages/local-service/src/store/store-service.ts b/packages/local-service/src/store/store-service.ts index 4f70e54..60cce2b 100644 --- a/packages/local-service/src/store/store-service.ts +++ b/packages/local-service/src/store/store-service.ts @@ -1,225 +1,48 @@ /** - * Store service (implementation notes; implementation notes): - * 1. Native yuplay2 store API on api.gaijinent.com: - * - POST /item_info.php (multi-guid and single-guid item pricing in GJN) - * - POST /item_purchase.php (pay=gjn purchase from in-game modals) - * - POST /redeem_code.php (ActivateAction redeem code) - * 2. Local web store at /store and /store/api/* for browsing vehicle packs, viewing GJN - * balance, purchasing with GJN, and redeeming codes. + * Store service (implementation notes; implementation notes): routes the game's + * yuplay2 store requests (yuplay-store-api.ts) and the local store page (/store: its files + * from web/, its JSON requests in store-web-api.ts). */ -import type { Account, AccountStore } from '../accounts/account-store.ts'; +import type { AccountStore } from '../accounts/account-store.ts'; import { redactLoginForm } from '../login/form-redaction.ts'; -import { userIdFromJwt, userIdFromToken } from '../login/session-credentials.ts'; -import { yuplayAnswer } from '../login/yuplay-answer.ts'; import type { PlayerProfiles } from '../profile/player-profiles.ts'; -import { balanceOf } from '../profile/profile-currency.ts'; -import { remainingPremiumDays } from '../profile/profile-entitlements.ts'; -import { serverTimeNow } from '../profile/server-time.ts'; import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts'; -import { - createStaticWebSite, - jsonResponse, - parseJsonBody, - requireWebActionAccount, - selectWebViewAccount, -} from '../web-ui/web-helpers.ts'; -import { redeemStoreCode, type RedeemOutcome } from './redeem-codes.ts'; -import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts'; -import { buyGjnProduct, canBuyGjnProduct, type GjnPurchaseOutcome } from './store-purchase.ts'; +import { createStaticWebSite, notFound } from '../web-ui/web-helpers.ts'; +import type { RedeemTuning } from './redeem-tuning.ts'; +import type { StoreCatalogue } from './store-catalogue.ts'; +import { StoreWebApi } from './store-web-api.ts'; +import { YUPLAY_STORE_PATHS, YuplayStoreApi } from './yuplay-store-api.ts'; -const STORE_API_PATHS = new Set(['/item_info.php', '/item_purchase.php', '/redeem_code.php']); -const STORE_WEB = createStaticWebSite(new URL('./web/', import.meta.url)); +const PAGE_PREFIX = '/store'; +const STORE_PAGE = createStaticWebSite(new URL('./web/', import.meta.url)); +const STORE_API_HOSTS = new Set(['api.gaijinent.com', 'store.gaijin.net']); export class StoreService implements Service { readonly name = 'store'; - readonly #accounts: AccountStore; - readonly #profiles: PlayerProfiles; - readonly #catalogue: StoreCatalogue; + readonly #yuplay: YuplayStoreApi; + readonly #web: StoreWebApi; - constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue) { - this.#accounts = accounts; - this.#profiles = profiles; - this.#catalogue = catalogue; + constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning) { + this.#yuplay = new YuplayStoreApi(accounts, profiles, catalogue, redeemCodes); + this.#web = new StoreWebApi(accounts, profiles, catalogue, redeemCodes); } accepts(request: ServiceRequest): boolean { - if (request.path === '/store' || request.path.startsWith('/store/')) return true; - if (!STORE_API_PATHS.has(request.path)) return false; - return request.originalHost === undefined || request.originalHost === 'api.gaijinent.com' || request.originalHost === 'store.gaijin.net'; + if (isPagePath(request.path)) return true; + return YUPLAY_STORE_PATHS.has(request.path) && (request.originalHost === undefined || STORE_API_HOSTS.has(request.originalHost)); } handle(request: ServiceRequest): ServiceResponse { - if (request.path === '/store' || request.path.startsWith('/store/')) { - return this.#handleWebRequest(request); + if (isPagePath(request.path)) { + const subPath = request.path.slice(PAGE_PREFIX.length) || '/'; + return this.#web.handle(subPath, request) ?? STORE_PAGE.serve(subPath, 'store page') ?? notFound(`store page 404: ${subPath}`); } - const redacted = redactLoginForm(request.body); - const apiResponse = request.method !== 'POST' - ? yuplayAnswer('ERROR', {}, `${request.method} ${request.path} not supported`) - : request.path === '/item_info.php' - ? this.#itemInfo(request) - : request.path === '/item_purchase.php' - ? this.#itemPurchase(request) - : this.#redeemCode(request); - return { ...apiResponse, logNotes: { ...apiResponse.logNotes, redactedRequestBody: redacted, requestText: redacted } }; - } - - #handleWebRequest(request: ServiceRequest): ServiceResponse { - const subPath = request.path.slice('/store'.length) || '/'; - if (subPath === '/api/state' && request.method === 'GET') return this.#webState(request); - if (subPath === '/api/buy' && request.method === 'POST') return this.#webBuy(request); - if (subPath === '/api/redeem' && request.method === 'POST') return this.#webRedeem(request); - return STORE_WEB.serve(subPath, 'store web') - ?? { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' }, body: 'Not found', logNotes: { summary: `store 404: ${subPath}` } }; - } - - #itemInfo(request: ServiceRequest): ServiceResponse { - const form = new URLSearchParams(request.body.toString('utf8')); - const guids = [...form.getAll('guids[]'), ...form.getAll('guids'), ...form.getAll('guid')].filter(Boolean); - const account = this.#accountFromForm(form); - const profile = account ? this.#profiles.profileOf(account.userId) : undefined; - const now = serverTimeNow(); - - const items: Record = {}; - let numericId = 1; - for (const rawGuid of guids) { - const product = this.#catalogue.byGuid(rawGuid); - if (!product || product.gjnCost === undefined) continue; - const canBuy = profile ? canBuyGjnProduct(profile, product, now) : true; - items[rawGuid] = { - item_id: numericId++, - shop_price: product.gjnCost, - price_usd: product.gjnCost, - discount_mul: 1.0, - discount_till: 0, - title: product.title.en, - url: '', - short_desc: product.title.en, - shop_price_curr: 'gjn', - multi_purch: product.kind !== 'vehicle-pack', - can_be_bought: canBuy, - }; - } - return yuplayAnswer('OK', { items }, `item_info (${Object.keys(items).length}/${guids.length} items)`); - } - - #itemPurchase(request: ServiceRequest): ServiceResponse { - const form = new URLSearchParams(request.body.toString('utf8')); - const account = this.#accountFromForm(form); - if (!account) return yuplayAnswer('LOGINERROR', {}, 'item_purchase: unknown token'); - - const payMethod = (form.get('pay') ?? 'gjn').toLowerCase(); - if (payMethod !== 'gjn') return yuplayAnswer('BADPAYMENT', {}, `item_purchase: unsupported pay=${payMethod}`); - - const guid = form.get('guid') ?? ''; - const product = this.#catalogue.byGuid(guid); - if (!product) return yuplayAnswer('NOTFOUND', {}, `item_purchase: unknown guid ${guid}`); - - let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' }; - const now = serverTimeNow(); - this.#profiles.updateWhen(account.userId, (saved) => { - outcome = buyGjnProduct(saved, product, now); - return outcome.ok; - }); - if (outcome.ok) return yuplayAnswer('OK', {}, `item_purchase ${product.id} (${product.gjnCost} GJN)`); - if (outcome.reason === 'NOT_ENOUGH_GJN') return yuplayAnswer('NOMONEY', {}, `item_purchase ${product.id}: insufficient GJN`); - if (outcome.reason === 'ALREADY_BOUGHT') return yuplayAnswer('ALREADY', {}, `item_purchase ${product.id}: already owned`); - return yuplayAnswer('NOTFOUND', {}, `item_purchase ${product.id}: not available`); - } - - #redeemCode(request: ServiceRequest): ServiceResponse { - const form = new URLSearchParams(request.body.toString('utf8')); - const account = this.#accountFromForm(form); - if (!account) return yuplayAnswer('LOGINERROR', {}, 'redeem_code: unknown token'); - - const code = form.get('code') ?? ''; - let outcome: RedeemOutcome = { ok: false, reason: 'INVALID_CODE', message: { en: '', zh: '' } }; - const now = serverTimeNow(); - this.#profiles.updateWhen(account.userId, (saved) => { - outcome = redeemStoreCode(saved, code, now); - return outcome.ok; - }); - if (outcome.ok) return yuplayAnswer('OK', {}, `redeem_code ${code} -> OK`); - return yuplayAnswer(outcome.reason === 'ALREADY_REDEEMED' ? 'ALREADY' : 'NOTFOUND', {}, `redeem_code ${code} -> ${outcome.reason}`); - } - - #webState(request: ServiceRequest): ServiceResponse { - const account = selectWebViewAccount(this.#accounts, request.query.get('userId')); - const now = serverTimeNow(); - const profile = account ? this.#profiles.profileOf(account.userId) : undefined; - const balance = profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjn: 0 }; - const premiumDays = profile ? remainingPremiumDays(profile, now) : 0; - - const products = this.#catalogue.allProducts() - .filter((product) => product.gjnCost !== undefined) - .map((product) => toWebProduct(product, profile ? !canBuyGjnProduct(profile, product, now) : false)); - - return jsonResponse({ - accounts: this.#accounts.all().map((entry) => ({ userId: entry.userId, login: entry.login, nick: entry.nick })), - activeUserId: account?.userId ?? '', - balance, - premiumDays, - products, - }, 'store web state'); - } - - #webBuy(request: ServiceRequest): ServiceResponse { - const body = parseJsonBody(request.body); - const account = requireWebActionAccount(this.#accounts, body.userId); - const productId = typeof body.productId === 'string' ? body.productId : ''; - const product = this.#catalogue.byId(productId); - if (!account || !product || product.gjnCost === undefined) { - return jsonResponse({ ok: false, message: '未找到指定账号或商品。' }, 'store web buy: invalid request'); - } - - let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' }; - const now = serverTimeNow(); - this.#profiles.updateWhen(account.userId, (saved) => { - outcome = buyGjnProduct(saved, product, now); - return outcome.ok; - }); - if (outcome.ok) { - return jsonResponse({ ok: true, message: `已购买「${product.title.zh}」(花费 ${product.gjnCost} GJN)。切回游戏窗口即可自动刷新。` }, `store web buy ${product.id}`); - } - const msg = outcome.reason === 'NOT_ENOUGH_GJN' - ? `GJN 余额不足(需要 ${product.gjnCost} GJN,可在兑换码页使用 GJN 充值码或运行 save-cli --gjn)。` - : outcome.reason === 'ALREADY_BOUGHT' - ? '已拥有该礼包载具。' - : '该商品当前不可购买。'; - return jsonResponse({ ok: false, message: msg }, `store web buy ${product.id}: ${outcome.reason}`); - } - - #webRedeem(request: ServiceRequest): ServiceResponse { - const body = parseJsonBody(request.body); - const account = requireWebActionAccount(this.#accounts, body.userId); - const code = typeof body.code === 'string' ? body.code : ''; - if (!account) return jsonResponse({ ok: false, message: '请先在游戏内登录本地账号并在右上角选择账号。' }, 'store web redeem: unknown account'); - - let outcome: RedeemOutcome = { ok: false, reason: 'INVALID_CODE', message: { en: '', zh: '无效的兑换码。' } }; - const now = serverTimeNow(); - this.#profiles.updateWhen(account.userId, (saved) => { - outcome = redeemStoreCode(saved, code, now); - return outcome.ok; - }); - return jsonResponse({ ok: outcome.ok, message: outcome.message.zh }, `store web redeem ${code.trim() || '(empty)'}`); - } - - #accountFromForm(form: URLSearchParams): Account | undefined { - const userId = userIdFromToken(form.get('token') ?? undefined) ?? userIdFromJwt(form.get('jwt') ?? undefined); - return userId ? this.#accounts.byUserId(userId) : undefined; + const response = this.#yuplay.handle(request); + return { ...response, logNotes: { ...response.logNotes, redactedRequestBody: redacted, requestText: redacted } }; } } -function toWebProduct(product: StoreProduct, owned: boolean): Record { - return { - id: product.id, - kind: product.kind, - titleZh: product.title.zh, - titleEn: product.title.en, - gjnCost: product.gjnCost, - ...(product.goldIncome ? { goldIncome: product.goldIncome } : {}), - ...(product.premiumDays ? { premiumDays: product.premiumDays } : {}), - ...(product.vehicle ? { unitName: product.vehicle.name, country: product.vehicle.country, rank: product.vehicle.rank } : {}), - owned, - }; +function isPagePath(path: string): boolean { + return path === PAGE_PREFIX || path.startsWith(`${PAGE_PREFIX}/`); } diff --git a/packages/local-service/src/store/store-tuning.ts b/packages/local-service/src/store/store-tuning.ts new file mode 100644 index 0000000..dcdd660 --- /dev/null +++ b/packages/local-service/src/store/store-tuning.ts @@ -0,0 +1,81 @@ +/** Typed content of tuning/store.jsonc. */ +import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts'; + +export interface GoldenEaglePack { + readonly id: string; + readonly goldenEagles: number; + readonly gjnCents: number; +} + +export interface SilverLionPack { + readonly id: string; + readonly silverLions: number; + readonly goldenEagles: number; +} + +export interface PremiumTier { + readonly id: string; + readonly days: number; + /** Price: golden eagles for premiumForGoldenEagles, GJN hundredths for premiumForGjn. */ + readonly price: number; +} + +export interface VehiclePackContent { + readonly gjnCents: number; + readonly goldenEagles: number; + readonly premiumDays: number; +} + +export interface StoreTuning { + readonly goldenEaglePacks: readonly GoldenEaglePack[]; + readonly silverLionPacks: readonly SilverLionPack[]; + readonly premiumForGoldenEagles: readonly PremiumTier[]; + readonly premiumForGjn: readonly PremiumTier[]; + /** Sorted by upToRank. */ + readonly vehiclePacksByRank: readonly (VehiclePackContent & { readonly upToRank: number })[]; + /** Per-vehicle content; a field left out comes from the vehicle's rank tier. */ + readonly vehiclePacksByVehicle: ReadonlyMap>; +} + +export function readStoreTuning(file: TuningReader): StoreTuning { + 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); + if (byRank.length === 0) throw new TuningError('tuning file store.jsonc: vehiclePacks.byRank must have at least one tier'); + return { + goldenEaglePacks: file.list('goldenEaglePacks', (entry) => ({ id: entry.string('id'), goldenEagles: entry.int('goldenEagles', { min: 1 }), gjnCents: entry.money('gjn', { min: 0.01 }) })), + silverLionPacks: file.list('silverLionPacks', (entry) => ({ id: entry.string('id'), silverLions: entry.int('silverLions', { min: 1 }), goldenEagles: entry.int('goldenEagles', { min: 1 }) })), + premiumForGoldenEagles: file.list('premiumForGoldenEagles', (entry) => premiumTier(entry, 'goldenEagles')), + premiumForGjn: file.list('premiumForGjn', (entry) => premiumTier(entry, 'gjn')), + vehiclePacksByRank: byRank, + vehiclePacksByVehicle: packs.table('byVehicle', partialPackContent), + }; +} + +/** 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]!; + const own = tuning.vehiclePacksByVehicle.get(vehicle) ?? {}; + return { + gjnCents: own.gjnCents ?? tier.gjnCents, + goldenEagles: own.goldenEagles ?? tier.goldenEagles, + premiumDays: own.premiumDays ?? tier.premiumDays, + }; +} + +function premiumTier(entry: TuningReader, currency: 'goldenEagles' | 'gjn'): PremiumTier { + const price = currency === 'gjn' ? entry.money('gjn', { min: 0.01 }) : entry.int('goldenEagles', { min: 1 }); + return { id: entry.string('id'), days: entry.int('days', { min: 1 }), price }; +} + +function packContent(entry: TuningReader): VehiclePackContent { + return { gjnCents: entry.money('gjn', { min: 0.01 }), goldenEagles: entry.int('goldenEagles', { min: 0 }), premiumDays: entry.int('premiumDays', { min: 0 }) }; +} + +function partialPackContent(entry: TuningReader): Partial { + return { + ...(entry.has('gjn') ? { gjnCents: entry.money('gjn', { min: 0.01 }) } : {}), + ...(entry.has('goldenEagles') ? { goldenEagles: entry.int('goldenEagles', { min: 0 }) } : {}), + ...(entry.has('premiumDays') ? { premiumDays: entry.int('premiumDays', { min: 0 }) } : {}), + }; +} diff --git a/packages/local-service/src/store/store-web-api.ts b/packages/local-service/src/store/store-web-api.ts new file mode 100644 index 0000000..5cb9c6b --- /dev/null +++ b/packages/local-service/src/store/store-web-api.ts @@ -0,0 +1,121 @@ +/** + * The JSON requests of the local store page (/store, shown in the game's built-in browser; + * implementation notes): + * GET /store/api/state?userId= balances, products and redeem code help for one account + * POST /store/api/buy { userId, productId } + * POST /store/api/redeem { userId, code } + * Texts for the player come in both page languages ({ en, zh }); the page picks one. + */ +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 { remainingPremiumDays } from '../profile/profile-entitlements.ts'; +import { serverTimeNow } from '../profile/server-time.ts'; +import type { ServiceRequest, ServiceResponse } from '../server/exchange.ts'; +import { jsonResponse, parseJsonBody, requireWebActionAccount, selectWebViewAccount } from '../web-ui/web-helpers.ts'; +import { describeRedeemCodes, gjnText, redeemStoreCode, type RedeemOutcome } from './redeem-codes.ts'; +import type { RedeemTuning } from './redeem-tuning.ts'; +import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts'; +import { buyGjnProduct, canBuyGjnProduct, type GjnPurchaseOutcome } from './store-purchase.ts'; + +const NO_ACCOUNT: LocalizedText = { zh: '没有找到这个账号,请先在右上角选择账号。', en: 'Account not found. Pick an account at the top right first.' }; + +export class StoreWebApi { + readonly #accounts: AccountStore; + readonly #profiles: PlayerProfiles; + readonly #catalogue: StoreCatalogue; + readonly #redeemCodes: RedeemTuning; + + constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning) { + this.#accounts = accounts; + this.#profiles = profiles; + this.#catalogue = catalogue; + this.#redeemCodes = redeemCodes; + } + + /** The answer for /store/api/, or undefined when it is not an API request. */ + handle(apiPath: string, request: ServiceRequest): ServiceResponse | undefined { + if (apiPath === '/api/state' && request.method === 'GET') return this.#state(request); + if (apiPath === '/api/buy' && request.method === 'POST') return this.#buy(request); + if (apiPath === '/api/redeem' && request.method === 'POST') return this.#redeem(request); + return undefined; + } + + #state(request: ServiceRequest): ServiceResponse { + const account = selectWebViewAccount(this.#accounts, request.query.get('userId')); + const now = serverTimeNow(); + const profile = account ? this.#profiles.profileOf(account.userId) : undefined; + const products = this.#catalogue.allProducts() + .filter((product) => product.gjnCostCents !== undefined) + .map((product) => webProduct(product, profile ? !canBuyGjnProduct(profile, product, now) : false)); + return jsonResponse({ + accounts: this.#accounts.all().map((entry) => ({ userId: entry.userId, login: entry.login, nick: entry.nick })), + activeUserId: account?.userId ?? '', + balance: profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjnCents: 0 }, + premiumDays: profile ? remainingPremiumDays(profile, now) : 0, + products, + redeemHelp: describeRedeemCodes(this.#redeemCodes), + }, `store web state (${account?.userId ?? 'no account'})`); + } + + #buy(request: ServiceRequest): ServiceResponse { + const body = parseJsonBody(request.body); + const account = requireWebActionAccount(this.#accounts, body.userId); + const product = typeof body.productId === 'string' ? this.#catalogue.byId(body.productId) : undefined; + if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store web buy: unknown account'); + if (!product || product.gjnCostCents === undefined) { + return jsonResponse({ ok: false, message: { zh: '没有找到这个商品。', en: 'Product not found.' } }, 'store web buy: unknown product'); + } + + let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' }; + const now = serverTimeNow(); + this.#profiles.updateWhen(account.userId, (saved) => { + outcome = buyGjnProduct(saved, product, now); + return outcome.ok; + }); + return jsonResponse({ ok: outcome.ok, message: purchaseMessage(outcome, product) }, `store web buy ${product.id}: ${outcome.ok ? 'OK' : outcome.reason}`); + } + + #redeem(request: ServiceRequest): ServiceResponse { + const body = parseJsonBody(request.body); + const account = requireWebActionAccount(this.#accounts, body.userId); + if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store web redeem: unknown account'); + const code = typeof body.code === 'string' ? body.code : ''; + let outcome: RedeemOutcome | undefined; + const now = serverTimeNow(); + this.#profiles.updateWhen(account.userId, (saved) => { + outcome = redeemStoreCode(saved, code, now, this.#redeemCodes); + return outcome.ok; + }); + return jsonResponse({ ok: outcome?.ok ?? false, message: outcome?.message }, `store web redeem ${code.trim() || '(empty)'}`); + } +} + +function purchaseMessage(outcome: GjnPurchaseOutcome, product: StoreProduct): LocalizedText { + const cost = gjnText(product.gjnCostCents ?? 0); + if (outcome.ok) { + return { + zh: `已购买「${product.title.zh}」,花费 ${cost} GJN。关闭商店窗口后机库会自动刷新。`, + en: `Bought "${product.title.en}" for ${cost} GJN. Close the store window to refresh the hangar.`, + }; + } + if (outcome.reason === 'NOT_ENOUGH_GJN') { + return { zh: `GJN 不够:需要 ${cost} GJN。可以在"兑换码"页用 GJN 充值码补充。`, en: `Not enough GJN: ${cost} GJN needed. A GJN code on the Redeem tab adds more.` }; + } + if (outcome.reason === 'ALREADY_BOUGHT') return { zh: '你已经拥有这辆载具。', en: 'You already own this vehicle.' }; + return { zh: '这个商品现在买不了。', en: 'This product cannot be bought right now.' }; +} + +function webProduct(product: StoreProduct, owned: boolean): Record { + return { + id: product.id, + kind: product.kind, + title: product.title, + gjnCostCents: product.gjnCostCents, + ...(product.goldIncome ? { goldIncome: product.goldIncome } : {}), + ...(product.premiumDays ? { premiumDays: product.premiumDays } : {}), + ...(product.vehicle ? { unitName: product.vehicle.name, country: product.vehicle.country, rank: product.vehicle.rank } : {}), + owned, + }; +} diff --git a/packages/local-service/src/store/web/app.js b/packages/local-service/src/store/web/app.js index bfe0b54..cf766de 100644 --- a/packages/local-service/src/store/web/app.js +++ b/packages/local-service/src/store/web/app.js @@ -1,151 +1,164 @@ -const COUNTRY_NAMES = { - country_usa: '美国', country_germany: '德国', country_ussr: '苏联', country_britain: '英国', - country_japan: '日本', country_china: '中国', country_italy: '意大利', country_france: '法国', - country_sweden: '瑞典', country_israel: '以色列' -}; +// Local store page, shown in the game's built-in browser. +'use strict'; -let state = { accounts: [], activeUserId: '', balance: { gjn: 0, goldenEagles: 0, silverLions: 0 }, premiumDays: 0, products: [] }; +const T = { + zh: { + title: 'WTOffline 本地商店', hint: '买完关闭本窗口,机库会自动刷新', toMarket: '前往交易所', + eagles: '金鹰', lions: '银狮', premium: '高级账户', premiumOff: '未开通', premiumLeft: '剩余 {days} 天', + tabPacks: '礼包载具', tabPremium: '高级账户', tabEagles: '金鹰', tabRedeem: '兑换码', + search: '搜索载具名称', allCountries: '全部国家', allRanks: '全部等级', rank: '{rank} 级', + containsEagles: '附赠 {n} 金鹰', containsPremium: '附赠 {days} 天高级账户', premiumDays: '{days} 天高级账户', + buy: '购买', owned: '已拥有', pickAccount: '请先选择账号', redeem: '兑换', codePlaceholder: '输入兑换码', empty: '没有符合条件的商品', + }, + en: { + title: 'WTOffline Store', hint: 'Close this window after buying to refresh the hangar', toMarket: 'Go to Marketplace', + eagles: 'Golden Eagles', lions: 'Silver Lions', premium: 'Premium', premiumOff: 'inactive', premiumLeft: '{days} days left', + tabPacks: 'Vehicle packs', tabPremium: 'Premium Account', tabEagles: 'Golden Eagles', tabRedeem: 'Redeem code', + search: 'Search vehicles', allCountries: 'All nations', allRanks: 'All ranks', rank: 'Rank {rank}', + containsEagles: '+{n} Golden Eagles', containsPremium: '+{days} days of Premium Account', premiumDays: '{days} days of Premium Account', + buy: 'Buy', owned: 'Owned', pickAccount: 'Pick an account first', redeem: 'Redeem', codePlaceholder: 'Enter a code', empty: 'Nothing matches the filters', + }, +}; +const ROMAN = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X']; +const t = (key, params) => WtoUi.tr(T, key, params); +const $ = (id) => document.getElementById(id); + +let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0, goldenEagles: 0, silverLions: 0 }, premiumDays: 0, products: [], redeemHelp: [] }; let currentTab = 'vehicle-pack'; -function showNotice(text, ok) { - const el = document.getElementById('notice'); - el.textContent = text; - el.className = 'notice ' + (ok ? 'ok' : 'err'); +function applyStaticTexts() { + for (const el of document.querySelectorAll('[data-t]')) el.textContent = t(el.dataset.t); + $('searchInput').placeholder = t('search'); + $('codeInput').placeholder = t('codePlaceholder'); + $('marketLink').href = WtoUi.pageLink('/trade.gaijin.net/'); } async function loadState(userId) { - const qs = userId ? '?userId=' + encodeURIComponent(userId) : ''; - const res = await fetch('/store/api/state' + qs); - state = await res.json(); + state = await WtoUi.getJson('/store/api/state' + (userId ? '?userId=' + encodeURIComponent(userId) : '')); + if (userId && !state.activeUserId) return loadState(''); + if (state.activeUserId) WtoUi.saveAccount(state.activeUserId); renderHeader(); - populateFilters(); + renderFilters(); renderContent(); } function renderHeader() { - const sel = document.getElementById('playerSelect'); - sel.innerHTML = ''; - for (const acc of state.accounts) { - const opt = document.createElement('option'); - opt.value = acc.userId; - opt.textContent = acc.nick + ' (' + acc.login + ')'; - if (acc.userId === state.activeUserId) opt.selected = true; - sel.appendChild(opt); - } - document.getElementById('gjnVal').textContent = state.balance.gjn.toLocaleString() + ' GJN'; - document.getElementById('goldVal').textContent = state.balance.goldenEagles.toLocaleString(); - document.getElementById('silverVal').textContent = state.balance.silverLions.toLocaleString(); - document.getElementById('premVal').textContent = state.premiumDays > 0 ? ('剩余 ' + state.premiumDays + ' 天') : '未激活'; + WtoUi.fillAccountSelect($('accountSelect'), state.accounts, state.activeUserId); + $('gjnVal').textContent = WtoUi.gjn(state.balance.gjnCents); + $('goldVal').textContent = WtoUi.num(state.balance.goldenEagles); + $('silverVal').textContent = WtoUi.num(state.balance.silverLions); + $('premVal').textContent = state.premiumDays > 0 ? t('premiumLeft', { days: state.premiumDays }) : t('premiumOff'); } -function populateFilters() { - const cSel = document.getElementById('countryFilter'); - const prevC = cSel.value; - const countries = [...new Set(state.products.filter(p => p.country).map(p => p.country))]; - cSel.innerHTML = ''; - for (const c of countries) { - const opt = document.createElement('option'); - opt.value = c; - opt.textContent = COUNTRY_NAMES[c] || c; - if (c === prevC) opt.selected = true; - cSel.appendChild(opt); - } - const rSel = document.getElementById('rankFilter'); - const prevR = rSel.value; - const ranks = [...new Set(state.products.filter(p => p.rank).map(p => p.rank))].sort((a, b) => a - b); - rSel.innerHTML = ''; - for (const r of ranks) { - const opt = document.createElement('option'); - opt.value = String(r); - opt.textContent = '等级 ' + r; - if (String(r) === prevR) opt.selected = true; - rSel.appendChild(opt); - } +function fillSelect(select, firstText, values, textOf) { + const previous = select.value; + select.innerHTML = ''; + select.appendChild(new Option(firstText, '')); + for (const value of values) select.appendChild(new Option(textOf(value), String(value), false, String(value) === previous)); +} + +function renderFilters() { + const packs = state.products.filter((p) => p.kind === 'vehicle-pack'); + fillSelect($('countryFilter'), t('allCountries'), [...new Set(packs.map((p) => p.country))], WtoUi.label); + fillSelect($('rankFilter'), t('allRanks'), [...new Set(packs.map((p) => p.rank))].sort((a, b) => a - b), (r) => t('rank', { rank: ROMAN[r] || r })); +} + +function matchesFilters(product) { + if (product.kind !== currentTab) return false; + if (currentTab !== 'vehicle-pack') return true; + const country = $('countryFilter').value; + const rank = $('rankFilter').value; + const query = $('searchInput').value.trim().toLowerCase(); + if (country && product.country !== country) return false; + if (rank && String(product.rank) !== rank) return false; + return !query || [product.title.zh, product.title.en, product.unitName].some((s) => (s || '').toLowerCase().includes(query)); } function renderContent() { const isRedeem = currentTab === 'redeem'; - document.getElementById('redeemPanel').style.display = isRedeem ? 'block' : 'none'; - document.getElementById('grid').style.display = isRedeem ? 'none' : 'grid'; - document.getElementById('packFilters').style.display = currentTab === 'vehicle-pack' ? 'flex' : 'none'; - if (isRedeem) return; + $('redeemPanel').hidden = !isRedeem; + $('grid').hidden = isRedeem; + $('packFilters').hidden = currentTab !== 'vehicle-pack'; + if (isRedeem) return renderRedeemHelp(); - const q = document.getElementById('searchInput').value.trim().toLowerCase(); - const cFilter = document.getElementById('countryFilter').value; - const rFilter = document.getElementById('rankFilter').value; - const grid = document.getElementById('grid'); + const grid = $('grid'); grid.innerHTML = ''; + const items = state.products.filter(matchesFilters); + if (items.length === 0) grid.innerHTML = '
' + WtoUi.escapeHtml(t('empty')) + '
'; + for (const product of items) grid.appendChild(productCard(product)); +} - const items = state.products.filter(p => { - if (p.kind !== currentTab) return false; - if (currentTab === 'vehicle-pack') { - if (cFilter && p.country !== cFilter) return false; - if (rFilter && String(p.rank) !== rFilter) return false; - if (q && !(p.titleZh.toLowerCase().includes(q) || p.titleEn.toLowerCase().includes(q) || (p.unitName || '').toLowerCase().includes(q))) return false; - } - return true; - }); - - for (const item of items) { - const card = document.createElement('div'); - card.className = 'card'; - const details = []; - if (item.country) details.push((COUNTRY_NAMES[item.country] || item.country) + ' · 等级 ' + item.rank); - if (item.goldIncome) details.push('包含金鹰:' + item.goldIncome.toLocaleString()); - if (item.premiumDays) details.push('包含高级账户:' + item.premiumDays + ' 天'); - card.innerHTML = '

'; - card.querySelector('h3').textContent = item.titleZh; - card.querySelector('.meta').textContent = details.join(' | '); - card.querySelector('.price').textContent = item.gjnCost + ' GJN'; - const btn = card.querySelector('button'); - if (item.owned) { - btn.textContent = '已拥有'; - btn.disabled = true; - } else if (!state.activeUserId) { - btn.textContent = '请先登录游戏'; - btn.disabled = true; - } else { - btn.textContent = '购买'; - btn.onclick = () => buyItem(item.id); - } - grid.appendChild(card); +function productCard(product) { + const card = document.createElement('div'); + card.className = 'card'; + const head = document.createElement('div'); + head.className = 'card-head'; + if (product.unitName) head.appendChild(WtoUi.iconImg('vehicle', product.unitName, 'vehicle-icon')); + const titles = document.createElement('div'); + titles.innerHTML = '

'; + titles.querySelector('.card-title').textContent = WtoUi.text(product.title); + if (product.country) { + const sub = titles.querySelector('.card-sub'); + sub.appendChild(WtoUi.iconImg('flag', product.country, 'flag')); + sub.appendChild(document.createTextNode(WtoUi.label(product.country) + ' · ' + t('rank', { rank: ROMAN[product.rank] || product.rank }))); } + head.appendChild(titles); + card.appendChild(head); + + const contents = []; + if (product.kind === 'premium-gjn') contents.push(t('premiumDays', { days: product.premiumDays })); + else if (product.premiumDays) contents.push(t('containsPremium', { days: product.premiumDays })); + if (product.kind === 'vehicle-pack' && product.goldIncome) contents.push(t('containsEagles', { n: WtoUi.num(product.goldIncome) })); + if (contents.length) { + const list = document.createElement('ul'); + list.className = 'contents'; + for (const line of contents) list.appendChild(Object.assign(document.createElement('li'), { textContent: line })); + card.appendChild(list); + } + + const foot = document.createElement('div'); + foot.className = 'card-foot'; + foot.innerHTML = ''; + foot.querySelector('.price').textContent = WtoUi.gjn(product.gjnCostCents) + ' GJN'; + const button = foot.querySelector('button'); + button.textContent = product.owned ? t('owned') : state.activeUserId ? t('buy') : t('pickAccount'); + button.disabled = product.owned || !state.activeUserId; + button.onclick = () => buy(product.id); + card.appendChild(foot); + return card; } -async function buyItem(productId) { - const res = await fetch('/store/api/buy', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ userId: state.activeUserId, productId }) - }); - const data = await res.json(); - showNotice(data.message, data.ok); +function renderRedeemHelp() { + const list = $('redeemHelp'); + list.innerHTML = ''; + for (const line of state.redeemHelp) list.appendChild(Object.assign(document.createElement('li'), { textContent: WtoUi.text(line) })); +} + +async function buy(productId) { + const result = await WtoUi.postJson('/store/api/buy', { userId: state.activeUserId, productId }); + WtoUi.showNotice($('notice'), WtoUi.text(result.message), result.ok); await loadState(state.activeUserId); } -document.getElementById('playerSelect').onchange = (e) => loadState(e.target.value); -document.getElementById('searchInput').oninput = renderContent; -document.getElementById('countryFilter').onchange = renderContent; -document.getElementById('rankFilter').onchange = renderContent; -for (const tab of document.querySelectorAll('.tab')) { - tab.onclick = () => { - for (const t of document.querySelectorAll('.tab')) t.classList.remove('active'); - tab.classList.add('active'); - currentTab = tab.dataset.tab; - renderContent(); - }; -} -document.getElementById('redeemBtn').onclick = async () => { - const code = document.getElementById('codeInput').value; - const res = await fetch('/store/api/redeem', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ userId: state.activeUserId, code }) - }); - const data = await res.json(); - showNotice(data.message, data.ok); - if (data.ok) document.getElementById('codeInput').value = ''; +async function redeem() { + const result = await WtoUi.postJson('/store/api/redeem', { userId: state.activeUserId, code: $('codeInput').value }); + WtoUi.showNotice($('notice'), WtoUi.text(result.message), result.ok); + if (result.ok) $('codeInput').value = ''; await loadState(state.activeUserId); +} + +$('accountSelect').onchange = (event) => loadState(event.target.value); +$('searchInput').oninput = renderContent; +$('countryFilter').onchange = renderContent; +$('rankFilter').onchange = renderContent; +$('redeemBtn').onclick = redeem; +$('tabs').onclick = (event) => { + const tab = event.target.closest('.tab'); + if (!tab) return; + for (const other of document.querySelectorAll('.tab')) other.classList.toggle('active', other === tab); + currentTab = tab.dataset.tab; + renderContent(); }; -loadState(''); +applyStaticTexts(); +WtoUi.loadLabels().then(() => loadState(WtoUi.savedAccount())); diff --git a/packages/local-service/src/store/web/index.html b/packages/local-service/src/store/web/index.html index 614a216..d513437 100644 --- a/packages/local-service/src/store/web/index.html +++ b/packages/local-service/src/store/web/index.html @@ -1,51 +1,50 @@ - + - War Thunder Offline — 本地商店 + WTOffline + -
-
WAR THUNDER OFFLINE 本地商店 · 切回游戏窗口自动同步档案
+
+
+
+
+
- 前往本地交易所 - -
GJN 余额 0
-
金鹰 0
-
银狮 0
-
高级账户 未激活
+ + + GJN0 + 0 + 0 +
-
- - - - +
+ + + +
-
- - - +
+ + +
-
- +
    +
    + diff --git a/packages/local-service/src/store/web/styles.css b/packages/local-service/src/store/web/styles.css index b7957c3..fbf2981 100644 --- a/packages/local-service/src/store/web/styles.css +++ b/packages/local-service/src/store/web/styles.css @@ -1,128 +1,7 @@ -:root { - --bg: #11161c; - --panel: #19212b; - --panel-alt: #212b38; - --border: #2e3b4d; - --text: #e6edf5; - --muted: #93a3b5; - --accent: #e09f3e; - --accent-hover: #f0b354; - --ok: #3ea66b; - --err: #d9534f; -} -* { box-sizing: border-box; } -body { - margin: 0; - font-family: "Segoe UI", "Microsoft YaHei", system-ui, sans-serif; - background: var(--bg); - color: var(--text); -} -header { - background: var(--panel); - border-bottom: 1px solid var(--border); - padding: 14px 24px; - display: flex; - flex-wrap: wrap; - gap: 16px; - align-items: center; - justify-content: space-between; -} -.brand { font-size: 18px; font-weight: 700; letter-spacing: 0.3px; } -.brand span { color: var(--accent); font-size: 13px; margin-left: 8px; font-weight: 500; } -.wallet { - display: flex; - flex-wrap: wrap; - gap: 12px; - align-items: center; -} -.pill { - background: var(--panel-alt); - border: 1px solid var(--border); - padding: 6px 12px; - border-radius: 6px; - font-size: 13px; -} -.pill strong { color: var(--accent); font-size: 15px; margin-left: 4px; } -.link-btn { - text-decoration: none; - color: var(--muted); - font-size: 13px; - padding: 6px 10px; - border: 1px solid var(--border); - border-radius: 6px; -} -select, input { - background: var(--panel-alt); - color: var(--text); - border: 1px solid var(--border); - border-radius: 6px; - padding: 7px 11px; - font-size: 14px; -} -#searchInput { min-width: 220px; } -main { max-width: 1240px; margin: 0 auto; padding: 20px 24px 48px; } -.tabs { display: flex; gap: 8px; margin-bottom: 18px; flex-wrap: wrap; } -.tab { - background: var(--panel); - color: var(--muted); - border: 1px solid var(--border); - padding: 9px 16px; - border-radius: 6px; - cursor: pointer; - font-size: 14px; - font-weight: 600; -} -.tab.active { background: var(--accent); color: #11161c; border-color: var(--accent); } -.filters { display: flex; gap: 10px; margin-bottom: 16px; flex-wrap: wrap; } -.notice { - padding: 10px 14px; - border-radius: 6px; - margin-bottom: 16px; - font-size: 14px; - display: none; -} -.notice.ok { display: block; background: rgba(62, 166, 107, 0.18); border: 1px solid var(--ok); } -.notice.err { display: block; background: rgba(217, 83, 79, 0.18); border: 1px solid var(--err); } -.grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(265px, 1fr)); - gap: 14px; -} -.card { - background: var(--panel); - border: 1px solid var(--border); - border-radius: 8px; - padding: 15px; - display: flex; - flex-direction: column; - justify-content: space-between; - gap: 12px; -} -.card h3 { margin: 0 0 6px; font-size: 16px; } -.meta { color: var(--muted); font-size: 12.5px; line-height: 1.5; } -.card-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 4px; } -.price { font-size: 17px; font-weight: 700; color: var(--accent); } -button.buy { - background: var(--accent); - color: #11161c; - border: none; - border-radius: 6px; - padding: 8px 14px; - font-weight: 700; - cursor: pointer; - font-size: 13.5px; -} -button.buy:hover:not(:disabled) { background: var(--accent-hover); } -button.buy:disabled { background: var(--border); color: var(--muted); cursor: default; } -.redeem-box { - background: var(--panel); - border: 1px solid var(--border); - border-radius: 8px; - padding: 20px; - max-width: 600px; -} -.redeem-box h3 { margin-top: 0; } -.redeem-row { display: flex; gap: 10px; margin: 12px 0 16px; } -.redeem-row input { flex: 1; } -.hint { color: var(--muted); font-size: 13px; line-height: 1.6; } -code { background: var(--panel-alt); padding: 2px 6px; border-radius: 4px; color: var(--accent); } +/* Store page only; the shared layout is /_wto/ui/common.css. */ +.contents { margin: 0; padding-left: 18px; color: var(--muted); font-size: 13px; } +.redeem { display: flex; flex-direction: column; gap: 12px; max-width: 760px; padding: 16px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); } +.redeem-row { display: flex; flex-wrap: wrap; gap: 8px; } +.redeem-row input { flex: 1 1 280px; } +.redeem-help { margin: 0; padding-left: 18px; color: var(--muted); } +.redeem-help li { margin: 2px 0; } diff --git a/packages/local-service/src/store/yuplay-store-api.ts b/packages/local-service/src/store/yuplay-store-api.ts new file mode 100644 index 0000000..9121a9a --- /dev/null +++ b/packages/local-service/src/store/yuplay-store-api.ts @@ -0,0 +1,110 @@ +/** + * The game's own store requests (yuplay2, implementation notes), sent to api.gaijinent.com + * and routed here by wto_ws.dll: + * POST /item_info.php GJN prices of the bundle GUIDs (scripts/onlineShop/entitlementsInfo.nut) + * POST /item_purchase.php pay=gjn purchase from the in-game payment window + * POST /redeem_code.php the in-game redeem code window + * The player is identified by the session token or JWT the local login service issued; a + * request whose player cannot be identified is refused. + */ +import type { Account, AccountStore } from '../accounts/account-store.ts'; +import { userIdFromJwt, userIdFromToken } from '../login/session-credentials.ts'; +import { yuplayAnswer } from '../login/yuplay-answer.ts'; +import type { PlayerProfiles } from '../profile/player-profiles.ts'; +import { serverTimeNow } from '../profile/server-time.ts'; +import type { ServiceRequest, ServiceResponse } from '../server/exchange.ts'; +import { gjnText, redeemStoreCode, type RedeemOutcome } from './redeem-codes.ts'; +import type { RedeemTuning } from './redeem-tuning.ts'; +import type { StoreCatalogue } from './store-catalogue.ts'; +import { buyGjnProduct, canBuyGjnProduct, type GjnPurchaseOutcome } from './store-purchase.ts'; + +export const YUPLAY_STORE_PATHS: ReadonlySet = new Set(['/item_info.php', '/item_purchase.php', '/redeem_code.php']); + +export class YuplayStoreApi { + readonly #accounts: AccountStore; + readonly #profiles: PlayerProfiles; + readonly #catalogue: StoreCatalogue; + readonly #redeemCodes: RedeemTuning; + + constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning) { + this.#accounts = accounts; + this.#profiles = profiles; + this.#catalogue = catalogue; + this.#redeemCodes = redeemCodes; + } + + handle(request: ServiceRequest): ServiceResponse { + if (request.method !== 'POST') return yuplayAnswer('ERROR', {}, `${request.method} ${request.path} not supported`); + const form = new URLSearchParams(request.body.toString('utf8')); + if (request.path === '/item_info.php') return this.#itemInfo(form); + if (request.path === '/item_purchase.php') return this.#itemPurchase(form); + return this.#redeemCode(form); + } + + #itemInfo(form: URLSearchParams): ServiceResponse { + const guids = [...form.getAll('guids[]'), ...form.getAll('guids'), ...form.getAll('guid')].filter(Boolean); + const account = this.#account(form); + const profile = account ? this.#profiles.profileOf(account.userId) : undefined; + const now = serverTimeNow(); + const items: Record = {}; + let numericId = 1; + for (const guid of guids) { + const product = this.#catalogue.byGuid(guid); + if (!product || product.gjnCostCents === undefined) continue; + items[guid] = { + item_id: numericId++, + shop_price: product.gjnCostCents / 100, + price_usd: product.gjnCostCents / 100, + discount_mul: 1.0, + discount_till: 0, + title: product.title.en, + url: '', + short_desc: product.title.en, + shop_price_curr: 'gjn', + multi_purch: product.kind !== 'vehicle-pack', + can_be_bought: profile ? canBuyGjnProduct(profile, product, now) : true, + }; + } + return yuplayAnswer('OK', { items }, `item_info (${Object.keys(items).length}/${guids.length} items)`); + } + + #itemPurchase(form: URLSearchParams): ServiceResponse { + const account = this.#account(form); + if (!account) return yuplayAnswer('LOGINERROR', {}, 'item_purchase: unknown token'); + const payMethod = (form.get('pay') ?? 'gjn').toLowerCase(); + if (payMethod !== 'gjn') return yuplayAnswer('BADPAYMENT', {}, `item_purchase: unsupported pay=${payMethod}`); + const guid = form.get('guid') ?? ''; + const product = this.#catalogue.byGuid(guid); + if (!product) return yuplayAnswer('NOTFOUND', {}, `item_purchase: unknown guid ${guid}`); + + let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' }; + const now = serverTimeNow(); + this.#profiles.updateWhen(account.userId, (saved) => { + outcome = buyGjnProduct(saved, product, now); + return outcome.ok; + }); + if (outcome.ok) return yuplayAnswer('OK', {}, `item_purchase ${product.id} (${gjnText(product.gjnCostCents ?? 0)} GJN)`); + if (outcome.reason === 'NOT_ENOUGH_GJN') return yuplayAnswer('NOMONEY', {}, `item_purchase ${product.id}: insufficient GJN`); + if (outcome.reason === 'ALREADY_BOUGHT') return yuplayAnswer('ALREADY', {}, `item_purchase ${product.id}: already owned`); + return yuplayAnswer('NOTFOUND', {}, `item_purchase ${product.id}: not available`); + } + + #redeemCode(form: URLSearchParams): ServiceResponse { + const account = this.#account(form); + if (!account) return yuplayAnswer('LOGINERROR', {}, 'redeem_code: unknown token'); + const code = form.get('code') ?? ''; + let outcome: RedeemOutcome | undefined; + const now = serverTimeNow(); + this.#profiles.updateWhen(account.userId, (saved) => { + outcome = redeemStoreCode(saved, code, now, this.#redeemCodes); + return outcome.ok; + }); + if (outcome?.ok) return yuplayAnswer('OK', {}, `redeem_code ${code} -> OK`); + return yuplayAnswer(outcome?.reason === 'ALREADY_REDEEMED' ? 'ALREADY' : 'NOTFOUND', {}, `redeem_code ${code} -> ${outcome?.reason ?? 'INVALID_CODE'}`); + } + + #account(form: URLSearchParams): Account | undefined { + const userId = userIdFromToken(form.get('token') ?? undefined) ?? userIdFromJwt(form.get('jwt') ?? undefined); + return userId ? this.#accounts.byUserId(userId) : undefined; + } +} diff --git a/packages/local-service/src/tuning/jsonc.ts b/packages/local-service/src/tuning/jsonc.ts new file mode 100644 index 0000000..4e40599 --- /dev/null +++ b/packages/local-service/src/tuning/jsonc.ts @@ -0,0 +1,44 @@ +/** + * Parse JSON with comments (// line comments and block comments), the format of the tuning + * files. Comments are blanked out, outside string literals only; the + * rest goes to JSON.parse, so the error positions still match the file. + */ +export function parseJsonc(text: string): unknown { + return JSON.parse(stripComments(text)); +} + +function stripComments(text: string): string { + let out = ''; + let index = 0; + while (index < text.length) { + const ch = text[index]!; + const next = text[index + 1]; + if (ch === '"') { + const end = stringEnd(text, index); + out += text.slice(index, end); + index = end; + } else if (ch === '/' && next === '/') { + while (index < text.length && text[index] !== '\n') index++; + } else if (ch === '/' && next === '*') { + const end = text.indexOf('*/', index + 2); + const stop = end < 0 ? text.length : end + 2; + out += text.slice(index, stop).replace(/[^\n]/g, ' '); + index = stop; + } else { + out += ch; + index++; + } + } + return out; +} + +/** Index just past the closing quote of the string literal starting at `start`. */ +function stringEnd(text: string, start: number): number { + let index = start + 1; + while (index < text.length) { + if (text[index] === '\\') index += 2; + else if (text[index] === '"') return index + 1; + else index++; + } + return text.length; +} diff --git a/packages/local-service/src/tuning/limits-tuning.ts b/packages/local-service/src/tuning/limits-tuning.ts new file mode 100644 index 0000000..9d12930 --- /dev/null +++ b/packages/local-service/src/tuning/limits-tuning.ts @@ -0,0 +1,14 @@ +/** Typed content of tuning/limits.jsonc: limits the offline version sets where the original server would. */ +import type { TuningReader } from './tuning-reader.ts'; + +export interface LimitsTuning { + readonly itemPiecesPerPurchase: number; + readonly userLogsKept: number; +} + +export function readLimitsTuning(file: TuningReader): LimitsTuning { + return { + itemPiecesPerPurchase: file.int('itemPiecesPerPurchase', { min: 1 }), + userLogsKept: file.int('userLogsKept', { min: 1 }), + }; +} diff --git a/packages/local-service/src/tuning/tuning-loader.ts b/packages/local-service/src/tuning/tuning-loader.ts new file mode 100644 index 0000000..1189d5d --- /dev/null +++ b/packages/local-service/src/tuning/tuning-loader.ts @@ -0,0 +1,51 @@ +/** + * Load one tuning file: the defaults shipped in + * packages/local-service/tuning/.jsonc, with /tuning/.jsonc laid + * over them field by field when the player or a developer put one there. Objects merge key + * by key; any other value (numbers, texts, lists) in the override replaces the default. + */ +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseJsonc } from './jsonc.ts'; +import { TuningError, TuningReader } from './tuning-reader.ts'; + +const DEFAULTS_FOLDER = fileURLToPath(new URL('../../tuning/', import.meta.url)); + +export interface TuningFiles { + /** The merged content of .jsonc, ready for typed reads. */ + read(name: string): TuningReader; +} + +export function tuningFiles(dataFolder: string, report: (line: string) => void): TuningFiles { + const overridesFolder = join(dataFolder, 'tuning'); + return { + read(name: string): TuningReader { + const fileName = `${name}.jsonc`; + const defaults = parseFile(join(DEFAULTS_FOLDER, fileName)); + const overridePath = join(overridesFolder, fileName); + if (!existsSync(overridePath)) return new TuningReader(fileName, defaults); + report(`tuning ${fileName}: using overrides from ${overridePath}`); + return new TuningReader(fileName, mergeOverride(defaults, parseFile(overridePath))); + }, + }; +} + +function parseFile(path: string): unknown { + try { + return parseJsonc(readFileSync(path, 'utf8')); + } catch (error) { + throw new TuningError(`tuning file ${path} cannot be read: ${error instanceof Error ? error.message : String(error)}`); + } +} + +function mergeOverride(base: unknown, override: unknown): unknown { + if (!isObject(base) || !isObject(override)) return override; + const merged: Record = { ...base }; + for (const [key, value] of Object.entries(override)) merged[key] = key in base ? mergeOverride(base[key], value) : value; + return merged; +} + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/packages/local-service/src/tuning/tuning-reader.ts b/packages/local-service/src/tuning/tuning-reader.ts new file mode 100644 index 0000000..c1762dd --- /dev/null +++ b/packages/local-service/src/tuning/tuning-reader.ts @@ -0,0 +1,120 @@ +/** + * Typed, validating reads of one tuning file. Every read names the field + * it wants; a missing field or a value of the wrong type or range stops start-up with the + * file, the field path and what was expected, so a typo in a tuning file never turns into a + * silent default. + */ +export class TuningError extends Error {} + +export interface IntRange { + readonly min?: number; + readonly max?: number; +} + +export class TuningReader { + readonly #file: string; + readonly #path: string; + readonly #value: Readonly>; + + constructor(file: string, value: unknown, path = '') { + this.#file = file; + this.#path = path; + if (!isPlainObject(value)) throw this.#error(path || '(root)', 'an object', value); + this.#value = value; + } + + has(key: string): boolean { + return this.#value[key] !== undefined; + } + + keys(): string[] { + return Object.keys(this.#value); + } + + int(key: string, range: IntRange = {}): number { + const value = this.#field(key); + if (typeof value !== 'number' || !Number.isSafeInteger(value)) throw this.#error(key, 'a whole number', value); + return this.#inRange(key, value, range); + } + + /** A number with a fractional part allowed (weights, multipliers). */ + number(key: string, range: IntRange = {}): number { + const value = this.#field(key); + if (typeof value !== 'number' || !Number.isFinite(value)) throw this.#error(key, 'a number', value); + return this.#inRange(key, value, range); + } + + /** A GJN amount with at most two decimals (12.99), returned in hundredths (1299). */ + money(key: string, range: IntRange = {}): number { + const value = this.number(key, range); + const cents = Math.round(value * 100); + if (Math.abs(cents - value * 100) > 1e-6) throw this.#error(key, 'an amount with at most two decimals', value); + return cents; + } + + string(key: string): string { + const value = this.#field(key); + if (typeof value !== 'string' || value === '') throw this.#error(key, 'a non-empty text', value); + return value; + } + + bool(key: string): boolean { + const value = this.#field(key); + if (typeof value !== 'boolean') throw this.#error(key, 'true or false', value); + return value; + } + + stringList(key: string): string[] { + const value = this.#field(key); + if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string' || entry === '')) throw this.#error(key, 'a list of texts', value); + return value as string[]; + } + + intList(key: string, range: IntRange = {}): number[] { + const value = this.#field(key); + if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'number' || !Number.isSafeInteger(entry))) throw this.#error(key, 'a list of whole numbers', value); + return (value as number[]).map((entry) => this.#inRange(key, entry, range)); + } + + object(key: string): TuningReader { + return new TuningReader(this.#file, this.#field(key), this.#join(key)); + } + + /** A list of objects; `read` turns each into a typed value. */ + list(key: string, read: (entry: TuningReader) => T): T[] { + const value = this.#field(key); + if (!Array.isArray(value)) throw this.#error(key, 'a list', value); + return value.map((entry, index) => read(new TuningReader(this.#file, entry, `${this.#join(key)}[${index}]`))); + } + + /** An object used as a table: every key maps to an entry `read` turns into a typed value. */ + table(key: string, read: (entry: TuningReader, name: string) => T): Map { + const table = this.object(key); + return new Map(table.keys().map((name) => [name, read(table.object(name), name)])); + } + + #field(key: string): unknown { + const value = this.#value[key]; + if (value === undefined) throw this.#error(key, 'a value', undefined); + return value; + } + + #inRange(key: string, value: number, { min, max }: IntRange): number { + if (min !== undefined && value < min) throw this.#error(key, `at least ${min}`, value); + if (max !== undefined && value > max) throw this.#error(key, `at most ${max}`, value); + return value; + } + + #join(key: string): string { + return this.#path ? `${this.#path}.${key}` : key; + } + + #error(key: string, expected: string, got: unknown): TuningError { + const field = key === this.#path || key === '(root)' ? key : this.#join(key); + return new TuningError(`tuning file ${this.#file}: ${field} must be ${expected} (found ${JSON.stringify(got) ?? 'nothing'})`); + } +} + +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/packages/local-service/src/tuning/tuning.ts b/packages/local-service/src/tuning/tuning.ts new file mode 100644 index 0000000..2089dc5 --- /dev/null +++ b/packages/local-service/src/tuning/tuning.ts @@ -0,0 +1,43 @@ +/** + * All tuning values of the offline version, read once at start-up (implementation notes; user + * quote 119): values the offline version decides itself (prices, rewards, drop weights, + * limits, preset content). Values the game data already has are read from the game files + * instead, and protocol constants stay in the code next to their source. + */ +import { readClanTuning, type ClanTuning } from '../clans/clan-tuning.ts'; +import { readMarketplaceTuning, type MarketplaceTuning } from '../inventory/marketplace-tuning.ts'; +import { readRecyclingTuning, type RecyclingTuning } from '../inventory/recycling-tuning.ts'; +import { readSupplyChestTuning, type SupplyChestTuning } from '../inventory/supply-chest-tuning.ts'; +import { readTrophyTuning, type TrophyTuning } from '../inventory/trophy-tuning.ts'; +import { readNewProfileTuning, type NewProfileTuning } from '../profile/new-profile-tuning.ts'; +import { readRedeemTuning, type RedeemTuning } from '../store/redeem-tuning.ts'; +import { readStoreTuning, type StoreTuning } from '../store/store-tuning.ts'; +import { readLimitsTuning, type LimitsTuning } from './limits-tuning.ts'; +import { tuningFiles } from './tuning-loader.ts'; + +export interface Tuning { + readonly store: StoreTuning; + readonly redeemCodes: RedeemTuning; + readonly newProfile: NewProfileTuning; + readonly marketplace: MarketplaceTuning; + readonly supplyChests: SupplyChestTuning; + readonly recycling: RecyclingTuning; + readonly trophies: TrophyTuning; + readonly clans: ClanTuning; + readonly limits: LimitsTuning; +} + +export function loadTuning(dataFolder: string, report: (line: string) => void): Tuning { + const files = tuningFiles(dataFolder, report); + return { + store: readStoreTuning(files.read('store')), + redeemCodes: readRedeemTuning(files.read('redeem-codes')), + newProfile: readNewProfileTuning(files.read('new-profile')), + marketplace: readMarketplaceTuning(files.read('marketplace')), + supplyChests: readSupplyChestTuning(files.read('supply-chests')), + recycling: readRecyclingTuning(files.read('recycling')), + trophies: readTrophyTuning(files.read('trophies')), + clans: readClanTuning(files.read('clans')), + limits: readLimitsTuning(files.read('limits')), + }; +} diff --git a/packages/local-service/src/web-ui/web-helpers.ts b/packages/local-service/src/web-ui/web-helpers.ts index 0f9126b..fc82e08 100644 --- a/packages/local-service/src/web-ui/web-helpers.ts +++ b/packages/local-service/src/web-ui/web-helpers.ts @@ -1,6 +1,7 @@ /** - * Shared static-asset server, JSON helpers, and explicit account resolution for local web UIs - * (`/store` and `/trade.gaijin.net`; implementation notes). + * Shared static-asset server, JSON helpers, and explicit account resolution for the local web + * pages (`/store`, `/trade.gaijin.net` and the shared `/_wto/ui/` files). The game opens them in + * its built-in browser (Chromium 100; implementation notes). */ import { readFileSync } from 'node:fs'; import { extname, join } from 'node:path'; @@ -12,32 +13,39 @@ const CONTENT_TYPES: Readonly> = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', + '.svg': 'image/svg+xml', + '.json': 'application/json; charset=utf-8', }; -const ALLOWED_ASSETS = new Set(['index.html', 'styles.css', 'app.js']); +const PAGE_FILES = ['index.html', 'styles.css', 'app.js']; export interface StaticWebSite { serve(subPath: string, summaryPrefix: string): ServiceResponse | undefined; } -export function createStaticWebSite(folderUrl: URL): StaticWebSite { +/** Serve the listed files of one folder; only names on the list are ever read from disk. */ +export function createStaticWebSite(folderUrl: URL, files: readonly string[] = PAGE_FILES): StaticWebSite { const rootDir = fileURLToPath(folderUrl); + const allowed = new Set(files); return { serve(subPath: string, summaryPrefix: string): ServiceResponse | undefined { const normalized = subPath === '' || subPath === '/' ? 'index.html' : subPath.replace(/^\/+/, ''); - if (!ALLOWED_ASSETS.has(normalized)) return undefined; - const contentType = CONTENT_TYPES[extname(normalized)] ?? 'application/octet-stream'; - const body = readFileSync(join(rootDir, normalized)); - return { - status: 200, - headers: { 'content-type': contentType, 'cache-control': 'no-cache' }, - body, - logNotes: { summary: `${summaryPrefix}: ${normalized}` }, - }; + if (!allowed.has(normalized)) return undefined; + return contentResponse(normalized, readFileSync(join(rootDir, normalized)), `${summaryPrefix}: ${normalized}`); }, }; } +/** A 200 answer whose content type follows the file name's extension. */ +export function contentResponse(fileName: string, body: Uint8Array | string, summary: string): ServiceResponse { + const contentType = CONTENT_TYPES[extname(fileName)] ?? 'application/octet-stream'; + return { status: 200, headers: { 'content-type': contentType, 'cache-control': 'no-cache' }, body, logNotes: { summary } }; +} + +export function notFound(summary: string): ServiceResponse { + return { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' }, body: 'Not found', logNotes: { summary } }; +} + export function parseJsonBody(raw: Buffer): Record { try { const parsed = JSON.parse(raw.toString('utf8')) as unknown; diff --git a/packages/local-service/src/web-ui/web-ui-service.ts b/packages/local-service/src/web-ui/web-ui-service.ts new file mode 100644 index 0000000..8338346 --- /dev/null +++ b/packages/local-service/src/web-ui/web-ui-service.ts @@ -0,0 +1,44 @@ +/** + * Files shared by the local web pages, under /_wto/ui/: + * common.css, common.js layout and helpers both pages load + * labels.json the game's country and vehicle type names (ui-labels dataset) + * vehicle/.svg the game's silhouette icon of a vehicle (web-icons dataset) + * flag/.svg the game's country flag (web-icons dataset) + * Icons and names come from the player's game files at start-up; nothing of Gaijin's is shipped. + */ +import type { WebIcons } from '../game-data/datasets/web-icons.ts'; +import type { UiLabels } from '../game-data/datasets/ui-labels.ts'; +import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts'; +import { contentResponse, createStaticWebSite, notFound } from './web-helpers.ts'; + +const PREFIX = '/_wto/ui/'; +const SHARED_FILES = createStaticWebSite(new URL('./web/', import.meta.url), ['common.css', 'common.js']); +const ICON_PATH = /^(vehicle|flag)\/([^/]+)\.svg$/; + +export class WebUiService implements Service { + readonly name = 'web-ui'; + readonly #icons: WebIcons; + readonly #labels: string; + + constructor(icons: WebIcons, labels: UiLabels) { + this.#icons = icons; + this.#labels = JSON.stringify(labels); + } + + accepts(request: ServiceRequest): boolean { + return request.originalHost === undefined && request.method === 'GET' && request.path.startsWith(PREFIX); + } + + handle(request: ServiceRequest): ServiceResponse { + const subPath = request.path.slice(PREFIX.length); + if (subPath === 'labels.json') return contentResponse(subPath, this.#labels, 'web ui: labels'); + const icon = ICON_PATH.exec(subPath); + if (icon) { + const [, kind, name] = icon; + const table = kind === 'vehicle' ? this.#icons.vehicles : this.#icons.flags; + const svg = Object.hasOwn(table, name!) ? table[name!] : undefined; + return svg ? contentResponse(subPath, svg, `web ui: ${kind} icon`) : notFound(`web ui: no ${kind} icon ${name}`); + } + return SHARED_FILES.serve(subPath, 'web ui') ?? notFound(`web ui 404: ${subPath}`); + } +} diff --git a/packages/local-service/src/web-ui/web/common.css b/packages/local-service/src/web-ui/web/common.css new file mode 100644 index 0000000..e9d5036 --- /dev/null +++ b/packages/local-service/src/web-ui/web/common.css @@ -0,0 +1,64 @@ +/* Shared layout of the local web pages, shown in the game's built-in browser (Chromium 100: + no :has(), no container queries, no CSS nesting). */ +:root { + --bg: #12171d; + --panel: #1a2129; + --panel-raised: #222b35; + --line: #2f3b48; + --text: #e4e9ee; + --muted: #8d9aa8; + --accent: #d9a441; + --accent-strong: #f0bd5a; + --ok: #4caf72; + --err: #d65a52; + --font: "Segoe UI", "Microsoft YaHei", "PingFang SC", system-ui, sans-serif; +} +* { box-sizing: border-box; } +[hidden] { display: none !important; } +html, body { margin: 0; } +body { background: var(--bg); color: var(--text); font-family: var(--font); font-size: 14px; line-height: 1.5; } + +.topbar { + position: sticky; top: 0; z-index: 5; + display: flex; flex-wrap: wrap; gap: 12px 20px; align-items: center; justify-content: space-between; + padding: 12px 24px; background: var(--panel); border-bottom: 1px solid var(--line); +} +.brand { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.brand-title { font-size: 17px; font-weight: 700; letter-spacing: 0.04em; } +.brand-hint { color: var(--muted); font-size: 12px; } +.wallet { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } +.pill { padding: 5px 11px; border: 1px solid var(--line); border-radius: 6px; background: var(--panel-raised); white-space: nowrap; } +.pill b { color: var(--accent); margin-left: 4px; font-variant-numeric: tabular-nums; } + +main { display: flex; flex-direction: column; gap: 14px; padding: 16px 24px 32px; } +.tabs { display: flex; flex-wrap: wrap; gap: 6px; } +.tab { padding: 7px 14px; border: 1px solid var(--line); border-radius: 6px; background: var(--panel); color: var(--muted); cursor: pointer; font: inherit; } +.tab.active { color: var(--text); border-color: var(--accent); background: var(--panel-raised); } +.filters { display: flex; flex-wrap: wrap; gap: 8px; } +select, input { padding: 7px 10px; border: 1px solid var(--line); border-radius: 6px; background: var(--panel-raised); color: var(--text); font: inherit; } +input[type="search"], input[type="text"] { min-width: 240px; } +a.link { color: var(--accent); text-decoration: none; } +a.link:hover { color: var(--accent-strong); } + +.notice { display: none; padding: 9px 14px; border-radius: 6px; border: 1px solid var(--line); } +.notice.ok { display: block; border-color: var(--ok); color: var(--ok); } +.notice.err { display: block; border-color: var(--err); color: var(--err); } + +.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 12px; } +.card { display: flex; flex-direction: column; gap: 10px; padding: 12px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); min-width: 0; } +.card.highlight { border-color: var(--accent); } +.card-head { display: flex; gap: 10px; align-items: center; min-width: 0; } +.card-title { margin: 0; font-size: 15px; font-weight: 600; overflow-wrap: anywhere; } +.card-sub { color: var(--muted); font-size: 12px; } +.vehicle-icon { width: 96px; height: 40px; object-fit: contain; flex: none; } +.flag { width: 22px; height: 14px; object-fit: contain; vertical-align: -2px; margin-right: 4px; } +.badges { display: flex; flex-wrap: wrap; gap: 5px; } +.badge { padding: 1px 7px; border-radius: 4px; background: var(--panel-raised); color: var(--muted); font-size: 12px; } +.badge.owned { color: var(--ok); } +.card-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: auto; } +.price { color: var(--accent); font-weight: 700; font-variant-numeric: tabular-nums; } +button.buy { padding: 7px 16px; border: none; border-radius: 6px; background: var(--accent); color: #1b1408; font: inherit; font-weight: 600; cursor: pointer; } +button.buy:hover { background: var(--accent-strong); } +button.buy:disabled { background: var(--panel-raised); color: var(--muted); cursor: default; } +button:focus-visible, .tab:focus-visible, select:focus-visible, input:focus-visible { outline: 2px solid var(--accent-strong); outline-offset: 1px; } +.empty { color: var(--muted); padding: 24px 0; } diff --git a/packages/local-service/src/web-ui/web/common.js b/packages/local-service/src/web-ui/web/common.js new file mode 100644 index 0000000..899e62e --- /dev/null +++ b/packages/local-service/src/web-ui/web/common.js @@ -0,0 +1,98 @@ +// Shared helpers of the local web pages, shown in the game's built-in browser (Chromium 100). +// The game adds ?skin_lang= to links tagged auto_local (scripts/onlineShop/url.nut), +// so the pages follow the game's language: Chinese for zh, English otherwise. +'use strict'; + +const WtoUi = (() => { + const query = new URLSearchParams(location.search); + const lang = (query.get('skin_lang') || navigator.language || 'en').toLowerCase().startsWith('zh') ? 'zh' : 'en'; + const ACCOUNT_KEY = 'wto.userId'; + let labels = {}; + + document.documentElement.lang = lang === 'zh' ? 'zh-CN' : 'en'; + + /** Pick this page's language from a { en, zh } pair. */ + function text(pair) { + return pair ? (pair[lang] || pair.en || '') : ''; + } + + /** Look up a page string: dict = { zh: {...}, en: {...} }; {name} placeholders are filled from params. */ + function tr(dict, key, params) { + const template = (dict[lang] && dict[lang][key]) || dict.en[key] || key; + return template.replace(/\{(\w+)\}/g, (_, name) => (params && params[name] !== undefined ? String(params[name]) : '')); + } + + function num(value) { + return Number(value || 0).toLocaleString(lang === 'zh' ? 'zh-CN' : 'en-US'); + } + + /** A GJN amount in hundredths: 1299 -> "12.99", 100 -> "1". */ + function gjn(cents) { + const value = Number(cents || 0) / 100; + return value.toLocaleString(lang === 'zh' ? 'zh-CN' : 'en-US', { minimumFractionDigits: value % 1 ? 2 : 0, maximumFractionDigits: 2 }); + } + + function escapeHtml(value) { + return String(value).replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch])); + } + + /** The game's name for a country or vehicle type key (country_usa, mainmenu/type_tank). */ + function label(key) { + return labels[key] ? text(labels[key]) : key; + } + + async function getJson(url) { + const response = await fetch(url); + return response.json(); + } + + async function postJson(url, body) { + const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + return response.json(); + } + + async function loadLabels() { + labels = await getJson('/_wto/ui/labels.json'); + } + + function iconImg(kind, name, className) { + const img = document.createElement('img'); + img.className = className; + img.alt = ''; + img.src = '/_wto/ui/' + kind + '/' + encodeURIComponent(name) + '.svg'; + img.onerror = () => { img.style.visibility = 'hidden'; }; + return img; + } + + /** The account the player picked last time on either page (kept in the built-in browser). */ + function savedAccount() { + try { return localStorage.getItem(ACCOUNT_KEY) || ''; } catch (error) { return ''; } + } + + function saveAccount(userId) { + try { localStorage.setItem(ACCOUNT_KEY, userId); } catch (error) { /* storage unavailable: the choice is not kept */ } + } + + function fillAccountSelect(select, accounts, currentId) { + select.innerHTML = ''; + for (const account of accounts) { + const option = document.createElement('option'); + option.value = account.userId; + option.textContent = account.nick + ' (' + account.login + ')'; + option.selected = account.userId === currentId; + select.appendChild(option); + } + } + + /** A link to another local page that keeps the language. */ + function pageLink(path) { + return path + '?skin_lang=' + lang; + } + + function showNotice(element, message, ok) { + element.textContent = message; + element.className = 'notice ' + (ok ? 'ok' : 'err'); + } + + return { lang, query, text, tr, num, gjn, escapeHtml, label, getJson, postJson, loadLabels, iconImg, savedAccount, saveAccount, fillAccountSelect, pageLink, showNotice }; +})(); diff --git a/packages/local-service/tuning/clans.jsonc b/packages/local-service/tuning/clans.jsonc new file mode 100644 index 0000000..a1ab912 --- /dev/null +++ b/packages/local-service/tuning/clans.jsonc @@ -0,0 +1,112 @@ +// 联队(功能清单 I 节;implementation notes 第 1~3 节)。原版的联队名录、活跃度结算由服务器维护,这里都是离线版的取值。 +{ + // 活跃度和联队研发点。前四项本地服务原样写进联队信息回复给客户端(maxActivityPerPeriod、maxClanActivity、rewardPeriodDays、historyDepth)。 + "activity": { + "maxPerPeriod": 360, // 每个结算周期的活跃度上限 + "squadronRpPerFullPeriod": 20000, // 活跃度满额时一个周期得到的联队研发点 + "rewardPeriodDays": 3, // 结算周期(天) + "historyDepthDays": 14, // 客户端显示的活跃度历史长度(天) + // 玩家加入或创建联队时直接给几个满额周期的记录,不用真等几天就能研发联队载具(implementation notes 第 3.4 节) + "startingPeriods": 3 + }, + + // 成员上限:正式联队,以及战斗群(battalion)刚建立时的上限(战斗群扩编的费用和步长来自游戏数据 warpoints.blk) + "memberLimits": { "normal": 128, "battalionInitial": 10 }, + + // 联队排行榜上显示的周期活跃度 = min(maxActivity, 成员当前活跃度之和 × activityMultiplier),让几名 NPC 也能显示出满编联队的规模 + "leaderboard": { "activityMultiplier": 10, "maxActivity": 100000 }, + + // 玩家新建联队的编号从这里开始 + "firstNewClanId": 600001, + + // 玩家的个人联队评分(街机、历史、全真):自己建队时、加入别人的联队时 + "playerRating": { + "founder": { "arc": 1500, "hist": 1500, "sim": 1500 }, + "joiner": { "arc": 1450, "hist": 1500, "sim": 1400 } + }, + + // 第一次运行时生成的预置联队(<数据目录>/clans.json 不存在时) + "presetClans": { + "createdDaysAgo": 180, // 第一支预置联队的建立时间;每支联队再加上自己的 createdAfterDays + "memberJoinSpacingMinutes": 60, + // 每支预置联队的累计战绩(客户端联队信息里的统计) + "stats": { + "akills_arc": 4280, "akills_hist": 6150, "akills_sim": 1420, + "gkills_arc": 7890, "gkills_hist": 11240, "gkills_sim": 2680, + "deaths_arc": 5120, "deaths_hist": 6890, "deaths_sim": 1950, + "ftime_arc": 18400, "ftime_hist": 32600, "ftime_sim": 8900 + }, + // NPC 成员的个人评分 = max(下限, 联队评分 − 排位序号 × 步长),按街机、历史、全真分别算 + "memberRating": { "step": { "arc": 45, "hist": 50, "sim": 40 }, "floor": { "arc": 800, "hist": 850, "sim": 700 } }, + // role:LEADER(指挥官)、DEPUTY(副指挥官)、OFFICER(军官)、SERGEANT(军士)、REGULAR(普通成员);activity 是当前周期活跃度 + "clans": [ + { + "id": "500001", "tag": "[WTOF]", "name": "War Thunder Offline Guard", "type": "normal", + "slogan": "离线天空与钢铁防线 · 自由研发全部联队载具", + "desc": "War Thunder Offline 官方预置主力联队。开启自动审批,加入即可获得完整联队活跃度与联队研发点支持。", + "announcement": "欢迎加入 [WTOF]!可在联队页面右上角点击「联队载具」或「活跃度」查看研发进度。", + "region": "CN / Global", "autoAccept": true, "createdAfterDays": 0, + "rating": { "arc": 1840, "hist": 2150, "sim": 1620 }, + "members": [ + { "uid": "900001001", "nick": "Lin_Wei", "role": "LEADER", "title": "title_marshall", "icon": "cardicon_28", "unit": "cn_ztz_99a", "activity": 360 }, + { "uid": "900001002", "nick": "Elena_Valkyrie", "role": "DEPUTY", "title": "title_ace", "icon": "cardicon_fem_01", "unit": "su_27sm", "activity": 360 }, + { "uid": "900001003", "nick": "iron_tiger_88", "role": "OFFICER", "title": "title_tank_destroyer", "icon": "cardicon_14", "unit": "germ_leopard_2a7v", "activity": 360 }, + { "uid": "900001004", "nick": "Tomcat_Actual", "role": "OFFICER", "title": "title_jet_powered", "icon": "cardicon_07", "unit": "f_14b", "activity": 345 }, + { "uid": "900001005", "nick": "Kuroshio_DD", "role": "SERGEANT", "title": "title_sea_wolf", "icon": "cardicon_19", "unit": "jp_destroyer_shimakaze", "activity": 330 }, + { "uid": "900001006", "nick": "Northern_Fox", "role": "REGULAR", "title": "title_sniper", "icon": "cardicon_11", "unit": "sw_strv_122b_plus", "activity": 310 } + ] + }, + { + "id": "500002", "tag": "=PLAF=", "name": "Red Falcon Aviation Wing", "type": "normal", + "slogan": "鹰击长空 · 现代喷气空战与陆空协同联队", + "desc": "专注于高阶喷气机与现代主战坦克联合作战的离线联队,支持自动入队与高活跃度加成。", + "announcement": "本期联队研发推荐:F-16A OCU、苏-33、豹 2PL、M1A1 AIM。", + "region": "Asia", "autoAccept": true, "createdAfterDays": 12, + "rating": { "arc": 1690, "hist": 2040, "sim": 1780 }, + "members": [ + { "uid": "900002001", "nick": "SkyDragon_J20", "role": "LEADER", "title": "title_ace", "icon": "cardicon_25", "unit": "j_11a", "activity": 360 }, + { "uid": "900002002", "nick": "Thunderbolt_CN", "role": "DEPUTY", "title": "title_pilot", "icon": "cardicon_09", "unit": "jh_7a", "activity": 360 }, + { "uid": "900002003", "nick": "SteelWall_99", "role": "OFFICER", "title": "title_unstoppable", "icon": "cardicon_16", "unit": "cn_vt_4a1", "activity": 350 }, + { "uid": "900002004", "nick": "NightHawk_04", "role": "REGULAR", "title": "title_eagle", "icon": "cardicon_05", "unit": "f_15j_kai", "activity": 300 } + ] + }, + { + "id": "500003", "tag": "-1STG-", "name": "1st Armored Guards Division", "type": "normal", + "slogan": "Steel & Fire — Heavy Armor Historical Squadron", + "desc": "Classic and modern armored warfare squadron. Open auto-accept recruitment for all tank commanders.", + "announcement": "Squadron vehicles ready for research at full 20,000 RP per period.", + "region": "EU / Global", "autoAccept": true, "createdAfterDays": 24, + "rating": { "arc": 1920, "hist": 1980, "sim": 1510 }, + "members": [ + { "uid": "900003001", "nick": "Kommissar_KVs", "role": "LEADER", "title": "title_hero", "icon": "cardicon_22", "unit": "ussr_t_90m", "activity": 360 }, + { "uid": "900003002", "nick": "PanzerMeyer_IV", "role": "OFFICER", "title": "title_tankman", "icon": "cardicon_12", "unit": "germ_pzkpfw_VI_ausf_h1_tiger", "activity": 340 }, + { "uid": "900003003", "nick": "DesertRat_UK", "role": "REGULAR", "title": "title_conqueror", "icon": "cardicon_18", "unit": "uk_challenger_2_black_night", "activity": 290 } + ] + }, + { + "id": "500004", "tag": "^82AB^", "name": "82nd Combined Task Force", "type": "normal", + "slogan": "All The Way — Air, Ground & Naval Task Force", + "desc": "需要审批模式的示例联队(用于测试发送与撤回入队申请流程)。若想立即加入联队,请选择 [WTOF]、=PLAF= 或 -1STG-。", + "announcement": "Manual application review enabled for testing request/cancel workflow.", + "region": "NA", "autoAccept": false, "createdAfterDays": 35, + "rating": { "arc": 1550, "hist": 1760, "sim": 1490 }, + "members": [ + { "uid": "900004001", "nick": "Major_Winters", "role": "LEADER", "title": "title_brother_in_arms", "icon": "cardicon_03", "unit": "us_m1a2_sep2_abrams", "activity": 360 }, + { "uid": "900004002", "nick": "Mustang_Lead", "role": "OFFICER", "title": "title_ace", "icon": "cardicon_08", "unit": "p-51d-30_usaaf_korea", "activity": 315 } + ] + }, + { + "id": "500005", "tag": "**RCON**", "name": "Reconnaissance Battalion Alpha", "type": "battalion", + "slogan": "轻量级战术分队 · 侦察与快速反应", + "desc": "战斗群(Battalion)类型预置联队,开启自动加入,支持体验战斗群架构与联队扩编。", + "announcement": "轻装侦察分队常驻开放。", + "region": "Global", "autoAccept": true, "createdAfterDays": 48, + "rating": { "arc": 1410, "hist": 1610, "sim": 1320 }, + "members": [ + { "uid": "900005001", "nick": "Ghost_Scout", "role": "LEADER", "title": "title_scout", "icon": "cardicon_15", "unit": "us_hstvl", "activity": 360 }, + { "uid": "900005002", "nick": "Lynx_Spotter", "role": "REGULAR", "title": "title_sniper", "icon": "cardicon_20", "unit": "it_centauro_rgo_120", "activity": 280 } + ] + } + ] + } +} diff --git a/packages/local-service/tuning/limits.jsonc b/packages/local-service/tuning/limits.jsonc new file mode 100644 index 0000000..b264435 --- /dev/null +++ b/packages/local-service/tuning/limits.jsonc @@ -0,0 +1,7 @@ +// 离线版自定的上限(原版由服务器决定,客户端数据里没有)。游戏规定的上限(例如备用载具最多 100 个,scripts/weaponry/weaponryConsts.nut)不在这里,按游戏的来。 +{ + // 一次最多买几张经典道具(cln_buy_item 的数量) + "itemPiecesPerPurchase": 1000, + // 存档里最多保留几条开箱记录(userlogs,客户端用它播放开箱动画、核对奖品),超出的删最早的 + "userLogsKept": 80 +} diff --git a/packages/local-service/tuning/marketplace.jsonc b/packages/local-service/tuning/marketplace.jsonc new file mode 100644 index 0000000..ffb525a --- /dev/null +++ b/packages/local-service/tuning/marketplace.jsonc @@ -0,0 +1,262 @@ +// 本地交易所(功能清单 G 节"市场";implementation notes 第 6、8 节):用 GJN 买兑换券,买到的券进游戏库存。 +// GJN 可以写两位小数(官方 GJN 价格等于美元价格)。 +{ + // 每次最多买几张 + "maxPerPurchase": 20, + + // 载具券(shop.blk 里有 marketplaceItemdefId 的载具) + "vehicleCoupons": { + // 单辆车的价格(GJN)。来源:原作者项目 data/market-catalog.json 的 referencePriceCents, + // 原作者在官方交易所记录的成交参考价(记录日期 2026-11-02 ~ 2026-11-02)。 + "byVehicle": { + "a6m6c": 22.99, + "a_7k": 88.0, + "b7a2_homare_23": 20.0, + "beaufighter_mk1_40mm": 14.79, + "bf-109e-7": 1176.48, + "bf-109f-4_hungary": 30.8, + "bf-110c-6": 17.99, + "bi": 160.0, + "boston_mk_1": 63.97, + "buccaneer_s1": 37.0, + "bv-155b-1": 29.99, + "cn_plz_83_130": 37.0, + "cn_qn506": 56.0, + "cn_t_80ud_478be": 24.97, + "cn_type_64": 55.99, + "cn_wz_141": 25.0, + "cr_32_bis": 57.99, + "db_7": 9.49, + "douglas_a_1h": 200.0, + "f-4f": 63.89, + "f-5a": 64.0, + "f-5ag_norway": 41.8, + "f11f_1_late": 40.0, + "f2g-1": 43.99, + "f4d_1": 35.29, + "f4f-4_martlet_mk4": 14.77, + "f4u-6_au-1": 168.0, + "f7f3": 52.19, + "f_100f_china": 54.0, + "f_106a_1972": 39.99, + "f_14a_iriaf": 119.99, + "f_16a_block_5_netherlands": 28.49, + "f_16xl": 41.5, + "f_6c_pakistan": 17.5, + "fj_4b_agm_12b": 30.0, + "fr_amd_35_sa35": 5.93, + "fr_amx_50_1950": 84.99, + "fr_amx_50_surblinde": 1649.95, + "fr_amx_elc_901": 25.74, + "fr_arras_class_amiens": 6.1, + "fr_battleship_strasbourg": 59.75, + "fr_m46_patton": 28.88, + "fr_panhard_ebr_1963": 84.79, + "fr_trident_class_glaive_p671": 9.97, + "fw-189a-1": 13.67, + "fw-190c": 31.5, + "germ_battlecruiser_mackensen_class": 28.24, + "germ_battleship_baden": 60.0, + "germ_battleship_ostfriesland": 39.66, + "germ_boxer_3105": 41.0, + "germ_destroyer_class1924_jaguar1941": 16.4, + "germ_frigate_koln_lubeck": 87.46, + "germ_kv_1B_finland": 69.0, + "germ_leopard_2_pt14": 139.8, + "germ_leopard_2av": 46.97, + "germ_leopard_c2_mexas": 74.5, + "germ_panzerjager_tiger_P_elefant": 148.0, + "germ_pzkpfw_VI_ausf_h1_tiger_animal_version": 87.7, + "germ_pzkpfw_VI_tiger_P": 58.99, + "germ_sdkfz_234_1": 41.96, + "germ_sdkfz_234_3": 25.52, + "germ_sdkfz_234_4": 178.95, + "germ_sdkfz_251_10": 27.87, + "germ_spz_12_3": 41.9, + "germ_th_400": 21.6, + "germ_th_800_bismark": 64.0, + "germ_type143_bussard": 35.99, + "germ_vilkas": 35.52, + "germ_vsw_flak_41": 129.0, + "germ_vt_1_2": 346.5, + "h-75a-2_finland": 13.97, + "h_34": 75.0, + "he-177a-3": 39.99, + "he51b_2w": 11.39, + "he_112b_2": 198.99, + "i_180": 31.8, + "i_29": 15.55, + "iar_93b": 39.9, + "il_2_m82": 22.87, + "il_8_1944": 14.0, + "il_sholef": 22.99, + "it_albatros_class_f544": 19.81, + "it_aubl_74_60_70m": 45.0, + "it_breda_52_autocannone": 31.98, + "it_cruiser_cadorna_class_cadorna": 17.15, + "it_fiat_6614_firos": 26.9, + "itp_m1": 26.4, + "j6k1": 72.0, + "jaguar_e": 54.0, + "jaguar_is": 28.57, + "jp_armoredcruiser_kurama": 36.85, + "jp_battlecruiser_haruna": 31.99, + "jp_battlecruiser_kirishima": 31.8, + "jp_battleship_tosa": 27.83, + "jp_destroyer_suzutsuki": 4.4, + "jp_destroyer_yugure": 17.5, + "jp_destroyer_yuudachi": 16.87, + "jp_escort_hiburi_class_shisaka": 14.99, + "jp_pzkpfw_VI_ausf_e_tiger": 86.0, + "ju-388j": 74.96, + "kfir_c10_colombia": 32.88, + "kfir_c2": 56.0, + "ki_21_1hei": 29.7, + "ki_48_2_otsu": 6.87, + "ki_94_2": 26.0, + "la_174": 48.0, + "lagg-3-34": 500.0, + "lagg-i-301": 24.0, + "marut_mk1": 17.5, + "mb_152c1": 21.77, + "mbr-2": 30.98, + "me-262a-2a": 64.4, + "meteor_frmk9_iaf": 15.99, + "mig-21_pfm": 54.99, + "mig_23mf_germany": 41.99, + "mig_25pd": 38.0, + "mirage_2000c_s4": 42.0, + "mosquito_j30_sweden": 5.89, + "p-26a_34": 130.0, + "p-38j_marge": 33.29, + "p-39q_25_france": 30.0, + "p-40c": 29.8, + "p-43a-1": 14.0, + "p-51b_7_sweden": 35.49, + "p-51c-10_france": 18.99, + "p-51c-11-nt_china": 9.83, + "p-59a": 50.0, + "p-63c-5_kingcobra_animal_version": 71.76, + "pbm_5a": 11.5, + "po-2m": 18.75, + "pv_2d": 43.7, + "re_2005_vdm": 19.96, + "sb2c_5_thailand": 12.94, + "sb_25j_netherlands": 7.06, + "spitfire_lf_mk9c_cw_greece": 10.4, + "spitfire_mk5b_float": 7.13, + "spitfire_mk9c_4cannons": 57.0, + "strikemaster_mk88": 68.99, + "su-8": 84.64, + "su_25_558arz": 51.8, + "sw_kungstiger": 69.0, + "sw_patria_amv_ctcv_105": 38.5, + "sw_patria_bmp_3": 12.0, + "sw_pbil_m40": 20.06, + "tis_ma": 93.99, + "tornado_ids_de_mfg": 40.99, + "uk_a_13_mk2_1939": 18.49, + "uk_a_22f_mk_7_churchill_crocodile": 68.4, + "uk_a_33_excelsior": 106.98, + "uk_a_34_comet_iron_duke": 35.99, + "uk_alecto_mk_1": 18.87, + "uk_armored_car_aec_mk_2": 34.06, + "uk_battlecruiser_renown": 33.87, + "uk_battleship_q_elizabet_class_barham": 57.99, + "uk_boxer_crv_block2": 17.99, + "uk_centurion_mk_2": 129.99, + "uk_centurion_mk_5_raac": 69.99, + "uk_churchill_avre": 29.65, + "uk_cruiser_tiger": 44.97, + "uk_destroyer_g_garland": 5.29, + "uk_destroyer_tribal_mohawk": 30.49, + "uk_frigate_river": 19.98, + "uk_fv107_scimitar_mk2": 9.18, + "uk_matilda_hedgehog": 15.5, + "uk_mk1_grant": 14.0, + "uk_ram_90mm_aa": 41.8, + "uk_sgb_309": 21.77, + "uk_shir_2": 34.35, + "us_ags_teledyne": 98.0, + "us_battleship_mississippi": 50.0, + "us_battleship_oklahoma": 24.84, + "us_ccvl": 94.0, + "us_cruiser_baltimore_class": 32.0, + "us_cruiser_des_moines_class_newport_news": 30.78, + "us_destroyer_porter_1944": 27.81, + "us_destroyer_somers_davis": 42.0, + "us_efv_p1": 15.85, + "us_losat_ccv": 68.0, + "us_lvt_4_zis_2": 29.9, + "us_m551_76": 99.78, + "us_m60a3_slep": 182.99, + "us_m6a2e1": 287.99, + "us_m8_greyhound": 23.47, + "us_m8a1": 22.59, + "us_merkava_mk_1": 115.88, + "us_merkava_mk_2b_late": 68.96, + "us_merkava_mk_3d": 98.79, + "us_pt811": 35.65, + "us_t18_e2": 77.99, + "us_t30": 97.09, + "us_t86": 11.77, + "us_xm_8": 109.99, + "ussr_a_12_mk_2_matilda_2A_F96": 33.99, + "ussr_ba_11": 32.49, + "ussr_battleship_oktyabrskaya_revolutsiya": 16.0, + "ussr_bm_13n": 79.98, + "ussr_bmd_4": 42.0, + "ussr_bt_7a_f32": 32.0, + "ussr_cruiser_maxim_gorky": 20.0, + "ussr_cruiser_omaha_class_murmansk": 12.49, + "ussr_cruiser_shcherbakov": 37.77, + "ussr_destroyer_leningrad": 235.31, + "ussr_is_7": 1999.99, + "ussr_kv_220": 67.5, + "ussr_kv_2_1940": 62.38, + "ussr_kv_8": 10.67, + "ussr_m3c": 102.86, + "ussr_mbk_161_1943": 15.0, + "ussr_mpk_122bis": 22.97, + "ussr_mpk_201k": 13.37, + "ussr_object_248": 81.4, + "ussr_object_279": 1450.0, + "ussr_object_292": 177.0, + "ussr_pr_205pe_k225": 37.85, + "ussr_pt_76_57": 744.98, + "ussr_pzkpfw_V": 50.0, + "ussr_rbt_5": 64.99, + "ussr_su_76d": 25.19, + "ussr_su_76m_5st_kav_corps": 16.35, + "ussr_su_85a": 37.83, + "ussr_t_10a": 129.99, + "ussr_t_26E": 67.99, + "ussr_t_34E": 33.69, + "ussr_t_34_85_zis_53_v80": 19.39, + "ussr_t_44_po": 25.7, + "ussr_t_72b3_arena": 38.5, + "ussr_t_72m2_moderna": 535.0, + "ussr_t_80um2": 69.0, + "ussr_type_62": 172.99, + "whirlwind_p9": 36.97, + "xf5f": 27.2, + "yak-3_eremin": 35.41, + "yak-9t_france": 41.99 + }, + // 上表没有的载具(例如游戏更新新加的)按等级定价:取第一个 upToRank 不小于载具等级的档位。离线版自定。 + "byRank": [ + { "upToRank": 1, "gjn": 8 }, { "upToRank": 2, "gjn": 14 }, { "upToRank": 3, "gjn": 22 }, { "upToRank": 4, "gjn": 35 }, + { "upToRank": 5, "gjn": 48 }, { "upToRank": 6, "gjn": 59 }, { "upToRank": 7, "gjn": 69 }, { "upToRank": 99, "gjn": 75 } + ], + // 券的品质(决定名字颜色),按载具等级。离线版自定。 + "qualityByRank": [ { "upToRank": 3, "quality": 2 }, { "upToRank": 5, "quality": 3 }, { "upToRank": 99, "quality": 4 } ] + }, + + // 外观券和解锁券:每类一个价格(GJN)和品质。离线版自定。 + "cosmeticCoupons": { + "skin": { "gjn": 5, "quality": 2 }, + "decal": { "gjn": 3, "quality": 2 }, + "attachable": { "gjn": 8, "quality": 3 }, + "unlock": { "gjn": 6, "quality": 3 } + } +} diff --git a/packages/local-service/tuning/new-profile.jsonc b/packages/local-service/tuning/new-profile.jsonc new file mode 100644 index 0000000..94716ac --- /dev/null +++ b/packages/local-service/tuning/new-profile.jsonc @@ -0,0 +1,6 @@ +// 新存档的初始货币(原话 98:新存档初始 500 金鹰、15 万银狮,和正版新账号一样)。gjn 可以写两位小数。 +{ + "silverLions": 150000, + "goldenEagles": 500, + "gjn": 0 +} diff --git a/packages/local-service/tuning/recycling.jsonc b/packages/local-service/tuning/recycling.jsonc new file mode 100644 index 0000000..9d45fa1 --- /dev/null +++ b/packages/local-service/tuning/recycling.jsonc @@ -0,0 +1,21 @@ +// 经典道具回收与再合成(功能清单 H 节"融炼 / 合成";implementation notes 第 6、8 节)。 +// 回收:每件经典道具回收成哪种零件,由游戏数据 config/items.blk 的 recycleItemResult 决定(不在这里)。 +// 再合成:零件换随机经典道具的配方,原版由服务器下发,离线版自定,就是下面这些。 +{ + // 零件在库存里显示的名字;键是零件编号(items.blk 的 recycleItemResult)。 + "partNames": { + "299000": { "zh": "备用载具回收组件", "en": "Spare Supply Fragment" }, + "299001": { "zh": "加成卡回收组件", "en": "Booster Fragment" }, + "299002": { "zh": "折扣券回收组件", "en": "Coupon Fragment" }, + "299003": { "zh": "任务令回收组件", "en": "Order Fragment" }, + "299004": { "zh": "合同回收组件", "en": "Wager Fragment" } + }, + // 同种零件几个换一件该类随机道具 + "partsPerItem": 2, + // 每种零件最多能换出几种道具(该类的永久道具按名字排序后取前几种) + "itemsPerPart": 8, + // 一张包装券给几个道具;没写的道具给 1 个 + "piecesPerItem": { "item_universal_spare": 3 }, + // 某种零件没有可换的道具时(例如折扣券都是限时的),改为换这些零件对应的道具 + "fallbackParts": [299000, 299001] +} diff --git a/packages/local-service/tuning/redeem-codes.jsonc b/packages/local-service/tuning/redeem-codes.jsonc new file mode 100644 index 0000000..3f72ea1 --- /dev/null +++ b/packages/local-service/tuning/redeem-codes.jsonc @@ -0,0 +1,23 @@ +// 兑换码(功能清单 G 节;implementation notes 第 5.3 节)。在本地网页商店和游戏原生的兑换码窗口里都能用,输入不分大小写。 +// 原话 116:GJN 充值码和新手礼包码保留,定位是给玩家的作弊码。 +{ + // 高级账户天数码:<前缀>-<天数>D,例如 PREMIUM-30D。 + "premiumDays": { + "prefixes": ["PREMIUM", "WTO-PREM", "PREM", "VIP"], + "maxDays": 3650, + // 页面上展示的示例 + "examples": ["PREMIUM-7D", "PREMIUM-30D", "PREMIUM-365D"] + }, + + // GJN 充值码(作弊码):<前缀>-<数量>,例如 WTO-GJN-1000。 + "gjn": { + "prefixes": ["WTO-GJN", "GJN"], + "maxAmount": 1000000, + "examples": ["WTO-GJN-100", "WTO-GJN-1000"] + }, + + // 固定兑换码:每个存档只能用一次。奖励可以写 premiumDays(高级账户天数)、goldenEagles(金鹰)、silverLions(银狮)、gjn,不写的就是 0。 + "fixedCodes": { + "WTO-STARTER": { "premiumDays": 7, "goldenEagles": 1000, "gjn": 100 } + } +} diff --git a/packages/local-service/tuning/store.jsonc b/packages/local-service/tuning/store.jsonc new file mode 100644 index 0000000..1407521 --- /dev/null +++ b/packages/local-service/tuning/store.jsonc @@ -0,0 +1,176 @@ +// 本地商店的商品和价格(功能清单 G 节;implementation notes 第 5、8 节)。 +// 原版的这些价格由 Gaijin 服务器下发,游戏文件里没有;这里是离线版的取值,出处见 implementation notes 第 8 节。 +{ + // GJN 价格一律是官方 Gaijin 商店的美元价,1 GJN = 1 美元(用户原话 121)。 + + // 金鹰包:用 GJN 买(游戏内的付款窗口、本地网页商店)。 + // id 必须和游戏 aces.vromfs.bin 的 config/gui.blk bundles/guid 里的名字一致,游戏靠它找到商品。 + // 档位和价格按官方商店 catalog.php?category=GoldenEagles(2026-11-25):官方只卖这 6 档(gui.blk 里另有 500、15000、20000 三档,官方不卖); + // 5000 以上三档官方页面同时标原价和现价($33、$66、$165),这里取现价。 + "goldenEaglePacks": [ + { "id": "eagles150", "goldenEagles": 150, "gjn": 0.99 }, + { "id": "eagles1000", "goldenEagles": 1000, "gjn": 6.6 }, + { "id": "eagles2500", "goldenEagles": 2500, "gjn": 16.5 }, + { "id": "eagles5000", "goldenEagles": 5000, "gjn": 24.75 }, + { "id": "eagles10000", "goldenEagles": 10000, "gjn": 49.5 }, + { "id": "eagles25000", "goldenEagles": 25000, "gjn": 114 } + ], + + // 银狮包:在游戏内的货币商店里用金鹰买。数值来自原作者项目 backend/COMMERCE.md(原作者注明出处是社区 wiki wikiwiki.jp 的"課金"页)。 + "silverLionPacks": [ + { "id": "warpoints1k", "silverLions": 1000, "goldenEagles": 3 }, + { "id": "warpoints11k", "silverLions": 11000, "goldenEagles": 30 }, + { "id": "warpoints58k", "silverLions": 58000, "goldenEagles": 150 }, + { "id": "warpoints120k", "silverLions": 120000, "goldenEagles": 300 }, + { "id": "warpoints630k", "silverLions": 630000, "goldenEagles": 1500 }, + { "id": "warpoints1300k", "silverLions": 1300000, "goldenEagles": 3000 } + ], + + // 高级账户:在游戏内的高级账户窗口里用金鹰买。 + "premiumForGoldenEagles": [ + { "id": "prem_1d", "days": 1, "goldenEagles": 190 }, + { "id": "prem_7d", "days": 7, "goldenEagles": 690 }, + { "id": "prem_15d", "days": 15, "goldenEagles": 1190 }, + { "id": "prem_30d", "days": 30, "goldenEagles": 1900 }, + { "id": "prem_90d", "days": 90, "goldenEagles": 4900 }, + { "id": "prem_365d", "days": 365, "goldenEagles": 14900 } + ], + + // 高级账户:用 GJN 买。id 必须和构建写进 gui.blk 的名字一致(packages/build/src/main-pack.ts EXTRA_STORE_BUNDLE_GUIDS)。 + // 档位和价格按官方商店 catalog.php?category=PremiumAccount(2026-11-25)。 + "premiumForGjn": [ + { "id": "wto_prem_20d", "days": 20, "gjn": 7.49 }, + { "id": "wto_prem_60d", "days": 60, "gjn": 19.99 }, + { "id": "wto_prem_180d", "days": 180, "gjn": 39.99 } + ], + + // 礼包载具:每辆科技树礼包车一个礼包,用 GJN 买,买下送载具和附赠内容。 + "vehiclePacks": { + // 默认内容按载具等级:取第一个 upToRank 不小于载具等级的档位。 + // 只用于官方价格查不到的车(implementation notes 第 8 节)。每档取官方礼包在该等级最常见的价格和附赠内容; + // 2 级官方没有单车礼包,按上面的规则落到 3 级那档。 + "byRank": [ + { "upToRank": 1, "gjn": 4.99, "goldenEagles": 0, "premiumDays": 7 }, + { "upToRank": 3, "gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15 }, + { "upToRank": 4, "gjn": 39.99, "goldenEagles": 1000, "premiumDays": 7 }, + { "upToRank": 5, "gjn": 49.99, "goldenEagles": 2000, "premiumDays": 15 }, + { "upToRank": 6, "gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15 }, + { "upToRank": 7, "gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20 }, + { "upToRank": 99, "gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30 } + ], + // 单辆车的礼包内容,覆盖按等级的默认值;键是载具名(char.vromfs.bin config/wpcost.blk)。 + // 价格是官方礼包的美元价(implementation notes,出处见 implementation notes 第 8 节); + // 附赠的金鹰和高级账户天数按官方礼包页面写的内容。多车礼包(如 Two Fronts)里的每辆车各记一次整个礼包的价格。 + "byVehicle": { + "a-26c-45-dt": {"gjn": 19.99, "goldenEagles": 2000, "premiumDays": 15}, + "a_10a_early": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "a_7e_greece": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "ah_64d_lightweight_japan": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "alpha_jet_a_jabog41": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "arado_234b_2_mt": {"gjn": 49.99, "goldenEagles": 2000, "premiumDays": 15}, + "cf_188a_canada": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "cn_al_khalid_1": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "cn_mbt2000_sm": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "cn_plz_45": {"gjn": 39.99, "goldenEagles": 1000, "premiumDays": 7}, + "cn_ztz_96b": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "f-4s": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "f-5c": {"gjn": 64.99, "goldenEagles": 2000, "premiumDays": 15}, + "f4u-4b_vmf_214": {"gjn": 29.99, "goldenEagles": 1000, "premiumDays": 15}, + "f_14d": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "f_16a_block_10_netz_mod": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "f_16am_block_20_mlu_netherlands": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "f_2a_adtw": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "fa_18c_early": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "fa_18c_switzerland": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "fa_18d_late": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "fr_battleship_richelieu_class_jean_bart": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "fr_leopard_2a4nl_les": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "fr_somua_sm": {"gjn": 44.99, "goldenEagles": 1000, "premiumDays": 7}, + "germ_battleship_gneisenau_380mm": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "germ_erprobungstrager_3_achs_turm": {"gjn": 49.99, "goldenEagles": 2000, "premiumDays": 15}, + "germ_flakpanzer_IV_Ostwind_2_net": {"gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15}, + "germ_leopard_2a4_pzbtl_123": {"gjn": 64.99, "goldenEagles": 2000, "premiumDays": 15}, + "germ_leopard_2a4m_can": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "germ_leopard_2a4m_can_sm": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "germ_leopard_a1a1_120": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "germ_marder_clovis": {"gjn": 49.99, "goldenEagles": 2000, "premiumDays": 15}, + "germ_pzkpfw_38t_Aufklarungspanzer": {"gjn": 4.99, "goldenEagles": 0, "premiumDays": 7}, + "germ_pzkpfw_VI_ausf_b_tiger_IIh_sla": {"gjn": 39.99, "goldenEagles": 1000, "premiumDays": 7}, + "germ_pzkpfw_VI_ausf_h1_tiger_east": {"gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15}, + "germ_pzkpfw_VI_ausf_h1_tiger_west": {"gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15}, + "germ_schutzenpanzer_puma_vjtf_mod": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "hawk_t1a": {"gjn": 49.99, "goldenEagles": 2000, "premiumDays": 15}, + "ia_58a_pucara": {"gjn": 39.99, "goldenEagles": 2000, "premiumDays": 15}, + "il_merkava_mk_3_raam_segol": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "it_battleship_giulio_cesare": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "it_c1_ariete_certezza": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "j_22m1a": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "jp_battleship_nagato": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "jp_type_16_mod": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "jp_type_61_mod": {"gjn": 39.99, "goldenEagles": 1000, "premiumDays": 7}, + "jp_type_90b_camo": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "jp_type_90b_sm": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "ka_50": {"gjn": 49.99, "goldenEagles": 2000, "premiumDays": 15}, + "l_39za": {"gjn": 49.99, "goldenEagles": 2000, "premiumDays": 15}, + "mig-21_bis_lazur": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "mig_23ml": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "mig_29_9_12_sniper": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "mirage_f1c_200": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "p-51d-20-na": {"gjn": 29.99, "goldenEagles": 2000, "premiumDays": 15}, + "q_5d": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "rah_66": {"gjn": 49.99, "goldenEagles": 2000, "premiumDays": 15}, + "saab_ajs37_early": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "saab_ja37di_f21": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "saab_jas39_pre_serie": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "su_25k": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "su_25tm": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "su_30mk2v_venezuela": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "su_30mkk": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "sw_cv_90105_tml": {"gjn": 64.99, "goldenEagles": 2000, "premiumDays": 15}, + "sw_k9_vidar": {"gjn": 49.99, "goldenEagles": 2000, "premiumDays": 15}, + "sw_strv121b_christian2": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "tiger_had_spain": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "tornado_ids_de_wtd61": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "uk_a30_sp_avenger_kit_3rank": {"gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15}, + "uk_battleship_duke_of_york": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "uk_battleship_nelson": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "uk_challenger_1_mk_3_gulf": {"gjn": 64.99, "goldenEagles": 2000, "premiumDays": 15}, + "uk_challenger_2_megatron_sm": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "uk_crusader_aa_mk_2_kit_3rank": {"gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15}, + "uk_olifant_optimering": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "uk_sherman_vc_firefly_kit_3rank": {"gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15}, + "uk_vickers_gbt_155": {"gjn": 39.99, "goldenEagles": 1000, "premiumDays": 7}, + "us_battleship_colorado_class_maryland": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "us_destroyer_fletcher_bennion": {"gjn": 49.99, "goldenEagles": 2000, "premiumDays": 15}, + "us_m18_hellcat_kit_3rank": {"gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15}, + "us_m1_abrams_kvt": {"gjn": 64.99, "goldenEagles": 2000, "premiumDays": 15}, + "us_m1a1_hc_usmc": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "us_m1a1_hc_usmc_sm": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "us_m3a1_stuart_usmc": {"gjn": 4.99, "goldenEagles": 0, "premiumDays": 7}, + "us_m4a3e8_76w_sherman_kit_3rank": {"gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15}, + "us_m60a1_rise_mod": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "us_rdf_lt": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "us_skink_aa_kit_3rank": {"gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15}, + "us_stingray_2": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "us_t29": {"gjn": 39.99, "goldenEagles": 1000, "premiumDays": 7}, + "us_t58": {"gjn": 49.99, "goldenEagles": 2000, "premiumDays": 15}, + "us_xm1_chrysler": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "ussr_battlecruiser_sevastopol": {"gjn": 79.99, "goldenEagles": 3000, "premiumDays": 30}, + "ussr_bmd_4m": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "ussr_bmpt_72": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "ussr_is_1_kit_3rank": {"gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15}, + "ussr_is_2m_kit_4rank": {"gjn": 59.99, "goldenEagles": 1000, "premiumDays": 15}, + "ussr_is_6": {"gjn": 44.99, "goldenEagles": 1000, "premiumDays": 7}, + "ussr_m53_59_kit_4rank": {"gjn": 59.99, "goldenEagles": 1000, "premiumDays": 15}, + "ussr_object_120": {"gjn": 49.99, "goldenEagles": 2000, "premiumDays": 15}, + "ussr_sdkfz_251_21_kit_3rank": {"gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15}, + "ussr_t_34_85_zis_53_kit_3rank": {"gjn": 34.99, "goldenEagles": 1000, "premiumDays": 15}, + "ussr_t_44_kit_4rank": {"gjn": 59.99, "goldenEagles": 1000, "premiumDays": 15}, + "ussr_t_55_am": {"gjn": 59.99, "goldenEagles": 2000, "premiumDays": 15}, + "ussr_t_72av_turms": {"gjn": 64.99, "goldenEagles": 2000, "premiumDays": 15}, + "ussr_t_80ue1": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "ussr_t_80ue1_sm": {"gjn": 69.99, "goldenEagles": 2500, "premiumDays": 20}, + "wyvern_s4": {"gjn": 29.99, "goldenEagles": 1000, "premiumDays": 15} + } + } +} diff --git a/packages/local-service/tuning/supply-chests.jsonc b/packages/local-service/tuning/supply-chests.jsonc new file mode 100644 index 0000000..194ca4c --- /dev/null +++ b/packages/local-service/tuning/supply-chests.jsonc @@ -0,0 +1,54 @@ +// 新版库存里的银狮补给箱(道具商店里用银狮买,开箱掉落兑换券或经典道具;implementation notes 第 6~8 节)。 +// 原作者没有对应的箱子,下面的数值都是离线版自定。 +// +// 每组奖品写一种,"weightEach" 是组里每一项的权重: +// { "classicItems": { "recyclePart": 零件编号, "pick": 取几种 } } 经典道具包装券,按回收零件分类(299000 备用载具、299001 加成卡、299002 折扣、299003 任务令、299004 合同),按名字排序后取前几种 +// { "coupons": { "kind": "skin|decal|attachable", "skip": 跳过前几张, "pick": 取几张 } } 外观兑换券,按编号排序 +// { "marketVehicles": { "minRank": 1, "maxRank": 4, "pick": 6 } } 交易所载具券,按等级、国家、名字排序后各国轮流取 +{ + // 开箱一次最多买几个(游戏道具商店里的数量上限) + "maxPerPurchase": 10, + "chests": [ + { + "id": 910001, + "openerId": 910101, + "silverLions": 60000, + "quality": 2, + "icon": "!#ui/images/chests/items_box2.avif", + "title": { "zh": "战术物资补给箱", "en": "Tactical Supply Chest" }, + "description": { + "zh": "银狮物资补给箱:内含加成卡、通用备用载具、涂装/贴花/挂件券及 I~IV 级交易所载具兑换券(点击可查看各项掉率)。", + "en": "Silver Lion supply chest with boosters, universal backups, decoration coupons and Rank I-IV marketplace vehicle coupons." + }, + "prizes": [ + { "classicItems": { "recyclePart": 299000, "pick": 3 }, "weightEach": 80 }, + { "classicItems": { "recyclePart": 299001, "pick": 5 }, "weightEach": 80 }, + { "classicItems": { "recyclePart": 299003, "pick": 2 }, "weightEach": 80 }, + { "coupons": { "kind": "skin", "skip": 0, "pick": 3 }, "weightEach": 18 }, + { "coupons": { "kind": "decal", "skip": 0, "pick": 2 }, "weightEach": 18 }, + { "coupons": { "kind": "attachable", "skip": 0, "pick": 3 }, "weightEach": 18 }, + { "marketVehicles": { "minRank": 1, "maxRank": 4, "pick": 6 }, "weightEach": 4 } + ] + }, + { + "id": 910002, + "openerId": 910102, + "silverLions": 250000, + "quality": 4, + "icon": "!#ui/images/chests/items_box3.avif", + "title": { "zh": "典藏收藏家补给箱", "en": "Collector's Supply Chest" }, + "description": { + "zh": "高阶银狮补给箱:V 级以上交易所载具券和挂件、涂装券的掉率更高。", + "en": "High-tier Silver Lion supply chest with better odds for Rank V+ marketplace vehicle and decoration coupons." + }, + "prizes": [ + { "classicItems": { "recyclePart": 299000, "pick": 3 }, "weightEach": 45 }, + { "classicItems": { "recyclePart": 299001, "pick": 2 }, "weightEach": 45 }, + { "coupons": { "kind": "skin", "skip": 3, "pick": 5 }, "weightEach": 22 }, + { "coupons": { "kind": "decal", "skip": 2, "pick": 2 }, "weightEach": 22 }, + { "coupons": { "kind": "attachable", "skip": 3, "pick": 5 }, "weightEach": 22 }, + { "marketVehicles": { "minRank": 5, "maxRank": 99, "pick": 10 }, "weightEach": 12 } + ] + } + ] +} diff --git a/packages/local-service/tuning/trophies.jsonc b/packages/local-service/tuning/trophies.jsonc new file mode 100644 index 0000000..40c056e --- /dev/null +++ b/packages/local-service/tuning/trophies.jsonc @@ -0,0 +1,54 @@ +// 经典战利品箱(功能清单 H 节"银狮补给箱""奖池载具直购";implementation notes 第 7、8 节)。 +// 原版的箱子由服务器下发,客户端数据里没有;客户端按奖品权重自己算出并公示每项概率(calcTrophiesDropChance)。 +// +// 每项奖品写一种: +// { "silverLions": 数量, "weight": 权重 } +// { "goldenEagles": 数量, "weight": 权重 } +// { "item": "道具名", "count": 张数, "weight": 权重 } 道具名见 char.vromfs.bin config/items.blk +// { "itemsOfType": "道具类型", "pick": 取几种, "count": 每种张数, ... } 类型:rateBooster、wager、universalSpare 等;只取永久道具,按名字排序后取前几种 +// { "eventVehicles": { "minRank": 1, "maxRank": 3, "pick": 4 }, ... } 活动载具(不在交易所卖的),按等级、国家、名字排序后各国轮流取 +// 一组奖品(itemsOfType、eventVehicles)写 "weightEach"(每项的权重)或 "weightTotal"(整组的权重,平分给每项)。 +// 已拥有的载具不会被抽到。 +{ + "supplyTrophies": [ + { + // 银狮补给箱。价格和奖品权重来自原作者项目 data/offline-crate-rules.json(silverPerDraw、rawWeights, + // 权重相加为 100,即每抽的百分比)。原作者的"50 GJN"奖品(权重 0.01)在经典战利品箱里没有对应的奖品类型,没有放进来。 + "id": "wto_silver_supply_trophy", + "iconStyle": "small_wooden_box", + "silverLions": 60000, + "goldenEagles": 0, + "prizes": [ + { "silverLions": 10000, "weight": 28.34 }, + { "silverLions": 50000, "weight": 22 }, + { "silverLions": 100000, "weight": 11 }, + { "silverLions": 500000, "weight": 0.1 }, + { "silverLions": 1000000, "weight": 0.05 }, + { "goldenEagles": 100, "weight": 1 }, + { "goldenEagles": 500, "weight": 0.4 }, + { "goldenEagles": 1000, "weight": 0.1 }, + { "item": "item_universal_spare", "count": 1, "weight": 22 }, + { "itemsOfType": "wager", "pick": 18, "count": 1, "weightTotal": 12 }, + { "eventVehicles": { "minRank": 1, "maxRank": 8, "pick": 12 }, "weightTotal": 3 } + ] + }, + { + // 老兵补给箱:原作者没有对应的箱子,离线版自定。 + "id": "wto_veteran_supply_trophy", + "iconStyle": "big_chest", + "silverLions": 150000, + "goldenEagles": 0, + "prizes": [ + { "eventVehicles": { "minRank": 4, "maxRank": 8, "pick": 6 }, "weightEach": 4 }, + { "goldenEagles": 150, "weight": 10 }, + { "silverLions": 500000, "weight": 12 }, + { "silverLions": 120000, "weight": 28 }, + { "item": "item_universal_spare", "count": 5, "weight": 30 }, + { "itemsOfType": "rateBooster", "pick": 4, "count": 1, "weightEach": 22 } + ] + } + ], + + // 奖池载具直购:每辆活动载具一个只能买一次的箱子,用金鹰买。价格来自原作者 offline-crate-rules.json 的 directVehiclePriceGE。 + "directVehicles": { "goldenEagles": 20000 } +}