diff options
Diffstat (limited to 'crates/fparkan-runtime')
| -rw-r--r-- | crates/fparkan-runtime/src/control_resources.rs | 172 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 29 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/production.rs | 48 |
3 files changed, 235 insertions, 14 deletions
diff --git a/crates/fparkan-runtime/src/control_resources.rs b/crates/fparkan-runtime/src/control_resources.rs new file mode 100644 index 00000000..e58c5a7b --- /dev/null +++ b/crates/fparkan-runtime/src/control_resources.rs @@ -0,0 +1,172 @@ +use crate::{control_resource_budget_pass, LoadedMissionState}; +use fparkan_world::{transform_state, ObjectHandle, World}; +use std::collections::BTreeMap; + +/// Factory Control updates; other owners and global Control ordering remain open. +pub(super) struct FactoryResources { + clocks: Vec<(ObjectHandle, ResourceClock)>, + rng: u32, + ticks: BTreeMap<u32, u64>, + stops: BTreeMap<u32, (u64, String)>, +} + +impl Default for FactoryResources { + fn default() -> Self { + Self { + clocks: Vec::new(), + // Explicit bootstrap seed until Control initialization and other owners are wired. + rng: 1, + ticks: BTreeMap::new(), + stops: BTreeMap::new(), + } + } +} + +impl FactoryResources { + pub(super) fn ticks(&self) -> impl Iterator<Item = (u32, u64)> + '_ { + self.ticks.iter().map(|(&unit, &count)| (unit, count)) + } + + pub(super) fn stops(&self) -> impl Iterator<Item = (u32, u64, &str)> + '_ { + self.stops + .iter() + .map(|(&unit, (count, reason))| (unit, *count, reason.as_str())) + } +} + +pub(super) fn tick(mission: &mut LoadedMissionState, world: &World, now_ms: u32) { + let state = &mut mission.factory_resources; + state + .clocks + .retain(|(handle, _)| transform_state(world, *handle).is_ok()); + for table in &mut mission.control_device_tables { + if !table + .original_id + .and_then(|id| mission.object_drafts.get(id.0 as usize)) + .is_some_and(|draft| draft.unit_dat_header_flags == Some(crate::autodemo::PLANT_CLASS)) + || transform_state(world, table.handle).is_err() + { + continue; + } + let clock = if let Some(index) = state + .clocks + .iter() + .position(|(handle, _)| *handle == table.handle) + { + &mut state.clocks[index].1 + } else { + state.clocks.push(( + table.handle, + ResourceClock { + frame_ms: now_ms as f32, + resource_ms: now_ms as f32, + forced: 0, + }, + )); + &mut state.clocks.last_mut().expect("new factory clock").1 + }; + // Control.dll+0x42480: default resource period; this is a separate RNG from Behavior. + let Some(seconds) = clock.step(now_ms as f32, true, 250.0, &mut state.rng) else { + continue; + }; + match control_resource_budget_pass(table, seconds) { + Ok(()) => { + let count = state.ticks.entry(table.handle.slot).or_default(); + *count += 1; + if *count == 1 { + eprintln!("sim_coverage factory_control_clock_approx=1 unit={} (factory owners; Control RNG seed and global order remain open)", table.handle.slot); + } + } + Err(reason) => { + let stop = state + .stops + .entry(table.handle.slot) + .or_insert_with(|| (0, format!("{reason:?}"))); + stop.0 += 1; + if stop.0 == 1 { + eprintln!( + "sim_coverage factory_control_budget_stub=1 unit={} reason={}", + table.handle.slot, stop.1 + ); + } + } + } + } +} + +#[derive(Default)] +struct ResourceClock { + frame_ms: f32, + resource_ms: f32, + forced: u32, +} + +impl ResourceClock { + fn step(&mut self, now_ms: f32, active: bool, period_ms: f32, rng: &mut u32) -> Option<f32> { + if now_ms - self.frame_ms < 1.0 { + return None; + } + self.frame_ms = now_ms; + if !active { + self.resource_ms = now_ms; + return None; + } + let low = (*rng as u16).wrapping_shl(1) ^ (*rng >> 16) as u16; + let high = ((*rng >> 16) as u16 >> 1) ^ low; + *rng = (u32::from(high) << 16) | u32::from(low); + let quarter = period_ms * 0.25; + let random_scale = quarter / 65536.0; + let deadline = + ((f32::from(high) * random_scale - quarter * 0.5) + period_ms) + self.resource_ms; + if self.forced == 0 && now_ms <= deadline { + return None; + } + self.forced = self.forced.saturating_sub(1); + let seconds = (now_ms - self.resource_ms) * 0.001; + self.resource_ms = now_ms; + Some(seconds) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn native_control_redraws_the_deadline_on_each_accepted_frame() { + let mut clock = ResourceClock::default(); + let mut rng = 0x1234_5678; + assert_eq!(clock.step(0.5, true, 500.0, &mut rng), None); + assert_eq!((clock.frame_ms, rng), (0.0, 0x1234_5678)); + for (now, random, last, due) in [ + (500.0, 0xb7de_bec4, 0.0, None), + (501.0, 0x91b9_ca56, 0.0, None), + (502.0, 0x4dc9_0515, 502.0, Some(0.50200003)), + (503.0, 0x6107_47e3, 502.0, None), + ] { + assert_eq!(clock.step(now, true, 500.0, &mut rng), due); + assert_eq!( + (clock.frame_ms, clock.resource_ms, rng), + (now, last, random) + ); + } + } + + #[test] + fn native_control_equality_forced_step_and_inactive_baseline() { + let mut clock = ResourceClock::default(); + let mut rng = 0xffff_0000; + assert_eq!(clock.step(500.0, true, 500.0, &mut rng), None); + assert_eq!((clock.resource_ms, rng), (0.0, 0x8000_ffff)); + assert_eq!(clock.step(501.0, true, 500.0, &mut rng), Some(0.50100005)); + assert_eq!((clock.resource_ms, rng), (501.0, 0x3ffe_7ffe)); + clock.forced = 2; + assert_eq!(clock.step(502.0, true, 500.0, &mut rng), Some(0.001)); + assert_eq!((clock.forced, rng), (1, 0xdffd_c002)); + assert_eq!(clock.step(503.0, false, 500.0, &mut rng), None); + assert_eq!( + (clock.resource_ms, clock.forced, rng), + (503.0, 1, 0xdffd_c002) + ); + } +} diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index ac635ad2..762c18f3 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -51,6 +51,7 @@ mod clan_area_strength; mod clan_build_limits; mod clan_building_queries; mod clan_clock; +mod control_resources; pub use clan_clock::note_mission_pause_elapsed; mod clan_combat_groups; mod clan_combat_strength; @@ -1368,6 +1369,7 @@ struct LoadedMissionState { research_trf_tables: Vec<MissionResearchTrfTable>, free_research: research::FreeResearch, laboratories: laboratory::Laboratories, + factory_resources: control_resources::FactoryResources, ai_startup_states: Vec<MissionAiStartupState>, script_bundles: Vec<MissionScriptBundle>, script_varset: Option<MissionScriptVarSet>, @@ -2697,6 +2699,7 @@ fn load_mission_with_options( research_trf_tables, free_research, laboratories: Default::default(), + factory_resources: Default::default(), ai_startup_states: loaded_scripts.ai_startup_states, script_bundles: loaded_scripts.bundles, script_varset: loaded_scripts.varset, @@ -2782,6 +2785,9 @@ pub fn step_headless( if let Some(resources) = resources { resources.apply(engine); } + if let Some(mission) = &mut engine.loaded { + control_resources::tick(mission, &engine.world, queue_time_ms); + } let (autodemo_combat_events, autodemo_combat_unavailable) = if let Some(mut combat) = engine.autodemo_combat.take() { let result = combat.tick(engine, queue_time_ms); @@ -2941,6 +2947,8 @@ pub struct SimulationReport { pub script_factory_orders: Vec<(u16, u32, u64)>, /// Active factory task updates; idle owner phases and global RNG order remain approximate. pub factory_clock_ticks: Vec<(u16, u32, u64)>, + pub factory_control_ticks: Vec<(u32, u64)>, + pub factory_control_stops: Vec<(u32, u64, String)>, /// Approximate clan strength queries, grouped by caller and target clan. pub script_strength_queries: Vec<(usize, u16, u64)>, pub script_capture_queries: Vec<(usize, u64)>, @@ -3015,6 +3023,8 @@ pub fn simulate_mission_report( script_factory_rejections: Vec::new(), script_factory_orders: Vec::new(), factory_clock_ticks: Vec::new(), + factory_control_ticks: Vec::new(), + factory_control_stops: Vec::new(), script_strength_queries: Vec::new(), script_capture_queries: Vec::new(), script_attack_queries: Vec::new(), @@ -3122,6 +3132,15 @@ pub fn simulate_mission_report( .clan_research_catalogs .extend(loaded.clan_ai_events.research_catalogs()); report.laboratory = loaded.laboratories.report(); + report + .factory_control_ticks + .extend(loaded.factory_resources.ticks()); + report.factory_control_stops.extend( + loaded + .factory_resources + .stops() + .map(|(unit, count, reason)| (unit, count, reason.to_owned())), + ); if let Some(production) = &engine.production { report.factory_clock_ticks.extend(production.clock_ticks()); } @@ -3724,8 +3743,8 @@ pub fn query_loaded_mission_control_resource( /// readers use the device key to read the current provider value and multiply /// it by coefficient 0. Only current tag 26 also multiplies by `M`; current /// tag 5 ignores `M` and descriptor word 8 for this selector. Explicit Control -/// update calls can change current provider or multiplier values; the mission -/// clock does not advance them automatically. Selector `6` first checks the +/// update calls can change current provider or multiplier values; factory +/// resource budgets also advance during mission steps. Selector `6` first checks the /// current descriptor tag: a non-2 tag returns `Ok(None)`. For the represented /// factory-2 layout it reads `+0x174`, subject to the normal-or-zero float /// range checks; an unsupported field or layout returns a typed error. This is @@ -3793,8 +3812,8 @@ pub fn set_loaded_mission_control_device_selector( /// `Transfer_Ore_OffBoard` value. Unsupported table/query paths return an error. /// Profile values come from full mission loading, while `0xe00` reads the /// current CPU-projected provider and device state. Explicit Control updates -/// can therefore change `0x1002`; the mission clock does not update it -/// automatically. +/// can therefore change `0x1002`; factory Control resource budgets also run +/// during mission steps. /// /// # Errors /// Returns an error for an invalid handle, unavailable mission/profile/table, @@ -4095,7 +4114,7 @@ pub fn distribute_loaded_mission_control_provider_amount( /// The pass supports the original factory callbacks for tags 9, 15, 19, and 26, /// plus the generic default callback pair. Current descriptor category tags are /// supported for the native map prefix `0..=34`. This is an explicit CPU update; -/// the mission clock does not call it yet. Rate outputs at `+0x5dc/+0x5e0` are +/// factories also run this pass on their resource clock. Rate outputs at `+0x5dc/+0x5e0` are /// stored on the table after a successful pass. /// /// # Errors diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs index d2d8a135..078fef31 100644 --- a/crates/fparkan-runtime/src/production.rs +++ b/crates/fparkan-runtime/src/production.rs @@ -278,16 +278,8 @@ impl Production { } let mut ready = now_ms.wrapping_sub(order.start_ms) >= order.duration_ms; if let Some(paid) = &mut order.paid { - // shortcut: gate the factory rate on clan power until Control - // propagates the delivered power to the production device. - let powered = mission.script_bundles.iter().any(|bundle| { - bundle.clan_index == usize::from(order.owner.0) - && bundle - .behavior_warm_start - .is_some_and(|state| f32::from_bits(state.cleared_words[0]) > 0.0) - }); let (table, ore) = factory_resources(mission, order.plant)?; - let rate = if powered { factory_rate(table)? } else { 0.0 }; + let rate = factory_rate(table)?; if paid.advance(now_ms, rate, ore) && paid.collected.power + RESOURCE_EPSILON >= paid.cost.power { @@ -1014,6 +1006,18 @@ mod tests { .unwrap() .1 .current_ore_bits = 100.0_f32.to_bits(); + // No Control budget runs in this isolated clock test: set the work multiplier explicitly. + let table = factory_resources(engine.loaded.as_mut().unwrap(), plant) + .unwrap() + .0; + let MissionControlDeviceTableStatus::Available(devices) = &mut table.status else { + panic!("factory devices"); + }; + devices + .iter_mut() + .find(|device| device.descriptor.tag == 26) + .unwrap() + .multiplier_bits = Some(0); // Isolate the factory's owner timer from unrelated clan updates. let mut rng = 1; for now in [100, 174] { @@ -1093,12 +1097,38 @@ mod tests { let cost = &order.paid.as_ref().unwrap().cost; assert!((cost.ore - 25.12).abs() < 0.001); assert!((cost.power - 72.7).abs() < 0.001); + // Debug fixture: empty the factory's local energy reserve as well as leaving it without a generator. + crate::set_control_device_table_multiplier( + factory_resources(engine.loaded.as_mut().unwrap(), plant) + .unwrap() + .0, + 0.0, + ) + .unwrap(); for now in (100..=6100).step_by(50) { assert!(step_headless(&mut engine, InputSnapshot::default(), now) .unwrap() .produced_unit .is_none()); } + let loaded = engine.loaded.as_ref().unwrap(); + assert!(loaded + .factory_resources + .ticks() + .any(|(unit, count)| unit == plant.slot && count > 0)); + assert!(!loaded + .factory_resources + .stops() + .any(|(unit, _, _)| unit == plant.slot)); + let table = loaded + .control_device_tables + .iter() + .find(|table| table.handle == plant) + .unwrap(); + assert!( + factory_rate(table).unwrap() < 5.0, + "unpowered production device must lose its full work rate" + ); let factory_position = pose.position; pose.position = [1288.99_f32, 807.4, 74.08].map(f32::to_bits); set_transform(&mut engine.world, cockpit.handle, pose).unwrap(); |
