diff options
| author | Valentin Popov <valentin@popov.link> | 2026-12-02 05:25:19 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-12-02 05:25:19 +0300 |
| commit | 6fde1faa1dfed89007566b3373114a89139390b9 (patch) | |
| tree | 05fff10a3442ba6304086defcb109c61a5a3410c /crates/fparkan-runtime/src/robot_designer.rs | |
| parent | 0ad190894afd8e9592ef182e36e16ee7a61483f6 (diff) | |
| download | fparkan-6fde1faa1dfed89007566b3373114a89139390b9.tar.xz fparkan-6fde1faa1dfed89007566b3373114a89139390b9.zip | |
feat(ui): edit installed warbot equipment
Choose researched internal equipment per mount and build the resulting Unit DAT with the projected Control devices. Verified pointer selection and order in Field Camp with Vulkan validation, and produced the edited two-gun design at the Constructor factory.
Diffstat (limited to 'crates/fparkan-runtime/src/robot_designer.rs')
| -rw-r--r-- | crates/fparkan-runtime/src/robot_designer.rs | 264 |
1 files changed, 262 insertions, 2 deletions
diff --git a/crates/fparkan-runtime/src/robot_designer.rs b/crates/fparkan-runtime/src/robot_designer.rs index 629efa3d..7bca5e18 100644 --- a/crates/fparkan-runtime/src/robot_designer.rs +++ b/crates/fparkan-runtime/src/robot_designer.rs @@ -12,6 +12,160 @@ 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<Vec<UnitComponentRecord>, 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) +} + +pub(super) fn part_variants( + records: &[UnitComponentRecord], + component: usize, + research: &ResearchTrfDocument, + learned: impl Fn(usize) -> bool, +) -> Vec<String> { + 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<dyn Vfs>, + source: &super::MissionObjectDraft, + records: Vec<UnitComponentRecord>, + mut table: super::MissionControlDeviceTableState, +) -> Result<super::MissionControlDeviceTableState, EngineError> { + 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 dat = vfs + .read(&normalize_engine_path( + "factory Unit DAT", + std::str::from_utf8(&source.resource_name_raw).map_err(invalid)?, + )?) + .map_err(invalid)?; + let mut bytes = dat.to_vec(); + let original = decode_unit_dat(&bytes).map_err(invalid)?; + if original.records != source.unit_components || original.records.len() != records.len() { + return Err(invalid( + "factory reserve does not match its source Unit DAT", + )); + } + for (index, (from, to)) in original.records.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); + } + } + 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<dyn Vfs> = 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() + || original + .records + .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 @@ -285,12 +439,17 @@ fn replaceable(part: &UnitComponentRecord) -> bool { 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 mut replacement = [0; 32]; - replacement[..to.len()].copy_from_slice(to.as_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() } @@ -332,6 +491,107 @@ fn invalid(error: impl std::fmt::Display) -> EngineError { #[cfg(test)] mod tests { + #[test] + #[ignore = "requires licensed corpus"] + fn licensed_constructor_edits_only_the_selected_guns_equipment() { + use super::{factory_design_parts, key, 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::<Vec<_>>(); + assert_eq!(mounts.len(), 2); + let variants = factory_part_variants(&engine, cockpit, scheme, 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(); + assert!(order_factory_design( + &mut engine, + cockpit, + None, + scheme, + &[FactoryPartChange { + component: armor, + resource: "i_arm_b_03".into() + }], + 1, + ) + .is_err()); + let changes = [FactoryPartChange { + component: mounts[0], + resource: "i_c06_b_01".into(), + }]; + assert_eq!( + order_factory_design(&mut engine, cockpit, None, scheme, &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] |
