From 16450724fa9d3052d315442a07b71e8d445c6cc3 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Sat, 14 Nov 2026 23:11:20 +0400 Subject: feat(ai): wait on scripted capture and group conditions Single.01 now reaches ST_SOLVING after dispatching a capturer and patrol. Compare the capture and destruction predicates with the original ai.dll at RVA 0x5180. Keep the default OR_TASK behavior and report the approximate lifecycle. --- apps/fparkan-game/src/script_coverage.rs | 3 + crates/fparkan-runtime/src/clan_ai_events.rs | 96 +++++++++++++++++++--- .../fparkan-runtime/src/clan_problem_conditions.rs | 65 +++++++++++++++ crates/fparkan-runtime/src/lib.rs | 6 ++ docs/appendices/knowledge-boundaries.md | 5 +- docs/tomes/06-behavior.md | 11 +++ 6 files changed, 172 insertions(+), 14 deletions(-) create mode 100644 crates/fparkan-runtime/src/clan_problem_conditions.rs diff --git a/apps/fparkan-game/src/script_coverage.rs b/apps/fparkan-game/src/script_coverage.rs index 6a96bb9f..436ec426 100644 --- a/apps/fparkan-game/src/script_coverage.rs +++ b/apps/fparkan-game/src/script_coverage.rs @@ -30,6 +30,9 @@ pub(super) fn log_clan_ai_stops(report: &SimulationReport) { for &(clan, target, count) in &report.script_group_orders { eprintln!("sim_coverage script_group_order_approx={count} clan={clan} target={target}"); } + for &(clan, problem, count) in &report.script_problem_waits { + eprintln!("sim_coverage script_problem_wait_approx={count} clan={clan} problem={problem}"); + } for &(clan, count) in &report.script_capturer_queries { eprintln!("sim_coverage script_nearest_capturer_approx={count} clan={clan}"); } diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index bc4e7408..284a9bc8 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -1,3 +1,4 @@ +use crate::clan_problem_conditions::Condition; use crate::{clan_combat_groups::CombatGroup, clan_targeting::CaptureApproach}; use crate::{BehaviorOreState, LoadedMissionState, MissionEventStop}; use fparkan_script::{ @@ -60,12 +61,13 @@ pub(super) fn resolve_captures( } } loaded.clan_ai_events.capture_orders.remove(index); - if let Some(queue) = loaded - .clan_ai_events - .problems - .get_mut(&usize::from(owner.0)) - { - queue.remove(key); + let clan = usize::from(owner.0); + let ai = &mut loaded.clan_ai_events; + if !valid_unit || !ai.waits.contains_key(&(clan, key)) { + if let Some(queue) = ai.problems.get_mut(&clan) { + queue.remove(key); + } + ai.waits.remove(&(clan, key)); } } Ok(captured) @@ -96,6 +98,34 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) { }); !group.members.is_empty() }); + let ai = &mut loaded.clan_ai_events; + ai.waits.retain(|&(clan, key), conditions| { + let group = ai.groups.get(&(clan, key)); + let ready = conditions.iter().any(|&condition| { + condition.met( + &engine.world, + OwnerId(clan as u16), + loaded.unit_patrol.as_ref(), + group, + ) + }); + if ready { + if let Some(queue) = ai.problems.get_mut(&clan) { + queue.remove(key); + } + if let Some(group) = ai.groups.remove(&(clan, key)) { + if let Some(patrol) = &mut loaded.unit_patrol { + for member in group.members { + patrol.clear_object_order(member, group.target); + } + } + } + eprintln!("script_problem_condition_met clan={clan} problem={} target={} queue_time_ms={now_ms}", key.word_0, key.argument_0); + false + } else { + true + } + }); let active = &mut loaded.clan_ai_events.factory_jobs; active.retain(|((clan, _), plant)| { engine @@ -169,6 +199,8 @@ pub(super) struct ClanAiEvents { capture_orders: Vec<(OwnerId, Handler2RecordKey, CaptureApproach)>, capture_approaches: BTreeMap<(u32, u32), u64>, groups: BTreeMap<(usize, Handler2RecordKey), CombatGroup>, + waits: BTreeMap<(usize, Handler2RecordKey), Vec>, + wait_starts: BTreeMap<(usize, u32), u64>, group_orders: BTreeMap<(usize, u32), u64>, } @@ -216,6 +248,7 @@ impl LoadedMissionState { let mut solving = false; let mut capturer = None; let mut group = None; + let mut conditions = Vec::new(); let result = varset.declarations.execute_event_prefix( event, bundle.formula_table.as_ref(), @@ -502,7 +535,8 @@ impl LoadedMissionState { Some(1) if problem .as_ref() - .is_some_and(|record| record.key.word_0 == 6) => + .is_some_and(|record| record.key.word_0 == 6) + || !conditions.is_empty() => { solving = true } @@ -515,20 +549,38 @@ impl LoadedMissionState { } Ok(None) } - ScriptDispatchSelector::Handler(27) if solving => { + ScriptDispatchSelector::Handler(27) if problem.is_some() => { let [action, mode, id] = instruction.references.as_slice() else { return Err("Handler(27) requires an action and target".into()); }; let word = |index: u32| { values.get(index as usize).and_then(|cell| cell.as_dword()) }; - let (Some(2), Some(0), Some(id)) = + let (Some(action), Some(mode), Some(id)) = (word(*action), word(*mode), word(*id)) else { - return Err( - "Handler(27) only supports waiting for a factory".into() - ); + return Err("Handler(27) requires three DWORD operands".into()); }; + let key = problem.as_ref().expect("condition requires a problem").key; + let condition = match (action, mode) { + (1 | 3, 0) if matches!(key.word_0, 7 | 9) => { + let target = crate::mission_events::placed_logic_objects( + &self.mission, world, id + ).next(); + Some(if action == 1 { Condition::ObjectDestroyed(target) } else { + Condition::BuildingCaptured(target.ok_or("Handler(27) capture target is unavailable")?) + }) + } + (4 | 5, 1) if id == 0 && self.clan_ai_events.groups.contains_key(&(clan, key)) => { + Some(if action == 4 { Condition::GroupDestroyed } else { Condition::GroupIdle }) + } + (2, 0) if solving => None, + _ => return Err("Handler(27) action or target mode is unsupported".into()), + }; + if let Some(condition) = condition { + conditions.push(condition); + return Ok(None); + } let order = orders .last_mut() .filter(|order| { @@ -759,6 +811,19 @@ impl LoadedMissionState { .entry(clan) .or_default() .remove(problem.key); + } else if solving && !conditions.is_empty() { + let count = self + .clan_ai_events + .wait_starts + .entry((clan, problem.key.word_0)) + .or_default(); + *count += 1; + if *count == 1 { + eprintln!("sim_coverage script_problem_wait_approx=1 clan={clan} problem={} target={} conditions={}", problem.key.word_0, problem.key.argument_0, conditions.len()); + } + self.clan_ai_events + .waits + .insert((clan, problem.key), conditions); } } else if let Some(queue) = self.clan_ai_events.problems.get(&clan) { pending = ranked_problems(queue.records()); @@ -781,6 +846,7 @@ impl LoadedMissionState { .clan_ai_events .groups .contains_key(&(clan, problem.key)) + || self.clan_ai_events.waits.contains_key(&(clan, problem.key)) { continue; } @@ -910,6 +976,12 @@ fn storage_space(ores: &[BehaviorOreState], world: &World, clan: OwnerId) -> f32 } impl ClanAiEvents { + pub(super) fn wait_starts(&self) -> impl Iterator + '_ { + self.wait_starts + .iter() + .map(|(&(clan, problem), &count)| (clan, problem, count)) + } + fn unit_assigned(&self, unit: ObjectHandle) -> bool { self.capture_orders .iter() diff --git a/crates/fparkan-runtime/src/clan_problem_conditions.rs b/crates/fparkan-runtime/src/clan_problem_conditions.rs new file mode 100644 index 00000000..bace9ec6 --- /dev/null +++ b/crates/fparkan-runtime/src/clan_problem_conditions.rs @@ -0,0 +1,65 @@ +use crate::clan_combat_groups::CombatGroup; +use crate::unit_patrol::UnitPatrol; +use fparkan_world::{identity_metadata, registration_sequence, ObjectHandle, OwnerId, World}; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Condition { + ObjectDestroyed(Option), + BuildingCaptured(ObjectHandle), + GroupDestroyed, + GroupIdle, +} + +impl Condition { + pub(super) fn met( + self, + world: &World, + clan: OwnerId, + patrol: Option<&UnitPatrol>, + group: Option<&CombatGroup>, + ) -> bool { + let live = + |unit| registration_sequence(world, unit).is_ok_and(|sequence| sequence.is_some()); + match self { + Self::ObjectDestroyed(target) => target.is_none_or(|target| !live(target)), + Self::BuildingCaptured(target) => { + live(target) + && identity_metadata(world, target) + .is_ok_and(|identity| identity.owner_id == Some(clan)) + } + Self::GroupDestroyed => { + group.is_none_or(|group| group.members.iter().all(|&unit| !live(unit))) + } + Self::GroupIdle => group.is_none_or(|group| { + group.members.iter().all(|&unit| { + !live(unit) || patrol.is_none_or(|patrol| !patrol.is_patrolling(unit)) + }) + }), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use fparkan_world::{ + construct_object, new, register_object, set_owner, ObjectDraft, WorldConfig, + }; + + #[test] + fn capture_waits_for_the_requested_clan_and_destruction_waits_for_removal() { + let mut world = new(WorldConfig); + let target = construct_object(&mut world, ObjectDraft { original_id: None }).unwrap(); + register_object(&mut world, target).unwrap(); + let clan = OwnerId(1); + set_owner(&mut world, target, Some(OwnerId(0))).unwrap(); + assert!(!Condition::BuildingCaptured(target).met(&world, clan, None, None)); + assert!(!Condition::ObjectDestroyed(Some(target)).met(&world, clan, None, None)); + set_owner(&mut world, target, Some(clan)).unwrap(); + assert!(Condition::BuildingCaptured(target).met(&world, clan, None, None)); + fparkan_world::request_delete(&mut world, target).unwrap(); + fparkan_world::step(&mut world, &fparkan_world::InputSnapshot).unwrap(); + assert!(Condition::ObjectDestroyed(Some(target)).met(&world, clan, None, None)); + assert!(!Condition::BuildingCaptured(target).met(&world, clan, None, None)); + } +} diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 6c7f0fe7..56063ca9 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -47,6 +47,7 @@ mod building_door; mod clan_ai_events; mod clan_combat_groups; mod clan_combat_strength; +mod clan_problem_conditions; mod clan_script_init; mod clan_targeting; mod mesh_collision; @@ -2931,6 +2932,7 @@ pub struct SimulationReport { pub script_capture_queries: Vec<(usize, u64)>, pub script_attack_queries: Vec<(usize, u64)>, pub script_group_orders: Vec<(usize, u32, u64)>, + pub script_problem_waits: Vec<(usize, u32, u64)>, pub script_capturer_queries: Vec<(usize, u64)>, pub script_capture_approaches: Vec<(u32, u32, u64)>, /// First factory completion by clan, in milliseconds. @@ -2978,6 +2980,7 @@ pub fn simulate_mission_report( script_capture_queries: Vec::new(), script_attack_queries: Vec::new(), script_group_orders: Vec::new(), + script_problem_waits: Vec::new(), script_capturer_queries: Vec::new(), script_capture_approaches: Vec::new(), first_factory_completion_ms: Default::default(), @@ -3068,6 +3071,9 @@ pub fn simulate_mission_report( report .script_group_orders .extend(loaded.clan_ai_events.group_orders()); + report + .script_problem_waits + .extend(loaded.clan_ai_events.wait_starts()); report .script_capturer_queries .extend(loaded.clan_ai_events.capturer_queries()); diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index b0f2bd1c..a8fa13fa 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -462,8 +462,9 @@ core и `ResearchCandidateSet::refresh_selection`: последний получ парам юнит/цель. Нужен маршрут внутри строения: наружная высота может оставить робота над площадкой. Нативные события завершения открыты. `script_group_order_approx` считает приказы группе по клану и цели. -Набор использует свободных варботов. Переназначение с менее важных заявок -и ожидания группы через `Handler(27)` открыты. +Набор использует свободных варботов. Переназначение с менее важных заявок открыто. +`script_problem_wait_approx` отмечает ожидание гибели, захвата или простоя +при `OR_TASK`. `AND_TASK`, старение и секции `_Continue` открыты. `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 3f798bb8..0bdcdba6 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -326,6 +326,17 @@ RVA `0x6700` ищет самое дальнее строение клана вн В GOG `ai.dll` обработчики находятся по RVA `0xab85` и `0xba01`. SHA-256 DLL `c19cd6cd31cd2896f8c4ba0f0e700dd3408aec8182daaf4863d98a7d233a2abc`. +`Handler(27)` по RVA `0x94f1` добавляет к заявке условия. Например, +прикрытие можно снять, когда целью завладел свой клан, цель уничтожена +или группа осталась без приказа. Цикл по RVA `0x4ee0` проверяет список, +а RVA `0x5180` определяет, выполнено ли отдельное условие. В режиме +`OR_TASK` достаточно одного. Пока заявка ждёт, её секция `_Start` +не отправляет ту же группу повторно. +Изолированный вызов RVA `0x5180` подтвердил два условия. Захват +засчитывается при смене владельца на клан заявки, а уничтожение — после +исчезновения объекта из реестра. Исчезновение объекта само по себе +условие захвата не выполняет. + ### Первый запуск сценария -- cgit v1.2.3