feat(ground-ai): add the hull decision channel

Score driving behaviors and reuse the existing action handlers. Face the
main threat and support reverse travel on the navigation corridor.
This commit is contained in:
N0VAN0M4LY committed 2026-12-06 01:11:55 +08:00
1 parent 4e658cae9c
commit ee360a5042
16 files changed
+737 -269

No files matched your search

@@ -529,12 +529,13 @@
"loadout": "Ground AI spawn ammunition",
"commander": "Commander & role quotas",
"macro": "Macro capture & SPAA",
"stateMachine": "Hull state machine & repair",
"stateMachine": "Hull actions & repair",
"perception": "Visual perception & exposure",
"tactics": "Situational awareness & memory",
"estimation": "Lead estimation & aim bias",
"threat": "Threat assessment",
"turret": "Turret attention",
"behavior": "Hull behavior",
"fireControl": "Fire control & fire gate",
"navigation": "Driving & navigation",
"navEngine": "Map navigation mesh & path costs",
@@ -549,12 +550,13 @@
"loadout": "Ready-rack carry count and primary/secondary shell split",
"commander": "Role percentages by game mode, flank lanes, rally and recall",
"macro": "Opening split, cap occupancy, death zones and SPAA positioning",
"stateMachine": "Short halts, reload cover retreat, angling, repositioning and repair",
"stateMachine": "Short halts, reload cover retreat, repositioning and repair",
"perception": "Foliage transparency, exposure accumulation and decay",
"tactics": "Vision range, audio detection, radio sharing and target memory",
"estimation": "Sample-based velocity lead, exit watch and natural shot spread",
"threat": "How dangerous each discovered enemy is: distance, aim, line of sight and recent hits",
"turret": "Where the turret looks without a target: threats, cues and scanning along the route",
"behavior": "Scores of the hull behaviors, commitment, facing the main threat and driving backwards",
"fireControl": "Hit probability and fire threshold, autocannon bursts, secondary weapons, barrel settle and ballistic safety",
"navigation": "Drive backend, pivot turns and tactical reverse",
"navEngine": "Baked map navigation packs, their fallback, and path costs per surface for tracked and wheeled vehicles",
@@ -617,17 +619,12 @@
"enemySpawnAvoidM": "Enemy spawn avoidance distance"
},
"stateMachine": {
"preaimAngleDeg": "Moving pre-aim angle threshold",
"movingShotWaitSec": "Time to attempt a moving shot before halting",
"shortHaltMaxSec": "Short halt max duration",
"shortHaltCooldownSec": "Short halt cooldown",
"turnLaunchSpeedMps": "Turn launch target speed",
"coverMinDistM": "Cover search min distance",
"coverMaxDistM": "Cover search max distance",
"coverRetreatBudgetSec": "Reload cover retreat max duration",
"reloadAdvanceAngleDeg": "Reload zigzag advance angle",
"hullAngleTriggerDeg": "Hull angling trigger angle",
"hullAngleTargetDeg": "Target hull angling offset",
"maxTotalHaltSec": "Max cumulative halt before reposition",
"stalemateMissShots": "Ineffective shots before reposition",
"stalemateNoShotHalts": "No-shot halts before reposition",
@@ -687,15 +684,37 @@
"scanArcDeg": "Scan arc either side of the route",
"scanPeriodSec": "Scan sweep period"
},
"behavior": {
"scoreIntervalSec": "Behavior scoring interval",
"minHoldSec": "Minimum time a behavior is kept",
"switchMargin": "Extra score needed to switch behavior",
"advanceScore": "Score: advance along the order route",
"engageScore": "Score: engage on the move",
"urgencyWeight": "Score shift by order urgency",
"haltScore": "Score: short halt for a shot",
"crossfirePenalty": "Short-halt penalty per extra enemy aiming at the bot",
"coverScore": "Score: pull back to cover to reload",
"coverDangerWeight": "Cover score added by threat danger",
"coverOffensivePenalty": "Cover penalty on an urgent attack",
"coverRetrySec": "Wait before searching for cover again after none was found",
"repositionScore": "Score: change firing position when the engagement is stuck",
"holdScore": "Score: hold the post, watch the last exit or wait at the rally point",
"disperseScore": "Score: spread out of a crowd",
"urgentSpeedKeep": "Share of march speed an urgent bot keeps when slowing for a shot",
"hullAngleDeg": "Hull angle to the main threat",
"faceToleranceDeg": "Facing tolerance while standing",
"faceMinDanger": "Threat danger needed to face it",
"faceHaltLimitDeg": "Facing error that turns the hull during a short halt",
"reverseTravelAngleDeg": "Threat angle off the travel direction for driving backwards",
"reverseMaxGoalDistM": "Drive backwards only toward a goal within",
"reverseMinSpeedMps": "Lowest top reverse speed for driving backwards",
"reverseHoldSec": "Minimum time between switching forwards and backwards"
},
"fireControl": {
"maxEngageRangeM": "Max engagement range",
"closeRangeM": "Close range band threshold",
"midRangeM": "Mid range band threshold",
"longRangeM": "Long range band threshold",
"midSlowSpeedRatio": "Mid-range fire-on-move speed ratio",
"midSlowMaxMps": "Mid-range fire-on-move speed cap",
"closeRangeMaxSpeedKmh": "Moving-fire speed cap at the close-range boundary",
"pointBlankMaxSpeedKmh": "Moving-fire speed cap at point blank",
"stopSpeedMaxMps": "Stopped speed threshold",
"longRangeWindowSec": "Long-range clear LOS window",
"baseAlignDeg": "Base gun alignment tolerance",
@@ -529,12 +529,13 @@
"loadout": "陆战 AI 出生携弹",
"commander": "指挥层与分路配额",
"macro": "宏观占点与防空",
"stateMachine": "单车状态机与掩体维修",
"stateMachine": "车体动作与掩体维修",
"perception": "视觉感知与曝光",
"tactics": "态势感知与目标记忆",
"estimation": "目击测速与瞄准偏差",
"threat": "威胁评估",
"turret": "炮塔关注方向",
"behavior": "车体行为",
"fireControl": "火控与开火许可",
"navigation": "机动与寻路控制",
"navEngine": "地图导航网格与通行代价",
@@ -549,12 +550,13 @@
"loadout": "待发架携弹量与主/副弹种分配",
"commander": "各模式进攻 / 侧翼 / 架枪比例、集结与回防",
"macro": "开局分兵、占点人数、死亡区规避与防空站位",
"stateMachine": "短停预算、装填回缩、摆角、换位与受损维修",
"stateMachine": "短停预算、装填回缩、换位与受损维修",
"perception": "植被透光、曝光累计速度与衰减",
"tactics": "视距、听觉发现范围、电台共享与记忆时长",
"estimation": "本车目击测速、守出口时长与自然散布",
"threat": "每个已发现敌人的危险程度:距离、是否瞄着本车、视线与最近是否命中本车",
"turret": "没有目标时炮塔看哪里:威胁、线索与沿路线扫视",
"behavior": "车体各行为的得分、承诺时间、车头对主威胁与倒车跟路",
"fireControl": "命中概率与开火门槛、机炮点射、副武器、炮管稳定和弹道安全",
"navigation": "驱动方式、原地转向与战术倒车",
"navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价",
@@ -617,17 +619,12 @@
"enemySpawnAvoidM": "敌方出生点规避距离"
},
"stateMachine": {
"preaimAngleDeg": "行进预瞄角度阈值",
"movingShotWaitSec": "转入短停前尝试行进射击的时间",
"shortHaltMaxSec": "单次短停最长时间",
"shortHaltCooldownSec": "短停冷却时间",
"turnLaunchSpeedMps": "甩弯起步目标车速",
"coverMinDistM": "掩体搜索最小距离",
"coverMaxDistM": "掩体搜索最大距离",
"coverRetreatBudgetSec": "装填回缩掩体最长用时",
"reloadAdvanceAngleDeg": "装填折线跃进偏角",
"hullAngleTriggerDeg": "触发车体摆角阈值",
"hullAngleTargetDeg": "车体目标摆角",
"maxTotalHaltSec": "累计停留强制换位上限",
"stalemateMissShots": "无伤害连射触发换位发数",
"stalemateNoShotHalts": "未开火短停触发换位次数",
@@ -687,15 +684,37 @@
"scanArcDeg": "沿路线向两侧扫视的角度",
"scanPeriodSec": "扫视一个来回的时长"
},
"behavior": {
"scoreIntervalSec": "行为打分间隔",
"minHoldSec": "行为最短保持时间",
"switchMargin": "切换行为所需高出的分数",
"advanceScore": "得分:沿任务路线推进",
"engageScore": "得分:交战推进",
"urgencyWeight": "任务紧迫度对得分的影响",
"haltScore": "得分:短停射击",
"crossfirePenalty": "每多一个瞄着本车的敌人,短停扣分",
"coverScore": "得分:退入掩体装填",
"coverDangerWeight": "威胁危险度对掩体得分的加成",
"coverOffensivePenalty": "紧急进攻时掩体扣分",
"coverRetrySec": "找不到掩体后再次搜索的间隔",
"repositionScore": "得分:交战僵持时换位",
"holdScore": "得分:守位、盯出口或在集结点等待",
"disperseScore": "得分:拥挤疏散",
"urgentSpeedKeep": "紧急任务为射击减速时保留的行军速度比例",
"hullAngleDeg": "车头对主威胁的倾角",
"faceToleranceDeg": "停车时朝向容差",
"faceMinDanger": "需要车头对准的威胁危险度下限",
"faceHaltLimitDeg": "短停时朝向偏差超过多少才转车体",
"reverseTravelAngleDeg": "威胁偏离行进方向多少度时倒车跟路",
"reverseMaxGoalDistM": "仅在离目的地这么近时倒车跟路",
"reverseMinSpeedMps": "倒车跟路所需的最低倒车极速",
"reverseHoldSec": "前进与倒车切换的最短间隔"
},
"fireControl": {
"maxEngageRangeM": "最大交战开火距离",
"closeRangeM": "近距交战分界距离",
"midRangeM": "中距交战分界距离",
"longRangeM": "远距交战分界距离",
"midSlowSpeedRatio": "中距行进射击最高车速比",
"midSlowMaxMps": "中距行进射击最高车速",
"closeRangeMaxSpeedKmh": "近距分界处行进射击最高车速",
"pointBlankMaxSpeedKmh": "贴身时行进射击最高车速",
"stopSpeedMaxMps": "停稳判定最高车速",
"longRangeWindowSec": "远距连续射界观察窗",
"baseAlignDeg": "主炮对准允许角误差",
@@ -54,7 +54,7 @@ function hasValidCrossFieldRules(effective: GroundAiTuningValues, patch: TuningP
if (est.watchMaxSec < est.watchMinSec || est.velStableSpanSec <= est.velSampleMinSpanSec) return false;
const fc = mergeSection(effective.fireControl, patch.fireControl);
if (fc.midRangeM <= fc.closeRangeM || fc.longRangeM <= fc.midRangeM) return false;
return fc.minFireThreshold <= fc.fireThreshold && fc.pointBlankMaxSpeedKmh >= fc.closeRangeMaxSpeedKmh;
return fc.minFireThreshold <= fc.fireThreshold;
}
export function BotTuningPanel({ data, saving, onSave }: Props) {
@@ -158,17 +158,12 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
defaultOpen: false,
customOnly: true,
fields: [
num('stateMachine', 'preaimAngleDeg', 1, 30, '°'),
num('stateMachine', 'movingShotWaitSec', 0.25, 5, 's'),
num('stateMachine', 'shortHaltMaxSec', 0.5, 12, 's'),
num('stateMachine', 'shortHaltCooldownSec', 0.5, 20, 's'),
num('stateMachine', 'turnLaunchSpeedMps', 0.5, 6, 'm/s'),
num('stateMachine', 'coverMinDistM', 2, 30, 'm'),
num('stateMachine', 'coverMaxDistM', 6, 80, 'm'),
num('stateMachine', 'coverRetreatBudgetSec', 1.5, 20, 's'),
num('stateMachine', 'reloadAdvanceAngleDeg', 0, 45, '°'),
num('stateMachine', 'hullAngleTriggerDeg', 15, 75, '°'),
num('stateMachine', 'hullAngleTargetDeg', 0, 35, '°'),
num('stateMachine', 'maxTotalHaltSec', 3, 40, 's'),
int('stateMachine', 'stalemateMissShots', 1, 8),
int('stateMachine', 'stalemateNoShotHalts', 1, 6),
@@ -254,6 +249,37 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
num('turret', 'scanPeriodSec', 1, 30, 's'),
],
},
{
id: 'behavior',
defaultOpen: false,
customOnly: true,
fields: [
num('behavior', 'scoreIntervalSec', 0.1, 3, 's'),
num('behavior', 'minHoldSec', 0, 10, 's'),
num('behavior', 'switchMargin', 0, 1),
num('behavior', 'advanceScore', 0, 1),
num('behavior', 'engageScore', 0, 1),
num('behavior', 'urgencyWeight', 0, 1),
num('behavior', 'haltScore', 0, 1),
num('behavior', 'crossfirePenalty', 0, 1),
num('behavior', 'coverScore', 0, 1),
num('behavior', 'coverDangerWeight', 0, 1),
num('behavior', 'coverOffensivePenalty', 0, 1),
num('behavior', 'coverRetrySec', 0.5, 30, 's'),
num('behavior', 'repositionScore', 0, 1),
num('behavior', 'holdScore', 0, 1),
num('behavior', 'disperseScore', 0, 1),
num('behavior', 'urgentSpeedKeep', 0, 1),
num('behavior', 'hullAngleDeg', 0, 45, '°'),
num('behavior', 'faceToleranceDeg', 3, 60, '°'),
num('behavior', 'faceMinDanger', 0, 2),
num('behavior', 'faceHaltLimitDeg', 10, 180, '°'),
num('behavior', 'reverseTravelAngleDeg', 60, 180, '°'),
num('behavior', 'reverseMaxGoalDistM', 0, 2000, 'm'),
num('behavior', 'reverseMinSpeedMps', 0.5, 10, 'm/s'),
num('behavior', 'reverseHoldSec', 0, 20, 's'),
],
},
{
id: 'fireControl',
defaultOpen: false,
@@ -263,10 +289,6 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
num('fireControl', 'closeRangeM', 30, 250, 'm'),
num('fireControl', 'midRangeM', 100, 600, 'm'),
num('fireControl', 'longRangeM', 300, 1500, 'm'),
num('fireControl', 'midSlowSpeedRatio', 0.1, 1),
num('fireControl', 'midSlowMaxMps', 1, 15, 'm/s'),
num('fireControl', 'closeRangeMaxSpeedKmh', 3.6, 100, 'km/h'),
num('fireControl', 'pointBlankMaxSpeedKmh', 3.6, 100, 'km/h'),
num('fireControl', 'stopSpeedMaxMps', 0.1, 2, 'm/s'),
num('fireControl', 'longRangeWindowSec', 1, 15, 's'),
num('fireControl', 'baseAlignDeg', 0.1, 3, '°'),
+29 -9
View File
@@ -188,17 +188,12 @@ const GroundAiPerceptionSchema = z.object({
});
const GroundAiStateMachineSchema = z.object({
preaimAngleDeg: z.number().min(1).max(30),
movingShotWaitSec: z.number().min(0.25).max(5),
shortHaltMaxSec: z.number().min(0.5).max(12),
shortHaltCooldownSec: z.number().min(0.5).max(20),
turnLaunchSpeedMps: z.number().min(0.5).max(6),
coverMinDistM: z.number().min(2).max(30),
coverMaxDistM: z.number().min(6).max(80),
coverRetreatBudgetSec: z.number().min(1.5).max(20),
reloadAdvanceAngleDeg: z.number().min(0).max(45),
hullAngleTriggerDeg: z.number().min(15).max(75),
hullAngleTargetDeg: z.number().min(0).max(35),
maxTotalHaltSec: z.number().min(3).max(40),
stalemateMissShots: z.number().int().min(1).max(8),
stalemateNoShotHalts: z.number().int().min(1).max(6),
@@ -234,6 +229,33 @@ const GroundAiTurretSchema = z.object({
scanPeriodSec: z.number().min(1).max(30),
});
const GroundAiBehaviorSchema = z.object({
scoreIntervalSec: z.number().min(0.1).max(3),
minHoldSec: z.number().min(0).max(10),
switchMargin: z.number().min(0).max(1),
advanceScore: z.number().min(0).max(1),
engageScore: z.number().min(0).max(1),
urgencyWeight: z.number().min(0).max(1),
haltScore: z.number().min(0).max(1),
crossfirePenalty: z.number().min(0).max(1),
coverScore: z.number().min(0).max(1),
coverDangerWeight: z.number().min(0).max(1),
coverOffensivePenalty: z.number().min(0).max(1),
coverRetrySec: z.number().min(0.5).max(30),
repositionScore: z.number().min(0).max(1),
holdScore: z.number().min(0).max(1),
disperseScore: z.number().min(0).max(1),
urgentSpeedKeep: z.number().min(0).max(1),
hullAngleDeg: z.number().min(0).max(45),
faceToleranceDeg: z.number().min(3).max(60),
faceMinDanger: z.number().min(0).max(2),
faceHaltLimitDeg: z.number().min(10).max(180),
reverseTravelAngleDeg: z.number().min(60).max(180),
reverseMaxGoalDistM: z.number().min(0).max(2000),
reverseMinSpeedMps: z.number().min(0.5).max(10),
reverseHoldSec: z.number().min(0).max(20),
});
const GroundAiEstimationSchema = z.object({
watchMinSec: z.number().min(0.5).max(10),
watchMaxSec: z.number().min(1).max(15),
@@ -250,10 +272,6 @@ const GroundAiFireControlSchema = z.object({
closeRangeM: z.number().min(30).max(250),
midRangeM: z.number().min(100).max(600),
longRangeM: z.number().min(300).max(1500),
midSlowSpeedRatio: z.number().min(0.1).max(1),
midSlowMaxMps: z.number().min(1).max(15),
closeRangeMaxSpeedKmh: z.number().min(3.6).max(100),
pointBlankMaxSpeedKmh: z.number().min(3.6).max(100),
stopSpeedMaxMps: z.number().min(0.1).max(2),
longRangeWindowSec: z.number().min(1).max(15),
baseAlignDeg: z.number().min(0.1).max(3),
@@ -320,6 +338,7 @@ export const GroundAiTuningSchema = z.object({
estimation: GroundAiEstimationSchema,
threat: GroundAiThreatSchema,
turret: GroundAiTurretSchema,
behavior: GroundAiBehaviorSchema,
fireControl: GroundAiFireControlSchema,
diagnostics: GroundAiDiagnosticsSchema,
});
@@ -344,6 +363,7 @@ export const GroundAiTuningPatchSchema = z.object({
estimation: GroundAiEstimationSchema.partial().optional(),
threat: GroundAiThreatSchema.partial().optional(),
turret: GroundAiTurretSchema.partial().optional(),
behavior: GroundAiBehaviorSchema.partial().optional(),
fireControl: GroundAiFireControlSchema.partial().optional(),
diagnostics: GroundAiDiagnosticsSchema.partial().optional(),
});
+30 -14
View File
@@ -59,6 +59,7 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning {
estimation: readEstimationSection(reader.object('estimation')),
threat: readThreatSection(reader.object('threat')),
turret: readTurretSection(reader.object('turret')),
behavior: readBehaviorSection(reader.object('behavior')),
fireControl: readFireControlSection(reader.object('fireControl')),
diagnostics: {
telemetry: diag.bool('telemetry'),
@@ -325,17 +326,12 @@ function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine
throw new TuningError('tuning file ground-ai.jsonc: stateMachine.coverMaxDistM must be > coverMinDistM');
}
return {
preaimAngleDeg: sm.number('preaimAngleDeg', { min: 1.0, max: 30.0 }),
movingShotWaitSec: sm.number('movingShotWaitSec', { min: 0.25, max: 5.0 }),
shortHaltMaxSec: sm.number('shortHaltMaxSec', { min: 0.5, max: 12.0 }),
shortHaltCooldownSec: sm.number('shortHaltCooldownSec', { min: 0.5, max: 20.0 }),
turnLaunchSpeedMps: sm.number('turnLaunchSpeedMps', { min: 0.5, max: 6.0 }),
coverMinDistM,
coverMaxDistM,
coverRetreatBudgetSec: sm.number('coverRetreatBudgetSec', { min: 1.5, max: 20.0 }),
reloadAdvanceAngleDeg: sm.number('reloadAdvanceAngleDeg', { min: 0.0, max: 45.0 }),
hullAngleTriggerDeg: sm.number('hullAngleTriggerDeg', { min: 15.0, max: 75.0 }),
hullAngleTargetDeg: sm.number('hullAngleTargetDeg', { min: 0.0, max: 35.0 }),
maxTotalHaltSec: sm.number('maxTotalHaltSec', { min: 3.0, max: 40.0 }),
stalemateMissShots: sm.int('stalemateMissShots', { min: 1, max: 8 }),
stalemateNoShotHalts: sm.int('stalemateNoShotHalts', { min: 1, max: 6 }),
@@ -378,6 +374,35 @@ function readTurretSection(turret: TuningReader): GroundAiTuning['turret'] {
};
}
function readBehaviorSection(bhv: TuningReader): GroundAiTuning['behavior'] {
return {
scoreIntervalSec: bhv.number('scoreIntervalSec', { min: 0.1, max: 3 }),
minHoldSec: bhv.number('minHoldSec', { min: 0, max: 10 }),
switchMargin: bhv.number('switchMargin', { min: 0, max: 1 }),
advanceScore: bhv.number('advanceScore', { min: 0, max: 1 }),
engageScore: bhv.number('engageScore', { min: 0, max: 1 }),
urgencyWeight: bhv.number('urgencyWeight', { min: 0, max: 1 }),
haltScore: bhv.number('haltScore', { min: 0, max: 1 }),
crossfirePenalty: bhv.number('crossfirePenalty', { min: 0, max: 1 }),
coverScore: bhv.number('coverScore', { min: 0, max: 1 }),
coverDangerWeight: bhv.number('coverDangerWeight', { min: 0, max: 1 }),
coverOffensivePenalty: bhv.number('coverOffensivePenalty', { min: 0, max: 1 }),
coverRetrySec: bhv.number('coverRetrySec', { min: 0.5, max: 30 }),
repositionScore: bhv.number('repositionScore', { min: 0, max: 1 }),
holdScore: bhv.number('holdScore', { min: 0, max: 1 }),
disperseScore: bhv.number('disperseScore', { min: 0, max: 1 }),
urgentSpeedKeep: bhv.number('urgentSpeedKeep', { min: 0, max: 1 }),
hullAngleDeg: bhv.number('hullAngleDeg', { min: 0, max: 45 }),
faceToleranceDeg: bhv.number('faceToleranceDeg', { min: 3, max: 60 }),
faceMinDanger: bhv.number('faceMinDanger', { min: 0, max: 2 }),
faceHaltLimitDeg: bhv.number('faceHaltLimitDeg', { min: 10, max: 180 }),
reverseTravelAngleDeg: bhv.number('reverseTravelAngleDeg', { min: 60, max: 180 }),
reverseMaxGoalDistM: bhv.number('reverseMaxGoalDistM', { min: 0, max: 2000 }),
reverseMinSpeedMps: bhv.number('reverseMinSpeedMps', { min: 0.5, max: 10 }),
reverseHoldSec: bhv.number('reverseHoldSec', { min: 0, max: 20 }),
};
}
function readEstimationSection(est: TuningReader): GroundAiTuning['estimation'] {
const watchMinSec = est.number('watchMinSec', { min: 0.5, max: 10.0 });
const watchMaxSec = est.number('watchMaxSec', { min: 1.0, max: 15.0 });
@@ -408,11 +433,6 @@ function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl']
if (midRangeM <= closeRangeM || longRangeM <= midRangeM) {
throw new TuningError('tuning file ground-ai.jsonc: fireControl ranges must satisfy closeRangeM < midRangeM < longRangeM');
}
const closeRangeMaxSpeedKmh = fc.number('closeRangeMaxSpeedKmh', { min: 3.6, max: 100 });
const pointBlankMaxSpeedKmh = fc.number('pointBlankMaxSpeedKmh', { min: 3.6, max: 100 });
if (pointBlankMaxSpeedKmh < closeRangeMaxSpeedKmh) {
throw new TuningError('tuning file ground-ai.jsonc: fireControl.pointBlankMaxSpeedKmh must be >= closeRangeMaxSpeedKmh');
}
const fireThreshold = fc.number('fireThreshold', { min: 0.05, max: 0.95 });
const minFireThreshold = fc.number('minFireThreshold', { min: 0.01, max: 0.9 });
if (minFireThreshold > fireThreshold) {
@@ -423,10 +443,6 @@ function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl']
closeRangeM,
midRangeM,
longRangeM,
midSlowSpeedRatio: fc.number('midSlowSpeedRatio', { min: 0.1, max: 1.0 }),
midSlowMaxMps: fc.number('midSlowMaxMps', { min: 1.0, max: 15.0 }),
closeRangeMaxSpeedKmh,
pointBlankMaxSpeedKmh,
stopSpeedMaxMps: fc.number('stopSpeedMaxMps', { min: 0.1, max: 2.0 }),
longRangeWindowSec: fc.number('longRangeWindowSec', { min: 1.0, max: 15.0 }),
baseAlignDeg: fc.number('baseAlignDeg', { min: 0.1, max: 3.0 }),
+43 -11
View File
@@ -282,20 +282,14 @@
"discoverScore": 0.35
},
// Per-bot hull state machine timings and thresholds (offline values).
// Timings and thresholds of the hull actions (short halt, cover pull-back, reposition, repair).
"stateMachine": {
"preaimAngleDeg": 8.0,
// Time a ready gun can be held up by speed or aim before attempting a short halt.
"movingShotWaitSec": 1.0,
"shortHaltMaxSec": 3.0,
"shortHaltCooldownSec": 4.0,
"turnLaunchSpeedMps": 2.1,
"coverMinDistM": 6.0,
"coverMaxDistM": 24.0,
"coverRetreatBudgetSec": 6.0,
"reloadAdvanceAngleDeg": 18.0,
"hullAngleTriggerDeg": 20.0,
"hullAngleTargetDeg": 10.0,
"maxTotalHaltSec": 12.0,
"stalemateMissShots": 2,
"stalemateNoShotHalts": 2,
@@ -352,6 +346,48 @@
"scanPeriodSec": 6.0
},
// Hull channel (decision layer design, section 7). Every scoreIntervalSec (at once when a target
// appears or is lost, a reload starts or ends, or the bot is hit) each behavior gets a score and
// the best runs; a running one is kept for minHoldSec, then until another scores switchMargin
// more. Scores: advance (no target in sight), engage (target in sight; +urgencyWeight when the
// order is urgent), halt (the trigger asks to stand for its shot; +urgencyWeight when not urgent,
// -crossfirePenalty per extra enemy aiming at the bot), cover (reloading with a known threat;
// +coverDangerWeight x danger, -coverOffensivePenalty on an urgent attack, not again for
// coverRetrySec after no cover was found), reposition (engagement stuck), hold (at the post,
// watching the last exit, waiting at the rally point) and disperse (crowded). Engaging on the
// move slows to the speed the trigger asks for; an urgent order keeps urgentSpeedKeep of the
// march speed. Medium and heavy tanks and tank destroyers face the most dangerous threat (danger
// at least faceMinDanger) angled by hullAngleDeg: holding within faceToleranceDeg, on a short halt
// only when more than faceHaltLimitDeg off. With that threat more than reverseTravelAngleDeg off
// the direction of travel and the goal within reverseMaxGoalDistM, a vehicle reversing at least
// reverseMinSpeedMps drives its route backwards; it switches at most every reverseHoldSec.
"behavior": {
"scoreIntervalSec": 0.5,
"minHoldSec": 1.5,
"switchMargin": 0.15,
"advanceScore": 0.5,
"engageScore": 0.55,
"urgencyWeight": 0.15,
"haltScore": 0.55,
"crossfirePenalty": 0.15,
"coverScore": 0.45,
"coverDangerWeight": 0.25,
"coverOffensivePenalty": 0.2,
"coverRetrySec": 4.0,
"repositionScore": 0.7,
"holdScore": 0.6,
"disperseScore": 0.62,
"urgentSpeedKeep": 0.5,
"hullAngleDeg": 20.0,
"faceToleranceDeg": 15.0,
"faceMinDanger": 0.15,
"faceHaltLimitDeg": 60.0,
"reverseTravelAngleDeg": 110.0,
"reverseMaxGoalDistM": 200.0,
"reverseMinSpeedMps": 2.5,
"reverseHoldSec": 3.0
},
// Fire permission (decision layer design, section 6). A main-gun shot needs its estimated hit
// probability to reach the fire threshold. The hit probability compares the visible part of the
// target (its projected width, targetHalfHeightM high, shrunk when only part of it is visible)
@@ -369,10 +405,6 @@
"closeRangeM": 100.0,
"midRangeM": 300.0,
"longRangeM": 800.0,
"midSlowSpeedRatio": 0.45,
"midSlowMaxMps": 5.5,
"closeRangeMaxSpeedKmh": 30.0,
"pointBlankMaxSpeedKmh": 35.0,
// At or below this speed the bot counts as standing (also the answer "stop" to a speed request).
"stopSpeedMaxMps": 0.45,
"longRangeWindowSec": 4.0,
+203
View File
@@ -0,0 +1,203 @@
// Hull channel behavior choice (decision layer design, 7.2): every behavior gets a 0-1 score from
// the order, the threat table, the bot's own state and the other channels' requests; the best one
// runs. A chosen behavior is kept for at least behavior.minHoldSec and afterwards until another
// scores behavior.switchMargin higher, unless it ends by itself or can no longer run. Scoring
// happens every behavior.scoreIntervalSec and at once when a target comes into sight or is lost,
// a reload starts or ends, or the bot is hit (a hit also lifts the minimum hold).
options indenting = 2
options no_global_heap = true
module wto_ai_behavior_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_order_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
// What one tactics tick knows, built once (wto_ai_tactics_common.das) and read by the scores and
// the behaviors. threatPos: the most dangerous known threat, else the remembered target, else the
// order goal. haltWanted: the trigger channel asks to stand for its shot.
[safe_when_uninitialized]
struct public WtoBhvCtx
hasTarget : bool = false
distTarget : float = 9999.0
remembered : bool = false
threatPos : float3 = float3(0.0, 0.0, 0.0)
threatDir : float3 = float3(1.0, 0.0, 0.0)
topDanger : float = 0.0
aimingCount : int = 0
baseGoal : float3 = float3(0.0, 0.0, 0.0)
distGoal : float = 0.0
atGoal : bool = false
urgent : bool = false
offensive : bool = false
haltWanted : bool = false
stopRangeOk : bool = false
stale : bool = false
crowded : bool = false
holdReason : int = 0
// Why HOLD applies (holdReason): at the order's post, watching where the target vanished, or
// waiting at the rally point for the group.
let public WTO_HOLD_NONE = 0
let public WTO_HOLD_POST = 1
let public WTO_HOLD_WATCH = 2
let public WTO_HOLD_RALLY = 3
// The order allows standing for a shot at this distance (beyond longRangeM only after a long
// enough clear look at a target showing at least two sample points).
def private wto_bhv_stop_range_ok(distXZ : float; slot : WtoBotSlot const&) : bool
let maxStop = slot.order.valid ? slot.order.maxStopRangeM : WTO_AI_FC_MAX_RANGE_M
if distXZ > min(maxStop, WTO_AI_FC_MAX_RANGE_M)
return false
return (distXZ <= WTO_AI_FC_LONG_RANGE_M ||
(slot.perceive.goodLosSec >= WTO_AI_FC_LONG_WINDOW_SEC && slot.perceive.visiblePointCount >= 2))
def private wto_bhv_hold_reason(now : float; myPos : float3; c : WtoBhvCtx const&; slot : WtoBotSlot const&) : int
if c.atGoal
return WTO_HOLD_POST
// A defending or watching bot near its post keeps watching the target's last exit for a while.
if !c.hasTarget && now < slot.perceive.watchUntil && slot.order.urgency != WTO_URGENCY_HIGH && c.distGoal <= 35.0
return WTO_HOLD_WATCH
// Wait at the rally point until the group sets off, unless a target is in sight within midRangeM.
if slot.order.rallyHold && slot.order.routeRelayValid && c.distTarget > WTO_AI_FC_MID_RANGE_M
let rallyHoldRad = max(18.0, WTO_AI_CMD_RALLY_RADIUS_M * 0.55)
if wto_xz_dist_sq(myPos, slot.order.routeRelayPos) <= rallyHoldRad * rallyHoldRad
return WTO_HOLD_RALLY
return WTO_HOLD_NONE
// Builds the tick's context. `stale` comes from the action layer (engagement stuck).
[never_inline]
def public wto_bhv_context(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; stale : bool;
slot : WtoBotSlot const&; var c : WtoBhvCtx&)
assume p = slot.perceive
c.baseGoal = slot.order.valid ? slot.order.goalPos : world.battleCenter
c.distGoal = sqrt(wto_xz_dist_sq(myPos, c.baseGoal))
c.atGoal = c.distGoal <= 8.0
c.hasTarget = p.hasClearLos && !!p.targetEid && !p.targetIsAir
c.distTarget = c.hasTarget ? sqrt(wto_xz_dist_sq(myPos, p.knownPos)) : 9999.0
c.remembered = !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
c.threatPos = c.remembered ? p.knownPos : c.baseGoal
let top = slot.threat.topIdx
if top >= 0
c.threatPos = slot.threat.entries[top].pos
c.topDanger = slot.threat.entries[top].danger
c.threatDir = wto_xz_normalize(c.threatPos - myPos, hullFwd)
for i in range(slot.threat.count)
if slot.threat.entries[i].aiming && slot.threat.entries[i].seesMe
c.aimingCount++
c.urgent = slot.order.urgency == WTO_URGENCY_HIGH || c.distGoal > 130.0
c.offensive = wto_order_is_offensive(slot.order.role)
assume tr = slot.trigger
c.haltWanted = (now - tr.wantSpeedAt) <= WTO_AI_TACTICS_TICK_SEC * 3.0 && tr.wantSpeedMps <= WTO_AI_FC_STOP_SPEED_MAX_MPS
c.stopRangeOk = c.hasTarget && wto_bhv_stop_range_ok(c.distTarget, slot)
c.stale = stale
c.crowded = slot.crowd.isCrowded
c.holdReason = wto_bhv_hold_reason(now, myPos, c, slot)
def private wto_bhv_name(bhv : int) : string
if bhv == WTO_BHV_ADVANCE
return "advance"
if bhv == WTO_BHV_ENGAGE
return "engage"
if bhv == WTO_BHV_HALT
return "halt"
if bhv == WTO_BHV_COVER
return "cover"
if bhv == WTO_BHV_REPOSITION
return "reposition"
if bhv == WTO_BHV_HOLD
return "hold"
if bhv == WTO_BHV_DISPERSE
return "disperse"
if bhv == WTO_BHV_WITHDRAW
return "withdraw"
return "repair"
[never_inline]
def private wto_bhv_scores(now : float; c : WtoBhvCtx const&; slot : WtoBotSlot const&; var s : float[9]&)
for i in range(WTO_BHV_COUNT)
s[i] = 0.0
let urgentF = c.urgent ? 1.0 : 0.0
if !c.atGoal
s[WTO_BHV_ADVANCE] = c.hasTarget ? 0.0 : WTO_AI_BHV_ADVANCE
s[WTO_BHV_ENGAGE] = c.hasTarget ? (WTO_AI_BHV_ENGAGE + WTO_AI_BHV_URGENCY_W * urgentF) : 0.0
if c.hasTarget && c.haltWanted && c.stopRangeOk && !c.atGoal && now >= slot.tactics.shortHaltCooldownUntil
let crossfire = float(max(0, c.aimingCount - 1))
s[WTO_BHV_HALT] = WTO_AI_BHV_HALT + WTO_AI_BHV_URGENCY_W * (1.0 - urgentF) - WTO_AI_BHV_CROSSFIRE * crossfire
let coverRetry = now - slot.tactics.coverFailedAt >= WTO_AI_BHV_COVER_RETRY_SEC
if slot.fire.reloading && (c.hasTarget || c.remembered) && !slot.spec.isAutocannonBelt && coverRetry
let pushing = c.offensive && c.urgent ? 1.0 : 0.0
s[WTO_BHV_COVER] = WTO_AI_BHV_COVER + WTO_AI_BHV_COVER_DANGER_W * min(1.0, c.topDanger) - WTO_AI_BHV_COVER_OFFENSIVE * pushing
if c.stale || slot.tactics.repositionActive
s[WTO_BHV_REPOSITION] = WTO_AI_BHV_REPOSITION
if c.holdReason != WTO_HOLD_NONE
s[WTO_BHV_HOLD] = WTO_AI_BHV_HOLD
if (c.crowded || now < slot.tactics.disperseUntil) && c.distTarget > WTO_AI_FC_CLOSE_RANGE_M
s[WTO_BHV_DISPERSE] = WTO_AI_BHV_DISPERSE
def private wto_bhv_best(s : float[9] const&; skip : int; var bestScore, secondScore : float&; var second : int&) : int
var best = WTO_BHV_ADVANCE
bestScore = -1.0
secondScore = -1.0
second = -1
for i in range(WTO_BHV_COUNT)
if i == skip
continue
if s[i] > bestScore
secondScore = bestScore
second = best
bestScore = s[i]
best = i
elif s[i] > secondScore
secondScore = s[i]
second = i
return best
// Scores now if due (or `force`, after the running behavior ended itself: it is then left out),
// and switches when the commitment allows it.
[never_inline]
def public wto_bhv_choose(now : float; c : WtoBhvCtx const&; force : bool; var slot : WtoBotSlot&)
assume tac = slot.tactics
let hit = slot.perceive.lastDamagedAt > tac.scoredDamageAt
let due = (force || hit || now >= tac.nextScoreAt || c.hasTarget != tac.scoredHasTarget ||
slot.fire.reloading != tac.scoredReloading)
if !due
return
tac.nextScoreAt = now + WTO_AI_BHV_SCORE_SEC
tac.scoredHasTarget = c.hasTarget
tac.scoredReloading = slot.fire.reloading
tac.scoredDamageAt = slot.perceive.lastDamagedAt
var s : float[9]
wto_bhv_scores(now, c, slot, s)
var bestScore = 0.0
var secondScore = 0.0
var second = -1
let best = wto_bhv_best(s, force ? tac.behavior : -1, bestScore, secondScore, second)
let cur = tac.behavior
let curScore = (cur >= 0 && cur < WTO_BHV_COUNT) ? s[cur] : 0.0
tac.behaviorScore = curScore
if best == cur || bestScore <= 0.0
return
let held = (now - tac.behaviorSince) < WTO_AI_BHV_MIN_HOLD_SEC && !hit
if !force && curScore > 0.0 && (held || bestScore < curScore + WTO_AI_BHV_SWITCH_MARGIN)
return
if WTO_AI_DIAG_TELEMETRY
let secondName = second >= 0 ? wto_bhv_name(second) : "-"
print("WTO_AI|BEHAVIOR|t={now}|eid={uint(slot.eid)}|from={wto_bhv_name(cur)}|to={wto_bhv_name(best)}|score={bestScore}|cur={curScore}|second={secondName}:{secondScore}|force={force}\n")
tac.behavior = best
tac.behaviorScore = bestScore
tac.behaviorSince = now
// A behavior that is not scored (repair, ridge withdrawal) took over this tick.
def public wto_bhv_take_over(now : float; bhv : int; var slot : WtoBotSlot&)
assume tac = slot.tactics
if tac.behavior != bhv
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|BEHAVIOR|t={now}|eid={uint(slot.eid)}|from={wto_bhv_name(tac.behavior)}|to={wto_bhv_name(bhv)}|score=1|cur=0|second=-:0|force=true\n")
tac.behavior = bhv
tac.behaviorSince = now
tac.behaviorScore = 1.0
tac.nextScoreAt = now
+83
View File
@@ -0,0 +1,83 @@
// Facing constraint of the hull channel (decision layer design, 7.3). Until penetration can be
// estimated, medium tanks, heavy tanks and tank destroyers turn the front toward the most dangerous
// known threat, angled by behavior.hullAngleDeg to the side nearer the current heading; light
// vehicles and SPAA are not bound. A target outside the gun's traverse overrides this for every
// vehicle (the hull turns the gun onto it). While advancing toward a nearby goal with the threat
// behind the direction of travel, the bot drives the route backwards instead of showing its rear.
options indenting = 2
options no_global_heap = true
module wto_ai_facing_common shared
require ecs
require math
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_nav_types_common
def private wto_face_bound_role(role : int) : bool
return role == WTO_ROLE_MEDIUM || role == WTO_ROLE_HEAVY || role == WTO_ROLE_TD
def private wto_face_rotate(dir : float3; rad : float) : float3
return float3(dir.x * cos(rad) - dir.z * sin(rad), 0.0, dir.x * sin(rad) + dir.z * cos(rad))
// `toThreat` turned by hullAngleDeg toward whichever side is nearer the current hull heading.
def private wto_face_angled(toThreat, hullFwd : float3) : float3
let rad = WTO_AI_BHV_HULL_ANGLE_DEG * WTO_DEG_TO_RAD
let a = wto_face_rotate(toThreat, rad)
let b = wto_face_rotate(toThreat, -rad)
return dot(a, hullFwd) >= dot(b, hullFwd) ? a : b
// Where the threat to face is: the most dangerous entry of the threat table above
// behavior.faceMinDanger, else the engaged target while remembered.
def private wto_face_threat_pos(now : float; slot : WtoBotSlot const&; var outPos : float3&) : bool
let top = slot.threat.topIdx
if top >= 0 && slot.threat.entries[top].danger >= WTO_AI_BHV_FACE_MIN_DANGER
outPos = slot.threat.entries[top].pos
return true
assume p = slot.perceive
if !!p.targetEid && !p.targetIsAir && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
outPos = p.knownPos
return true
return false
// Per tactics tick, before the behaviors run.
[never_inline]
def public wto_face_update(now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&)
assume tac = slot.tactics
tac.faceActive = false
tac.faceFromThreat = false
if !!slot.fire.hullAimTarget && slot.fire.hullAimTarget == slot.perceive.targetEid
tac.faceDir = wto_xz_normalize(slot.fire.hullAimDir, hullFwd)
tac.faceActive = true
return
var threatPos = myPos
if !wto_face_bound_role(slot.spec.role) || !wto_face_threat_pos(now, slot, threatPos)
return
tac.faceThreatDir = wto_xz_normalize(threatPos - myPos, hullFwd)
tac.faceDir = wto_face_angled(tac.faceThreatDir, hullFwd)
tac.faceActive = true
tac.faceFromThreat = true
// Whether to drive the route backwards this tick (advancing or engaging toward a goal within
// behavior.reverseMaxGoalDistM with the faced threat more than reverseTravelAngleDeg off the
// direction of travel). A decision is kept for at least behavior.reverseHoldSec.
[never_inline]
def public wto_face_reverse_update(now, distGoal : float; var slot : WtoBotSlot&)
assume tac = slot.tactics
let moving = tac.behavior == WTO_BHV_ADVANCE || tac.behavior == WTO_BHV_ENGAGE
let able = slot.spec.vMaxRev >= WTO_AI_BHV_REVERSE_MIN_MPS && !slot.tactics.immobilized
var want = moving && able && tac.faceFromThreat && distGoal <= WTO_AI_BHV_REVERSE_MAX_GOAL_M
if want
let travel = wto_xz_normalize(slot.nav.steerDir, tac.faceThreatDir)
let offDeg = acos(clamp(dot(travel, tac.faceThreatDir), -1.0, 1.0)) * WTO_RAD_TO_DEG
want = offDeg >= WTO_AI_BHV_REVERSE_ANGLE_DEG
if want == tac.reverseTravel
return
if (now - tac.reverseSince) < WTO_AI_BHV_REVERSE_HOLD_SEC && moving
return
tac.reverseTravel = want
tac.reverseSince = now
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|REVERSE_TRAVEL|t={now}|eid={uint(slot.eid)}|on={want}|goal={distGoal}\n")
@@ -1,19 +0,0 @@
// Shared speed limit for the movement command and the shot permission check.
options indenting = 2
options no_global_heap = true
module wto_ai_fire_speed_common shared
require math
require %appGame.wtoai.wto_ai_config_common
def public wto_fire_speed_limit_mps(distXZ, maxFwdMps : float) : float
let stop = WTO_AI_FC_STOP_SPEED_MAX_MPS
if distXZ > WTO_AI_FC_MID_RANGE_M
return stop
let close = max(stop, min(maxFwdMps, WTO_AI_FC_CLOSE_MAX_MPS))
let mid = clamp(min(maxFwdMps * WTO_AI_FC_MID_SLOW_RATIO, WTO_AI_FC_MID_SLOW_MAX_MPS), stop, close)
if distXZ <= WTO_AI_FC_CLOSE_RANGE_M
let pointBlank = max(close, min(maxFwdMps, WTO_AI_FC_POINT_BLANK_MAX_MPS))
return lerp(pointBlank, close, distXZ / WTO_AI_FC_CLOSE_RANGE_M)
let frac = (distXZ - WTO_AI_FC_CLOSE_RANGE_M) / (WTO_AI_FC_MID_RANGE_M - WTO_AI_FC_CLOSE_RANGE_M)
return lerp(close, mid, frac)
+15 -2
View File
@@ -1,6 +1,6 @@
// Pure-pursuit path following on a bot's corridor: where the bot is along it, the lookahead point
// it steers at, and how fast it may go so it slows down before sharp corners and its destination
// instead of braking at the wall.
// it steers at, how fast it may go so it slows down before sharp corners and its destination
// instead of braking at the wall, and whether it drives forwards or backwards along it.
options indenting = 2
options no_global_heap = true
module wto_ai_follow_common shared
@@ -23,6 +23,19 @@ def public wto_drive_cmd_set(var cmd : WtoDriveCmd&; mode : int; targetPos, desi
cmd.frontClearM = frontClr
cmd.rearClearM = rearClr
// Drive mode for travelling along `dir` (decision layer design, 7.3). Forward: cruise, or pivot
// for a sharp turn. Reverse route following: the rear leads along `dir` and the front stays
// toward the threat; for a sharp turn the hull first pivots until its rear points along `dir`.
def public wto_follow_drive_mode(dir, hullFwd : float3; reverse : bool; var outDir : float3&) : int
let lead = reverse ? -hullFwd : hullFwd
let turnDeg = acos(clamp(dot(dir, lead), -1.0, 1.0)) * WTO_RAD_TO_DEG
outDir = dir
if turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG
if reverse
outDir = -dir
return WTO_DRIVE_PIVOT
return reverse ? WTO_DRIVE_REVERSE : WTO_DRIVE_CRUISE
// Moves the bot's place on its corridor forward and records its XZ distance from the corridor.
[never_inline]
def public wto_follow_track(myPos : float3; var rt : WtoRouteState&)
+33 -12
View File
@@ -1,6 +1,7 @@
// Navigation layer of one bot per nav tick: turns the tactics goal into a drive command.
// Stationary and hull-angle states hold or pivot in place; tactical withdrawals and unstick
// manoeuvres back up along checked ground; otherwise the bot follows its corridor (route) with a
// Stationary states hold, or pivot in place toward the facing direction of the hull channel;
// tactical withdrawals and unstick manoeuvres back up along checked ground; a bot keeping its front
// toward a threat drives its corridor backwards; otherwise the bot follows its corridor (route) with a
// lookahead point it can reach in a straight line (follow), passes or follows vehicles and wrecks
// (traffic), slows for corners, narrow passages and fresh obstacles (avoid), backs off at once
// when pressed against a vehicle, and escalates when it stops making progress (unstick).
@@ -36,7 +37,9 @@ def private wto_nav_halt(myPos, hullFwd : float3; var slot : WtoBotSlot&)
[never_inline]
def private wto_try_hull_aim(myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool
let state = slot.tactics.state
if state != WTO_STATE_MARCH && state != WTO_STATE_RUN_AND_GUN && state != WTO_STATE_PREAIM && state != WTO_STATE_SHORT_HALT
let allowed = (state == WTO_STATE_MARCH || state == WTO_STATE_RUN_AND_GUN || state == WTO_STATE_PREAIM ||
state == WTO_STATE_SHORT_HALT || state == WTO_STATE_HULL_ANGLE)
if !allowed
return false
if !slot.fire.hullAimTarget || slot.fire.hullAimTarget != slot.perceive.targetEid || slot.tactics.immobilized
return false
@@ -51,12 +54,23 @@ def private wto_try_hull_aim(myPos, hullFwd : float3; var slot : WtoBotSlot&) :
def private wto_nav_hull_angle(myPos, hullFwd : float3; var slot : WtoBotSlot&)
let wishAngle = wto_xz_normalize(slot.tactics.hullAngleDir, hullFwd)
let angErr = acos(clamp(dot(wishAngle, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG
if angErr > 8.0
if angErr > WTO_AI_BHV_FACE_TOL_DEG
slot.nav.stuckCheckAt = -100.0
wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + wishAngle * 14.0, wishAngle, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
else
wto_nav_halt(myPos, hullFwd, slot)
// Standing for a shot or in cover: turn toward the facing direction (decision layer design, 7.3)
// only when the hull is more than limitDeg off it, else hold still.
[never_inline]
def private wto_nav_stand(myPos, hullFwd : float3; limitDeg : float; var slot : WtoBotSlot&)
assume tac = slot.tactics
if tac.faceActive && acos(clamp(dot(tac.faceDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG > limitDeg
slot.nav.stuckCheckAt = -100.0
wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + tac.faceDir * 14.0, tac.faceDir, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
return
wto_nav_halt(myPos, hullFwd, slot)
// Ridge withdrawal and backing into cover: reverse straight to the goal when the way is free.
[never_inline]
def private wto_nav_tactical_reverse(navState : int; myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool
@@ -154,10 +168,12 @@ def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : floa
wto_nav_halt(myPos, hullFwd, slot)
return
wto_follow_track(myPos, rt)
let reverse = slot.tactics.reverseTravel
let lead = reverse ? -hullFwd : hullFwd
let speedNow = abs(slot.drive.lastVFwd)
let lookM = wto_follow_lookahead(slot.spec, speedNow)
let pathTarget = wto_nav_visible_target(navState, myPos, lookM, slot)
let pathDir = wto_xz_normalize(pathTarget - myPos, hullFwd)
let pathDir = wto_xz_normalize(pathTarget - myPos, lead)
let narrow = slot.nav.wallDistM < WTO_AI_PF_NARROW_WALL_M || slot.nav.chokepoint
wto_traffic_update(world, navState, now, myPos, pathDir, speedNow, narrow, slot)
if wto_traffic_in_contact(now, slot.nav)
@@ -166,12 +182,14 @@ def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : floa
wto_nav_halt(myPos, hullFwd, slot)
return
let target = slot.nav.avoidActive ? slot.nav.avoidTarget : pathTarget
let dir = wto_xz_normalize(target - myPos, hullFwd)
let speed = wto_nav_speed(navState, now, myPos, dir, lookM, narrow, slot)
let dir = wto_xz_normalize(target - myPos, lead)
var speed = wto_nav_speed(navState, now, myPos, dir, lookM, narrow, slot)
if reverse
speed = min(speed, slot.spec.vMaxRev)
slot.nav.steerDir = dir
let turnDeg = acos(clamp(dot(dir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG
let mode = turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG ? WTO_DRIVE_PIVOT : WTO_DRIVE_CRUISE
wto_drive_cmd_set(slot.driveCmd, mode, target, dir, speed, slot.nav.frontClearM, slot.nav.rearClearM)
var cmdDir = dir
let mode = wto_follow_drive_mode(dir, hullFwd, reverse, cmdDir)
wto_drive_cmd_set(slot.driveCmd, mode, target, cmdDir, speed, slot.nav.frontClearM, slot.nav.rearClearM)
let movingIntent = slot.tactics.desiredSpeedMps > 1.2 && now >= slot.nav.yieldUntil
wto_unstick_watch(world, navState, now, myPos, hullFwd, myPos + dir * 6.0, movingIntent, slot)
@@ -186,12 +204,15 @@ def public wto_nav_update(var world : WtoWorldSnap&; navState, slotIdx : int; no
slot.nav.frontClearM = wto_terrain_hard_ray(probeBase, hullFwd, 24.0)
slot.nav.rearClearM = wto_terrain_hard_ray(probeBase, -hullFwd, 18.0)
let st = slot.tactics.state
if wto_try_hull_aim(myPos, hullFwd, slot)
return
if st == WTO_STATE_HULL_ANGLE
wto_nav_hull_angle(myPos, hullFwd, slot)
return
if wto_try_hull_aim(myPos, hullFwd, slot)
if st == WTO_STATE_SHORT_HALT || st == WTO_STATE_COVER_RELOAD
wto_nav_stand(myPos, hullFwd, st == WTO_STATE_SHORT_HALT ? WTO_AI_BHV_FACE_HALT_LIMIT_DEG : WTO_AI_BHV_FACE_TOL_DEG, slot)
return
if st == WTO_STATE_SHORT_HALT || st == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05
if slot.tactics.desiredSpeedMps <= 0.05
wto_nav_halt(myPos, hullFwd, slot)
return
if wto_nav_tactical_reverse(navState, myPos, hullFwd, slot) || wto_unstick_reversing(now, myPos, slot)
@@ -1,5 +1,6 @@
// Tactics action handlers: damage retreat & repair (plan 6.1), cover retreat & 3-way reload
// actions, and stalemate detection / reposition unlock.
// Hull channel actions (decision layer design, 7.1): damage retreat & repair (rebuild plan 6.1),
// cover pull-back while reloading, and stalemate detection / reposition. The behaviors in
// wto_ai_tactics_common.das run them.
options indenting = 2
options no_global_heap = true
module wto_ai_tactics_actions_common shared
@@ -116,42 +117,32 @@ def public wto_sm_continue_cover_retreat(world : WtoWorldSnap const&; now : floa
return false
return false
// Reloading under threat: pull back into remembered or nearby cover (6..24 m), backwards when the
// cover lies behind the hull. False when no cover is found.
[never_inline]
def public wto_sm_start_reload_action(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, threatPos, baseGoal : float3;
distXZ, distGoal : float; var slot : WtoBotSlot&) : bool
def public wto_sm_start_cover_retreat(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, threatPos : float3; distXZ : float;
var slot : WtoBotSlot&) : bool
assume tac = slot.tactics
// Option 1: pull back into remembered or nearby cover (6..24m).
var cov = myPos
if wto_cover_pick_candidate(world, now, myPos, threatPos, false, slot, cov)
let toCov = wto_xz_normalize(cov - myPos, -hullFwd)
let behindHull = dot(toCov, hullFwd) < -0.15
tac.retreatTarget = cov
tac.retreatUntil = now + WTO_AI_SM_COVER_RETREAT_SEC
tac.retreatReverse = behindHull && slot.nav.rearClearM > 3.2 && slot.spec.vMaxRev >= 2.0
let spd = tac.retreatReverse ? max(2.2, slot.spec.vMaxRev) : (slot.spec.vMaxFwd * 0.92)
wto_sm_set_state(now, WTO_STATE_RETREAT_COVER, cov, spd, "reload_pullback", distXZ, slot)
return true
// Option 2: no near cover and offensive/advancing -> zigzag push toward objective.
if wto_order_is_offensive(slot.order.role) || distGoal > 35.0
let toGoal = wto_xz_normalize(baseGoal - myPos, hullFwd)
let zigSign = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0
let ang = zigSign * WTO_AI_SM_RELOAD_ADV_DEG * WTO_DEG_TO_RAD
let zigDir = float3(toGoal.x * cos(ang) - toGoal.z * sin(ang), 0.0, toGoal.x * sin(ang) + toGoal.z * cos(ang))
let zigGoal = wto_clamp_battle_xz(myPos + zigDir * min(distGoal, 48.0), world.battleCenter, world.battleRadius, 35.0)
wto_sm_set_state(now, WTO_STATE_RELOAD_ADVANCE, zigGoal, slot.spec.vMaxFwd * 0.92, "reload_advance", distXZ, slot)
return true
// Option 3: defensive hold with side/rear exposed > 30 deg -> angle hull front +/-15 deg toward threat.
let toThreat = wto_xz_normalize(threatPos - myPos, hullFwd)
let exposureDeg = acos(clamp(dot(hullFwd, toThreat), -1.0, 1.0)) * WTO_RAD_TO_DEG
let hasPivotRoom = slot.nav.frontClearM >= slot.spec.halfLen + 1.5 && slot.nav.rearClearM >= slot.spec.halfLen + 1.2
if exposureDeg > WTO_AI_SM_HULL_ANGLE_TRIG_DEG && hasPivotRoom
let angSign = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0
let ang = angSign * WTO_AI_SM_HULL_ANGLE_TGT_DEG * WTO_DEG_TO_RAD
tac.hullAngleDir = float3(toThreat.x * cos(ang) - toThreat.z * sin(ang), 0.0, toThreat.x * sin(ang) + toThreat.z * cos(ang))
wto_sm_set_state(now, WTO_STATE_HULL_ANGLE, myPos, 0.0, "reload_angle_hull", distXZ, slot)
return true
return false
if !wto_cover_pick_candidate(world, now, myPos, threatPos, false, slot, cov)
return false
let toCov = wto_xz_normalize(cov - myPos, -hullFwd)
let behindHull = dot(toCov, hullFwd) < -0.15
tac.retreatTarget = cov
tac.retreatUntil = now + WTO_AI_SM_COVER_RETREAT_SEC
tac.retreatReverse = behindHull && slot.nav.rearClearM > 3.2 && slot.spec.vMaxRev >= 2.0
let spd = tac.retreatReverse ? max(2.2, slot.spec.vMaxRev) : (slot.spec.vMaxFwd * 0.92)
wto_sm_set_state(now, WTO_STATE_RETREAT_COVER, cov, spd, "reload_pullback", distXZ, slot)
return true
// The engagement is stuck: shots without effect, halts without a shot, or too long halted.
def public wto_sm_reposition_stale(now : float; slot : WtoBotSlot const&) : bool
assume tac = slot.tactics
let shotTimeoutOk = (now - slot.fire.lastShotAt) >= 1.2
let staleShots = tac.engageShotsNoEffect >= WTO_AI_SM_STALE_MISS_SHOTS && shotTimeoutOk
let staleHalts = tac.engageNoShotHalts >= WTO_AI_SM_STALE_NOSHOT_HALTS
return staleShots || staleHalts || tac.engageTotalHaltSec >= WTO_AI_SM_MAX_TOTAL_HALT_SEC
[never_inline]
def public wto_sm_handle_reposition(world : WtoWorldSnap const&; now : float;
@@ -170,11 +161,7 @@ def public wto_sm_handle_reposition(world : WtoWorldSnap const&; now : float;
wto_sm_set_state(now, WTO_STATE_REPOSITION, tac.repositionGoal, slot.spec.vMaxFwd * 0.92, "reposition_move", distXZ, slot)
return true
let shotTimeoutOk = (now - slot.fire.lastShotAt) >= 1.2
let staleShots = tac.engageShotsNoEffect >= WTO_AI_SM_STALE_MISS_SHOTS && shotTimeoutOk
let staleHalts = tac.engageNoShotHalts >= WTO_AI_SM_STALE_NOSHOT_HALTS
let staleTime = tac.engageTotalHaltSec >= WTO_AI_SM_MAX_TOTAL_HALT_SEC
if !staleShots && !staleHalts && !staleTime
if !wto_sm_reposition_stale(now, slot)
return false
let lat = float3(-threatDir.z, 0.0, threatDir.x)
let side = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0
@@ -191,5 +178,5 @@ def public wto_sm_handle_reposition(world : WtoWorldSnap const&; now : float;
tac.engageShotsNoEffect = 0
tac.engageNoShotHalts = 0
tac.engageTotalHaltSec = 0.0
wto_sm_set_state(now, WTO_STATE_REPOSITION, goal, slot.spec.vMaxFwd * 0.92, staleShots ? "stale_no_effect" : (staleHalts ? "stale_no_shot" : "stale_halt_time"), distXZ, slot)
wto_sm_set_state(now, WTO_STATE_REPOSITION, goal, slot.spec.vMaxFwd * 0.92, "stale_engagement", distXZ, slot)
return true
+98 -111
View File
@@ -1,6 +1,9 @@
// Per-bot hull state machine orchestrator: strict priority arbitration across safety/repair,
// active cover retreat, ridge withdrawal, stalemate reposition, short-halt budget, dispersion,
// 3-way reload actions, and distance-tier x task-order movement/shooting.
// Hull channel (decision layer design, section 7), once per tactics tick: damage/repair and ridge
// withdrawal take over at once; otherwise the behavior chosen by score (wto_ai_behavior_common.das)
// runs as a small action that sets the goal, speed and WTO_STATE_* for navigation. The facing
// constraint and the reverse-travel decision (wto_ai_facing_common.das) are updated every tick.
// A behavior that ends by itself (shot taken, cover reached and reloaded, no cover found) is
// replaced in the same tick.
options indenting = 2
options no_global_heap = true
module wto_ai_tactics_common shared
@@ -11,13 +14,14 @@ require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_order_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_fire_speed_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_nav_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_crowd_common
require %appGame.wtoai.wto_ai_cover_common
require %appGame.wtoai.wto_ai_tactics_actions_common
require %appGame.wtoai.wto_ai_behavior_common
require %appGame.wtoai.wto_ai_facing_common
[never_inline]
def private wto_sm_sync_engagement_counters(dt : float; var slot : WtoBotSlot&)
@@ -25,7 +29,6 @@ def private wto_sm_sync_engagement_counters(dt : float; var slot : WtoBotSlot&)
assume p = slot.perceive
if p.hasClearLos && !!p.targetEid && !p.targetIsAir && tac.engageTargetEid != p.targetEid
tac.engageTargetEid = p.targetEid
tac.movingShotBlockedSince = -100.0
tac.engageShotsNoEffect = 0
tac.engageNoShotHalts = 0
tac.engageTotalHaltSec = 0.0
@@ -64,49 +67,18 @@ def private wto_sm_handle_ridge(world : WtoWorldSnap const&; now : float;
return false
[never_inline]
def private wto_sm_stop_range_allowed(distXZ : float; slot : WtoBotSlot const&) : bool
let maxStop = slot.order.valid ? slot.order.maxStopRangeM : WTO_AI_FC_MAX_RANGE_M
if distXZ > min(maxStop, WTO_AI_FC_MAX_RANGE_M)
return false
return (distXZ <= WTO_AI_FC_LONG_RANGE_M ||
(slot.perceive.goodLosSec >= WTO_AI_FC_LONG_WINDOW_SEC && slot.perceive.visiblePointCount >= 2))
[never_inline]
def private wto_sm_continue_short_halt(now : float; myPos : float3; hasGroundTgt : bool;
distXZ : float; var slot : WtoBotSlot&) : bool
def private wto_tac_disperse(world : WtoWorldSnap const&; now : float; myPos : float3; c : WtoBhvCtx const&;
var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) : bool
assume tac = slot.tactics
if tac.state != WTO_STATE_SHORT_HALT
return false
if slot.fire.shotCount > tac.haltStartShots || slot.fire.reloading
if slot.fire.shotCount > tac.haltStartShots
tac.engageShotsNoEffect += slot.fire.shotCount - tac.haltStartShots
tac.haltStartShots = slot.fire.shotCount
return false
if !hasGroundTgt || !wto_sm_stop_range_allowed(distXZ, slot)
return false
if (now - tac.haltEnterAt) >= WTO_AI_SM_SHORT_HALT_MAX_SEC
tac.engageNoShotHalts++
tac.shortHaltCooldownUntil = now + WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC
return false
wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_continue", distXZ, slot)
return true
[never_inline]
def private wto_sm_handle_dispersion(world : WtoWorldSnap const&; now : float;
myPos, threatDir : float3; distXZ : float;
var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) : bool
assume tac = slot.tactics
if distXZ <= WTO_AI_FC_CLOSE_RANGE_M
return false
if now < tac.disperseUntil && wto_xz_dist_sq(myPos, tac.disperseGoal) > 25.0
wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_hold", distXZ, slot)
wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_hold", c.distTarget, slot)
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.disperseGoal = wto_crowd_pick_disperse_pos(world, slot.army, slot.eid, myPos, c.threatDir, slot.crowd)
tac.disperseUntil = now + WTO_AI_CROWD_DISPERSE_HOLD_SEC
crowdSummary.disperseEvents++
wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_start", distXZ, slot)
wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_start", c.distTarget, slot)
return true
[never_inline]
@@ -116,93 +88,108 @@ def private wto_sm_march_speed(slot : WtoBotSlot const&; distGoal : float) : flo
let capScale = slot.order.cautious ? 0.78 : 0.98
return distGoal < 24.0 ? min(slot.spec.vMaxFwd * 0.55, 6.0) : (slot.spec.vMaxFwd * capScale)
// Short halt (7.1): stand until the shot leaves, the reload starts, the target is gone or
// stateMachine.shortHaltMaxSec runs out; then a cooldown of shortHaltCooldownSec.
[never_inline]
def private wto_sm_waited_for_moving_shot(now : float; aimReady : bool; var slot : WtoBotSlot&) : bool
def private wto_tac_halt(now : float; myPos : float3; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool
assume tac = slot.tactics
let deny = slot.fire.lastDenyReason
let blocked = deny == WTO_DENY_HIT_PROB || deny == WTO_DENY_AIM_ERR || deny == WTO_DENY_SETTLE
if tac.state != WTO_STATE_RUN_AND_GUN || !aimReady || !blocked
tac.movingShotBlockedSince = -100.0
if tac.state != WTO_STATE_SHORT_HALT
wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_for_shot", c.distTarget, slot)
return true
let shots = slot.fire.shotCount - tac.haltStartShots
if shots > 0
tac.engageShotsNoEffect += shots
tac.haltStartShots = slot.fire.shotCount
let timeout = (now - tac.haltEnterAt) >= WTO_AI_SM_SHORT_HALT_MAX_SEC
if timeout && shots <= 0
tac.engageNoShotHalts++
if shots > 0 || timeout || slot.fire.reloading || !c.hasTarget || !c.stopRangeOk
tac.shortHaltCooldownUntil = now + WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC
return false
if tac.movingShotBlockedSince < tac.stateEnteredAt
tac.movingShotBlockedSince = now
return now - tac.movingShotBlockedSince >= WTO_AI_SM_MOVING_SHOT_WAIT_SEC
wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_hold", c.distTarget, slot)
return true
// Engaging on the move (7.1): along the route, as fast as the trigger channel's speed request
// allows; an urgent order keeps behavior.urgentSpeedKeep of the march speed regardless.
[never_inline]
def private wto_tac_engage(now : float; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool
let march = wto_sm_march_speed(slot, c.distGoal)
var speed = march
assume tr = slot.trigger
let fresh = (now - tr.wantSpeedAt) <= WTO_AI_TACTICS_TICK_SEC * 3.0
if fresh && tr.wantSpeedMps > WTO_AI_FC_STOP_SPEED_MAX_MPS && tr.wantSpeedMps < march
speed = lerp(tr.wantSpeedMps, march, c.urgent ? WTO_AI_BHV_URGENT_SPEED_KEEP : 0.0)
wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, c.baseGoal, speed, "engage", c.distTarget, slot)
return true
[never_inline]
def private wto_sm_handle_combat(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, threatPos, baseGoal : float3;
distXZ, distGoal : float; var slot : WtoBotSlot&) : bool
def private wto_tac_hold(now : float; myPos, hullFwd : float3; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool
assume tac = slot.tactics
assume fc = slot.fire
let marchSpd = wto_sm_march_speed(slot, distGoal)
if fc.reloading
return wto_sm_start_reload_action(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot)
let close = distXZ <= WTO_AI_FC_CLOSE_RANGE_M
let urgentPush = slot.order.urgency == WTO_URGENCY_HIGH || distGoal > 130.0
let canHalt = now >= tac.shortHaltCooldownUntil && !tac.repositionActive && wto_sm_stop_range_allowed(distXZ, slot)
let aimReady = (fc.gunReady && fc.aimTargetEid == slot.perceive.targetEid && fc.lastAimErrDeg <= WTO_AI_SM_PREAIM_DEG)
if marchSpd > 0.0 && (close || (distXZ <= WTO_AI_FC_MID_RANGE_M && urgentPush))
if wto_sm_waited_for_moving_shot(now, aimReady, slot) && canHalt
wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "moving_shot_halt", distXZ, slot)
else
let speed = min(marchSpd, wto_fire_speed_limit_mps(distXZ, slot.spec.vMaxFwd))
wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, baseGoal, speed, close ? "close_run_gun" : "mid_slow_fire", distXZ, slot)
tac.hullAngleDir = tac.faceActive ? tac.faceDir : hullFwd
let why = c.holdReason == WTO_HOLD_WATCH ? "watch_last_exit" : (c.holdReason == WTO_HOLD_RALLY ? "rally_wait" : "hold_post")
wto_sm_set_state(now, WTO_STATE_HULL_ANGLE, myPos, 0.0, why, c.distTarget, slot)
return c.holdReason != WTO_HOLD_NONE
[never_inline]
def private wto_tac_cover(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; c : WtoBhvCtx const&;
var slot : WtoBotSlot&) : bool
assume tac = slot.tactics
if tac.state == WTO_STATE_RETREAT_COVER || tac.state == WTO_STATE_COVER_RELOAD
return wto_sm_continue_cover_retreat(world, now, myPos, c.threatPos, c.distTarget, slot)
if wto_sm_start_cover_retreat(world, now, myPos, hullFwd, c.threatPos, c.distTarget, slot)
return true
if !canHalt
return false
if !aimReady
wto_sm_set_state(now, WTO_STATE_PREAIM, baseGoal, marchSpd, "preaim_move", distXZ, slot)
return true
wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "short_halt_ready", distXZ, slot)
tac.coverFailedAt = now
return false
[never_inline]
def private wto_tac_advance(now : float; myPos : float3; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool
let speed = wto_sm_march_speed(slot, c.distGoal)
wto_sm_set_state(now, WTO_STATE_MARCH, c.atGoal ? myPos : c.baseGoal, speed, "advance", c.distTarget, slot)
return true
// Runs the chosen behavior; false when it has ended or cannot run.
[never_inline]
def private wto_tac_run(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; c : WtoBhvCtx const&;
var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) : bool
let bhv = slot.tactics.behavior
if bhv == WTO_BHV_ENGAGE
return c.hasTarget && wto_tac_engage(now, c, slot)
if bhv == WTO_BHV_HALT
return wto_tac_halt(now, myPos, c, slot)
if bhv == WTO_BHV_COVER
return wto_tac_cover(world, now, myPos, hullFwd, c, slot)
if bhv == WTO_BHV_REPOSITION
return wto_sm_handle_reposition(world, now, myPos, c.threatDir, c.baseGoal, c.distTarget, slot)
if bhv == WTO_BHV_HOLD
return wto_tac_hold(now, myPos, hullFwd, c, slot)
if bhv == WTO_BHV_DISPERSE
return wto_tac_disperse(world, now, myPos, c, slot, crowdSummary)
if bhv == WTO_BHV_ADVANCE
return wto_tac_advance(now, myPos, c, slot)
return false
[never_inline]
def public wto_tactics_update(world : WtoWorldSnap const&; now, dt : float;
myPos, rawHullFwd : float3; isBurn : bool;
repairRemainingSec : float;
var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&)
let hullFwd = wto_xz_normalize(rawHullFwd, float3(1.0, 0.0, 0.0))
let baseGoal = slot.order.valid ? slot.order.goalPos : world.battleCenter
let distGoal = sqrt(wto_xz_dist_sq(myPos, baseGoal))
if !WTO_AI_LAYER_TACTICS
wto_sm_set_state(now, WTO_STATE_MARCH, slot.order.valid ? slot.order.goalPos : myPos, slot.spec.vMaxFwd * 0.9, "layer_off", 9999.0, slot)
return
assume p = slot.perceive
let hasGroundTgt = p.hasClearLos && !!p.targetEid && !p.targetIsAir
let distXZ = hasGroundTgt ? sqrt(wto_xz_dist_sq(myPos, p.knownPos)) : 9999.0
let threatPos = !!p.targetEid ? p.knownPos : baseGoal
let threatDir = wto_xz_normalize(threatPos - myPos, hullFwd)
var c = WtoBhvCtx()
wto_bhv_context(world, now, myPos, hullFwd, wto_sm_reposition_stale(now, slot), slot, c)
wto_sm_sync_engagement_counters(dt, slot)
wto_cover_update_memory(world, now, myPos, slot)
if wto_sm_handle_disabled_and_repair(world, now, myPos, threatPos, threatDir, isBurn, repairRemainingSec, distXZ, slot)
return
if wto_sm_continue_cover_retreat(world, now, myPos, threatPos, distXZ, slot)
return
if wto_sm_handle_ridge(world, now, myPos, threatDir, distXZ, slot)
return
if wto_sm_handle_reposition(world, now, myPos, threatDir, baseGoal, distXZ, slot)
return
if wto_sm_continue_short_halt(now, myPos, hasGroundTgt, distXZ, slot)
return
if wto_sm_handle_dispersion(world, now, myPos, threatDir, distXZ, slot, crowdSummary)
return
if hasGroundTgt && wto_sm_handle_combat(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot)
return
if slot.fire.reloading && !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
if wto_sm_start_reload_action(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot)
return
// Stationary overwatch/defend bots hold their firing post briefly to watch the enemy's last exit point;
// marching/pushing bots keep advancing while the turret watches.
if !hasGroundTgt && now < p.watchUntil && slot.order.urgency != WTO_URGENCY_HIGH && distGoal <= 35.0
wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "watch_last_exit", distXZ, slot)
return
// Hold at the 40% rally staging point until the group launches (unless threatened inside 300 m).
if slot.order.rallyHold && slot.order.routeRelayValid && distXZ > WTO_AI_FC_MID_RANGE_M
let rallyHoldRad = max(18.0, WTO_AI_CMD_RALLY_RADIUS_M * 0.55)
if wto_xz_dist_sq(myPos, slot.order.routeRelayPos) <= rallyHoldRad * rallyHoldRad
wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "rally_wait", distXZ, slot)
return
let marchSpd = wto_sm_march_speed(slot, distGoal)
let marchGoal = distGoal <= 8.0 ? myPos : baseGoal
wto_sm_set_state(now, WTO_STATE_MARCH, marchGoal, marchSpd, "march_task", distXZ, slot)
wto_face_update(now, myPos, hullFwd, slot)
if wto_sm_handle_disabled_and_repair(world, now, myPos, c.threatPos, c.threatDir, isBurn, repairRemainingSec, c.distTarget, slot)
wto_bhv_take_over(now, WTO_BHV_REPAIR, slot)
elif wto_sm_handle_ridge(world, now, myPos, c.threatDir, c.distTarget, slot)
wto_bhv_take_over(now, WTO_BHV_WITHDRAW, slot)
else
wto_bhv_choose(now, c, false, slot)
if !wto_tac_run(world, now, myPos, hullFwd, c, slot, crowdSummary)
wto_bhv_choose(now, c, true, slot)
if !wto_tac_run(world, now, myPos, hullFwd, c, slot, crowdSummary)
wto_tac_advance(now, myPos, c, slot)
wto_face_reverse_update(now, c.distGoal, slot)
+33
View File
@@ -35,6 +35,20 @@ let public WTO_STATE_DISABLED = 9
let public WTO_STATE_DISPERSE = 10
let public WTO_STATE_RIDGE_WITHDRAW = 11
// Hull channel behaviors (decision layer design, 7.1), chosen by score in
// wto_ai_behavior_common.das; each runs as one or more WTO_STATE_* actions. REPAIR and WITHDRAW
// are not scored: they take over at once.
let public WTO_BHV_ADVANCE = 0
let public WTO_BHV_ENGAGE = 1
let public WTO_BHV_HALT = 2
let public WTO_BHV_COVER = 3
let public WTO_BHV_REPOSITION = 4
let public WTO_BHV_HOLD = 5
let public WTO_BHV_DISPERSE = 6
let public WTO_BHV_WITHDRAW = 7
let public WTO_BHV_REPAIR = 8
let public WTO_BHV_COUNT = 9
let public WTO_DRIVE_HALT = 0
let public WTO_DRIVE_CRUISE = 1
let public WTO_DRIVE_PIVOT = 2
@@ -195,6 +209,25 @@ struct public WtoTacticsState
withdrawUntil : float = -100.0
disperseGoal : float3 = float3(0.0, 0.0, 0.0)
disperseUntil : float = -100.0
// Hull channel (decision layer design, section 7): the chosen behavior, its score, since when
// it runs, when to score again, and what the last scoring saw (a change scores at once).
behavior : int = 0
behaviorScore : float = 0.0
behaviorSince : float = -100.0
nextScoreAt : float = 0.0
scoredHasTarget : bool = false
scoredReloading : bool = false
scoredDamageAt : float = -100.0
coverFailedAt : float = -100.0
// Facing constraint (7.3): the hull should point along faceDir (within the facing tolerance)
// when it stands; threatDir is the threat it faces. reverseTravel: drive the route backwards
// to keep the front toward that threat, decided at reverseSince.
faceActive : bool = false
faceDir : float3 = float3(1.0, 0.0, 0.0)
faceThreatDir : float3 = float3(1.0, 0.0, 0.0)
faceFromThreat : bool = false
reverseTravel : bool = false
reverseSince : float = -100.0
[safe_when_uninitialized]
struct public WtoDriveCmd
@@ -205,17 +205,12 @@ export interface GroundAiConfig {
readonly discoverScore: number;
};
readonly stateMachine: {
readonly preaimAngleDeg: number;
readonly movingShotWaitSec: number;
readonly shortHaltMaxSec: number;
readonly shortHaltCooldownSec: number;
readonly turnLaunchSpeedMps: number;
readonly coverMinDistM: number;
readonly coverMaxDistM: number;
readonly coverRetreatBudgetSec: number;
readonly reloadAdvanceAngleDeg: number;
readonly hullAngleTriggerDeg: number;
readonly hullAngleTargetDeg: number;
readonly maxTotalHaltSec: number;
readonly stalemateMissShots: number;
readonly stalemateNoShotHalts: number;
@@ -257,15 +252,37 @@ export interface GroundAiConfig {
readonly scanArcDeg: number;
readonly scanPeriodSec: number;
};
readonly behavior: {
readonly scoreIntervalSec: number;
readonly minHoldSec: number;
readonly switchMargin: number;
readonly advanceScore: number;
readonly engageScore: number;
readonly urgencyWeight: number;
readonly haltScore: number;
readonly crossfirePenalty: number;
readonly coverScore: number;
readonly coverDangerWeight: number;
readonly coverOffensivePenalty: number;
readonly coverRetrySec: number;
readonly repositionScore: number;
readonly holdScore: number;
readonly disperseScore: number;
readonly urgentSpeedKeep: number;
readonly hullAngleDeg: number;
readonly faceToleranceDeg: number;
readonly faceMinDanger: number;
readonly faceHaltLimitDeg: number;
readonly reverseTravelAngleDeg: number;
readonly reverseMaxGoalDistM: number;
readonly reverseMinSpeedMps: number;
readonly reverseHoldSec: number;
};
readonly fireControl: {
readonly maxEngageRangeM: number;
readonly closeRangeM: number;
readonly midRangeM: number;
readonly longRangeM: number;
readonly midSlowSpeedRatio: number;
readonly midSlowMaxMps: number;
readonly closeRangeMaxSpeedKmh: number;
readonly pointBlankMaxSpeedKmh: number;
readonly stopSpeedMaxMps: number;
readonly longRangeWindowSec: number;
readonly baseAlignDeg: number;
@@ -440,17 +457,12 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] {
['WTO_AI_PERC_LOOK_AROUND_SEC', 'float', c.perception.lookAroundSec],
['WTO_AI_PERC_LOOK_AROUND_HOLD_SEC', 'float', c.perception.lookAroundHoldSec],
['WTO_AI_PERC_DISCOVER_SCORE', 'float', c.perception.discoverScore],
['WTO_AI_SM_PREAIM_DEG', 'float', c.stateMachine.preaimAngleDeg],
['WTO_AI_SM_MOVING_SHOT_WAIT_SEC', 'float', c.stateMachine.movingShotWaitSec],
['WTO_AI_SM_SHORT_HALT_MAX_SEC', 'float', c.stateMachine.shortHaltMaxSec],
['WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC', 'float', c.stateMachine.shortHaltCooldownSec],
['WTO_AI_SM_TURN_LAUNCH_MPS', 'float', c.stateMachine.turnLaunchSpeedMps],
['WTO_AI_SM_COVER_MIN_DIST_M', 'float', c.stateMachine.coverMinDistM],
['WTO_AI_SM_COVER_MAX_DIST_M', 'float', c.stateMachine.coverMaxDistM],
['WTO_AI_SM_COVER_RETREAT_SEC', 'float', c.stateMachine.coverRetreatBudgetSec],
['WTO_AI_SM_RELOAD_ADV_DEG', 'float', c.stateMachine.reloadAdvanceAngleDeg],
['WTO_AI_SM_HULL_ANGLE_TRIG_DEG', 'float', c.stateMachine.hullAngleTriggerDeg],
['WTO_AI_SM_HULL_ANGLE_TGT_DEG', 'float', c.stateMachine.hullAngleTargetDeg],
['WTO_AI_SM_MAX_TOTAL_HALT_SEC', 'float', c.stateMachine.maxTotalHaltSec],
['WTO_AI_SM_STALE_MISS_SHOTS', 'int', c.stateMachine.stalemateMissShots],
['WTO_AI_SM_STALE_NOSHOT_HALTS', 'int', c.stateMachine.stalemateNoShotHalts],
@@ -483,14 +495,34 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] {
['WTO_AI_TURRET_SWITCH_MARGIN', 'float', c.turret.switchMargin],
['WTO_AI_TURRET_SCAN_ARC_DEG', 'float', c.turret.scanArcDeg],
['WTO_AI_TURRET_SCAN_PERIOD_SEC', 'float', c.turret.scanPeriodSec],
['WTO_AI_BHV_SCORE_SEC', 'float', c.behavior.scoreIntervalSec],
['WTO_AI_BHV_MIN_HOLD_SEC', 'float', c.behavior.minHoldSec],
['WTO_AI_BHV_SWITCH_MARGIN', 'float', c.behavior.switchMargin],
['WTO_AI_BHV_ADVANCE', 'float', c.behavior.advanceScore],
['WTO_AI_BHV_ENGAGE', 'float', c.behavior.engageScore],
['WTO_AI_BHV_URGENCY_W', 'float', c.behavior.urgencyWeight],
['WTO_AI_BHV_HALT', 'float', c.behavior.haltScore],
['WTO_AI_BHV_CROSSFIRE', 'float', c.behavior.crossfirePenalty],
['WTO_AI_BHV_COVER', 'float', c.behavior.coverScore],
['WTO_AI_BHV_COVER_DANGER_W', 'float', c.behavior.coverDangerWeight],
['WTO_AI_BHV_COVER_OFFENSIVE', 'float', c.behavior.coverOffensivePenalty],
['WTO_AI_BHV_COVER_RETRY_SEC', 'float', c.behavior.coverRetrySec],
['WTO_AI_BHV_REPOSITION', 'float', c.behavior.repositionScore],
['WTO_AI_BHV_HOLD', 'float', c.behavior.holdScore],
['WTO_AI_BHV_DISPERSE', 'float', c.behavior.disperseScore],
['WTO_AI_BHV_URGENT_SPEED_KEEP', 'float', c.behavior.urgentSpeedKeep],
['WTO_AI_BHV_HULL_ANGLE_DEG', 'float', c.behavior.hullAngleDeg],
['WTO_AI_BHV_FACE_TOL_DEG', 'float', c.behavior.faceToleranceDeg],
['WTO_AI_BHV_FACE_MIN_DANGER', 'float', c.behavior.faceMinDanger],
['WTO_AI_BHV_FACE_HALT_LIMIT_DEG', 'float', c.behavior.faceHaltLimitDeg],
['WTO_AI_BHV_REVERSE_ANGLE_DEG', 'float', c.behavior.reverseTravelAngleDeg],
['WTO_AI_BHV_REVERSE_MAX_GOAL_M', 'float', c.behavior.reverseMaxGoalDistM],
['WTO_AI_BHV_REVERSE_MIN_MPS', 'float', c.behavior.reverseMinSpeedMps],
['WTO_AI_BHV_REVERSE_HOLD_SEC', 'float', c.behavior.reverseHoldSec],
['WTO_AI_FC_MAX_RANGE_M', 'float', c.fireControl.maxEngageRangeM],
['WTO_AI_FC_CLOSE_RANGE_M', 'float', c.fireControl.closeRangeM],
['WTO_AI_FC_MID_RANGE_M', 'float', c.fireControl.midRangeM],
['WTO_AI_FC_LONG_RANGE_M', 'float', c.fireControl.longRangeM],
['WTO_AI_FC_MID_SLOW_RATIO', 'float', c.fireControl.midSlowSpeedRatio],
['WTO_AI_FC_MID_SLOW_MAX_MPS', 'float', c.fireControl.midSlowMaxMps],
['WTO_AI_FC_CLOSE_MAX_MPS', 'float', c.fireControl.closeRangeMaxSpeedKmh / 3.6],
['WTO_AI_FC_POINT_BLANK_MAX_MPS', 'float', c.fireControl.pointBlankMaxSpeedKmh / 3.6],
['WTO_AI_FC_STOP_SPEED_MAX_MPS', 'float', c.fireControl.stopSpeedMaxMps],
['WTO_AI_FC_LONG_WINDOW_SEC', 'float', c.fireControl.longRangeWindowSec],
['WTO_AI_FC_BASE_ALIGN_DEG', 'float', c.fireControl.baseAlignDeg],