From dfbdef7d4d1d295ee962dd8aab754ce6be902f8d Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Thu, 26 Nov 2026 12:16:16 +0400 Subject: fix(ai): follow capture passages through building doors A stock Two Fortresses run now takes the generator after the capturer descends its authored hallway. Symmetric Res17 door links drive the CTLD animation and unsupported routes retain explicit coverage. Checked the approach and descent in the game window with Vulkan validation and verified the owner transfer in a licensed test. --- apps/fparkan-game/src/main.rs | 13 ++ crates/fparkan-msh/src/hallway.rs | 27 +++- crates/fparkan-msh/src/lib.rs | 2 +- crates/fparkan-runtime/src/building_door.rs | 36 ++++- crates/fparkan-runtime/src/building_passage.rs | 200 +++++++++++++++++++++++-- crates/fparkan-runtime/src/clan_ai_events.rs | 7 +- crates/fparkan-runtime/src/clan_targeting.rs | 35 +++-- crates/fparkan-runtime/src/lib.rs | 2 +- crates/fparkan-runtime/src/unit_combat.rs | 21 ++- crates/fparkan-runtime/src/unit_patrol.rs | 103 +++++++++++-- docs/appendices/knowledge-boundaries.md | 7 +- docs/tomes/06-behavior.md | 17 ++- 12 files changed, 413 insertions(+), 57 deletions(-) diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index 4f90b9eb..6c33404a 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -7411,6 +7411,19 @@ fn update_gameplay_animation_pose_buffers( } } } + if component_index == 0 && fparkan_runtime::has_proximity_doors(&instance.control) { + if let Some((root, engine)) = motion.and_then(|(roots, _, engine)| { + Some((roots.get(object_index)?.as_ref()?, engine)) + }) { + fparkan_runtime::sample_capture_doors( + engine, + root.handle, + &instance.control, + &mut instance.door_blends, + &mut node_times, + ); + } + } let walking = motion.is_some_and(|(roots, snapshot, engine)| { roots .get(object_index) diff --git a/crates/fparkan-msh/src/hallway.rs b/crates/fparkan-msh/src/hallway.rs index d0d646d8..5145c3df 100644 --- a/crates/fparkan-msh/src/hallway.rs +++ b/crates/fparkan-msh/src/hallway.rs @@ -5,8 +5,17 @@ use crate::{read_f32, read_u32, MshError, NodeId, RawStream}; pub struct Hallway { /// Points in native selection order. pub points: Vec, - /// Start and end point indexes for each authored link. - pub links: Vec<[u32; 2]>, + /// Authored links between passage points. + pub links: Vec, +} + +/// A passage connection and its four directional access pairs. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct HallwayLink { + /// Start and end point indexes. + pub endpoints: [u32; 2], + /// Raw pairs of device key and state mask. + pub access: [[u32; 2]; 4], } /// A navigation point attached to a mesh node. @@ -48,7 +57,16 @@ pub(super) fn parse(stream: &RawStream) -> Result { .collect::>()?; let links = link_bytes .chunks_exact(LINK_BYTES) - .map(|link| Ok([read_u32(link, 0)?, read_u32(link, 4)?])) + .map(|link| { + let mut access = [[0; 2]; 4]; + for (i, pair) in access.iter_mut().enumerate() { + *pair = [read_u32(link, 8 + i * 8)?, read_u32(link, 12 + i * 8)?]; + } + Ok(HallwayLink { + endpoints: [read_u32(link, 0)?, read_u32(link, 4)?], + access, + }) + }) .collect::>()?; Ok(Hallway { points, links }) } @@ -124,7 +142,8 @@ mod tests { node: NodeId(4), } ); - assert_eq!(hallway.links, [[1, 0]]); + assert_eq!(hallway.links[0].endpoints, [1, 0]); + assert_eq!(hallway.links[0].access, [[0; 2]; 4]); assert_eq!(hallway.hero_exits(5).unwrap(), [(NodeId(2), [0.0; 3])]); } } diff --git a/crates/fparkan-msh/src/lib.rs b/crates/fparkan-msh/src/lib.rs index 7a388e3d..016998e3 100644 --- a/crates/fparkan-msh/src/lib.rs +++ b/crates/fparkan-msh/src/lib.rs @@ -9,7 +9,7 @@ use fparkan_animation::{ use fparkan_nres::{EntryMeta, NresDocument, NresError}; mod hallway; -pub use hallway::{Hallway, HallwayPoint}; +pub use hallway::{Hallway, HallwayLink, HallwayPoint}; /// Node table stream. pub const STREAM_NODE_TABLE: u32 = 1; 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, + times: &mut [Option], +) { + 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>, +} + +#[derive(Clone)] +pub(super) struct PassageLeg { + position: [f32; 3], + door: Option, +} + +#[derive(Clone)] +pub(super) struct CapturePassage { + pub(super) building: ObjectHandle, + pub(super) legs: VecDeque, + 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> { +fn links_to(hallway: &Hallway, goal: usize) -> Vec> { 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> { 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> { 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> { + 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> { + 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>, + capture_passage: Option, } 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, + ) { + 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 + '_ { + 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() { diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index e6be81c5..7f15237c 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -624,9 +624,10 @@ ID выпущенной машины внутренний. Подъезд исп Для выбора цели и оценки охраны используется реестр размещённых объектов. Порядок областей ArealMap и учёт произведённых роботов открыты. `script_nearest_capturer_approx` отмечает выбор по расстоянию при общей скорости -роботов. `script_capture_approach_stub` считает маршруты захватчиков по -парам юнит/цель. При наличии графа машина подходит к связанной двери. -Проход по внутренним связям, открытие ворот и резервный обход BAS открыты. +роботов. `script_capture_approach_stub` считает заявки, где недоступен +проход по Res17. Поддержаны свободные связи и симметричные связи с дверью CTLD +типа 12. Открыты точный темп двери, остальные условия связи, выход из рубки +и резервный обход BAS. `script_group_order_approx` считает приказы группе по клану и цели. `TAKE_BY_HITS` использует свободных варботов, `TAKE_ALL_FREE` — свободные записи всех классов. `TAKE_ALL_BATTLE_UNITS` забирает свободных варботов и diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index 98f83cc7..8dbd08f6 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -389,10 +389,19 @@ FParkan скорость движения пока общая, поэтому д Граф хранится в `Res17` модели. Запись точки занимает 20 байт и содержит три координаты, флаги и индекс узла MSH. Запись связи занимает 40 байт -и начинается с пары индексов точек. FParkan находит связанную с рубкой -наружную дверь и ведёт робота к ней. Промежуточная цель остаётся за -границей охраняемого контура, пока не подключён ход по внутренним связям. -При смене владельца запись строения переносится между распределителями. +и содержит два индекса точек и четыре пары условий прохода. +`ArealMap.dll` по RVA `0x9cb0` разрешает ключ устройства и проверяет +его состояние. Для устройств типа 12 ветка `0x9b40` опрашивает +селекторы `0x70`, `0x71` и `0x52`. На симметричных связях малого +завода ключи 22 и 7 совпадают с узлами дверей в записях CTLD типа 12. + +FParkan прокладывает внешнюю часть пути до двери с запасом по ширине +корпуса. Внутри робот движется по трёхмерным отрезкам графа, поэтому +может спуститься ниже поверхности. Связь с дверью ждёт окончания её +анимации и расходует то же время кадра, что разворот и движение. Темп +открытия унаследован от дверей игрока и остаётся приближением. +Со штатного старта «Двух крепостей» захватчик проходит к рубке генератора. +При прибытии запись строения переносится между распределителями. Если вход не удаётся, RVA `0x309ce` выбирает ближайшую доступную точку через селектор `0x203` строения. В оригинале десять точек склада и -- cgit v1.2.3