//! Prepares player factory schemes from compatible components. use crate::{ load_mission_with_options, normalize_engine_path, read_vfs, Engine, EngineError, LoadedMission, MissionDocument, MissionLoadOptions, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_assets::ResearchTrfDocument; use fparkan_path::NormalizedPath; use fparkan_prototype::{decode_unit_dat, unit_component_tree, UnitComponentRecord, UnitDat}; use fparkan_vfs::{MemoryVfs, OverlayVfs, Vfs}; use fparkan_world::OwnerId; use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; /// One replacement in an existing Unit DAT, indexed by mount record. #[derive(Clone, Debug, Eq, PartialEq)] pub struct FactoryPartChange { /// Preorder record index in the source project. pub component: usize, /// Original prototype name selected from the research table. pub resource: String, } /// Applies the selected equipment to the corresponding records for the project view. pub fn factory_design_parts( source: &[UnitComponentRecord], changes: &[FactoryPartChange], ) -> Result, EngineError> { let mut parts = source.to_vec(); for change in changes { let part = parts .get_mut(change.component) .filter(|part| change.component != 0 && replaceable(part)) .ok_or_else(|| invalid("equipment is not attached to this mount"))?; let old = std::str::from_utf8(key(&part.resource_raw)).map_err(invalid)?; validate_change(old, &change.resource)?; part.resource_raw = part_key(&change.resource); part.description_raw = part.resource_raw; } Ok(parts) } /// Writes replacements into a project being edited outside the factory catalogue. pub fn edit_factory_project( project: &UnitDat, changes: &[FactoryPartChange], ) -> Result, EngineError> { let records = factory_design_parts(&project.records, changes)?; Ok(crate::designer_chassis::encode_project(project, &records)) } /// Checks the edited project against the current clan's research before transfer. pub fn check_factory_design( engine: &Engine, cockpit: super::StartingCockpit, scheme: usize, changes: &[FactoryPartChange], ) -> Result<(), EngineError> { let mission = engine .loaded .as_ref() .ok_or_else(|| invalid("no mission"))?; let owner = super::production::player_owner(&engine.world, cockpit)?; let base = super::factory_project_components(engine, scheme) .ok_or_else(|| invalid("project has no Unit DAT"))?; let records = factory_design_parts(base, changes)?; super::production::clan_scheme_cost(&engine.services.vfs, mission, owner, &records)?; Ok(()) } /// Writes a modified prepared project in the original Unit DAT layout. pub fn factory_design_bytes( engine: &Engine, scheme: usize, changes: &[FactoryPartChange], ) -> Result, EngineError> { let index = super::factory_project_root(engine, scheme).ok_or_else(|| invalid("unknown project"))?; let mission = engine .loaded .as_ref() .ok_or_else(|| invalid("no mission"))?; let draft = &mission.object_drafts[index]; let base = super::factory_project_components(engine, scheme) .ok_or_else(|| invalid("project has no Unit DAT"))?; let records = factory_design_parts(base, changes)?; let vfs = engine .production .as_ref() .and_then(|state| state.scheme_vfs.as_ref()) .ok_or(EngineError::MissingVfs)?; write_project(vfs.as_ref(), &draft.resource_name_raw, base, &records) } /// Finds a prepared base whose mounts can represent the saved project. pub fn restore_factory_design( engine: &Engine, cockpit: super::StartingCockpit, schemes: impl IntoIterator, bytes: &[u8], ) -> Option<(usize, Vec)> { let project = decode_unit_dat(bytes).ok()?; let [0xf1, 0xf0, 0, 0, class @ ..] = project.header_opaque else { return None; }; let flags = Some(u32::from_le_bytes(class)); let mission = engine.loaded.as_ref()?; let owner = super::production::player_owner(&engine.world, cockpit).ok()?; unit_component_tree(&project.records).ok()?; super::production::clan_scheme_cost(&engine.services.vfs, mission, owner, &project.records) .ok()?; schemes.into_iter().find_map(|scheme| { let index = super::factory_project_root(engine, scheme)?; let base = super::factory_project_components(engine, scheme)?; if mission.object_drafts[index].unit_dat_header_flags != flags { return None; } restore_mounts(base, &project.records).map(|changes| (scheme, changes)) }) } pub(super) fn restore_mounts( base: &[UnitComponentRecord], project: &[UnitComponentRecord], ) -> Option> { if base.is_empty() || base.len() != project.len() { return None; } let mut changes = Vec::new(); for (component, (from, to)) in base.iter().zip(project).enumerate() { if from.kind != to.kind || from.parent_or_link != to.parent_or_link || from.immediate_child_count != to.immediate_child_count || from.tail0 != to.tail0 || !key(&from.archive_raw).eq_ignore_ascii_case(key(&to.archive_raw)) { return None; } if key(&from.resource_raw).eq_ignore_ascii_case(key(&to.resource_raw)) { continue; } if component == 0 || !replaceable(from) { return None; } let previous = std::str::from_utf8(key(&from.resource_raw)).ok()?; let resource = std::str::from_utf8(key(&to.resource_raw)).ok()?; validate_change(previous, resource).ok()?; changes.push(FactoryPartChange { component, resource: resource.to_owned(), }); } Some(changes) } fn write_project( vfs: &dyn Vfs, path: &[u8], base: &[UnitComponentRecord], records: &[UnitComponentRecord], ) -> Result, EngineError> { let path = normalize_engine_path( "factory Unit DAT", std::str::from_utf8(path).map_err(invalid)?, )?; let mut bytes = vfs.read(&path).map_err(invalid)?.to_vec(); let original = decode_unit_dat(&bytes).map_err(invalid)?; if original.records != base || base.len() != records.len() { return Err(invalid( "factory reserve does not match its source Unit DAT", )); } for (index, (from, to)) in base.iter().zip(records).enumerate() { if from != to { let name = std::str::from_utf8(key(&to.resource_raw)).map_err(invalid)?; replace_part(&mut bytes, index, name); } } Ok(bytes) } pub(super) fn part_variants( records: &[UnitComponentRecord], component: usize, research: &ResearchTrfDocument, learned: impl Fn(usize) -> bool, ) -> Vec { let Some(part) = records .get(component) .filter(|part| component != 0 && replaceable(part)) else { return Vec::new(); }; let Some(required) = std::str::from_utf8(key(&part.resource_raw)) .ok() .and_then(family) else { return Vec::new(); }; (0..research.row_count()) .filter(|&row| { let flags = research.flag_byte(row).unwrap_or_default(); flags & 4 != 0 && (flags & 2 != 0 || learned(row)) }) .filter_map(|row| std::str::from_utf8(research.row_name(row).ok()?).ok()) .filter(|name| family(name).is_some_and(|key| key.eq_ignore_ascii_case(required))) .map(str::to_owned) .collect() } pub(super) fn prepare_factory_parts( vfs: Arc, source: &super::MissionObjectDraft, records: Vec, mut table: super::MissionControlDeviceTableState, ) -> Result { use super::{ build_control_device_projection_with_class, build_prototype_graph_report, initial_node_provider_amount, initial_node_provider_maximum_amount, resolve_factory2_pair_from_assets, AssetManager, CachedResourceRepository, Factory2PairOutcome, MissionControlDeviceTableStatus, PROTOTYPE_TYPE_INTO, }; // The prepared world model can be reused only for internal parts. let bytes = write_project( vfs.as_ref(), &source.resource_name_raw, &source.unit_components, &records, )?; let path = normalize_engine_path("factory design", "fparkan/edited-design.dat")?; let mut overlay = MemoryVfs::default(); overlay.insert(path.clone(), bytes.into()); let vfs: Arc = Arc::new(OverlayVfs::from_layers(vec![Arc::new(overlay), vfs])); let manager = AssetManager::new(CachedResourceRepository::new(vfs.clone())); let (_, prototypes, report) = build_prototype_graph_report( manager.repository(), vfs.as_ref(), &[super::resource_name(path.as_str().as_bytes())], ); if !report.is_success() { return Err(EngineError::PrototypeGraph { failures: report.failures, }); } if prototypes.len() != records.len() || source .unit_components .iter() .zip(&records) .zip(&prototypes) .any(|((from, to), prototype)| { from != to && prototype.source_type != Some(PROTOTYPE_TYPE_INTO) }) { return Err(invalid("edited components must be internal equipment")); } let span = 0..prototypes.len(); let assets = manager .prepare_mission_assets(std::slice::from_ref(&span), &prototypes) .map_err(invalid)?; let mut draft = source.clone(); draft.unit_components = records; let mut asset_error = None; let projection = build_control_device_projection_with_class( 0, &draft, &assets, Some(&span), &prototypes, table.native_control_class, &mut |pair| match resolve_factory2_pair_from_assets(&manager, vfs.as_ref(), pair) { Ok(outcome) => outcome, Err(error) => { asset_error = Some(error); Factory2PairOutcome::Unrepresentable } }, ); if let Some(error) = asset_error { return Err(invalid(error)); } let projection = projection.map_err(|reason| invalid(format!("{reason:?}")))?; table.status = MissionControlDeviceTableStatus::Available(projection.devices); table.owner_profile = projection.owner_profile; table.projectile_resistance_bits = projection.projectile_resistance_bits; table.node_provider_maximum_amount_bits = initial_node_provider_maximum_amount(&projection.node_provider_status); table.node_provider_amount_bits = initial_node_provider_amount(&projection.node_provider_status); table.node_provider_status = projection.node_provider_status; table.node_provider_dirty = true; Ok(table) } /// Loads the gameplay world and prepares the player's optional Unit DAT design. /// /// # Errors /// /// Returns an error if the mission or selected design cannot be loaded. pub fn load_gameplay_mission( engine: &mut Engine, request: MissionRequest, startup_input: MissionStartupInput, build_scheme: Option<&str>, ) -> Result { load_gameplay_mission_with_build_parts(engine, request, startup_input, build_scheme, &[]) } /// Loads a mission with replacements for internal parts of the selected player scheme. /// /// # Errors /// /// Returns an error if the replacements have no compatible slot or the design /// or mission cannot be loaded. pub fn load_gameplay_mission_with_build_parts( engine: &mut Engine, request: MissionRequest, startup_input: MissionStartupInput, build_scheme: Option<&str>, changes: &[(String, String)], ) -> Result { if build_scheme.is_some() && request.mode != MissionMode::SingleMission { return Err(invalid("build schemes require a player mission")); } if build_scheme.is_none() && !changes.is_empty() { return Err(invalid("component replacements require a base scheme")); } let build_scheme = build_scheme .map(|path| normalize_engine_path("factory Unit DAT", path)) .transpose()?; load_mission_with_options( engine, request, MissionLoadOptions { allow_partial_init: true, start_autodemo: true, ..MissionLoadOptions::default() }, Some(startup_input), build_scheme.as_ref().map(|path| (path, changes)), ) } const HEADER_BYTES: usize = 8; const RECORD_BYTES: usize = 112; const RESOURCE_KEY: std::ops::Range = 32..64; const DESCRIPTION: std::ops::Range = 72..104; pub(super) const STARTER_SCHEME_PREFIX: &str = "fparkan/starter/"; const RECENT_PROJECT_LIMIT: usize = 5; /// Mission prebuilds enter the shared factory and designer history newest first. pub(super) fn recent_mission_projects(config: &[u8]) -> Result, EngineError> { let mut projects = VecDeque::with_capacity(RECENT_PROJECT_LIMIT); let mut in_prebuild = false; for line in config.split(|&byte| byte == b'\n') { let line = line.trim_ascii(); let mut words = line.split(u8::is_ascii_whitespace); match words.next() { Some(word) if word.eq_ignore_ascii_case(b"object") => { in_prebuild = words .find(|word| !word.is_empty()) .is_some_and(|name| name.eq_ignore_ascii_case(b"prebuild")); } Some(word) if word.eq_ignore_ascii_case(b"end") => in_prebuild = false, Some(word) if in_prebuild && !word.starts_with(b"#") && !word.starts_with(b"//") => { let mut fields = line.splitn(3, |&byte| byte == b'"'); let key = fields.next().unwrap_or_default(); let name = fields.next().filter(|name| !name.is_empty()); if let Some(name) = name.filter(|_| key.trim_ascii_end().ends_with(b"=") && fields.next().is_some()) { let name = std::str::from_utf8(name).map_err(invalid)?; let path = normalize_engine_path( "mission prebuild", &format!("UNITS/UNITS/PREBLD/{name}"), )?; if projects.len() == RECENT_PROJECT_LIMIT { projects.pop_back(); } projects.push_front(path); } } _ => {} } } Ok(projects.into()) } pub(super) fn prepare( vfs: Arc, source: &NormalizedPath, changes: &[(String, String)], ) -> Result<(Arc, NormalizedPath), EngineError> { let mut bytes = read_vfs(&vfs, source)?.to_vec(); let scheme = decode_unit_dat(&bytes).map_err(invalid)?; unit_component_tree(&scheme.records).map_err(invalid)?; for (index, (from, to)) in changes.iter().enumerate() { validate_change(from, to)?; if changes[..index] .iter() .any(|(other, _)| other.eq_ignore_ascii_case(from)) { return Err(invalid(format!( "component {from} has already been replaced" ))); } let mut matched = false; for (index, part) in scheme.records.iter().enumerate().skip(1) { if !key(&part.resource_raw).eq_ignore_ascii_case(from.as_bytes()) { continue; } if !replaceable(part) { return Err(invalid(format!( "component {from} is not a replaceable leaf" ))); } replace_part(&mut bytes, index, to); matched = true; } if !matched { return Err(invalid(format!( "scheme has no replaceable component {from}" ))); } } let path = normalize_engine_path("custom robot Unit DAT", "fparkan/custom.dat")?; let mut overlay = MemoryVfs::default(); overlay.insert(path.clone(), bytes.into()); Ok(( Arc::new(OverlayVfs::from_layers(vec![Arc::new(overlay), vfs])), path, )) } /// Offers one starting design per learned chassis from the local template library. pub(super) fn starting_designs( vfs: Arc, mission: &MissionDocument, ) -> (Arc, Vec) { let Some(owner) = mission_player(mission) else { return (vfs, Vec::new()); }; let Ok(research) = crate::research::load_technology_table(vfs.as_ref(), mission, owner) else { return (vfs, Vec::new()); }; let directory = normalize_engine_path("factory templates", "UNITS/UNITS/PREBLD") .expect("static template directory"); let Ok(entries) = vfs.list(&directory) else { return (vfs, Vec::new()); }; let mut by_chassis = BTreeMap::new(); for entry in entries { let Some((parent, name)) = entry.path.as_str().rsplit_once('/') else { continue; }; if !parent.eq_ignore_ascii_case(directory.as_str()) || !name.to_ascii_lowercase().ends_with(".dat") { continue; } let Some((chassis, changes, bytes)) = vfs .read(&entry.path) .ok() .and_then(|bytes| adapt_template(bytes.to_vec(), &research)) else { continue; }; let Ok(path) = normalize_engine_path( "factory starting design", &format!("{STARTER_SCHEME_PREFIX}{name}"), ) else { continue; }; if by_chassis .get(&chassis) .is_none_or(|(best_changes, best_path, _)| { (changes, &path) < (*best_changes, best_path) }) { by_chassis.insert(chassis, (changes, path, bytes)); } } if by_chassis.is_empty() { return (vfs, Vec::new()); } let mut overlay = MemoryVfs::default(); let mut paths = Vec::with_capacity(by_chassis.len()); for (_, path, bytes) in by_chassis.into_values() { overlay.insert(path.clone(), bytes.into()); paths.push(path); } ( Arc::new(OverlayVfs::from_layers(vec![Arc::new(overlay), vfs])), paths, ) } pub(super) fn mission_player(mission: &MissionDocument) -> Option { let mut players = mission .clans .iter() .enumerate() .filter(|(_, clan)| clan.mode == 1); let (index, _) = players.next().filter(|_| players.next().is_none())?; u16::try_from(index).ok().map(OwnerId) } fn adapt_template( mut bytes: Vec, research: &ResearchTrfDocument, ) -> Option<([u8; 32], usize, Vec)> { let UnitDat { header_opaque, records, } = decode_unit_dat(&bytes).ok()?; let class = u32::from_le_bytes(header_opaque[4..].try_into().ok()?); if class != crate::boarding::WARBOT_CLASS { return None; } let chassis = records.first()?.resource_raw; if !known_part(research, &chassis) { return None; } let mut changes = 0; for (index, part) in records.iter().enumerate().skip(1) { if !replaceable(part) || known_part(research, &part.resource_raw) { continue; } let Some(family) = std::str::from_utf8(key(&part.resource_raw)) .ok() .and_then(family) else { continue; }; let to = (0..research.row_count()) .filter(|&row| research.flag_byte(row).is_some_and(|flag| flag & 6 == 6)) .filter_map(|row| std::str::from_utf8(research.row_name(row).ok()?).ok()) .find(|name| { self::family(name).is_some_and(|other| other.eq_ignore_ascii_case(family)) }); if let Some(to) = to { replace_part(&mut bytes, index, to); changes += 1; } } let design = decode_unit_dat(&bytes).ok()?; crate::production::scheme_cost(&design.records, research, |_| false).ok()?; Some((chassis, changes, bytes)) } fn known_part(research: &ResearchTrfDocument, key: &[u8]) -> bool { research .find_key(key) .ok() .flatten() .and_then(|row| research.flag_byte(row)) .is_some_and(|flag| flag & 6 == 6) } fn replaceable(part: &UnitComponentRecord) -> bool { part.kind == 1 && part.immediate_child_count == 0 && key(&part.archive_raw).eq_ignore_ascii_case(b"objects.rlb") } fn replace_part(bytes: &mut [u8], index: usize, to: &str) { let offset = HEADER_BYTES + index * RECORD_BYTES; let record = &mut bytes[offset..offset + RECORD_BYTES]; let replacement = part_key(to); record[RESOURCE_KEY].copy_from_slice(&replacement); record[DESCRIPTION].copy_from_slice(&replacement); } fn part_key(name: &str) -> [u8; 32] { let mut raw = [0; 32]; raw[..name.len()].copy_from_slice(name.as_bytes()); raw } fn key(raw: &[u8; 32]) -> &[u8] { raw.split(|&byte| byte == 0).next().unwrap_or_default() } fn family(resource: &str) -> Option<&str> { let (family, variant) = resource.rsplit_once('_')?; (family.len() > 2 && resource.len() < 32 && variant.len() == 2 && family .get(..2) .is_some_and(|prefix| prefix.eq_ignore_ascii_case("i_")) && resource .bytes() .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')) .then_some(family) } fn validate_change(from: &str, to: &str) -> Result<(), EngineError> { if family(from) .zip(family(to)) .is_none_or(|(a, b)| !a.eq_ignore_ascii_case(b)) { return Err(invalid(format!( "components {from} and {to} must belong to the same internal family" ))); } if from.eq_ignore_ascii_case(to) { return Err(invalid(format!( "replacement for {from} must select another component" ))); } Ok(()) } fn invalid(error: impl std::fmt::Display) -> EngineError { EngineError::Production(error.to_string()) } #[cfg(test)] mod tests { #[test] #[ignore = "requires licensed corpus"] fn licensed_constructor_edits_only_the_selected_guns_equipment() { use super::{ check_factory_design, factory_design_bytes, factory_design_parts, key, restore_factory_design, FactoryPartChange, }; use crate::{ capture_neutral_building, create, factory_part_variants, factory_project_components, frame, loaded_mission_control_device_tables, loaded_mission_object_drafts, order_factory_design, starting_cockpit, EngineServices, MissionControlDeviceTableStatus, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_vfs::DirectoryVfs; use fparkan_world::{set_transform, transform_state, OriginalObjectId}; use std::sync::Arc; let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed root"); let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap(); super::load_gameplay_mission_with_build_parts( &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, }, Some("UNITS/UNITS/PREBLD/tut2_f1.dat"), &[ ("i_pws_b_02".into(), "i_pws_b_01".into()), ("i_rdr_b_02".into(), "i_rdr_b_01".into()), ], ) .unwrap(); frame(&mut engine, 0).unwrap(); let cockpit = starting_cockpit(&engine).unwrap(); // The communicator is a fixture for this production test. let mut pose = transform_state(&engine.world, cockpit.handle).unwrap(); pose.position = [391.3_f32, 740.1, 140.74].map(f32::to_bits); set_transform(&mut engine.world, cockpit.handle, pose).unwrap(); assert_eq!( capture_neutral_building(&mut engine, cockpit).unwrap(), Some(OriginalObjectId(0)) ); let scheme = 0; let base = factory_project_components(&engine, scheme) .unwrap() .to_vec(); let mounts = base .iter() .enumerate() .filter_map(|(index, part)| (key(&part.resource_raw) == b"i_c06_b_df").then_some(index)) .collect::>(); assert_eq!(mounts.len(), 2); let variants = factory_part_variants(&engine, cockpit, &base, mounts[0]).unwrap(); assert_eq!(variants, ["i_c06_b_01", "i_c06_b_02", "i_c06_b_df"]); let armor = base .iter() .position(|part| key(&part.resource_raw) == b"i_arm_b_df") .unwrap(); let unavailable = [FactoryPartChange { component: armor, resource: "i_arm_b_03".into(), }]; assert!(check_factory_design(&engine, cockpit, scheme, &unavailable) .unwrap_err() .to_string() .contains("i_arm_b_03")); assert!( order_factory_design(&mut engine, cockpit, None, scheme, &unavailable, 1,).is_err() ); let changes = [FactoryPartChange { component: mounts[0], resource: "i_c06_b_01".into(), }]; check_factory_design(&engine, cockpit, scheme, &changes).unwrap(); let bytes = factory_design_bytes(&engine, scheme, &changes).unwrap(); let decoded = super::decode_unit_dat(&bytes).unwrap(); assert_eq!(&decoded.header_opaque[..4], &[0xf1, 0xf0, 0, 0]); assert_eq!( decoded.records, factory_design_parts(&base, &changes).unwrap() ); let (restored_scheme, restored_changes) = restore_factory_design(&engine, cockpit, [scheme], &bytes).unwrap(); assert_eq!(restored_changes, changes); let mut damaged = bytes; // Alter the first mount index in the root record. damaged[8 + 68] ^= 1; assert!(restore_factory_design(&engine, cockpit, [scheme], &damaged).is_none()); assert_eq!( order_factory_design( &mut engine, cockpit, None, restored_scheme, &restored_changes, 2 ) .unwrap(), 60_000 ); let robot = (60_002..80_000) .step_by(100) .find_map(|now| frame(&mut engine, now).unwrap().produced_unit) .expect("the factory released the edited project"); let draft = &loaded_mission_object_drafts(&engine).unwrap()[robot.object_index]; assert_eq!( draft.unit_components, factory_design_parts(&base, &changes).unwrap() ); assert_eq!(draft.unit_components[mounts[1]], base[mounts[1]]); assert_eq!(factory_project_components(&engine, scheme).unwrap(), base); let table = loaded_mission_control_device_tables(&engine) .unwrap() .iter() .find(|table| table.handle == robot.handle) .unwrap(); assert!(matches!( table.status, MissionControlDeviceTableStatus::Available(_) )); } use super::{recent_mission_projects, validate_change, NormalizedPath}; #[test] fn prebuilds_fill_five_recent_slots_newest_first() { let config = b"object other\nmodel1 = \"ignored.dat\"\nend\r\n\ OBJECT PreBuild\r\n# model0 = \"comment.dat\"\r\n\ model6=\"evicted.dat\"\r\nmodel2=\"old.dat\"\r\nmodel1 = \"first.dat\"\r\n\ model3 = \"second.dat\"\r\nmodel5 = \"FIRST.DAT\"\r\nmodel4 = \"new.dat\"\r\nend"; let projects = recent_mission_projects(config).unwrap(); assert_eq!( projects .iter() .map(NormalizedPath::as_str) .collect::>(), [ "UNITS/UNITS/PREBLD/new.dat", "UNITS/UNITS/PREBLD/FIRST.DAT", "UNITS/UNITS/PREBLD/second.dat", "UNITS/UNITS/PREBLD/first.dat", "UNITS/UNITS/PREBLD/old.dat", ] ); assert!(recent_mission_projects( b"object prebuild\nend\nobject other\nmodel1 = \"ignored.dat\"\nend" ) .unwrap() .is_empty()); } #[test] fn design_changes_keep_the_component_family_and_chassis_size() { assert!(validate_change("i_pws_b_02", "I_PWS_B_01").is_ok()); for (from, to) in [ ("i_pws_b_02", "i_pws_l_02"), ("i_pws_b_02", "i_eng_b_02"), ("i_pws_b_02", "i_pws_b_02"), ("i_pws_b_02", "../i_pws_b_02"), ("e_tur_bb_01", "e_tur_bb_02"), ] { assert!(validate_change(from, to).is_err()); } } #[test] #[ignore = "requires licensed corpus"] fn licensed_constructor_prepares_a_buildable_design_on_stock_load() { use crate::{create, EngineServices, MissionMode, MissionRequest, MissionStartupInput}; use fparkan_vfs::DirectoryVfs; use std::{path::PathBuf, sync::Arc}; let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed root"); let vfs = Arc::new(DirectoryVfs::new(PathBuf::from(root))); let mut engine = create(EngineServices::new(vfs)).unwrap(); super::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 drafts = crate::loaded_mission_object_drafts(&engine).unwrap(); let design = drafts .iter() .find(|draft| draft.resource_name_raw == b"fparkan/starter/tut2_f1.dat") .expect("starting design is available without a command-line override"); let keys: Vec<_> = design .unit_components .iter() .map(|part| super::key(&part.resource_raw)) .collect(); assert_eq!(keys.first().copied(), Some(&b"R_B_02"[..])); for (known, unavailable) in [ (&b"i_pws_b_01"[..], &b"i_pws_b_02"[..]), (&b"i_rdr_b_01"[..], &b"i_rdr_b_02"[..]), ] { assert!(keys.contains(&known)); assert!(!keys.contains(&unavailable)); } } #[test] #[ignore = "requires licensed corpus"] fn licensed_constructor_spawns_a_modified_scheme_with_known_parts() { use crate::{ capture_neutral_building, create, factory_schemes, frame, loaded_mission_object_drafts, order_factory_robot, starting_cockpit, EngineServices, }; use fparkan_vfs::DirectoryVfs; use fparkan_world::{set_transform, transform_state, OriginalObjectId}; use std::sync::Arc; let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed root"); let vfs = Arc::new(DirectoryVfs::new(std::path::PathBuf::from(root))); for unknown_armor in [true, false] { let mut engine = create(EngineServices::new(vfs.clone())).unwrap(); let mut parts = vec![ ("i_pws_b_02".into(), "i_pws_b_01".into()), ("i_rdr_b_02".into(), "i_rdr_b_01".into()), ]; if unknown_armor { parts.push(("i_arm_b_df".into(), "i_arm_b_03".into())); } super::load_gameplay_mission_with_build_parts( &mut engine, crate::MissionRequest { key: "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.02/data.tma".into(), mode: crate::MissionMode::SingleMission, }, crate::MissionStartupInput { queue_time_ms: 0, research_creation_gate: false, }, Some("UNITS/UNITS/PREBLD/tut2_f1.dat"), &parts, ) .unwrap(); frame(&mut engine, 0).unwrap(); let hero = starting_cockpit(&engine).unwrap(); let mut pose = transform_state(&engine.world, hero.handle).unwrap(); pose.position = [391.3_f32, 740.1, 140.74].map(f32::to_bits); set_transform(&mut engine.world, hero.handle, pose).unwrap(); assert_eq!( capture_neutral_building(&mut engine, hero).unwrap(), Some(OriginalObjectId(0)) ); assert_eq!( factory_schemes(&engine, hero).unwrap(), [(0, "fparkan/custom.dat")] ); let order = order_factory_robot(&mut engine, hero, 1); if unknown_armor { assert!(order.unwrap_err().to_string().contains("i_arm_b_03")); continue; } assert_eq!(order.unwrap(), 60_000); let robot = (60_001..80_000) .step_by(100) .find_map(|now| frame(&mut engine, now).unwrap().produced_unit) .expect("factory released the custom scheme"); let draft = &loaded_mission_object_drafts(&engine).unwrap()[robot.object_index]; for (previous, new) in &parts { assert!(draft .unit_components .iter() .any(|part| super::key(&part.resource_raw) == new.as_bytes())); assert!(!draft .unit_components .iter() .any(|part| super::key(&part.resource_raw) == previous.as_bytes())); } } } }