aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-14 21:38:25 +0300
committerValentin Popov <valentin@popov.link>2026-11-14 21:38:25 +0300
commit04ac1b927abde1e5e448718f94834de83a01fff8 (patch)
tree700bb593deccdd7d69ed5b4fdedda1a25f630573
parente1bf8981fc92dd134da925254f10721f30941369 (diff)
downloadfparkan-04ac1b927abde1e5e448718f94834de83a01fff8.tar.xz
fparkan-04ac1b927abde1e5e448718f94834de83a01fff8.zip
feat(ai): send scripted capturers toward hostile buildings
Single.01 dispatches its placed warbot and later factory robots from stock startup. Approach uses the shared movement task. Ownership transfer, native approach points and the script completion expressions remain open.
-rw-r--r--apps/fparkan-game/src/script_coverage.rs6
-rw-r--r--crates/fparkan-runtime/src/clan_ai_events.rs69
-rw-r--r--crates/fparkan-runtime/src/clan_targeting.rs126
-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.md3
-rw-r--r--docs/tomes/06-behavior.md6
7 files changed, 220 insertions, 2 deletions
diff --git a/apps/fparkan-game/src/script_coverage.rs b/apps/fparkan-game/src/script_coverage.rs
index 4689d1a4..90717549 100644
--- a/apps/fparkan-game/src/script_coverage.rs
+++ b/apps/fparkan-game/src/script_coverage.rs
@@ -24,6 +24,12 @@ pub(super) fn log_clan_ai_stops(report: &SimulationReport) {
for &(clan, count) in &report.script_capture_queries {
eprintln!("sim_coverage script_capture_target_approx={count} clan={clan}");
}
+ for &(clan, count) in &report.script_capturer_queries {
+ eprintln!("sim_coverage script_nearest_capturer_approx={count} clan={clan}");
+ }
+ for &(unit, target, count) in &report.script_capture_approaches {
+ eprintln!("sim_coverage script_capture_approach_stub={count} unit={unit} target={target}");
+ }
for &(clan, target, count) in &report.script_strength_queries {
eprintln!("sim_coverage script_combat_strength_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 17e57b76..7e83a7e9 100644
--- a/crates/fparkan-runtime/src/clan_ai_events.rs
+++ b/crates/fparkan-runtime/src/clan_ai_events.rs
@@ -21,6 +21,14 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) {
let Some(loaded) = &mut engine.loaded else {
return;
};
+ loaded
+ .clan_ai_events
+ .capture_orders
+ .retain(|&(owner, _, unit, target)| {
+ identity_metadata(&engine.world, unit).is_ok_and(|unit| unit.owner_id == Some(owner))
+ && identity_metadata(&engine.world, target)
+ .is_ok_and(|target| target.owner_id != Some(owner))
+ });
let active = &mut loaded.clan_ai_events.factory_jobs;
active.retain(|((clan, _), plant)| {
engine
@@ -88,6 +96,9 @@ pub(super) struct ClanAiEvents {
factory_rejections: BTreeMap<(u16, u32), u64>,
strength_queries: BTreeMap<(usize, u16), u64>,
capture_queries: BTreeMap<usize, u64>,
+ capturer_queries: BTreeMap<usize, u64>,
+ capture_orders: Vec<(OwnerId, Handler2RecordKey, ObjectHandle, ObjectHandle)>,
+ capture_approaches: BTreeMap<(u32, u32), u64>,
}
impl LoadedMissionState {
@@ -132,6 +143,7 @@ impl LoadedMissionState {
let mut solved = false;
let mut assignment = None;
let mut solving = false;
+ let mut capturer = None;
let result = varset.declarations.execute_event_prefix(
event,
bundle.formula_table.as_ref(),
@@ -259,6 +271,22 @@ impl LoadedMissionState {
.declarations
.resolve_handler15_with_values(instruction, values)
.map_err(|error| error.to_string())?;
+ if let (0x11, 3, Handler15TargetPayload::ByLogicId(target_id)) =
+ (order.word_1, order.word_2, order.target)
+ {
+ let unit = capturer.filter(|unit: &crate::clan_targeting::Capturer| unit.id == order.word_0)
+ .ok_or("Handler(15) capture requires a selected capturer")?;
+ let problem = problem.as_ref()
+ .ok_or("Handler(15) capture requires a current problem")?;
+ let approach = crate::clan_targeting::send_capturer(
+ &mut self.unit_patrol, world, &self.object_drafts, unit, target_id,
+ );
+ if let Some((unit, target)) = approach {
+ self.clan_ai_events.capture_orders.push((OwnerId(clan as u16), problem.key, unit, target));
+ *self.clan_ai_events.capture_approaches.entry((unit.slot, target.slot)).or_default() += 1;
+ }
+ return Ok(Some(VarSetDefault::Dword(u32::from(approach.is_some()))));
+ }
if order.word_1 == 0x0a
&& order.word_2 == 3
&& order.word_3 == 0
@@ -400,6 +428,28 @@ impl LoadedMissionState {
Ok(None)
}
ScriptDispatchSelector::Handler(14) if problem.is_some() => {
+ if let &[mode, target_mode, target] = instruction.references.as_slice() {
+ let word = |index: u32| values.get(index as usize)?.as_dword();
+ let (Some(4), Some(0x201), Some(target)) =
+ (word(mode), word(target_mode), word(target))
+ else {
+ return Err("Handler(14) requires a logical ID for nearest capturer selection".into());
+ };
+ capturer = crate::clan_targeting::nearest_capturer(
+ &self.mission, &self.object_drafts, &self.mission_events,
+ world, OwnerId(clan as u16), target, |handle| {
+ !self.clan_ai_events.capture_orders.iter().any(|&(_, _, unit, _)| unit == handle)
+ && self.unit_patrol.as_ref().is_none_or(|patrol| !patrol.is_shut_down(handle))
+ },
+ );
+ let id = capturer.map_or(u32::MAX, |unit| unit.id);
+ let count = self.clan_ai_events.capturer_queries.entry(clan).or_default();
+ *count += 1;
+ if *count == 1 {
+ eprintln!("sim_coverage script_nearest_capturer_approx=1 clan={clan} target={target} unit={id}");
+ }
+ return Ok(Some(VarSetDefault::Dword(id)));
+ }
let (mode, class) = instruction
.dword_pair(values)
.ok_or("Handler(14) requires a unit mode and class")?;
@@ -597,6 +647,13 @@ impl LoadedMissionState {
.factory_jobs
.iter()
.any(|&(key, _)| key == (clan as u16, problem.key))
+ || self
+ .clan_ai_events
+ .capture_orders
+ .iter()
+ .any(|&(owner, key, _, _)| {
+ owner == OwnerId(clan as u16) && key == problem.key
+ })
{
continue;
}
@@ -726,12 +783,24 @@ fn storage_space(ores: &[BehaviorOreState], world: &World, clan: OwnerId) -> f32
}
impl ClanAiEvents {
+ pub(super) fn capture_approaches(&self) -> impl Iterator<Item = (u32, u32, u64)> + '_ {
+ self.capture_approaches
+ .iter()
+ .map(|(&(unit, target), &count)| (unit, target, count))
+ }
+
pub(super) fn capture_queries(&self) -> impl Iterator<Item = (usize, u64)> + '_ {
self.capture_queries
.iter()
.map(|(&clan, &count)| (clan, count))
}
+ pub(super) fn capturer_queries(&self) -> impl Iterator<Item = (usize, u64)> + '_ {
+ self.capturer_queries
+ .iter()
+ .map(|(&clan, &count)| (clan, count))
+ }
+
pub(super) fn strength_queries(&self) -> impl Iterator<Item = (usize, u16, u64)> + '_ {
self.strength_queries
.iter()
diff --git a/crates/fparkan-runtime/src/clan_targeting.rs b/crates/fparkan-runtime/src/clan_targeting.rs
index f8c1b4ca..05ac970a 100644
--- a/crates/fparkan-runtime/src/clan_targeting.rs
+++ b/crates/fparkan-runtime/src/clan_targeting.rs
@@ -3,9 +3,99 @@ use crate::{
MissionObjectDraft,
};
use fparkan_world::{
- handle_by_original_id, identity_metadata, registration_sequence, transform_state, World,
+ handle_by_original_id, identity_metadata, registration_sequence, transform_state, ObjectHandle,
+ OwnerId, World,
};
+#[derive(Clone, Copy)]
+pub(super) struct Capturer {
+ handle: ObjectHandle,
+ target: ObjectHandle,
+ pub(super) id: u32,
+ target_id: u32,
+}
+
+pub(super) fn send_capturer(
+ patrol: &mut Option<crate::unit_patrol::UnitPatrol>,
+ world: &World,
+ drafts: &[MissionObjectDraft],
+ unit: Capturer,
+ target_id: u32,
+) -> Option<(ObjectHandle, ObjectHandle)> {
+ let pose = transform_state(world, unit.target).ok()?;
+ let target = identity_metadata(world, unit.target).ok()?;
+ if unit.target_id != target_id
+ || target_id & 0x8000_0000 == 0
+ || target.owner_id == identity_metadata(world, unit.handle).ok()?.owner_id
+ || target
+ .original_id
+ .and_then(|id| drafts.get(id.0 as usize))
+ .and_then(|draft| draft.unit_dat_header_flags)
+ == Some(0x8000_0200)
+ {
+ return None;
+ }
+ let [x, y, _] = pose.position.map(f32::from_bits);
+ // shortcut: route towards the building; native entrance selection and capture are still open.
+ patrol
+ .get_or_insert_with(crate::unit_patrol::UnitPatrol::scripted)
+ .move_to(world, unit.handle, [x, y], false);
+ eprintln!(
+ "sim_coverage script_capture_approach_stub=1 unit={} target={} target_id={target_id}",
+ unit.handle.slot, unit.target.slot
+ );
+ Some((unit.handle, unit.target))
+}
+
+pub(super) fn nearest_capturer(
+ mission: &MissionDocument,
+ drafts: &[MissionObjectDraft],
+ roster: &crate::mission_events::MissionEvents,
+ world: &World,
+ owner: OwnerId,
+ target_id: u32,
+ available: impl Fn(ObjectHandle) -> bool,
+) -> Option<Capturer> {
+ let target = crate::mission_events::placed_logic_objects(mission, world, target_id).next()?;
+ let point = transform_state(world, target)
+ .ok()?
+ .position
+ .map(f32::from_bits);
+ // shortcut: all routed robots currently share one speed, so travel time ranks by XY distance.
+ roster
+ .clan_units(world, owner, true)
+ .filter(|&handle| available(handle))
+ .filter_map(|handle| {
+ let original_id = identity_metadata(world, handle).ok()?.original_id?.0;
+ let index = original_id as usize;
+ let chassis = drafts.get(index)?.unit_components.first()?;
+ if !crate::mission_events::capturer_chassis(&chassis.resource_raw) {
+ return None;
+ }
+ let position = transform_state(world, handle)
+ .ok()?
+ .position
+ .map(f32::from_bits);
+ let distance = (point[0] - position[0]).hypot(point[1] - position[1]);
+ // shortcut: generated ID is local to this script section until native robot IDs are allocated.
+ let id = mission
+ .objects
+ .get(index)
+ .map_or(original_id, |object| object.identity_or_clan_raw);
+ (id != u32::MAX).then_some((
+ Capturer {
+ handle,
+ target,
+ id,
+ target_id,
+ },
+ distance,
+ ))
+ })
+ .min_by(|(_, a), (_, b)| a.total_cmp(b))
+ .map(|(unit, _)| unit)
+}
+
pub(super) fn encode_strength(strength: f32) -> f32 {
// The original narrows the truncated x87 result to a DWORD before the script assignment.
(strength as i64 as u32) as f32
@@ -74,6 +164,40 @@ mod tests {
use super::*;
#[test]
+ fn capture_order_replaces_patrol_and_rejects_a_friendly_target() {
+ use fparkan_world::{
+ construct_object, new, register_object, set_owner, ObjectDraft, WorldConfig,
+ };
+
+ let mut world = new(WorldConfig);
+ let mut create = |owner| {
+ let handle = construct_object(&mut world, ObjectDraft { original_id: None }).unwrap();
+ register_object(&mut world, handle).unwrap();
+ set_owner(&mut world, handle, Some(OwnerId(owner))).unwrap();
+ handle
+ };
+ let handle = create(1);
+ let target = create(0);
+ let capturer = Capturer {
+ handle,
+ target,
+ id: 3,
+ target_id: 0x8000_0002,
+ };
+ let mut patrol = None;
+ assert_eq!(
+ send_capturer(&mut patrol, &world, &[], capturer, capturer.target_id),
+ Some((handle, target))
+ );
+ assert!(patrol.as_ref().unwrap().is_moving_to_destination(handle));
+ set_owner(&mut world, target, Some(OwnerId(1))).unwrap();
+ assert_eq!(
+ send_capturer(&mut patrol, &world, &[], capturer, capturer.target_id),
+ None
+ );
+ }
+
+ #[test]
fn generators_and_factories_rank_ahead_of_other_buildings() {
let classes = [
0x8000_0002,
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 475a4c2c..5eefdd33 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -2913,6 +2913,8 @@ pub struct SimulationReport {
/// Approximate clan strength queries, grouped by caller and target clan.
pub script_strength_queries: Vec<(usize, u16, u64)>,
pub script_capture_queries: Vec<(usize, u64)>,
+ pub script_capturer_queries: Vec<(usize, u64)>,
+ pub script_capture_approaches: Vec<(u32, u32, u64)>,
/// First factory completion by clan, in milliseconds.
pub first_factory_completion_ms: std::collections::BTreeMap<u16, u32>,
/// Total requests for mission information messages.
@@ -2956,6 +2958,8 @@ pub fn simulate_mission_report(
script_factory_orders: Vec::new(),
script_strength_queries: Vec::new(),
script_capture_queries: Vec::new(),
+ script_capturer_queries: Vec::new(),
+ script_capture_approaches: Vec::new(),
first_factory_completion_ms: Default::default(),
mission_messages: 0,
autodemo_first_shot_ms: None,
@@ -3038,6 +3042,12 @@ pub fn simulate_mission_report(
report
.script_capture_queries
.extend(loaded.clan_ai_events.capture_queries());
+ report
+ .script_capturer_queries
+ .extend(loaded.clan_ai_events.capturer_queries());
+ report
+ .script_capture_approaches
+ .extend(loaded.clan_ai_events.capture_approaches());
}
Ok(report)
}
diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs
index d13b6327..ee189ca9 100644
--- a/crates/fparkan-runtime/src/mission_events.rs
+++ b/crates/fparkan-runtime/src/mission_events.rs
@@ -892,7 +892,7 @@ fn inside_exit_volume([x, y, z]: [f32; 3], [px, py, pz]: [f32; 3]) -> bool {
(pz - z).abs() <= 3.0 && (px - x).powi(2) + (py - y).powi(2) <= 25.0
}
-fn capturer_chassis(chassis: &[u8; 32]) -> bool {
+pub(super) fn capturer_chassis(chassis: &[u8; 32]) -> bool {
// shortcut: stock robot keys map to native size classes 1 and 2;
// query the effective Behavior controller when custom types are supported.
matches!(
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index 8780c2ee..4d7ae3bf 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -457,6 +457,9 @@ core и `ResearchCandidateSet::refresh_selection`: последний получ
`script_capture_target_approx` считает запросы `Handler(35)` по кланам.
Для выбора цели и оценки охраны используется реестр размещённых объектов.
Порядок областей ArealMap и учёт произведённых роботов открыты.
+`script_nearest_capturer_approx` отмечает выбор по расстоянию при общей скорости
+роботов. `script_capture_approach_stub` считает приказы дойти до строения по парам
+юнит/цель. Нативный подход, смена владельца и завершение заявки открыты.
`Handler(15)` для `ORDER_ROBOT_SEARCH` генератора пока проходит как
`script_init_handler_stub`. GOG Behavior.dll по RVA `0x30110` настраивает
поиск строения, а задача по RVA `0x30300` обрабатывает в том числе захват.
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index 0b67494b..dc8ae10e 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -284,6 +284,12 @@ Control. Снаряд использует скорость, время жизн
`0xffffffff`. SHA-256 этой сборки DLL
`c19cd6cd31cd2896f8c4ba0f0e700dd3408aec8182daaf4863d98a7d233a2abc`.
+Секция заявки обращается к `Handler(14)` за варботом с лёгким или малым шасси
+и передаёт его ID в `ORDER_ROBOT_CAPTURE`. В оригинале обработчик по RVA
+`0x8a99` сравнивает оценки времени подхода по расстоянию и скорости. В
+FParkan скорость движения пока общая, поэтому достаточно сравнить расстояния.
+Если подходящий робот ещё собирается, он становится кандидатом после выпуска.
+
### Первый запуск сценария
Перед настройкой первого шага каждый AI получает начальный массив DWORD. В