feat(ground-ai): implement modular zero-heap tank AI daScript layers

Add 14 modular daScript files under game-ai/ground covering per-vehicle
DataBlock specs, foliage-filtered terrain and cliff crest lookahead,
flat world snapshots, anti-clustering telemetry and active dispersion,
cap-insider-bounded macro scheduling, sticky 6-channel perception,
ridge snipe/reverse withdraw tactics, wide-projected NavMesh routing,
bidirectional forward/reverse DWA local planning, closed-loop
VehiclePhys chassis control, and settled ballistic fire control.
This commit is contained in:
N0VAN0M4LY committed 2026-12-03 12:12:17 +08:00
1 parent 4ac3484f56
commit 975a28441a
14 files changed
+2928

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
// Anti-clustering telemetry & active dispersion solver: measures local friendly density around
// every tracked bot, updates match-wide crowd statistics for `.clog`, and computes drivable
// lateral/oblique dispersion anchors whenever allies bunch up.
options indenting = 2
options no_global_heap = true
module wto_ai_crowd_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_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common
[never_inline]
def public wto_crowd_point_penalty(world : WtoWorldSnap const&; army : int; selfEid : EntityId;
pt : float3) : float
let rad = max(12.0, WTO_AI_CROWD_CLUSTER_RADIUS_M)
let radSq = rad * rad
var pen = 0.0
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.army != army || u.eid == selfEid
continue
let dSq = wto_xz_dist_sq(pt, u.pos)
if dSq < radSq
let d = sqrt(dSq)
pen += (1.0 - d / rad) * 24.0
if d < WTO_AI_CROWD_PERSONAL_SPACE_M
pen += (WTO_AI_CROWD_PERSONAL_SPACE_M - d) * 4.5
return pen
[never_inline]
def private wto_eval_bot_crowd(world : WtoWorldSnap const&; myPos : float3; mySpeed : float;
slot : WtoBotSlot const&; var outInfo : WtoCrowdInfo&)
outInfo = WtoCrowdInfo()
let personalSq = wto_sq(WTO_AI_CROWD_PERSONAL_SPACE_M)
let clusterSq = wto_sq(WTO_AI_CROWD_CLUSTER_RADIUS_M)
var repulse = float3(0.0, 0.0, 0.0)
var nearestSpeed = 0.0
var higherPriorityAllies = 0
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.army != slot.army || u.eid == slot.eid
continue
let dSq = wto_xz_dist_sq(myPos, u.pos)
if dSq >= clusterSq
continue
let d = max(0.5, sqrt(dSq))
outInfo.clusterAllyCount++
if u.isHuman || uint(u.eid) < uint(slot.eid)
higherPriorityAllies++
if d < outInfo.nearestAllyDistM
outInfo.nearestAllyDistM = d
outInfo.nearestAllyEid = u.eid
nearestSpeed = wto_xz_len(u.vel)
if dSq <= personalSq
outInfo.nearPersonalCount++
let away = wto_xz_normalize(myPos - u.pos, float3(1.0, 0.0, 0.0))
let w = clamp((WTO_AI_CROWD_CLUSTER_RADIUS_M - d) / max(4.0, d), 0.15, 6.0)
repulse += away * w
let hashYaw = float(int(uint(slot.eid) % 7u) - 3) * 0.45
let fallbackDir = float3(cos(hashYaw), 0.0, sin(hashYaw))
outInfo.repulseDirXZ = wto_xz_normalize(repulse, fallbackDir)
// Trigger dispersion when personal space is violated (yielding to human or lower-eid leader,
// or whenever both tanks are nearly parked) OR when local cluster exceeds max allies.
let yieldPair = higherPriorityAllies > 0 || (mySpeed < 1.5 && nearestSpeed < 1.5)
if outInfo.nearPersonalCount > 0 && yieldPair
outInfo.isCrowded = true
elif outInfo.clusterAllyCount >= WTO_AI_CROWD_CLUSTER_MAX_ALLIES && higherPriorityAllies >= 1
outInfo.isCrowded = true
[never_inline]
def public wto_crowd_update_all(world : WtoWorldSnap const&; var bots : WtoBotSlot[64]&;
var summary : WtoCrowdSummary&)
summary.crowdedBotCount = 0
summary.maxClusterSize = 1
summary.minPairDistM = 999.0
for i in range(WTO_MAX_BOTS)
if !bots[i].used
continue
let uIdx = wto_world_find_unit(world, bots[i].eid)
if uIdx < 0
bots[i].crowd = WtoCrowdInfo()
continue
let myPos = world.units[uIdx].pos
let mySpd = wto_xz_len(world.units[uIdx].vel)
wto_eval_bot_crowd(world, myPos, mySpd, bots[i], bots[i].crowd)
if bots[i].crowd.isCrowded
summary.crowdedBotCount++
summary.maxClusterSize = max(summary.maxClusterSize, bots[i].crowd.clusterAllyCount + 1)
summary.minPairDistM = min(summary.minPairDistM, bots[i].crowd.nearestAllyDistM)
// Pick a drivable dispersion target 22..34m laterally/away from the cluster that maximizes
// spacing from teammates without stepping onto a cliff or into enemy spawn.
[never_inline]
def public wto_crowd_pick_disperse_pos(world : WtoWorldSnap const&; army : int; selfEid : EntityId;
myPos, threatDirXZ : float3; crowd : WtoCrowdInfo const&) : float3
let fwd = wto_xz_normalize(threatDirXZ, float3(1.0, 0.0, 0.0))
let lat = float3(-fwd.z, 0.0, fwd.x)
let rep = wto_xz_normalize(crowd.repulseDirXZ, lat)
let baseYaw = atan2(rep.z, rep.x)
let stepM = WTO_AI_CROWD_DISPERSE_STEP_M
let sideBias = (uint(selfEid) & 1u) == 0u ? 1.0 : -1.0
var bestPos = myPos + rep * stepM
var bestScore = -1.0e9
for k in range(8)
let angOff = float(k - 3) * 0.52 * sideBias
let candYaw = baseYaw + angOff
let dir = float3(cos(candYaw), 0.0, sin(candYaw))
var cand = float3(myPos.x + dir.x * stepM, myPos.y, myPos.z + dir.z * stepM)
cand = wto_clamp_battle_xz(cand, world.battleCenter, world.battleRadius, 35.0)
if !wto_terrain_point_valid(army, cand)
continue
if wto_terrain_has_cliff_ahead(myPos, dir, min(stepM, 18.0))
continue
if wto_terrain_hard_ray(myPos + float3(0.0, 1.3, 0.0), dir, min(stepM, 16.0)) < 9.0
continue
// Prefer lateral dispersion over pushing blindly forward into enemy guns.
let fwdProj = dot(dir, fwd)
let repAlign = dot(dir, rep) * 14.0
let latBonus = (1.0 - abs(fwdProj)) * 12.0 - max(0.0, fwdProj) * 8.0
let score = repAlign + latBonus - wto_crowd_point_penalty(world, army, selfEid, cand)
if score > bestScore
bestScore = score
bestPos = cand
return bestPos
+210
View File
@@ -0,0 +1,210 @@
// Chassis drive actuator: translates `WtoDriveCmd` into closed-loop `VehiclePhysActor` axes
// (throttle, steering, brakes, auto-transmission) with space-aware 3-point turns, smooth
// long-distance reverse control, and dead-echo watchdog fallback to `MoveSys`.
options indenting = 2
options no_global_heap = true
module wto_ai_drive_common shared
require ecs
require math
require DagorMath
require DagorDataBlock
require DagorSystem
require Mission
require Unit
require IGroundModel
require vehicle
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_types_common
[never_inline]
def public wto_drive_prepare_unit(unitMissionName : string)
if empty(unitMissionName)
return
using() <| $(var blk : DataBlock)
add(blk, "object", unitMissionName)
add(blk, "avoidObstacles", false)
add(blk, "movementTraceRI", true)
add(blk, "destroyRIByCollision", true)
call_mission_action("unitSetProperties", blk)
[never_inline]
def public wto_drive_apply_movesys(var unit : Unit?; cmd : WtoDriveCmd const&)
if unit == null || !cmd.valid
return
let gm = as_gm(unit)
if gm == null || gm.moveSys == null
return
if cmd.mode == WTO_DRIVE_HALT || cmd.speedMps <= 0.05
set_destination_way_point(unit, "HALT", unit.unitTm, 0.0)
return
var tm = unit.unitTm
tm[3] = cmd.targetPos
let dir = wto_xz_normalize(cmd.desiredDir, float3(1.0, 0.0, 0.0))
tm[0] = cmd.mode == WTO_DRIVE_REVERSE ? -dir : dir
tm[1] = float3(0.0, 1.0, 0.0)
tm[2] = float3(-tm[0].z, 0.0, tm[0].x)
set_destination_way_point(unit, "MOVE_TO_STRAIGHT", tm, cmd.speedMps)
[never_inline]
def private wto_set_phys_axes(var actor : VehiclePhysActor&; thr, str, brk, handBrk : float)
actor.phys.producedCT |> ground_control_state_setAutomaticTransmission(true)
actor.phys.producedCT |> ground_control_state_setCruiseControl(int8(0))
actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_THROTTLE, clamp(thr, -1.0, 1.0))
actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_STEERING, clamp(str, -1.0, 1.0))
actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_BRAKE_LEFT, clamp(brk, 0.0, 1.0))
actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_BRAKE_RIGHT, clamp(brk, 0.0, 1.0))
actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_CLUTCH, 0.0)
actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_HAND_BRAKE, clamp(handBrk, 0.0, 1.0))
[never_inline]
def private wto_check_echo_watchdog(unitMissionName : string; var gm : IGroundModel?;
var actor : VehiclePhysActor&; dt : float; var slot : WtoBotSlot&) : bool
assume st = slot.drive
let appThr = ground_control_state_getAxisValue(actor.phys.appliedCT, EGroundControlAxis.GCA_THROTTLE)
let appStr = ground_control_state_getAxisValue(actor.phys.appliedCT, EGroundControlAxis.GCA_STEERING)
let wanted = abs(st.prevThr) >= 0.35 || abs(st.prevStr) >= 0.45
let echoed = abs(appThr) >= 0.05 || abs(appStr) >= 0.05
if wanted && !echoed
st.deadEchoSec += clamp(dt, 0.0, 0.15)
if st.deadEchoSec >= WTO_AI_NAV_DEAD_ECHO_SEC
wto_set_phys_axes(actor, 0.0, 0.0, 0.0, 0.0)
if gm != null && gm.moveSys != null
gm.moveSys.inactive = false
st.routeBOwned = false
st.routeAFallback = true
print("WTO_AI|PHYS_FALLBACK|actor={unitMissionName}|eid={uint(slot.eid)}\n")
return false
else
st.deadEchoSec = 0.0
return true
[never_inline]
def private wto_compute_pivot_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&;
fwd, left : float3; vFwd, omega : float;
var outThr, outStr, outBrk : float&)
let wish = wto_xz_normalize(cmd.desiredDir, fwd)
let errRad = atan2(dot(wish, left), dot(wish, fwd))
let turnSign = errRad >= 0.0 ? 1.0 : -1.0
if abs(vFwd) > 3.6
outThr = vFwd > 0.0 ? -0.9 : 0.9
outBrk = 1.0
outStr = turnSign * WTO_AI_NAV_STEER_SIGN
return
let frontRoom = cmd.frontClearM >= spec.halfLen + 2.4
if spec.canPivot && cmd.frontClearM >= spec.halfLen + 1.2 && cmd.rearClearM >= spec.halfLen + 1.0 && abs(omega) >= 0.22
outThr = 0.0
outStr = clamp(turnSign - omega * 0.35, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN
return
if frontRoom
outThr = vFwd < 1.9 ? 0.72 : 0.42
outStr = (vFwd < 1.4 && abs(omega) < 0.22 ? 0.35 : 1.0) * turnSign * WTO_AI_NAV_STEER_SIGN
else
// Tight front obstacle: execute clean 3-point reverse turn instead of ramming the wall!
outThr = vFwd > -1.7 ? -0.78 : -0.48
outStr = -(vFwd > -1.2 && abs(omega) < 0.22 ? 0.35 : 1.0) * turnSign * WTO_AI_NAV_STEER_SIGN
[never_inline]
def private wto_compute_reverse_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&;
fwd, left : float3; vFwd, omega : float;
var outThr, outStr, outBrk, outHand : float&)
if cmd.rearClearM < 2.1
outThr = 0.0
outBrk = 1.0
outHand = 1.0
return
if vFwd > 0.30
outThr = -1.0
outBrk = 1.0
return
let rear = -fwd
let wishRear = wto_xz_normalize(cmd.desiredDir, rear)
// Coordinate-free signed rear angle: >0 means desired rear travel lies toward hull LEFT (+Z).
let rearErr = atan2(dot(wishRear, left), dot(wishRear, rear))
outStr = clamp(rearErr * 1.45 + omega * 0.28, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN
let maxSafeRev = min(spec.vMaxRev, sqrt(max(1.0, (cmd.rearClearM - 1.8) * 2.2)))
let vTarget = -clamp(cmd.speedMps, 1.2, max(1.4, maxSafeRev))
let vErr = vTarget - vFwd
outThr = vErr < -0.15 ? clamp(-0.52 + vErr * 0.32, -1.0, -0.35) : -0.28
[never_inline]
def private wto_compute_cruise_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&;
fwd, left : float3; vFwd, omega : float;
var outThr, outStr, outBrk : float&)
let wish = wto_xz_normalize(cmd.desiredDir, fwd)
let yawErr = atan2(dot(wish, left), dot(wish, fwd))
outStr = clamp(yawErr * 1.38 - omega * 0.28, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN
let absErr = abs(yawErr)
var vLimit = min(cmd.speedMps, spec.vMaxFwd)
if absErr > 0.22
let radiusEst = max(4.0, 14.0 / max(0.25, absErr))
vLimit = min(vLimit, sqrt(WTO_AI_NAV_CORNER_BRAKE_ACCEL * radiusEst))
if cmd.frontClearM < 12.0
vLimit = min(vLimit, max(2.2, (cmd.frontClearM - 2.0) * 0.75))
let vErr = vLimit - vFwd
if vErr < -1.8
outThr = 0.0
outBrk = clamp((-vErr - 1.5) * 0.35, 0.2, 1.0)
else
outThr = clamp(0.32 + vErr * 0.28, 0.12, 1.0)
[never_inline]
def private wto_prepare_phys_owner(var unit : Unit?; unitMissionName : string;
var gm : IGroundModel?; var actor : VehiclePhysActor&;
dt : float; var slot : WtoBotSlot&) : bool
assume st = slot.drive
if !st.routeBOwned
slot.spec.isTracked = actor.phys.trackWidth > 0.01
slot.spec.canPivot = slot.spec.isTracked && actor.phys.haveSeparateBrakes
if gm != null && gm.moveSys != null
set_destination_way_point(unit, "HALT", unit.unitTm, 0.0)
gm.moveSys.inactive = true
st.routeBOwned = true
elif gm != null && gm.moveSys != null
gm.moveSys.inactive = true
assume dmg = actor.phys.currentState.damageState
if !dmg.allowMoveControl || dmg.engineReadyness <= 0.0 || dmg.driverReadyness <= 0.0 || (dmg.trackLBroken && dmg.trackRBroken)
st.deadEchoSec = 0.0
wto_set_phys_axes(actor, 0.0, 0.0, 1.0, 1.0)
return false
vehicle_actor_set_allow_move_control(actor, true)
return wto_check_echo_watchdog(unitMissionName, gm, actor, dt, slot)
[never_inline]
def public wto_drive_step_phys(var unit : Unit?; unitMissionName : string;
var gm : IGroundModel?; var actor : VehiclePhysActor&;
dt, now : float; var slot : WtoBotSlot&)
if unit == null || actor.physEdit == null || slot.drive.routeAFallback
return
if !wto_prepare_phys_owner(unit, unitMissionName, gm, actor, dt, slot)
return
assume st = slot.drive
assume cmd = slot.driveCmd
let fwd = wto_xz_normalize(unit.unitTm[0], float3(1.0, 0.0, 0.0))
let left = float3(-fwd.z, 0.0, fwd.x)
let curYaw = atan2(fwd.z, fwd.x)
let vFwd = dot(vehicle_phys_getCurrentStateVelocity(actor.phys), fwd)
st.lastVFwd = vFwd
let age = now - st.prevYawAt
st.omegaYawRad = (age > 1.0e-4 && age <= 0.25) ? lerp(clamp(wto_wrap_rad(curYaw - st.prevYaw) / age, -3.0, 3.0), st.omegaYawRad, 0.6) : 0.0
st.prevYaw = curYaw
st.prevYawAt = now
var thr = 0.0
var str = 0.0
var brk = 0.0
var hand = 0.0
if !cmd.valid || cmd.mode == WTO_DRIVE_HALT || cmd.speedMps <= 0.05
thr = abs(vFwd) > 0.35 ? (vFwd > 0.0 ? -1.0 : 1.0) : 0.0
brk = 1.0
hand = abs(vFwd) > 0.35 ? 0.0 : 1.0
elif cmd.mode == WTO_DRIVE_PIVOT
wto_compute_pivot_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk)
elif cmd.mode == WTO_DRIVE_REVERSE
wto_compute_reverse_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk, hand)
else
wto_compute_cruise_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk)
st.prevThr = thr
st.prevStr = str
wto_set_phys_axes(actor, thr, str, brk, hand)
+274
View File
@@ -0,0 +1,274 @@
// Deterministic custom fire-control & ballistics actuator:
// - Keeps stock C++ ground inaccuracy ("attack_target" sway & target list bloat) locked out via
// "dont_aim", yielding only for SPAA vs aircraft or missile-only vehicles;
// - Reads authoritative `gun.isReadyToShoot`, `gun.currentLoadedAmmoCount`, and live muzzle
// `weapon_calcShootTm` transform (`gunTm[3]` muzzle position, `gunTm[0]` barrel vector);
// - Solves ballistic elevation & smoothed velocity lead via `Ballistics::calculate_arc_low_start_dir`;
// - Enforces strict barrel angular-velocity settle (`settleHoldSec`) + friendly corridor safety
// before triggering `unit_single_shot`.
options indenting = 2
options no_global_heap = true
module wto_ai_fire_common shared
require ecs
require app
require math
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_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_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_inspect_primary_weapon(unit : Unit 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 anyLoaded = false
foreach_primary_gun(unit.weap.Weapons) <| $(weapon)
if weapon == null || weapon.isDummyGun || weapon.prop.launcher
return
let gun = as_gun(weapon)
if gun == null
return
anyGun = true
if gun.isInoperable
return
anyAlive = true
if fc.turretNo < 0
fc.turretNo = weapon.turretNo
if gun.isReadyToShoot
fc.gunReady = true
if gun.currentLoadedAmmoCount > 0 || gun.currentBulletSet.bulletsCount > 0 || weapon.countBullets > 0
anyLoaded = true
fc.gunDamaged = anyGun && !anyAlive
fc.reloading = anyAlive && !fc.gunReady && anyLoaded
[never_inline]
def private wto_friendly_corridor_clear(world : WtoWorldSnap const&; selfEid : EntityId;
army : int; muzzlePos, aimPos : float3) : bool
let delta = aimPos - muzzlePos
let segLen = length(delta)
if segLen < 4.0
return true
let dir = delta / segLen
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.army != army || u.eid == selfEid
continue
let core = u.pos + float3(0.0, 1.3, 0.0)
let along = dot(core - muzzlePos, dir)
if along <= 1.5 || along >= segLen - 1.5
continue
let clearR = WTO_AI_FC_FRIENDLY_CORRIDOR_M + u.halfWid
if length_sq(core - (muzzlePos + dir * along)) < clearR * clearR
return false
return true
[never_inline]
def private wto_solve_ballistic_aim(muzzlePos : float3; myVel : float3; slot : WtoBotSlot const&;
tgtPos : float3; var outAimPt, outWishDir : float3&) : float
// Prefer center-of-mass (+1.25m); shift up to turret (+1.85m) when lower hull is terrain-masked!
var aimPt = tgtPos + float3(0.0, 1.25, 0.0)
if !wto_terrain_los_clear(muzzlePos, aimPt)
aimPt = tgtPos + float3(0.0, 1.88, 0.0)
let rawDist = length(aimPt - muzzlePos)
let dragLoss = clamp(slot.spec.shellDragCx * 0.00011 * rawDist, 0.0, 0.28)
let vEff = max(180.0, slot.spec.muzzleSpeedMps * (1.0 - dragLoss))
var leadPt = aimPt
for _iter in range(2)
let tof = clamp(length(leadPt - muzzlePos) / vEff, 0.0, 3.2)
let selfComp = slot.spec.hasVertStab ? (myVel * (tof * 0.15)) : float3(0.0, 0.0, 0.0)
leadPt = aimPt + slot.perceive.smoothedVel * tof - selfComp
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 : float; 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.35) * dtStep
let maxPitchStep = max(10.0, slot.spec.turretPitchSpd * 1.45) * dtStep
let yawDelta = clamp(wto_wrap_deg(wishYawDeg - fc.curYawDeg), -maxYawStep * 3.0, maxYawStep * 3.0)
let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep * 3.0, maxPitchStep * 3.0)
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 private wto_try_delegate_stock_fire(var unit : Unit?; var gm : IGroundModel?; slot : WtoBotSlot const&) : bool
if !slot.tactics.spaaYieldAir && !(slot.spec.isPureLauncher && slot.perceive.hasClearLos && !!slot.perceive.targetEid)
return false
if gm != null
*gm |> set_check_visibility_target(true)
*gm |> set_ignore_stop_for_fire(slot.tactics.spaaYieldAir)
if slot.spec.isPureLauncher
var tgtU = get_unit_by_eid(slot.perceive.targetEid)
if tgtU != null && tgtU.isAlive
add_unit_for_target(*gm, tgtU)
set_unit_attack_type(unit, "attack_target")
return true
[never_inline]
def private wto_try_pull_trigger(world : WtoWorldSnap const&; var unit : Unit?;
now, dt, distToTgt : float; muzzlePos, aimPt, liveDir, wishDir : float3;
var slot : WtoBotSlot&)
assume fc = slot.fire
let aimErrDeg = acos(clamp(dot(liveDir, wishDir), -1.0, 1.0)) * WTO_RAD_TO_DEG
fc.lastAimErrDeg = aimErrDeg
let allowErrDeg = clamp(atan2(WTO_AI_FC_CLOSE_HIT_RADIUS_M, max(distToTgt, 6.0)) * WTO_RAD_TO_DEG, WTO_AI_FC_BASE_ALIGN_DEG, 2.4)
let chassisStable = slot.spec.hasVertStab || length(unit.vel) <= WTO_AI_FC_UNSTAB_STOP_MPS || distToTgt < 22.0
let settled = aimErrDeg <= allowErrDeg && fc.barrelOmegaDegSec <= WTO_AI_FC_BARREL_SETTLE_DEG_SEC && chassisStable
fc.lastAligned = settled
fc.settleHoldSec = settled ? (fc.settleHoldSec + clamp(dt, 0.005, 0.10)) : max(0.0, fc.settleHoldSec - dt * 2.0)
let minCadence = slot.spec.isAutocannonBelt ? 0.12 : 0.65
if !fc.gunReady || fc.settleHoldSec < WTO_AI_FC_SETTLE_HOLD_SEC || (now - fc.lastShotAt) < minCadence
return
if wto_terrain_hard_ray(muzzlePos, liveDir, min(distToTgt - 1.5, 45.0)) < min(distToTgt - 2.0, 42.0)
return
if !wto_friendly_corridor_clear(world, slot.eid, slot.army, muzzlePos, aimPt)
return
unit_single_shot(unit, int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY))
fc.lastShotAt = now
fc.shotCount++
fc.shotErrSumDeg += aimErrDeg
fc.maxShotErrDeg = max(fc.maxShotErrDeg, aimErrDeg)
if !slot.spec.isAutocannonBelt
fc.settleHoldSec = 0.0
[never_inline]
def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?;
now, dt : float; var slot : WtoBotSlot&)
if !WTO_AI_LAYER_FIRE_CONTROL || unit == null || unit.weap == null
return
if wto_try_delegate_stock_fire(unit, as_gm(unit), slot)
return
set_unit_attack_type(unit, "dont_aim")
wto_inspect_primary_weapon(unit, 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.posture == WTO_POSTURE_RETREAT))
if engageValid
distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, slot, slot.perceive.knownPos, aimPt, wishWorldDir)
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
wto_try_pull_trigger(world, unit, now, dt, distToTgt, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot)
+181
View File
@@ -0,0 +1,181 @@
// Team-level macro objective scheduler: monotone opening lateral lane split, capture-circle
// insider cap (`capMaxInsiders`) with dispersed flank overwatch anchors outside the circle,
// bounded recapture response, death-zone caution, SPAA rear anchor, and enemy spawn avoidance.
options indenting = 2
options no_global_heap = true
module wto_ai_macro_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_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common
[never_inline]
def private wto_death_zone_kills(world : WtoWorldSnap const&; army : int; pos : float3; now : float) : int
let radSq = wto_sq(WTO_AI_MACRO_DEATH_ZONE_RAD_M)
var kills = 0
for i in range(WTO_MAX_DEATHS)
assume d = world.deaths[i]
if d.army == army && (now - d.at) <= WTO_AI_MACRO_DEATH_ZONE_TTL_SEC && wto_xz_dist_sq(pos, d.pos) <= radSq
kills++
return kills
[never_inline]
def private wto_clamp_away_enemy_spawn(world : WtoWorldSnap const&; army : int; pos : float3) : float3
let enemyArmy = army == 1 ? 2 : 1
if enemyArmy < 1 || enemyArmy > 2 || !world.teamSpawnValid[enemyArmy]
return pos
let eSpawn = world.teamSpawnCenter[enemyArmy]
let minDist = WTO_AI_MACRO_ENEMY_SPAWN_AVOID_M
let dSq = wto_xz_dist_sq(pos, eSpawn)
if dSq >= minDist * minDist
return pos
let away = wto_xz_normalize(pos - eSpawn, float3(1.0, 0.0, 0.0))
return float3(eSpawn.x + away.x * minDist, pos.y, eSpawn.z + away.z * minDist)
[never_inline]
def private wto_pick_cap_anchor(world : WtoWorldSnap const&; army : int; eid : EntityId;
capIdx : int; outsideOverwatch : bool) : float3
assume cap = world.caps[capIdx]
let h = uint(eid)
let friendlySpawn = world.teamSpawnValid[army] ? world.teamSpawnCenter[army] : world.battleCenter
let toCap = wto_xz_normalize(cap.center - friendlySpawn, float3(1.0, 0.0, 0.0))
let lat = float3(-toCap.z, 0.0, toCap.x)
if !outsideOverwatch
let slotAng = float(h % 5u) * (2.0 * WTO_PI / 5.0) + float(capIdx) * 0.7
let inRad = clamp(cap.radius * 0.52, 7.0, max(8.0, cap.radius - 4.5))
var insidePt = float3(cap.center.x + cos(slotAng) * inRad, cap.center.y, cap.center.z + sin(slotAng) * inRad)
if wto_terrain_point_valid(army, insidePt)
return insidePt
return cap.center
// Cap already has enough insiders -> fan remaining bots onto flank overwatch 24..48m outside!
let fanIdx = int(h % 6u)
let sideSign = (fanIdx % 2) == 0 ? 1.0 : -1.0
let tier = float(fanIdx / 2 + 1)
let latOff = sideSign * (cap.radius + 18.0 + tier * 12.0)
let depthOff = -8.0 + float(int((h / 6u) % 3u) - 1) * 14.0
for attempt in range(4)
let scale = attempt == 0 ? 1.0 : (attempt == 1 ? -1.0 : (attempt == 2 ? 0.65 : -0.65))
var cand = cap.center + lat * (latOff * scale) + toCap * depthOff
if cap.ownerArmy == army
cand = wto_clamp_away_enemy_spawn(world, army, cand)
cand = wto_clamp_battle_xz(cand, world.battleCenter, world.battleRadius, 40.0)
if wto_terrain_point_valid(army, cand)
return cand
return cap.center - toCap * (cap.radius + 22.0)
[never_inline]
def private wto_assign_spaa_order(world : WtoWorldSnap const&; now : float; myPos : float3;
var slot : WtoBotSlot&)
let army = slot.army
let needNew = !slot.macro.spaaAnchorValid || (slot.fire.lastShotAt > slot.macro.spaaRelocateAt && (now - slot.fire.lastShotAt) > 3.0)
if !needNew
slot.macro.goalPos = slot.macro.spaaAnchorPos
slot.macro.capIndex = -1
slot.macro.valid = true
return
let spawnPt = world.teamSpawnValid[army] ? world.teamSpawnCenter[army] : myPos
let frontPt = world.capCount > 0 ? world.caps[0].center : world.battleCenter
let toFront = wto_xz_normalize(frontPt - spawnPt, float3(1.0, 0.0, 0.0))
let lat = float3(-toFront.z, 0.0, toFront.x)
let base = frontPt - toFront * WTO_AI_MACRO_SPAA_REAR_OFFSET_M
let tickIdx = max(0, int(now / max(5.0, WTO_AI_MACRO_SPAA_RELOCATE_SEC)))
let phase = int((uint(slot.eid) + uint(tickIdx)) % 5u)
let side = float(phase - 2) * 42.0
var cand = wto_clamp_battle_xz(base + lat * side, world.battleCenter, world.battleRadius, 45.0)
if !wto_terrain_point_valid(army, cand)
cand = myPos
slot.macro.spaaAnchorPos = cand
slot.macro.spaaAnchorValid = true
slot.macro.spaaRelocateAt = now + WTO_AI_MACRO_SPAA_RELOCATE_SEC
slot.macro.goalPos = cand
slot.macro.capIndex = -1
slot.macro.valid = true
[never_inline]
def private wto_count_cap_insiders(world : WtoWorldSnap const&; army : int; var counts : int[8]&)
for k in range(WTO_MAX_CAPS)
counts[k] = 0
for c in range(world.capCount)
let rSq = wto_sq(world.caps[c].radius + 14.0)
for u in range(world.unitCount)
assume uSnap = world.units[u]
if uSnap.isAlive && uSnap.isGround && uSnap.army == army && wto_xz_dist_sq(uSnap.pos, world.caps[c].center) <= rSq
counts[c]++
[never_inline]
def private wto_pick_best_cap_idx(world : WtoWorldSnap const&; army : int; now : float;
openingSplit : bool; myPos, axisLat : float3;
prevCapIdx : int; capAssigned : int[8]) : int
var bestCap = 0
var bestCost = 1.0e9
let myLat = dot(myPos - world.battleCenter, axisLat)
for c in range(world.capCount)
assume cap = world.caps[c]
var cost = sqrt(wto_xz_dist_sq(myPos, cap.center))
if cap.ownerArmy != army
if capAssigned[c] < WTO_AI_MACRO_RECAP_MIN_BOTS
cost -= 240.0
elif capAssigned[c] >= WTO_AI_MACRO_RECAP_MAX_BOTS && world.capCount > 1
cost += 220.0
else
cost -= 95.0
else
cost += 120.0 + float(capAssigned[c]) * 65.0
if prevCapIdx == c
cost -= WTO_AI_MACRO_CAP_STICKY_BONUS_M
if openingSplit && world.capCount > 1
cost += abs(myLat - dot(cap.center - world.battleCenter, axisLat)) * 0.85
let kills = wto_death_zone_kills(world, army, cap.center, now)
if kills >= WTO_AI_MACRO_DEATH_ZONE_MIN_KILLS
cost += float(kills) * 85.0
if cost < bestCost
bestCost = cost
bestCap = c
return bestCap
[never_inline]
def private wto_assign_army_caps(world : WtoWorldSnap const&; army : int; now : float;
var bots : WtoBotSlot[64]&)
var capInsiders : int[8]
var capAssigned : int[8]
wto_count_cap_insiders(world, army, capInsiders)
for c in range(WTO_MAX_CAPS)
capAssigned[c] = capInsiders[c]
let openingSplit = (now - world.matchStartAt) <= WTO_AI_MACRO_OPENING_SPLIT_SEC
let spawnPt = world.teamSpawnValid[army] ? world.teamSpawnCenter[army] : world.battleCenter
let axisFwd = wto_xz_normalize(world.battleCenter - spawnPt, float3(1.0, 0.0, 0.0))
let axisLat = float3(-axisFwd.z, 0.0, axisFwd.x)
for i in range(WTO_MAX_BOTS)
if !bots[i].used || bots[i].army != army
continue
let uIdx = wto_world_find_unit(world, bots[i].eid)
if uIdx < 0
continue
let myPos = world.units[uIdx].pos
if bots[i].spec.role == WTO_ROLE_SPAA
wto_assign_spaa_order(world, now, myPos, bots[i])
continue
if world.capCount <= 0
bots[i].macro.goalPos = wto_clamp_away_enemy_spawn(world, army, world.battleCenter + axisLat * float(int(uint(bots[i].eid) % 5u) - 2) * 55.0)
bots[i].macro.capIndex = -1
bots[i].macro.valid = true
continue
let bestCap = wto_pick_best_cap_idx(world, army, now, openingSplit, myPos, axisLat, bots[i].macro.capIndex, capAssigned)
let overwatchOut = capAssigned[bestCap] >= WTO_AI_MACRO_CAP_MAX_INSIDERS || bots[i].spec.role == WTO_ROLE_TD
if !overwatchOut
capAssigned[bestCap]++
bots[i].macro.capIndex = bestCap
bots[i].macro.overwatchOutside = overwatchOut
bots[i].macro.cautious = wto_death_zone_kills(world, army, world.caps[bestCap].center, now) >= WTO_AI_MACRO_DEATH_ZONE_MIN_KILLS
bots[i].macro.goalPos = wto_pick_cap_anchor(world, army, bots[i].eid, bestCap, overwatchOut)
bots[i].macro.valid = true
[never_inline]
def public wto_macro_update_all(world : WtoWorldSnap const&; now : float; var bots : WtoBotSlot[64]&)
wto_assign_army_caps(world, 1, now, bots)
wto_assign_army_caps(world, 2, now, bots)
+57
View File
@@ -0,0 +1,57 @@
// Pure zero-heap scalar, angle, and XZ plane math helpers for WTOffline's ground AI modules.
options indenting = 2
options no_global_heap = true
module wto_ai_math_common shared
require math
let public WTO_PI = 3.14159265
let public WTO_RAD_TO_DEG = 57.29577951
let public WTO_DEG_TO_RAD = 0.01745329
def public wto_sq(x : float) : float
return x * x
def public wto_is_finite(x : float) : bool
return x == x && x > -1.0e20 && x < 1.0e20
def public wto_is_finite3(v : float3) : bool
return wto_is_finite(v.x) && wto_is_finite(v.y) && wto_is_finite(v.z)
def public wto_xz_dist_sq(a, b : float3) : float
return wto_sq(a.x - b.x) + wto_sq(a.z - b.z)
def public wto_xz_len(v : float3) : float
return sqrt(v.x * v.x + v.z * v.z)
def public wto_xz_normalize(v, fallback : float3) : float3
let l = sqrt(v.x * v.x + v.z * v.z)
return l > 1.0e-4 ? float3(v.x / l, 0.0, v.z / l) : fallback
def public wto_wrap_rad(angle : float) : float
var a = angle
while a > WTO_PI
a -= 2.0 * WTO_PI
while a < -WTO_PI
a += 2.0 * WTO_PI
return a
def public wto_wrap_deg(angle : float) : float
var a = angle
while a > 180.0
a -= 360.0
while a < -180.0
a += 360.0
return a
def public wto_clamp_battle_xz(pos, center : float3; radius, margin : float) : float3
if radius <= margin + 10.0
return pos
let maxR = radius - margin
let dx = pos.x - center.x
let dz = pos.z - center.z
let dSq = dx * dx + dz * dz
if dSq <= maxR * maxR
return pos
let s = maxR / max(1.0, sqrt(dSq))
return float3(center.x + dx * s, pos.y, center.z + dz * s)
+248
View File
@@ -0,0 +1,248 @@
// Bidirectional non-holonomic local planner:
// - Directed 7-arc reverse trajectory planner for ridge withdrawals, tactical peeks, cliff escapes,
// and jam unsticking (enabling sustained 30-50m reverse transfers);
// - Stationary combat hull discipline (zero hull-pivot whip on turreted tanks during ENGAGE_HALT);
// - Forward 9-arc DWA rollout with cliff rejection, TTC ally overtaking, and jam/crowd penalties.
options indenting = 2
options no_global_heap = true
module wto_ai_nav_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_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_crowd_common
require %appGame.wtoai.wto_ai_route_common
[never_inline]
def private wto_wreck_or_ally_clearance(world : WtoWorldSnap const&; selfEid : EntityId;
pt : float3; tSec, selfRad : float) : float
var pen = 0.0
for w in range(world.wreckCount)
let r = selfRad + max(world.wrecks[w].halfLen, world.wrecks[w].halfWid) + WTO_AI_TERRAIN_MARGIN_M
let dSq = wto_xz_dist_sq(pt, world.wrecks[w].pos)
if dSq < r * r
return 1.0e6
elif dSq < wto_sq(r + 3.5)
pen += 18.0
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.eid == selfEid
continue
let predPos = u.pos + u.vel * min(tSec, 1.6)
let r = selfRad + max(u.halfLen, u.halfWid) + WTO_AI_TERRAIN_MARGIN_M
let dSq = wto_xz_dist_sq(pt, predPos)
if dSq < r * r
return 1.0e6
elif dSq < wto_sq(r + 5.0)
pen += 22.0
return pen
// Evaluate 7 curved rear trajectories (`16m` behind chassis) toward `reverseGoal`.
[never_inline]
def private wto_eval_reverse_arcs(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, reverseGoal : float3;
var slot : WtoBotSlot&; var outRearDir : float3&) : bool
let rearBase = -wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))
let baseYaw = atan2(rearBase.z, rearBase.x)
let wishDir = wto_xz_normalize(reverseGoal - myPos, rearBase)
let selfRad = max(slot.spec.halfWid, 1.65)
var bestScore = -1.0e9
var found = false
outRearDir = rearBase
for a in range(7)
let steerFrac = float(a - 3) / 3.0
let arcCurv = steerFrac * 0.042
var cur = myPos
var blocked = false
var arcPen = abs(steerFrac) * 2.5
for s in range(1, 5)
let dist = float(s) * 3.8
let yaw = baseYaw + arcCurv * dist
let stepDir = float3(cos(yaw), 0.0, sin(yaw))
let nx = cur.x + stepDir.x * 3.8
let nz = cur.z + stepDir.z * 3.8
var gy = cur.y
if !wto_terrain_drivable_y(cur, nx, nz, gy)
blocked = true
break
if wto_terrain_hard_ray(cur + float3(0.0, 1.25, 0.0), stepDir, 4.2) < 3.7
blocked = true
break
let nxt = float3(nx, gy, nz)
let dynPen = wto_wreck_or_ally_clearance(world, slot.eid, nxt, dist / max(1.8, slot.spec.vMaxRev), selfRad)
if dynPen >= 1.0e5
blocked = true
break
arcPen += dynPen * 0.25 + wto_crowd_point_penalty(world, slot.army, slot.eid, nxt) * 0.2
cur = nxt
if blocked
continue
let firstYaw = baseYaw + arcCurv * 5.5
let candDir = float3(cos(firstYaw), 0.0, sin(firstYaw))
if wto_terrain_has_cliff_ahead(myPos, candDir, 15.0)
continue
let score = dot(candDir, wishDir) * 35.0 - arcPen - wto_world_jam_penalty(world, cur, now) * 0.4
if score > bestScore
bestScore = score
outRearDir = candDir
found = true
return found
// Evaluate 9 curved forward trajectories (`22m` ahead) with hard cliff rejection and traffic cost.
[never_inline]
def private wto_eval_forward_arcs(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, wishDir : float3; speedCmd : float;
var slot : WtoBotSlot&; var outFwdDir : float3&) : bool
let fwdBase = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))
let baseYaw = atan2(fwdBase.z, fwdBase.x)
let selfRad = max(slot.spec.halfWid, 1.65)
var bestScore = -1.0e9
var found = false
outFwdDir = wishDir
for a in range(9)
let steerFrac = float(a - 4) / 4.0
let arcCurv = steerFrac * 0.038
let firstYaw = baseYaw + arcCurv * 6.5
let candDir = float3(cos(firstYaw), 0.0, sin(firstYaw))
if wto_terrain_has_cliff_ahead(myPos, candDir, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M)
continue
var cur = myPos
var blocked = false
var arcPen = abs(steerFrac) * 2.2
for s in range(1, 6)
let dist = float(s) * 4.2
let yaw = baseYaw + arcCurv * dist
let stepDir = float3(cos(yaw), 0.0, sin(yaw))
let nx = cur.x + stepDir.x * 4.2
let nz = cur.z + stepDir.z * 4.2
var gy = cur.y
if !wto_terrain_drivable_y(cur, nx, nz, gy)
blocked = true
break
if wto_terrain_hard_ray(cur + float3(0.0, 1.3, 0.0), stepDir, 4.6) < 4.1
blocked = true
break
let nxt = float3(nx, gy, nz)
let dynPen = wto_wreck_or_ally_clearance(world, slot.eid, nxt, dist / max(2.5, speedCmd), selfRad)
if dynPen >= 1.0e5
blocked = true
break
arcPen += dynPen * 0.3 + wto_crowd_point_penalty(world, slot.army, slot.eid, nxt) * 0.35
cur = nxt
if blocked
continue
let align = dot(candDir, wishDir) * 40.0 + dot(candDir, slot.nav.steerDir) * 4.5
let score = align - arcPen - wto_world_jam_penalty(world, cur, now)
if score > bestScore
bestScore = score
outFwdDir = candDir
found = true
return found
[never_inline]
def private wto_set_drive_cmd(var cmd : WtoDriveCmd&; mode : int; targetPos, desiredDir : float3;
speedMps, frontClr, rearClr : float)
cmd.valid = true
cmd.mode = mode
cmd.targetPos = targetPos
cmd.desiredDir = desiredDir
cmd.speedMps = speedMps
cmd.frontClearM = frontClr
cmd.rearClearM = rearClr
[never_inline]
def private wto_handle_stationary_engage(myPos, hullFwd : float3; var slot : WtoBotSlot&)
// Casemate / limited-traverse TDs rotate hull ONLY while target is outside 78% of gun arc.
if slot.spec.isLimitedTraverse && !!slot.perceive.targetEid
let toTgt = wto_xz_normalize(slot.perceive.knownPos - myPos, hullFwd)
let angDeg = acos(clamp(dot(toTgt, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG
if angDeg > slot.spec.yawLimitDeg * 0.78
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + toTgt * 18.0, toTgt, 2.0, slot.nav.frontClearM, slot.nav.rearClearM)
return
// Turreted tanks (and aligned TDs) hold chassis completely still so barrel settles cleanly!
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
[never_inline]
def private wto_check_stuck_watchdog(var world : WtoWorldSnap&; now : float;
myPos, wishDir : float3; var slot : WtoBotSlot&)
assume nav = slot.nav
let movingIntent = slot.tactics.desiredSpeedMps > 1.2 && now >= nav.reverseUntil
if !movingIntent
nav.stuckOrigin = myPos
nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
return
if nav.stuckCheckAt < -50.0
nav.stuckOrigin = myPos
nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
return
if now < nav.stuckCheckAt
return
let moved = sqrt(wto_xz_dist_sq(myPos, nav.stuckOrigin))
nav.stuckOrigin = myPos
nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
if moved >= WTO_AI_NAV_STUCK_MIN_MOVE_M
return
wto_world_record_jam(world, myPos + wishDir * 6.0, now)
wto_route_request_detour(world, now, myPos, wishDir, slot)
let backIdx = clamp(slot.route.corridorIdx - 2, 0, max(0, slot.route.corridorLen - 1))
nav.reverseAnchor = slot.route.corridorLen > 0 ? slot.route.corridor[backIdx] : (myPos - wishDir * 22.0)
nav.reverseUntil = now + max(WTO_AI_NAV_UNSTICK_REV_SEC, 3.6)
nav.reverseCount++
[never_inline]
def private wto_try_reverse_drive(world : WtoWorldSnap const&; now : float;
myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool
let posMode = slot.tactics.posture
let wantTacRev = posMode == WTO_POSTURE_REVERSE_WITHDRAW || posMode == WTO_POSTURE_PEEK_BACK
if !wantTacRev && now >= slot.nav.reverseUntil
return false
let revGoal = wantTacRev ? slot.tactics.moveGoal : slot.nav.reverseAnchor
var rearDir = -hullFwd
if slot.nav.rearClearM > 2.4 && wto_eval_reverse_arcs(world, now, myPos, hullFwd, revGoal, slot, rearDir)
slot.nav.steerDir = rearDir
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_REVERSE, myPos + rearDir * 18.0, rearDir, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM)
return true
slot.nav.reverseUntil = -100.0
return false
[never_inline]
def public wto_nav_update(var world : WtoWorldSnap&; now : float;
myPos, rawHullFwd : float3; var slot : WtoBotSlot&)
if !WTO_AI_LAYER_NAVIGATION
slot.driveCmd.valid = false
return
let hullFwd = wto_xz_normalize(rawHullFwd, float3(1.0, 0.0, 0.0))
let probeBase = myPos + float3(0.0, 1.25, 0.0)
slot.nav.frontClearM = wto_terrain_hard_ray(probeBase, hullFwd, 24.0)
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.posture == WTO_POSTURE_ENGAGE_HALT || slot.tactics.desiredSpeedMps <= 0.05
slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
wto_handle_stationary_engage(myPos, hullFwd, slot)
return
if wto_try_reverse_drive(world, now, myPos, hullFwd, slot)
return
let wp = wto_route_select_waypoint(world, now, myPos, slot.tactics.moveGoal, slot)
let wishDir = wto_xz_normalize(wp - myPos, hullFwd)
wto_check_stuck_watchdog(world, now, myPos, wishDir, slot)
var bestDir = wishDir
if !wto_eval_forward_arcs(world, now, myPos, hullFwd, wishDir, slot.tactics.desiredSpeedMps, slot, bestDir)
if slot.nav.rearClearM > 3.2
slot.nav.reverseAnchor = myPos - hullFwd * 26.0
slot.nav.reverseUntil = now + 4.8
slot.nav.reverseCount++
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_REVERSE, slot.nav.reverseAnchor, -hullFwd, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM)
return
bestDir = wishDir
slot.nav.steerDir = bestDir
let turnDeg = acos(clamp(dot(bestDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG
let needPivot = turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG || (slot.nav.frontClearM < slot.spec.halfLen + 1.8 && turnDeg > 32.0)
wto_set_drive_cmd(slot.driveCmd, needPivot ? WTO_DRIVE_PIVOT : WTO_DRIVE_CRUISE, myPos + bestDir * 22.0, bestDir, slot.tactics.desiredSpeedMps, slot.nav.frontClearM, slot.nav.rearClearM)
+169
View File
@@ -0,0 +1,169 @@
// 6-channel no-wallhack perception: foliage-filtered visual LOS, close engine & gunfire audio,
// team radio sharing, hit retaliation alert, frozen visual memory, strong target stickiness,
// smoothed target velocity, and fanned-out radio hunting bearings.
options indenting = 2
options no_global_heap = true
module wto_ai_perceive_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_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common
[never_inline]
def private wto_check_visual_enemy(myEye, lookDir : float3; cosHalfFov : float;
enemy : WtoUnitSnap const&; var outDist : float&) : bool
let aimMid = enemy.pos + float3(0.0, enemy.isAir ? 0.0 : 1.35, 0.0)
let delta = aimMid - myEye
let dist = length(delta)
outDist = dist
let maxRange = enemy.isAir ? 2600.0 : WTO_AI_TACTICS_VISION_RANGE_M
if dist > maxRange || dist < 1.0
return false
let dirXZ = wto_xz_normalize(delta, lookDir)
let inCone = dot(dirXZ, lookDir) >= cosHalfFov
let inPeriph = dist <= WTO_AI_TACTICS_PERIPHERAL_RANGE_M
if !inCone && !inPeriph && !enemy.isAir
return false
if wto_terrain_los_clear(myEye, aimMid)
return true
if !enemy.isAir && dist <= 900.0
let aimTurret = enemy.pos + float3(0.0, 2.05, 0.0)
if wto_terrain_los_clear(myEye, aimTurret)
return true
return false
[never_inline]
def private wto_update_audio_and_radio_alerts(world : WtoWorldSnap const&; now : float;
myPos : float3; var slot : WtoBotSlot&)
assume p = slot.perceive
// Priority A: Recent hit retaliation alert (never reveals hidden position, only direction).
if (now - p.lastDamagedAt) <= 4.0 && !!p.lastOffenderEid
let offIdx = wto_world_find_unit(world, p.lastOffenderEid)
if offIdx >= 0 && world.units[offIdx].army != slot.army
let d = world.units[offIdx].pos - myPos
p.alertYawRad = atan2(d.z, d.x)
p.alertUntil = now + 4.5
return
// Priority B: Close enemy engine / cannon audio.
var bestAudioDist = 1.0e9
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.army == slot.army
continue
let d = sqrt(wto_xz_dist_sq(myPos, u.pos))
let engRange = WTO_AI_TACTICS_ENGINE_AUDIO_M * (0.35 + 0.65 * u.engineRpm)
let heard = d <= engRange || (u.isShooting && d <= WTO_AI_TACTICS_SHOT_AUDIO_M)
if heard && d < bestAudioDist
bestAudioDist = d
let dir = u.pos - myPos
p.alertYawRad = atan2(dir.z, dir.x)
p.alertUntil = now + 3.2
if bestAudioDist < 1.0e8
return
// Priority C: Friendly radio spot alert bearing.
let radioSq = wto_sq(WTO_AI_TACTICS_RADIO_SHARE_M)
for r in range(WTO_MAX_RADIO)
assume sp = world.radioSpots[r]
if sp.untilAt > now && sp.army == slot.army && wto_xz_dist_sq(myPos, sp.pos) <= radioSq
let dir = sp.pos - myPos
p.alertYawRad = atan2(dir.z, dir.x)
p.alertUntil = now + 2.8
return
[never_inline]
def private wto_select_best_visual_enemy(world : WtoWorldSnap const&; now : float;
myEye, lookDir : float3; slot : WtoBotSlot const&) : int
assume p = slot.perceive
let cosHalfFov = cos(0.5 * WTO_AI_TACTICS_VISION_FOV_DEG * WTO_DEG_TO_RAD)
let isSpaa = slot.spec.role == WTO_ROLE_SPAA
var bestIdx = -1
var bestScore = 1.0e9
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || u.army == slot.army || (u.isAir && !isSpaa)
continue
var dist = 0.0
if !wto_check_visual_enemy(myEye, lookDir, cosHalfFov, u, dist)
continue
var score = dist - (u.isAir && isSpaa ? 900.0 : 0.0)
if u.eid == p.lockedEid && now < p.lockedUntil
score -= 320.0
elif u.eid == p.lastOffenderEid && (now - p.lastDamagedAt) <= 5.0
score -= 90.0
elif u.isShooting && dist < 220.0
score -= 35.0
if dist < 45.0
score -= 180.0
if score < bestScore
bestScore = score
bestIdx = i
return bestIdx
[never_inline]
def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float;
myPos, hullFwd : float3; var slot : WtoBotSlot&)
assume p = slot.perceive
let myEye = myPos + float3(0.0, 2.15, 0.0)
var lookDir = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))
if slot.fire.servoInit
let worldYaw = atan2(hullFwd.z, hullFwd.x) - slot.fire.curYawDeg * WTO_DEG_TO_RAD
lookDir = float3(cos(worldYaw), 0.0, sin(worldYaw))
let bestIdx = wto_select_best_visual_enemy(world, now, myEye, lookDir, slot)
if bestIdx >= 0
assume tgt = world.units[bestIdx]
let sameTarget = p.targetEid == tgt.eid
p.targetEid = tgt.eid
p.targetIsAir = tgt.isAir
p.hasClearLos = true
p.knownPos = tgt.pos
let alpha = sameTarget ? clamp(dt * 6.0, 0.18, 0.65) : 1.0
p.smoothedVel = sameTarget ? lerp(p.smoothedVel, tgt.vel, alpha) : tgt.vel
p.lastSeenAt = now
if p.lockedEid != tgt.eid || now >= p.lockedUntil - 0.5
p.lockedEid = tgt.eid
p.lockedUntil = now + WTO_AI_TACTICS_STICKY_SEC
if !tgt.isAir && (now - p.lastRadioSentAt) >= 2.5
p.lastRadioSentAt = now
wto_world_broadcast_radio(world, slot.army, tgt.eid, tgt.pos, now)
return
p.hasClearLos = false
p.smoothedVel *= 0.5
if !!p.targetEid && (now - p.lastSeenAt) > WTO_AI_TACTICS_MEMORY_TTL_SEC
p.targetEid = INVALID_ENTITY_ID
p.lockedEid = INVALID_ENTITY_ID
wto_update_audio_and_radio_alerts(world, now, myPos, slot)
// Compute a fanned-out hunting anchor toward a team radio spot so multiple bots pincer from
// spread-out angles instead of converging onto the exact same coordinate.
[never_inline]
def public wto_perceive_pick_hunt_pos(world : WtoWorldSnap const&; army : int; eid : EntityId;
myPos : float3; now : float; var outPos : float3&) : bool
var bestDistSq = wto_sq(min(WTO_AI_TACTICS_RADIO_SHARE_M, 560.0))
var found = false
var spotPos = myPos
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(myPos, sp.pos)
if dSq < bestDistSq && dSq > 2500.0
bestDistSq = dSq
spotPos = sp.pos
found = true
if !found
return false
let toSpot = wto_xz_normalize(spotPos - myPos, float3(1.0, 0.0, 0.0))
let lat = float3(-toSpot.z, 0.0, toSpot.x)
let fanOffset = float(int(uint(eid) % 5u) - 2) * 28.0
var cand = spotPos - toSpot * 65.0 + lat * fanOffset
cand = wto_clamp_battle_xz(cand, world.battleCenter, world.battleRadius, 40.0)
if !wto_terrain_point_valid(army, cand)
cand = spotPos
outPos = cand
return true
+180
View File
@@ -0,0 +1,180 @@
// Corridor route planner: wide-projected `nm1` NavMesh pathfinding (fixing off-road hill caps),
// 5-wing lateral approach relays, crest-safe cross-country shortcuts, and corridor-independent
// jam/cluster bypass waypoints.
options indenting = 2
options no_global_heap = true
module wto_ai_route_common shared
require ecs
require math
require pathfinder
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_crowd_common
[never_inline]
def private wto_project_nav_wide(navIdx : int; var pt : float3&) : bool
if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(28.0, 64.0, 28.0))
return true
return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(165.0, 130.0, 165.0))
[never_inline]
def private wto_ensure_wing_relay(world : WtoWorldSnap const&; myPos, dest : float3; var slot : WtoBotSlot&)
assume rt = slot.route
if !rt.wingInit
rt.wingInit = true
let h = uint(slot.eid)
rt.wingSign = int(h % 5u) - 2
rt.laneOffsetM = float(int((h / 5u) % 5u) - 2) * 4.5
let capIdx = slot.macro.capIndex
if rt.wingCapIdx == capIdx
return
rt.wingCapIdx = capIdx
rt.wingRelayValid = false
let dist = sqrt(wto_xz_dist_sq(myPos, dest))
if rt.wingSign == 0 || dist < 140.0
return
let toGoal = wto_xz_normalize(dest - myPos, float3(1.0, 0.0, 0.0))
let lat = float3(-toGoal.z, 0.0, toGoal.x)
let anchor = lerp(myPos, dest, 0.58)
let swing = clamp(dist * 0.30, 55.0, 240.0) * (abs(rt.wingSign) == 2 ? 1.0 : 0.55)
let side = swing * (rt.wingSign > 0 ? 1.0 : -1.0)
var relay = wto_clamp_battle_xz(anchor + lat * side, world.battleCenter, world.battleRadius, 40.0)
if wto_terrain_point_valid(slot.army, relay) && !wto_terrain_has_cliff_ahead(relay, toGoal, 16.0)
rt.wingRelayPos = relay
rt.wingRelayValid = true
[never_inline]
def private wto_replan_corridor(now : float; myPos, goal : float3; var rt : WtoRouteState&)
rt.nextReplanAt = now + 2.8
rt.corridorGoal = goal
rt.corridorLen = 0
rt.corridorIdx = 0
let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1)
if navIdx < 0
rt.lastStartOk = false
rt.lastGoalOk = false
return
var sPt = myPos
var gPt = goal
rt.lastStartOk = wto_project_nav_wide(navIdx, sPt)
rt.lastGoalOk = wto_project_nav_wide(navIdx, gPt)
if !rt.lastStartOk || !rt.lastGoalOk
return
let maxKeep = WTO_MAX_PATH_PTS - 1
find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array<float3>#)
let total = length(path)
if total <= 0
return
let stride = max(1, (total + maxKeep - 1) / maxKeep)
var idx = 0
while idx < total && rt.corridorLen < maxKeep
rt.corridor[rt.corridorLen] = path[idx]
rt.corridorLen++
idx += stride
if rt.corridorLen < maxKeep && wto_xz_dist_sq(rt.corridor[rt.corridorLen - 1], path[total - 1]) > 9.0
rt.corridor[rt.corridorLen] = path[total - 1]
rt.corridorLen++
// Append exact final destination when the goal sits off-road (e.g. hilltop capture zone).
if rt.corridorLen > 0 && rt.corridorLen < WTO_MAX_PATH_PTS && wto_xz_dist_sq(rt.corridor[rt.corridorLen - 1], goal) > 64.0
rt.corridor[rt.corridorLen] = goal
rt.corridorLen++
// Validate a crest-safe cross-country shortcut (<= 145m) with zero cliff drop-offs or jams.
[never_inline]
def private wto_try_shortcut(world : WtoWorldSnap const&; now : float; myPos, target : float3;
var slot : WtoBotSlot&)
assume rt = slot.route
rt.shortcutValid = false
rt.nextShortcutAt = now + 1.1
let dist = sqrt(wto_xz_dist_sq(myPos, target))
if dist < 22.0 || dist > 145.0
return
let dir = wto_xz_normalize(target - myPos, float3(1.0, 0.0, 0.0))
if wto_terrain_has_cliff_ahead(myPos, dir, min(dist, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M + 8.0))
return
let steps = clamp(int(dist / 7.5), 2, 20)
var prev = myPos
for s in range(1, steps + 1)
let d = (dist * float(s)) / float(steps)
let tx = myPos.x + dir.x * d
let tz = myPos.z + dir.z * d
var gy = prev.y
if !wto_terrain_drivable_y(prev, tx, tz, gy)
return
let samplePt = float3(tx, gy, tz)
if wto_world_jam_penalty(world, samplePt, now) > 4.0 || wto_crowd_point_penalty(world, slot.army, slot.eid, samplePt) > 18.0
return
if wto_terrain_hard_ray(prev + float3(0.0, 1.3, 0.0), dir, 8.0) < 7.5
return
prev = samplePt
rt.shortcutPos = target
rt.shortcutValid = true
// Generate a lateral bypass waypoint around an obstacle/jam, even when no NavMesh corridor exists.
[never_inline]
def public wto_route_request_detour(world : WtoWorldSnap const&; now : float;
myPos, blockedDir : float3; var slot : WtoBotSlot&)
assume rt = slot.route
let fwd = wto_xz_normalize(blockedDir, float3(1.0, 0.0, 0.0))
let lat = float3(-fwd.z, 0.0, fwd.x)
let pref = ((uint(slot.eid) + uint(rt.detourCount)) & 1u) == 0u ? 1.0 : -1.0
var bestScore = -1.0e9
var found = false
var bestPt = myPos
for k in range(4)
let side = (k % 2 == 0 ? pref : -pref) * (k < 2 ? 38.0 : 56.0)
let fwdStep = k < 2 ? 22.0 : 12.0
var cand = wto_clamp_battle_xz(myPos + fwd * fwdStep + lat * side, world.battleCenter, world.battleRadius, 35.0)
if !wto_terrain_point_valid(slot.army, cand)
continue
let candDir = wto_xz_normalize(cand - myPos, lat)
if wto_terrain_has_cliff_ahead(myPos, candDir, 18.0)
continue
if wto_terrain_hard_ray(myPos + float3(0.0, 1.3, 0.0), candDir, 16.0) < 10.0
continue
let score = -wto_world_jam_penalty(world, cand, now) - wto_crowd_point_penalty(world, slot.army, slot.eid, cand)
if score > bestScore
bestScore = score
bestPt = cand
found = true
if found
rt.detourPos = bestPt
rt.detourValid = true
rt.detourUntil = now + 11.0
rt.detourCount++
[never_inline]
def public wto_route_select_waypoint(world : WtoWorldSnap const&; now : float;
myPos, finalGoal : float3; var slot : WtoBotSlot&) : float3
assume rt = slot.route
if rt.detourValid
if now < rt.detourUntil && wto_xz_dist_sq(myPos, rt.detourPos) > 100.0
return rt.detourPos
rt.detourValid = false
let useWing = slot.tactics.posture == WTO_POSTURE_MARCH
if useWing
wto_ensure_wing_relay(world, myPos, finalGoal, slot)
if useWing && rt.wingRelayValid && wto_xz_dist_sq(myPos, rt.wingRelayPos) <= 625.0
rt.wingRelayValid = false
let activeGoal = (useWing && rt.wingRelayValid) ? rt.wingRelayPos : finalGoal
if now >= rt.nextShortcutAt
wto_try_shortcut(world, now, myPos, activeGoal, slot)
if rt.shortcutValid && wto_xz_dist_sq(rt.shortcutPos, activeGoal) <= 144.0
return activeGoal
if now >= rt.nextReplanAt || wto_xz_dist_sq(rt.corridorGoal, activeGoal) > 400.0
wto_replan_corridor(now, myPos, activeGoal, rt)
while rt.corridorIdx < rt.corridorLen - 1 && wto_xz_dist_sq(myPos, rt.corridor[rt.corridorIdx]) <= 256.0
rt.corridorIdx++
if rt.corridorLen > 0 && rt.corridorIdx < rt.corridorLen
let wp = rt.corridor[rt.corridorIdx]
let toWp = wto_xz_normalize(wp - myPos, float3(1.0, 0.0, 0.0))
let lat = float3(-toWp.z, 0.0, toWp.x)
return wp + lat * clamp(rt.laneOffsetM, -6.0, 6.0)
return activeGoal
+251
View File
@@ -0,0 +1,251 @@
// Thin ECS orchestrator for WTOffline's modular ground AI system.
// Frame pipeline: world snapshot -> crowd density -> macro objectives -> tactics & perception ->
// corridor & bidirectional local nav -> chassis drive actuator -> deterministic fire control.
options indenting = 2
options no_global_variables = false
options no_global_heap = true
options stack = 65536
require ecs
require app
require math
require DagorMath
require dm
require WTDamageModel
require Unit
require IGroundModel
require HeavyVehicleModel
require vehicle
require pathfinder
require %appGame.wt_events
require %game.events
require %game.unit.unit_events
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_specs_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_crowd_common
require %appGame.wtoai.wto_ai_macro_common
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
var private @safe_when_uninitialized g_world : WtoWorldSnap
var private @safe_when_uninitialized g_crowd : WtoCrowdSummary
var private @safe_when_uninitialized g_bots : WtoBotSlot[64]
var private g_last_world_frame : float = -1.0
var private g_next_macro_at : float = 0.0
var private g_next_diag_at : float = 0.0
def private wto_any_layer_active() : bool
return WTO_AI_ENABLED && (WTO_AI_LAYER_MACRO || WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_NAVIGATION || WTO_AI_LAYER_FIRE_CONTROL)
[never_inline]
def private wto_reset_runtime()
wto_world_reset(g_world)
g_crowd = WtoCrowdSummary()
g_last_world_frame = -1.0
g_next_macro_at = 0.0
g_next_diag_at = 0.0
for i in range(WTO_MAX_BOTS)
g_bots[i] = WtoBotSlot()
[never_inline]
def private wto_find_slot(eid : EntityId) : int
let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS)
for i in range(cap)
if g_bots[i].used && g_bots[i].eid == eid
return i
return -1
[never_inline]
def private wto_acquire_slot(eid : EntityId; army : int; now : float) : int
let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS)
var freeIdx = -1
for i in range(cap)
if g_bots[i].used && g_bots[i].eid == eid
g_bots[i].army = army
g_bots[i].lastSeenAt = now
return i
if !g_bots[i].used && freeIdx < 0
freeIdx = i
if freeIdx >= 0
g_bots[freeIdx] = WtoBotSlot()
g_bots[freeIdx].used = true
g_bots[freeIdx].eid = eid
g_bots[freeIdx].army = army
g_bots[freeIdx].lastSeenAt = now
g_bots[freeIdx].nextTacticsAt = now + float(freeIdx % 8) * (WTO_AI_TACTICS_TICK_SEC / 8.0)
g_bots[freeIdx].nextNavAt = now + float(freeIdx % 10) * (WTO_AI_NAV_TICK_SEC / 10.0)
g_bots[freeIdx].route.nextReplanAt = now + float(freeIdx % 12) * 0.2
return freeIdx
[never_inline]
def private wto_phys_slot_available() : bool
if WTO_AI_NAV_MAX_PHYS_BOTS <= 0
return false
var count = 0
for i in range(WTO_MAX_BOTS)
if g_bots[i].used && g_bots[i].drive.routeBOwned && !g_bots[i].drive.routeAFallback
count++
if count >= WTO_AI_NAV_MAX_PHYS_BOTS
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.spec.muzzleSpeedMps}|pos={b.tactics.posture}|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.posture == WTO_POSTURE_ENGAGE_HALT ? 1 : 0
dispNow += b.tactics.posture == WTO_POSTURE_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()
[es(tag=server, on_event=(EventOnUnitDead, EventUnitBecameDead))]
def wto_ai_unit_dead_es(evt : Event; eid : EntityId; unit__ref : UnitRef)
let u = unit__ref.unit
if u != null && as_gm(u) != null && (int(u.army) == 1 || int(u.army) == 2)
wto_world_record_death(g_world, int(u.army), u.pos, float(get_app().usefulTotalTime))
let idx = wto_find_slot(eid)
if idx >= 0
g_bots[idx] = WtoBotSlot()
[es(tag=server, on_disappear, on_event=EventUnitRespawn)]
def wto_ai_unit_cleanup_es(evt : Event; eid : EntityId)
let idx = wto_find_slot(eid)
if idx >= 0
g_bots[idx] = WtoBotSlot()
[es(tag=server)]
def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId)
if !wto_any_layer_active() || !WTO_AI_LAYER_TACTICS
return
let idx = wto_find_slot(eid)
let offEid = evt.offender.eid
if idx < 0 || !offEid || offEid == eid
return
let offUnitIdx = wto_world_find_unit(g_world, offEid)
if offUnitIdx >= 0 && g_world.units[offUnitIdx].army == g_bots[idx].army
return
g_bots[idx].perceive.lastDamagedAt = float(get_app().usefulTotalTime)
g_bots[idx].perceive.lastOffenderEid = offEid
[es(tag=server, before=wto_ai_pipeline_es)]
def wto_ai_world_tick_es(act : UpdateStageInfoAct)
if !wto_any_layer_active() || !is_app_in_flight()
return
if abs(act.curTime - g_last_world_frame) <= 1.0e-4
return
g_last_world_frame = act.curTime
let now = float(get_app().usefulTotalTime)
if g_world.valid && now < g_world.time - 1.0
wto_reset_runtime()
for i in range(WTO_MAX_BOTS)
if g_bots[i].used && (now - g_bots[i].lastSeenAt) > 3.5
g_bots[i] = WtoBotSlot()
wto_world_refresh(now, g_world)
wto_crowd_update_all(g_world, g_bots, g_crowd)
if WTO_AI_LAYER_MACRO && now >= g_next_macro_at
g_next_macro_at = now + WTO_AI_MACRO_TICK_SEC
wto_macro_update_all(g_world, now, 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)
[es(tag=server, no_order)]
def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&;
unit__missionName : string; unit__className : string = "")
if !wto_any_layer_active() || !g_world.valid
return
var unit = unit__ref.unit
if unit == null || !unit.isAlive || unit.isDelayed || unit.isHumanPlayer
return
let army = int(unit.army)
let gm = as_gm(unit)
if (army != 1 && army != 2) || gm == null || gm.moveSys == null || as_hv(unit) == null
return
let now = float(get_app().usefulTotalTime)
let idx = wto_acquire_slot(eid, army, now)
if idx < 0
return
assume slot = g_bots[idx]
if !slot.prepared
slot.prepared = true
wto_specs_load(eid, unit__className, unit, gm, slot.spec)
if WTO_AI_LAYER_NAVIGATION
wto_drive_prepare_unit(unit__missionName)
if now >= slot.nextTacticsAt
slot.nextTacticsAt = now + WTO_AI_TACTICS_TICK_SEC
wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, 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)
let usingPhys = WTO_AI_NAV_DRIVE_MODE == "vehicle_phys" && slot.drive.routeBOwned && !slot.drive.routeAFallback
if !usingPhys
wto_drive_apply_movesys(unit, slot.driveCmd)
wto_fire_update(g_world, unit, now, act.dt, slot)
[es(tag=server, after=wto_ai_pipeline_es)]
def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&;
unit__missionName : string; var vehicle_net_phys : VehiclePhysActor&)
if !wto_any_layer_active() || !WTO_AI_LAYER_NAVIGATION || WTO_AI_NAV_DRIVE_MODE != "vehicle_phys"
return
var unit = unit__ref.unit
if unit == null || !unit.isAlive || unit.isDelayed || unit.isHumanPlayer || vehicle_net_phys.physEdit == null
return
let idx = wto_find_slot(eid)
if idx < 0 || g_bots[idx].drive.routeAFallback
return
if !g_bots[idx].drive.routeBOwned && !wto_phys_slot_available()
return
let now = float(get_app().usefulTotalTime)
wto_drive_step_phys(unit, unit__missionName, as_gm(unit), vehicle_net_phys, act.dt, now, g_bots[idx])
+170
View File
@@ -0,0 +1,170 @@
// Authoritative per-vehicle specification loader: reads unit & weapon DataBlocks once per
// spawned bot (`gamedata/units/<className>.blk`) to extract exact role, gun stabilizer,
// traverse limits, turret slew rates, shell muzzle velocity, and reverse speed capability.
options indenting = 2
options no_global_heap = true
module wto_ai_specs_common shared
require ecs
require app
require math
require strings
require DagorMath
require DagorDataBlock
require Unit
require IGroundModel
require HeavyVehicleModel
require Weapon
require %game.utils.utils_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_types_common
[never_inline]
def private wto_parse_role_strings(unitType : string; expClass : string; isLightTag : bool) : int
if unitType == "typeSPAA" || expClass == "exp_SPAA"
return WTO_ROLE_SPAA
if unitType == "typeTankDestroyer" || expClass == "exp_tank_destroyer"
return WTO_ROLE_TD
if unitType == "typeHeavyTank" || expClass == "exp_heavy_tank"
return WTO_ROLE_HEAVY
if unitType == "typeLightTank" || isLightTag
return WTO_ROLE_LIGHT
return WTO_ROLE_MEDIUM
[never_inline]
def private wto_parse_turret_limits(turretBlk : DataBlock const?; var spec : WtoVehicleSpec&)
if turretBlk == null
return
let lim1 = *turretBlk |> datablock_getPoint4("lim1", float4(0.0, 0.0, 0.0, 0.0))
let lim2 = *turretBlk |> datablock_getPoint4("lim2", float4(0.0, 0.0, 0.0, 0.0))
var maxAbsYaw = 0.0
var minPitch = 0.0
var maxPitch = 0.0
if abs(lim1.x) > 0.1 || abs(lim1.y) > 0.1
maxAbsYaw = max(maxAbsYaw, max(abs(lim1.x), abs(lim1.y)))
minPitch = min(minPitch, lim1.z)
maxPitch = max(maxPitch, lim1.w)
if abs(lim2.x) > 0.1 || abs(lim2.y) > 0.1
maxAbsYaw = max(maxAbsYaw, max(abs(lim2.x), abs(lim2.y)))
minPitch = min(minPitch, lim2.z)
maxPitch = max(maxPitch, lim2.w)
let limitsBlk = *turretBlk |> datablock_get_block_by_name("limits")
if limitsBlk != null
let yawRange = *limitsBlk |> datablock_getPoint2("yaw", float2(-180.0, 180.0))
let pitchRange = *limitsBlk |> datablock_getPoint2("pitch", float2(-8.0, 22.0))
maxAbsYaw = max(maxAbsYaw, max(abs(yawRange.x), abs(yawRange.y)))
minPitch = min(minPitch, pitchRange.x)
maxPitch = max(maxPitch, pitchRange.y)
if maxAbsYaw > 0.5
spec.yawLimitDeg = clamp(maxAbsYaw, 4.0, 180.0)
spec.isLimitedTraverse = spec.yawLimitDeg < 75.0
if minPitch < -0.5
spec.minPitchDeg = clamp(minPitch, -25.0, -2.0)
if maxPitch > 1.0
spec.maxPitchDeg = clamp(maxPitch, 8.0, 88.0)
[never_inline]
def private wto_parse_weapon_blk(weapBlkPath : string; var spec : WtoVehicleSpec&)
if empty(weapBlkPath) || find(weapBlkPath, "dummy_weapon") >= 0
return
datablock_load_cached(weapBlkPath, DataBlockReadFlag.ROBUST) <| $(wBlk)
let isRocket = wBlk |> datablock_getBool("rocketGun", false)
let isCannon = wBlk |> datablock_getBool("cannon", false)
let isBelt = wBlk |> datablock_getBool("isBulletBelt", false)
if isRocket && !isCannon
return
spec.isAutocannonBelt = isBelt
var bestSpd = 0.0
var bestCx = spec.shellDragCx
datablock_for_each_block(wBlk, "bullet") <| $(bBlk)
let spd = bBlk |> datablock_getReal("speed", 0.0)
let cx = bBlk |> datablock_getReal("Cx", 0.35)
if spd > bestSpd && spd < 2400.0
bestSpd = spd
bestCx = clamp(cx, 0.05, 1.5)
if bestSpd > 80.0
spec.muzzleSpeedMps = bestSpd
spec.shellDragCx = bestCx
[never_inline]
def private wto_parse_unit_blk(className : string; isLightTag : bool; var spec : WtoVehicleSpec&) : bool
if empty(className)
return false
let relPath = find(className, "/") >= 0 ? ("gamedata/units/" + className + ".blk") : ("gamedata/units/tankModels/" + className + ".blk")
var loaded = false
datablock_load_cached(relPath, DataBlockReadFlag.ROBUST) <| $(mBlk)
if mBlk.paramCount == 0u && mBlk.blockCount == 0u
return
loaded = true
let uType = mBlk |> datablock_getStr("type", "")
let expCls = mBlk |> datablock_getStr("expClass", "")
spec.role = wto_parse_role_strings(uType, expCls, isLightTag)
let fwdKmh = mBlk |> datablock_getReal("maxFwdSpeed", 0.0)
let revKmh = mBlk |> datablock_getReal("maxRevSpeed", 0.0)
if fwdKmh > 5.0
spec.vMaxFwd = clamp(fwdKmh / 3.6, 4.0, 28.0)
if revKmh > 1.0
spec.vMaxRev = clamp(revKmh / 3.6, 1.0, 16.0)
let commonBlk = mBlk |> datablock_get_block_by_name("commonWeapons")
if commonBlk == null
return
var primaryParsed = false
datablock_for_each_block(*commonBlk, "Weapon") <| $(weapBlk)
if primaryParsed
return
let trig = weapBlk |> datablock_getStr("triggerGroup", "primary")
let wPath = weapBlk |> datablock_getStr("blk", "")
if trig != "primary" || empty(wPath) || find(wPath, "dummy_weapon") >= 0 || find(wPath, "machinegun") >= 0
return
primaryParsed = true
let sy = weapBlk |> datablock_getReal("speedYaw", 24.0)
let sp = weapBlk |> datablock_getReal("speedPitch", 8.0)
spec.turretYawSpd = clamp(sy, 4.0, 120.0)
spec.turretPitchSpd = clamp(sp, 2.0, 90.0)
let stabBlk = weapBlk |> datablock_get_block_by_name("gunStabilizer")
if stabBlk != null
spec.hasVertStab = *stabBlk |> datablock_getBool("hasVertical", false)
wto_parse_turret_limits(weapBlk |> datablock_get_block_by_name("turret"), spec)
wto_parse_weapon_blk(wPath, spec)
return loaded
[never_inline]
def private wto_apply_runtime_fallbacks(unit : Unit const?; gm : IGroundModel const?;
isLightTag : bool; blkLoaded : bool; var spec : WtoVehicleSpec&)
if gm != null
let box = gm.bodyBoundingBox
spec.halfLen = max(2.0, max(abs(box.boxMin.x), abs(box.boxMax.x)) + 0.15)
spec.halfWid = max(1.0, max(abs(box.boxMin.z), abs(box.boxMax.z)) + 0.18)
let hv = unit != null ? as_hv(unit) : null
if hv != null && hv.getMaxSpeed > 1.5 && wto_is_finite(hv.getMaxSpeed)
spec.vMaxFwd = min(spec.vMaxFwd, hv.getMaxSpeed)
if unit == null || unit.weap == null
return
var gunCount = 0
var launcherCount = 0
foreach_primary_gun(unit.weap.Weapons) <| $(weapon)
if weapon == null || weapon.isDummyGun
return
if weapon.prop.launcher
launcherCount++
elif as_gun(weapon) != null
gunCount++
spec.isPureLauncher = gunCount == 0 && launcherCount > 0
if length(unit.weap.turret) == 0 && gunCount > 0
spec.isLimitedTraverse = true
spec.yawLimitDeg = min(spec.yawLimitDeg, 12.0)
if !blkLoaded
if spec.isLimitedTraverse
spec.role = WTO_ROLE_TD
elif isLightTag
spec.role = WTO_ROLE_LIGHT
elif spec.vMaxFwd <= 10.5 && spec.halfLen >= 3.3
spec.role = WTO_ROLE_HEAVY
[never_inline]
def public wto_specs_load(eid : EntityId; className : string; unit : Unit const?;
gm : IGroundModel const?; var spec : WtoVehicleSpec&)
let isLightTag = has(eid, "unit_tag__light_vehicle")
let blkLoaded = wto_parse_unit_blk(className, isLightTag, spec)
wto_apply_runtime_fallbacks(unit, gm, isLightTag, blkLoaded, spec)
spec.ready = true
+204
View File
@@ -0,0 +1,204 @@
// Tactical posture arbitrator: arbitrates survival retreat, SPAA priority, high-ground cliff
// ridge dwell/reverse discipline, anti-clustering dispersion, and stabilizer-aware combat halts.
options indenting = 2
options no_global_heap = true
module wto_ai_tactics_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_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_crowd_common
require %appGame.wtoai.wto_ai_perceive_common
[never_inline]
def private wto_friendly_retreat_dir(world : WtoWorldSnap const&; army : int;
myPos, threatDir : float3) : float3
if world.teamSpawnValid[army]
let toSpawn = world.teamSpawnCenter[army] - myPos
if wto_xz_len(toSpawn) > 25.0
return wto_xz_normalize(toSpawn, -threatDir)
return -wto_xz_normalize(threatDir, float3(1.0, 0.0, 0.0))
[never_inline]
def private wto_latch_reverse_withdraw(world : WtoWorldSnap const&; now : float; myPos, backDir : float3;
lateralShift : float; var slot : WtoBotSlot&)
let bDir = wto_xz_normalize(backDir, float3(-1.0, 0.0, 0.0))
let lat = float3(-bDir.z, 0.0, bDir.x)
let side = ((uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0) * lateralShift
let revDist = WTO_AI_NAV_TAC_REV_DIST_M
var anchor = myPos + bDir * revDist + lat * side
anchor = wto_clamp_battle_xz(anchor, world.battleCenter, world.battleRadius, 35.0)
if !wto_terrain_point_valid(slot.army, anchor)
anchor = myPos + bDir * max(16.0, revDist * 0.6)
slot.tactics.withdrawAnchor = anchor
slot.tactics.withdrawUntil = now + WTO_AI_NAV_TAC_REV_MAX_SEC
slot.tactics.posture = WTO_POSTURE_REVERSE_WITHDRAW
slot.tactics.moveGoal = anchor
slot.tactics.desiredSpeedMps = slot.spec.vMaxRev
slot.nav.ridgeWithdrawEvents++
[never_inline]
def private wto_handle_ridge_discipline(world : WtoWorldSnap const&; now : float;
myPos, threatDir : float3; var slot : WtoBotSlot&) : bool
assume tac = slot.tactics
let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir)
if now < tac.withdrawUntil
if wto_xz_dist_sq(myPos, tac.withdrawAnchor) > 36.0
tac.posture = WTO_POSTURE_REVERSE_WITHDRAW
tac.moveGoal = tac.withdrawAnchor
tac.desiredSpeedMps = slot.spec.vMaxRev
return true
tac.withdrawUntil = -100.0
let onRidge = wto_terrain_is_exposed_ridge(myPos, threatDir, backDir)
if !onRidge
tac.onExposedRidge = false
return false
if !tac.onExposedRidge
tac.onExposedRidge = true
tac.ridgeEnterAt = now
tac.ridgeShotsStart = slot.fire.shotCount
let shotsOnRidge = slot.fire.shotCount - tac.ridgeShotsStart
let dwellSec = now - tac.ridgeEnterAt
let mustLeave = (shotsOnRidge >= WTO_AI_TERRAIN_RIDGE_MAX_SHOTS ||
dwellSec >= WTO_AI_TERRAIN_RIDGE_MAX_DWELL_SEC || slot.fire.pitchBlocked)
if mustLeave && slot.spec.vMaxRev >= 1.6
tac.onExposedRidge = false
wto_latch_reverse_withdraw(world, now, myPos, backDir, 16.0, slot)
return true
// Brief ridge snipe window: hold before the cliff edge; never advance toward the drop-off!
tac.posture = WTO_POSTURE_ENGAGE_HALT
tac.moveGoal = myPos
tac.desiredSpeedMps = 0.0
return true
[never_inline]
def private wto_handle_crippled_or_spaa(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, threatDir : float3;
isBurn : bool; var slot : WtoBotSlot&) : bool
assume tac = slot.tactics
assume p = slot.perceive
tac.spaaYieldAir = slot.spec.role == WTO_ROLE_SPAA && p.hasClearLos && p.targetIsAir
if tac.spaaYieldAir
tac.posture = WTO_POSTURE_ENGAGE_HALT
tac.moveGoal = myPos
tac.desiredSpeedMps = 0.0
return true
let crippled = isBurn || slot.fire.gunDamaged
let spaaThreatened = (slot.spec.role == WTO_ROLE_SPAA && p.hasClearLos && !p.targetIsAir &&
wto_xz_dist_sq(myPos, p.knownPos) < wto_sq(380.0))
if !crippled && !spaaThreatened
return false
let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir)
let enemyInFront = p.hasClearLos && dot(threatDir, hullFwd) > -0.2
if enemyInFront && slot.spec.vMaxRev >= 2.0
if now >= tac.withdrawUntil
wto_latch_reverse_withdraw(world, now, myPos, backDir, 12.0, slot)
else
tac.posture = WTO_POSTURE_REVERSE_WITHDRAW
tac.moveGoal = tac.withdrawAnchor
tac.desiredSpeedMps = slot.spec.vMaxRev
return true
var retGoal = wto_clamp_battle_xz(myPos + backDir * 85.0, world.battleCenter, world.battleRadius, 40.0)
let _valid = wto_terrain_point_valid(slot.army, retGoal)
tac.posture = WTO_POSTURE_RETREAT
tac.moveGoal = retGoal
tac.desiredSpeedMps = slot.spec.vMaxFwd
return true
[never_inline]
def private wto_handle_dispersion(world : WtoWorldSnap const&; now : float;
myPos, threatDir : float3; var slot : WtoBotSlot&;
var crowdSummary : WtoCrowdSummary&) : bool
assume tac = slot.tactics
if slot.fire.settleHoldSec > 0.08 && slot.perceive.hasClearLos
return false
if now < tac.disperseUntil && wto_xz_dist_sq(myPos, tac.disperseGoal) > 25.0
tac.posture = WTO_POSTURE_DISPERSE
tac.moveGoal = tac.disperseGoal
tac.desiredSpeedMps = slot.spec.vMaxFwd * 0.82
return true
if !slot.crowd.isCrowded
return false
tac.disperseGoal = wto_crowd_pick_disperse_pos(world, slot.army, slot.eid, myPos, threatDir, slot.crowd)
tac.disperseUntil = now + WTO_AI_CROWD_DISPERSE_HOLD_SEC
tac.posture = WTO_POSTURE_DISPERSE
tac.moveGoal = tac.disperseGoal
tac.desiredSpeedMps = slot.spec.vMaxFwd * 0.85
crowdSummary.disperseEvents++
return true
[never_inline]
def private wto_handle_combat_or_march(world : WtoWorldSnap const&; now : float;
myPos, threatDir : float3; var slot : WtoBotSlot&)
assume tac = slot.tactics
assume p = slot.perceive
let baseGoal = slot.macro.valid ? slot.macro.goalPos : world.battleCenter
if p.hasClearLos && !!p.targetEid && !p.targetIsAir
let dist = sqrt(wto_xz_dist_sq(myPos, p.knownPos))
// Shoot-and-scoot: back into cover during reload when medium-close and reverse gear is capable.
if slot.fire.reloading && dist < 520.0 && slot.spec.vMaxRev >= 2.2 && slot.nav.rearClearM > 8.0
if now >= tac.peekUntil && now >= tac.peekCooldownUntil
let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir)
tac.peekHomePos = myPos + backDir * 15.0
tac.peekUntil = now + 3.6
tac.peekCooldownUntil = now + WTO_AI_TACTICS_PEEK_COOLDOWN_SEC + 3.6
if now < tac.peekUntil
tac.posture = WTO_POSTURE_PEEK_BACK
tac.moveGoal = tac.peekHomePos
tac.desiredSpeedMps = slot.spec.vMaxRev
return
// Gun ready (or nearly ready): halt unstabilized chassis or long-range sniper shots cleanly!
if !slot.fire.reloading && dist <= WTO_AI_FC_MAX_RANGE_M
if !slot.spec.hasVertStab || dist > 420.0 || slot.spec.isLimitedTraverse
tac.posture = WTO_POSTURE_ENGAGE_HALT
tac.moveGoal = myPos
tac.desiredSpeedMps = 0.0
return
// Two-plane stabilized tank at medium/close range: smooth low-speed tactical creep/flank!
let lat = float3(-threatDir.z, 0.0, threatDir.x)
let flankSign = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0
let engageGoal = dist > 165.0 ? (myPos + threatDir * 35.0 + lat * (flankSign * 22.0)) : (myPos + lat * (flankSign * 30.0))
tac.posture = WTO_POSTURE_MARCH
tac.moveGoal = wto_clamp_battle_xz(engageGoal, world.battleCenter, world.battleRadius, 35.0)
tac.desiredSpeedMps = WTO_AI_FC_STAB_CREEP_MPS
return
var marchGoal = baseGoal
if !p.hasClearLos && wto_xz_dist_sq(myPos, baseGoal) > 6400.0
var huntPos = baseGoal
if slot.spec.role != WTO_ROLE_SPAA && wto_perceive_pick_hunt_pos(world, slot.army, slot.eid, myPos, now, huntPos)
marchGoal = huntPos
tac.posture = WTO_POSTURE_MARCH
tac.moveGoal = marchGoal
let distGoal = sqrt(wto_xz_dist_sq(myPos, marchGoal))
if distGoal <= 8.0
tac.posture = WTO_POSTURE_ENGAGE_HALT
tac.desiredSpeedMps = 0.0
else
let capScale = slot.macro.cautious ? 0.72 : 0.96
tac.desiredSpeedMps = distGoal < 24.0 ? min(slot.spec.vMaxFwd * 0.55, 6.0) : (slot.spec.vMaxFwd * capScale)
[never_inline]
def public wto_tactics_update(var world : WtoWorldSnap&; now, dt : float;
myPos, hullFwd : float3; isBurn : bool;
var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&)
if !WTO_AI_LAYER_TACTICS
slot.tactics.posture = WTO_POSTURE_MARCH
slot.tactics.moveGoal = slot.macro.valid ? slot.macro.goalPos : myPos
slot.tactics.desiredSpeedMps = slot.spec.vMaxFwd * 0.9
return
wto_perceive_update(world, now, dt, myPos, hullFwd, slot)
let fallbackGoal = slot.macro.valid ? slot.macro.goalPos : world.battleCenter
let threatRef = !!slot.perceive.targetEid ? slot.perceive.knownPos : fallbackGoal
let threatDir = wto_xz_normalize(threatRef - myPos, wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)))
if wto_handle_crippled_or_spaa(world, now, myPos, hullFwd, threatDir, isBurn, slot)
return
if wto_handle_ridge_discipline(world, now, myPos, threatDir, slot)
return
if wto_handle_dispersion(world, now, myPos, threatDir, slot, crowdSummary)
return
wto_handle_combat_or_march(world, now, myPos, threatDir, slot)
+261
View File
@@ -0,0 +1,261 @@
// 3D terrain, foliage-filtered obstacle raycasting, cliff drop-off lookahead, exposed high-ground
// ridge detection, and smoke/foliage-filtered line-of-sight checks.
options indenting = 2
options no_global_heap = true
module wto_ai_terrain_common shared
require ecs
require math
require strings
require DagorMath
require Mission
require Dacoll
require RendInst
require PhysMat
require SmokeOccluder
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_types_common
let private TERRAIN_STATIC_MASK = ETF_STRUCTURES | ETF_FRT
let private TERRAIN_GROUND_MASK = ETF_LMESH | ETF_HEIGHTMAP | ETF_STRUCTURES | ETF_FRT
let private TERRAIN_LOS_MASK = ETF_LMESH | ETF_HEIGHTMAP | ETF_STRUCTURES | ETF_FRT
[never_inline]
def private wto_ri_is_soft_foliage(name : string) : bool
if empty(name)
return false
if (find(name, "house") >= 0 || find(name, "building") >= 0 || find(name, "bridge") >= 0 ||
find(name, "wall") >= 0 || find(name, "bunker") >= 0 || find(name, "rock") >= 0 ||
find(name, "cliff") >= 0 || find(name, "stone") >= 0 || find(name, "concrete") >= 0 ||
find(name, "brick") >= 0 || find(name, "container") >= 0 || find(name, "wagon") >= 0 ||
find(name, "train") >= 0 || find(name, "pillar") >= 0 || find(name, "barricade") >= 0)
return false
return (starts_with(name, "tree_") || find(name, "_tree_") >= 0 || starts_with(name, "bush_") ||
find(name, "_bush_") >= 0 || starts_with(name, "shrub_") || find(name, "_shrub_") >= 0 ||
starts_with(name, "hedge_") || find(name, "_hedge_") >= 0 || starts_with(name, "genus_") ||
find(name, "_pine_") >= 0 || find(name, "_oak_") >= 0 || find(name, "_birch_") >= 0 ||
find(name, "_spruce_") >= 0 || find(name, "_palm_") >= 0 || find(name, "_reed_") >= 0 ||
find(name, "lamp") >= 0 || find(name, "fence_wood") >= 0 || find(name, "wooden_fence") >= 0 ||
find(name, "sign_") >= 0 || find(name, "bench") >= 0 || find(name, "hay") >= 0)
[never_inline]
def public wto_terrain_ri_is_hard(desc : RendInstDesc const&; acceptInvalid : bool = false) : bool
if desc.isValid && desc.isRiExtra && desc.riExtraHandle != RIEX_HANDLE_NULL
let handle = desc.riExtraHandle
let poolId = uint(handle_to_ri_type(handle))
if rendinst_isRIExtraGenPosInst(poolId)
return false
let initHp = riex_getInitialHP(handle)
let isWall = riex_isWalls(poolId)
let immortal = riex_isImmortal(poolId)
if !isWall && wto_ri_is_soft_foliage(riex_getRIGenExtraName(poolId))
return false
if immortal || riex_isInvincible(handle) || isWall || initHp >= 250.0
return true
let bsphRad = riex_getBsphRad(poolId)
return bsphRad >= 1.65 && initHp >= 65.0
if !desc.isValid
return acceptInvalid
if rendinst_isRIGenPosInst(desc) || wto_ri_is_soft_foliage(getRIGenResName(desc))
return false
if !rendinst_isRIGenDestr(desc)
return true
let box = getRIGenBBox(desc)
let ext = box.boxMax - box.boxMin
return max(ext.x, ext.z) >= 2.2 && ext.y >= 1.4
[never_inline]
def public wto_terrain_hard_ray(startPos, dir : float3; maxRange : float) : float
if maxRange <= 0.0
return 0.0
var structDist = maxRange
var sTraveled = 0.0
for _hop in range(0, 4)
var hitD = maxRange - sTraveled
if hitD <= 0.0
break
var mat = PHYSMAT_INVALID
var norm = float3(0.0)
var desc = RendInstDesc()
let origin = startPos + dir * sTraveled
if !traceray_normalized(origin, dir, hitD, mat, norm, TERRAIN_STATIC_MASK, desc, PHYSMAT_INVALID)
break
if norm.y < 0.72
structDist = clamp(sTraveled + hitD, 0.0, maxRange)
break
sTraveled += max(0.0, hitD) + 0.5
var traveled = 0.0
for _hop in range(0, 4)
var hitDist = structDist - traveled
if hitDist <= 0.0
break
var mat = PHYSMAT_INVALID
var norm = float3(0.0)
var desc = RendInstDesc()
let origin = startPos + dir * traveled
if !traceray_normalized(origin, dir, hitDist, mat, norm, ETF_RI | ETF_RI_PHYS, desc, PHYSMAT_INVALID)
break
if norm.y < 0.72 && wto_terrain_ri_is_hard(desc, true)
return clamp(traveled + hitDist, 0.0, structDist)
traveled += max(0.0, hitDist) + 0.35
return structDist
[never_inline]
def private wto_trace_bridge_deck(refY, testX, testZ, maxUp, maxDown : float;
var outY, outNormY : float&) : bool
let topY = refY + min(maxUp, 2.8) + 0.45
let span = max(0.5, topY - (refY - maxDown - 0.5))
var traveled = 0.0
let downDir = float3(0.0, -1.0, 0.0)
for _hop in range(0, 4)
var hitD = span - traveled
if hitD <= 0.0
break
var mat = PHYSMAT_INVALID
var norm = float3(0.0)
var desc = RendInstDesc()
let origin = float3(testX, topY - traveled, testZ)
if !traceray_normalized(origin, downDir, hitD, mat, norm, ETF_RI | ETF_RI_PHYS, desc, PHYSMAT_INVALID)
break
let hitY = topY - traveled - max(0.0, hitD)
if hitY > refY + maxUp || !wto_terrain_ri_is_hard(desc, false)
traveled += max(0.0, hitD) + 0.35
continue
outY = hitY
outNormY = norm.y
return true
return false
[never_inline]
def public wto_terrain_drivable_yn(refPos : float3; testX, testZ : float;
var outGroundY, outNormY : float&) : bool
outGroundY = refPos.y
outNormY = 1.0
let horizDist = max(1.0, sqrt(wto_sq(testX - refPos.x) + wto_sq(testZ - refPos.z)))
let climbTan = tan(WTO_AI_TERRAIN_MAX_CLIMB_DEG * WTO_DEG_TO_RAD)
let dropTan = tan(WTO_AI_TERRAIN_MAX_DROP_DEG * WTO_DEG_TO_RAD)
let maxUp = min(3.6, horizDist * climbTan + 0.38)
let maxDown = min(3.0, horizDist * dropTan + 0.35)
let probeTop = float3(testX, refPos.y + min(max(2.2, maxUp + 0.6), 3.0), testZ)
var drop = max(7.0, maxDown + 4.5)
var baseNorm = float3(0.0, 1.0, 0.0)
let baseHit = tracedown_normalized(probeTop, drop, baseNorm, TERRAIN_GROUND_MASK)
let baseY = probeTop.y - drop
var riY = 0.0
var riNormY = 0.0
let riHit = wto_trace_bridge_deck(refPos.y, testX, testZ, maxUp, maxDown, riY, riNormY)
var ok = false
if riHit && riY <= refPos.y + maxUp && riY >= refPos.y - maxDown && riNormY >= 0.68
if !baseHit || riY > baseY + 0.15 || baseNorm.y < 0.82
outGroundY = riY
outNormY = riNormY
ok = true
let minNormY = cos(max(WTO_AI_TERRAIN_MAX_CLIMB_DEG, WTO_AI_TERRAIN_MAX_DROP_DEG) * WTO_DEG_TO_RAD)
if !ok && baseHit && refPos.y - baseY <= maxDown && baseY - refPos.y <= maxUp && baseNorm.y >= minNormY
outGroundY = baseY
outNormY = baseNorm.y
ok = true
if !ok
return false
let waterProbe = float3(testX, outGroundY + 0.5, testZ)
var waterY = 0.0
if traceht_water(waterProbe, waterY) && waterY - outGroundY > WTO_AI_TERRAIN_MAX_WATER_M
return false
return true
[never_inline]
def public wto_terrain_drivable_y(refPos : float3; testX, testZ : float; var outGroundY : float&) : bool
var ny = 1.0
return wto_terrain_drivable_yn(refPos, testX, testZ, outGroundY, ny)
[never_inline]
def public wto_terrain_point_valid(army : int; var pt : float3&) : bool
let checkPt = pt
if !das_is_in_battle_area(checkPt, true, army, 0.0, false, false)
return false
let probeTop = float3(pt.x, pt.y + 80.0, pt.z)
var drop = 220.0
var norm = float3(0.0, 1.0, 0.0)
if !tracedown_normalized(probeTop, drop, norm, TERRAIN_GROUND_MASK) || norm.y < 0.82
return false
let gy = probeTop.y - drop
let waterProbe = float3(pt.x, gy + 0.5, pt.z)
var waterY = 0.0
if traceht_water(waterProbe, waterY) && waterY - gy > WTO_AI_TERRAIN_MAX_WATER_M
return false
pt.y = gy
return true
// Detect sheer cliff drop-offs or deep water beyond an uphill/flat crest along `dirXZ`.
[never_inline]
def public wto_terrain_has_cliff_ahead(startPos, dirXZ : float3; lookaheadM : float) : bool
let dir = wto_xz_normalize(dirXZ, float3(1.0, 0.0, 0.0))
let stepM = 3.5
let steps = clamp(int(lookaheadM / stepM), 2, 10)
let dropTan = tan(WTO_AI_TERRAIN_MAX_DROP_DEG * WTO_DEG_TO_RAD)
let minDropNormY = cos((WTO_AI_TERRAIN_MAX_DROP_DEG + 4.0) * WTO_DEG_TO_RAD)
var curY = startPos.y
var peakY = startPos.y
for s in range(1, steps + 1)
let d = float(s) * stepM
let tx = startPos.x + dir.x * d
let tz = startPos.z + dir.z * d
let top = float3(tx, curY + 4.0, tz)
var drop = 18.0
var norm = float3(0.0, 1.0, 0.0)
if !tracedown_normalized(top, drop, norm, TERRAIN_GROUND_MASK)
return true
let gy = top.y - drop
var deckY = 0.0
var deckNormY = 0.0
if wto_trace_bridge_deck(curY, tx, tz, 3.0, 3.0, deckY, deckNormY) && deckNormY >= 0.72 && deckY > gy + 0.3
curY = deckY
peakY = max(peakY, deckY)
continue
let stepDrop = curY - gy
if stepDrop > stepM * dropTan + 0.48
return true
if stepDrop > 0.8 && norm.y < minDropNormY
return true
if peakY - gy > 2.6 && norm.y < 0.80
return true
let wProbe = float3(tx, gy + 0.5, tz)
var wY = 0.0
if traceht_water(wProbe, wY) && wY - gy > WTO_AI_TERRAIN_MAX_WATER_M
return true
curY = gy
peakY = max(peakY, gy)
return false
// True when perched on an elevated plateau/ridge whose enemy-facing edge drops off into a cliff
// while the friendly rear has a drivable gentler back-slope.
[never_inline]
def public wto_terrain_is_exposed_ridge(pos, threatDirXZ, backDirXZ : float3) : bool
if !wto_terrain_has_cliff_ahead(pos, threatDirXZ, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M)
return false
let bDir = wto_xz_normalize(backDirXZ, -wto_xz_normalize(threatDirXZ, float3(1.0, 0.0, 0.0)))
var backY = pos.y
let bx = pos.x + bDir.x * 10.0
let bz = pos.z + bDir.z * 10.0
if !wto_terrain_drivable_y(pos, bx, bz, backY)
return false
return backY <= pos.y + 1.4
// Foliage-ignoring LOS check: blocks on terrain, buildings, smoke screens, and hard RendInsts,
// while seeing cleanly through soft bushes/leaves without 4 Hz aim flicker.
[never_inline]
def public wto_terrain_los_clear(fromPos, toPos : float3) : bool
let delta = toPos - fromPos
let dist = length(delta)
if dist <= 1.5
return true
let dir = delta / dist
let traceLen = max(0.5, dist - 1.2)
var p0 = fromPos
var p1 = toPos
if rayhit_smoke_occluders(p0, p1)
return false
if rayhit_normalized(p0, dir, traceLen, TERRAIN_LOS_MASK, -1)
return false
return wto_terrain_hard_ray(p0, dir, traceLen) >= traceLen - 0.25
+296
View File
@@ -0,0 +1,296 @@
// Shared zero-heap POD data structures and domain constants for WTOffline's ground AI pipeline.
options indenting = 2
options no_global_heap = true
module wto_ai_types_common shared
require ecs
let public WTO_MAX_BOTS = 64
let public WTO_MAX_UNITS = 96
let public WTO_MAX_WRECKS = 64
let public WTO_MAX_CAPS = 8
let public WTO_MAX_PATH_PTS = 32
let public WTO_MAX_DEATHS = 32
let public WTO_MAX_JAMS = 24
let public WTO_MAX_RADIO = 24
let public WTO_ROLE_MEDIUM = 0
let public WTO_ROLE_LIGHT = 1
let public WTO_ROLE_HEAVY = 2
let public WTO_ROLE_TD = 3
let public WTO_ROLE_SPAA = 4
let public WTO_POSTURE_MARCH = 0
let public WTO_POSTURE_DISPERSE = 1
let public WTO_POSTURE_ENGAGE_HALT = 2
let public WTO_POSTURE_PEEK_BACK = 4
let public WTO_POSTURE_REVERSE_WITHDRAW = 5
let public WTO_POSTURE_RETREAT = 6
let public WTO_DRIVE_HALT = 0
let public WTO_DRIVE_CRUISE = 1
let public WTO_DRIVE_PIVOT = 2
let public WTO_DRIVE_REVERSE = 3
[safe_when_uninitialized]
struct public WtoVehicleSpec
ready : bool = false
role : int = 0
hasVertStab : bool = false
isLimitedTraverse : bool = false
yawLimitDeg : float = 180.0
minPitchDeg : float = -8.0
maxPitchDeg : float = 22.0
turretYawSpd : float = 24.0
turretPitchSpd : float = 8.0
muzzleSpeedMps : float = 880.0
shellDragCx : float = 0.35
isAutocannonBelt : bool = false
isPureLauncher : bool = false
halfLen : float = 3.4
halfWid : float = 1.75
isTracked : bool = true
canPivot : bool = false
vMaxFwd : float = 13.5
vMaxRev : float = 3.2
[safe_when_uninitialized]
struct public WtoUnitSnap
eid : EntityId = INVALID_ENTITY_ID
army : int = 0
pos : float3 = float3(0.0, 0.0, 0.0)
vel : float3 = float3(0.0, 0.0, 0.0)
hullFwd : float3 = float3(1.0, 0.0, 0.0)
halfLen : float = 3.4
halfWid : float = 1.75
engineRpm : float = 0.0
isAlive : bool = false
isGround : bool = false
isAir : bool = false
isLightTag : bool = false
isShooting : bool = false
isBurn : bool = false
isHuman : bool = false
[safe_when_uninitialized]
struct public WtoWreckSnap
eid : EntityId = INVALID_ENTITY_ID
pos : float3 = float3(0.0, 0.0, 0.0)
halfLen : float = 3.4
halfWid : float = 1.75
[safe_when_uninitialized]
struct public WtoCapSnap
zoneId : int = -1
center : float3 = float3(0.0, 0.0, 0.0)
radius : float = 25.0
ownerArmy : int = 0
progress : float = 0.0
[safe_when_uninitialized]
struct public WtoDeathEvent
pos : float3 = float3(0.0, 0.0, 0.0)
army : int = 0
at : float = -100.0
[safe_when_uninitialized]
struct public WtoJamZone
pos : float3 = float3(0.0, 0.0, 0.0)
untilAt : float = -100.0
hits : int = 0
[safe_when_uninitialized]
struct public WtoRadioSpot
pos : float3 = float3(0.0, 0.0, 0.0)
army : int = 0
targetEid : EntityId = INVALID_ENTITY_ID
untilAt : float = -100.0
[safe_when_uninitialized]
struct public WtoWorldSnap
valid : bool = false
time : float = 0.0
matchStartAt : float = -100.0
unitCount : int = 0
units : WtoUnitSnap[96]
wreckCount : int = 0
wrecks : WtoWreckSnap[64]
recordedDeadCount : int = 0
recordedDeadEids : EntityId[64]
capCount : int = 0
caps : WtoCapSnap[8]
nextCapRefreshAt : float = -100.0
battleCenter : float3 = float3(0.0, 0.0, 0.0)
battleRadius : float = 0.0
spawnsResolved : bool = false
teamSpawnValid : bool[3]
teamSpawnCenter : float3[3]
deathCursor : int = 0
deaths : WtoDeathEvent[32]
jamCursor : int = 0
jams : WtoJamZone[24]
radioCursor : int = 0
radioSpots : WtoRadioSpot[24]
[safe_when_uninitialized]
struct public WtoCrowdInfo
nearestAllyEid : EntityId = INVALID_ENTITY_ID
nearestAllyDistM : float = 999.0
nearPersonalCount : int = 0
clusterAllyCount : int = 0
repulseDirXZ : float3 = float3(0.0, 0.0, 0.0)
isCrowded : bool = false
[safe_when_uninitialized]
struct public WtoCrowdSummary
crowdedBotCount : int = 0
maxClusterSize : int = 1
minPairDistM : float = 999.0
disperseEvents : int = 0
[safe_when_uninitialized]
struct public WtoMacroOrder
goalPos : float3 = float3(0.0, 0.0, 0.0)
capIndex : int = -1
cautious : bool = false
overwatchOutside : bool = false
spaaAnchorValid : bool = false
spaaAnchorPos : float3 = float3(0.0, 0.0, 0.0)
spaaRelocateAt : float = -100.0
valid : bool = false
[safe_when_uninitialized]
struct public WtoPerceiveState
targetEid : EntityId = INVALID_ENTITY_ID
targetIsAir : bool = false
hasClearLos : bool = false
knownPos : float3 = float3(0.0, 0.0, 0.0)
smoothedVel : float3 = float3(0.0, 0.0, 0.0)
lastSeenAt : float = -100.0
lockedEid : EntityId = INVALID_ENTITY_ID
lockedUntil : float = -100.0
alertYawRad : float = 0.0
alertUntil : float = -100.0
lastDamagedAt : float = -100.0
lastOffenderEid : EntityId = INVALID_ENTITY_ID
lastRadioSentAt : float = -100.0
[safe_when_uninitialized]
struct public WtoTacticsState
posture : int = 0
moveGoal : float3 = float3(0.0, 0.0, 0.0)
desiredSpeedMps : float = 10.0
spaaYieldAir : bool = false
onExposedRidge : bool = false
ridgeEnterAt : float = -100.0
ridgeShotsStart : int = 0
withdrawAnchor : float3 = float3(0.0, 0.0, 0.0)
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
corridor : float3[32]
corridorLen : int = 0
corridorIdx : int = 0
corridorGoal : float3 = float3(0.0, 0.0, 0.0)
nextReplanAt : float = -100.0
nextShortcutAt : float = -100.0
wingInit : bool = false
wingSign : int = 0
laneOffsetM : float = 0.0
wingCapIdx : int = -2
wingRelayPos : float3 = float3(0.0, 0.0, 0.0)
wingRelayValid : bool = false
shortcutPos : float3 = float3(0.0, 0.0, 0.0)
shortcutValid : bool = false
detourPos : float3 = float3(0.0, 0.0, 0.0)
detourValid : bool = false
detourUntil : float = -100.0
detourCount : int = 0
lastStartOk : bool = false
lastGoalOk : bool = false
[safe_when_uninitialized]
struct public WtoNavState
steerDir : float3 = float3(1.0, 0.0, 0.0)
frontClearM : float = 30.0
rearClearM : float = 16.0
cliffAhead : bool = false
stuckOrigin : float3 = float3(0.0, 0.0, 0.0)
stuckCheckAt : float = -100.0
reverseAnchor : float3 = float3(0.0, 0.0, 0.0)
reverseUntil : float = -100.0
reverseCount : int = 0
ridgeWithdrawEvents : int = 0
[safe_when_uninitialized]
struct public WtoDriveCmd
valid : bool = false
mode : int = 0
targetPos : float3 = float3(0.0, 0.0, 0.0)
desiredDir : float3 = float3(1.0, 0.0, 0.0)
speedMps : float = 0.0
frontClearM : float = 30.0
rearClearM : float = 16.0
[safe_when_uninitialized]
struct public WtoDriveState
routeBOwned : bool = false
routeAFallback : bool = false
deadEchoSec : float = 0.0
prevYaw : float = 0.0
prevYawAt : float = -100.0
omegaYawRad : float = 0.0
prevThr : float = 0.0
prevStr : float = 0.0
lastVFwd : float = 0.0
[safe_when_uninitialized]
struct public WtoFireState
turretNo : int = -1
gunReady : bool = false
reloading : bool = false
gunDamaged : bool = false
pitchBlocked : bool = false
pitchClampSec : float = 0.0
cmdYawDeg : float = 0.0
cmdPitchDeg : float = 0.0
curYawDeg : float = 0.0
curPitchDeg : float = 0.0
prevPitchDeg : float = 0.0
servoInit : bool = false
prevBarrelDir : float3 = float3(1.0, 0.0, 0.0)
prevBarrelAt : float = -100.0
barrelOmegaDegSec : float = 0.0
settleHoldSec : float = 0.0
lastAligned : bool = false
lastAimErrDeg : float = 0.0
lastShotAt : float = -100.0
shotCount : int = 0
shotErrSumDeg : float = 0.0
maxShotErrDeg : float = 0.0
[safe_when_uninitialized]
struct public WtoBotSlot
used : bool = false
eid : EntityId = INVALID_ENTITY_ID
army : int = 0
lastSeenAt : float = -100.0
prepared : bool = false
nextTacticsAt : float = -100.0
nextNavAt : float = -100.0
spec : WtoVehicleSpec = WtoVehicleSpec()
crowd : WtoCrowdInfo = WtoCrowdInfo()
macro : WtoMacroOrder = WtoMacroOrder()
perceive : WtoPerceiveState = WtoPerceiveState()
tactics : WtoTacticsState = WtoTacticsState()
route : WtoRouteState = WtoRouteState()
nav : WtoNavState = WtoNavState()
driveCmd : WtoDriveCmd = WtoDriveCmd()
drive : WtoDriveState = WtoDriveState()
fire : WtoFireState = WtoFireState()
+299
View File
@@ -0,0 +1,299 @@
// World observation layer: builds one flat per-frame snapshot of units, wrecks, authoritative
// capture zones, respawn anchors, and ring buffers for deaths, traffic jams, and radio spots.
options indenting = 2
options no_global_heap = true
module wto_ai_world_common shared
require ecs
require math
require strings
require DagorMath
require Mission
require Unit
require IGroundModel
require HeavyVehicleModel
require Dacoll
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_types_common
[never_inline]
def public wto_world_reset(var snap : WtoWorldSnap&)
snap.valid = false
snap.time = 0.0
snap.matchStartAt = -100.0
snap.unitCount = 0
snap.wreckCount = 0
snap.recordedDeadCount = 0
snap.capCount = 0
snap.nextCapRefreshAt = -100.0
snap.battleCenter = float3(0.0, 0.0, 0.0)
snap.battleRadius = 0.0
snap.spawnsResolved = false
snap.deathCursor = 0
snap.jamCursor = 0
snap.radioCursor = 0
for a in range(3)
snap.teamSpawnValid[a] = false
snap.teamSpawnCenter[a] = float3(0.0, 0.0, 0.0)
for i in range(WTO_MAX_WRECKS)
snap.recordedDeadEids[i] = INVALID_ENTITY_ID
for i in range(WTO_MAX_DEATHS)
snap.deaths[i] = WtoDeathEvent()
for i in range(WTO_MAX_JAMS)
snap.jams[i] = WtoJamZone()
for i in range(WTO_MAX_RADIO)
snap.radioSpots[i] = WtoRadioSpot()
[never_inline]
def public wto_world_record_death(var snap : WtoWorldSnap&; army : int; pos : float3; now : float)
if !wto_is_finite3(pos)
return
let idx = snap.deathCursor % WTO_MAX_DEATHS
snap.deaths[idx].pos = pos
snap.deaths[idx].army = army
snap.deaths[idx].at = now
snap.deathCursor = (snap.deathCursor + 1) % 100000
[never_inline]
def public wto_world_record_jam(var snap : WtoWorldSnap&; pos : float3; now : float)
if !wto_is_finite3(pos)
return
for i in range(WTO_MAX_JAMS)
if snap.jams[i].untilAt > now && wto_xz_dist_sq(snap.jams[i].pos, pos) <= 324.0
snap.jams[i].pos = lerp(snap.jams[i].pos, pos, 0.35)
snap.jams[i].untilAt = now + 26.0
snap.jams[i].hits = min(snap.jams[i].hits + 1, 12)
return
let idx = snap.jamCursor % WTO_MAX_JAMS
snap.jams[idx].pos = pos
snap.jams[idx].untilAt = now + 24.0
snap.jams[idx].hits = 1
snap.jamCursor = (snap.jamCursor + 1) % 100000
[never_inline]
def public wto_world_active_jams(snap : WtoWorldSnap const&; now : float) : int
var cnt = 0
for i in range(WTO_MAX_JAMS)
if snap.jams[i].untilAt > now
cnt++
return cnt
[never_inline]
def public wto_world_jam_penalty(snap : WtoWorldSnap const&; pt : float3; now : float) : float
var pen = 0.0
for i in range(WTO_MAX_JAMS)
if snap.jams[i].untilAt <= now
continue
let dSq = wto_xz_dist_sq(pt, snap.jams[i].pos)
if dSq < 676.0
let frac = 1.0 - sqrt(dSq) / 26.0
pen += frac * (16.0 + float(snap.jams[i].hits) * 4.0)
return pen
[never_inline]
def public wto_world_broadcast_radio(var snap : WtoWorldSnap&; army : int;
targetEid : EntityId; pos : float3; now : float)
for i in range(WTO_MAX_RADIO)
if snap.radioSpots[i].untilAt > now && snap.radioSpots[i].army == army && snap.radioSpots[i].targetEid == targetEid
snap.radioSpots[i].pos = pos
snap.radioSpots[i].untilAt = now + 14.0
return
let idx = snap.radioCursor % WTO_MAX_RADIO
snap.radioSpots[idx].pos = pos
snap.radioSpots[idx].army = army
snap.radioSpots[idx].targetEid = targetEid
snap.radioSpots[idx].untilAt = now + 14.0
snap.radioCursor = (snap.radioCursor + 1) % 100000
[never_inline]
def public wto_world_find_unit(snap : WtoWorldSnap const&; eid : EntityId) : int
if !eid
return -1
for i in range(snap.unitCount)
if snap.units[i].eid == eid
return i
return -1
[never_inline]
def private wto_record_wreck_once(var snap : WtoWorldSnap&; eid : EntityId; u : Unit const?; gm : IGroundModel const?)
if gm == null || snap.wreckCount >= WTO_MAX_WRECKS
return
let box = gm.bodyBoundingBox
let wIdx = snap.wreckCount
snap.wrecks[wIdx].eid = eid
snap.wrecks[wIdx].pos = u.pos
snap.wrecks[wIdx].halfLen = max(2.0, max(abs(box.boxMin.x), abs(box.boxMax.x)))
snap.wrecks[wIdx].halfWid = max(1.1, max(abs(box.boxMin.z), abs(box.boxMax.z)))
snap.wreckCount = wIdx + 1
let wArmy = int(u.army)
if wArmy != 1 && wArmy != 2
return
for r in range(snap.recordedDeadCount)
if snap.recordedDeadEids[r] == eid
return
let dst = snap.recordedDeadCount < WTO_MAX_WRECKS ? snap.recordedDeadCount++ : int(uint(eid) % uint(WTO_MAX_WRECKS))
snap.recordedDeadEids[dst] = eid
wto_world_record_death(snap, wArmy, u.pos, snap.time)
[never_inline]
def private wto_refresh_units(var snap : WtoWorldSnap&)
snap.unitCount = 0
snap.wreckCount = 0
let maxDistSq = wto_sq(max(snap.battleRadius * 2.5, 2200.0))
query() <| $ [es] (eid : EntityId; unit__ref : UnitRef)
let u = unit__ref.unit
if u == null || u.isDelayed
return
let gm = as_gm(u)
if snap.battleRadius > 1.0 && gm != null && wto_xz_dist_sq(u.pos, snap.battleCenter) > maxDistSq
return
if !u.isAlive
wto_record_wreck_once(snap, eid, u, gm)
return
if snap.unitCount >= WTO_MAX_UNITS
return
let army = int(u.army)
if army != 1 && army != 2
return
let isGround = gm != null && gm.moveSys != null && as_hv(u) != null
let isAir = u.isFlightModelWrap
if !isGround && !isAir
return
var halfLen = 3.4
var halfWid = 1.75
if gm != null
let box = gm.bodyBoundingBox
halfLen = max(1.8, max(abs(box.boxMin.x), abs(box.boxMax.x)))
halfWid = max(0.9, max(abs(box.boxMin.z), abs(box.boxMax.z)))
let idx = snap.unitCount
snap.units[idx].eid = eid
snap.units[idx].army = army
snap.units[idx].pos = u.pos
snap.units[idx].vel = u.vel
snap.units[idx].hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0))
snap.units[idx].halfLen = halfLen
snap.units[idx].halfWid = halfWid
snap.units[idx].engineRpm = gm != null ? clamp(abs(gm.engineRelativeRPM), 0.0, 1.2) : 0.0
snap.units[idx].isAlive = true
snap.units[idx].isGround = isGround
snap.units[idx].isAir = isAir
snap.units[idx].isLightTag = false
snap.units[idx].isShooting = gm != null && (gm.isShooting || gm.hasMissilesInFlight)
snap.units[idx].isBurn = u.isBurn
snap.units[idx].isHuman = u.isHumanPlayer
snap.unitCount = idx + 1
for i in range(snap.unitCount)
if snap.units[i].isGround
snap.units[i].isLightTag = has(snap.units[i].eid, "unit_tag__light_vehicle")
[never_inline]
def private wto_snap_cap_y(x, refY, z : float) : float
let top = float3(x, refY + 25.0, z)
var drop = 65.0
if tracedown_normalized(top, drop, ETF_LMESH | ETF_HEIGHTMAP | ETF_STRUCTURES)
return top.y - drop
let hiTop = float3(x, max(refY + 120.0, 800.0), z)
var hiDrop = hiTop.y + 200.0
if tracedown_normalized(hiTop, hiDrop, ETF_LMESH | ETF_HEIGHTMAP)
return hiTop.y - hiDrop
return refY
[never_inline]
def private wto_refresh_caps(var snap : WtoWorldSnap&)
snap.capCount = 0
var pCount = 0
var pIds : int[8]
var pPos : float3[8]
var pRad : float[8]
var pOwn : int[8]
query() <| $ [es] (capture_zone__zoneId : int; transform : float3x4;
capture_zone__name : string = ""; sphere_zone__radius : float = 0.0;
capzone__approximateRadius : float = 0.0; capzone__owningTeam : int = -1)
if pCount >= WTO_MAX_CAPS || capture_zone__zoneId < 0
return
var rad = max(sphere_zone__radius, capzone__approximateRadius)
if rad <= 2.0 && !empty(capture_zone__name)
let areaId = get_area_id(capture_zone__name)
if areaId >= 0
let lim = get_area_limits_xz(areaId)
rad = 0.25 * (abs(lim.z - lim.x) + abs(lim.w - lim.y))
if rad <= 2.0
rad = 0.5 * min(length(transform[0]), length(transform[2]))
pIds[pCount] = capture_zone__zoneId
pPos[pCount] = transform[3]
pRad[pCount] = clamp(rad > 2.0 ? rad : 25.0, 14.0, 80.0)
pOwn[pCount] = (capzone__owningTeam == 1 || capzone__owningTeam == 2) ? capzone__owningTeam : 0
pCount++
for_each_capture_zone() <| $(zone : CaptureZone)
if snap.capCount >= WTO_MAX_CAPS || !zone.isEnabled
return
var f = -1
for p in range(pCount)
if pIds[p] == zone.id
f = p
break
if f < 0
return
let c = float3(pPos[f].x, wto_snap_cap_y(pPos[f].x, pPos[f].y, pPos[f].z), pPos[f].z)
let cIdx = snap.capCount
snap.caps[cIdx].zoneId = zone.id
snap.caps[cIdx].center = c
snap.caps[cIdx].radius = pRad[f]
snap.caps[cIdx].ownerArmy = pOwn[f]
snap.caps[cIdx].progress = float(zone.captureProgressVal)
snap.capCount = cIdx + 1
[never_inline]
def private wto_refresh_bounds_and_spawns(var snap : WtoWorldSnap&)
var sum = float3(0.0, 0.0, 0.0)
var cnt = 0
for i in range(snap.capCount)
sum += snap.caps[i].center
cnt++
if cnt > 0
snap.battleCenter = sum / float(cnt)
var maxDSq = 0.0
for i in range(snap.capCount)
maxDSq = max(maxDSq, wto_xz_dist_sq(snap.caps[i].center, snap.battleCenter))
snap.battleRadius = clamp(sqrt(maxDSq) + 650.0, 850.0, 2400.0)
if snap.spawnsResolved
return
var sumPos : float3[3]
var spCnt : int[3]
for a in range(3)
sumPos[a] = float3(0.0, 0.0, 0.0)
spCnt[a] = 0
let maxDistSq = wto_sq(max(snap.battleRadius * 2.2, 2200.0))
get_respawn_points() <| $(active, resptype, team, pos)
if !active || (team != 1 && team != 2)
return
if resptype == "human" || resptype == "aircraft" || resptype == "helicopter"
return
if snap.battleRadius > 1.0 && wto_xz_dist_sq(pos, snap.battleCenter) > maxDistSq
return
sumPos[team] += pos
spCnt[team]++
for a in range(1, 3)
if spCnt[a] == 0
for i in range(snap.unitCount)
assume u = snap.units[i]
if u.isAlive && u.isGround && u.army == a
sumPos[a] += u.pos
spCnt[a]++
if spCnt[a] > 0
snap.teamSpawnCenter[a] = sumPos[a] / float(spCnt[a])
snap.teamSpawnValid[a] = true
snap.spawnsResolved = snap.teamSpawnValid[1] && snap.teamSpawnValid[2]
[never_inline]
def public wto_world_refresh(now : float; var snap : WtoWorldSnap&)
snap.time = now
if snap.matchStartAt < -50.0
snap.matchStartAt = now
if now >= snap.nextCapRefreshAt
snap.nextCapRefreshAt = now + 0.5
wto_refresh_caps(snap)
wto_refresh_bounds_and_spawns(snap)
wto_refresh_units(snap)
snap.valid = true