diff options
Diffstat (limited to 'crates/fparkan-runtime/src/unit_patrol')
| -rw-r--r-- | crates/fparkan-runtime/src/unit_patrol/orders.rs | 35 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_patrol/search_and_destroy.rs | 175 |
2 files changed, 207 insertions, 3 deletions
diff --git a/crates/fparkan-runtime/src/unit_patrol/orders.rs b/crates/fparkan-runtime/src/unit_patrol/orders.rs index 48a849f3..b956c599 100644 --- a/crates/fparkan-runtime/src/unit_patrol/orders.rs +++ b/crates/fparkan-runtime/src/unit_patrol/orders.rs @@ -15,6 +15,7 @@ pub(crate) enum UnitOrder { Stand, Route(Vec<[f32; 2]>), StrategicPatrol(PatrolTarget), + SearchAndDestroy, Shutdown, Resume(Box<PatrollingUnit>), } @@ -25,6 +26,7 @@ impl UnitOrder { Self::Move(_) | Self::Route(_) => 2, Self::Attack(..) => 3, Self::Patrol(..) | Self::StrategicPatrol(_) => 4, + Self::SearchAndDestroy => 5, Self::Shutdown => 0x13, Self::Stand => 0x15, Self::Resume(_) => unreachable!("a suspended order has already started"), @@ -82,6 +84,8 @@ impl UnitPatrol { }; if unit.capture_target.is_some() { 0x11 + } else if unit.search.is_some() { + UnitOrder::SearchAndDestroy.opcode() } else if unit.attack_target.is_some() || unit.raid_factory.is_some() { 3 } else if unit @@ -99,8 +103,9 @@ impl UnitPatrol { pub(crate) fn satellite_route(&self, actor: ObjectHandle) -> Vec<[f32; 2]> { let active = self.units.iter().find(|unit| unit.handle == actor); - // iron3d+0x77ae0 prefers the path whenever there are unvisited points. - if let Some(unit) = active.filter(|unit| !unit.points.is_empty()) { + // iron3d+0x77ae0 draws published waypoints. Search does not publish its + // internal navigation path to the satellite map. + if let Some(unit) = active.filter(|unit| unit.search.is_none() && !unit.points.is_empty()) { return unit.points.iter().copied().collect(); } let mut points = Vec::new(); @@ -119,7 +124,10 @@ impl UnitPatrol { UnitOrder::Route(route) => points.extend(route), UnitOrder::StrategicPatrol(PatrolTarget::Point(point)) => points.push(*point), UnitOrder::StrategicPatrol(PatrolTarget::Object(_)) => {} - UnitOrder::Attack(..) | UnitOrder::Shutdown | UnitOrder::Stand => {} + UnitOrder::Attack(..) + | UnitOrder::Shutdown + | UnitOrder::Stand + | UnitOrder::SearchAndDestroy => {} } } } @@ -299,6 +307,7 @@ impl UnitPatrol { self.standing.insert(actor); return true; } + UnitOrder::SearchAndDestroy => return self.start_search(world, actor), UnitOrder::Route(route) => { for (index, &point) in route.iter().enumerate() { self.move_to(world, actor, point, index != 0); @@ -494,6 +503,26 @@ mod tests { } #[test] + fn command_panel_search_replaces_the_route_without_a_target_click() { + let mut world = fparkan_world::new(Default::default()); + let actor = object(&mut world); + let mut patrol = UnitPatrol::scripted(); + patrol.command_order(&world, actor, UnitOrder::Route(vec![[45.0, 60.0]])); + + patrol.command_order(&world, actor, UnitOrder::SearchAndDestroy); + assert_eq!(patrol.active_order_code(actor), 5); + assert!(patrol.satellite_route(actor).is_empty()); + patrol.units[0].points = VecDeque::from([[25.0, 35.0]]); + assert!(patrol.satellite_route(actor).is_empty()); + assert_eq!(patrol.search_target(actor), Some(None)); + assert!(patrol.attack_limit(&world, actor).is_none()); + + patrol.command_order(&world, actor, UnitOrder::Stand); + assert_eq!(patrol.active_order_code(actor), 0x15); + assert_eq!(patrol.search_target(actor), None); + } + + #[test] fn command_panel_patrol_replaces_the_route_and_tracks_an_object_center() { let mut world = fparkan_world::new(Default::default()); let actor = object(&mut world); diff --git a/crates/fparkan-runtime/src/unit_patrol/search_and_destroy.rs b/crates/fparkan-runtime/src/unit_patrol/search_and_destroy.rs new file mode 100644 index 00000000..08cf355c --- /dev/null +++ b/crates/fparkan-runtime/src/unit_patrol/search_and_destroy.rs @@ -0,0 +1,175 @@ +//! Behavior task 5 in mode 0x204: find a reachable hostile mobile unit. + +use super::{ObjectHandle, UnitPatrol, World}; +use crate::{ + attack_target, next_crt_rand, route_motion::route_points, EngineError, LoadedMissionState, + MissionControlDeviceTableState, +}; +use fparkan_terrain::{NavigationQuery, SurfaceQuery}; +use fparkan_world::{identity_metadata, registration_sequence, transform_state}; +use std::collections::VecDeque; + +#[derive(Clone, Default)] +pub(super) struct Search { + target: Option<ObjectHandle>, +} + +impl UnitPatrol { + pub(super) fn start_search(&mut self, world: &World, actor: ObjectHandle) -> bool { + let Ok(pose) = transform_state(world, actor) else { + return false; + }; + let [x, y, _] = pose.position.map(f32::from_bits); + self.order(world, actor, [x, y], f32::INFINITY); + if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == actor) { + unit.search = Some(Search::default()); + } + true + } + + /// Outer option denotes an active search, inner option its current target. + pub(crate) fn search_target(&self, actor: ObjectHandle) -> Option<Option<ObjectHandle>> { + let unit = self.units.iter().find(|unit| unit.handle == actor)?; + Some(unit.search.as_ref()?.target) + } +} + +impl Search { + pub(super) fn forget_depleted( + &mut self, + world: &World, + controls: &[MissionControlDeviceTableState], + ) -> bool { + if self + .target + .is_some_and(|target| attack_target::complete(world, controls, target)) + { + self.target = None; + return true; + } + false + } + + pub(super) fn route( + &mut self, + world: &World, + mission: &LoadedMissionState, + actor: ObjectHandle, + from: [f32; 3], + crt: &mut u32, + ) -> Result<VecDeque<[f32; 2]>, EngineError> { + let terrain = &mission.terrain; + let clans = &mission.mission.clans; + let owner = identity_metadata(world, actor) + .ok() + .and_then(|meta| meta.owner_id); + let clan = owner.and_then(|owner| clans.get(usize::from(owner.0))); + // Behavior+0x30d27 walks native object groups. Use the live Control registry + // until the search task's native group membership is available. + let candidates = mission.control_device_tables.iter().filter_map(|table| { + let handle = table.handle; + let class = mission + .object_drafts + .get(table.original_id?.0 as usize)? + .unit_dat_header_flags?; + let target_owner = identity_metadata(world, handle).ok()?.owner_id?; + let target_clan = clans.get(usize::from(target_owner.0))?; + if Some(target_owner) == owner + || !clan?.relations.iter().any(|relation| { + relation.relation_value == 0 + && relation.other_clan_name.raw == target_clan.name.raw + }) + || table.node_provider_depletion_marked + || registration_sequence(world, handle).ok()?.is_none() + { + return None; + } + let position = transform_state(world, handle) + .ok()? + .position + .map(f32::from_bits); + (position != [0.0; 3]).then_some((handle, class, position)) + }); + if let Some((target, points)) = + nearest_reachable(candidates, from, |goal| route_points(terrain, from, goal))? + { + self.target = Some(target); + return Ok(points); + } + self.target = None; + let Some(bounds) = terrain.surface_bounds() else { + return Ok(VecDeque::new()); + }; + // Behavior+0x30ecd draws up to 150 points, inset 100 units from each edge. + for _ in 0..150 { + let xy = [0, 1].map(|axis| { + let fraction = next_crt_rand(crt) as f32 * (1.0 / 32767.0); + bounds[0][axis] + 100.0 + fraction * (bounds[1][axis] - bounds[0][axis] - 200.0) + }); + let Some(z) = terrain.height_at(xy).map_err(EngineError::Terrain)? else { + continue; + }; + let goal = [xy[0], xy[1], z]; + let areal = terrain.locate_areal(goal).map_err(EngineError::Terrain)?; + if areal + .and_then(|areal| terrain.areal_logic_flag(areal)) + .is_some_and(|flag| flag != 0) + { + return Ok(route_points(terrain, from, goal)?.unwrap_or_default()); + } + } + Ok(VecDeque::new()) + } +} + +fn nearest_reachable<T>( + candidates: impl Iterator<Item = (ObjectHandle, u32, [f32; 3])>, + from: [f32; 3], + mut route_to: impl FnMut([f32; 3]) -> Result<Option<T>, EngineError>, +) -> Result<Option<(ObjectHandle, T)>, EngineError> { + let mut best_distance = 3000.0; + let mut best = None; + for (handle, class, to) in candidates { + if class == 0 || class & 0x0100_e000 != class { + continue; + } + let [dx, dy, dz] = std::array::from_fn(|axis| to[axis] - from[axis]); + let distance = dx.hypot(dy).hypot(dz); + if distance <= best_distance { + if let Some(route) = route_to(to)? { + best_distance = distance; + best = Some((handle, route)); + } + } + } + Ok(best) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn search_prefers_the_last_equally_close_reachable_mobile_target() { + let handle = |slot| ObjectHandle { + slot, + generation: 1, + }; + let closest = [10.0, 0.0, 0.0]; + let blocked = [0.0, 0.0, 9.0]; + let last = [-10.0, 0.0, 0.0]; + let candidates = [ + (handle(0), 0x0100_4000, closest), + (handle(1), 0x0100_8000, blocked), + (handle(2), 0x8001_0000, [1.0, 0.0, 0.0]), + (handle(3), 0x0100_2000, last), + (handle(4), 0x0100_4000, [3000.0, 0.0, 15.0]), + ]; + let selected = nearest_reachable(candidates.into_iter(), [0.0; 3], |point| { + assert!(point == closest || point == blocked || point == last); + Ok((point != blocked).then_some(point)) + }) + .unwrap(); + assert_eq!(selected, Some((handle(3), last))); + } +} |
