aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src/unit_patrol
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-12-02 12:27:06 +0300
committerValentin Popov <valentin@popov.link>2026-12-02 12:27:06 +0300
commitc846377ead77ef7184cdeddd25c3f2c9d76a6736 (patch)
tree6980b05a3fa7ea41b26f64c40ad1fef91849af23 /crates/fparkan-runtime/src/unit_patrol
parent7dd027fd5130daf532cd2214a6d9689293bb2c86 (diff)
downloadfparkan-c846377ead77ef7184cdeddd25c3f2c9d76a6736.tar.xz
fparkan-c846377ead77ef7184cdeddd25c3f2c9d76a6736.zip
feat(ui): send warbots to recharge from the strategic panel
Verify LTW-3 approaches the generator and clears its recharge status after leaving from the stock Two Fortresses start. Reuse authored building passages and shared Control replenishment, with a licensed test for refilling an empty magazine.
Diffstat (limited to 'crates/fparkan-runtime/src/unit_patrol')
-rw-r--r--crates/fparkan-runtime/src/unit_patrol/orders.rs17
-rw-r--r--crates/fparkan-runtime/src/unit_patrol/recharge.rs267
2 files changed, 281 insertions, 3 deletions
diff --git a/crates/fparkan-runtime/src/unit_patrol/orders.rs b/crates/fparkan-runtime/src/unit_patrol/orders.rs
index b956c599..8198b17d 100644
--- a/crates/fparkan-runtime/src/unit_patrol/orders.rs
+++ b/crates/fparkan-runtime/src/unit_patrol/orders.rs
@@ -16,6 +16,7 @@ pub(crate) enum UnitOrder {
Route(Vec<[f32; 2]>),
StrategicPatrol(PatrolTarget),
SearchAndDestroy,
+ Recharge,
Shutdown,
Resume(Box<PatrollingUnit>),
}
@@ -27,6 +28,7 @@ impl UnitOrder {
Self::Attack(..) => 3,
Self::Patrol(..) | Self::StrategicPatrol(_) => 4,
Self::SearchAndDestroy => 5,
+ Self::Recharge => 8,
Self::Shutdown => 0x13,
Self::Stand => 0x15,
Self::Resume(_) => unreachable!("a suspended order has already started"),
@@ -86,6 +88,8 @@ impl UnitPatrol {
0x11
} else if unit.search.is_some() {
UnitOrder::SearchAndDestroy.opcode()
+ } else if unit.recharge.is_some() {
+ UnitOrder::Recharge.opcode()
} else if unit.attack_target.is_some() || unit.raid_factory.is_some() {
3
} else if unit
@@ -105,7 +109,9 @@ impl UnitPatrol {
let active = self.units.iter().find(|unit| unit.handle == actor);
// 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()) {
+ if let Some(unit) = active.filter(|unit| {
+ unit.search.is_none() && unit.recharge.is_none() && !unit.points.is_empty()
+ }) {
return unit.points.iter().copied().collect();
}
let mut points = Vec::new();
@@ -127,7 +133,8 @@ impl UnitPatrol {
UnitOrder::Attack(..)
| UnitOrder::Shutdown
| UnitOrder::Stand
- | UnitOrder::SearchAndDestroy => {}
+ | UnitOrder::SearchAndDestroy
+ | UnitOrder::Recharge => {}
}
}
}
@@ -308,6 +315,7 @@ impl UnitPatrol {
return true;
}
UnitOrder::SearchAndDestroy => return self.start_search(world, actor),
+ UnitOrder::Recharge => return self.start_recharge(world, actor),
UnitOrder::Route(route) => {
for (index, &point) in route.iter().enumerate() {
self.move_to(world, actor, point, index != 0);
@@ -399,7 +407,7 @@ impl UnitPatrol {
.iter()
.find(|unit| unit.handle == actor)
.is_none_or(|unit| {
- if unit.capture_target.is_some() {
+ if unit.capture_target.is_some() || unit.recharge.is_some() {
return false;
}
if let Some(points) = &unit.destinations {
@@ -434,6 +442,9 @@ impl UnitPatrol {
impl PatrollingUnit {
fn append_point_orders(&self, points: &mut Vec<[f32; 2]>) {
+ if self.recharge.is_some() {
+ return;
+ }
if let Some(destinations) = &self.destinations {
points.extend(destinations);
} else if self.patrols_point(self.center) && self.raid_factory.is_none() {
diff --git a/crates/fparkan-runtime/src/unit_patrol/recharge.rs b/crates/fparkan-runtime/src/unit_patrol/recharge.rs
new file mode 100644
index 00000000..2ea9371b
--- /dev/null
+++ b/crates/fparkan-runtime/src/unit_patrol/recharge.rs
@@ -0,0 +1,267 @@
+//! Behavior task 8: approach a friendly recharge point, service, then leave.
+
+use super::{ObjectHandle, PatrollingUnit, UnitPatrol, World};
+use crate::{
+ building_passage::{building_entrance, BuildingPassage, PassageLeg},
+ LoadedMissionState,
+};
+use fparkan_terrain::SurfaceQuery;
+use fparkan_world::{identity_metadata, registration_sequence, transform_state, OwnerId};
+use std::collections::VecDeque;
+
+#[derive(Clone)]
+pub(super) enum Recharge {
+ FindFacility,
+ Approach {
+ facility: ObjectHandle,
+ exit: VecDeque<PassageLeg>,
+ },
+ Service {
+ facility: ObjectHandle,
+ exit: VecDeque<PassageLeg>,
+ since_ms: u32,
+ },
+ Leave {
+ facility: ObjectHandle,
+ },
+}
+
+impl UnitPatrol {
+ pub(super) fn start_recharge(&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.recharge = Some(Recharge::FindFacility);
+ unit.destinations = Some(VecDeque::new());
+ }
+ true
+ }
+
+ pub(crate) fn is_servicing(&self, actor: ObjectHandle) -> bool {
+ self.units.iter().any(|unit| {
+ unit.handle == actor && matches!(unit.recharge, Some(Recharge::Service { .. }))
+ })
+ }
+}
+
+impl PatrollingUnit {
+ /// Returns whether the recharge task is still active.
+ pub(super) fn advance_recharge(
+ &mut self,
+ world: &World,
+ mission: &LoadedMissionState,
+ now_ms: u32,
+ from: [f32; 3],
+ clearance: f32,
+ ) -> bool {
+ let Some(task) = self.recharge.take() else {
+ return false;
+ };
+ let owner = identity_metadata(world, self.handle)
+ .ok()
+ .and_then(|meta| meta.owner_id);
+ let travel_complete = self.destinations.as_ref().is_none_or(VecDeque::is_empty)
+ && self
+ .building_passage
+ .as_ref()
+ .is_none_or(|route| route.legs.is_empty());
+ self.recharge = match task {
+ Recharge::FindFacility => owner.and_then(|owner| {
+ let (destination, passage, exit) =
+ approach(world, mission, owner, from, clearance)?;
+ let facility = passage.building;
+ self.destinations = Some(VecDeque::from([destination]));
+ self.building_passage = Some(passage);
+ Some(Recharge::Approach { facility, exit })
+ }),
+ Recharge::Approach { facility, exit } if travel_complete => Some(Recharge::Service {
+ facility,
+ exit,
+ since_ms: now_ms,
+ }),
+ Recharge::Service {
+ facility,
+ exit,
+ since_ms,
+ } if now_ms.saturating_sub(since_ms) > 10_000 => {
+ // Behavior+0x2eaa0 changes from service to leaving after ten seconds.
+ self.building_passage = Some(BuildingPassage {
+ building: facility,
+ legs: exit,
+ opening: None,
+ });
+ Some(Recharge::Leave { facility })
+ }
+ Recharge::Leave { .. } if travel_complete => None,
+ _ => Some(task),
+ };
+ let valid = self.recharge.as_ref().is_some_and(|task| match task {
+ Recharge::FindFacility => false,
+ Recharge::Approach { facility, .. }
+ | Recharge::Service { facility, .. }
+ | Recharge::Leave { facility } => usable(world, mission, *facility, owner),
+ });
+ if !valid {
+ self.recharge = None;
+ self.destinations = Some(VecDeque::new());
+ self.points.clear();
+ self.building_passage = None;
+ }
+ valid
+ }
+}
+
+fn approach(
+ world: &World,
+ mission: &LoadedMissionState,
+ owner: OwnerId,
+ from: [f32; 3],
+ clearance: f32,
+) -> Option<([f32; 2], BuildingPassage, VecDeque<PassageLeg>)> {
+ mission
+ .control_device_tables
+ .iter()
+ .filter_map(|table| {
+ let facility = table.handle;
+ let index = table.original_id?.0 as usize;
+ let class = mission.object_drafts.get(index)?.unit_dat_header_flags?;
+ if class & 0x8000_0000 == 0 || !usable(world, mission, facility, Some(owner)) {
+ return None;
+ }
+ let pose = transform_state(world, facility).ok()?;
+ // Behavior+0x23b60 requests a Hallway point with mask 0x620.
+ let entry = building_entrance(
+ &mission.mission_assets,
+ &mission.terrain,
+ index,
+ pose,
+ from,
+ clearance,
+ 0x620,
+ )?;
+ let ground = mission.terrain.height_at(entry.staging).ok()??;
+ let distance = (from[0] - entry.staging[0]).hypot(from[1] - entry.staging[1]);
+ let exit = entry.exit(ground);
+ Some((
+ distance,
+ entry.staging,
+ BuildingPassage {
+ building: facility,
+ legs: entry.legs,
+ opening: None,
+ },
+ exit,
+ ))
+ })
+ .min_by(|a, b| a.0.total_cmp(&b.0))
+ .map(|(_, staging, passage, exit)| (staging, passage, exit))
+}
+
+fn usable(
+ world: &World,
+ mission: &LoadedMissionState,
+ facility: ObjectHandle,
+ owner: Option<OwnerId>,
+) -> bool {
+ owner.is_some()
+ && registration_sequence(world, facility).is_ok_and(|sequence| sequence.is_some())
+ && identity_metadata(world, facility).is_ok_and(|meta| meta.owner_id == owner)
+ && !mission
+ .control_device_tables
+ .iter()
+ .any(|table| table.handle == facility && table.node_provider_depletion_marked)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{
+ create, frame, load_gameplay_mission, starting_cockpit, strategic_orders, strategic_roster,
+ EngineServices, MissionControlDeviceTableStatus, MissionMode, MissionRequest,
+ MissionStartupInput,
+ };
+ use fparkan_vfs::DirectoryVfs;
+ use std::sync::Arc;
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
+ fn licensed_fortresses_recharges_the_first_warbot_from_its_start() {
+ let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus");
+ let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap();
+ load_gameplay_mission(
+ &mut engine,
+ MissionRequest {
+ key: "MISSIONS/Single.01/data.tma".into(),
+ mode: MissionMode::SingleMission,
+ },
+ MissionStartupInput {
+ queue_time_ms: 0,
+ research_creation_gate: false,
+ },
+ None,
+ )
+ .unwrap();
+ let cockpit = starting_cockpit(&engine).unwrap();
+ let actor = strategic_roster::warbot_rows(&engine, cockpit)[0].handle;
+ let before = transform_state(&engine.world, actor).unwrap();
+ let mission = engine.loaded.as_mut().unwrap();
+ let table = mission
+ .control_device_tables
+ .iter_mut()
+ .find(|table| table.handle == actor)
+ .unwrap();
+ let MissionControlDeviceTableStatus::Available(devices) = &mut table.status else {
+ panic!("stock LTW-3 has no Control devices");
+ };
+ let (gun, device) = devices
+ .iter_mut()
+ .enumerate()
+ .find(|(_, device)| {
+ device.descriptor.tag == 2 && device.weapon_rounds.is_some_and(|rounds| rounds > 0)
+ })
+ .unwrap();
+ device.weapon_rounds = Some(0);
+
+ assert!(strategic_orders::recharge(&mut engine, cockpit, actor));
+ assert_eq!(
+ strategic_roster::warbot_rows(&engine, cockpit)[0].order_label,
+ 0x1831
+ );
+ let mut docked = None;
+ for now in (0..=90_000).step_by(100) {
+ frame(&mut engine, now).unwrap();
+ let mission = engine.loaded.as_ref().unwrap();
+ let patrol = mission.unit_patrol.as_ref().unwrap();
+ assert!(patrol.satellite_route(actor).is_empty());
+ if patrol.is_servicing(actor) {
+ docked = Some(transform_state(&engine.world, actor).unwrap());
+ }
+ if patrol.active_order_code(actor) == 0 {
+ let docked = docked.expect("recharge finished before reaching the service point");
+ let after = transform_state(&engine.world, actor).unwrap();
+ assert_ne!(docked.position, before.position);
+ assert_ne!(after.position, docked.position);
+ let table = mission
+ .control_device_tables
+ .iter()
+ .find(|table| table.handle == actor)
+ .unwrap();
+ let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
+ panic!("stock LTW-3 lost its Control devices");
+ };
+ assert!(devices[gun].weapon_rounds.unwrap() > 0);
+ return;
+ }
+ }
+ let last = transform_state(&engine.world, actor).unwrap();
+ panic!(
+ "stock LTW-3 did not leave its recharge facility: start={:?} docked={} end={:?}",
+ before.position.map(f32::from_bits),
+ docked.is_some(),
+ last.position.map(f32::from_bits)
+ );
+ }
+}