diff options
Diffstat (limited to 'crates/fparkan-runtime')
| -rw-r--r-- | crates/fparkan-runtime/src/building_door.rs | 36 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/building_passage.rs | 200 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 7 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_targeting.rs | 35 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 2 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_combat.rs | 21 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_patrol.rs | 103 |
7 files changed, 359 insertions, 45 deletions
diff --git a/crates/fparkan-runtime/src/building_door.rs b/crates/fparkan-runtime/src/building_door.rs index 0d9c88a1..9ac89206 100644 --- a/crates/fparkan-runtime/src/building_door.rs +++ b/crates/fparkan-runtime/src/building_door.rs @@ -2,6 +2,8 @@ use fparkan_assets::PreparedComponentControl; use fparkan_msh::{selected_slot, Group, Lod, ModelAsset, NodeId}; use fparkan_render::LegacyIron3dEulerTransform; +pub(super) const DOOR_BLEND_PER_SECOND: f32 = 2.0; + /// Whether this controller has a door record with a supported node binding. pub fn has_proximity_doors(control: &PreparedComponentControl) -> bool { door_bindings(control).next().is_some() @@ -25,6 +27,38 @@ fn door_bindings( }) } +pub(super) fn is_bound_door(control: &PreparedComponentControl, key: u32) -> bool { + door_bindings(control).any(|binding| binding.node_index == key as usize) +} + +/// Mixes the active hallway door request into the capture target's pose. +pub fn sample_capture_doors( + engine: &crate::Engine, + handle: crate::ObjectHandle, + control: &PreparedComponentControl, + blends: &mut Vec<f32>, + times: &mut [Option<f32>], +) { + let Some(patrol) = engine + .loaded + .as_ref() + .and_then(|mission| mission.unit_patrol.as_ref()) + else { + return; + }; + for (node, requested) in patrol.hallway_doors(handle) { + let Some(binding) = door_bindings(control).find(|binding| binding.node_index == node) + else { + continue; + }; + blends.resize(control.model_node_count, 0.0); + if let (Some(blend), Some(time)) = (blends.get_mut(node), times.get_mut(node)) { + *blend = blend.max(requested); + *time = Some(binding.frame_a + (binding.frame_b - binding.frame_a) * *blend); + } + } +} + /// Updates the authored door tracks next to the player. pub fn sample_proximity_doors( control: &PreparedComponentControl, @@ -72,7 +106,7 @@ pub fn sample_proximity_doors( } else { -1.0 }; - *blend = (*blend + direction * delta_seconds * 2.0).clamp(0.0, 1.0); + *blend = (*blend + direction * delta_seconds * DOOR_BLEND_PER_SECOND).clamp(0.0, 1.0); if let Some(time) = times.get_mut(index) { *time = Some(binding.frame_a + (binding.frame_b - binding.frame_a) * *blend); } diff --git a/crates/fparkan-runtime/src/building_passage.rs b/crates/fparkan-runtime/src/building_passage.rs index 9ed02556..e4304a99 100644 --- a/crates/fparkan-runtime/src/building_passage.rs +++ b/crates/fparkan-runtime/src/building_passage.rs @@ -1,10 +1,14 @@ -//! Exterior approach to a capture point in a building's authored hallway. +//! Approaches and doors along a building's authored route to the capture point. use crate::{ - projectile_parts::root_model, route_motion::route_points, route_obstacles::model_footprint, - MissionAssets, TerrainWorld, + building_door::{is_bound_door, DOOR_BLEND_PER_SECOND}, + projectile_parts::root_model, + route_motion::{route_points, turn_toward, WAYPOINT_TOLERANCE}, + route_obstacles::{model_footprint, Footprint}, + MissionAssets, ObjectHandle, TerrainWorld, }; -use fparkan_msh::{node38_fallback_hierarchy, Hallway}; +use fparkan_assets::PreparedComponentControl; +use fparkan_msh::{node38_fallback_hierarchy, Hallway, HallwayLink}; use fparkan_render::LegacyIron3dEulerTransform; use fparkan_terrain::SurfaceQuery; use fparkan_world::TransformState; @@ -13,6 +17,20 @@ use std::collections::VecDeque; pub(super) struct CaptureEntrance { pub(super) staging: [f32; 2], pub(super) capture: [f32; 3], + pub(super) legs: Option<VecDeque<PassageLeg>>, +} + +#[derive(Clone)] +pub(super) struct PassageLeg { + position: [f32; 3], + door: Option<usize>, +} + +#[derive(Clone)] +pub(super) struct CapturePassage { + pub(super) building: ObjectHandle, + pub(super) legs: VecDeque<PassageLeg>, + pub(super) opening: Option<(usize, f32)>, } pub(super) fn capture_entrance( @@ -26,11 +44,16 @@ pub(super) fn capture_entrance( let model = &root_model(assets, index)?.validated; let hallway = &model.hallway; // Behavior::GoInside passes mask 0x40 to HallWay's first-match query. - let capture = hallway + let goal = hallway .points .iter() .position(|point| point.flags & 0x40 != 0)?; - let toward_capture = links_to(hallway, capture); + let toward_capture = links_to(hallway, goal); + let control = assets + .object_component_controls + .get(index)? + .first()? + .as_ref()?; let hierarchy = node38_fallback_hierarchy(model)?; let transform = LegacyIron3dEulerTransform { translation: pose.position.map(f32::from_bits), @@ -42,7 +65,7 @@ pub(super) fn capture_entrance( let node = hierarchy.poses.get(point.node.0 as usize)?; transform.try_transform_scaled_point(node.transform_point(point.position), scale) }; - let capture = project(capture)?; + let capture = project(goal)?; let footprint = model_footprint(assets, index, pose)?.expanded(clearance); hallway .points @@ -51,7 +74,7 @@ pub(super) fn capture_entrance( .filter(|(_, point)| point.flags & 0x1000_0001 == 1) .filter_map(|(index, _)| { let entrance = project(index)?; - let inside = project(toward_capture[index]?)?; + let inside = project(toward_capture[index]?.0)?; let staging = footprint.exterior_along( [entrance[0], entrance[1]], [entrance[0] - inside[0], entrance[1] - inside[1]], @@ -59,18 +82,27 @@ pub(super) fn capture_entrance( let ground = terrain.height_at(staging).ok()??; route_points(terrain, from, [staging[0], staging[1], ground]).ok()??; let distance: f32 = (0..3).map(|i| (from[i] - entrance[i]).powi(2)).sum(); - Some((distance, CaptureEntrance { staging, capture })) + let legs = passage_legs(index, goal, &toward_capture, hallway, control, project); + Some(( + distance, + CaptureEntrance { + staging, + capture, + legs, + }, + )) }) .min_by(|a, b| a.0.total_cmp(&b.0)) .map(|(_, entrance)| entrance) } -fn links_to(hallway: &Hallway, goal: usize) -> Vec<Option<usize>> { +fn links_to(hallway: &Hallway, goal: usize) -> Vec<Option<(usize, usize)>> { let mut next = vec![None; hallway.points.len()]; - next[goal] = Some(goal); + next[goal] = Some((goal, usize::MAX)); let mut queue = VecDeque::from([goal]); while let Some(point) = queue.pop_front() { - for &[a, b] in &hallway.links { + for (index, link) in hallway.links.iter().enumerate() { + let [a, b] = link.endpoints; let (a, b) = (a as usize, b as usize); let neighbor = if a == point { b @@ -80,7 +112,7 @@ fn links_to(hallway: &Hallway, goal: usize) -> Vec<Option<usize>> { continue; }; if let Some(slot @ None) = next.get_mut(neighbor) { - *slot = Some(point); + *slot = Some((point, index)); queue.push_back(neighbor); } } @@ -88,6 +120,106 @@ fn links_to(hallway: &Hallway, goal: usize) -> Vec<Option<usize>> { next } +fn passage_legs( + mut point: usize, + goal: usize, + steps: &[Option<(usize, usize)>], + hallway: &Hallway, + control: &PreparedComponentControl, + project: impl Fn(usize) -> Option<[f32; 3]>, +) -> Option<VecDeque<PassageLeg>> { + let mut legs = VecDeque::from([PassageLeg { + position: project(point)?, + door: None, + }]); + while point != goal { + let (next, link) = steps[point]?; + let door = linked_door(&hallway.links[link], control)?; + legs.push_back(PassageLeg { + position: project(next)?, + door, + }); + point = next; + } + Some(legs) +} + +fn linked_door(link: &HallwayLink, control: &PreparedComponentControl) -> Option<Option<usize>> { + let [[key, mask], ..] = link.access; + if link.access != [[key, mask]; 4] { + return None; + } + if [key, mask] == [u32::MAX; 2] { + return Some(None); + } + (mask == 1 && is_bound_door(control, key)).then_some(Some(key as usize)) +} + +impl CapturePassage { + pub(super) fn advance( + &mut self, + mut pose: TransformState, + speed: f32, + mut seconds: f32, + neighbors: &[Footprint], + ) -> (TransformState, Footprint) { + let [x, y, _] = pose.position.map(f32::from_bits); + let mut swept = Footprint::point([x, y]); + while let Some(leg) = self.legs.front() { + if seconds <= 0.0 || speed <= 0.0 { + break; + } + let from = pose.position.map(f32::from_bits); + let [x, y, _] = from; + let [tx, ty, _] = leg.position; + if neighbors + .iter() + .any(|bounds| bounds.intersects([x, y], [tx, ty])) + { + break; + } + if let Some(door) = leg.door { + let blend = self + .opening + .filter(|&(node, _)| node == door) + .map_or(0.0, |(_, blend)| blend); + let delay = seconds.min((1.0 - blend) / DOOR_BLEND_PER_SECOND); + self.opening = Some((door, (blend + delay * DOOR_BLEND_PER_SECOND).min(1.0))); + seconds -= delay; + if seconds == 0.0 { + break; + } + } + let delta = std::array::from_fn::<_, 3, _>(|axis| leg.position[axis] - from[axis]); + let distance = delta[0].hypot(delta[1]).hypot(delta[2]); + if delta[0].hypot(delta[1]) > WAYPOINT_TOLERANCE { + let (yaw, delay) = turn_toward( + f32::from_bits(pose.orientation[2]), + [delta[0], delta[1]], + seconds, + ); + pose.orientation[2] = yaw.to_bits(); + seconds -= delay; + } + let duration = distance / speed; + let reached = duration <= seconds; + let next = if reached { + leg.position + } else { + std::array::from_fn(|axis| from[axis] + delta[axis] * (seconds / duration)) + }; + pose.position = next.map(f32::to_bits); + swept.include([next[0], next[1]]); + if !reached { + break; + } + seconds -= duration; + self.legs.pop_front(); + } + (pose, swept) + } +} + #[cfg(test)] mod tests { use super::*; @@ -104,11 +236,49 @@ mod tests { }; 5 ], - links: vec![[1, 0], [1, 2], [2, 3], [3, 0], [4, 9]], + links: [[1, 0], [1, 2], [2, 3], [3, 0], [4, 9]] + .map(|endpoints| HallwayLink { + endpoints, + access: [[u32::MAX; 2]; 4], + }) + .to_vec(), }; assert_eq!( links_to(&hallway, 3), - [Some(3), Some(2), Some(3), Some(3), None] + [ + Some((3, 3)), + Some((2, 1)), + Some((3, 2)), + Some((3, usize::MAX)), + None + ] ); } + + #[test] + fn capture_link_waits_for_the_door_and_follows_the_sloped_passage() { + let mut route = CapturePassage { + building: ObjectHandle { + slot: 0, + generation: 1, + }, + legs: VecDeque::from([PassageLeg { + position: [0.0, 1.0, -1.0], + door: Some(12), + }]), + opening: None, + }; + let start = TransformState::default(); + let (waiting, _) = route.advance(start, 2.0, 0.25, &[]); + assert_eq!(waiting.position, start.position); + assert_eq!(route.opening, Some((12, 0.5))); + let (moving, _) = route.advance(waiting, 2.0, 0.5, &[]); + let [x, y, z] = moving.position.map(f32::from_bits); + assert_eq!(x, 0.0); + assert!((y - 0.5_f32 / 2.0_f32.sqrt()).abs() < 0.0001); + assert_eq!(z, -y); + let (arrived, _) = route.advance(moving, 2.0, 1.0, &[]); + assert_eq!(arrived.position.map(f32::from_bits), [0.0, 1.0, -1.0]); + assert!(route.legs.is_empty()); + } } diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index 30ceb573..0ccebdcb 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -72,6 +72,9 @@ pub(super) fn resolve_captures( ); } } + if let Some(patrol) = &mut loaded.unit_patrol { + patrol.clear_capture_passage(approach.unit, approach.target); + } loaded.clan_ai_events.capture_orders.remove(index); let clan = usize::from(owner.0); let ai = &mut loaded.clan_ai_events; @@ -810,7 +813,9 @@ impl LoadedMissionState { ); 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; + if approach.fallback { + *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())))); } diff --git a/crates/fparkan-runtime/src/clan_targeting.rs b/crates/fparkan-runtime/src/clan_targeting.rs index 14ecb4b7..b98afec0 100644 --- a/crates/fparkan-runtime/src/clan_targeting.rs +++ b/crates/fparkan-runtime/src/clan_targeting.rs @@ -1,7 +1,8 @@ use crate::{ - building_passage::capture_entrance, clan_combat_strength::unit_strength, - projectile::unit_sphere, MissionControlDeviceTableState, MissionDocument, MissionObjectDraft, - TerrainWorld, + building_passage::{capture_entrance, CapturePassage}, + clan_combat_strength::unit_strength, + projectile::unit_sphere, + MissionControlDeviceTableState, MissionDocument, MissionObjectDraft, TerrainWorld, }; use fparkan_world::{ handle_by_original_id, identity_metadata, registration_sequence, transform_state, ObjectHandle, @@ -20,6 +21,7 @@ pub(super) struct Capturer { pub(super) struct CaptureApproach { pub(super) unit: ObjectHandle, pub(super) target: ObjectHandle, + pub(super) fallback: bool, point: [f32; 3], } @@ -47,28 +49,35 @@ pub(super) fn send_capturer( let from = unit_pose.position.map(f32::from_bits); let unit_id = identity_metadata(world, unit.handle).ok()?.original_id?; let clearance = unit_sphere(assets, unit_id.0 as usize, unit_pose).map_or(0.0, |(_, r)| r); - let (destination, point) = + let (destination, point, passage) = if let Some(entrance) = capture_entrance(assets, terrain, index, pose, from, clearance) { - // shortcut: stop outside the connected door until movement on the - // indoor links and their gate messages are supported. - (entrance.staging, entrance.capture) + let passage = entrance.legs.map(|legs| CapturePassage { + building: unit.target, + legs, + opening: None, + }); + (entrance.staging, entrance.capture, passage) } else { let point = nearest_platform_point( crate::mission_events::communicator_triangles(assets, index, class, pose)?, from, )?; - ([point[0], point[1]], point) + ([point[0], point[1]], point, None) }; + let indoor_route = passage.is_some(); patrol .get_or_insert_with(crate::unit_patrol::UnitPatrol::scripted) - .move_to(world, unit.handle, destination, false); - eprintln!( - "sim_coverage script_capture_approach_stub=1 unit={} target={} target_id={target_id} destination={destination:?}", - unit.handle.slot, unit.target.slot - ); + .move_to_capture(world, unit.handle, destination, passage); + if !indoor_route { + eprintln!( + "sim_coverage script_capture_approach_stub=1 unit={} target={} target_id={target_id} destination={destination:?}", + unit.handle.slot, unit.target.slot + ); + } Some(CaptureApproach { unit: unit.handle, target: unit.target, + fallback: !indoor_route, point, }) } diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 9f3557af..fb21af54 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -143,7 +143,7 @@ pub use autodemo::{autodemo_camera, AutoDemoCamera, AutoDemoReinforcement, AutoD pub use boarding::{ board_friendly_warbot, disembark_warbot, player_vehicle, select_boarding_target, }; -pub use building_door::{has_proximity_doors, sample_proximity_doors}; +pub use building_door::{has_proximity_doors, sample_capture_doors, sample_proximity_doors}; pub use fparkan_assets::MissionAssets; pub use mesh_collision::{query_building_segment_world, BuildingMeshHit, BuildingMeshNode}; pub use mining::deploy_mine; diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs index eaadc159..c7d807cc 100644 --- a/crates/fparkan-runtime/src/unit_combat.rs +++ b/crates/fparkan-runtime/src/unit_combat.rs @@ -1106,10 +1106,15 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] - fn licensed_stock_capturer_and_defender_exchange_fire() { + fn licensed_stock_capturer_presses_through_defender_fire_and_takes_generator() { let mut engine = stock_two_fortresses(); let defender = mission_object_handle(&engine, OriginalObjectId(17)).unwrap(); let capturer = mission_object_handle(&engine, OriginalObjectId(11)).unwrap(); + let generator = mission_object_handle(&engine, OriginalObjectId(1)).unwrap(); + let original_owner = identity_metadata(&engine.world, generator) + .unwrap() + .owner_id; + assert_ne!(original_owner, Some(OwnerId(1))); let before = transform_state(&engine.world, defender).unwrap(); assert_eq!(mission_guard_fallback_count(&engine), 0); assert!(frame(&mut engine, 0) @@ -1119,7 +1124,7 @@ mod tests { let mut capturer_fired_while_moving = false; let mut defender_fired = false; - for tick in 1..=60 * 190 { + for tick in 1..=60 * 210 { let before_capturer = transform_state(&engine.world, capturer).ok(); let result = frame(&mut engine, tick * 1000 / 60).unwrap(); for event in result.autodemo_combat_events { @@ -1150,11 +1155,19 @@ mod tests { } } } - if capturer_fired_while_moving && defender_fired { + if identity_metadata(&engine.world, generator) + .unwrap() + .owner_id + == Some(OwnerId(1)) + { + assert!(capturer_fired_while_moving && defender_fired); + let position = transform_state(&engine.world, capturer).unwrap().position; + let roof = transform_state(&engine.world, generator).unwrap().position; + assert!(f32::from_bits(position[2]) < f32::from_bits(roof[2])); return; } } - panic!("expected both sides to fire (moving={capturer_fired_while_moving}, defender={defender_fired})"); + panic!("the first capturer did not take the generator (moving={capturer_fired_while_moving}, defender={defender_fired})"); } #[test] diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs index e73c2404..cfe49901 100644 --- a/crates/fparkan-runtime/src/unit_patrol.rs +++ b/crates/fparkan-runtime/src/unit_patrol.rs @@ -1,6 +1,7 @@ use super::{ autodemo::{MOBILE_UNIT, PLANT_CLASS}, boarding::WARBOT_CLASS, + building_passage::CapturePassage, factory_release::FactoryDeparture, flight_altitude::FlightClearance, ground_support::GroundSupport, @@ -53,6 +54,7 @@ struct PatrollingUnit { attack_target: Option<(ObjectHandle, usize)>, raid_factory: Option<(ObjectHandle, usize)>, ground_support: Option<Option<GroundSupport>>, + capture_passage: Option<CapturePassage>, } pub(super) struct PreparedPatrol { @@ -214,6 +216,7 @@ impl UnitPatrol { attack_target: None, raid_factory: None, ground_support: None, + capture_passage: None, }); true } @@ -244,6 +247,40 @@ impl UnitPatrol { } } + pub(super) fn move_to_capture( + &mut self, + world: &World, + handle: ObjectHandle, + destination: [f32; 2], + passage: Option<CapturePassage>, + ) { + self.move_to(world, handle, destination, false); + if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == handle) { + unit.capture_passage = passage; + } + } + + pub(super) fn hallway_doors( + &self, + building: ObjectHandle, + ) -> impl Iterator<Item = (usize, f32)> + '_ { + self.units + .iter() + .filter_map(|unit| unit.capture_passage.as_ref()) + .filter(move |route| route.building == building) + .filter_map(|route| route.opening) + } + + pub(super) fn clear_capture_passage(&mut self, unit: ObjectHandle, building: ObjectHandle) { + self.units.retain(|patrol| { + patrol.handle != unit + || patrol + .capture_passage + .as_ref() + .is_none_or(|route| route.building != building) + }); + } + pub(super) fn order_around_object( &mut self, world: &World, @@ -418,6 +455,7 @@ impl UnitPatrol { attack_target: None, raid_factory: None, ground_support: None, + capture_passage: None, }) .collect(); Some(Self { @@ -451,9 +489,14 @@ impl UnitPatrol { let mut state = self.clone(); state.advance_script_orders(world, &mission.control_device_tables); state.units.retain(|unit| { - unit.destinations + (unit + .destinations .as_ref() .is_none_or(|items| !items.is_empty()) + || unit + .capture_passage + .as_ref() + .is_some_and(|route| !route.legs.is_empty())) && unit.center(world).is_some() }); let seconds = now_ms.saturating_sub(state.clock_ms) as f32 * 0.001; @@ -503,6 +546,30 @@ impl UnitPatrol { unit.retry_ms = 0; } if destinations.is_empty() { + if let Some(route) = &mut unit.capture_passage { + if transform_state(world, route.building).is_err() { + route.legs.clear(); + continue; + } + let radius = traffic.radius(unit.handle); + let Some(neighbors) = + traffic.blockers(unit.handle, [from[0], from[1]], radius) + else { + continue; + }; + let speed = movement_speed( + mission, + unit.handle, + original_id, + UnitSpeedKind::Go, + &mut state.speed_report, + ); + let (after, swept) = route.advance(before, speed, seconds, &neighbors); + traffic.reserve(unit.handle, swept); + if after != before { + poses.push((unit.handle, before, after)); + } + } continue; } } @@ -681,15 +748,13 @@ impl UnitPatrol { } else { UnitSpeedKind::Go }; - let table = mission - .control_device_tables - .iter() - .find(|table| table.handle == unit.handle); - let behavior = mission - .behavior_profiles - .iter() - .find(|profile| profile.handle == unit.handle); - order_speed(table, behavior, original_id, kind, &mut state.speed_report) + movement_speed( + mission, + unit.handle, + original_id, + kind, + &mut state.speed_report, + ) } else { 9.0 }; @@ -719,6 +784,24 @@ impl UnitPatrol { } } +fn movement_speed( + mission: &LoadedMissionState, + handle: ObjectHandle, + original_id: u32, + kind: UnitSpeedKind, + report: &mut UnitSpeedReport, +) -> f32 { + let table = mission + .control_device_tables + .iter() + .find(|table| table.handle == handle); + let behavior = mission + .behavior_profiles + .iter() + .find(|profile| profile.handle == handle); + order_speed(table, behavior, original_id, kind, report) +} + #[cfg(test)] #[test] fn new_patrol_replaces_a_script_attack_order() { |
