aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-14 22:19:00 +0300
committerValentin Popov <valentin@popov.link>2026-11-14 22:19:00 +0300
commit41ff7eec69baff620f97a636bd5a7709f7e27eb1 (patch)
treecbfe7e0c454f57e8038afc1d3d095b3191bf559a
parent16450724fa9d3052d315442a07b71e8d445c6cc3 (diff)
downloadfparkan-41ff7eec69baff620f97a636bd5a7709f7e27eb1.tar.xz
fparkan-41ff7eec69baff620f97a636bd5a7709f7e27eb1.zip
feat(ai): evaluate factory guards and threats to the base
Single.01 reaches the end of Problems0 and enters its building protection and construction jobs. Confirm radius boundaries, first-factory order, hero priority and duplicate exclusion via GOG ai.dll. Unavailable building upgrades log a stub and return no eligible target.
-rw-r--r--apps/fparkan-game/src/script_coverage.rs6
-rw-r--r--crates/fparkan-runtime/src/clan_ai_events.rs62
-rw-r--r--crates/fparkan-runtime/src/clan_targeting.rs174
-rw-r--r--crates/fparkan-runtime/src/lib.rs10
-rw-r--r--crates/fparkan-runtime/src/mission_events.rs2
-rw-r--r--docs/appendices/knowledge-boundaries.md7
-rw-r--r--docs/tomes/06-behavior.md13
7 files changed, 249 insertions, 25 deletions
diff --git a/apps/fparkan-game/src/script_coverage.rs b/apps/fparkan-game/src/script_coverage.rs
index 436ec426..82146541 100644
--- a/apps/fparkan-game/src/script_coverage.rs
+++ b/apps/fparkan-game/src/script_coverage.rs
@@ -27,6 +27,12 @@ pub(super) fn log_clan_ai_stops(report: &SimulationReport) {
for &(clan, count) in &report.script_attack_queries {
eprintln!("sim_coverage script_attack_target_approx={count} clan={clan}");
}
+ for &(clan, target, count) in &report.script_factory_defence_queries {
+ eprintln!("sim_coverage script_factory_defence_approx={count} clan={clan} target={target}");
+ }
+ for &(clan, target, count) in &report.script_base_threat_queries {
+ eprintln!("sim_coverage script_base_threat_approx={count} clan={clan} target={target}");
+ }
for &(clan, target, count) in &report.script_group_orders {
eprintln!("sim_coverage script_group_order_approx={count} clan={clan} target={target}");
}
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs
index 284a9bc8..f7841366 100644
--- a/crates/fparkan-runtime/src/clan_ai_events.rs
+++ b/crates/fparkan-runtime/src/clan_ai_events.rs
@@ -194,6 +194,8 @@ pub(super) struct ClanAiEvents {
strength_queries: BTreeMap<(usize, u16), u64>,
capture_queries: BTreeMap<usize, u64>,
attack_queries: BTreeMap<usize, u64>,
+ factory_defence_queries: BTreeMap<(usize, u32), u64>,
+ base_threat_queries: BTreeMap<(usize, u32), u64>,
base_radius_limits: BTreeMap<usize, f32>,
capturer_queries: BTreeMap<usize, u64>,
capture_orders: Vec<(OwnerId, Handler2RecordKey, CaptureApproach)>,
@@ -768,6 +770,54 @@ impl LoadedMissionState {
),
)))
}
+ ScriptDispatchSelector::Handler(58) => {
+ single_dword(&instruction.references, values)
+ .ok_or("Handler(58) requires a DWORD building index")?;
+ // shortcut: an unavailable upgrade catalog exposes no eligible buildings.
+ self.clan_ai_events.log_research_stub(clan, 58, &bundle.script_path);
+ Ok(Some(VarSetDefault::Dword(u32::MAX)))
+ }
+ ScriptDispatchSelector::Handler(handler @ (47 | 67)) => {
+ let (output, selection) = match (handler, instruction.references.as_slice()) {
+ (47, &[extension, output]) => {
+ let extension = values.get(extension as usize).and_then(|cell| cell.as_dword())
+ .ok_or("Handler(47) requires a DWORD extension of the base radius")?;
+ let selection = crate::clan_targeting::base_threat(
+ &self.mission, &self.object_drafts, &self.control_device_tables,
+ world, clan, extension,
+ self.clan_ai_events.base_radius_limits.get(&clan).copied().unwrap_or(700.0),
+ |id| self.clan_ai_events.problems.get(&clan).is_some_and(|queue| {
+ queue.records().iter().any(|record| record.key.word_0 == 12 && record.key.argument_0 == id)
+ }),
+ );
+ (output, selection)
+ }
+ (67, &[output]) => {
+ let units = self.mission_events.clan_units(world, OwnerId(clan as u16), false);
+ (output, crate::clan_targeting::factory_defence(world, &self.object_drafts, &self.control_device_tables, units))
+ }
+ _ => return Err("defence query requires a strength output".into()),
+ };
+ let cell = values.get_mut(output as usize)
+ .ok_or("defence query strength output is unavailable")?;
+ let (id, power) = selection.unwrap_or((u32::MAX, 0.0));
+ let power = crate::clan_targeting::encode_strength(power);
+ *cell = match *cell {
+ VarSetDefault::Dword(_) => VarSetDefault::Dword(power as u32),
+ VarSetDefault::FloatBits(_) => VarSetDefault::FloatBits(power.to_bits()),
+ };
+ let (queries, name) = if handler == 47 {
+ (&mut self.clan_ai_events.base_threat_queries, "script_base_threat_approx")
+ } else {
+ (&mut self.clan_ai_events.factory_defence_queries, "script_factory_defence_approx")
+ };
+ let count = queries.entry((clan, id)).or_default();
+ *count += 1;
+ if *count == 1 {
+ eprintln!("sim_coverage {name}=1 clan={clan} target={id} strength={power}");
+ }
+ Ok(Some(VarSetDefault::Dword(id)))
+ }
ScriptDispatchSelector::Handler(handler @ (56 | 65))
if instruction.references.is_empty() =>
{
@@ -976,6 +1026,18 @@ fn storage_space(ores: &[BehaviorOreState], world: &World, clan: OwnerId) -> f32
}
impl ClanAiEvents {
+ pub(super) fn base_threat_queries(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ {
+ self.base_threat_queries
+ .iter()
+ .map(|(&(clan, id), &count)| (clan, id, count))
+ }
+
+ pub(super) fn factory_defence_queries(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ {
+ self.factory_defence_queries
+ .iter()
+ .map(|(&(clan, id), &count)| (clan, id, count))
+ }
+
pub(super) fn wait_starts(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ {
self.wait_starts
.iter()
diff --git a/crates/fparkan-runtime/src/clan_targeting.rs b/crates/fparkan-runtime/src/clan_targeting.rs
index 909c14eb..e81af415 100644
--- a/crates/fparkan-runtime/src/clan_targeting.rs
+++ b/crates/fparkan-runtime/src/clan_targeting.rs
@@ -144,6 +144,48 @@ pub(super) fn encode_strength(strength: f32) -> f32 {
(strength as i64 as u32) as f32
}
+pub(super) fn factory_defence(
+ world: &World,
+ drafts: &[MissionObjectDraft],
+ controls: &[MissionControlDeviceTableState],
+ units: impl Iterator<Item = ObjectHandle> + Clone,
+) -> Option<(u32, f32)> {
+ let (id, position) = units.clone().find_map(|handle| {
+ let index = identity_metadata(world, handle).ok()?.original_id?.0 as usize;
+ let draft = drafts.get(index)?;
+ (draft.unit_dat_header_flags == Some(crate::autodemo::PLANT_CLASS)).then_some(())?;
+ Some((
+ draft.identity_or_clan_raw,
+ transform_state(world, handle)
+ .ok()?
+ .position
+ .map(f32::from_bits),
+ ))
+ })?;
+ // shortcut: sum from live Control tables until the ArealMap street records are available.
+ let guards = units.filter(|&handle| {
+ let mobile = identity_metadata(world, handle)
+ .ok()
+ .and_then(|identity| drafts.get(identity.original_id?.0 as usize))
+ .and_then(|draft| draft.unit_dat_header_flags)
+ .is_some_and(|class| class & crate::autodemo::MOBILE_UNIT != 0);
+ mobile
+ && transform_state(world, handle).is_ok_and(|pose| {
+ within_factory_radius(position, pose.position.map(f32::from_bits))
+ })
+ });
+ Some((
+ id,
+ guards
+ .map(|handle| unit_strength(controls, handle))
+ .fold(0.0, |sum, amount| sum + amount),
+ ))
+}
+
+fn within_factory_radius([x, y, _]: [f32; 3], [px, py, _]: [f32; 3]) -> bool {
+ (x - px).hypot(y - py) < 250.0
+}
+
pub(super) fn capture_target(
mission: &MissionDocument,
drafts: &[MissionObjectDraft],
@@ -174,28 +216,7 @@ pub(super) fn attack_target(
radius: f32,
base_radius_limit: f32,
) -> Option<(u32, f32)> {
- let anchor = mission
- .clans
- .get(clan)?
- .anchor
- .map(|axis| (axis.round_ties_even() as i64 as u32) as f32);
- let distance = |[x, y, _]: [f32; 3]| (x - anchor[0]).hypot(y - anchor[1]);
- let base_radius = base_radius(
- base_radius_limit,
- drafts.iter().filter_map(|draft| {
- (draft.unit_dat_header_flags? & 0x8000_0000 != 0).then_some(())?;
- let handle = handle_by_original_id(world, draft.original_id?)?;
- registration_sequence(world, handle).ok()??;
- (usize::from(identity_metadata(world, handle).ok()?.owner_id?.0) == clan)
- .then_some(())?;
- Some(distance(
- transform_state(world, handle)
- .ok()?
- .position
- .map(f32::from_bits),
- ))
- }),
- );
+ let (anchor, base_radius) = clan_area(mission, drafts, world, clan, base_radius_limit)?;
building_target(
mission,
drafts,
@@ -207,12 +228,100 @@ pub(super) fn attack_target(
// initializing it here. Use the map origin for a stable estimate.
Some([0.0; 3]),
|_, _, position| {
- let distance = distance(position);
+ let distance = distance_from_anchor(anchor, position);
(distance >= base_radius).then_some(distance)
},
)
}
+pub(super) fn base_threat(
+ mission: &MissionDocument,
+ drafts: &[MissionObjectDraft],
+ controls: &[MissionControlDeviceTableState],
+ world: &World,
+ clan: usize,
+ extension: u32,
+ limit: f32,
+ already_targeted: impl Fn(u32) -> bool,
+) -> Option<(u32, f32)> {
+ let (anchor, radius) = clan_area(mission, drafts, world, clan, limit)?;
+ let source = mission.clans.get(clan)?;
+ // shortcut: use placed logical IDs and mission order until the ArealMap roster is wired.
+ let candidates = drafts
+ .iter()
+ .take(mission.objects.len())
+ .filter_map(|draft| {
+ let class = draft.unit_dat_header_flags?;
+ let id = draft.identity_or_clan_raw;
+ if class & crate::autodemo::MOBILE_UNIT == 0 || id == u32::MAX || already_targeted(id) {
+ return None;
+ }
+ let handle = handle_by_original_id(world, draft.original_id?)?;
+ registration_sequence(world, handle).ok()??;
+ let owner = usize::from(identity_metadata(world, handle).ok()?.owner_id?.0);
+ let other = mission.clans.get(owner)?;
+ if owner == clan
+ || !source.relations.iter().any(|relation| {
+ relation.relation_value == 0 && relation.other_clan_name.raw == other.name.raw
+ })
+ {
+ return None;
+ }
+ let position = transform_state(world, handle)
+ .ok()?
+ .position
+ .map(f32::from_bits);
+ (distance_from_anchor(anchor, position).trunc() < radius + extension as f32)
+ .then(|| (id, class, unit_strength(controls, handle)))
+ });
+ strongest_threat(candidates)
+}
+
+fn strongest_threat(candidates: impl IntoIterator<Item = (u32, u32, f32)>) -> Option<(u32, f32)> {
+ let mut strongest = None;
+ for (id, class, strength) in candidates {
+ if class == crate::HERO_UNIT_CLASS {
+ return Some((id, strength));
+ }
+ if strength > strongest.map_or(0.0, |(_, power)| power) {
+ strongest = Some((id, strength));
+ }
+ }
+ strongest
+}
+
+fn clan_area(
+ mission: &MissionDocument,
+ drafts: &[MissionObjectDraft],
+ world: &World,
+ clan: usize,
+ limit: f32,
+) -> Option<([f32; 2], f32)> {
+ let anchor = mission
+ .clans
+ .get(clan)?
+ .anchor
+ .map(|axis| (axis.round_ties_even() as i64 as u32) as f32);
+ let distances = drafts.iter().filter_map(|draft| {
+ (draft.unit_dat_header_flags? & 0x8000_0000 != 0).then_some(())?;
+ let handle = handle_by_original_id(world, draft.original_id?)?;
+ registration_sequence(world, handle).ok()??;
+ (usize::from(identity_metadata(world, handle).ok()?.owner_id?.0) == clan).then_some(())?;
+ Some(distance_from_anchor(
+ anchor,
+ transform_state(world, handle)
+ .ok()?
+ .position
+ .map(f32::from_bits),
+ ))
+ });
+ Some((anchor, base_radius(limit, distances)))
+}
+
+fn distance_from_anchor([ax, ay]: [f32; 2], [x, y, _]: [f32; 3]) -> f32 {
+ (x - ax).hypot(y - ay)
+}
+
fn base_radius(limit: f32, distances: impl IntoIterator<Item = f32>) -> f32 {
let furthest = distances
.into_iter()
@@ -333,4 +442,23 @@ mod tests {
assert_eq!(encode_strength(8.2), 8.0);
assert_eq!(encode_strength(1e12), 3_567_583_232.0);
}
+
+ #[test]
+ fn factory_defence_uses_a_strict_horizontal_radius() {
+ assert!(within_factory_radius([100., 100., 75.], [249., 100., 0.]));
+ assert!(!within_factory_radius([100., 100., 75.], [250., 300., 75.]));
+ }
+
+ #[test]
+ fn threats_prioritize_the_hero_and_keep_the_first_equal_strength() {
+ let bots = [
+ (7, crate::boarding::WARBOT_CLASS, 40.),
+ (9, crate::boarding::WARBOT_CLASS, 40.),
+ ];
+ assert_eq!(strongest_threat(bots), Some((7, 40.)));
+ assert_eq!(
+ strongest_threat(bots.into_iter().chain([(3, crate::HERO_UNIT_CLASS, 0.)])),
+ Some((3, 0.))
+ );
+ }
}
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 56063ca9..aca04ebd 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -2931,6 +2931,8 @@ pub struct SimulationReport {
pub script_strength_queries: Vec<(usize, u16, u64)>,
pub script_capture_queries: Vec<(usize, u64)>,
pub script_attack_queries: Vec<(usize, u64)>,
+ pub script_factory_defence_queries: Vec<(usize, u32, u64)>,
+ pub script_base_threat_queries: Vec<(usize, u32, u64)>,
pub script_group_orders: Vec<(usize, u32, u64)>,
pub script_problem_waits: Vec<(usize, u32, u64)>,
pub script_capturer_queries: Vec<(usize, u64)>,
@@ -2979,6 +2981,8 @@ pub fn simulate_mission_report(
script_strength_queries: Vec::new(),
script_capture_queries: Vec::new(),
script_attack_queries: Vec::new(),
+ script_factory_defence_queries: Vec::new(),
+ script_base_threat_queries: Vec::new(),
script_group_orders: Vec::new(),
script_problem_waits: Vec::new(),
script_capturer_queries: Vec::new(),
@@ -3069,6 +3073,12 @@ pub fn simulate_mission_report(
.script_attack_queries
.extend(loaded.clan_ai_events.attack_queries());
report
+ .script_factory_defence_queries
+ .extend(loaded.clan_ai_events.factory_defence_queries());
+ report
+ .script_base_threat_queries
+ .extend(loaded.clan_ai_events.base_threat_queries());
+ report
.script_group_orders
.extend(loaded.clan_ai_events.group_orders());
report
diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs
index e90743fd..c19c53f8 100644
--- a/crates/fparkan-runtime/src/mission_events.rs
+++ b/crates/fparkan-runtime/src/mission_events.rs
@@ -157,7 +157,7 @@ impl MissionEvents {
world: &'a World,
owner: OwnerId,
free_only: bool,
- ) -> impl Iterator<Item = ObjectHandle> + 'a {
+ ) -> impl Iterator<Item = ObjectHandle> + Clone + 'a {
self.placed_clan_objects
.iter()
.filter_map(move |&(handle, class)| {
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index a8fa13fa..0878c84e 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -439,7 +439,12 @@ core и `ResearchCandidateSet::refresh_selection`: последний получ
`+0x41c`. Игровой `Init` учитывает эту форму как заглушку до подключения
потребителя поля к логике AI.
`script_research_status_stubs` считает `Handler(65)` и `Handler(41)` без
-каталога, а также `Handler(56)` без флага автоматических исследований.
+каталога, `Handler(58)` без списка улучшений и `Handler(56)` без флага
+автоматических исследований.
+`script_factory_defence_approx` считает оценки охраны завода по клану и
+цели. Радиус восстановлен, сила берётся из текущих таблиц Control.
+`script_base_threat_approx` отмечает поиск угрозы у базы по клану и
+цели. В выборе пока участвуют машины с логическими ID карты.
`script_problem_dispatch_stubs` считает накопленные заявки по клану и типу.
Очередь принимает заявки с секциями `_Start` и `_Continue`.
`script_problem_start_approx` отмечает запуск заявок по убыванию веса.
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index 0bdcdba6..7dae1c3a 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -316,6 +316,19 @@ RVA `0x6700` ищет самое дальнее строение клана вн
### Боевые группы
+`Handler(67)` находит первый завод в списке клана и суммирует силу
+своих машин ближе 250 единиц к нему. Сценарий получает ID завода и
+отдельное число, по которому может решить, нужно ли прикрытие.
+Вызов GOG `ai.dll` по RVA `0xeec7` подтвердил порядок выбора,
+строгую границу радиуса и исключение чужих машин. При отсутствии
+завода вызов вернул `0xffffffff` и силу 0.
+
+`Handler(47)` ищет противника внутри радиуса базы с добавленным
+сценарием запасом. Он пропускает цели, на которые уже заведена заявка
+обороны. Герой имеет приоритет, затем выбирается самая сильная машина.
+Вызов по RVA `0xd79b` подтвердил выбор героя, пропуск уже назначенной
+цели и переход через строгую границу поиска.
+
`Handler(25)` в режиме `TAKE_BY_HITS` набирает свободных варботов по
расстоянию до цели. Когда суммарная сила достигает запроса, набор заканчивается.
Если сил не хватило, сценарий получает набранную силу и может запросить