diff options
| -rw-r--r-- | crates/fparkan-assets/src/lib.rs | 332 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 157 | ||||
| -rw-r--r-- | crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs | 224 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 90 | ||||
| -rw-r--r-- | docs/reference/tma.md | 12 | ||||
| -rw-r--r-- | docs/tomes/03-resources.md | 29 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 203 |
7 files changed, 1020 insertions, 27 deletions
diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs index d34effb..da3411e 100644 --- a/crates/fparkan-assets/src/lib.rs +++ b/crates/fparkan-assets/src/lib.rs @@ -1180,6 +1180,19 @@ impl Default for ControlTag21InstanceState { /// Input or metadata prevented a safe native control sample. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ControlSamplingError { + /// This resource-device helper only implements typed-record tag 26. + UnsupportedResourceDeviceTag { actual: u32 }, + /// The record's raw provider key has no resolved NDP table. + MissingResourceDeviceNodeData { key: u32 }, + /// The record's raw provider key is not a row in its NDP table. + ResourceDeviceNodeDataKeyOutOfRange { key: u32, row_count: usize }, + /// The caller did not supply the provider's current type-1 value. + MissingResourceDeviceProviderValue { key: u32 }, + /// A coefficient is outside the helper's finite normal-or-zero contract. + InvalidResourceDeviceOperand { operand: &'static str }, + /// The native x87 intermediate is outside the range represented by normal + /// f32 values, so the Rust result could differ from the original. + UnsupportedResourceDeviceFloatRange { stage: &'static str }, /// A state object was reused with a different model node count. StateNodeCountMismatch { expected: usize, actual: usize }, /// A state object was reused with a different number of tag-21 records. @@ -1216,6 +1229,74 @@ pub enum ControlSamplingError { NonFiniteSample { record_index: usize }, } +/// Samples Control's tag-26 typed-record query `0x300` for one current state. +/// +/// The key in fixed word 1 must select an existing NDP row. The caller supplies +/// that provider's current type-1 value and the object's current multiplier; +/// this function does not invent their runtime state. Fixed word 11 is the +/// coefficient loaded by selector `0x300`. Native code multiplies in the order +/// `provider_now * coefficient * multiplier_now`. +/// +/// The source x87 code returns a value with an extended exponent range even +/// though it uses 24-bit precision. This f32 helper therefore accepts only +/// finite normal-or-zero operands and normal-or-exact-zero intermediate and +/// final products. It rejects subnormal or out-of-f32-range products rather +/// than silently underflowing or overflowing differently from x87. +pub fn sample_control_resource_device_selector_300( + record: &PreparedControlTypedRecord, + node_data: Option<&PreparedControlNodeDataTable>, + provider_now: Option<f32>, + multiplier_now: f32, +) -> Result<f32, ControlSamplingError> { + if record.tag != 26 { + return Err(ControlSamplingError::UnsupportedResourceDeviceTag { actual: record.tag }); + } + + let key = record.fixed_words[1]; + let Some(node_data) = node_data else { + return Err(ControlSamplingError::MissingResourceDeviceNodeData { key }); + }; + if !usize::try_from(key).is_ok_and(|key| key < node_data.rows.len()) { + return Err(ControlSamplingError::ResourceDeviceNodeDataKeyOutOfRange { + key, + row_count: node_data.rows.len(), + }); + } + let provider_now = + provider_now.ok_or(ControlSamplingError::MissingResourceDeviceProviderValue { key })?; + let base = f32::from_bits(record.fixed_words[11]); + + for (operand, value) in [ + ("provider", provider_now), + ("base coefficient", base), + ("multiplier", multiplier_now), + ] { + if !value.is_finite() || (value != 0.0 && !value.is_normal()) { + return Err(ControlSamplingError::InvalidResourceDeviceOperand { operand }); + } + } + + let provider_times_base = + native_range_compatible_product(provider_now, base, "provider times base")?; + native_range_compatible_product(provider_times_base, multiplier_now, "then multiplier") +} + +fn native_range_compatible_product( + lhs: f32, + rhs: f32, + stage: &'static str, +) -> Result<f32, ControlSamplingError> { + let exact = f64::from(lhs) * f64::from(rhs); + let absolute = exact.abs(); + let minimum_normal = f64::from(f32::MIN_POSITIVE); + let maximum = f64::from(f32::MAX); + if exact != 0.0 && (absolute < minimum_normal || absolute > maximum) { + return Err(ControlSamplingError::UnsupportedResourceDeviceFloatRange { stage }); + } + + Ok(lhs * rhs) +} + /// Samples per-node animation times using the decoded Control timeline. /// /// `native_clock_ms` is the absolute u32 millisecond clock passed to native @@ -4141,6 +4222,203 @@ mod tests { // Preserve the authored CTLD fixture bits; this is not the `f32` value of tau. const AUTHORED_TAG21_RAW_PARAMETER_3: f32 = f32::from_bits(0x40C8_F5C3); + fn resource_device_record(tag: u32, key: u32, base_bits: u32) -> PreparedControlTypedRecord { + let mut fixed_words = [0; 44]; + fixed_words[1] = key; + fixed_words[11] = base_bits; + PreparedControlTypedRecord { + tag, + fixed_words, + values: Vec::new(), + string_bytes: Vec::new(), + gate_provider: PreparedControlGateProvider::NotApplicable, + } + } + + fn resource_device_node_data_table(row_count: usize) -> PreparedControlNodeDataTable { + PreparedControlNodeDataTable { + source: ResourceKey { + archive: parse_path("parts.rlb").expect("NDP archive"), + name: resource_name(b"resource-device.ndp"), + type_id: None, + }, + rows: vec![ + PreparedControlNodeDataRow { + raw_flags: 0, + max_volume: 0.0, + mobility_per_volume: 0.0, + effect: PreparedControlResourcePair { + archive: [0; 32], + name: [0; 32], + }, + }; + row_count + ], + } + } + + #[test] + fn tag26_selector_300_multiplies_provider_then_fixed_base_then_multiplier() { + let record = resource_device_record(26, 1, 0x3D25_AE4A); + let node_data = resource_device_node_data_table(2); + let provider_now = f32::from_bits(0x3FE6_982F); + let multiplier_now = f32::from_bits(0x4071_5539); + + let sampled = sample_control_resource_device_selector_300( + &record, + Some(&node_data), + Some(provider_now), + multiplier_now, + ) + .expect("valid tag-26 resource-device sample"); + + assert_eq!(sampled.to_bits(), 0x3E8C_B02E); + assert_ne!( + sampled.to_bits(), + ((provider_now * multiplier_now) * f32::from_bits(record.fixed_words[11])).to_bits(), + "the original selector multiplies the provider by the record base first" + ); + } + + #[test] + fn tag26_selector_300_requires_its_ndp_row_and_explicit_provider() { + let record = resource_device_record(26, 1, 2.0_f32.to_bits()); + let one_row = resource_device_node_data_table(1); + assert_eq!( + sample_control_resource_device_selector_300(&record, Some(&one_row), Some(3.0), 4.0,), + Err(ControlSamplingError::ResourceDeviceNodeDataKeyOutOfRange { + key: 1, + row_count: 1, + }) + ); + + let two_rows = resource_device_node_data_table(2); + assert_eq!( + sample_control_resource_device_selector_300(&record, Some(&two_rows), None, 4.0), + Err(ControlSamplingError::MissingResourceDeviceProviderValue { key: 1 }) + ); + assert_eq!( + sample_control_resource_device_selector_300(&record, None, Some(3.0), 4.0), + Err(ControlSamplingError::MissingResourceDeviceNodeData { key: 1 }) + ); + } + + #[test] + fn tag26_selector_300_rejects_other_tags_and_extended_x87_ranges() { + let node_data = resource_device_node_data_table(1); + let tag21 = resource_device_record(21, 0, 1.0_f32.to_bits()); + assert_eq!( + sample_control_resource_device_selector_300(&tag21, Some(&node_data), Some(1.0), 1.0), + Err(ControlSamplingError::UnsupportedResourceDeviceTag { actual: 21 }) + ); + + let tag26 = resource_device_record(26, 0, f32::MIN_POSITIVE.to_bits()); + assert_eq!( + sample_control_resource_device_selector_300( + &tag26, + Some(&node_data), + Some(f32::MIN_POSITIVE), + 1.0, + ), + Err(ControlSamplingError::UnsupportedResourceDeviceFloatRange { + stage: "provider times base", + }) + ); + } + + #[test] + fn tag26_selector_300_preserves_negative_and_signed_zero_values() { + let node_data = resource_device_node_data_table(1); + let record = resource_device_record(26, 0, 0.5_f32.to_bits()); + let negative = + sample_control_resource_device_selector_300(&record, Some(&node_data), Some(-2.0), 4.0) + .expect("negative factors are not clamped"); + assert_eq!(negative, -4.0); + + let negative_zero = sample_control_resource_device_selector_300( + &resource_device_record(26, 0, 2.0_f32.to_bits()), + Some(&node_data), + Some(-0.0), + 3.0, + ) + .expect("signed zero is an exact native input"); + assert_eq!(negative_zero.to_bits(), (-0.0_f32).to_bits()); + + let positive_zero = sample_control_resource_device_selector_300( + &resource_device_record(26, 0, 2.0_f32.to_bits()), + Some(&node_data), + Some(0.0), + 3.0, + ) + .expect("positive zero is an exact native input"); + assert_eq!(positive_zero.to_bits(), 0.0_f32.to_bits()); + } + + #[test] + fn tag26_selector_300_rejects_nonfinite_and_subnormal_operands() { + let node_data = resource_device_node_data_table(1); + for (operand, provider_now, multiplier_now, base_bits) in [ + ("provider", f32::NAN, 1.0, 1.0_f32.to_bits()), + ("multiplier", 1.0, f32::INFINITY, 1.0_f32.to_bits()), + ("base coefficient", 1.0, 1.0, 1), + ] { + let record = resource_device_record(26, 0, base_bits); + assert_eq!( + sample_control_resource_device_selector_300( + &record, + Some(&node_data), + Some(provider_now), + multiplier_now, + ), + Err(ControlSamplingError::InvalidResourceDeviceOperand { operand }) + ); + } + } + + #[test] + fn tag26_selector_300_rejects_extended_intermediate_and_final_ranges() { + let node_data = resource_device_node_data_table(1); + let provider = f32::MAX; + let overflowing_intermediate = resource_device_record(26, 0, 2.0_f32.to_bits()); + assert_eq!( + sample_control_resource_device_selector_300( + &overflowing_intermediate, + Some(&node_data), + Some(provider), + 0.25, + ), + Err(ControlSamplingError::UnsupportedResourceDeviceFloatRange { + stage: "provider times base", + }) + ); + + let underflowing_intermediate = resource_device_record(26, 0, f32::MIN_POSITIVE.to_bits()); + assert_eq!( + sample_control_resource_device_selector_300( + &underflowing_intermediate, + Some(&node_data), + Some(f32::MIN_POSITIVE), + f32::MAX, + ), + Err(ControlSamplingError::UnsupportedResourceDeviceFloatRange { + stage: "provider times base", + }) + ); + + let subnormal_final = resource_device_record(26, 0, 1.0_f32.to_bits()); + assert_eq!( + sample_control_resource_device_selector_300( + &subnormal_final, + Some(&node_data), + Some(f32::MIN_POSITIVE), + 0.5, + ), + Err(ControlSamplingError::UnsupportedResourceDeviceFloatRange { + stage: "then multiplier", + }) + ); + } + fn tag21_fullcycle_control() -> PreparedComponentControl { let source = ResourceKey { archive: parse_path("parts.rlb").expect("archive"), @@ -6166,6 +6444,60 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] + fn tag26_selector_300_uses_a_real_control_record_and_ndp_key() { + let root = fixture_root("IS"); + let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(&root)); + let repository = CachedResourceRepository::new(Arc::clone(&vfs)); + let roots = [resource_name(b"UNITS/BUILDS/MINE/min_l_n1.dat")]; + let (_graph, prototypes) = + build_prototype_graph(&repository, vfs.as_ref(), &roots).expect("prototype graph"); + let assets = prepare_mission_assets_with_repository( + &repository, + &[0..prototypes.len()], + &prototypes, + ) + .expect("prepared licensed unit controls"); + + let mut sampled_records = 0; + for control in assets.object_component_controls.iter().flatten().flatten() { + for record in control + .typed_records + .iter() + .filter(|record| record.tag == 26) + { + let node_data = control + .node_data + .as_ref() + .expect("tag-26 control has its explicit NDP table"); + assert_eq!(control.source.name.0, b"fr_l_mine.ctl"); + assert_eq!(node_data.source.name.0, b"fr_l_mine.ndp"); + assert_eq!(node_data.rows.len(), 22); + assert_eq!(record.fixed_words[1], 2); + assert_eq!(record.fixed_words[11], 0x3F80_0000); + let sample = sample_control_resource_device_selector_300( + record, + Some(node_data), + Some(1.0), + 1.0, + ) + .expect("real tag-26 key selects an NDP row"); + assert_eq!(sample.to_bits(), record.fixed_words[11]); + println!( + "control={}: ndp={}: key={} rows={} coefficient=0x{:08x}", + String::from_utf8_lossy(&control.source.name.0), + String::from_utf8_lossy(&node_data.source.name.0), + record.fixed_words[1], + node_data.rows.len(), + record.fixed_words[11], + ); + sampled_records += 1; + } + } + assert_eq!(sampled_records, 1); + } + + #[test] + #[ignore = "requires licensed corpus"] fn repository_plan_deduplicates_duplicate_visuals_but_graph_preserves_requests() { let root = fixture_root("IS"); let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(&root)); diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 3964f78..baba3b3 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -134,6 +134,21 @@ pub struct BehaviorRegisteredObject { pub native_tail: [u32; 5], } +/// Native `CurrentOre`/`MaximumOre` state for one full Unit DAT mission object. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct BehaviorOreState { + /// Stable identity from the source TMA object order. + pub original_id: OriginalObjectId, + /// Corresponding live Rust world object. + pub handle: ObjectHandle, + /// Class word recovered from the root Unit DAT header. + pub class_flags: u32, + /// Raw bits of the `CurrentOre` float property. + pub current_ore_bits: u32, + /// Raw bits of the read-only `MaximumOre` float property. + pub maximum_ore_bits: u32, +} + /// Resource distributor state associated with one TMA clan's constructed AI. #[derive(Clone, Debug, PartialEq)] pub struct BehaviorDistributorState { @@ -464,6 +479,7 @@ struct LoadedMissionState { asset_plan: MissionAssetPlan, object_drafts: Vec<MissionObjectDraft>, behavior_distributors: Vec<BehaviorDistributorState>, + behavior_ore_states: Vec<BehaviorOreState>, script_bundles: Vec<MissionScriptBundle>, script_varset: Option<MissionScriptVarSet>, script_init_states: Vec<MissionScriptInitState>, @@ -1045,6 +1061,24 @@ fn load_mission_with_options( Vec::new() }; + let behavior_ore_states = if options.asset_scope == MissionAssetScope::Full { + // Property callbacks also run for Unit DAT objects that do not join a distributor. + object_drafts + .iter() + .zip(&handles) + .filter_map(|(draft, handle)| { + Some(initialize_behavior_ore_state( + draft.original_id?, + *handle, + draft.unit_dat_header_flags?, + &draft.properties, + )) + }) + .collect() + } else { + Vec::new() + }; + let mut next_behavior_rng_state = engine.behavior_rng_state; if options.asset_scope == MissionAssetScope::Full { let queue_time_ms = queue_time_ms.expect("full mission loading requires a queue time"); @@ -1120,6 +1154,7 @@ fn load_mission_with_options( asset_plan: mission_asset_plan, object_drafts, behavior_distributors, + behavior_ore_states, script_bundles: loaded_scripts.bundles, script_varset: loaded_scripts.varset, script_init_states: loaded_scripts.init_states, @@ -1402,6 +1437,15 @@ pub fn loaded_mission_behavior_distributors( .map(|state| state.behavior_distributors.as_slice()) } +/// Returns native ore properties attached to full Unit DAT mission objects. +#[must_use] +pub fn loaded_mission_behavior_ore_states(engine: &Engine) -> Option<&[BehaviorOreState]> { + engine + .loaded + .as_ref() + .map(|state| state.behavior_ore_states.as_slice()) +} + fn behavior_clan_for_selector( selector: u32, clan_count: usize, @@ -1418,6 +1462,38 @@ fn has_behavior_registration_key(class_flags: u32) -> bool { class_flags & BEHAVIOR_REGISTRATION_KEY_FLAG != 0 } +fn native_behavior_ore_defaults(class_flags: u32) -> (u32, u32) { + match class_flags { + 0x8000_0004 => (0, 0x43fa_0000), + 0x8000_0008 => (0, 0x457a_0000), + 0x0100_2000 => (0, 0x44fa_0000), + 0x0100_4000 => (0x44fa_0000, 0x44fa_0000), + _ => (0, 0), + } +} + +fn initialize_behavior_ore_state( + original_id: OriginalObjectId, + handle: ObjectHandle, + class_flags: u32, + properties: &[MissionObjectProperty], +) -> BehaviorOreState { + let (mut current_ore_bits, maximum_ore_bits) = native_behavior_ore_defaults(class_flags); + if let Some(property) = properties + .iter() + .find(|property| property.name_raw.as_slice() == b"CurrentOre") + { + current_ore_bits = property.raw_value[1]; + } + BehaviorOreState { + original_id, + handle, + class_flags, + current_ore_bits, + maximum_ore_bits, + } +} + fn add_behavior_registered_object( distributor: &mut BehaviorDistributorState, mut object: BehaviorRegisteredObject, @@ -2470,6 +2546,26 @@ mod tests { .collect::<Vec<_>>(), vec![(0, true), (1, true)] ); + let ore_states = loaded_mission_behavior_ore_states(&engine).expect("Behavior ore state"); + let unit_dat_drafts = drafts + .iter() + .filter(|draft| draft.unit_dat_header_flags.is_some()) + .collect::<Vec<_>>(); + assert_eq!(ore_states.len(), unit_dat_drafts.len()); + assert_eq!(ore_states.len(), 8); + for state in ore_states { + let draft = unit_dat_drafts + .iter() + .find(|draft| draft.original_id == Some(state.original_id)) + .expect("ore state has a Unit DAT source"); + assert_eq!( + state.handle, + handle_by_original_id(&engine.world, state.original_id).unwrap() + ); + assert_eq!(state.class_flags, draft.unit_dat_header_flags.unwrap()); + assert_eq!(state.current_ore_bits, 0); + assert_eq!(state.maximum_ore_bits, 0); + } let registered = distributors .iter() .flat_map(|distributor| { @@ -2538,6 +2634,15 @@ mod tests { ] ); assert_eq!(registered.len(), 4); + assert!(ore_states.iter().any(|state| { + state.class_flags == 0x0100_8000 + && !distributors.iter().any(|distributor| { + distributor + .registered_objects + .iter() + .any(|object| object.handle == state.handle) + }) + })); for (_, object) in registered { assert_eq!( handle_by_original_id(&engine.world, object.original_id), @@ -2620,6 +2725,55 @@ mod tests { } #[test] + fn behavior_ore_initialization_uses_first_exact_current_value_and_read_only_maximum() { + let handle = ObjectHandle { + generation: 7, + slot: 19, + }; + let state = initialize_behavior_ore_state( + OriginalObjectId(19), + handle, + 0x0100_2000, + &[ + MissionObjectProperty { + name_raw: b"currentore".to_vec(), + raw_value: [0x1111_1111, 0xdead_beef, 0, 0], + }, + MissionObjectProperty { + name_raw: b"CurrentOre".to_vec(), + raw_value: [0x3f80_0000, 0x7fc1_2345, 0, 0], + }, + MissionObjectProperty { + name_raw: b"CurrentOre".to_vec(), + raw_value: [0, 0x4400_0000, 0, 0], + }, + MissionObjectProperty { + name_raw: b"MaximumOre".to_vec(), + raw_value: [0, 0x4123_4567, 0, 0], + }, + ], + ); + + assert_eq!(state.original_id, OriginalObjectId(19)); + assert_eq!(state.handle, handle); + assert_eq!(state.class_flags, 0x0100_2000); + assert_eq!(state.current_ore_bits, 0x7fc1_2345); + assert_eq!(state.maximum_ore_bits, 0x44fa_0000); + } + + #[test] + fn behavior_ore_defaults_follow_native_class_dispatch() { + assert_eq!(native_behavior_ore_defaults(0x8000_0004), (0, 0x43fa_0000)); + assert_eq!(native_behavior_ore_defaults(0x8000_0008), (0, 0x457a_0000)); + assert_eq!(native_behavior_ore_defaults(0x0100_2000), (0, 0x44fa_0000)); + assert_eq!( + native_behavior_ore_defaults(0x0100_4000), + (0x44fa_0000, 0x44fa_0000) + ); + assert_eq!(native_behavior_ore_defaults(0x0100_8000), (0, 0)); + } + + #[test] fn behavior_distributor_add_uses_handle_and_preserves_duplicate_tail() { let mut distributor = BehaviorDistributorState { clan_index: 0, @@ -2767,6 +2921,9 @@ mod tests { assert!(loaded_mission_behavior_distributors(&engine) .expect("preview Behavior distributors") .is_empty()); + assert!(loaded_mission_behavior_ore_states(&engine) + .expect("preview Behavior ore state") + .is_empty()); assert!(bundles .iter() .all(|bundle| bundle.behavior_warm_start.is_none())); diff --git a/crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs b/crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs index 5c7c4f2..d2e5bb9 100644 --- a/crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs +++ b/crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs @@ -5,9 +5,10 @@ using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; -// Calls the original x86 Behavior.dll distributor Add, normalize, and tick paths -// against synthetic storage. Only GetSystemArealMap and the bounded vector backing -// are substituted; Behavior's corresponding instructions remain the installed DLL. +// Calls the original x86 Behavior.dll distributor Add, normalize, indexed resource +// property, and tick paths against synthetic storage. Only GetSystemArealMap and the +// bounded vector backing are substituted; Behavior's corresponding instructions +// remain the installed DLL. internal static class BehaviorDistributorTickOracle { private const uint LoadWithAlteredSearchPath = 0x00000008; private const uint MemCommitReserve = 0x00003000; @@ -15,10 +16,17 @@ internal static class BehaviorDistributorTickOracle { private const uint MemRelease = 0x00008000; private const uint PageReadWrite = 0x04; private const string ExpectedBehaviorSha256 = "ddfbdbde07832358fe6e35e01c8dba9b58e7313789498b6049ed51d4ed9baf99"; + private const string ExpectedControlSha256 = "bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e"; private const int TickRva = 0x19e80; private const int AddObjectRva = 0x1aac0; private const int NormalizeRva = 0x1ac90; + private const int IndexedPropertySetRva = 0x0b470; + private const int IndexedPropertyGetRva = 0x0b5b0; + private const int OreInitializationRva = 0x08790; private const int GetSystemArealMapIatRva = 0x59008; + private const int ControlResourceDeviceGetterRva = 0x21d00; + private const int ControlProviderInterfaceVtableRva = 0x3d254; + private const int ControlProviderType1GetterRva = 0x0dc40; private const uint ResourceProperty = 0x02000100; private static Fixture active; @@ -45,6 +53,10 @@ internal static class BehaviorDistributorTickOracle { [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void ObjectSetProperty(IntPtr self, uint property, float value, IntPtr result); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int InterfaceGetProperty(IntPtr self, uint selector, IntPtr result); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int InterfaceSetProperty(IntPtr self, uint selector, IntPtr value); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void IndexedPropertySet(IntPtr self, uint index, uint valueBits); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int IndexedPropertyGet(IntPtr self, uint index, IntPtr resultBits); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeOreInitialization(IntPtr self); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate float NativeControlResourceDeviceGet(IntPtr self, uint selector); private static readonly AreaMapGetter AreaMapGetterCallback = GetAreaMap; private static readonly VectorInsert VectorInsertCallback = InsertVector; @@ -158,7 +170,7 @@ internal static class BehaviorDistributorTickOracle { Marshal.WriteInt32(entry, 0x04, BitConverter.ToInt32(BitConverter.GetBytes(1.0f), 0)); } } - private IntPtr Allocate(int size) { + public IntPtr Allocate(int size) { IntPtr value = Marshal.AllocHGlobal(size); Zero(value, size); Allocations.Add(value); @@ -299,13 +311,20 @@ internal static class BehaviorDistributorTickOracle { private static int Main() { if (IntPtr.Size != 4) { Console.Error.WriteLine("Build with /platform:x86."); return 2; } + string controlPath = Environment.GetEnvironmentVariable("FPARKAN_ORIGINAL_CONTROL_DLL"); + if (String.IsNullOrEmpty(controlPath)) controlPath = @"C:\GOG Games\Parkan - Iron Strategy\Control.dll"; + if (!File.Exists(controlPath)) { Console.Error.WriteLine("Set FPARKAN_ORIGINAL_CONTROL_DLL to the installed Control.dll."); return 7; } + string controlHash = Hash(controlPath); + if (controlHash != ExpectedControlSha256) { Console.Error.WriteLine("Unexpected Control.dll SHA-256: " + controlHash); return 8; } + IntPtr controlModule = LoadLibraryEx(controlPath, IntPtr.Zero, LoadWithAlteredSearchPath); + if (controlModule == IntPtr.Zero) { Console.Error.WriteLine("LoadLibraryEx(Control.dll) failed: " + Marshal.GetLastWin32Error()); return 9; } string path = Environment.GetEnvironmentVariable("FPARKAN_ORIGINAL_BEHAVIOR_DLL"); if (String.IsNullOrEmpty(path)) path = @"C:\GOG Games\Parkan - Iron Strategy\Behavior.dll"; - if (!File.Exists(path)) { Console.Error.WriteLine("Set FPARKAN_ORIGINAL_BEHAVIOR_DLL to the installed Behavior.dll."); return 3; } + if (!File.Exists(path)) { Console.Error.WriteLine("Set FPARKAN_ORIGINAL_BEHAVIOR_DLL to the installed Behavior.dll."); FreeLibrary(controlModule); return 3; } string hash = Hash(path); - if (hash != ExpectedBehaviorSha256) { Console.Error.WriteLine("Unexpected Behavior.dll SHA-256: " + hash); return 4; } + if (hash != ExpectedBehaviorSha256) { Console.Error.WriteLine("Unexpected Behavior.dll SHA-256: " + hash); FreeLibrary(controlModule); return 4; } IntPtr module = LoadLibraryEx(path, IntPtr.Zero, LoadWithAlteredSearchPath); - if (module == IntPtr.Zero) { Console.Error.WriteLine("LoadLibraryEx(Behavior.dll) failed: " + Marshal.GetLastWin32Error()); return 5; } + if (module == IntPtr.Zero) { Console.Error.WriteLine("LoadLibraryEx(Behavior.dll) failed: " + Marshal.GetLastWin32Error()); FreeLibrary(controlModule); return 5; } IntPtr import = IntPtr.Add(module, GetSystemArealMapIatRva); IntPtr originalImport = Marshal.ReadIntPtr(import); uint oldProtection = 0; @@ -327,7 +346,7 @@ internal static class BehaviorDistributorTickOracle { throw new InvalidOperationException("VirtualProtect(GetSystemArealMap IAT) failed: " + Marshal.GetLastWin32Error()); protectionChanged = true; Marshal.WriteIntPtr(import, Marshal.GetFunctionPointerForDelegate(AreaMapGetterCallback)); - RunSmokeCases(module); + RunSmokeCases(module, controlModule); Console.WriteLine("original Behavior.dll distributor oracle passed (native Add 0x1aac0, normalize 0x1ac90, tick 0x19e80; only GetSystemArealMap IAT and bounded vector insertion are substituted; this does not compare Rust parity)."); return 0; } @@ -350,10 +369,11 @@ internal static class BehaviorDistributorTickOracle { throw new InvalidOperationException("VirtualFree(fastcall callback thunks) failed: " + Marshal.GetLastWin32Error()); if (x87ControlWordCell != IntPtr.Zero) { Marshal.FreeHGlobal(x87ControlWordCell); x87ControlWordCell = IntPtr.Zero; } FreeLibrary(module); + FreeLibrary(controlModule); } } - private static void RunSmokeCases(IntPtr module) { + private static void RunSmokeCases(IntPtr module, IntPtr controlModule) { ushort savedControlWord = CurrentX87ControlWord(); Console.WriteLine("x87-control-word-before=0x" + savedControlWord.ToString("x4") + " (x86 oracle process)"); try { @@ -361,10 +381,13 @@ internal static class BehaviorDistributorTickOracle { Console.WriteLine("native-add-normalize-x87-control-word=0x" + CurrentX87ControlWord().ToString("x4")); RunNativeAddCases(module); RunNativeNormalizeCases(module); + RunNativeControlResourceDeviceCase(controlModule); } finally { SetX87ControlWord(savedControlWord); Console.WriteLine("x87-control-word-restored=0x" + CurrentX87ControlWord().ToString("x4")); } + RunNativeIndexedPropertyCases(module); + RunNativeOreInitializationCases(module); TickDelegate tick = (TickDelegate)Marshal.GetDelegateForFunctionPointer(IntPtr.Add(module, TickRva), typeof(TickDelegate)); using (Fixture empty = NewFixture()) { empty.MakeDistributor(); active = empty; tick(empty.Distributor, 0.0f); @@ -387,6 +410,187 @@ internal static class BehaviorDistributorTickOracle { RunSkippedCase(tick); } + private static void RunNativeControlResourceDeviceCase(IntPtr module) { + Expect(CurrentX87ControlWord() == 0x007f, "Control selector 0x300 uses x87 control word 0x007f"); + const uint key = 2; + const int rowCount = 22; + const int providerRow = (int)key * 0x2c; + IntPtr providerOwner = Marshal.AllocHGlobal(0x560); + IntPtr providerRows = Marshal.AllocHGlobal(rowCount * 0x2c); + IntPtr device = IntPtr.Zero; + try { + Zero(providerOwner, 0x560); + Zero(providerRows, rowCount * 0x2c); + IntPtr providerInterface = IntPtr.Add(providerOwner, 4); + IntPtr providerVtable = IntPtr.Add(module, ControlProviderInterfaceVtableRva); + Marshal.WriteIntPtr(providerInterface, providerVtable); + Expect( + Marshal.ReadIntPtr(providerVtable, 0x0c) == IntPtr.Add(module, ControlProviderType1GetterRva), + "Control provider interface vtable uses the native type-1 getter"); + Marshal.WriteIntPtr(providerOwner, 0x55c, providerRows); + + device = Marshal.AllocHGlobal(0x94); + Zero(device, 0x94); + Marshal.WriteInt32(device, 0x04, unchecked((int)key)); + Marshal.WriteIntPtr(device, 0x44, providerInterface); + + NativeControlResourceDeviceGet getter = (NativeControlResourceDeviceGet) + Marshal.GetDelegateForFunctionPointer( + IntPtr.Add(module, ControlResourceDeviceGetterRva), + typeof(NativeControlResourceDeviceGet)); + ExpectControlResourceDeviceResult(getter, device, providerRows, providerRow, + 0x3fe6982f, 0x3d25ae4a, 0x40715539, 0x3e8cb02e, "order-sensitive normal"); + ExpectControlResourceDeviceResult(getter, device, providerRows, providerRow, + 0x7f7fffff, 0x40000000, 0x3e800000, 0x7effffff, "extended intermediate overflow then finite"); + ExpectControlResourceDeviceResult(getter, device, providerRows, providerRow, + 0x00800000, 0x00800000, 0x7f7fffff, 0x017fffff, "extended intermediate underflow then finite"); + ExpectControlResourceDeviceResult(getter, device, providerRows, providerRow, + 0x00800000, 0x3f800000, 0x3f000000, 0x00400000, "subnormal final result"); + ExpectControlResourceDeviceResult(getter, device, providerRows, providerRow, + 0xc0000000, 0x3f000000, 0x40800000, 0xc0800000, "negative factors"); + ExpectControlResourceDeviceResult(getter, device, providerRows, providerRow, + 0x80000000, 0x40000000, 0x40400000, 0x80000000, "negative zero"); + Expect(CurrentX87ControlWord() == 0x007f, "Control selector 0x300 retains x87 control word 0x007f"); + Console.WriteLine("native-control-tag26-selector-300: controlHash=" + ExpectedControlSha256 + + " cw=0x" + CurrentX87ControlWord().ToString("x4") + " key=2 rows=22"); + GC.KeepAlive(getter); + } finally { + if (device != IntPtr.Zero) Marshal.FreeHGlobal(device); + Marshal.FreeHGlobal(providerRows); + Marshal.FreeHGlobal(providerOwner); + } + } + + private static void ExpectControlResourceDeviceResult( + NativeControlResourceDeviceGet getter, + IntPtr device, + IntPtr providerRows, + int providerRow, + uint providerBits, + uint baseBits, + uint multiplierBits, + uint expectedBits, + string label) { + Marshal.WriteInt32(providerRows, providerRow + 0x14, unchecked((int)providerBits)); + Marshal.WriteInt32(device, 0x54, unchecked((int)baseBits)); + Marshal.WriteInt32(device, 0x4c, unchecked((int)multiplierBits)); + uint actualBits = unchecked((uint)FloatBits(getter(device, 0x300))); + Expect(actualBits == expectedBits, + "Control selector 0x300 " + label + " expected " + Hex(expectedBits) + " but got " + Hex(actualBits)); + Console.WriteLine("native-control-tag26-selector-300-" + label + ": result=" + Hex(actualBits)); + } + + private static void RunNativeIndexedPropertyCases(IntPtr module) { + IndexedPropertySet set = (IndexedPropertySet)Marshal.GetDelegateForFunctionPointer( + IntPtr.Add(module, IndexedPropertySetRva), typeof(IndexedPropertySet)); + IndexedPropertyGet get = (IndexedPropertyGet)Marshal.GetDelegateForFunctionPointer( + IntPtr.Add(module, IndexedPropertyGetRva), typeof(IndexedPropertyGet)); + using (Fixture fixture = NewFixture()) { + // The handlers receive the embedded interface at owner+4. Its descriptor + // vector is at interface+0xa3c and its keyed property store at interface+0x5e4. + IntPtr owner = fixture.Allocate(0x0b20); + IntPtr iface = IntPtr.Add(owner, 4); + IntPtr descriptors = fixture.Allocate(6 * 0x18); + IntPtr propertyEntry = fixture.Allocate(0x18); + IntPtr maximumOutput = fixture.Allocate(sizeof(uint)); + IntPtr currentOutput = fixture.Allocate(sizeof(uint)); + + Marshal.WriteInt32(iface, 0xa3c, 6); + Marshal.WriteIntPtr(iface, 0xa44, descriptors); + Marshal.WriteInt32(IntPtr.Add(descriptors, 4 * 0x18), 4, 4); + Marshal.WriteInt32(IntPtr.Add(descriptors, 5 * 0x18), 4, 5); + + Marshal.WriteInt32(iface, 0x5e4, 0); // vector vtable is not used by these callbacks + Marshal.WriteInt32(iface, 0x5e8, 1); // count + Marshal.WriteInt32(iface, 0x5ec, 1); // capacity + Marshal.WriteIntPtr(iface, 0x5f0, propertyEntry); + Marshal.WriteInt32(propertyEntry, 0x00, unchecked((int)ResourceProperty)); + Marshal.WriteInt32(propertyEntry, 0x04, unchecked((int)0x11223344)); + Marshal.WriteInt32(propertyEntry, 0x08, FloatBits(2500.0f)); // auxiliary maximum + Marshal.WriteInt32(propertyEntry, 0x0c, unchecked((int)0x55667788)); + Marshal.WriteInt32(propertyEntry, 0x10, unchecked((int)0x99aabbcc)); + Marshal.WriteInt32(propertyEntry, 0x14, FloatBits(12.5f)); // primary current amount + + Expect(get(iface, 4, maximumOutput) == 1 && Marshal.ReadInt32(maximumOutput) == FloatBits(2500.0f), + "descriptor 4 reads keyed auxiliary value as MaximumOre"); + Expect(get(iface, 5, currentOutput) == 1 && Marshal.ReadInt32(currentOutput) == FloatBits(12.5f), + "descriptor 5 reads keyed primary float as CurrentOre"); + + set(iface, 5, unchecked((uint)FloatBits(21.75f))); + Expect(Marshal.ReadInt32(propertyEntry, 0x14) == FloatBits(21.75f) && + Marshal.ReadInt32(propertyEntry, 0x08) == FloatBits(2500.0f), + "descriptor 5 updates CurrentOre and preserves MaximumOre auxiliary value"); + set(iface, 4, unchecked((uint)FloatBits(999.0f))); + Expect(Marshal.ReadInt32(propertyEntry, 0x14) == FloatBits(21.75f) && + Marshal.ReadInt32(propertyEntry, 0x08) == FloatBits(2500.0f), + "descriptor 4 is read-only through the indexed setter"); + Expect(get(iface, 4, maximumOutput) == 1 && Marshal.ReadInt32(maximumOutput) == FloatBits(2500.0f) && + get(iface, 5, currentOutput) == 1 && Marshal.ReadInt32(currentOutput) == FloatBits(21.75f), + "indexed resource values remain independently readable after CurrentOre write"); + + IntPtr reorderedDescriptors = fixture.Allocate(2 * 0x18); + Marshal.WriteInt32(iface, 0xa3c, 2); + Marshal.WriteIntPtr(iface, 0xa44, reorderedDescriptors); + Marshal.WriteInt32(reorderedDescriptors, 4, 5); + Marshal.WriteInt32(IntPtr.Add(reorderedDescriptors, 0x18), 4, 4); + Expect(get(iface, 0, currentOutput) == 1 && Marshal.ReadInt32(currentOutput) == FloatBits(21.75f), + "descriptor index zero follows its CurrentOre code 5 row"); + Expect(get(iface, 1, maximumOutput) == 1 && Marshal.ReadInt32(maximumOutput) == FloatBits(2500.0f), + "descriptor index one follows its MaximumOre code 4 row"); + set(iface, 0, unchecked((uint)FloatBits(31.25f))); + set(iface, 1, unchecked((uint)FloatBits(999.0f))); + Expect(Marshal.ReadInt32(propertyEntry, 0x14) == FloatBits(31.25f) && + Marshal.ReadInt32(propertyEntry, 0x08) == FloatBits(2500.0f), + "reordered descriptor rows preserve CurrentOre write and MaximumOre read-only behavior"); + Expect(get(iface, 0, currentOutput) == 1 && Marshal.ReadInt32(currentOutput) == FloatBits(31.25f) && + get(iface, 1, maximumOutput) == 1 && Marshal.ReadInt32(maximumOutput) == FloatBits(2500.0f), + "reordered descriptor rows remain readable after their indexed writes"); + Console.WriteLine("native-indexed-resource-property: maximum=" + Float(unchecked((uint)Marshal.ReadInt32(maximumOutput))) + + " current=" + Float(unchecked((uint)Marshal.ReadInt32(currentOutput))) + + "; descriptor4-write=no-op descriptor5-write=primary-only; reordered-indices=verified"); + } + } + + private static void RunNativeOreInitializationCases(IntPtr module) { + NativeOreInitialization initialize = (NativeOreInitialization)Marshal.GetDelegateForFunctionPointer( + IntPtr.Add(module, OreInitializationRva), typeof(NativeOreInitialization)); + uint[][] cases = new uint[][] { + new uint[] { 0x80000004, 0x00000000, 0x43fa0000 }, + new uint[] { 0x80000008, 0x00000000, 0x457a0000 }, + new uint[] { 0x01002000, 0x00000000, 0x44fa0000 }, + new uint[] { 0x01004000, 0x44fa0000, 0x44fa0000 }, + new uint[] { 0x01008000, 0x00000000, 0x00000000 } + }; + IntPtr vtable = IntPtr.Add(module, 0x59250); + foreach (uint[] test in cases) { + using (Fixture fixture = NewFixture()) { + IntPtr owner = fixture.Allocate(0x0b20); + IntPtr propertyEntry = fixture.Allocate(0x18); + Marshal.WriteIntPtr(owner, vtable); + Marshal.WriteIntPtr(owner, 0x30, owner); + Marshal.WriteInt32(owner, 0xa04, 2); + Marshal.WriteInt32(owner, 0xa64, 1); // suppress the wrapper's deferred side effect + Marshal.WriteInt32(owner, 0xafc, unchecked((int)test[0])); + Marshal.WriteInt32(owner, 0x70c, FloatBits(500.0f)); + Marshal.WriteInt32(owner, 0x710, FloatBits(4000.0f)); + Marshal.WriteInt32(owner, 0x720, FloatBits(2000.0f)); + Marshal.WriteInt32(propertyEntry, 0x00, unchecked((int)ResourceProperty)); + Marshal.WriteInt32(propertyEntry, 0x08, unchecked((int)0xbf800000)); // native add default auxiliary + Marshal.WriteInt32(propertyEntry, 0x14, FloatBits(123.0f)); // prove initialization overwrites primary + Marshal.WriteInt32(owner, 0x5ec, 1); // property count + Marshal.WriteInt32(owner, 0x5f0, 1); // property capacity + Marshal.WriteIntPtr(owner, 0x5f4, propertyEntry); + + initialize(owner); + + Expect(unchecked((uint)Marshal.ReadInt32(propertyEntry, 0x14)) == test[1] && + unchecked((uint)Marshal.ReadInt32(propertyEntry, 0x08)) == test[2], + "native ore defaults for class 0x" + test[0].ToString("x8")); + } + } + Console.WriteLine("native-behavior-ore-initialization: classes=80000004,80000008,01002000,01004000,01008000; defaults=verified"); + } + private static ushort CurrentX87ControlWord() { if (x87ControlWordReader == null || x87ControlWordCell == IntPtr.Zero) throw new InvalidOperationException("x87 control-word reader is not initialized"); @@ -791,7 +995,7 @@ internal static class BehaviorDistributorTickOracle { foreach (byte value in digest) hex.Append(value.ToString("x2")); return hex.ToString(); } } - private static void Expect(bool value, string message) { if (!value) throw new InvalidOperationException("original Behavior oracle failed: " + message); } + private static void Expect(bool value, string message) { if (!value) throw new InvalidOperationException("original native oracle failed: " + message); } private static void ExpectLookupOrder(Fixture fixture, params string[] keys) { List<string> actual = new List<string>(); foreach (string item in fixture.Trace) if (item.StartsWith("lookup:", StringComparison.Ordinal)) actual.Add(item.Substring(7)); diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index 873497c..5791836 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -130,7 +130,7 @@ host construction phases. Не проверена другая лицензирÐ непустым `Init`. Вызов `Behavior.dll!FUN_10019e80` (RVA `0x19e80`, SHA-256 `ddfbdbde07832358fe6e35e01c8dba9b58e7313789498b6049ed51d4ed9baf99`) исполнялся на синтетических интерфейсах. Путь членства в реальных distributor-списках -теперь связан с полями TMA и Unit DAT: `World3D!CreateObject` передаёт selector +связан с полями TMA и Unit DAT: `World3D!CreateObject` передаёт selector и class word через дескриптор в Behavior (RVA `0x7e55`, `0x7e62`), а `Behavior.dll!FUN_10005e60` (RVA `0x5e60`) проверяет высокий бит registration key, AI и distributor. Selector из первого DWORD после имени ресурса выбирает @@ -169,6 +169,50 @@ Behavior (`Behavior.dll`, RVA `0x3600`) вызывает `World3D!stdGetGameMode с реальными интерфейсами ArealMap, нужными `FUN_10019e80`; полный Behavior tick flow и общий dispatcher событий также остаются открытыми. +Начальные свойства `CurrentOre`/`MaximumOre` восстановлены отдельно от +регулярного обмена. В проверенных `Behavior.dll` (SHA-256 +`ddfbdbde07832358fe6e35e01c8dba9b58e7313789498b6049ed51d4ed9baf99`) RVA +`0x8790` выбирает начальные значения по class word, `0xb110` регистрирует +дескрипторы кодов 4/5, `0xb470` пишет только код 5, а `0xb5b0` читает код 4 +как дополнительное слово и код 5 как основное. `MisLoad.dll` (SHA-256 +`c607762bb67db14ca530927c8e1347339b62b0a163ac90c708ee83142292e2bf`) RVA +`0x40b0` выбирает первое свойство TMA с точным именем `CurrentOre` и передаёт +его `raw_value[1]`; setter сохраняет биты напрямую. В AutoDemo snapshot на этих +входах было восемь объектов Unit DAT, у всех raw `CurrentOre` равен нулю; +четыре объекта класса `0x01008000` не вошли в distributor, но остались среди +инициализированных Rust-состояний. Поэтому путь нулевого значения наблюдался +наживую, но ненулевое TMA-значение в живой миссии пока не проверено. + +Синтетический x86 oracle вызвал `Behavior.dll!FUN_10008790` напрямую для классов +`0x80000004`, `0x80000008`, `0x01002000`, `0x01004000` и `0x01008000`; перед +вызовом в записи были значения `CurrentOre=123` и `MaximumOre=-1`, так что +проверено их перезаписывание. Тест выставляет `a64=1`, чтобы отключить отложенный +side effect обёртки setter-а. Это подтверждает ветви initializer-а, но не весь +путь его запуска и связи с остальными фазами объекта. Другой изолированный x86 +oracle проверяет ненулевое raw-слово `CurrentOre`, только чтение `MaximumOre` и +перестановку строк дескрипторов на синтетических записях свойств. + +Не проверен селектор 4 для внешнего config-like ресурса: в наблюдавшемся +AutoDemo его вызова нет, а установленный `Behavior.ini` не содержит +`Mine_MaxOre`, `Storage_MaxOre` или `Transport_MaxOre`. Поэтому Rust пока +воспроизводит доказанные class defaults (500, 4000 и 2000) и не заявляет +поддержку конфигурационного переопределения. Отдельно не доказано, что каждый +Unit DAT создаёт тот же Behavior-компонент во всех host factory paths. Rust +ограничивает новую запись полными TMA-объектами с Unit DAT; preview, прямые +prototype roots без Unit DAT и отложенные spawn после исходной загрузки вне +этой модели. Путь в `ArealMap.dll` (SHA-256 +`a25f9254ebb339d70e2e07c8121950191e9584ca0858d8e9c2e2b6c671edf6ea`) к +`CreateObject` по RVA `0x14fd0`/`0x15290` показывает выбор World3D class 3 или 4 +по старшему биту. Для ветки GOG `AniMesh.dll` (SHA-256 +`65659bf67f20e5be77d67a5b2f59968f61b94293143807fa59ca451c560c4f7e`) RVA +`0x2ff0` показывает одну ветку создания: после QueryInterface для IID `0x204` +выполняется отдельный импорт `GetQueue()`, а на возвращённом объекте вызывается +метод через vtable slot `+0x30`. `CreateBehaviour` вызывается только при +ненулевом результате этого метода и host class `3` или `4`; class `4` получает +адреса полей prototype `+0x140` и `+0x160`. Семантика метода slot `+0x30` не +установлена. Другие factory paths, нулевой результат и spawn после исходной +загрузки остаются за границами подтверждённой ветки. + Для `Handler(30)` отдельно подтверждены обратный вызов `iron3d.dll` RVA `0x611d0` (SHA-256 `d1dc4ea8535e2069b0a05c9e8be2724dd438ba44cca7a83007d8b2e50f9e35fa`), начальные поля IGame и проверки режима/состояния. Обработчик выбора миссии @@ -203,6 +247,50 @@ CTLD и связанные resources структурно читаются, coun известны. Не названы все секции, shape types, coefficients и точный contact solver. То же относится к редким MSH auxiliary streams и части CTPT/NDPR flags. +Одна цепочка Unit DAT → AniMesh descriptor → Control теперь восстановлена +статически в [главе о Behavior и Control](../tomes/06-behavior.md): raw +`parent_or_link` копируется в descriptor. В non-`EXTO` registry path parent ID +разрешается в индекс устройства и сдвигает локальный индекс только когда parent +ID не равен `-1` и IID `0x202` доступен; иначе используется raw локальный индекс. +В этом потоке нулевой raw kind пропускает узел вместе с потомками, поэтому общий +assigned ID нельзя получать из preorder-позиции записи. Это закрывает только +передачу полей в native loader-е; Rust ещё должен строить такую же проекцию. + +Control loader также различает добавление устройств и применение одной записи +к уже выбранному устройству. Для tag `19` найденные поля и ветви описаны в +главе, но эффективное слияние пока не реализовано. В Rust parser-е +`Unsupported { typed_record_index: Some(_) }` означает, что разбор остановился +внутри списка typed records; без индекса остановки unsupported может относиться +к effect-tail после уже разобранного списка. Эти случаи нужно различать. +Ветка default native-фабрики вызывает конструктор по RVA `0x20800`, поэтому +неизвестный Rust parser-у tag не доказывает отказ оригинального loader-а. Подготовка assets +сейчас пропускает Control refs у non-geometric prototype, поэтому отсутствие +подготовленного CTL должно оставаться явным unavailable result, а не +трактоваться как пустой список. + +Глобальные Control selectors `1/2` и setter selector `1` по tag `19` описаны +там же только по статическому разбору `Control.dll`; execution oracle для этих +глобальных вызовов нет. Остаются открытыми проверка effective merge на живых +объектах, полный охват registry types и host factory paths, а также runtime +жизненный цикл множителя `+0x4c`. + +Для `Control.dll` (SHA-256 +`bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e`) tag-26 +getter selector `0x300` восстановлен локально: RVA `0x21d00` читает provider по +ключу `fixed_words[1]`, затем умножает provider, CTLD coefficient `fixed_words[11]` +и поле объекта `+0x4c` именно в таком порядке. Rust helper принимает текущие +provider и multiplier извне; он не восстанавливает их жизненный цикл или весь +Control tick. В x86 oracle при x87 control word `0x007f` проверены порядок, +signed zero, отрицательные входы, расширенный промежуточный диапазон и +subnormal return. Helper ограничивает себя normal-or-zero значениями, поэтому +явно отклоняет промежуточные случаи, где результат выходит за поддерживаемый +диапазон f32, даже если позднее умножение вернуло бы его в диапазон. Это +ограничение поддержки Rust helper-а, а не неверный native-результат. + +В Unit DAT fixture `UNITS/BUILDS/MINE/min_l_n1.dat` проверена реальная связка +`fr_l_mine.ctl` + `fr_l_mine.ndp`: tag `26`, ключ `2` в таблице из `22` строк, +коэффициент `1.0`. Это не запись живого resource-device значения в миссии. + Закрывающий эксперимент: трассировать `LoadControlSystem`, `LoadPhysicalModel`, `CreateCollManager` и создание collision objects; связать каждый изменяемый field с созданным shape, contact или реакцией на движение. diff --git a/docs/reference/tma.md b/docs/reference/tma.md index 2a84d6d..8eb6f66 100644 --- a/docs/reference/tma.md +++ b/docs/reference/tma.md @@ -92,3 +92,15 @@ slot `+0x40` в путь выбора AI в Behavior. Поэтому Rust сох `Property` состоит из четырёх raw `u32` и имени. Typed views разрешены только для доказанных property names и consumers. + +Для свойств объекта `MisLoad.dll!FUN_10003ab0` (RVA `0x3ab0`) переставляет +дисковые слова в runtime-запись, а `FUN_100040b0` (RVA `0x40b0`) проходит её +таблицу в порядке runtime-дескрипторов. Поиск имени учитывает длину и байты с +точным регистром и использует первое совпадение. В подтверждённом пути +дисковое `raw_value[1]` становится первым DWORD аргумента setter-а, поэтому +значение передаётся как биты, без промежуточного float-преобразования. +Например, Behavior регистрирует `CurrentOre` под кодом `5`; его setter кладёт +полученные биты в основное слово свойства `0x02000100`. `MaximumOre` с кодом +`4` читает дополнительное слово той же записи, а setter этого дескриптора +ничего не меняет. Подтверждение классов и native getter/setter находится в +[главе о Behavior](../tomes/06-behavior.md#начальные-свойства-запасов-руды). diff --git a/docs/tomes/03-resources.md b/docs/tomes/03-resources.md index 29fef77..a11ad55 100644 --- a/docs/tomes/03-resources.md +++ b/docs/tomes/03-resources.md @@ -448,21 +448,28 @@ struct UnitDatRecord112 { char archive_name[32]; // +0x00 char resource_name[32]; // +0x20 uint32_t kind; // +0x40, в корпусе всегда 1 - int32_t parent_or_link; // +0x44 + int32_t parent_or_link; // +0x44, context-dependent local index char description[32]; // +0x48 uint32_t tail0; // +0x68, opaque - uint32_t tail1; // +0x6C, opaque + uint32_t tail1; // +0x6C, immediate_child_count }; #pragma pack(pop) ``` Во всех проверенных records `archive_name == "objects.rlb"` и `kind == 1`. -Поле `parent_or_link` встречается как `-1`, `0`, `1` и другие небольшие индексы -и связывает компоненты составного unit; точная предметная классификация ссылки -ещё не закрыта. `description` -- человекочитаемое описание компонента. В Части 2 -есть поля `description[32]`, полностью заполненные без NUL; это валидная bounded -string длиной 32 байта. Требование обязательного terminator применяется только -к полям, где оно доказано форматом. `tail0` и `tail1` нельзя нормализовать. +`tail1` задаёт `immediate_child_count` — число непосредственных дочерних +записей при построении дерева Unit DAT; оно не opaque. Поле `parent_or_link` +встречается как `-1`, `0`, `1` и другие небольшие индексы. В подтверждённой +цепочке Unit DAT → AniMesh → Control оно становится локальным индексом. Для +`INTO` индекс задаёт устройство Control относительно первого устройства +родительского компонента, а `EXTO` обрабатывается отдельной ветвью. Поэтому +поле нельзя трактовать как универсальный parent ID или одинаковую ссылку для +всех registry types. Детали передачи описаны в [главе о Behavior и Control](06-behavior.md). +`tail0` сохраняется как raw DWORD без установленной семантики. `description` -- +человекочитаемое описание компонента. В Части 2 есть поля `description[32]`, +полностью заполненные без NUL; это валидная bounded string длиной 32 байта. +Требование обязательного terminator применяется только к полям, где оно доказано +форматом. Проверено 425 файлов / 5 219 records Части 1 и 676 файлов / 8 145 records Части 2. Все соответствуют формуле размера, `kind == 1` и @@ -470,10 +477,8 @@ string длиной 32 байта. Требование обязательног При построении mission prototype graph FParkan сохраняет для каждого root упорядоченный список этих raw records. Список передаётся в -`MissionObjectDraft` без преобразования `kind`, `parent_or_link`, description -или tails в предполагаемые роли. Так runtime уже располагает исходными данными -составного unit для будущих Control/physics/AniMesh consumers, но не выдаёт -структурное сходство за доказанную семантику. +`MissionObjectDraft` с исходными `kind`, `parent_or_link`, description и tails; +эти данные пока не объединяются в таблицу эффективных устройств Control. Каждый graph edge от `UnitDatRoot` к effective component и далее к его MSH dependency также несёт `unit_component_index`. Это индекс исходной записи в diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index c00705b..9d7b01e 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -255,6 +255,56 @@ Rust хранит этот небольшой начальный список с опирается на уже созданный `ObjectHandle`. Регулярный обмен ресурсами пока остаётся отдельным этапом, потому что для него нужны интерфейсы игровых объектов. +### Начальные свойства запасов руды + +Behavior хранит `CurrentOre` и `MaximumOre` в одной записи свойства с ключом +`0x02000100`: текущее количество лежит в основном float-слове, предел — в +дополнительном DWORD. В TMA это не означает, что оба значения свободно задаются +файлом. При загрузке `MisLoad.dll` ищет первое свойство с точным, чувствительным +к регистру совпадением имени и передаёт его второе raw-слово в setter. В +Behavior дескриптор `CurrentOre` записывает это слово в основное значение; +дескриптор `MaximumOre` читает дополнительное слово, но его setter ничего не +меняет. + +Оба дескриптора регистрируются как коды `4` и `5`. Это коды обработчика, а не +позиции в таблице дескрипторов: исходная DLL корректно работает и после +перестановки строк, потому что callback выбирает обработчик по коду строки. +Поэтому начальное состояние можно описать так, сохраняя биты без пересчёта +через `float`: + +```text +current = first_exact("CurrentOre").raw_value[1] ?? class_default_current +maximum = class_default_maximum +``` + +Класс задаёт значения по умолчанию в Behavior RVA `0x8790`: + +| Слово класса | `CurrentOre` | `MaximumOre` | +| --- | ---: | ---: | +| `0x80000004` | 0 | 500 | +| `0x80000008` | 0 | 4000 | +| `0x01002000` | 0 | 2000 | +| `0x01004000` | 2000 | 2000 | +| прочие слова в этой ветви | 0 | 0 | + +Вызов RVA `0x8790` на синтетической структуре подтвердил эти значения для +классов таблицы, включая `0x01008000`; он проверяет тело native initializer-а, +но не его полный жизненный цикл в игре. + +В полной загрузке Rust сохраняет эти два raw-значения рядом с исходным TMA ID +и `ObjectHandle` каждого объекта с Unit DAT; список участников распределителя +для этого не требуется. Это важно для объектов, у которых есть компонент +Behavior, но нет членства в ресурсном distributor. Preview намеренно не создаёт +начальное состояние. Лицензированная AutoDemo показывает восемь объектов с +Unit DAT, включая объекты класса `0x01008000` вне списков distributor; в этом +снимке TMA `CurrentOre` равен нулю у всех восьми. Нативный x86 oracle отдельно +проверяет ненулевое raw-слово, чтение предела, отсутствие записи в `MaximumOre` +и переставленные строки дескрипторов. + +Эта модель покрывает именно начальную загрузку полных TMA-объектов. Она не +утверждает, что уже восстановлены все пути создания Behavior, отложенное +создание объектов или внешняя подмена class defaults конфигурацией. + ### Регулярная передача ресурсов Resource Distributor работает со списком зарегистрированных объектов. За один @@ -492,10 +542,155 @@ component как ordered raw-string/resource provenance, но не для при этим строкам смысловых имён до трассировки private update methods. Runtime сохраняет ordered raw Unit DAT records рядом с каждым mission object -draft. Это создаёт проверяемую границу передачи данных от loader-а к будущему -Control consumer-у: никакой компонент пока не получает имя `Control` только -по `kind`, `parent_or_link` или description; semantic binding появится лишь -после trace private update/load methods. +draft. Теперь подтверждена связь Unit DAT с descriptor-ом AniMesh, который +передаётся в Control: порядок узлов задаётся деревом immediate-child counts, +а `parent_or_link` попадает в descriptor как локальное поле. Его смысл зависит +от registry type и состояния Control manager-а; в частности, для `INTO` это +локальный индекс устройства, а `EXTO` проходит отдельную ветвь. + +### От Unit DAT к Control descriptor + +В GOG `ArealMap.dll` (SHA-256 +`a25f9254ebb339d70e2e07c8121950191e9584ca0858d8e9c2e2b6c671edf6ea`) +`FUN_10016a10` (RVA `0x16a10`) читает запись Unit DAT в дерево узлов по +`0x78` байт: перед сырыми полями узла находятся указатель и количество детей, +а байты файла копируются начиная с node `+0x0c`. `FUN_10015290` (RVA +`0x15290`) передаёт каждый непосредственный узел корня в `FUN_10014b90` +(RVA `0x14b90`) с начальным parent ID `0`. + +Для узла с ненулевым raw kind `FUN_10014b90` формирует descriptor размером +`0x4c`: две строки ресурса копируются из node `+0x0c` и `+0x2c`, поле +descriptor `+0x40` получает parent ID, `+0x44` — DWORD node `+0x50`, а +`+0x48` начинается со значения `-1`. Из-за смещения raw-полей на `0x0c` +node `+0x50` — это ровно `parent_or_link` по смещению `0x44` в записи Unit +DAT. Затем `ArealMap` посылает owner-у событие `6 / 0x80000020` через vtable +slot `+0x34`. + +В `AniMesh.dll` (SHA-256 +`65659bf67f20e5be77d67a5b2f59968f61b94293143807fa59ca451c560c4f7e`) +dispatcher `FUN_10001370` (RVA `0x1370`) передаёт это событие в +`FUN_10003760` (RVA `0x3760`). Тот выбирает следующий свободный ID, записывает +его в descriptor `+0x48` и сохраняет descriptor в списке компонентов. +Вернувшись после virtual call, `FUN_10014b90` передаёт этот ID как parent ID +рекурсивного обхода детей. Поэтому родительская связь Control descriptor-а +строится по фактически назначенному ID в обходе дерева, а локальный индекс +устройства приходит из `parent_or_link`. + +У этого обхода есть ранний выход: если raw kind в node `+0x4c` равен нулю, +узел и его дети пропускаются. AniMesh начинает со служебного root ID `0`, но +из-за пропусков и других записей назначенный ID нельзя в общем случае считать +равным индексу узла или номеру его записи в Unit DAT. + +Для registry type `INTO` и других не-`EXTO` значений `FUN_10003760` разрешает +parent ID через Control IID `0x202`, virtual slot `+0x44`, только если parent ID +не равен `-1` и интерфейс IID `0x202` доступен. `Control.dll` +`FUN_1002ecc0` (RVA `0x2ecc0`) возвращает индекс первого устройства, чьё поле +`+0x08` равно этому ID, или `-1`, если совпадения нет; AniMesh прибавляет +возвращённое значение к локальному индексу `+0x44` без отдельной проверки +`-1`. Если parent ID равен `-1` или IID `0x202` недоступен, используется сам +локальный индекс без смещения. Отсутствие устройства с parent ID — отдельный +случай: native path даёт индекс на единицу меньше локального, и Rust-проекции +нужно проверить это поведение явно. `EXTO` проходит отдельную ветвь, поэтому +это правило нельзя распространять на все registry types. + +### Как Control добавляет и переопределяет устройства + +В `Control.dll` (SHA-256 +`bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e`) +`FUN_10008b10` (RVA `0x8b10`) выбирает путь по полю descriptor `+0xc8`. +Значение `-1` запускает цикл по typed records; фабрика `FUN_1002d4b0` (RVA +`0x2d4b0`) создаёт по устройству на запись и сохраняет их порядок. Иное +значение вызывает `FUN_1002d890` (RVA `0x2d890`) только один раз; цикл по +typed-record count в этой ветви отсутствует. Следовательно, подтверждённый +override path применяет первую typed record и не добавляет новый объект. +Так модуль меняет характеристики уже существующего слота, не увеличивая число +устройств. Неизвестный tag в Rust CTLD parser приводит к `Unsupported` и может +оставить typed-record list неполным. Native factory имеет отдельный default +путь `0x20800`, поэтому такой результат парсера сам по себе не доказывает отказ +оригинального loader-а и не позволяет объявить Rust merge полным. + +Для tag `19` фабрика создаёт объект с его исходными классом и vtable. Базовый +конструктор `FUN_100218b0` задаёт multiplier `+0x4c = 1.0`. Override через +`FUN_1002d890` вызывает у выбранного объекта vtable slot `+0x1c`, то есть +`FUN_10021d50` с флагом инициализации `0`. Этот вызов не создаёт объект и не +заменяет класс или vtable. Он сохраняет уже существующий ключ `+0x04`; сохраняет +текущее значение multiplier `+0x4c` (которое могло измениться после +конструктора); и копирует коэффициенты из CTLD в блок `+0x54`. Поле `+0x50` +обновляется лишь когда слово записи `+0x18` не равно `-1`. Сопоставленные +записи значений прибавляются к текущим полям объекта `+0x1c/+0x20`, а не +сбрасывают их. Поэтому «переопределение» здесь означает обновить часть данных +того же устройства, с ограничениями конкретного метода. + +Статический разбор глобального Control interface показывает aggregate getters +`1/2` (`FUN_1002b410`, RVA `0x2b410`) и setter `1` (`FUN_1002ba30`, RVA +`0x2ba30`) для устройств tag `19`. Для конечных значений getter `1` вычисляет +`sum(base * multiplier) / sum(base)`, а getter `2` — `sum(base)`. При встрече +отрицательного base selector `1` сразу возвращает `1.0`, а selector +`2` — этот base. Если подходящих записей нет или сумма base неположительна, +getter возвращает неуспех без записи результата. Setter пишет multiplier `+0x4c` +только устройствам tag `19` с положительным selector-0 значением; пустой набор +возвращает успех. Это вывод статического анализа для конечных входных значений, +без отдельного native execution oracle для глобальных selectors. + +Отдельная ветка того же GOG `AniMesh.dll` показывает, когда создаётся Behavior +для host object. В `FUN_10002ff0` (RVA `0x2ff0`, SHA-256 +`65659bf67f20e5be77d67a5b2f59968f61b94293143807fa59ca451c560c4f7e`) вызывающая +сторона запрашивает IID `0x204` и сохраняет интерфейс в поле `+0x168`. Затем +отдельный импорт `GetQueue()` возвращает объект очереди; вызов метода через его +vtable slot `+0x30` даёт результат, который проверяется на ненулевое значение. +Только при ненулевом результате host class `3` вызывает +`CreateBehaviour(0, 0, self)` (RVA `0x34bd`); class `4` передаёт в +`CreateBehaviour` адреса полей prototype `+0x140` и `+0x160` (RVA `0x3426`). +Семантика метода slot `+0x30` здесь не установлена. Это подтверждает только +такую ветку и эти два класса; другие фабрики, нулевой результат и отложенные +spawn сюда не входят. + +### Один запрос Control для ресурсного устройства + +В CTLD запись tag `26` задаёт ресурсный множитель, но текущее значение +поставщика живёт в runtime state Control. GOG `Control.dll` (SHA-256 +`bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e`) +`FUN_10021d00` (RVA `0x21d00`) реализует getter selector `0x300`. Его фиксированное +слово `+0x2c` становится `fixed_words[11]` при копировании записи RVA `0x21d50`; +`fixed_words[1]` — ключ строки NDP. В объекте Control getter использует ключ +`+0x04`, provider interface `+0x44`, множитель `+0x4c` и коэффициент `+0x54`. +Provider interface направляет selector `1` и ключ в Control RVA `0xdc40`, где +читается текущее type-1 значение выбранной строки. Затем selector умножает +сначала provider на коэффициент, после чего на множитель: `provider * base * +multiplier`. Коэффициент приходит из CTLD; NDP связывает ключ с описанной +строкой, а текущее значение provider нельзя заменить предположением о состоянии +мира. + +Так этот селектор включён в цепочку добычи руды оригинала. В той же сборке +`Behavior.dll` (SHA-256 +`ddfbdbde07832358fe6e35e01c8dba9b58e7313789498b6049ed51d4ed9baf99`) +`FUN_100186b0` (RVA `0x186b0`) перечисляет устройства типа `0x1a`, а +`FUN_100198e0` (RVA `0x198e0`) суммирует успешные запросы IID `0x204` с selector +`0xe00`. В парной `Control.dll` выше `FUN_1002bb40` (RVA `0x2bb40`) для типа +`0x1a` вызывает selector `0x300`, описанный в этом разделе. Затем Behavior query +`0x1002` (RVA `0xa490`) умножает полученную сумму на текущее значение block +`+0x820`, поле `+0x58` `Transfer_Ore_OffBoard` (имя — RVA `0x22e20`, default +5.0 — RVA `0x22d90`; config selector 2 загружает блок через RVA `0x0a1a0`). +Отдельный query `0x1005` (RVA `0xa490`) возвращает поле `+0x60` +`Transfer_Power_Out` (имя — RVA `0x22e20`, default 100.0 — RVA `0x22d90`; +setter — RVA `0xaa40`). Rust helper пока описывает один Control selector `0x300` +при явно переданных входах; он не реализует эту сумму, Behavior-умножение или +подключение к игровому циклу. + +На x87 control word `0x007f` каждое умножение округляет мантиссу до 24 бит, +но промежуточная степень может выйти за диапазон `f32` и вернуться в него при +следующем умножении. Rust helper поэтому принимает явные текущие значения +provider и multiplier, проверяет tag, ключ и строку NDP, сохраняет порядок +операций, но поддерживает только конечные нормализованные значения или ноль на +входе, промежуточном и конечном этапах. Остальные случаи за этим численным +диапазоном он отклоняет; полный x87 accumulator здесь не эмулируется. + +Лицензированный тест на Unit DAT `UNITS/BUILDS/MINE/min_l_n1.dat` проходит через +компонент `fr_l_mine.ctl` и sidecar `fr_l_mine.ndp`: у найденного tag-26 +дескриптора ключ равен `2` из `22` строк, а raw коэффициент — `0x3f800000`. +Тест передаёт helper-у искусственные текущие значения `1.0` только для проверки +записи и привязки ключа; этот Unit DAT не является наблюдением живого Control +tick-а. ### Control system и physical model |
