aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-25 13:03:31 +0300
committerValentin Popov <valentin@popov.link>2026-11-25 13:03:31 +0300
commit2656cca01b65745e9e6aa7b11d80414039e4cc67 (patch)
treeaca8b310eb3ecebfb9f2f9c19770a0fed838b235 /crates/fparkan-runtime/src
parent3278b382a1580e45ba915b64ad283168ab9ea7e1 (diff)
downloadfparkan-2656cca01b65745e9e6aa7b11d80414039e4cc67.tar.xz
fparkan-2656cca01b65745e9e6aa7b11d80414039e4cc67.zip
feat(ai): select convoy targets using original class queries
Connect Handler(71) to least-defended hostile buildings of the requested class and Handler(72) to the object's prototype size class. The stock Convoy script now assigns its delayed attack instead of stopping at these queries. Keep descriptor binding, guard strength and candidate order explicit approximations with coverage counters. Execute the original ai.dll handlers and Behavior.dll class getter in native oracles, including strict radius, ties, missing objects and name classes. Add a Rust class rule test and a licensed stock-start test for the delayed attack; check owner independence separately with a debug change after the stock assertion. Validate fmt, workspace check/tests, licensed test, release simulation and the running mission with Vulkan validation. Accelerated scene time is a mechanic check, not mission-completion acceptance. Handler(30) message dispatch remains the next Convoy script stop.
Diffstat (limited to 'crates/fparkan-runtime/src')
-rw-r--r--crates/fparkan-runtime/src/clan_ai_events.rs56
-rw-r--r--crates/fparkan-runtime/src/clan_building_queries.rs170
-rw-r--r--crates/fparkan-runtime/src/clan_targeting.rs2
-rw-r--r--crates/fparkan-runtime/src/lib.rs12
-rw-r--r--crates/fparkan-runtime/src/unit_size_class.rs80
5 files changed, 319 insertions, 1 deletions
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs
index 8f9e7e99..5af3c086 100644
--- a/crates/fparkan-runtime/src/clan_ai_events.rs
+++ b/crates/fparkan-runtime/src/clan_ai_events.rs
@@ -253,6 +253,8 @@ pub(super) struct ClanAiEvents {
point_patrol_continues: BTreeMap<(usize, u32, u32), u64>,
free_unit_queries: BTreeMap<(usize, u32, u32), u64>,
group_recruitments: BTreeMap<(usize, u32), u64>,
+ class_target_queries: BTreeMap<(usize, u32, u32), u64>,
+ size_class_queries: BTreeMap<(usize, u32), u64>,
}
impl LoadedMissionState {
@@ -418,6 +420,48 @@ impl LoadedMissionState {
.scalar_1;
Ok(Some(VarSetDefault::FloatBits(priority.to_bits())))
}
+ ScriptDispatchSelector::Handler(71) => {
+ let &[radius, class, estimate] = instruction.references.as_slice() else {
+ return Err("Handler(71) requires radius, class and strength output".into());
+ };
+ let radius = match values.get(radius as usize) {
+ Some(VarSetDefault::Dword(value)) => *value as f32,
+ Some(VarSetDefault::FloatBits(bits)) => f32::from_bits(*bits),
+ None => return Err("Handler(71) radius is unavailable".into()),
+ };
+ let class = values.get(class as usize).and_then(|value| value.as_dword())
+ .ok_or("Handler(71) class must be a DWORD")?;
+ let (target, strength) = crate::clan_building_queries::weakest_enemy_of_class(
+ &self.mission, &self.mission_events, &self.object_drafts,
+ &self.control_device_tables, world, clan, class, radius,
+ ).unwrap_or((u32::MAX, 1e12_f32));
+ let strength = strength as i64 as u32;
+ let output = values.get_mut(estimate as usize)
+ .ok_or("Handler(71) strength output is unavailable")?;
+ *output = match *output {
+ VarSetDefault::Dword(_) => VarSetDefault::Dword(strength),
+ VarSetDefault::FloatBits(_) => VarSetDefault::FloatBits((strength as f32).to_bits()),
+ };
+ let count = self.clan_ai_events.class_target_queries.entry((clan, class, target)).or_default();
+ *count += 1;
+ if *count == 1 {
+ eprintln!("sim_coverage script_class_target_approx=1 clan={clan} class={class} target={target} strength={strength}");
+ }
+ Ok(Some(VarSetDefault::Dword(target)))
+ }
+ ScriptDispatchSelector::Handler(72) => {
+ let id = single_dword(&instruction.references, values)
+ .ok_or("Handler(72) requires a logical ID")?;
+ let size = crate::unit_size_class::query(
+ &self.mission, &self.mission_events, &self.object_drafts, world, id,
+ )?;
+ let count = self.clan_ai_events.size_class_queries.entry((clan, id)).or_default();
+ *count += 1;
+ if *count == 1 {
+ eprintln!("sim_coverage script_size_class_approx=1 clan={clan} unit={id} class={size}");
+ }
+ Ok(Some(VarSetDefault::Dword(size)))
+ }
ScriptDispatchSelector::Handler(handler @ (35 | 64)) => {
let &[radius, estimate] = instruction.references.as_slice() else {
return Err("target query requires a radius and strength output".into());
@@ -1392,6 +1436,18 @@ impl ClanAiEvents {
.map(|(&(clan, mode), &count)| (clan, mode, count))
}
+ pub(super) fn class_target_queries(&self) -> impl Iterator<Item = (usize, u32, u32, u64)> + '_ {
+ self.class_target_queries
+ .iter()
+ .map(|(&(clan, class, target), &count)| (clan, class, target, count))
+ }
+
+ pub(super) fn size_class_queries(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ {
+ self.size_class_queries
+ .iter()
+ .map(|(&(clan, id), &count)| (clan, id, count))
+ }
+
pub(super) fn point_group_orders(&self) -> impl Iterator<Item = (usize, u32, u32, u64)> + '_ {
self.point_group_orders
.iter()
diff --git a/crates/fparkan-runtime/src/clan_building_queries.rs b/crates/fparkan-runtime/src/clan_building_queries.rs
new file mode 100644
index 00000000..399dd28c
--- /dev/null
+++ b/crates/fparkan-runtime/src/clan_building_queries.rs
@@ -0,0 +1,170 @@
+use crate::{
+ mission_events::MissionEvents, MissionControlDeviceTableState, MissionDocument,
+ MissionObjectDraft,
+};
+use fparkan_world::{handle_by_original_id, transform_state, OwnerId, World};
+
+pub(super) fn weakest_enemy_of_class(
+ mission: &MissionDocument,
+ roster: &MissionEvents,
+ drafts: &[MissionObjectDraft],
+ controls: &[MissionControlDeviceTableState],
+ world: &World,
+ caller: usize,
+ class: u32,
+ radius: f32,
+) -> Option<(u32, f32)> {
+ let source = mission.clans.get(caller)?;
+ let enemies: Vec<_> = mission
+ .clans
+ .iter()
+ .enumerate()
+ .filter(|(index, candidate)| {
+ *index != caller
+ && source.relations.iter().any(|relation| {
+ relation.relation_value == 0
+ && relation.other_clan_name.raw == candidate.name.raw
+ })
+ })
+ .flat_map(|(index, _)| roster.clan_units(world, OwnerId(index as u16), false))
+ .collect();
+ // shortcut: use mission order until the native ArealMap building lists are wired.
+ let candidates = drafts.iter().filter_map(|draft| {
+ if class & 0x8000_0000 == 0
+ || draft.unit_dat_header_flags != Some(class)
+ || draft.identity_or_clan_raw == u32::MAX
+ {
+ return None;
+ }
+ let handle = handle_by_original_id(world, draft.original_id?)?;
+ if !enemies.contains(&handle) {
+ return None;
+ }
+ let position = transform_state(world, handle)
+ .ok()?
+ .position
+ .map(f32::from_bits);
+ let strength = crate::clan_targeting::area_strength(
+ world,
+ drafts,
+ controls,
+ enemies.iter().copied(),
+ position,
+ radius,
+ );
+ Some((draft.identity_or_clan_raw, strength))
+ });
+ crate::clan_targeting::least_defended(candidates)
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ #[ignore = "requires licensed corpus"]
+ fn licensed_stock_convoy_uses_size_class_and_assigns_an_attack() {
+ use crate::{EngineServices, MissionMode, MissionRequest, MissionStartupInput};
+ use fparkan_vfs::DirectoryVfs;
+ use fparkan_world::{identity_metadata, set_owner, OwnerId};
+ 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.03/Mission.02/data.tma".into(),
+ mode: MissionMode::SingleMission,
+ },
+ MissionStartupInput {
+ queue_time_ms: 0,
+ research_creation_gate: false,
+ },
+ None,
+ )
+ .unwrap();
+ for now in (0..=900_000).step_by(100) {
+ crate::frame(&mut engine, now).unwrap();
+ if engine
+ .loaded
+ .as_ref()
+ .unwrap()
+ .clan_ai_events
+ .class_target_queries()
+ .any(|(clan, _, _, _)| clan == 2)
+ {
+ break;
+ }
+ }
+ let loaded = engine.loaded.as_ref().unwrap();
+ let actor = loaded
+ .mission_events
+ .logic_objects(&loaded.mission, &engine.world, 15)
+ .next()
+ .unwrap();
+ let target = loaded
+ .mission_events
+ .logic_objects(&loaded.mission, &engine.world, 0x8000_0001)
+ .next()
+ .unwrap();
+ assert_eq!(
+ loaded
+ .unit_patrol
+ .as_ref()
+ .unwrap()
+ .attack_target(actor)
+ .map(|(unit, _)| unit),
+ Some(target)
+ );
+ assert!(loaded
+ .clan_ai_events
+ .class_target_queries()
+ .any(|(clan, class, id, count)| {
+ clan == 2 && class == 0x8001_0000 && id == 0x8000_0001 && count > 0
+ }));
+ assert!(loaded
+ .clan_ai_events
+ .size_class_queries()
+ .any(|(clan, id, count)| clan == 1 && id == 0x8000_0003 && count > 0));
+ assert!(loaded
+ .clan_ai_events
+ .stops()
+ .all(|(stop, _)| !["Handler(71)", "Handler(72)"]
+ .iter()
+ .any(|handler| stop.reason.starts_with(handler))));
+
+ let classified = loaded
+ .mission_events
+ .logic_objects(&loaded.mission, &engine.world, 0x8000_0003)
+ .next()
+ .unwrap();
+ let original_owner = identity_metadata(&engine.world, classified)
+ .unwrap()
+ .owner_id;
+ // Debug ownership change checks the descriptor binding, separately from the stock-start attack.
+ set_owner(&mut engine.world, classified, Some(OwnerId(3))).unwrap();
+ assert_eq!(
+ crate::unit_size_class::query(
+ &loaded.mission,
+ &loaded.mission_events,
+ &loaded.object_drafts,
+ &engine.world,
+ 0x8000_0003
+ )
+ .unwrap(),
+ 2
+ );
+ set_owner(&mut engine.world, classified, original_owner).unwrap();
+ assert_eq!(
+ crate::unit_size_class::query(
+ &loaded.mission,
+ &loaded.mission_events,
+ &loaded.object_drafts,
+ &engine.world,
+ u32::MAX
+ )
+ .unwrap(),
+ u32::MAX
+ );
+ }
+}
diff --git a/crates/fparkan-runtime/src/clan_targeting.rs b/crates/fparkan-runtime/src/clan_targeting.rs
index 8f35acee..490a42f8 100644
--- a/crates/fparkan-runtime/src/clan_targeting.rs
+++ b/crates/fparkan-runtime/src/clan_targeting.rs
@@ -190,7 +190,7 @@ pub(super) fn building_defence(
least_defended(candidates)
}
-fn least_defended(candidates: impl Iterator<Item = (u32, f32)>) -> Option<(u32, f32)> {
+pub(super) 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 {
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 027af788..0b250ad5 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -46,6 +46,7 @@ mod boarding;
mod building_door;
mod clan_ai_events;
mod clan_area_strength;
+mod clan_building_queries;
mod clan_combat_groups;
mod clan_combat_strength;
mod clan_problem_conditions;
@@ -68,6 +69,7 @@ mod script_patrol;
mod script_time;
mod unit_combat;
mod unit_patrol;
+mod unit_size_class;
pub use autodemo::{
autodemo_camera, AutoDemoCamera, AutoDemoReinforcement, AutoDemoView, SpawnedUnit,
@@ -2974,6 +2976,8 @@ pub struct SimulationReport {
pub script_point_patrol_continues: Vec<(usize, u32, u32, u64)>,
pub script_free_unit_queries: Vec<(usize, u32, u32, u64)>,
pub script_group_recruitments: Vec<(usize, u32, u64)>,
+ pub script_class_target_queries: Vec<(usize, u32, u32, u64)>,
+ pub script_size_class_queries: Vec<(usize, u32, u64)>,
pub script_problem_waits: Vec<(usize, u32, u64)>,
pub script_factory_patrol_continues: Vec<(usize, u32, u64)>,
pub script_ore_transport_orders: Vec<(usize, u32, u64)>,
@@ -3034,6 +3038,8 @@ pub fn simulate_mission_report(
script_point_patrol_continues: Vec::new(),
script_free_unit_queries: Vec::new(),
script_group_recruitments: Vec::new(),
+ script_class_target_queries: Vec::new(),
+ script_size_class_queries: Vec::new(),
script_problem_waits: Vec::new(),
script_factory_patrol_continues: Vec::new(),
script_ore_transport_orders: Vec::new(),
@@ -3154,6 +3160,12 @@ pub fn simulate_mission_report(
.script_group_recruitments
.extend(loaded.clan_ai_events.group_recruitments());
report
+ .script_class_target_queries
+ .extend(loaded.clan_ai_events.class_target_queries());
+ report
+ .script_size_class_queries
+ .extend(loaded.clan_ai_events.size_class_queries());
+ report
.script_problem_waits
.extend(loaded.clan_ai_events.wait_starts());
report
diff --git a/crates/fparkan-runtime/src/unit_size_class.rs b/crates/fparkan-runtime/src/unit_size_class.rs
new file mode 100644
index 00000000..8f9a2d93
--- /dev/null
+++ b/crates/fparkan-runtime/src/unit_size_class.rs
@@ -0,0 +1,80 @@
+use crate::{mission_events::MissionEvents, MissionDocument, MissionObjectDraft};
+use fparkan_world::{identity_metadata, World};
+
+pub(super) fn query(
+ mission: &MissionDocument,
+ roster: &MissionEvents,
+ drafts: &[MissionObjectDraft],
+ world: &World,
+ id: u32,
+) -> Result<u32, String> {
+ let Some(unit) = roster.logic_objects(mission, world, id).next() else {
+ return Ok(u32::MAX);
+ };
+ let draft = identity_metadata(world, unit)
+ .ok()
+ .and_then(|identity| identity.original_id)
+ .and_then(|id| drafts.get(id.0 as usize))
+ .ok_or("Handler(72) unit descriptor is unavailable")?;
+ let resource = &draft
+ .unit_components
+ .first()
+ .ok_or("Handler(72) root prototype is unavailable")?
+ .resource_raw;
+ // shortcut: infer the descriptor kind from Unit DAT until native descriptor interfaces are wired.
+ let kind = match draft.unit_dat_header_flags {
+ Some(class) if class & 0x8000_0000 != 0 || class == 0x0101_0000 => 3,
+ Some(class) if class & 0x0100_0000 != 0 => 4,
+ _ => return Err("Handler(72) descriptor kind is unavailable".into()),
+ };
+ Ok(classify(kind, resource))
+}
+
+fn classify(kind: u32, name: &[u8]) -> u32 {
+ let name = &name[..name
+ .iter()
+ .position(|&byte| byte == 0)
+ .unwrap_or(name.len())];
+ let index = match kind {
+ 3 => 3,
+ 4 => 2,
+ _ => return 0,
+ };
+ match (kind, name.get(index).map(u8::to_ascii_lowercase)) {
+ (4, Some(b't')) => 1,
+ (3 | 4, Some(b'l')) | (4, Some(b'h')) => 2,
+ (3 | 4, Some(b'm')) => 3,
+ (3 | 4, Some(b'b')) => 4,
+ (3, Some(b'e')) => 5,
+ _ => 0,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn native_descriptor_classes_use_the_kind_and_fixed_character() {
+ for (kind, name, expected) in [
+ (4, "R_T_02", 1),
+ (4, "r_l_01", 2),
+ (4, "r_h_03", 2),
+ (4, "r_m_02", 3),
+ (4, "r_b_01", 4),
+ (4, "r_e_01", 0),
+ (3, "fr_l_bunker", 2),
+ (3, "fr_m_cargo", 3),
+ (3, "fr_b_plant", 4),
+ (3, "fr_e_lab", 5),
+ (3, "fr_h_invalid", 0),
+ (3, "fr_t_invalid", 0),
+ (3, "xx_m", 3),
+ (2, "r_l_01", 0),
+ (4, "r", 0),
+ ] {
+ assert_eq!(classify(kind, name.as_bytes()), expected, "{kind} {name}");
+ }
+ assert_eq!(classify(4, b"r_\0m"), 0);
+ }
+}