Files
WT-Offline/game-ai/ground/wto_ai_fire_common.das
T
N0VAN0M4LY 45ff082a36 feat(ground-ai): add sample-based lead estimation, exit watch, and bounded bias
Replace direct reads of true enemy velocity with an own-sight sample
estimator, add 2-5 s last-seen exit watching, and sample bounded aiming
bias once per shooting opportunity:

- Add the estimation section to tuning/ground-ai.jsonc (watchMinSec,
  watchMaxSec, velSampleMinSpanSec, velStableSpanSec, velJumpResetMps,
  baseAimSigmaM, leadErrorFrac, maxBiasM), validated in
  ground-ai-tuning.ts and compiled into WTO_AI_EST_* constants.
- Add wto_ai_estimate_common.das:
  - Maintain a 6-sample timestamped ring buffer from each bot's own
    visual sightings; compute smoothed observed velocity and convergence
    quality, dropping quality and re-seeding bias on sudden braking/turns
    or target switches.
  - On LOS loss from an active ground engagement, freeze watchPos at the
    last-seen exit point, clear observed velocity, and draw one random
    2-5 s watch duration; stationary overwatch/defend bots hold their
    post while watching, whereas pushing/retreating bots keep moving
    while keeping their turret on the exit.
  - Compute lead from observed velocity and loaded-shell flight time,
    sampling one bounded bias vector per shooting opportunity (target,
    shot count, state, 12 m position cell) that narrows as observation
    quality improves and still passes the single fire-permission gate.

Verified root and launcher type checks, isolated 2.61.0.58 build (25
ground AI modules packed), and clean in-engine daScript compilation/load
(wto_ai_runtime.das loaded in 184 ms, 0 compile errors). Live battle
acceptance deferred until the full pipeline is wired.
2026-12-03 18:23:12 +08:00

255 lines
11 KiB
Plaintext

