//! Live contacts for the satellite map. use crate::{Engine, MissionObjectDraft, StartingCockpit}; use fparkan_render::LegacyIron3dEulerTransform; use fparkan_world::{ handle_by_original_id, identity_metadata, registration_sequence, transform_state, ObjectHandle, TransformState, }; pub(super) const OWN_TINT: [u8; 3] = [128, 128, 255]; /// The original icon crop and position within the 256-pixel satellite image. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct BuildingContact { pub pixel: [i32; 2], pub icon_x: u32, pub tint: [u8; 3], } /// The original mark for a moving unit within the satellite image. #[derive(Clone, Debug, Eq, PartialEq)] pub struct UnitContact { pub pixel: [i32; 2], pub cross: bool, pub tint: [u8; 3], pub heading: Option, pub route: Vec<[i32; 2]>, } /// The selected vehicle or unboarded hero's outline and heading stroke. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct UnitHeading { pub tip_offset: [i32; 2], pub selected: bool, } /// Width of the original landscape square used by the map projection. pub fn landscape_extent(engine: &Engine) -> Option { let source = engine.loaded.as_ref()?.terrain.source_mesh()?; let extent = source .positions .iter() .map(|position| position[0]) .reduce(f32::max)?; (extent.is_finite() && extent > 0.0).then_some(extent) } /// Picks a live unit within 40 world units or a building within 80, in registry order. pub fn pick_contact( engine: &Engine, cockpit: StartingCockpit, [x, y]: [f32; 2], ) -> Option { let extent = landscape_extent(engine)?; visible_contacts(engine, cockpit, extent, |_, class| { let unit = unit_class(class); (unit || icon_x(class).is_some()).then_some(unit) }) .filter_map(|(_, handle, pose, _, unit)| { let [u, v, _] = pose.position.map(f32::from_bits); let limit = if unit { 40.0 } else { 80.0 }; let distance = f64::from(u - x).hypot(f64::from(v - y)); (distance < limit).then_some(())?; let sequence = registration_sequence(&engine.world, handle).ok()??; Some((!unit, sequence, handle)) }) .min_by_key(|&(building, sequence, _)| (building, sequence)) .map(|(_, _, handle)| handle) } /// Building marks for the player's own clan and its radar contacts. pub fn visible_buildings( engine: &Engine, cockpit: StartingCockpit, extent: f32, selected: Option, ) -> impl Iterator + '_ { let selected = selected.filter(|&target| { identity_metadata(&engine.world, target) .ok() .and_then(|identity| identity.owner_id) .is_some_and(|owner| { identity_metadata(&engine.world, cockpit.handle) .is_ok_and(|identity| identity.owner_id == Some(owner)) }) }); visible_contacts(engine, cockpit, extent, |_, class| icon_x(class)).map( move |(pixel, handle, _, tint, icon_x)| BuildingContact { pixel, icon_x, tint: if Some(handle) == selected { [255; 3] } else { tint }, }, ) } /// Unit marks for the player's own clan and its radar contacts. pub fn visible_units( engine: &Engine, cockpit: StartingCockpit, extent: f32, selected: Option, ) -> impl Iterator + '_ { let boarded = crate::player_vehicle(engine).map(|vehicle| vehicle.handle); let selected = selected.or(boarded); let patrol = engine .loaded .as_ref() .and_then(|mission| mission.unit_patrol.as_ref()); visible_contacts(engine, cockpit, extent, move |draft, class| { if !unit_class(class) { return None; } // iron3d+0x77f33 reads Behavior property 0x207 (ChassisType). let flags = engine .loaded .as_ref()? .unit_chassis_flags .get(&draft.original_id?.0)?; Some(( class == crate::HERO_UNIT_CLASS, flags.chassis_type == Some(1), )) }) .map(move |(pixel, handle, pose, tint, (hero, cross))| { let selected = selected == Some(handle); UnitContact { pixel, cross, tint, heading: if hero || selected { unit_heading(pose, cross, selected) } else { None }, route: patrol.filter(|_| selected).map_or_else(Vec::new, |patrol| { patrol .satellite_route(handle) .into_iter() .filter_map(|xy| project(xy, extent)) .collect() }), } }) } fn unit_heading(pose: TransformState, cross: bool, selected: bool) -> Option { // iron3d+0x753e0 takes the second column of the unit's world transform. let basis = LegacyIron3dEulerTransform { translation: [0.0; 3], orientation_radians: pose.orientation.map(f32::from_bits), } .try_row_major()?; // iron3d+0x77ae0 scales forward XY by the glyph width and inverts Y. let length = f64::from(if cross { 4 } else { 3 }) * f64::from(1.8_f32); let tip_offset = [basis[1], -basis[5]].map(|axis| (f64::from(axis) * length).round_ties_even() as i32); Some(UnitHeading { tip_offset, selected, }) } fn visible_contacts<'a, T>( engine: &'a Engine, cockpit: StartingCockpit, extent: f32, marker: impl Fn(&MissionObjectDraft, u32) -> Option + Copy + 'a, ) -> impl Iterator + 'a { let owner = identity_metadata(&engine.world, cockpit.handle) .ok() .and_then(|identity| identity.owner_id); engine.loaded.iter().flat_map(move |mission| { mission.object_drafts.iter().filter_map(move |draft| { let owner = owner?; let class = draft.unit_dat_header_flags?; let marker = marker(draft, class)?; let handle = handle_by_original_id(&engine.world, draft.original_id?)?; let clan = identity_metadata(&engine.world, handle).ok()?.owner_id?; registration_sequence(&engine.world, handle).ok()??; if mission .boarding .is_some_and(|boarding| boarding.hero.handle == handle) { return None; } let tint = if clan == owner { OWN_TINT } else { if !mission.radar.contains(owner, handle) { return None; } let observer = mission.mission.clans.get(usize::from(owner.0))?; let target = mission.mission.clans.get(usize::from(clan.0))?; let relation = target .relations .iter() .find(|entry| entry.other_clan_name.raw == observer.name.raw) .map(|entry| entry.relation_value); // iron3d+0x77ae0 skips dormant hostile units, except the spatial clan. if unit_class(class) && target.mode != 0 && relation == Some(0) && mission .unit_patrol .as_ref() .is_some_and(|patrol| patrol.is_shut_down(handle)) { return None; } clan_tint(target.mode, relation) }; // Both native contact renderers reject Control's 0xfffe sentinel // even while the object is still registered as a ruin. if mission .control_device_tables .iter() .any(|table| table.handle == handle && table.node_provider_depletion_marked) { return None; } let pose = transform_state(&engine.world, handle).ok()?; let [world_x, world_y, _] = pose.position.map(f32::from_bits); Some(( project([world_x, world_y], extent)?, handle, pose, tint, marker, )) }) }) } fn unit_class(class: u32) -> bool { class & crate::autodemo::MOBILE_UNIT != 0 || class == crate::projectile::ANIMAL_UNIT_CLASS } pub(super) fn clan_tint(mode: u32, relation: Option) -> [u8; 3] { // iron3d+0x658a0 selects the observed clan's relation to the viewer. match (mode, relation) { (0, _) => [255, 255, 0], (3, _) => [160; 3], (_, Some(0)) => [255, 0, 0], (_, Some(1)) => [255, 0, 255], (_, Some(2)) => [0, 255, 255], _ => [255, 255, 0], } } fn icon_x(class: u32) -> Option { // iron3d+0x9f460 selects the icon. The atlas positions come from +0x65370. Some(match class { 0x8000_0002 => 0, 0x8000_0004 => 24, 0x8000_0008 | 0x8000_0400 => 48, 0x8000_0010 => 72, 0x8001_0000 | 0x8002_0000 | 0x8004_0000 => 96, 0x8000_0040 => 120, 0x8010_0000 | 0x8020_0000 => 168, 0x8000_0200 => 216, _ => return None, }) } /// Projects world XY onto the original 256-pixel map, including the inverted Y axis. pub fn project([x, y]: [f32; 2], extent: f32) -> Option<[i32; 2]> { if !x.is_finite() || !y.is_finite() || !extent.is_finite() || extent <= 0.0 { return None; } // iron3d+0x349b0 rounds world coordinates before +0x745f0 scales them. let scale = 256.0 / f64::from(extent); let x = (f64::from(x.round_ties_even()) * scale).round_ties_even() as i32; let y = (f64::from(y.round_ties_even()) * scale).round_ties_even() as i32; Some([x, 256i32.saturating_sub(y)]) } #[cfg(test)] mod tests { use super::{icon_x, project, unit_heading, TransformState, UnitHeading}; #[test] fn satellite_coordinates_match_the_original_inset_and_rounding() { assert_eq!(project([300.31543, 556.2101], 1696.6862), Some([45, 172])); assert_eq!(project([0.0, 0.0], 256.0), Some([0, 256])); assert_eq!(project([256.0, 256.0], 256.0), Some([256, 0])); assert_eq!(project([2.5, 3.5], 256.0), Some([2, 252])); assert_eq!(icon_x(0x8000_0010), Some(72)); assert_eq!(icon_x(0x8000_0400), Some(48)); assert_eq!(icon_x(0x0100_8000), None); } #[test] fn satellite_heading_uses_chassis_glyph_width_and_inverts_world_y() { let mut pose = TransformState::default(); pose.orientation[2] = std::f32::consts::FRAC_PI_2.to_bits(); assert_eq!( unit_heading(pose, false, false), Some(UnitHeading { tip_offset: [-5, 0], selected: false, }), ); pose.orientation[2] = (-0.6_f32).atan2(0.8).to_bits(); assert_eq!(unit_heading(pose, false, true).unwrap().tip_offset, [3, -4]); assert_eq!(unit_heading(pose, true, true).unwrap().tip_offset, [4, -6]); } #[test] #[ignore = "requires licensed corpus"] fn captured_warbot_mark_uses_its_live_owner_and_position() { use super::{landscape_extent, visible_units, UnitContact}; use crate::{ create, load_gameplay_mission, starting_cockpit, EngineServices, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_vfs::DirectoryVfs; use fparkan_world::{ handle_by_original_id, identity_metadata, set_owner, set_transform, transform_state, OriginalObjectId, }; 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 cockpit = starting_cockpit(&engine).unwrap(); let extent = landscape_extent(&engine).unwrap(); let handle = handle_by_original_id(&engine.world, OriginalObjectId(11)).unwrap(); let owner = identity_metadata(&engine.world, cockpit.handle) .unwrap() .owner_id; assert_ne!( identity_metadata(&engine.world, handle).unwrap().owner_id, owner ); let mut pose = transform_state(&engine.world, handle).unwrap(); let [x, y, _] = pose.position.map(f32::from_bits); let start = project([x, y], extent).unwrap(); assert!(!visible_units(&engine, cockpit, extent, Some(handle)) .any(|contact| contact.pixel == start)); set_owner(&mut engine.world, handle, owner).unwrap(); let destination = [x, y + 50.0]; engine .loaded .as_mut() .unwrap() .unit_patrol .get_or_insert_with(crate::unit_patrol::UnitPatrol::scripted) .move_to(&engine.world, handle, destination, false); let chosen = visible_units(&engine, cockpit, extent, Some(handle)) .find(|contact| contact.pixel == start) .expect("selected warbot mark"); assert!(chosen.heading.is_some_and(|heading| heading.selected)); assert_eq!(chosen.route, [project(destination, extent).unwrap()]); let captured = visible_units(&engine, cockpit, extent, None) .find(|contact| contact.pixel == start) .expect("captured warbot mark"); assert_eq!(captured.heading, None); assert!(captured.route.is_empty()); engine .loaded .as_mut() .unwrap() .unit_patrol .as_mut() .unwrap() .clear_move(handle); pose.position[0] = (x + extent / 8.0).to_bits(); set_transform(&mut engine.world, handle, pose).unwrap(); let moved = project([x + extent / 8.0, y], extent).unwrap(); assert_eq!(moved, [start[0] + 32, start[1]]); let units: Vec<_> = visible_units(&engine, cockpit, extent, None).collect(); let moved_contact = UnitContact { pixel: moved, ..captured }; assert!(units.contains(&moved_contact)); assert!(!units.iter().any(|contact| contact.pixel == start)); assert!(units .iter() .any(|contact| contact.heading.is_some_and(|heading| !heading.selected))); let mut hero_pose = transform_state(&engine.world, cockpit.handle).unwrap(); hero_pose.position = pose.position; hero_pose.position[0] = (f32::from_bits(pose.position[0]) - 15.0).to_bits(); set_transform(&mut engine.world, cockpit.handle, hero_pose).unwrap(); let vehicle = crate::board_friendly_warbot(&mut engine, Some(handle)) .unwrap() .unwrap(); let headings: Vec<_> = visible_units(&engine, vehicle, extent, None) .filter(|unit| unit.heading.is_some()) .collect(); assert_eq!( headings, [UnitContact { heading: unit_heading(pose, moved_contact.cross, true), ..moved_contact }] ); assert_eq!(crate::disembark_warbot(&mut engine).unwrap(), Some(cockpit)); let headings: Vec<_> = visible_units(&engine, cockpit, extent, None) .filter_map(|unit| unit.heading) .collect(); assert_eq!(headings, [unit_heading(pose, false, false).unwrap()]); } #[test] #[ignore = "requires licensed corpus"] fn captured_factory_mark_disappears_at_control_depletion() { use super::{landscape_extent, visible_buildings, BuildingContact}; use crate::{ apply_loaded_mission_control_node_delta, create, load_gameplay_mission, loaded_mission_control_device_tables, starting_cockpit, EngineServices, MissionControlNodeProviderTableStatus, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_vfs::DirectoryVfs; use fparkan_world::{ handle_by_original_id, identity_metadata, registration_sequence, set_owner, 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.02/data.tma".into(), mode: MissionMode::SingleMission, }, MissionStartupInput { queue_time_ms: 0, research_creation_gate: false, }, None, ) .unwrap(); let cockpit = starting_cockpit(&engine).unwrap(); let extent = landscape_extent(&engine).unwrap(); assert_eq!(extent.to_bits(), 1696.6862f32.to_bits()); let factory = engine .loaded .as_ref() .unwrap() .object_drafts .iter() .find(|draft| draft.unit_dat_header_flags == Some(0x8000_0010)) .unwrap(); let handle = handle_by_original_id(&engine.world, factory.original_id.unwrap()).unwrap(); let [x, y, _] = transform_state(&engine.world, handle) .unwrap() .position .map(f32::from_bits); let marker = BuildingContact { pixel: project([x, y], extent).unwrap(), icon_x: 72, tint: super::OWN_TINT, }; assert!(!visible_buildings(&engine, cockpit, extent, None).any(|contact| contact == marker)); let owner = identity_metadata(&engine.world, cockpit.handle) .unwrap() .owner_id; assert!(owner.is_some()); set_owner(&mut engine.world, handle, owner).unwrap(); assert!(visible_buildings(&engine, cockpit, extent, None).any(|contact| contact == marker)); let table = loaded_mission_control_device_tables(&engine) .unwrap() .iter() .find(|table| table.handle == handle) .unwrap(); let MissionControlNodeProviderTableStatus::Available(rows) = &table.node_provider_status else { panic!("factory provider"); }; let root_amount = f32::from_bits(rows[0].current_amount_bits); assert!(root_amount > 0.0); let publication = apply_loaded_mission_control_node_delta(&mut engine, handle, 0, -root_amount) .unwrap() .unwrap(); assert_eq!(publication.type1_value_bits, 0); assert!(registration_sequence(&engine.world, handle) .unwrap() .is_some()); assert!(!visible_buildings(&engine, cockpit, extent, None).any(|contact| contact == marker)); } }