diff options
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 76 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_targeting.rs | 107 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 4 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/mission_events.rs | 156 |
4 files changed, 225 insertions, 118 deletions
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index 7e83a7e9..9745c8d0 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_targeting::CaptureApproach; use crate::{BehaviorOreState, LoadedMissionState, MissionEventStop}; use fparkan_script::{ Handler15TargetPayload, Handler2Record, Handler2RecordInput, Handler2RecordKey, @@ -17,18 +18,63 @@ pub(super) struct ScriptFactoryOrder { wait_for_factory: bool, } +pub(super) fn resolve_captures( + engine: &mut crate::Engine, + now_ms: u32, +) -> Result<bool, crate::EngineError> { + let Some(loaded) = &mut engine.loaded else { + return Ok(false); + }; + let mut captured = false; + let mut index = 0; + while let Some(&(owner, key, approach)) = loaded.clan_ai_events.capture_orders.get(index) { + let valid_unit = identity_metadata(&engine.world, approach.unit) + .is_ok_and(|identity| identity.owner_id == Some(owner)); + let target = identity_metadata(&engine.world, approach.target).ok(); + let target = target + .and_then(|identity| identity.original_id.zip(identity.owner_id)) + .filter(|&(_, former_owner)| valid_unit && former_owner != owner); + if let Some((id, former_owner)) = target { + if !approach.reached(&engine.world) { + index += 1; + continue; + } + if let Some(class) = loaded + .object_drafts + .get(id.0 as usize) + .and_then(|draft| draft.unit_dat_header_flags) + { + loaded.transfer_building( + &mut engine.world, + approach.target, + id, + former_owner, + owner, + class, + )?; + captured = true; + eprintln!( + "script_building_captured clan={} unit={} target={} queue_time_ms={now_ms}", + owner.0, approach.unit.slot, approach.target.slot + ); + } + } + 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); + } + } + Ok(captured) +} + 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 @@ -97,7 +143,7 @@ pub(super) struct ClanAiEvents { strength_queries: BTreeMap<(usize, u16), u64>, capture_queries: BTreeMap<usize, u64>, capturer_queries: BTreeMap<usize, u64>, - capture_orders: Vec<(OwnerId, Handler2RecordKey, ObjectHandle, ObjectHandle)>, + capture_orders: Vec<(OwnerId, Handler2RecordKey, CaptureApproach)>, capture_approaches: BTreeMap<(u32, u32), u64>, } @@ -279,11 +325,11 @@ impl LoadedMissionState { 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, + &mut self.unit_patrol, world, &self.object_drafts, &self.mission_assets, 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; + if let Some(approach) = approach { + self.clan_ai_events.capture_orders.push((OwnerId(clan as u16), problem.key, approach)); + *self.clan_ai_events.capture_approaches.entry((approach.unit.slot, approach.target.slot)).or_default() += 1; } return Ok(Some(VarSetDefault::Dword(u32::from(approach.is_some())))); } @@ -438,7 +484,7 @@ impl LoadedMissionState { 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.clan_ai_events.capture_orders.iter().any(|&(_, _, order)| order.unit == handle) && self.unit_patrol.as_ref().is_none_or(|patrol| !patrol.is_shut_down(handle)) }, ); @@ -651,7 +697,7 @@ impl LoadedMissionState { .clan_ai_events .capture_orders .iter() - .any(|&(owner, key, _, _)| { + .any(|&(owner, key, _)| { owner == OwnerId(clan as u16) && key == problem.key }) { diff --git a/crates/fparkan-runtime/src/clan_targeting.rs b/crates/fparkan-runtime/src/clan_targeting.rs index 05ac970a..5b5a4786 100644 --- a/crates/fparkan-runtime/src/clan_targeting.rs +++ b/crates/fparkan-runtime/src/clan_targeting.rs @@ -15,28 +15,42 @@ pub(super) struct Capturer { target_id: u32, } +#[derive(Clone, Copy)] +pub(super) struct CaptureApproach { + pub(super) unit: ObjectHandle, + pub(super) target: ObjectHandle, + point: [f32; 3], +} + pub(super) fn send_capturer( patrol: &mut Option<crate::unit_patrol::UnitPatrol>, world: &World, drafts: &[MissionObjectDraft], + assets: &crate::MissionAssets, unit: Capturer, target_id: u32, -) -> Option<(ObjectHandle, ObjectHandle)> { +) -> Option<CaptureApproach> { let pose = transform_state(world, unit.target).ok()?; let target = identity_metadata(world, unit.target).ok()?; + let index = target.original_id?.0 as usize; + let class = drafts.get(index)?.unit_dat_header_flags?; 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) + || class == 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. + let from = transform_state(world, unit.handle) + .ok()? + .position + .map(f32::from_bits); + // shortcut: use the communicator mesh until the native door and interior route are wired. + let point = nearest_platform_point( + crate::mission_events::communicator_triangles(assets, index, class, pose)?, + from, + )?; + let [x, y, _] = point; patrol .get_or_insert_with(crate::unit_patrol::UnitPatrol::scripted) .move_to(world, unit.handle, [x, y], false); @@ -44,7 +58,36 @@ pub(super) fn send_capturer( "sim_coverage script_capture_approach_stub=1 unit={} target={} target_id={target_id}", unit.handle.slot, unit.target.slot ); - Some((unit.handle, unit.target)) + Some(CaptureApproach { + unit: unit.handle, + target: unit.target, + point, + }) +} + +fn nearest_platform_point(triangles: Vec<[[f32; 3]; 3]>, from: [f32; 3]) -> Option<[f32; 3]> { + triangles + .into_iter() + .map(|[a, b, c]| std::array::from_fn(|axis| (a[axis] + b[axis] + c[axis]) / 3.0)) + .min_by(|a, b| distance_squared(from, *a).total_cmp(&distance_squared(from, *b))) +} + +fn distance_squared(from: [f32; 3], to: [f32; 3]) -> f32 { + from.into_iter() + .zip(to) + .map(|(from, to)| (from - to).powi(2)) + .sum() +} + +impl CaptureApproach { + pub(super) fn reached(self, world: &World) -> bool { + transform_state(world, self.unit) + .is_ok_and(|pose| at_platform(pose.position.map(f32::from_bits), self.point)) + } +} + +fn at_platform([x, y, z]: [f32; 3], [tx, ty, tz]: [f32; 3]) -> bool { + (x - tx).hypot(y - ty) <= 0.05 && (z - tz).abs() <= 2.0 } pub(super) fn nearest_capturer( @@ -164,40 +207,28 @@ 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; + fn approach_targets_the_nearest_platform_triangle() { 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 + nearest_platform_point( + vec![ + [[12., 10., 0.], [15., 10., 0.], [12., 13., 0.]], + [[0., 0., 2.], [3., 0., 2.], [0., 3., 2.]], + ], + [1., 1., 0.], + ), + Some([1., 1., 2.]) ); } #[test] + fn capture_requires_the_platform_height_as_well_as_the_route_endpoint() { + let platform = [425.7, 326.9, 61.1]; + assert!(!at_platform([425.7, 326.9, 76.6], platform)); + assert!(!at_platform([425.8, 326.9, 61.1], platform)); + assert!(at_platform([425.7, 326.9, 61.1], platform)); + } + + #[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 5eefdd33..1d8665c3 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -2800,7 +2800,9 @@ pub fn step_headless( if let (Some(combat), Some(unit)) = (&mut engine.autodemo_combat, produced_unit) { combat.activate(&engine.world, unit.object_index, unit.handle); } - if produced_unit.is_some() + let building_captured = clan_ai_events::resolve_captures(engine, queue_time_ms)?; + if building_captured + || produced_unit.is_some() || !autodemo_reinforcements.is_empty() || autodemo_combat_events .iter() diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs index ee189ca9..e90743fd 100644 --- a/crates/fparkan-runtime/src/mission_events.rs +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -442,9 +442,33 @@ fn capture_building_at_communicator( }) }); if let Some((handle, id, former_owner, class)) = candidate { - set_owner(&mut engine.world, handle, Some(player_owner))?; + mission.transfer_building( + &mut engine.world, + handle, + id, + former_owner, + player_owner, + class, + )?; + Ok(Some(id)) + } else { + Ok(None) + } +} + +impl LoadedMissionState { + pub(super) fn transfer_building( + &mut self, + world: &mut World, + handle: ObjectHandle, + id: OriginalObjectId, + former_owner: OwnerId, + new_owner: OwnerId, + class: u32, + ) -> Result<(), EngineError> { + set_owner(world, handle, Some(new_owner))?; if has_behavior_registration_key(class) { - let distributors = &mut mission.behavior_distributors; + let distributors = &mut self.behavior_distributors; if let Some(previous) = distributors.get_mut(usize::from(former_owner.0)) { let count = previous.registered_objects.len(); previous @@ -455,7 +479,7 @@ fn capture_building_at_communicator( } } if let Some(next) = distributors - .get_mut(usize::from(player_owner.0)) + .get_mut(usize::from(new_owner.0)) .filter(|entry| entry.super_ai_visible) { add_behavior_registered_object( @@ -463,7 +487,7 @@ fn capture_building_at_communicator( BehaviorRegisteredObject { original_id: id, handle, - selector: u32::from(player_owner.0), + selector: u32::from(new_owner.0), class_flags: class, share: 0.0, native_tail: [0; 5], @@ -471,9 +495,7 @@ fn capture_building_at_communicator( ); } } - Ok(Some(id)) - } else { - Ok(None) + Ok(()) } } @@ -484,6 +506,21 @@ pub(super) fn on_communicator( pose: super::TransformState, [x, y, z]: [f32; 3], ) -> bool { + let platform_height = communicator_triangles(assets, object_index, class, pose) + .into_iter() + .flatten() + .filter(|triangle| in_tactical_polygon(triangle, x, y)) + .map(|[a, b, c]| a[2].max(b[2]).max(c[2])) + .max_by(f32::total_cmp); + platform_height.is_some_and(|height| (z - height).abs() <= 2.0) +} + +pub(super) fn communicator_triangles( + assets: &super::MissionAssets, + object_index: usize, + class: u32, + pose: super::TransformState, +) -> Option<Vec<[[f32; 3]; 3]>> { let is_generator = class == 0x8000_0002; let floor_only = is_generator || class == MAIN_TELEPORT_CLASS; let material = if is_generator { @@ -491,77 +528,68 @@ pub(super) fn on_communicator( } else { &b"B_COMP_4G"[..] }; - let Some(visual) = assets + let visual = assets .visual_for_object(object_index) - .and_then(|id| assets.visual_by_id(id)) - else { - return false; - }; + .and_then(|id| assets.visual_by_id(id))?; if visual.source_type != Some(u32::from_le_bytes(*b"FORT")) { - return false; + return None; } - let Some(wear) = assets + let wear = assets .wears .iter() - .find(|wear| Some(wear.id) == visual.wear_id) - else { - return false; - }; - let Some(model) = visual + .find(|wear| Some(wear.id) == visual.wear_id)?; + let model = visual .model_id .and_then(|id| assets.model_by_id(id)) - .map(|model| &model.validated) - else { - return false; - }; - let Some(hierarchy) = node38_sampled_hierarchy(model, 0) else { - return false; - }; + .map(|model| &model.validated)?; + let hierarchy = node38_sampled_hierarchy(model, 0)?; let transform = LegacyIron3dEulerTransform { translation: pose.position.map(f32::from_bits), orientation_radians: pose.orientation.map(f32::from_bits), }; let scale = pose.scale.map(f32::from_bits); // shortcut: use the green platform mesh until the native volume is known. - let platform_height = hierarchy - .poses - .iter() - .enumerate() - .filter_map(|(index, pose)| { - let slot = selected_slot(model, NodeId(index as u32), Lod(0), Group(0))?; - Some((*pose, draw_batches(model, slot).ok()?)) - }) - .flat_map(|(pose, batches)| batches.iter().map(move |batch| (pose, batch))) - .filter(|(_, batch)| { - wear.table - .entries - .get(usize::from(batch.material_index)) - .is_some_and(|entry| entry.material.0.eq_ignore_ascii_case(material)) - }) - .flat_map(|(pose, batch)| { - let first = batch.index_start as usize; - let end = first + usize::from(batch.index_count); - model.indices[first..end] - .chunks_exact(3) - .filter_map(move |indices| { - let [a, b, c] = [indices[0], indices[1], indices[2]].map(|index| { - let local = - model.positions[batch.base_vertex as usize + usize::from(index)]; - transform.try_transform_scaled_point(pose.transform_point(local), scale) - }); - let (a, b, c) = (a?, b?, c?); - if floor_only { - // These models use the platform material on both the floor and the surface above it. - let winding = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); - if winding <= 0.0 { - return None; + Some( + hierarchy + .poses + .iter() + .enumerate() + .filter_map(|(index, pose)| { + let slot = selected_slot(model, NodeId(index as u32), Lod(0), Group(0))?; + Some((*pose, draw_batches(model, slot).ok()?)) + }) + .flat_map(|(pose, batches)| batches.iter().map(move |batch| (pose, batch))) + .filter(|(_, batch)| { + wear.table + .entries + .get(usize::from(batch.material_index)) + .is_some_and(|entry| entry.material.0.eq_ignore_ascii_case(material)) + }) + .flat_map(|(pose, batch)| { + let first = batch.index_start as usize; + let end = first + usize::from(batch.index_count); + model.indices[first..end] + .chunks_exact(3) + .filter_map(move |indices| { + let [a, b, c] = [indices[0], indices[1], indices[2]].map(|index| { + let local = + model.positions[batch.base_vertex as usize + usize::from(index)]; + transform.try_transform_scaled_point(pose.transform_point(local), scale) + }); + let (a, b, c) = (a?, b?, c?); + if floor_only { + // These models use the platform material on both the floor and the surface above it. + let winding = + (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + if winding <= 0.0 { + return None; + } } - } - in_tactical_polygon(&[a, b, c], x, y).then_some(a[2].max(b[2]).max(c[2])) - }) - }) - .max_by(f32::total_cmp); - platform_height.is_some_and(|height| (z - height).abs() <= 2.0) + Some([a, b, c]) + }) + }) + .collect(), + ) } impl LoadedMissionState { |
