diff options
Diffstat (limited to 'crates/fparkan-runtime/src')
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 38 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_research.rs | 22 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/laboratory.rs | 488 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 9 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/research.rs | 63 |
5 files changed, 551 insertions, 69 deletions
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index 57de496d..3b3bb708 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -20,6 +20,7 @@ const ATTACK_UNIT: u32 = 13; const OPTIMAL_TRANSPORT: u32 = 4; const BUILDING_NEEDED: u32 = 3; const MINE_NEEDED: u32 = 1; +const MAKE_RESEARCH: u32 = 10; pub(super) struct ScriptFactoryOrder { pub owner: OwnerId, @@ -89,6 +90,7 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) -> Vec<MissionNotice let Some(loaded) = &mut engine.loaded else { return notices; }; + crate::laboratory::tick(loaded, &engine.world, now_ms); crate::construction::tick( loaded, &mut engine.world, @@ -141,7 +143,8 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) -> Vec<MissionNotice OwnerId(clan as u16), loaded.unit_patrol.as_ref(), group, - |unit| loaded.construction.active(unit) || ai.transports.iter().any(|(job, task)| *job == (clan, key) && task.unit == unit), + |unit| loaded.construction.active(unit) || loaded.laboratories.active(unit) + || ai.transports.iter().any(|(job, task)| *job == (clan, key) && task.unit == unit), ) }); if ready { @@ -568,6 +571,7 @@ impl LoadedMissionState { .filter(|&unit| !self.mission_events.is_reserved(owner, unit) && !self.clan_ai_events.unit_assigned(unit) && !self.construction.active(unit) + && !self.laboratories.active(unit) && !production.is_some_and(|queue| queue.is_building_at(unit, owner)) && !orders.iter().any(|order: &ScriptFactoryOrder| order.plant == unit)) .filter(|&unit| mode == 1 || self.unit_patrol.as_ref().is_none_or(|patrol| !patrol.is_shut_down(unit))); @@ -696,6 +700,7 @@ impl LoadedMissionState { class, |unit| !self.clan_ai_events.unit_assigned(unit) && !self.construction.active(unit) + && !self.laboratories.active(unit) && !production.is_some_and(|queue| queue.is_building_at(unit, owner)) && !orders.iter().any(|order: &ScriptFactoryOrder| order.plant == unit), ).unwrap_or(u32::MAX); @@ -908,7 +913,7 @@ impl LoadedMissionState { Some(1) if problem .as_ref() - .is_some_and(|record| matches!(record.key.word_0, OPTIMAL_TRANSPORT | MINE_NEEDED | 6 | BUILDING_PROTECT | PLACE_PROTECT)) + .is_some_and(|record| matches!(record.key.word_0, OPTIMAL_TRANSPORT | MINE_NEEDED | MAKE_RESEARCH | 6 | BUILDING_PROTECT | PLACE_PROTECT)) || !conditions.is_empty() => { solving = true @@ -936,14 +941,14 @@ impl LoadedMissionState { }; let key = problem.as_ref().expect("condition requires a problem").key; let condition = match (action, mode) { - (2, 0) if matches!(key.word_0, BUILDING_NEEDED | MINE_NEEDED) || (key.word_0 == OPTIMAL_TRANSPORT && solving) => { + (2, 0) if matches!(key.word_0, BUILDING_NEEDED | MINE_NEEDED | MAKE_RESEARCH) || (key.word_0 == OPTIMAL_TRANSPORT && solving) => { let unit = assignment.filter(|&unit| self.mission_events .logic_objects(&self.mission, world, id).any(|handle| handle == unit)) .ok_or("Handler(27) task wait requires the assigned unit")?; Some(Condition::TaskInactive(unit)) } - (1 | 3, 0) if matches!(key.word_0, 7 | 9) || (action == 1 && matches!(key.word_0, BUILDING_PROTECT | ATTACK_UNIT)) => { - let target = crate::mission_events::placed_logic_objects( + (1 | 3, 0) if matches!(key.word_0, 7 | 9) || (action == 1 && matches!(key.word_0, BUILDING_PROTECT | ATTACK_UNIT | MAKE_RESEARCH)) => { + let target = self.mission_events.logic_objects( &self.mission, world, id ).next(); Some(if action == 1 { Condition::ObjectDestroyed(target) } else { @@ -1043,20 +1048,23 @@ impl LoadedMissionState { ScriptDispatchSelector::Handler(41) if problem.is_some() => { let id = single_dword(&instruction.references, values) .ok_or("Handler(41) requires a laboratory logical ID")?; - let exists = self.mission_events.logic_objects( + let lab = self.mission_events.logic_objects( &self.mission, world, id, ) - .any(|handle| Some(handle) == assignment); - // shortcut: reject the order until the native laboratory research task is wired. - self.clan_ai_events - .log_research_stub(clan, 41, &bundle.script_path); - Ok(Some(VarSetDefault::Dword(if exists { - 0 - } else { - u32::MAX - }))) + .find(|handle| Some(*handle) == assignment); + let Some(lab) = lab else { return Ok(Some(VarSetDefault::Dword(u32::MAX))); }; + let result = crate::laboratory::order(&mut self.laboratories, &self.clan_ai_events.research_catalogs, + &self.object_drafts, &self.free_research, world, vfs, clan, lab, now_ms); + if let Err(reason) = &result { self.laboratories.rejected(clan, lab, reason); } + Ok(Some(VarSetDefault::Dword(u32::from(result.is_ok())))) + } + ScriptDispatchSelector::Handler(43) if crate::clan_script_init::research_catalog(instruction) => { + let vfs = vfs.ok_or("research VFS is unavailable")?; + let catalog = self.clan_ai_events.research_catalogs.get_mut(&clan).ok_or("research catalog is unavailable")?; + catalog.refresh(vfs)?; + Ok(None) } ScriptDispatchSelector::Handler(2) => { let (name, input) = problem_operands( diff --git a/crates/fparkan-runtime/src/clan_research.rs b/crates/fparkan-runtime/src/clan_research.rs index 94e0696a..303d065e 100644 --- a/crates/fparkan-runtime/src/clan_research.rs +++ b/crates/fparkan-runtime/src/clan_research.rs @@ -7,6 +7,7 @@ use fparkan_world::OwnerId; pub(super) struct ClanResearch { pub(super) candidates: ResearchCandidateSet, pub(super) table: ResearchTrfDocument, + pub(super) refreshes: u64, } impl ClanResearch { @@ -26,13 +27,21 @@ impl ClanResearch { loaded: true, ..Default::default() }; - let mut catalog = Self { candidates, table }; - catalog - .candidates - .refresh_selection(vfs, Some(&catalog.table)) - .map_err(|error| error.to_string())?; + let mut catalog = Self { + candidates, + table, + refreshes: 0, + }; + catalog.refresh(vfs)?; Ok(catalog) } + + pub(super) fn refresh(&mut self, vfs: &dyn Vfs) -> Result<(), String> { + self.refreshes += 1; + self.candidates + .refresh_selection(vfs, Some(&self.table)) + .map_err(|error| error.to_string()) + } } pub(super) fn initialize( @@ -62,12 +71,13 @@ pub(super) fn initialize( } impl crate::clan_ai_events::ClanAiEvents { - pub(super) fn research_catalogs(&self) -> impl Iterator<Item = (usize, usize, u32)> + '_ { + pub(super) fn research_catalogs(&self) -> impl Iterator<Item = (usize, usize, u32, u64)> + '_ { self.research_catalogs.iter().map(|(&clan, catalog)| { ( clan, catalog.candidates.entries.len(), catalog.candidates.selected_index, + catalog.refreshes, ) }) } diff --git a/crates/fparkan-runtime/src/laboratory.rs b/crates/fparkan-runtime/src/laboratory.rs new file mode 100644 index 00000000..28fe51f1 --- /dev/null +++ b/crates/fparkan-runtime/src/laboratory.rs @@ -0,0 +1,488 @@ +use crate::{BehaviorOreState, LoadedMissionState, MissionControlDeviceTableState}; +use fparkan_assets::{decode_behavior_work_rates, research_project_rows}; +use fparkan_vfs::Vfs; +use fparkan_world::{identity_metadata, ObjectHandle, OwnerId, World}; +use std::collections::BTreeMap; + +const LAB_CLASS: u32 = 0x8000_0400; + +/// Executed laboratory orders and the remaining native completion boundary. +#[derive(Default, Debug, Clone, PartialEq, Eq)] +pub struct LaboratoryReport { + /// Accepted/rejected orders by clan and laboratory. + pub orders: Vec<(usize, u32, u64, u64)>, + /// Completed technologies by clan, laboratory and TRF row. + pub completed: Vec<(usize, u32, usize, u64)>, + /// Native availability propagation still omitted after each completed row. + pub unlock_stubs: Vec<(usize, usize, u64)>, + /// Orders stopped by unavailable runtime state, by clan and laboratory. + pub stopped: Vec<(usize, u32, u64)>, +} + +#[derive(Default)] +pub(super) struct Laboratories { + tasks: Vec<Order>, + rates: Option<[f32; 2]>, + progress: BTreeMap<(usize, usize), f32>, + orders: BTreeMap<(usize, u32), (u64, u64)>, + completed: BTreeMap<(usize, u32, usize), u64>, + unlock_stubs: BTreeMap<(usize, usize), u64>, + stopped: BTreeMap<(usize, u32), u64>, +} + +struct Order { + clan: usize, + lab: ObjectHandle, + slot: usize, + rows: Vec<usize>, + current: Option<(usize, Work)>, + duration: f32, + last_ms: u32, +} + +#[derive(Default)] +struct Work { + ore_cost: f32, + power_cost: f32, + duration: f32, + ore: f32, + power: f32, + time: f32, +} + +impl Work { + fn fraction(&self) -> f32 { + let ratio = |value, target| if target > 0.0 { value / target } else { 1.0 }; + ratio(self.ore, self.ore_cost) + .min(ratio(self.power, self.power_cost)) + .min(ratio(self.time, self.duration)) + } + + fn advance( + &mut self, + seconds: f32, + rate: f32, + uses: [f32; 2], + buffer: &mut BehaviorOreState, + progress: f32, + ) -> f32 { + let before = self.fraction(); + self.ore += (rate * uses[1] * seconds).min(f32::from_bits(buffer.current_ore_bits)); + let remaining = self.ore_cost - self.ore; + buffer.current_ore_bits = 0; + buffer.maximum_ore_bits = (if remaining > 5.0 { + remaining * 0.5 + } else { + remaining + }) + .max(0.0) + .to_bits(); + self.power += rate * uses[0] * seconds; + self.time += seconds; + (progress + (self.fraction() - before)).min(1.0) + } +} + +impl Laboratories { + pub(super) fn active(&self, lab: ObjectHandle) -> bool { + self.tasks.iter().any(|order| order.lab == lab) + } + + pub(super) fn rejected(&mut self, clan: usize, lab: ObjectHandle, reason: &str) { + let rates = self.orders.entry((clan, lab.slot)).or_default(); + rates.1 += 1; + if rates.1 == 1 { + eprintln!( + "script_lab_research_rejected clan={clan} lab={} reason={reason}", + lab.slot + ); + } + } + + pub(super) fn report(&self) -> LaboratoryReport { + LaboratoryReport { + orders: self + .orders + .iter() + .map(|(&(clan, lab), &(accepted, rejected))| (clan, lab, accepted, rejected)) + .collect(), + completed: self + .completed + .iter() + .map(|(&(clan, lab, row), &count)| (clan, lab, row, count)) + .collect(), + unlock_stubs: self + .unlock_stubs + .iter() + .map(|(&(clan, row), &count)| (clan, row, count)) + .collect(), + stopped: self + .stopped + .iter() + .map(|(&(clan, lab), &count)| (clan, lab, count)) + .collect(), + } + } +} + +pub(super) fn order( + state: &mut Laboratories, + catalogs: &BTreeMap<usize, crate::clan_research::ClanResearch>, + drafts: &[crate::MissionObjectDraft], + free: &crate::research::FreeResearch, + world: &World, + vfs: Option<&dyn Vfs>, + clan: usize, + lab: ObjectHandle, + now_ms: u32, +) -> Result<(), String> { + if state.active(lab) || free.active(lab) { + return Err("laboratory is busy".into()); + } + let owner = OwnerId(u16::try_from(clan).map_err(|_| "invalid research clan")?); + let identity = identity_metadata(world, lab).map_err(|error| error.to_string())?; + if identity.owner_id != Some(owner) { + return Err("laboratory belongs to another clan".into()); + } + let slot = identity + .original_id + .ok_or("laboratory has no resource slot")? + .0 as usize; + let draft = drafts.get(slot).ok_or("laboratory draft is unavailable")?; + if draft.unit_dat_header_flags != Some(LAB_CLASS) { + return Err("research target is not a laboratory".into()); + } + let vfs = vfs.ok_or("research VFS is unavailable")?; + let catalog = catalogs + .get(&clan) + .ok_or("research catalog is unavailable")?; + let selected = catalog + .candidates + .entries + .get(catalog.candidates.selected_index as usize) + .ok_or("research project is unavailable")?; + if selected.status != 0 { + return Err("research project is already complete".into()); + } + let bytes = vfs + .read(&selected.path) + .map_err(|error| error.to_string())?; + let unit = fparkan_prototype::decode_unit_dat(&bytes).map_err(|error| error.to_string())?; + let rows = research_project_rows(&unit, &catalog.table).map_err(|error| error.to_string())?; + if rows.is_empty() { + return Err("research project has no technologies".into()); + } + let duration = f32::from_bits( + crate::research::property(draft, b"FreeResearchTime").unwrap_or(2.0_f32.to_bits()), + ); + if !duration.is_finite() || duration < 0.0 { + return Err("invalid laboratory research time".into()); + } + if state.rates.is_none() { + state.rates = Some(load_rates(vfs)?); + } + state.orders.entry((clan, lab.slot)).or_default().0 += 1; + state.tasks.push(Order { + clan, + lab, + slot, + rows, + current: None, + duration, + last_ms: now_ms, + }); + eprintln!( + "sim_coverage script_lab_research_approx=1 clan={clan} lab={} project={}", + lab.slot, + selected.path.as_str() + ); + Ok(()) +} + +pub(super) fn tick(mission: &mut LoadedMissionState, world: &World, now_ms: u32) { + let mut state = std::mem::take(&mut mission.laboratories); + let mut index = 0; + while index < state.tasks.len() { + let result = advance(&mut state, index, mission, world, now_ms); + if matches!(result, Ok(true)) { + index += 1; + continue; + } + let task = state.tasks.remove(index); + if let Err(reason) = result { + *state.stopped.entry((task.clan, task.lab.slot)).or_default() += 1; + eprintln!( + "script_lab_research_stopped clan={} lab={} reason={reason}", + task.clan, task.lab.slot + ); + } + if let Some(ore) = mission + .behavior_ore_states + .iter_mut() + .find(|ore| ore.handle == task.lab) + { + ore.current_ore_bits = 0; + ore.maximum_ore_bits = 0; + } + if let Some(table) = mission + .control_device_tables + .iter_mut() + .find(|table| table.handle == task.lab) + { + if let Err(reason) = power(table, 0.0) { + eprintln!( + "script_lab_power_reset_failed lab={} reason={reason}", + task.lab.slot + ); + } + } + } + mission.laboratories = state; +} + +fn advance( + state: &mut Laboratories, + index: usize, + mission: &mut LoadedMissionState, + world: &World, + now_ms: u32, +) -> Result<bool, String> { + let order = &mut state.tasks[index]; + let owner = OwnerId(order.clan as u16); + if !identity_metadata(world, order.lab).is_ok_and(|id| id.owner_id == Some(owner)) { + return Ok(false); + } + let seconds = now_ms.wrapping_sub(order.last_ms) as f32 * 0.001; + order.last_ms = now_ms; + let catalog = mission + .clan_ai_events + .research_catalogs + .get_mut(&order.clan) + .ok_or("research catalog disappeared")?; + let ore = mission + .behavior_ore_states + .iter_mut() + .find(|ore| ore.handle == order.lab) + .ok_or("laboratory ore state is unavailable")?; + let table = mission + .control_device_tables + .iter_mut() + .find(|table| table.handle == order.lab) + .ok_or("laboratory controls are unavailable")?; + let uses = state.rates.ok_or("laboratory rates are unavailable")?; + if order.current.is_none() { + let Some(row) = order.rows.iter().copied().find(|&row| { + catalog + .table + .flag_byte(row) + .is_some_and(|flag| flag & 3 == 1) + }) else { + return Ok(false); + }; + let free = mission.free_research.take_free(order.slot); + let data = catalog + .table + .row_words(row) + .ok_or("research row is unavailable")?; + let ore_cost = if free { 0.0 } else { f32::from_bits(data[1]) }; + let power_cost = if free { 0.0 } else { f32::from_bits(data[0]) }; + if !ore_cost.is_finite() || !power_cost.is_finite() { + return Err("research costs are non-finite".into()); + } + order.current = Some(( + row, + Work { + ore_cost, + power_cost, + duration: order.duration, + ..Default::default() + }, + )); + ore.current_ore_bits = 0; + ore.maximum_ore_bits = ore_cost.to_bits(); + power(table, uses[0])?; + eprintln!("script_lab_technology_started clan={} lab={} row={row} ore={ore_cost} power={power_cost} free={free} queue_time_ms={now_ms}", order.clan, order.lab.slot); + } + let (row, work) = order.current.as_mut().unwrap(); + if catalog + .table + .flag_byte(*row) + .is_some_and(|flag| flag & 2 != 0) + { + order.current = None; + return Ok(true); + } + let rate = crate::query_behavior_profile_ore_rate(table, 1.0_f32.to_bits()) + .map_err(|error| format!("{error:?}"))?; + let progress = state.progress.entry((order.clan, *row)).or_default(); + *progress = work.advance(seconds, rate, uses, ore, *progress); + if *progress + 0.001 >= 1.0 { + *progress = 1.0; + catalog + .table + .mark_researched_flag(*row) + .map_err(|error| error.to_string())?; + mission.free_research.learned.insert((owner, *row)); + *state + .completed + .entry((order.clan, order.lab.slot, *row)) + .or_default() += 1; + // shortcut: mark the learned row until native dependent-availability propagation is wired. + *state.unlock_stubs.entry((order.clan, *row)).or_default() += 1; + eprintln!( + "sim_coverage script_research_unlock_stub=1 clan={} row={row}", + order.clan + ); + eprintln!( + "script_lab_technology_researched clan={} lab={} row={row} queue_time_ms={now_ms}", + order.clan, order.lab.slot + ); + order.current = None; + } + Ok(true) +} + +fn power(table: &mut MissionControlDeviceTableState, demand: f32) -> Result<(), String> { + let crate::MissionControlDeviceTableStatus::Available(devices) = &table.status else { + return Err("laboratory control table is unavailable".into()); + }; + for index in 0..devices.len() { + crate::set_control_device_table_selector(table, index, 0x500, demand) + .map_err(|error| format!("{error:?}"))?; + } + Ok(()) +} + +fn load_rates(vfs: &dyn Vfs) -> Result<[f32; 2], String> { + let path = crate::normalize_engine_path("research profile", "behpsp.res") + .map_err(|error| error.to_string())?; + let data = vfs.read(&path).map_err(|error| error.to_string())?; + let archive = fparkan_assets::decode_nres_payload(data).map_err(|error| error.to_string())?; + let entry = archive + .find("prof_institute.var") + .ok_or("laboratory profile is unavailable")?; + let rates = + decode_behavior_work_rates(archive.payload(entry).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string())?; + let values = [rates.power_bits, rates.ore_bits].map(f32::from_bits); + if values.iter().any(|rate| !rate.is_finite() || *rate < 0.0) { + return Err("invalid laboratory work rates".into()); + } + Ok(values) +} + +#[cfg(test)] +mod tests { + use super::*; + fn buffer(current: f32) -> BehaviorOreState { + BehaviorOreState { + original_id: fparkan_world::OriginalObjectId(0), + handle: ObjectHandle { + slot: 0, + generation: 0, + }, + class_flags: LAB_CLASS, + current_ore_bits: current.to_bits(), + maximum_ore_bits: 0, + } + } + + #[test] + fn native_paid_tick_uses_the_slowest_completion_fraction_and_requests_remaining_ore() { + let mut work = Work { + ore_cost: 10.0, + power_cost: 30.0, + duration: 10.0, + ..Default::default() + }; + let mut ore = buffer(4.0); + assert_eq!(work.advance(1.0, 2.0, [3.0, 1.0], &mut ore, 0.0), 0.1); + assert_eq!([work.ore, work.power, work.time], [2.0, 6.0, 1.0]); + assert_eq!(ore.current_ore_bits, 0); + assert_eq!(f32::from_bits(ore.maximum_ore_bits), 4.0); + } + + #[test] + fn native_free_work_finishes_by_time_without_resource_supply() { + let mut work = Work { + duration: 5.0, + ..Default::default() + }; + let mut ore = buffer(0.0); + let progress = work.advance(1.0, 0.0, [3.0, 1.0], &mut ore, 0.0); + assert_eq!(progress, 0.2); + assert_eq!(work.advance(4.0, 0.0, [3.0, 1.0], &mut ore, progress), 1.0); + } + + #[test] + #[ignore = "requires licensed corpus"] + fn licensed_stock_ai_laboratories_finish_a_technology_and_release_the_lab() { + 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 vfs = Arc::new(DirectoryVfs::new(root)); + assert_eq!(load_rates(vfs.as_ref()).unwrap(), [3.0, 1.0]); + let mut engine = create(EngineServices::new(vfs)).unwrap(); + load_gameplay_mission( + &mut engine, + MissionRequest { + key: "MISSIONS/Single.02/data.tma".into(), + mode: MissionMode::SingleMission, + }, + MissionStartupInput { + queue_time_ms: 0, + research_creation_gate: false, + }, + None, + ) + .unwrap(); + for now in (0..=900_000).step_by(100) { + frame(&mut engine, now).unwrap(); + let loaded = engine.loaded.as_ref().unwrap(); + for task in &loaded.laboratories.tasks { + assert!( + loaded + .clan_ai_events + .pending_problems() + .any(|problem| problem == (task.clan, 10)), + "research request was removed while laboratory {} was busy at {now}", + task.lab.slot + ); + } + } + let loaded = engine.loaded.as_ref().unwrap(); + assert!(loaded.clan_ai_events.stops().next().is_none()); + assert!( + !loaded.laboratories.completed.is_empty(), + "no completed laboratory technology" + ); + assert!(!loaded.free_research.learned.is_empty()); + assert!(loaded.laboratories.stopped.is_empty()); + assert!( + loaded.laboratories.tasks.is_empty(), + "laboratory remained busy" + ); + for &(clan, _, row, _) in &loaded.laboratories.report().completed { + assert_eq!( + loaded.clan_ai_events.research_catalogs[&clan] + .table + .flag_byte(row) + .unwrap() + & 2, + 2 + ); + } + assert!(loaded + .clan_ai_events + .research_status_stubs() + .all(|(_, handler, _)| handler != 41)); + println!( + "stock research completions={:?}", + loaded.laboratories.report().completed + ); + } +} diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 1b80a8ac..9eb5f23d 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -59,8 +59,10 @@ mod clan_targeting; mod clan_transport_schemes; mod construction; mod construction_site; +mod laboratory; mod mesh_collision; mod mining; +pub use laboratory::LaboratoryReport; mod mission_events; mod ore_transport; mod player_motion; @@ -1370,6 +1372,7 @@ struct LoadedMissionState { behavior_control_groupings: Vec<MissionBehaviorControlGroupingState>, research_trf_tables: Vec<MissionResearchTrfTable>, free_research: research::FreeResearch, + laboratories: laboratory::Laboratories, ai_startup_states: Vec<MissionAiStartupState>, script_bundles: Vec<MissionScriptBundle>, script_varset: Option<MissionScriptVarSet>, @@ -2698,6 +2701,7 @@ fn load_mission_with_options( behavior_control_groupings, research_trf_tables, free_research, + laboratories: Default::default(), ai_startup_states: loaded_scripts.ai_startup_states, script_bundles: loaded_scripts.bundles, script_varset: loaded_scripts.varset, @@ -2921,7 +2925,8 @@ pub struct SimulationReport { pub clan_ai_event_stops: Vec<(MissionEventStop, u64)>, /// Calls to stubbed research policy or status, grouped by clan and handler. pub clan_research_status_stubs: Vec<(usize, u8, u64)>, - pub clan_research_catalogs: Vec<(usize, usize, u32)>, + pub clan_research_catalogs: Vec<(usize, usize, u32, u64)>, + pub laboratory: LaboratoryReport, /// Counts of pending script problems by clan and problem kind. pub clan_problem_dispatch_stubs: std::collections::BTreeMap<(usize, u32), u64>, /// Starts under the approximate scheduler, grouped by clan and problem kind. @@ -2994,6 +2999,7 @@ pub fn simulate_mission_report( clan_ai_event_stops: Vec::new(), clan_research_status_stubs: Vec::new(), clan_research_catalogs: Vec::new(), + laboratory: Default::default(), clan_problem_dispatch_stubs: Default::default(), clan_problem_starts: Vec::new(), script_factory_rejections: Vec::new(), @@ -3097,6 +3103,7 @@ pub fn simulate_mission_report( report .clan_research_catalogs .extend(loaded.clan_ai_events.research_catalogs()); + report.laboratory = loaded.laboratories.report(); for problem in loaded.clan_ai_events.pending_problems() { *report .clan_problem_dispatch_stubs diff --git a/crates/fparkan-runtime/src/research.rs b/crates/fparkan-runtime/src/research.rs index 97e37d2e..3510a295 100644 --- a/crates/fparkan-runtime/src/research.rs +++ b/crates/fparkan-runtime/src/research.rs @@ -31,6 +31,21 @@ struct Order { } impl FreeResearch { + pub(super) fn active(&self, lab: ObjectHandle) -> bool { + self.pending.as_ref().is_some_and(|order| order.lab == lab) + } + + pub(super) fn take_free(&mut self, slot: usize) -> bool { + let Some((_, count)) = self + .remaining + .iter_mut() + .find(|(index, count)| *index == slot && *count > 0) + else { + return false; + }; + *count -= 1; + true + } pub(super) fn new(drafts: &[MissionObjectDraft]) -> Self { let remaining = drafts .iter() @@ -172,52 +187,6 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] - fn licensed_new_lab_rejects_an_unwired_research_task_without_stopping_the_script() { - 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.02/data.tma".into(), - mode: MissionMode::SingleMission, - }, - MissionStartupInput { - queue_time_ms: 0, - research_creation_gate: false, - }, - None, - ) - .unwrap(); - for now in (0..=900_000).step_by(100) { - frame(&mut engine, now).unwrap(); - } - let loaded = engine.loaded.as_ref().unwrap(); - let lab = loaded - .object_drafts - .iter() - .skip(loaded.mission.objects.len()) - .filter(|draft| draft.unit_dat_header_flags == Some(LAB_CLASS)) - .find_map(|draft| handle_by_original_id(&engine.world, draft.original_id?)) - .unwrap(); - let id = loaded - .mission_events - .logic_id(&loaded.mission, &engine.world, lab) - .unwrap(); - assert!(loaded - .mission_events - .logic_objects(&loaded.mission, &engine.world, id) - .any(|handle| handle == lab)); - assert!(loaded - .clan_ai_events - .research_status_stubs() - .any(|(clan, handler, count)| clan == 1 && handler == 41 && count > 0)); - assert!(loaded.clan_ai_events.stops().next().is_none()); - assert!(loaded.free_research.pending.is_none()); - assert!(loaded.free_research.learned.is_empty()); - } - - #[test] - #[ignore = "requires licensed corpus"] fn licensed_teleport_lab_researches_the_available_turret() { let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap(); let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(std::path::PathBuf::from(root))); @@ -268,7 +237,7 @@ mod tests { } } -fn property(draft: &MissionObjectDraft, name: &[u8]) -> Option<u32> { +pub(super) fn property(draft: &MissionObjectDraft, name: &[u8]) -> Option<u32> { draft .properties .iter() |
