Price LocalMP battle rewards in the local service

The LocalMP host has no battle server, and the previous bridge filled the
gap by computing money in the client: the native ledger wrote invented
amounts into SessionStatsNet, the spawn patch derived reward rates from
warpoints.blk, and the settlement patch summed and rescaled the result.
Rewards came out as zero or several orders of magnitude too high.

Now the client reports facts and the local service prices them.

Native (wto_ws.dll):
- local_mp_ledger.c is removed together with its SessionStatsNet
  offsets and four signatures (43 -> 39).
- local_mp_awards.c raises the HUD script event wtoLocalMpExpEvent for
  every combat event of the local player (event code, victim expClass
  and name, player or AI victim, friendly, naval damage). The DataBlock
  helpers and the HUD event queue are resolved from call sites inside
  GameSaveData::addScoreMessage, which already has a signature.

GUI patches:
- record-local-battle-awards records events and lives in nestdb and
  raises the stock InBattleReward banner from launch-time parameters.
- report-local-battle-settlement sends only facts and rebuilds the
  debriefing from the settled table; failures show the stock error box.
- use-settled-debriefing-stats makes gatherDebriefingResult read that
  table instead of the empty stat_get_exp().
- pass-spawn-modifications-blk no longer computes economy factors.

Local service:
- battle-economy dataset reads every reward factor from wpcost.blk,
  warpoints.blk and rank.blk; tuning/battle-economy.jsonc holds the
  mission score per event with its source (official values where
  published, otherwise marked).
- battle-economy.ts is the single pricing function, shared by the
  banner parameters and the settlement; battle-rewards.ts adds battle
  time, timed award, win/defeat bonus, activity, premium account,
  talisman, skill bonus and free research points; the debriefing table
  has the stat_get_exp() layout and travels in EULT_SESSION_RESULT.
- Crews earn skill points from the battle's research points.
- A battle left before it ends counts as a defeat.

Verified: npm run typecheck, check-gui (35 patches), check-patches,
check-offsets, native build. Not yet run in game.
This commit is contained in:
N0VAN0M4LY committed 2026-11-28 04:42:27 +08:00
1 parent b1392c0512
commit 7f570c85c3
39 files changed
+1488 -1128

No files matched your search

