From b553096eb9a4d9ccaa46ec2616c5c392e8a39325 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Wed, 25 Nov 2026 12:30:01 +0400 Subject: feat(ai): evaluate scripted area defence strength Execute Handler(44) for XY and logical-object targets, an explicit clan or hostile clans. Reuse the strict horizontal radius calculation and report approximate query counts by clan, event and instruction. Direct GOG AI DLL calls cover target forms, DWORD coordinates, clan filtering, missing targets and the radius boundary. A stock mission regression runs the query through the script dispatcher. Five affected missions complete 900 simulated seconds, with the remaining point-group selection failures exposed explicitly. Mission 10 ran in the window with clean Vulkan validation. Workspace formatting, checking and tests pass. --- apps/fparkan-game/src/script_coverage.rs | 3 + crates/fparkan-runtime/src/clan_ai_events.rs | 23 ++++ crates/fparkan-runtime/src/clan_area_strength.rs | 156 +++++++++++++++++++++++ crates/fparkan-runtime/src/clan_targeting.rs | 28 ++-- crates/fparkan-runtime/src/lib.rs | 6 + docs/appendices/knowledge-boundaries.md | 3 + docs/tomes/06-behavior.md | 12 ++ 7 files changed, 223 insertions(+), 8 deletions(-) create mode 100644 crates/fparkan-runtime/src/clan_area_strength.rs diff --git a/apps/fparkan-game/src/script_coverage.rs b/apps/fparkan-game/src/script_coverage.rs index de7d50b4..2e3d276a 100644 --- a/apps/fparkan-game/src/script_coverage.rs +++ b/apps/fparkan-game/src/script_coverage.rs @@ -35,6 +35,9 @@ pub(super) fn log_clan_ai_stops(report: &SimulationReport) { "sim_coverage script_building_defence_approx={count} clan={clan} target={target}" ); } + for &(clan, event, instruction, count) in &report.script_area_strength_queries { + eprintln!("sim_coverage script_area_strength_approx={count} clan={clan} event={event} instruction={instruction}"); + } for &(clan, target, count) in &report.script_base_threat_queries { eprintln!("sim_coverage script_base_threat_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 602ecf0c..245868e0 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -227,6 +227,7 @@ pub(super) struct ClanAiEvents { attack_queries: BTreeMap, factory_defence_queries: BTreeMap<(usize, u32), u64>, building_defence_queries: BTreeMap<(usize, u32), u64>, + area_strength_queries: BTreeMap<(usize, usize, usize), u64>, base_threat_queries: BTreeMap<(usize, u32), u64>, base_radius_limits: BTreeMap, capturer_queries: BTreeMap, @@ -368,6 +369,20 @@ impl LoadedMissionState { bundle.formula_table.as_ref(), &mut state.values, |instruction, values| match instruction.dispatch_selector() { + ScriptDispatchSelector::Handler(44) => { + let strength = crate::clan_area_strength::query( + &self.mission, &self.mission_events, world, &self.object_drafts, + &self.control_device_tables, clan, instruction, values, + )?; + let index = event.instructions.iter().position(|item| std::ptr::eq(item, instruction)) + .expect("instruction belongs to the executing event"); + let count = self.clan_ai_events.area_strength_queries.entry((clan, event_index, index)).or_default(); + *count += 1; + if *count == 1 { + eprintln!("sim_coverage script_area_strength_approx=1 clan={clan} event={event_index} instruction={index} strength={strength}"); + } + Ok(Some(VarSetDefault::Dword(strength))) + } ScriptDispatchSelector::Handler(9) if instruction.references.is_empty() && instruction.header_words[1] == u32::MAX => @@ -1243,6 +1258,14 @@ impl ClanAiEvents { .map(|(&(clan, target), &count)| (clan, target, count)) } + pub(super) fn area_strength_queries( + &self, + ) -> impl Iterator + '_ { + self.area_strength_queries + .iter() + .map(|(&(clan, event, instruction), &count)| (clan, event, instruction, count)) + } + pub(super) fn wait_starts(&self) -> impl Iterator + '_ { self.wait_starts .iter() diff --git a/crates/fparkan-runtime/src/clan_area_strength.rs b/crates/fparkan-runtime/src/clan_area_strength.rs new file mode 100644 index 00000000..b4ba9381 --- /dev/null +++ b/crates/fparkan-runtime/src/clan_area_strength.rs @@ -0,0 +1,156 @@ +use crate::{ + mission_events::MissionEvents, MissionControlDeviceTableState, MissionDocument, + MissionObjectDraft, +}; +use fparkan_script::{ScriptInstruction, VarSetDefault}; +use fparkan_world::{transform_state, OwnerId, World}; + +pub(super) fn query( + mission: &MissionDocument, + roster: &MissionEvents, + world: &World, + drafts: &[MissionObjectDraft], + controls: &[MissionControlDeviceTableState], + caller: usize, + instruction: &ScriptInstruction, + values: &[VarSetDefault], +) -> Result { + let number = |index: u32| { + values.get(index as usize).map(|cell| match *cell { + VarSetDefault::Dword(value) => value as f32, + VarSetDefault::FloatBits(bits) => f32::from_bits(bits), + }) + }; + let word = |index: u32| values.get(index as usize).and_then(|cell| cell.as_dword()); + let &[radius, clan, mode, ref target @ ..] = instruction.references.as_slice() else { + return Err("Handler(44) requires radius, clan and a place or logical target".into()); + }; + let radius = number(radius).ok_or("Handler(44) radius is unavailable")?; + let clan = word(clan).ok_or("Handler(44) clan is unavailable")?; + let position = match (word(mode), target) { + (Some(0x202), &[x, y]) => Some([ + number(x).ok_or("Handler(44) X is unavailable")?, + number(y).ok_or("Handler(44) Y is unavailable")?, + 0.0, + ]), + (Some(0x201), &[id]) => { + let id = word(id).ok_or("Handler(44) logical ID is unavailable")?; + roster + .logic_objects(mission, world, id) + .find_map(|handle| transform_state(world, handle).ok()) + .map(|pose| pose.position.map(f32::from_bits)) + } + _ => return Err("Handler(44) requires TARGET_BY_PLACE or TARGET_BY_LOGIC_ID".into()), + }; + let Some(position) = position else { + return Ok(0); + }; + let source = &mission.clans[caller]; + let units = mission + .clans + .iter() + .enumerate() + .filter(|(index, candidate)| { + if clan != u32::MAX { + return *index == clan as usize; + } + *index != caller + && source.relations.iter().any(|relation| { + relation.other_clan_name.raw == candidate.name.raw + && relation.relation_value == 0 + }) + }) + .flat_map(|(index, _)| roster.clan_units(world, OwnerId(index as u16), false)); + let strength = + crate::clan_targeting::area_strength(world, drafts, controls, units, position, radius); + Ok(crate::clan_targeting::encode_strength(strength) as u32) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[ignore = "requires licensed corpus"] + fn licensed_area_queries_accept_both_target_forms_and_continue_the_script() { + 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(); + + let loaded = engine.loaded.as_ref().unwrap(); + let run = |references: &[u32], values: &[VarSetDefault]| { + let instruction = ScriptInstruction { + header_words: [ + 44, + 6, + u32::MAX, + u32::MAX, + 6, + references.len() as u32, + u32::MAX, + ], + references: references.to_vec(), + }; + query( + &loaded.mission, + &loaded.mission_events, + &engine.world, + &loaded.object_drafts, + &loaded.control_device_tables, + 0, + &instruction, + values, + ) + }; + let mut values = vec![ + VarSetDefault::FloatBits(10_000.0_f32.to_bits()), + VarSetDefault::Dword(1), + VarSetDefault::Dword(0x202), + VarSetDefault::Dword(0), + VarSetDefault::Dword(0), + VarSetDefault::Dword(0x8000_0001), + ]; + let own = run(&[0, 1, 2, 3, 4], &values).unwrap(); + assert!(own > 0); + values[2] = VarSetDefault::Dword(0x201); + assert_eq!(run(&[0, 1, 2, 5], &values).unwrap(), own); + values[5] = VarSetDefault::Dword(u32::MAX); + assert_eq!(run(&[0, 1, 2, 5], &values).unwrap(), 0); + values[2] = VarSetDefault::Dword(0x202); + values[3] = VarSetDefault::FloatBits(0.25_f32.to_bits()); + assert_eq!(run(&[0, 1, 2, 3, 4], &values).unwrap(), own); + assert!(run(&[0, 1, 2, 3], &values).is_err()); + assert!(run(&[0, 1, 2, 3, 99], &values).is_err()); + + 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.area_strength_queries().any( + |(clan, event, instruction, count)| { + (clan, event, instruction, count) == (1, 1, 12, 1) + } + )); + assert!(loaded + .clan_ai_events + .stops() + .all(|(stop, _)| stop.reason != "Handler(44)")); + } +} diff --git a/crates/fparkan-runtime/src/clan_targeting.rs b/crates/fparkan-runtime/src/clan_targeting.rs index f0b4608c..8f35acee 100644 --- a/crates/fparkan-runtime/src/clan_targeting.rs +++ b/crates/fparkan-runtime/src/clan_targeting.rs @@ -162,7 +162,10 @@ pub(super) fn factory_defence( .map(f32::from_bits), )) })?; - Some((id, guard_strength(world, drafts, controls, units, position))) + Some(( + id, + area_strength(world, drafts, controls, units, position, 250.0), + )) } pub(super) fn building_defence( @@ -181,7 +184,7 @@ pub(super) fn building_defence( .map(f32::from_bits); Some(( id, - guard_strength(world, drafts, controls, units.clone(), position), + area_strength(world, drafts, controls, units.clone(), position, 250.0), )) }); least_defended(candidates) @@ -199,12 +202,13 @@ fn least_defended(candidates: impl Iterator) -> Option<(u32, selected } -fn guard_strength( +pub(super) fn area_strength( world: &World, drafts: &[MissionObjectDraft], controls: &[MissionControlDeviceTableState], units: impl Iterator, position: [f32; 3], + radius: f32, ) -> f32 { // shortcut: sum from live Control tables until the ArealMap street records are available. let guards = units.filter(|&handle| { @@ -215,7 +219,7 @@ fn guard_strength( .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)) + within_radius(position, pose.position.map(f32::from_bits), radius) }) }); guards @@ -223,8 +227,8 @@ fn guard_strength( .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 +fn within_radius([x, y, _]: [f32; 3], [px, py, _]: [f32; 3], radius: f32) -> bool { + (x - px).hypot(y - py) < radius } pub(super) fn capture_target( @@ -500,8 +504,16 @@ mod tests { #[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.])); + assert!(within_radius([100., 100., 75.], [249., 100., 0.], 250.0)); + assert!(!within_radius([100., 100., 75.], [250., 300., 75.], 250.0)); + assert!(within_radius([100., 100., 75.], [149., 100., 500.], 50.0)); + assert!(!within_radius([100., 100., 75.], [150., 100., 75.], 50.0)); + assert!(!within_radius([100., 100., 75.], [100., 100., 75.], 0.0)); + assert!(!within_radius( + [100., 100., 75.], + [100., 100., 75.], + f32::NAN + )); } #[test] diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 722c7750..78144fa3 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -45,6 +45,7 @@ mod autodemo; mod boarding; mod building_door; mod clan_ai_events; +mod clan_area_strength; mod clan_combat_groups; mod clan_combat_strength; mod clan_problem_conditions; @@ -2966,6 +2967,7 @@ pub struct SimulationReport { 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_area_strength_queries: Vec<(usize, usize, usize, 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)>, @@ -3021,6 +3023,7 @@ pub fn simulate_mission_report( script_attack_queries: Vec::new(), script_factory_defence_queries: Vec::new(), script_building_defence_queries: Vec::new(), + script_area_strength_queries: Vec::new(), script_base_threat_queries: Vec::new(), script_group_orders: Vec::new(), script_problem_waits: Vec::new(), @@ -3121,6 +3124,9 @@ pub fn simulate_mission_report( report .script_building_defence_queries .extend(loaded.clan_ai_events.building_defence_queries()); + report + .script_area_strength_queries + .extend(loaded.clan_ai_events.area_strength_queries()); report .script_base_threat_queries .extend(loaded.clan_ai_events.base_threat_queries()); diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index 660f4cce..27e08a6b 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -452,6 +452,9 @@ core и `ResearchCandidateSet::refresh_selection`: последний получ `script_building_defence_approx` считает выбор наименее охраняемого своего строения через `Handler(37)`. Сила и порядок кандидатов пока берутся из реестра мира и Control вместо записей ArealMap. +`script_area_strength_approx` считает запросы `Handler(44)` по клану, +событию и инструкции. Используются живой реестр мира и оценка Control, +пока записи областей и агрегаты силы ArealMap остаются открытыми. `script_base_threat_approx` отмечает поиск угрозы у базы по клану и цели. В выборе пока участвуют машины с логическими ID карты. `script_problem_dispatch_stubs` считает накопленные заявки по клану и типу. diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index b04a996d..4ad4aa65 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -376,6 +376,18 @@ SHA-256 DLL `c19cd6cd31cd2896f8c4ba0f0e700dd3408aec8182daaf4863d98a7d233a2abc`. При пустом списке возвращается ID `0xffffffff`, а выходная оценка получает DWORD от усечения исходного значения `1e12_f32`. +`Handler(44)` оценивает охрану уже заданного места. Сценарий передаёт радиус, +клан и координаты XY либо логический ID объекта. Команда складывает силу +машин выбранного клана строго внутри радиуса и возвращает усечённый DWORD. +Высота машин не участвует в расстоянии. Значение `ERROR` вместо номера клана +означает сумму по враждебным кланам, а отсутствие объекта с заданным ID даёт +ноль. Координаты можно передать как DWORD или float. + +В GOG `ai.dll` эта команда находится по RVA `0xd57e`, общий расчёт области — +по RVA `0x6130`. Изолированный вызов подтвердил обе формы цели, выбор клана, +строгую границу радиуса и преобразование координат. В сценариях эта оценка +определяет, требуется ли дополнительный патруль в указанном месте. + `PBM_BUILDING_PROTECT_Start` сравнивает силу машин возле завода с порогом сценария. При достаточной охране заявка переходит в `ST_SOLVING` без нового приказа. В действующей заявке `PBM_BUILDING_PROTECT_Continue` -- cgit v1.2.3