-- ============================================================ -- PhantomGladiator — 《影之刃零》斗蛐蛐 Mod (UE4SS Lua) -- 让 NPC 互相为敌、召唤单位、观战、慢动作、自由镜头。 -- 功能快捷键在面板配置;首次使用全部未绑定。 -- ============================================================ local Config = require("config") -- Before any module can register one: hooks on blueprints that leave with their map (hook_registry.lua). local hookRegistry = require("hook_registry").install(_G) local UEHelpers = require("UEHelpers") local Session = require("battle_session") local CombatProbe = require("combat_probe") local AttackProfile = require("attack_profile") local Catalog = require("npc_catalog") local AssetExporter = require("asset_inventory") local ArenaController = require("arena_controller") local PanelRuntime = require("panel_runtime") local SpectatorMode = require("spectator_mode") local SpawnPolicy = require("spawn_policy") local RuntimeSession = require("runtime_session") local SpawnAudit = require("spawn_audit") local CodexExporter = require("codex_catalog_export") local SpawnGuard = require("spawn_guard") local SpawnInspector = require("spawn_inspector") local WorldMapCatalog = require("world_map_catalog") local SpawnCatalog = require("spawn_catalog_export") local ReferenceAudit = require("asset_reference_audit") local TableCatalog = require("table_catalog_export") local SummonLinks = require('arena_summon_links') local BossHUD = require('arena_hud') local EngineObjectState = require('engine_object_state') local UEObserve = require('ue_observe') local UnitKeys = require('unit_keybinds') local ArenaActivity = require('arena_activity') local FreeCamera = require('free_camera') local GrabStudy = require('grab_study') local ArenaGrabs = require('arena_grabs') local StatMatch = require('stat_match') local ObserverGuard = require('observer_guard') local SpectatorTargets = require('spectator_targets') local KeyRouter = require('key_router') local KeyPoll = require('key_poll') local SpawnDifficulty=require('spawn_difficulty') local AIDifficulty=require('ai_difficulty') local Companion=require('companion') local FunFeatures=require('fun_features') local SpawnLevel=require('spawn_level') local StatFormulaProbe=require('stat_formula_probe') local StatFieldProbe=require('stat_field_probe') local CompanionHitProbe=require('companion_hit_probe') local AttackFactionScan=require('attack_faction_scan') local CodexArtProbe=require('codex_art_probe') local CodexIcons=require('codex_icons') local ImmortalTeams=require('immortal_teams') local BattleClockHUD=require('battle_clock_hud') local CombatLock=require('combat_lock') local CompanionBars=require('companion_bars') local AreaLevels=require('area_levels') local HomeLevels=require('home_levels') local Escorts=require('escorts') local Mounts=require('mounts') local BossStages=require('boss_stages') local ArenaExecutions=require('arena_executions') local ExecutionCamera=require('execution_camera') local MOD = "[PhantomGladiator]" local runLogPath=Config.RuntimePath..'/run-'..os.date('%Y%m%d-%H%M%S')..'.log' local runLogBytes,runLogWarning=0,false local function log(msg) local line=string.format('%s %s\n',MOD,tostring(msg)) print(line) -- UE4SS.log is overwritten on game restart. Preserve bounded per-load UTF-8 -- evidence outside the source tree, without touching game save data. local durable=os.date('%Y-%m-%d %H:%M:%S')..' '..line if runLogBytes+#durable>8*1024*1024 then return end local ok,saved=pcall(function() local file=io.open(runLogPath,'ab') if not file then return false end local wrote=file:write(durable) local flushed=file:flush() local closed=file:close() return wrote~=nil and flushed~=nil and closed~=nil end) if ok and saved then runLogBytes=runLogBytes+#durable elseif not runLogWarning then runLogWarning=true;print(MOD..' 独立运行日志写入未确认;UE4SS日志仍保留\n') end end if hookRegistry then hookRegistry.log=log end local BUILD = "v0.40.25" SpawnPolicy.loadTrials(Config.RuntimePath..'/spawn-trials.tsv',log) SpawnPolicy.enableAllCatalog() log('[SpawnPolicy] 用户开启全部目录尝试召唤;总量不设上限;运行时检查Actor继承和对象有效性') local function safeValid(obj) if obj == nil then return false end local ok, value = pcall(function() return obj:IsValid() end) return ok and value == true end local engineObjectState=EngineObjectState.new({log=log}) local function engineValid(obj) return safeValid(obj) and engineObjectState:check(obj)~=false end UEObserve.setEngineValidator(function(obj) return engineObjectState:check(obj) end) local function checked(obj) if not safeValid(obj) then error("object invalid; access refused") end return obj end local function objectName(obj) if not safeValid(obj) then return "UNKNOWN(invalid)" end local ok, value = pcall(function() return obj:GetFullName() end) return ok and tostring(value) or "UNKNOWN(name)" end local function actorIsDestroying(actor) checked(actor) return actor:IsActorBeingDestroyed() end -- A valid wrapper can still point to an Actor already entering destruction. local function summonActorLive(actor) local ok,destroying=pcall(actorIsDestroying,actor) return ok and destroying==false end local battle = Session.new(log) local probeFinished local probe = CombatProbe.new({log=log, valid=safeValid, config=Config.Probe, onStop=function(state) if probeFinished then probeFinished(state) end end}) local probeSampleGen = 0 local arenaActors = {} local spawnRoutes={} local arena local panelRuntime local spectator local bossHUD local arenaActivity local arenaGrabs local statMatch local spawnDifficulty local spawnLevel local statProbe local fieldProbe local companionHitProbe local attackScan local codexArt local codexIcons local companions local aiDifficulty local funFeatures local immortalTeams local clockHUD local combatLock local playerAim local aiParams local bossCombos local fightWatch local onGround local arenaExecutions local executionCamera local mounts local arenaSupport={} local bossStages local BeginArenaObservation local spawnAudit=SpawnAudit.new(Config.RuntimePath.."/spawn-attempts.tsv",log) local spawnGuard=SpawnGuard.new() local spawnInspector=SpawnInspector.new({log=log,canSpawn=SpawnPolicy.check}) local function FNameToString(v) local ok, s = pcall(function() return v:ToString() end) if ok and s then return s end return tostring(v) end -- ---------- 基础工具 ---------- function arenaSupport:viewportWorld() if type(UEHelpers.GetGameViewportClient)~='function' then return nil end local ok,viewport=pcall(UEHelpers.GetGameViewportClient) if not ok or not safeValid(viewport) then return nil end local world=UEObserve.field(viewport,'World') return safeValid(world) and world or nil end function arenaSupport:controllerCurrent(pc,world) local player=UEObserve.field(pc,'Player') local owner=UEObserve.field(player,'PlayerController') local key=UEObserve.key(pc) if not key or UEObserve.key(owner)~=key then return false end if type(UEHelpers.GetGameViewportClient)=='function' then local ok,viewport=pcall(UEHelpers.GetGameViewportClient) if ok and safeValid(viewport) then if not safeValid(UEObserve.field(viewport,'World')) then return false end local players=UEObserve.array(UEObserve.field(UEObserve.field(viewport,'GameInstance'),'LocalPlayers')) if not players then return false end local found=false for _,current in ipairs(players)do if UEObserve.key(current)==UEObserve.key(player) then found=true;break end end if not found then return false end end end if safeValid(world) then local ok,current=pcall(function()return pc:GetWorld()end) if not ok or UEObserve.key(current)~=UEObserve.key(world) then return false end end return true end -- A retained controller can remain valid after its local player has moved to another controller/world. local function GetRealPlayerController() local world=arenaSupport:viewportWorld() local function current(pc) local okP, good = pcall(function() if not safeValid(pc) then return false end local cls = pc:GetClass() if not safeValid(cls) or objectName(cls):find("DebugCameraController") then return false end return arenaSupport:controllerCurrent(pc,world) end) return okP and good end -- Resolve the viewport's current local players afresh; no controller survives here across calls/worlds. if type(UEHelpers.GetGameViewportClient)=='function' then local ok,viewport=pcall(UEHelpers.GetGameViewportClient) if ok and safeValid(viewport) and not safeValid(world) then return nil end if ok and safeValid(viewport) then local instance=UEObserve.field(viewport,'GameInstance') for _,player in ipairs(UEObserve.array(UEObserve.field(instance,'LocalPlayers')) or {})do local pc=UEObserve.field(player,'PlayerController') if current(pc) then return pc end end return nil end end local ok,list=pcall(FindAllOf,'PlayerController') if not ok then return nil end for _,pc in ipairs(UEObserve.array(list) or {})do if current(pc) then return pc end end return nil end local function GetCurrentWorld() local world=arenaSupport:viewportWorld() if world then return world end local pc=GetRealPlayerController() if not safeValid(pc) then return nil end local ok,current=pcall(function()return pc:GetWorld()end) return ok and safeValid(current) and current or nil end local function GetPlayerPawn() local pc = GetRealPlayerController() local pawn=UEObserve.field(pc,'Pawn') if not summonActorLive(pawn) then return nil end local world=GetCurrentWorld() local ok,actual=pcall(function()return pawn:GetWorld()end) if ok and safeValid(world) and UEObserve.key(actual)==UEObserve.key(world) then return pawn end return nil end local function GetLocation(actor) if not safeValid(actor) then return nil end local ok, loc = pcall(function() return actor:K2_GetActorLocation() end) if ok and loc then return loc end return nil end function arenaSupport:pointText(point) local ok,x,y,z=pcall(function()return point.X,point.Y,point.Z end) if not ok or type(x)~='number' or type(y)~='number' or type(z)~='number' then return '?' end return string.format('%.1f,%.1f,%.1f',x,y,z) end function arenaSupport:spawnSpace(actor,transform,world) local ok,actualWorld=pcall(function()return actor:GetWorld()end) local match='unknown' if ok and safeValid(actualWorld) then match=UEObserve.key(actualWorld)==UEObserve.key(world) end local mesh=UEObserve.field(actor,'Mesh') return string.format('requested=%s actual=%s world_match=%s hidden=%s mesh_visible=%s', self:pointText(transform and transform.Translation),self:pointText(GetLocation(actor)),tostring(match), tostring(UEObserve.field(actor,'bHidden')),tostring(UEObserve.field(mesh,'bVisible'))) end -- World time in seconds (stops while the game is paused, follows slow motion); nil before a world exists. local gameplayStatics local function GameSeconds() if not safeValid(gameplayStatics) then gameplayStatics=StaticFindObject('/Script/Engine.Default__GameplayStatics') end local world=GetCurrentWorld() if not safeValid(gameplayStatics) or not safeValid(world) then return nil end local ok,seconds=pcall(function()return gameplayStatics:GetTimeSeconds(world)end) return ok and type(seconds)=='number' and seconds or nil end local function DistSq(a, b) local dx, dy, dz = a.X - b.X, a.Y - b.Y, a.Z - b.Z return dx * dx + dy * dy + dz * dz end local function IsExcluded(pawn) if not safeValid(pawn) then return true end local ok, name = pcall(function() return pawn:GetFullName() end) if not ok or not name then return true end for _, kw in ipairs(Config.ExcludeClassKeywords) do if name:find(kw) then return true end end return false end local function GetGameplayStatics() local gps = StaticFindObject("/Script/Engine.Default__GameplayStatics") if gps and gps:IsValid() then return gps end return nil end local playerNeutral = false local dilationIndex = 1 -- 旧态度返回值修改已移除。脚本态度函数由 CombatProbe 正确注册只读回调。 -- 单位类型目录与活怪列表分开;已知路径及选择跨热重载保存。 local npcCatalog=Catalog.new({log=log,valid=safeValid,getPlayer=GetPlayerPawn, path=Config.CatalogPath,knownPaths=Config.KnownMonsterClasses,canSpawn=SpawnPolicy.check,allowActors=true, audit=function(stage,unit,detail) return spawnAudit:record(stage,unit,detail) end}) local exporter=AssetExporter.new({log=log,path=Config.RuntimePath, config=Config.AssetCatalog}) local worldMaps=WorldMapCatalog.new({log=log,getWorld=GetCurrentWorld}) local codexExporter=CodexExporter.new({log=log,path=Config.RuntimePath.."/codex.tsv",getWorld=GetCurrentWorld, locationsPath=Config.RuntimePath..'/codex-locations.tsv', maps=worldMaps,onWritten=function()if bossHUD then bossHUD:reloadCodex()end end}) -- ---------- 强制锁敌:走 SGameAI 自家的作战指令 ---------- -- SGameAIComponent:ForceIntoCombat(Target) = "进入战斗,目标是他"; -- 另把目标写进 AI 的黑板目标键(PBZ_TargetingHandler_AI 从那里读目标)做双保险。 local function GetAIComp(pawn) if not safeValid(pawn) then return nil end local ok, sg = pcall(function() local ctrl = pawn.Controller if not ctrl or not ctrl:IsValid() then return nil end local c = ctrl.SGameAIComponent return (c ~= nil and c:IsValid()) and c or nil end) if ok then return sg end return nil end -- 本作的原生仇恨组件(挂在每个 NPC/玩家身上,感知与索敌都以它为准) local function GetHatredComp(pawn) if not safeValid(pawn) then return nil end local ok, h = pcall(function() return pawn.BP_PBZHatredManagerComponent end) if ok and h ~= nil then local okV, v = pcall(function() return h:IsValid() end) if okV and v then return h end end return nil end local function HatredListContains(hm, actor) if not safeValid(hm) or not safeValid(actor) then return nil end local found, unreadable = false, false local ok = pcall(function() local hl = hm.HatredList local addr = actor:GetAddress() for i = 1, #hl do local okE, hit = pcall(function() local entry = hl[i] return safeValid(entry) and entry:GetAddress() == addr end) if not okE then unreadable = true end if okE and hit then found = true; return end end end) if found then return true end if not ok or unreadable then return nil end return false end function arenaSupport:rememberHatred(hm,victim) -- A record whose objects are gone has nothing left to put back, whoever's unit it was. Kept, it would hold up every -- later cleanup and summon: an adopted summon is engaged before the arena registers it as its own. battle:remember("hatred:" .. hm:GetAddress() .. ":" .. victim:GetAddress(), function() if not engineValid(hm) or not engineValid(victim) then return true,"参赛对象有效性读回=false,目标已不存在;丢弃过期成员记录" end checked(hm); checked(victim) hm:RemoveActorFromHatredList(victim) local has = HatredListContains(hm, victim) return has == false, "成员读回=" .. tostring(has) end) end local function AddHatred(attacker, victim) local hm = GetHatredComp(attacker) if not hm or not safeValid(victim) then return false, "对象无效" end local before = HatredListContains(hm, victim) if before == nil then return false, "成员读取失败" end if before then return true, "原本存在" end arenaSupport:rememberHatred(hm,victim) local ok, err = pcall(function() hm:AddActorToHatredList(victim, false) end) local has = HatredListContains(hm, victim) -- 仅对本Mod创建的两名参赛者保留历史已观察到出招的数组配对路径。 local ownA,ownB=false,false for _,actor in ipairs(arenaActors) do if safeValid(actor) then ownA=ownA or actor:GetAddress()==attacker:GetAddress() ownB=ownB or actor:GetAddress()==victim:GetAddress() end end -- A rider's mount carries the fight for its rider (mounts.lua). if mounts and mounts:holds(attacker) then ownA=true end if not has and ownA and ownB then local wrote=pcall(function() checked(hm); checked(victim) local list=hm.HatredList list[#list+1]=victim end) has=HatredListContains(hm,victim) log("参赛者配对数组写入=" .. tostring(wrote) .. ";成员读回=" .. tostring(has)) return wrote and has==true,"参赛者数组配对(官方门禁尚未修复)" end log("官方Add调用=" .. tostring(ok) .. ";成员读回=" .. tostring(has)) return ok and has == true, ok and (has and "官方Add读回存在" or "官方Add未接纳") or tostring(err) end -- ---------- 原生阵营系统 ---------- -- NPC 和玩家身上的 "Faction Component"(UFactionComponent)决定谁和谁是敌人, -- 伤害、格挡、攻击开关等系统都引用它。SetFactionRelationOverride(对手, 关系, Both) -- 可以针对单个对手覆盖敌我关系,Both=true 时双方同时生效。 -- ETeamAttitude: 0=Friendly 1=Neutral 2=Hostile local ATTITUDE_NAME = { [0] = "友好", [1] = "中立", [2] = "敌对" } local HOSTILE, NEUTRAL = 2, 1 local function GetFactionComp(pawn) if not safeValid(pawn) then return nil end local ok, fc = pcall(function() return pawn["Faction Component"] end) if ok and fc ~= nil then local okV, v = pcall(function() return fc:IsValid() end) if okV and v then return fc end end return nil end local function ReadRelation(a, b) if not safeValid(b) then return nil end local fc = GetFactionComp(a) if not fc then return nil end local ok, r = pcall(function() return fc:GetFactionRelation(b) end) if ok and type(r) == "number" then return r end return nil end local function RelationName(r) if r == nil then return "?" end return ATTITUDE_NAME[r] or tostring(r) end local function ReadFactionTag(pawn) local fc = GetFactionComp(pawn) if not fc then return "无阵营组件" end local ok, tag = pcall(function() return fc:GetCurrnetFaction() end) if not ok or tag == nil then return "?" end local okN, n = pcall(function() return FNameToString(tag.TagName) end) return okN and n or "?" end local function SetFactionRelation(a, b, relation) local fa, fb = GetFactionComp(a), GetFactionComp(b) if not fa or not fb then return false,nil,nil end local beforeA,beforeB = ReadRelation(a,b),ReadRelation(b,a) if beforeA == nil or beforeB == nil then return false,beforeA,nil end local function rememberOne(source,target,fc,original) battle:remember("relation:" .. source:GetAddress() .. ":" .. target:GetAddress(), function(gone) local function expired(obj) if gone and gone[obj] then return true end if engineValid(obj) then return false end if gone then gone[obj]=true end return true end if expired(source) or expired(target) or expired(fc) then return true,"参赛对象有效性读回=false,目标已不存在;丢弃过期关系记录" end checked(source); checked(target); checked(fc) -- 停止擂台时仍开启的全局观战模式继续生效,不撤销它的单向中立关系。 if spectator and spectator:status().enabled_requested then local player=GetPlayerPawn() if safeValid(player) and target:GetAddress()==player:GetAddress() and source:GetAddress()~=player:GetAddress() then fc:SetFactionRelationOverride(target,NEUTRAL,false) local neutral=ReadRelation(source,target) return neutral==NEUTRAL,"观战模式仍开启,保留单向中立;读回="..tostring(neutral) end end fc:ClearFactionRelationOverride(target) local actual=ReadRelation(source,target) return actual==original,"清除本轮覆盖;原关系=" .. tostring(original) .. ";读回=" .. tostring(actual) .. ";原覆盖结构未知" end) end rememberOne(a,b,fa,beforeA); rememberOne(b,a,fb,beforeB) local ok=pcall(function() fa:SetFactionRelationOverride(b,relation,true) end) local afterA,afterB=ReadRelation(a,b),ReadRelation(b,a) log(string.format("关系写入=%s;A %s→%s;B %s→%s",tostring(relation),tostring(beforeA),tostring(afterA),tostring(beforeB),tostring(afterB))) return ok and afterA==relation and afterB==relation,beforeA,afterA end local function GetASC(pawn) if not safeValid(pawn) then return nil end local ok, asc = pcall(function() return pawn.AbilitySystemComponent end) if ok and asc ~= nil then local okV, v = pcall(function() return asc:IsValid() end) if okV and v then return asc end end return nil end local aiLib = nil local function GetAILib() if aiLib then local okV, v = pcall(function() return aiLib:IsValid() end) if okV and v then return aiLib end end for _, path in ipairs({ "/SGameAI/BP_SGameAIFunctionLibrary.Default__BP_SGameAIFunctionLibrary_C", "/SGameAI/Utils/BP_SGameAIFunctionLibrary.Default__BP_SGameAIFunctionLibrary_C", }) do local ok, obj = pcall(StaticFindObject, path) if ok and obj ~= nil and pcall(function() return obj:IsValid() end) and obj:IsValid() then aiLib = obj return obj end end local ok, obj = pcall(FindObject, "BP_SGameAIFunctionLibrary_C", "Default__BP_SGameAIFunctionLibrary_C") if ok and obj ~= nil and pcall(function() return obj:IsValid() end) and obj:IsValid() then aiLib = obj return obj end return nil end -- 碰撞诊断:胶囊体和模型的碰撞是否开启、用的什么碰撞配置 -- ECollisionEnabled: 0=关 1=仅查询 2=仅物理 3=查询+物理 local function DescribeCollision(pawn) if not safeValid(pawn) then return "UNKNOWN(invalid pawn)" end local function comp(c) if c == nil then return "无" end local okV, v = pcall(function() return c:IsValid() end) if not okV or not v then return "无" end local en, prof = "?", "?" pcall(function() en = tostring(c:GetCollisionEnabled()) end) pcall(function() prof = FNameToString(c:GetCollisionProfileName()) end) return en .. "/" .. prof end local cap, mesh = nil, nil pcall(function() cap = pawn.CapsuleComponent end) pcall(function() mesh = pawn.Mesh end) return string.format("胶囊=%s 模型=%s", comp(cap), comp(mesh)) end -- 延迟生成只负责拿到Actor;控制器登记所有权后才会调用FinishSpawn。 -- given: the catalog entry of a unit summoned along with the selected one (escorts.lua). local function SpawnViaAILib(cls, t, world, given, team) if not safeValid(cls) or not safeValid(world) then return nil,"Class/World无效","not_started" end local className=objectName(cls) local classPath=className:match(" (/.+)$") local allowed,why=SpawnPolicy.check(classPath) if not allowed then return nil,why,"not_started" end -- A unit that writes story progress itself only once the story holds what it would write (story_writes.lua). local storyAllowed,storyWhy=arenaSupport.storyWrites:allowsUnit(classPath) if not storyAllowed then return nil,storyWhy,"not_started" end local entry=given or npcCatalog:selected() if not entry or entry.path~=classPath or type(entry.isNPC)~='boolean' then return nil,'实体类型未读回','not_started' end local npc=entry.isNPC local lib=npc and GetAILib() or StaticFindObject('/Script/Engine.Default__GameplayStatics') if not safeValid(lib) then return nil,'找不到函数库','not_started' end local pc=GetRealPlayerController() local player=UEObserve.field(pc,'Pawn') if not summonActorLive(player) then player=nil end local context=objectName(world)..' controller='..tostring(UEObserve.key(pc))..' player='..tostring(UEObserve.key(player)) ..' player_at='..arenaSupport:pointText(GetLocation(player))..' requested='..arenaSupport:pointText(t and t.Translation) if not spawnAudit:record("spawn_deferred_begin",classPath,context) then return nil,"阶段日志写入失败;未生成","not_started" end if not safeValid(cls) or not safeValid(lib) or not safeValid(world) then return nil,"生成前对象失效","not_started" end local pawn = nil local ok, err = pcall(function() if npc then pawn=lib:SpawnAIDefered(cls,t,nil,world) else pawn=lib:BeginDeferredActorSpawnFromClass(world,cls,t,1,nil,1) end end) spawnAudit:record("spawn_deferred_return",classPath,"call="..tostring(ok).." valid="..tostring(safeValid(pawn))) if not ok then return nil, "延迟生成接口报错,创建结果未知: " .. tostring(err),"uncertain" end local okV = safeValid(pawn) if not okV then return nil, "延迟生成接口未返回有效实例;创建结果未知","uncertain" end spawnRoutes[pawn]=npc and 'npc' or 'actor' if team=='companion' and classPath==require('companion_profile').second then arenaSupport.muDeferred=arenaSupport.muDeferred or setmetatable({},{__mode='k'}) arenaSupport.muDeferred[pawn]=true end if arenaSupport.hunBody then arenaSupport.hunBody:capture(pawn,classPath)end log('生成路径读回='..spawnRoutes[pawn]..';actor='..objectName(pawn)) return pawn,nil,"created" end -- leader: the unit an escort comes with; the escort takes its level, as a map group shares its domain's. local function FinishSpawnViaAILib(pawn,t,world,leader,replacing) if not summonActorLive(pawn) or not safeValid(world) then return false,"Actor/World无效或Actor正在销毁,保留清理记录" end local route=spawnRoutes[pawn] if route~='npc' and route~='actor' then return false,'生成路径未登记,保留清理记录' end if arenaSupport.muDeferred and arenaSupport.muDeferred[pawn] then local ok,why=require('companion_mu').isolate(pawn,StaticFindObject('/Script/SGameAI.Default__SGameAIFunctionLibrary')) if not ok then return false,why end end if arenaSupport.hunBody then local ready,why=arenaSupport.hunBody:prepare(pawn) if not ready then return false,why end end if route=='npc' and arenaActivity then arenaActivity:prepare(pawn) end -- The app's chosen difficulty goes into this actor's own config slots before it initialises. if route=='npc' and spawnDifficulty then local applied=spawnDifficulty:prepare(pawn,objectName(pawn)) -- Its AI asks for the difficulty while it initialises, so the hooks must be in place first. if applied and applied.applied and aiDifficulty then aiDifficulty:ensure(pawn,spawnDifficulty:levelOf(pawn)) end end -- Map NPCs get their Level from their spawner before they start; a summoned one gets it here. if route=='npc' and spawnLevel then local leveled,level=pcall(function()return spawnLevel:prepare(pawn,objectName(pawn),leader)end) if not leveled then log('[SpawnLevel] 出生前失败: '..tostring(level)) elseif type(level)=='table' and level.report and arenaSupport.matchReport then arenaSupport.matchReport:rememberLevel(pawn,level.report,leader) end end -- A spot behind a wall comes back to this side of it (spawn_spot.lua). if route=='npc' and not replacing and arenaSupport.spawnSpot then local cleared,clearError=pcall(function()arenaSupport.spawnSpot:clear(world,t)end) if not cleared then log('[SpawnSpot] 查墙失败: '..tostring(clearError)) end end -- A summon starts on the ground, not over it (on_ground.lua). local placedOnGround=route=='npc' and not replacing and onGround and onGround:place(pawn,t,world) or nil -- A rider's script puts its mount where the rider's spawner stands, and a few bosses aim a move at their spawner; -- a summon gets one where it is summoned (mounts.lua). if route=='npc' and mounts then local placed,placeError=pcall(function()mounts:prepare(pawn,t,world)end) if not placed then log('[Mount] 出生前失败: '..tostring(placeError)) end end -- 冷荼's abilities find her arena by class; its markers go around her before she starts (boss_stages.lua). if route=='npc' and bossStages then local placed,placeError=pcall(function()bossStages:prepare(pawn,t,world)end) if not placed then log('[BossStage] 出生前失败: '..tostring(placeError)) end end local lib=route=='npc' and GetAILib() or StaticFindObject('/Script/Engine.Default__GameplayStatics') if not summonActorLive(pawn) or not safeValid(lib) or not safeValid(world) then return false,"FinishSpawn前对象失效或进入销毁,保留清理记录" end local name=objectName(pawn) if arenaSupport.menghuaPhase and not leader then local ready,why=arenaSupport.menghuaPhase:prepare(pawn) if not ready then return false,why end end local standalone if route=='npc' and not leader and arenaSupport.standaloneStoryUnits:matches(name) then local why standalone,why=arenaSupport.standaloneStoryUnits:prepare(pawn) if not standalone then return false,why end end if not spawnAudit:record("finish_spawn_begin",name,"所有权已登记;"..objectName(world)) then return false,"FinishSpawn阶段日志写入失败;未继续初始化" end if not safeValid(pawn) or not safeValid(lib) or not safeValid(world) then return false,"FinishSpawn前对象失效" end local ok2, err2 = pcall(function() if route=='npc' then lib:FinishSpawnAIDefered(pawn,t,world) else lib:FinishSpawningActor(pawn,t,1) end end) local live=summonActorLive(pawn) local space=live and arenaSupport:spawnSpace(pawn,t,world) or 'spatial_read=skipped_destroying' local audited=spawnAudit:record("finish_spawn_return",name,"call="..tostring(ok2).." live="..tostring(live)..' '..space) if not ok2 or not audited then return false,"FinishSpawn未确认: "..tostring(err2)..";保留对象供F4清理" end if not live then return false,"FinishSpawn 后对象进入销毁或状态不可读" end if arenaSupport.hunBody then local ready,why=arenaSupport.hunBody:finished(pawn) if not ready then return false,why end end if standalone and not arenaSupport.standaloneStoryUnits:verify(standalone) then return false,'出场时的剧情查找未读回;保留对象供清理' end -- 冷荼 born under her old save ID (a checkpoint cleared for the save-repair button) moves to the mod's now. if route=='npc' and bossStages then local moved,moveError=pcall(function()bossStages:finished(pawn)end) if not moved then log('[BossStage] 出生后失败: '..tostring(moveError)) end end if not summonActorLive(pawn) then return false,"出生后对象进入销毁或状态不可读" end if onGround then onGround:settle(pawn,placedOnGround) end if route=='npc' and summonActorLive(pawn) then local placeholder=mounts and mounts:placeholderOf(pawn) if not placeholder and arenaSupport.swordFormation then placeholder=arenaSupport.swordFormation:placeholderOf(pawn) end if placeholder then arenaSupport.summonTargetRegistration:enqueue(pawn,placeholder,world) end end return summonActorLive(pawn),nil end -- 请求原生登场并读回可见状态;不移除游戏效果。 local function FinishEntrance(pawn) local lib=GetAILib() local world=GetCurrentWorld() local live=summonActorLive(pawn) if not live or not safeValid(lib) or not safeValid(world) then return false,live end local name=objectName(pawn) if not spawnAudit:record("activate_begin",name,objectName(world)) then return false,live end local activated=pcall(function() lib:ActivateAI(pawn,world) end) live=summonActorLive(pawn) local space=live and arenaSupport:spawnSpace(pawn,nil,world) or 'spatial_read=skipped_destroying' spawnAudit:record("activate_return",name,"call="..tostring(activated).." live="..tostring(live)..' '..space) if live then log(string.format(" 登场处理: ActivateAI调用=%s(行为未验收) | %s",tostring(activated),DescribeCollision(pawn))) end return activated,live end -- ---------- 战况只读采样 ---------- local function GetHP(pawn) if not safeValid(pawn) then return nil end -- APBZCharacter.AttributeSetBase 已由本地头文件确认;优先直接读,避免每秒全局扫描。 local okDirect, direct = pcall(function() local attributes = pawn.AttributeSetBase if not safeValid(attributes) then return nil end return attributes.Health.CurrentValue end) if okDirect and type(direct) == "number" then return direct end local hp = nil pcall(function() local sets=arenaSupport:attributeSetsForSupport() if not sets then return end local pawnAddr = pawn:GetAddress() local ascAddr = nil pcall(function() local asc = pawn.AbilitySystemComponent if asc and asc:IsValid() then ascAddr = asc:GetAddress() end end) for _, s in ipairs(sets) do local okO, outer = pcall(function() if not safeValid(s) then return nil end return s:GetOuter() end) if okO and outer and outer:IsValid() then local oa = outer:GetAddress() if oa == pawnAddr or oa == ascAddr then hp = s.Health.CurrentValue return end end end end) return hp end local function StartDuelWatch(a,b) local token=battle:begin("两只NPC对照") local attackProfile=Config.EnableDuelAttackProbe==true and AttackProfile.new({log=log,valid=safeValid}) local ticks,handle=0,nil local function cancel() if handle then pcall(CancelDelayedAction,handle); handle=nil end end local function sample() if not battle:isCurrent(token) then cancel(); return end if not safeValid(a) or not safeValid(b) then log("对象失效,停止采样;无法据此判定死亡/胜负") battle:cancel("对象失效"); cancel(); return end ticks=ticks+1 if attackProfile then attackProfile:sample({a,b},"duel_sample_"..ticks,GetPlayerPawn()) end if ticks==1 or ticks==20 or ticks==80 then local ok,err=pcall(function() spawnInspector:combat(a,b,'tick'..ticks) spawnInspector:combat(b,a,'tick'..ticks) end) if not ok then log('[SpawnInspect] 战斗状态读取失败: '..tostring(err)) end end if ticks%8~=0 then return end local hpA,hpB=GetHP(a),GetHP(b) log(string.format("战况[%d] HP=%s/%s 关系=%s/%s;只读",ticks,tostring(hpA),tostring(hpB),RelationName(ReadRelation(a,b)),RelationName(ReadRelation(b,a)))) if ticks>=240 or (hpA and hpA<=0) or (hpB and hpB<=0) then battle:cancel("采样结束;F4恢复当前账本"); cancel() end end handle=LoopInGameThreadWithDelay(250,sample) end -- A fighting unit's fallback target (arena_controller.lua hold_target): PBZ_TargetingHandler_AI, the AI's default -- targeting handler, reads the blackboard key "Target Key" and, when that holds nothing, "LastSensedActorKey"; the -- handler instance is the unit's own (Targeting Component.DefaultTargetHandler, its Blackboard set in Initialize). -- Repair player fallback, confirmed empty keys and an owned corpse still selected in either key. local senseHold={written=0,cleared=0,failed=0,lines=0,summaryAt=nil} function arenaSupport:writeArenaTarget(bb,key,wanted,defeated,actor) if not engineValid(bb) or not engineValid(wanted) then return false end local original=UEObserve.unwrap(bb:GetValueAsObject(key)) if defeated and (UEObserve.key(original)~=UEObserve.key(defeated) or not arena:canReplaceDefeatedTarget(actor,defeated,wanted)) then return false end local originalValid=not defeated and engineValid(original) battle:remember("blackboard:" .. bb:GetAddress() .. ":" .. FNameToString(key),function() if not engineValid(bb) then return true,"黑板已失效" end local back=originalValid and engineValid(original) if back then bb:SetValueAsObject(key,original) else bb:ClearValue(key) end if not engineValid(bb) then return true,"黑板已失效" end local actual=UEObserve.unwrap(bb:GetValueAsObject(key)) return (back and engineValid(actual) and UEObserve.key(actual)==UEObserve.key(original)) or (not back and not engineValid(actual)), "恢复目标读回="..objectName(actual)..((originalValid and not back) and ";原目标已不存在,改为清空" or "") end) if not engineValid(bb) or not engineValid(wanted) then return false end bb:SetValueAsObject(key,wanted) if not engineValid(bb) then return false end local actual=UEObserve.unwrap(bb:GetValueAsObject(key)) local actualKey=UEObserve.key(actual) return actualKey~=nil and actualKey==UEObserve.key(wanted),actual end local function HoldSensedTarget(actor,target,why) local handler=UEObserve.field(UEObserve.field(actor,'Targeting Component'),'DefaultTargetHandler') local bb=UEObserve.field(handler,'Blackboard') local key=UEObserve.field(handler,'LastSensedActorKey') if not safeValid(bb) or key==nil then return false end local okNow,current=pcall(function()return UEObserve.unwrap(bb:GetValueAsObject(key))end) if not okNow then return false end local wanted=safeValid(target) and target or nil local player=GetPlayerPawn() local wasPlayer=safeValid(player) and UEObserve.key(current)==UEObserve.key(player) local function replaceCorpse(ref,keyName) if not wanted or not safeValid(ref) or UEObserve.key(ref)==UEObserve.key(wanted) or not arena or not arena:canReplaceDefeatedTarget(actor,ref,wanted) then return end local called,wrote=pcall(arenaSupport.writeArenaTarget,arenaSupport,bb,keyName,wanted,ref,actor) if senseHold.lines<12 then senseHold.lines=senseHold.lines+1 log('[Arena] 尸体目标改派 '..objectName(actor)..' -> '..objectName(wanted)..';读回='..tostring(called and wrote==true)) end return called and wrote==true end local primaryKey=UEObserve.field(handler,'Target Key') local primaryRead,primary if wanted and primaryKey~=nil then local got,value=pcall(function()return UEObserve.unwrap(bb:GetValueAsObject(primaryKey))end) primaryRead=got primary=got and value or nil local replaced=replaceCorpse(primary,primaryKey) if replaced==false then return false end if replaced then primary=wanted end end local replaced=replaceCorpse(current,key) if replaced~=nil then return replaced end if not wasPlayer then if safeValid(current) or not wanted then return true end if not primaryRead then return false end if safeValid(primary) then return true end end if wanted then pcall(function()bb:SetValueAsObject(key,wanted)end) else pcall(function()bb:ClearValue(key)end) end local readAfter,after=pcall(function()return UEObserve.unwrap(bb:GetValueAsObject(key))end) local ok=readAfter and (wanted and UEObserve.key(after)==UEObserve.key(wanted) or (not wanted and not safeValid(after))) if not ok then senseHold.failed=senseHold.failed+1 elseif wanted then senseHold.written=senseHold.written+1 else senseHold.cleared=senseHold.cleared+1 end if senseHold.lines<12 then senseHold.lines=senseHold.lines+1 log(string.format('[Arena] 锁定回退目标 %s 的 Last Sensed Actor:%s%s -> %s;写后=%s;读回=%s;%s',objectName(actor), safeValid(current) and objectName(current) or '空',wasPlayer and '(玩家)' or '',wanted and objectName(wanted) or '清空', safeValid(after) and objectName(after) or '空',tostring(ok),tostring(why))) end local now=os.clock() senseHold.summaryAt=senseHold.summaryAt or now if now-senseHold.summaryAt>=30 then senseHold.summaryAt=now log(string.format('[Arena] 锁定回退目标累计:改成对手=%d 从玩家身上清空=%d 读回不符=%d',senseHold.written,senseHold.cleared,senseHold.failed)) end return ok end local function ForceAttack(attacker, victim) if not safeValid(attacker) or not safeValid(victim) then return false end if arenaSupport.swordFormation and not arenaSupport.swordFormation:beforeAttack(attacker,victim) then return false end if arenaSupport.menghuaPhase and arenaSupport.menghuaPhase:busy(attacker) then return false end local okF = SetFactionRelation(attacker, victim, HOSTILE) local okH, how = AddHatred(attacker, victim) local sg = GetAIComp(attacker) local okForce = false if sg then okForce = pcall(function() sg:ForceIntoCombat(victim) end) end local targetVerified -- 只写实际绑定该控制器的黑板键,并保留原目标供F4恢复。 if sg then local wrote=pcall(function() local bb=sg.BlackboardComponent if not safeValid(bb) then return end local handler=arenaSupport:targetHandler(attacker,bb,true) if safeValid(handler) then local key=handler["Target Key"] local actual targetVerified,actual=arenaSupport:writeArenaTarget(bb,key,victim) log("参赛目标写入=" .. objectName(victim) .. ";黑板读回=" .. objectName(actual)..';确认='..tostring(targetVerified)) end end);if not wrote then targetVerified=false end end local state = "UNKNOWN" if sg then pcall(function() state = FNameToString(sg.CurrentStateTag.TagName) end) end log("作战请求=" .. tostring(okForce) .. ";状态读回=" .. state .. ";仇恨=" .. tostring(okH) .. "/" .. tostring(how) .. ";实际出招待观察") local combat=state=='AI.State.Combat' or (type(state)=='string' and state:sub(1,#'AI.State.Combat.')=='AI.State.Combat.') return okF and okH and okForce and (targetVerified==true or (targetVerified==nil and combat)) end function arenaSupport:targetHandler(actor,bb,refreshMissing) local board=UEObserve.key(bb) if not board then return nil end local function bound(handler) return UEObserve.valid(handler) and UEObserve.key(UEObserve.field(handler,'Blackboard'))==board and UEObserve.field(handler,'Target Key')~=nil end local own=UEObserve.field(UEObserve.field(actor,'Targeting Component'),'DefaultTargetHandler') if bound(own) then return own end -- Some controllers expose the bound handler only through the object list. -- Index bindings across fighters, but always read the target from the live board. local world=UEObserve.key(GetCurrentWorld()) local cache=world and self.targetHandlerCache if cache and cache.world==world and bound(cache.boards[board]) then return cache.boards[board] end local now=world and (GameSeconds() or os.clock()) if not refreshMissing and cache and cache.world==world and now>=cache.at and now-cache.at<.5 then return nil end cache={world=world,at=now,boards={}} local ok,list=pcall(FindAllOf,'PBZ_TargetingHandler_AI_C') for _,handler in ipairs(ok and UEObserve.array(list) or {})do local key=UEObserve.key(UEObserve.field(handler,'Blackboard')) if key and not cache.boards[key] and UEObserve.field(handler,'Target Key')~=nil then cache.boards[key]=handler end end self.targetHandlerCache=world and cache or nil if bound(cache.boards[board]) then return cache.boards[board] end end -- 不再调用通用ApplyDamage种仇恨;本版不执行假伤害或假死亡。 -- ---------- 扫描 ---------- local function CollectNPCs(linkOwners) local player = GetPlayerPawn() local playerAddr = player and player:GetAddress() or nil local result, seen, complete = {}, {}, true for _, className in ipairs(Config.EnemyClasses or {"PBZCharacter_NPC"}) do local ok, found = pcall(FindAllOf, className) if ok and found~=nil and type(found)~='table' then found=UEObserve.array(found) if not found then complete=false end end if not ok then complete=false elseif found then for _, pawn in ipairs(found) do if safeValid(pawn) then local addr = pawn:GetAddress() if addr ~= playerAddr and not seen[addr] then seen[addr] = true -- For summon discovery, run the name filter only after owner/instigator proof. if linkOwners then if not linkOwners[tostring(addr)] then result[#result+1]=pawn end elseif not IsExcluded(pawn) then result[#result+1]=pawn end end end end end end if linkOwners then return result,complete end return result end -- ---------- 解剖:把最近一只怪的 AI 大脑结构写到文件(Shift+扫描键) ---------- -- 注意:UE4SS 对象的空指针链式调用会原生崩溃,pcall 拦不住, -- 所以每一步都先取引用、IsValid 之后再往下走。 local function DumpBrain() ExecuteInGameThread(function() local player = GetPlayerPawn() local pLoc = player and GetLocation(player) local npcs = CollectNPCs() if pLoc then table.sort(npcs, function(a, b) local la, lb = GetLocation(a), GetLocation(b) if not la then return false end if not lb then return true end return DistSq(la, pLoc) < DistSq(lb, pLoc) end) end local target = nil for _, pawn in ipairs(npcs) do local ok, ctrl = pcall(function() return pawn.Controller end) if ok and safeValid(ctrl) then target = { pawn = pawn, ctrl = ctrl } break end end if not target then log("解剖失败:附近没有带可用控制器的怪") return end local lines = {} local function emit(s) table.insert(lines, s) end emit("== 解剖对象: " .. target.pawn:GetFullName()) -- 把一个对象的类链(属性+函数)全部倒出来 local function dumpClassChain(obj, label) emit("") emit("######## " .. label) if not safeValid(obj) then emit("UNKNOWN(invalid)"); return end local okCls, cls = pcall(function() return obj:GetClass() end) while okCls and safeValid(cls) do local okN, clsName = pcall(function() return cls:GetFullName() end) emit("") emit("==== " .. (okN and clsName or "?")) pcall(function() cls:ForEachProperty(function(prop) pcall(function() emit(" prop " .. prop:GetFullName()) end) end) end) pcall(function() cls:ForEachFunction(function(fn) pcall(function() emit(" func " .. fn:GetFullName()) end) end) end) local nxt = nil pcall(function() nxt = cls:GetSuperStruct() end) cls = nxt okCls = safeValid(cls) end end -- 1) 控制器 + 它的 SGameAI 组件 + 感知组件 + 怪物本体 dumpClassChain(target.ctrl, "AIController") local okSG, sg = pcall(function() return target.ctrl.SGameAIComponent end) if okSG and safeValid(sg) then dumpClassChain(sg, "SGameAIComponent") end local okPC, perc = pcall(function() return target.ctrl.PerceptionComponent end) if okPC and safeValid(perc) then dumpClassChain(perc, "PerceptionComponent") end dumpClassChain(target.pawn, "Pawn 本体") -- 2) AI 黑板的键("打谁"大概率藏在这里) local okBB, bb = pcall(function() return target.ctrl.Blackboard end) if okBB and safeValid(bb) then emit("") emit("==== Blackboard keys") local okData, data = pcall(function() return bb.DefaultBlackboardAsset end) if okData and safeValid(data) then pcall(function() local keys = data.Keys for i = 1, #keys do pcall(function() local entry = keys[i] emit(string.format(" key [%d] %s", i, tostring(entry.EntryName))) end) end end) else emit(" (DefaultBlackboardAsset 不可用)") end else emit("") emit("==== 无 Blackboard 组件") end local f, usedPath = nil, nil for _, path in ipairs({ "ue4ss\\Mods\\PhantomGladiator\\brain_dump.txt", "ue4ss/Mods/PhantomGladiator/brain_dump.txt", "brain_dump.txt", }) do f = io.open(path, "w") if f then usedPath = path break end end if f then f:write(table.concat(lines, "\n")) f:close() log(string.format("解剖完成:%d 行已写入 %s(游戏 exe 目录下)", #lines, usedPath)) else log("解剖完成但写文件失败,改打到日志(共 " .. #lines .. " 行)") for _, s in ipairs(lines) do print(s .. "\n") end end end) end -- ---------- 目标系统诊断(Shift+互殴键):读出双方的目标类型标签 ---------- local function ReadTargetTypes(pawn, label) if not safeValid(pawn) then log(label .. " 目标类型=UNKNOWN(invalid)"); return end local ok, err = pcall(function() local out = {} pawn:GetTargetTypes(out) local names = {} for i = 1, #out do local tag = out[i] local okN, n = pcall(function() return FNameToString(tag.TagName) end) table.insert(names, okN and n or "?") end log(string.format("%s 可打类型 [%d 个]: %s", label, #out, table.concat(names, ", "))) end) if not ok then log(string.format("%s 读取目标类型失败: %s", label, tostring(err))) end end local function ReadActorTags(pawn, label) -- 已知本构建没有 GetOwnedGameplayTags 反射入口,不重复失败调用。 log(label .. " 身份标签=UNKNOWN(GetOwnedGameplayTags非反射函数;不据此推断无标签)") end local function TargetDiag() ExecuteInGameThread(function() local player = GetPlayerPawn() if player then ReadTargetTypes(player, "玩家") ReadActorTags(player, "玩家") end local npcs = CollectNPCs() if player then log("玩家 阵营: " .. ReadFactionTag(player)) end -- 附近每只 NPC 的阵营标签和它对玩家的关系(在原生 NPC 互打的场景按这个键, -- 能直接看到双方用的阵营) for i = 1, math.min(#npcs, 8) do local rel = player and RelationName(ReadRelation(npcs[i], player)) or "?" local okN, n = pcall(function() return objectName(npcs[i]):match("([%w_]+)$") end) log(string.format(" NPC[%d] %s 阵营=%s 对玩家=%s %s", i, okN and n or "?", ReadFactionTag(npcs[i]), rel, DescribeCollision(npcs[i]))) end if #npcs >= 2 then log(string.format(" NPC[1]→NPC[2] 关系=%s", RelationName(ReadRelation(npcs[1], npcs[2])))) end if #npcs > 0 then ReadTargetTypes(npcs[1], "怪物") ReadActorTags(npcs[1], "怪物") -- 怪物的 TargetingComponent 挂了哪些 handler pcall(function() local tc = npcs[1]["Targeting Component"] if tc and tc:IsValid() then local hs = tc.TargetingHandlers for i = 1, #hs do pcall(function() local entry = hs[i] log(string.format(" handler[%d] tag=%s", i, FNameToString(entry.Tag.TagName))) end) end end end) -- 它的原生仇恨列表里现在有谁 pcall(function() local hm = GetHatredComp(npcs[1]) if hm then local hl = hm.HatredList log(string.format(" 仇恨列表 %d 个:", #hl)) for i = 1, math.min(#hl, 5) do pcall(function() log(" " .. objectName(hl[i])) end) end else log(" (没有仇恨组件)") end end) -- 它的感知里现在装着谁 pcall(function() local ctrl = npcs[1].Controller if ctrl and ctrl:IsValid() then local perc = ctrl.PerceptionComponent if perc and perc:IsValid() then local seen = {} perc:GetPerceivedHostileActors(seen) log(string.format(" 感知到的敌对者 %d 个:", #seen)) for i = 1, math.min(#seen, 5) do local okE, nameE = pcall(function() local a = seen[i] if safeValid(a) then return objectName(a) end local okGet,resolved=pcall(function() return a:get() end) return okGet and objectName(resolved) or "UNKNOWN" end) log(" " .. (okE and nameE or "?")) end end end end) end end) end -- ---------- 碰撞通道对照(Shift+决斗键):玩家 vs 最近的怪 ---------- -- 每个碰撞组件输出:对象类型、碰撞开关、对 32 个通道的反应(0 忽略 1 重叠 2 阻挡)。 -- 怪物攻击检测线如果只扫"玩家受击框"那类通道,而怪物身上没有对应反应的组件, -- 怪打怪就会打空——对照这张表能直接看出来。 local function DumpCollisionMatrix() ExecuteInGameThread(function() local primClass = StaticFindObject("/Script/Engine.PrimitiveComponent") if not primClass or not primClass:IsValid() then log("碰撞对照失败:找不到 PrimitiveComponent 类") return end local lines = {} local function emit(s) table.insert(lines, s) end -- K2_GetComponentsByClass 在本作返回空数组(实测),改为遍历几类碰撞相关组件, -- 按拥有者筛选;武器等挂件是独立 Actor,拥有者链再往上查一层 local allComps = {} for _, cn in ipairs({ "ShapeComponent", "SkeletalMeshComponent", "StaticMeshComponent" }) do local ok, list = pcall(FindAllOf, cn) if ok and list then for _, c in ipairs(list) do table.insert(allComps, c) end end end local function ownedBy(c, actorAddr) local ok, hit = pcall(function() if not safeValid(c) then return false end local o = c:GetOwner() if not safeValid(o) then return false end if o:GetAddress() == actorAddr then return true end local o2 = o:GetOwner() return o2 ~= nil and o2:IsValid() and o2:GetAddress() == actorAddr end) return ok and hit end local function dumpActor(actor, label) if not safeValid(actor) then return end emit("######## " .. label .. " " .. actor:GetFullName()) local actorAddr = actor:GetAddress() local comps = {} for _, c in ipairs(allComps) do if ownedBy(c, actorAddr) then table.insert(comps, c) end end emit(string.format(" (找到 %d 个碰撞相关组件,全局扫描 %d 个)", #comps, #allComps)) for i = 1, #comps do pcall(function() local c = comps[i] if not c:IsValid() then return end local name = c:GetFullName():match("([%w_]+)$") or "?" pcall(function() local o = c:GetOwner() if not safeValid(o) then return end if o:GetAddress() ~= actor:GetAddress() then name = (o:GetFullName():match("([%w_]+)$") or "?") .. "." .. name end end) local objType, enabled, prof = "?", "?", "?" pcall(function() objType = tostring(c:GetCollisionObjectType()) end) pcall(function() enabled = tostring(c:GetCollisionEnabled()) end) pcall(function() prof = FNameToString(c:GetCollisionProfileName()) end) local resp = {} for ch = 0, 31 do local r = "?" pcall(function() r = tostring(c:GetCollisionResponseToChannel(ch)) end) table.insert(resp, r) end emit(string.format(" %-40s 类型=%s 开关=%s 配置=%s", name, objType, enabled, prof)) emit(" 通道0-31: " .. table.concat(resp, "")) end) end end local player = GetPlayerPawn() if player then dumpActor(player, "玩家") end local pLoc = player and GetLocation(player) local npcs = CollectNPCs() if pLoc then table.sort(npcs, function(a, b) local la, lb = GetLocation(a), GetLocation(b) if not la then return false end if not lb then return true end return DistSq(la, pLoc) < DistSq(lb, pLoc) end) end if npcs[1] then dumpActor(npcs[1], "怪物") end local f = io.open("collision_matrix.txt", "w") if f then f:write(table.concat(lines, "\n")) f:close() log(string.format("碰撞对照完成:%d 行已写入 collision_matrix.txt", #lines)) else log("碰撞对照写文件失败") end end) end -- ---------- 慢动作 ---------- local function CycleSlowMo() ExecuteInGameThread(function() dilationIndex = dilationIndex % #Config.TimeDilationSteps + 1 local target = Config.TimeDilationSteps[dilationIndex] local count = 0 local ok, list = pcall(FindAllOf, "WorldSettings") if ok and list then for _, ws in ipairs(list) do if safeValid(ws) then local okChange=battle:change("time:" .. ws:GetAddress(), function() checked(ws); return ws.TimeDilation end, function(value) checked(ws); ws.TimeDilation=value end,target, function(a,b) return type(a)=="number" and math.abs(a-b)<0.0001 end) if okChange then count=count+1 end end end end if count > 0 then log(string.format("时间流速: %.2fx(%d 个世界)", target, count)) else log("设置 TimeDilation 失败") end end) end -- ---------- 自由镜头 ---------- -- Shipping 版的 DebugCameraController 没有自己的 CheatManager(被编译剔除), -- 而原生退出流程恰恰依赖它:现场构造一个再调 DisableDebugCamera。实测有效。 local function ExitFreeCam(dcc) checked(dcc) local cm = dcc.CheatManager if not cm or not cm:IsValid() then local cmClass = StaticFindObject("/Script/Engine.CheatManager") if not cmClass or not cmClass:IsValid() then error("CheatManager class not found") end cm = StaticConstructObject(cmClass, dcc) if not cm or not cm:IsValid() then error("construct CheatManager failed") end dcc.CheatManager = cm end cm:DisableDebugCamera() end -- 找"当前真正掌权"的调试相机:每次进出都会生成新实例,旧的会残留, -- 只有持有 UPlayer 的那个才是激活中的 local function FindActiveDebugCam() local ok, list = pcall(FindAllOf, "DebugCameraController") if not ok or not list then return nil end for _, dcc in ipairs(list) do local okP, active = pcall(function() return dcc:IsValid() and dcc.Player and dcc.Player:IsValid() end) if okP and active then return dcc end end return nil end -- Only supportSteps owns this short-lived snapshot; no UObject survives into the next support tick. function arenaSupport:supportRead(key,reader) local frame=self.frameContext if not frame then return reader() end local entry=frame[key] if not entry then entry={value=reader()};frame[key]=entry end return entry.value end function arenaSupport:debugCameraForSupport() return self:supportRead('debugCamera',FindActiveDebugCam) end function arenaSupport:attributeSetsForSupport() return self:supportRead('attributeSets',function() local ok,list=pcall(FindAllOf,'BasicAttributeSet') return ok and UEObserve.array(list) or nil end) end local observerGuard=ObserverGuard.new({log=log,getSpectator=function()return spectator end}) local freeCamera=FreeCamera.new({path=Config.RuntimePath,log=log,getController=GetRealPlayerController,guard=observerGuard, getWorld=GetCurrentWorld,moveSpeed=Config.FreeCamera.MoveSpeed,mouseSensitivity=Config.FreeCamera.MouseSensitivity, track=function()return arenaSupport.track end}) -- Real seconds less the time 时停 held the game: timers about units that cannot move meanwhile (a companion stuck -- for 6 s is teleported) wait while it lasts. local frozenSince,frozenTotal=nil,0 local function LiveSeconds() local now=os.clock() local frozen=freeCamera:isFrozen() if frozen and not frozenSince then frozenSince=now elseif not frozen and frozenSince then frozenTotal=frozenTotal+(now-frozenSince);frozenSince=nil end return (frozenSince or now)-frozenTotal end local function ToggleFreeCam() local dcc=FindActiveDebugCam() if dcc then local ok,why=pcall(ExitFreeCam,dcc);return {ok=ok,message=ok and '已退出原生调试镜头' or tostring(why),spawned_count=0}end local ok,result=pcall(function()return freeCamera:toggle()end) local confirmed=ok and result==true local protection=observerGuard:status() return {ok=confirmed,message=confirmed and (freeCamera:isActive() and (protection.health_verified and '自由观战已开启:无仇恨、隐身、无敌锁血;声音跟随镜头' or '自由观战已开启;锁血状态待确认,请查看面板保护状态') or '已退出自由观战并恢复') or ('相机操作未确认,可点击退出观战重试:'..tostring(result)),spawned_count=0} end local function ForceExitFreeCam() local ok,restored=pcall(function()return freeCamera:stop('面板/自定义退出键')end) local dcc=FindActiveDebugCam();local legacyOK=true if dcc then legacyOK=pcall(ExitFreeCam,dcc)end return {ok=ok and restored==true and legacyOK,message=ok and restored==true and legacyOK and '已退出自由观战并恢复原状态' or '退出恢复待确认,可再次点击退出观战',spawned_count=0} end -- ---------- 只读攻击追踪 ---------- local function LogProbeScene(label) local player=GetPlayerPawn() log("[Scene] " .. label .. " 玩家=" .. objectName(player) .. " HP=" .. tostring(GetHP(player))) local origin=player and GetLocation(player) local npcs=CollectNPCs() if origin then table.sort(npcs,function(a,b) local la,lb=GetLocation(a),GetLocation(b) return (la and DistSq(la,origin) or math.huge)<(lb and DistSq(lb,origin) or math.huge) end) end local subjects = {} if safeValid(player) then subjects[#subjects+1]=player end for i=1,math.min(#npcs,4) do local npc=npcs[i] subjects[#subjects+1]=npc log("[Scene] NPC=" .. objectName(npc) .. " HP=" .. tostring(GetHP(npc)) .. " 阵营=" .. ReadFactionTag(npc) .. " 对玩家=" .. RelationName(ReadRelation(npc,player))) end return subjects end local healthSubjects = {} probeFinished = function(state) probeSampleGen=probeSampleGen+1 for _,entry in ipairs(healthSubjects) do local hp=GetHP(entry.actor) log("[HPWatch] 结束 " .. objectName(entry.actor) .. " start=" .. tostring(entry.initial) .. " final=" .. tostring(hp) .. " reason=" .. tostring(state.reason)) end healthSubjects={} end local function StartHealthWatch(subjects,token) healthSubjects={} for _,actor in ipairs(subjects) do local hp=GetHP(actor) healthSubjects[#healthSubjects+1]={actor=actor,initial=hp,last=hp} end local ticks,lines,handle=0,0,nil local function cancel() if handle then pcall(CancelDelayedAction,handle); handle=nil end end local function sample() if token~=probeSampleGen or not probe:status().active then cancel(); return end ticks=ticks+1 for _,entry in ipairs(healthSubjects) do local hp=GetHP(entry.actor) if hp~=entry.last and lines<40 then log("[HPWatch] sample="..ticks.." "..objectName(entry.actor) .." HP="..tostring(entry.last).."→"..tostring(hp).."(只读,不据此判断伤害来源)") lines=lines+1 end entry.last=hp end if ticks>=60 then cancel() end end handle=LoopInGameThreadWithDelay(1000,sample) end BeginArenaObservation=function(a,b) probe:stop("开始参赛者对照") local subjects={a,b} local player=GetPlayerPawn() if safeValid(player) then subjects[#subjects+1]=player end probeSampleGen=probeSampleGen+1 if probe:start("arena_duel",subjects) then StartHealthWatch(subjects,probeSampleGen) end end local function ToggleProbe() ExecuteInGameThread(function() local state=probe:status() probeSampleGen=probeSampleGen+1 if state.active or state.stopPending then probe:stop("F11手动结束"); LogProbeScene("结束"); return end local subjects=LogProbeScene("开始;只读阳性对照") local ok=probe:start("native_baseline",subjects) if not ok then return end local token=probeSampleGen StartHealthWatch(subjects,token) ExecuteInGameThreadWithDelay(60050,function() if token~=probeSampleGen then return end LogProbeScene("60秒窗口结束") end) end) end -- ---------- 单位控制器:按钮与快捷键共用,只有本Mod的参赛者受管理 ---------- local runtimeSession=RuntimeSession.new({valid=safeValid,getWorld=GetCurrentWorld, getPlayer=GetPlayerPawn,isDestroying=actorIsDestroying,hp=GetHP}) local spectatorTargets=SpectatorTargets.new({log=log}) local spectatorExcluded={count=0} -- The player's side: companions (their adopted summons included) and anything carrying the player's faction tag. -- No-aggro leaves these alone and never brings back the relation one had before it joined. local sideKeys,sideAt={},-1 local function IsPlayerSide(npc) local now=os.clock() if now-sideAt>=0.5 or now