From acc5af7cc79a5ee2132c5d10528ca1cf06186832 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Sat, 14 Nov 2026 09:30:58 +0400 Subject: feat(runtime): route AutoDemo patrols through terrain areas --- crates/fparkan-runtime/src/autodemo.rs | 5 +- crates/fparkan-runtime/src/lib.rs | 81 +++++++++++--- crates/fparkan-runtime/src/unit_patrol.rs | 176 ++++++++++++++++++++++++++++++ 3 files changed, 246 insertions(+), 16 deletions(-) create mode 100644 crates/fparkan-runtime/src/unit_patrol.rs (limited to 'crates/fparkan-runtime/src') diff --git a/crates/fparkan-runtime/src/autodemo.rs b/crates/fparkan-runtime/src/autodemo.rs index a31a8c7b..5ac401fd 100644 --- a/crates/fparkan-runtime/src/autodemo.rs +++ b/crates/fparkan-runtime/src/autodemo.rs @@ -13,7 +13,7 @@ const PITCH: f32 = 1.25; const YAW: f32 = std::f32::consts::FRAC_PI_2; const FOLLOW_DISTANCE: f32 = 30.0; const PLANT_CLASS: u32 = 0x8000_0010; -const MOBILE_UNIT: u32 = 0x0100_0000; +pub(super) const MOBILE_UNIT: u32 = 0x0100_0000; pub(super) fn read_config( vfs: &Arc, @@ -156,8 +156,7 @@ pub(super) fn reinforcement_position( let scale = plant.scale.into_iter().map(f32::abs).fold(0.0, f32::max); let radius = bounds.bounding_sphere_radius * scale; // shortcut: isolated CRT state until AutoDemo shares the host's complete RNG call order. - *rng = rng.wrapping_mul(0x343fd).wrapping_add(0x269ec3); - let angle = (((*rng >> 16) & 0x7fff) % 360) as f32; + let angle = (super::next_crt_rand(rng) % 360) as f32; let (sin, cos) = angle.to_radians().sin_cos(); let [x, y] = [x + sin * radius, y + cos * radius]; let z = terrain diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index ddfde368..e553c6bc 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -47,6 +47,7 @@ mod mission_events; mod player_motion; mod player_weapon; mod projectile; +mod unit_patrol; pub use autodemo::{autodemo_camera, AutoDemoCamera, AutoDemoView}; pub use fparkan_assets::MissionAssets; @@ -1017,8 +1018,7 @@ impl BehaviorWarmStartState { const BASE_INTERVAL_MS: u32 = 3 * 64; const JITTER_RANGE_MS: u32 = 64; - *rng_state = (*rng_state).wrapping_mul(0x343fd).wrapping_add(0x269ec3); - let random = (*rng_state >> 16) & 0x7fff; + let random = next_crt_rand(rng_state); let jitter_ms = ((random & 0xff) * JITTER_RANGE_MS) >> 8; Self { @@ -1029,6 +1029,11 @@ impl BehaviorWarmStartState { } } +fn next_crt_rand(state: &mut u32) -> u32 { + *state = state.wrapping_mul(0x343fd).wrapping_add(0x269ec3); + (*state >> 16) & 0x7fff +} + fn behavior_elapsed_seconds(elapsed_ms: u32) -> f32 { // The exact integer product is rounded once to f32; scaling by 2^-33 is // exact and matches native FILD / FMUL / FSTP under the measured control word. @@ -1305,6 +1310,7 @@ struct LoadedMissionState { script_init_states: Vec, script_varset_states: Vec, mission_events: MissionEvents, + unit_patrol: Option, player_pitch_bits: u32, script_host_mode: MissionMode, script_host_status: u32, @@ -2270,6 +2276,9 @@ fn load_mission_with_options( } else { MissionEvents::default() }; + let unit_patrol = (request.mode == MissionMode::AutoDemo && options.start_autodemo) + .then(|| unit_patrol::UnitPatrol::new(&mission, &object_drafts, &handles)) + .flatten(); engine.world = new_runtime_world; engine.behavior_rng_state = next_behavior_rng_state; engine.loaded = Some(LoadedMissionState { @@ -2294,6 +2303,7 @@ fn load_mission_with_options( script_init_states: loaded_scripts.init_states, script_varset_states: loaded_scripts.varset_states, mission_events, + unit_patrol, player_pitch_bits: 0, script_host_mode: request.mode, // Fresh IGame construction seeds this field with 5; this is not the @@ -2335,7 +2345,31 @@ pub fn step_headless( queue_time_ms: u32, ) -> Result { let resources = prepare_loaded_mission_resources(engine, queue_time_ms)?; - let snapshot = step(&mut engine.world, &input)?; + let patrol = engine + .loaded + .as_ref() + .and_then(|mission| { + mission + .unit_patrol + .as_ref() + .map(|patrol| patrol.prepare(&engine.world, &mission.terrain, queue_time_ms)) + }) + .transpose()?; + if let Some(patrol) = &patrol { + patrol.apply_poses(&mut engine.world)?; + } + let snapshot = match step(&mut engine.world, &input) { + Ok(snapshot) => snapshot, + Err(error) => { + if let Some(patrol) = patrol { + patrol.restore_poses(&mut engine.world)?; + } + return Err(error.into()); + } + }; + if let (Some(patrol), Some(mission)) = (patrol, &mut engine.loaded) { + mission.unit_patrol = Some(patrol.state); + } if let Some(resources) = resources { resources.apply(engine); } @@ -15966,7 +16000,7 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] - fn autodemo_registers_one_starting_reinforcement_per_clan() { + fn autodemo_registers_reinforcements_and_moves_six_patrolling_robots() { let vfs = Arc::new(DirectoryVfs::new(licensed_root("IS"))); let mut engine = create(EngineServices::new(vfs)).unwrap(); let loaded = load_mission_with_init_stubs( @@ -15998,16 +16032,37 @@ mod tests { newcomers.push((handle, root.position.map(f32::to_bits))); } assert_eq!(extras.len(), 2); - for ms in [16, 1_000] { - let snapshot = frame(&mut engine, ms).unwrap().snapshot; - assert_eq!(snapshot.objects.len(), 10); - for (handle, position) in &newcomers { - assert!(snapshot - .transforms - .iter() - .any(|(h, pose)| h == handle && &pose.position == position)); - } + let start = frame(&mut engine, 0).unwrap().snapshot; + assert_eq!(start.objects.len(), 10); + for (handle, position) in newcomers { + assert!(start + .transforms + .iter() + .any(|(h, pose)| *h == handle && pose.position == position)); + } + for tick in 1..=300 { + frame(&mut engine, tick * 1000 / 60).unwrap(); } + let later = frame(&mut engine, 5_000).unwrap().snapshot; + assert_eq!(later.objects.len(), 10); + let moved: Vec<_> = start + .transforms + .iter() + .filter_map(|(handle, before)| { + let after = later.transforms.iter().find(|(h, _)| h == handle)?.1; + let [x0, y0, _] = before.position.map(f32::from_bits); + let [x1, y1, _] = after.position.map(f32::from_bits); + let distance = (x1 - x0).hypot(y1 - y0); + (distance > 0.0).then_some(distance) + }) + .collect(); + assert_eq!(moved.len(), 6, "all six starting robots should patrol"); + assert!( + moved + .iter() + .all(|distance| (10.0..=45.01).contains(distance)), + "{moved:?}" + ); } #[test] diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs new file mode 100644 index 00000000..8ef4e5f1 --- /dev/null +++ b/crates/fparkan-runtime/src/unit_patrol.rs @@ -0,0 +1,176 @@ +use super::{ + autodemo::MOBILE_UNIT, next_crt_rand, EngineError, MissionDocument, MissionObjectDraft, + ObjectHandle, TerrainWorld, TransformState, World, +}; +use fparkan_terrain::{NavigationQuery, RouteRequest, SurfaceQuery}; +use fparkan_world::{set_transform, transform_state}; +use std::collections::VecDeque; + +#[derive(Clone)] +pub(super) struct UnitPatrol { + center: [f32; 2], + units: Vec, + clock_ms: u32, + rng: u32, +} + +#[derive(Clone)] +struct PatrollingUnit { + handle: ObjectHandle, + points: VecDeque<[f32; 2]>, + retry_ms: u32, +} + +pub(super) struct PreparedPatrol { + pub(super) state: UnitPatrol, + poses: Vec<(ObjectHandle, TransformState, TransformState)>, +} + +impl UnitPatrol { + pub(super) fn new( + mission: &MissionDocument, + drafts: &[MissionObjectDraft], + handles: &[ObjectHandle], + ) -> Option { + // shortcut: use the observed AutoDemo meeting area from the first clan anchor + // until we can execute the native producer of the patrol order. + let center = mission.clans.first()?.anchor.map(f32::round); + let units = drafts + .iter() + .zip(handles) + .filter(|(draft, _)| { + draft + .unit_dat_header_flags + .is_some_and(|class| class & MOBILE_UNIT != 0) + && (draft.raw_after_resource as usize) < mission.clans.len() + }) + .map(|(_, &handle)| PatrollingUnit { + handle, + points: VecDeque::new(), + retry_ms: 0, + }) + .collect(); + Some(Self { + center, + units, + clock_ms: 0, + rng: 1, + }) + } + + pub(super) fn prepare( + &self, + world: &World, + terrain: &TerrainWorld, + now_ms: u32, + ) -> Result { + let mut state = self.clone(); + let seconds = now_ms.saturating_sub(state.clock_ms) as f32 * 0.001; + state.clock_ms = state.clock_ms.max(now_ms); + let mut poses = Vec::new(); + if seconds == 0.0 { + return Ok(PreparedPatrol { state, poses }); + } + for unit in &mut state.units { + let Ok(before) = transform_state(world, unit.handle) else { + continue; + }; + let from = before.position.map(f32::from_bits); + if unit.points.is_empty() && now_ms >= unit.retry_ms { + unit.points = choose_route(terrain, from, state.center, &mut state.rng)?; + unit.retry_ms = now_ms.saturating_add(1_000); + } + let Some(&target) = unit.points.front() else { + continue; + }; + let dx = target[0] - from[0]; + let dy = target[1] - from[1]; + let distance = dx.hypot(dy); + if distance <= 0.05 { + unit.points.pop_front(); + continue; + } + let mut after = before; + // shortcut: fixed turn rate and patrol speed until the per-chassis Control step is available. + let yaw = f32::from_bits(before.orientation[2]); + let goal_yaw = (-dx).atan2(dy); + let turn = (goal_yaw - yaw + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) + - std::f32::consts::PI; + let turn_budget = 2.0 * seconds; + after.orientation[2] = (yaw + turn.clamp(-turn_budget, turn_budget)).to_bits(); + let travel = 9.0 * (seconds - turn.abs() * 0.5).max(0.0); + if travel > 0.0 { + let fraction = (travel / distance).min(1.0); + let xy = [from[0] + dx * fraction, from[1] + dy * fraction]; + if let Some(ground) = terrain.height_at(xy).map_err(EngineError::Terrain)? { + let old_ground = terrain + .height_at([from[0], from[1]]) + .map_err(EngineError::Terrain)?; + let z = ground + old_ground.map_or(0.0, |height| from[2] - height); + after.position = [xy[0], xy[1], z].map(f32::to_bits); + if fraction == 1.0 { + unit.points.pop_front(); + } + } else { + unit.points.clear(); + } + } + if after != before { + poses.push((unit.handle, before, after)); + } + } + Ok(PreparedPatrol { state, poses }) + } +} + +fn choose_route( + terrain: &TerrainWorld, + from: [f32; 3], + center: [f32; 2], + rng: &mut u32, +) -> Result, EngineError> { + // shortcut: choose one routed patrol point at a time with separate RNG state. + for _ in 0..16 { + let [x, y] = + center.map(|axis| axis + (next_crt_rand(rng) as f32 / 32767.0 * 2.0 - 1.0) * 150.0); + let Some(z) = terrain.height_at([x, y]).map_err(EngineError::Terrain)? else { + continue; + }; + let Some(route) = terrain + .route(RouteRequest { + start: from, + goal: [x, y, z], + }) + .map_err(EngineError::Terrain)? + else { + continue; + }; + let crossings: Option> = route + .areas + .windows(2) + .map(|pair| terrain.route_crossing(pair[0], pair[1])) + .collect(); + if let Some(mut points) = crossings { + points.push_back([x, y]); + return Ok(points); + } + } + Ok(VecDeque::new()) +} + +impl PreparedPatrol { + pub(super) fn apply_poses(&self, world: &mut World) -> Result<(), EngineError> { + // These handles were read during preparation and the world has yet to step. + for &(handle, _, after) in &self.poses { + set_transform(world, handle, after)?; + } + Ok(()) + } + + pub(super) fn restore_poses(&self, world: &mut World) -> Result<(), EngineError> { + for &(handle, before, _) in &self.poses { + set_transform(world, handle, before)?; + } + Ok(()) + } +} -- cgit v1.2.3