//! Clan unit registration and the live rows of the strategic warbot list. use crate::{Engine, MissionObjectDraft, StartingCockpit}; use fparkan_world::{identity_metadata, registration_sequence, ObjectHandle, OwnerId, World}; use std::collections::HashMap; const CATEGORY: u32 = 0x0101_8000; const WARBOT: u32 = 0x0100_8000; const COMMAND_WARBOT: u32 = 0x0101_0000; #[derive(Default)] pub(super) struct UnitSerials { counts: HashMap, slots: HashMap, } impl UnitSerials { pub(super) fn placed( world: &World, drafts: &[MissionObjectDraft], handles: &[ObjectHandle], ) -> Self { let mut serials = Self::default(); for (draft, &handle) in drafts.iter().zip(handles) { if let (Some(class), Some(owner)) = ( draft.unit_dat_header_flags, identity_metadata(world, handle) .ok() .and_then(|meta| meta.owner_id), ) { serials.register(handle, owner, class); } } serials } pub(super) fn register(&mut self, handle: ObjectHandle, owner: OwnerId, class: u32) { if class & crate::autodemo::MOBILE_UNIT == 0 && class != crate::projectile::ANIMAL_UNIT_CLASS { return; } // iron3d+0x761a0 advances the naming counter of the registering clan. let serial = self.counts.entry(owner).or_default(); *serial += 1; self.slots.insert(handle.slot, (handle.generation, *serial)); } pub(super) fn get(&self, handle: ObjectHandle) -> Option { let &(generation, serial) = self.slots.get(&handle.slot)?; (generation == handle.generation).then_some(serial) } } /// Snapshot of an eligible unit for the strategic list. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct WarbotRow { /// Unit represented by the row, including its generation. pub handle: ObjectHandle, /// Three ASCII letters identifying size, chassis, and class. pub prefix: [char; 3], /// Stable number assigned at creation in the original clan. pub serial: u32, /// String table ID for the name suffix. pub class_label: u32, /// String table ID for the active order. pub order_label: u32, /// Display class, from Behavior property 0x201. pub size: u32, /// Locomotion type, from Behavior property 0x207. pub chassis: u32, /// Whether the unit is eligible for automatic selection. pub selectable: bool, /// Original sound resource symbol played when selecting this unit. pub selection_voice: &'static str, /// Remaining provider capacity of all nodes, rounded as in the original list. pub durability_percent: Option, } /// Returns the player's warbots in registration order, including any entries whose controller is depleted. pub fn warbot_rows(engine: &Engine, cockpit: StartingCockpit) -> Vec { let Some((mission, owner)) = engine.loaded.as_ref().zip( identity_metadata(&engine.world, cockpit.handle) .ok() .and_then(|meta| meta.owner_id), ) else { return Vec::new(); }; let mut rows: Vec<_> = mission .control_device_tables .iter() .filter_map(|table| { let handle = table.handle; let draft = mission.object_drafts.get(table.original_id?.0 as usize)?; let class = draft.unit_dat_header_flags?; if class == 0 || class & CATEGORY != class || identity_metadata(&engine.world, handle).ok()?.owner_id != Some(owner) { return None; } let (role, class_label) = match class { WARBOT => ('W', 0x183a), COMMAND_WARBOT => ('C', 0x183b), _ => return None, }; let sequence = registration_sequence(&engine.world, handle).ok()??; let serial = mission.unit_serials.get(handle)?; let size = crate::unit_size_class::classify(4, &draft.unit_components.first()?.resource_raw); let chassis = mission .unit_chassis_flags .get(&table.original_id?.0) .and_then(|flags| flags.chassis_type) .unwrap_or(0); let order = mission .unit_patrol .as_ref() .map_or(0, |patrol| patrol.active_order_code(handle)); let row = WarbotRow { handle, prefix: unit_prefix(size, chassis, role), serial, class_label, order_label: order_label(order), size, chassis, selectable: !table.node_provider_depletion_marked, selection_voice: selection_voice(class, size), durability_percent: crate::warbot_stats::durability_percent(table), }; Some((sequence, row)) }) .collect(); rows.sort_unstable_by_key(|&(sequence, _)| sequence); rows.into_iter().map(|(_, row)| row).collect() } fn selection_voice(class: u32, size: u32) -> &'static str { // iron3d+0x61fb0 tests the command vehicle descriptor before its size. match (class, size) { (COMMAND_WARBOT, _) | (_, 4 | 5) => "VOICE_SELECTED_B", (_, 1 | 2) => "VOICE_SELECTED_S", _ => "VOICE_SELECTED", } } fn letter(alphabet: &[u8], value: u32) -> char { char::from(alphabet.get(value as usize).copied().unwrap_or(b'?')) } pub(super) fn unit_prefix(size: u32, chassis: u32, role: char) -> [char; 3] { [letter(b"?TSML", size), letter(b"?FSWTAU", chassis), role] } pub(super) fn order_label(order: u32) -> u32 { match order { 0 => 0x1824, 2 => 0x1828, 3 => 0x182c, 4 => 0x182d, 5 => 0x182e, 8 => 0x1831, 0x11 => 0x1833, 0x13 => 0x1826, 0x14 => 0x1829, 0x15 => 0x1827, _ => 0x1835, } } #[cfg(test)] mod tests { use super::*; #[test] fn warbot_selection_voice_uses_the_native_size_banks() { assert_eq!(selection_voice(WARBOT, 1), "VOICE_SELECTED_S"); assert_eq!(selection_voice(WARBOT, 2), "VOICE_SELECTED_S"); assert_eq!(selection_voice(WARBOT, 3), "VOICE_SELECTED"); assert_eq!(selection_voice(WARBOT, 4), "VOICE_SELECTED_B"); assert_eq!(selection_voice(COMMAND_WARBOT, 2), "VOICE_SELECTED_B"); } #[test] fn numbers_all_mobile_classes_per_creation_clan_without_reusing_a_stale_handle() { let mut serials = UnitSerials::default(); let handle = |slot, generation| ObjectHandle { slot, generation }; let local = OwnerId(0); serials.register(handle(0, 1), local, 0x8001_0000); serials.register(handle(1, 1), local, 0x0100_2000); serials.register(handle(2, 1), local, 0x0100_4000); serials.register(handle(3, 1), OwnerId(1), WARBOT); serials.register(handle(4, 1), local, WARBOT); assert_eq!(serials.get(handle(4, 1)), Some(3)); assert_eq!(serials.get(handle(3, 1)), Some(1)); serials.register(handle(4, 2), local, COMMAND_WARBOT); assert_eq!(serials.get(handle(4, 1)), None); assert_eq!(serials.get(handle(4, 2)), Some(4)); } #[test] #[ignore = "requires licensed corpus"] fn licensed_two_fortresses_roster_uses_live_clan_and_original_serials() { use crate::{ create, load_gameplay_mission, starting_cockpit, EngineServices, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_vfs::DirectoryVfs; use fparkan_world::set_owner; use std::sync::Arc; 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 cockpit = starting_cockpit(&engine).unwrap(); let rows = warbot_rows(&engine, cockpit); let labels: Vec<_> = rows .iter() .map(|row| (row.prefix, row.serial, row.order_label)) .collect(); assert_eq!( labels, [ (['L', 'T', 'W'], 3, 0x1824), (['L', 'T', 'W'], 4, 0x1824), (['M', 'T', 'W'], 5, 0x1824) ] ); let heavy = crate::warbot_stats::warbot_stats(&engine, rows[1].handle).unwrap(); assert_eq!(rows[1].durability_percent, Some(100)); assert_eq!(heavy.radar, Some(400.0)); assert_eq!(heavy.offence.unwrap().to_bits(), 0x4556_9556); assert!( (heavy.defence.unwrap() - 14_329.729).abs() < 0.5, "{heavy:?}" ); set_owner(&mut engine.world, rows[0].handle, None).unwrap(); assert_eq!(warbot_rows(&engine, cockpit), rows[1..]); } }