@@ -22,7 +22,7 @@ function onWtoBattleNotify(ev) {
if (ev?.func != "launch" || isInFlight())
return
let DataBlock = require("DataBlock")
let { ndbWrite } = require("nestdb")
let { ndbWrite, ndbExists, ndbDelete } = require("nestdb")
let guiMis = require("guiMission")
let { set_game_mode } = require("mission")
let { GM_DOMINATION } = require("%globalScripts/gameModeNativeConsts.nut")
@@ -38,6 +38,8 @@ function onWtoBattleNotify(ev) {
notifyQueueLeave({})
destroySessionScripted("on start wto local battle")
ndbWrite(["wto", "activeBattle"], ev.battle)
if (ndbExists(["wto", "battleLog"]))
ndbDelete(["wto", "battleLog"])
invalidateCrewsList(true)
let misBlk = wtoBlkFromWire(DataBlock(), ev.mission)
@@ -1,11 +1,14 @@
// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes.
// Send the vehicle's enabled and disabled modifications with every LocalMP spawn request, and count
// backup vehicles used for the settlement.
// Why the client: the battle server would read the modifications from the profile; on a LocalMP host
// the native spawn receiver (wto_ws.dll local_mp_loadout.c) only gets what this request carries.
// Without it: every spawned vehicle is stock (no fire extinguisher, smoke, repair kit, upgrades).
{
"id": "battle/pass-spawn-modifications-blk",
"title": "Pass enabled modifications, spaded extra-slot loadout, and unit reward rates on LocalMP spawn",
"title": "Pass enabled modifications and extra-slot loadout on LocalMP spawn",
"file": "scripts/respawn/respawn.nut",
"features": [
"modifications-loadout",
"local-battle"
"K-出生点数 / 重生"
],
"verified_on": [
"2.61.0.37"
@@ -6,7 +6,6 @@
let wtoBattle = wtoNdb.ndbTryRead(["wto", "activeBattle"])
let wtoGuiRespawn = require("guiRespawn")
let wtoChardRes = require("chardResearch")
let wtoBlkGetters = require("blkGetters")
let wtoUnitName = requestData?.name ?? ""
local wtoExtraSlot = null
foreach (slot in (wtoBattle?.extraBattleSlots ?? [])) {
@@ -30,24 +29,10 @@
else if (wtoChardRes.shopIsModificationPurchased(wtoUnitName, wtoModName))
wtoDisabledMods.append(wtoModName)
}
let wtoEdiff = this.getCurrentEdiff()
let wtoDiffRem = wtoEdiff >= 0 ? (wtoEdiff % 3) : 1
let wtoDiffSuffix = wtoDiffRem == 0 ? "Arcade" : wtoDiffRem == 1 ? "Historical" : "Simulation"
let wtoUnitCost = get_wpcost_blk()?[wtoUnitName]
let wtoWarBlk = wtoBlkGetters.get_warpoints_blk()
let wtoBlk = DataBlock()
wtoBlk.enabledMods = ";".join(wtoEnabledMods)
wtoBlk.disabledMods = ";".join(wtoDisabledMods)
wtoBlk.isSilentPreview = isSilent ? "1" : "0"
if (wtoUnitCost != null && wtoWarBlk != null) {
let wtoClassKillMul = wtoWarBlk.units[wtoUnitCost.unitClass].tofloat()
let wtoRewardMul = wtoUnitCost[$"rewardMul{wtoDiffSuffix}"].tofloat()
wtoBlk.wpPerKill = (wtoWarBlk.aKill.tofloat() * wtoClassKillMul * wtoWarBlk.wpMultiplier.tofloat() * wtoRewardMul).tofloat()
wtoBlk.expMul = wtoUnitCost.expMul.tofloat()
wtoBlk.battleTimeAward = wtoUnitCost[$"battleTimeAward{wtoDiffSuffix}"].tofloat()
wtoBlk.aiKillK = wtoWarBlk.aiKillK.tofloat()
wtoBlk.winK = wtoWarBlk.winK.tofloat()
}
if (!isSilent && (requestData?.spareUid ?? "") != "" && wtoUnitName != "") {
let prevSpares = wtoBattle?.usedSpares ?? {}
prevSpares[wtoUnitName] <- (prevSpares?[wtoUnitName] ?? 0) + 1
@@ -0,0 +1,3 @@
return {
g_hud_reward_message
}
@@ -0,0 +1,22 @@
// Record the local player's lives and combat events in a LocalMP battle and show their reward banner.
// Why the client: online the battle server prices each event and sends the banner (packet 0xb03d);
// a LocalMP host has no battle server, so the native bridge reports the facts as the HUD event
// "wtoLocalMpExpEvent" and only the client sees when the player spawns and dies.
// Without it: no reward banners in battle and nothing to settle after it.
{
"id": "battle/record-local-battle-awards",
"title": "Record LocalMP combat events and lives, and show their reward banner",
"file": "scripts/hud/hudrewardmessage.nut",
"features": [
"K-击杀、助攻、占点计分"
],
"verified_on": [
"2.61.0.37"
],
"edits": [
{
"find": "find.nut",
"replace": "replace.nut"
}
]
}
@@ -0,0 +1,112 @@
// WTOffline: record the local player's lives and combat events in a LocalMP battle and show the
// reward banner. A LocalMP host has no battle server to price events: the native bridge raises the
// HUD event "wtoLocalMpExpEvent" with the facts, the banner amount comes from the parameters the
// local service sent at launch (nestdb wto.activeBattle.awards, battle-economy.ts BannerParams), and
// the record (nestdb wto.battleLog) is settled by the local service after the battle.
function wtoAppendBattleLog(key, entry) {
let { ndbTryRead, ndbWrite } = require("nestdb")
let list = (ndbTryRead(["wto", "battleLog", key]) ?? []).map(@(v) v)
list.append(entry)
ndbWrite(["wto", "battleLog", key], list)
}
function wtoBannerReward(awards, unit, ev) {
let code = ev?.messageCode ?? -1
let isCapture = code == EXP_EVENT_CAPTURE_ZONE
let expClass = ev?.expClass ?? ""
let group = isCapture ? "own" : (awards?.groups?[expClass] ?? "ground")
let base = awards?.vehicles?[unit]?[$"{code}:{group}"]
if (base == null)
return null
let ai = (isCapture || (ev?.victimIsPlayer ?? 0) != 0) ? 1.0 : awards.aiKillK
let slClass = isCapture ? 1.0 : (awards?.slClass?[expClass] ?? 1.0)
let rpClass = isCapture ? 1.0 : (awards?.rpClass?[expClass] ?? 1.0)
if ((ev?.friendly ?? 0) != 0)
return { wp = -(base[0] * slClass * ai * awards.friendlyKillPenaltyMul + 0.5).tointeger(), exp = 0 }
let count = code == EXP_EVENT_UNIT_DAMAGE ? (ev?.damage ?? 0) : 1
return {
wp = (base[0] * slClass * ai * count + 0.5).tointeger()
exp = (base[1] * rpClass * ai * count + 0.5).tointeger()
}
}
function wtoOnLocalMpExpEvent(ev) {
let { ndbTryRead } = require("nestdb")
let battle = ndbTryRead(["wto", "activeBattle"])
if (battle == null)
return
let wtoMission = require("mission")
let unit = ndbTryRead(["wto", "battleLog", "openLife"])?.unit ?? require("unit").get_player_unit_name()
wtoAppendBattleLog("events", {
time = wtoMission.get_mission_time()
unit
code = ev?.messageCode ?? -1
expClass = ev?.expClass ?? ""
victim = ev?.victim ?? ""
victimIsPlayer = (ev?.victimIsPlayer ?? 0) != 0
friendly = (ev?.friendly ?? 0) != 0
modifier = ev?.messageModifier ?? ""
damage = ev?.damage ?? 0
})
let reward = wtoBannerReward(battle?.awards, unit, ev)
if (reward == null)
return
let { g_hud_event_manager } = require("%scripts/hud/hudEventManager.nut")
g_hud_event_manager.onHudEvent("InBattleReward", {
messageCode = ev?.messageCode ?? -1
warpoints = reward.wp
experience = reward.exp
counter = 1
expClass = ev?.expClass ?? ""
messageModifier = ev?.messageModifier ?? ""
})
}
function wtoCloseBattleLife() {
let { ndbTryRead, ndbDelete } = require("nestdb")
let life = ndbTryRead(["wto", "battleLog", "openLife"])
if (life == null)
return
ndbDelete(["wto", "battleLog", "openLife"])
wtoAppendBattleLog("lives", life.__merge({ end = require("mission").get_mission_time() }))
}
function wtoOnLocalPlayerAlive(_ev) {
let { ndbExists, ndbWrite } = require("nestdb")
if (!ndbExists(["wto", "activeBattle"]))
return
wtoCloseBattleLife()
let unit = require("unit").get_player_unit_name()
if ((unit ?? "") != "")
ndbWrite(["wto", "battleLog", "openLife"], { unit, start = require("mission").get_mission_time() })
}
function wtoOnLocalPlayerDead(_ev) {
if (require("nestdb").ndbExists(["wto", "activeBattle"]))
wtoCloseBattleLife()
}
function wtoSubscribeBattleAwards() {
let { g_hud_event_manager } = require("%scripts/hud/hudEventManager.nut")
g_hud_event_manager.subscribe("wtoLocalMpExpEvent", wtoOnLocalMpExpEvent)
g_hud_event_manager.subscribe("LocalPlayerAlive", wtoOnLocalPlayerAlive)
g_hud_event_manager.subscribe("LocalPlayerDead", wtoOnLocalPlayerDead)
}
// The battle ends for the local player here: close the open life and keep the end time, which the
// settlement report needs after the mission has been left.
function wtoOnQuitToDebriefing(_p) {
let { ndbExists, ndbWrite } = require("nestdb")
if (!ndbExists(["wto", "activeBattle"]))
return
wtoCloseBattleLife()
ndbWrite(["wto", "battleLog", "sessionEnd"], require("mission").get_mission_time())
}
wtoSubscribeBattleAwards()
require("%sqStdLibs/helpers/subscriptions.nut").add_event_listener("HudEventManagerReset", @(_p) wtoSubscribeBattleAwards())
require("eventbus").eventbus_subscribe("onQuitToDebriefing", wtoOnQuitToDebriefing)
return {
g_hud_reward_message
}
@@ -1,11 +1,14 @@
// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes.
// Report a finished LocalMP battle to the local service (cln_wto_finish_battle) and open the
// debriefing with the statistics it settled.
// Why the client: online the battle server reports the battle to the char server by itself; on a
// LocalMP host only the client knows the battle has ended, and there is no stock char action for it.
// Without it: battles pay nothing and the debriefing stays empty.
{
"id": "battle/report-local-battle-settlement",
"title": "Report LocalMP debriefing statistics to local-service before opening DebriefingModal",
"title": "Report LocalMP battle facts to local-service and show the settled debriefing",
"file": "scripts/debriefing/debriefingmodal.nut",
"features": [
"battle-rewards",
"post-battle-settlement"
"L-结算页"
],
"verified_on": [
"2.61.0.37"
@@ -1,195 +1,63 @@
let WTO_ADDITIVE_REWARD_CATS = [
"AirKills", "GroundKills", "HumanKills", "NavalKills",
"Landings", "Takeoffs", "Captures", "Destruction", "Damage",
"Critical", "Hit", "Assist", "BattleTime", "Mission",
"MissionObjective", "Race", "Scout", "ScoutCriticalHit",
"ScoutKill", "ScoutKillUnknown", "Unlocks", "AwardDamage",
"TimedAward", "AirSevereDamage", "ShipSevereDamage",
"MissileEvade", "ShellInterception", "SectorCapture",
"SuppliesDelivery", "SuppliesReturn", "SuppliesDestroy", "SuppliesEscort"
]
let WTO_MAIL_REWARD_CATS = [
"AirKills", "GroundKills", "NavalKills", "HumanKills",
"Assist", "AirSevereDamage", "ShipSevereDamage", "Critical",
"Hit", "Captures", "SectorCapture", "Destruction", "Damage",
"Scout", "ScoutCriticalHit", "ScoutKill", "ScoutKillUnknown",
"Takeoffs", "Landings", "MissileEvade", "ShellInterception",
"TimedAward", "Unlocks", "BattleTime",
"SuppliesDelivery", "SuppliesReturn", "SuppliesDestroy", "SuppliesEscort"
]
let WTO_SCALABLE_EXTRA_EXP_KEYS = [
"expTotal", "expFree", "expScouting", "expSkillBonus", "expSkillBonusTotal",
"expModsTotal", "expUnitTotal", "expInvestModule", "expInvestModuleTotal",
"expInvestUnit", "expInvestUnitTotal"
]
function hydrateWtoContainerTotals(tbl, isUnitTbl) {
if (!u.isTable(tbl))
return
local wpSum = 0
local expSum = 0
foreach (cat in WTO_ADDITIVE_REWARD_CATS) {
if (!isUnitTbl && cat == "Race")
continue
let wpVal = tbl?[$"wp{cat}"]
if (is_numeric(wpVal) && wpVal > 0)
wpSum += wpVal.tointeger()
let expVal = tbl?[$"exp{cat}"]
if (is_numeric(expVal) && expVal > 0)
expSum += expVal.tointeger()
}
let tblTotal = tbl?.tblTotal
if ((tbl?.wpTotal ?? 0) <= 0) {
let fallbackWp = (tblTotal?.noBonusWp ?? 0).tointeger()
tbl.wpTotal <- wpSum > fallbackWp ? wpSum : fallbackWp
}
if ((tbl?.expTotal ?? 0) <= 0) {
let fallbackExp = (tblTotal?.noBonusExp ?? 0).tointeger()
tbl.expTotal <- expSum > fallbackExp ? expSum : fallbackExp
}
}
function ensureWtoDebriefingTotals(cur) {
if (!u.isTable(cur?.exp))
return
hydrateWtoContainerTotals(cur.exp, false)
foreach (_u, airData in (cur.exp?.aircrafts ?? {}))
hydrateWtoContainerTotals(airData, true)
}
function writeWtoRewardCategories(dstBlk, srcTbl) {
if (!u.isTable(srcTbl))
return
local catsBlk = null
foreach (cat in WTO_MAIL_REWARD_CATS) {
let tblRow = srcTbl?[$"tbl{cat}"]
let countVal = (srcTbl?[$"num{cat}"] ?? tblRow?.count ?? 0).tointeger()
let wpVal = (srcTbl?[$"wp{cat}"] ?? tblRow?.noBonusWp ?? 0).tointeger()
let expVal = (srcTbl?[$"exp{cat}"] ?? tblRow?.noBonusExp ?? 0).tointeger()
if (countVal <= 0 && wpVal <= 0 && expVal <= 0)
continue
if (catsBlk == null)
catsBlk = dstBlk.addNewBlock("rewards")
let cBlk = catsBlk.addNewBlock(cat)
cBlk.count = countVal
cBlk.wp = wpVal
cBlk.exp = expVal
}
}
function buildWtoFinishBattleBlk(wtoBattle, res) {
ensureWtoDebriefingTotals(res)
// WTOffline: report a finished LocalMP battle to the local service as facts (lives and combat events
// recorded by record-local-battle-awards, the outcome and the team scores), then build the debriefing
// from the statistics the service settled (see use-settled-debriefing-stats). The client computes
// no rewards itself.
function buildWtoBattleReport(wtoBattle, res) {
let { ndbTryRead } = require("nestdb")
let guiMis = require("guiMission")
let exp = res?.exp ?? {}
let battleLog = ndbTryRead(["wto", "battleLog"]) ?? {}
let mStatus = guiMis.get_mission_status()
let expRes = exp?.result
let outcome = (mStatus == guiMis.MISSION_STATUS_SUCCESS || expRes == STATS_RESULT_SUCCESS || res?.isSucceed == true) ? "win"
: (mStatus == guiMis.MISSION_STATUS_FAIL || expRes == STATS_RESULT_FAIL || res?.state == guiMis.MISSION_STATUS_FAIL) ? "lose"
: "running"
local teamAKills = 0
local teamBKills = 0
foreach (p in (res?.mplayers_list ?? [])) {
let k = (p?.kills ?? 0) + (p?.groundKills ?? 0) + (p?.navalKills ?? 0)
if (p?.team == 2)
teamBKills += k
else if (p?.team == 1)
teamAKills += k
}
let blk = DataBlock()
blk.sessionId = wtoBattle.sessionId
blk.country = (wtoBattle?.country ?? "") != "" ? wtoBattle.country : (res?.country ?? "")
blk.outcome = outcome
blk.outcome = mStatus == guiMis.MISSION_STATUS_SUCCESS ? "win"
: mStatus == guiMis.MISSION_STATUS_FAIL ? "lose"
: "running"
blk.localTeam = (res?.localTeam ?? 1).tointeger()
blk.teamAScore = (res?.mpTblTeams?[0]?.score ?? 0).tointeger()
blk.teamBScore = (res?.mpTblTeams?[1]?.score ?? 0).tointeger()
blk.teamAKills = teamAKills.tointeger()
blk.teamBKills = teamBKills.tointeger()
blk.wpTotal = (exp?.wpTotal ?? 0).tointeger()
blk.expTotal = (exp?.expTotal ?? 0).tointeger()
blk.expFree = (exp?.expFree ?? 0).tointeger()
blk.wpMission = (exp?.wpMission ?? 0).tointeger()
blk.wpTeamKills = (exp?.wpTeamKills ?? exp?.wpFriendlyKills ?? 0).tointeger()
blk.expSkillBonusTotal = (exp?.expSkillBonusTotal ?? 0).tointeger()
blk.expSkillBonusLevel = (exp?.expSkillBonusLevel ?? 0).tointeger()
blk.activity = (exp?.activity ?? 0.0).tofloat()
blk.sessionTime = (exp?.sessionTime ?? 0.0).tofloat()
blk.battleTime = (exp?.battleTime ?? 0.0).tofloat()
writeWtoRewardCategories(blk, exp)
let usedSpares = wtoBattle?.usedSpares
if (u.isTable(usedSpares) && usedSpares.len() > 0) {
let spBlk = blk.addNewBlock("spares")
foreach (spUnit, spCnt in usedSpares)
if (spUnit != "" && is_numeric(spCnt) && spCnt > 0)
spBlk[spUnit] = spCnt.tointeger()
let lives = battleLog?.lives ?? []
let sessionEnd = battleLog?.sessionEnd ?? lives.reduce(@(acc, life) life.end > acc ? life.end : acc, 0.0)
blk.sessionStart = 0.0
blk.sessionEnd = sessionEnd.tofloat()
let livesBlk = blk.addNewBlock("lives")
foreach (life in lives) {
let lifeBlk = livesBlk.addNewBlock("life")
lifeBlk.unit = life.unit
lifeBlk.start = life.start.tofloat()
lifeBlk.end = life.end.tofloat()
}
let vehiclesBlk = blk.addNewBlock("vehicles")
foreach (unitName, airData in (exp?.aircrafts ?? {})) {
let uBlk = vehiclesBlk.addNewBlock(unitName)
uBlk.wpTotal = (airData?.wpTotal ?? 0).tointeger()
uBlk.expTotal = (airData?.expTotal ?? 0).tointeger()
uBlk.expModsTotal = (airData?.expInvestModuleTotal ?? 0).tointeger()
uBlk.expUnitTotal = (airData?.expInvestUnitTotal ?? 0).tointeger()
uBlk.wpMission = (airData?.wpMission ?? 0).tointeger()
uBlk.expSkillBonusTotal = (airData?.expSkillBonusTotal ?? 0).tointeger()
uBlk.expSkillBonusLevel = (airData?.expSkillBonusLevel ?? 0).tointeger()
uBlk.sessionTime = (airData?.sessionTime ?? 0.0).tofloat()
uBlk.battleTime = (airData?.battleTime ?? 0.0).tofloat()
writeWtoRewardCategories(uBlk, airData)
let eventsBlk = blk.addNewBlock("events")
foreach (ev in (battleLog?.events ?? [])) {
let evBlk = eventsBlk.addNewBlock("e")
evBlk.time = ev.time.tofloat()
evBlk.unit = ev.unit
evBlk.code = ev.code.tointeger()
evBlk.expClass = ev.expClass
evBlk.victim = ev.victim
evBlk.victimIsPlayer = ev.victimIsPlayer
evBlk.friendly = ev.friendly
evBlk.modifier = ev.modifier
evBlk.damage = ev.damage.tointeger()
}
let sparesBlk = blk.addNewBlock("spares")
foreach (spUnit, spCnt in (wtoBattle?.usedSpares ?? {}))
if (spUnit != "" && spCnt > 0)
sparesBlk[spUnit] = spCnt.tointeger()
return blk
}
function scaleWtoPositiveField(tbl, key, mul) {
if ((key in tbl) && is_numeric(tbl[key]) && tbl[key] > 0)
tbl[key] = (tbl[key] * mul + 0.5).tointeger()
}
function scaleWtoStatContainer(tbl, slMul, rpMul) {
if (!u.isTable(tbl))
return
if (slMul != 1.0) {
foreach (cat in WTO_ADDITIVE_REWARD_CATS)
scaleWtoPositiveField(tbl, $"wp{cat}", slMul)
scaleWtoPositiveField(tbl, "wpScouting", slMul)
scaleWtoPositiveField(tbl, "wpTotal", slMul)
}
if (rpMul != 1.0) {
foreach (cat in WTO_ADDITIVE_REWARD_CATS)
scaleWtoPositiveField(tbl, $"exp{cat}", rpMul)
foreach (eKey in WTO_SCALABLE_EXTRA_EXP_KEYS)
scaleWtoPositiveField(tbl, eKey, rpMul)
foreach (k, _v in tbl)
if (k.len() > 13 && k.slice(0, 13) == "expInvestUnit" && !k.endswith("Name"))
scaleWtoPositiveField(tbl, k, rpMul)
}
foreach (k, val in tbl) {
if (k.len() >= 4 && k.slice(0, 3) == "tbl" && !k.endswith("F") && u.isTable(val)) {
foreach (subKey, _sv in val) {
if (slMul != 1.0 && subKey.endswith("Wp"))
scaleWtoPositiveField(val, subKey, slMul)
else if (rpMul != 1.0 && subKey.endswith("Exp"))
scaleWtoPositiveField(val, subKey, rpMul)
}
}
}
}
function scaleWtoDebriefingMultipliers(cur, slMul, rpMul) {
if (slMul == 1.0 && rpMul == 1.0)
return
scaleWtoStatContainer(cur.exp, slMul, rpMul)
foreach (_u, airData in (cur.exp?.aircrafts ?? {}))
scaleWtoStatContainer(airData, slMul, rpMul)
}
function applyWtoSettledDebriefing(wtoBattle) {
let debrFull = require("%scripts/debriefing/debriefingFull.nut")
let cur = getDebriefingResult()
if (cur == null)
let { ndbWrite, ndbDelete } = require("nestdb")
let sessionLog = getUserLogsList({ show = [EULT_SESSION_RESULT], disableVisible = true })
.findvalue(@(l) l?.wtoSessionId == wtoBattle.sessionId)
if (sessionLog?.wtoDebriefing == null)
return
ensureWtoDebriefingTotals(cur)
ndbWrite(["wto", "settledExp"], sessionLog.wtoDebriefing)
gatherDebriefingResult()
ndbDelete(["wto", "settledExp"])
let cur = getDebriefingResult()
cur.isSucceed = sessionLog?.win ?? false
cur.roomUserlogs = [sessionLog].extend((cur?.roomUserlogs ?? []).filter(@(l) l?.type != EULT_SESSION_RESULT))
let evObj = events.getEvent(wtoBattle?.modeName ?? "")
if (evObj != null && cur.roomEvent == null)
cur.roomEvent = {
@@ -199,40 +67,21 @@ function applyWtoSettledDebriefing(wtoBattle) {
chapter = evObj?.chapter
gameModeId = evObj?.gameModeId
}
let sessionLogs = getUserLogsList({ show = [EULT_SESSION_RESULT], disableVisible = true })
let matched = sessionLogs.findvalue(@(l) l?.wtoSessionId == wtoBattle.sessionId)
if (matched == null)
return
let others = (cur?.roomUserlogs ?? []).filter(@(l) l?.type != EULT_SESSION_RESULT)
cur.roomUserlogs = [matched].extend(others)
let isWin = matched?.win ?? false
cur.isSucceed = isWin
if ((cur.exp?.result ?? STATS_RESULT_IN_PROGRESS) == STATS_RESULT_IN_PROGRESS)
cur.exp.result <- isWin ? STATS_RESULT_SUCCESS : STATS_RESULT_FAIL
scaleWtoDebriefingMultipliers(cur, (matched?.wtoSlMul ?? 1.0).tofloat(), (matched?.wtoRpMul ?? 1.0).tofloat())
debrFull.recountDebriefingResult()
}
function settleWtoBattleAndOpen(wtoBattle, params) {
let { charSendBlk } = require("chard")
let { addTask } = require("%scripts/tasker.nut")
if (getDebriefingResult() == null)
gatherDebriefingResult()
let blk = buildWtoFinishBattleBlk(wtoBattle, getDebriefingResult())
let openModal = function() {
updateGamercards()
loadHandler(get_gui_handler("DebriefingModal"), params)
}
let onSuccess = function() {
try {
applyWtoSettledDebriefing(wtoBattle)
} catch (e) {
log($"[WTO] applyWtoSettledDebriefing error: {e}")
}
applyWtoSettledDebriefing(wtoBattle)
openModal()
}
let taskId = charSendBlk("cln_wto_finish_battle", blk)
if (taskId < 0 || !addTask(taskId, { showProgressBox = true }, onSuccess, @(_) openModal()))
let taskId = charSendBlk("cln_wto_finish_battle", buildWtoBattleReport(wtoBattle, getDebriefingResult()))
if (taskId < 0 || !addTask(taskId, { showProgressBox = true, showErrorMsgBox = true }, onSuccess, @(_) openModal()))
openModal()
}
@@ -0,0 +1 @@
let exp = stat_get_exp() ?? {}
@@ -0,0 +1,21 @@
// Build the debriefing of a settled LocalMP battle from the statistics the local service computed.
// Why the client: the debriefing reads stat_get_exp() (aces.exe 0x1053b70, the battle's
// SessionStatsNet), which online the battle server fills; a LocalMP host has none, so it is empty.
// Without it: the debriefing shows no rewards, activity or research.
{
"id": "battle/use-settled-debriefing-stats",
"title": "Use the local service's battle statistics in the LocalMP debriefing",
"file": "scripts/debriefing/debriefingfull.nut",
"features": [
"L-结算页"
],
"verified_on": [
"2.61.0.37"
],
"edits": [
{
"find": "find.nut",
"replace": "replace.nut"
}
]
}
@@ -0,0 +1,5 @@
// WTOffline: while a LocalMP battle is being settled, take the debriefing statistics the local
// service computed (nestdb wto.settledExp, written by report-local-battle-settlement) instead of
// the local SessionStatsNet, which no battle server fills on a LocalMP host.
let wtoSettledExp = require("nestdb").ndbTryRead(["wto", "settledExp"])
let exp = wtoSettledExp != null ? u.copy(wtoSettledExp) : (stat_get_exp() ?? {})
+1 -1
View File
@@ -22,7 +22,7 @@ New-Item -ItemType Directory -Force $obj | Out-Null
$sources = @(
"$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c",
"$src\local_mp_core.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_ledger.c", "$src\local_mp_kills.c", "$src\local_mp_events.c",
"$src\local_mp_core.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c",
"$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c"
) | ForEach-Object { '"' + (Resolve-Path $_) + '"' }
+120
View File
@@ -0,0 +1,120 @@
/*
* Reports the local player's combat events to the GUI scripts.
*
* Online, the battle server prices every combat event and sends it to the client
* (packet 0xb03d -> GameSaveData::addScoreMessage), which raises the HUD script event
* "InBattleReward". A LocalMP host has no battle server, so the kill and event hooks call
* local_mp_report_award_event() instead. It raises the HUD script event
* LMP_AWARD_EVENT_NAME carrying facts only (event code, victim class and name); the
* scripts price it with the parameters sent by the local service, show the banner and keep
* the record that the local service settles after the battle. Nothing here computes money.
*
* The event is queued with the same call addScoreMessage uses, but without its
* "hudShowAwardMessages" option gate, so the record does not depend on a HUD setting.
* Every engine helper below is resolved from a call site inside addScoreMessage
* (LMP_SIG_HUD_ADD_SCORE_MSG); see local_mp_offsets.h for the 2.61.0.37 addresses.
*/
#include "hooks.h"
#include "hook_config.h"
#include "local_mp_internal.h"
#include "local_mp_offsets.h"
#include <string.h>
typedef void (__fastcall *BlkCtorFn)(void *blk);
typedef void (__fastcall *BlkDtorFn)(void *blk);
typedef void (__fastcall *BlkToOwnedFn)(void *blk);
typedef void (__fastcall *BlkSetStrFn)(void *blk, const char *name, const char *value);
typedef void (__fastcall *BlkSetIntFn)(void *blk, const char *name, const int32_t *value);
typedef void (__fastcall *HudNotifyScriptFn)(void *queue, const char *event_name, const void *blk);
static uint8_t **g_game_save_data;
static uint32_t g_hud_queue_off;
static BlkCtorFn fn_blk_ctor;
static BlkDtorFn fn_blk_dtor;
static BlkToOwnedFn fn_blk_to_owned;
static BlkSetStrFn fn_blk_set_str;
static BlkSetIntFn fn_blk_set_int;
static HudNotifyScriptFn fn_hud_notify_script;
/* Mirrors addScoreMessage: integer setters expect an owned DataBlock, string setters convert it. */
static void blk_set_int(uint8_t *blk, const char *name, int32_t value)
{
if (*(int32_t *)(blk + LMP_BLK_OFF_OWNED_STATE) != -1)
fn_blk_to_owned(blk);
fn_blk_set_int(blk, name, &value);
}
const char *local_mp_unit_exp_class(const uint8_t *unit)
{
const uint8_t *uinfo;
const char *exp_class;
if (unit == NULL)
return NULL;
uinfo = *(const uint8_t *const *)(unit + LMP_UNIT_OFF_INFO);
if (uinfo == NULL)
return NULL;
exp_class = *(const char *const *)(uinfo + LMP_UNIT_INFO_OFF_EXP_CLASS);
return (exp_class != NULL && exp_class[0] != '\0') ? exp_class : NULL;
}
void local_mp_report_award_event(const LocalMpAwardEvent *ev)
{
__declspec(align(16)) uint8_t blk[LMP_BLK_SIZE];
uint8_t *gsd = g_game_save_data ? *g_game_save_data : NULL;
const char *victim_name = ev ? local_mp_unit_name(ev->victim) : NULL;
const char *victim_class = ev ? local_mp_unit_exp_class(ev->victim) : NULL;
if (ev == NULL || gsd == NULL || fn_hud_notify_script == NULL)
return;
memset(blk, 0, sizeof(blk));
fn_blk_ctor(blk);
fn_blk_set_str(blk, "expClass", victim_class ? victim_class : "");
fn_blk_set_str(blk, "victim", victim_name ? victim_name : "");
fn_blk_set_str(blk, "messageModifier", ev->modifier ? ev->modifier : "");
blk_set_int(blk, "messageCode", (int32_t)ev->exp_event);
blk_set_int(blk, "victimIsPlayer", ev->victim_is_player ? 1 : 0);
blk_set_int(blk, "friendly", ev->friendly ? 1 : 0);
blk_set_int(blk, "damage", ev->damage);
fn_hud_notify_script(gsd + g_hud_queue_off, LMP_AWARD_EVENT_NAME, blk);
fn_blk_dtor(blk);
}
static void *call_target(uint8_t *score_msg, size_t call_off)
{
return local_mp_resolve_rip(score_msg + call_off, 1, 5);
}
int install_local_mp_award_hooks(const uint8_t *text, size_t text_size, uint8_t *p_ground_dead)
{
uint8_t *p_score_msg = local_mp_scan_unique(text, text_size, "GameSaveData::addScoreMessage", LMP_SIG_HUD_ADD_SCORE_MSG);
static const size_t call_offs[] = {
LMP_SCORE_MSG_CALL_BLK_CTOR, LMP_SCORE_MSG_CALL_BLK_SET_STR, LMP_SCORE_MSG_CALL_BLK_TO_OWNED,
LMP_SCORE_MSG_CALL_BLK_SET_INT, LMP_SCORE_MSG_CALL_HUD_NOTIFY, LMP_SCORE_MSG_CALL_BLK_DTOR,
};
size_t i;
if (!p_ground_dead || !p_score_msg)
return 0;
if (p_ground_dead[0xa19] != 0x48 || p_ground_dead[0xa1a] != 0x8b || p_ground_dead[0xa1b] != 0x0d)
return 0;
for (i = 0; i < sizeof(call_offs) / sizeof(call_offs[0]); i++) {
if (p_score_msg[call_offs[i]] != 0xe8)
return 0;
}
if (p_score_msg[LMP_SCORE_MSG_ADD_HUD_QUEUE] != 0x48 ||
p_score_msg[LMP_SCORE_MSG_ADD_HUD_QUEUE + 1] != 0x81 ||
p_score_msg[LMP_SCORE_MSG_ADD_HUD_QUEUE + 2] != 0xc1)
return 0;
g_game_save_data = (uint8_t **)local_mp_resolve_rip(p_ground_dead + 0xa19, 3, 7);
memcpy(&g_hud_queue_off, p_score_msg + LMP_SCORE_MSG_ADD_HUD_QUEUE + 3, sizeof(g_hud_queue_off));
fn_blk_ctor = (BlkCtorFn)call_target(p_score_msg, LMP_SCORE_MSG_CALL_BLK_CTOR);
fn_blk_set_str = (BlkSetStrFn)call_target(p_score_msg, LMP_SCORE_MSG_CALL_BLK_SET_STR);
fn_blk_to_owned = (BlkToOwnedFn)call_target(p_score_msg, LMP_SCORE_MSG_CALL_BLK_TO_OWNED);
fn_blk_set_int = (BlkSetIntFn)call_target(p_score_msg, LMP_SCORE_MSG_CALL_BLK_SET_INT);
fn_hud_notify_script = (HudNotifyScriptFn)call_target(p_score_msg, LMP_SCORE_MSG_CALL_HUD_NOTIFY);
fn_blk_dtor = (BlkDtorFn)call_target(p_score_msg, LMP_SCORE_MSG_CALL_BLK_DTOR);
return 1;
}
+1 -1
View File
@@ -280,7 +280,7 @@ void install_local_mp_hooks(void)
if (!install_local_mp_player_hooks(text, text_size, p_do_respawn) ||
!install_local_mp_loadout_hooks(text, text_size) ||
!install_local_mp_action_hooks(text, text_size) ||
!install_local_mp_ledger_hooks(text, text_size, p_ground_dead) ||
!install_local_mp_award_hooks(text, text_size, p_ground_dead) ||
!install_local_mp_kill_hooks(text, text_size, p_ground_dead) ||
!install_local_mp_event_hooks(text, text_size)) {
log_line("local_mp: one or more LocalMP subsystem hooks failed to initialize");
+15 -33
View File
@@ -25,8 +25,6 @@
#define MAX_OFFENDER_SNAP 64u
#define MAX_ASSIST_DEDUP 64u
#define HUD_MSG_HIT_FEED 3u
#define HUD_MSG_CENTER_BANNER 4u
typedef struct AssistDedupRecord {
const uint8_t *victim;
@@ -94,13 +92,8 @@ static void credit_assist_to_mplayer(uint8_t *mp, uint8_t *victim)
local_mp_add_mplayer_score(mp, pts, LMP_EXP_EVENT_ASSIST);
local_mp_mark_mplayer_dirty(mp);
if (local_mp_is_local_mplayer(mp)) {
const char *uname = local_mp_active_player_unit_name();
const LocalMpUnitRates *rates = local_mp_ledger_rates_for_unit(uname);
float mul = victim_mp ? 0.45f : (0.45f * rates->ai_kill_k);
int32_t wp = (int32_t)(rates->wp_per_kill * mul + 0.5f);
int32_t rp = (int32_t)(180.0f * rates->exp_mul * mul + 0.5f);
local_mp_ledger_record_event(uname, LMP_STAT_BKT_ASSIST, 1, wp, rp, pts);
local_mp_ledger_banner(LMP_EXP_EVENT_ASSIST, HUD_MSG_CENTER_BANNER, rp, wp, victim);
LocalMpAwardEvent award = { LMP_EXP_EVENT_ASSIST, victim, victim_mp != NULL, 0, NULL, 0 };
local_mp_report_award_event(&award);
}
}
@@ -155,12 +148,8 @@ static void __fastcall hook_dispatch_capture_zone(int64_t uid, uint8_t *capturer
local_mp_add_mplayer_score(mp, SCORE_CAPTURE_ZONE, LMP_EXP_EVENT_CAPTURE_ZONE);
local_mp_mark_mplayer_dirty(mp);
if (local_mp_is_local_mplayer(mp)) {
const char *uname = capturer_unit ? local_mp_unit_name(capturer_unit) : NULL;
const LocalMpUnitRates *rates = local_mp_ledger_rates_for_unit(uname);
int32_t wp = (int32_t)(rates->wp_per_kill + 0.5f);
int32_t rp = (int32_t)(200.0f * rates->exp_mul + 0.5f);
local_mp_ledger_record_event(uname, LMP_STAT_BKT_CAPTURES, 1, wp, rp, SCORE_CAPTURE_ZONE);
local_mp_ledger_banner(LMP_EXP_EVENT_CAPTURE_ZONE, HUD_MSG_CENTER_BANNER, rp, wp, capturer_unit);
LocalMpAwardEvent award = { LMP_EXP_EVENT_CAPTURE_ZONE, NULL, 0, 0, NULL, 0 };
local_mp_report_award_event(&award);
}
}
}
@@ -179,13 +168,10 @@ static void __fastcall hook_dispatch_hit_crit(
local_mp_add_mplayer_score(mp, pts, ev);
local_mp_mark_mplayer_dirty(mp);
if (local_mp_is_local_mplayer(mp)) {
const char *uname = local_mp_active_player_unit_name();
const LocalMpUnitRates *rates = local_mp_ledger_rates_for_unit(uname);
float mul = is_crit ? 0.20f : 0.06f;
int32_t wp = (int32_t)(rates->wp_per_kill * mul + 0.5f);
int32_t rp = (int32_t)(180.0f * rates->exp_mul * mul + 0.5f);
local_mp_ledger_record_event(uname, is_crit ? LMP_STAT_BKT_CRITICAL : LMP_STAT_BKT_HIT, 1, wp, rp, pts);
local_mp_ledger_banner(ev, HUD_MSG_HIT_FEED, rp, wp, victim);
LocalMpAwardEvent award = {
ev, victim, *(uint8_t **)(victim + LMP_UNIT_OFF_MPLAYER) != NULL, 0, NULL, 0
};
local_mp_report_award_event(&award);
}
}
}
@@ -207,12 +193,8 @@ static void __fastcall hook_dispatch_severe_damage(int64_t uid, uint8_t *victim,
local_mp_add_mplayer_score(mp, SCORE_SEVERE_DAMAGE, LMP_EXP_EVENT_SEVERE_DAMAGE);
local_mp_mark_mplayer_dirty(mp);
if (local_mp_is_local_mplayer(mp)) {
const char *uname = local_mp_active_player_unit_name();
const LocalMpUnitRates *rates = local_mp_ledger_rates_for_unit(uname);
int32_t wp = (int32_t)(rates->wp_per_kill * 0.8f + 0.5f);
int32_t rp = (int32_t)(144.0f * rates->exp_mul + 0.5f);
local_mp_ledger_record_event(uname, is_air ? LMP_STAT_BKT_AIR_SEVERE : LMP_STAT_BKT_SHIP_SEVERE, 1, wp, rp, SCORE_SEVERE_DAMAGE);
local_mp_ledger_banner(LMP_EXP_EVENT_SEVERE_DAMAGE, HUD_MSG_CENTER_BANNER, rp, wp, victim);
LocalMpAwardEvent award = { LMP_EXP_EVENT_SEVERE_DAMAGE, victim, 1, 0, NULL, 0 };
local_mp_report_award_event(&award);
}
}
}
@@ -233,11 +215,11 @@ static void __fastcall hook_dispatch_naval_damage(int64_t uid, uint8_t *victim,
if (pts >= 1.0f) local_mp_add_mplayer_score(mp, pts, LMP_EXP_EVENT_UNIT_DAMAGE);
local_mp_mark_mplayer_dirty(mp);
if (local_mp_is_local_mplayer(mp) && add_dmg > 0) {
const char *uname = local_mp_active_player_unit_name();
const LocalMpUnitRates *rates = local_mp_ledger_rates_for_unit(uname);
int32_t wp = (int32_t)(rates->wp_per_kill * (award_dmg / 1500.0f) + 0.5f);
int32_t rp = (int32_t)(rates->exp_mul * (award_dmg * 0.10f) + 0.5f);
local_mp_ledger_record_event(uname, LMP_STAT_BKT_AWARD_DAMAGE, add_dmg, wp, rp, pts >= 1.0f ? pts : 0.0f);
LocalMpAwardEvent award = {
LMP_EXP_EVENT_UNIT_DAMAGE, victim, *(uint8_t **)(victim + LMP_UNIT_OFF_MPLAYER) != NULL,
0, NULL, add_dmg
};
local_mp_report_award_event(&award);
}
}
}
+15 -36
View File
@@ -10,7 +10,8 @@
#include <stddef.h>
#include <stdint.h>
#define LMP_MAX_UNIT_RATES 32u
/* HUD script event raised for each combat event of the local player (local_mp_awards.c). */
#define LMP_AWARD_EVENT_NAME "wtoLocalMpExpEvent"
typedef char *(__fastcall *LmpGetPlayerCountryFn)(uint8_t *mis, int32_t pid, char *buf, int32_t buf_size);
typedef void (__fastcall *LmpSetPlayerGuiStateFn)(int32_t player_id, int32_t state);
@@ -19,19 +20,15 @@ typedef void *(__fastcall *LmpGetUnitByEidFn)(uint32_t eid);
typedef void (__fastcall *LmpSetOwningMPlayerFn)(void *unit, void *mplayer, uint8_t f1, uint8_t set_pid);
typedef const char *(__fastcall *LmpDataBlockGetStrFn)(const void *blk, const char *name, const char *def);
typedef struct LocalMpUnitRates {
char unit_name[64];
float wp_per_kill;
float exp_mul;
float battle_time_award;
float ai_kill_k;
float win_k;
} LocalMpUnitRates;
typedef struct LocalMpUnitRateEntry {
LocalMpUnitRates rates;
uint8_t spawned;
} LocalMpUnitRateEntry;
/* One combat event of the local player, as facts only (see local_mp_awards.c). */
typedef struct LocalMpAwardEvent {
uint32_t exp_event; /* EXP_EVENT_* code (globalScripts/expEventConsts.nut) */
const uint8_t *victim; /* destroyed or damaged unit; NULL for a zone capture */
int victim_is_player; /* victim belongs to an MPlayer (player or bound bot) */
int friendly; /* victim was on the local player's team */
const char *modifier; /* stock messageModifier, e.g. "from_severe_damage", or NULL */
int32_t damage; /* naval award damage for EXP_EVENT_UNIT_DAMAGE, else 0 */
} LocalMpAwardEvent;
extern uint8_t **g_local_mp_multiplayer;
extern uint8_t **g_local_mp_app;
@@ -59,31 +56,13 @@ void *local_mp_mem_alloc(size_t size);
void local_mp_mem_free(void *ptr);
char *local_mp_strdup(const char *s);
const char *local_mp_unit_name(const uint8_t *unit);
const char *local_mp_active_player_unit_name(void);
/* Player state & slot tracking notifications shared with loadout module. */
void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int is_silent);
/* SessionStatsNet ledger & HUD center-screen reward banner API. */
void local_mp_ledger_reset(void);
void local_mp_ledger_store_rates(const LocalMpUnitRates *rates);
void local_mp_ledger_activate_unit(const char *unit_name);
const LocalMpUnitRates *local_mp_ledger_rates_for_unit(const char *unit_name);
void local_mp_ledger_record_event(
const char *unit_name,
size_t bucket_off,
int32_t count_inc,
int32_t wp,
int32_t exp,
float score_delta
);
void local_mp_ledger_banner(
uint32_t event_id,
uint32_t msg_type,
int32_t xp,
int32_t wp,
void *target_unit
);
/* Combat event reporting to the GUI scripts (local_mp_awards.c). */
void local_mp_report_award_event(const LocalMpAwardEvent *ev);
const char *local_mp_unit_exp_class(const uint8_t *unit);
/* Assist deduplication lifecycle shared between kill and event hooks. */
void local_mp_events_reset(void);
@@ -98,6 +77,6 @@ void local_mp_inc_mplayer_stat(uint8_t *mp, size_t off);
int install_local_mp_player_hooks(const uint8_t *text, size_t text_size, uint8_t *p_do_respawn);
int install_local_mp_loadout_hooks(const uint8_t *text, size_t text_size);
int install_local_mp_action_hooks(const uint8_t *text, size_t text_size);
int install_local_mp_ledger_hooks(const uint8_t *text, size_t text_size, uint8_t *p_ground_dead);
int install_local_mp_award_hooks(const uint8_t *text, size_t text_size, uint8_t *p_ground_dead);
int install_local_mp_kill_hooks(const uint8_t *text, size_t text_size, uint8_t *p_ground_dead);
int install_local_mp_event_hooks(const uint8_t *text, size_t text_size);
+21 -13
View File
@@ -3,7 +3,8 @@
*
* Hooks BOTH `IGroundModel::onBecameDead` (tanks, IFVs, SPAA, boats, ships, infantry)
* and `onUnitDeadOnce` (aircraft & helicopters). All 31 bound MPlayer bots receive 1:1
* PvP kill/death counters and battle score alongside the local player.
* PvP kill/death counters and battle score alongside the local player. Kills made by the
* local player are also reported as facts through local_mp_report_award_event().
*/
#include "hooks.h"
#include "hook_config.h"
@@ -18,7 +19,6 @@
#define SCORE_SEVERE_FINISH 40.0f
#define SCORE_AI_UNIT_KILL 60.0f
#define SCORE_DEATH 30.0f
#define HUD_MSG_CENTER_BANNER 4u
typedef void (__fastcall *MPlayerAddScoreFn)(uint8_t *mp, float delta, uint32_t event_id, uint8_t add_team);
typedef void (__fastcall *NetMarkDirtyFn)(void *dirty_field, void *owner_obj, void *payload_ptr);
@@ -80,8 +80,6 @@ static void record_enemy_kill(uint8_t *killer_mp, uint8_t *victim, int is_pvp)
int is_human = (utype == 0xeu);
int own_sev = is_pvp && (is_air || is_ship) && is_same_severe_offender(victim, killer_mp);
uint32_t ev = is_air ? LMP_EXP_EVENT_KILL : (is_human ? LMP_EXP_EVENT_KILL_HUMAN : LMP_EXP_EVENT_KILL_GROUND);
size_t bkt = is_air ? LMP_STAT_BKT_AIR_KILLS : (is_ship ? LMP_STAT_BKT_NAVAL_KILLS :
(is_human ? LMP_STAT_BKT_HUMAN_KILLS : LMP_STAT_BKT_GROUND_KILLS));
float pts = is_pvp ? (own_sev ? SCORE_SEVERE_FINISH : SCORE_PVP_KILL) : SCORE_AI_UNIT_KILL;
if (is_pvp) {
@@ -97,13 +95,24 @@ static void record_enemy_kill(uint8_t *killer_mp, uint8_t *victim, int is_pvp)
local_mp_mark_mplayer_dirty(killer_mp);
if (local_mp_is_local_mplayer(killer_mp)) {
const char *uname = local_mp_active_player_unit_name();
const LocalMpUnitRates *rates = local_mp_ledger_rates_for_unit(uname);
float mul = is_pvp ? (own_sev ? 0.2f : 1.0f) : rates->ai_kill_k;
int32_t wp = (int32_t)(rates->wp_per_kill * mul + 0.5f);
int32_t rp = (int32_t)(180.0f * rates->exp_mul * mul + 0.5f);
local_mp_ledger_record_event(uname, bkt, 1, wp, rp, pts);
local_mp_ledger_banner(ev, HUD_MSG_CENTER_BANNER, rp, wp, victim);
LocalMpAwardEvent award = { ev, victim, is_pvp, 0, own_sev ? "from_severe_damage" : NULL, 0 };
local_mp_report_award_event(&award);
}
}
static void record_team_kill(uint8_t *killer_mp, uint8_t *victim, int is_pvp)
{
uint16_t utype = *(uint16_t *)(victim + LMP_UNIT_OFF_TYPE);
int is_air = (utype == 0u || utype == 0xdu);
local_mp_inc_mplayer_stat(killer_mp, LMP_MP_OFF_TEAM_KILLS);
local_mp_mark_mplayer_dirty(killer_mp);
if (local_mp_is_local_mplayer(killer_mp)) {
LocalMpAwardEvent award = {
is_air ? LMP_EXP_EVENT_KILL : (utype == 0xeu ? LMP_EXP_EVENT_KILL_HUMAN : LMP_EXP_EVENT_KILL_GROUND),
victim, is_pvp, 1, NULL, 0
};
local_mp_report_award_event(&award);
}
}
@@ -122,8 +131,7 @@ static void process_unit_death(uint8_t *victim, uint8_t *killer_mp, int32_t kill
if (killer_army <= 0)
killer_army = (int32_t)killer_mp[LMP_MP_OFF_TEAM];
if (victim_army != 0 && killer_army == (int32_t)victim_army) {
local_mp_inc_mplayer_stat(killer_mp, LMP_MP_OFF_TEAM_KILLS);
local_mp_mark_mplayer_dirty(killer_mp);
record_team_kill(killer_mp, victim, victim_mp != NULL);
} else {
record_enemy_kill(killer_mp, victim, victim_mp != NULL);
}
-295
View File
@@ -1,295 +0,0 @@
/*
* LocalMP SessionStatsNet & UnitSessionStat ledger, per-unit rate table,
* and center-screen HUD reward banner.
*/
#include "hooks.h"
#include "hook_config.h"
#include "local_mp_internal.h"
#include "local_mp_offsets.h"
#include "MinHook.h"
#include <string.h>
typedef struct DagorSimpleStr {
const char *ptr;
void *alloc;
uint64_t len_cap;
} DagorSimpleStr;
typedef void (__fastcall *SessionStatsResetFn)(void *stats_net);
typedef uint8_t *(__fastcall *SessionStatsGetUnitFn)(void *stats_net, const char *unit_name);
typedef void (__fastcall *StartActualizeClientFn)(void *econ_state, int32_t p2, uint8_t p3);
typedef void (__fastcall *HudAddScoreMessageFn)(
void *hud, uint32_t event_id, uint32_t msg_type, int32_t xp, int32_t wp,
uint32_t delay, void *target_unit, const DagorSimpleStr *str, int64_t a9, int64_t a10
);
static void **g_hud_ptr;
static SessionStatsResetFn fn_stats_reset;
static SessionStatsGetUnitFn fn_stats_get_unit;
static HudAddScoreMessageFn fn_hud_add_score_msg;
static StartActualizeClientFn orig_start_actualize;
static LocalMpUnitRateEntry g_unit_rates[LMP_MAX_UNIT_RATES];
static size_t g_unit_rate_count = 0;
static char g_last_spawned_unit[64];
static int g_finalized_this_match = 0;
static const LocalMpUnitRates k_empty_rates = { "", 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
static void sat_add_i32(int32_t *dst, int32_t delta)
{
int64_t sum = (int64_t)(*dst) + (int64_t)delta;
if (sum > 0x7fffffffLL) sum = 0x7fffffffLL;
if (sum < 0) sum = 0;
*dst = (int32_t)sum;
}
static void add_bucket_values(uint8_t *base, size_t bkt_off, int32_t count_inc, int32_t wp, int32_t exp)
{
uint8_t *b = base + bkt_off;
sat_add_i32((int32_t *)(b + LMP_BKT_OFF_COUNT), count_inc);
sat_add_i32((int32_t *)(b + LMP_BKT_OFF_EXP), exp);
sat_add_i32((int32_t *)(b + LMP_BKT_OFF_WP), wp);
sat_add_i32((int32_t *)(b + LMP_BKT_OFF_RAW_EXP), exp);
sat_add_i32((int32_t *)(b + LMP_BKT_OFF_RAW_WP), wp);
sat_add_i32((int32_t *)(b + LMP_BKT_OFF_NO_BONUS_EXP), exp);
sat_add_i32((int32_t *)(b + LMP_BKT_OFF_NO_BONUS_WP), wp);
}
static void record_on_unit(
uint8_t *sstat, const char *unit_name, size_t bkt_off,
int32_t count_inc, int32_t wp, int32_t exp, float score_delta
)
{
int32_t total_inc = count_inc > 0 ? 1 : 0;
uint8_t *ustat;
add_bucket_values(sstat, bkt_off, count_inc, wp, exp);
if (bkt_off != LMP_STAT_BKT_TOTAL)
add_bucket_values(sstat, LMP_STAT_BKT_TOTAL, total_inc, wp, exp);
sat_add_i32((int32_t *)(sstat + LMP_SSTAT_OFF_EXP_FREE), exp);
if (unit_name == NULL || unit_name[0] == '\0' || fn_stats_get_unit == NULL)
return;
ustat = fn_stats_get_unit(sstat, unit_name);
if (ustat == NULL)
return;
add_bucket_values(ustat, bkt_off, count_inc, wp, exp);
if (bkt_off != LMP_STAT_BKT_TOTAL)
add_bucket_values(ustat, LMP_STAT_BKT_TOTAL, total_inc, wp, exp);
*(float *)(ustat + LMP_USTAT_OFF_SCORE) += score_delta;
sat_add_i32((int32_t *)(ustat + LMP_USTAT_OFF_EXP_MOD), exp);
sat_add_i32((int32_t *)(ustat + LMP_USTAT_OFF_EXP_MOD_TOTAL), exp);
sat_add_i32((int32_t *)(ustat + LMP_USTAT_OFF_EXP_UNIT), exp);
sat_add_i32((int32_t *)(ustat + LMP_USTAT_OFF_EXP_UNIT_TOTAL), exp);
}
void local_mp_ledger_reset(void)
{
uint8_t *econ = local_mp_econ_state();
g_unit_rate_count = 0;
g_finalized_this_match = 0;
memset(g_unit_rates, 0, sizeof(g_unit_rates));
memset(g_last_spawned_unit, 0, sizeof(g_last_spawned_unit));
local_mp_events_reset();
if (econ != NULL && fn_stats_reset != NULL)
fn_stats_reset(econ + LMP_ECON_OFF_SESSION_STATS);
}
void local_mp_ledger_store_rates(const LocalMpUnitRates *rates)
{
size_t i;
if (rates == NULL || rates->unit_name[0] == '\0')
return;
for (i = 0; i < g_unit_rate_count; i++) {
if (strcmp(g_unit_rates[i].rates.unit_name, rates->unit_name) == 0) {
g_unit_rates[i].rates = *rates;
return;
}
}
if (g_unit_rate_count < LMP_MAX_UNIT_RATES) {
g_unit_rates[g_unit_rate_count].rates = *rates;
g_unit_rates[g_unit_rate_count].spawned = 0;
g_unit_rate_count++;
}
}
void local_mp_ledger_activate_unit(const char *unit_name)
{
uint8_t *econ = local_mp_econ_state();
size_t i;
if (unit_name == NULL || unit_name[0] == '\0')
return;
g_finalized_this_match = 0;
memset(g_last_spawned_unit, 0, sizeof(g_last_spawned_unit));
strncpy(g_last_spawned_unit, unit_name, sizeof(g_last_spawned_unit) - 1);
if (econ != NULL && fn_stats_get_unit != NULL)
fn_stats_get_unit(econ + LMP_ECON_OFF_SESSION_STATS, unit_name);
for (i = 0; i < g_unit_rate_count; i++) {
if (strcmp(g_unit_rates[i].rates.unit_name, unit_name) == 0) {
g_unit_rates[i].spawned = 1;
return;
}
}
if (g_unit_rate_count < LMP_MAX_UNIT_RATES) {
memset(&g_unit_rates[g_unit_rate_count], 0, sizeof(g_unit_rates[0]));
strncpy(g_unit_rates[g_unit_rate_count].rates.unit_name, unit_name,
sizeof(g_unit_rates[0].rates.unit_name) - 1);
g_unit_rates[g_unit_rate_count].spawned = 1;
g_unit_rate_count++;
}
}
const char *local_mp_active_player_unit_name(void)
{
uint8_t *mplayer = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL;
const char *hero_name = (g_local_mp_hero && *g_local_mp_hero) ? local_mp_unit_name(*g_local_mp_hero) : NULL;
if (hero_name != NULL && mplayer != NULL && mplayer[LMP_MP_OFF_GUI_STATE] == LMP_GUI_STATE_PILOT_CONTROL) {
local_mp_ledger_activate_unit(hero_name);
return hero_name;
}
return g_last_spawned_unit[0] != '\0' ? g_last_spawned_unit : hero_name;
}
const LocalMpUnitRates *local_mp_ledger_rates_for_unit(const char *unit_name)
{
const char *target = (unit_name && unit_name[0] != '\0') ? unit_name : local_mp_active_player_unit_name();
size_t i;
if (target != NULL && target[0] != '\0') {
for (i = 0; i < g_unit_rate_count; i++) {
if (strcmp(g_unit_rates[i].rates.unit_name, target) == 0)
return &g_unit_rates[i].rates;
}
}
return &k_empty_rates;
}
void local_mp_ledger_record_event(
const char *unit_name, size_t bucket_off, int32_t count_inc, int32_t wp, int32_t exp, float score_delta
)
{
uint8_t *econ = local_mp_econ_state();
const char *active_name = (unit_name && unit_name[0] != '\0') ? unit_name : local_mp_active_player_unit_name();
if (econ == NULL)
return;
if (active_name != NULL && active_name[0] != '\0')
local_mp_ledger_activate_unit(active_name);
record_on_unit(econ + LMP_ECON_OFF_SESSION_STATS, active_name,
bucket_off, count_inc, wp > 0 ? wp : 0, exp > 0 ? exp : 0, score_delta);
}
void local_mp_ledger_banner(uint32_t event_id, uint32_t msg_type, int32_t xp, int32_t wp, void *target_unit)
{
void *hud = g_hud_ptr ? *g_hud_ptr : NULL;
DagorSimpleStr empty_str = { NULL, g_local_mp_stdmem ? *g_local_mp_stdmem : NULL, 0 };
if (hud != NULL && fn_hud_add_score_msg != NULL)
fn_hud_add_score_msg(hud, event_id, msg_type, xp, wp, 0, target_unit, &empty_str, 0, 0);
}
static size_t count_spawned_units(void)
{
size_t i, spawned = 0;
for (i = 0; i < g_unit_rate_count; i++) {
if (g_unit_rates[i].spawned && g_unit_rates[i].rates.wp_per_kill > 0.0f)
spawned++;
}
return spawned;
}
static void finalize_session_stats_before_exit(uint8_t *econ)
{
uint8_t *sstat = econ + LMP_ECON_OFF_SESSION_STATS;
uint8_t *app = g_local_mp_app ? *g_local_mp_app : NULL;
uint8_t *rules = app ? *(uint8_t **)(app + LMP_APP_OFF_SCORE_RULES) : NULL;
int32_t mstat = rules ? *(int32_t *)(rules + LMP_SCORE_RULES_OFF_MSTATUS) : 0;
uint8_t *local_mp = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL;
float score = local_mp ? (float)(*(int32_t *)(local_mp + LMP_MP_OFF_SCORE)) : 0.0f;
float total_bt = *(float *)(sstat + LMP_STAT_OFF_BATTLE_TIME);
float total_st = *(float *)(sstat + LMP_STAT_OFF_SESSION_TIME);
float active_sec = total_bt > 1.0f ? total_bt : (total_st * 0.65f);
float activity = 0.0f;
size_t spawned_count, i;
if (g_finalized_this_match)
return;
g_finalized_this_match = 1;
*(int32_t *)(sstat + LMP_SSTAT_OFF_RESULT) = (mstat == LMP_MISSION_STATUS_SUCCESS) ? LMP_STATS_RESULT_SUCCESS :
((mstat == LMP_MISSION_STATUS_FAIL) ? LMP_STATS_RESULT_FAIL : LMP_STATS_RESULT_IN_PROGRESS);
if (score > 0.0f || active_sec > 3.0f) {
activity = (score / 1200.0f) * 0.65f + (active_sec / 480.0f) * 0.35f;
if (activity < 0.15f) activity = 0.15f;
if (activity > 1.0f) activity = 1.0f;
}
*(float *)(sstat + LMP_SSTAT_OFF_ACTIVITY) = activity;
if (total_bt < 1.0f && active_sec > 0.0f)
*(float *)(sstat + LMP_STAT_OFF_BATTLE_TIME) = active_sec;
spawned_count = count_spawned_units();
if (spawned_count == 0)
return;
for (i = 0; i < g_unit_rate_count; i++) {
const LocalMpUnitRates *r = &g_unit_rates[i].rates;
uint8_t *ustat;
float u_bt, u_st, share_st, eff_sec;
if (!g_unit_rates[i].spawned || r->wp_per_kill <= 0.0f)
continue;
ustat = fn_stats_get_unit ? fn_stats_get_unit(sstat, r->unit_name) : NULL;
u_bt = ustat ? *(float *)(ustat + LMP_STAT_OFF_BATTLE_TIME) : 0.0f;
u_st = ustat ? *(float *)(ustat + LMP_STAT_OFF_SESSION_TIME) : 0.0f;
share_st = total_st > 1.0f ? (total_st / (float)spawned_count) : active_sec;
eff_sec = u_bt > 1.0f ? u_bt : (u_st > 1.0f ? u_st * 0.65f : (active_sec / (float)spawned_count));
if (ustat != NULL && u_st < 1.0f && share_st > 0.5f)
*(float *)(ustat + LMP_STAT_OFF_SESSION_TIME) = share_st;
if (eff_sec > 2.0f && activity > 0.0f) {
int32_t bt_wp = (int32_t)((eff_sec / 60.0f) * r->battle_time_award * activity + 0.5f);
int32_t bt_rp = (int32_t)((eff_sec * 1.4f) * r->exp_mul * activity + 0.5f);
if (ustat != NULL && u_bt < 1.0f)
*(float *)(ustat + LMP_STAT_OFF_BATTLE_TIME) = eff_sec;
record_on_unit(sstat, r->unit_name, LMP_STAT_BKT_BATTLE_TIME, 1, bt_wp, bt_rp, 0.0f);
if (*(int32_t *)(sstat + LMP_SSTAT_OFF_RESULT) == LMP_STATS_RESULT_SUCCESS) {
record_on_unit(sstat, r->unit_name, LMP_STAT_BKT_MISSION, 1,
(int32_t)((float)bt_wp * r->win_k + 0.5f), (int32_t)((float)bt_rp * r->win_k + 0.5f), 0.0f);
}
}
}
}
static void __fastcall hook_start_actualize_client(void *econ_state, int32_t p2, uint8_t p3)
{
if (local_mp_is_host() && econ_state != NULL)
finalize_session_stats_before_exit((uint8_t *)econ_state);
orig_start_actualize(econ_state, p2, p3);
}
int install_local_mp_ledger_hooks(const uint8_t *text, size_t text_size, uint8_t *p_ground_dead)
{
uint8_t *p_hud_msg = local_mp_scan_unique(text, text_size, "Hud::addScoreMessage", LMP_SIG_HUD_ADD_SCORE_MSG);
uint8_t *p_reset = local_mp_scan_unique(text, text_size, "SessionStatsNet::reset", LMP_SIG_SESSION_STATS_RESET);
uint8_t *p_get_u = local_mp_scan_unique(text, text_size, "SessionStatsNet::getOrCreateUnitStat", LMP_SIG_SESSION_STATS_GET_UNIT);
uint8_t *p_actualize = local_mp_scan_unique(text, text_size, "GameSaveData::startActualizeClient", LMP_SIG_START_ACTUALIZE_CLIENT);
if (!p_ground_dead || !p_hud_msg || !p_reset || !p_get_u || !p_actualize)
return 0;
if (p_ground_dead[0xa19] != 0x48 || p_ground_dead[0xa1a] != 0x8b || p_ground_dead[0xa1b] != 0x0d)
return 0;
g_hud_ptr = (void **)local_mp_resolve_rip(p_ground_dead + 0xa19, 3, 7);
fn_hud_add_score_msg = (HudAddScoreMessageFn)p_hud_msg;
fn_stats_reset = (SessionStatsResetFn)p_reset;
fn_stats_get_unit = (SessionStatsGetUnitFn)p_get_u;
if (MH_CreateHook(p_actualize, (void *)&hook_start_actualize_client, (void **)&orig_start_actualize) != MH_OK ||
MH_EnableHook(p_actualize) != MH_OK) {
log_line("local_mp: failed to install startActualizeClient hook");
return 0;
}
return 1;
}
+4 -20
View File
@@ -26,7 +26,6 @@ typedef void (__fastcall *ReflDtorFn)(void *refl);
typedef uint8_t (__fastcall *UnitChangeAircraftFn)(void *unit, void *refl, uint8_t async);
typedef void *(__fastcall *DataBlockSetFromFn)(void *dst_blk, const void *src_blk, const char *src_fname);
typedef void (__fastcall *DataBlockDtorFn)(void *blk);
typedef float (__fastcall *DataBlockGetRealFn)(const void *blk, const char *name, float def);
typedef void (__fastcall *BulletSetVecAssignFn)(void *dst_vec, const void *first, const void *last);
typedef void *(__fastcall *GetDecalsBlkFn)(
void *econ, void *out_blk, const char *unit, const char *skin, const char *def_key, const char *cskin
@@ -44,7 +43,6 @@ static ReflDtorFn fn_refl_dtor;
static UnitChangeAircraftFn fn_unit_change_aircraft;
static DataBlockSetFromFn fn_datablock_set_from;
static DataBlockDtorFn fn_datablock_dtor;
static DataBlockGetRealFn fn_datablock_get_real;
static BulletSetVecAssignFn fn_bullet_vec_assign;
static GetDecalsBlkFn fn_get_decals_blk;
static GetAttachablesBlkFn fn_get_attachables_blk;
@@ -73,34 +71,22 @@ static void populate_namemap_csv(void *map, const char *csv)
}
}
static int parse_spawn_metadata_blk(const char *unit_name, const void *mods_blk, uint8_t *refl)
static int parse_spawn_metadata_blk(const void *mods_blk, uint8_t *refl)
{
LocalMpUnitRates rates;
const char *enabled_csv = "";
const char *disabled_csv = "";
const char *silent_str = "0";
memset(&rates, 0, sizeof(rates));
if (unit_name != NULL)
strncpy(rates.unit_name, unit_name, sizeof(rates.unit_name) - 1);
if (mods_blk != NULL && g_lmp_datablock_get_str != NULL) {
enabled_csv = g_lmp_datablock_get_str(mods_blk, "enabledMods", "");
disabled_csv = g_lmp_datablock_get_str(mods_blk, "disabledMods", "");
silent_str = g_lmp_datablock_get_str(mods_blk, "isSilentPreview", "0");
rates.wp_per_kill = fn_datablock_get_real(mods_blk, "wpPerKill", 0.0f);
rates.exp_mul = fn_datablock_get_real(mods_blk, "expMul", 0.0f);
rates.battle_time_award = fn_datablock_get_real(mods_blk, "battleTimeAward", 0.0f);
rates.ai_kill_k = fn_datablock_get_real(mods_blk, "aiKillK", 0.0f);
rates.win_k = fn_datablock_get_real(mods_blk, "winK", 0.0f);
}
if (refl != NULL) {
populate_namemap_csv(refl + LMP_REFL_OFF_ENABLED_MODS, enabled_csv);
populate_namemap_csv(refl + LMP_REFL_OFF_DISABLED_MODS, disabled_csv);
}
if (rates.unit_name[0] != '\0' && rates.wp_per_kill > 0.0f)
local_mp_ledger_store_rates(&rates);
return silent_str != NULL && strcmp(silent_str, "1") == 0;
}
@@ -165,7 +151,7 @@ static void __fastcall hook_sem_change_aircraft_send(
return;
if (mplayer[LMP_MP_OFF_GUI_STATE] == LMP_GUI_STATE_PILOT_CONTROL &&
parse_spawn_metadata_blk(unit_name, modifications_blk, NULL)) {
parse_spawn_metadata_blk(modifications_blk, NULL)) {
g_lmp_aircraft_change_result(econ_state, 0);
return;
}
@@ -185,7 +171,7 @@ static void __fastcall hook_sem_change_aircraft_send(
*(char **)(refl + LMP_REFL_OFF_SKIN_NAME) = local_mp_strdup(skin_name);
*(char **)(refl + LMP_REFL_OFF_CUSTOM_SKIN) = local_mp_strdup(custom_skin);
populate_cosmetics(refl, econ_state, unit_name, skin_name, custom_skin);
is_silent = parse_spawn_metadata_blk(unit_name, modifications_blk, refl);
is_silent = parse_spawn_metadata_blk(modifications_blk, refl);
if (custom_preset_blk != NULL)
fn_datablock_set_from(refl + LMP_REFL_OFF_CUSTOM_PRESET_BLK, custom_preset_blk, NULL);
if (bullets_begin != NULL && bullets_end != NULL && bullets_end > bullets_begin)
@@ -220,7 +206,6 @@ int install_local_mp_loadout_hooks(const uint8_t *text, size_t text_size)
uint8_t *p_change_air = local_mp_scan_unique(text, text_size, "Unit::changeAircraft", LMP_SIG_UNIT_CHANGE_AIRCRAFT);
uint8_t *p_blk_set = local_mp_scan_unique(text, text_size, "DataBlock::setFrom", LMP_SIG_DATABLOCK_SET_FROM);
uint8_t *p_blk_dtor = local_mp_scan_unique(text, text_size, "DataBlock::~DataBlock", LMP_SIG_DATABLOCK_DTOR);
uint8_t *p_blk_real = local_mp_scan_unique(text, text_size, "DataBlock::getReal", LMP_SIG_DATABLOCK_GET_REAL);
uint8_t *p_bullets = local_mp_scan_unique(text, text_size, "BulletSetVec::assign", LMP_SIG_BULLET_VEC_ASSIGN);
uint8_t *p_decals = local_mp_scan_unique(text, text_size, "GameSaveData::getDecalsBlk", LMP_SIG_GET_DECALS_BLK);
uint8_t *p_attach = local_mp_scan_unique(text, text_size, "GameSaveData::getAttachablesBlk", LMP_SIG_GET_ATTACHABLES_BLK);
@@ -229,7 +214,7 @@ int install_local_mp_loadout_hooks(const uint8_t *text, size_t text_size)
uint8_t *p_crew = local_mp_scan_unique(text, text_size, "UnitCrewSkills::initFromSave", LMP_SIG_CREW_SKILLS_INIT);
if (!p_sem_send || !p_refl_ctor || !p_refl_dtor || !p_change_air || !p_blk_set || !p_blk_dtor ||
!p_blk_real || !p_bullets || !p_decals || !p_attach || !p_hash || !p_nm_add || !p_crew)
!p_bullets || !p_decals || !p_attach || !p_hash || !p_nm_add || !p_crew)
return 0;
fn_refl_ctor = (ReflCtorFn)p_refl_ctor;
@@ -237,7 +222,6 @@ int install_local_mp_loadout_hooks(const uint8_t *text, size_t text_size)
fn_unit_change_aircraft = (UnitChangeAircraftFn)p_change_air;
fn_datablock_set_from = (DataBlockSetFromFn)p_blk_set;
fn_datablock_dtor = (DataBlockDtorFn)p_blk_dtor;
fn_datablock_get_real = (DataBlockGetRealFn)p_blk_real;
fn_bullet_vec_assign = (BulletSetVecAssignFn)p_bullets;
fn_get_decals_blk = (GetDecalsBlkFn)p_decals;
fn_get_attachables_blk = (GetAttachablesBlkFn)p_attach;
+32 -60
View File
@@ -59,11 +59,8 @@
/*
* @anchor "set_aircraft_accepted_cb"
* @anchor "warpoints::stat_get_exp current exp %d"
* @anchor "GameSaveData::startActualizeClient"
*/
#define LMP_ECON_OFF_CHANGE_REQ 0xf578u
#define LMP_ECON_OFF_SESSION_STATS 0xf678u
#define LMP_REQ_OFF_BULLETS_BEGIN 0x0090u
#define LMP_REQ_OFF_BULLETS_END 0x0098u
#define LMP_REQ_OFF_RESP_BASE_ID 0x00b8u
@@ -141,6 +138,8 @@
#define LMP_UNIT_OFF_PID 0x1018u
#define LMP_UNIT_OFF_INFO 0x1020u
#define LMP_UNIT_INFO_OFF_NAME 0x0010u
/* Unit info expClass string; addScoreMessage reads it for the "expClass" field (2.61.0.37 0x189bb20). */
#define LMP_UNIT_INFO_OFF_EXP_CLASS 0x0038u
#define LMP_UNIT_OFF_CREW_SKILLS 0x10a8u
#define LMP_UNIT_VTF_CHOOSE_OFFENDER 0x0498u
#define LMP_UNIT_OFF_SKIP_KILL 0x3058u
@@ -181,61 +180,31 @@
#define LMP_REFL_OFF_BULLETS_VEC 0x0190u
/*
* GameSaveData::addScoreMessage (2.61.0.37 0x189a8e0, LMP_SIG_HUD_ADD_SCORE_MSG) builds the
* "InBattleReward" HUD script event. local_mp_awards.c resolves the DataBlock helpers and the
* HUD event queue from these call sites in it instead of scanning each helper separately
* (DataBlock::setStr and the queue function have byte-identical twins elsewhere in .text).
* +0x10bc call DataBlock::DataBlock (0x3093000)
* +0x1154 call DataBlock set string (0x3094950, name, const char *)
* +0x116f call DataBlock make-owned (0x30998c0), called while +0x14 != -1
* +0x1188 call DataBlock set int (0x3095130, name, const int *)
* +0x155b add rcx, imm32 (GameSaveData HUD event queue offset, 0xae8)
* +0x1571 call HUD script event queue (0x1804900, queue, event name, const DataBlock *)
* +0x15b0 call DataBlock::~DataBlock (0x3093a60)
* The DataBlock object is 0x20 bytes (constructor 0x3093000 writes +0x00..+0x1f).
*
* @anchor "GameSaveData::addScoreMessage - bad messageType received %d"
* @anchor "numAirKills"
* @anchor "numGroundKills"
* @anchor "numHumanKills"
* @anchor "numNavalKills"
* @anchor "numCaptures"
* @anchor "numDamage"
* @anchor "numCritical"
* @anchor "numHit"
* @anchor "numAssist"
* @anchor "numBattleTime"
* @anchor "numMission"
* @anchor "numTotal"
* @anchor "numAwardDamage"
* @anchor "numAirSevereDamage"
* @anchor "numShipSevereDamage"
* @anchor "noBonusWp"
* @anchor "expInvestModuleTotal"
* @anchor "expInvestUnitTotal"
* @anchor "ucavLaunch"
* @anchor "prepareSupportPlane"
* @anchor "InBattleReward"
*/
#define LMP_STAT_OFF_SESSION_TIME 0x0000u
#define LMP_STAT_OFF_BATTLE_TIME 0x0008u
#define LMP_STAT_BKT_AIR_KILLS 0x0110u
#define LMP_STAT_BKT_GROUND_KILLS 0x0150u
#define LMP_STAT_BKT_HUMAN_KILLS 0x01d0u
#define LMP_STAT_BKT_NAVAL_KILLS 0x0250u
#define LMP_STAT_BKT_CAPTURES 0x0350u
#define LMP_STAT_BKT_DAMAGE 0x03d0u
#define LMP_STAT_BKT_CRITICAL 0x0410u
#define LMP_STAT_BKT_HIT 0x0450u
#define LMP_STAT_BKT_ASSIST 0x0490u
#define LMP_STAT_BKT_BATTLE_TIME 0x04d0u
#define LMP_STAT_BKT_MISSION 0x0550u
#define LMP_STAT_BKT_TOTAL 0x0650u
#define LMP_STAT_BKT_AWARD_DAMAGE 0x0790u
#define LMP_STAT_BKT_AIR_SEVERE 0x0810u
#define LMP_STAT_BKT_SHIP_SEVERE 0x0850u
#define LMP_USTAT_OFF_SCORE 0x0a5cu
#define LMP_USTAT_OFF_EXP_MOD 0x0a78u
#define LMP_USTAT_OFF_EXP_MOD_TOTAL 0x0a7cu
#define LMP_USTAT_OFF_EXP_UNIT 0x0a80u
#define LMP_USTAT_OFF_EXP_UNIT_TOTAL 0x0a84u
#define LMP_SSTAT_OFF_ACTIVITY 0x0aa4u
#define LMP_SSTAT_OFF_EXP_FREE 0x0ae0u
#define LMP_SSTAT_OFF_RESULT 0x0ae4u
#define LMP_BKT_OFF_COUNT 0x00u
#define LMP_BKT_OFF_EXP 0x04u
#define LMP_BKT_OFF_WP 0x08u
#define LMP_BKT_OFF_RAW_EXP 0x0cu
#define LMP_BKT_OFF_RAW_WP 0x10u
#define LMP_BKT_OFF_NO_BONUS_EXP 0x14u
#define LMP_BKT_OFF_NO_BONUS_WP 0x18u
#define LMP_SCORE_MSG_CALL_BLK_CTOR 0x10bcu
#define LMP_SCORE_MSG_CALL_BLK_SET_STR 0x1154u
#define LMP_SCORE_MSG_CALL_BLK_TO_OWNED 0x116fu
#define LMP_SCORE_MSG_CALL_BLK_SET_INT 0x1188u
#define LMP_SCORE_MSG_ADD_HUD_QUEUE 0x155bu
#define LMP_SCORE_MSG_CALL_HUD_NOTIFY 0x1571u
#define LMP_SCORE_MSG_CALL_BLK_DTOR 0x15b0u
#define LMP_BLK_SIZE 0x0020u
#define LMP_BLK_OFF_OWNED_STATE 0x0014u
/* @rip_check LMP_SIG_DISABLED_SLOTS_MASK + 0x02 : 48 83 3d */
/* @rip_check LMP_SIG_DISABLED_SLOTS_MASK + 0x0c : 48 8b 0d */
@@ -251,6 +220,13 @@
/* @rip_check LMP_SIG_CALLER_HIT_CRIT + 0x59 : e8 */
/* @rip_check LMP_SIG_CALLER_SEVERE_DMG + 0x2f : e8 */
/* @rip_check LMP_SIG_CALLER_NAVAL_DMG + 0x67 : e8 */
/* @rip_check LMP_SIG_HUD_ADD_SCORE_MSG + 0x10bc : e8 */
/* @rip_check LMP_SIG_HUD_ADD_SCORE_MSG + 0x1154 : e8 */
/* @rip_check LMP_SIG_HUD_ADD_SCORE_MSG + 0x116f : e8 */
/* @rip_check LMP_SIG_HUD_ADD_SCORE_MSG + 0x1188 : e8 */
/* @rip_check LMP_SIG_HUD_ADD_SCORE_MSG + 0x155b : 48 81 c1 */
/* @rip_check LMP_SIG_HUD_ADD_SCORE_MSG + 0x1571 : e8 */
/* @rip_check LMP_SIG_HUD_ADD_SCORE_MSG + 0x15b0 : e8 */
#define LMP_SIG_DISABLED_SLOTS_MASK "31 c0 48 83 3d ?? ?? ?? ?? 00 74 ?? 48 8b 0d ?? ?? ?? ?? 0f b6 89 f3 00 00 00 f6 c1 01 74 ?? 48 8b 0d ?? ?? ?? ?? 48 85 c9 74 ?? 8b 81 a0 04 00 00 0b 81 d0 04 00 00 c3"
#define LMP_SIG_DO_RESPAWN_PLAYER "56 57 53 48 81 ec 40 01 00 00 44 0f 29 84 24 30 01 00 00 0f 29 bc 24 20 01 00 00 0f 29 b4 24 10 01 00 00 48 8b 91 e0 03 00 00 48 c7 c0 ff ff ff ff 48 85 d2 0f 84 ?? ?? ?? ?? 8b 92 f0 00 00 00 83 fa 01 0f 85 ?? ?? ?? ?? f3 0f 10 81 e4 06 00 00 0f 57 c9 0f 2e c1 0f 83 ?? ?? ?? ?? 4c 8b 05 ?? ?? ?? ?? 40 b6 01 4d 85 c0 0f 84 ?? ?? ?? ?? f6 05 ?? ?? ?? ?? 04 0f 84 ?? ?? ?? ?? 48 8b 15 ?? ?? ?? ?? 48 85 d2 0f 84 ?? ?? ?? ??"
@@ -266,7 +242,6 @@
#define LMP_SIG_DATABLOCK_SET_FROM "41 57 41 56 41 55 41 54 56 57 55 53 48 83 ec 48 48 89 d7 48 89 ce 66 2e 0f 1f 84 00 00 00 00 00 b9 90 00 00 00 e8 ?? ?? ?? ?? 48 85 c0 75 ?? 48 8b 05 ?? ?? ?? ??"
#define LMP_SIG_DATABLOCK_DTOR "41 57 41 56 41 54 56 57 53 48 83 ec 38 0f 29 74 24 20 48 8b 41 18"
#define LMP_SIG_DATABLOCK_GET_STR "48 83 ec 28 4c 89 44 24 20 4c 8d 44 24 20 e8 ?? ?? ?? ?? 90 48 83 c4 28 c3 cc cc cc cc cc cc cc 41 57"
#define LMP_SIG_DATABLOCK_GET_REAL "48 83 ec 28 f3 0f 11 54 24 24 4c 8d 44 24 24 e8 ?? ?? ?? ?? 90 48 83 c4 28 c3 cc cc cc cc cc cc 56 57 53 48 83 ec 30 48 89 d7 48 89 ce 48 8d 15"
#define LMP_SIG_MP_CONSTRUCT_LOCAL "56 57 53 48 83 ec 60 48 89 ce 48 81 c1 f8 00 00 00 e8 ?? ?? ?? ?? 66 c7 46 60 01 01"
#define LMP_SIG_MP_INIT_CHAT "41 57 41 56 41 54 56 57 53 48 83 ec 48 48 89 d7 48 89 ce 48 8b 05 ?? ?? ?? ?? 48 85 c0 74 ?? c6 00 01 48 8b 9e 00 02 00 00"
#define LMP_SIG_IGROUND_AWARD_ASSISTS "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec a8 01 00 00 44 0f 29 94 24 90 01 00 00 44 0f 29 8c 24 80 01 00 00 44 0f 29 84 24 70 01 00 00 0f 29 bc 24 60 01 00 00 0f 29 b4 24 50 01 00 00 48 89 ce 48 8b 01 48 8d 54 24 28 41 b0 01 ff 90 98 04 00 00"
@@ -285,9 +260,6 @@
#define LMP_SIG_MPLAYER_ADD_SCORE "41 57 41 56 56 57 55 53 48 81 ec 88 00 00 00 0f 29 7c 24 70 0f 29 74 24 60 48 89 ce 44 89 c0 f3 0f 2a 84 81 fc 08 00 00 0f 28 f9 f3 0f 58 c1 f3 0f 2c c8 89 8c 86 fc 08 00 00"
#define LMP_SIG_NET_MARK_DIRTY "56 57 53 48 83 ec 40 81 7a 20 44 4e 45 54 0f 85 ?? ?? ?? ?? 48 89 ce 0f b7 41 02 a8 02 75 ?? f6 42 48 02 75 ?? a8 01 75 ?? 4c 89 c7 83 c8 01 66 89 46 02"
#define LMP_SIG_HUD_ADD_SCORE_MSG "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 38 01 00 00 45 89 c5 41 8d 45 fd"
#define LMP_SIG_SESSION_STATS_RESET "41 56 56 57 53 48 83 ec 48 0f 29 74 24 30 48 89 ce 48 8d 05 ?? ?? ?? ?? 48 89 44 24 28"
#define LMP_SIG_SESSION_STATS_GET_UNIT "56 57 53 48 83 ec 40 48 89 d6 48 89 cf 48 89 54 24 30"
#define LMP_SIG_START_ACTUALIZE_CLIENT "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 38 01 00 00 0f 29 b4 24 20 01 00 00 83 b9 80 02 01 00 ff"
#define LMP_SIG_DISPATCH_ASSIST "41 57 41 56 41 55 41 54 56 57 55 53 48 83 ec 78 0f 29 7c 24 60 0f 29 74 24 50 0f 28 f3 4c 89 c6 48 89 d7 48 89 cb 48 8b 05 ?? ?? ?? ?? 48 85 c9 7e ?? 48 85 c0"
#define LMP_SIG_CALLER_CAPTURE_ZONE "41 57 41 56 41 55 41 54 56 57 55 53 48 83 ec 38 44 0f b7 72 02 44 8b 7a 04 4c 8b 62 08 4c 8b 6a 18 49 8d 85 88 06 00 00 48 89 44 24 30 49 8d 85 50 06 00 00 48 89 44 24 28 eb ?? 48 8b 90 08 0e 00 00 89 d1 83 e1 01 0b 0d ?? ?? ?? ?? 3b 88 14 0e 00 00 0f 85 ?? ?? ?? ?? 48 83 e2 fe 48 8b 82 98 0f 00 00 48 8b 88 b8 00 00 00 e8 ?? ?? ?? ??"
#define LMP_SIG_CALLER_HIT_CRIT "8b 0d ?? ?? ?? ?? f7 c1 00 00 08 00 75 ?? f7 c1 00 00 00 01 75 ?? 0f b6 8f 10 10 00 00 39 4e 1c 74 ?? 41 20 c0 0f b6 86 49 01 00 00 0f 57 db f3 0f 5f 9e 30 01 00 00 48 8b 4e 58 85 ed f3 0f 5d 1d ?? ?? ?? ?? 88 44 24 30 0f 9f 44 24 28 44 88 44 24 20 48 89 fa 49 89 f0 e8 ?? ?? ?? ??"
+2 -4
View File
@@ -1,6 +1,6 @@
/*
* LocalMP player team alignment, AI MPlayer <-> Unit ownership binding,
* asynchronous aircraftChangeResultFromHost handshake, and spawn-only ledger activation.
* asynchronous aircraftChangeResultFromHost handshake, and spawn-slot bookkeeping.
*/
#include "hooks.h"
#include "hook_config.h"
@@ -106,7 +106,7 @@ static void __fastcall hook_mplayer_init_from_matching(uint8_t *mplayer, uint8_t
int32_t desired_team = resolve_configured_player_team();
if (desired_team == 1 || desired_team == 2)
*(int32_t *)(info + LMP_MATCH_INFO_OFF_TEAM) = desired_team;
local_mp_ledger_reset();
local_mp_events_reset();
log_line("local_mp: initialized local player team=%d",
(int)(*(int32_t *)(info + LMP_MATCH_INFO_OFF_TEAM)));
}
@@ -128,8 +128,6 @@ static void consume_pending_slot_if_spawned(uint8_t *mplayer)
g_respawn_dispatched = 0;
hero_name = g_local_mp_hero ? local_mp_unit_name(*g_local_mp_hero) : NULL;
if (hero_name != NULL)
local_mp_ledger_activate_unit(hero_name);
if (g_pending_slot_id >= 0 && g_pending_slot_id < 32) {
uint32_t bit = 1u << (uint32_t)g_pending_slot_id;
@@ -0,0 +1,106 @@
/**
* The debriefing table of a settled battle, in the shape of `stat_get_exp()` (aces.exe 0x1053b70,
* which serializes the battle's SessionStatsNet; online the battle server fills it). The client's
* settlement patch puts it in `debriefingResult.exp` in place of the empty local statistics.
*
* Root and every `aircrafts.<vehicle>`:
* num<Row>:i wp<Row>:i exp<Row>:i tbl<Row>{ noBonusWp noBonusExp premAccWp premAccExp premModExp }
* tblTotal{ ... } wpTotal:i expTotal:i sessionTime:r battleTime:r
* Root only: result:i activity:r expFree:i expSkillBonusTotal:i expSkillBonusLevel:i
* investUnitName<Type>:t expInvestUnit<Type>:i expInvestUnitTotal<Type>:i
* Vehicle only: expSkillBonus:i investModuleName:t expInvestModule:i expInvestModuleTotal:i
* expInvestUnit:i expInvestUnitTotal:i
* (key names from the strings of 0x1053b70, 0xf86c10 and 0xf89f90).
*/
import { emptyBlock, setParam, type BlkBlock } from '@wto/blk';
import type { BattleRewards, RewardRow, RowRewards } from './battle-rewards.ts';
/** STATS_RESULT_* script constants, registered by aces.exe 0x17db810 (SUCCESS 1, FAIL 2). */
const STATS_RESULT_SUCCESS = 1;
const STATS_RESULT_FAIL = 2;
export interface ModuleInvestment {
readonly vehicle: string;
readonly module: string;
readonly rp: number;
}
export interface BranchInvestment {
/** Unit type suffix of the research branch: Aircraft, Tank, Ship, Boat or Helicopter. */
readonly type: string;
readonly unit: string;
readonly rp: number;
}
export interface DebriefingInvestments {
readonly modules: readonly ModuleInvestment[];
readonly branches: readonly BranchInvestment[];
}
export function debriefingTable(name: string, rewards: BattleRewards, investments: DebriefingInvestments): BlkBlock {
const root = emptyBlock(name);
const rootRows = new Map<RewardRow, RowRewards>();
for (const vehicle of rewards.vehicles) {
for (const [row, amounts] of vehicle.rows) {
const sum = rootRows.get(row) ?? { count: 0, noBonusWp: 0, noBonusExp: 0, premAccWp: 0, premAccExp: 0, premModExp: 0 };
for (const key of Object.keys(sum) as (keyof RowRewards)[]) sum[key] += amounts[key];
rootRows.set(row, sum);
}
}
setParam(root, 'result', { type: 'int', value: rewards.win ? STATS_RESULT_SUCCESS : STATS_RESULT_FAIL });
setParam(root, 'activity', { type: 'real', value: rewards.activity });
setParam(root, 'sessionTime', { type: 'real', value: rewards.sessionTime });
setParam(root, 'battleTime', { type: 'real', value: rewards.battleTime });
writeRows(root, rootRows, rewards.wpTotal, rewards.expTotal);
setParam(root, 'expFree', { type: 'int', value: rewards.expFree });
setParam(root, 'expSkillBonusTotal', { type: 'int', value: rewards.vehicles.reduce((sum, v) => sum + v.skillBonusExp, 0) });
setParam(root, 'expSkillBonusLevel', { type: 'int', value: rewards.skillBonusLevel });
for (const branch of investments.branches) {
setParam(root, `investUnitName${branch.type}`, { type: 'string', value: branch.unit });
setParam(root, `expInvestUnit${branch.type}`, { type: 'int', value: branch.rp });
setParam(root, `expInvestUnitTotal${branch.type}`, { type: 'int', value: branch.rp });
}
const aircrafts = emptyBlock('aircrafts');
for (const vehicle of rewards.vehicles) {
const block = emptyBlock(vehicle.vehicle);
setParam(block, 'sessionTime', { type: 'real', value: vehicle.sessionTime });
setParam(block, 'battleTime', { type: 'real', value: vehicle.sessionTime });
writeRows(block, vehicle.rows, vehicle.wpTotal, vehicle.expTotal);
setParam(block, 'expSkillBonus', { type: 'int', value: vehicle.skillBonusExp });
setParam(block, 'expSkillBonusTotal', { type: 'int', value: vehicle.skillBonusExp });
const module = investments.modules.find((m) => m.vehicle === vehicle.vehicle);
if (module) setParam(block, 'investModuleName', { type: 'string', value: module.module });
setParam(block, 'expInvestModule', { type: 'int', value: module?.rp ?? 0 });
setParam(block, 'expInvestModuleTotal', { type: 'int', value: module?.rp ?? 0 });
setParam(block, 'expInvestUnit', { type: 'int', value: vehicle.expTotal });
setParam(block, 'expInvestUnitTotal', { type: 'int', value: vehicle.expTotal });
aircrafts.blocks.push(block);
}
root.blocks.push(aircrafts);
return root;
}
function writeRows(block: BlkBlock, rows: ReadonlyMap<RewardRow, RowRewards>, wpTotal: number, expTotal: number): void {
const total: RowRewards = { count: 0, noBonusWp: 0, noBonusExp: 0, premAccWp: 0, premAccExp: 0, premModExp: 0 };
for (const [row, amounts] of rows) {
setParam(block, `num${row}`, { type: 'int', value: amounts.count });
setParam(block, `wp${row}`, { type: 'int', value: amounts.noBonusWp + amounts.premAccWp });
setParam(block, `exp${row}`, { type: 'int', value: amounts.noBonusExp + amounts.premAccExp + amounts.premModExp });
block.blocks.push(rowTable(`tbl${row}`, amounts));
for (const key of Object.keys(total) as (keyof RowRewards)[]) total[key] += amounts[key];
}
setParam(block, 'wpTotal', { type: 'int', value: wpTotal });
setParam(block, 'expTotal', { type: 'int', value: expTotal });
block.blocks.push(rowTable('tblTotal', total));
}
function rowTable(name: string, amounts: RowRewards): BlkBlock {
const table = emptyBlock(name);
setParam(table, 'noBonusWp', { type: 'int', value: amounts.noBonusWp });
setParam(table, 'noBonusExp', { type: 'int', value: amounts.noBonusExp });
setParam(table, 'premAccWp', { type: 'int', value: amounts.premAccWp });
setParam(table, 'premAccExp', { type: 'int', value: amounts.premAccExp });
setParam(table, 'premModExp', { type: 'int', value: amounts.premModExp });
return table;
}
@@ -0,0 +1,52 @@
/**
* Typed reader for `tuning/battle-economy.jsonc`: the mission score of each combat event and the
* offline choices the game files do not carry (see the file for the source of every value).
*/
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
export const VICTIM_GROUPS = ['ground', 'air', 'naval', 'human'] as const;
export type VictimGroup = (typeof VICTIM_GROUPS)[number];
export const SCORED_EVENTS = ['kill', 'assist', 'severeDamage', 'criticalHit', 'hit'] as const;
export type ScoredEvent = (typeof SCORED_EVENTS)[number];
export interface BattleEconomyTuning {
/** Destroyed-unit expClass -> victim group; classes not listed are "ground". */
readonly victimGroups: ReadonlyMap<string, VictimGroup>;
readonly eventScores: Readonly<Record<VictimGroup, Readonly<Record<ScoredEvent, number>>>>;
readonly captureZoneScore: Readonly<Record<VictimGroup, number>>;
readonly navalDamageScorePerPoint: number;
readonly referenceScore: Readonly<Record<VictimGroup, number>>;
readonly friendlyKillPenaltyMul: number;
}
export function readBattleEconomyTuning(reader: TuningReader): BattleEconomyTuning {
const groups = reader.object('victimGroups');
const victimGroups = new Map<string, VictimGroup>();
for (const group of groups.keys()) {
if (!isVictimGroup(group) || group === 'ground') {
throw new TuningError(`tuning file battle-economy.jsonc: victimGroups.${group} is not one of air, naval, human`);
}
for (const expClass of groups.stringList(group)) victimGroups.set(expClass, group);
}
const scores = reader.object('eventScores');
const perGroup = (key: string, min: number): Record<VictimGroup, number> => {
const table = reader.object(key);
return Object.fromEntries(VICTIM_GROUPS.map((group) => [group, table.number(group, { min, max: 100000 })])) as Record<VictimGroup, number>;
};
return {
victimGroups,
eventScores: Object.fromEntries(VICTIM_GROUPS.map((group) => {
const table = scores.object(group);
return [group, Object.fromEntries(SCORED_EVENTS.map((event) => [event, table.number(event, { min: 0, max: 100000 })]))];
})) as Record<VictimGroup, Record<ScoredEvent, number>>,
captureZoneScore: perGroup('captureZoneScore', 0),
navalDamageScorePerPoint: reader.number('navalDamageScorePerPoint', { min: 0, max: 100 }),
referenceScore: perGroup('referenceScore', 1),
friendlyKillPenaltyMul: reader.number('friendlyKillPenaltyMul', { min: 0, max: 100 }),
};
}
function isVictimGroup(value: string): value is VictimGroup {
return (VICTIM_GROUPS as readonly string[]).includes(value);
}
@@ -0,0 +1,212 @@
/**
* Prices the local player's combat events: the one place battle rewards are computed.
*
* The in-battle banner and the settlement use the same two steps, so what the banner shows is
* what the settlement pays:
* 1. baseReward(vehicle, event, victim group): Silver Lions and Research Points of the event
* before the destroyed unit's class factor (sent to the client at launch, `bannerParams`);
* 2. x class factor of the victim's expClass (warpoints.blk / rank.blk units{}), x aiKillK when
* the victim is not a player, x damage points for naval damage.
* The formula and the source of every factor are in tuning/battle-economy.jsonc.
*/
import type { BattleEconomyData, EconomyDifficulty, VehicleEconomy } from '../game-data/datasets/battle-economy.ts';
import type { ModeDifficulty } from '../game-modes/catalogue/game-mode-declaration.ts';
import type { BattleEconomyTuning, ScoredEvent, VictimGroup } from './battle-economy-tuning.ts';
/** EXP_EVENT_* codes the LocalMP host reports (gui.vromfs.bin globalScripts/expEventConsts.nut). */
export const ExpEvent = {
CAPTURE_ZONE: 2,
KILL: 5,
KILL_GROUND: 6,
ASSIST: 9,
CRITICAL_HIT: 10,
HIT: 13,
UNIT_DAMAGE: 24,
SEVERE_DAMAGE: 35,
KILL_HUMAN: 39,
} as const;
/** Debriefing rows (`stat_get_exp()` `num<Row>`/`wp<Row>`/`exp<Row>`, aces.exe 0x1053b70) an event lands in. */
export type DebriefingRow =
| 'AirKills' | 'GroundKills' | 'NavalKills' | 'HumanKills' | 'FriendlyKills'
| 'Assist' | 'AirSevereDamage' | 'ShipSevereDamage' | 'Critical' | 'Hit'
| 'Captures' | 'AwardDamage';
/** What the client reports for one combat event (gui-patches/battle/record-local-battle-awards). */
export interface CombatEventFact {
readonly code: number;
readonly expClass: string;
readonly victimIsPlayer: boolean;
readonly friendly: boolean;
readonly damage: number;
}
export interface PricedEvent {
readonly row: DebriefingRow;
/** How much the row's counter grows: 1, or the damage points for AwardDamage. */
readonly count: number;
readonly wp: number;
readonly exp: number;
}
export interface RewardPair {
readonly wp: number;
readonly exp: number;
}
/**
* Launch-time parameters of the in-battle banner (`battle.awards` of the launch message):
* vehicles.<name>["<code>:<group>"] = [wp, exp] before the class factor; capture uses the group
* "own". The client multiplies by slClass/rpClass of the victim's expClass, by aiKillK for a
* victim that is not a player, by the damage points for naval damage, and shows a friendly kill as
* -wp x friendlyKillPenaltyMul.
*/
export interface BannerParams {
readonly vehicles: Readonly<Record<string, Readonly<Record<string, readonly [number, number]>>>>;
readonly groups: Readonly<Record<string, VictimGroup>>;
readonly slClass: Readonly<Record<string, number>>;
readonly rpClass: Readonly<Record<string, number>>;
readonly aiKillK: number;
readonly friendlyKillPenaltyMul: number;
}
export interface RewardMultipliers {
readonly silverLions: number;
readonly researchPoints: number;
}
export function economyDifficulty(difficulty: ModeDifficulty): EconomyDifficulty {
return difficulty === 'arcade' ? 'arcade' : difficulty === 'realistic' ? 'historical' : 'simulation';
}
export class BattleEconomy {
readonly data: BattleEconomyData;
readonly #tuning: BattleEconomyTuning;
readonly #multipliers: RewardMultipliers;
readonly #premiumVehicles: ReadonlySet<string>;
/** `premiumVehicles`: vehicles the client counts as special (isUnitSpecial: costGold > 0 or premPackAir). */
constructor(
data: BattleEconomyData,
tuning: BattleEconomyTuning,
multipliers: RewardMultipliers,
premiumVehicles: ReadonlySet<string>,
) {
this.data = data;
this.#tuning = tuning;
this.#multipliers = multipliers;
this.#premiumVehicles = premiumVehicles;
}
/** Premium vehicles earn the talisman research bonus without a talisman (scripts/airinfo.nut hasTalisman). */
isPremiumVehicle(name: string): boolean {
return this.#premiumVehicles.has(name);
}
get multipliers(): RewardMultipliers {
return this.#multipliers;
}
vehicle(name: string): VehicleEconomy | undefined {
return this.data.vehicles[name];
}
victimGroup(expClass: string): VictimGroup {
return this.#tuning.victimGroups.get(expClass) ?? 'ground';
}
/** Reward of one event before the victim's class factor; undefined for an event that pays nothing. */
baseReward(vehicle: string, difficulty: EconomyDifficulty, code: number, group: VictimGroup): RewardPair | undefined {
const economy = this.vehicle(vehicle);
if (!economy) return undefined;
const score = this.#score(code, group);
if (score === undefined) return undefined;
const reference = this.#tuning.referenceScore[code === ExpEvent.UNIT_DAMAGE ? 'naval' : group];
return {
wp: this.data.killSilverLions * economy.rewardMul[difficulty] * (score / reference) * this.#multipliers.silverLions,
exp: score * economy.expMul * this.#multipliers.researchPoints,
};
}
price(vehicle: string, difficulty: EconomyDifficulty, fact: CombatEventFact): PricedEvent | undefined {
const economy = this.vehicle(vehicle);
if (!economy) return undefined;
const isCapture = fact.code === ExpEvent.CAPTURE_ZONE;
const group = isCapture ? this.victimGroup(economy.unitClass) : this.victimGroup(fact.expClass);
const row = debriefingRow(fact, group);
const base = this.baseReward(vehicle, difficulty, fact.code, group);
if (!row || !base) return undefined;
const count = fact.code === ExpEvent.UNIT_DAMAGE ? Math.max(0, Math.trunc(fact.damage)) : 1;
const ai = isCapture || fact.victimIsPlayer ? 1 : this.data.aiKillK;
const slClass = isCapture ? 1 : this.data.silverLionsClassFactors[fact.expClass] ?? 1;
const rpClass = isCapture ? 1 : this.data.researchClassFactors[fact.expClass] ?? 1;
if (fact.friendly) {
return { row: 'FriendlyKills', count: 1, wp: -Math.round(base.wp * slClass * ai * this.#tuning.friendlyKillPenaltyMul), exp: 0 };
}
return {
row,
count,
wp: Math.round(base.wp * slClass * ai * count),
exp: Math.round(base.exp * rpClass * ai * count),
};
}
bannerParams(vehicles: Iterable<string>, difficulty: EconomyDifficulty): BannerParams {
const table: Record<string, Record<string, [number, number]>> = {};
for (const name of vehicles) {
const economy = this.vehicle(name);
if (!economy || table[name]) continue;
const entries: Record<string, [number, number]> = {};
for (const code of Object.values(ExpEvent)) {
const groups: readonly (VictimGroup | 'own')[] = code === ExpEvent.CAPTURE_ZONE ? ['own'] : ['ground', 'air', 'naval', 'human'];
for (const group of groups) {
const priceGroup = group === 'own' ? this.victimGroup(economy.unitClass) : group;
const base = this.baseReward(name, difficulty, code, priceGroup);
if (base) entries[`${code}:${group}`] = [base.wp, base.exp];
}
}
table[name] = entries;
}
return {
vehicles: table,
groups: Object.fromEntries(this.#tuning.victimGroups),
slClass: this.data.silverLionsClassFactors,
rpClass: this.data.researchClassFactors,
aiKillK: this.data.aiKillK,
friendlyKillPenaltyMul: this.#tuning.friendlyKillPenaltyMul,
};
}
#score(code: number, group: VictimGroup): number | undefined {
const scored = (event: ScoredEvent): number => this.#tuning.eventScores[group][event];
switch (code) {
case ExpEvent.KILL:
case ExpEvent.KILL_GROUND:
case ExpEvent.KILL_HUMAN: return scored('kill');
case ExpEvent.ASSIST: return scored('assist');
case ExpEvent.CRITICAL_HIT: return scored('criticalHit');
case ExpEvent.HIT: return scored('hit');
case ExpEvent.SEVERE_DAMAGE: return scored('severeDamage');
case ExpEvent.CAPTURE_ZONE: return this.#tuning.captureZoneScore[group];
case ExpEvent.UNIT_DAMAGE: return this.#tuning.navalDamageScorePerPoint;
default: return undefined;
}
}
}
function debriefingRow(fact: CombatEventFact, group: VictimGroup): DebriefingRow | undefined {
switch (fact.code) {
case ExpEvent.KILL:
case ExpEvent.KILL_GROUND:
case ExpEvent.KILL_HUMAN:
if (fact.friendly) return 'FriendlyKills';
return group === 'air' ? 'AirKills' : group === 'naval' ? 'NavalKills' : group === 'human' ? 'HumanKills' : 'GroundKills';
case ExpEvent.ASSIST: return 'Assist';
case ExpEvent.CRITICAL_HIT: return 'Critical';
case ExpEvent.HIT: return 'Hit';
case ExpEvent.SEVERE_DAMAGE: return group === 'naval' ? 'ShipSevereDamage' : 'AirSevereDamage';
case ExpEvent.CAPTURE_ZONE: return 'Captures';
case ExpEvent.UNIT_DAMAGE: return 'AwardDamage';
default: return undefined;
}
}
@@ -1,167 +1,101 @@
/**
* Battle debriefing report schema and DataBlock parser for `cln_wto_finish_battle`,
* including per-unit and top-level reward categories mapped to `EULT_SESSION_RESULT`
* `body/container` event blocks (`scripts/userlog/getuserlogbattlerewardstable.nut`).
* The battle report of `cln_wto_finish_battle` (gui-patches/battle/report-local-battle-settlement):
* what happened in the battle, as facts only. The client sends no money; the local service
* prices every event (battle-economy.ts).
*
* sessionId:t outcome:t ("win" | "lose" | "running") localTeam:i
* teamAScore:i teamBScore:i sessionStart:r sessionEnd:r (mission time, seconds)
* lives{ life{ unit:t start:r end:r } ... } one per spawn of the local player
* events{ e{ time:r unit:t code:i expClass:t victim:t victimIsPlayer:b friendly:b
* modifier:t damage:i } ... } the local player's combat events
* spares{ <unit>:i ... } backup vehicles used
*/
import { findBlock, type BlkBlock } from '@wto/blk';
import type { CombatEventFact } from './battle-economy.ts';
export type BattleOutcomeKind = 'win' | 'lose' | 'running';
export interface RewardCategoryStat {
readonly count: number;
readonly wp: number;
readonly exp: number;
export interface BattleLife {
readonly unit: string;
readonly start: number;
readonly end: number;
}
export interface RewardCategorySpec {
readonly category: string;
readonly containerId: string;
readonly victimUnitFileName?: string;
readonly singleSummaryEvent?: boolean;
}
export const REWARD_CATEGORY_SPECS: readonly RewardCategorySpec[] = [
{ category: 'AirKills', containerId: 'eventKill' },
{ category: 'GroundKills', containerId: 'eventKillGround' },
{ category: 'NavalKills', containerId: 'eventKillGround', victimUnitFileName: 'ships/' },
{ category: 'HumanKills', containerId: 'eventKillHuman' },
{ category: 'Assist', containerId: 'eventAssist' },
{ category: 'AirSevereDamage', containerId: 'eventSevereDamage' },
{ category: 'ShipSevereDamage', containerId: 'eventSevereDamage' },
{ category: 'Critical', containerId: 'eventCriticalHit' },
{ category: 'Hit', containerId: 'eventHit' },
{ category: 'Takeoffs', containerId: 'eventTakeoff' },
{ category: 'Landings', containerId: 'eventLanding' },
{ category: 'MissileEvade', containerId: 'eventMissileEvade' },
{ category: 'ShellInterception', containerId: 'eventShellInterception' },
{ category: 'Captures', containerId: 'eventCaptureZone' },
{ category: 'SectorCapture', containerId: 'eventSectorCapture' },
{ category: 'SuppliesDelivery', containerId: 'eventSuppliesDelivery' },
{ category: 'SuppliesReturn', containerId: 'eventSuppliesReturn' },
{ category: 'SuppliesDestroy', containerId: 'eventSuppliesDestroy' },
{ category: 'SuppliesEscort', containerId: 'eventSuppliesEscort' },
{ category: 'Destruction', containerId: 'eventDestroyZone' },
{ category: 'Damage', containerId: 'eventDamageZone' },
{ category: 'Scout', containerId: 'eventScout' },
{ category: 'ScoutCriticalHit', containerId: 'eventScoutCriticalHit' },
{ category: 'ScoutKill', containerId: 'eventScoutKill' },
{ category: 'ScoutKillUnknown', containerId: 'eventScoutKill' },
{ category: 'TimedAward', containerId: 'eventTimedAward' },
{ category: 'Unlocks', containerId: 'eventStreak' },
{ category: 'BattleTime', containerId: 'eventBattletime', singleSummaryEvent: true },
];
export interface VehicleBattleStats {
readonly vehicle: string;
readonly wpTotal: number;
readonly expTotal: number;
readonly expModsTotal: number;
readonly expUnitTotal: number;
readonly wpMission: number;
readonly expSkillBonusTotal: number;
readonly expSkillBonusLevel: number;
readonly sessionTime: number;
readonly battleTime: number;
readonly rewards: Readonly<Record<string, RewardCategoryStat>>;
export interface ReportedCombatEvent extends CombatEventFact {
readonly time: number;
readonly unit: string;
readonly victim: string;
readonly modifier: string;
}
export interface BattleReport {
readonly sessionId: string;
readonly country: string;
readonly outcome: BattleOutcomeKind;
readonly localTeam: number;
readonly teamAScore: number;
readonly teamBScore: number;
readonly teamAKills: number;
readonly teamBKills: number;
readonly wpTotal: number;
readonly expTotal: number;
readonly expFree: number;
readonly wpMission: number;
readonly wpTeamKills: number;
readonly expSkillBonusTotal: number;
readonly expSkillBonusLevel: number;
readonly activity: number;
readonly sessionTime: number;
readonly battleTime: number;
readonly rewards: Readonly<Record<string, RewardCategoryStat>>;
readonly sessionStart: number;
readonly sessionEnd: number;
readonly lives: readonly BattleLife[];
readonly events: readonly ReportedCombatEvent[];
readonly usedSpares: Readonly<Record<string, number>>;
readonly vehicles: readonly VehicleBattleStats[];
}
/** Undefined when the report is malformed; lives and events that make no sense are dropped. */
export function parseBattleReport(payload: BlkBlock): BattleReport | undefined {
const sessionId = strOf(payload, 'sessionId');
if (!sessionId || !/^[0-9a-f]{16}$/i.test(sessionId)) return undefined;
const rawOutcome = strOf(payload, 'outcome');
const outcome: BattleOutcomeKind = rawOutcome === 'win' || rawOutcome === 'lose' ? rawOutcome : 'running';
const vehiclesBlock = findBlock(payload, 'vehicles');
const vehicles: VehicleBattleStats[] = (vehiclesBlock?.blocks ?? [])
.filter((block) => block.name.length > 0)
.map((block) => ({
vehicle: block.name,
wpTotal: intOf(block, 'wpTotal'),
expTotal: intOf(block, 'expTotal'),
expModsTotal: intOf(block, 'expModsTotal'),
expUnitTotal: intOf(block, 'expUnitTotal'),
wpMission: intOf(block, 'wpMission'),
expSkillBonusTotal: intOf(block, 'expSkillBonusTotal'),
expSkillBonusLevel: intOf(block, 'expSkillBonusLevel'),
sessionTime: realOf(block, 'sessionTime'),
battleTime: realOf(block, 'battleTime'),
rewards: parseRewardMap(findBlock(block, 'rewards')),
}));
const sessionStart = Math.max(0, realOf(payload, 'sessionStart'));
const sessionEnd = Math.max(sessionStart, realOf(payload, 'sessionEnd'));
const lives = (findBlock(payload, 'lives')?.blocks ?? []).flatMap((block): BattleLife[] => {
const unit = strOf(block, 'unit');
const start = Math.max(sessionStart, realOf(block, 'start'));
const end = Math.min(sessionEnd, Math.max(start, realOf(block, 'end')));
return unit ? [{ unit, start, end }] : [];
});
const livedUnits = new Set(lives.map((life) => life.unit));
const events = (findBlock(payload, 'events')?.blocks ?? []).flatMap((block): ReportedCombatEvent[] => {
const unit = strOf(block, 'unit');
if (!unit || !livedUnits.has(unit)) return [];
return [{
time: realOf(block, 'time'),
unit,
code: intOf(block, 'code'),
expClass: strOf(block, 'expClass') ?? '',
victim: strOf(block, 'victim') ?? '',
victimIsPlayer: boolOf(block, 'victimIsPlayer'),
friendly: boolOf(block, 'friendly'),
modifier: strOf(block, 'modifier') ?? '',
damage: Math.max(0, intOf(block, 'damage')),
}];
});
return {
sessionId: sessionId.toLowerCase(),
country: strOf(payload, 'country') ?? '',
outcome,
outcome: rawOutcome === 'win' || rawOutcome === 'lose' ? rawOutcome : 'running',
localTeam: intOf(payload, 'localTeam', 1),
teamAScore: intOf(payload, 'teamAScore'),
teamBScore: intOf(payload, 'teamBScore'),
teamAKills: intOf(payload, 'teamAKills'),
teamBKills: intOf(payload, 'teamBKills'),
wpTotal: intOf(payload, 'wpTotal'),
expTotal: intOf(payload, 'expTotal'),
expFree: intOf(payload, 'expFree'),
wpMission: intOf(payload, 'wpMission'),
wpTeamKills: intOf(payload, 'wpTeamKills'),
expSkillBonusTotal: intOf(payload, 'expSkillBonusTotal'),
expSkillBonusLevel: intOf(payload, 'expSkillBonusLevel'),
activity: realOf(payload, 'activity'),
sessionTime: realOf(payload, 'sessionTime'),
battleTime: realOf(payload, 'battleTime'),
rewards: parseRewardMap(findBlock(payload, 'rewards')),
sessionStart,
sessionEnd,
lives,
events,
usedSpares: parseSpareMap(findBlock(payload, 'spares')),
vehicles,
};
}
function parseRewardMap(rewardsBlk: BlkBlock | undefined): Record<string, RewardCategoryStat> {
const out: Record<string, RewardCategoryStat> = {};
if (!rewardsBlk) return out;
for (const catBlk of rewardsBlk.blocks) {
if (!catBlk.name) continue;
const count = Math.max(0, intOf(catBlk, 'count'));
const wp = Math.max(0, intOf(catBlk, 'wp'));
const exp = Math.max(0, intOf(catBlk, 'exp'));
if (count > 0 || wp > 0 || exp > 0) out[catBlk.name] = { count, wp, exp };
}
return out;
}
function parseSpareMap(sparesBlk: BlkBlock | undefined): Record<string, number> {
const out: Record<string, number> = {};
if (!sparesBlk) return out;
for (const param of sparesBlk.params) {
if (!param.name) continue;
const count = param.value.type === 'int' ? param.value.value : param.value.type === 'int64' ? Number(param.value.value) : 0;
if (count > 0) out[param.name] = count;
for (const param of sparesBlk?.params ?? []) {
const count = param.value.type === 'int' ? param.value.value : 0;
if (param.name && count > 0) out[param.name] = count;
}
return out;
}
function strOf(block: BlkBlock, name: string): string | undefined {
const value = block.params.find((p) => p.name === name)?.value;
return value?.type === 'string' ? value.value : undefined;
return value?.type === 'string' && value.value !== '' ? value.value : undefined;
}
function intOf(block: BlkBlock, name: string, fallback = 0): number {
@@ -173,7 +107,11 @@ function intOf(block: BlkBlock, name: string, fallback = 0): number {
function realOf(block: BlkBlock, name: string): number {
const value = block.params.find((p) => p.name === name)?.value;
if (value?.type === 'real') return value.value;
if (value?.type === 'int') return value.value;
if (value?.type === 'real' || value?.type === 'int') return Number.isFinite(value.value) ? value.value : 0;
return 0;
}
function boolOf(block: BlkBlock, name: string): boolean {
const value = block.params.find((p) => p.name === name)?.value;
return value?.type === 'bool' ? value.value : value?.type === 'int' ? value.value !== 0 : false;
}
@@ -1,12 +1,13 @@
/**
* Assemble and append full `EULT_SESSION_RESULT` (`type = 2`) battle mail entries into
* `profile.userlogs` matching `scripts/userlog/userlogviewdata.nut` and
* `scripts/userlog/getuserlogbattlerewardstable.nut`.
* The `EULT_SESSION_RESULT` (type 2) user log of a settled battle, in the shape the client's battle
* log reads (gui.vromfs.bin scripts/userlog/userlogviewdata.nut, getuserlogbattlerewardstable.nut),
* plus the debriefing table (`wtoDebriefing`, battle-debriefing.ts) the settlement patch shows.
*/
import { emptyBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
import { REWARD_CATEGORY_SPECS, type BattleReport, type RewardCategorySpec } from './battle-report.ts';
import type { DebriefingRow } from './battle-economy.ts';
import type { BattleRewards, Bonuses } from './battle-rewards.ts';
import type { BattleSession } from './battle-session-store.ts';
export interface EarnedRpItem {
@@ -17,19 +18,33 @@ export interface EarnedRpItem {
}
export interface BattleResultSummary {
readonly win: boolean;
readonly country: string;
readonly wpEarned: number;
readonly xpEarned: number;
readonly activity: number;
readonly slMul: number;
readonly rpMul: number;
readonly rewards: BattleRewards;
readonly weaponRefillSl: number;
readonly friendlyFirePenalty: number;
readonly report: BattleReport;
readonly usedSpares: Readonly<Record<string, number>>;
readonly rpItems: readonly EarnedRpItem[];
readonly debriefing: BlkBlock;
}
const NO_BONUSES: Bonuses = { premAccWp: 0, premAccExp: 0, premModExp: 0 };
/** Container list of each debriefing row's events (getuserlogbattlerewardstable.nut ids). */
const CONTAINER_OF_ROW: Readonly<Record<DebriefingRow, string | undefined>> = {
AirKills: 'eventKill',
GroundKills: 'eventKillGround',
NavalKills: 'eventKillGround',
HumanKills: 'eventKillHuman',
FriendlyKills: undefined,
Assist: 'eventAssist',
AirSevereDamage: 'eventSevereDamage',
ShipSevereDamage: 'eventSevereDamage',
Critical: 'eventCriticalHit',
Hit: 'eventHit',
Captures: 'eventCaptureZone',
// No user log list carries naval damage awards; they show in the debriefing table only.
AwardDamage: undefined,
};
export function mergeEarnedRpItems(items: readonly EarnedRpItem[]): EarnedRpItem[] {
const byKey = new Map<string, EarnedRpItem>();
for (const item of items) {
@@ -51,32 +66,28 @@ export function mergeEarnedRpItems(items: readonly EarnedRpItem[]): EarnedRpItem
return [...byKey.values()];
}
export function appendBattleResultLog(
profile: BlkBlock,
session: BattleSession,
summary: BattleResultSummary,
): void {
export function appendBattleResultLog(profile: BlkBlock, session: BattleSession, summary: BattleResultSummary): void {
const { rewards } = summary;
const friendlyFirePenalty = rewards.events
.filter((settled) => settled.priced.row === 'FriendlyKills')
.reduce((sum, settled) => sum + settled.priced.wp, 0);
const bodyParams: BlkParam[] = [
{ name: 'win', value: { type: 'bool', value: summary.win } },
{ name: 'win', value: { type: 'bool', value: rewards.win } },
{ name: 'mission', value: { type: 'string', value: session.missionName } },
...(session.missionLocName ? [{ name: 'locName', value: { type: 'string' as const, value: session.missionLocName } }] : []),
{ name: 'country', value: { type: 'string', value: summary.country } },
{ name: 'eventId', value: { type: 'string', value: session.modeName } },
{ name: 'wpEarned', value: { type: 'int', value: summary.wpEarned } },
{ name: 'xpEarned', value: { type: 'int', value: summary.xpEarned } },
{ name: 'activity', value: { type: 'real', value: summary.activity } },
...(summary.friendlyFirePenalty !== 0
? [{ name: 'friendlyFirePenalty', value: { type: 'int' as const, value: summary.friendlyFirePenalty } }]
: []),
{ name: 'wpEarned', value: { type: 'int', value: rewards.wpTotal } },
{ name: 'xpEarned', value: { type: 'int', value: rewards.expTotal } },
{ name: 'activity', value: { type: 'real', value: rewards.activity } },
...(friendlyFirePenalty !== 0 ? [{ name: 'friendlyFirePenalty', value: { type: 'int' as const, value: friendlyFirePenalty } }] : []),
{ name: 'wtoSessionId', value: { type: 'string', value: session.sessionId } },
{ name: 'wtoSlMul', value: { type: 'real', value: summary.slMul } },
{ name: 'wtoRpMul', value: { type: 'real', value: summary.rpMul } },
];
const bodyBlocks: BlkBlock[] = [buildContainerBlock(summary)];
const aircrafts = buildAircraftsBlock(summary.report);
if (aircrafts) bodyBlocks.push(aircrafts);
const spare = buildSpareBlock(summary.report);
const bodyBlocks: BlkBlock[] = [buildContainerBlock(summary), summary.debriefing];
const aircrafts = emptyBlock('aircrafts');
for (const vehicle of rewards.vehicles) setParam(aircrafts, vehicle.vehicle, { type: 'real', value: 1.0 });
if (aircrafts.params.length > 0) bodyBlocks.push(aircrafts);
const spare = buildSpareBlock(summary.usedSpares);
if (spare) bodyBlocks.push(spare);
const rpEarned = buildRpEarnedBlock(summary.rpItems);
if (rpEarned) bodyBlocks.push(rpEarned);
@@ -92,171 +103,81 @@ export function appendBattleResultLog(
function buildContainerBlock(summary: BattleResultSummary): BlkBlock {
const container = emptyBlock('container');
const { report, slMul, rpMul } = summary;
if (summary.weaponRefillSl > 0) {
setParam(container, 'wpCostWeaponRefill', { type: 'int', value: summary.weaponRefillSl });
}
const wpMission = scalePositive(
Math.max(report.wpMission, report.vehicles.reduce((s, v) => s + Math.max(0, v.wpMission), 0)),
slMul,
);
if (wpMission > 0) {
setParam(container, 'wpMissionEndAward', { type: 'int', value: wpMission });
}
const { rewards } = summary;
if (summary.weaponRefillSl > 0) setParam(container, 'wpCostWeaponRefill', { type: 'int', value: summary.weaponRefillSl });
const eventLists = new Map<string, BlkBlock[]>();
for (const spec of REWARD_CATEGORY_SPECS) {
appendCategoryEvents(eventLists, spec, report, slMul, rpMul);
}
for (const [containerId, events] of eventLists) {
if (events.length > 0) {
container.blocks.push({ name: containerId, params: [], blocks: events });
const lists = new Map<string, BlkBlock[]>();
const push = (id: string, event: BlkBlock): void => {
const list = lists.get(id);
if (list) list.push(event);
else lists.set(id, [event]);
};
for (const { event, priced, bonuses } of rewards.events) {
const id = CONTAINER_OF_ROW[priced.row];
if (!id) continue;
const block = emptyBlock('event');
setParam(block, 'offenderUnit', { type: 'string', value: event.unit });
if (event.victim) setParam(block, 'victimUnit', { type: 'string', value: event.victim });
if (priced.row === 'NavalKills' || priced.row === 'ShipSevereDamage') {
setParam(block, 'victimUnitFileName', { type: 'string', value: 'ships/' });
}
writeAmounts(block, priced.wp, priced.exp, bonuses);
push(id, block);
}
const sessionAward = buildUnitSessionAwardBlock(report);
if (sessionAward) container.blocks.push(sessionAward);
const skillBonus = buildSkillBonusBlock(report, rpMul);
if (skillBonus) container.blocks.push(skillBonus);
let missionWp = 0;
for (const vehicle of rewards.vehicles) {
if (vehicle.sessionTime > 0) {
const block = emptyBlock('event');
setParam(block, 'unit', { type: 'string', value: vehicle.vehicle });
setParam(block, 'lifetime', { type: 'int', value: Math.round(vehicle.sessionTime) });
writeAmounts(block, 0, 0, NO_BONUSES);
push('unitSessionAward', block);
}
const time = vehicle.rows.get('BattleTime');
if (time) {
const block = emptyBlock('event');
setParam(block, 'offenderUnit', { type: 'string', value: vehicle.vehicle });
writeAmounts(block, time.noBonusWp, time.noBonusExp, time);
push('eventBattletime', block);
}
const timed = vehicle.rows.get('TimedAward');
if (timed) {
const block = emptyBlock('event');
setParam(block, 'offenderUnit', { type: 'string', value: vehicle.vehicle });
writeAmounts(block, timed.noBonusWp, 0, timed);
push('eventTimedAward', block);
}
const mission = vehicle.rows.get('Mission');
if (mission) missionWp += mission.noBonusWp + mission.premAccWp;
}
for (const [id, events] of lists) container.blocks.push({ name: id, params: [], blocks: events });
if (missionWp > 0) setParam(container, 'wpMissionEndAward', { type: 'int', value: missionWp });
const skillUnits = rewards.vehicles.filter((vehicle) => vehicle.skillBonusExp > 0).map((vehicle) => {
const unit = emptyBlock('unit');
setParam(unit, 'unit', { type: 'string', value: vehicle.vehicle });
setParam(unit, 'bonusLevel', { type: 'int', value: rewards.skillBonusLevel });
setParam(unit, 'exp', { type: 'int', value: vehicle.skillBonusExp });
return unit;
});
if (skillUnits.length > 0) container.blocks.push({ name: 'expSkillBonus', params: [], blocks: skillUnits });
return container;
}
function appendCategoryEvents(
eventLists: Map<string, BlkBlock[]>,
spec: RewardCategorySpec,
report: BattleReport,
slMul: number,
rpMul: number,
): void {
let unitWpSum = 0;
let unitExpSum = 0;
let hasUnitEntries = false;
for (const vehicle of report.vehicles) {
const stat = vehicle.rewards[spec.category];
if (!stat) continue;
hasUnitEntries = true;
const wp = scalePositive(stat.wp, slMul);
const exp = scalePositive(stat.exp, rpMul);
unitWpSum += stat.wp;
unitExpSum += stat.exp;
pushSplitEvents(eventLists, spec, vehicle.vehicle, stat.count, wp, exp);
}
const rootStat = report.rewards[spec.category];
if (!rootStat) return;
if (!hasUnitEntries) {
const fallbackUnit = report.vehicles[0]?.vehicle ?? '';
pushSplitEvents(
eventLists,
spec,
fallbackUnit,
rootStat.count,
scalePositive(rootStat.wp, slMul),
scalePositive(rootStat.exp, rpMul),
);
return;
}
const extraWp = scalePositive(rootStat.wp - unitWpSum, slMul);
const extraExp = scalePositive(rootStat.exp - unitExpSum, rpMul);
if (extraWp > 0 || extraExp > 0) {
pushSplitEvents(eventLists, spec, report.vehicles[0]?.vehicle ?? '', 1, extraWp, extraExp);
}
function writeAmounts(block: BlkBlock, wp: number, exp: number, bonuses: Bonuses): void {
setParam(block, 'wpNoBonus', { type: 'int', value: wp });
setParam(block, 'expNoBonus', { type: 'int', value: exp });
if (bonuses.premAccWp) setParam(block, 'wpPremAcc', { type: 'int', value: bonuses.premAccWp });
if (bonuses.premAccExp) setParam(block, 'expPremAcc', { type: 'int', value: bonuses.premAccExp });
if (bonuses.premModExp) setParam(block, 'expPremMod', { type: 'int', value: bonuses.premModExp });
}
function pushSplitEvents(
eventLists: Map<string, BlkBlock[]>,
spec: RewardCategorySpec,
offenderUnit: string,
rawCount: number,
totalWp: number,
totalExp: number,
): void {
if (rawCount <= 0 && totalWp <= 0 && totalExp <= 0) return;
const count = spec.singleSummaryEvent ? 1 : Math.min(64, Math.max(1, rawCount));
let list = eventLists.get(spec.containerId);
if (!list) {
list = [];
eventLists.set(spec.containerId, list);
}
let prevWp = 0;
let prevExp = 0;
for (let i = 0; i < count; i++) {
const nextWp = Math.round((totalWp * (i + 1)) / count);
const nextExp = Math.round((totalExp * (i + 1)) / count);
const ev = emptyBlock('event');
if (offenderUnit) setParam(ev, 'offenderUnit', { type: 'string', value: offenderUnit });
if (spec.victimUnitFileName) setParam(ev, 'victimUnitFileName', { type: 'string', value: spec.victimUnitFileName });
setParam(ev, 'wpNoBonus', { type: 'int', value: nextWp - prevWp });
setParam(ev, 'expNoBonus', { type: 'int', value: nextExp - prevExp });
list.push(ev);
prevWp = nextWp;
prevExp = nextExp;
}
}
function buildUnitSessionAwardBlock(report: BattleReport): BlkBlock | undefined {
const events: BlkBlock[] = [];
for (const v of report.vehicles) {
const sec = Math.round(v.sessionTime > 0 ? v.sessionTime : v.battleTime);
if (sec <= 0) continue;
const ev = emptyBlock('event');
setParam(ev, 'unit', { type: 'string', value: v.vehicle });
setParam(ev, 'lifetime', { type: 'int', value: sec });
setParam(ev, 'wpNoBonus', { type: 'int', value: 0 });
setParam(ev, 'expNoBonus', { type: 'int', value: 0 });
events.push(ev);
}
if (events.length === 0) {
const rootSec = Math.round(report.sessionTime > 0 ? report.sessionTime : report.battleTime);
if (rootSec <= 0) return undefined;
const ev = emptyBlock('event');
setParam(ev, 'lifetime', { type: 'int', value: rootSec });
setParam(ev, 'wpNoBonus', { type: 'int', value: 0 });
setParam(ev, 'expNoBonus', { type: 'int', value: 0 });
events.push(ev);
}
return { name: 'unitSessionAward', params: [], blocks: events };
}
function buildSkillBonusBlock(report: BattleReport, rpMul: number): BlkBlock | undefined {
const units: BlkBlock[] = [];
for (const v of report.vehicles) {
const exp = scalePositive(v.expSkillBonusTotal, rpMul);
if (exp <= 0) continue;
const uBlk = emptyBlock('unit');
setParam(uBlk, 'unit', { type: 'string', value: v.vehicle });
setParam(uBlk, 'bonusLevel', { type: 'int', value: Math.max(1, v.expSkillBonusLevel || report.expSkillBonusLevel) });
setParam(uBlk, 'exp', { type: 'int', value: exp });
units.push(uBlk);
}
if (units.length === 0 && report.expSkillBonusTotal > 0) {
const exp = scalePositive(report.expSkillBonusTotal, rpMul);
if (exp > 0) {
const uBlk = emptyBlock('unit');
setParam(uBlk, 'unit', { type: 'string', value: report.vehicles[0]?.vehicle ?? '' });
setParam(uBlk, 'bonusLevel', { type: 'int', value: Math.max(1, report.expSkillBonusLevel) });
setParam(uBlk, 'exp', { type: 'int', value: exp });
units.push(uBlk);
}
}
return units.length > 0 ? { name: 'expSkillBonus', params: [], blocks: units } : undefined;
}
function buildAircraftsBlock(report: BattleReport): BlkBlock | undefined {
if (report.vehicles.length === 0) return undefined;
const blk = emptyBlock('aircrafts');
for (const v of report.vehicles) {
setParam(blk, v.vehicle, { type: 'real', value: 1.0 });
}
return blk;
}
function buildSpareBlock(report: BattleReport): BlkBlock | undefined {
const entries = Object.entries(report.usedSpares).filter(([unit, cnt]) => unit.length > 0 && cnt > 0);
function buildSpareBlock(usedSpares: Readonly<Record<string, number>>): BlkBlock | undefined {
const entries = Object.entries(usedSpares).filter(([unit, count]) => unit.length > 0 && count > 0);
if (entries.length === 0) return undefined;
const blk = emptyBlock('spare');
for (const [unit, count] of entries) {
setParam(blk, unit, { type: 'int', value: Math.trunc(count) });
}
for (const [unit, count] of entries) setParam(blk, unit, { type: 'int', value: Math.trunc(count) });
return blk;
}
@@ -267,14 +188,7 @@ function buildRpEarnedBlock(items: readonly EarnedRpItem[]): BlkBlock | undefine
setParam(rpEarned, `aname${index}`, { type: 'string', value: item.unit });
if (item.modification) setParam(rpEarned, `mname${index}`, { type: 'string', value: item.modification });
setParam(rpEarned, `mrp${index}`, { type: 'int', value: item.rp });
if (item.excessRp && item.excessRp > 0) {
setParam(rpEarned, `merp${index}`, { type: 'int', value: item.excessRp });
}
if (item.excessRp && item.excessRp > 0) setParam(rpEarned, `merp${index}`, { type: 'int', value: item.excessRp });
});
return rpEarned;
}
function scalePositive(base: number, mul: number): number {
if (!Number.isFinite(base) || base <= 0) return 0;
return Math.min(0x7fffffff, Math.max(0, Math.round(base * mul)));
}
@@ -0,0 +1,193 @@
/**
* Settles a battle report into rewards, row by row as the debriefing shows them (pure: reads no
* profile, writes nothing).
*
* - Combat events: priced by battle-economy.ts against the vehicle the player was in.
* - BattleTime: Silver Lions = battleTimeAward x active minutes x activity (offline: the game
* files do not say what battleTimeAward measures; the client labels the sibling timedAward
* "per minute"); Research Points = active seconds x expForVictoryVersusPerSec (win) or
* expForPlayingVersusPerSec x expMul x activity (rank.blk; the per-second rates match the
* official numbers).
* - TimedAward: timedAward (Silver Lions per minute, client label "max_timed_reward") x active minutes.
* - Mission: winK or defeatK (warpoints.blk) x the vehicle's other Silver Lions; a battle the player
* left before it ended counts as a defeat.
* - Activity: time spent in a vehicle / time in the battle (offline: the online formula is not published).
* - Premium account: + (wpMultiplier - 1) Silver Lions and + (xpMultiplier - 1) Research Points on
* every row; premium vehicle or talisman: + (goldPlaneExpMul - 1) Research Points (the same terms
* as the client's vehicle card, scripts/airinfo.nut).
* - Skill bonus: rank.blk ExpSkillBonus of the mode's economic name, by kills of players (or naval
* damage), as a percentage of the Research Points without bonuses.
* - Free Research Points: total Research Points / denominateFreeExp (rank.blk; how the server uses
* it is inferred from the name, not verified).
*/
import type { EconomyDifficulty } from '../game-data/datasets/battle-economy.ts';
import { BattleEconomy, ExpEvent, type DebriefingRow, type PricedEvent } from './battle-economy.ts';
import type { BattleReport, ReportedCombatEvent } from './battle-report.ts';
export type RewardRow = DebriefingRow | 'BattleTime' | 'TimedAward' | 'Mission';
export interface RowRewards {
count: number;
noBonusWp: number;
noBonusExp: number;
premAccWp: number;
premAccExp: number;
premModExp: number;
}
export interface VehicleRewards {
readonly vehicle: string;
/** Seconds the player spent in this vehicle. */
readonly sessionTime: number;
readonly rows: ReadonlyMap<RewardRow, RowRewards>;
readonly skillBonusExp: number;
readonly wpTotal: number;
readonly expTotal: number;
}
export interface Bonuses {
readonly premAccWp: number;
readonly premAccExp: number;
readonly premModExp: number;
}
export interface SettledEvent {
readonly event: ReportedCombatEvent;
readonly priced: PricedEvent;
readonly bonuses: Bonuses;
}
export interface BattleRewards {
readonly win: boolean;
readonly activity: number;
readonly sessionTime: number;
readonly battleTime: number;
readonly vehicles: readonly VehicleRewards[];
readonly events: readonly SettledEvent[];
readonly skillBonusLevel: number;
readonly wpTotal: number;
readonly expTotal: number;
readonly expFree: number;
}
export interface RewardContext {
readonly difficulty: EconomyDifficulty;
/** The mode's economic name, which selects rank.blk ExpSkillBonus. */
readonly economicName: string;
readonly premiumAccount: boolean;
/** Premium vehicle (costGold or premPackAir) or talisman installed. */
readonly hasTalisman: (vehicle: string) => boolean;
}
export function computeBattleRewards(report: BattleReport, economy: BattleEconomy, ctx: RewardContext): BattleRewards {
const win = report.outcome === 'win';
const sessionTime = Math.max(0, report.sessionEnd - report.sessionStart);
const timeByVehicle = new Map<string, number>();
for (const life of report.lives) {
if (!economy.vehicle(life.unit)) continue;
timeByVehicle.set(life.unit, (timeByVehicle.get(life.unit) ?? 0) + (life.end - life.start));
}
const battleTime = [...timeByVehicle.values()].reduce((sum, seconds) => sum + seconds, 0);
const activity = sessionTime > 0 ? Math.min(1, battleTime / sessionTime) : 0;
const { data, multipliers } = economy;
const bonusesOf = (vehicle: string, wp: number, exp: number): Bonuses => ({
premAccWp: ctx.premiumAccount ? Math.max(0, Math.round(wp * (data.premiumSilverLionsMul - 1))) : 0,
premAccExp: ctx.premiumAccount ? Math.round(exp * (data.premiumResearchMul - 1)) : 0,
premModExp: ctx.hasTalisman(vehicle) ? Math.round(exp * (data.talismanResearchMul - 1)) : 0,
});
const rowsByVehicle = new Map<string, Map<RewardRow, RowRewards>>();
const add = (vehicle: string, row: RewardRow, count: number, wp: number, exp: number): Bonuses => {
let rows = rowsByVehicle.get(vehicle);
if (!rows) rowsByVehicle.set(vehicle, rows = new Map());
let amounts = rows.get(row);
if (!amounts) rows.set(row, amounts = { count: 0, noBonusWp: 0, noBonusExp: 0, premAccWp: 0, premAccExp: 0, premModExp: 0 });
const bonuses = bonusesOf(vehicle, wp, exp);
amounts.count += count;
amounts.noBonusWp += wp;
amounts.noBonusExp += exp;
amounts.premAccWp += bonuses.premAccWp;
amounts.premAccExp += bonuses.premAccExp;
amounts.premModExp += bonuses.premModExp;
return bonuses;
};
for (const vehicle of timeByVehicle.keys()) rowsByVehicle.set(vehicle, new Map());
const events: SettledEvent[] = [];
for (const event of report.events) {
const priced = economy.price(event.unit, ctx.difficulty, event);
if (!priced) continue;
events.push({ event, priced, bonuses: add(event.unit, priced.row, priced.count, priced.wp, priced.exp) });
}
for (const [vehicle, seconds] of timeByVehicle) {
const veh = economy.vehicle(vehicle)!;
const minutes = seconds / 60;
const timeWp = Math.round(veh.battleTimeAward[ctx.difficulty] * minutes * activity * multipliers.silverLions);
const timeRp = Math.round(seconds * (win ? data.researchPerSecondWin : data.researchPerSecondPlaying)
* veh.expMul * activity * multipliers.researchPoints);
if (timeWp > 0 || timeRp > 0) add(vehicle, 'BattleTime', Math.round(seconds), timeWp, timeRp);
const timedWp = Math.round(veh.timedAward[ctx.difficulty] * minutes * multipliers.silverLions);
if (timedWp > 0) add(vehicle, 'TimedAward', 1, timedWp, 0);
}
for (const [vehicle, rows] of rowsByVehicle) {
const earned = [...rows.values()].reduce((sum, amounts) => sum + Math.max(0, amounts.noBonusWp), 0);
const missionWp = Math.round(earned * (win ? data.winK : data.defeatK));
if (missionWp > 0) add(vehicle, 'Mission', 1, missionWp, 0);
}
const { level: skillBonusLevel, percent: skillBonusPercent } = skillBonus(report.events, economy, ctx.economicName);
const vehicles: VehicleRewards[] = [];
for (const [vehicle, rows] of rowsByVehicle) {
let wpTotal = 0;
let baseExp = 0;
let expTotal = 0;
for (const amounts of rows.values()) {
wpTotal += amounts.noBonusWp + amounts.premAccWp;
baseExp += amounts.noBonusExp;
expTotal += amounts.noBonusExp + amounts.premAccExp + amounts.premModExp;
}
const skillBonusExp = Math.round(baseExp * skillBonusPercent / 100);
expTotal += skillBonusExp;
vehicles.push({ vehicle, sessionTime: timeByVehicle.get(vehicle) ?? 0, rows, skillBonusExp, wpTotal, expTotal });
}
const wpTotal = vehicles.reduce((sum, v) => sum + v.wpTotal, 0);
const expTotal = vehicles.reduce((sum, v) => sum + v.expTotal, 0);
return {
win,
activity,
sessionTime,
battleTime,
vehicles,
events,
skillBonusLevel,
wpTotal,
expTotal,
expFree: data.freeResearchDivisor > 0 ? Math.round(expTotal / data.freeResearchDivisor) : 0,
};
}
function skillBonus(
events: readonly ReportedCombatEvent[],
economy: BattleEconomy,
economicName: string,
): { level: number; percent: number } {
const levels = economy.data.skillBonus[economicName] ?? [];
let level = 0;
let percent = 0;
for (const rule of levels) {
const value = rule.metric === 'damage'
? events.reduce((sum, e) => sum + (e.code === ExpEvent.UNIT_DAMAGE && !e.friendly ? e.damage : 0), 0)
: events.filter((e) => isKill(e.code) && e.victimIsPlayer && !e.friendly).length;
if (value >= rule.threshold) {
level = rule.level;
percent = rule.bonusPercent;
}
}
return { level, percent };
}
function isKill(code: number): boolean {
return code === ExpEvent.KILL || code === ExpEvent.KILL_GROUND || code === ExpEvent.KILL_HUMAN;
}
@@ -39,7 +39,6 @@ import { addResearchPoints } from '../research/research-progress.ts';
import type { ResearchRules } from '../research/research-rules.ts';
import { currentStatus, refreshResearchState } from '../research/research-state.ts';
import { VehicleStatus } from '../research/vehicle-status.ts';
import type { BattleReport } from './battle-report.ts';
import type { EarnedRpItem } from './battle-result-log.ts';
import type { BattleSession } from './battle-session-store.ts';
@@ -49,34 +48,31 @@ export interface BattleRpDeps {
readonly crew: CrewSkillCatalogue;
}
export interface VehicleRp {
readonly vehicle: string;
readonly rp: number;
}
/** Each vehicle's Research Points go both to its own modification research and to its branch's vehicle research. */
export function collectEarnedBattleRp(
profile: BlkBlock,
report: BattleReport,
earned: readonly VehicleRp[],
session: BattleSession,
deps: BattleRpDeps,
rpMul: number,
earnedTotalRp: number,
): EarnedRpItem[] {
const rpItems: EarnedRpItem[] = [];
const owned = ownedVehicles(profile);
const branchTotals = new Map<string, { readonly country: string; readonly branchType: string; amount: number }>();
refreshResearchState(profile, deps.research);
for (const stat of report.vehicles) {
const modRp = scaleRp(stat.expModsTotal > 0 ? stat.expModsTotal : stat.expTotal, rpMul);
const unitRp = scaleRp(stat.expUnitTotal > 0 ? stat.expUnitTotal : stat.expTotal, rpMul);
if (modRp > 0 && owned.has(stat.vehicle)) {
const modItem = investModificationRp(profile, deps.equipment, stat.vehicle, modRp);
for (const { vehicle, rp } of earned) {
if (rp <= 0) continue;
if (owned.has(vehicle)) {
const modItem = investModificationRp(profile, deps.equipment, vehicle, rp);
if (modItem) rpItems.push(modItem);
investAceCrewRp(profile, deps.crew, session.country, vehicle, rp);
}
if (unitRp > 0) {
if (owned.has(stat.vehicle)) investAceCrewRp(profile, deps.crew, session.country, stat.vehicle, unitRp);
accumulateBranchRp(branchTotals, profile, deps.research, stat.vehicle, session, unitRp);
}
}
if (report.vehicles.length === 0 && earnedTotalRp > 0) {
const fallbackBranch = resolveFallbackBranch(profile, session.country, session.requiredClass);
if (fallbackBranch) addToBranchMap(branchTotals, session.country, fallbackBranch, earnedTotalRp);
accumulateBranchRp(branchTotals, profile, deps.research, vehicle, session, rp);
}
for (const entry of branchTotals.values()) {
const item = investIntoBranch(profile, deps.research, entry.country, entry.branchType, entry.amount);
@@ -259,8 +255,3 @@ function investAceCrewRp(
addExpertToAceRp(crew, vehicleName, amount, targetRp);
}
}
function scaleRp(base: number, multiplier: number): number {
if (!Number.isFinite(base) || base <= 0) return 0;
return Math.min(0x7fffffff, Math.max(0, Math.round(base * multiplier)));
}
@@ -1,75 +1,88 @@
/**
* Post-battle settlement rules (`cln_wto_finish_battle`):
* - Resolves battle win/loss (direct outcome when finished, weighted ticket + kill ratio on
* early leave).
* - Applies offline multipliers (`tuning/battle.jsonc`) to Silver Lions, Free RP, Modification
* RP, and Vehicle RP, runs `autoRefillWeapons` equipment top-ups, and appends the full
* `EULT_SESSION_RESULT` battle mail log.
* Post-battle settlement (`cln_wto_finish_battle`): prices the reported battle (battle-rewards.ts),
* pays Silver Lions and free Research Points, invests the vehicles' Research Points, credits crew
* skill points, refills equipment when the player has it enabled, and appends the
* `EULT_SESSION_RESULT` log that carries the debriefing table back to the client.
*/
import type { BlkBlock } from '@wto/blk';
import type { CrewSkillCatalogue } from '../crew/crew-skill-rules.ts';
import { stockAndRefillEquipment } from '../modifications/ammo-refill.ts';
import type { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts';
import { isAutoRefillWeaponsEnabled } from '../profile/profile-client-settings.ts';
import { addEarnedSkillPoints } from '../profile/profile-crew-skills.ts';
import { crewForVehicleInCountry } from '../profile/profile-crews.ts';
import { addSilverLions, balanceOf, pay } from '../profile/profile-currency.ts';
import { remainingPremiumDays } from '../profile/profile-entitlements.ts';
import { ownedVehicles } from '../profile/profile-hangar.ts';
import { ownsModification } from '../profile/profile-modifications.ts';
import { addFreeResearchPoints } from '../profile/profile-research-points.ts';
import { serverTimeNow } from '../profile/server-time.ts';
import type { ResearchRules } from '../research/research-rules.ts';
import { debriefingTable, type BranchInvestment, type ModuleInvestment } from './battle-debriefing.ts';
import { economyDifficulty, type BattleEconomy } from './battle-economy.ts';
import type { BattleReport } from './battle-report.ts';
import { appendBattleResultLog, mergeEarnedRpItems } from './battle-result-log.ts';
import { appendBattleResultLog, mergeEarnedRpItems, type EarnedRpItem } from './battle-result-log.ts';
import { computeBattleRewards } from './battle-rewards.ts';
import { collectEarnedBattleRp } from './battle-rp-investment.ts';
import type { BattleSession } from './battle-session-store.ts';
import type { BattleTuning } from './battle-tuning.ts';
export type { BattleOutcomeKind, BattleReport, VehicleBattleStats } from './battle-report.ts';
/** Talisman modification name (scripts/airinfo.nut shopIsModificationEnabled(unit, "premExpMul")). */
const TALISMAN = 'premExpMul';
export interface BattleSettlementDeps {
readonly research: ResearchRules;
readonly equipment: EquipmentCatalogue;
readonly crew: CrewSkillCatalogue;
readonly tuning: BattleTuning;
readonly economy: BattleEconomy;
}
export function settleBattle(
profile: BlkBlock,
report: BattleReport,
session: BattleSession,
deps: BattleSettlementDeps,
): void {
const win = resolveWin(report, deps.tuning);
const slMul = deps.tuning.rewardMultiplierSilverLions;
const rpMul = deps.tuning.rewardMultiplierResearchPoints;
const earnedSilverLions = scaleNonNegative(report.wpTotal, slMul);
const friendlyFirePenalty = report.wpTeamKills !== 0
? -scaleNonNegative(Math.abs(report.wpTeamKills), slMul)
: 0;
const baseTotalRp = Math.max(
report.expTotal,
report.vehicles.reduce((sum, vehicle) => sum + Math.max(0, vehicle.expTotal), 0),
);
const earnedTotalRp = scaleNonNegative(baseTotalRp, rpMul);
const earnedFreeRp = scaleNonNegative(report.expFree > 0 ? report.expFree : baseTotalRp, rpMul);
applyNetSilverLions(profile, earnedSilverLions + friendlyFirePenalty);
if (earnedFreeRp > 0) addFreeResearchPoints(profile, earnedFreeRp);
const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment);
const rpItems = collectEarnedBattleRp(profile, report, session, deps, rpMul, earnedTotalRp);
const country = report.country.startsWith('country_') ? report.country : session.country;
appendBattleResultLog(profile, session, {
win,
country,
wpEarned: earnedSilverLions,
xpEarned: earnedTotalRp,
activity: clampActivity(report.activity),
slMul,
rpMul,
weaponRefillSl,
friendlyFirePenalty,
report,
rpItems: mergeEarnedRpItems(rpItems),
export function settleBattle(profile: BlkBlock, report: BattleReport, session: BattleSession, deps: BattleSettlementDeps): void {
const difficulty = economyDifficulty(session.difficulty);
const rewards = computeBattleRewards(report, deps.economy, {
difficulty,
economicName: session.economicName,
premiumAccount: remainingPremiumDays(profile, serverTimeNow()) > 0,
hasTalisman: (vehicle) => deps.economy.isPremiumVehicle(vehicle) || ownsModification(profile, vehicle, TALISMAN),
});
applyNetSilverLions(profile, rewards.wpTotal);
if (rewards.expFree > 0) addFreeResearchPoints(profile, rewards.expFree);
const crewExpMul = deps.economy.data.crewExpMul[difficulty];
for (const vehicle of rewards.vehicles) {
const crew = crewForVehicleInCountry(profile, session.country, vehicle.vehicle);
if (crew && vehicle.expTotal > 0) addEarnedSkillPoints(crew, vehicle.expTotal * crewExpMul);
}
const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment);
const rpItems = collectEarnedBattleRp(
profile,
rewards.vehicles.map((vehicle) => ({ vehicle: vehicle.vehicle, rp: vehicle.expTotal })),
session,
deps,
);
const debriefing = debriefingTable('wtoDebriefing', rewards, investmentsOf(rpItems, deps.research));
appendBattleResultLog(profile, session, {
country: session.country.startsWith('country_') ? session.country : `country_${session.country}`,
rewards,
weaponRefillSl,
usedSpares: report.usedSpares,
rpItems: mergeEarnedRpItems(rpItems),
debriefing,
});
}
function investmentsOf(items: readonly EarnedRpItem[], research: ResearchRules): { modules: ModuleInvestment[]; branches: BranchInvestment[] } {
const modules: ModuleInvestment[] = [];
const branches: BranchInvestment[] = [];
for (const item of items) {
if (item.rp <= 0) continue;
if (item.modification) {
modules.push({ vehicle: item.unit, module: item.modification, rp: item.rp });
continue;
}
const type = research.techTree.vehicle(item.unit)?.type;
if (type) branches.push({ type, unit: item.unit, rp: item.rp });
}
return { modules, branches };
}
function applyNetSilverLions(profile: BlkBlock, netDelta: number): void {
@@ -91,27 +104,3 @@ function refillOwnedEquipment(profile: BlkBlock, catalogue: EquipmentCatalogue):
}
return totalSpent;
}
function resolveWin(report: BattleReport, tuning: BattleTuning): boolean {
if (report.outcome === 'win') return true;
if (report.outcome === 'lose') return false;
const isTeamB = report.localTeam === 2;
const myTickets = Math.max(0, isTeamB ? report.teamBScore : report.teamAScore);
const enemyTickets = Math.max(0, isTeamB ? report.teamAScore : report.teamBScore);
const myKills = Math.max(0, isTeamB ? report.teamBKills : report.teamAKills);
const enemyKills = Math.max(0, isTeamB ? report.teamAKills : report.teamBKills);
const ticketShare = myTickets + enemyTickets > 0 ? myTickets / (myTickets + enemyTickets) : 0.5;
const killShare = myKills + enemyKills > 0 ? myKills / (myKills + enemyKills) : 0.5;
const totalWeight = tuning.earlyLeaveTicketWeight + tuning.earlyLeaveKillWeight;
return (ticketShare * tuning.earlyLeaveTicketWeight + killShare * tuning.earlyLeaveKillWeight) / totalWeight >= 0.5;
}
function scaleNonNegative(base: number, multiplier: number): number {
if (!Number.isFinite(base) || base <= 0) return 0;
return Math.min(0x7fffffff, Math.max(0, Math.round(base * multiplier)));
}
function clampActivity(activity: number): number {
if (!Number.isFinite(activity)) return 0;
return Math.min(1, Math.max(0, activity));
}
@@ -1,7 +1,6 @@
/**
* Typed reader for `tuning/battle.jsonc`: offline Silver Lions and Research Points
* multipliers, LocalMP slot and bot counts, matchmaking BR window, coalition pairing
* rules, and early-leave win-inference weights.
* multipliers, LocalMP slot and bot counts, matchmaking BR window and coalition pairing rules.
*/
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
@@ -22,8 +21,6 @@ export interface BattleTuning {
readonly simColdWarMinMrank: number;
readonly tankBotRespawns: number;
readonly airBotRespawns: number;
readonly earlyLeaveTicketWeight: number;
readonly earlyLeaveKillWeight: number;
}
export function readBattleTuning(reader: TuningReader): BattleTuning {
@@ -45,11 +42,6 @@ export function readBattleTuning(reader: TuningReader): BattleTuning {
`tuning file battle.jsonc: rbCoalitionMaxCountries (${rbCoalitionMaxCountries}) must be at least rbCoalitionMinCountries (${rbCoalitionMinCountries})`,
);
}
const earlyLeaveTicketWeight = reader.number('earlyLeaveTicketWeight', { min: 0, max: 1 });
const earlyLeaveKillWeight = reader.number('earlyLeaveKillWeight', { min: 0, max: 1 });
if (earlyLeaveTicketWeight + earlyLeaveKillWeight <= 0) {
throw new TuningError('tuning file battle.jsonc: earlyLeaveTicketWeight + earlyLeaveKillWeight must be positive');
}
return {
rewardMultiplierSilverLions: reader.number('rewardMultiplierSilverLions', { min: 0, max: 100 }),
rewardMultiplierResearchPoints: reader.number('rewardMultiplierResearchPoints', { min: 0, max: 100 }),
@@ -67,7 +59,5 @@ export function readBattleTuning(reader: TuningReader): BattleTuning {
simColdWarMinMrank: reader.int('simColdWarMinMrank', { min: 0, max: 40 }),
tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }),
airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }),
earlyLeaveTicketWeight,
earlyLeaveKillWeight,
};
}
@@ -1,13 +1,13 @@
/**
* Char action `cln_wto_finish_battle`: receives the client's local-battle debriefing stats
* (`stat_get_exp()`), settles Silver Lions, Research Points, equipment refills, and
* `EULT_SESSION_RESULT` into the player's save, and answers the updated profile.
* Char action `cln_wto_finish_battle`: receives the facts of a local battle (battle-report.ts),
* settles them into the player's save (battle-settlement.ts) and answers the updated profile,
* whose new `EULT_SESSION_RESULT` log carries the debriefing table.
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { parseBattleReport } from '../../battle/battle-report.ts';
import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
import { settleBattle, type BattleSettlementDeps } from '../../battle/battle-settlement.ts';
import type { BattleTuning } from '../../battle/battle-tuning.ts';
import type { BattleEconomy } from '../../battle/battle-economy.ts';
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { clientProfile } from '../../profile/client-profile.ts';
@@ -18,7 +18,7 @@ import { withAccount } from './account-context.ts';
export interface BattleActionDependencies {
readonly sessions: BattleSessionStore;
readonly tuning: BattleTuning;
readonly economy: BattleEconomy;
}
export interface FinishBattleContext {
@@ -34,7 +34,7 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio
research: ctx.research,
equipment: ctx.equipment,
crew: ctx.crew,
tuning: battle.tuning,
economy: battle.economy,
};
return (context) => withAccount(context, ctx.accounts, (account) => {
const report = context.payload && parseBattleReport(context.payload);
@@ -0,0 +1,138 @@
/**
* Dataset: the battle reward factors the game files carry (implementation notes "3d").
*
* char.vromfs.bin config/wpcost.blk, per vehicle:
* unitClass, expMul, rewardMul<Arcade|Historical|Simulation>, battleTimeAward<...>, timedAward<...>
* char.vromfs.bin config/warpoints.blk:
* aKill (Silver Lions of a reference kill), aiKillK, winK, defeatK, wpMultiplier (premium account),
* units{} (Silver Lions factor by the destroyed unit's expClass)
* char.vromfs.bin config/rank.blk:
* xpMultiplier (premium account), goldPlaneExpMul (premium vehicle / talisman),
* expForVictoryVersusPerSec, expForPlayingVersusPerSec, crew_exp_mul_<difficulty>, denominateFreeExp,
* units{} (Research Points factor by the destroyed unit's expClass),
* ExpSkillBonus{<economic name>{BonusLevel<N>{bonusPercent, kills|damage}}}
*
* The stock client shows the same factors on the vehicle card (gui.vromfs.bin scripts/airinfo.nut,
* reward formula: expMul x (1 + premium + talisman), rewardMul x (1 + premium)).
*/
import type { BlkBlock } from '@wto/blk';
import { blockAt, numberField, stringField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export type EconomyDifficulty = 'arcade' | 'historical' | 'simulation';
const DIFFICULTY_SUFFIX: Readonly<Record<EconomyDifficulty, string>> = {
arcade: 'Arcade',
historical: 'Historical',
simulation: 'Simulation',
};
export interface VehicleEconomy {
readonly unitClass: string;
readonly expMul: number;
readonly rewardMul: Readonly<Record<EconomyDifficulty, number>>;
readonly battleTimeAward: Readonly<Record<EconomyDifficulty, number>>;
readonly timedAward: Readonly<Record<EconomyDifficulty, number>>;
}
export interface SkillBonusLevel {
readonly level: number;
readonly bonusPercent: number;
/** Kills needed, or naval damage needed when `metric` is "damage". */
readonly threshold: number;
readonly metric: 'kills' | 'damage';
}
export interface BattleEconomyData {
readonly vehicles: Readonly<Record<string, VehicleEconomy>>;
readonly killSilverLions: number;
readonly aiKillK: number;
readonly winK: number;
readonly defeatK: number;
readonly premiumSilverLionsMul: number;
readonly premiumResearchMul: number;
readonly talismanResearchMul: number;
readonly silverLionsClassFactors: Readonly<Record<string, number>>;
readonly researchClassFactors: Readonly<Record<string, number>>;
readonly researchPerSecondWin: number;
readonly researchPerSecondPlaying: number;
readonly crewExpMul: Readonly<Record<EconomyDifficulty, number>>;
readonly freeResearchDivisor: number;
readonly skillBonus: Readonly<Record<string, readonly SkillBonusLevel[]>>;
}
export const battleEconomy: Dataset<BattleEconomyData> = {
id: 'battle-economy',
version: 1,
extract: (source) => {
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
const warpoints = source.readBlk('char.vromfs.bin', 'config/warpoints.blk');
const rank = source.readBlk('char.vromfs.bin', 'config/rank.blk');
const required = (block: BlkBlock, file: string, name: string): number => {
const value = numberField(block, name);
if (value === undefined) throw new Error(`${file}: ${name} is missing`);
return value;
};
return {
vehicles: Object.fromEntries(wpcost.blocks.map((vehicle) => [vehicle.name, vehicleEconomy(vehicle)])),
killSilverLions: required(warpoints, 'warpoints.blk', 'aKill'),
aiKillK: required(warpoints, 'warpoints.blk', 'aiKillK'),
winK: required(warpoints, 'warpoints.blk', 'winK'),
defeatK: required(warpoints, 'warpoints.blk', 'defeatK'),
premiumSilverLionsMul: required(warpoints, 'warpoints.blk', 'wpMultiplier'),
premiumResearchMul: required(rank, 'rank.blk', 'xpMultiplier'),
talismanResearchMul: required(rank, 'rank.blk', 'goldPlaneExpMul'),
silverLionsClassFactors: numberMap(blockAt(warpoints, 'units')),
researchClassFactors: numberMap(blockAt(rank, 'units')),
researchPerSecondWin: required(rank, 'rank.blk', 'expForVictoryVersusPerSec'),
researchPerSecondPlaying: required(rank, 'rank.blk', 'expForPlayingVersusPerSec'),
crewExpMul: {
arcade: required(rank, 'rank.blk', 'crew_exp_mul_arcade'),
historical: required(rank, 'rank.blk', 'crew_exp_mul_historical'),
simulation: required(rank, 'rank.blk', 'crew_exp_mul_simulation'),
},
freeResearchDivisor: required(rank, 'rank.blk', 'denominateFreeExp'),
skillBonus: skillBonusTable(blockAt(rank, 'ExpSkillBonus')),
};
},
};
function vehicleEconomy(vehicle: BlkBlock): VehicleEconomy {
const perDifficulty = (prefix: string, fallback: number): Record<EconomyDifficulty, number> => ({
arcade: numberField(vehicle, `${prefix}${DIFFICULTY_SUFFIX.arcade}`) ?? fallback,
historical: numberField(vehicle, `${prefix}${DIFFICULTY_SUFFIX.historical}`) ?? fallback,
simulation: numberField(vehicle, `${prefix}${DIFFICULTY_SUFFIX.simulation}`) ?? fallback,
});
return {
unitClass: stringField(vehicle, 'unitClass') ?? '',
expMul: numberField(vehicle, 'expMul') ?? 1,
// The client reads a missing rewardMul as 1.0 (scripts/unit/unit.nut getWpRewardMulList).
rewardMul: perDifficulty('rewardMul', 1),
battleTimeAward: perDifficulty('battleTimeAward', 0),
timedAward: perDifficulty('timedAward', 0),
};
}
function numberMap(block: BlkBlock | undefined): Record<string, number> {
return Object.fromEntries((block?.params ?? []).flatMap((param) =>
param.value.type === 'real' || param.value.type === 'int' ? [[param.name, param.value.value]] : []));
}
function skillBonusTable(block: BlkBlock | undefined): Record<string, SkillBonusLevel[]> {
return Object.fromEntries((block?.blocks ?? []).map((event) => [
event.name,
event.blocks.flatMap((level): SkillBonusLevel[] => {
const index = /^BonusLevel(\d+)$/.exec(level.name)?.[1];
const bonusPercent = numberField(level, 'bonusPercent');
const kills = numberField(level, 'kills');
const damage = numberField(level, 'damage');
if (index === undefined || bonusPercent === undefined || (kills === undefined && damage === undefined)) return [];
return [{
level: Number(index),
bonusPercent,
threshold: kills ?? damage ?? 0,
metric: kills !== undefined ? 'kills' : 'damage',
}];
}).sort((a, b) => a.level - b.level),
]));
}
+11 -1
View File
@@ -4,6 +4,7 @@
*/
import type { Server } from 'node:net';
import { AccountStore } from './accounts/account-store.ts';
import { BattleEconomy } from './battle/battle-economy.ts';
import { BattleMatchmaker } from './battle/battle-matchmaker.ts';
import { BattleSessionStore } from './battle/battle-session-store.ts';
import { actionTable } from './char/actions/action-table.ts';
@@ -13,6 +14,7 @@ import { CloudSettingsStore } from './cloud-settings/cloud-settings-store.ts';
import { CrewSkillCatalogue } from './crew/crew-skill-rules.ts';
import { DecorShop } from './decor/decor-purchase.ts';
import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts';
import { battleEconomy } from './game-data/datasets/battle-economy.ts';
import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts';
import { clanEconomy } from './game-data/datasets/clan-economy.ts';
import { crewSkillData } from './game-data/datasets/crew-skills.ts';
@@ -80,6 +82,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
const cloudSettings = new CloudSettingsStore(options.dataFolder);
const vehicles = datasets.load(vehicleCatalogue);
const spawnRules = datasets.load(battleSpawnRules);
const economyData = datasets.load(battleEconomy);
const decals = datasets.load(decalTextures);
const labels = datasets.load(uiLabels);
const { profiles, research, equipment } = setUpProfiles(options.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
@@ -97,6 +100,12 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' });
const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept);
const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules);
const economy = new BattleEconomy(
economyData,
tuning.battleEconomy,
{ silverLions: tuning.battle.rewardMultiplierSilverLions, researchPoints: tuning.battle.rewardMultiplierResearchPoints },
new Set(vehicles.filter((vehicle) => vehicle.goldenEagles > 0 || vehicle.premiumPack).map((vehicle) => vehicle.name)),
);
const router = new Router([
webUi,
@@ -112,7 +121,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
...catalogues,
clans: { store: clans, economy: squadronEconomy },
cloudSettings,
battle: { sessions: battleSessions, tuning: tuning.battle },
battle: { sessions: battleSessions, economy },
notifyInventoryChanged,
})),
new DownloadableContentService(decals, options.gameFolder),
@@ -128,6 +137,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
profiles,
matchmaker: battleMatchmaker,
sessions: battleSessions,
economy,
notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload),
},
}),
@@ -9,9 +9,11 @@
* with typed getters, so the type travels with every value. Repeated blocks stay separate.
* - `lobby`: the session lobby settings the client's own room scripts read during the battle
* (game mode and both sides' countries).
* - `battle`: what the client keeps for this battle (session id for the settlement, extra slots).
* - `battle`: what the client keeps for this battle (session id for the settlement, extra slots,
* and `awards`, the parameters of the in-battle reward banner, battle-economy.ts BannerParams).
*/
import type { BlkBlock, BlkValue } from '@wto/blk';
import type { BannerParams } from '../battle/battle-economy.ts';
import type { BattleLaunchPlan } from '../battle/battle-matchmaker.ts';
import { battleMissionSettings } from '../battle/battle-mission-settings.ts';
@@ -30,7 +32,7 @@ export interface BattleLaunchNotify extends Record<string, unknown> {
readonly battle: Readonly<Record<string, unknown>>;
}
export function battleLaunchNotify(plan: BattleLaunchPlan): BattleLaunchNotify {
export function battleLaunchNotify(plan: BattleLaunchPlan, awards: BannerParams): BattleLaunchNotify {
return {
from: 'wto_battle',
func: 'launch',
@@ -53,6 +55,7 @@ export function battleLaunchNotify(plan: BattleLaunchPlan): BattleLaunchNotify {
extraBattleSlots: plan.extraBattleSlots,
randomUnits: plan.randomUnits,
randomUnitsEventName: plan.randomUnitsEventName ?? '',
awards,
},
};
}
@@ -6,6 +6,7 @@
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
* - `match.check_reconnect`
*/
import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.ts';
import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts';
import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankEntry } from '../battle/battle-ranks.ts';
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
@@ -20,6 +21,7 @@ export interface BattleQueueDependencies {
readonly profiles: PlayerProfiles;
readonly matchmaker: BattleMatchmaker;
readonly sessions: BattleSessionStore;
readonly economy: BattleEconomy;
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
}
@@ -99,10 +101,16 @@ function handleEnqueue(
}
const { launch } = outcome;
session.note(`mode=${launch.modeName}, mission=${launch.missionName}, mrank=${launch.minMrank}..${launch.maxMrank}`);
const playerVehicles = new Set([
...slotVehicles,
...launch.extraBattleSlots.map((slot) => slot.unitName),
...Object.values(launch.randomUnits).flat(),
]);
const awards = deps.economy.bannerParams(playerVehicles, economyDifficulty(modes[0]!.declaration.difficulty));
setImmediate(() => {
if (!deps.sessions.isPending(userId, launch.sessionId)) return;
deps.sessions.clearPending(userId, launch.sessionId);
deps.notifyLaunch(userId, battleLaunchNotify(launch));
deps.notifyLaunch(userId, battleLaunchNotify(launch, awards));
});
return {};
}
@@ -49,6 +49,11 @@ export function addSkillPoints(crew: BlkBlock, points: number): void {
setParam(crew, BOOKED_POINTS, { type: 'int64', value: BigInt(intOf(crew, BOOKED_POINTS) + points * POINTS_SCALE) });
}
/** Skill points the crew earned in battle (kept apart from bought or spent points, as the client does). */
export function addEarnedSkillPoints(crew: BlkBlock, points: number): void {
setParam(crew, EARNED_POINTS, { type: 'int64', value: BigInt(intOf(crew, EARNED_POINTS) + Math.round(points * POINTS_SCALE)) });
}
export function isTrainedFor(crew: BlkBlock, vehicle: string): boolean {
return (findBlock(crew, VEHICLES)?.params ?? []).some((param) => param.name === TRAINED && param.value.type === 'string' && param.value.value === vehicle);
}
@@ -4,6 +4,7 @@
* 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 { readBattleEconomyTuning, type BattleEconomyTuning } from '../battle/battle-economy-tuning.ts';
import { readBattleTuning, type BattleTuning } from '../battle/battle-tuning.ts';
import { readClanTuning, type ClanTuning } from '../clans/clan-tuning.ts';
import { readMarketplaceTuning, type MarketplaceTuning } from '../inventory/marketplace-tuning.ts';
@@ -28,6 +29,7 @@ export interface Tuning {
readonly trophies: TrophyTuning;
readonly clans: ClanTuning;
readonly battle: BattleTuning;
readonly battleEconomy: BattleEconomyTuning;
readonly limits: LimitsTuning;
}
@@ -44,6 +46,7 @@ export function loadTuning(dataFolder: string, report: (line: string) => void):
trophies: readTrophyTuning(files.read('trophies')),
clans: readClanTuning(files.read('clans')),
battle: readBattleTuning(files.read('battle')),
battleEconomy: readBattleEconomyTuning(files.read('battle-economy')),
limits: readLimitsTuning(files.read('limits')),
};
}
@@ -0,0 +1,57 @@
// Battle rewards the game files do not carry. The reward factors themselves (aKill, rewardMul,
// expMul, class factors, win/defeat bonus, premium multipliers, time RP rates, skill bonus) are
// read from wpcost.blk, warpoints.blk and rank.blk. What the battle server keeps private is the
// mission score of each combat event; the values below are the official published ones where
// they exist, and the offline version's own choice where they do not (marked "offline").
//
// How a combat event is priced (battle/battle-economy.ts):
// Silver Lions = aKill x SL class factor(victim) x rewardMul(own vehicle, difficulty)
// x eventScore / referenceScore(victim group)
// Research Points = eventScore x expMul(own vehicle) x RP class factor(victim)
// both x aiKillK when the victim is not a player.
{
// Destroyed-unit classes (warpoints.blk / rank.blk units{} keys) by victim group; any class not
// listed counts as "ground".
"victimGroups": {
"air": ["exp_bomber", "exp_fighter", "exp_assault", "exp_helicopter", "exp_ufo"],
"naval": [
"exp_torpedo_boat", "exp_gun_boat", "exp_torpedo_gun_boat", "exp_submarine_chaser",
"exp_destroyer", "exp_cruiser", "exp_naval_ferry_barge",
"exp_ship", "exp_ca_ship", "exp_bb_ship", "exp_cv_ship"
],
"human": ["exp_human", "exp_infantry"]
},
// Mission score per combat event, by victim group.
// ground kill 180: official ("Basic mission score for destruction of an enemy ground vehicle
// ... 150 -> 180", server update 2021-11-10, devtrackers.gg/war-thunder/p/2edb7e23).
// air kill 450, air assist 300, air critical 150: official, same update (air simulator values).
// naval kill 30, naval assist 10: official, same update; naval damage is scored separately below.
// ground assist 120, air severe damage 360, naval severe damage 15: original author's values.
// ground critical 30, hits 10, ground severe damage 0: offline (no published value).
"eventScores": {
"ground": { "kill": 180, "assist": 120, "severeDamage": 0, "criticalHit": 30, "hit": 10 },
"air": { "kill": 450, "assist": 300, "severeDamage": 360, "criticalHit": 150, "hit": 10 },
"naval": { "kill": 30, "assist": 10, "severeDamage": 15, "criticalHit": 0, "hit": 0 },
"human": { "kill": 180, "assist": 120, "severeDamage": 0, "criticalHit": 30, "hit": 10 }
},
// Score of a capture by a single player, by the capturing vehicle's group. ground 300: official
// (300 for the first capturer, +200 for each additional one, shared; same 2021 update).
// naval 200: official ("175 -> 200", same update). air and human: offline, as ground. The
// LocalMP host reports captures without the number of capturers, so a capture always scores
// the single-capturer value.
"captureZoneScore": { "ground": 300, "air": 300, "naval": 200, "human": 300 },
// Naval mission score per point of damage dealt: official ("0.15 -> 0.18", same update).
"navalDamageScorePerPoint": 0.18,
// The score at which an event pays exactly one reference kill (warpoints.blk aKill), by victim
// group. ground 180 and air 450 are the official base kill scores; naval 216 is the official
// example of a boat destruction ("now awarded with 216 points instead of 180").
"referenceScore": { "ground": 180, "air": 450, "naval": 216, "human": 180 },
// Destroying a teammate costs the Silver Lions that destroying an enemy of that class would pay,
// times this factor (offline: the penalty rules are not published).
"friendlyKillPenaltyMul": 1.0
}
+3 -6
View File
@@ -1,6 +1,7 @@
// Offline battle session capacity, AI bot pool rules, nation coalitions, and post-battle multipliers.
{
// Global post-battle Silver Lions and Research Points multipliers (1.0 matches stock rates).
// Offline multipliers on every battle reward, Silver Lions and Research Points (1.0 = the rates of
// tuning/battle-economy.jsonc and the game files).
"rewardMultiplierSilverLions": 1.0,
"rewardMultiplierResearchPoints": 1.0,
@@ -33,9 +34,5 @@
// AI bot respawn limits per battle in multi-slot versus modes.
"tankBotRespawns": 3,
"airBotRespawns": 2,
// Team win-inference weights when the player leaves while the battle is still running.
"earlyLeaveTicketWeight": 0.7,
"earlyLeaveKillWeight": 0.3
"airBotRespawns": 2
}