use super::{ component_cockpit, control_device_provider_value, projectile::{projectile_terrain_hit, projectile_unit_hit, unit_sphere}, starting_cockpit, Engine, EngineError, MissionControlDeviceTableState, MissionControlDeviceTableStatus, StartingCockpit, SurfaceQuery, TransformState, }; use crate::player_motion::FLOOR_CLEARANCE; use fparkan_world::{ handle_by_original_id, identity_metadata, set_transform, transform_state, ObjectHandle, OriginalObjectId, }; pub(super) const WARBOT_CLASS: u32 = 0x0100_8000; mod remote_control; pub use remote_control::{ can_control_warbot_remotely, control_warbot_remotely, remote_automatic_weapons, remote_warbot_control, RemoteWarbotControl, }; /// Ownership and cockpit changes from one Enter command. pub struct VehicleEntry { /// Original ID of the neutral machine transferred to the player's clan. pub captured: Option, /// New player cockpit if the machine supports boarding. pub cockpit: Option, } impl VehicleEntry { /// Captures that leave the player outside the machine receive a spoken acknowledgement. pub fn capture_notice(&self) -> Option { (self.captured.is_some() && self.cockpit.is_none()) .then_some(crate::MissionNotice::VehicleCaptured) } } #[derive(Clone, Copy)] pub(super) struct Boarding { pub(super) cockpit: StartingCockpit, pub(super) hero: StartingCockpit, pub(super) remote: Option, pub(super) can_fly: bool, pub(super) ground: Option, pub(super) on_building_floor: bool, pub(super) flight_velocity: [f32; 3], } impl Boarding { pub(super) fn controls_chassis(self) -> bool { self.remote != Some(RemoteWarbotControl::Autopilot) } pub(super) fn controls_weapons(self) -> bool { self.remote .is_none_or(|mode| mode == RemoteWarbotControl::Manual) } } /// The vehicle cockpit while the player is aboard. #[must_use] pub fn player_vehicle(engine: &Engine) -> Option { Some(engine.loaded.as_ref()?.boarding.as_ref()?.cockpit) } /// Selects the friendly warbot under a line of sight supplied by the camera. pub fn select_boarding_target( engine: &Engine, hero: StartingCockpit, segment: [[f32; 3]; 2], ) -> Option { let target = projectile_unit_hit(engine, hero.handle, segment)?; let owner = identity_metadata(&engine.world, hero.handle) .ok()? .owner_id?; let mission = engine.loaded.as_ref()?; // shortcut: use the cockpit sight ray until the original selection ranking is recovered. if projectile_terrain_hit(&mission.terrain, segment) .ok()? .is_some_and(|ground| ground <= target.fraction) { return None; } let warbot = mission.object_drafts.iter().any(|draft| { draft.unit_dat_header_flags == Some(WARBOT_CLASS) && draft .original_id .and_then(|id| handle_by_original_id(&engine.world, id)) == Some(target.handle) }); (warbot && identity_metadata(&engine.world, target.handle) .ok()? .owner_id == Some(owner)) .then_some(target.handle) } /// Boards a selected ally or captures an available neutral machine. /// /// Capturing a working warbot also boards it during the same command. /// /// # Errors /// /// Returns an error if the hero's world state or the ownership update fails. pub fn enter_vehicle( engine: &mut Engine, hero: StartingCockpit, target: Option, ) -> Result { if let Some(cockpit) = board_friendly_warbot(engine, target)? { return Ok(VehicleEntry { captured: None, cockpit: Some(cockpit), }); } let captured = super::mission_events::capture_neutral_warbot(engine, hero)?; let new_ally = captured.and_then(|id| handle_by_original_id(&engine.world, id)); let cockpit = board_friendly_warbot(engine, new_ally)?; Ok(VehicleEntry { captured, cockpit }) } /// Boards the selected compatible allied warbot within 20 units in XY. /// /// # Errors /// /// Returns an error if the hero's world handle is stale. pub fn board_friendly_warbot( engine: &mut Engine, target: Option, ) -> Result, EngineError> { let Some(target) = target else { return Ok(None); }; let Some(hero) = starting_cockpit(engine) else { return Ok(None); }; let Some(mission) = &engine.loaded else { return Ok(None); }; if mission.boarding.is_some() { return Ok(None); } let Some(owner) = identity_metadata(&engine.world, hero.handle)?.owner_id else { return Ok(None); }; let hero_pose = transform_state(&engine.world, hero.handle)?; let hero_position = hero_pose.position.map(f32::from_bits); let candidate = mission .object_drafts .iter() .enumerate() .filter_map(|(index, draft)| { if draft.unit_dat_header_flags != Some(WARBOT_CLASS) { return None; } let handle = handle_by_original_id(&engine.world, draft.original_id?)?; if handle != target || identity_metadata(&engine.world, handle).ok()?.owner_id != Some(owner) { return None; } let table = mission .control_device_tables .iter() .find(|table| table.handle == handle)?; if !has_working_pilot_control(table) { return None; } let state = transform_state(&engine.world, handle).ok()?; vehicle_interaction_distance_sq(hero_position, state.position.map(f32::from_bits))?; Some((component_cockpit(mission, index, handle)?, state.position)) }) .next(); let Some((cockpit, position)) = candidate else { return Ok(None); }; set_transform( &mut engine.world, hero.handle, TransformState { position, ..hero_pose }, )?; start_warbot_control(engine, hero, cockpit, None); Ok(Some(cockpit)) } fn start_warbot_control( engine: &mut Engine, hero: StartingCockpit, cockpit: StartingCockpit, remote: Option, ) { let can_fly = crate::player_motion::warbot_can_fly(engine, cockpit.object_index); if let Some(mission) = &mut engine.loaded { mission.boarding = Some(Boarding { cockpit, hero, remote, can_fly, ground: (!can_fly) .then(|| { crate::ground_support::GroundSupport::prepare( &mission.mission_assets, cockpit.object_index, ) }) .flatten(), on_building_floor: false, flight_velocity: [0.0; 3], }); mission.player_pitch_bits = 0; mission.hero_walk_velocity = [0.0; 2]; mission.hero_look.reset(); } } pub(super) fn vehicle_interaction_distance_sq( [hero_x, hero_y, _]: [f32; 3], [x, y, _]: [f32; 3], ) -> Option { // iron3d+0x7240b narrows the X delta to f32 before comparing the // horizontal length without storing it back to f32. let dx = f64::from(x - hero_x); let dy = f64::from(y) - f64::from(hero_y); let distance_sq = dx * dx + dy * dy; (distance_sq < 20.0 * 20.0).then_some(distance_sq) } #[cfg(test)] mod tests { #[test] fn vehicle_interaction_ignores_height_and_excludes_the_horizontal_boundary() { use super::vehicle_interaction_distance_sq; let hero = [0.0; 3]; assert!(vehicle_interaction_distance_sq(hero, [12.0, 15.99, 1_000.0]).is_some()); assert!(vehicle_interaction_distance_sq(hero, [19.0, 0.0, -1_000.0]).is_some()); assert!(vehicle_interaction_distance_sq(hero, [12.0, 16.0, 0.0]).is_none()); assert!(vehicle_interaction_distance_sq(hero, [20.0, 0.0, 0.0]).is_none()); assert!(vehicle_interaction_distance_sq(hero, [f32::NAN, 0.0, 0.0]).is_none()); } #[test] #[ignore = "requires licensed corpus"] fn one_enter_captures_and_boards_the_neutral_warbot() { use super::{enter_vehicle, player_vehicle, starting_cockpit, OriginalObjectId}; use crate::{ create, load_gameplay_mission, EngineServices, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_vfs::DirectoryVfs; use fparkan_world::{handle_by_original_id, set_transform, transform_state}; use std::sync::Arc; 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/CAMPAIGN/CAMPAIGN.00/Mission.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 id = OriginalObjectId(11); let target = handle_by_original_id(&engine.world, id).unwrap(); let mut pose = transform_state(&engine.world, hero.handle).unwrap(); let [x, y, z] = transform_state(&engine.world, target) .unwrap() .position .map(f32::from_bits); pose.position = [x - 15.0, y, z].map(f32::to_bits); set_transform(&mut engine.world, hero.handle, pose).unwrap(); let entry = enter_vehicle(&mut engine, hero, None).unwrap(); assert_eq!(entry.captured, Some(id)); assert_eq!(entry.cockpit.unwrap().handle, target); assert_eq!(entry.capture_notice(), None); assert_eq!(player_vehicle(&engine), entry.cockpit); } } fn has_working_pilot_control(table: &MissionControlDeviceTableState) -> bool { let MissionControlDeviceTableStatus::Available(devices) = &table.status else { return false; }; devices .iter() .find(|device| device.descriptor.tag == 1) .is_some_and(|device| { control_device_provider_value(table, device).is_ok_and(|value| value > 0.0) }) } /// Leaves the vehicle and restores the hero's cockpit. /// /// # Errors /// /// Returns an error when the hero pose or terrain query cannot be read. pub fn disembark_warbot(engine: &mut Engine) -> Result, EngineError> { let Some(mission) = &mut engine.loaded else { return Ok(None); }; let Some(Boarding { cockpit: vehicle, hero, remote, can_fly, on_building_floor, .. }) = mission.boarding else { return Ok(None); }; let mut pose = transform_state(&engine.world, hero.handle)?; let vehicle_pose = remote .is_none() .then(|| transform_state(&engine.world, vehicle.handle).ok()) .flatten(); if let Some(vehicle_pose) = vehicle_pose { let [x, y, _] = vehicle_pose.position.map(f32::from_bits); let yaw = f32::from_bits(vehicle_pose.orientation[2]); let (sin, cos) = yaw.sin_cos(); let radius = unit_sphere(&mission.mission_assets, vehicle.object_index, vehicle_pose) .map_or(1.0, |(_, radius)| radius); // shortcut: use the sides and terrain surface until the exit // point and collision checks are recovered. let mut exit = None; for side in [1.0, -1.0] { let xy = [ x + cos * (radius + 1.0) * side, y + sin * (radius + 1.0) * side, ]; if let Some(ground) = mission .terrain .height_at(xy) .map_err(EngineError::Terrain)? { exit = Some([xy[0], xy[1], ground + FLOOR_CLEARANCE]); break; } } let Some(exit) = exit else { return Ok(None); }; pose.position = exit.map(f32::to_bits); pose.orientation[2] = yaw.to_bits(); set_transform(&mut engine.world, hero.handle, pose)?; } else if remote.is_none() && !can_fly && !on_building_floor { // The passenger still has the destroyed chassis's root height. let [x, y, _] = pose.position.map(f32::from_bits); if let Some(ground) = mission .terrain .height_at([x, y]) .map_err(EngineError::Terrain)? { pose.position[2] = (ground + FLOOR_CLEARANCE).to_bits(); set_transform(&mut engine.world, hero.handle, pose)?; } } mission.boarding = None; mission.player_pitch_bits = 0; mission.hero_walk_velocity = [0.0; 2]; mission.hero_look.reset(); Ok(Some(hero)) } pub(super) fn move_passenger( engine: &mut Engine, cockpit: StartingCockpit, vehicle_pose: TransformState, ) -> Option<(ObjectHandle, TransformState)> { let boarding = engine.loaded.as_ref()?.boarding.as_ref()?; if boarding.remote.is_some() || boarding.cockpit.handle != cockpit.handle { return None; } let hero = boarding.hero; let previous = transform_state(&engine.world, hero.handle).ok()?; let pose = TransformState { position: vehicle_pose.position, ..previous }; set_transform(&mut engine.world, hero.handle, pose).ok()?; Some((hero.handle, previous)) }