diff --git a/exe-patches/battle/allow-local-host-bot-spawns/locate.json b/exe-patches/battle/allow-local-host-bot-spawns/locate.json deleted file mode 100644 index 54dadc3..0000000 --- a/exe-patches/battle/allow-local-host-bot-spawns/locate.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "method": "signature", - "section": ".text", - - "how": [ - "取 BotSystem::changeUnit 内出生点检查(call 0x111a010)至 g_multiplayer 空指针拦截处共 0x3c 字节的掩码特征(authoring.py 生成)。", - "包含结构体偏移 +0x3e0 与栈槽偏移 [rsp+0x20],rip 相对位移和跳转目标已全部通配。", - "在 2.61.0.37 原版 aces.exe 的 .text 段唯一命中 0x11b2c14,目标修改点位于 +38(0x11b2c3a)。" - ], - - "pattern": "48 8b 05 ?? ?? ?? ?? 48 8b 88 e0 03 00 00 48 8b 5c 24 20 48 89 da 4d 89 f0 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 48 8b 54 24 20" -} diff --git a/exe-patches/battle/allow-local-host-bot-spawns/locate.jsonc b/exe-patches/battle/allow-local-host-bot-spawns/locate.jsonc new file mode 100644 index 0000000..4c8f2ab --- /dev/null +++ b/exe-patches/battle/allow-local-host-bot-spawns/locate.jsonc @@ -0,0 +1,8 @@ +// Masked signature of BotSystem::changeUnit from the spawn point check (call 0x111a010) +// to the g_multiplayer null guard, 0x3c bytes; rip-relative and branch targets are wildcards. +// 2.61.0.37: unique hit at 0x11b2c14, edited instruction at +38 (0x11b2c3a). +{ + "method": "signature", + "section": ".text", + "pattern": "48 8b 05 ?? ?? ?? ?? 48 8b 88 e0 03 00 00 48 8b 5c 24 20 48 89 da 4d 89 f0 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 48 8b 54 24 20" +} diff --git a/exe-patches/battle/allow-local-host-bot-spawns/patch.json b/exe-patches/battle/allow-local-host-bot-spawns/patch.json deleted file mode 100644 index 738e60f..0000000 --- a/exe-patches/battle/allow-local-host-bot-spawns/patch.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "id": "battle/allow-local-host-bot-spawns", - "title": "允许本地多人主机模式下 BotSystem 为双方 AI 槽位刷出载具", - - "program_behaviour": { - "stock": "BotSystem::changeUnit 在选好 AI 载具并找到可用出生点(0x111a010)后,在 0x11b2c3a 检查全局多人对象 [0x7b83cb0] 是否为空:仅单机模式(g_multiplayer == nullptr)跳至 0x11b314e 执行 Unit::changeAircraft;多人模式下因客户端裁掉了服务端脚本校验分支,直接落入错误日志 \"BotSystem::changeUnit spawn denied by scripts\" 并放弃刷车。", - "patched": "将 0x11b2c3a 处的空指针比较与条件跳转改为无条件跳至 0x11b314e,使 LocalMP 本地权威主机通过出生点检查后直接执行 Unit::changeAircraft 为双方 AI 刷出坦克/飞机/舰艇(远程 Peer 模式已在函数入口 0x11b2259 因 isHost == 0 提前返回,不受影响)。" - }, - - "derivation": { - "requirement": "功能清单 L「AI 出车」。玩家排队进入本地多人对局后,双方 AI 必须按 customBots 载具池在各自出生点正常刷出参战。", - "cause": "2.61.0.37 客户端 exe 在编译时移除了专用服务端在 BotSystem::changeUnit 中调用的服务端脚本出生许可钩子,只保留了 g_multiplayer == nullptr 的单机跳转,导致 LocalMP 主机(g_multiplayer != nullptr 且 isHost == 1)每次刷 AI 都报 spawn denied by scripts。", - "lighter_options_ruled_out": [ - "原生配置或任务参数:0x11b2c3a 只判断 [0x7b83cb0] 是否为 0,不读任何 MissionSettings 或 DataBlock 开关。", - "本地服务或界面脚本:该判断位于客户端物理主机每帧原生 BotSystem::update 内部,不发网络请求也不调客户端 Quirrel 脚本。" - ], - "conclusion": "只能改 exe,在出生点检查通过后跳入原有的 0x11b314e 刷车构造分支。", - "if_not_applied": "进入 LocalMP 对局后双方 AI 槽位虽然加入房间,但因每次 changeUnit 都被拦截,战局内一辆 AI 载具都不会刷出。" - }, - - "why_this_site": [ - "0x11b2c32 刚完成出生点可用性检查(test al, al; je 0x11b2d15),紧接着的 14 字节(0x11b2c3a-0x11b2c48)就是唯一的 g_multiplayer == 0 拦截。", - "函数开头 0x11b224d-0x11b225d 已经拦住了所有非主机多人会话(isHost == 0 直接返回 0),所以能走到 0x11b2c3a 的多人会话一定是本地主机。", - "原地用 5 字节近跳转加 9 字节 nop 覆盖 14 字节原指令,不改栈帧大小,不引入新调用,异常展开信息保持不变。" - ], - - "features": ["L-AI出车"], - "requires": [], - "evidence": [ - "2.61.0.37 原版 aces.exe:BotSystem::changeUnit 0x11b2200,主机检查 0x11b224d-0x11b225d,出生点选择 0x11b2c2d(call 0x111a010),拦截点 0x11b2c3a-0x11b2c48,错误日志 0x11b2cfe,刷车构造入口 0x11b314e -> 0xff1020(Unit::changeAircraft)。", - "2.61.0.37 实测战斗日志:未打补丁时连续输出 \"BotSystem::changeUnit spawn denied by scripts for fm ... unit ...\"。" - ], - "verified_on": ["2.61.0.37"], - - "edit": { - "offset": 38, - "asm": [ - "jmp 0x514", - "nop", - "nop", - "nop", - "nop", - "nop", - "nop", - "nop", - "nop", - "nop" - ], - "bytes": "e90f050000909090909090909090", - "expect_original": "48833d6e109d06000f8406050000" - } -} diff --git a/exe-patches/battle/allow-local-host-bot-spawns/patch.jsonc b/exe-patches/battle/allow-local-host-bot-spawns/patch.jsonc new file mode 100644 index 0000000..acc90c6 --- /dev/null +++ b/exe-patches/battle/allow-local-host-bot-spawns/patch.jsonc @@ -0,0 +1,29 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/allow-local-host-bot-spawns", + "title": "允许本地多人主机模式下 BotSystem 为双方 AI 槽位刷出载具", + "features": [ + "L-AI出车" + ], + "requires": [], + "verified_on": [ + "2.61.0.37" + ], + "edit": { + "offset": 38, + "asm": [ + "jmp 0x514", + "nop", + "nop", + "nop", + "nop", + "nop", + "nop", + "nop", + "nop", + "nop" + ], + "bytes": "e90f050000909090909090909090", + "expect_original": "48833d6e109d06000f8406050000" + } +} diff --git a/exe-patches/battle/allow-local-host-player-respawn/locate.json b/exe-patches/battle/allow-local-host-player-respawn/locate.json deleted file mode 100644 index 27a42ab..0000000 --- a/exe-patches/battle/allow-local-host-player-respawn/locate.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "method": "signature", - "section": ".text", - - "how": [ - "取 Unit::onEvent(0x103fbc0)中 0xf02f(UnitRespawnRequest)分支自人类玩家判定(call 0xfd34a0)至出生逻辑入口前(xor edx, edx)共 0x68 字节的掩码特征(authoring.py 生成)。", - "包含 MPlayer 指针偏移 [r13+0xf98]、出生目标偏移 [rdx+0xbf8]/[rdx+0xbf4] 与 GUI_STATE_CA_SELECT 常量 6,rip 相对位移与相对调用/跳转目标均已通配。", - "在 2.61.0.37 原版 aces.exe 的 .text 段唯一命中 0x1044e9b,目标修改点位于 +49(0x1044ecc)。" - ], - - "pattern": "48 89 d9 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 8b 05 ?? ?? ?? ?? 83 c0 fd 49 8b 95 98 0f 00 00 83 f8 02 72 ?? 0f b6 4a 08 83 ba f8 0b 00 00 00 79 ?? 83 ba f4 0b 00 00 00 0f 88 ?? ?? ?? ?? ba 06 00 00 00 e8 ?? ?? ?? ?? 4c 89 e9 b2 01 e8 ?? ?? ?? ?? e9 ?? ?? ?? ?? 31 d2" -} diff --git a/exe-patches/battle/allow-local-host-player-respawn/locate.jsonc b/exe-patches/battle/allow-local-host-player-respawn/locate.jsonc new file mode 100644 index 0000000..81331a3 --- /dev/null +++ b/exe-patches/battle/allow-local-host-player-respawn/locate.jsonc @@ -0,0 +1,8 @@ +// Masked signature of the 0xf02f (UnitRespawnRequest) branch of Unit::onEvent (0x103fbc0), from the +// human player check (call 0xfd34a0) to the spawn logic entry, 0x68 bytes; relative targets are wildcards. +// 2.61.0.37: unique hit at 0x1044e9b, edited instruction at +49 (0x1044ecc). +{ + "method": "signature", + "section": ".text", + "pattern": "48 89 d9 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 8b 05 ?? ?? ?? ?? 83 c0 fd 49 8b 95 98 0f 00 00 83 f8 02 72 ?? 0f b6 4a 08 83 ba f8 0b 00 00 00 79 ?? 83 ba f4 0b 00 00 00 0f 88 ?? ?? ?? ?? ba 06 00 00 00 e8 ?? ?? ?? ?? 4c 89 e9 b2 01 e8 ?? ?? ?? ?? e9 ?? ?? ?? ?? 31 d2" +} diff --git a/exe-patches/battle/allow-local-host-player-respawn/patch.json b/exe-patches/battle/allow-local-host-player-respawn/patch.json deleted file mode 100644 index 3f2900c..0000000 --- a/exe-patches/battle/allow-local-host-player-respawn/patch.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "id": "battle/allow-local-host-player-respawn", - "title": "允许本地多人主机模式下人类玩家在对战模式(GM_DOMINATION 等)中正常刷出载具参战", - - "program_behaviour": { - "stock": "Unit::onEvent(0x103fbc0)收到 0xf02f(UnitRespawnRequest)时,在 0x1044e9b-0x1044ecc 判断若为人类玩家载具且 g_multiplayer 非空,则仅允许 g_game_mode(0x7bb5060)为 3(GM_SINGLE_MISSION)或 4(GM_DYNAMIC)时跳至 0x1044f03 执行完整的出生位计算与 0xf030(UnitRespawn)派发;客户端二进制因编译期移除了专用对战服授权分支,在其它多人模式(如随机匹配的 GM_DOMINATION = 2)下无论出生点校验是否通过都会汇入 0x1044ee8,调用 setPlayerGuiState(playerId, GUI_STATE_CA_SELECT = 6) 并将载具重新置为延迟隐藏,导致玩家点击「加入战斗!」倒计时结束后无报错直接退回选车界面。", - "patched": "将 0x1044ecc 处的 2 字节条件短跳转(jb 0x1044f03)改为无条件短跳转(jmp 0x1044f03),使本地权威主机(isHost == 1;远程客户端的 0xf02f 发往远端服务端,不会在本地触发此分支)在所有对战模式下都能进入 0x1044f03 原生出生流程,按 MPlayer 记录的出生点 ID 刷出玩家载具并切入操控视角。" - }, - - "derivation": { - "requirement": "功能清单 K「战局任务加载与玩家出击」。玩家在重生界面选择乘员组载具与出生点并点击「加入战斗!」后,必须在所选出生点正常刷出载具进入战斗。", - "cause": "2.61.0.37 客户端 aces.exe 在 Unit::onEvent 的 0xf02f 分支中保留了完整的 0x1044f03 -> 0xfec9c0 -> 0xf030 人类玩家出生实现(供单机与联机合作单人任务/动态战役主机使用),但用 #ifdef DEDICATED_SERVER 裁掉了多人对战模式(GM_DOMINATION 等)放行路径,令 0x1044ed2 与 0x1046b61 所有分支最终均落入 0x1044ee8 退回 GUI_STATE_CA_SELECT(状态 6)。", - "lighter_options_ruled_out": [ - "原生配置或任务参数:0x1044eb9 硬编码判断全局 g_game_mode 枚举是否属于 {3, 4},把对局改成 GM_SINGLE_MISSION 会破坏占点统治规则、重生点机制与计分板。", - "本地服务或界面脚本:0xf02f 由 AcesApp::tryRespawn 在本地进程内通过 MPI 回环投递至 Unit::onEvent,纯属 C++ 战局权威状态机,不经过网络服务或 Quirrel 脚本。" - ], - "conclusion": "在 0x1044ecc 处将 1 字节条件跳转操作码 0x72(jb)改为 0xeb(jmp),复用紧随其后的完整 0x1044f03 人类玩家出生流程(rdx 已在 0x1044ec2 加载为 MPlayer*)。", - "if_not_applied": "玩家在 LocalMP 对局重生界面选车点击「加入战斗!」并等完倒计时后,每次都会被静默重置回 GUI_STATE_CA_SELECT,按钮恢复为「加入战斗!」,永远无法刷出载具参战。" - }, - - "why_this_site": [ - "0x1044dfa-0x1044e8a 已在前方完成了 GUI_STATE_CA_READY(8)与开局倒计时检查,0x1044ec2 也已将 MPlayer* 装入 rdx(0x1044f03 入口所需寄存器状态已就绪)。", - "远程联机客户端在 AcesApp::tryRespawn(0xc6c3da)中将 0xf02f 发往远端主机而非本地执行,只有本地作为权威主机时才会走到 0x1044ecc。", - "仅修改 1 个字节(72 35 -> eb 35),指令长度完全不变(2 字节),不改任何寄存器、栈帧或异常展开表。" - ], - - "features": ["K-战局任务加载"], - "requires": [], - "evidence": [ - "2.61.0.37 原版 aces.exe:AcesApp::tryRespawn 0xc6c279-0xc6c4af(投递 0xf02f),Unit::onEvent 0x103fbc0 中 0xf02f 入口 0x1042cff,模式拦截 0x1044eb9-0x1044efc,区域校验汇合点 0x1046b61-0x1046c33,完整人类出生路径 0x1044f03-0x104502c -> 0x1045c4c -> 0x1046a24(0xfec9c0 派发 0xf030)。", - "2.61.0.37 实测战斗日志(2026_11_27_07_21_47__51360.clog 154.23s):输出 \"unit respawn request received uid:44 name:tankModels/ussr_t_72b3_arena\" 后紧接着输出 \"[GUISTATE] set GUI_STATE_CA_SELECT to player 0\",未输出 \"sending unit respawn\"。" - ], - "verified_on": ["2.61.0.37"], - - "edit": { - "offset": 49, - "asm": [ - "jmp 0x37" - ], - "bytes": "eb35", - "expect_original": "7235" - } -} diff --git a/exe-patches/battle/allow-local-host-player-respawn/patch.jsonc b/exe-patches/battle/allow-local-host-player-respawn/patch.jsonc new file mode 100644 index 0000000..15169a4 --- /dev/null +++ b/exe-patches/battle/allow-local-host-player-respawn/patch.jsonc @@ -0,0 +1,20 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/allow-local-host-player-respawn", + "title": "允许本地多人主机模式下人类玩家在对战模式(GM_DOMINATION 等)中正常刷出载具参战", + "features": [ + "K-战局任务加载" + ], + "requires": [], + "verified_on": [ + "2.61.0.37" + ], + "edit": { + "offset": 49, + "asm": [ + "jmp 0x37" + ], + "bytes": "eb35", + "expect_original": "7235" + } +} diff --git a/exe-patches/isolation/never-load-battleye/locate.json b/exe-patches/isolation/never-load-battleye/locate.jsonc similarity index 54% rename from exe-patches/isolation/never-load-battleye/locate.json rename to exe-patches/isolation/never-load-battleye/locate.jsonc index 1983191..5105d9c 100644 --- a/exe-patches/isolation/never-load-battleye/locate.json +++ b/exe-patches/isolation/never-load-battleye/locate.jsonc @@ -1,11 +1,8 @@ +// Anti-cheat init, from the already-initialised check to the end of the "Disabled from CMD" branch, 109 bytes; +// rip-relative and branch targets are wildcards. +// 2.61.0.37: unique hit at 0x30c7112, edited je at +0x4a (0x30c715c). { "method": "signature", "section": ".text", - - "how": [ - "反作弊初始化函数里,从\"是否已经初始化\"的检查到\"Disabled from CMD\"分支结束,共 109 字节。rip 相对地址和相对跳转目标已通配(authoring.py 生成)。", - "在 2.61.0.37 原版 aces.exe 上唯一命中 0x30c7112;要改的 je 在 +0x4a(0x30c715c)。" - ], - "pattern": "48 83 3d ?? ?? ?? ?? 00 74 ?? 48 8d 15 ?? ?? ?? ?? 31 db b9 03 00 00 00 45 31 c0 45 31 c9 e8 ?? ?? ?? ?? e9 ?? ?? ?? ?? 49 89 ce c7 44 24 50 01 00 00 00 48 8d 0d ?? ?? ?? ?? 48 8d 54 24 50 45 31 c0 e8 ?? ?? ?? ?? 48 85 c0 74 ?? 48 8d 15 ?? ?? ?? ?? b9 03 00 00 00 45 31 c0 45 31 c9 e8 ?? ?? ?? ?? bb 01 00 00 00 e9 ?? ?? ?? ??" } diff --git a/exe-patches/isolation/never-load-battleye/patch.json b/exe-patches/isolation/never-load-battleye/patch.json deleted file mode 100644 index 1c091cd..0000000 --- a/exe-patches/isolation/never-load-battleye/patch.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "id": "isolation/never-load-battleye", - "title": "反作弊 BattlEye 永远不加载,和带上原版启动参数 -nobeac 的效果相同", - - "program_behaviour": { - "stock": "反作弊初始化时,程序先检查命令行里有没有 -nobeac。没有的话就加载 win64\\BEClient_x64.dll 并初始化,反作弊随后尝试连接 BattlEye 主服务器(端口 20010)。", - "patched": "这一处检查永远走\"命令行带了 -nobeac\"的分支:记录 \"[BEAC] Disabled from CMD\",不加载反作弊 DLL,初始化照常返回成功。" - }, - - "derivation": { - "requirement": "开发纪律第 18 条、功能清单 A「与正版隔离」「不连 Gaijin」。反作弊在改过的程序里运行,一旦有一次上报成功,就可能牵连玩家的机器和账号。离线版里它没有任何用处。", - "cause": "反作弊在启动时默认加载。实验副本的游戏日志:[BEAC] Loading DLL …BEClient_x64.dll / Initialized (v1.250),并反复尝试重连主服务器。", - "lighter_options_ruled_out": [ - "原生自带:-nobeac 启动参数正是这个开关,启动器会带上它;但玩家绕过启动器、直接运行 exe 时就没有了。这个补丁保证任何启动方式下都不加载。", - "删除 BEClient_x64.dll:程序会走加载失败的分支,行为没有核对过;不如走原版自带的\"关闭\"分支。", - "本地服务:不适用,反作弊连接的是 BattlEye 的服务器。" - ], - "conclusion": "启动参数 + 这个补丁,两层保证。", - "if_not_applied": "玩家不经启动器直接运行时,反作弊会加载,并尝试向 BattlEye 上报。" - }, - - "why_this_site": [ - "检查本身是 call(查找命令行参数)、test rax,rax、je(没找到就去加载)。把 je 换成两个 nop,就等于\"找到了 -nobeac\",走的是原版自己的关闭分支,后续流程全部是原版代码。", - "只改 2 个字节,不新增代码。" - ], - - "features": ["A-与正版隔离", "A-不连 Gaijin"], - "requires": [], - "evidence": [ - "2.61.0.37 原版 aces.exe:反作弊初始化函数 0x30c7100。0x30c7145 取 \"nobeac\",0x30c7154 调用命令行查找,0x30c715c 的 je 跳过 0x30c715e 的 \"[BEAC] Disabled from CMD\" 分支(该分支设返回值为 1 后退出)。", - "尚未在游戏里验证,由隔离观察确认(日志应出现 \"[BEAC] Disabled from CMD\",不出现 \"Loading DLL\")。" - ], - "verified_on": [], - - "edit": { - "offset": 74, - "asm": ["nop", "nop"], - "bytes": "9090", - "expect_original": "7421" - } -} diff --git a/exe-patches/isolation/never-load-battleye/patch.jsonc b/exe-patches/isolation/never-load-battleye/patch.jsonc new file mode 100644 index 0000000..00ef66d --- /dev/null +++ b/exe-patches/isolation/never-load-battleye/patch.jsonc @@ -0,0 +1,24 @@ +// Always take the "-nobeac on the command line" branch, so BattlEye is never loaded. +// Why the executable: the anti-cheat loader runs before any network request; no service can answer it. +// Without it: launching aces.exe directly loads BattlEye and it tries to report to its servers. +{ + "id": "isolation/never-load-battleye", + "title": "反作弊 BattlEye 永远不加载,和带上原版启动参数 -nobeac 的效果相同", + "features": [ + "A-与正版隔离", + "A-不连 Gaijin" + ], + "requires": [], + "verified_on": [ + "2.61.0.37" + ], + "edit": { + "offset": 74, + "asm": [ + "nop", + "nop" + ], + "bytes": "9090", + "expect_original": "7421" + } +} diff --git a/exe-patches/isolation/never-upload-crash-reports/locate.json b/exe-patches/isolation/never-upload-crash-reports/locate.json deleted file mode 100644 index fe572a6..0000000 --- a/exe-patches/isolation/never-upload-crash-reports/locate.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "method": "signature", - "section": ".text", - - "how": [ - "取命令行开关、查找、根据结果设置 dl、调用 crashpad 设置函数的这一段,共 45 字节。rip 相对地址和相对调用目标已通配(authoring.py 生成)。", - "在 2.61.0.37 原版 aces.exe 上唯一命中 0x40f5930;要改的 sete dl 在 +0x1a(0x40f594a)。" - ], - - "pattern": "48 8d 0d ?? ?? ?? ?? 48 8d 94 24 f0 00 00 00 45 31 c0 e8 ?? ?? ?? ?? 48 85 c0 0f 94 c2 48 89 d9 e8 ?? ?? ?? ?? 48 89 f9 ba 01 00 00 00" -} diff --git a/exe-patches/isolation/never-upload-crash-reports/locate.jsonc b/exe-patches/isolation/never-upload-crash-reports/locate.jsonc new file mode 100644 index 0000000..e0a1ce2 --- /dev/null +++ b/exe-patches/isolation/never-upload-crash-reports/locate.jsonc @@ -0,0 +1,7 @@ +// Command line switch lookup that sets dl and calls the crashpad setter, 45 bytes; call targets are wildcards. +// 2.61.0.37: unique hit at 0x40f5930, edited sete dl at +0x1a (0x40f594a). +{ + "method": "signature", + "section": ".text", + "pattern": "48 8d 0d ?? ?? ?? ?? 48 8d 94 24 f0 00 00 00 45 31 c0 e8 ?? ?? ?? ?? 48 85 c0 0f 94 c2 48 89 d9 e8 ?? ?? ?? ?? 48 89 f9 ba 01 00 00 00" +} diff --git a/exe-patches/isolation/never-upload-crash-reports/patch.json b/exe-patches/isolation/never-upload-crash-reports/patch.json deleted file mode 100644 index 33a5c56..0000000 --- a/exe-patches/isolation/never-upload-crash-reports/patch.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "id": "isolation/never-upload-crash-reports", - "title": "崩溃报告永远不上传,和带上原版启动参数 -crashpad-disable-upload 的效果相同", - - "program_behaviour": { - "stock": "程序启动崩溃报告组件 crashpad 时检查命令行有没有 -crashpad-disable-upload。没有就允许上传:游戏崩溃时,崩溃转储会被发往 Gaijin。", - "patched": "这一处永远按\"带了 -crashpad-disable-upload\"处理:崩溃转储只留在本机,不上传。" - }, - - "derivation": { - "requirement": "开发纪律第 18 条、功能清单 A「不连 Gaijin」。崩溃转储包含进程内存,来自改过的程序,不能发给 Gaijin。", - "cause": "上传默认开启(实验副本日志:crashpad enabled)。", - "lighter_options_ruled_out": [ - "原生自带:-crashpad-disable-upload 启动参数正是这个开关,启动器会带上它;但玩家直接运行 exe 时就没有了。这个补丁保证任何启动方式下都不上传。", - "本地服务:上传地址不在 network.blk 里,没法统一改到本机。" - ], - "conclusion": "启动参数 + 这个补丁,两层保证。", - "if_not_applied": "玩家不经启动器直接运行且游戏崩溃时,崩溃转储会上传给 Gaijin。" - }, - - "why_this_site": [ - "检查是 call(查找命令行参数)、test rax,rax、sete dl:dl 就是\"允许上传\",作为参数传给 crashpad 的设置函数。把 sete dl 换成 xor dl,dl(再补一个 nop),参数恒为\"不允许\",等同于命令行带了这个开关。", - "只改 3 个字节,不新增代码。" - ], - - "features": ["A-不连 Gaijin"], - "requires": [], - "evidence": [ - "2.61.0.37 原版 aces.exe:0x40f5930 取 \"crashpad-disable-upload\",0x40f5942 调用命令行查找,0x40f594a 的 sete dl 把\"没找到\"变成\"允许上传\",0x40f5950 把它传给设置函数。", - "尚未在游戏里验证,由隔离观察确认(不应出现发往崩溃上报地址的连接)。" - ], - "verified_on": [], - - "edit": { - "offset": 26, - "asm": ["xor dl, dl", "nop"], - "bytes": "30d290", - "expect_original": "0f94c2" - } -} diff --git a/exe-patches/isolation/never-upload-crash-reports/patch.jsonc b/exe-patches/isolation/never-upload-crash-reports/patch.jsonc new file mode 100644 index 0000000..b6a5b85 --- /dev/null +++ b/exe-patches/isolation/never-upload-crash-reports/patch.jsonc @@ -0,0 +1,23 @@ +// Always behave as if -crashpad-disable-upload was given: crash dumps stay on the machine. +// Why the executable: the upload switch is read from the command line only. +// Without it: a crash of a directly launched game uploads its dump to Gaijin. +{ + "id": "isolation/never-upload-crash-reports", + "title": "崩溃报告永远不上传,和带上原版启动参数 -crashpad-disable-upload 的效果相同", + "features": [ + "A-不连 Gaijin" + ], + "requires": [], + "verified_on": [ + "2.61.0.37" + ], + "edit": { + "offset": 26, + "asm": [ + "xor dl, dl", + "nop" + ], + "bytes": "30d290", + "expect_original": "0f94c2" + } +} diff --git a/exe-patches/isolation/registry-key/locate.json b/exe-patches/isolation/registry-key/locate.jsonc similarity index 53% rename from exe-patches/isolation/registry-key/locate.json rename to exe-patches/isolation/registry-key/locate.jsonc index 2eda4b3..9289ee9 100644 --- a/exe-patches/isolation/registry-key/locate.json +++ b/exe-patches/isolation/registry-key/locate.jsonc @@ -1,11 +1,7 @@ +// The wide string L"Software\Gaijin\WarThunder" with its terminating zero, 54 bytes. +// 2.61.0.37: unique hit at 0x7a39c4e. { "method": "signature", "section": ".rdata", - - "how": [ - "常量区里完整的宽字符串 L\"Software\\\\Gaijin\\\\WarThunder\",包括结尾的 0,共 54 字节。", - "在 2.61.0.37 原版 aces.exe 上唯一命中 0x7a39c4e。" - ], - "pattern": "53 00 6f 00 66 00 74 00 77 00 61 00 72 00 65 00 5c 00 47 00 61 00 69 00 6a 00 69 00 6e 00 5c 00 57 00 61 00 72 00 54 00 68 00 75 00 6e 00 64 00 65 00 72 00 00 00" } diff --git a/exe-patches/isolation/registry-key/patch.json b/exe-patches/isolation/registry-key/patch.json deleted file mode 100644 index c1b0dbf..0000000 --- a/exe-patches/isolation/registry-key/patch.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "id": "isolation/registry-key", - "title": "把注册表位置从 Software\\Gaijin\\WarThunder 改成 Software\\WTOffline,不碰正版保存的登录信息", - - "program_behaviour": { - "stock": "程序把\"记住的账号、密码、登录凭证\"等保存在注册表 HKEY_CURRENT_USER\\Software\\Gaijin\\WarThunder(IntAuthLogin、IntAuthPass、IntAuthShortToken、IntAuthSaveBitset)。Steam 正版用的是同一个位置。", - "patched": "改用 HKEY_CURRENT_USER\\Software\\WTOffline。离线版读不到正版保存的登录信息,登录时也不会覆盖它。" - }, - - "derivation": { - "requirement": "开发纪律第 18 条、功能清单 A「与正版隔离」。实测中,未打这个补丁的副本在登录时写入了这个注册表位置(最后写入时间与登录时间一致)。", - "cause": "注册表路径是程序里的常量(游戏身份表 0x7a9a7c8 的第二个字段)。", - "lighter_options_ruled_out": [ - "原生自带:没有改这个路径的配置项或启动参数。", - "本地服务:不适用,这是客户端在本机读写注册表。" - ], - "conclusion": "只能改 exe。改的是数据(一个字符串),不改代码。", - "if_not_applied": "离线版的登录窗口会读到正版保存的账号和凭证;在离线版登录会覆盖正版保存的登录信息。" - }, - - "why_this_site": [ - "这个字符串只被身份表的注册表字段引用。", - "新路径比原来短,原地替换,剩余位置补 0。" - ], - - "features": ["A-与正版隔离"], - "requires": [], - "evidence": [ - "2.61.0.37 原版 aces.exe:身份表 0x7a9a7c8 第二个字段指向 0x7a39c4e 的宽字符串 L\"Software\\\\Gaijin\\\\WarThunder\"。", - "用户机器上 HKCU\\Software\\Gaijin\\WarThunder 含 IntAuthLogin / IntAuthPass / IntAuthShortToken / IntAuthSaveBitset,最后写入时间是实验副本登录的时刻。", - "尚未在游戏里验证,由隔离观察确认。" - ], - "verified_on": [], - - "edit": { - "offset": 0, - "data": { "encoding": "utf-16-le", "text": "Software\\WTOffline" }, - "bytes": "53006f006600740077006100720065005c00570054004f00660066006c0069006e006500000000000000000000000000000000000000", - "expect_original": "53006f006600740077006100720065005c004700610069006a0069006e005c005700610072005400680075006e006400650072000000" - } -} diff --git a/exe-patches/isolation/registry-key/patch.jsonc b/exe-patches/isolation/registry-key/patch.jsonc new file mode 100644 index 0000000..0030d71 --- /dev/null +++ b/exe-patches/isolation/registry-key/patch.jsonc @@ -0,0 +1,23 @@ +// Use HKCU\Software\WTOffline instead of Software\Gaijin\WarThunder. +// Why the executable: the registry path is a constant in the game identity table. +// Without it: the offline login reads and overwrites the retail client's saved credentials. +{ + "id": "isolation/registry-key", + "title": "把注册表位置从 Software\\Gaijin\\WarThunder 改成 Software\\WTOffline,不碰正版保存的登录信息", + "features": [ + "A-与正版隔离" + ], + "requires": [], + "verified_on": [ + "2.61.0.37" + ], + "edit": { + "offset": 0, + "data": { + "encoding": "utf-16-le", + "text": "Software\\WTOffline" + }, + "bytes": "53006f006600740077006100720065005c00570054004f00660066006c0069006e006500000000000000000000000000000000000000", + "expect_original": "53006f006600740077006100720065005c004700610069006a0069006e005c005700610072005400680075006e006400650072000000" + } +} diff --git a/exe-patches/isolation/user-data-folder-name/locate.json b/exe-patches/isolation/user-data-folder-name/locate.json deleted file mode 100644 index d7a6642..0000000 --- a/exe-patches/isolation/user-data-folder-name/locate.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "method": "signature", - "section": ".rdata", - - "how": [ - "常量区里的 \"WarThunder\" 字符串,连同前一个字节(上一个字符串的结尾 0)和后面紧跟的 \"War Thunder\",共 24 字节,用来确保命中的是身份表引用的那一处。", - "在 2.61.0.37 原版 aces.exe 上唯一命中 0x777eb96,字符串本身在 0x777eb97。" - ], - - "pattern": "00 57 61 72 54 68 75 6e 64 65 72 00 57 61 72 20 54 68 75 6e 64 65 72 00" -} diff --git a/exe-patches/isolation/user-data-folder-name/locate.jsonc b/exe-patches/isolation/user-data-folder-name/locate.jsonc new file mode 100644 index 0000000..1f258bf --- /dev/null +++ b/exe-patches/isolation/user-data-folder-name/locate.jsonc @@ -0,0 +1,8 @@ +// "WarThunder" with the preceding string terminator and the following "War Thunder", 24 bytes, +// so the hit is the copy referenced by the game identity table. +// 2.61.0.37: unique hit at 0x777eb96, string at 0x777eb97. +{ + "method": "signature", + "section": ".rdata", + "pattern": "00 57 61 72 54 68 75 6e 64 65 72 00 57 61 72 20 54 68 75 6e 64 65 72 00" +} diff --git a/exe-patches/isolation/user-data-folder-name/patch.json b/exe-patches/isolation/user-data-folder-name/patch.json deleted file mode 100644 index 6b86cca..0000000 --- a/exe-patches/isolation/user-data-folder-name/patch.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "id": "isolation/user-data-folder-name", - "title": "把游戏名从 WarThunder 改成 WTOffline,让离线版的用户数据目录和正版分开", - - "program_behaviour": { - "stock": "程序的游戏身份表里,游戏名是 \"WarThunder\"。引擎的文件夹模块用它拼出用户数据目录:我的文档\\My Games\\WarThunder(设置、上次登录的账号、机器识别码),以及 AppData\\Local\\WarThunder;日志路径、内置浏览器缓存、\"同一时间只能运行一个游戏\" 的检查也用它。这些位置和 Steam 正版完全相同。", - "patched": "游戏名变成 \"WTOffline\"。上面这些位置全部变成离线版自己的:我的文档\\My Games\\WTOffline 等,正版的数据既不会被读到,也不会被改写。" - }, - - "derivation": { - "requirement": "开发纪律第 18 条、功能清单 A「与正版隔离」:离线版不得读写正版的任何数据。实测中,未打这个补丁的副本在退出时改写了正版账号的 global.blk、machine.blk,并把\"上次登录的账号\"改成了测试账号。", - "cause": "目录由引擎按游戏名拼出(DagorEngine prog/gameLibs/folders/platform/windows.cpp,get_gamedata_dir:我的文档 + \"My Games\" + 游戏名),游戏名是程序里的常量。", - "lighter_options_ruled_out": [ - "原生自带:文件夹模块没有改默认目录的配置项(folders.cpp:load_custom_folders 只能新增具名位置,不能覆盖 gamedatadir)。", - "本地服务:不适用。这是客户端在本机读写文件,不经过网络。", - "换 Windows 用户运行:只适合开发期的观察,不能要求玩家这样做。" - ], - "conclusion": "只能改 exe。改的是数据(一个字符串),不改代码。", - "if_not_applied": "离线版会读写正版的设置目录:退出时改写正版账号的设置,登录时改写\"上次登录的账号\"。" - }, - - "why_this_site": [ - "游戏身份表(0x7a9a7c8)的游戏名字段和第三个字段都指向这同一个字符串,程序里其他地方不直接引用它。改这一个字符串,所有由游戏名派生的位置一起改变。", - "用到游戏名的 13 处都已核对:反作弊初始化、浏览器缓存路径、日志路径、单实例检查、脚本里的 app 名、语音客户端名、Steam 初始化。没有一处影响玩法;原版界面脚本不按游戏名分支。", - "新名字比原来短,原地替换即可,不需要新增数据。" - ], - - "features": ["A-与正版隔离"], - "requires": [], - "evidence": [ - "2.61.0.37 原版 aces.exe:身份表 0x7a9a7c8 = { \"WarThunder\", L\"Software\\\\Gaijin\\\\WarThunder\", \"WarThunder\", \"wt\", …, \"production\", \"aces.vromfs.bin\" }。", - "Original client logs show that the default save directory is shared with the retail installation.", - "尚未在游戏里验证改名后的效果,由隔离观察(local development tool)确认。" - ], - "verified_on": [], - - "edit": { - "offset": 1, - "data": { "encoding": "ascii", "text": "WTOffline" }, - "bytes": "57544f66666c696e6500", - "expect_original": "5761725468756e646572" - } -} diff --git a/exe-patches/isolation/user-data-folder-name/patch.jsonc b/exe-patches/isolation/user-data-folder-name/patch.jsonc new file mode 100644 index 0000000..590dfa4 --- /dev/null +++ b/exe-patches/isolation/user-data-folder-name/patch.jsonc @@ -0,0 +1,23 @@ +// Rename the game from WarThunder to WTOffline, which moves every per-user data folder. +// Why the executable: the engine derives Documents/AppData folders from this constant name. +// Without it: the offline client reads and rewrites the retail client's settings. +{ + "id": "isolation/user-data-folder-name", + "title": "把游戏名从 WarThunder 改成 WTOffline,让离线版的用户数据目录和正版分开", + "features": [ + "A-与正版隔离" + ], + "requires": [], + "verified_on": [ + "2.61.0.37" + ], + "edit": { + "offset": 1, + "data": { + "encoding": "ascii", + "text": "WTOffline" + }, + "bytes": "57544f66666c696e6500", + "expect_original": "5761725468756e646572" + } +} diff --git a/exe-patches/online/accept-local-tls-certificate/locate.json b/exe-patches/online/accept-local-tls-certificate/locate.jsonc similarity index 67% rename from exe-patches/online/accept-local-tls-certificate/locate.json rename to exe-patches/online/accept-local-tls-certificate/locate.jsonc index 6b51017..1bfe73d 100644 --- a/exe-patches/online/accept-local-tls-certificate/locate.json +++ b/exe-patches/online/accept-local-tls-certificate/locate.jsonc @@ -1,11 +1,7 @@ +// libcurl Curl_clone_primary_ssl_config from entry to the cert_blob null check, 176 bytes; branch targets are wildcards. +// 2.61.0.37: unique hit at 0x56463c0, edited instruction at +0x52 (0x5646412). { "method": "signature", "section": ".text", - - "how": [ - "libcurl 的 Curl_clone_primary_ssl_config(从入口到读取 cert_blob 判空跳转,共 176 字节)。跳转位移已通配(authoring.py 生成)。", - "在 2.61.0.37 原版 aces.exe 上唯一命中 0x56463c0;要改的指令在 +0x52(0x5646412)。" - ], - "pattern": "56 57 53 48 83 ec 20 48 89 d6 48 89 cf 8b 82 98 00 00 00 83 c8 20 89 82 98 00 00 00 0f b6 89 95 00 00 00 88 8a 95 00 00 00 8b 8f 90 00 00 00 89 8a 90 00 00 00 8b 8f 98 00 00 00 83 e1 01 83 e0 fe 09 c8 89 82 98 00 00 00 8b 8f 98 00 00 00 83 e1 02 83 e0 fd 09 c8 89 82 98 00 00 00 8b 8f 98 00 00 00 83 e1 04 83 e0 fb 09 c8 89 82 98 00 00 00 8b 8f 98 00 00 00 83 e1 08 83 e0 f7 09 c8 89 82 98 00 00 00 8b 8f 98 00 00 00 83 e1 10 83 e0 ef 09 c8 89 82 98 00 00 00 0f b6 87 94 00 00 00 88 82 94 00 00 00 48 8b 5f 68 48 85 db 74 ??" } diff --git a/exe-patches/online/accept-local-tls-certificate/patch.json b/exe-patches/online/accept-local-tls-certificate/patch.json deleted file mode 100644 index a737da8..0000000 --- a/exe-patches/online/accept-local-tls-certificate/patch.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "id": "online/accept-local-tls-certificate", - "title": "让客户端的 HTTPS 连接接受本地服务的自签证书", - - "program_behaviour": { - "stock": "libcurl 建立新连接时用 Curl_clone_primary_ssl_config 把请求侧的 SSL 配置复制到连接侧(+0x98 的第 0 位 verifypeer、第 1 位 verifyhost 默认都是 1)。对于没有读取 enableSslCertCheck 开关的 HTTPS 请求(如脚本的 dagor.http、yuplay2 的购买与兑换码、事件上报),连接被 wto_ws.dll 改道到本地服务后,因本地服务使用自签证书而报 CURLE_PEER_FAILED_VERIFICATION(60)断开。", - "patched": "复制 SSL 配置到连接侧时,把 verifypeer 和 verifyhost 两位一并清零,所有经 wto_ws.dll 改道到本地服务的 HTTPS 连接都直接接受本地服务的自签证书。" - }, - - "derivation": { - "requirement": "HTTPS requests routed to the local service must complete their TLS handshake for purchases, product information, and code redemption.", - "cause": "network.blk 的 enableSslCertCheck 只被 0x155c950 的 4 个调用点读取;dagor.http(httpRequest)等请求不读它,保留了 libcurl 默认的证书链和主机名校验。实测日志:newsfeed.gap.gaijin.net 握手后报 SSL peer certificate or SSH remote key was not OK。", - "lighter_options_ruled_out": [ - "network.blk 的 enableSslCertCheck:已设为 false,但 dagor.http 等路径根本不读取这个配置。", - "把本地服务的根证书装进 Windows 系统受信任根证书库:会改动玩家操作系统的全局信任链,影响正版和其他软件,违反隔离原则。" - ], - "conclusion": "在 libcurl 复制连接 SSL 配置的单点清掉 verifypeer 和 verifyhost 两位(仅改 5 字节),同时由于 wto_ws.dll 已拦截所有外部连接,客户端不会连向任何真实外网服务器。", - "if_not_applied": "经 wto_ws.dll 改道到本地服务的 https 请求在 TLS 握手后因自签证书校验失败断开,GJN 付款、商品价格查询(item_info.php)和兑换码等无法到达本地服务。" - }, - - "why_this_site": [ - "aces.exe 只静态链接了一份 libcurl(OpenSSL 后端),AsyncHTTPClient、dagor.http、YuHttp 全部共用它;Curl_clone_primary_ssl_config 是每个连接初始化 SSL 配置的必经入口。", - "0x5646412 原本是清除第 1 位后把 verifyhost 合进 eax,紧接着 0x5646417 写回 [rdx+0x98]。改成 and eax, -4 加两个 nop,一次把第 0 位(verifypeer)和第 1 位(verifyhost)都清零并写回,只改 5 字节,不改变栈和跳转结构。" - ], - - "features": ["A-不连 Gaijin", "G-礼包商店", "G-兑换码"], - "requires": ["online/network-hook-library"], - "evidence": [ - "2.61.0.37 原版 aces.exe:Curl_clone_primary_ssl_config 位于 0x56463c0,由 0x5646360 对主连接(+0x1b0)和代理连接(+0x250)调用;OpenSSL 校验函数 0x63adb70 在 0x63afed5、0x63b0522、0x63b05b7 读取 +0x98 的第 0、1 位。" - ], - "verified_on": [], - - "edit": { - "offset": 82, - "asm": ["and eax, -4", "nop", "nop"], - "bytes": "83e0fc9090", - "expect_original": "83e0fd09c8" - } -} diff --git a/exe-patches/online/accept-local-tls-certificate/patch.jsonc b/exe-patches/online/accept-local-tls-certificate/patch.jsonc new file mode 100644 index 0000000..a45605e --- /dev/null +++ b/exe-patches/online/accept-local-tls-certificate/patch.jsonc @@ -0,0 +1,28 @@ +// Clear libcurl's verifypeer and verifyhost bits when a connection copies its SSL settings. +// Why the executable: dagor.http and yuplay2 requests ignore network.blk enableSslCertCheck. +// Without it: redirected HTTPS requests (GJN purchases, item_info, redeem codes) fail the TLS handshake. +{ + "id": "online/accept-local-tls-certificate", + "title": "让客户端的 HTTPS 连接接受本地服务的自签证书", + "features": [ + "A-不连 Gaijin", + "G-礼包商店", + "G-兑换码" + ], + "requires": [ + "online/network-hook-library" + ], + "verified_on": [ + "2.61.0.37" + ], + "edit": { + "offset": 82, + "asm": [ + "and eax, -4", + "nop", + "nop" + ], + "bytes": "83e0fc9090", + "expect_original": "83e0fd09c8" + } +} diff --git a/exe-patches/online/matching-server-public-key/locate.json b/exe-patches/online/matching-server-public-key/locate.json deleted file mode 100644 index 85ebc70..0000000 --- a/exe-patches/online/matching-server-public-key/locate.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "method": "signature", - "section": ".rdata", - "how": [ - "常量区里 2048 位 RSA 公钥的 PEM 文本开头:\"-----BEGIN PUBLIC KEY-----\n\" 加上所有 2048 位、指数 65537 的公钥共有的 DER 前缀(base64 \"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\")。", - "不含 Gaijin 公钥本身的字节,Gaijin 换了公钥也能定位;原字节由 expect_original 核对。", - "程序里另一段 PEM(0x7a3543d)是 1024 位公钥,前缀不同,不会命中。", - "在 2.61.0.37 原版 aces.exe 上唯一命中 0x73422b0。" - ], - "pattern": "2d 2d 2d 2d 2d 42 45 47 49 4e 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d 2d 2d 0a 4d 49 49 42 49 6a 41 4e 42 67 6b 71 68 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 41 51 38 41 4d 49 49 42 43 67 4b 43 41 51 45 41" -} \ No newline at end of file diff --git a/exe-patches/online/matching-server-public-key/locate.jsonc b/exe-patches/online/matching-server-public-key/locate.jsonc new file mode 100644 index 0000000..0677c75 --- /dev/null +++ b/exe-patches/online/matching-server-public-key/locate.jsonc @@ -0,0 +1,9 @@ +// PEM header plus the DER prefix shared by every 2048-bit RSA key with exponent 65537; +// Gaijin's key bytes are not part of the pattern, so a rotated key is still found and expect_original checks it. +// The 1024-bit PEM at 0x7a3543d has a different prefix and does not match. +// 2.61.0.37: unique hit at 0x73422b0. +{ + "method": "signature", + "section": ".rdata", + "pattern": "2d 2d 2d 2d 2d 42 45 47 49 4e 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d 2d 2d 0a 4d 49 49 42 49 6a 41 4e 42 67 6b 71 68 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 41 51 38 41 4d 49 49 42 43 67 4b 43 41 51 45 41" +} diff --git a/exe-patches/online/matching-server-public-key/patch.json b/exe-patches/online/matching-server-public-key/patch.jsonc similarity index 51% rename from exe-patches/online/matching-server-public-key/patch.json rename to exe-patches/online/matching-server-public-key/patch.jsonc index cfd8282..b7d919d 100644 --- a/exe-patches/online/matching-server-public-key/patch.json +++ b/exe-patches/online/matching-server-public-key/patch.jsonc @@ -1,37 +1,17 @@ +// Replace the matching server public key with the local service's key. +// Why the executable: the session key is encrypted with this constant; only its private key can open it. +// Without it: the client cannot connect to the local matching server and the hangar never finishes loading. { "id": "online/matching-server-public-key", "title": "把程序里匹配服务器的公钥换成本地服务的公钥,让本地服务能解出匹配连接的会话密钥", - "program_behaviour": { - "stock": "登录匹配服务器时(mlogin.login,0x44e8160),客户端随机生成 16 字节会话密钥,和 chard_token 等放进一个 JSON,用写死的 Gaijin 2048 位 RSA 公钥(PKCS#1 v1.5 填充)加密,base64 后作为请求的 login 字段;之后双方的包都用会话密钥 AES-128-CBC 加密(0x55cc3c0)。只有持有 Gaijin 私钥的服务器能解出会话密钥。", - "patched": "客户端用本地服务的公钥加密会话密钥。本地服务用对应私钥(packages/local-service/src/matching/session-crypto/local-matching-server.key.pem)解出会话密钥,按原协议收发加密包。客户端的登录和加密逻辑不变。" - }, - "derivation": { - "requirement": "第一个里程碑:登录流程要等 MATCHING_CONNECTED 才初始化槽位栏(implementation notes 第 8 节)。", - "cause": "会话密钥只能用 Gaijin 的私钥解开;公钥是程序里的常量(0x73422b0,只在 0x44e93e5 被引用)。", - "lighter_options_ruled_out": [ - "原生自带:没有找到换公钥或关闭加密的配置项、启动参数。", - "本地服务:拿不到会话密钥就无法回复(第五轮实测:本地服务回明文,客户端 15 秒后超时)。", - "Changing the matching encryption path would alter client protocol behavior. The use of the unencrypted branch has not been established." - ], - "conclusion": "改 exe 的数据(一段 PEM 文本),不改代码。新公钥与原公钥都是 2048 位、指数 65537,PEM 文本长度相同(451 字节),原地替换。", - "if_not_applied": "匹配服务器连不上,机库一直显示\"正在连接服务器\",槽位栏不出现。" - }, - "why_this_site": [ - "这段 PEM 只在 mlogin.login 的组装代码里被引用一次(0x44e93e5,作为长度 0x1c4 的内存 BIO 读入)。", - "长度不变,结尾的 0 保持原样。" - ], - "key_pair": "固定的一对密钥,随项目代码提供。它只用于本机客户端和本机本地服务之间,不保护任何东西;固定密钥让补丁字节固定,check-patches 可以逐字节核对。", "features": [ "J-对局模式", "B-机库与载具" ], "requires": [], - "evidence": [ - "2.61.0.37 原版 aces.exe:0x73422b0 起 451 字节为 PEM 公钥,0x73423f3 为结尾的 0;0x44e93e5 把它交给 BIO,长度 0x1c4。", - "0x44e9518 以填充方式 1(RSA_PKCS1_PADDING)调用公钥加密;0x379b070 类型 1 为 NID 419(AES-128-CBC),类型 2 为 NID 895(AES-128-GCM)。", - "尚未在游戏里验证。" + "verified_on": [ + "2.61.0.37" ], - "verified_on": [], "edit": { "offset": 0, "data": { @@ -41,4 +21,4 @@ "bytes": "2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0a4d494942496a414e42676b71686b6947397730424151454641414f43415138414d49494243674b4341514541735067442f2f43316e70516874794f70624f34410a706442734a4a53744544486170664d39536c4b66686a756158784a6737676e39694e6b594458397143696a5845483969752f42566749326432526d48493166430a686d456e527459764869426759596842386c6b4d7230544844576757375536456d536a79505a317732755a75554b4475716b6c38726b736e766554302b507a350a67414b315379637a5174657530786f4868732f5175504e3952472f7574754357712f683671506e6450682b5651724d7772316e38386558345746444d495252300a35586f7a30534c503171356d3250726e4b316a51386173535476552f645462487a4d582b585979553969354753583262754f50756738514431556d454a57786f0a6a53643852397a7338595841636e69334962467967446c4e76503143337231666a7467316f7161595258783450445447613876744e706d34356437587454794b0a57514944415141420a2d2d2d2d2d454e44205055424c4943204b45592d2d2d2d2d0a", "expect_original": "2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0a4d494942496a414e42676b71686b6947397730424151454641414f43415138414d49494243674b434151454135566b754b6e6d5a3131777a66696169646b4c710a6256436f6f6448755a4b716c30547577516b2b4148306151625834773350373976584b57455751504c556156734f7a2b7a6166564455344b64764f374a2b62360a78706a6e49387632666c305653684e4e6a77664762386844364b32794532684f6466564f4e35676e6b3274456764654147443065324d38744e457869344d35770a707145545348336a6438376b6a30707a3941377231584c304d505163475664397236746e5a6f4d74754b6b786276754f326669452b4368306e41716b336461340a63424d756a43634963553849766362374733464841463572426d456c58524c6a485746566859446835336b52524c2f472f6d6e4a4a6e4b684e3638575070414d0a7167506457566f6f495731573646467a6c6f6a627338644241662f4e33616c5a4f46616378422f35373537516c7647364b38734952796d556b71396f4f6839500a62514944415141420a2d2d2d2d2d454e44205055424c4943204b45592d2d2d2d2d0a" } -} \ No newline at end of file +} diff --git a/exe-patches/online/network-hook-library/locate.json b/exe-patches/online/network-hook-library/locate.json deleted file mode 100644 index 4cce405..0000000 --- a/exe-patches/online/network-hook-library/locate.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "method": "signature", - "section": ".rdata", - - "how": [ - "导入表里系统网络库的名字 \"WS2_32.dll\",包括结尾的 0,共 11 字节。", - "在 2.61.0.37 原版 aces.exe 上唯一命中 0x7a4b090(导入描述符 Name 字段指向这里)。" - ], - - "pattern": "57 53 32 5f 33 32 2e 64 6c 6c 00" -} diff --git a/exe-patches/online/network-hook-library/locate.jsonc b/exe-patches/online/network-hook-library/locate.jsonc new file mode 100644 index 0000000..62203e3 --- /dev/null +++ b/exe-patches/online/network-hook-library/locate.jsonc @@ -0,0 +1,7 @@ +// The import name "WS2_32.dll" with its terminating zero, 11 bytes. +// 2.61.0.37: unique hit at 0x7a4b090 (referenced by the import descriptor Name field). +{ + "method": "signature", + "section": ".rdata", + "pattern": "57 53 32 5f 33 32 2e 64 6c 6c 00" +} diff --git a/exe-patches/online/network-hook-library/patch.json b/exe-patches/online/network-hook-library/patch.json deleted file mode 100644 index 3ebf5fb..0000000 --- a/exe-patches/online/network-hook-library/patch.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "id": "online/network-hook-library", - "title": "让游戏加载离线版的网络钩子库 wto_ws.dll(代替直接加载 WS2_32.dll),把所有联网都接到本地服务", - - "program_behaviour": { - "stock": "exe 从系统的 WS2_32.dll 导入 49 个网络函数(getaddrinfo、connect、sendto 等),程序里写死的 Gaijin 地址(api.gaijinent.com 的购买和兑换码、purch.gaijinent.com、统计上报等)照常解析、连到外网。", - "patched": "exe 改从同一目录的 wto_ws.dll 导入。wto_ws.dll 把这 49 个函数原样转发给系统的 ws2_32.dll,并在进程里给系统 ws2_32 的解析、连接、UDP 发送函数挂钩子:任何域名都解析到 127.0.0.2,任何连向 127.0.0.2 或外部地址的连接都改到 127.0.0.1:<本地服务端口>(端口读 exe 旁边的 wto_ws.cfg)。" - }, - - "derivation": { - "requirement": "Route hard-coded endpoints to the isolated local service at its configured port, including the endpoints for purchases and code redemption.", - "cause": "这些地址是程序和 yuplay2 里的常量,network.blk 的 storeApiHost 等只能换主机名,协议和端口(https/443)改不了,很多地址根本没有配置项。", - "lighter_options_ruled_out": [ - "原生自带:没有统一改所有地址和端口的配置项。", - "Replacing individual address strings has length constraints and misses calls made by other libraries in the process.", - "改 Windows hosts 文件:影响整台电脑和正版(6.1 排除),而且改不了端口。", - "代码洞里的钩子:只能拦 exe 自己的调用,fmod64、controller、gameHook、libcef 等 DLL 直接调 ws2_32,拦不到(implementation notes)。" - ], - "conclusion": "只改导入表里的一个 DLL 名(数据,同样 11 字节),钩子代码在离线版自己的 DLL 里。", - "if_not_applied": "写死的 https 地址照常连外网(断网守护拦下后功能失效);GJN 付款、兑换码等请求到不了本地服务。" - }, - - "why_this_site": [ - "这个字符串只被 ws2_32 的导入描述符引用。", - "新名字和原名一样长,原地替换,导入表结构不变。" - ], - - "features": ["A-不连 Gaijin", "A-与正版隔离", "G-礼包商店", "G-兑换码"], - "requires": [], - "evidence": [ - "2.61.0.37 原版 aces.exe:导入表 WS2_32.dll 描述符的 Name = 0x7a4b090,49 个按名导入的函数。", - "尚未在游戏里验证。" - ], - "verified_on": [], - - "edit": { - "offset": 0, - "data": { "encoding": "ascii", "text": "wto_ws.dll" }, - "bytes": "77746f5f77732e646c6c00", - "expect_original": "5753325f33322e646c6c00" - } -} diff --git a/exe-patches/online/network-hook-library/patch.jsonc b/exe-patches/online/network-hook-library/patch.jsonc new file mode 100644 index 0000000..1641f9e --- /dev/null +++ b/exe-patches/online/network-hook-library/patch.jsonc @@ -0,0 +1,26 @@ +// Import wto_ws.dll instead of WS2_32.dll; it forwards every export and redirects lookups and connections. +// Why the executable: many Gaijin addresses, ports and schemes are constants with no configuration entry. +// Without it: hard-coded https endpoints try the real internet and purchases/redeem codes never reach the local service. +{ + "id": "online/network-hook-library", + "title": "让游戏加载离线版的网络钩子库 wto_ws.dll(代替直接加载 WS2_32.dll),把所有联网都接到本地服务", + "features": [ + "A-不连 Gaijin", + "A-与正版隔离", + "G-礼包商店", + "G-兑换码" + ], + "requires": [], + "verified_on": [ + "2.61.0.37" + ], + "edit": { + "offset": 0, + "data": { + "encoding": "ascii", + "text": "wto_ws.dll" + }, + "bytes": "77746f5f77732e646c6c00", + "expect_original": "5753325f33322e646c6c00" + } +} diff --git a/exe-patches/startup/skip-resource-archive-signature-check/locate.json b/exe-patches/startup/skip-resource-archive-signature-check/locate.json deleted file mode 100644 index cd2a5a8..0000000 --- a/exe-patches/startup/skip-resource-archive-signature-check/locate.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "method": "signature", - "section": ".text", - - "how": [ - "整函数开头 0x60 字节的掩码特征。rip 相对操作数里的地址、以及相对跳转的目标,都已通配(authoring.py 生成)。", - "为什么要用这么长的特征:这个函数的开头是很常见的函数序言,只取十几个字节会匹配到几十处。", - "特征里的 56 52 46 78 是容器魔数 \"VRFx\" 的比较,和我们自己的脚本包读写实现对得上,是一个语义锚点,不太可能随版本变化。", - "备用:开头 0x40 字节在 2.61.0.37 上同样唯一命中。如果将来 0x60 的特征失配,先用 0x40 核对是不是只有后半段变了。", - "在 2.61.0.37 原版 aces.exe 上唯一命中 0x4073d30,函数范围 0x4073d30-0x407497d。" - ], - - "pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 68 01 00 00 0f 29 b4 24 50 01 00 00 48 8b 7a 40 48 85 ff 74 ?? 8b 5a 48 85 db 74 ?? 8b 42 08 83 f8 10 73 ?? 31 c0 0f 28 b4 24 50 01 00 00 48 81 c4 68 01 00 00 5b 5d 5f 5e 41 5c 41 5d 41 5e 41 5f c3 48 89 ce 4c 8b 32 41 81 3e 56 52 46 78 75 ??" -} diff --git a/exe-patches/startup/skip-resource-archive-signature-check/locate.jsonc b/exe-patches/startup/skip-resource-archive-signature-check/locate.jsonc new file mode 100644 index 0000000..b0a3584 --- /dev/null +++ b/exe-patches/startup/skip-resource-archive-signature-check/locate.jsonc @@ -0,0 +1,9 @@ +// First 0x60 bytes of the function, masked; a shorter prologue matches dozens of functions. +// Contains the "VRFx" archive magic comparison (56 52 46 78), a stable semantic anchor. +// Fallback: the first 0x40 bytes are also unique on 2.61.0.37; try them first if this pattern stops matching. +// 2.61.0.37: unique hit at 0x4073d30 (function 0x4073d30-0x407497d). +{ + "method": "signature", + "section": ".text", + "pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 68 01 00 00 0f 29 b4 24 50 01 00 00 48 8b 7a 40 48 85 ff 74 ?? 8b 5a 48 85 db 74 ?? 8b 42 08 83 f8 10 73 ?? 31 c0 0f 28 b4 24 50 01 00 00 48 81 c4 68 01 00 00 5b 5d 5f 5e 41 5c 41 5d 41 5e 41 5f c3 48 89 ce 4c 8b 32 41 81 3e 56 52 46 78 75 ??" +} diff --git a/exe-patches/startup/skip-resource-archive-signature-check/patch.json b/exe-patches/startup/skip-resource-archive-signature-check/patch.json deleted file mode 100644 index 2eec3a4..0000000 --- a/exe-patches/startup/skip-resource-archive-signature-check/patch.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "id": "startup/skip-resource-archive-signature-check", - "title": "让资源包签名校验直接返回通过", - - "program_behaviour": { - "stock": "挂载 .vromfs.bin 资源包时,程序调用一个函数校验包尾的 256 字节签名。返回 0(不合法)时,调用方跳到失败分支,这个包不会被挂载。", - "patched": "这个校验函数一进去就返回「通过」,不再读取签名。" - }, - - "derivation": { - "requirement": "功能清单 A「离线启动」。服务地址写在 char.vromfs.bin 的 config/network.blk 里(implementation notes),要把它们指向本地服务,就要重新打包这个数据包。", - "cause": "签名用 Gaijin 的私钥生成,我们无法为重新打包的内容生成有效签名。校验失败是运行时的硬拦截:包不会被挂载。", - "lighter_options_ruled_out": [ - "原生自带:校验在挂载路径上无条件执行,没有跳过它的配置项。", - "本地服务:不适用。程序挂载本地数据包时不联网。", - "客户端脚本:不适用。脚本本身也在数据包里,而且挂载发生在脚本运行之前。" - ], - "conclusion": "只能改 exe。", - "if_not_applied": "重新打包的 char.vromfs.bin 不会被挂载,客户端拿不到指向本地服务的地址。" - }, - - "why_this_site": [ - "校验函数的返回值直接控制流程:调用方是 call、test al,al、je 失败分支。让函数立即返回 1,就等于「签名通过」。", - "改函数入口只需要 3 字节、一个位置;改调用点要动 3 处。改一处更小、更稳。", - "打了补丁后这个函数不再调用任何东西,是个立即返回的叶子函数,所以不需要补异常展开信息。" - ], - - "features": ["A-离线启动"], - "requires": [], - "evidence": [ - "2.61.0.37 原版 aces.exe:校验函数 0x4073d30 在挂载路径上无条件调用,返回 0 时调用方跳到失败分支。", - "已在 2.61.0.37 上实测:打补丁后,重新打包的数据包可以正常挂载。" - ], - "verified_on": ["2.61.0.37"], - - "edit": { - "offset": 0, - "asm": ["mov al, 1", "ret"], - "bytes": "b001c3", - "expect_original": "415741" - } -} diff --git a/exe-patches/startup/skip-resource-archive-signature-check/patch.jsonc b/exe-patches/startup/skip-resource-archive-signature-check/patch.jsonc new file mode 100644 index 0000000..dcbb823 --- /dev/null +++ b/exe-patches/startup/skip-resource-archive-signature-check/patch.jsonc @@ -0,0 +1,23 @@ +// Make the resource archive signature check return success. +// Why the executable: rebuilt archives cannot carry a Gaijin signature and are refused at mount time. +// Without it: the rebuilt char.vromfs.bin is not mounted and the client never learns the local addresses. +{ + "id": "startup/skip-resource-archive-signature-check", + "title": "让资源包签名校验直接返回通过", + "features": [ + "A-离线启动" + ], + "requires": [], + "verified_on": [ + "2.61.0.37" + ], + "edit": { + "offset": 0, + "asm": [ + "mov al, 1", + "ret" + ], + "bytes": "b001c3", + "expect_original": "415741" + } +} diff --git a/gui-patches/battle/append-extra-battle-slots/find.nut b/gui-patches/battle/append-extra-battle-slots/find.nut new file mode 100644 index 0000000..465d759 --- /dev/null +++ b/gui-patches/battle/append-extra-battle-slots/find.nut @@ -0,0 +1,7 @@ + let res = crewInfo.filter(@(v) v.country == curCountry) + if (res.len() == 1) + return res.map( + @(countryInfo) countryInfo.__merge({ + crews = countryInfo.crews.map(@(crew) crew.__merge({idCountry = 0})) + }) + ) diff --git a/gui-patches/battle/append-extra-battle-slots/patch.json b/gui-patches/battle/append-extra-battle-slots/patch.json deleted file mode 100644 index 485ab59..0000000 --- a/gui-patches/battle/append-extra-battle-slots/patch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "battle/append-extra-battle-slots", - "title": "Append session killstreak aircraft and random-spawn vehicles to in-battle crew list", - "file": "scripts/slotbar/crewslist.nut", - "reason": "Dedicated servers append nuclear bombers, strike UCAVs, and RandomSpawnUnits filler slots to the battle crew list; appending activeBattle.extraBattleSlots when isInBattle is true exposes those slots to the respawn screen and slotbar.", - "features": ["J-本地对局", "K-战局任务加载"], - "edit": { - "find": " let res = crewInfo.filter(@(v) v.country == curCountry)\r\n if (res.len() == 1)\r\n return res.map(\r\n @(countryInfo) countryInfo.__merge({\r\n crews = countryInfo.crews.map(@(crew) crew.__merge({idCountry = 0}))\r\n })\r\n )", - "replace": " let appendWtoExtraBattleCrews = function(baseCrews) {\r\n let { ndbTryRead } = require(\"nestdb\")\r\n let wtoBattle = ndbTryRead([\"wto\", \"activeBattle\"])\r\n let extraSlots = wtoBattle?.extraBattleSlots\r\n if (extraSlots == null || extraSlots.len() == 0)\r\n return baseCrews\r\n if ((wtoBattle?.country ?? \"\") != \"\" && wtoBattle.country != curCountry)\r\n return baseCrews\r\n let merged = [].extend(baseCrews)\r\n foreach (idx, slot in extraSlots) {\r\n if (merged.len() >= 32)\r\n break\r\n let unitName = slot?.unitName ?? \"\"\r\n if (unitName == \"\")\r\n continue\r\n merged.append({\r\n id = -1 - idx\r\n idCountry = 0\r\n idInCountry = merged.len()\r\n country = curCountry\r\n aircraft = unitName\r\n isEmpty = 0\r\n trainedSpec = { [unitName] = 2 }\r\n trained = [unitName]\r\n skillPoints = 0\r\n lockedTillSec = 0\r\n isLocked = 0\r\n })\r\n }\r\n return merged\r\n }\r\n let res = crewInfo.filter(@(v) v.country == curCountry)\r\n if (res.len() == 1)\r\n return res.map(\r\n @(countryInfo) countryInfo.__merge({\r\n crews = appendWtoExtraBattleCrews(\r\n countryInfo.crews.map(@(crew) crew.__merge({idCountry = 0}))\r\n )\r\n })\r\n )" - } -} diff --git a/gui-patches/battle/append-extra-battle-slots/patch.jsonc b/gui-patches/battle/append-extra-battle-slots/patch.jsonc new file mode 100644 index 0000000..6c49f12 --- /dev/null +++ b/gui-patches/battle/append-extra-battle-slots/patch.jsonc @@ -0,0 +1,19 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/append-extra-battle-slots", + "title": "Append session killstreak aircraft and random-spawn vehicles to in-battle crew list", + "file": "scripts/slotbar/crewslist.nut", + "features": [ + "J-本地对局", + "K-战局任务加载" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/append-extra-battle-slots/replace.nut b/gui-patches/battle/append-extra-battle-slots/replace.nut new file mode 100644 index 0000000..6fa2eec --- /dev/null +++ b/gui-patches/battle/append-extra-battle-slots/replace.nut @@ -0,0 +1,40 @@ + let appendWtoExtraBattleCrews = function(baseCrews) { + let { ndbTryRead } = require("nestdb") + let wtoBattle = ndbTryRead(["wto", "activeBattle"]) + let extraSlots = wtoBattle?.extraBattleSlots + if (extraSlots == null || extraSlots.len() == 0) + return baseCrews + if ((wtoBattle?.country ?? "") != "" && wtoBattle.country != curCountry) + return baseCrews + let merged = [].extend(baseCrews) + foreach (idx, slot in extraSlots) { + if (merged.len() >= 32) + break + let unitName = slot?.unitName ?? "" + if (unitName == "") + continue + merged.append({ + id = -1 - idx + idCountry = 0 + idInCountry = merged.len() + country = curCountry + aircraft = unitName + isEmpty = 0 + trainedSpec = { [unitName] = 2 } + trained = [unitName] + skillPoints = 0 + lockedTillSec = 0 + isLocked = 0 + }) + } + return merged + } + let res = crewInfo.filter(@(v) v.country == curCountry) + if (res.len() == 1) + return res.map( + @(countryInfo) countryInfo.__merge({ + crews = appendWtoExtraBattleCrews( + countryInfo.crews.map(@(crew) crew.__merge({idCountry = 0})) + ) + }) + ) diff --git a/gui-patches/battle/force-extra-slot-weapons/find.nut b/gui-patches/battle/force-extra-slot-weapons/find.nut new file mode 100644 index 0000000..fbadd9e --- /dev/null +++ b/gui-patches/battle/force-extra-slot-weapons/find.nut @@ -0,0 +1,7 @@ + function getForcedUnitWeapon(unit) { + let groupName = this.getRandomUnitsGroupName(unit.name) + if (groupName == null) + return this.missionParams?.editSlotbar[unit.shopCountry][unit.name]["forceWeapon"] + + return getRandomUnitsForceWeapon(getEventEconomicName(getRoomEvent()), unit.name) + } diff --git a/gui-patches/battle/force-extra-slot-weapons/patch.json b/gui-patches/battle/force-extra-slot-weapons/patch.json deleted file mode 100644 index f4549aa..0000000 --- a/gui-patches/battle/force-extra-slot-weapons/patch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "battle/force-extra-slot-weapons", - "title": "Lock nuclear, strike-UCAV, and RandomSpawnUnits forced weapon presets in LocalMP", - "file": "scripts/miscustomrules/rulebase.nut", - "reason": "Extra battle slots require fixed nuclear bomb or strike-UCAV missile presets and fallback RandomSpawnUnits event lookup when session room event metadata is local.", - "features": ["D-改装件与挂载", "J-本地对局"], - "edit": { - "find": " function getForcedUnitWeapon(unit) {\r\n let groupName = this.getRandomUnitsGroupName(unit.name)\r\n if (groupName == null)\r\n return this.missionParams?.editSlotbar[unit.shopCountry][unit.name][\"forceWeapon\"]\r\n\r\n return getRandomUnitsForceWeapon(getEventEconomicName(getRoomEvent()), unit.name)\r\n }", - "replace": " function getForcedUnitWeapon(unit) {\r\n let { ndbTryRead } = require(\"nestdb\")\r\n let wtoBattle = ndbTryRead([\"wto\", \"activeBattle\"])\r\n foreach (wtoSlot in (wtoBattle?.extraBattleSlots ?? [])) {\r\n if (wtoSlot?.unitName == unit.name && (wtoSlot?.forceWeapon ?? \"\") != \"\")\r\n return wtoSlot.forceWeapon\r\n }\r\n let groupName = this.getRandomUnitsGroupName(unit.name)\r\n if (groupName == null)\r\n return this.missionParams?.editSlotbar[unit.shopCountry][unit.name][\"forceWeapon\"]\r\n\r\n let wtoRoomEcon = getEventEconomicName(getRoomEvent())\r\n let wtoEconName = wtoRoomEcon != \"\" ? wtoRoomEcon : (wtoBattle?.randomUnitsEventName ?? \"\")\r\n return getRandomUnitsForceWeapon(wtoEconName, unit.name)\r\n }" - } -} diff --git a/gui-patches/battle/force-extra-slot-weapons/patch.jsonc b/gui-patches/battle/force-extra-slot-weapons/patch.jsonc new file mode 100644 index 0000000..cd32050 --- /dev/null +++ b/gui-patches/battle/force-extra-slot-weapons/patch.jsonc @@ -0,0 +1,19 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/force-extra-slot-weapons", + "title": "Lock nuclear, strike-UCAV, and RandomSpawnUnits forced weapon presets in LocalMP", + "file": "scripts/miscustomrules/rulebase.nut", + "features": [ + "D-改装件与挂载", + "J-本地对局" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/force-extra-slot-weapons/replace.nut b/gui-patches/battle/force-extra-slot-weapons/replace.nut new file mode 100644 index 0000000..2a17a62 --- /dev/null +++ b/gui-patches/battle/force-extra-slot-weapons/replace.nut @@ -0,0 +1,15 @@ + function getForcedUnitWeapon(unit) { + let { ndbTryRead } = require("nestdb") + let wtoBattle = ndbTryRead(["wto", "activeBattle"]) + foreach (wtoSlot in (wtoBattle?.extraBattleSlots ?? [])) { + if (wtoSlot?.unitName == unit.name && (wtoSlot?.forceWeapon ?? "") != "") + return wtoSlot.forceWeapon + } + let groupName = this.getRandomUnitsGroupName(unit.name) + if (groupName == null) + return this.missionParams?.editSlotbar[unit.shopCountry][unit.name]["forceWeapon"] + + let wtoRoomEcon = getEventEconomicName(getRoomEvent()) + let wtoEconName = wtoRoomEcon != "" ? wtoRoomEcon : (wtoBattle?.randomUnitsEventName ?? "") + return getRandomUnitsForceWeapon(wtoEconName, unit.name) + } diff --git a/gui-patches/battle/launch-local-battle-from-queue/find.nut b/gui-patches/battle/launch-local-battle-from-queue/find.nut new file mode 100644 index 0000000..35473fe --- /dev/null +++ b/gui-patches/battle/launch-local-battle-from-queue/find.nut @@ -0,0 +1,4 @@ + matchingApiFunc("match.enqueue", cb, params) +} + +matchingRpcSubscribe("match.notify_clusters_changed", onClustersChanged) diff --git a/gui-patches/battle/launch-local-battle-from-queue/patch.json b/gui-patches/battle/launch-local-battle-from-queue/patch.json deleted file mode 100644 index 972d407..0000000 --- a/gui-patches/battle/launch-local-battle-from-queue/patch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "battle/launch-local-battle-from-queue", - "title": "Launch local authoritative multiplayer battle on queue notification", - "file": "scripts/matching/servicenotifications/match.nut", - "reason": "Start an authoritative LocalMP host session from matching notifications with multi-nation coalition room state, per-difficulty mission ticket overrides, persistent killstreak spawn costs, and extra battle slot metadata.", - "features": ["battle-matchmaking", "mission-launch", "ai-bots"], - "edit": { - "find": " matchingApiFunc(\"match.enqueue\", cb, params)\r\n}\r\n\r\nmatchingRpcSubscribe(\"match.notify_clusters_changed\", onClustersChanged)", - "replace": " matchingApiFunc(\"match.enqueue\", cb, params)\r\n}\r\n\r\nfunction fillWtoBotEntries(parentBlk, blockName, entries) {\r\n if (entries == null)\r\n return\r\n foreach (entry in entries) {\r\n let b = parentBlk.addNewBlock(blockName)\r\n b.name = entry.name\r\n b.weight = (entry?.weight ?? 1.0).tofloat()\r\n b.country = entry.country\r\n }\r\n}\r\n\r\nfunction copyWtoMissionMetadata(misBlk, missionFile, difficulty) {\r\n if (missionFile == null || missionFile == \"\")\r\n return\r\n let { blkOptFromPath } = require(\"%sqstd/datablock.nut\")\r\n let rawMis = blkOptFromPath(missionFile)?.mission_settings?.mission\r\n if (rawMis == null)\r\n return\r\n let ruleKeys = [\r\n \"scoreLimit\", \"timeLimit\", \"killLimit\", \"deathPenaltyMul\",\r\n \"ctaCaptureZoneEqualPenaltyMul\", \"ctaCaptureZonePenaltyMul\",\r\n \"captureZonePenaltyMul\", \"scorePerSec\",\r\n \"ctaInstantDecreaseTicketsWhenNoRespawn\",\r\n \"randomSpawnTeams\", \"remapAiTankModels\", \"useAlternativeMapCoord\"\r\n ]\r\n foreach (key in [\r\n \"locName\", \"locDesc\", \"locNameTeamA\", \"locNameTeamB\",\r\n \"locDescTeamA\", \"locDescTeamB\", \"loc_name\", \"postfix\", \"restoreType\"\r\n ].extend(ruleKeys)) {\r\n let val = rawMis?[key]\r\n if (val != null)\r\n misBlk[key] = val\r\n }\r\n let targetDiff = (difficulty == \"simulator\" || difficulty == \"fullreal\") ? \"hardcore\"\r\n : (difficulty == \"historical\" ? \"realistic\" : difficulty)\r\n foreach (sub in (rawMis % \"mission\")) {\r\n let subDiff = sub?.difficulty\r\n if (subDiff != difficulty && subDiff != targetDiff)\r\n continue\r\n foreach (dKey in ruleKeys) {\r\n let dVal = sub?[dKey]\r\n if (dVal != null)\r\n misBlk[dKey] = dVal\r\n }\r\n }\r\n}\r\n\r\nfunction toWtoPrefixedCountries(list, fallback) {\r\n let src = (list != null && list.len() > 0) ? list : [fallback]\r\n return src.map(@(c) c.indexof(\"country_\") == 0 ? c : $\"country_{c}\")\r\n}\r\n\r\nfunction buildWtoMissionBlk(ev, gmConsts, guiMis) {\r\n let DataBlock = require(\"DataBlock\")\r\n let misBlk = DataBlock()\r\n let baseBlk = guiMis.get_meta_mission_info_by_gm_and_name(gmConsts.GM_SKIRMISH, ev.missionName)\r\n ?? guiMis.get_meta_mission_info_by_name(ev.missionName)\r\n copyWtoMissionMetadata(misBlk, ev?.missionFile, ev.difficulty)\r\n let levelVal = ev?.level ?? baseBlk?.level ?? misBlk?.level\r\n let envVal = ev?.environment ?? baseBlk?.environment ?? misBlk?.environment\r\n let weatherVal = ev?.weather ?? baseBlk?.weather ?? misBlk?.weather\r\n if (levelVal != null)\r\n misBlk.level = levelVal\r\n if (envVal != null)\r\n misBlk.environment = envVal\r\n if (weatherVal != null)\r\n misBlk.weather = weatherVal\r\n\r\n misBlk.localMP = true\r\n misBlk._gameMode = gmConsts.GM_DOMINATION\r\n misBlk.name = ev.missionName\r\n misBlk.economicName = ev.economicName\r\n misBlk.mis_file = ev.missionFile\r\n misBlk.chapter = \"skirmish\"\r\n misBlk.type = ev.missionType\r\n misBlk.difficulty = ev.difficulty\r\n misBlk.country_allies = ev.countryAllies\r\n misBlk.country_axis = ev.countryAxis\r\n misBlk.arcadeCountry = true\r\n misBlk.symmetricTeams = ev?.symmetricTeams ?? false\r\n misBlk.gt_versus = true\r\n misBlk.gt_mp_tickets = true\r\n misBlk.gt_mp_capture = true\r\n misBlk.gt_mp_solo = false\r\n misBlk.gt_use_wp = true\r\n misBlk.gt_use_xp = true\r\n misBlk.gt_use_stats = true\r\n misBlk.gt_use_unlocks = true\r\n misBlk.useSpawnScore = ev?.useSpawnScore ?? false\r\n misBlk.allowSpare = true\r\n misBlk.isLimitedAmmo = true\r\n misBlk.allowUseArtillerySupport = true\r\n misBlk.isBotsAllowed = true\r\n misBlk.useTankBots = ev?.useTankBots ?? false\r\n misBlk.useShipBots = ev?.useShipBots ?? false\r\n misBlk.autoBalance = true\r\n misBlk.maxPlayers = ev.maxPlayers\r\n misBlk.maxBots = ev.maxBots\r\n\r\n let extraSlots = ev?.extraBattleSlots ?? []\r\n local persistentBlk = null\r\n foreach (slot in extraSlots) {\r\n let cost = slot?.persistentCost ?? 0\r\n let uName = slot?.unitName ?? \"\"\r\n if (cost > 0 && uName != \"\") {\r\n if (persistentBlk == null)\r\n persistentBlk = misBlk.addNewBlock(\"customSpawnScore\").addNewBlock(\"persistent_costs\")\r\n persistentBlk[uName] = cost.tointeger()\r\n }\r\n }\r\n\r\n foreach (tag in [\"ranks\", \"forcedRanks\"]) {\r\n let rBlk = misBlk.addNewBlock(tag)\r\n rBlk.min = ev.minMrank\r\n rBlk.max = ev.maxMrank\r\n }\r\n let alliesBare = ev?.countriesAllies ?? [ev.countryAllies]\r\n let axisBare = ev?.countriesAxis ?? [ev.countryAxis]\r\n let botsBlk = misBlk.addNewBlock(\"customBots\")\r\n botsBlk.wtoPlayerTeam = $\"{ev?.playerTeam ?? 1}\"\r\n botsBlk.wtoTeamACountries = \";\".join(alliesBare)\r\n botsBlk.wtoTeamBCountries = \";\".join(axisBare)\r\n botsBlk.numBotRespawnsInMultiSlot = ev.airBotRespawns\r\n botsBlk.numTankBotRespawnsInMultiSlot = ev.tankBotRespawns\r\n botsBlk.numBotRespawnsInVersus = ev.airBotRespawns\r\n botsBlk.numTankBotRespawnsInVersus = ev.tankBotRespawns\r\n fillWtoBotEntries(botsBlk.addNewBlock(\"allowedTanks\"), \"tank\", ev?.customBots?.tanks)\r\n fillWtoBotEntries(botsBlk.addNewBlock(\"allowedAircrafts\"), \"aircraft\", ev?.customBots?.aircrafts)\r\n fillWtoBotEntries(botsBlk.addNewBlock(\"allowedShips\"), \"ship\", ev?.customBots?.ships)\r\n return misBlk\r\n}\r\n\r\nfunction enterWtoSessionRoom(ev, gmConsts) {\r\n let lobbyStates = require(\"%scripts/matchingRooms/lobbyStates.nut\")\r\n let { setSessionLobbySettings, switchSessionLobbyStatus } = require(\"%scripts/matchingRooms/sessionLobbyManager.nut\")\r\n let alliesCountries = toWtoPrefixedCountries(ev?.countriesAllies, ev.countryAllies)\r\n let axisCountries = toWtoPrefixedCountries(ev?.countriesAxis, ev.countryAxis)\r\n setSessionLobbySettings({\r\n game_mode_id = ev.modeId\r\n game_mode_name = ev.modeName\r\n economicName = ev.economicName\r\n symmetricTeams = ev?.symmetricTeams ?? false\r\n country_allies = alliesCountries\r\n country_axis = axisCountries\r\n mission = {\r\n name = ev.missionName\r\n _gameMode = gmConsts.GM_DOMINATION\r\n difficulty = ev.difficulty\r\n }\r\n }, true, false)\r\n switchSessionLobbyStatus(lobbyStates.IN_SESSION)\r\n}\r\n\r\nfunction onWtoBattleNotify(ev) {\r\n if (ev?.func != \"launch\" || isInFlight())\r\n return\r\n let { ndbWrite } = require(\"nestdb\")\r\n let guiMis = require(\"guiMission\")\r\n let missionMod = require(\"mission\")\r\n let gmConsts = require(\"%globalScripts/gameModeNativeConsts.nut\")\r\n let { reset_cur_mission_mode } = require(\"%appGlobals/ranks_common_shared.nut\")\r\n let { notifyQueueLeave } = require(\"%scripts/queue/queueManager.nut\")\r\n let destroySessionScripted = require(\"%scripts/matchingRooms/destroySessionScripted.nut\")\r\n let { invalidateCrewsList } = require(\"%scripts/slotbar/crewsList.nut\")\r\n let { guiStartFlight } = require(\"%scripts/missions/startMissionsList.nut\")\r\n let { currentCampaignMission } = require(\"%scripts/missions/missionsStates.nut\")\r\n\r\n notifyQueueLeave({})\r\n destroySessionScripted(\"on start wto local battle\")\r\n ndbWrite([\"wto\", \"activeBattle\"], {\r\n sessionId = ev.sessionId\r\n modeName = ev.modeName\r\n economicName = ev.economicName\r\n country = ev.country\r\n missionName = ev.missionName\r\n extraBattleSlots = ev?.extraBattleSlots ?? []\r\n randomUnits = ev?.randomUnits ?? {}\r\n randomUnitsEventName = ev?.randomUnitsEventName ?? \"\"\r\n })\r\n invalidateCrewsList(true)\r\n let misBlk = buildWtoMissionBlk(ev, gmConsts, guiMis)\r\n currentCampaignMission.set(ev.missionName)\r\n missionMod.set_game_mode(gmConsts.GM_DOMINATION)\r\n enterWtoSessionRoom(ev, gmConsts)\r\n reset_cur_mission_mode()\r\n guiMis.select_training_mission(misBlk)\r\n reset_cur_mission_mode()\r\n guiStartFlight()\r\n}\r\n\r\nrequire(\"%sqStdLibs/helpers/subscriptions.nut\").addListenersWithoutEnv({\r\n SessionDestroyed = function(_p) {\r\n if (!isInFlight()) {\r\n let { ndbExists, ndbDelete } = require(\"nestdb\")\r\n if (ndbExists([\"wto\", \"activeBattle\"])) {\r\n ndbDelete([\"wto\", \"activeBattle\"])\r\n require(\"%scripts/slotbar/crewsList.nut\").invalidateCrewsList(true)\r\n }\r\n }\r\n }\r\n})\r\n\r\nrequire(\"%scripts/matching/serviceNotifications/mrpc.nut\").mnSubscribe(\"wto_battle\", onWtoBattleNotify)\r\n\r\nmatchingRpcSubscribe(\"match.notify_clusters_changed\", onClustersChanged)" - } -} diff --git a/gui-patches/battle/launch-local-battle-from-queue/patch.jsonc b/gui-patches/battle/launch-local-battle-from-queue/patch.jsonc new file mode 100644 index 0000000..8fc2b90 --- /dev/null +++ b/gui-patches/battle/launch-local-battle-from-queue/patch.jsonc @@ -0,0 +1,20 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/launch-local-battle-from-queue", + "title": "Launch local authoritative multiplayer battle on queue notification", + "file": "scripts/matching/servicenotifications/match.nut", + "features": [ + "battle-matchmaking", + "mission-launch", + "ai-bots" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/launch-local-battle-from-queue/replace.nut b/gui-patches/battle/launch-local-battle-from-queue/replace.nut new file mode 100644 index 0000000..ba00b67 --- /dev/null +++ b/gui-patches/battle/launch-local-battle-from-queue/replace.nut @@ -0,0 +1,208 @@ + matchingApiFunc("match.enqueue", cb, params) +} + +function fillWtoBotEntries(parentBlk, blockName, entries) { + if (entries == null) + return + foreach (entry in entries) { + let b = parentBlk.addNewBlock(blockName) + b.name = entry.name + b.weight = (entry?.weight ?? 1.0).tofloat() + b.country = entry.country + } +} + +function copyWtoMissionMetadata(misBlk, missionFile, difficulty) { + if (missionFile == null || missionFile == "") + return + let { blkOptFromPath } = require("%sqstd/datablock.nut") + let rawMis = blkOptFromPath(missionFile)?.mission_settings?.mission + if (rawMis == null) + return + let ruleKeys = [ + "scoreLimit", "timeLimit", "killLimit", "deathPenaltyMul", + "ctaCaptureZoneEqualPenaltyMul", "ctaCaptureZonePenaltyMul", + "captureZonePenaltyMul", "scorePerSec", + "ctaInstantDecreaseTicketsWhenNoRespawn", + "randomSpawnTeams", "remapAiTankModels", "useAlternativeMapCoord" + ] + foreach (key in [ + "locName", "locDesc", "locNameTeamA", "locNameTeamB", + "locDescTeamA", "locDescTeamB", "loc_name", "postfix", "restoreType" + ].extend(ruleKeys)) { + let val = rawMis?[key] + if (val != null) + misBlk[key] = val + } + let targetDiff = (difficulty == "simulator" || difficulty == "fullreal") ? "hardcore" + : (difficulty == "historical" ? "realistic" : difficulty) + foreach (sub in (rawMis % "mission")) { + let subDiff = sub?.difficulty + if (subDiff != difficulty && subDiff != targetDiff) + continue + foreach (dKey in ruleKeys) { + let dVal = sub?[dKey] + if (dVal != null) + misBlk[dKey] = dVal + } + } +} + +function toWtoPrefixedCountries(list, fallback) { + let src = (list != null && list.len() > 0) ? list : [fallback] + return src.map(@(c) c.indexof("country_") == 0 ? c : $"country_{c}") +} + +function buildWtoMissionBlk(ev, gmConsts, guiMis) { + let DataBlock = require("DataBlock") + let misBlk = DataBlock() + let baseBlk = guiMis.get_meta_mission_info_by_gm_and_name(gmConsts.GM_SKIRMISH, ev.missionName) + ?? guiMis.get_meta_mission_info_by_name(ev.missionName) + copyWtoMissionMetadata(misBlk, ev?.missionFile, ev.difficulty) + let levelVal = ev?.level ?? baseBlk?.level ?? misBlk?.level + let envVal = ev?.environment ?? baseBlk?.environment ?? misBlk?.environment + let weatherVal = ev?.weather ?? baseBlk?.weather ?? misBlk?.weather + if (levelVal != null) + misBlk.level = levelVal + if (envVal != null) + misBlk.environment = envVal + if (weatherVal != null) + misBlk.weather = weatherVal + + misBlk.localMP = true + misBlk._gameMode = gmConsts.GM_DOMINATION + misBlk.name = ev.missionName + misBlk.economicName = ev.economicName + misBlk.mis_file = ev.missionFile + misBlk.chapter = "skirmish" + misBlk.type = ev.missionType + misBlk.difficulty = ev.difficulty + misBlk.country_allies = ev.countryAllies + misBlk.country_axis = ev.countryAxis + misBlk.arcadeCountry = true + misBlk.symmetricTeams = ev?.symmetricTeams ?? false + misBlk.gt_versus = true + misBlk.gt_mp_tickets = true + misBlk.gt_mp_capture = true + misBlk.gt_mp_solo = false + misBlk.gt_use_wp = true + misBlk.gt_use_xp = true + misBlk.gt_use_stats = true + misBlk.gt_use_unlocks = true + misBlk.useSpawnScore = ev?.useSpawnScore ?? false + misBlk.allowSpare = true + misBlk.isLimitedAmmo = true + misBlk.allowUseArtillerySupport = true + misBlk.isBotsAllowed = true + misBlk.useTankBots = ev?.useTankBots ?? false + misBlk.useShipBots = ev?.useShipBots ?? false + misBlk.autoBalance = true + misBlk.maxPlayers = ev.maxPlayers + misBlk.maxBots = ev.maxBots + + let extraSlots = ev?.extraBattleSlots ?? [] + local persistentBlk = null + foreach (slot in extraSlots) { + let cost = slot?.persistentCost ?? 0 + let uName = slot?.unitName ?? "" + if (cost > 0 && uName != "") { + if (persistentBlk == null) + persistentBlk = misBlk.addNewBlock("customSpawnScore").addNewBlock("persistent_costs") + persistentBlk[uName] = cost.tointeger() + } + } + + foreach (tag in ["ranks", "forcedRanks"]) { + let rBlk = misBlk.addNewBlock(tag) + rBlk.min = ev.minMrank + rBlk.max = ev.maxMrank + } + let alliesBare = ev?.countriesAllies ?? [ev.countryAllies] + let axisBare = ev?.countriesAxis ?? [ev.countryAxis] + let botsBlk = misBlk.addNewBlock("customBots") + botsBlk.wtoPlayerTeam = $"{ev?.playerTeam ?? 1}" + botsBlk.wtoTeamACountries = ";".join(alliesBare) + botsBlk.wtoTeamBCountries = ";".join(axisBare) + botsBlk.numBotRespawnsInMultiSlot = ev.airBotRespawns + botsBlk.numTankBotRespawnsInMultiSlot = ev.tankBotRespawns + botsBlk.numBotRespawnsInVersus = ev.airBotRespawns + botsBlk.numTankBotRespawnsInVersus = ev.tankBotRespawns + fillWtoBotEntries(botsBlk.addNewBlock("allowedTanks"), "tank", ev?.customBots?.tanks) + fillWtoBotEntries(botsBlk.addNewBlock("allowedAircrafts"), "aircraft", ev?.customBots?.aircrafts) + fillWtoBotEntries(botsBlk.addNewBlock("allowedShips"), "ship", ev?.customBots?.ships) + return misBlk +} + +function enterWtoSessionRoom(ev, gmConsts) { + let lobbyStates = require("%scripts/matchingRooms/lobbyStates.nut") + let { setSessionLobbySettings, switchSessionLobbyStatus } = require("%scripts/matchingRooms/sessionLobbyManager.nut") + let alliesCountries = toWtoPrefixedCountries(ev?.countriesAllies, ev.countryAllies) + let axisCountries = toWtoPrefixedCountries(ev?.countriesAxis, ev.countryAxis) + setSessionLobbySettings({ + game_mode_id = ev.modeId + game_mode_name = ev.modeName + economicName = ev.economicName + symmetricTeams = ev?.symmetricTeams ?? false + country_allies = alliesCountries + country_axis = axisCountries + mission = { + name = ev.missionName + _gameMode = gmConsts.GM_DOMINATION + difficulty = ev.difficulty + } + }, true, false) + switchSessionLobbyStatus(lobbyStates.IN_SESSION) +} + +function onWtoBattleNotify(ev) { + if (ev?.func != "launch" || isInFlight()) + return + let { ndbWrite } = require("nestdb") + let guiMis = require("guiMission") + let missionMod = require("mission") + let gmConsts = require("%globalScripts/gameModeNativeConsts.nut") + let { reset_cur_mission_mode } = require("%appGlobals/ranks_common_shared.nut") + let { notifyQueueLeave } = require("%scripts/queue/queueManager.nut") + let destroySessionScripted = require("%scripts/matchingRooms/destroySessionScripted.nut") + let { invalidateCrewsList } = require("%scripts/slotbar/crewsList.nut") + let { guiStartFlight } = require("%scripts/missions/startMissionsList.nut") + let { currentCampaignMission } = require("%scripts/missions/missionsStates.nut") + + notifyQueueLeave({}) + destroySessionScripted("on start wto local battle") + ndbWrite(["wto", "activeBattle"], { + sessionId = ev.sessionId + modeName = ev.modeName + economicName = ev.economicName + country = ev.country + missionName = ev.missionName + extraBattleSlots = ev?.extraBattleSlots ?? [] + randomUnits = ev?.randomUnits ?? {} + randomUnitsEventName = ev?.randomUnitsEventName ?? "" + }) + invalidateCrewsList(true) + let misBlk = buildWtoMissionBlk(ev, gmConsts, guiMis) + currentCampaignMission.set(ev.missionName) + missionMod.set_game_mode(gmConsts.GM_DOMINATION) + enterWtoSessionRoom(ev, gmConsts) + reset_cur_mission_mode() + guiMis.select_training_mission(misBlk) + reset_cur_mission_mode() + guiStartFlight() +} + +require("%sqStdLibs/helpers/subscriptions.nut").addListenersWithoutEnv({ + SessionDestroyed = function(_p) { + if (!isInFlight()) { + let { ndbExists, ndbDelete } = require("nestdb") + if (ndbExists(["wto", "activeBattle"])) { + ndbDelete(["wto", "activeBattle"]) + require("%scripts/slotbar/crewsList.nut").invalidateCrewsList(true) + } + } + } +}) + +require("%scripts/matching/serviceNotifications/mrpc.nut").mnSubscribe("wto_battle", onWtoBattleNotify) + +matchingRpcSubscribe("match.notify_clusters_changed", onClustersChanged) diff --git a/gui-patches/battle/lineup-br-for-submodes/find.nut b/gui-patches/battle/lineup-br-for-submodes/find.nut new file mode 100644 index 0000000..6069abb --- /dev/null +++ b/gui-patches/battle/lineup-br-for-submodes/find.nut @@ -0,0 +1,7 @@ +function getCurRank(event) { + if (isInSquad()) + return getRecentSquadMrank() + + let unit = getPlayerCurUnit() + return unit == null ? null : getEffectiveMrank(unit, events.getEDiffByEvent(event)) +} diff --git a/gui-patches/battle/lineup-br-for-submodes/patch.json b/gui-patches/battle/lineup-br-for-submodes/patch.json deleted file mode 100644 index d034703..0000000 --- a/gui-patches/battle/lineup-br-for-submodes/patch.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "id": "battle/lineup-br-for-submodes", - "title": "多槽位预设模式下按整套可用出击阵容最高权重判定夜间战斗等附加子模式可用性", - "file": "scripts/events/secondgamemodesutils.nut", - - "program_behaviour": { - "stock": "secondgamemodesutils.nut 的 getCurRank(event) 在单人未组队状态下只读取机库当前鼠标高亮的单辆载具 getPlayerCurUnit(),导致在陆战历史性能等多槽位(multiSlot)模式中,即使预设编队内拥有 10.0+ 载具(面板标题已显示 12.0 权重),只要当前高亮槽位载具低于 10.0(如 9.7 的 BMD-4M),夜间战斗就会被误判为「不可用(仅限 10.0 及以上权重)」。", - "patched": "当处于单人且当前赛事启用了多槽位出击(events.isEventMultiSlotEnabled(event))时,遍历玩家当前国家的可用预设乘员组载具(getOwnCraftNames() 中允许参加该赛事的载具),取最高有效匹配分房等级(mrank)用于判定子模式可用性;单槽位模式(如空战历史性能的小规模战斗)仍保持只检查当前选中载具。" - }, - - "derivation": { - "requirement": "Evaluate Night Battles and other multi-slot sub-mode BR requirements against the highest-BR eligible vehicle in the player's active preset lineup rather than only the currently highlighted crew slot.", - "cause": "getCurRank(event) 在组队时调用 getRecentSquadMrank()(来自 wtmm_static.calc_ranks 的整套预设最高分房),但单人分支直接退化为读取 getPlayerCurUnit(),忽略了多槽位赛事中同预设其它槽位的高权重载具。", - "lighter_options_ruled_out": [ - "仅靠本地服务:本地服务 wtmm_static.calc_ranks 已正确返回 12.0 权重(recentBR 已显示 12.0),但客户端 isNightModeAvalible(event) 不读取 recentBR,而是直接调用本地脚本函数 getCurRank(event) 禁用开关控件。" - ], - "conclusion": "在 secondgamemodesutils.nut 的 getCurRank(event) 中对多槽位模式汇总预设内赛事允许载具的最大有效 mrank。", - "if_not_applied": "多槽位编队同时携带低权重与 10.0+ 高权重载具时,一旦机库高亮停留在低于 10.0 的槽位上,夜间战斗开关即被锁死并提示不可用,与顶栏显示的整套编队权重自相矛盾。" - }, - - "features": ["J-对局模式目录与队列"], - "evidence": [ - "2.61.0.37 gui.vromfs.bin:scripts/events/secondgamemodesutils.nut 第 123-157、426-460 行,scripts/mainmenu/secondgamemodespanel.nut 第 70-103 行,scripts/events/eventsmanager.nut 第 902、1043、1248 行。" - ], - - "edit": { - "find": "function getCurRank(event) {\r\n if (isInSquad())\r\n return getRecentSquadMrank()\r\n\r\n let unit = getPlayerCurUnit()\r\n return unit == null ? null : getEffectiveMrank(unit, events.getEDiffByEvent(event))\r\n}", - "replace": "function getCurRank(event) {\r\n if (isInSquad())\r\n return getRecentSquadMrank()\r\n\r\n let ediff = events.getEDiffByEvent(event)\r\n if (events.isEventMultiSlotEnabled(event)) {\r\n let ownCraftNames = getOwnCraftNames()\r\n let mrankDeltaByUnit = getMrankDeltaByUnit(ownCraftNames)\r\n local maxMrank = null\r\n foreach (unitName in ownCraftNames) {\r\n let unit = getAircraftByName(unitName)\r\n if (unit != null && events.isUnitAllowedForEvent(event, unit)) {\r\n let mrank = getEffectiveMrank(unit, ediff, mrankDeltaByUnit?[unitName] ?? 0)\r\n maxMrank = maxMrank == null ? mrank : max(maxMrank, mrank)\r\n }\r\n }\r\n if (maxMrank != null)\r\n return maxMrank\r\n }\r\n\r\n let unit = getPlayerCurUnit()\r\n return unit == null ? null : getEffectiveMrank(unit, ediff)\r\n}" - } -} diff --git a/gui-patches/battle/lineup-br-for-submodes/patch.jsonc b/gui-patches/battle/lineup-br-for-submodes/patch.jsonc new file mode 100644 index 0000000..a09cf37 --- /dev/null +++ b/gui-patches/battle/lineup-br-for-submodes/patch.jsonc @@ -0,0 +1,18 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/lineup-br-for-submodes", + "title": "多槽位预设模式下按整套可用出击阵容最高权重判定夜间战斗等附加子模式可用性", + "file": "scripts/events/secondgamemodesutils.nut", + "features": [ + "J-对局模式目录与队列" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/lineup-br-for-submodes/replace.nut b/gui-patches/battle/lineup-br-for-submodes/replace.nut new file mode 100644 index 0000000..ccd1143 --- /dev/null +++ b/gui-patches/battle/lineup-br-for-submodes/replace.nut @@ -0,0 +1,23 @@ +function getCurRank(event) { + if (isInSquad()) + return getRecentSquadMrank() + + let ediff = events.getEDiffByEvent(event) + if (events.isEventMultiSlotEnabled(event)) { + let ownCraftNames = getOwnCraftNames() + let mrankDeltaByUnit = getMrankDeltaByUnit(ownCraftNames) + local maxMrank = null + foreach (unitName in ownCraftNames) { + let unit = getAircraftByName(unitName) + if (unit != null && events.isUnitAllowedForEvent(event, unit)) { + let mrank = getEffectiveMrank(unit, ediff, mrankDeltaByUnit?[unitName] ?? 0) + maxMrank = maxMrank == null ? mrank : max(maxMrank, mrank) + } + } + if (maxMrank != null) + return maxMrank + } + + let unit = getPlayerCurUnit() + return unit == null ? null : getEffectiveMrank(unit, ediff) +} diff --git a/gui-patches/battle/local-host-spawn-score/find.nut b/gui-patches/battle/local-host-spawn-score/find.nut new file mode 100644 index 0000000..e98e272 --- /dev/null +++ b/gui-patches/battle/local-host-spawn-score/find.nut @@ -0,0 +1,2 @@ +registerRespondent("get_spawn_score_type_mul", get_spawn_score_type_mul) +registerRespondent("get_unit_spawn_score_weapon_mul", get_unit_spawn_score_weapon_mul) diff --git a/gui-patches/battle/local-host-spawn-score/patch.json b/gui-patches/battle/local-host-spawn-score/patch.json deleted file mode 100644 index 46336ef..0000000 --- a/gui-patches/battle/local-host-spawn-score/patch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "battle/local-host-spawn-score", - "title": "Register missing LocalMP host spawn-point callbacks and preserve persistent costs", - "file": "scripts/respawn/respawnstate.nut", - "reason": "Client script packs omit server-only get_max_spawn_score and get_unit_spawn_score callbacks, and get_unit_spawn_score_weapon_mul otherwise scales persistent killstreak costs by bomb/missile mass.", - "features": ["K-战局任务加载"], - "edit": { - "find": "registerRespondent(\"get_spawn_score_type_mul\", get_spawn_score_type_mul)\r\nregisterRespondent(\"get_unit_spawn_score_weapon_mul\", get_unit_spawn_score_weapon_mul)", - "replace": "function calcWtoMaxSpawnScore(_userId, _maxRank) {\r\n let ranksShared = require(\"%appGlobals/ranks_common_shared.nut\")\r\n let mathMod = require(\"math\")\r\n let baseCoef = ranksShared.get_spawn_score_param(\"base_respawn_points_coef\", 450)\r\n let maxMul = ranksShared.get_spawn_score_param(\"maxRespawnPointsMul\", 1.0)\r\n return mathMod.max(0, mathMod.round(baseCoef * maxMul).tointeger())\r\n}\r\n\r\nfunction calcWtoUnitSpawnScore(_userId, unitName, _unitRankArg) {\r\n if (unitName == null || unitName == \"\")\r\n return 0\r\n let ranksShared = require(\"%appGlobals/ranks_common_shared.nut\")\r\n let { get_current_mission_info_cached, get_wpcost_blk } = require(\"blkGetters\")\r\n let { round_by_value } = require(\"%sqstd/math.nut\")\r\n let mathMod = require(\"math\")\r\n let misBlk = get_current_mission_info_cached()\r\n let persistentCost = misBlk?.customSpawnScore?.persistent_costs?[unitName] ?? 0\r\n if (persistentCost > 0)\r\n return persistentCost.tointeger()\r\n let unitClass = ranksShared.getWpcostUnitClass(unitName)\r\n let costMul = ranksShared.get_spawn_score_param(unitName, null)\r\n ?? ranksShared.get_spawn_score_param(unitClass, 0.0)\r\n if (costMul <= 0.0)\r\n return 0\r\n let baseCoef = ranksShared.get_spawn_score_param(\"base_respawn_points_coef\", 450)\r\n let unitType = ranksShared.get_unit_type_by_unit_name(unitName)\r\n let brDiffMul = ranksShared.get_spawn_score_param($\"br_diff_mul_{unitType}\", 0.0)\r\n let maxBrDiff = ranksShared.get_spawn_score_param(\"max_br_diff\", 1.0)\r\n let sessionMaxRank = misBlk?.ranks?.max ?? 0\r\n let unitBlk = get_wpcost_blk()?[unitName]\r\n let ediff = ranksShared.get_mission_mode()\r\n let unitRank = ranksShared.get_unit_blk_economic_rank_by_mode(unitBlk, ediff, sessionMaxRank)\r\n local brFactor = 1.0\r\n if (maxBrDiff > 0.0 && brDiffMul != 0.0) {\r\n let sessionBr = ranksShared.calcBattleRatingFromRank(sessionMaxRank)\r\n let unitBr = ranksShared.calcBattleRatingFromRank(unitRank)\r\n let brDiff = mathMod.clamp(sessionBr - unitBr, 0.0, maxBrDiff)\r\n brFactor = 1.0 - brDiffMul * (brDiff / maxBrDiff)\r\n }\r\n let rawScore = baseCoef * costMul * brFactor\r\n return mathMod.max(1, round_by_value(rawScore, 10).tointeger())\r\n}\r\n\r\nfunction calcWtoUnitSpawnScoreWeaponMul(unitname, weapon, bulletArray, presetTbl = {}) {\r\n let { get_current_mission_info_cached } = require(\"blkGetters\")\r\n let persistentCost = get_current_mission_info_cached()?.customSpawnScore?.persistent_costs?[unitname] ?? 0\r\n if (persistentCost > 0)\r\n return 1.0\r\n return get_unit_spawn_score_weapon_mul(unitname, weapon, bulletArray, presetTbl)\r\n}\r\n\r\nregisterRespondent(\"get_max_spawn_score\", calcWtoMaxSpawnScore)\r\nregisterRespondent(\"get_unit_spawn_score\", calcWtoUnitSpawnScore)\r\nregisterRespondent(\"get_spawn_score_type_mul\", get_spawn_score_type_mul)\r\nregisterRespondent(\"get_unit_spawn_score_weapon_mul\", calcWtoUnitSpawnScoreWeaponMul)" - } -} diff --git a/gui-patches/battle/local-host-spawn-score/patch.jsonc b/gui-patches/battle/local-host-spawn-score/patch.jsonc new file mode 100644 index 0000000..54157c2 --- /dev/null +++ b/gui-patches/battle/local-host-spawn-score/patch.jsonc @@ -0,0 +1,18 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/local-host-spawn-score", + "title": "Register missing LocalMP host spawn-point callbacks and preserve persistent costs", + "file": "scripts/respawn/respawnstate.nut", + "features": [ + "K-战局任务加载" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/local-host-spawn-score/replace.nut b/gui-patches/battle/local-host-spawn-score/replace.nut new file mode 100644 index 0000000..2d10889 --- /dev/null +++ b/gui-patches/battle/local-host-spawn-score/replace.nut @@ -0,0 +1,55 @@ +function calcWtoMaxSpawnScore(_userId, _maxRank) { + let ranksShared = require("%appGlobals/ranks_common_shared.nut") + let mathMod = require("math") + let baseCoef = ranksShared.get_spawn_score_param("base_respawn_points_coef", 450) + let maxMul = ranksShared.get_spawn_score_param("maxRespawnPointsMul", 1.0) + return mathMod.max(0, mathMod.round(baseCoef * maxMul).tointeger()) +} + +function calcWtoUnitSpawnScore(_userId, unitName, _unitRankArg) { + if (unitName == null || unitName == "") + return 0 + let ranksShared = require("%appGlobals/ranks_common_shared.nut") + let { get_current_mission_info_cached, get_wpcost_blk } = require("blkGetters") + let { round_by_value } = require("%sqstd/math.nut") + let mathMod = require("math") + let misBlk = get_current_mission_info_cached() + let persistentCost = misBlk?.customSpawnScore?.persistent_costs?[unitName] ?? 0 + if (persistentCost > 0) + return persistentCost.tointeger() + let unitClass = ranksShared.getWpcostUnitClass(unitName) + let costMul = ranksShared.get_spawn_score_param(unitName, null) + ?? ranksShared.get_spawn_score_param(unitClass, 0.0) + if (costMul <= 0.0) + return 0 + let baseCoef = ranksShared.get_spawn_score_param("base_respawn_points_coef", 450) + let unitType = ranksShared.get_unit_type_by_unit_name(unitName) + let brDiffMul = ranksShared.get_spawn_score_param($"br_diff_mul_{unitType}", 0.0) + let maxBrDiff = ranksShared.get_spawn_score_param("max_br_diff", 1.0) + let sessionMaxRank = misBlk?.ranks?.max ?? 0 + let unitBlk = get_wpcost_blk()?[unitName] + let ediff = ranksShared.get_mission_mode() + let unitRank = ranksShared.get_unit_blk_economic_rank_by_mode(unitBlk, ediff, sessionMaxRank) + local brFactor = 1.0 + if (maxBrDiff > 0.0 && brDiffMul != 0.0) { + let sessionBr = ranksShared.calcBattleRatingFromRank(sessionMaxRank) + let unitBr = ranksShared.calcBattleRatingFromRank(unitRank) + let brDiff = mathMod.clamp(sessionBr - unitBr, 0.0, maxBrDiff) + brFactor = 1.0 - brDiffMul * (brDiff / maxBrDiff) + } + let rawScore = baseCoef * costMul * brFactor + return mathMod.max(1, round_by_value(rawScore, 10).tointeger()) +} + +function calcWtoUnitSpawnScoreWeaponMul(unitname, weapon, bulletArray, presetTbl = {}) { + let { get_current_mission_info_cached } = require("blkGetters") + let persistentCost = get_current_mission_info_cached()?.customSpawnScore?.persistent_costs?[unitname] ?? 0 + if (persistentCost > 0) + return 1.0 + return get_unit_spawn_score_weapon_mul(unitname, weapon, bulletArray, presetTbl) +} + +registerRespondent("get_max_spawn_score", calcWtoMaxSpawnScore) +registerRespondent("get_unit_spawn_score", calcWtoUnitSpawnScore) +registerRespondent("get_spawn_score_type_mul", get_spawn_score_type_mul) +registerRespondent("get_unit_spawn_score_weapon_mul", calcWtoUnitSpawnScoreWeaponMul) diff --git a/gui-patches/battle/pass-spawn-modifications-blk/find.nut b/gui-patches/battle/pass-spawn-modifications-blk/find.nut new file mode 100644 index 0000000..dbe63ae --- /dev/null +++ b/gui-patches/battle/pass-spawn-modifications-blk/find.nut @@ -0,0 +1,41 @@ + function requestAircraftAndWeapon(requestData) { + if (this.requestInProgress) + return + + set_aircraft_accepted_cb(this, this.aircraftAcceptedCb); + let _taskId = requestAircraftAndWeaponWithSpare(requestData, requestData.idInCountry, + requestData.respBaseId, requestData.spareUid) + if (_taskId < 0) + set_aircraft_accepted_cb(null, null); + else { + this.requestInProgress = true + this.showTaskProgressBox(loc("charServer/purchase0"), function() { this.requestInProgress = false }) + + this.lastRequestData = requestData + } + } + + function requestChangeUnitSilent() { + let unit = this.getCurSlotUnit() + if (!unit?.isHuman() || !this.canChangeAircraft || this.isApplyPressed) { + this.isSilentRequestPending = false + return + } + this.isSilentRequestPending = this.requestInProgress || !canRequestAircraftNow() + if (this.isSilentRequestPending) + return + + let requestData = this.getSelectedRequestData(true) + if (!requestData) + return + + set_aircraft_accepted_cb(this, this.silentAircraftAcceptedCb); + let _taskId = requestAircraftAndWeaponWithSpare(requestData, requestData.idInCountry, + requestData.respBaseId, requestData.spareUid) + if (_taskId < 0) + set_aircraft_accepted_cb(null, null); + else { + this.requestInProgress = true + this.lastRequestData = requestData + } + } diff --git a/gui-patches/battle/pass-spawn-modifications-blk/patch.json b/gui-patches/battle/pass-spawn-modifications-blk/patch.json deleted file mode 100644 index a7cf0bd..0000000 --- a/gui-patches/battle/pass-spawn-modifications-blk/patch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "battle/pass-spawn-modifications-blk", - "title": "Pass enabled modifications, spaded extra-slot loadout, and unit reward rates on LocalMP spawn", - "file": "scripts/respawn/respawn.nut", - "reason": "Forward enabled/disabled modifications, forced presets for extra battle slots, class-scaled warpoints/wpcost rates, and silent-preview state through requestAircraftAndWeaponWithSlots for LocalMP.", - "features": ["modifications-loadout", "local-battle"], - "edit": { - "find": " function requestAircraftAndWeapon(requestData) {\r\n if (this.requestInProgress)\r\n return\r\n\r\n set_aircraft_accepted_cb(this, this.aircraftAcceptedCb);\r\n let _taskId = requestAircraftAndWeaponWithSpare(requestData, requestData.idInCountry,\r\n requestData.respBaseId, requestData.spareUid)\r\n if (_taskId < 0)\r\n set_aircraft_accepted_cb(null, null);\r\n else {\r\n this.requestInProgress = true\r\n this.showTaskProgressBox(loc(\"charServer/purchase0\"), function() { this.requestInProgress = false })\r\n\r\n this.lastRequestData = requestData\r\n }\r\n }\r\n\r\n function requestChangeUnitSilent() {\r\n let unit = this.getCurSlotUnit()\r\n if (!unit?.isHuman() || !this.canChangeAircraft || this.isApplyPressed) {\r\n this.isSilentRequestPending = false\r\n return\r\n }\r\n this.isSilentRequestPending = this.requestInProgress || !canRequestAircraftNow()\r\n if (this.isSilentRequestPending)\r\n return\r\n\r\n let requestData = this.getSelectedRequestData(true)\r\n if (!requestData)\r\n return\r\n\r\n set_aircraft_accepted_cb(this, this.silentAircraftAcceptedCb);\r\n let _taskId = requestAircraftAndWeaponWithSpare(requestData, requestData.idInCountry,\r\n requestData.respBaseId, requestData.spareUid)\r\n if (_taskId < 0)\r\n set_aircraft_accepted_cb(null, null);\r\n else {\r\n this.requestInProgress = true\r\n this.lastRequestData = requestData\r\n }\r\n }", - "replace": " function sendWtoAircraftAndWeaponRequest(requestData, isSilent = false) {\r\n let wtoNdb = require(\"nestdb\")\r\n if (!wtoNdb.ndbExists([\"wto\", \"activeBattle\"]))\r\n return requestAircraftAndWeaponWithSpare(requestData, requestData.idInCountry,\r\n requestData.respBaseId, requestData.spareUid)\r\n let wtoBattle = wtoNdb.ndbTryRead([\"wto\", \"activeBattle\"])\r\n let wtoGuiRespawn = require(\"guiRespawn\")\r\n let wtoChardRes = require(\"chardResearch\")\r\n let wtoBlkGetters = require(\"blkGetters\")\r\n let wtoUnitName = requestData?.name ?? \"\"\r\n local wtoExtraSlot = null\r\n foreach (slot in (wtoBattle?.extraBattleSlots ?? [])) {\r\n if (slot?.unitName == wtoUnitName) {\r\n wtoExtraSlot = slot\r\n break\r\n }\r\n }\r\n if ((wtoExtraSlot?.forceWeapon ?? \"\") != \"\")\r\n requestData.weapon = wtoExtraSlot.forceWeapon\r\n let wtoIsSpaded = wtoExtraSlot?.spaded == true\r\n let wtoUnit = getAircraftByName(wtoUnitName) ?? this.getCurSlotUnit()\r\n let wtoEnabledMods = []\r\n let wtoDisabledMods = []\r\n foreach (wtoMod in (wtoUnit?.getModifications() ?? [])) {\r\n let wtoModName = wtoMod?.name ?? \"\"\r\n if (wtoModName == \"\")\r\n continue\r\n if (wtoIsSpaded || wtoChardRes.shopIsModificationEnabled(wtoUnitName, wtoModName))\r\n wtoEnabledMods.append(wtoModName)\r\n else if (wtoChardRes.shopIsModificationPurchased(wtoUnitName, wtoModName))\r\n wtoDisabledMods.append(wtoModName)\r\n }\r\n let wtoEdiff = this.getCurrentEdiff()\r\n let wtoDiffRem = wtoEdiff >= 0 ? (wtoEdiff % 3) : 1\r\n let wtoDiffSuffix = wtoDiffRem == 0 ? \"Arcade\" : wtoDiffRem == 1 ? \"Historical\" : \"Simulation\"\r\n let wtoUnitCost = get_wpcost_blk()?[wtoUnitName]\r\n let wtoWarBlk = wtoBlkGetters.get_warpoints_blk()\r\n let wtoBlk = DataBlock()\r\n wtoBlk.enabledMods = \";\".join(wtoEnabledMods)\r\n wtoBlk.disabledMods = \";\".join(wtoDisabledMods)\r\n wtoBlk.isSilentPreview = isSilent ? \"1\" : \"0\"\r\n if (wtoUnitCost != null && wtoWarBlk != null) {\r\n let wtoClassKillMul = wtoWarBlk.units[wtoUnitCost.unitClass].tofloat()\r\n let wtoRewardMul = wtoUnitCost[$\"rewardMul{wtoDiffSuffix}\"].tofloat()\r\n wtoBlk.wpPerKill = (wtoWarBlk.aKill.tofloat() * wtoClassKillMul * wtoWarBlk.wpMultiplier.tofloat() * wtoRewardMul).tofloat()\r\n wtoBlk.expMul = wtoUnitCost.expMul.tofloat()\r\n wtoBlk.battleTimeAward = wtoUnitCost[$\"battleTimeAward{wtoDiffSuffix}\"].tofloat()\r\n wtoBlk.aiKillK = wtoWarBlk.aiKillK.tofloat()\r\n wtoBlk.winK = wtoWarBlk.winK.tofloat()\r\n }\r\n if (!isSilent && (requestData?.spareUid ?? \"\") != \"\" && wtoUnitName != \"\") {\r\n let prevSpares = wtoBattle?.usedSpares ?? {}\r\n prevSpares[wtoUnitName] <- (prevSpares?[wtoUnitName] ?? 0) + 1\r\n wtoBattle.usedSpares <- prevSpares\r\n wtoNdb.ndbWrite([\"wto\", \"activeBattle\"], wtoBattle)\r\n }\r\n return wtoGuiRespawn.requestAircraftAndWeaponWithSlots(requestData, requestData.idInCountry,\r\n requestData.respBaseId, requestData.spareUid, wtoBlk, DataBlock())\r\n }\r\n\r\n function requestAircraftAndWeapon(requestData) {\r\n if (this.requestInProgress)\r\n return\r\n\r\n set_aircraft_accepted_cb(this, this.aircraftAcceptedCb);\r\n let _taskId = this.sendWtoAircraftAndWeaponRequest(requestData, false)\r\n if (_taskId < 0)\r\n set_aircraft_accepted_cb(null, null);\r\n else {\r\n this.requestInProgress = true\r\n this.showTaskProgressBox(loc(\"charServer/purchase0\"), function() { this.requestInProgress = false })\r\n\r\n this.lastRequestData = requestData\r\n }\r\n }\r\n\r\n function requestChangeUnitSilent() {\r\n let unit = this.getCurSlotUnit()\r\n if (!unit?.isHuman() || !this.canChangeAircraft || this.isApplyPressed) {\r\n this.isSilentRequestPending = false\r\n return\r\n }\r\n this.isSilentRequestPending = this.requestInProgress || !canRequestAircraftNow()\r\n if (this.isSilentRequestPending)\r\n return\r\n\r\n let requestData = this.getSelectedRequestData(true)\r\n if (!requestData)\r\n return\r\n\r\n set_aircraft_accepted_cb(this, this.silentAircraftAcceptedCb);\r\n let _taskId = this.sendWtoAircraftAndWeaponRequest(requestData, true)\r\n if (_taskId < 0)\r\n set_aircraft_accepted_cb(null, null);\r\n else {\r\n this.requestInProgress = true\r\n this.lastRequestData = requestData\r\n }\r\n }" - } -} diff --git a/gui-patches/battle/pass-spawn-modifications-blk/patch.jsonc b/gui-patches/battle/pass-spawn-modifications-blk/patch.jsonc new file mode 100644 index 0000000..c32d4ea --- /dev/null +++ b/gui-patches/battle/pass-spawn-modifications-blk/patch.jsonc @@ -0,0 +1,19 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/pass-spawn-modifications-blk", + "title": "Pass enabled modifications, spaded extra-slot loadout, and unit reward rates on LocalMP spawn", + "file": "scripts/respawn/respawn.nut", + "features": [ + "modifications-loadout", + "local-battle" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/pass-spawn-modifications-blk/replace.nut b/gui-patches/battle/pass-spawn-modifications-blk/replace.nut new file mode 100644 index 0000000..8b592c6 --- /dev/null +++ b/gui-patches/battle/pass-spawn-modifications-blk/replace.nut @@ -0,0 +1,99 @@ + function sendWtoAircraftAndWeaponRequest(requestData, isSilent = false) { + let wtoNdb = require("nestdb") + if (!wtoNdb.ndbExists(["wto", "activeBattle"])) + return requestAircraftAndWeaponWithSpare(requestData, requestData.idInCountry, + requestData.respBaseId, requestData.spareUid) + 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 ?? [])) { + if (slot?.unitName == wtoUnitName) { + wtoExtraSlot = slot + break + } + } + if ((wtoExtraSlot?.forceWeapon ?? "") != "") + requestData.weapon = wtoExtraSlot.forceWeapon + let wtoIsSpaded = wtoExtraSlot?.spaded == true + let wtoUnit = getAircraftByName(wtoUnitName) ?? this.getCurSlotUnit() + let wtoEnabledMods = [] + let wtoDisabledMods = [] + foreach (wtoMod in (wtoUnit?.getModifications() ?? [])) { + let wtoModName = wtoMod?.name ?? "" + if (wtoModName == "") + continue + if (wtoIsSpaded || wtoChardRes.shopIsModificationEnabled(wtoUnitName, wtoModName)) + wtoEnabledMods.append(wtoModName) + 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 + wtoBattle.usedSpares <- prevSpares + wtoNdb.ndbWrite(["wto", "activeBattle"], wtoBattle) + } + return wtoGuiRespawn.requestAircraftAndWeaponWithSlots(requestData, requestData.idInCountry, + requestData.respBaseId, requestData.spareUid, wtoBlk, DataBlock()) + } + + function requestAircraftAndWeapon(requestData) { + if (this.requestInProgress) + return + + set_aircraft_accepted_cb(this, this.aircraftAcceptedCb); + let _taskId = this.sendWtoAircraftAndWeaponRequest(requestData, false) + if (_taskId < 0) + set_aircraft_accepted_cb(null, null); + else { + this.requestInProgress = true + this.showTaskProgressBox(loc("charServer/purchase0"), function() { this.requestInProgress = false }) + + this.lastRequestData = requestData + } + } + + function requestChangeUnitSilent() { + let unit = this.getCurSlotUnit() + if (!unit?.isHuman() || !this.canChangeAircraft || this.isApplyPressed) { + this.isSilentRequestPending = false + return + } + this.isSilentRequestPending = this.requestInProgress || !canRequestAircraftNow() + if (this.isSilentRequestPending) + return + + let requestData = this.getSelectedRequestData(true) + if (!requestData) + return + + set_aircraft_accepted_cb(this, this.silentAircraftAcceptedCb); + let _taskId = this.sendWtoAircraftAndWeaponRequest(requestData, true) + if (_taskId < 0) + set_aircraft_accepted_cb(null, null); + else { + this.requestInProgress = true + this.lastRequestData = requestData + } + } diff --git a/gui-patches/battle/populate-random-spawn-units-state/find.nut b/gui-patches/battle/populate-random-spawn-units-state/find.nut new file mode 100644 index 0000000..e0497cb --- /dev/null +++ b/gui-patches/battle/populate-random-spawn-units-state/find.nut @@ -0,0 +1,3 @@ + function getMyStateBlk() { + return get_user_custom_state(userIdInt64.get(), false) + } diff --git a/gui-patches/battle/populate-random-spawn-units-state/patch.json b/gui-patches/battle/populate-random-spawn-units-state/patch.json deleted file mode 100644 index 0e20cb8..0000000 --- a/gui-patches/battle/populate-random-spawn-units-state/patch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "battle/populate-random-spawn-units-state", - "title": "Populate local player's random_units state block in LocalMP sessions", - "file": "scripts/miscustomrules/rulebase.nut", - "reason": "Online servers replicate random_units candidate lists into MPlayer custom state; populating get_user_custom_state from activeBattle.randomUnits enables native dice icons, group titles, BR ranges, and hover candidate tooltips on slotbarview.", - "features": ["J-本地对局", "K-战局任务加载"], - "edit": { - "find": " function getMyStateBlk() {\r\n return get_user_custom_state(userIdInt64.get(), false)\r\n }", - "replace": " function getMyStateBlk() {\r\n let wtoUid = userIdInt64.get()\r\n local wtoStateBlk = get_user_custom_state(wtoUid, false)\r\n let { ndbTryRead } = require(\"nestdb\")\r\n let wtoRandom = ndbTryRead([\"wto\", \"activeBattle\"])?.randomUnits\r\n if (wtoRandom == null || wtoRandom.len() == 0)\r\n return wtoStateBlk\r\n if (wtoStateBlk == null)\r\n wtoStateBlk = get_user_custom_state(wtoUid, true) ?? DataBlock()\r\n if (wtoStateBlk?.random_units == null) {\r\n let wtoRuBlk = wtoStateBlk.addNewBlock(\"random_units\")\r\n foreach (wtoGroupName, wtoUnits in wtoRandom) {\r\n if (wtoUnits == null || wtoUnits.len() == 0)\r\n continue\r\n let wtoGroupBlk = wtoRuBlk.addNewBlock(wtoGroupName)\r\n foreach (wtoUnitName in wtoUnits)\r\n wtoGroupBlk[wtoUnitName] = true\r\n }\r\n }\r\n return wtoStateBlk\r\n }" - } -} diff --git a/gui-patches/battle/populate-random-spawn-units-state/patch.jsonc b/gui-patches/battle/populate-random-spawn-units-state/patch.jsonc new file mode 100644 index 0000000..a6261e6 --- /dev/null +++ b/gui-patches/battle/populate-random-spawn-units-state/patch.jsonc @@ -0,0 +1,19 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/populate-random-spawn-units-state", + "title": "Populate local player's random_units state block in LocalMP sessions", + "file": "scripts/miscustomrules/rulebase.nut", + "features": [ + "J-本地对局", + "K-战局任务加载" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/populate-random-spawn-units-state/replace.nut b/gui-patches/battle/populate-random-spawn-units-state/replace.nut new file mode 100644 index 0000000..23e56cd --- /dev/null +++ b/gui-patches/battle/populate-random-spawn-units-state/replace.nut @@ -0,0 +1,21 @@ + function getMyStateBlk() { + let wtoUid = userIdInt64.get() + local wtoStateBlk = get_user_custom_state(wtoUid, false) + let { ndbTryRead } = require("nestdb") + let wtoRandom = ndbTryRead(["wto", "activeBattle"])?.randomUnits + if (wtoRandom == null || wtoRandom.len() == 0) + return wtoStateBlk + if (wtoStateBlk == null) + wtoStateBlk = get_user_custom_state(wtoUid, true) ?? DataBlock() + if (wtoStateBlk?.random_units == null) { + let wtoRuBlk = wtoStateBlk.addNewBlock("random_units") + foreach (wtoGroupName, wtoUnits in wtoRandom) { + if (wtoUnits == null || wtoUnits.len() == 0) + continue + let wtoGroupBlk = wtoRuBlk.addNewBlock(wtoGroupName) + foreach (wtoUnitName in wtoUnits) + wtoGroupBlk[wtoUnitName] = true + } + } + return wtoStateBlk + } diff --git a/gui-patches/battle/quit-local-host-spectator-to-debriefing/find.nut b/gui-patches/battle/quit-local-host-spectator-to-debriefing/find.nut new file mode 100644 index 0000000..ee09302 --- /dev/null +++ b/gui-patches/battle/quit-local-host-spectator-to-debriefing/find.nut @@ -0,0 +1,2 @@ + if (is_multiplayer()) + return leave_mp_session() diff --git a/gui-patches/battle/quit-local-host-spectator-to-debriefing/patch.json b/gui-patches/battle/quit-local-host-spectator-to-debriefing/patch.json deleted file mode 100644 index fe3c44b..0000000 --- a/gui-patches/battle/quit-local-host-spectator-to-debriefing/patch.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "id": "battle/quit-local-host-spectator-to-debriefing", - "title": "重生与观战界面在本地多人主机模式下退出任务时直接进入战后结算", - "file": "scripts/hud/starthud.nut", - - "program_behaviour": { - "stock": "quitMission() 在重生或观战界面只要判断 is_multiplayer() 为真就调用 leave_mp_session() 并提前返回;在 LocalMP 主机模式下 leave_mp_session() 为空操作,无法退到结算界面。", - "patched": "仅在 is_multiplayer() && !is_mplayer_host() 时调用 leave_mp_session(),本地主机继续执行下方的 quit_to_debriefing() 与 interrupt_multiplayer(true)。" - }, - - "derivation": { - "requirement": "Allow leaving a LocalMP battle from the respawn or spectator screen (e.g. when out of spawn points or crews) and proceeding to debriefing.", - "cause": "与 flightmenu.nut 相同,原生 leave_mp_session(aces.exe 0x17909a0)在主机模式下直接空返回。", - "lighter_options_ruled_out": [ - "仅修 flightmenu.nut:当玩家载具全部阵亡或重生点不足停留在重生/观战界面点「返回基地」时,调用的是 scripts/hud/starthud.nut 的 quitMission()(respawn.nut 第 2671 行等引用)。" - ], - "conclusion": "在 starthud.nut 的 quitMission() 中同样排除 is_mplayer_host(),使本地主机走 quit_to_debriefing()。", - "if_not_applied": "载具耗尽或重生点不足时在重生/观战界面点「返回基地」无法退出战局。" - }, - - "features": ["K-战局任务加载", "M-战后结算"], - "evidence": [ - "2.61.0.37 aces.exe:0x17909a0-0x17909be(leave_mp_session 主机空返回)。", - "2.61.0.37 gui.vromfs.bin:scripts/hud/starthud.nut 第 33-44 行。" - ], - - "edit": { - "find": " if (is_multiplayer())\r\n return leave_mp_session()", - "replace": " if (is_multiplayer() && !require(\"multiplayer\").is_mplayer_host())\r\n return leave_mp_session()" - } -} diff --git a/gui-patches/battle/quit-local-host-spectator-to-debriefing/patch.jsonc b/gui-patches/battle/quit-local-host-spectator-to-debriefing/patch.jsonc new file mode 100644 index 0000000..6082cae --- /dev/null +++ b/gui-patches/battle/quit-local-host-spectator-to-debriefing/patch.jsonc @@ -0,0 +1,19 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/quit-local-host-spectator-to-debriefing", + "title": "重生与观战界面在本地多人主机模式下退出任务时直接进入战后结算", + "file": "scripts/hud/starthud.nut", + "features": [ + "K-战局任务加载", + "M-战后结算" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/quit-local-host-spectator-to-debriefing/replace.nut b/gui-patches/battle/quit-local-host-spectator-to-debriefing/replace.nut new file mode 100644 index 0000000..820f217 --- /dev/null +++ b/gui-patches/battle/quit-local-host-spectator-to-debriefing/replace.nut @@ -0,0 +1,2 @@ + if (is_multiplayer() && !require("multiplayer").is_mplayer_host()) + return leave_mp_session() diff --git a/gui-patches/battle/quit-local-host-to-debriefing/find.nut b/gui-patches/battle/quit-local-host-to-debriefing/find.nut new file mode 100644 index 0000000..44237e4 --- /dev/null +++ b/gui-patches/battle/quit-local-host-to-debriefing/find.nut @@ -0,0 +1,29 @@ + function sendDisconnectMessage() { + broadcastEvent("PlayerQuitMission") + if (is_multiplayer()) { + leave_mp_session() + this.onResumeRaw() + } + else + this.quitToDebriefing() + } + + function quitToDebriefing() { + disableOrders() + quit_to_debriefing() + interrupt_multiplayer(true) + HudBattleLog.reset() + this.onResumeRaw() + } + + function onQuitMission(_obj) { + if (is_offline_version() && !ludeo?.is_running()) + return restart_mission() + + if (is_replay_playing()) { + this.quitToDebriefing() + } + else if (get_mission_status() == MISSION_STATUS_RUNNING) { + local text = "" + if (is_mplayer_host()) + text = loc("flightmenu/questionQuitMissionHost") diff --git a/gui-patches/battle/quit-local-host-to-debriefing/patch.json b/gui-patches/battle/quit-local-host-to-debriefing/patch.json deleted file mode 100644 index d3eaf44..0000000 --- a/gui-patches/battle/quit-local-host-to-debriefing/patch.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "id": "battle/quit-local-host-to-debriefing", - "title": "局内菜单在本地多人主机模式下显示常规随机战退局提示并直接进入战后结算", - "file": "scripts/flightmenu/flightmenu.nut", - - "program_behaviour": { - "stock": "FlightMenu.onQuitMission 对 is_mplayer_host() 一律显示自定义房主专用提示(\"其他玩家将无法完成该任务\"),且 sendDisconnectMessage 只要判断 is_multiplayer() 为真就调用主机下为空操作的 leave_mp_session()。", - "patched": "随机战(GM_DOMINATION)下跳过自定义房主提示,照常列出剩余可出击载具与随机战中途退出提示;确认退出时仅对非主机调用 leave_mp_session(),本地主机走 this.quitToDebriefing() 进入战后结算。" - }, - - "derivation": { - "requirement": "Show the standard random-battle quit confirmation (remaining crews and early-leave notice) and proceed cleanly to debriefing when pressing Esc -> Return to Hangar in a LocalMP battle.", - "cause": "flightmenu.nut 第 255 行把 is_mplayer_host() 放在 get_game_mode() == GM_DOMINATION 之前,误将 LocalMP 随机战当成联机合作自定义房主;且原生 leave_mp_session(aces.exe 0x17909a0)在 is_mplayer_host() 为真时直接 ret。", - "lighter_options_ruled_out": [ - "仅靠本地服务:按 Esc 弹窗与退局确认均为纯客户端本地界面逻辑,期间不发网络请求。" - ], - "conclusion": "在 onQuitMission 中把房主提示限定为 get_game_mode() != GM_DOMINATION,并在 sendDisconnectMessage 中将 Peer 退房条件收紧为 is_multiplayer() && !is_mplayer_host()。", - "if_not_applied": "按 Esc 点返回基地会弹出「其他玩家将无法完成该任务」的联机房主提示,甚至因 leave_mp_session 空返回而无法退出。" - }, - - "features": ["K-战局任务加载", "M-战后结算"], - "evidence": [ - "2.61.0.37 aces.exe:0x17909a0-0x17909be(leave_mp_session 在 [0x7b83cb0 + 0x60] != 0 时直接跳至返回)、0x17897c0(quit_to_debriefing)。", - "2.61.0.37 gui.vromfs.bin:scripts/flightmenu/flightmenu.nut 第 26-34、228-277 行。" - ], - - "edit": { - "find": " function sendDisconnectMessage() {\r\n broadcastEvent(\"PlayerQuitMission\")\r\n if (is_multiplayer()) {\r\n leave_mp_session()\r\n this.onResumeRaw()\r\n }\r\n else\r\n this.quitToDebriefing()\r\n }\r\n\r\n function quitToDebriefing() {\r\n disableOrders()\r\n quit_to_debriefing()\r\n interrupt_multiplayer(true)\r\n HudBattleLog.reset()\r\n this.onResumeRaw()\r\n }\r\n\r\n function onQuitMission(_obj) {\r\n if (is_offline_version() && !ludeo?.is_running())\r\n return restart_mission()\r\n\r\n if (is_replay_playing()) {\r\n this.quitToDebriefing()\r\n }\r\n else if (get_mission_status() == MISSION_STATUS_RUNNING) {\r\n local text = \"\"\r\n if (is_mplayer_host())\r\n text = loc(\"flightmenu/questionQuitMissionHost\")", - "replace": " function sendDisconnectMessage() {\r\n broadcastEvent(\"PlayerQuitMission\")\r\n if (is_multiplayer() && !is_mplayer_host()) {\r\n leave_mp_session()\r\n this.onResumeRaw()\r\n }\r\n else\r\n this.quitToDebriefing()\r\n }\r\n\r\n function quitToDebriefing() {\r\n disableOrders()\r\n quit_to_debriefing()\r\n interrupt_multiplayer(true)\r\n HudBattleLog.reset()\r\n this.onResumeRaw()\r\n }\r\n\r\n function onQuitMission(_obj) {\r\n if (is_offline_version() && !ludeo?.is_running())\r\n return restart_mission()\r\n\r\n if (is_replay_playing()) {\r\n this.quitToDebriefing()\r\n }\r\n else if (get_mission_status() == MISSION_STATUS_RUNNING) {\r\n local text = \"\"\r\n if (is_mplayer_host() && get_game_mode() != GM_DOMINATION)\r\n text = loc(\"flightmenu/questionQuitMissionHost\")" - } -} diff --git a/gui-patches/battle/quit-local-host-to-debriefing/patch.jsonc b/gui-patches/battle/quit-local-host-to-debriefing/patch.jsonc new file mode 100644 index 0000000..a099f0b --- /dev/null +++ b/gui-patches/battle/quit-local-host-to-debriefing/patch.jsonc @@ -0,0 +1,19 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/quit-local-host-to-debriefing", + "title": "局内菜单在本地多人主机模式下显示常规随机战退局提示并直接进入战后结算", + "file": "scripts/flightmenu/flightmenu.nut", + "features": [ + "K-战局任务加载", + "M-战后结算" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/quit-local-host-to-debriefing/replace.nut b/gui-patches/battle/quit-local-host-to-debriefing/replace.nut new file mode 100644 index 0000000..a0b7d5e --- /dev/null +++ b/gui-patches/battle/quit-local-host-to-debriefing/replace.nut @@ -0,0 +1,29 @@ + function sendDisconnectMessage() { + broadcastEvent("PlayerQuitMission") + if (is_multiplayer() && !is_mplayer_host()) { + leave_mp_session() + this.onResumeRaw() + } + else + this.quitToDebriefing() + } + + function quitToDebriefing() { + disableOrders() + quit_to_debriefing() + interrupt_multiplayer(true) + HudBattleLog.reset() + this.onResumeRaw() + } + + function onQuitMission(_obj) { + if (is_offline_version() && !ludeo?.is_running()) + return restart_mission() + + if (is_replay_playing()) { + this.quitToDebriefing() + } + else if (get_mission_status() == MISSION_STATUS_RUNNING) { + local text = "" + if (is_mplayer_host() && get_game_mode() != GM_DOMINATION) + text = loc("flightmenu/questionQuitMissionHost") diff --git a/gui-patches/battle/ready-local-host-respawn/find.nut b/gui-patches/battle/ready-local-host-respawn/find.nut new file mode 100644 index 0000000..a9446d7 --- /dev/null +++ b/gui-patches/battle/ready-local-host-respawn/find.nut @@ -0,0 +1,24 @@ +g_mis_loading_state.isReadyToShowRespawn <- function isReadyToShowRespawn() { + return (getCurState() & MIS_LOAD.RESPAWN_DATA_LOADED) == MIS_LOAD.RESPAWN_DATA_LOADED +} + +g_mis_loading_state.isCrewsListReceived <- function isCrewsListReceived() { + return (getCurState() & MIS_LOAD.ECONOMIC_STATE) != 0 +} + +g_mis_loading_state.onEventUpdateEsFromHost <- function onEventUpdateEsFromHost(_p) { + if (getCurState() & MIS_LOAD.ECONOMIC_STATE) + return + + log("misLoadState: received initial economicState") + setCurState(getCurState() | MIS_LOAD.ECONOMIC_STATE) + this.checkRespawnBases() +} + +g_mis_loading_state.onEventLoadingStateChange <- function onEventLoadingStateChange(_p) { + if (!isInFlight()) { + if (getCurState() != 0) + log("misLoadState: reset mision loading state") + setCurState(0) + } +} diff --git a/gui-patches/battle/ready-local-host-respawn/patch.json b/gui-patches/battle/ready-local-host-respawn/patch.json deleted file mode 100644 index 5ddeb21..0000000 --- a/gui-patches/battle/ready-local-host-respawn/patch.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "id": "battle/ready-local-host-respawn", - "title": "本地多人主机模式下自动置位战局经济与出生点就绪状态以打开乘员组重生面板", - "file": "scripts/respawn/misloadingstate.nut", - - "program_behaviour": { - "stock": "misloadingstate.nut 一直等待远程专用对战服发来 0xb0b7 数据包触发 on_update_es_from_host 事件后才置位 MIS_LOAD.ECONOMIC_STATE 并检查出生点;在 LocalMP 本地主机下没有远程包下发,导致 isReadyToShowRespawn() 恒为 false,界面一直卡在「等待服务器返回数据...」与「等待乘员组的相关数据...」。", - "patched": "当处于局内本地多人主机(isInFlight() && is_mplayer_host())时,立即置位 MIS_LOAD.ECONOMIC_STATE(本地档案与 wasReadySlots 掩码已在内存中就绪),并在出生点激活后置位 MIS_LOAD.RESPAWN_BASES、触发 ChangedMissionRespawnBasesStatus 刷新重生界面。" - }, - - "derivation": { - "requirement": "Display the crew slotbar, tactical map, spawn points, and spawn button immediately upon entering a LocalMP battle.", - "cause": "on_update_es_from_host 仅在客户端收到远程对战服网络同步包(0x5c7146 / 0xb0b7)时广播;LocalMP 主机(is_mplayer_host() == true)自身即为权威端,不会给自己发 Peer 同步包,且对称遭遇战(CTA)出生点在任务加载后约 1 秒激活。", - "lighter_options_ruled_out": [ - "仅靠本地服务:战局内重生界面状态机纯属客户端内存状态,对局加载期间不请求 HTTP/TCP 本地服务。" - ], - "conclusion": "在 misloadingstate.nut 中为本地多人主机补齐 ECONOMIC_STATE 置位与出生点就绪复核。", - "if_not_applied": "进入对局后卡在观战镜头顶栏「等待服务器返回数据...」,打开重生面板一直显示「等待乘员组的相关数据...」,无法选车出击。" - }, - - "features": ["K-战局任务加载"], - "evidence": [ - "2.61.0.37 aces.exe:0x5acce6(MPlayer.wasReadySlots 默认初始化为 0xffffffff)、0x5c7146(远程同步路径触发 on_update_es_from_host)。", - "2.61.0.37 gui.vromfs.bin:scripts/respawn/misloadingstate.nut 第 12-90 行,scripts/respawn/respawn.nut 第 701-705、836-844、996-1006 行。" - ], - - "edit": { - "find": "g_mis_loading_state.isReadyToShowRespawn <- function isReadyToShowRespawn() {\r\n return (getCurState() & MIS_LOAD.RESPAWN_DATA_LOADED) == MIS_LOAD.RESPAWN_DATA_LOADED\r\n}\r\n\r\ng_mis_loading_state.isCrewsListReceived <- function isCrewsListReceived() {\r\n return (getCurState() & MIS_LOAD.ECONOMIC_STATE) != 0\r\n}\r\n\r\ng_mis_loading_state.onEventUpdateEsFromHost <- function onEventUpdateEsFromHost(_p) {\r\n if (getCurState() & MIS_LOAD.ECONOMIC_STATE)\r\n return\r\n\r\n log(\"misLoadState: received initial economicState\")\r\n setCurState(getCurState() | MIS_LOAD.ECONOMIC_STATE)\r\n this.checkRespawnBases()\r\n}\r\n\r\ng_mis_loading_state.onEventLoadingStateChange <- function onEventLoadingStateChange(_p) {\r\n if (!isInFlight()) {\r\n if (getCurState() != 0)\r\n log(\"misLoadState: reset mision loading state\")\r\n setCurState(0)\r\n }\r\n}", - "replace": "function syncWtoLocalHostLoadingState() {\r\n if (!isInFlight() || !require(\"multiplayer\").is_mplayer_host())\r\n return\r\n if (!(getCurState() & MIS_LOAD.ECONOMIC_STATE))\r\n setCurState(getCurState() | MIS_LOAD.ECONOMIC_STATE)\r\n if (!(getCurState() & MIS_LOAD.RESPAWN_BASES)) {\r\n g_mis_loading_state.checkRespawnBases()\r\n if (getCurState() & MIS_LOAD.RESPAWN_BASES)\r\n require(\"dagor.workcycle\").defer(@() broadcastEvent(\"ChangedMissionRespawnBasesStatus\"))\r\n }\r\n}\r\n\r\ng_mis_loading_state.isReadyToShowRespawn <- function isReadyToShowRespawn() {\r\n syncWtoLocalHostLoadingState()\r\n return (getCurState() & MIS_LOAD.RESPAWN_DATA_LOADED) == MIS_LOAD.RESPAWN_DATA_LOADED\r\n}\r\n\r\ng_mis_loading_state.isCrewsListReceived <- function isCrewsListReceived() {\r\n syncWtoLocalHostLoadingState()\r\n return (getCurState() & MIS_LOAD.ECONOMIC_STATE) != 0\r\n}\r\n\r\ng_mis_loading_state.onEventUpdateEsFromHost <- function onEventUpdateEsFromHost(_p) {\r\n if (getCurState() & MIS_LOAD.ECONOMIC_STATE)\r\n return\r\n\r\n log(\"misLoadState: received initial economicState\")\r\n setCurState(getCurState() | MIS_LOAD.ECONOMIC_STATE)\r\n this.checkRespawnBases()\r\n}\r\n\r\ng_mis_loading_state.onEventLoadingStateChange <- function onEventLoadingStateChange(_p) {\r\n if (!isInFlight()) {\r\n if (getCurState() != 0)\r\n log(\"misLoadState: reset mision loading state\")\r\n setCurState(0)\r\n }\r\n else\r\n syncWtoLocalHostLoadingState()\r\n}" - } -} diff --git a/gui-patches/battle/ready-local-host-respawn/patch.jsonc b/gui-patches/battle/ready-local-host-respawn/patch.jsonc new file mode 100644 index 0000000..a252aa4 --- /dev/null +++ b/gui-patches/battle/ready-local-host-respawn/patch.jsonc @@ -0,0 +1,18 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/ready-local-host-respawn", + "title": "本地多人主机模式下自动置位战局经济与出生点就绪状态以打开乘员组重生面板", + "file": "scripts/respawn/misloadingstate.nut", + "features": [ + "K-战局任务加载" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/ready-local-host-respawn/replace.nut b/gui-patches/battle/ready-local-host-respawn/replace.nut new file mode 100644 index 0000000..cc93c1c --- /dev/null +++ b/gui-patches/battle/ready-local-host-respawn/replace.nut @@ -0,0 +1,40 @@ +function syncWtoLocalHostLoadingState() { + if (!isInFlight() || !require("multiplayer").is_mplayer_host()) + return + if (!(getCurState() & MIS_LOAD.ECONOMIC_STATE)) + setCurState(getCurState() | MIS_LOAD.ECONOMIC_STATE) + if (!(getCurState() & MIS_LOAD.RESPAWN_BASES)) { + g_mis_loading_state.checkRespawnBases() + if (getCurState() & MIS_LOAD.RESPAWN_BASES) + require("dagor.workcycle").defer(@() broadcastEvent("ChangedMissionRespawnBasesStatus")) + } +} + +g_mis_loading_state.isReadyToShowRespawn <- function isReadyToShowRespawn() { + syncWtoLocalHostLoadingState() + return (getCurState() & MIS_LOAD.RESPAWN_DATA_LOADED) == MIS_LOAD.RESPAWN_DATA_LOADED +} + +g_mis_loading_state.isCrewsListReceived <- function isCrewsListReceived() { + syncWtoLocalHostLoadingState() + return (getCurState() & MIS_LOAD.ECONOMIC_STATE) != 0 +} + +g_mis_loading_state.onEventUpdateEsFromHost <- function onEventUpdateEsFromHost(_p) { + if (getCurState() & MIS_LOAD.ECONOMIC_STATE) + return + + log("misLoadState: received initial economicState") + setCurState(getCurState() | MIS_LOAD.ECONOMIC_STATE) + this.checkRespawnBases() +} + +g_mis_loading_state.onEventLoadingStateChange <- function onEventLoadingStateChange(_p) { + if (!isInFlight()) { + if (getCurState() != 0) + log("misLoadState: reset mision loading state") + setCurState(0) + } + else + syncWtoLocalHostLoadingState() +} diff --git a/gui-patches/battle/report-local-battle-settlement/find.nut b/gui-patches/battle/report-local-battle-settlement/find.nut new file mode 100644 index 0000000..4ad0295 --- /dev/null +++ b/gui-patches/battle/report-local-battle-settlement/find.nut @@ -0,0 +1,3 @@ +function guiStartDebriefingFull(params = {}) { + loadHandler(get_gui_handler("DebriefingModal"), params) +} diff --git a/gui-patches/battle/report-local-battle-settlement/patch.json b/gui-patches/battle/report-local-battle-settlement/patch.json deleted file mode 100644 index 9519c66..0000000 --- a/gui-patches/battle/report-local-battle-settlement/patch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "battle/report-local-battle-settlement", - "title": "Report LocalMP debriefing statistics to local-service before opening DebriefingModal", - "file": "scripts/debriefing/debriefingmodal.nut", - "reason": "Hydrate and scale only explicit additive stat_get_exp reward categories (never expBefore, expAfter, or *F float duplicates), forward full per-unit reward breakdowns to cln_wto_finish_battle, and attach the resulting EULT_SESSION_RESULT userlog to DebriefingModal.", - "features": ["battle-rewards", "post-battle-settlement"], - "edit": { - "find": "function guiStartDebriefingFull(params = {}) {\r\n loadHandler(get_gui_handler(\"DebriefingModal\"), params)\r\n}", - "replace": "let WTO_ADDITIVE_REWARD_CATS = [\r\n \"AirKills\", \"GroundKills\", \"HumanKills\", \"NavalKills\",\r\n \"Landings\", \"Takeoffs\", \"Captures\", \"Destruction\", \"Damage\",\r\n \"Critical\", \"Hit\", \"Assist\", \"BattleTime\", \"Mission\",\r\n \"MissionObjective\", \"Race\", \"Scout\", \"ScoutCriticalHit\",\r\n \"ScoutKill\", \"ScoutKillUnknown\", \"Unlocks\", \"AwardDamage\",\r\n \"TimedAward\", \"AirSevereDamage\", \"ShipSevereDamage\",\r\n \"MissileEvade\", \"ShellInterception\", \"SectorCapture\",\r\n \"SuppliesDelivery\", \"SuppliesReturn\", \"SuppliesDestroy\", \"SuppliesEscort\"\r\n]\r\n\r\nlet WTO_MAIL_REWARD_CATS = [\r\n \"AirKills\", \"GroundKills\", \"NavalKills\", \"HumanKills\",\r\n \"Assist\", \"AirSevereDamage\", \"ShipSevereDamage\", \"Critical\",\r\n \"Hit\", \"Captures\", \"SectorCapture\", \"Destruction\", \"Damage\",\r\n \"Scout\", \"ScoutCriticalHit\", \"ScoutKill\", \"ScoutKillUnknown\",\r\n \"Takeoffs\", \"Landings\", \"MissileEvade\", \"ShellInterception\",\r\n \"TimedAward\", \"Unlocks\", \"BattleTime\",\r\n \"SuppliesDelivery\", \"SuppliesReturn\", \"SuppliesDestroy\", \"SuppliesEscort\"\r\n]\r\n\r\nlet WTO_SCALABLE_EXTRA_EXP_KEYS = [\r\n \"expTotal\", \"expFree\", \"expScouting\", \"expSkillBonus\", \"expSkillBonusTotal\",\r\n \"expModsTotal\", \"expUnitTotal\", \"expInvestModule\", \"expInvestModuleTotal\",\r\n \"expInvestUnit\", \"expInvestUnitTotal\"\r\n]\r\n\r\nfunction hydrateWtoContainerTotals(tbl, isUnitTbl) {\r\n if (!u.isTable(tbl))\r\n return\r\n local wpSum = 0\r\n local expSum = 0\r\n foreach (cat in WTO_ADDITIVE_REWARD_CATS) {\r\n if (!isUnitTbl && cat == \"Race\")\r\n continue\r\n let wpVal = tbl?[$\"wp{cat}\"]\r\n if (is_numeric(wpVal) && wpVal > 0)\r\n wpSum += wpVal.tointeger()\r\n let expVal = tbl?[$\"exp{cat}\"]\r\n if (is_numeric(expVal) && expVal > 0)\r\n expSum += expVal.tointeger()\r\n }\r\n let tblTotal = tbl?.tblTotal\r\n if ((tbl?.wpTotal ?? 0) <= 0) {\r\n let fallbackWp = (tblTotal?.noBonusWp ?? 0).tointeger()\r\n tbl.wpTotal <- wpSum > fallbackWp ? wpSum : fallbackWp\r\n }\r\n if ((tbl?.expTotal ?? 0) <= 0) {\r\n let fallbackExp = (tblTotal?.noBonusExp ?? 0).tointeger()\r\n tbl.expTotal <- expSum > fallbackExp ? expSum : fallbackExp\r\n }\r\n}\r\n\r\nfunction ensureWtoDebriefingTotals(cur) {\r\n if (!u.isTable(cur?.exp))\r\n return\r\n hydrateWtoContainerTotals(cur.exp, false)\r\n foreach (_u, airData in (cur.exp?.aircrafts ?? {}))\r\n hydrateWtoContainerTotals(airData, true)\r\n}\r\n\r\nfunction writeWtoRewardCategories(dstBlk, srcTbl) {\r\n if (!u.isTable(srcTbl))\r\n return\r\n local catsBlk = null\r\n foreach (cat in WTO_MAIL_REWARD_CATS) {\r\n let tblRow = srcTbl?[$\"tbl{cat}\"]\r\n let countVal = (srcTbl?[$\"num{cat}\"] ?? tblRow?.count ?? 0).tointeger()\r\n let wpVal = (srcTbl?[$\"wp{cat}\"] ?? tblRow?.noBonusWp ?? 0).tointeger()\r\n let expVal = (srcTbl?[$\"exp{cat}\"] ?? tblRow?.noBonusExp ?? 0).tointeger()\r\n if (countVal <= 0 && wpVal <= 0 && expVal <= 0)\r\n continue\r\n if (catsBlk == null)\r\n catsBlk = dstBlk.addNewBlock(\"rewards\")\r\n let cBlk = catsBlk.addNewBlock(cat)\r\n cBlk.count = countVal\r\n cBlk.wp = wpVal\r\n cBlk.exp = expVal\r\n }\r\n}\r\n\r\nfunction buildWtoFinishBattleBlk(wtoBattle, res) {\r\n ensureWtoDebriefingTotals(res)\r\n let guiMis = require(\"guiMission\")\r\n let exp = res?.exp ?? {}\r\n let mStatus = guiMis.get_mission_status()\r\n let expRes = exp?.result\r\n let outcome = (mStatus == guiMis.MISSION_STATUS_SUCCESS || expRes == STATS_RESULT_SUCCESS || res?.isSucceed == true) ? \"win\"\r\n : (mStatus == guiMis.MISSION_STATUS_FAIL || expRes == STATS_RESULT_FAIL || res?.state == guiMis.MISSION_STATUS_FAIL) ? \"lose\"\r\n : \"running\"\r\n local teamAKills = 0\r\n local teamBKills = 0\r\n foreach (p in (res?.mplayers_list ?? [])) {\r\n let k = (p?.kills ?? 0) + (p?.groundKills ?? 0) + (p?.navalKills ?? 0)\r\n if (p?.team == 2)\r\n teamBKills += k\r\n else if (p?.team == 1)\r\n teamAKills += k\r\n }\r\n let blk = DataBlock()\r\n blk.sessionId = wtoBattle.sessionId\r\n blk.country = (wtoBattle?.country ?? \"\") != \"\" ? wtoBattle.country : (res?.country ?? \"\")\r\n blk.outcome = outcome\r\n blk.localTeam = (res?.localTeam ?? 1).tointeger()\r\n blk.teamAScore = (res?.mpTblTeams?[0]?.score ?? 0).tointeger()\r\n blk.teamBScore = (res?.mpTblTeams?[1]?.score ?? 0).tointeger()\r\n blk.teamAKills = teamAKills.tointeger()\r\n blk.teamBKills = teamBKills.tointeger()\r\n blk.wpTotal = (exp?.wpTotal ?? 0).tointeger()\r\n blk.expTotal = (exp?.expTotal ?? 0).tointeger()\r\n blk.expFree = (exp?.expFree ?? 0).tointeger()\r\n blk.wpMission = (exp?.wpMission ?? 0).tointeger()\r\n blk.wpTeamKills = (exp?.wpTeamKills ?? exp?.wpFriendlyKills ?? 0).tointeger()\r\n blk.expSkillBonusTotal = (exp?.expSkillBonusTotal ?? 0).tointeger()\r\n blk.expSkillBonusLevel = (exp?.expSkillBonusLevel ?? 0).tointeger()\r\n blk.activity = (exp?.activity ?? 0.0).tofloat()\r\n blk.sessionTime = (exp?.sessionTime ?? 0.0).tofloat()\r\n blk.battleTime = (exp?.battleTime ?? 0.0).tofloat()\r\n writeWtoRewardCategories(blk, exp)\r\n let usedSpares = wtoBattle?.usedSpares\r\n if (u.isTable(usedSpares) && usedSpares.len() > 0) {\r\n let spBlk = blk.addNewBlock(\"spares\")\r\n foreach (spUnit, spCnt in usedSpares)\r\n if (spUnit != \"\" && is_numeric(spCnt) && spCnt > 0)\r\n spBlk[spUnit] = spCnt.tointeger()\r\n }\r\n let vehiclesBlk = blk.addNewBlock(\"vehicles\")\r\n foreach (unitName, airData in (exp?.aircrafts ?? {})) {\r\n let uBlk = vehiclesBlk.addNewBlock(unitName)\r\n uBlk.wpTotal = (airData?.wpTotal ?? 0).tointeger()\r\n uBlk.expTotal = (airData?.expTotal ?? 0).tointeger()\r\n uBlk.expModsTotal = (airData?.expInvestModuleTotal ?? 0).tointeger()\r\n uBlk.expUnitTotal = (airData?.expInvestUnitTotal ?? 0).tointeger()\r\n uBlk.wpMission = (airData?.wpMission ?? 0).tointeger()\r\n uBlk.expSkillBonusTotal = (airData?.expSkillBonusTotal ?? 0).tointeger()\r\n uBlk.expSkillBonusLevel = (airData?.expSkillBonusLevel ?? 0).tointeger()\r\n uBlk.sessionTime = (airData?.sessionTime ?? 0.0).tofloat()\r\n uBlk.battleTime = (airData?.battleTime ?? 0.0).tofloat()\r\n writeWtoRewardCategories(uBlk, airData)\r\n }\r\n return blk\r\n}\r\n\r\nfunction scaleWtoPositiveField(tbl, key, mul) {\r\n if ((key in tbl) && is_numeric(tbl[key]) && tbl[key] > 0)\r\n tbl[key] = (tbl[key] * mul + 0.5).tointeger()\r\n}\r\n\r\nfunction scaleWtoStatContainer(tbl, slMul, rpMul) {\r\n if (!u.isTable(tbl))\r\n return\r\n if (slMul != 1.0) {\r\n foreach (cat in WTO_ADDITIVE_REWARD_CATS)\r\n scaleWtoPositiveField(tbl, $\"wp{cat}\", slMul)\r\n scaleWtoPositiveField(tbl, \"wpScouting\", slMul)\r\n scaleWtoPositiveField(tbl, \"wpTotal\", slMul)\r\n }\r\n if (rpMul != 1.0) {\r\n foreach (cat in WTO_ADDITIVE_REWARD_CATS)\r\n scaleWtoPositiveField(tbl, $\"exp{cat}\", rpMul)\r\n foreach (eKey in WTO_SCALABLE_EXTRA_EXP_KEYS)\r\n scaleWtoPositiveField(tbl, eKey, rpMul)\r\n foreach (k, _v in tbl)\r\n if (k.len() > 13 && k.slice(0, 13) == \"expInvestUnit\" && !k.endswith(\"Name\"))\r\n scaleWtoPositiveField(tbl, k, rpMul)\r\n }\r\n foreach (k, val in tbl) {\r\n if (k.len() >= 4 && k.slice(0, 3) == \"tbl\" && !k.endswith(\"F\") && u.isTable(val)) {\r\n foreach (subKey, _sv in val) {\r\n if (slMul != 1.0 && subKey.endswith(\"Wp\"))\r\n scaleWtoPositiveField(val, subKey, slMul)\r\n else if (rpMul != 1.0 && subKey.endswith(\"Exp\"))\r\n scaleWtoPositiveField(val, subKey, rpMul)\r\n }\r\n }\r\n }\r\n}\r\n\r\nfunction scaleWtoDebriefingMultipliers(cur, slMul, rpMul) {\r\n if (slMul == 1.0 && rpMul == 1.0)\r\n return\r\n scaleWtoStatContainer(cur.exp, slMul, rpMul)\r\n foreach (_u, airData in (cur.exp?.aircrafts ?? {}))\r\n scaleWtoStatContainer(airData, slMul, rpMul)\r\n}\r\n\r\nfunction applyWtoSettledDebriefing(wtoBattle) {\r\n let debrFull = require(\"%scripts/debriefing/debriefingFull.nut\")\r\n let cur = getDebriefingResult()\r\n if (cur == null)\r\n return\r\n ensureWtoDebriefingTotals(cur)\r\n let evObj = events.getEvent(wtoBattle?.modeName ?? \"\")\r\n if (evObj != null && cur.roomEvent == null)\r\n cur.roomEvent = {\r\n name = evObj?.name\r\n economicName = evObj?.economicName\r\n difficulty = evObj?.difficulty\r\n chapter = evObj?.chapter\r\n gameModeId = evObj?.gameModeId\r\n }\r\n let sessionLogs = getUserLogsList({ show = [EULT_SESSION_RESULT], disableVisible = true })\r\n let matched = sessionLogs.findvalue(@(l) l?.wtoSessionId == wtoBattle.sessionId)\r\n if (matched == null)\r\n return\r\n let others = (cur?.roomUserlogs ?? []).filter(@(l) l?.type != EULT_SESSION_RESULT)\r\n cur.roomUserlogs = [matched].extend(others)\r\n let isWin = matched?.win ?? false\r\n cur.isSucceed = isWin\r\n if ((cur.exp?.result ?? STATS_RESULT_IN_PROGRESS) == STATS_RESULT_IN_PROGRESS)\r\n cur.exp.result <- isWin ? STATS_RESULT_SUCCESS : STATS_RESULT_FAIL\r\n scaleWtoDebriefingMultipliers(cur, (matched?.wtoSlMul ?? 1.0).tofloat(), (matched?.wtoRpMul ?? 1.0).tofloat())\r\n debrFull.recountDebriefingResult()\r\n}\r\n\r\nfunction settleWtoBattleAndOpen(wtoBattle, params) {\r\n let { charSendBlk } = require(\"chard\")\r\n let { addTask } = require(\"%scripts/tasker.nut\")\r\n if (getDebriefingResult() == null)\r\n gatherDebriefingResult()\r\n let blk = buildWtoFinishBattleBlk(wtoBattle, getDebriefingResult())\r\n let openModal = function() {\r\n updateGamercards()\r\n loadHandler(get_gui_handler(\"DebriefingModal\"), params)\r\n }\r\n let onSuccess = function() {\r\n try {\r\n applyWtoSettledDebriefing(wtoBattle)\r\n } catch (e) {\r\n log($\"[WTO] applyWtoSettledDebriefing error: {e}\")\r\n }\r\n openModal()\r\n }\r\n let taskId = charSendBlk(\"cln_wto_finish_battle\", blk)\r\n if (taskId < 0 || !addTask(taskId, { showProgressBox = true }, onSuccess, @(_) openModal()))\r\n openModal()\r\n}\r\n\r\nfunction guiStartDebriefingFull(params = {}) {\r\n let { ndbTryRead, ndbDelete } = require(\"nestdb\")\r\n let wtoBattle = ndbTryRead([\"wto\", \"activeBattle\"])\r\n if (wtoBattle != null) {\r\n ndbDelete([\"wto\", \"activeBattle\"])\r\n if (getDebriefingResult() == null)\r\n gatherDebriefingResult()\r\n let curMis = getDebriefingResult()?.missionName ?? \"\"\r\n let expectedMis = wtoBattle?.missionName ?? \"\"\r\n if (get_game_mode() == GM_DOMINATION && (expectedMis == \"\" || curMis == expectedMis)) {\r\n settleWtoBattleAndOpen(wtoBattle, params)\r\n return\r\n }\r\n }\r\n loadHandler(get_gui_handler(\"DebriefingModal\"), params)\r\n}" - } -} diff --git a/gui-patches/battle/report-local-battle-settlement/patch.jsonc b/gui-patches/battle/report-local-battle-settlement/patch.jsonc new file mode 100644 index 0000000..25beb8b --- /dev/null +++ b/gui-patches/battle/report-local-battle-settlement/patch.jsonc @@ -0,0 +1,19 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/report-local-battle-settlement", + "title": "Report LocalMP debriefing statistics to local-service before opening DebriefingModal", + "file": "scripts/debriefing/debriefingmodal.nut", + "features": [ + "battle-rewards", + "post-battle-settlement" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/report-local-battle-settlement/replace.nut b/gui-patches/battle/report-local-battle-settlement/replace.nut new file mode 100644 index 0000000..dbd0cff --- /dev/null +++ b/gui-patches/battle/report-local-battle-settlement/replace.nut @@ -0,0 +1,254 @@ +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) + let guiMis = require("guiMission") + let exp = res?.exp ?? {} + 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.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 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) + } + 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) + return + ensureWtoDebriefingTotals(cur) + let evObj = events.getEvent(wtoBattle?.modeName ?? "") + if (evObj != null && cur.roomEvent == null) + cur.roomEvent = { + name = evObj?.name + economicName = evObj?.economicName + difficulty = evObj?.difficulty + 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}") + } + openModal() + } + let taskId = charSendBlk("cln_wto_finish_battle", blk) + if (taskId < 0 || !addTask(taskId, { showProgressBox = true }, onSuccess, @(_) openModal())) + openModal() +} + +function guiStartDebriefingFull(params = {}) { + let { ndbTryRead, ndbDelete } = require("nestdb") + let wtoBattle = ndbTryRead(["wto", "activeBattle"]) + if (wtoBattle != null) { + ndbDelete(["wto", "activeBattle"]) + if (getDebriefingResult() == null) + gatherDebriefingResult() + let curMis = getDebriefingResult()?.missionName ?? "" + let expectedMis = wtoBattle?.missionName ?? "" + if (get_game_mode() == GM_DOMINATION && (expectedMis == "" || curMis == expectedMis)) { + settleWtoBattleAndOpen(wtoBattle, params) + return + } + } + loadHandler(get_gui_handler("DebriefingModal"), params) +} diff --git a/gui-patches/battle/scoreboard-team-country-flags/find.nut b/gui-patches/battle/scoreboard-team-country-flags/find.nut new file mode 100644 index 0000000..43bb440 --- /dev/null +++ b/gui-patches/battle/scoreboard-team-country-flags/find.nut @@ -0,0 +1,5 @@ + let country = useOperatorFlagsInBattle ? unit.getOperatorCountry() : getCountryOverride(getUnitCountry(unit)) + u.appendOnce(getCountryFlagSubstitute(country), countries, true) + } + return countries + } diff --git a/gui-patches/battle/scoreboard-team-country-flags/patch.json b/gui-patches/battle/scoreboard-team-country-flags/patch.json deleted file mode 100644 index 6efa3f9..0000000 --- a/gui-patches/battle/scoreboard-team-country-flags/patch.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "id": "battle/scoreboard-team-country-flags", - "title": "开局倒计时载具尚未生成前从房间国家配置回退渲染计分板双方参战国旗", - "file": "scripts/statistics/mpstatistics.nut", - - "program_behaviour": { - "stock": "MPStatistics.getCountriesByTeam(team) 只遍历本队已生成载具(ownedUnitName / aircraftName 非空)的成员来汇总参战国旗;开局首秒全体成员尚处于待出击伞兵状态时返回空数组,导致顶栏国旗区空白直至首批载具落地且 3 秒刷新周期到达。", - "patched": "当已出击成员汇总列表为空时,回退读取当前房间会话配置的 country_allies / country_axis 列表并经 getCountryFlagSubstitute 转换,使重生界面与计分板从第 0 帧起即稳定显示双方参战国家国旗;载具出击后仍按原版实时载具所属国汇总。" - }, - - "derivation": { - "requirement": "Display participating nation flags on the scoreboard and respawn header immediately upon entering a battle, before AI bots or the player spawn their first vehicles.", - "cause": "mpstatistics.nut 第 972-988 行 getCountriesByTeam(team) 仅从 getMplayersList(team) 成员的已生成载具反查国籍;在 isTeamsWithCountryFlags 为真时 teamIco 已被置为 null,若此时无人完成首次出击则国旗区完全为空。", - "lighter_options_ruled_out": [ - "仅靠本地服务:getCountriesByTeam 为纯客户端统计面板方法,在无人出击时不读取房间 country_allies / country_axis 字段。" - ], - "conclusion": "在 getCountriesByTeam 末尾当 countries 为空时回退读取 getSessionLobbyPublicParam 内的队伍国家数组。", - "if_not_applied": "开局选车阶段打开计分板或查看顶栏时,在首批载具生成前的数秒内阵营国旗位显示空白。" - }, - - "features": ["K-战局任务加载"], - "evidence": [ - "2.61.0.37 gui.vromfs.bin:scripts/statistics/mpstatistics.nut 第 288-291、930-989 行,scripts/matchingRooms/sessionLobbyState.nut 第 222-226 行(getSessionLobbyPublicParam)。" - ], - - "edit": { - "find": " let country = useOperatorFlagsInBattle ? unit.getOperatorCountry() : getCountryOverride(getUnitCountry(unit))\r\n u.appendOnce(getCountryFlagSubstitute(country), countries, true)\r\n }\r\n return countries\r\n }", - "replace": " let country = useOperatorFlagsInBattle ? unit.getOperatorCountry() : getCountryOverride(getUnitCountry(unit))\r\n u.appendOnce(getCountryFlagSubstitute(country), countries, true)\r\n }\r\n if (countries.len() == 0) {\r\n let roomKey = team == Team.B ? \"country_axis\" : \"country_allies\"\r\n foreach (country in getSessionLobbyPublicParam(roomKey, []))\r\n u.appendOnce(getCountryFlagSubstitute(getCountryOverride(country)), countries, true)\r\n }\r\n return countries\r\n }" - } -} diff --git a/gui-patches/battle/scoreboard-team-country-flags/patch.jsonc b/gui-patches/battle/scoreboard-team-country-flags/patch.jsonc new file mode 100644 index 0000000..ede2123 --- /dev/null +++ b/gui-patches/battle/scoreboard-team-country-flags/patch.jsonc @@ -0,0 +1,18 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/scoreboard-team-country-flags", + "title": "开局倒计时载具尚未生成前从房间国家配置回退渲染计分板双方参战国旗", + "file": "scripts/statistics/mpstatistics.nut", + "features": [ + "K-战局任务加载" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/scoreboard-team-country-flags/replace.nut b/gui-patches/battle/scoreboard-team-country-flags/replace.nut new file mode 100644 index 0000000..ec9c7e8 --- /dev/null +++ b/gui-patches/battle/scoreboard-team-country-flags/replace.nut @@ -0,0 +1,10 @@ + let country = useOperatorFlagsInBattle ? unit.getOperatorCountry() : getCountryOverride(getUnitCountry(unit)) + u.appendOnce(getCountryFlagSubstitute(country), countries, true) + } + if (countries.len() == 0) { + let roomKey = team == Team.B ? "country_axis" : "country_allies" + foreach (country in getSessionLobbyPublicParam(roomKey, [])) + u.appendOnce(getCountryFlagSubstitute(getCountryOverride(country)), countries, true) + } + return countries + } diff --git a/gui-patches/battle/stabilize-respawn-countdown-button/find.nut b/gui-patches/battle/stabilize-respawn-countdown-button/find.nut new file mode 100644 index 0000000..3e28128 --- /dev/null +++ b/gui-patches/battle/stabilize-respawn-countdown-button/find.nut @@ -0,0 +1,2 @@ + foreach (btnId in this.mainButtonsId) { + let buttonSelectObj = setColoredDoubleTextToButton(this.scene.findObject("nav-help"), btnId, this.applyText) diff --git a/gui-patches/battle/stabilize-respawn-countdown-button/patch.json b/gui-patches/battle/stabilize-respawn-countdown-button/patch.json deleted file mode 100644 index e35d8c4..0000000 --- a/gui-patches/battle/stabilize-respawn-countdown-button/patch.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "id": "battle/stabilize-respawn-countdown-button", - "title": "开局倒计时期间保持重生主按钮同步显示剩余秒数避免与「取消」来回闪烁", - "file": "scripts/respawn/respawn.nut", - - "program_behaviour": { - "stock": "开局 15 秒准备倒计时内,玩家点击「加入战斗!」进入等待出击状态(isApplyPressed == true && readyForRespawn == true)后,onUpdate 每帧调用 updateCountdown(countdown) 将主按钮设为「取消 (15秒)」,而任务自定义状态事件 MissionCustomStateChanged 高频触发 checkUpdateCustomStateRespawns() -> updateApplyText() 又把同一按钮重置为不带秒数的「取消」,导致右下角按钮在「取消」与「取消 (15秒)」之间高频闪烁。", - "patched": "在 updateApplyText() 刷新底部主按钮(mainButtonsId)时,若处于等待倒计时出击状态且 get_mp_respawn_countdown() > 0,同样拼接「(N秒)」后缀(同时保持 this.applyText 与乘员槽小按钮文案不变),与 updateCountdown() 输出完全一致。" - }, - - "derivation": { - "requirement": "Keep the respawn screen bottom-right cancel button text stable during the match-start countdown without flickering between '取消' and '取消 (15秒)'.", - "cause": "respawn.nut 中 updateApplyText() 直接向 mainButtonsId 写入不带倒计时后缀的 this.applyText(\"取消\"),而 updateCountdown() 向同一组按钮写入拼接了倒计时秒数的 btnText(\"取消 (15秒)\");战局内 MissionCustomStateChanged 每秒触发十余次 updateApplyText(),与 onUpdate 交替覆盖按钮文本。", - "lighter_options_ruled_out": [ - "仅靠本地服务:战局内 UI 刷新完全在客户端重生界面脚本内闭环运行,不经过本地服务。" - ], - "conclusion": "在 respawn.nut 的 updateApplyText() 中对底部主按钮同步附带当前开局倒计时秒数。", - "if_not_applied": "开局 15 秒倒计时等待出击期间,右下角主按钮在「取消」与「取消 (15秒)」之间持续高频跳变。" - }, - - "features": ["K-战局任务加载"], - "evidence": [ - "2.61.0.37 gui.vromfs.bin:scripts/respawn/respawn.nut 第 104、2366-2367、2457-2467、2639-2640、2972-2977、3439-3445 行。" - ], - - "edit": { - "find": " foreach (btnId in this.mainButtonsId) {\r\n let buttonSelectObj = setColoredDoubleTextToButton(this.scene.findObject(\"nav-help\"), btnId, this.applyText)", - "replace": " local mainBtnText = this.applyText\r\n if (!this.stayOnRespScreen && this.readyForRespawn && this.isApplyPressed) {\r\n let countdown = get_mp_respawn_countdown()\r\n if (countdown > 0)\r\n mainBtnText = \"\".concat(mainBtnText, loc(\"ui/parentheses/space\", { text = \"\".concat(countdown, loc(\"mainmenu/seconds\")) }))\r\n }\r\n\r\n foreach (btnId in this.mainButtonsId) {\r\n let buttonSelectObj = setColoredDoubleTextToButton(this.scene.findObject(\"nav-help\"), btnId, mainBtnText)" - } -} diff --git a/gui-patches/battle/stabilize-respawn-countdown-button/patch.jsonc b/gui-patches/battle/stabilize-respawn-countdown-button/patch.jsonc new file mode 100644 index 0000000..9af5f95 --- /dev/null +++ b/gui-patches/battle/stabilize-respawn-countdown-button/patch.jsonc @@ -0,0 +1,18 @@ +// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +{ + "id": "battle/stabilize-respawn-countdown-button", + "title": "开局倒计时期间保持重生主按钮同步显示剩余秒数避免与「取消」来回闪烁", + "file": "scripts/respawn/respawn.nut", + "features": [ + "K-战局任务加载" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/battle/stabilize-respawn-countdown-button/replace.nut b/gui-patches/battle/stabilize-respawn-countdown-button/replace.nut new file mode 100644 index 0000000..6d95296 --- /dev/null +++ b/gui-patches/battle/stabilize-respawn-countdown-button/replace.nut @@ -0,0 +1,9 @@ + local mainBtnText = this.applyText + if (!this.stayOnRespScreen && this.readyForRespawn && this.isApplyPressed) { + let countdown = get_mp_respawn_countdown() + if (countdown > 0) + mainBtnText = "".concat(mainBtnText, loc("ui/parentheses/space", { text = "".concat(countdown, loc("mainmenu/seconds")) })) + } + + foreach (btnId in this.mainButtonsId) { + let buttonSelectObj = setColoredDoubleTextToButton(this.scene.findObject("nav-help"), btnId, mainBtnText) diff --git a/gui-patches/inventory/local-content-public-key/find.nut b/gui-patches/inventory/local-content-public-key/find.nut new file mode 100644 index 0000000..5b55d15 --- /dev/null +++ b/gui-patches/inventory/local-content-public-key/find.nut @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBKDANBgkqhkiG9w0BAQEFAAOCARUAMIIBEAKCAQcAy9WagPn8/uLbbPHebobA +ftDiwrGpi23Ed0fQsSCZfGYupBkYl3mZD3fgOMgmLSYsTqFHDe0CMTQKpHYGFfT3 +EuvTHKwwyo2ckpaLNI/flZysDXRuoWXvwd6FzGBx3l2/I1Yw+cAle/aWB9YZnQtX +fy3j3k/fJfiv7+72Sm95h3Dg715XuBILC4vSYVqvCn+UlQyrJkAZrIahWR9Gzsm6 +ovxSaduvosn83Hx1ZixD+U5wcn1hoTT0niwnrqiPuEUV3wC887JIR4KzMXYpyzvF +nEhlqTKoGN7oGS7vqN4tCH6/l3hAomxfVGT+5UHGugQEauNqccYq44Hfu3t3tY1r +j+eTYc35NQIDAQAB +-----END PUBLIC KEY----- diff --git a/gui-patches/inventory/local-content-public-key/patch.json b/gui-patches/inventory/local-content-public-key/patch.json deleted file mode 100644 index ffceca3..0000000 --- a/gui-patches/inventory/local-content-public-key/patch.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "id": "inventory/local-content-public-key", - "title": "外部库存内容验签公钥替换为本地服务的固定公钥", - "file": "scripts/inventory/inventorycontentsign.nut", - - "program_behaviour": { - "stock": "scripts/inventory/inventoryContentSign.nut 启动时把内置的 Gaijin RSA 公钥通过 inventory.addContentPublicKey(key)(aces.exe 0x459b090)注册到原生 charsq 库存客户端;inventoryClient.nut 请求 GetItemDefsClient 时开启 content_sign_check = true,原生层(0x336d590 -> 0x4e6eba0 -> 0x3c38270)用已注册公钥校验响应头 chardContentSign 与 chardContentSignHashAlgo 对原始响应体的签名。", - "patched": "保持客户端 addContentPublicKey 与 requestWithSignCheck 原生验签流程不变,将 inventoryContentSign.nut 中的公钥替换为本地服务固定密钥对(local-inventory-content.key.pem)对应的 RSA-2048 公钥,本地服务对库存 JSON 响应附带 RSA-SHA256 签名。" - }, - - "derivation": { - "requirement": "功能清单 G「市场」、H「补给箱」「物品回收与合成」「兑换券」。客户端必须通过原生内容签名校验接收本地服务生成的外部物品定义(GetItemDefsClient),使 233 辆交易所载具恢复市场载具状态并显示「在交易所中查找」,同时使外部库存兑换券、补给箱与回收零件定义正常生效。", - "cause": "inventoryContentSign.nut 硬编码了 Gaijin 私钥对应的 RSA 公钥,本地服务没有 Gaijin 的私钥,无法生成能通过原版公钥 EVP_VerifyFinal(0x51e3e80)校验的 chardContentSign 签名;校验失败时 0x40cc070 直接将结果替换为错误 CONTENT_SIGN_VALIDATION_FAILED 并丢弃全部物品定义。", - "lighter_options_ruled_out": [ - "仅在本地服务响应头填占位签名:原生层 0x3c38270 调用 OpenSSL EVP_VerifyFinal 做真实 RSA 验签,无对应私钥返回错误码 6,仍触发 CONTENT_SIGN_VALIDATION_FAILED。", - "改 inventoryClient.nut 跳过 requestWithSignCheck 或打 exe 补丁绕过 0x40cc188:直接破坏客户端原有的验签逻辑;按匹配服务器公钥(online/matching-server-public-key,方案 A)同一原则,替换公钥并由本地服务真实签名更能原样保留客户端原生代码路径。" - ], - "conclusion": "在 gui.vromfs.bin 的 scripts/inventory/inventorycontentsign.nut 将公钥替换为离线版固定 RSA-2048 公钥,本地服务用配对私钥按 chardContentSign + chardContentSignHashAlgo=SHA256 对原始响应体签名。", - "if_not_applied": "每次 GetItemDefsClient 均报 CONTENT_SIGN_VALIDATION_FAILED,客户端外部物品定义表为空,233 辆交易所载具全部退回礼包车显示且右键无「在交易所中查找」,外部库存中的兑换券、银狮补给箱和回收零件无法显示详情与正常使用。" - }, - - "features": ["G-市场", "H-补给箱", "H-物品回收与合成", "H-兑换券"], - "evidence": [ - "2.61.0.37 gui.vromfs.bin:scripts/inventory/inventorycontentsign.nut(keys、inventory.addContentPublicKey)、scripts/inventory/inventoryclient.nut 第 276-288、468 行(requestWithSignCheck、GetItemDefsClient)。", - "2.61.0.37 aces.exe:0x459b090(addContentPublicKey -> 0x4e6e840 PEM_read_bio_PUBKEY + i2d_PUBKEY -> 0x4e6ea30)、0x336f5d0(提取响应头 chardContentSign 与 chardContentSignHashAlgo)、0x336d9ac..0x336da05 -> 0x4e6eba0 -> 0x3c38270(EVP_get_digestbyname + Base64 解码 + EVP_VerifyFinal)、0x40cc070(0x40cc188..0x40cc2e0 校验结果非 1 时报 CONTENT_SIGN_VALIDATION_FAILED)。" - ], - - "edit": { - "find": "-----BEGIN PUBLIC KEY-----\r\nMIIBKDANBgkqhkiG9w0BAQEFAAOCARUAMIIBEAKCAQcAy9WagPn8/uLbbPHebobA\r\nftDiwrGpi23Ed0fQsSCZfGYupBkYl3mZD3fgOMgmLSYsTqFHDe0CMTQKpHYGFfT3\r\nEuvTHKwwyo2ckpaLNI/flZysDXRuoWXvwd6FzGBx3l2/I1Yw+cAle/aWB9YZnQtX\r\nfy3j3k/fJfiv7+72Sm95h3Dg715XuBILC4vSYVqvCn+UlQyrJkAZrIahWR9Gzsm6\r\novxSaduvosn83Hx1ZixD+U5wcn1hoTT0niwnrqiPuEUV3wC887JIR4KzMXYpyzvF\r\nnEhlqTKoGN7oGS7vqN4tCH6/l3hAomxfVGT+5UHGugQEauNqccYq44Hfu3t3tY1r\r\nj+eTYc35NQIDAQAB\r\n-----END PUBLIC KEY-----", - "replace": "-----BEGIN PUBLIC KEY-----\r\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5U86nI/1f8us73a5Tn8K\r\nNjcrWyT6oZzz18uC4eH4LM+VaIJlGvzA0UWMMv8/otX+u8M3wBl/uONv39wc382d\r\neKxTPmo0gWb1cwZ8SeqNUvQJl5HxD0zSPlA2LbQFwoA3aI4nSYcaFV7at7XGph/N\r\nHdYbtSCJei0N7hiqWeeIHcSYjZpmBk5KUs/E+OODquII5liol5LiC9AnvFCVHcT4\r\n1mliTgdHt/LKiLbc0AoVCDHdVMBPEPuZAn9MQJpfIPJdexU8Hzn4xBQ9K2NyISYS\r\n7eRwxratNPdNUHixaw6tyuUCDEV2ELAYw5rwoaFsqP7M76SubBRZObZ8DUgsZZaE\r\nlQIDAQAB\r\n-----END PUBLIC KEY-----" - } -} diff --git a/gui-patches/inventory/local-content-public-key/patch.jsonc b/gui-patches/inventory/local-content-public-key/patch.jsonc new file mode 100644 index 0000000..3c11868 --- /dev/null +++ b/gui-patches/inventory/local-content-public-key/patch.jsonc @@ -0,0 +1,23 @@ +// Replace the inventory content-signing public key with the local service's key; native verification stays on. +// Why the client: the key is hard-coded in the script and the service cannot sign with Gaijin's private key. +// Without it: GetItemDefsClient fails CONTENT_SIGN_VALIDATION_FAILED and every external item definition is dropped. +{ + "id": "inventory/local-content-public-key", + "title": "外部库存内容验签公钥替换为本地服务的固定公钥", + "file": "scripts/inventory/inventorycontentsign.nut", + "features": [ + "G-市场", + "H-补给箱", + "H-物品回收与合成", + "H-兑换券" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/inventory/local-content-public-key/replace.nut b/gui-patches/inventory/local-content-public-key/replace.nut new file mode 100644 index 0000000..6ccbebe --- /dev/null +++ b/gui-patches/inventory/local-content-public-key/replace.nut @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5U86nI/1f8us73a5Tn8K +NjcrWyT6oZzz18uC4eH4LM+VaIJlGvzA0UWMMv8/otX+u8M3wBl/uONv39wc382d +eKxTPmo0gWb1cwZ8SeqNUvQJl5HxD0zSPlA2LbQFwoA3aI4nSYcaFV7at7XGph/N +HdYbtSCJei0N7hiqWeeIHcSYjZpmBk5KUs/E+OODquII5liol5LiC9AnvFCVHcT4 +1mliTgdHt/LKiLbc0AoVCDHdVMBPEPuZAn9MQJpfIPJdexU8Hzn4xBQ9K2NyISYS +7eRwxratNPdNUHixaw6tyuUCDEV2ELAYw5rwoaFsqP7M76SubBRZObZ8DUgsZZaE +lQIDAQAB +-----END PUBLIC KEY----- diff --git a/gui-patches/inventory/show-coupon-redemption-reward/find.nut b/gui-patches/inventory/show-coupon-redemption-reward/find.nut new file mode 100644 index 0000000..ba0030c --- /dev/null +++ b/gui-patches/inventory/show-coupon-redemption-reward/find.nut @@ -0,0 +1,18 @@ + let taskCallback = function() { + let item = findItemByUid(uid) + + + if (item && item.amountByUids[uid] == itemAmountByUid) { + item.amountByUids[uid] -= consumeAmount + item.amount -= consumeAmount + if (item.amountByUids[uid] <= 0) { + inventoryClient.removeItem(uid) + if (item.uids?[0] == uid) + item.uids.remove(0) + } + } + if (cb) + cb({ success = true }) + } + let itemId = this.id + let taskId = char_send_blk("cln_consume_inventory_item", blk) diff --git a/gui-patches/inventory/show-coupon-redemption-reward/patch.json b/gui-patches/inventory/show-coupon-redemption-reward/patch.json deleted file mode 100644 index 0162fe5..0000000 --- a/gui-patches/inventory/show-coupon-redemption-reward/patch.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "id": "inventory/show-coupon-redemption-reward", - "title": "Show the granted reward after manual coupon redemption", - "file": "scripts/items/itemsclasses/itemexternal.nut", - "program_behaviour": { - "stock": "The coupon confirmation previews the reward from item metadata. The successful request updates the inventory stack.", - "patched": "The same reward metadata opens the existing native reward dialog after the successful redemption." - }, - "derivation": { - "requirement": "Show the actual contents of a manually redeemed vehicle, decoration, or unlock coupon.", - "cause": "A successful coupon activation updates the profile and consumes the coupon. Its existing success handler does not open a native reward dialog.", - "lighter_options_ruled_out": [ - "Use the reward confirmation before sending the grant. A refused exchange would then look as though it had succeeded.", - "Use the same receipt for automatic consumption. Supply chest rewards already have a native result path." - ], - "if_not_applied": "A redeemed coupon updates the inventory and profile without a native receipt." - }, - "features": [ - "G-Marketplace", - "H-External inventory" - ], - "evidence": [ - "2.61.0.37 scripts/items/itemsclasses/itemexternal.nut: consume previews metaBlk and consumeImpl uses the task success callback.", - "2.61.0.37 scripts/items/trophyrewardwnd.nut and trophyreward.nut: guiStartOpenTrophy accepts unit, resource, unlock and item rewards.", - "2.61.0.37 scripts/items/itemsmanagerchecks.nut and inventory/inventoryclient.nut: the definition cache outlives a consumed stack.", - "packages/local-service/src/inventory/coupons and recycling-defs.ts: coupon metadata matches the successful grant." - ], - "edit": { - "find": " let taskCallback = function() {\r\n let item = findItemByUid(uid)\r\n \n \n if (item && item.amountByUids[uid] == itemAmountByUid) {\r\n item.amountByUids[uid] -= consumeAmount\r\n item.amount -= consumeAmount\r\n if (item.amountByUids[uid] <= 0) {\r\n inventoryClient.removeItem(uid)\r\n if (item.uids?[0] == uid)\r\n item.uids.remove(0)\r\n }\r\n }\r\n if (cb)\r\n cb({ success = true })\r\n }\r\n let itemId = this.id\r\n let taskId = char_send_blk(\"cln_consume_inventory_item\", blk)", - "replace": " let couponReward = this.shouldAutoConsume || this.metaBlk == null\r\n ? null\r\n : require(\"%sqstd/datablock.nut\").convertBlk(this.metaBlk)\r\n if (couponReward != null)\r\n couponReward.itemDefId <- this.id\r\n\r\n let taskCallback = function() {\r\n let item = findItemByUid(uid)\r\n \n \n if (item && item.amountByUids[uid] == itemAmountByUid) {\r\n item.amountByUids[uid] -= consumeAmount\r\n item.amount -= consumeAmount\r\n if (item.amountByUids[uid] <= 0) {\r\n inventoryClient.removeItem(uid)\r\n if (item.uids?[0] == uid)\r\n item.uids.remove(0)\r\n }\r\n }\r\n if (cb)\r\n cb({ success = true })\r\n\r\n if (couponReward != null) {\r\n let { eventbus_send } = require(\"eventbus\")\r\n eventbus_send(\"guiStartOpenTrophy\", {\r\n [couponReward.itemDefId.tostring()] = [couponReward]\r\n rewardTitle = loc(\"mainmenu/you_received\")\r\n isHidePrizeActionBtn = true\r\n })\r\n }\r\n }\r\n let itemId = this.id\r\n let taskId = char_send_blk(\"cln_consume_inventory_item\", blk)" - } -} diff --git a/gui-patches/inventory/show-coupon-redemption-reward/patch.jsonc b/gui-patches/inventory/show-coupon-redemption-reward/patch.jsonc new file mode 100644 index 0000000..8873632 --- /dev/null +++ b/gui-patches/inventory/show-coupon-redemption-reward/patch.jsonc @@ -0,0 +1,21 @@ +// Open the existing native reward window after a manual coupon redemption succeeds. +// Why the client: the stock success handler never opens a reward window, whatever the service answers. +// Without it: a redeemed coupon updates the inventory without any receipt. +{ + "id": "inventory/show-coupon-redemption-reward", + "title": "Show the granted reward after manual coupon redemption", + "file": "scripts/items/itemsclasses/itemexternal.nut", + "features": [ + "G-Marketplace", + "H-External inventory" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/inventory/show-coupon-redemption-reward/replace.nut b/gui-patches/inventory/show-coupon-redemption-reward/replace.nut new file mode 100644 index 0000000..567c916 --- /dev/null +++ b/gui-patches/inventory/show-coupon-redemption-reward/replace.nut @@ -0,0 +1,33 @@ + let couponReward = this.shouldAutoConsume || this.metaBlk == null + ? null + : require("%sqstd/datablock.nut").convertBlk(this.metaBlk) + if (couponReward != null) + couponReward.itemDefId <- this.id + + let taskCallback = function() { + let item = findItemByUid(uid) + + + if (item && item.amountByUids[uid] == itemAmountByUid) { + item.amountByUids[uid] -= consumeAmount + item.amount -= consumeAmount + if (item.amountByUids[uid] <= 0) { + inventoryClient.removeItem(uid) + if (item.uids?[0] == uid) + item.uids.remove(0) + } + } + if (cb) + cb({ success = true }) + + if (couponReward != null) { + let { eventbus_send } = require("eventbus") + eventbus_send("guiStartOpenTrophy", { + [couponReward.itemDefId.tostring()] = [couponReward] + rewardTitle = loc("mainmenu/you_received") + isHidePrizeActionBtn = true + }) + } + } + let itemId = this.id + let taskId = char_send_blk("cln_consume_inventory_item", blk) diff --git a/gui-patches/online-shop/bypass-external-sso-for-local-urls/find.nut b/gui-patches/online-shop/bypass-external-sso-for-local-urls/find.nut new file mode 100644 index 0000000..f110675 --- /dev/null +++ b/gui-patches/online-shop/bypass-external-sso-for-local-urls/find.nut @@ -0,0 +1 @@ + let shouldLogin = isInArray(URL_TAG_AUTO_LOGIN, urlTags) diff --git a/gui-patches/online-shop/bypass-external-sso-for-local-urls/patch.json b/gui-patches/online-shop/bypass-external-sso-for-local-urls/patch.json deleted file mode 100644 index 919b4ff..0000000 --- a/gui-patches/online-shop/bypass-external-sso-for-local-urls/patch.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "id": "online-shop/bypass-external-sso-for-local-urls", - "title": "本地服务地址打开网页时跳过 Gaijin 外网单点登录跳转", - "file": "scripts/onlineshop/url.nut", - - "program_behaviour": { - "stock": "打开带 auto_login 标签的链接(如 inventoryClient.nut 的 getMarketplaceBaseUrl())时,scripts/onlineshop/url.nut 调用原生 SsoLoggedUrlAction(yu_sessionProc.cpp:951),把目标地址包装进写死的 https://login.gaijin.net/sso/LoginByStoken 链接,再按 openUrlImpl 的判断交给游戏内置浏览器(PC 非 Steam 下就是内置浏览器,implementation notes 第 9 节)打开。", - "patched": "当目标链接指向本次启动的本地服务地址(://:)时,shouldLogin 取 false,内置浏览器直接打开本地网页(/store、/trade.gaijin.net 等)。" - }, - - "derivation": { - "requirement": "功能清单 G「礼包商店」「市场」与 A「不连 Gaijin」。玩家在游戏内点击「在交易所中查找」或顶栏「交易所」时,必须在内置浏览器里直接打开本地交易所页面,且浏览器不访问 login.gaijin.net。", - "cause": "yu_sessionProc.cpp:951 的 SsoLoggedUrlAction 硬编码拼接 https://login.gaijin.net/sso/LoginByStoken(YuSession::setOptionStringSync 无覆盖该域名的选项),再交给内置浏览器打开;内置浏览器 cefprocess.exe 是独立进程,不加载游戏的 wto_ws.dll,会直接连向真实 Gaijin 登录服务器。", - "lighter_options_ruled_out": [ - "在 network.blk 去掉 marketplaceURL 的 auto_login:auto_login 不在 network.blk 配置值里,而是由 scripts/inventory/inventoryClient.nut 的 getMarketplaceBaseUrl() 在脚本里前置拼接。", - "让本地登录服务的 get_short_token 返回错误以触发回退分支:url.nut 为配合 SSO 参数对 notAuthUrl 做了 Base64 编码,SsoLoggedUrlAction 失败回调会把这段 Base64 字符串原样当作地址打开,打不开。" - ], - "conclusion": "在 gui.vromfs.bin 的 scripts/onlineshop/url.nut 单点为 shouldLogin 增加本地服务地址排除条件(仅对包含 ://<本地地址>:<端口> 的链接跳过 auto_login)。", - "if_not_applied": "在机库点击交易所或市场载具「在交易所中查找」时,内置浏览器会跳转到真实 https://login.gaijin.net/sso/LoginByStoken,无法打开本地交易所且产生外网请求。" - }, - - "features": ["A-不连 Gaijin", "G-礼包商店", "G-市场"], - "evidence": [ - "2.61.0.37 gui.vromfs.bin:scripts/onlineshop/url.nut(let shouldLogin = isInArray(URL_TAG_AUTO_LOGIN, urlTags))、scripts/inventory/inventoryClient.nut(getMarketplaceBaseUrl 前置 auto_login)。", - "DagorEngine 公开源码:prog/gameLibs/yuplay2/yu_sessionProc.cpp 第 951 行 SsoLoggedUrlAction。" - ], - - "edit": { - "find": " let shouldLogin = isInArray(URL_TAG_AUTO_LOGIN, urlTags)", - "replace": " let shouldLogin = isInArray(URL_TAG_AUTO_LOGIN, urlTags) && url.indexof(\"://{{LOCAL_ENDPOINT}}\") == null" - } -} diff --git a/gui-patches/online-shop/bypass-external-sso-for-local-urls/patch.jsonc b/gui-patches/online-shop/bypass-external-sso-for-local-urls/patch.jsonc new file mode 100644 index 0000000..91cf76e --- /dev/null +++ b/gui-patches/online-shop/bypass-external-sso-for-local-urls/patch.jsonc @@ -0,0 +1,22 @@ +// Skip the yuplay2 single sign-on wrapper for URLs that point at the local service. +// Why the client: SsoLoggedUrlAction always wraps the URL in https://login.gaijin.net and the embedded browser does not load wto_ws.dll. +// Without it: opening the local store or marketplace sends the browser to the real Gaijin login server. +{ + "id": "online-shop/bypass-external-sso-for-local-urls", + "title": "本地服务地址打开网页时跳过 Gaijin 外网单点登录跳转", + "file": "scripts/onlineshop/url.nut", + "features": [ + "A-不连 Gaijin", + "G-礼包商店", + "G-市场" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/bypass-external-sso-for-local-urls/replace.nut b/gui-patches/online-shop/bypass-external-sso-for-local-urls/replace.nut new file mode 100644 index 0000000..6a3feaa --- /dev/null +++ b/gui-patches/online-shop/bypass-external-sso-for-local-urls/replace.nut @@ -0,0 +1 @@ + let shouldLogin = isInArray(URL_TAG_AUTO_LOGIN, urlTags) && url.indexof("://{{LOCAL_ENDPOINT}}") == null diff --git a/gui-patches/online-shop/collect-entitlement-purchase-rewards/find.nut b/gui-patches/online-shop/collect-entitlement-purchase-rewards/find.nut new file mode 100644 index 0000000..cebf6dd --- /dev/null +++ b/gui-patches/online-shop/collect-entitlement-purchase-rewards/find.nut @@ -0,0 +1,2 @@ + let entitlementRewards = {} + diff --git a/gui-patches/online-shop/collect-entitlement-purchase-rewards/patch.json b/gui-patches/online-shop/collect-entitlement-purchase-rewards/patch.json deleted file mode 100644 index 1ba3316..0000000 --- a/gui-patches/online-shop/collect-entitlement-purchase-rewards/patch.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "id": "online-shop/collect-entitlement-purchase-rewards", - "title": "Track entitlement purchases by user log", - "file": "scripts/userlog/userlogdata.nut", - "program_behaviour": { - "stock": "Resource rewards share an entitlement-name map.", - "patched": "Maintain a separate list of purchases so every purchase can open its own receipt." - }, - "derivation": { - "requirement": "Present each saved entitlement purchase and acknowledge the log after its receipt opens.", - "cause": "Several purchases of the same entitlement can be present in one profile refresh.", - "lighter_options_ruled_out": [ - "Reuse the resource map keyed by product ID. Two purchases of the same product would collapse into one receipt." - ], - "if_not_applied": "Repeated purchases in one update can be under-reported." - }, - "features": [ - "G-Store", - "G-Premium Account" - ], - "evidence": [ - "2.61.0.37 scripts/userlog/userlogdata.nut: checkNewNotificationUserlogs declares the entitlement reward collection." - ], - "edit": { - "find": " let entitlementRewards = {}\r\n", - "replace": " let entitlementRewards = {}\r\n let purchaseReceipts = []\r\n" - } -} diff --git a/gui-patches/online-shop/collect-entitlement-purchase-rewards/patch.jsonc b/gui-patches/online-shop/collect-entitlement-purchase-rewards/patch.jsonc new file mode 100644 index 0000000..9180e56 --- /dev/null +++ b/gui-patches/online-shop/collect-entitlement-purchase-rewards/patch.jsonc @@ -0,0 +1,21 @@ +// Collect entitlement purchases per user log entry so every purchase opens its own receipt. +// Why the client: the stock scan merges purchases of the same entitlement that arrive in one refresh. +// Without it: repeated purchases in one profile update are under-reported. +{ + "id": "online-shop/collect-entitlement-purchase-rewards", + "title": "Track entitlement purchases by user log", + "file": "scripts/userlog/userlogdata.nut", + "features": [ + "G-Store", + "G-Premium Account" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/collect-entitlement-purchase-rewards/replace.nut b/gui-patches/online-shop/collect-entitlement-purchase-rewards/replace.nut new file mode 100644 index 0000000..a3641c4 --- /dev/null +++ b/gui-patches/online-shop/collect-entitlement-purchase-rewards/replace.nut @@ -0,0 +1,3 @@ + let entitlementRewards = {} + let purchaseReceipts = [] + diff --git a/gui-patches/online-shop/defer-explicit-browser-update-to-close/find.nut b/gui-patches/online-shop/defer-explicit-browser-update-to-close/find.nut new file mode 100644 index 0000000..a861313 --- /dev/null +++ b/gui-patches/online-shop/defer-explicit-browser-update-to-close/find.nut @@ -0,0 +1,2 @@ + function browserCloseAndUpdateEntitlements() { + addTask(updateEntitlementsLimited(), diff --git a/gui-patches/online-shop/defer-explicit-browser-update-to-close/patch.json b/gui-patches/online-shop/defer-explicit-browser-update-to-close/patch.json deleted file mode 100644 index b157861..0000000 --- a/gui-patches/online-shop/defer-explicit-browser-update-to-close/patch.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "id": "online-shop/defer-explicit-browser-update-to-close", - "title": "Refresh local commerce once from the browser close handler", - "file": "scripts/onlineshop/browserwnd.nut", - "program_behaviour": { - "stock": "The browser close-and-update control issues a refresh before closing the window.", - "patched": "For local commerce, the control closes the window and leaves the refresh to its close handler." - }, - "derivation": { - "requirement": "Perform the same profile refresh for the close-and-update control and other close paths.", - "cause": "The control already requests an update. A second update before the first completes could add a redundant task.", - "lighter_options_ruled_out": [ - "The local service observes requests and grants. The window lifecycle is managed by the client.", - "Keep two refresh paths for local commerce. This can send two native tasks for one close." - ], - "if_not_applied": "The explicit close-and-update control can request an extra refresh." - }, - "features": [ - "G-Store", - "G-Marketplace" - ], - "evidence": [ - "2.61.0.37 scripts/onlineshop/browserwnd.nut: BrowserModalHandler.browserCloseAndUpdateEntitlements.", - "gui-patches/online-shop/refresh-profile-after-browser-close: local commerce close detection." - ], - "edit": { - "find": " function browserCloseAndUpdateEntitlements() {\r\n addTask(updateEntitlementsLimited(),", - "replace": " function browserCloseAndUpdateEntitlements() {\r\n if (this.isLocalCommercePage())\r\n return this.goBack()\r\n\r\n addTask(updateEntitlementsLimited()," - } -} diff --git a/gui-patches/online-shop/defer-explicit-browser-update-to-close/patch.jsonc b/gui-patches/online-shop/defer-explicit-browser-update-to-close/patch.jsonc new file mode 100644 index 0000000..aa60c6a --- /dev/null +++ b/gui-patches/online-shop/defer-explicit-browser-update-to-close/patch.jsonc @@ -0,0 +1,21 @@ +// For local commerce pages, close the browser and leave the refresh to the close handler. +// Why the client: the stock control already starts an update before the close handler starts another. +// Without it: the close-and-update control can queue a redundant profile refresh. +{ + "id": "online-shop/defer-explicit-browser-update-to-close", + "title": "Refresh local commerce once from the browser close handler", + "file": "scripts/onlineshop/browserwnd.nut", + "features": [ + "G-Store", + "G-Marketplace" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/defer-explicit-browser-update-to-close/replace.nut b/gui-patches/online-shop/defer-explicit-browser-update-to-close/replace.nut new file mode 100644 index 0000000..b32c6ef --- /dev/null +++ b/gui-patches/online-shop/defer-explicit-browser-update-to-close/replace.nut @@ -0,0 +1,5 @@ + function browserCloseAndUpdateEntitlements() { + if (this.isLocalCommercePage()) + return this.goBack() + + addTask(updateEntitlementsLimited(), diff --git a/gui-patches/online-shop/free-offline-payment-method/find.nut b/gui-patches/online-shop/free-offline-payment-method/find.nut new file mode 100644 index 0000000..604d0ac --- /dev/null +++ b/gui-patches/online-shop/free-offline-payment-method/find.nut @@ -0,0 +1,2 @@ + let name = "yuNetwork/payMethod/other" + items.append({ diff --git a/gui-patches/online-shop/free-offline-payment-method/patch.json b/gui-patches/online-shop/free-offline-payment-method/patch.json deleted file mode 100644 index d5e79cc..0000000 --- a/gui-patches/online-shop/free-offline-payment-method/patch.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "id": "online-shop/free-offline-payment-method", - "title": "游戏内支付方式窗口增加「老福爷付过了」免 GJN 直接购买选项", - "file": "scripts/onlineshop/onlinepurchase.nut", - - "program_behaviour": { - "stock": "scripts/onlineshop/onlinepurchase.nut 的 onOnlinePurchase 根据 yuplay2_get_payment_methods() 的位掩码生成支付方式列表(默认只有 Gaijin 币 YU2_PAY_GJN),再固定追加「其他支付方式」(yuNetwork/payMethod/other),交由 PaymentHandler 展示。", - "patched": "在「其他支付方式」之前固定追加一项文字按钮「老福爷付过了」(icon 为空字符串,使 paymentHandler.nut 显示文字标题),点击确认后以 YU2_PAY_NONE(0,PurchaseAction 不附带 pay 参数)调用 doYuplayPurchase,本地服务的 /item_purchase.php 识别无 pay 参数时免扣 GJN 直接发放商品。" - }, - - "derivation": { - "requirement": "用户反馈(反馈20261125.md):在支付方式里除了 Gaijin 币外增加一项「老福爷付过了」,点击即视为已支付并直接买下商品,供不想刷 GJN 的玩家使用。", - "cause": "原版 payMethodsCfg 只列出 paypal、webmoney、amazon、gjncoins 四项,且均设置非空 SVG 图标(paymenthandler.nut 第 26 行在 icon 非空时隐藏文字标题只显示图标),无法仅靠登录服务下发位掩码在窗口里显示自定义中文名称「老福爷付过了」。", - "lighter_options_ruled_out": [ - "仅在登录服务返回 autopay_pp 等标签开启原版其他支付位:按钮只会显示 PayPal 等原版图标,不会显示「老福爷付过了」文字。" - ], - "conclusion": "在 scripts/onlineshop/onlinepurchase.nut 的支付列表追加无图标文字项「老福爷付过了」,传入已导出的原生常量 YU2_PAY_NONE(aces.exe 0x17cd280 -> YuSession::buyItemSync 不校验位掩码,PurchaseAction 发送不含 pay 字段的表单),由本地服务免扣 GJN 发放。", - "if_not_applied": "游戏内购买金鹰包或 GJN 高级账户弹出「选择支付方式」窗口时只有「Gaijin 币」和「其他支付方式」,没有「老福爷付过了」选项。" - }, - - "features": ["G-货币", "G-高级账户", "G-礼包商店"], - "evidence": [ - "2.61.0.37 gui.vromfs.bin:scripts/onlineshop/onlinepurchase.nut(onOnlinePurchase、onYuplayPurchase、doYuplayPurchase)、scripts/paymenthandler.nut 第 24-26 行、globalScripts/yuplay2Consts.nut 第 38 行(YU2_PAY_NONE)。", - "2.61.0.37 aces.exe:0x17cd280(yuplay2_buy_entitlement 绑定)-> 0x55ecbd0(YuSession::buyItemSync)。", - "DagorEngine 公开源码:prog/1stPartyLibs/yuplay2auth/session/yu_session.cpp 第 2175 行、yu_sessionProc.cpp 第 260-296 行(PurchaseAction::run 在 payment 为 YU2_PAY_NONE 时不写 pay 字段)。" - ], - - "edit": { - "find": " let name = \"yuNetwork/payMethod/other\"\r\n items.append({", - "replace": " let freePayName = \"老福爷付过了\"\r\n items.append({\r\n name = freePayName\r\n icon = \"\"\r\n callback = @() onYuplayPurchase(product, YU2_PAY_NONE, freePayName)\r\n })\r\n\r\n let name = \"yuNetwork/payMethod/other\"\r\n items.append({" - } -} diff --git a/gui-patches/online-shop/free-offline-payment-method/patch.jsonc b/gui-patches/online-shop/free-offline-payment-method/patch.jsonc new file mode 100644 index 0000000..1e3e9a2 --- /dev/null +++ b/gui-patches/online-shop/free-offline-payment-method/patch.jsonc @@ -0,0 +1,22 @@ +// Add a text-only payment option that purchases with YU2_PAY_NONE (no GJN charge). +// Why the client: payMethodsCfg only lists four icon-only methods; a login bitmask cannot add a named option. +// Without it: the in-game payment window offers no free offline purchase. +{ + "id": "online-shop/free-offline-payment-method", + "title": "游戏内支付方式窗口增加「老福爷付过了」免 GJN 直接购买选项", + "file": "scripts/onlineshop/onlinepurchase.nut", + "features": [ + "G-货币", + "G-高级账户", + "G-礼包商店" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/free-offline-payment-method/replace.nut b/gui-patches/online-shop/free-offline-payment-method/replace.nut new file mode 100644 index 0000000..e1fd249 --- /dev/null +++ b/gui-patches/online-shop/free-offline-payment-method/replace.nut @@ -0,0 +1,9 @@ + let freePayName = "老福爷付过了" + items.append({ + name = freePayName + icon = "" + callback = @() onYuplayPurchase(product, YU2_PAY_NONE, freePayName) + }) + + let name = "yuNetwork/payMethod/other" + items.append({ diff --git a/gui-patches/online-shop/localize-vehicle-pack-titles/find.nut b/gui-patches/online-shop/localize-vehicle-pack-titles/find.nut new file mode 100644 index 0000000..db3bba2 --- /dev/null +++ b/gui-patches/online-shop/localize-vehicle-pack-titles/find.nut @@ -0,0 +1,2 @@ +function getEntitlementShortName(ent) { + local name = "" diff --git a/gui-patches/online-shop/localize-vehicle-pack-titles/patch.json b/gui-patches/online-shop/localize-vehicle-pack-titles/patch.json deleted file mode 100644 index 0007a05..0000000 --- a/gui-patches/online-shop/localize-vehicle-pack-titles/patch.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "id": "online-shop/localize-vehicle-pack-titles", - "title": "Display localized titles for offline vehicle packs", - "file": "scripts/onlineshop/entitlements.nut", - "program_behaviour": { - "stock": "The entitlement name is looked up in the game's localization table by product ID, alias, or group.", - "patched": "Use the catalogue title for offline vehicle packs, selecting Chinese or English from the current game language. Products without a catalogue title use the existing name formatter." - }, - "derivation": { - "requirement": "The purchase receipt title matches the name of the vehicle pack shown in the local store.", - "cause": "The game's localization table has no entries for the locally generated vehicle pack IDs.", - "lighter_options_ruled_out": [ - "Supply the names in the price response alone. The original name formatter does not read those fields." - ], - "if_not_applied": "Vehicle pack receipts can show the raw localization key as the title." - }, - "features": [ - "G-Store" - ], - "evidence": [ - "2.61.0.37 scripts/onlineshop/entitlements.nut: getEntitlementConfig copies all price parameters, and getEntitlementName calls getEntitlementShortName.", - "2.61.0.37 scripts/onlineshop/entitlementrewardwnd.nut: getTitle uses getEntitlementName.", - "packages/local-service/src/char/actions/store-actions.ts: localized titles in the entitlement price response." - ], - "edit": { - "find": "function getEntitlementShortName(ent) {\r\n local name = \"\"", - "replace": "function getEntitlementShortName(ent) {\r\n let catalogueTitle = ent?.wtoTitleEn\r\n if (catalogueTitle != null) {\r\n let { isChineseVersion, isChineseHarmonized } = require(\"%scripts/langUtils/language.nut\")\r\n let isChinese = isChineseVersion() || isChineseHarmonized()\r\n return isChinese ? (ent?.wtoTitleZh ?? catalogueTitle) : catalogueTitle\r\n }\r\n\r\n local name = \"\"" - } -} diff --git a/gui-patches/online-shop/localize-vehicle-pack-titles/patch.jsonc b/gui-patches/online-shop/localize-vehicle-pack-titles/patch.jsonc new file mode 100644 index 0000000..d12704c --- /dev/null +++ b/gui-patches/online-shop/localize-vehicle-pack-titles/patch.jsonc @@ -0,0 +1,20 @@ +// Use the catalogue title for offline vehicle packs in the current game language. +// Why the client: the localization tables have no entries for locally generated pack ids. +// Without it: vehicle pack receipts show raw localization keys. +{ + "id": "online-shop/localize-vehicle-pack-titles", + "title": "Display localized titles for offline vehicle packs", + "file": "scripts/onlineshop/entitlements.nut", + "features": [ + "G-Store" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/localize-vehicle-pack-titles/replace.nut b/gui-patches/online-shop/localize-vehicle-pack-titles/replace.nut new file mode 100644 index 0000000..27578ea --- /dev/null +++ b/gui-patches/online-shop/localize-vehicle-pack-titles/replace.nut @@ -0,0 +1,9 @@ +function getEntitlementShortName(ent) { + let catalogueTitle = ent?.wtoTitleEn + if (catalogueTitle != null) { + let { isChineseVersion, isChineseHarmonized } = require("%scripts/langUtils/language.nut") + let isChinese = isChineseVersion() || isChineseHarmonized() + return isChinese ? (ent?.wtoTitleZh ?? catalogueTitle) : catalogueTitle + } + + local name = "" diff --git a/gui-patches/online-shop/open-entitlement-purchase-receipts/find.nut b/gui-patches/online-shop/open-entitlement-purchase-receipts/find.nut new file mode 100644 index 0000000..f87464a --- /dev/null +++ b/gui-patches/online-shop/open-entitlement-purchase-receipts/find.nut @@ -0,0 +1,2 @@ + entitlementRewards.each( + @(_, entId) handler.doWhenActive(@() showEntitlement(entId, { ignoreAvailability = true }))) diff --git a/gui-patches/online-shop/open-entitlement-purchase-receipts/patch.json b/gui-patches/online-shop/open-entitlement-purchase-receipts/patch.json deleted file mode 100644 index 6bb23e4..0000000 --- a/gui-patches/online-shop/open-entitlement-purchase-receipts/patch.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "id": "online-shop/open-entitlement-purchase-receipts", - "title": "Acknowledge each purchase after its receipt opens", - "file": "scripts/userlog/userlogdata.nut", - "program_behaviour": { - "stock": "The resource reward queue acknowledges records before opening entitlement windows.", - "patched": "Queue each saved purchase once per active handler and acknowledge it after the receipt opens." - }, - "derivation": { - "requirement": "Present each saved entitlement purchase and acknowledge the log after its receipt opens.", - "cause": "A refresh can return multiple purchases and the current price table can temporarily lack a product.", - "lighter_options_ruled_out": [ - "Use the existing resource map and acknowledgement timing. Repeated purchases would merge and missing products could be marked seen." - ], - "if_not_applied": "Repeated purchases or products missing from the current catalogue can lose their unread notification." - }, - "features": [ - "G-Store", - "G-Premium Account" - ], - "evidence": [ - "2.61.0.37 scripts/userlog/userlogdata.nut: entitlementRewards dispatches dialogs through doWhenActive.", - "2.61.0.37 scripts/sqDagui/framework/baseGuiHandler.nut: doWhenActive queues while another modal owns the scene.", - "2.61.0.37 scripts/userlog/userlogutils.nut: disableSeenUserlogs persists seen IDs through job 223.", - "2.61.0.37 scripts/sqdagui/framework/baseguihandlermanager.nut: isHandlerValid and handler weak references." - ], - "edit": { - "find": " entitlementRewards.each(\r\n @(_, entId) handler.doWhenActive(@() showEntitlement(entId, { ignoreAvailability = true })))", - "replace": " entitlementRewards.each(\r\n @(_, entId) handler.doWhenActive(@() showEntitlement(entId, { ignoreAvailability = true })))\r\n\r\n if (purchaseReceipts.len() > 0 && !ENTITLEMENTS_PRICE.isActual()) {\r\n waitingForPurchasePrices = true\r\n ENTITLEMENTS_PRICE.checkUpdate()\r\n }\r\n\r\n foreach (logId, owner in clone queuedPurchaseReceipts)\r\n if (!handlersManager.isHandlerValid(owner))\r\n queuedPurchaseReceipts.$rawdelete(logId)\r\n\r\n foreach (entry in purchaseReceipts) {\r\n let receipt = entry\r\n if (receipt.logId in queuedPurchaseReceipts)\r\n continue\r\n\r\n queuedPurchaseReceipts[receipt.logId] <- handler.weakref()\r\n handler.doWhenActive(function() {\r\n if (!shownUserlogNotifications.get().contains(receipt.logId)\r\n && ENTITLEMENTS_PRICE.isActual()\r\n && showPurchaseReceipt(receipt) != null)\r\n disableSeenUserlogs([receipt.logId])\r\n\r\n queuedPurchaseReceipts.$rawdelete(receipt.logId)\r\n })\r\n }" - } -} diff --git a/gui-patches/online-shop/open-entitlement-purchase-receipts/patch.jsonc b/gui-patches/online-shop/open-entitlement-purchase-receipts/patch.jsonc new file mode 100644 index 0000000..415c512 --- /dev/null +++ b/gui-patches/online-shop/open-entitlement-purchase-receipts/patch.jsonc @@ -0,0 +1,21 @@ +// Queue each saved purchase once per handler and acknowledge it after its receipt opens. +// Why the client: one refresh can return several purchases before the price table is available. +// Without it: repeated purchases or products missing from the catalogue lose their unread notification. +{ + "id": "online-shop/open-entitlement-purchase-receipts", + "title": "Acknowledge each purchase after its receipt opens", + "file": "scripts/userlog/userlogdata.nut", + "features": [ + "G-Store", + "G-Premium Account" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/open-entitlement-purchase-receipts/replace.nut b/gui-patches/online-shop/open-entitlement-purchase-receipts/replace.nut new file mode 100644 index 0000000..a3bedd1 --- /dev/null +++ b/gui-patches/online-shop/open-entitlement-purchase-receipts/replace.nut @@ -0,0 +1,27 @@ + entitlementRewards.each( + @(_, entId) handler.doWhenActive(@() showEntitlement(entId, { ignoreAvailability = true }))) + + if (purchaseReceipts.len() > 0 && !ENTITLEMENTS_PRICE.isActual()) { + waitingForPurchasePrices = true + ENTITLEMENTS_PRICE.checkUpdate() + } + + foreach (logId, owner in clone queuedPurchaseReceipts) + if (!handlersManager.isHandlerValid(owner)) + queuedPurchaseReceipts.$rawdelete(logId) + + foreach (entry in purchaseReceipts) { + let receipt = entry + if (receipt.logId in queuedPurchaseReceipts) + continue + + queuedPurchaseReceipts[receipt.logId] <- handler.weakref() + handler.doWhenActive(function() { + if (!shownUserlogNotifications.get().contains(receipt.logId) + && ENTITLEMENTS_PRICE.isActual() + && showPurchaseReceipt(receipt) != null) + disableSeenUserlogs([receipt.logId]) + + queuedPurchaseReceipts.$rawdelete(receipt.logId) + }) + } diff --git a/gui-patches/online-shop/present-saved-entitlement-grants/find.nut b/gui-patches/online-shop/present-saved-entitlement-grants/find.nut new file mode 100644 index 0000000..b59ae72 --- /dev/null +++ b/gui-patches/online-shop/present-saved-entitlement-grants/find.nut @@ -0,0 +1,2 @@ +let { ENTITLEMENTS_PRICE } = require("%scripts/utils/configs.nut") + diff --git a/gui-patches/online-shop/present-saved-entitlement-grants/patch.json b/gui-patches/online-shop/present-saved-entitlement-grants/patch.json deleted file mode 100644 index 3231cef..0000000 --- a/gui-patches/online-shop/present-saved-entitlement-grants/patch.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "id": "online-shop/present-saved-entitlement-grants", - "title": "Present the benefits recorded by the purchase", - "file": "scripts/userlog/userlogdata.nut", - "program_behaviour": { - "stock": "Entitlement rewards are displayed from the current catalogue.", - "patched": "Use the stored grant amounts and vehicle IDs for the purchase receipt. A retired product uses the existing text confirmation." - }, - "derivation": { - "requirement": "Present the benefits recorded by the purchase", - "cause": "Catalogue bundles include all offered benefits, including vehicles the buyer may already own, and can be retired after the purchase.", - "lighter_options_ruled_out": [ - "Render the current catalogue product directly. This cannot describe what was actually granted." - ], - "if_not_applied": "Already owned vehicles can be listed as new, and receipts for removed products do not open." - }, - "features": [ - "G-Store", - "G-Premium Account" - ], - "evidence": [ - "2.61.0.37 scripts/onlineshop/entitlementview.nut: aircraftGift, goldIncome, wpIncome and entitlementGift are the reward list inputs.", - "2.61.0.37 scripts/onlineshop/onlinepurchase.nut and scripts/sqdagui/framework/msgbox.nut: purchase_done text confirmation and modal result.", - "packages/local-service/src/profile/profile-trophies-log.ts: purchaseReceipt stores the actual grant." - ], - "edit": { - "find": "let { ENTITLEMENTS_PRICE } = require(\"%scripts/utils/configs.nut\")\r\n", - "replace": "let { ENTITLEMENTS_PRICE } = require(\"%scripts/utils/configs.nut\")\r\n\r\nlet queuedPurchaseReceipts = {}\r\nlocal waitingForPurchasePrices = false\r\n\r\nfunction showPurchaseReceipt(receipt) {\r\n let { getEntitlementConfig } = require(\"%scripts/onlineShop/entitlements.nut\")\r\n if (getEntitlementConfig(receipt.entitlement) == null)\r\n return scene_msg_box(\"purchase_done\", get_cur_gui_scene(),\r\n format(loc(\"userlog/buy_entitlement\"), receipt.entitlement),\r\n [[\"ok\", @() null]], \"ok\", { cancel_fn = @() null })\r\n\r\n let granted = receipt.granted\r\n let premiumDays = granted?.premiumDays ?? 0\r\n return showEntitlement(receipt.entitlement, { ignoreAvailability = true }, {\r\n goldIncome = granted?.goldIncome\r\n wpIncome = granted?.wpIncome\r\n aircraftGift = granted % \"aircraftGift\"\r\n entitlementGift = premiumDays > 0 ? [{ alias = \"PremiumAccount\", ttl = premiumDays }] : []\r\n })\r\n}\r\n" - } -} diff --git a/gui-patches/online-shop/present-saved-entitlement-grants/patch.jsonc b/gui-patches/online-shop/present-saved-entitlement-grants/patch.jsonc new file mode 100644 index 0000000..7fbdb6f --- /dev/null +++ b/gui-patches/online-shop/present-saved-entitlement-grants/patch.jsonc @@ -0,0 +1,21 @@ +// Show the grant recorded with the purchase instead of the current catalogue contents. +// Why the client: the stock receipt reads the catalogue, which lists already owned vehicles and can retire products. +// Without it: owned vehicles are shown as new and receipts of removed products do not open. +{ + "id": "online-shop/present-saved-entitlement-grants", + "title": "Present the benefits recorded by the purchase", + "file": "scripts/userlog/userlogdata.nut", + "features": [ + "G-Store", + "G-Premium Account" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/present-saved-entitlement-grants/replace.nut b/gui-patches/online-shop/present-saved-entitlement-grants/replace.nut new file mode 100644 index 0000000..59a374d --- /dev/null +++ b/gui-patches/online-shop/present-saved-entitlement-grants/replace.nut @@ -0,0 +1,22 @@ +let { ENTITLEMENTS_PRICE } = require("%scripts/utils/configs.nut") + +let queuedPurchaseReceipts = {} +local waitingForPurchasePrices = false + +function showPurchaseReceipt(receipt) { + let { getEntitlementConfig } = require("%scripts/onlineShop/entitlements.nut") + if (getEntitlementConfig(receipt.entitlement) == null) + return scene_msg_box("purchase_done", get_cur_gui_scene(), + format(loc("userlog/buy_entitlement"), receipt.entitlement), + [["ok", @() null]], "ok", { cancel_fn = @() null }) + + let granted = receipt.granted + let premiumDays = granted?.premiumDays ?? 0 + return showEntitlement(receipt.entitlement, { ignoreAvailability = true }, { + goldIncome = granted?.goldIncome + wpIncome = granted?.wpIncome + aircraftGift = granted % "aircraftGift" + entitlementGift = premiumDays > 0 ? [{ alias = "PremiumAccount", ttl = premiumDays }] : [] + }) +} + diff --git a/gui-patches/online-shop/refresh-profile-after-browser-close/find.nut b/gui-patches/online-shop/refresh-profile-after-browser-close/find.nut new file mode 100644 index 0000000..1ca6464 --- /dev/null +++ b/gui-patches/online-shop/refresh-profile-after-browser-close/find.nut @@ -0,0 +1,3 @@ + function onDestroy() { + broadcastEvent("DestroyEmbeddedBrowser") + } diff --git a/gui-patches/online-shop/refresh-profile-after-browser-close/patch.json b/gui-patches/online-shop/refresh-profile-after-browser-close/patch.json deleted file mode 100644 index 413fddf..0000000 --- a/gui-patches/online-shop/refresh-profile-after-browser-close/patch.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "id": "online-shop/refresh-profile-after-browser-close", - "title": "Refresh the current profile when the embedded commerce browser closes", - "file": "scripts/onlineshop/browserwnd.nut", - "program_behaviour": { - "stock": "Destroying the browser broadcasts its normal close event. Only the dedicated update button requests the profile, subject to the shared cooldown.", - "patched": "Closing a local store or marketplace page through any browser close path requests an immediate profile update." - }, - "derivation": { - "requirement": "Refresh the hangar after the local store or marketplace is closed, including when no purchase was made.", - "cause": "The local web request cannot observe the browser close. The existing update command can also omit a quick repeat close within its 20-second cooldown.", - "lighter_options_ruled_out": [ - "The local service observes requests and grants. The window lifecycle is managed by the client.", - "Keep the refetch on the dedicated button. Ordinary close paths still omit the refresh, and rapid repeats hit its cooldown." - ], - "if_not_applied": "A local browser window can close with stale purchase information in the hangar." - }, - "features": [ - "G-Store", - "G-Marketplace" - ], - "evidence": [ - "2.61.0.37 scripts/onlineshop/browserwnd.nut: BrowserModalHandler.onDestroy and browserCloseAndUpdateEntitlements.", - "2.61.0.37 scripts/onlineshop/entitlementsupdate.nut: updateEntitlementsLimited(true) forces a refresh when the char service is available.", - "packages/build/src/network/redirect-network-config.ts and scripts/inventory/inventoryclient.nut: local storefront and marketplace entry paths." - ], - "edit": { - "find": " function onDestroy() {\r\n broadcastEvent(\"DestroyEmbeddedBrowser\")\r\n }", - "replace": " function isLocalCommercePage() {\r\n let queryStart = this.url.indexof(\"?\")\r\n let page = queryStart == null ? this.url : this.url.slice(0, queryStart)\r\n return page == \"http://{{LOCAL_ENDPOINT}}/store\"\r\n || page == \"http://{{LOCAL_ENDPOINT}}/store/\"\r\n || page == \"http://{{LOCAL_ENDPOINT}}/trade.gaijin.net\"\r\n || page == \"http://{{LOCAL_ENDPOINT}}/trade.gaijin.net/\"\r\n }\r\n\r\n function onDestroy() {\r\n broadcastEvent(\"DestroyEmbeddedBrowser\")\r\n if (this.isLocalCommercePage())\r\n addTask(updateEntitlementsLimited(true), null, @() updateGamercards())\r\n }" - } -} diff --git a/gui-patches/online-shop/refresh-profile-after-browser-close/patch.jsonc b/gui-patches/online-shop/refresh-profile-after-browser-close/patch.jsonc new file mode 100644 index 0000000..9eeb4e2 --- /dev/null +++ b/gui-patches/online-shop/refresh-profile-after-browser-close/patch.jsonc @@ -0,0 +1,21 @@ +// Request a profile update whenever the embedded commerce browser closes. +// Why the client: the service cannot observe the browser closing, and the stock update has a 20 s cooldown. +// Without it: the hangar can show stale purchases after the local store closes. +{ + "id": "online-shop/refresh-profile-after-browser-close", + "title": "Refresh the current profile when the embedded commerce browser closes", + "file": "scripts/onlineshop/browserwnd.nut", + "features": [ + "G-Store", + "G-Marketplace" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/refresh-profile-after-browser-close/replace.nut b/gui-patches/online-shop/refresh-profile-after-browser-close/replace.nut new file mode 100644 index 0000000..0a6b8b6 --- /dev/null +++ b/gui-patches/online-shop/refresh-profile-after-browser-close/replace.nut @@ -0,0 +1,14 @@ + function isLocalCommercePage() { + let queryStart = this.url.indexof("?") + let page = queryStart == null ? this.url : this.url.slice(0, queryStart) + return page == "http://{{LOCAL_ENDPOINT}}/store" + || page == "http://{{LOCAL_ENDPOINT}}/store/" + || page == "http://{{LOCAL_ENDPOINT}}/trade.gaijin.net" + || page == "http://{{LOCAL_ENDPOINT}}/trade.gaijin.net/" + } + + function onDestroy() { + broadcastEvent("DestroyEmbeddedBrowser") + if (this.isLocalCommercePage()) + addTask(updateEntitlementsLimited(true), null, @() updateGamercards()) + } diff --git a/gui-patches/online-shop/refresh-profile-after-currency-shop-close/find.nut b/gui-patches/online-shop/refresh-profile-after-currency-shop-close/find.nut new file mode 100644 index 0000000..0220977 --- /dev/null +++ b/gui-patches/online-shop/refresh-profile-after-currency-shop-close/find.nut @@ -0,0 +1,3 @@ + function onDestroy() { + this.popCloseFunc() + } diff --git a/gui-patches/online-shop/refresh-profile-after-currency-shop-close/patch.json b/gui-patches/online-shop/refresh-profile-after-currency-shop-close/patch.json deleted file mode 100644 index 2a96021..0000000 --- a/gui-patches/online-shop/refresh-profile-after-currency-shop-close/patch.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "id": "online-shop/refresh-profile-after-currency-shop-close", - "title": "Refresh the current profile after the currency shop closes", - "file": "scripts/onlineshop/onlineshop.nut", - "program_behaviour": { - "stock": "The close handler invokes its registered close callback. Automatic updates while open depend on overlay or application activity.", - "patched": "The close handler also schedules a full profile update through the existing entitlement task." - }, - "derivation": { - "requirement": "Refresh the hangar after leaving the currency shop, including when no purchase was made.", - "cause": "The native shop can close without transitioning through the focus or overlay state that starts the existing refresh.", - "lighter_options_ruled_out": [ - "The local service observes requests and grants. The window lifecycle is managed by the client.", - "Rely on the existing overlay activity check. A native currency shop can close without opening an overlay." - ], - "if_not_applied": "Closing the native currency shop does not always request a fresh profile." - }, - "features": [ - "G-Store", - "G-Premium Account" - ], - "evidence": [ - "2.61.0.37 scripts/onlineshop/onlineshop.nut: onDestroy, popCloseFunc, and the existing entitlement refresh task.", - "2.61.0.37 scripts/onlineshop/entitlementsupdate.nut: updateEntitlementsLimited(true)." - ], - "edit": { - "find": " function onDestroy() {\r\n this.popCloseFunc()\r\n }", - "replace": " function onDestroy() {\r\n this.popCloseFunc()\r\n addTask(updateEntitlementsLimited(true), null, @() updateGamercards())\r\n }" - } -} diff --git a/gui-patches/online-shop/refresh-profile-after-currency-shop-close/patch.jsonc b/gui-patches/online-shop/refresh-profile-after-currency-shop-close/patch.jsonc new file mode 100644 index 0000000..5312c7e --- /dev/null +++ b/gui-patches/online-shop/refresh-profile-after-currency-shop-close/patch.jsonc @@ -0,0 +1,21 @@ +// Schedule a full profile update when the native currency shop closes. +// Why the client: the shop can close without the focus transition that starts the stock refresh. +// Without it: closing the currency shop does not always refresh the profile. +{ + "id": "online-shop/refresh-profile-after-currency-shop-close", + "title": "Refresh the current profile after the currency shop closes", + "file": "scripts/onlineshop/onlineshop.nut", + "features": [ + "G-Store", + "G-Premium Account" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/refresh-profile-after-currency-shop-close/replace.nut b/gui-patches/online-shop/refresh-profile-after-currency-shop-close/replace.nut new file mode 100644 index 0000000..75ea2ac --- /dev/null +++ b/gui-patches/online-shop/refresh-profile-after-currency-shop-close/replace.nut @@ -0,0 +1,4 @@ + function onDestroy() { + this.popCloseFunc() + addTask(updateEntitlementsLimited(true), null, @() updateGamercards()) + } diff --git a/gui-patches/online-shop/refresh-profile-after-premium-shop-close/find.nut b/gui-patches/online-shop/refresh-profile-after-premium-shop-close/find.nut new file mode 100644 index 0000000..0220977 --- /dev/null +++ b/gui-patches/online-shop/refresh-profile-after-premium-shop-close/find.nut @@ -0,0 +1,3 @@ + function onDestroy() { + this.popCloseFunc() + } diff --git a/gui-patches/online-shop/refresh-profile-after-premium-shop-close/patch.json b/gui-patches/online-shop/refresh-profile-after-premium-shop-close/patch.json deleted file mode 100644 index c3d5850..0000000 --- a/gui-patches/online-shop/refresh-profile-after-premium-shop-close/patch.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "id": "online-shop/refresh-profile-after-premium-shop-close", - "title": "Refresh the current profile after the Premium Account shop closes", - "file": "scripts/onlineshop/buypremiumhandler.nut", - "program_behaviour": { - "stock": "The close handler invokes its registered close callback. Automatic updates while open depend on overlay or application activity.", - "patched": "The close handler also schedules a full profile update through the existing entitlement task." - }, - "derivation": { - "requirement": "Refresh the hangar after leaving the Premium Account shop, including when no purchase was made.", - "cause": "The native shop can close without transitioning through the focus or overlay state that starts the existing refresh.", - "lighter_options_ruled_out": [ - "The local service observes requests and grants. The window lifecycle is managed by the client.", - "Rely on the existing overlay activity check. The Premium Account shop can close without opening an overlay." - ], - "if_not_applied": "Closing the Premium Account shop does not always request a fresh profile." - }, - "features": [ - "G-Store", - "G-Premium Account" - ], - "evidence": [ - "2.61.0.37 scripts/onlineshop/buypremiumhandler.nut: onDestroy, popCloseFunc, and the existing entitlement refresh task.", - "2.61.0.37 scripts/onlineshop/entitlementsupdate.nut: updateEntitlementsLimited(true)." - ], - "edit": { - "find": " function onDestroy() {\r\n this.popCloseFunc()\r\n }", - "replace": " function onDestroy() {\r\n this.popCloseFunc()\r\n addTask(updateEntitlementsLimited(true), null, @() updateGamercards())\r\n }" - } -} diff --git a/gui-patches/online-shop/refresh-profile-after-premium-shop-close/patch.jsonc b/gui-patches/online-shop/refresh-profile-after-premium-shop-close/patch.jsonc new file mode 100644 index 0000000..67979bf --- /dev/null +++ b/gui-patches/online-shop/refresh-profile-after-premium-shop-close/patch.jsonc @@ -0,0 +1,21 @@ +// Schedule a full profile update when the Premium Account shop closes. +// Why the client: the shop can close without the focus transition that starts the stock refresh. +// Without it: closing the Premium Account shop does not always refresh the profile. +{ + "id": "online-shop/refresh-profile-after-premium-shop-close", + "title": "Refresh the current profile after the Premium Account shop closes", + "file": "scripts/onlineshop/buypremiumhandler.nut", + "features": [ + "G-Store", + "G-Premium Account" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/refresh-profile-after-premium-shop-close/replace.nut b/gui-patches/online-shop/refresh-profile-after-premium-shop-close/replace.nut new file mode 100644 index 0000000..75ea2ac --- /dev/null +++ b/gui-patches/online-shop/refresh-profile-after-premium-shop-close/replace.nut @@ -0,0 +1,4 @@ + function onDestroy() { + this.popCloseFunc() + addTask(updateEntitlementsLimited(true), null, @() updateGamercards()) + } diff --git a/gui-patches/online-shop/render-retired-entitlement-log/find.nut b/gui-patches/online-shop/render-retired-entitlement-log/find.nut new file mode 100644 index 0000000..b0dce5b --- /dev/null +++ b/gui-patches/online-shop/render-retired-entitlement-log/find.nut @@ -0,0 +1,8 @@ + let ent = getEntitlementConfig(logObj.name) + if ("cost" in logObj) + ent["goldCost"] <- logObj.cost + local costText = getEntitlementPrice(ent) + if (costText != "") + costText = $" ({costText})" + + res.name = "".concat(format(loc($"userlog/{logName}"), getEntitlementName(ent)), costText) diff --git a/gui-patches/online-shop/render-retired-entitlement-log/patch.json b/gui-patches/online-shop/render-retired-entitlement-log/patch.json deleted file mode 100644 index 3804c99..0000000 --- a/gui-patches/online-shop/render-retired-entitlement-log/patch.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "id": "online-shop/render-retired-entitlement-log", - "title": "Keep purchase history readable after a product is removed", - "file": "scripts/userlog/userlogviewdata.nut", - "program_behaviour": { - "stock": "The purchase history renderer looks up the recorded entitlement in the current store catalogue and passes that result to the price and name formatters.", - "patched": "Use the recorded product ID when the current catalogue no longer includes its entry." - }, - "derivation": { - "requirement": "Purchase history remains readable when store tuning removes a configurable product.", - "cause": "getEntitlementConfig returns null for a removed product. The original formatter expects a table.", - "lighter_options_ruled_out": [ - "Remove purchase logs when a product is removed. That loses valid acquisition history." - ], - "if_not_applied": "An older purchase can trigger a script error in the user log after its catalogue entry is removed." - }, - "features": [ - "G-Store", - "G-Premium Account" - ], - "evidence": [ - "2.61.0.37 scripts/userlog/userlogviewdata.nut: EULT_BUYENTITLEMENT renderer.", - "2.61.0.37 scripts/onlineshop/entitlements.nut: getEntitlementConfig, getEntitlementPrice and getEntitlementName.", - "packages/local-service/src/store/store-tuning.ts: configurable product IDs and packs." - ], - "edit": { - "find": " let ent = getEntitlementConfig(logObj.name)\r\n if (\"cost\" in logObj)\r\n ent[\"goldCost\"] <- logObj.cost\r\n local costText = getEntitlementPrice(ent)\r\n if (costText != \"\")\r\n costText = $\" ({costText})\"\r\n\r\n res.name = \"\".concat(format(loc($\"userlog/{logName}\"), getEntitlementName(ent)), costText)", - "replace": " let ent = getEntitlementConfig(logObj.name)\r\n if (ent != null && \"cost\" in logObj)\r\n ent[\"goldCost\"] <- logObj.cost\r\n local costText = ent != null ? getEntitlementPrice(ent) : \"\"\r\n if (costText != \"\")\r\n costText = $\" ({costText})\"\r\n\r\n let productName = ent != null ? getEntitlementName(ent) : logObj.name\r\n res.name = \"\".concat(format(loc($\"userlog/{logName}\"), productName), costText)" - } -} diff --git a/gui-patches/online-shop/render-retired-entitlement-log/patch.jsonc b/gui-patches/online-shop/render-retired-entitlement-log/patch.jsonc new file mode 100644 index 0000000..f9f7b82 --- /dev/null +++ b/gui-patches/online-shop/render-retired-entitlement-log/patch.jsonc @@ -0,0 +1,21 @@ +// Fall back to the recorded product id when the catalogue no longer has the entry. +// Why the client: getEntitlementConfig returns null for removed products and the formatter expects a table. +// Without it: an old purchase log raises a script error once its product is retired. +{ + "id": "online-shop/render-retired-entitlement-log", + "title": "Keep purchase history readable after a product is removed", + "file": "scripts/userlog/userlogviewdata.nut", + "features": [ + "G-Store", + "G-Premium Account" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/render-retired-entitlement-log/replace.nut b/gui-patches/online-shop/render-retired-entitlement-log/replace.nut new file mode 100644 index 0000000..74837d7 --- /dev/null +++ b/gui-patches/online-shop/render-retired-entitlement-log/replace.nut @@ -0,0 +1,9 @@ + let ent = getEntitlementConfig(logObj.name) + if (ent != null && "cost" in logObj) + ent["goldCost"] <- logObj.cost + local costText = ent != null ? getEntitlementPrice(ent) : "" + if (costText != "") + costText = $" ({costText})" + + let productName = ent != null ? getEntitlementName(ent) : logObj.name + res.name = "".concat(format(loc($"userlog/{logName}"), productName), costText) diff --git a/gui-patches/online-shop/resume-purchase-receipts-after-price-update/find.nut b/gui-patches/online-shop/resume-purchase-receipts-after-price-update/find.nut new file mode 100644 index 0000000..ba8317e --- /dev/null +++ b/gui-patches/online-shop/resume-purchase-receipts-after-price-update/find.nut @@ -0,0 +1,2 @@ + UpdateGamercard = @(_p) checkNewNotificationUserlogs() +}) diff --git a/gui-patches/online-shop/resume-purchase-receipts-after-price-update/patch.json b/gui-patches/online-shop/resume-purchase-receipts-after-price-update/patch.json deleted file mode 100644 index b0da179..0000000 --- a/gui-patches/online-shop/resume-purchase-receipts-after-price-update/patch.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "id": "online-shop/resume-purchase-receipts-after-price-update", - "title": "Open pending receipts when the price table arrives", - "file": "scripts/userlog/userlogdata.nut", - "program_behaviour": { - "stock": "The reward scan runs on profile updates and after the reward window closes.", - "patched": "Resume the reward scan when a price update completes for waiting purchase receipts." - }, - "derivation": { - "requirement": "A successful purchase can be displayed when its profile arrives ahead of the price table.", - "cause": "The catalogue and profile are returned by different native tasks.", - "lighter_options_ruled_out": [ - "Wait for the next profile update. A player can remain in the hangar without another profile request after the current refresh." - ], - "if_not_applied": "A recorded receipt can remain unread until an unrelated profile update." - }, - "features": [ - "G-Store", - "G-Premium Account" - ], - "evidence": [ - "2.61.0.37 scripts/utils/configs.nut: ENTITLEMENTS_PRICE broadcasts EntitlementsPriceUpdated.", - "2.61.0.37 scripts/utils/configbase.nut: checkUpdate and the existing price update task.", - "2.61.0.37 scripts/userlog/userlogdata.nut: listener registration for reward scans." - ], - "edit": { - "find": " UpdateGamercard = @(_p) checkNewNotificationUserlogs()\r\n})", - "replace": " UpdateGamercard = @(_p) checkNewNotificationUserlogs()\r\n EntitlementsPriceUpdated = function(_p) {\r\n if (!waitingForPurchasePrices)\r\n return\r\n\r\n waitingForPurchasePrices = false\r\n checkNewNotificationUserlogs()\r\n }\r\n})" - } -} diff --git a/gui-patches/online-shop/resume-purchase-receipts-after-price-update/patch.jsonc b/gui-patches/online-shop/resume-purchase-receipts-after-price-update/patch.jsonc new file mode 100644 index 0000000..be29a68 --- /dev/null +++ b/gui-patches/online-shop/resume-purchase-receipts-after-price-update/patch.jsonc @@ -0,0 +1,21 @@ +// Resume the pending receipt scan when a price table update completes. +// Why the client: the catalogue and the profile arrive through separate native tasks. +// Without it: a recorded receipt stays unread until an unrelated profile update. +{ + "id": "online-shop/resume-purchase-receipts-after-price-update", + "title": "Open pending receipts when the price table arrives", + "file": "scripts/userlog/userlogdata.nut", + "features": [ + "G-Store", + "G-Premium Account" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/resume-purchase-receipts-after-price-update/replace.nut b/gui-patches/online-shop/resume-purchase-receipts-after-price-update/replace.nut new file mode 100644 index 0000000..e1e7233 --- /dev/null +++ b/gui-patches/online-shop/resume-purchase-receipts-after-price-update/replace.nut @@ -0,0 +1,9 @@ + UpdateGamercard = @(_p) checkNewNotificationUserlogs() + EntitlementsPriceUpdated = function(_p) { + if (!waitingForPurchasePrices) + return + + waitingForPurchasePrices = false + checkNewNotificationUserlogs() + } +}) diff --git a/gui-patches/online-shop/return-entitlement-reward-handler/find.nut b/gui-patches/online-shop/return-entitlement-reward-handler/find.nut new file mode 100644 index 0000000..df23235 --- /dev/null +++ b/gui-patches/online-shop/return-entitlement-reward-handler/find.nut @@ -0,0 +1,12 @@ +function showEntitlement(entitlementId, params = {}) { + let config = getEntitlementConfig(entitlementId) + if (!config) { + logerr($"Entitlement Reward: Could not find entitlement config {entitlementId}") + return + } + + handlersManager.loadHandler(EntitlementRewardWnd, { + entitlementConfig = config + viewParams = params + }) +} diff --git a/gui-patches/online-shop/return-entitlement-reward-handler/patch.json b/gui-patches/online-shop/return-entitlement-reward-handler/patch.json deleted file mode 100644 index bed273c..0000000 --- a/gui-patches/online-shop/return-entitlement-reward-handler/patch.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "id": "online-shop/return-entitlement-reward-handler", - "title": "Open a receipt using the persisted grant", - "file": "scripts/onlineshop/entitlementrewardwnd.nut", - "program_behaviour": { - "stock": "showEntitlement opens the configured reward handler without returning it.", - "patched": "Accept a grant override for saved purchases and return the handler opened by the GUI manager." - }, - "derivation": { - "requirement": "Present each saved entitlement purchase and acknowledge the log after its receipt opens.", - "cause": "A saved purchase can grant fewer items than the current catalogue lists, and the log should be marked seen only once the window opens.", - "lighter_options_ruled_out": [ - "Assume the dialog opened if the product is present. The modal manager may still fail to create the handler." - ], - "if_not_applied": "The calling code cannot distinguish successful display from an unavailable receipt." - }, - "features": [ - "G-Store", - "G-Premium Account" - ], - "evidence": [ - "2.61.0.37 scripts/onlineshop/entitlementrewardwnd.nut: showEntitlement.", - "2.61.0.37 scripts/sqDagui/framework/baseGuiHandlerManager.nut: loadHandler returns the loaded handler." - ], - "edit": { - "find": "function showEntitlement(entitlementId, params = {}) {\r\n let config = getEntitlementConfig(entitlementId)\r\n if (!config) {\r\n logerr($\"Entitlement Reward: Could not find entitlement config {entitlementId}\")\r\n return\r\n }\r\n\r\n handlersManager.loadHandler(EntitlementRewardWnd, {\r\n entitlementConfig = config\r\n viewParams = params\r\n })\r\n}", - "replace": "function showEntitlement(entitlementId, params = {}, granted = null) {\r\n let config = getEntitlementConfig(entitlementId)\r\n if (!config) {\r\n logerr($\"Entitlement Reward: Could not find entitlement config {entitlementId}\")\r\n return\r\n }\r\n\r\n return handlersManager.loadHandler(EntitlementRewardWnd, {\r\n entitlementConfig = granted == null ? config : config.__merge(granted)\r\n viewParams = params\r\n })\r\n}" - } -} diff --git a/gui-patches/online-shop/return-entitlement-reward-handler/patch.jsonc b/gui-patches/online-shop/return-entitlement-reward-handler/patch.jsonc new file mode 100644 index 0000000..6eb3611 --- /dev/null +++ b/gui-patches/online-shop/return-entitlement-reward-handler/patch.jsonc @@ -0,0 +1,21 @@ +// Accept a grant override for saved purchases and return the opened handler. +// Why the client: the stock function neither takes the saved grant nor reports whether the window opened. +// Without it: callers cannot tell a shown receipt from an unavailable one. +{ + "id": "online-shop/return-entitlement-reward-handler", + "title": "Open a receipt using the persisted grant", + "file": "scripts/onlineshop/entitlementrewardwnd.nut", + "features": [ + "G-Store", + "G-Premium Account" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/return-entitlement-reward-handler/replace.nut b/gui-patches/online-shop/return-entitlement-reward-handler/replace.nut new file mode 100644 index 0000000..d9af400 --- /dev/null +++ b/gui-patches/online-shop/return-entitlement-reward-handler/replace.nut @@ -0,0 +1,12 @@ +function showEntitlement(entitlementId, params = {}, granted = null) { + let config = getEntitlementConfig(entitlementId) + if (!config) { + logerr($"Entitlement Reward: Could not find entitlement config {entitlementId}") + return + } + + return handlersManager.loadHandler(EntitlementRewardWnd, { + entitlementConfig = granted == null ? config : config.__merge(granted) + viewParams = params + }) +} diff --git a/gui-patches/online-shop/show-direct-entitlement-gift-icons/find.nut b/gui-patches/online-shop/show-direct-entitlement-gift-icons/find.nut new file mode 100644 index 0000000..3d46673 --- /dev/null +++ b/gui-patches/online-shop/show-direct-entitlement-gift-icons/find.nut @@ -0,0 +1,2 @@ + .filter(@(entId) getEntitlementConfig(entId) != null) + diff --git a/gui-patches/online-shop/show-direct-entitlement-gift-icons/patch.json b/gui-patches/online-shop/show-direct-entitlement-gift-icons/patch.json deleted file mode 100644 index 7b82172..0000000 --- a/gui-patches/online-shop/show-direct-entitlement-gift-icons/patch.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "id": "online-shop/show-direct-entitlement-gift-icons", - "title": "Include awarded Premium Account days in the receipt icon list", - "file": "scripts/onlineshop/entitlementview.nut", - "program_behaviour": { - "stock": "Gift icons are listed for current catalogue products.", - "patched": "Use the same entitlement gift resolver as the reward list." - }, - "derivation": { - "requirement": "Include awarded Premium Account days in the receipt icon list", - "cause": "A duration recorded by a purchase does not always correspond to a current product ID.", - "lighter_options_ruled_out": [ - "List the new gift only as text. The award would be omitted from the icon count." - ], - "if_not_applied": "The receipt art would omit awarded Premium Account days." - }, - "features": [ - "G-Store", - "G-Premium Account" - ], - "evidence": [ - "2.61.0.37 scripts/onlineshop/entitlementview.nut: getSortedLayersIcons and reward_entitlement." - ], - "edit": { - "find": " .filter(@(entId) getEntitlementConfig(entId) != null)\r\n", - "replace": " .filter(@(gift) getEntitlementGiftConfig(gift) != null)\r\n" - } -} diff --git a/gui-patches/online-shop/show-direct-entitlement-gift-icons/patch.jsonc b/gui-patches/online-shop/show-direct-entitlement-gift-icons/patch.jsonc new file mode 100644 index 0000000..7503ac3 --- /dev/null +++ b/gui-patches/online-shop/show-direct-entitlement-gift-icons/patch.jsonc @@ -0,0 +1,21 @@ +// Use the entitlement gift resolver for the receipt icon list as well. +// Why the client: a recorded Premium Account duration need not match a current product id. +// Without it: receipt art omits awarded Premium Account days. +{ + "id": "online-shop/show-direct-entitlement-gift-icons", + "title": "Include awarded Premium Account days in the receipt icon list", + "file": "scripts/onlineshop/entitlementview.nut", + "features": [ + "G-Store", + "G-Premium Account" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/show-direct-entitlement-gift-icons/replace.nut b/gui-patches/online-shop/show-direct-entitlement-gift-icons/replace.nut new file mode 100644 index 0000000..6d313c8 --- /dev/null +++ b/gui-patches/online-shop/show-direct-entitlement-gift-icons/replace.nut @@ -0,0 +1,2 @@ + .filter(@(gift) getEntitlementGiftConfig(gift) != null) + diff --git a/gui-patches/online-shop/show-direct-entitlement-gifts/find.nut b/gui-patches/online-shop/show-direct-entitlement-gifts/find.nut new file mode 100644 index 0000000..874652c --- /dev/null +++ b/gui-patches/online-shop/show-direct-entitlement-gifts/find.nut @@ -0,0 +1,2 @@ +let getEntitlementGiftView = @(entitlement) (entitlement?.entitlementGift ?? []).map(function(giftId) { + let config = getEntitlementConfig(giftId) diff --git a/gui-patches/online-shop/show-direct-entitlement-gifts/patch.json b/gui-patches/online-shop/show-direct-entitlement-gifts/patch.json deleted file mode 100644 index 1f0e8a0..0000000 --- a/gui-patches/online-shop/show-direct-entitlement-gifts/patch.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "id": "online-shop/show-direct-entitlement-gifts", - "title": "Render awarded Premium Account days in purchase receipts", - "file": "scripts/onlineshop/entitlementview.nut", - "program_behaviour": { - "stock": "Entitlement gift entries are resolved from catalog IDs.", - "patched": "The same gift renderer accepts a Premium Account gift carrying its awarded duration." - }, - "derivation": { - "requirement": "Render awarded Premium Account days in purchase receipts", - "cause": "A pack can grant a duration that is not sold as a separate catalogue product.", - "lighter_options_ruled_out": [ - "Look up a separate Premium Account SKU by duration. Pack durations are independently configurable." - ], - "if_not_applied": "The receipt can omit Premium Account days granted by a pack." - }, - "features": [ - "G-Store", - "G-Premium Account" - ], - "evidence": [ - "2.61.0.37 scripts/onlineshop/entitlementview.nut: getEntitlementGiftView uses the Premium Account icon and getEntitlementName." - ], - "edit": { - "find": "let getEntitlementGiftView = @(entitlement) (entitlement?.entitlementGift ?? []).map(function(giftId) {\r\n let config = getEntitlementConfig(giftId)", - "replace": "let getEntitlementGiftConfig = @(gift) type(gift) == \"table\" ? gift : getEntitlementConfig(gift)\r\n\r\nlet getEntitlementGiftView = @(entitlement) (entitlement?.entitlementGift ?? []).map(function(gift) {\r\n let config = getEntitlementGiftConfig(gift)" - } -} diff --git a/gui-patches/online-shop/show-direct-entitlement-gifts/patch.jsonc b/gui-patches/online-shop/show-direct-entitlement-gifts/patch.jsonc new file mode 100644 index 0000000..5da0fdf --- /dev/null +++ b/gui-patches/online-shop/show-direct-entitlement-gifts/patch.jsonc @@ -0,0 +1,21 @@ +// Render Premium Account gifts that carry their own awarded duration. +// Why the client: packs can grant a duration that is not sold as a separate product. +// Without it: receipts omit Premium Account days granted by a pack. +{ + "id": "online-shop/show-direct-entitlement-gifts", + "title": "Render awarded Premium Account days in purchase receipts", + "file": "scripts/onlineshop/entitlementview.nut", + "features": [ + "G-Store", + "G-Premium Account" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/show-direct-entitlement-gifts/replace.nut b/gui-patches/online-shop/show-direct-entitlement-gifts/replace.nut new file mode 100644 index 0000000..a1ea337 --- /dev/null +++ b/gui-patches/online-shop/show-direct-entitlement-gifts/replace.nut @@ -0,0 +1,4 @@ +let getEntitlementGiftConfig = @(gift) type(gift) == "table" ? gift : getEntitlementConfig(gift) + +let getEntitlementGiftView = @(entitlement) (entitlement?.entitlementGift ?? []).map(function(gift) { + let config = getEntitlementGiftConfig(gift) diff --git a/gui-patches/online-shop/show-entitlement-purchase-rewards/find.nut b/gui-patches/online-shop/show-entitlement-purchase-rewards/find.nut new file mode 100644 index 0000000..249ff22 --- /dev/null +++ b/gui-patches/online-shop/show-entitlement-purchase-rewards/find.nut @@ -0,0 +1,2 @@ + else if (blk?.type == EULT_BUYING_RESOURCE) { + diff --git a/gui-patches/online-shop/show-entitlement-purchase-rewards/patch.json b/gui-patches/online-shop/show-entitlement-purchase-rewards/patch.json deleted file mode 100644 index 1be7161..0000000 --- a/gui-patches/online-shop/show-entitlement-purchase-rewards/patch.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "id": "online-shop/show-entitlement-purchase-rewards", - "title": "Read each saved entitlement purchase", - "file": "scripts/userlog/userlogdata.nut", - "program_behaviour": { - "stock": "The notification parser queues receipt dialogs for resource logs carrying an entitlement name.", - "patched": "Collect each purchase log carrying its persisted grant details." - }, - "derivation": { - "requirement": "Present each saved entitlement purchase and acknowledge the log after its receipt opens.", - "cause": "Entitlement purchases belong to EULT_BUYENTITLEMENT. The resource log detail view requires decorator fields.", - "lighter_options_ruled_out": [ - "Use an EULT_BUYING_RESOURCE log for general store products. That would provide an invalid decorator log." - ], - "if_not_applied": "The saved purchase has no receipt when the profile loads." - }, - "features": [ - "G-Store", - "G-Premium Account" - ], - "evidence": [ - "2.61.0.37 scripts/userlog/userlogdata.nut: checkNewNotificationUserlogs, entitlementRewards and disableSeenUserlogs.", - "2.61.0.37 scripts/userlog/userlogviewdata.nut: EULT_BUYENTITLEMENT reads name and optional cost.", - "2.61.0.37 aces.exe: EULT_BUYENTITLEMENT is registered with value 13 at 0x1a5569e." - ], - "edit": { - "find": " else if (blk?.type == EULT_BUYING_RESOURCE) {\r\n", - "replace": " else if (blk?.type == EULT_BUYENTITLEMENT) {\r\n let entitlement = blk?.body.name\r\n let granted = blk?.body.purchaseReceipt\r\n let logId = blk?.id\r\n if (entitlement != null && granted != null && logId != null)\r\n purchaseReceipts.append({ entitlement, granted, logId })\r\n }\r\n else if (blk?.type == EULT_BUYING_RESOURCE) {\r\n" - } -} diff --git a/gui-patches/online-shop/show-entitlement-purchase-rewards/patch.jsonc b/gui-patches/online-shop/show-entitlement-purchase-rewards/patch.jsonc new file mode 100644 index 0000000..e5ffe86 --- /dev/null +++ b/gui-patches/online-shop/show-entitlement-purchase-rewards/patch.jsonc @@ -0,0 +1,21 @@ +// Collect EULT_BUYENTITLEMENT logs that carry persisted grant details. +// Why the client: the stock resource log view only reads decorator fields. +// Without it: saved purchases have no receipt when the profile loads. +{ + "id": "online-shop/show-entitlement-purchase-rewards", + "title": "Read each saved entitlement purchase", + "file": "scripts/userlog/userlogdata.nut", + "features": [ + "G-Store", + "G-Premium Account" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/show-entitlement-purchase-rewards/replace.nut b/gui-patches/online-shop/show-entitlement-purchase-rewards/replace.nut new file mode 100644 index 0000000..3eaf57d --- /dev/null +++ b/gui-patches/online-shop/show-entitlement-purchase-rewards/replace.nut @@ -0,0 +1,9 @@ + else if (blk?.type == EULT_BUYENTITLEMENT) { + let entitlement = blk?.body.name + let granted = blk?.body.purchaseReceipt + let logId = blk?.id + if (entitlement != null && granted != null && logId != null) + purchaseReceipts.append({ entitlement, granted, logId }) + } + else if (blk?.type == EULT_BUYING_RESOURCE) { + diff --git a/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/find.nut b/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/find.nut new file mode 100644 index 0000000..2c738cd --- /dev/null +++ b/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/find.nut @@ -0,0 +1,5 @@ + update_entitlements() + + scene_msg_box("purchase_done", get_cur_gui_scene(), + format(loc("userlog/buy_entitlement"), getEntitlementName(product)), + [["ok", @() null]], "ok", { cancel_fn = @() null }) diff --git a/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/patch.json b/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/patch.json deleted file mode 100644 index 54f618b..0000000 --- a/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/patch.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "id": "online-shop/use-entitlement-receipt-for-native-payment", - "title": "Use the entitlement receipt as the native payment confirmation", - "file": "scripts/onlineshop/onlinepurchase.nut", - "program_behaviour": { - "stock": "A successful native payment requests a profile update and immediately shows a text-only confirmation.", - "patched": "Track the profile task through its native error handler. The saved purchase log provides the success receipt." - }, - "derivation": { - "requirement": "Present a single success dialog for a successful native payment.", - "cause": "The immediate confirmation and the reward from the persisted purchase log would both report the same grant.", - "lighter_options_ruled_out": [ - "Keep an immediate native success box alongside the receipt. The confirmed grant would be presented again when its log arrives.", - "Show a separate success box on a refresh error. The purchase still has a pending log and would be presented a second time on the next successful refresh." - ], - "if_not_applied": "A successful native purchase can display an immediate confirmation followed by a second one from the purchase log." - }, - "features": [ - "G-Store", - "G-Premium Account" - ], - "evidence": [ - "2.61.0.37 scripts/onlineshop/onlinepurchase.nut: doYuplayPurchase displays a confirmation after update_entitlements.", - "2.61.0.37 scripts/clientstate/localprofile.nut and scripts/userlog/userlogdata.nut: the profile update triggers a gamercard update and unread reward processing.", - "2.61.0.37 scripts/tasker.nut: showErrorMessageBox displays the existing task error on a failed refresh." - ], - "edit": { - "find": " update_entitlements()\r\n\r\n scene_msg_box(\"purchase_done\", get_cur_gui_scene(),\r\n format(loc(\"userlog/buy_entitlement\"), getEntitlementName(product)),\r\n [[\"ok\", @() null]], \"ok\", { cancel_fn = @() null })", - "replace": " let { addTask } = require(\"%scripts/tasker.nut\")\r\n addTask(update_entitlements(), { showErrorMessageBox = true })" - } -} diff --git a/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/patch.jsonc b/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/patch.jsonc new file mode 100644 index 0000000..f7ef153 --- /dev/null +++ b/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/patch.jsonc @@ -0,0 +1,21 @@ +// Track native payment through its error handler and let the saved purchase log show the receipt. +// Why the client: the stock success confirmation duplicates the receipt from the purchase log. +// Without it: a successful payment shows two confirmations for the same grant. +{ + "id": "online-shop/use-entitlement-receipt-for-native-payment", + "title": "Use the entitlement receipt as the native payment confirmation", + "file": "scripts/onlineshop/onlinepurchase.nut", + "features": [ + "G-Store", + "G-Premium Account" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/replace.nut b/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/replace.nut new file mode 100644 index 0000000..fded915 --- /dev/null +++ b/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/replace.nut @@ -0,0 +1,2 @@ + let { addTask } = require("%scripts/tasker.nut") + addTask(update_entitlements(), { showErrorMessageBox = true }) diff --git a/gui-patches/tutorials/immediate-save-skip-tutorial/find.nut b/gui-patches/tutorials/immediate-save-skip-tutorial/find.nut new file mode 100644 index 0000000..8671be5 --- /dev/null +++ b/gui-patches/tutorials/immediate-save-skip-tutorial/find.nut @@ -0,0 +1,3 @@ + skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue()) + saveLocalByAccount(skipTutorialBitmaskId, skipTutorial) + } diff --git a/gui-patches/tutorials/immediate-save-skip-tutorial/patch.json b/gui-patches/tutorials/immediate-save-skip-tutorial/patch.json deleted file mode 100644 index 8a0d1f5..0000000 --- a/gui-patches/tutorials/immediate-save-skip-tutorial/patch.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "id": "tutorials/immediate-save-skip-tutorial", - "title": "新手教程询问窗勾选「不再询问」后立即落盘保存", - "file": "scripts/tutorials/nexttutorialhandler.nut", - - "program_behaviour": { - "stock": "scripts/tutorials/nexttutorialhandler.nut 的 onSkipTutorial 调用 saveLocalByAccount(skipTutorialBitmaskId, skipTutorial),默认走 saveProfile() 的 60 秒延迟定时器才调用 save_profile(false) 写盘与上行同步。", - "patched": "向 saveLocalByAccount 第三参数显式传入 @() save_profile(false)(与同文件第 52 行 prepareStartTutorial 一致),勾选或取消「不再询问」后立即触发本地 global.blk 写入与云端设置上行同步。" - }, - - "derivation": { - "requirement": "Persist the tutorial opt-out immediately so it remains set when the client restarts.", - "cause": "原版 saveLocalByAccount 默认回调 saveProfile()(scripts/clientState/saveProfile.nut SAVE_TIMEOUT = 60000)仅启动 60 秒延迟定时器,期间既不写本地磁盘也不向本地服务发送请求;若 60 秒内进程异常退出或被外部终止,跳过标记即丢失。", - "lighter_options_ruled_out": [ - "仅靠本地服务:勾选后的 60 秒窗口内客户端不发出任何网络请求,本地服务无从获知勾选状态。" - ], - "conclusion": "利用 saveLocalByAccount 原生支持的第三参数 saveFunc,传入本文件第 20 行已导入的 save_profile(false),使勾选变更即时落盘并触发 cln_bulk_set_gblk 同步。", - "if_not_applied": "勾选「不再询问」后 60 秒内若游戏崩溃或强退,下次启动仍会重复弹出新手教程询问窗。" - }, - - "features": ["A-新手流程"], - "evidence": [ - "2.61.0.37 gui.vromfs.bin:scripts/tutorials/nexttutorialhandler.nut 第 20、52、121-128 行;scripts/clientstate/localprofiledeprecated.nut 第 40-53 行(saveLocalByAccount 第三参数 saveFunc);scripts/clientstate/saveprofile.nut 第 12、65 行(SAVE_TIMEOUT = 60000)。", - "2.61.0.37 aces.exe:0x1555600(chard.save_profile 绑定)-> 0x15ffb30 -> 0x4664880(online_storage::save_locally)与 0x4663080(online_storage::send_to_server)。" - ], - - "edit": { - "find": " skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue())\r\n saveLocalByAccount(skipTutorialBitmaskId, skipTutorial)\r\n }", - "replace": " skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue())\r\n saveLocalByAccount(skipTutorialBitmaskId, skipTutorial, @() save_profile(false))\r\n }" - } -} diff --git a/gui-patches/tutorials/immediate-save-skip-tutorial/patch.jsonc b/gui-patches/tutorials/immediate-save-skip-tutorial/patch.jsonc new file mode 100644 index 0000000..17ebcf7 --- /dev/null +++ b/gui-patches/tutorials/immediate-save-skip-tutorial/patch.jsonc @@ -0,0 +1,20 @@ +// Save the tutorial opt-out immediately via save_profile(false). +// Why the client: the stock callback waits 60 s before writing or sending anything to the service. +// Without it: a crash within 60 s of ticking "do not ask again" brings the tutorial prompt back. +{ + "id": "tutorials/immediate-save-skip-tutorial", + "title": "新手教程询问窗勾选「不再询问」后立即落盘保存", + "file": "scripts/tutorials/nexttutorialhandler.nut", + "features": [ + "A-新手流程" + ], + "verified_on": [ + "2.61.0.37" + ], + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] +} diff --git a/gui-patches/tutorials/immediate-save-skip-tutorial/replace.nut b/gui-patches/tutorials/immediate-save-skip-tutorial/replace.nut new file mode 100644 index 0000000..e2721db --- /dev/null +++ b/gui-patches/tutorials/immediate-save-skip-tutorial/replace.nut @@ -0,0 +1,3 @@ + skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue()) + saveLocalByAccount(skipTutorialBitmaskId, skipTutorial, @() save_profile(false)) + } diff --git a/package-lock.json b/package-lock.json index d91de4d..f8924b5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,6 +38,10 @@ "resolved": "packages/exepatch", "link": true }, + "node_modules/@wto/jsonc": { + "resolved": "packages/jsonc", + "link": true + }, "node_modules/@wto/local-service": { "resolved": "packages/local-service", "link": true @@ -73,15 +77,30 @@ }, "packages/build": { "name": "@wto/build", - "version": "0.1.0" + "version": "0.1.0", + "dependencies": { + "@wto/jsonc": "*" + } }, "packages/exepatch": { "name": "@wto/exepatch", + "version": "0.1.0", + "dependencies": { + "@wto/jsonc": "*" + } + }, + "packages/jsonc": { + "name": "@wto/jsonc", "version": "0.1.0" }, "packages/local-service": { "name": "@wto/local-service", - "version": "0.1.0" + "version": "0.1.0", + "dependencies": { + "@wto/blk": "*", + "@wto/jsonc": "*", + "@wto/vromfs": "*" + } }, "packages/vromfs": { "name": "@wto/vromfs", diff --git a/packages/build/package.json b/packages/build/package.json index 47ad3a5..6b8b8e2 100644 --- a/packages/build/package.json +++ b/packages/build/package.json @@ -5,5 +5,8 @@ "type": "module", "exports": { ".": "./src/index.ts" + }, + "dependencies": { + "@wto/jsonc": "*" } } diff --git a/packages/build/src/gui-pack.ts b/packages/build/src/gui-pack.ts index 1e0cf80..82cc28e 100644 --- a/packages/build/src/gui-pack.ts +++ b/packages/build/src/gui-pack.ts @@ -1,47 +1,23 @@ /** - * Rebuild gui.vromfs.bin by applying declarative script modification records from `gui-patches/` - *. + * Rebuild gui.vromfs.bin by applying the script patch definitions in `gui-patches/` + * (implementation notes, format in gui-patch-definition.ts). * - * Just like `exe-patches/`, every GUI script modification lives in its own folder under - * `gui-patches/` with a `patch.json` documenting the requirement, why the local service cannot - * handle it alone, lighter options ruled out, and the exact unique text to replace. + * Every edit must find its stock text exactly once in the current script; anything else + * refuses the whole build rather than writing a half-patched archive. */ -import { readdirSync, readFileSync } from 'node:fs'; -import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { getFile, putFile, readArchive, writeArchive } from '@wto/vromfs'; +import { loadGuiPatches, type GuiScriptPatch } from './gui-patch-definition.ts'; import type { LocalEndpoint } from './network/local-endpoint.ts'; const DEFAULT_GUI_PATCHES_DIR = fileURLToPath(new URL('../../../gui-patches', import.meta.url)); const ENDPOINT_PLACEHOLDER = '{{LOCAL_ENDPOINT}}'; -export interface GuiScriptPatch { - readonly id: string; - readonly title: string; - readonly file: string; - readonly features: readonly string[]; - readonly edit: { - readonly find: string; - readonly replace: string; - }; -} - export interface GuiPackResult { readonly pack: Uint8Array; readonly applied: readonly GuiScriptPatch[]; } -export function loadGuiPatches(patchesFolder: string = DEFAULT_GUI_PATCHES_DIR): readonly GuiScriptPatch[] { - const files = collectPatchJsonPaths(patchesFolder).sort(); - return files.map((filePath) => { - const raw = JSON.parse(readFileSync(filePath, 'utf8')) as GuiScriptPatch; - if (!raw.id || !raw.file || !raw.edit?.find || typeof raw.edit.replace !== 'string') { - throw new Error(`${filePath}: invalid GUI patch record`); - } - return raw; - }); -} - export function rebuildGuiPack( stockPack: Uint8Array, endpoint: LocalEndpoint, @@ -52,17 +28,13 @@ export function rebuildGuiPack( const hostPortText = `${endpoint.host}:${endpoint.port}`; for (const patch of patches) { - const current = Buffer.from(getFile(archive, patch.file)).toString('utf8'); - const firstIndex = current.indexOf(patch.edit.find); - if (firstIndex === -1) { - throw new Error(`GUI patch ${patch.id}: target snippet not found in ${patch.file}; refusing to write`); + let current = Buffer.from(getFile(archive, patch.file)).toString('utf8'); + const newline = current.includes('\r\n') ? '\r\n' : '\n'; + for (const [index, edit] of patch.edits.entries()) { + const replace = edit.replace.replaceAll('\n', newline).replaceAll(ENDPOINT_PLACEHOLDER, hostPortText); + current = replaceUnique(current, edit.find, replace, `GUI patch ${patch.id} edit ${index + 1} in ${patch.file}`); } - if (current.indexOf(patch.edit.find, firstIndex + patch.edit.find.length) !== -1) { - throw new Error(`GUI patch ${patch.id}: target snippet appears more than once in ${patch.file}; refusing to write`); - } - const replacement = patch.edit.replace.replaceAll(ENDPOINT_PLACEHOLDER, hostPortText); - const updated = current.slice(0, firstIndex) + replacement + current.slice(firstIndex + patch.edit.find.length); - putFile(archive, patch.file, Buffer.from(updated, 'utf8')); + putFile(archive, patch.file, Buffer.from(current, 'utf8')); } return { @@ -71,15 +43,37 @@ export function rebuildGuiPack( }; } -function collectPatchJsonPaths(dir: string): string[] { - const out: string[] = []; - for (const entry of readdirSync(dir, { withFileTypes: true })) { - const full = join(dir, entry.name); - if (entry.isDirectory()) { - out.push(...collectPatchJsonPaths(full)); - } else if (entry.isFile() && entry.name === 'patch.json') { - out.push(full); +/** + * Replace the single occurrence of `find` (written with `\n` line endings) in `text`, treating + * `\r\n` and `\n` in the script as the same line break; stock scripts mix both. Only the matched + * span changes, every other byte of the script is kept. + */ +function replaceUnique(text: string, find: string, replace: string, label: string): string { + const { normalized, original } = withoutCarriageReturns(text); + const first = normalized.indexOf(find); + if (first === -1) throw new Error(`${label}: stock text not found; refusing to write`); + if (normalized.indexOf(find, first + find.length) !== -1) throw new Error(`${label}: stock text appears more than once; refusing to write`); + return text.slice(0, original[first]!) + replace + text.slice(original[first + find.length]!); +} + +/** + * `text` with `\r\n` turned into `\n`, and for every normalized index the index in `text` where + * that character's original sequence starts (a `\r\n` maps to its `\r`). + */ +function withoutCarriageReturns(text: string): { readonly normalized: string; readonly original: readonly number[] } { + const kept: string[] = []; + const original: number[] = []; + let index = 0; + while (index < text.length) { + original.push(index); + if (text[index] === '\r' && text[index + 1] === '\n') { + kept.push('\n'); + index += 2; + } else { + kept.push(text[index]!); + index += 1; } } - return out; + original.push(text.length); + return { normalized: kept.join(''), original }; } diff --git a/packages/build/src/gui-patch-definition.ts b/packages/build/src/gui-patch-definition.ts new file mode 100644 index 0000000..a9c23d4 --- /dev/null +++ b/packages/build/src/gui-patch-definition.ts @@ -0,0 +1,140 @@ +/** + * GUI script patch definitions as stored on disk, one folder per change under + * `gui-patches///`: + * + * patch.jsonc id, title, target script, features, the game versions it was verified on, + * and the list of edits; comments explain what the change does and why the + * local service cannot provide it + * .nut the edit fragments named by `edits` (stock text to find, text to put there) + * + * Fragment files hold the exact script text followed by one terminating newline, which is not + * part of the fragment. Line endings are normalised to `\n` here; applying matches regardless of + * the script's line endings (stock scripts mix `\r\n` and `\n`), so fragments survive editors + * and git newline conversion. + */ +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join } from 'node:path'; +import { parseJsonc } from '@wto/jsonc'; + +const PATCH_FILE = 'patch.jsonc'; +const ALLOWED_KEYS = new Set(['id', 'title', 'file', 'features', 'verified_on', 'edits']); + +export interface GuiScriptEdit { + /** Stock text that must occur exactly once in the target script, with `\n` line endings. */ + readonly find: string; + /** Text written in its place, with `\n` line endings. */ + readonly replace: string; +} + +export interface GuiScriptPatch { + readonly id: string; + readonly title: string; + /** Script path inside gui.vromfs.bin. */ + readonly file: string; + readonly features: readonly string[]; + readonly verifiedOn: readonly string[]; + readonly edits: readonly GuiScriptEdit[]; + readonly directory: string; +} + +/** Every definition under `root`, sorted by id. */ +export function loadGuiPatches(root: string): readonly GuiScriptPatch[] { + const patches = findDefinitionDirectories(root).map(readDefinition); + rejectDuplicateIds(patches); + return patches.sort((left, right) => left.id.localeCompare(right.id)); +} + +function findDefinitionDirectories(root: string): string[] { + const found: string[] = []; + for (const entry of readdirSync(root, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const directory = join(root, entry.name); + if (isFile(join(directory, PATCH_FILE))) found.push(directory); + else found.push(...findDefinitionDirectories(directory)); + } + return found; +} + +function readDefinition(directory: string): GuiScriptPatch { + const where = join(directory, PATCH_FILE); + const raw = readObject(where); + const unknown = Object.keys(raw).filter((key) => !ALLOWED_KEYS.has(key)); + if (unknown.length) { + throw new Error(`${where}: unknown key(s) ${unknown.join(', ')}; explanations belong in comments or the patch notes`); + } + return { + id: requiredString(raw.id, where, 'id'), + title: requiredString(raw.title, where, 'title'), + file: requiredString(raw.file, where, 'file'), + features: stringList(raw.features, where, 'features'), + verifiedOn: nonEmptyStringList(raw.verified_on, where, 'verified_on'), + edits: readEdits(raw.edits, directory, where), + directory, + }; +} + +function readEdits(value: unknown, directory: string, where: string): GuiScriptEdit[] { + if (!Array.isArray(value) || value.length === 0) throw new Error(`${where}: "edits" must be a non-empty list`); + return value.map((item, index) => { + if (!item || typeof item !== 'object') throw new Error(`${where}: edits[${index}] must be an object`); + const edit = item as Record; + const find = readFragment(directory, requiredString(edit.find, where, `edits[${index}].find`)); + if (find === '') throw new Error(`${where}: edits[${index}].find is empty`); + const replace = readFragment(directory, requiredString(edit.replace, where, `edits[${index}].replace`)); + return { find, replace }; + }); +} + +/** Fragment text with `\n` line endings and the file's terminating newline removed. */ +export function readFragment(directory: string, name: string): string { + if (name.includes('/') || name.includes('\\')) throw new Error(`${directory}: fragment "${name}" must be a file in the patch folder`); + const text = readFileSync(join(directory, name), 'utf8').replace(/^/, '').replace(/\r\n/g, '\n'); + return text.endsWith('\n') ? text.slice(0, -1) : text; +} + +function readObject(path: string): Record { + let data: unknown; + try { + data = parseJsonc(readFileSync(path, 'utf8')); + } catch (error) { + throw new Error(`${path}: ${(error as Error).message}`); + } + if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error(`${path}: expected an object`); + return data as Record; +} + +function requiredString(value: unknown, where: string, key: string): string { + if (typeof value !== 'string' || value === '') throw new Error(`${where}: "${key}" must be a non-empty string`); + return value; +} + +function stringList(value: unknown, where: string, key: string): string[] { + if (value === undefined) return []; + if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) { + throw new Error(`${where}: "${key}" must be a list of strings`); + } + return value; +} + +function nonEmptyStringList(value: unknown, where: string, key: string): string[] { + const list = stringList(value, where, key); + if (list.length === 0) throw new Error(`${where}: "${key}" must name at least one game version`); + return list; +} + +function rejectDuplicateIds(patches: readonly GuiScriptPatch[]): void { + const seen = new Map(); + for (const patch of patches) { + const previous = seen.get(patch.id); + if (previous) throw new Error(`two GUI patches use id "${patch.id}": ${previous} and ${patch.directory}`); + seen.set(patch.id, patch.directory); + } +} + +function isFile(path: string): boolean { + try { + return statSync(path).isFile(); + } catch { + return false; + } +} diff --git a/packages/build/src/index.ts b/packages/build/src/index.ts index a894d00..e8a4dce 100644 --- a/packages/build/src/index.ts +++ b/packages/build/src/index.ts @@ -6,7 +6,8 @@ export { NETWORK_CONFIG_PATH, rebuildCharPack, type CharPackResult } from './char-pack.ts'; export { patchExecutable, type ExecutableResult } from './executable.ts'; export { assertWritableCopy, GAME_FILES } from './game-copy.ts'; -export { loadGuiPatches, rebuildGuiPack, type GuiPackResult, type GuiScriptPatch } from './gui-pack.ts'; +export { rebuildGuiPack, type GuiPackResult } from './gui-pack.ts'; +export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch } from './gui-patch-definition.ts'; export { ENGINE_SETTINGS_PATH, EXTRA_STORE_BUNDLE_GUID_MAP, EXTRA_STORE_BUNDLE_GUIDS, rebuildMainPack, type MainPackResult } from './main-pack.ts'; export { redirectAddresses, type AddressChange } from './network/address-rewrite.ts'; export { hostPort, localEndpoint, localUrl, type LocalEndpoint } from './network/local-endpoint.ts'; diff --git a/packages/build/src/store/offline-bundles.ts b/packages/build/src/store/offline-bundles.ts index 752338b..2263be7 100644 --- a/packages/build/src/store/offline-bundles.ts +++ b/packages/build/src/store/offline-bundles.ts @@ -10,6 +10,7 @@ */ import { existsSync, readFileSync } from 'node:fs'; import { singleVehiclePackId, stableGuid, type BlkBlock } from '@wto/blk'; +import { parseJsonc } from '@wto/jsonc'; import { readPackBlk } from '../pack-edit.ts'; export const WPCOST_PATH = 'config/wpcost.blk'; @@ -25,11 +26,17 @@ function giftVehicles(wpcost: BlkBlock): string[] { return wpcost.blocks.filter((unit) => unit.params.some((param) => param.name === 'gift')).map((unit) => unit.name); } -/** Pack ids of `multiVehiclePacks` in tuning/store.jsonc (a plain scan; the file is JSON with comments). */ +/** Pack ids of `vehiclePacks.multiVehiclePacks` in tuning/store.jsonc. */ function multiVehiclePackIds(storeTuningPath: string): string[] { if (!existsSync(storeTuningPath)) return []; - const text = readFileSync(storeTuningPath, 'utf8'); - const start = text.indexOf('"multiVehiclePacks"'); - if (start < 0) return []; - return [...text.slice(start).matchAll(/"id"\s*:\s*"([^"]+)"/g)].map((match) => match[1]!); + const tuning = parseJsonc(readFileSync(storeTuningPath, 'utf8')) as { + readonly vehiclePacks?: { readonly multiVehiclePacks?: ReadonlyArray<{ readonly id?: unknown }> }; + }; + const packs = tuning.vehiclePacks?.multiVehiclePacks ?? []; + return packs.map((pack, index) => { + if (typeof pack.id !== 'string' || pack.id === '') { + throw new Error(`${storeTuningPath}: vehiclePacks.multiVehiclePacks[${index}].id must be a non-empty string`); + } + return pack.id; + }); } diff --git a/packages/exepatch/package.json b/packages/exepatch/package.json index b09a37e..77f2c69 100644 --- a/packages/exepatch/package.json +++ b/packages/exepatch/package.json @@ -5,5 +5,8 @@ "type": "module", "exports": { ".": "./src/index.ts" + }, + "dependencies": { + "@wto/jsonc": "*" } } diff --git a/packages/exepatch/src/definition.ts b/packages/exepatch/src/definition.ts index 101e24d..b4be444 100644 --- a/packages/exepatch/src/definition.ts +++ b/packages/exepatch/src/definition.ts @@ -2,18 +2,24 @@ * Patch definitions as stored on disk, one directory per change to the program's behaviour, * under exe-patches///: * - * patch.json what the program does, what it does after the patch, why the executable - * has to change, which features depend on it, and the bytes to write - * locate.json how to find the site + * patch.jsonc id, title, features, required patches, the game versions it was verified + * on, and the bytes to write; comments explain the change and why the local + * service cannot provide it + * locate.jsonc how to find the site * - * This code reads only what applying needs; the explanatory fields are for people. + * Unknown keys are rejected so that explanations stay in comments and in the patch notes + * instead of growing into data fields. */ import { readdirSync, readFileSync, statSync } from 'node:fs'; import { join } from 'node:path'; +import { parseJsonc } from '@wto/jsonc'; import { DefinitionError } from './errors.ts'; -const PATCH_FILE = 'patch.json'; -const LOCATE_FILE = 'locate.json'; +const PATCH_FILE = 'patch.jsonc'; +const LOCATE_FILE = 'locate.jsonc'; +const PATCH_KEYS = new Set(['id', 'title', 'features', 'requires', 'verified_on', 'edit']); +const EDIT_KEYS = new Set(['offset', 'asm', 'data', 'bytes', 'expect_original']); +const LOCATE_KEYS = new Set(['method', 'section', 'pattern']); export interface PatchEdit { /** Distance from the located site to the first byte written. */ @@ -32,6 +38,7 @@ export interface PatchDefinition { readonly title: string; readonly features: readonly string[]; readonly requires: readonly string[]; + readonly verifiedOn: readonly string[]; readonly edit: PatchEdit; readonly locate: LocateSpec; readonly directory: string; @@ -57,16 +64,22 @@ function findDefinitionDirectories(root: string): string[] { } function readDefinition(directory: string): PatchDefinition { - const patch = readJson(join(directory, PATCH_FILE)); - const locate = readJson(join(directory, LOCATE_FILE)); const where = join(directory, PATCH_FILE); + const locateWhere = join(directory, LOCATE_FILE); + const patch = readJson(where); + const locate = readJson(locateWhere); + rejectUnknownKeys(patch, PATCH_KEYS, where); + rejectUnknownKeys(locate, LOCATE_KEYS, locateWhere); if (typeof patch.id !== 'string' || typeof patch.title !== 'string') throw new DefinitionError(`${where}: needs string "id" and "title"`); - if (typeof locate.method !== 'string') throw new DefinitionError(`${join(directory, LOCATE_FILE)}: needs a string "method"`); + if (typeof locate.method !== 'string') throw new DefinitionError(`${locateWhere}: needs a string "method"`); + const verifiedOn = stringList(patch.verified_on, where, 'verified_on'); + if (verifiedOn.length === 0) throw new DefinitionError(`${where}: "verified_on" must name at least one game version`); return { id: patch.id, title: patch.title, features: stringList(patch.features, where, 'features'), requires: stringList(patch.requires, where, 'requires'), + verifiedOn, edit: readEdit(patch.edit, where), locate: locate as LocateSpec, directory, @@ -76,6 +89,7 @@ function readDefinition(directory: string): PatchDefinition { function readEdit(raw: unknown, where: string): PatchEdit { if (!raw || typeof raw !== 'object') throw new DefinitionError(`${where}: "edit" must be an object`); const edit = raw as Record; + rejectUnknownKeys(edit, EDIT_KEYS, `${where} edit`); const payload = hexBytes(edit.bytes, where, 'bytes'); const expectOriginal = hexBytes(edit.expect_original, where, 'expect_original'); if (payload.length !== expectOriginal.length) { @@ -100,7 +114,7 @@ function stringList(value: unknown, where: string, key: string): string[] { function readJson(path: string): Record { let data: unknown; try { - data = JSON.parse(readFileSync(path, 'utf-8')); + data = parseJsonc(readFileSync(path, 'utf-8')); } catch (error) { throw new DefinitionError(`${path}: ${(error as Error).message}`); } @@ -108,6 +122,13 @@ function readJson(path: string): Record { return data as Record; } +function rejectUnknownKeys(object: Record, allowed: ReadonlySet, where: string): void { + const unknown = Object.keys(object).filter((key) => !allowed.has(key)); + if (unknown.length) { + throw new DefinitionError(`${where}: unknown key(s) ${unknown.join(', ')}; explanations belong in comments or the patch notes`); + } +} + function isFile(path: string): boolean { try { return statSync(path).isFile(); diff --git a/packages/jsonc/package.json b/packages/jsonc/package.json new file mode 100644 index 0000000..24d5dbb --- /dev/null +++ b/packages/jsonc/package.json @@ -0,0 +1,9 @@ +{ + "name": "@wto/jsonc", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + } +} diff --git a/packages/jsonc/src/index.ts b/packages/jsonc/src/index.ts new file mode 100644 index 0000000..6c7e87e --- /dev/null +++ b/packages/jsonc/src/index.ts @@ -0,0 +1 @@ +export { parseJsonc } from './jsonc.ts'; diff --git a/packages/local-service/src/tuning/jsonc.ts b/packages/jsonc/src/jsonc.ts similarity index 87% rename from packages/local-service/src/tuning/jsonc.ts rename to packages/jsonc/src/jsonc.ts index 4e40599..da72246 100644 --- a/packages/local-service/src/tuning/jsonc.ts +++ b/packages/jsonc/src/jsonc.ts @@ -1,7 +1,7 @@ /** * Parse JSON with comments (// line comments and block comments), the format of the tuning - * files. Comments are blanked out, outside string literals only; the - * rest goes to JSON.parse, so the error positions still match the file. + * files and of the patch definitions. Comments are blanked out, outside string literals only; + * the rest goes to JSON.parse, so the error positions still match the file. */ export function parseJsonc(text: string): unknown { return JSON.parse(stripComments(text)); diff --git a/packages/local-service/package.json b/packages/local-service/package.json index 44ba112..d43cc38 100644 --- a/packages/local-service/package.json +++ b/packages/local-service/package.json @@ -8,6 +8,7 @@ }, "dependencies": { "@wto/blk": "*", + "@wto/jsonc": "*", "@wto/vromfs": "*" } } diff --git a/packages/local-service/src/tuning/tuning-loader.ts b/packages/local-service/src/tuning/tuning-loader.ts index 1189d5d..6231b38 100644 --- a/packages/local-service/src/tuning/tuning-loader.ts +++ b/packages/local-service/src/tuning/tuning-loader.ts @@ -7,7 +7,7 @@ import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { parseJsonc } from './jsonc.ts'; +import { parseJsonc } from '@wto/jsonc'; import { TuningError, TuningReader } from './tuning-reader.ts'; const DEFAULTS_FOLDER = fileURLToPath(new URL('../../tuning/', import.meta.url)); diff --git a/tools/src/wtotools/exepatch/definition.py b/tools/src/wtotools/exepatch/definition.py index 5539069..05f3592 100644 --- a/tools/src/wtotools/exepatch/definition.py +++ b/tools/src/wtotools/exepatch/definition.py @@ -2,10 +2,12 @@ One directory per change to the program's behaviour, under exe-patches///: - patch.json what the program does now, what it does after the patch, why the - executable has to change at all, which features depend on it, and the - bytes to write - locate.json how to find the site, and how that was established + patch.jsonc id, title, features, required patches, the game versions it was verified + on, and the bytes to write; comments explain the change and why the local + service cannot provide it + locate.jsonc how to find the site + +Unknown keys are rejected so that explanations stay in comments and in the patch notes. The engine reads these; it holds no knowledge about any particular patch. Keeping the definitions as data is what lets the installer report exactly which changes did not apply @@ -13,14 +15,17 @@ and which features are affected. """ from __future__ import annotations -import json -from dataclasses import dataclass, field +from dataclasses import dataclass from pathlib import Path +from .. import jsonc from .errors import DefinitionError -PATCH_FILE = "patch.json" -LOCATE_FILE = "locate.json" +PATCH_FILE = "patch.jsonc" +LOCATE_FILE = "locate.jsonc" +PATCH_KEYS = frozenset({"id", "title", "features", "requires", "verified_on", "edit"}) +EDIT_KEYS = frozenset({"offset", "asm", "data", "bytes", "expect_original"}) +LOCATE_KEYS = frozenset({"method", "section", "pattern"}) @dataclass(frozen=True) @@ -47,10 +52,10 @@ class PatchDefinition: title: str features: tuple[str, ...] requires: tuple[str, ...] + verified_on: tuple[str, ...] edit: PatchEdit locate: dict directory: Path | None = None - notes: dict = field(default_factory=dict) @property def locate_method(self) -> str: @@ -68,27 +73,39 @@ def load_patches(root: Path) -> list[PatchDefinition]: def _read(directory: Path) -> PatchDefinition: patch = _read_json(directory / PATCH_FILE) locate = _read_json(directory / LOCATE_FILE) + _reject_unknown_keys(patch, PATCH_KEYS, directory / PATCH_FILE) + _reject_unknown_keys(locate, LOCATE_KEYS, directory / LOCATE_FILE) for key in ("id", "title", "edit"): if key not in patch: raise DefinitionError(f"{directory / PATCH_FILE}: missing key {key!r}") if "method" not in locate: raise DefinitionError(f"{directory / LOCATE_FILE}: missing key 'method'") + verified_on = tuple(str(item) for item in patch.get("verified_on", ())) + if not verified_on: + raise DefinitionError(f"{directory / PATCH_FILE}: 'verified_on' must name at least one game version") return PatchDefinition( identifier=str(patch["id"]), title=str(patch["title"]), features=tuple(str(item) for item in patch.get("features", ())), requires=tuple(str(item) for item in patch.get("requires", ())), + verified_on=verified_on, edit=_read_edit(directory, patch["edit"]), locate=locate, directory=directory, - notes={key: value for key, value in patch.items() - if key not in ("id", "title", "features", "requires", "edit")}, ) +def _reject_unknown_keys(data: dict, allowed: frozenset[str], where: Path) -> None: + unknown = sorted(set(data) - allowed) + if unknown: + raise DefinitionError(f"{where}: unknown key(s) {', '.join(unknown)}; " + "explanations belong in comments or the patch notes") + + def _read_edit(directory: Path, raw: object) -> PatchEdit: if not isinstance(raw, dict): raise DefinitionError(f"{directory / PATCH_FILE}: 'edit' must be an object") + _reject_unknown_keys(raw, EDIT_KEYS, directory / PATCH_FILE) for key in ("bytes", "expect_original"): if not isinstance(raw.get(key), str): raise DefinitionError(f"{directory / PATCH_FILE}: edit needs a hex string {key!r}") @@ -109,15 +126,10 @@ def _hex(directory: Path, key: str, text: str) -> bytes: def _read_json(path: Path) -> dict: - if not path.is_file(): - raise DefinitionError(f"{path}: file not found") try: - data = json.loads(path.read_text("utf-8")) - except json.JSONDecodeError as error: - raise DefinitionError(f"{path}: invalid JSON: {error}") from error - if not isinstance(data, dict): - raise DefinitionError(f"{path}: expected a JSON object") - return data + return jsonc.load_object(path) + except ValueError as error: + raise DefinitionError(str(error)) from error def _reject_duplicate_ids(definitions: list[PatchDefinition]) -> None: diff --git a/tools/src/wtotools/gui_check.py b/tools/src/wtotools/gui_check.py index 34d0360..0d099d2 100644 --- a/tools/src/wtotools/gui_check.py +++ b/tools/src/wtotools/gui_check.py @@ -8,13 +8,13 @@ with the target script's real `gui.vromfs.bin` imports runs the full `SQParser` """ from __future__ import annotations -import json import re import subprocess import tempfile from dataclasses import dataclass from pathlib import Path +from .guipatch import apply, load_gui_patches from .vromfs import Archive, read_archive MOUNT_PREFIXES: tuple[tuple[str, str], ...] = ( @@ -112,54 +112,48 @@ def verify_gui_patches( endpoint: str = "127.0.0.1:47115", ) -> GuiCheckReport: archive = read_archive(gui_pack_path.read_bytes()) - patch_files = sorted(patches_dir.rglob("patch.json")) + patches = load_gui_patches(patches_dir) touched_files: list[str] = [] errors: list[str] = [] - for patch_path in patch_files: - raw = json.loads(patch_path.read_text(encoding="utf-8")) - target = raw["file"].lower() + for patch in patches: + target = patch.file.lower() if target not in archive.files: - errors.append(f"{raw['id']}: missing file {target} in gui.vromfs.bin") + errors.append(f"{patch.identifier}: missing file {target} in gui.vromfs.bin") continue - current = archive.files[target].decode("utf-8") - find_text = raw["edit"]["find"] - first = current.find(find_text) - if first == -1: - errors.append(f"{raw['id']}: target snippet not found in {target}") + if any("`" in edit.replace for edit in patch.edits): + errors.append(f"{patch.identifier}: backtick string syntax is unsupported by 2.61.0.37 Quirrel VM; use $\"...\" or +") continue - if current.find(find_text, first + len(find_text)) != -1: - errors.append(f"{raw['id']}: target snippet appears more than once in {target}") + try: + updated = apply(archive.files[target].decode("utf-8"), patch, endpoint) + except ValueError as error: + errors.append(str(error)) continue - replace_text = raw["edit"]["replace"].replace("{{LOCAL_ENDPOINT}}", endpoint) - if "`" in replace_text: - errors.append(f"{raw['id']}: backtick string syntax is unsupported by 2.61.0.37 Quirrel VM; use $\"...\" or +") - continue - updated = current[:first] + replace_text + current[first + len(find_text):] archive.put(target, updated.encode("utf-8")) if target not in touched_files: touched_files.append(target) if errors: - return GuiCheckReport(len(patch_files), 0, tuple(errors)) + return GuiCheckReport(len(patches), 0, tuple(errors)) export_cache: dict[str, set[str]] = {} native_syms = _collect_all_named_imports(archive) stock_archive = read_archive(gui_pack_path.read_bytes()) - for patch_path in patch_files: - raw = json.loads(patch_path.read_text(encoding="utf-8")) - target = raw["file"].lower() + for patch in patches: + target = patch.file.lower() stock_src = stock_archive.files[target].decode("utf-8") imp_names, imp_classes = _resolve_file_bindings(stock_src, stock_archive, export_cache, native_syms) reserved = (imp_names | imp_classes) - set(MODULE_BUILTINS) - new_locals = _declared_locals(raw["edit"]["replace"]) - _declared_locals(raw["edit"]["find"]) + new_locals: set[str] = set() + for edit in patch.edits: + new_locals |= _declared_locals(edit.replace) - _declared_locals(edit.find) collisions = sorted(new_locals & reserved) if collisions: - errors.append(f"{raw['id']}: local binding(s) {collisions} conflict with module imports in {target}") + errors.append(f"{patch.identifier}: local binding(s) {collisions} conflict with module imports in {target}") if errors: - return GuiCheckReport(len(patch_files), 0, tuple(errors)) + return GuiCheckReport(len(patches), 0, tuple(errors)) with tempfile.TemporaryDirectory(prefix="wto-gui-check-") as tmp: tmp_dir = Path(tmp) @@ -191,7 +185,7 @@ def verify_gui_patches( if line.strip(): errors.append(line.strip()) - return GuiCheckReport(len(patch_files), len(touched_files), tuple(errors)) + return GuiCheckReport(len(patches), len(touched_files), tuple(errors)) def _resolve_vromfs_path(spec: str) -> str | None: diff --git a/tools/src/wtotools/guipatch.py b/tools/src/wtotools/guipatch.py new file mode 100644 index 0000000..6b73f53 --- /dev/null +++ b/tools/src/wtotools/guipatch.py @@ -0,0 +1,124 @@ +"""GUI script patch definitions, one folder per change under gui-patches///. + + patch.jsonc id, title, target script, features, game versions verified on, and the edits; + comments explain the change and why the local service cannot provide it + .nut edit fragments named by `edits`: the stock text to find and its replacement + +Fragment files hold the exact script text followed by one terminating newline, which is not part +of the fragment. Line endings are normalised to "\\n" here; `apply` matches regardless of the +script's line endings (stock scripts mix "\\r\\n" and "\\n") and writes replacements with the +script's dominant line ending. Same rules as packages/build/src/gui-patch-definition.ts. +""" +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from . import jsonc + +PATCH_FILE = "patch.jsonc" +ALLOWED_KEYS = frozenset({"id", "title", "file", "features", "verified_on", "edits"}) +ENDPOINT_PLACEHOLDER = "{{LOCAL_ENDPOINT}}" + + +@dataclass(frozen=True) +class GuiEdit: + find: str + replace: str + + +@dataclass(frozen=True) +class GuiPatch: + identifier: str + title: str + file: str + features: tuple[str, ...] + verified_on: tuple[str, ...] + edits: tuple[GuiEdit, ...] + directory: Path + + +def load_gui_patches(root: Path) -> list[GuiPatch]: + patches = [_read(path.parent) for path in sorted(root.rglob(PATCH_FILE))] + seen: dict[str, Path] = {} + for patch in patches: + if patch.identifier in seen: + raise ValueError(f"two GUI patches use id {patch.identifier!r}: {seen[patch.identifier]} and {patch.directory}") + seen[patch.identifier] = patch.directory + return sorted(patches, key=lambda item: item.identifier) + + +def apply(text: str, patch: GuiPatch, endpoint: str) -> str: + """`text` with every edit of `patch` applied; raises ValueError when an edit does not match once.""" + newline = "\r\n" if "\r\n" in text else "\n" + for number, edit in enumerate(patch.edits, start=1): + replace = edit.replace.replace("\n", newline).replace(ENDPOINT_PLACEHOLDER, endpoint) + text = _replace_unique(text, edit.find, replace, f"{patch.identifier} edit {number} in {patch.file}") + return text + + +def _replace_unique(text: str, find: str, replace: str, label: str) -> str: + """Replace the single occurrence of `find` (written with "\\n" line endings), treating "\\r\\n" + and "\\n" in the script as the same line break; stock scripts mix both. Only the matched span + changes, every other character of the script is kept.""" + # For every normalized character, where its original sequence starts ("\r\n" maps to its "\r"). + original: list[int] = [] + kept: list[str] = [] + index = 0 + while index < len(text): + original.append(index) + if text[index] == "\r" and text[index + 1:index + 2] == "\n": + kept.append("\n") + index += 2 + else: + kept.append(text[index]) + index += 1 + original.append(len(text)) + normalized = "".join(kept) + first = normalized.find(find) + if first == -1: + raise ValueError(f"{label}: stock text not found") + if normalized.find(find, first + len(find)) != -1: + raise ValueError(f"{label}: stock text appears more than once") + return text[:original[first]] + replace + text[original[first + len(find)]:] + + +def read_fragment(directory: Path, name: str) -> str: + if "/" in name or "\\" in name: + raise ValueError(f"{directory}: fragment {name!r} must be a file in the patch folder") + text = (directory / name).read_text("utf-8-sig").replace("\r\n", "\n") + return text[:-1] if text.endswith("\n") else text + + +def _read(directory: Path) -> GuiPatch: + where = directory / PATCH_FILE + raw = jsonc.load_object(where) + unknown = sorted(set(raw) - ALLOWED_KEYS) + if unknown: + raise ValueError(f"{where}: unknown key(s) {', '.join(unknown)}; explanations belong in comments or the patch notes") + for key in ("id", "title", "file"): + if not isinstance(raw.get(key), str) or not raw[key]: + raise ValueError(f"{where}: {key!r} must be a non-empty string") + verified_on = tuple(str(item) for item in raw.get("verified_on", ())) + if not verified_on: + raise ValueError(f"{where}: 'verified_on' must name at least one game version") + edits_raw = raw.get("edits") + if not isinstance(edits_raw, list) or not edits_raw: + raise ValueError(f"{where}: 'edits' must be a non-empty list") + edits = [] + for number, item in enumerate(edits_raw, start=1): + if not isinstance(item, dict) or not isinstance(item.get("find"), str) or not isinstance(item.get("replace"), str): + raise ValueError(f"{where}: edit {number} needs fragment file names 'find' and 'replace'") + find = read_fragment(directory, item["find"]) + if not find: + raise ValueError(f"{where}: edit {number} has an empty 'find' fragment") + edits.append(GuiEdit(find=find, replace=read_fragment(directory, item["replace"]))) + return GuiPatch( + identifier=raw["id"], + title=raw["title"], + file=raw["file"], + features=tuple(str(item) for item in raw.get("features", ())), + verified_on=verified_on, + edits=tuple(edits), + directory=directory, + ) diff --git a/tools/src/wtotools/jsonc.py b/tools/src/wtotools/jsonc.py new file mode 100644 index 0000000..88edd8e --- /dev/null +++ b/tools/src/wtotools/jsonc.py @@ -0,0 +1,64 @@ +"""JSON with comments: the format of the patch definitions and the local service's tuning files. + +Line comments (//) and block comments are blanked out, outside string literals only; the rest +goes to json.loads, so error positions still match the file. Same rules as the TypeScript +reader in packages/jsonc. +""" +from __future__ import annotations + +import json +from pathlib import Path + + +def loads(text: str): + return json.loads(_strip_comments(text)) + + +def load_object(path: Path) -> dict: + """The object stored in `path`; raises ValueError naming the file when it is not one.""" + if not path.is_file(): + raise ValueError(f"{path}: file not found") + try: + data = loads(path.read_text("utf-8-sig")) + except json.JSONDecodeError as error: + raise ValueError(f"{path}: invalid JSON: {error}") from error + if not isinstance(data, dict): + raise ValueError(f"{path}: expected a JSON object") + return data + + +def _strip_comments(text: str) -> str: + out: list[str] = [] + index = 0 + length = len(text) + while index < length: + ch = text[index] + nxt = text[index + 1] if index + 1 < length else "" + if ch == '"': + end = _string_end(text, index) + out.append(text[index:end]) + index = end + elif ch == "/" and nxt == "/": + while index < length and text[index] != "\n": + index += 1 + elif ch == "/" and nxt == "*": + end = text.find("*/", index + 2) + stop = length if end < 0 else end + 2 + out.append("".join("\n" if c == "\n" else " " for c in text[index:stop])) + index = stop + else: + out.append(ch) + index += 1 + return "".join(out) + + +def _string_end(text: str, start: int) -> int: + index = start + 1 + while index < len(text): + if text[index] == "\\": + index += 2 + elif text[index] == '"': + return index + 1 + else: + index += 1 + return len(text)