//! Mobile Control device budgets and weapon charge snapshots. use crate::{ checked_control_float, checked_control_product, checked_control_ratio, checked_control_sum, control_budget_device, control_device_budget_active_provider_value, control_device_budget_coefficient, control_device_budget_descriptor_float, ControlResourceAccessError, EffectiveControlDevice, MissionAssets, MissionControlDeviceTableState, MissionControlDeviceTableStatus, TransformState, }; use fparkan_assets::{ControlDriveStates, PreparedControlDrive}; use std::collections::BTreeMap; #[derive(Clone, Debug)] pub(super) struct Charge { pub(super) capacity: f32, pub(super) cost: f32, pub(super) amount: f32, } impl Charge { pub(super) fn can_start(&self) -> bool { self.capacity <= 0.0 || self.cost <= self.amount } pub(super) fn finish_shot(&mut self) { if self.capacity > 0.0 && self.cost <= self.amount { self.amount -= self.cost; } } } /// Mobile budget steps, omitted motion inputs and energy waits, by original ID. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct MobileBudgetReport { pub ticks: BTreeMap, pub stubs: BTreeMap<(u32, String), u64>, pub weapon_waits: BTreeMap, } impl MobileBudgetReport { pub(super) fn stub(&mut self, object: u32, reason: String) { let count = self.stubs.entry((object, reason.clone())).or_default(); *count += 1; if *count == 1 { eprintln!("control_mobile_budget_stub object={object} reason={reason}"); } } } fn charge_rate( amount: f32, capacity: f32, dt: f32, upkeep: f32, active: bool, ) -> Result { let deficit = checked_control_sum(2, "weapon charge deficit", amount, -capacity)?; if active { checked_control_sum( 2, "weapon charge and upkeep", deficit, -checked_control_product(2, "weapon upkeep interval", dt, upkeep)?, ) } else { Ok(deficit) } } fn charge_update( amount: f32, capacity: f32, dt: f32, upkeep: f32, active: bool, allocation: f32, ) -> Result<(f32, Option), ControlResourceAccessError> { let rate = charge_rate(amount, capacity, dt, upkeep, active)?; let mut received = -checked_control_product(2, "weapon allocated charge", rate, allocation)?; if active { received = checked_control_sum( 2, "weapon received minus upkeep", received, -checked_control_product(2, "weapon upkeep interval", dt, upkeep)?, )?; } if capacity <= 0.0 { return Ok((amount, None)); } let amount = checked_control_sum(2, "weapon updated charge", received, amount)?; Ok(( amount, Some(checked_control_ratio( "weapon charge ratio", amount, capacity, )?), )) } fn weapon_amount(device: &EffectiveControlDevice) -> Result { let bits = device .weapon_charge_bits .ok_or(ControlResourceAccessError::UnsupportedField { factory_tag: 2, field: "weapon charge +0x120", })?; checked_control_float(2, "weapon charge", f32::from_bits(bits)) } pub(super) fn weapon_rate( table: &MissionControlDeviceTableState, device: &EffectiveControlDevice, dt: f32, ) -> Result { let active = control_device_budget_active_provider_value(table, device)?.is_some(); charge_rate( weapon_amount(device)?, control_device_budget_coefficient(device, 1)?, dt, control_device_budget_descriptor_float(device, 8, "weapon upkeep")?, active, ) } pub(super) fn weapon_update( table: &mut MissionControlDeviceTableState, index: usize, dt: f32, allocation: f32, ) -> Result<(), ControlResourceAccessError> { let device = control_budget_device(table, index)?; let active = control_device_budget_active_provider_value(table, device)?.is_some(); let (amount, ratio) = charge_update( weapon_amount(device)?, control_device_budget_coefficient(device, 1)?, dt, control_device_budget_descriptor_float(device, 8, "weapon upkeep")?, active, allocation, )?; let MissionControlDeviceTableStatus::Available(devices) = &mut table.status else { unreachable!("checked table") }; devices[index].weapon_charge_bits = Some(amount.to_bits()); if let Some(ratio) = ratio { devices[index].multiplier_bits = Some(ratio.to_bits()); } Ok(()) } pub(super) fn passive_device_rate( device: &EffectiveControlDevice, dt: f32, ) -> Result { if device.native_word_50_bits != Some(0x2000) { return Err(ControlResourceAccessError::UnsupportedField { factory_tag: 10, field: "active mode +0x50", }); } Ok(-checked_control_product( 10, "passive device upkeep", dt, control_device_budget_descriptor_float(device, 8, "passive device rate")?, )?) } pub(super) fn unmodeled_motion_rate() -> f32 { // shortcut: omit demand where the live CTL state has not been recovered. 0.0 } #[derive(Default)] pub(super) struct DriveStateSelection { current: usize, destination: Option, } impl DriveStateSelection { fn advance(&mut self, states: &ControlDriveStates, velocity: [f32; 6]) -> Option { if let Some(destination) = states.destination(self.current, velocity) { self.destination = Some(destination); } if let Some(destination) = self.destination { let next = states.next_state(self.current, destination); self.destination = next .filter(|&next| next != destination) .map(|_| destination); if let Some(next) = next { self.current = next; } } states.factor(self.current) } } #[derive(Clone, Copy)] pub(super) struct DriveMotion { local_speed: f32, profile_limit: f32, state_factor: f32, } impl DriveMotion { pub(super) fn sample( table: &MissionControlDeviceTableState, assets: &MissionAssets, [previous, current]: [TransformState; 2], frame_seconds: f32, can_fly: bool, selection: &mut DriveStateSelection, ) -> Option { let object = table.original_id?.0 as usize; let profile = table.owner_profile.as_ref()?; let control = assets .object_component_controls .get(object)? .get(profile.unit_component_index)? .as_ref()?; let limits = profile.original_words[6..9] .iter() .map(|&word| f32::from_bits(word)); let profile_limit = largest_component(limits)?; let [dx, dy, dz] = std::array::from_fn(|axis| { f32::from_bits(current.position[axis]) - f32::from_bits(previous.position[axis]) }); let (sin, cos) = f32::from_bits(current.orientation[2]).sin_cos(); // shortcut: use the frame's realized displacement until native motion publishes its local vector. let local_velocity = [ (cos * dx + sin * dy) / frame_seconds, (-sin * dx + cos * dy) / frame_seconds, if can_fly { dz / frame_seconds } else { 0.0 }, ]; let local_speed = largest_component(local_velocity)?; let state_factor = match &control.drive { PreparedControlDrive::Uniform(bits) => f32::from_bits(*bits), PreparedControlDrive::Automatic(states) => { let [x, y, z] = local_velocity; let [roll, pitch, yaw] = std::array::from_fn(|axis| { let delta = f32::from_bits(current.orientation[axis]) - f32::from_bits(previous.orientation[axis]); use std::f32::consts::{PI, TAU}; ((delta + PI).rem_euclid(TAU) - PI) / frame_seconds }); selection.advance(states, [x, y, z, roll, pitch, yaw])? } PreparedControlDrive::Unavailable => return None, }; (profile_limit > 0.0 && state_factor.is_finite() && !state_factor.is_subnormal()).then_some( Self { local_speed, profile_limit, state_factor, }, ) } pub(super) fn rate( self, table: &MissionControlDeviceTableState, device: &EffectiveControlDevice, seconds: f32, ) -> Result { if control_device_budget_active_provider_value(table, device)?.is_none() { return Ok(0.0); } self.demand( control_device_budget_descriptor_float(device, 8, "drive rate")?, seconds, ) } fn demand(self, descriptor_rate: f32, seconds: f32) -> Result { let fraction = checked_control_ratio("drive speed fraction", self.local_speed, self.profile_limit)?; let rate = checked_control_product(5, "drive nominal demand", fraction, descriptor_rate)?; let rate = checked_control_product(5, "drive state demand", rate, self.state_factor)?; Ok(-checked_control_product( 5, "drive interval demand", rate, seconds, )?) } } fn largest_component(values: impl IntoIterator) -> Option { values.into_iter().try_fold(0.0_f32, |largest, value| { (value.is_finite() && !value.is_subnormal()).then(|| largest.max(value.abs())) }) } pub(super) fn read( mission: &crate::LoadedMissionState, handle: crate::ObjectHandle, weapons: &mut [crate::player_weapon::PlayerWeapon], ) { let table = mission .control_device_tables .iter() .find(|table| table.handle == handle); let devices = table.and_then(|table| match &table.status { MissionControlDeviceTableStatus::Available(devices) => Some(devices), _ => None, }); for weapon in weapons { let device = devices .and_then(|devices| devices.iter().find(|device| matches_weapon(device, weapon))); if let Some(device) = device { weapon.rounds_remaining = device.weapon_rounds; } weapon.destroyed = device .and_then(|device| crate::control_node_provider_row(table?, device.key).ok()) .is_some_and(|row| row.current_flags.is_some_and(|flags| flags & 0x10 != 0)); weapon.charge = if !weapon.destroyed && mission.control_resources.energy_available(handle) { device.and_then(|device| { let coefficients = device.coefficient_bits?; let charge = Charge { capacity: f32::from_bits(coefficients[1]), cost: f32::from_bits(coefficients[2]), amount: f32::from_bits(device.weapon_charge_bits?), }; [charge.capacity, charge.cost, charge.amount] .into_iter() .all(|value| value.is_finite() && !value.is_subnormal()) .then_some(charge) }) } else { None }; } } fn matches_weapon( device: &EffectiveControlDevice, weapon: &crate::player_weapon::PlayerWeapon, ) -> bool { device.factory_tag == 2 && device.factory_provenance.unit_component_index == weapon.component_index && device.factory_provenance.typed_record_index == weapon.control_record_index } pub(super) fn publish( mission: &mut crate::LoadedMissionState, handle: crate::ObjectHandle, weapons: &mut [crate::player_weapon::PlayerWeapon], ) { if weapons.is_empty() { return; } let available = mission.control_resources.energy_available(handle); let Some(table) = mission .control_device_tables .iter_mut() .find(|table| table.handle == handle) else { mission .control_resources .mobile .stub(handle.slot, "weapon_owner_table".into()); return; }; let object = table.original_id.map_or(handle.slot, |id| id.0); let waits: u64 = weapons.iter().map(|weapon| weapon.energy_waits).sum(); let total = mission .control_resources .mobile .weapon_waits .entry(object) .or_default(); let previous = *total; *total += waits; if previous == 0 && waits > 0 { eprintln!("weapon_energy_wait object={object} samples={waits}"); } for weapon in weapons { weapon.energy_waits = 0; if weapon.destroyed { continue; } let device = match &mut table.status { MissionControlDeviceTableStatus::Available(devices) => devices .iter_mut() .find(|device| matches_weapon(device, weapon)), _ => None, }; if let Some(device) = device { device.weapon_rounds = weapon.rounds_remaining; if let Some(charge) = &weapon.charge { device.weapon_charge_bits = Some(charge.amount.to_bits()); if charge.capacity > 0.0 { device.multiplier_bits = Some((charge.amount / charge.capacity).to_bits()); } continue; } } if available { mission.control_resources.mobile.stub( object, format!( "weapon_link_{}_{}", weapon.component_index, weapon.control_record_index ), ); } } } #[cfg(test)] mod tests { use super::*; #[test] fn drive_demand_uses_largest_local_axis_and_the_ctl_factor() { let profile_limit = largest_component([5.0, 14.0, 7.0]).unwrap(); for (velocity, state_factor, seconds, expected) in [ ([0.0, -7.0, 2.0], 0.8, 0.25, 0xbe80_0000), ([-14.0, 1.0, 2.0], 1.0, 0.5, 0xbfa0_0000), ([1.0, 2.0, -7.0], 1.0, 1.0, 0xbfa0_0000), ([0.0, -7.0, 2.0], 0.0, 0.25, 0x8000_0000), ] { let motion = DriveMotion { local_speed: largest_component(velocity).unwrap(), profile_limit, state_factor, }; assert_eq!(motion.demand(2.5, seconds).unwrap().to_bits(), expected); } } #[test] fn native_weapon_budget_refills_disabled_devices_and_can_go_negative() { // GOG Control.dll +0x29a40 / +0x29a90, x87 CW 0x007f. for (capacity, amount, dt, upkeep, allocation, active, rate, charge, multiplier) in [ ( 10.0, 3.0, 0.25, 4.0, 0.5, true, 0xc1000000, 0x40c00000, 0x3f19999a, ), ( 10.0, 10.0, 0.25, 4.0, 0.5, true, 0xbf800000, 0x41180000, 0x3f733333, ), ( 10.0, 3.0, 0.25, 4.0, 0.5, false, 0xc0e00000, 0x40d00000, 0x3f266666, ), ( 10.0, 3.0, 0.25, 4.0, 0.0, true, 0xc1000000, 0x40000000, 0x3e4ccccd, ), (0.0, 0.0, 0.25, 4.0, 1.0, true, 0xbf800000, 0, 0x3e800000), ( 10.0, 0.5, 0.25, 4.0, 0.0, true, 0xc1280000, 0xbf000000, 0xbd4ccccd, ), ( 19.81, 0.23, 0.375491, 17.258, 0.234267, true, 0xc1d07b56, 0xbe14a841, 0xbbf02203, ), ] { let rate_value = charge_rate(amount, capacity, dt, upkeep, active).unwrap(); assert_eq!(rate_value.to_bits(), rate); let (amount, ratio) = charge_update(amount, capacity, dt, upkeep, active, allocation).unwrap(); assert_eq!(amount.to_bits(), charge); assert_eq!(ratio.unwrap_or(0.25).to_bits(), multiplier); } } #[test] fn charge_allows_equality_and_is_spent_after_a_completed_shot() { let mut charge = Charge { capacity: 10.0, cost: 4.0, amount: 8.0, }; assert!(charge.can_start()); charge.finish_shot(); assert!(charge.can_start()); charge.finish_shot(); assert!(!charge.can_start()); let unlimited = Charge { capacity: 0.0, cost: 4.0, amount: 0.0, }; assert!(unlimited.can_start()); } #[test] #[ignore = "requires licensed corpus"] fn licensed_spider_drive_uses_the_authored_gait_and_resource_budget() { use crate::{ create, frame, load_gameplay_mission, EngineServices, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_vfs::DirectoryVfs; use fparkan_world::OriginalObjectId; 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 mission = engine.loaded.as_ref().unwrap(); let control = mission.mission_assets.object_component_controls[58][0] .as_ref() .expect("stock 12spd1 chassis CTL"); let PreparedControlDrive::Automatic(states) = &control.drive else { panic!("stock spider selects its drive state using velocity"); }; let mut selection = DriveStateSelection::default(); // Consecutive 0x51c0 calls on the GOG profile, applying the first // queued state after each call as in 0xc317–0xc37a. for (forward, yaw, expected) in [ (0.0, 0.0, &[0, 0][..]), (0.5, 0.0, &[0, 0]), (6.0, 0.0, &[15, 16, 15, 16, 15]), (6.0, 0.25, &[16, 15, 16, 15, 16]), (13.0, 0.0, &[19, 20, 21, 22, 19]), (0.0, 0.0, &[20, 21, 22, 0, 0, 0]), (-6.0, 0.0, &[17, 18, 17, 18, 17]), (0.0, 0.0, &[18, 0, 0, 0, 0, 0]), (0.0, 0.25, &[8, 9, 10, 11, 12]), (0.0, 0.0, &[13, 14, 0, 0, 0, 0]), ] { let velocity = [0.0, forward, 0.0, 0.0, 0.0, yaw]; for &state in expected { let factor = selection.advance(states, velocity).unwrap(); assert_eq!(selection.current, state, "{velocity:?}"); assert_eq!(factor, if state == 0 { 0.0 } else { 1.0 }); } } let mut first_position = None; let mut moving_budget = false; for now in (0..=40_000).step_by(100) { frame(&mut engine, now).unwrap(); let mission = engine.loaded.as_ref().unwrap(); if let Some(table) = mission.control_device_tables.iter().find(|table| { table.original_id == Some(OriginalObjectId(58)) && fparkan_world::transform_state(&engine.world, table.handle).is_ok() }) { let position = fparkan_world::transform_state(&engine.world, table.handle) .unwrap() .position; let initial = first_position.get_or_insert(position); let horizontal_move = position[..2] != initial[..2]; moving_budget |= horizontal_move && f32::from_bits(table.current_output_rate_5e0_bits) > 0.0; } } let report = &engine.loaded.as_ref().unwrap().control_resources.mobile; assert!(!report.stubs.contains_key(&(58, "motion_factory_5".into()))); assert!( moving_budget, "the first released spider must spend power while walking" ); } #[test] #[ignore = "requires licensed corpus"] fn licensed_autodemo_flyer_uses_its_drive_budget_in_motion() { use crate::{ create, frame, load_gameplay_mission, EngineServices, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_vfs::DirectoryVfs; 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/Autodemo.00/data.tma".into(), mode: MissionMode::AutoDemo, }, MissionStartupInput { queue_time_ms: 0, research_creation_gate: false, }, None, ) .unwrap(); engine.autodemo_combat = None; let mission = engine.loaded.as_ref().unwrap(); let flyer = mission .control_device_tables .iter() .position(|table| table.original_id == Some(fparkan_world::OriginalObjectId(2))) .unwrap(); let handle = mission.control_device_tables[flyer].handle; let start = fparkan_world::transform_state(&engine.world, handle) .unwrap() .position; let mut drive_spent = false; for now in (0..=6_000).step_by(100) { frame(&mut engine, now).unwrap(); let mission = engine.loaded.as_ref().unwrap(); drive_spent |= f32::from_bits(mission.control_device_tables[flyer].current_output_rate_5e0_bits) > 0.0; } let end = fparkan_world::transform_state(&engine.world, handle) .unwrap() .position; assert_ne!(start, end); let stubs = &engine .loaded .as_ref() .unwrap() .control_resources .mobile .stubs; assert!(!stubs.contains_key(&(2, "motion_factory_5".into()))); assert!(drive_spent, "motion must draw from the budget"); let mut at_rest = engine.loaded.as_ref().unwrap().control_device_tables[flyer].clone(); let MissionControlDeviceTableStatus::Available(devices) = &mut at_rest.status else { panic!("stock flyer has a complete Control table"); }; for device in devices.iter_mut().filter(|device| device.factory_tag == 2) { device.weapon_charge_bits = Some(0); } let mut in_motion = at_rest.clone(); crate::control_resource_budget_pass(&mut at_rest, 0.5).unwrap(); crate::control_resource_budget_pass_with_motion( &mut in_motion, 0.5, Some(DriveMotion { local_speed: 10.0, profile_limit: 10.0, state_factor: 1.0, }), ) .unwrap(); let charge = |table: &MissionControlDeviceTableState| { let MissionControlDeviceTableStatus::Available(devices) = &table.status else { panic!("stock flyer has a complete Control table"); }; let weapon = devices .iter() .find(|device| device.factory_tag == 2) .unwrap(); f32::from_bits(weapon.weapon_charge_bits.unwrap()) }; assert!(charge(&in_motion) < charge(&at_rest)); } #[test] #[ignore = "requires licensed corpus"] fn licensed_stock_lasers_wait_for_charge_and_recover_from_the_unit_budget() { use crate::{ create, frame, load_gameplay_mission, EngineServices, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_vfs::DirectoryVfs; 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/Autodemo.00/data.tma".into(), mode: MissionMode::AutoDemo, }, MissionStartupInput { queue_time_ms: 0, research_creation_gate: false, }, None, ) .unwrap(); // Isolate a held trigger on an unchanged stock unit; this is not mission acceptance. engine.autodemo_combat = None; let mission = engine.loaded.as_ref().unwrap(); let handle = mission.control_device_tables[1].handle; let mut weapons = crate::player_weapon::prepare_unit_weapons( &mission.mission_assets.object_component_controls[1], ); let mut idle_bank = weapons.clone(); assert_eq!(weapons.weapons().len(), 2); assert!(weapons .weapons() .iter() .all(|weapon| weapon.rounds_remaining().is_none())); let mut shots = 0; frame(&mut engine, 0).unwrap(); for now in (50..=120_000).step_by(50) { frame(&mut engine, now).unwrap(); weapons.read_control_energy(&engine, handle); shots += weapons.fire(true, now).count(); weapons.publish_control_energy(&mut engine, handle); idle_bank.read_control_energy(&engine, handle); idle_bank.publish_control_energy(&mut engine, handle); } let report = &engine.loaded.as_ref().unwrap().control_resources.mobile; assert!(shots > 0); assert!( report.weapon_waits[&1] > 0, "expected depleted laser charge" ); assert!( !report.stubs.keys().any(|(object, reason)| *object == 1 && (reason.starts_with("budget_") || reason.starts_with("weapon_link"))), "{:?}", report.stubs ); for now in (120_050..=140_000).step_by(50) { frame(&mut engine, now).unwrap(); weapons.read_control_energy(&engine, handle); weapons.fire(false, now).count(); weapons.publish_control_energy(&mut engine, handle); } let mut resumed = 0; for now in (140_050..=142_000).step_by(50) { frame(&mut engine, now).unwrap(); weapons.read_control_energy(&engine, handle); resumed += weapons.fire(true, now).count(); weapons.publish_control_energy(&mut engine, handle); } assert!(resumed > 0, "laser must resume after regeneration"); } }