//! Sources of the player's strategic camera. use crate::{Engine, MissionControlDeviceTableStatus, StartingCockpit, SurfaceQuery}; use fparkan_render::{LegacyIron3dEulerTransform, RawCameraTransform}; use fparkan_world::{identity_metadata, registration_sequence, transform_state, ObjectHandle}; use std::f32::consts::FRAC_PI_2; mod vehicle_camera; /// Horizontal field of view of the strategic camera. pub const COMMAND_FOV: f32 = 1.04; /// The object providing the command interface. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CommandPost { /// Hero at their own clan's bunker communicator. Bunker(ObjectHandle), /// A vehicle providing a mobile command link. Warbot(ObjectHandle), } /// Returns the source of strategic control available to the player. #[must_use] pub fn command_post(engine: &Engine, cockpit: StartingCockpit) -> Option { let mission = engine.loaded.as_ref()?; if let Some(vehicle) = crate::player_vehicle(engine) { if vehicle.handle != cockpit.handle { return None; } return vehicle_command_link(engine, vehicle.handle) .then_some(CommandPost::Warbot(vehicle.handle)); } let owner = identity_metadata(&engine.world, cockpit.handle) .ok()? .owner_id?; let position = transform_state(&engine.world, cockpit.handle) .ok()? .position .map(f32::from_bits); mission .object_drafts .iter() .enumerate() .find_map(|(index, draft)| { let class = draft.unit_dat_header_flags?; if !matches!(class, 0x8001_0000 | 0x8002_0000 | 0x8004_0000) { return None; } let handle = crate::mission_object_handle(engine, draft.original_id?)?; if identity_metadata(&engine.world, handle).ok()?.owner_id != Some(owner) { return None; } let pose = transform_state(&engine.world, handle).ok()?; crate::mission_events::on_communicator( &mission.mission_assets, index, class, pose, position, ) .then_some(CommandPost::Bunker(handle)) }) } /// Connects the hero to a selected allied mobile command center within reach. pub fn mobile_command_post( engine: &Engine, cockpit: StartingCockpit, target: ObjectHandle, ) -> Option { if crate::player_vehicle(engine).is_some() { return None; } let hero_owner = identity_metadata(&engine.world, cockpit.handle) .ok()? .owner_id?; let metadata = identity_metadata(&engine.world, target).ok()?; let draft = engine .loaded .as_ref()? .object_drafts .get(metadata.original_id?.0 as usize)?; if metadata.owner_id != Some(hero_owner) || draft.unit_dat_header_flags != Some(crate::mission_events::MOBILE_HQ_CLASS) || !vehicle_command_link(engine, target) { return None; } let hero = post_position(engine, cockpit.handle)?; let position = post_position(engine, target)?; crate::boarding::vehicle_interaction_distance_sq(hero, position)?; Some(CommandPost::Warbot(target)) } fn vehicle_command_link(engine: &Engine, handle: ObjectHandle) -> bool { engine.loaded.as_ref().is_some_and(|mission| { mission.control_device_tables.iter().any(|table| { table.handle == handle && !table.node_provider_depletion_marked && matches!(&table.status, MissionControlDeviceTableStatus::Available(devices) if has_command_link(devices)) }) }) } fn has_command_link(devices: &[crate::EffectiveControlDevice]) -> bool { // iron3d+0x773a0 and Control+0x2c3c0 search the current tags from index zero. let index = devices.iter().position(|device| device.descriptor.tag == 1); // Control+0x2b410 uses the separate cached factory-1 pointer and the // descriptor currently applied to that device. index.is_some_and(|index| index > 0) && devices .iter() .rfind(|device| device.factory_tag == 1) .is_some_and(|device| device.descriptor.fixed_words[2] & 0x0800_0000 != 0) } fn post_position(engine: &Engine, handle: ObjectHandle) -> Option<[f32; 3]> { registration_sequence(&engine.world, handle).ok()??; Some( transform_state(&engine.world, handle) .ok()? .position .map(f32::from_bits), ) } /// Held command camera directions during the current frame. #[derive(Clone, Copy, Default)] pub struct CommandCameraInput { /// Motion along the camera's right, forward and vertical axes. pub translation: [i8; 3], /// Yaw and upward tilt when the pointer is at a screen edge. pub rotation: [i8; 2], } impl CommandCameraInput { /// Native edge zones in the 640×480 command interface space. #[must_use] pub fn edge_rotation([x, y]: [f32; 2]) -> [i8; 2] { let x = x.round_ties_even(); let y = y.round_ties_even(); [ i8::from(x < 7.0) - i8::from(x > 633.0), i8::from(y < 7.0) - i8::from(y > 473.0), ] } } #[derive(Clone, Copy, Default)] struct CameraAxis { direction: i8, held: f32, rate: f32, } impl CameraAxis { fn step(&mut self, direction: i8, max_rate: f32, dt: f32) -> f32 { // iron3d+0x372a0/+0x37540 use a half-second ramp, then multiply // the previous frame's rate by (0.5 - dt) during release. if direction == 0 { self.rate *= (0.5 - dt).max(0.0); } else { self.held = if direction == self.direction { (self.held + dt).min(0.5) } else { 0.0 }; self.rate = f32::from(direction.signum()) * max_rate * (2.0 * self.held); } self.direction = direction; self.rate * dt } } /// The external camera retained while the player uses a command post. pub struct CommandCamera { post: CommandPost, position: [f32; 3], yaw: f32, tilt: f32, follow_distance: f32, axes: [CameraAxis; 5], } impl CommandCamera { /// Starts at the command post, looking north. #[must_use] pub fn new(engine: &Engine, post: CommandPost) -> Option { let handle = match post { CommandPost::Bunker(handle) | CommandPost::Warbot(handle) => handle, }; Some(Self { post, position: post_position(engine, handle)?, yaw: FRAC_PI_2, tilt: 1.0, follow_distance: 0.0, axes: [CameraAxis::default(); 5], }) } /// Switches to a live bunker of the player clan and returns the previous post. pub fn focus_bunker( &mut self, engine: &Engine, cockpit: StartingCockpit, target: ObjectHandle, ) -> Option { use crate::strategic_buildings::{building_rows, BuildingSection}; let post = CommandPost::Bunker(target); // iron3d+0x62ee0 skips the transition when this post already supplies the view. if self.post == post || !building_rows(engine, cockpit, BuildingSection::Bunkers) .iter() .any(|row| row.handle == target) { return None; } let previous = self.post; *self = Self::new(engine, post)?; Some(previous) } /// Advances the external view and returns the pose for this frame. /// `building_height` reports the highest building hit on the downward segment. pub fn sample( &mut self, engine: &Engine, dt: f32, input: CommandCameraInput, building_height: impl FnOnce([[f32; 3]; 2]) -> Option, ) -> Option { let mission = engine.loaded.as_ref()?; let terrain = &mission.terrain; let [min, max] = terrain.surface_bounds()?; match self.post { CommandPost::Bunker(_) => { self.advance_bunker(dt, input, max); } CommandPost::Warbot(handle) => { if !vehicle_command_link(engine, handle) { return None; } let target = post_position(engine, handle)?; let state = transform_state(&engine.world, handle).ok()?; let index = identity_metadata(&engine.world, handle) .ok()? .original_id? .0 as usize; let (_, radius) = crate::projectile::unit_sphere(&mission.mission_assets, index, state)?; self.advance_vehicle(dt, input.rotation, max, target, radius); } } let [x, y, z] = self.position; let ground = terrain.height_at([x, y]).ok()?; let surface = match self.post { CommandPost::Bunker(handle) => { // Only the bunker passes the roof flags to iron3d+0xa1470. let surface = building_height([[x, y, max[2]], [x, y, ground.unwrap_or(min[2])]]).or(ground); self.limit_to_bunker(post_position(engine, handle)?); surface } CommandPost::Warbot(_) => ground, } .unwrap_or(0.0); // The last camera update at iron3d+0x37720 applies this band in both modes. self.position[2] = z.clamp(surface + 36.0, surface + 236.0); if !self.position.into_iter().all(f32::is_finite) { return None; } let matrix = LegacyIron3dEulerTransform { translation: self.position, orientation_radians: [0.0, FRAC_PI_2 - self.tilt, self.yaw], } .try_row_major()?; Some(RawCameraTransform { words: matrix.map(f32::to_bits), }) } fn advance_bunker(&mut self, dt: f32, input: CommandCameraInput, map_max: [f32; 3]) { if dt <= 0.0 { return; } // On a stalled frame one large step can be rejected at both tilt limits. // Use the ordinary 60 Hz step size to keep those slow frames controllable. let steps = if dt > 0.1 { (dt * 60.0).ceil() as u32 } else { 1 }; let slice = dt / steps as f32; for _ in 0..steps { self.move_bunker(slice, input, map_max); } } fn move_bunker(&mut self, dt: f32, input: CommandCameraInput, map_max: [f32; 3]) { let [right, forward, up] = input.translation; let right = self.axes[0].step(right, 125.0, dt); let forward = self.axes[1].step(forward, 125.0, dt); let up = self.axes[2].step(up, 62.5, dt); let (sin, cos) = self.yaw.sin_cos(); let margin = (0.5 * COMMAND_FOV).tan() * self.position[2]; // The native update checks each of the two motions separately. for [dx, dy] in [[right * sin, -right * cos], [forward * cos, forward * sin]] { for (axis, step) in [dx, dy].into_iter().enumerate() { let next = self.position[axis] + step; if margin < next && next < map_max[axis] { self.position[axis] = next; } } } self.position[2] += up; self.rotate(dt, input.rotation); } fn rotate(&mut self, dt: f32, [yaw, tilt]: [i8; 2]) { self.yaw += self.axes[3].step(yaw, 1.5, dt); let next_tilt = self.tilt + self.axes[4].step(tilt, 1.5, dt); if 0.0 < next_tilt && next_tilt < FRAC_PI_2 { self.tilt = next_tilt; } } fn limit_to_bunker(&mut self, origin: [f32; 3]) { // iron3d+0x37720 rounds each relative coordinate before testing it. for (point, center) in self.position[..2].iter_mut().zip(origin) { let offset = *point - center; if offset.round_ties_even().abs() > 200.0 { *point = center + offset.signum() * 200.0; } } } } #[cfg(test)] mod tests { use super::*; use crate::tests::synthetic_effective_control_device; use crate::{ create, load_gameplay_mission, starting_cockpit, EngineServices, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_vfs::DirectoryVfs; use fparkan_world::{set_owner, OriginalObjectId}; use std::sync::Arc; #[test] fn command_link_requires_a_nonzero_match_and_the_cached_pilot_flag() { let device = |factory, current| synthetic_effective_control_device(factory, current, 0, None, None); let generator = device(19, 19); let mut pilot = device(1, 1); pilot.descriptor.fixed_words[2] = 0x0800_0000; assert!(!has_command_link(&[pilot.clone(), generator.clone()])); assert!(has_command_link(&[generator.clone(), pilot.clone()])); let mut last_pilot = device(1, 1); last_pilot.descriptor.fixed_words[2] = 0x0400_0000; assert!(!has_command_link(&[generator, pilot, last_pilot])); } #[test] fn bunker_camera_moves_in_view_axes_with_native_limits() { let origin = [300.0, 300.0, 100.0]; let mut camera = CommandCamera { post: CommandPost::Bunker(ObjectHandle { generation: 0, slot: 0, }), position: origin, yaw: FRAC_PI_2, tilt: 1.0, follow_distance: 0.0, axes: [CameraAxis::default(); 5], }; let input = CommandCameraInput { translation: [1, 1, 1], rotation: [0, 0], }; let map_max = [1024.0, 1024.0, 220.0]; camera.move_bunker(0.25, input, map_max); assert_eq!(camera.position, origin); camera.move_bunker(0.25, input, map_max); assert_eq!(camera.position, [315.625, 315.625, 107.8125]); camera.move_bunker(0.25, CommandCameraInput::default(), map_max); assert_eq!(camera.position, [319.53125, 319.53125, 109.765625]); camera.position[0] = 500.5; camera.limit_to_bunker(origin); assert_eq!(camera.position[0], 500.5); camera.position[0] = 500.6; camera.limit_to_bunker(origin); assert_eq!(camera.position[0], 500.0); assert_eq!(CommandCameraInput::edge_rotation([634.0, 6.0]), [-1, 1]); assert_eq!(CommandCameraInput::edge_rotation([633.0, 7.0]), [0, 0]); camera.advance_bunker( 0.8, CommandCameraInput { rotation: [0, 1], ..Default::default() }, map_max, ); assert!(camera.tilt > 1.5 && camera.tilt < FRAC_PI_2); } #[test] #[ignore = "requires licensed corpus"] fn licensed_starting_bunker_supplies_strategy_camera() { let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap(); 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 hero = starting_cockpit(&engine).unwrap(); let bunker = crate::mission_object_handle(&engine, OriginalObjectId(0)).unwrap(); let post = command_post(&engine, hero); assert_eq!(post, Some(CommandPost::Bunker(bunker))); let mut camera = CommandCamera::new(&engine, post.unwrap()).unwrap(); let input = CommandCameraInput::default(); let previous = camera .sample(&engine, 0.0, input, |_| None) .unwrap() .translation(); let native_roof = 108.54639; let raised = camera .sample(&engine, 0.0, input, |[[x, y, top], [_, _, ground]]| { assert_eq!([x, y], [previous[0], previous[1]]); assert!(ground < native_roof && native_roof < top); Some(native_roof) }) .unwrap(); assert_eq!(raised.translation(), [previous[0], previous[1], 144.54639]); use crate::strategic_buildings::{building_rows, BuildingSection}; let rows = building_rows(&engine, hero, BuildingSection::Bunkers); assert_eq!(rows.len(), 1); assert_eq!((rows[0].handle, rows[0].label), (bunker, 0x17cc)); camera.position[0] += 10.0; assert_eq!(camera.focus_bunker(&engine, hero, bunker), None); assert_eq!(camera.position[0], previous[0] + 10.0); let other = engine .loaded .as_ref() .unwrap() .object_drafts .iter() .filter(|draft| { draft .unit_dat_header_flags .is_some_and(|class| BuildingSection::Bunkers.matches(class)) }) .filter_map(|draft| crate::mission_object_handle(&engine, draft.original_id?)) .find(|&handle| handle != bunker) .unwrap(); assert_eq!(camera.focus_bunker(&engine, hero, other), None); let owner = identity_metadata(&engine.world, hero.handle) .unwrap() .owner_id; set_owner(&mut engine.world, other, owner).unwrap(); assert_eq!(camera.focus_bunker(&engine, hero, other), post); assert_eq!(camera.post, CommandPost::Bunker(other)); assert_eq!(camera.position, post_position(&engine, other).unwrap()); } }