From 80113bdd2e2605f9520ab53f162370cfb5633bf1 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:14:43 +0800 Subject: [PATCH] feat(ground-ai): add cover reload, stalemate reposition, and damage repair Complete the single-vehicle tactical loop for reload survival, stalemate breaking, and vehicle damage repair: - Add cover, reload, hull-angle, stalemate, reposition, and repair-cover parameters to tuning/ground-ai.jsonc, validated in ground-ai-tuning.ts and compiled into WTO_AI_SM_* constants. - Add wto_ai_cover_common.das: continuously record the last hard-concealed hull position before peeking, and evaluate 9 cover candidates around the tank (with enemy-clearance scoring when searching for a repair cover). - Add wto_ai_tactics_actions_common.das and wire wto_ai_tactics_common.das: - Damage retreat & repair (plan 6.1): when gun is inoperable while mobile, retreat to an enemy-free cover and send EventRepairSystemRequestRepair(repair=true) once safe; when engine or tracks immobilize the chassis, halt in place, request repair, and keep gun self-defense active; stay halted while repair_system_remaining_repair_time > 0. - 3-way reload action: pull back into remembered/nearby cover (up to 6 s budget, uninterrupted by flashes/new orders) -> zigzag advance at +/-18 deg when pushing without cover -> angle hull front +/-15 deg when side-exposed >30 deg with pivot room. - Stalemate reposition: confirm outgoing effective damage via EventUnitDamage (uint(hpFixed) < uint(prevHpFixed)) and enemy death; trigger lateral reposition after 2 no-effect shots, 2 no-shot halts, or 12 s cumulative halt time, unlocking short-halt only after 20 m progress or reaching the new position. - Split periodic telemetry out of wto_ai_runtime.das into wto_ai_diag_common.das to keep every module under 300 lines. Verified root and launcher type checks, isolated 2.61.0.58 build (24 ground AI modules packed), and clean in-engine daScript compilation/load (wto_ai_runtime.das loaded in 228 ms, 0 compile errors). Live battle acceptance deferred until the full pipeline is wired. --- apps/server/src/tuning/ground-ai-tuning.ts | 17 ++ apps/server/tuning/ground-ai.jsonc | 14 +- game-ai/ground/wto_ai_cover_common.das | 121 +++++++++++ game-ai/ground/wto_ai_diag_common.das | 64 ++++++ game-ai/ground/wto_ai_drive_common.das | 4 +- game-ai/ground/wto_ai_nav_common.das | 13 +- game-ai/ground/wto_ai_runtime.das | 90 +++----- .../ground/wto_ai_tactics_actions_common.das | 193 ++++++++++++++++++ game-ai/ground/wto_ai_tactics_common.das | 101 ++++----- game-ai/ground/wto_ai_types_common.das | 21 +- .../patcher/src/ground-ai/ground-ai-config.ts | 24 +++ 11 files changed, 535 insertions(+), 127 deletions(-) create mode 100644 game-ai/ground/wto_ai_cover_common.das create mode 100644 game-ai/ground/wto_ai_diag_common.das create mode 100644 game-ai/ground/wto_ai_tactics_actions_common.das diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 3940ddc..475c9b3 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -191,11 +191,28 @@ function readPerceptionSection(perc: TuningReader): GroundAiTuning['perception'] } function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine'] { + const coverMinDistM = sm.number('coverMinDistM', { min: 2.0, max: 30.0 }); + const coverMaxDistM = sm.number('coverMaxDistM', { min: 6.0, max: 80.0 }); + if (coverMaxDistM <= coverMinDistM) { + throw new TuningError('tuning file ground-ai.jsonc: stateMachine.coverMaxDistM must be > coverMinDistM'); + } return { preaimAngleDeg: sm.number('preaimAngleDeg', { min: 1.0, max: 30.0 }), shortHaltMaxSec: sm.number('shortHaltMaxSec', { min: 0.5, max: 12.0 }), shortHaltCooldownSec: sm.number('shortHaltCooldownSec', { min: 0.5, max: 20.0 }), turnLaunchSpeedMps: sm.number('turnLaunchSpeedMps', { min: 0.5, max: 6.0 }), + coverMinDistM, + coverMaxDistM, + coverRetreatBudgetSec: sm.number('coverRetreatBudgetSec', { min: 1.5, max: 20.0 }), + reloadAdvanceAngleDeg: sm.number('reloadAdvanceAngleDeg', { min: 0.0, max: 45.0 }), + hullAngleTriggerDeg: sm.number('hullAngleTriggerDeg', { min: 15.0, max: 75.0 }), + hullAngleTargetDeg: sm.number('hullAngleTargetDeg', { min: 0.0, max: 35.0 }), + maxTotalHaltSec: sm.number('maxTotalHaltSec', { min: 3.0, max: 40.0 }), + stalemateMissShots: sm.int('stalemateMissShots', { min: 1, max: 8 }), + stalemateNoShotHalts: sm.int('stalemateNoShotHalts', { min: 1, max: 6 }), + repositionMinMoveM: sm.number('repositionMinMoveM', { min: 5.0, max: 80.0 }), + repositionStepM: sm.number('repositionStepM', { min: 15.0, max: 120.0 }), + repairSafeEnemyDistM: sm.number('repairSafeEnemyDistM', { min: 30.0, max: 400.0 }), }; } diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 0cf9fa8..289a34e 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -113,7 +113,19 @@ "preaimAngleDeg": 8.0, "shortHaltMaxSec": 3.0, "shortHaltCooldownSec": 4.0, - "turnLaunchSpeedMps": 2.1 + "turnLaunchSpeedMps": 2.1, + "coverMinDistM": 6.0, + "coverMaxDistM": 24.0, + "coverRetreatBudgetSec": 6.0, + "reloadAdvanceAngleDeg": 18.0, + "hullAngleTriggerDeg": 30.0, + "hullAngleTargetDeg": 15.0, + "maxTotalHaltSec": 12.0, + "stalemateMissShots": 2, + "stalemateNoShotHalts": 2, + "repositionMinMoveM": 20.0, + "repositionStepM": 48.0, + "repairSafeEnemyDistM": 140.0 }, "tactics": { diff --git a/game-ai/ground/wto_ai_cover_common.das b/game-ai/ground/wto_ai_cover_common.das new file mode 100644 index 0000000..4098094 --- /dev/null +++ b/game-ai/ground/wto_ai_cover_common.das @@ -0,0 +1,121 @@ +// Cover memory, hull concealment check, 9-candidate retreat cover search, and +// enemy-free repair cover search (plan sections 5.1, 6, 6.1). +options indenting = 2 +options no_global_heap = true +module wto_ai_cover_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common +require %appGame.wtoai.wto_ai_sight_common + +[never_inline] +def public wto_cover_is_hull_concealed(world : WtoWorldSnap const&; + selfEid, targetEid : EntityId; + myPos, threatPos : float3) : bool + let myHull = myPos + float3(0.0, 1.15, 0.0) + let tgtEye = threatPos + float3(0.0, 1.85, 0.0) + return wto_sight_hard_segment_blocked(world, selfEid, targetEid, myHull, tgtEye, 0.0, 0.45, 0.65) != WTO_BLOCK_NONE + +[never_inline] +def public wto_cover_update_memory(world : WtoWorldSnap const&; now : float; + myPos : float3; var slot : WtoBotSlot&) + assume tac = slot.tactics + assume p = slot.perceive + if tac.state == WTO_STATE_RETREAT_COVER || tac.state == WTO_STATE_COVER_RELOAD || tac.state == WTO_STATE_DISABLED + return + if !p.targetEid || p.targetIsAir || (now - p.lastSeenAt) > WTO_AI_TACTICS_MEMORY_TTL_SEC + return + if wto_cover_is_hull_concealed(world, slot.eid, p.targetEid, myPos, p.knownPos) + tac.lastCoverPos = myPos + tac.lastCoverValid = true + tac.lastCoverAt = now + +[never_inline] +def private wto_cover_enemy_danger(world : WtoWorldSnap const&; now : float; + army : int; cand : float3) : float + var danger = 0.0 + let safeR = WTO_AI_SM_REPAIR_SAFE_DIST_M + let safeRSq = safeR * safeR + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || !u.isGround || u.army == army + continue + let dSq = wto_xz_dist_sq(cand, u.pos) + if dSq < safeRSq + let d = sqrt(dSq) + danger += (safeR - d) * 2.5 + for r in range(WTO_MAX_RADIO) + assume sp = world.radioSpots[r] + if sp.untilAt <= now || sp.army != army + continue + let dSq = wto_xz_dist_sq(cand, sp.pos) + if dSq < safeRSq + let d = sqrt(dSq) + danger += (safeR - d) * 1.2 + return danger + +[never_inline] +def private wto_cover_eval_candidate(world : WtoWorldSnap const&; now : float; + myPos, threatPos, spawnDir : float3; + avoidEnemies : bool; isOriginalCover : bool; + candIn : float3; slot : WtoBotSlot const&; + var bestScore : float&; var outPos : float3&) : bool + var cand = wto_clamp_battle_xz(candIn, world.battleCenter, world.battleRadius, 35.0) + if !wto_terrain_point_valid(slot.army, cand) + return false + if !wto_cover_is_hull_concealed(world, slot.eid, slot.perceive.targetEid, cand, threatPos) + return false + let dist = sqrt(wto_xz_dist_sq(myPos, cand)) + var sc = dist + if isOriginalCover + sc -= 14.0 + let stepDir = wto_xz_normalize(cand - myPos, spawnDir) + sc -= dot(stepDir, spawnDir) * (avoidEnemies ? 18.0 : 6.0) + if avoidEnemies + sc += wto_cover_enemy_danger(world, now, slot.army, cand) + if sc < bestScore + bestScore = sc + outPos = cand + return true + return false + +[never_inline] +def public wto_cover_pick_candidate(world : WtoWorldSnap const&; now : float; + myPos, threatPos : float3; avoidEnemies : bool; + slot : WtoBotSlot const&; var outPos : float3&) : bool + let threatDir = wto_xz_normalize(threatPos - myPos, float3(1.0, 0.0, 0.0)) + let away = -threatDir + let lat = float3(-threatDir.z, 0.0, threatDir.x) + let spawnDir = world.teamSpawnValid[slot.army] ? wto_xz_normalize(world.teamSpawnCenter[slot.army] - myPos, away) : away + var bestScore = 1.0e9 + var found = false + + // Candidate 0: remembered last cover position along the peek path. + assume tac = slot.tactics + if tac.lastCoverValid && (now - tac.lastCoverAt) <= 25.0 + let dOrig = sqrt(wto_xz_dist_sq(myPos, tac.lastCoverPos)) + if dOrig >= WTO_AI_SM_COVER_MIN_DIST_M && dOrig <= (avoidEnemies ? 45.0 : WTO_AI_SM_COVER_MAX_DIST_M) + if wto_cover_eval_candidate(world, now, myPos, threatPos, spawnDir, avoidEnemies, true, tac.lastCoverPos, slot, bestScore, outPos) + found = true + + // Candidates 1..8: two rings (rear + side-rear) around current position. + let r1 = avoidEnemies ? 24.0 : 14.0 + let r2 = avoidEnemies ? 44.0 : 24.0 + var offsets : float3[8] + offsets[0] = away * r1 + offsets[1] = wto_xz_normalize(away + lat * 0.75, away) * r1 + offsets[2] = wto_xz_normalize(away - lat * 0.75, away) * r1 + offsets[3] = lat * r1 + offsets[4] = -lat * r1 + offsets[5] = away * r2 + offsets[6] = wto_xz_normalize(away + lat * 0.9, away) * r2 + offsets[7] = wto_xz_normalize(away - lat * 0.9, away) * r2 + for k in range(8) + if wto_cover_eval_candidate(world, now, myPos, threatPos, spawnDir, avoidEnemies, false, myPos + offsets[k], slot, bestScore, outPos) + found = true + return found diff --git a/game-ai/ground/wto_ai_diag_common.das b/game-ai/ground/wto_ai_diag_common.das new file mode 100644 index 0000000..1aebff1 --- /dev/null +++ b/game-ai/ground/wto_ai_diag_common.das @@ -0,0 +1,64 @@ +// Periodic telemetry and sample logging for the ground AI runtime. +options indenting = 2 +options no_global_heap = true +module wto_ai_diag_common shared + +require ecs +require math +require pathfinder +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_common + +[never_inline] +def private wto_log_bot_and_cap_samples(world : WtoWorldSnap const&; bots : WtoBotSlot[64]) + var sampled = 0 + for i in range(WTO_MAX_BOTS) + if !bots[i].used || sampled >= 2 + continue + assume b = bots[i] + print("WTO_AI|BOT_SAMPLE|eid={uint(b.eid)}|role={b.spec.role}|stab={b.spec.hasVertStab}|v0={b.fire.activeSpeedMps}|st={b.tactics.state}|allyD={b.crowd.nearestAllyDistM}|clust={b.crowd.clusterAllyCount}|ridge={b.tactics.onExposedRidge}|los={b.perceive.hasClearLos}|fc={b.fire.gunReady}/{b.fire.reloading}/{b.fire.lastAligned}|err={b.fire.lastAimErrDeg}|omB={b.fire.barrelOmegaDegSec}|mode={b.driveCmd.mode}|v={b.drive.lastVFwd}|clr={b.nav.frontClearM}/{b.nav.rearClearM}|wp={b.route.corridorIdx}/{b.route.corridorLen}|proj={b.route.lastStartOk}/{b.route.lastGoalOk}\n") + sampled++ + for c in range(world.capCount) + assume z = world.caps[c] + print("WTO_AI|CAP|idx={c}|owner={z.ownerArmy}|rad={z.radius}|prog={z.progress}\n") + +[never_inline] +def public wto_diag_log_telemetry(world : WtoWorldSnap const&; now : float; + bots : WtoBotSlot[64]; crowd : WtoCrowdSummary const&) + var active = 0 + var routeB = 0 + var revNow = 0 + var engNow = 0 + var dispNow = 0 + var ridgeNow = 0 + var revEvents = 0 + var ridgeWithdraws = 0 + var detours = 0 + var shots = 0 + var errSum = 0.0 + var maxErr = 0.0 + var roles : int[5] + for r in range(5) + roles[r] = 0 + for i in range(WTO_MAX_BOTS) + if !bots[i].used + continue + assume b = bots[i] + active++ + roles[clamp(b.spec.role, 0, 4)]++ + routeB += b.drive.routeBOwned ? 1 : 0 + revNow += b.driveCmd.mode == WTO_DRIVE_REVERSE ? 1 : 0 + engNow += b.tactics.state == WTO_STATE_SHORT_HALT ? 1 : 0 + dispNow += b.tactics.state == WTO_STATE_DISPERSE ? 1 : 0 + ridgeNow += b.tactics.onExposedRidge ? 1 : 0 + revEvents += b.nav.reverseCount + ridgeWithdraws += b.nav.ridgeWithdrawEvents + detours += b.route.detourCount + shots += b.fire.shotCount + errSum += b.fire.shotErrSumDeg + maxErr = max(maxErr, b.fire.maxShotErrDeg) + let avgErr = shots > 0 ? (errSum / float(shots)) : 0.0 + let jams = wto_world_active_jams(world, now) + let nm1 = pathfinder_is_loaded_ex(1) + print("WTO_AI|STAT|t={now}|bots={active}|roles={roles[0]}/{roles[1]}/{roles[2]}/{roles[3]}/{roles[4]}|crowd={crowd.crowdedBotCount}|maxClust={crowd.maxClusterSize}|minAllyD={crowd.minPairDistM}|dispNow={dispNow}|dispEv={crowd.disperseEvents}|ridgeNow={ridgeNow}|ridgeRevEv={ridgeWithdraws}|eng={engNow}|revNow={revNow}|revEv={revEvents}|jams={jams}|detours={detours}|shots={shots}|avgAimErr={avgErr}|maxAimErr={maxErr}|routeB={routeB}|caps={world.capCount}|nm1={nm1}\n") + wto_log_bot_and_cap_samples(world, bots) diff --git a/game-ai/ground/wto_ai_drive_common.das b/game-ai/ground/wto_ai_drive_common.das index 1d0df91..297ad1d 100644 --- a/game-ai/ground/wto_ai_drive_common.das +++ b/game-ai/ground/wto_ai_drive_common.das @@ -211,7 +211,9 @@ def public wto_drive_step_phys(var unit : Unit?; unitMissionName : string; if now > slot.nextNavAt + WTO_AI_NAV_TICK_SEC wto_drive_handle_failure(gm, actor, slot, "stale_nav_tick", false) return - if wto_drive_is_immobilized(actor) + let immobile = wto_drive_is_immobilized(actor) + slot.tactics.immobilized = immobile + if immobile slot.drive.prevThr = 0.0 slot.drive.prevStr = 0.0 slot.drive.deadEchoSec = 0.0 diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index 8aa0e83..f067fe1 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -197,7 +197,7 @@ def private wto_check_stuck_watchdog(var world : WtoWorldSnap&; now : float; def private wto_try_reverse_drive(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool let stMode = slot.tactics.state - let wantTacRev = stMode == WTO_STATE_RIDGE_WITHDRAW || stMode == WTO_STATE_RETREAT_COVER + let wantTacRev = stMode == WTO_STATE_RIDGE_WITHDRAW || (stMode == WTO_STATE_RETREAT_COVER && slot.tactics.retreatReverse) if !wantTacRev && now >= slot.nav.reverseUntil return false let revGoal = wantTacRev ? slot.tactics.moveGoal : slot.nav.reverseAnchor @@ -221,7 +221,16 @@ def public wto_nav_update(var world : WtoWorldSnap&; now : float; slot.nav.rearClearM = wto_terrain_hard_ray(probeBase, -hullFwd, 18.0) slot.nav.cliffAhead = wto_terrain_has_cliff_ahead(myPos, hullFwd, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M) - if slot.tactics.state == WTO_STATE_SHORT_HALT || slot.tactics.desiredSpeedMps <= 0.05 + if slot.tactics.state == WTO_STATE_HULL_ANGLE + slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC + let wishAngle = wto_xz_normalize(slot.tactics.hullAngleDir, hullFwd) + let angErr = acos(clamp(dot(wishAngle, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG + if angErr > 8.0 + wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + wishAngle * 14.0, wishAngle, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + else + wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + return + if slot.tactics.state == WTO_STATE_SHORT_HALT || slot.tactics.state == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05 slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC wto_handle_stationary_engage(myPos, hullFwd, slot) return diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index fd20eea..cb1bdb3 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -33,6 +33,7 @@ require %appGame.wtoai.wto_ai_tactics_common require %appGame.wtoai.wto_ai_nav_common require %appGame.wtoai.wto_ai_drive_common require %appGame.wtoai.wto_ai_fire_common +require %appGame.wtoai.wto_ai_diag_common var private @safe_when_uninitialized g_world : WtoWorldSnap var private @safe_when_uninitialized g_crowd : WtoCrowdSummary @@ -105,59 +106,6 @@ def private wto_phys_slot_available() : bool return false return true -[never_inline] -def private wto_log_bot_and_cap_samples() - var sampled = 0 - for i in range(WTO_MAX_BOTS) - if !g_bots[i].used || sampled >= 2 - continue - assume b = g_bots[i] - print("WTO_AI|BOT_SAMPLE|eid={uint(b.eid)}|role={b.spec.role}|stab={b.spec.hasVertStab}|v0={b.fire.activeSpeedMps}|st={b.tactics.state}|allyD={b.crowd.nearestAllyDistM}|clust={b.crowd.clusterAllyCount}|ridge={b.tactics.onExposedRidge}|los={b.perceive.hasClearLos}|fc={b.fire.gunReady}/{b.fire.reloading}/{b.fire.lastAligned}|err={b.fire.lastAimErrDeg}|omB={b.fire.barrelOmegaDegSec}|mode={b.driveCmd.mode}|v={b.drive.lastVFwd}|clr={b.nav.frontClearM}/{b.nav.rearClearM}|wp={b.route.corridorIdx}/{b.route.corridorLen}|proj={b.route.lastStartOk}/{b.route.lastGoalOk}\n") - sampled++ - for c in range(g_world.capCount) - assume z = g_world.caps[c] - print("WTO_AI|CAP|idx={c}|owner={z.ownerArmy}|rad={z.radius}|prog={z.progress}\n") - -[never_inline] -def private wto_log_telemetry(now : float) - var active = 0 - var routeB = 0 - var revNow = 0 - var engNow = 0 - var dispNow = 0 - var ridgeNow = 0 - var revEvents = 0 - var ridgeWithdraws = 0 - var detours = 0 - var shots = 0 - var errSum = 0.0 - var maxErr = 0.0 - var roles : int[5] - for r in range(5) - roles[r] = 0 - for i in range(WTO_MAX_BOTS) - if !g_bots[i].used - continue - assume b = g_bots[i] - active++ - roles[clamp(b.spec.role, 0, 4)]++ - routeB += b.drive.routeBOwned ? 1 : 0 - revNow += b.driveCmd.mode == WTO_DRIVE_REVERSE ? 1 : 0 - engNow += b.tactics.state == WTO_STATE_SHORT_HALT ? 1 : 0 - dispNow += b.tactics.state == WTO_STATE_DISPERSE ? 1 : 0 - ridgeNow += b.tactics.onExposedRidge ? 1 : 0 - revEvents += b.nav.reverseCount - ridgeWithdraws += b.nav.ridgeWithdrawEvents - detours += b.route.detourCount - shots += b.fire.shotCount - errSum += b.fire.shotErrSumDeg - maxErr = max(maxErr, b.fire.maxShotErrDeg) - let avgErr = shots > 0 ? (errSum / float(shots)) : 0.0 - let jams = wto_world_active_jams(g_world, now) - let nm1 = pathfinder_is_loaded_ex(1) - print("WTO_AI|STAT|t={now}|bots={active}|roles={roles[0]}/{roles[1]}/{roles[2]}/{roles[3]}/{roles[4]}|crowd={g_crowd.crowdedBotCount}|maxClust={g_crowd.maxClusterSize}|minAllyD={g_crowd.minPairDistM}|dispNow={dispNow}|dispEv={g_crowd.disperseEvents}|ridgeNow={ridgeNow}|ridgeRevEv={ridgeWithdraws}|eng={engNow}|revNow={revNow}|revEv={revEvents}|jams={jams}|detours={detours}|shots={shots}|avgAimErr={avgErr}|maxAimErr={maxErr}|routeB={routeB}|caps={g_world.capCount}|nm1={nm1}\n") - wto_log_bot_and_cap_samples() - [es(tag=server, on_event=(EventMissionUnload, EventEntityManagerBeforeClear, EventEcsMissionLoaded))] def wto_ai_mission_reset_es(evt : Event) wto_reset_runtime() @@ -181,6 +129,11 @@ def wto_ai_unit_dead_es(evt : Event; eid : EntityId; unit__ref : UnitRef) wto_drive_request_control(eid, 0) g_bots[idx] = WtoBotSlot() g_cmd_dirty = true + for i in range(WTO_MAX_BOTS) + if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid + g_bots[i].tactics.engageShotsNoEffect = 0 + g_bots[i].tactics.engageNoShotHalts = 0 + g_bots[i].tactics.engageTotalHaltSec = 0.0 [es(tag=server, on_disappear, on_event=EventUnitRespawn)] def wto_ai_unit_cleanup_es(evt : Event; eid : EntityId) @@ -190,22 +143,40 @@ def wto_ai_unit_cleanup_es(evt : Event; eid : EntityId) wto_drive_request_control(eid, 0) g_bots[idx] = WtoBotSlot() g_cmd_dirty = true + for i in range(WTO_MAX_BOTS) + if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid + g_bots[i].tactics.engageShotsNoEffect = 0 + g_bots[i].tactics.engageNoShotHalts = 0 + g_bots[i].tactics.engageTotalHaltSec = 0.0 [es(tag=server)] def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : UnitRef) if !wto_any_layer_active() || !WTO_AI_LAYER_TACTICS return - let idx = wto_find_slot(eid) let offEid = evt.offender.eid let u = unit__ref.unit - if idx < 0 || u == null || !offEid || offEid == eid + if u == null || !offEid || offEid == eid + return + let now = float(get_app().usefulTotalTime) + let vicArmy = int(u.army) + // Outgoing effective damage confirmation for our firing bot (resets stalemate counters). + let offBotIdx = wto_find_slot(offEid) + if offBotIdx >= 0 && g_bots[offBotIdx].army != vicArmy && uint(evt.hpFixed) < uint(evt.prevHpFixed) + assume tac = g_bots[offBotIdx].tactics + if tac.engageTargetEid == eid || g_bots[offBotIdx].perceive.targetEid == eid + tac.engageShotsNoEffect = 0 + tac.engageNoShotHalts = 0 + tac.lastEffectAt = now + // Incoming hit direction cue for our damaged bot (never leaks hidden offender coords). + let idx = wto_find_slot(eid) + if idx < 0 return let offUnitIdx = wto_world_find_unit(g_world, offEid) if offUnitIdx >= 0 && g_world.units[offUnitIdx].army == g_bots[idx].army return let imp = evt.pos - u.pos g_bots[idx].perceive.lastHitYawRad = (imp.x * imp.x + imp.z * imp.z) > 0.04 ? atan2(imp.z, imp.x) : atan2(u.unitTm[0].z, u.unitTm[0].x) - g_bots[idx].perceive.lastDamagedAt = float(get_app().usefulTotalTime) + g_bots[idx].perceive.lastDamagedAt = now g_bots[idx].perceive.lastOffenderEid = offEid [es(tag=server, before=wto_ai_pipeline_es)] @@ -236,11 +207,12 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) wto_commander_update_all(g_world, now, zoneChanged, g_bots) if WTO_AI_DIAG_TELEMETRY && now >= g_next_diag_at g_next_diag_at = now + WTO_AI_DIAG_INTERVAL_SEC - wto_log_telemetry(now) + wto_diag_log_telemetry(g_world, now, g_bots, g_crowd) [es(tag=server, no_order)] def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; - unit__className : string = "") + unit__className : string = ""; + repair_system_remaining_repair_time : float = -1.0) if !wto_any_layer_active() || !g_world.valid return var unit = unit__ref.unit @@ -262,7 +234,7 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : slot.nextTacticsAt = now + WTO_AI_TACTICS_TICK_SEC if WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_FIRE_CONTROL wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot) - wto_tactics_update(g_world, now, unit.pos, unit.unitTm[0], unit.isBurn, slot, g_crowd) + wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd) if now >= slot.nextNavAt slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC wto_nav_update(g_world, now, unit.pos, unit.unitTm[0], slot) diff --git a/game-ai/ground/wto_ai_tactics_actions_common.das b/game-ai/ground/wto_ai_tactics_actions_common.das new file mode 100644 index 0000000..7162148 --- /dev/null +++ b/game-ai/ground/wto_ai_tactics_actions_common.das @@ -0,0 +1,193 @@ +// Tactics action handlers: damage retreat & repair (plan 6.1), cover retreat & 3-way reload +// actions, and stalemate detection / reposition unlock. +options indenting = 2 +options no_global_heap = true +module wto_ai_tactics_actions_common shared + +require ecs +require math +require %game.unit.repair_system_events +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common +require %appGame.wtoai.wto_ai_cover_common + +[never_inline] +def public wto_sm_set_state(now : float; newState : int; goalPos : float3; speedMps : float; + reason : string; distXZ : float; var slot : WtoBotSlot&) + assume tac = slot.tactics + if tac.state != newState + if WTO_AI_DIAG_TELEMETRY + print("WTO_AI|STATE|t={now}|eid={uint(slot.eid)}|from={tac.state}|to={newState}|reason={reason}|dist={distXZ}|v={slot.drive.lastVFwd}\n") + tac.state = newState + tac.stateEnteredAt = now + if newState == WTO_STATE_SHORT_HALT + tac.haltEnterAt = now + tac.haltStartShots = slot.fire.shotCount + tac.moveGoal = goalPos + tac.desiredSpeedMps = speedMps + +[never_inline] +def public wto_friendly_retreat_dir(world : WtoWorldSnap const&; army : int; + myPos, threatDir : float3) : float3 + if world.teamSpawnValid[army] + let toSpawn = wto_xz_normalize(world.teamSpawnCenter[army] - myPos, -threatDir) + let blended = toSpawn * 0.65 - threatDir * 0.35 + return wto_xz_normalize(blended, toSpawn) + return wto_xz_normalize(-threatDir, float3(1.0, 0.0, 0.0)) + +[never_inline] +def public wto_sm_handle_disabled_and_repair(world : WtoWorldSnap const&; now : float; + myPos, threatPos, threatDir : float3; + isBurn : bool; repairRemainingSec, distXZ : float; + var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + assume p = slot.perceive + tac.spaaYieldAir = false + if slot.spec.role == WTO_ROLE_SPAA + if p.hasClearLos && p.targetIsAir && !!p.targetEid + tac.spaaYieldAir = true + wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "spaa_air_engage", distXZ, slot) + return true + if p.hasClearLos && !p.targetIsAir && !!p.targetEid && distXZ < 220.0 + let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) + let goal = wto_clamp_battle_xz(myPos + backDir * 70.0, world.battleCenter, world.battleRadius, 40.0) + wto_sm_set_state(now, WTO_STATE_DISABLED, goal, slot.spec.vMaxFwd, "spaa_evade_tank", distXZ, slot) + return true + + // Engine/tracks broken (cannot move): halt in place and request native repair; gun keeps self-defending. + if tac.immobilized + tac.repairCoverValid = false + if !isBurn && repairRemainingSec <= 0.0 + sendEvent(slot.eid, EventRepairSystemRequestRepair(repair = true)) + wto_sm_set_state(now, WTO_STATE_DISABLED, myPos, 0.0, "immobilized_repair", distXZ, slot) + return true + + // Main gun damaged or burning while mobile: immediately retreat to an enemy-free cover and repair there. + if slot.fire.gunDamaged || isBurn + let inSafeSpot = (tac.repairCoverValid && wto_xz_dist_sq(myPos, tac.repairCoverGoal) <= 25.0) || (wto_cover_is_hull_concealed(world, slot.eid, p.targetEid, myPos, threatPos) && distXZ > 90.0) + if inSafeSpot + if !isBurn && repairRemainingSec <= 0.0 + sendEvent(slot.eid, EventRepairSystemRequestRepair(repair = true)) + wto_sm_set_state(now, WTO_STATE_DISABLED, myPos, 0.0, "cover_repair_hold", distXZ, slot) + return true + if !tac.repairCoverValid + var cov = myPos + if wto_cover_pick_candidate(world, now, myPos, threatPos, true, slot, cov) + tac.repairCoverGoal = cov + else + let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) + tac.repairCoverGoal = wto_clamp_battle_xz(myPos + backDir * 75.0, world.battleCenter, world.battleRadius, 40.0) + tac.repairCoverValid = true + wto_sm_set_state(now, WTO_STATE_DISABLED, tac.repairCoverGoal, slot.spec.vMaxFwd, slot.fire.gunDamaged ? "gun_damaged_retreat" : "burn_retreat", distXZ, slot) + return true + + tac.repairCoverValid = false + if repairRemainingSec > 0.0 + wto_sm_set_state(now, WTO_STATE_DISABLED, myPos, 0.0, "finishing_repair", distXZ, slot) + return true + return false + +[never_inline] +def public wto_sm_continue_cover_retreat(world : WtoWorldSnap const&; now : float; + myPos, threatPos : float3; distXZ : float; + var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + if tac.state == WTO_STATE_RETREAT_COVER + let arrived = wto_xz_dist_sq(myPos, tac.retreatTarget) <= 12.25 + let concealed = wto_cover_is_hull_concealed(world, slot.eid, slot.perceive.targetEid, myPos, threatPos) + if arrived || concealed + wto_sm_set_state(now, WTO_STATE_COVER_RELOAD, myPos, 0.0, "cover_reached", distXZ, slot) + return true + if now >= tac.retreatUntil + return false + let spd = tac.retreatReverse ? max(2.2, slot.spec.vMaxRev) : (slot.spec.vMaxFwd * 0.92) + wto_sm_set_state(now, WTO_STATE_RETREAT_COVER, tac.retreatTarget, spd, "cover_retreating", distXZ, slot) + return true + if tac.state == WTO_STATE_COVER_RELOAD + if slot.fire.reloading + wto_sm_set_state(now, WTO_STATE_COVER_RELOAD, myPos, 0.0, "cover_reloading", distXZ, slot) + return true + return false + return false + +[never_inline] +def public wto_sm_start_reload_action(world : WtoWorldSnap const&; now : float; + myPos, hullFwd, threatPos, baseGoal : float3; + distXZ, distGoal : float; var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + // Option 1: pull back into remembered or nearby cover (6..24m). + var cov = myPos + if wto_cover_pick_candidate(world, now, myPos, threatPos, false, slot, cov) + let toCov = wto_xz_normalize(cov - myPos, -hullFwd) + let behindHull = dot(toCov, hullFwd) < -0.15 + tac.retreatTarget = cov + tac.retreatUntil = now + WTO_AI_SM_COVER_RETREAT_SEC + tac.retreatReverse = behindHull && slot.nav.rearClearM > 3.2 && slot.spec.vMaxRev >= 2.0 + let spd = tac.retreatReverse ? max(2.2, slot.spec.vMaxRev) : (slot.spec.vMaxFwd * 0.92) + wto_sm_set_state(now, WTO_STATE_RETREAT_COVER, cov, spd, "reload_pullback", distXZ, slot) + return true + // Option 2: no near cover and offensive/advancing -> zigzag push toward objective. + if wto_order_is_offensive(slot.order.role) || distGoal > 35.0 + let toGoal = wto_xz_normalize(baseGoal - myPos, hullFwd) + let zigSign = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 + let ang = zigSign * WTO_AI_SM_RELOAD_ADV_DEG * WTO_DEG_TO_RAD + let zigDir = float3(toGoal.x * cos(ang) - toGoal.z * sin(ang), 0.0, toGoal.x * sin(ang) + toGoal.z * cos(ang)) + let zigGoal = wto_clamp_battle_xz(myPos + zigDir * min(distGoal, 48.0), world.battleCenter, world.battleRadius, 35.0) + wto_sm_set_state(now, WTO_STATE_RELOAD_ADVANCE, zigGoal, slot.spec.vMaxFwd * 0.92, "reload_advance", distXZ, slot) + return true + // Option 3: defensive hold with side/rear exposed > 30 deg -> angle hull front +/-15 deg toward threat. + let toThreat = wto_xz_normalize(threatPos - myPos, hullFwd) + let exposureDeg = acos(clamp(dot(hullFwd, toThreat), -1.0, 1.0)) * WTO_RAD_TO_DEG + let hasPivotRoom = slot.nav.frontClearM >= slot.spec.halfLen + 1.5 && slot.nav.rearClearM >= slot.spec.halfLen + 1.2 + if exposureDeg > WTO_AI_SM_HULL_ANGLE_TRIG_DEG && hasPivotRoom + let angSign = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 + let ang = angSign * WTO_AI_SM_HULL_ANGLE_TGT_DEG * WTO_DEG_TO_RAD + tac.hullAngleDir = float3(toThreat.x * cos(ang) - toThreat.z * sin(ang), 0.0, toThreat.x * sin(ang) + toThreat.z * cos(ang)) + wto_sm_set_state(now, WTO_STATE_HULL_ANGLE, myPos, 0.0, "reload_angle_hull", distXZ, slot) + return true + return false + +[never_inline] +def public wto_sm_handle_reposition(world : WtoWorldSnap const&; now : float; + myPos, threatDir, baseGoal : float3; + distXZ : float; var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + if tac.repositionActive + let movedSq = wto_xz_dist_sq(myPos, tac.repositionOrigin) + let remSq = wto_xz_dist_sq(myPos, tac.repositionGoal) + if movedSq >= wto_sq(WTO_AI_SM_REPOS_MIN_MOVE_M) || remSq <= 64.0 + tac.repositionActive = false + tac.engageTotalHaltSec = 0.0 + return false + if distXZ <= WTO_AI_FC_CLOSE_RANGE_M + return false + wto_sm_set_state(now, WTO_STATE_REPOSITION, tac.repositionGoal, slot.spec.vMaxFwd * 0.92, "reposition_move", distXZ, slot) + return true + + let shotTimeoutOk = (now - slot.fire.lastShotAt) >= 1.2 + let staleShots = tac.engageShotsNoEffect >= WTO_AI_SM_STALE_MISS_SHOTS && shotTimeoutOk + let staleHalts = tac.engageNoShotHalts >= WTO_AI_SM_STALE_NOSHOT_HALTS + let staleTime = tac.engageTotalHaltSec >= WTO_AI_SM_MAX_TOTAL_HALT_SEC + if !staleShots && !staleHalts && !staleTime + return false + let lat = float3(-threatDir.z, 0.0, threatDir.x) + let side = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 + var goal = baseGoal + for attempt in range(2) + let s = attempt == 0 ? side : -side + var cand = wto_clamp_battle_xz(myPos + lat * (s * WTO_AI_SM_REPOS_STEP_M) + threatDir * 14.0, world.battleCenter, world.battleRadius, 35.0) + if wto_terrain_point_valid(slot.army, cand) + goal = cand + break + tac.repositionOrigin = myPos + tac.repositionGoal = goal + tac.repositionActive = true + tac.engageShotsNoEffect = 0 + tac.engageNoShotHalts = 0 + tac.engageTotalHaltSec = 0.0 + wto_sm_set_state(now, WTO_STATE_REPOSITION, goal, slot.spec.vMaxFwd * 0.92, staleShots ? "stale_no_effect" : (staleHalts ? "stale_no_shot" : "stale_halt_time"), distXZ, slot) + return true diff --git a/game-ai/ground/wto_ai_tactics_common.das b/game-ai/ground/wto_ai_tactics_common.das index 37244e0..8d0afaf 100644 --- a/game-ai/ground/wto_ai_tactics_common.das +++ b/game-ai/ground/wto_ai_tactics_common.das @@ -1,6 +1,6 @@ -// Per-bot hull state machine: arbitrates safety, ridge withdrawal, ongoing short-halt budget, -// crowd dispersion, and distance-tier x task-order movement/shooting (MARCH, RUN_AND_GUN, -// PREAIM, SHORT_HALT, RELOAD_ADVANCE). Every state transition logs its reason. +// Per-bot hull state machine orchestrator: strict priority arbitration across safety/repair, +// active cover retreat, ridge withdrawal, stalemate reposition, short-halt budget, dispersion, +// 3-way reload actions, and distance-tier x task-order movement/shooting. options indenting = 2 options no_global_heap = true module wto_ai_tactics_common shared @@ -14,54 +14,20 @@ require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_crowd_common +require %appGame.wtoai.wto_ai_cover_common +require %appGame.wtoai.wto_ai_tactics_actions_common [never_inline] -def private wto_sm_set_state(now : float; newState : int; goalPos : float3; speedMps : float; - reason : string; distXZ : float; var slot : WtoBotSlot&) - assume tac = slot.tactics - if tac.state != newState - if WTO_AI_DIAG_TELEMETRY - print("WTO_AI|STATE|t={now}|eid={uint(slot.eid)}|from={tac.state}|to={newState}|reason={reason}|dist={distXZ}|v={slot.drive.lastVFwd}\n") - tac.state = newState - tac.stateEnteredAt = now - if newState == WTO_STATE_SHORT_HALT - tac.haltEnterAt = now - tac.haltStartShots = slot.fire.shotCount - tac.moveGoal = goalPos - tac.desiredSpeedMps = speedMps - -[never_inline] -def private wto_friendly_retreat_dir(world : WtoWorldSnap const&; army : int; - myPos, threatDir : float3) : float3 - if world.teamSpawnValid[army] - let toSpawn = wto_xz_normalize(world.teamSpawnCenter[army] - myPos, -threatDir) - let blended = toSpawn * 0.65 - threatDir * 0.35 - return wto_xz_normalize(blended, toSpawn) - return wto_xz_normalize(-threatDir, float3(1.0, 0.0, 0.0)) - -[never_inline] -def private wto_sm_handle_safety_or_spaa(world : WtoWorldSnap const&; now : float; - myPos, threatDir : float3; isBurn : bool; - distXZ : float; var slot : WtoBotSlot&) : bool +def private wto_sm_sync_engagement_counters(dt : float; var slot : WtoBotSlot&) assume tac = slot.tactics assume p = slot.perceive - tac.spaaYieldAir = false - if slot.spec.role == WTO_ROLE_SPAA - if p.hasClearLos && p.targetIsAir && !!p.targetEid - tac.spaaYieldAir = true - wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "spaa_air_engage", distXZ, slot) - return true - if p.hasClearLos && !p.targetIsAir && !!p.targetEid && distXZ < 220.0 - let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) - let goal = wto_clamp_battle_xz(myPos + backDir * 70.0, world.battleCenter, world.battleRadius, 40.0) - wto_sm_set_state(now, WTO_STATE_DISABLED, goal, slot.spec.vMaxFwd, "spaa_evade_tank", distXZ, slot) - return true - if slot.fire.gunDamaged || isBurn - let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) - let goal = wto_clamp_battle_xz(myPos + backDir * 75.0, world.battleCenter, world.battleRadius, 40.0) - wto_sm_set_state(now, WTO_STATE_DISABLED, goal, slot.spec.vMaxFwd, slot.fire.gunDamaged ? "gun_damaged" : "burning", distXZ, slot) - return true - return false + if p.hasClearLos && !!p.targetEid && !p.targetIsAir && tac.engageTargetEid != p.targetEid + tac.engageTargetEid = p.targetEid + tac.engageShotsNoEffect = 0 + tac.engageNoShotHalts = 0 + tac.engageTotalHaltSec = 0.0 + if tac.state == WTO_STATE_SHORT_HALT + tac.engageTotalHaltSec += dt [never_inline] def private wto_sm_handle_ridge(world : WtoWorldSnap const&; now : float; @@ -72,8 +38,7 @@ def private wto_sm_handle_ridge(world : WtoWorldSnap const&; now : float; wto_sm_set_state(now, WTO_STATE_RIDGE_WITHDRAW, tac.withdrawAnchor, max(2.2, slot.spec.vMaxRev), "ridge_hold", distXZ, slot) return true let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) - let exposed = wto_terrain_is_exposed_ridge(myPos, threatDir, backDir) - if !exposed + if !wto_terrain_is_exposed_ridge(myPos, threatDir, backDir) tac.onExposedRidge = false return false if !tac.onExposedRidge @@ -102,6 +67,9 @@ def private wto_sm_continue_short_halt(now : float; myPos : float3; hasGroundTgt if tac.state != WTO_STATE_SHORT_HALT return false if slot.fire.shotCount > tac.haltStartShots || slot.fire.reloading + if slot.fire.shotCount > tac.haltStartShots + tac.engageShotsNoEffect += slot.fire.shotCount - tac.haltStartShots + tac.haltStartShots = slot.fire.shotCount return false if !hasGroundTgt || distXZ > WTO_AI_FC_MAX_RANGE_M return false @@ -111,6 +79,7 @@ def private wto_sm_continue_short_halt(now : float; myPos : float3; hasGroundTgt if distXZ > WTO_AI_FC_LONG_RANGE_M && (slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC || slot.perceive.visiblePointCount < 2) return false if (now - tac.haltEnterAt) >= WTO_AI_SM_SHORT_HALT_MAX_SEC + tac.engageNoShotHalts++ tac.shortHaltCooldownUntil = now + WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC return false wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_continue", distXZ, slot) @@ -142,16 +111,14 @@ def private wto_sm_march_speed(slot : WtoBotSlot const&; distGoal : float) : flo return distGoal < 24.0 ? min(slot.spec.vMaxFwd * 0.55, 6.0) : (slot.spec.vMaxFwd * capScale) [never_inline] -def private wto_sm_handle_combat(now : float; myPos, baseGoal : float3; +def private wto_sm_handle_combat(world : WtoWorldSnap const&; now : float; + myPos, hullFwd, threatPos, baseGoal : float3; distXZ, distGoal : float; var slot : WtoBotSlot&) : bool assume tac = slot.tactics assume fc = slot.fire let marchSpd = wto_sm_march_speed(slot, distGoal) if fc.reloading - if wto_order_is_offensive(slot.order.role) || distGoal > 35.0 - wto_sm_set_state(now, WTO_STATE_RELOAD_ADVANCE, baseGoal, max(marchSpd, slot.spec.vMaxFwd * 0.85), "reload_push", distXZ, slot) - return true - return false + return wto_sm_start_reload_action(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot) if distXZ <= WTO_AI_FC_CLOSE_RANGE_M let closeSpd = slot.spec.hasVertStab ? (slot.spec.vMaxFwd * 0.92) : min(slot.spec.vMaxFwd * 0.65, WTO_AI_FC_MID_SLOW_MAX_MPS) wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, baseGoal, max(2.5, closeSpd), "close_run_gun", distXZ, slot) @@ -162,7 +129,7 @@ def private wto_sm_handle_combat(now : float; myPos, baseGoal : float3; wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, baseGoal, max(2.2, slowCap), "mid_slow_fire", distXZ, slot) return true let maxStop = slot.order.valid ? slot.order.maxStopRangeM : WTO_AI_FC_MAX_RANGE_M - if distXZ > maxStop || distXZ > WTO_AI_FC_MAX_RANGE_M + if distXZ > maxStop || distXZ > WTO_AI_FC_MAX_RANGE_M || tac.repositionActive return false if distXZ > WTO_AI_FC_LONG_RANGE_M && (slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC || slot.perceive.visiblePointCount < 2) return false @@ -176,9 +143,11 @@ def private wto_sm_handle_combat(now : float; myPos, baseGoal : float3; return true [never_inline] -def public wto_tactics_update(world : WtoWorldSnap const&; now : float; - myPos, hullFwd : float3; isBurn : bool; +def public wto_tactics_update(world : WtoWorldSnap const&; now, dt : float; + myPos, rawHullFwd : float3; isBurn : bool; + repairRemainingSec : float; var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) + let hullFwd = wto_xz_normalize(rawHullFwd, float3(1.0, 0.0, 0.0)) let baseGoal = slot.order.valid ? slot.order.goalPos : world.battleCenter let distGoal = sqrt(wto_xz_dist_sq(myPos, baseGoal)) if !WTO_AI_LAYER_TACTICS @@ -187,18 +156,28 @@ def public wto_tactics_update(world : WtoWorldSnap const&; now : float; assume p = slot.perceive let hasGroundTgt = p.hasClearLos && !!p.targetEid && !p.targetIsAir let distXZ = hasGroundTgt ? sqrt(wto_xz_dist_sq(myPos, p.knownPos)) : 9999.0 - let threatRef = !!p.targetEid ? p.knownPos : baseGoal - let threatDir = wto_xz_normalize(threatRef - myPos, wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))) - if wto_sm_handle_safety_or_spaa(world, now, myPos, threatDir, isBurn, distXZ, slot) + let threatPos = !!p.targetEid ? p.knownPos : baseGoal + let threatDir = wto_xz_normalize(threatPos - myPos, hullFwd) + + wto_sm_sync_engagement_counters(dt, slot) + wto_cover_update_memory(world, now, myPos, slot) + if wto_sm_handle_disabled_and_repair(world, now, myPos, threatPos, threatDir, isBurn, repairRemainingSec, distXZ, slot) + return + if wto_sm_continue_cover_retreat(world, now, myPos, threatPos, distXZ, slot) return if wto_sm_handle_ridge(world, now, myPos, threatDir, distXZ, slot) return + if wto_sm_handle_reposition(world, now, myPos, threatDir, baseGoal, distXZ, slot) + return if wto_sm_continue_short_halt(now, myPos, hasGroundTgt, distXZ, slot) return if wto_sm_handle_dispersion(world, now, myPos, threatDir, distXZ, slot, crowdSummary) return - if hasGroundTgt && wto_sm_handle_combat(now, myPos, baseGoal, distXZ, distGoal, slot) + if hasGroundTgt && wto_sm_handle_combat(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot) return + if slot.fire.reloading && !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC + if wto_sm_start_reload_action(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot) + return let marchSpd = wto_sm_march_speed(slot, distGoal) let marchGoal = distGoal <= 8.0 ? myPos : baseGoal wto_sm_set_state(now, WTO_STATE_MARCH, marchGoal, marchSpd, "march_task", distXZ, slot) diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index 434c464..6835707 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -172,6 +172,24 @@ struct public WtoTacticsState haltEnterAt : float = -100.0 haltStartShots : int = 0 shortHaltCooldownUntil : float = -100.0 + immobilized : bool = false + lastCoverPos : float3 = float3(0.0, 0.0, 0.0) + lastCoverValid : bool = false + lastCoverAt : float = -100.0 + retreatTarget : float3 = float3(0.0, 0.0, 0.0) + retreatUntil : float = -100.0 + retreatReverse : bool = false + hullAngleDir : float3 = float3(1.0, 0.0, 0.0) + repositionGoal : float3 = float3(0.0, 0.0, 0.0) + repositionOrigin : float3 = float3(0.0, 0.0, 0.0) + repositionActive : bool = false + engageTargetEid : EntityId = INVALID_ENTITY_ID + engageShotsNoEffect : int = 0 + engageNoShotHalts : int = 0 + engageTotalHaltSec : float = 0.0 + lastEffectAt : float = -100.0 + repairCoverGoal : float3 = float3(0.0, 0.0, 0.0) + repairCoverValid : bool = false spaaYieldAir : bool = false onExposedRidge : bool = false ridgeEnterAt : float = -100.0 @@ -180,9 +198,6 @@ struct public WtoTacticsState withdrawUntil : float = -100.0 disperseGoal : float3 = float3(0.0, 0.0, 0.0) disperseUntil : float = -100.0 - peekHomePos : float3 = float3(0.0, 0.0, 0.0) - peekUntil : float = -100.0 - peekCooldownUntil : float = -100.0 [safe_when_uninitialized] struct public WtoRouteState diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 7253433..a2d4b4a 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -97,6 +97,18 @@ export interface GroundAiConfig { readonly shortHaltMaxSec: number; readonly shortHaltCooldownSec: number; readonly turnLaunchSpeedMps: number; + readonly coverMinDistM: number; + readonly coverMaxDistM: number; + readonly coverRetreatBudgetSec: number; + readonly reloadAdvanceAngleDeg: number; + readonly hullAngleTriggerDeg: number; + readonly hullAngleTargetDeg: number; + readonly maxTotalHaltSec: number; + readonly stalemateMissShots: number; + readonly stalemateNoShotHalts: number; + readonly repositionMinMoveM: number; + readonly repositionStepM: number; + readonly repairSafeEnemyDistM: number; }; readonly tactics: { readonly visionRangeM: number; @@ -245,6 +257,18 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_SM_SHORT_HALT_MAX_SEC', 'float', c.stateMachine.shortHaltMaxSec], ['WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC', 'float', c.stateMachine.shortHaltCooldownSec], ['WTO_AI_SM_TURN_LAUNCH_MPS', 'float', c.stateMachine.turnLaunchSpeedMps], + ['WTO_AI_SM_COVER_MIN_DIST_M', 'float', c.stateMachine.coverMinDistM], + ['WTO_AI_SM_COVER_MAX_DIST_M', 'float', c.stateMachine.coverMaxDistM], + ['WTO_AI_SM_COVER_RETREAT_SEC', 'float', c.stateMachine.coverRetreatBudgetSec], + ['WTO_AI_SM_RELOAD_ADV_DEG', 'float', c.stateMachine.reloadAdvanceAngleDeg], + ['WTO_AI_SM_HULL_ANGLE_TRIG_DEG', 'float', c.stateMachine.hullAngleTriggerDeg], + ['WTO_AI_SM_HULL_ANGLE_TGT_DEG', 'float', c.stateMachine.hullAngleTargetDeg], + ['WTO_AI_SM_MAX_TOTAL_HALT_SEC', 'float', c.stateMachine.maxTotalHaltSec], + ['WTO_AI_SM_STALE_MISS_SHOTS', 'int', c.stateMachine.stalemateMissShots], + ['WTO_AI_SM_STALE_NOSHOT_HALTS', 'int', c.stateMachine.stalemateNoShotHalts], + ['WTO_AI_SM_REPOS_MIN_MOVE_M', 'float', c.stateMachine.repositionMinMoveM], + ['WTO_AI_SM_REPOS_STEP_M', 'float', c.stateMachine.repositionStepM], + ['WTO_AI_SM_REPAIR_SAFE_DIST_M', 'float', c.stateMachine.repairSafeEnemyDistM], ['WTO_AI_TACTICS_VISION_RANGE_M', 'float', c.tactics.visionRangeM], ['WTO_AI_TACTICS_VISION_FOV_DEG', 'float', c.tactics.visionFovDeg], ['WTO_AI_TACTICS_PERIPHERAL_RANGE_M', 'float', c.tactics.peripheralRangeM],