diff options
| author | Valentin Popov <valentin@popov.link> | 2026-11-14 21:57:44 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-11-14 21:57:44 +0300 |
| commit | a25aa2959dbac4d0f2a91299de16e12f492699f3 (patch) | |
| tree | 1ecda6259b74d51b33dd4e932623f3824531ff10 /crates | |
| parent | 239c4504d6fcfe0e78559d1587605a7b5707e5c2 (diff) | |
| download | fparkan-a25aa2959dbac4d0f2a91299de16e12f492699f3.tar.xz fparkan-a25aa2959dbac4d0f2a91299de16e12f492699f3.zip | |
feat(ai): select enemy buildings beyond the clan base radius
Connect the initial radius limit and Handler(64) target lookup. Compare target IDs with an isolated GOG ai.dll call at RVA 0xe8e7. Campaign branches still depend on their original timers and free-mind conditions.
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 47 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_script_init.rs | 37 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_targeting.rs | 95 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 15 |
4 files changed, 161 insertions, 33 deletions
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index 9745c8d0..565fd41f 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -142,6 +142,8 @@ pub(super) struct ClanAiEvents { factory_rejections: BTreeMap<(u16, u32), u64>, strength_queries: BTreeMap<(usize, u16), u64>, capture_queries: BTreeMap<usize, u64>, + attack_queries: BTreeMap<usize, u64>, + base_radius_limits: BTreeMap<usize, f32>, capturer_queries: BTreeMap<usize, u64>, capture_orders: Vec<(OwnerId, Handler2RecordKey, CaptureApproach)>, capture_approaches: BTreeMap<(u32, u32), u64>, @@ -210,19 +212,25 @@ impl LoadedMissionState { .scalar_1; Ok(Some(VarSetDefault::FloatBits(priority.to_bits()))) } - ScriptDispatchSelector::Handler(35) => { + ScriptDispatchSelector::Handler(handler @ (35 | 64)) => { let &[radius, estimate] = instruction.references.as_slice() else { - return Err("Handler(35) requires a radius and strength output".into()); + return Err("target query requires a radius and strength output".into()); }; let radius = values.get(radius as usize).and_then(|cell| cell.as_float()) - .ok_or("Handler(35) requires a float radius")?; + .ok_or("target query requires a float radius")?; if !matches!(values.get(instruction.header_words[1] as usize), Some(VarSetDefault::Dword(_)) | None) { - return Err("Handler(35) requires a DWORD result".into()); + return Err("target query requires a DWORD result".into()); } let estimate = values.get_mut(estimate as usize) - .ok_or("Handler(35) strength output is unavailable")?; - let capture = crate::clan_targeting::capture_target( + .ok_or("target query strength output is unavailable")?; + let selection = if handler == 64 { + crate::clan_targeting::attack_target( + &self.mission, &self.object_drafts, &self.control_device_tables, + world, clan, radius, + self.clan_ai_events.base_radius_limits.get(&clan).copied().unwrap_or(700.0), + ) + } else { crate::clan_targeting::capture_target( &self.mission, &self.object_drafts, &self.control_device_tables, world, clan, radius, |id| { self.clan_ai_events.problems.get(&clan).is_some_and(|scheduler| { @@ -232,20 +240,25 @@ impl LoadedMissionState { }) }) }, - ); - let (target, strength) = capture.unwrap_or((u32::MAX, 1e12_f32)); + ) }; + let (target, strength) = selection.unwrap_or((u32::MAX, 1e12_f32)); let strength = crate::clan_targeting::encode_strength(strength); *estimate = match *estimate { VarSetDefault::Dword(_) => VarSetDefault::Dword( problem_dword(strength.to_bits()) - .ok_or("Handler(35) strength is outside the DWORD range")? + .ok_or("target strength is outside the DWORD range")? ), VarSetDefault::FloatBits(_) => VarSetDefault::FloatBits(strength.to_bits()), }; - let count = self.clan_ai_events.capture_queries.entry(clan).or_default(); + let (queries, name) = if handler == 64 { + (&mut self.clan_ai_events.attack_queries, "script_attack_target_approx") + } else { + (&mut self.clan_ai_events.capture_queries, "script_capture_target_approx") + }; + let count = queries.entry(clan).or_default(); *count += 1; if *count == 1 { - eprintln!("sim_coverage script_capture_target_approx=1 clan={clan} target={target} strength={strength}"); + eprintln!("sim_coverage {name}=1 clan={clan} target={target} strength={strength}"); } Ok(Some(VarSetDefault::Dword(target))) } @@ -829,6 +842,18 @@ fn storage_space(ores: &[BehaviorOreState], world: &World, clan: OwnerId) -> f32 } impl ClanAiEvents { + pub(super) fn set_base_radius(&mut self, clan: usize, limit: f32) { + if limit.is_finite() && limit > 0.0 { + self.base_radius_limits.insert(clan, limit); + } + } + + pub(super) fn attack_queries(&self) -> impl Iterator<Item = (usize, u64)> + '_ { + self.attack_queries + .iter() + .map(|(&clan, &count)| (clan, count)) + } + pub(super) fn capture_approaches(&self) -> impl Iterator<Item = (u32, u32, u64)> + '_ { self.capture_approaches .iter() diff --git a/crates/fparkan-runtime/src/clan_script_init.rs b/crates/fparkan-runtime/src/clan_script_init.rs index 3e102be3..c6a070de 100644 --- a/crates/fparkan-runtime/src/clan_script_init.rs +++ b/crates/fparkan-runtime/src/clan_script_init.rs @@ -4,6 +4,10 @@ use fparkan_script::{ }; pub(super) enum InitOrder { + BaseRadius { + clan: usize, + limit: f32, + }, Patrol(ScriptPatrol), Attack { id: u32, @@ -22,6 +26,18 @@ pub(super) enum InitOrder { }, } +pub(super) fn base_radius( + instruction: &ScriptInstruction, + values: &[VarSetDefault], +) -> Option<f32> { + let ([68, u32::MAX, u32::MAX, u32::MAX, 6, 1, u32::MAX], &[index]) = + (instruction.header_words, instruction.references.as_slice()) + else { + return None; + }; + values.get(index as usize)?.as_float() +} + pub(super) fn reservation( instruction: &ScriptInstruction, values: &[VarSetDefault], @@ -84,15 +100,6 @@ pub(super) fn stubbed_handler( match (instruction.header_words, instruction.references.as_slice()) { // shortcut: resume Init until the live research context is wired. ([43, u32::MAX, u32::MAX, u32::MAX, 6, 0, u32::MAX], []) => Some(43), - // shortcut: resume Init until the native AI base-area state is wired. - ([68, u32::MAX, u32::MAX, u32::MAX, 6, 1, u32::MAX], [index]) - if matches!( - values.get(*index as usize), - Some(VarSetDefault::FloatBits(_)) - ) => - { - Some(68) - } // shortcut: resume Init until the AI consumer of this setting is wired. ([69, u32::MAX, u32::MAX, u32::MAX, 6, 1, u32::MAX], [index]) if matches!(values.get(*index as usize), Some(VarSetDefault::Dword(_))) => @@ -131,23 +138,19 @@ mod tests { } #[test] - fn base_area_stub_requires_a_float_operand_and_no_result() { + fn base_area_requires_a_float_operand_and_no_result() { let mut instruction = ScriptInstruction { header_words: [68, u32::MAX, u32::MAX, u32::MAX, 6, 1, u32::MAX], references: vec![0], }; let values = [VarSetDefault::FloatBits(500.0_f32.to_bits())]; - let declarations = fparkan_script::parse_varset(b"").unwrap(); + assert_eq!(base_radius(&instruction, &values), Some(500.0)); assert_eq!( - stubbed_handler(&instruction, &values, &declarations), - Some(68) - ); - assert_eq!( - stubbed_handler(&instruction, &[VarSetDefault::Dword(500)], &declarations), + base_radius(&instruction, &[VarSetDefault::Dword(500)]), None ); instruction.header_words[1] = 0; - assert_eq!(stubbed_handler(&instruction, &values, &declarations), None); + assert_eq!(base_radius(&instruction, &values), None); } #[test] diff --git a/crates/fparkan-runtime/src/clan_targeting.rs b/crates/fparkan-runtime/src/clan_targeting.rs index 5b5a4786..909c14eb 100644 --- a/crates/fparkan-runtime/src/clan_targeting.rs +++ b/crates/fparkan-runtime/src/clan_targeting.rs @@ -153,6 +153,84 @@ pub(super) fn capture_target( radius: f32, already_targeted: impl Fn(u32) -> bool, ) -> Option<(u32, f32)> { + building_target( + mission, + drafts, + controls, + world, + clan, + radius, + None, + |id, class, _| (!already_targeted(id)).then_some(f32::from(building_priority(class))), + ) +} + +pub(super) fn attack_target( + mission: &MissionDocument, + drafts: &[MissionObjectDraft], + controls: &[MissionControlDeviceTableState], + world: &World, + clan: usize, + radius: f32, + base_radius_limit: f32, +) -> Option<(u32, f32)> { + let anchor = mission + .clans + .get(clan)? + .anchor + .map(|axis| (axis.round_ties_even() as i64 as u32) as f32); + let distance = |[x, y, _]: [f32; 3]| (x - anchor[0]).hypot(y - anchor[1]); + let base_radius = base_radius( + base_radius_limit, + drafts.iter().filter_map(|draft| { + (draft.unit_dat_header_flags? & 0x8000_0000 != 0).then_some(())?; + let handle = handle_by_original_id(world, draft.original_id?)?; + registration_sequence(world, handle).ok()??; + (usize::from(identity_metadata(world, handle).ok()?.owner_id?.0) == clan) + .then_some(())?; + Some(distance( + transform_state(world, handle) + .ok()? + .position + .map(f32::from_bits), + )) + }), + ); + building_target( + mission, + drafts, + controls, + world, + clan, + radius, + // shortcut: native Handler(64) uses a separate stack vector without + // initializing it here. Use the map origin for a stable estimate. + Some([0.0; 3]), + |_, _, position| { + let distance = distance(position); + (distance >= base_radius).then_some(distance) + }, + ) +} + +fn base_radius(limit: f32, distances: impl IntoIterator<Item = f32>) -> f32 { + let furthest = distances + .into_iter() + .filter(|&distance| distance < limit) + .fold(0.0, f32::max); + (furthest + 100.0).min(limit) +} + +fn building_target( + mission: &MissionDocument, + drafts: &[MissionObjectDraft], + controls: &[MissionControlDeviceTableState], + world: &World, + clan: usize, + radius: f32, + strength_center: Option<[f32; 3]>, + rank: impl Fn(u32, u32, [f32; 3]) -> Option<f32>, +) -> Option<(u32, f32)> { let source = mission.clans.get(clan)?; // shortcut: use placed-object order until the native ArealMap roster is wired. let hostile_objects = || { @@ -176,11 +254,13 @@ pub(super) fn capture_target( Some((draft.identity_or_clan_raw, class, handle, position)) }) }; - let (id, _, _, position) = hostile_objects() - .filter(|&(id, class, _, _)| { - id != u32::MAX && class & 0x8000_0000 != 0 && !already_targeted(id) + let (id, position, _) = hostile_objects() + .filter_map(|(id, class, _, position)| { + (id != u32::MAX && class & 0x8000_0000 != 0).then_some(())?; + Some((id, position, rank(id, class, position)?)) }) - .min_by_key(|&(_, class, _, _)| building_priority(class))?; + .min_by(|(_, _, a), (_, _, b)| a.total_cmp(b))?; + let position = strength_center.unwrap_or(position); let strength = hostile_objects() .filter(|&(_, class, _, candidate)| { class & crate::autodemo::MOBILE_UNIT != 0 @@ -229,6 +309,13 @@ mod tests { } #[test] + fn base_radius_excludes_buildings_beyond_the_limit_and_caps_the_margin() { + assert_eq!(base_radius(700.0, [300.0, 700.0, 750.0]), 400.0); + assert_eq!(base_radius(700.0, [650.0]), 700.0); + assert_eq!(base_radius(40.0, []), 40.0); + } + + #[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 1d8665c3..72c291b5 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -2528,8 +2528,12 @@ fn load_mission_with_options( unit_patrol = Some(patrol); } } + let mut clan_ai_events = clan_ai_events::ClanAiEvents::default(); for order in init_orders { match order { + clan_script_init::InitOrder::BaseRadius { clan, limit } => { + clan_ai_events.set_base_radius(clan, limit); + } clan_script_init::InitOrder::Patrol(order) => { let Some(patrol) = &mut unit_patrol else { continue; @@ -2689,7 +2693,7 @@ fn load_mission_with_options( script_init_states: loaded_scripts.init_states, script_varset_states: loaded_scripts.varset_states, mission_events, - clan_ai_events: clan_ai_events::ClanAiEvents::default(), + clan_ai_events, mine_sites, unit_patrol, player_pitch_bits: 0, @@ -2915,6 +2919,7 @@ 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_attack_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. @@ -2960,6 +2965,7 @@ pub fn simulate_mission_report( script_factory_orders: Vec::new(), script_strength_queries: Vec::new(), script_capture_queries: Vec::new(), + script_attack_queries: Vec::new(), script_capturer_queries: Vec::new(), script_capture_approaches: Vec::new(), first_factory_completion_ms: Default::default(), @@ -3045,6 +3051,9 @@ pub fn simulate_mission_report( .script_capture_queries .extend(loaded.clan_ai_events.capture_queries()); report + .script_attack_queries + .extend(loaded.clan_ai_events.attack_queries()); + report .script_capturer_queries .extend(loaded.clan_ai_events.capturer_queries()); report @@ -8280,6 +8289,10 @@ fn resolve_init_states( if let Some(write) = script_time::deadline_write(instruction, values) { return Some(Some(write)); } + if let Some(limit) = clan_script_init::base_radius(instruction, values) { + init_orders.push(clan_script_init::InitOrder::BaseRadius { clan, limit }); + return Some(None); + } if let Some(order) = clan_script_init::unit_order(&varset.declarations, instruction, values) { |
