aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-25 11:20:10 +0300
committerValentin Popov <valentin@popov.link>2026-11-25 11:20:10 +0300
commitbccae28a00af19dc095910073e7e820aa81dc393 (patch)
tree77f8f37bff10b6274a84b87fd7f3b3e329089c1b /crates
parent05fe0d6d8c10629d0b485d1eb3c1e25279164a53 (diff)
downloadfparkan-bccae28a00af19dc095910073e7e820aa81dc393.tar.xz
fparkan-bccae28a00af19dc095910073e7e820aa81dc393.zip
feat(ai): guard the least defended clan building
Execute Handler(37) from the live clan roster, rank nearby guard strength and feed the existing protection scheduler. Keep the native strict 250-unit radius, first tie and empty-roster sentinel. Count approximate selections by clan and target in simulation reports. The GOG AI handler was called directly for weak buildings, equal strength, the radius boundary and an empty roster. Stock missions 8, 9 and 10 now assign guard patrols before reaching the next explicit script blocker. Mission 9 ran in the window with clean Vulkan validation. The existing factory protection regression and workspace checks pass.
Diffstat (limited to 'crates')
-rw-r--r--crates/fparkan-runtime/src/clan_ai_events.rs92
-rw-r--r--crates/fparkan-runtime/src/clan_targeting.rs67
-rw-r--r--crates/fparkan-runtime/src/lib.rs5
3 files changed, 150 insertions, 14 deletions
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs
index 6e844899..602ecf0c 100644
--- a/crates/fparkan-runtime/src/clan_ai_events.rs
+++ b/crates/fparkan-runtime/src/clan_ai_events.rs
@@ -226,6 +226,7 @@ pub(super) struct ClanAiEvents {
capture_queries: BTreeMap<usize, u64>,
attack_queries: BTreeMap<usize, u64>,
factory_defence_queries: BTreeMap<(usize, u32), u64>,
+ building_defence_queries: BTreeMap<(usize, u32), u64>,
base_threat_queries: BTreeMap<(usize, u32), u64>,
base_radius_limits: BTreeMap<usize, f32>,
capturer_queries: BTreeMap<usize, u64>,
@@ -1018,7 +1019,7 @@ impl LoadedMissionState {
self.clan_ai_events.log_research_stub(clan, 58, &bundle.script_path);
Ok(Some(VarSetDefault::Dword(u32::MAX)))
}
- ScriptDispatchSelector::Handler(handler @ (47 | 67)) => {
+ ScriptDispatchSelector::Handler(handler @ (37 | 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())
@@ -1033,24 +1034,29 @@ impl LoadedMissionState {
);
(output, selection)
}
- (67, &[output]) => {
+ (37 | 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))
+ let selection = if handler == 37 {
+ crate::clan_targeting::building_defence(world, &self.object_drafts, &self.control_device_tables, units)
+ } else {
+ crate::clan_targeting::factory_defence(world, &self.object_drafts, &self.control_device_tables, units)
+ };
+ (output, selection)
}
_ => 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 (id, power) = selection.unwrap_or((u32::MAX, if handler == 37 { 1e12_f32 } else { 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 (queries, name) = match handler {
+ 37 => (&mut self.clan_ai_events.building_defence_queries, "script_building_defence_approx"),
+ 47 => (&mut self.clan_ai_events.base_threat_queries, "script_base_threat_approx"),
+ _ => (&mut self.clan_ai_events.factory_defence_queries, "script_factory_defence_approx"),
};
let count = queries.entry((clan, id)).or_default();
*count += 1;
@@ -1231,6 +1237,12 @@ impl ClanAiEvents {
.map(|(&(clan, id), &count)| (clan, id, count))
}
+ pub(super) fn building_defence_queries(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ {
+ self.building_defence_queries
+ .iter()
+ .map(|(&(clan, target), &count)| (clan, target, count))
+ }
+
pub(super) fn wait_starts(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ {
self.wait_starts
.iter()
@@ -1390,6 +1402,70 @@ mod tests {
#[test]
#[ignore = "requires licensed corpus"]
+ fn licensed_weak_building_gets_scripted_guards_from_stock_start() {
+ use crate::{EngineServices, MissionMode, MissionRequest, MissionStartupInput};
+ use fparkan_vfs::DirectoryVfs;
+ use std::sync::Arc;
+
+ let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus root");
+ let mut engine =
+ crate::create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap();
+ crate::load_gameplay_mission(
+ &mut engine,
+ MissionRequest {
+ key: "MISSIONS/CAMPAIGN/CAMPAIGN.01/Mission.03/data.tma".into(),
+ mode: MissionMode::SingleMission,
+ },
+ MissionStartupInput {
+ queue_time_ms: 0,
+ research_creation_gate: false,
+ },
+ None,
+ )
+ .unwrap();
+
+ for now in (0..=7_000).step_by(100) {
+ crate::frame(&mut engine, now).unwrap();
+ }
+ let loaded = engine.loaded.as_ref().unwrap();
+ assert!(loaded
+ .clan_ai_events
+ .stops()
+ .all(|(stop, _)| stop.reason != "Handler(37)"));
+ let target = crate::mission_events::placed_logic_objects(
+ &loaded.mission,
+ &engine.world,
+ 0x8000_0001,
+ )
+ .next()
+ .unwrap();
+ let group = loaded
+ .clan_ai_events
+ .groups
+ .iter()
+ .find_map(|(&(clan, key), group)| {
+ (clan == 1 && key.word_0 == BUILDING_PROTECT && key.argument_0 == 0x8000_0001)
+ .then_some(group)
+ })
+ .expect("weak building receives a guard group");
+ assert_eq!(group.target, target);
+ assert!(!group.members.is_empty());
+ let patrol = loaded.unit_patrol.as_ref().unwrap();
+ assert!(group
+ .members
+ .iter()
+ .all(|&unit| patrol.has_object_order(unit, target)));
+ assert_eq!(
+ loaded
+ .clan_ai_events
+ .building_defence_queries()
+ .collect::<Vec<_>>(),
+ vec![(1, 0x8000_0001, 1)]
+ );
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
fn licensed_factory_protection_resumes_and_assigns_a_patrol_from_stock_start() {
use crate::{
create, load_gameplay_mission, simulate_mission_report, EngineServices, MissionMode,
diff --git a/crates/fparkan-runtime/src/clan_targeting.rs b/crates/fparkan-runtime/src/clan_targeting.rs
index e81af415..f0b4608c 100644
--- a/crates/fparkan-runtime/src/clan_targeting.rs
+++ b/crates/fparkan-runtime/src/clan_targeting.rs
@@ -162,6 +162,50 @@ pub(super) fn factory_defence(
.map(f32::from_bits),
))
})?;
+ Some((id, guard_strength(world, drafts, controls, units, position)))
+}
+
+pub(super) fn building_defence(
+ world: &World,
+ drafts: &[MissionObjectDraft],
+ controls: &[MissionControlDeviceTableState],
+ units: impl Iterator<Item = ObjectHandle> + Clone,
+) -> Option<(u32, f32)> {
+ let candidates = units.clone().filter_map(|handle| {
+ let index = identity_metadata(world, handle).ok()?.original_id?.0 as usize;
+ let id = drafts.get(index)?.identity_or_clan_raw;
+ (id & 0x8000_0000 != 0 && id != u32::MAX).then_some(())?;
+ let position = transform_state(world, handle)
+ .ok()?
+ .position
+ .map(f32::from_bits);
+ Some((
+ id,
+ guard_strength(world, drafts, controls, units.clone(), position),
+ ))
+ });
+ least_defended(candidates)
+}
+
+fn least_defended(candidates: impl Iterator<Item = (u32, f32)>) -> Option<(u32, f32)> {
+ let mut selected = None;
+ let mut minimum = 1e12_f32;
+ for (id, strength) in candidates {
+ if strength < minimum {
+ selected = Some((id, strength));
+ minimum = strength;
+ }
+ }
+ selected
+}
+
+fn guard_strength(
+ world: &World,
+ drafts: &[MissionObjectDraft],
+ controls: &[MissionControlDeviceTableState],
+ units: impl Iterator<Item = ObjectHandle>,
+ position: [f32; 3],
+) -> f32 {
// shortcut: sum from live Control tables until the ArealMap street records are available.
let guards = units.filter(|&handle| {
let mobile = identity_metadata(world, handle)
@@ -174,12 +218,9 @@ pub(super) fn factory_defence(
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),
- ))
+ 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 {
@@ -396,6 +437,20 @@ mod tests {
use super::*;
#[test]
+ fn defence_selects_the_smallest_strength_and_keeps_the_first_tie() {
+ assert_eq!(
+ least_defended([(1, 8.0), (2, 4.0), (3, 4.0)].into_iter()),
+ Some((2, 4.0))
+ );
+ assert_eq!(
+ least_defended([(1, 0.0), (2, 0.0)].into_iter()),
+ Some((1, 0.0))
+ );
+ assert_eq!(least_defended(std::iter::empty()), None);
+ assert_eq!(least_defended([(1, f32::NAN), (2, 1e12)].into_iter()), None);
+ }
+
+ #[test]
fn approach_targets_the_nearest_platform_triangle() {
assert_eq!(
nearest_platform_point(
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index a2d24893..722c7750 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -2965,6 +2965,7 @@ pub struct SimulationReport {
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_building_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)>,
@@ -3019,6 +3020,7 @@ pub fn simulate_mission_report(
script_capture_queries: Vec::new(),
script_attack_queries: Vec::new(),
script_factory_defence_queries: Vec::new(),
+ script_building_defence_queries: Vec::new(),
script_base_threat_queries: Vec::new(),
script_group_orders: Vec::new(),
script_problem_waits: Vec::new(),
@@ -3117,6 +3119,9 @@ pub fn simulate_mission_report(
.script_factory_defence_queries
.extend(loaded.clan_ai_events.factory_defence_queries());
report
+ .script_building_defence_queries
+ .extend(loaded.clan_ai_events.building_defence_queries());
+ report
.script_base_threat_queries
.extend(loaded.clan_ai_events.base_threat_queries());
report