// Turret servo, active loaded-shell inspection, and ballistic aim solver.
// All ground weapon firing goes exclusively through wto_fire_gate_try_shoot.
options indenting = 2
options no_global_heap = true
module wto_ai_fire_common shared
require ecs
require app
require math
require strings
require DagorMath
require Mission
require Unit
require IGroundModel
require Weapon
require Ballistics
require %game.utils.utils_common
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_estimate_common
require %appGame.wtoai.wto_ai_fire_gate_common
[never_inline]
def private wto_world_to_hull_deg(worldDir, hullFwd, hullUp, hullLeft : float3;
var outYawDeg, outPitchDeg : float&)
let len = length(worldDir)
if len < 1.0e-5
outYawDeg = 0.0
outPitchDeg = 0.0
return
let d = worldDir / len
let f = dot(d, hullFwd)
let u = dot(d, hullUp)
let l = dot(d, hullLeft)
let horiz = sqrt(f * f + l * l)
outYawDeg = horiz > 1.0e-5 ? (-atan2(l, f) * WTO_RAD_TO_DEG) : 0.0
outPitchDeg = clamp(atan2(u, max(1.0e-5, horiz)) * WTO_RAD_TO_DEG, -24.0, 65.0)
[never_inline]
def private wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3
let yr = yawDeg * WTO_DEG_TO_RAD
let pr = pitchDeg * WTO_DEG_TO_RAD
let cp = cos(pr)
let dir = hullFwd * (cp * cos(yr)) - hullLeft * (cp * sin(yr)) + hullUp * sin(pr)
let l = length(dir)
return l > 1.0e-5 ? (dir / l) : hullFwd
[never_inline]
def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec const&; var fc : WtoFireState&)
if gun == null
return
let chosenIdx = int(gun.chosenBulletType)
if fc.loadedBulletIdx == chosenIdx && fc.activeSpeedMps > 80.0
return
fc.loadedBulletIdx = chosenIdx
fc.activeSpeedMps = spec.muzzleSpeedMps
fc.activeDragCx = spec.shellDragCx
fc.activeMassKg = spec.shellMassKg
fc.activeCaliberM = spec.shellCaliberM
if chosenIdx >= 0 && chosenIdx < length(gun.properties.bulletSets)
assume bs = gun.properties.bulletSets[chosenIdx]
if length(bs.bullet) > 0 && bs.bullet[0] != null
let bName = bs.bullet[0].getName
if !empty(bName)
let h = ecs_hash(bName)
for i in range(spec.shellCount)
if spec.shells[i].nameHash == h
fc.activeSpeedMps = spec.shells[i].speedMps
fc.activeDragCx = spec.shells[i].dragCx
fc.activeMassKg = spec.shells[i].massKg
fc.activeCaliberM = spec.shells[i].caliberM
return
[never_inline]
def private wto_inspect_primary_weapon(unit : Unit const?; now : float;
spec : WtoVehicleSpec const&; var fc : WtoFireState&)
fc.turretNo = -1
fc.gunReady = false
fc.reloading = false
fc.gunDamaged = false
if unit == null || unit.weap == null
return
var anyGun = false
var anyAlive = false
var anyReserve = false
var totalLoaded = 0
foreach_primary_gun(unit.weap.Weapons) <| $(weapon)
if weapon == null || weapon.isDummyGun
return
let gun = as_gun(weapon)
if gun == null
if weapon.prop.launcher && weapon.countBullets > 0
anyGun = true
anyAlive = true
anyReserve = true
if fc.turretNo < 0
fc.turretNo = weapon.turretNo
fc.gunReady = true
totalLoaded += weapon.countBullets
return
anyGun = true
if gun.isInoperable
return
anyAlive = true
if fc.turretNo < 0
fc.turretNo = weapon.turretNo
wto_sync_active_shell(gun, spec, fc)
if gun.isReadyToShoot
fc.gunReady = true
totalLoaded += max(0, gun.currentLoadedAmmoCount)
if gun.currentLoadedAmmoCount > 0 || gun.currentBulletSet.bulletsCount > 0 || weapon.countBullets > 0
anyReserve = true
fc.gunDamaged = anyGun && !anyAlive
fc.reloading = anyAlive && !fc.gunReady && anyReserve
if fc.pendingShotConfirm
if (fc.prevLoadedAmmo >= 0 && totalLoaded < fc.prevLoadedAmmo) || !fc.gunReady
fc.shotCount++
fc.pendingShotConfirm = false
elif (now - fc.pendingShotAt) > 0.35
fc.pendingShotConfirm = false
fc.prevLoadedAmmo = totalLoaded
[never_inline]
def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; var slot : WtoBotSlot&;
aimBase : float3; var outAimPt, outWishDir : float3&) : float
var leadPt = aimBase
let rawDist = wto_est_compute_biased_lead(muzzlePos, myVel, aimBase, slot, leadPt)
let dragLoss = clamp(slot.fire.activeDragCx * 0.00011 * rawDist, 0.0, 0.28)
let vEff = max(120.0, slot.fire.activeSpeedMps * (1.0 - dragLoss))
outAimPt = leadPt
var arcDir = float3(0.0, 0.0, 0.0)
if calculate_arc_low_start_dir(muzzlePos, leadPt, vEff, arcDir) && length_sq(arcDir) > 0.25
outWishDir = normalize(arcDir)
else
let d = max(1.0, length(leadPt - muzzlePos))
let tof = d / vEff
let dropComp = float3(0.0, 0.5 * 9.81 * tof * tof, 0.0)
outWishDir = normalize(leadPt + dropComp - muzzlePos)
return rawDist
[never_inline]
def private wto_sample_turret_muzzle(unit : Unit const?; turretNo : int;
var outPos, outDir : float3&) : bool
if unit == null || unit.weap == null
return false
for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret
if (turretNo >= 0 && tIdx != turretNo) || (turretNo < 0 && int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY))
continue
let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex))
if weapon == null
continue
var gunTm : float3x4
weapon_calcShootTm(weapon, unit.unitTm, gunTm)
if length_sq(gunTm[0]) > 0.25
outPos = gunTm[3]
outDir = normalize(gunTm[0])
return true
return false
[never_inline]
def private wto_drive_turret_and_sample_barrel(var unit : Unit?; dt, now : float;
wishYawDeg, wishPitchDeg : float;
var slot : WtoBotSlot&;
var outMuzzlePos, outLiveDir : float3&)
assume fc = slot.fire
let dtStep = clamp(dt, 0.005, 0.12)
for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret
if (fc.turretNo >= 0 && tIdx != fc.turretNo) || (fc.turretNo < 0 && int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY))
continue
fc.curYawDeg = turret.currentState.yaw
fc.curPitchDeg = turret.currentState.pitch
if !fc.servoInit
fc.cmdYawDeg = fc.curYawDeg
fc.cmdPitchDeg = fc.curPitchDeg
fc.prevPitchDeg = fc.curPitchDeg
fc.servoInit = true
let pitchSpd = abs(fc.curPitchDeg - fc.prevPitchDeg) / dtStep
fc.prevPitchDeg = fc.curPitchDeg
if slot.perceive.hasClearLos && wishPitchDeg < fc.curPitchDeg - 2.3 && pitchSpd < 0.8
fc.pitchClampSec = min(2.0, fc.pitchClampSec + dtStep)
fc.pitchBlocked = fc.pitchClampSec >= 0.75
else
fc.pitchClampSec = max(0.0, fc.pitchClampSec - dtStep * 2.5)
if fc.pitchClampSec <= 0.05
fc.pitchBlocked = false
let maxYawStep = max(24.0, slot.spec.turretYawSpd * 1.1) * dtStep
let maxPitchStep = max(10.0, slot.spec.turretPitchSpd * 1.1) * dtStep
let yawDelta = clamp(wto_wrap_deg(wishYawDeg - fc.curYawDeg), -maxYawStep, maxYawStep)
let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep, maxPitchStep)
fc.cmdYawDeg = wto_wrap_deg(fc.curYawDeg + yawDelta)
fc.cmdPitchDeg = clamp(fc.curPitchDeg + pitchDelta, slot.spec.minPitchDeg - 2.0, slot.spec.maxPitchDeg + 2.0)
turret.yawLim = fc.cmdYawDeg
turret.pitchLim = fc.cmdPitchDeg
break
var uPos = unit.pos
updateWeaponAnims(*unit.weap, dtStep, 1.0, uPos)
if !wto_sample_turret_muzzle(unit, fc.turretNo, outMuzzlePos, outLiveDir)
outLiveDir = wto_hull_deg_to_world(fc.curYawDeg, fc.curPitchDeg, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2])
let bAge = now - fc.prevBarrelAt
if bAge > 1.0e-4 && bAge <= 0.25
let stepDeg = acos(clamp(dot(outLiveDir, fc.prevBarrelDir), -1.0, 1.0)) * WTO_RAD_TO_DEG
fc.barrelOmegaDegSec = lerp(stepDeg / bAge, fc.barrelOmegaDegSec, 0.45)
else
fc.barrelOmegaDegSec = 0.0
fc.prevBarrelDir = outLiveDir
fc.prevBarrelAt = now
[never_inline]
def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?;
now, dt : float; var slot : WtoBotSlot&; var fireBudget : int&)
if !WTO_AI_LAYER_FIRE_CONTROL || unit == null || unit.weap == null
return
// SPAA vs aircraft only delegates to stock air-target fire control (never ground targets).
if slot.tactics.spaaYieldAir
var gm = as_gm(unit)
if gm != null
*gm |> set_check_visibility_target(true)
*gm |> set_ignore_stop_for_fire(true)
set_unit_attack_type(unit, "attack_target")
return
set_unit_attack_type(unit, "dont_aim")
wto_inspect_primary_weapon(unit, now, slot.spec, slot.fire)
var muzzlePos = unit.pos + float3(0.0, 1.95, 0.0)
var liveBarrelDir = unit.unitTm[0]
let _preSample = wto_sample_turret_muzzle(unit, slot.fire.turretNo, muzzlePos, liveBarrelDir)
let hFwd = unit.unitTm[0]
var wishWorldDir = hFwd
var aimPt = muzzlePos + hFwd * 50.0
var distToTgt = 9999.0
let engageValid = (slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir &&
!(slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED))
if engageValid
let baseAim = slot.perceive.visibleAimPt
distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, slot, baseAim, aimPt, wishWorldDir)
elif now < slot.perceive.watchUntil
wishWorldDir = normalize(slot.perceive.watchPos - muzzlePos)
elif !!slot.perceive.targetEid && (now - slot.perceive.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
wishWorldDir = normalize((slot.perceive.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos)
elif now < slot.perceive.alertUntil
wishWorldDir = float3(cos(slot.perceive.alertYawRad), 0.0, sin(slot.perceive.alertYawRad))
var wishYaw = 0.0
var wishPitch = 0.0
wto_world_to_hull_deg(wishWorldDir, hFwd, unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch)
wto_drive_turret_and_sample_barrel(unit, dt, now, wishYaw, wishPitch, slot, muzzlePos, liveBarrelDir)
if !engageValid || distToTgt > WTO_AI_FC_MAX_RANGE_M
slot.fire.settleHoldSec = 0.0
slot.fire.lastAligned = false
return
let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos))
wto_fire_gate_try_shoot(world, unit, now, dt, distXZ, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot, fireBudget)