diff options
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/fparkan-msh/src/lib.rs | 12 | ||||
| -rw-r--r-- | crates/fparkan-runtime/Cargo.toml | 1 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 1572 | ||||
| -rw-r--r-- | crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs | 1084 |
4 files changed, 2651 insertions, 18 deletions
diff --git a/crates/fparkan-msh/src/lib.rs b/crates/fparkan-msh/src/lib.rs index b6459ab..4b561e7 100644 --- a/crates/fparkan-msh/src/lib.rs +++ b/crates/fparkan-msh/src/lib.rs @@ -140,7 +140,10 @@ pub struct Node { /// Raw fields of the standard 38-byte node layout that precede slot selection. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Node38Metadata { - /// Unassigned source link value at byte offset two. + /// Raw Node38 header/flag word at byte offset zero. + pub header_flags: u16, + /// Source-local parent word at byte offset two; `0xFFFF` is the native + /// sentinel before component rebasing. pub parent_or_link_raw: u16, /// Offset into the type-19 frame map, or `0xFFFF` for no map. pub anim_map_start: u16, @@ -431,6 +434,7 @@ pub fn node38_metadata(model: &ModelAsset, node: NodeId) -> Option<Node38Metadat } let offset = node_index.checked_mul(model.node_stride)?; Some(Node38Metadata { + header_flags: read_u16(&model.nodes_raw, offset)?, parent_or_link_raw: read_u16(&model.nodes_raw, offset + 2)?, anim_map_start: read_u16(&model.nodes_raw, offset + 4)?, fallback_key: read_u16(&model.nodes_raw, offset + 6)?, @@ -441,8 +445,8 @@ pub fn node38_metadata(model: &ModelAsset, node: NodeId) -> Option<Node38Metadat /// /// The legacy sampler uses this key when a node has no frame map or its current /// frame falls outside that map. It is a static-pose input only; callers must -/// still recover animation state and the meaning of `parent_or_link_raw` before -/// assembling a runtime hierarchy. Its quaternion is converted to match native +/// assemble the runtime hierarchy separately and apply the component-specific +/// mapping of `parent_or_link_raw`. Its quaternion is converted to match native /// AniMesh's quaternion-to-matrix convention. #[must_use] pub fn node38_fallback_pose(model: &ModelAsset, node: NodeId) -> Option<Pose> { @@ -1412,6 +1416,7 @@ mod tests { #[test] fn standard_node_exposes_fallback_pose_and_unassigned_link() { let mut node = node38([u16::MAX; 15]); + node[0..2].copy_from_slice(&0x8201_u16.to_le_bytes()); node[2..4].copy_from_slice(&7_u16.to_le_bytes()); node[4..6].copy_from_slice(&u16::MAX.to_le_bytes()); node[6..8].copy_from_slice(&0_u16.to_le_bytes()); @@ -1440,6 +1445,7 @@ mod tests { assert_eq!( node38_metadata(&model, NodeId(0)), Some(Node38Metadata { + header_flags: 0x8201, parent_or_link_raw: 7, anim_map_start: u16::MAX, fallback_key: 0, diff --git a/crates/fparkan-runtime/Cargo.toml b/crates/fparkan-runtime/Cargo.toml index ddf09a1..f66551b 100644 --- a/crates/fparkan-runtime/Cargo.toml +++ b/crates/fparkan-runtime/Cargo.toml @@ -7,6 +7,7 @@ repository.workspace = true [dependencies] fparkan-assets = { path = "../fparkan-assets" } +fparkan-msh = { path = "../fparkan-msh" } fparkan-path = { path = "../fparkan-path" } fparkan-platform = { path = "../fparkan-platform" } fparkan-prototype = { path = "../fparkan-prototype" } diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index b4c13df..e74976f 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -13,6 +13,7 @@ use fparkan_assets::{ PreparedControlNodeDataTable, PreparedControlTypedRecord, PreparedVisual, TerrainFormatError, TerrainPreparationError, TerrainWorld, TmaProfile, }; +use fparkan_msh::{node38_metadata, selected_slot, Group, Lod, NodeId}; use fparkan_path::{normalize_relative, NormalizedPath, PathError, PathPolicy}; use fparkan_prototype::{ build_prototype_graph_report, unit_component_tree, PrototypeGraph, PrototypeGraphFailure, @@ -134,9 +135,8 @@ pub struct BehaviorRegisteredObject { pub class_flags: u32, /// Native share field at record offset `+0x04`. pub share: f32, - /// Raw DWORDs at offsets `+0x08..+0x18`; the first controls whether - /// normalization treats this record as fixed, and the remaining words are - /// not yet assigned semantics. A normal native Add initializes all five to 0. + /// Raw DWORDs at offsets `+0x08..+0x18`: fixed-share flag, power demand, + /// power allocation, ore demand, and ore allocation. A native Add zeros them. pub native_tail: [u32; 5], } @@ -211,10 +211,23 @@ pub struct EffectiveControlDevice { pub descriptor_provenance: ControlDeviceRecordProvenance, } +/// Initial Control metadata projected from one node in AniMesh's global table. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct MissionControlNodeInitialMeshState { + /// Parent index in AniMesh's concatenated runtime-node table. + pub parent_index: i32, + /// Node38 header bits translated to the Control row's `+0x28` flags. + pub flags: u32, + /// Effective state count; an empty native state prefix is exposed as one. + pub stage_count: u32, +} + /// Initial row in the loaded global Control node-data provider. /// /// The native table is indexed independently of MSH model nodes. Its rows are /// appended in root/EXTO resource order and begin with a type-1 value of 1.0. +/// Mesh metadata uses the global row ordinal; `None` records that the matching +/// MSH projection was unavailable and does not affect provider queries. #[derive(Clone, Debug, PartialEq)] pub struct MissionControlNodeProviderRow { /// NDP resource that contributed the row. @@ -225,8 +238,16 @@ pub struct MissionControlNodeProviderRow { pub source_row_index: usize, /// Original NDP descriptor fields and provenance for this provider row. pub source_row: PreparedControlNodeDataRow, + /// Shared initial provider amount (`+0x08` and `+0x0c`) as raw bits. + /// + /// Control initializes both fields from the selector-3 result. On the + /// confirmed UnitDAT load path, the two scale factors are 1.0, so this is + /// the NDP row's `max_volume`; later mutations can change both fields. + pub initial_amount_bits: u32, /// Initial native provider selector-1 value (`+0x14`) as raw bits. pub initial_type1_value_bits: u32, + /// MSH state exposed at the same global ordinal, if the mesh projection exists. + pub initial_mesh_state: Option<MissionControlNodeInitialMeshState>, } /// Availability of the initial global Control node-data provider projection. @@ -457,19 +478,20 @@ pub struct MissionScriptBundle { pub package: ScriptPackage, /// Outcome of the restricted first-`Init` resolution for this bundle. pub init_execution: MissionScriptInitExecution, - /// Recovered per-AI Behavior state computed by a full mission startup. + /// Recovered per-AI Behavior scheduler and total state. /// Static previews leave this empty because they do not run script startup. pub behavior_warm_start: Option<BehaviorWarmStartState>, } -/// Initial Behavior distributor fields recovered from the original warm-start path. +/// Behavior distributor clock and totals tracked from warm start through resource ticks. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct BehaviorWarmStartState { - /// Queue-clock value copied to distributor offset `+0x10` when it is zero. + /// Native offset `+0x10`: startup queue time, later replaced by the last due tick time. pub first_time_ms: u32, - /// Initial scheduled time written to distributor offset `+0x14`. + /// Native offset `+0x14`: current deadline, rescheduled after each due tick. pub next_deadline_ms: u32, - /// Opaque distributor words at offsets `+0x30..=+0x40`, cleared on first start. + /// Native totals at offsets `+0x30..=+0x40`: zeroed at startup, then power + /// available, ore available, ore in buffer, power usage, and ore usage. pub cleared_words: [u32; 5], } @@ -490,6 +512,35 @@ impl BehaviorWarmStartState { } } +fn behavior_elapsed_seconds(elapsed_ms: u32) -> f32 { + // The exact integer product is rounded once to f32; scaling by 2^-33 is + // exact and matches native FILD / FMUL / FSTP under the measured control word. + ((u64::from(elapsed_ms) * 0x0083_126f) as f32) * f32::from_bits(0x2f00_0000) +} + +fn schedule_behavior_distributor_tick( + state: &mut BehaviorWarmStartState, + queue_time_ms: u32, + rng_state: &mut u32, +) -> Option<f32> { + if state.first_time_ms == 0 { + let initialized = BehaviorWarmStartState::start(queue_time_ms, rng_state); + state.first_time_ms = initialized.first_time_ms; + state.next_deadline_ms = initialized.next_deadline_ms; + state.cleared_words = [0; 5]; + return None; + } + if state.next_deadline_ms != 0 && queue_time_ms <= state.next_deadline_ms { + return None; + } + + let elapsed_ms = queue_time_ms.wrapping_sub(state.first_time_ms); + let next = BehaviorWarmStartState::start(queue_time_ms, rng_state); + state.first_time_ms = next.first_time_ms; + state.next_deadline_ms = next.next_deadline_ms; + Some(behavior_elapsed_seconds(elapsed_ms)) +} + /// Numeric script defaults selected for the mission's first script bundle. /// /// GOG `ai.dll` first tries `<bundle-base>.var`, then falls back to the shared @@ -833,6 +884,13 @@ pub enum EngineError { /// Entry, field, or format diagnostic. message: String, }, + /// A Behavior resource tick could not resolve a required runtime value. + BehaviorDistributorTick { + /// TMA clan whose distributor could not complete its tick. + clan_index: usize, + /// Unsupported query, property, or arithmetic detail. + message: String, + }, /// World error. World(fparkan_world::WorldError), /// Reference movement input or terrain query failed. @@ -960,6 +1018,10 @@ impl std::fmt::Display for EngineError { entry, message, } => write!(f, "{path}:{entry}: Behavior profile failed: {message}"), + Self::BehaviorDistributorTick { + clan_index, + message, + } => write!(f, "Behavior resource tick for clan {clan_index}: {message}"), Self::World(source) => write!(f, "{source}"), Self::Movement(message) => write!(f, "reference movement: {message}"), Self::RegistrationTeardown { @@ -994,6 +1056,7 @@ impl std::error::Error for EngineError { | Self::Movement(_) | Self::PrototypeGraph { .. } | Self::BehaviorProfile { .. } + | Self::BehaviorDistributorTick { .. } | Self::RegistrationTeardown { .. } => None, } } @@ -1880,6 +1943,100 @@ pub fn query_loaded_mission_behavior_resource( } } +/// Runs due native Behavior resource-distributor ticks against the loaded mission. +/// +/// `queue_time_ms` is an explicit sample from the original wrapping 32-bit +/// queue clock. The method updates the distributor schedule, its five totals, +/// per-object row values, CurrentOre, and supported Control selector-1 state +/// atomically. Preview missions and loaded missions without visible Behavior +/// bundles have no due distributors and return `Ok(0)`. Otherwise it returns +/// the number of distributors whose schedule was due; this includes a due +/// tick with zero elapsed time, which leaves resource rows unchanged. +/// +/// # Errors +/// Returns an error when a live registered object reaches an unsupported +/// Behavior profile, Control query, or property state. On error, all +/// schedules, RNG state, totals, rows, ore values, and Control values remain +/// unchanged. +pub fn advance_loaded_mission_resources( + engine: &mut Engine, + queue_time_ms: u32, +) -> Result<usize, EngineError> { + let Some(loaded) = engine.loaded.as_ref() else { + return Ok(0); + }; + + let mut distributors = loaded.behavior_distributors.clone(); + let mut ore_states = loaded.behavior_ore_states.clone(); + let mut control_tables = loaded.control_device_tables.clone(); + let mut warm_starts = loaded + .script_bundles + .iter() + .map(|bundle| bundle.behavior_warm_start) + .collect::<Vec<_>>(); + let profiles = &loaded.behavior_profiles; + let world = &engine.world; + let mut rng_state = engine.behavior_rng_state; + let mut scheduled_ticks = 0; + + for distributor in distributors.iter_mut() { + if !distributor.super_ai_visible { + continue; + } + let bundle_index = loaded + .script_bundles + .iter() + .position(|bundle| bundle.clan_index == distributor.clan_index) + .ok_or_else(|| EngineError::BehaviorDistributorTick { + clan_index: distributor.clan_index, + message: "visible distributor has no matching script bundle".to_string(), + })?; + let Some(schedule) = warm_starts.get_mut(bundle_index).and_then(Option::as_mut) else { + return Err(EngineError::BehaviorDistributorTick { + clan_index: distributor.clan_index, + message: "visible distributor has no warm-start schedule".to_string(), + }); + }; + + let delta_seconds = + schedule_behavior_distributor_tick(schedule, queue_time_ms, &mut rng_state); + let Some(delta_seconds) = delta_seconds else { + continue; + }; + scheduled_ticks += 1; + if delta_seconds == 0.0 { + continue; + } + + let totals = advance_behavior_distributor_tick( + distributor, + delta_seconds, + world, + &mut ore_states, + profiles, + &mut control_tables, + ) + .map_err(|message| EngineError::BehaviorDistributorTick { + clan_index: distributor.clan_index, + message, + })?; + schedule.cleared_words = totals; + } + + let loaded = engine + .loaded + .as_mut() + .expect("loaded mission was checked above"); + loaded.behavior_distributors = distributors; + loaded.behavior_ore_states = ore_states; + loaded.control_device_tables = control_tables; + for (bundle, warm_start) in loaded.script_bundles.iter_mut().zip(warm_starts) { + bundle.behavior_warm_start = warm_start; + } + engine.behavior_rng_state = rng_state; + Ok(scheduled_ticks) +} + /// Sets native Control global-table selector 1 on rows whose selector-0 value /// is positive. Validation is completed before any row is changed. /// @@ -2059,6 +2216,387 @@ fn query_behavior_profile_ore_rate( ) } +#[derive(Clone, Copy, Default)] +struct BehaviorTickTotals { + power_available: f32, + ore_available: f32, + power_weighted_demand: f32, + power_demand: f32, + ore_weighted_demand: f32, + ore_demand: f32, + ore_in_buffer: f32, +} + +#[derive(Clone, Copy, Default)] +struct BehaviorAllocation { + priority: f32, + residual: f32, + consumption: f32, +} + +fn behavior_difference(lhs: f32, rhs: f32, field: &'static str) -> Result<f32, String> { + let range_probe = f64::from(lhs) - f64::from(rhs); + check_control_range_probe(None, field, range_probe).map_err(|error| format!("{error:?}"))?; + checked_control_float(0, field, lhs - rhs).map_err(|error| format!("{error:?}")) +} + +fn behavior_product(lhs: f32, rhs: f32, field: &'static str) -> Result<f32, String> { + checked_control_product(0, field, lhs, rhs).map_err(|error| format!("{error:?}")) +} + +fn behavior_allocation( + available: f32, + demand: f32, + weighted_demand: f32, +) -> Result<BehaviorAllocation, String> { + if available <= 0.0 || demand <= 0.0 { + Ok(BehaviorAllocation::default()) + } else if available <= weighted_demand { + Ok(BehaviorAllocation { + priority: checked_control_ratio("priority allocation", available, weighted_demand) + .map_err(|error| format!("{error:?}"))?, + residual: 0.0, + consumption: 1.0, + }) + } else if available < demand { + let residual_available = + behavior_difference(available, weighted_demand, "residual available")?; + let residual_demand = behavior_difference(demand, weighted_demand, "residual demand")?; + Ok(BehaviorAllocation { + priority: 1.0, + residual: checked_control_ratio( + "residual allocation", + residual_available, + residual_demand, + ) + .map_err(|error| format!("{error:?}"))?, + consumption: 1.0, + }) + } else { + Ok(BehaviorAllocation { + priority: 1.0, + residual: 1.0, + consumption: checked_control_ratio("source consumption", demand, available) + .map_err(|error| format!("{error:?}"))?, + }) + } +} + +fn behavior_add_total(total: &mut f32, value: f32, field: &'static str) -> Result<(), String> { + *total = checked_control_sum(0, field, *total, value).map_err(|error| format!("{error:?}"))?; + Ok(()) +} + +fn behavior_profile_for_handle<'a>( + profiles: &'a [BehaviorProfileState], + handle: ObjectHandle, +) -> Result<&'a BehaviorProfileState, String> { + profiles + .iter() + .find(|profile| profile.handle == handle) + .ok_or_else(|| format!("Behavior profile for object {handle:?} is unavailable")) +} + +fn behavior_ore_index_for_handle( + ore_states: &[BehaviorOreState], + handle: ObjectHandle, +) -> Result<usize, String> { + ore_states + .iter() + .position(|state| state.handle == handle) + .ok_or_else(|| format!("CurrentOre property for object {handle:?} is unavailable")) +} + +fn behavior_control_index_for_handle( + control_tables: &[MissionControlDeviceTableState], + handle: ObjectHandle, +) -> Result<usize, String> { + let index = control_tables + .iter() + .position(|table| table.handle == handle) + .ok_or_else(|| format!("Control interface for object {handle:?} is unavailable"))?; + match &control_tables[index].status { + MissionControlDeviceTableStatus::Available(_) => Ok(index), + MissionControlDeviceTableStatus::Unavailable(reason) => Err(format!( + "Control interface for object {handle:?} is unresolved: {reason:?}" + )), + } +} + +fn behavior_checked_property(state: &BehaviorOreState, maximum: bool) -> Result<f32, String> { + let (field, bits) = if maximum { + ("MaximumOre", state.maximum_ore_bits) + } else { + ("CurrentOre", state.current_ore_bits) + }; + checked_control_float(state.class_flags, field, f32::from_bits(bits)) + .map_err(|error| format!("{error:?}")) +} + +fn behavior_tick_resource_rate( + class_flags: u32, + handle: ObjectHandle, + selector: u32, + profiles: &[BehaviorProfileState], + control_tables: &[MissionControlDeviceTableState], +) -> Result<f32, String> { + let profile = behavior_profile_for_handle(profiles, handle)?; + match selector { + 0x1005 => checked_control_float( + class_flags, + "Transfer_Power_Out", + f32::from_bits(profile.transfer_power_out_bits), + ) + .map_err(|error| format!("{error:?}")), + 0x1002 => { + let table_index = behavior_control_index_for_handle(control_tables, handle)?; + query_behavior_profile_ore_rate( + &control_tables[table_index], + profile.transfer_ore_off_board_bits, + ) + .map_err(|error| format!("{error:?}")) + } + _ => Err(format!( + "unsupported Behavior resource selector {selector:#x}" + )), + } +} + +fn behavior_query_control( + control_tables: &[MissionControlDeviceTableState], + handle: ObjectHandle, + selector: u32, +) -> Result<f32, String> { + let table_index = behavior_control_index_for_handle(control_tables, handle)?; + query_control_device_table_resource(&control_tables[table_index], selector) + .map(|value| value.unwrap_or(0.0)) + .map_err(|error| format!("{error:?}")) +} + +fn advance_behavior_distributor_tick( + distributor: &mut BehaviorDistributorState, + delta_seconds: f32, + world: &World, + ore_states: &mut [BehaviorOreState], + profiles: &[BehaviorProfileState], + control_tables: &mut [MissionControlDeviceTableState], +) -> Result<[u32; 5], String> { + let mut totals = BehaviorTickTotals::default(); + + // Native pass one measures supply and demand, then records per-row demand. + for object in &mut distributor.registered_objects { + let Some(live_handle) = handle_by_original_id(world, object.original_id) else { + object.native_tail[1] = 0; + object.native_tail[3] = 0; + continue; + }; + if live_handle != object.handle { + return Err(format!( + "live original object {} maps to {live_handle:?}, expected {:?}", + object.original_id.0, object.handle + )); + } + let share = checked_control_float(object.class_flags, "Behavior share", object.share) + .map_err(|error| format!("{error:?}"))?; + + let power_source = matches!( + object.class_flags, + 0x8000_0002 | 0x8001_0000 | 0x8002_0000 | 0x8004_0000 + ); + let power_demand = if power_source { + let rate = behavior_tick_resource_rate( + object.class_flags, + live_handle, + 0x1005, + profiles, + control_tables, + )?; + let production = behavior_product(delta_seconds, rate, "power production")?; + behavior_add_total(&mut totals.power_available, production, "power available")?; + 0.0 + } else { + let total_power = behavior_query_control(control_tables, live_handle, 2)?; + let power_ratio = behavior_query_control(control_tables, live_handle, 1)?; + if total_power > 0.0 { + let used_power = behavior_product(power_ratio, total_power, "used power")?; + behavior_difference(total_power, used_power, "power demand")? + } else { + 0.0 + } + }; + object.native_tail[1] = power_demand.to_bits(); + behavior_add_total(&mut totals.power_demand, power_demand, "power demand")?; + behavior_add_total( + &mut totals.power_weighted_demand, + behavior_product(power_demand, share, "weighted power demand")?, + "weighted power demand", + )?; + + let ore_source = matches!(object.class_flags, 0x8000_0004 | 0x8000_0008); + let ore_index = behavior_ore_index_for_handle(ore_states, live_handle)?; + let current = behavior_checked_property(&ore_states[ore_index], false)?; + let ore_demand = if ore_source { + let rate = behavior_tick_resource_rate( + object.class_flags, + live_handle, + 0x1002, + profiles, + control_tables, + )?; + let production = behavior_product(delta_seconds, rate, "ore production")?; + let available = if current < production { + current + } else { + production + }; + behavior_add_total(&mut totals.ore_available, available, "ore available")?; + behavior_add_total(&mut totals.ore_in_buffer, current, "ore in buffer")?; + 0.0 + } else { + let maximum = behavior_checked_property(&ore_states[ore_index], true)?; + let deficit = behavior_difference(maximum, current, "ore deficit")?; + if deficit >= f32::from_bits(0x3c23_d70a) { + deficit + } else { + ore_states[ore_index].current_ore_bits = maximum.to_bits(); + 0.0 + } + }; + object.native_tail[3] = ore_demand.to_bits(); + behavior_add_total(&mut totals.ore_demand, ore_demand, "ore demand")?; + behavior_add_total( + &mut totals.ore_weighted_demand, + behavior_product(ore_demand, share, "weighted ore demand")?, + "weighted ore demand", + )?; + } + + let power_allocation = behavior_allocation( + totals.power_available, + totals.power_demand, + totals.power_weighted_demand, + )?; + let ore_allocation = behavior_allocation( + totals.ore_available, + totals.ore_demand, + totals.ore_weighted_demand, + )?; + + // Native pass two re-reads callbacks before applying each row in order. + for object in &mut distributor.registered_objects { + let Some(live_handle) = handle_by_original_id(world, object.original_id) else { + object.native_tail[2] = 0; + object.native_tail[4] = 0; + continue; + }; + if live_handle != object.handle { + return Err(format!( + "live original object {} maps to {live_handle:?}, expected {:?}", + object.original_id.0, object.handle + )); + } + object.native_tail[2] = 0; + object.native_tail[4] = 0; + + let power_source = matches!( + object.class_flags, + 0x8000_0002 | 0x8001_0000 | 0x8002_0000 | 0x8004_0000 + ); + if power_source { + let table_index = behavior_control_index_for_handle(control_tables, live_handle)?; + set_control_device_table_multiplier(&mut control_tables[table_index], 1.0) + .map_err(|error| format!("{error:?}"))?; + } else { + let table_index = behavior_control_index_for_handle(control_tables, live_handle)?; + let total_power = behavior_query_control(control_tables, live_handle, 2)?; + if total_power > 0.0 { + let power_ratio = behavior_query_control(control_tables, live_handle, 1)?; + let used_power = behavior_product(power_ratio, total_power, "used power")?; + let demand = behavior_difference(total_power, used_power, "power demand")?; + let share = object.share; + let priority_share = + behavior_product(share, power_allocation.priority, "priority power share")?; + let residual_share = behavior_product( + behavior_difference(1.0, share, "remaining share")?, + power_allocation.residual, + "residual power share", + )?; + let fraction = checked_control_sum( + 0, + "power allocation fraction", + residual_share, + priority_share, + ) + .map_err(|error| format!("{error:?}"))?; + let allocated = behavior_product(demand, fraction, "power allocation")?; + let updated = + checked_control_sum(0, "used plus allocated power", used_power, allocated) + .map_err(|error| format!("{error:?}"))?; + let new_ratio = + checked_control_ratio("new Control selector 1", updated, total_power) + .map_err(|error| format!("{error:?}"))?; + set_control_device_table_multiplier(&mut control_tables[table_index], new_ratio) + .map_err(|error| format!("{error:?}"))?; + object.native_tail[2] = allocated.to_bits(); + } + } + + let ore_source = matches!(object.class_flags, 0x8000_0004 | 0x8000_0008); + let ore_index = behavior_ore_index_for_handle(ore_states, live_handle)?; + let current = behavior_checked_property(&ore_states[ore_index], false)?; + if ore_source { + let rate = behavior_tick_resource_rate( + object.class_flags, + live_handle, + 0x1002, + profiles, + control_tables, + )?; + let production = behavior_product(delta_seconds, rate, "ore withdrawal rate")?; + let bounded_production = if current < production { + current + } else { + production + }; + let taken = behavior_product( + bounded_production, + ore_allocation.consumption, + "ore withdrawal", + )?; + ore_states[ore_index].current_ore_bits = + behavior_difference(current, taken, "remaining ore")?.to_bits(); + } else { + let maximum = behavior_checked_property(&ore_states[ore_index], true)?; + let capacity = behavior_difference(maximum, current, "ore capacity")?; + let share = object.share; + let priority_share = + behavior_product(share, ore_allocation.priority, "priority ore share")?; + let residual_share = behavior_product( + behavior_difference(1.0, share, "remaining share")?, + ore_allocation.residual, + "residual ore share", + )?; + let fraction = + checked_control_sum(0, "ore allocation fraction", residual_share, priority_share) + .map_err(|error| format!("{error:?}"))?; + let allocated = behavior_product(capacity, fraction, "ore allocation")?; + ore_states[ore_index].current_ore_bits = + checked_control_sum(0, "current plus allocated ore", current, allocated) + .map_err(|error| format!("{error:?}"))? + .to_bits(); + object.native_tail[4] = allocated.to_bits(); + } + } + + Ok([ + totals.power_available.to_bits(), + totals.ore_available.to_bits(), + totals.ore_in_buffer.to_bits(), + totals.power_demand.to_bits(), + totals.ore_demand.to_bits(), + ]) +} + fn set_control_device_table_multiplier( table: &mut MissionControlDeviceTableState, value: f32, @@ -2740,6 +3278,57 @@ fn build_control_device_projection( } } + let mut global_mesh_states = Vec::new(); + let mut global_node_cursor = 0_usize; + for component_index in active_components.iter().copied() { + let prototype = + prototype_for(component_index).ok_or(Unavailable::ComponentAlignmentMismatch)?; + let is_root = component_index == 0; + let is_ex_to = !is_root && prototype.source_type == Some(PROTOTYPE_TYPE_EXTO); + if !is_root && !is_ex_to { + continue; + } + + let visual = object_visuals + .get(component_index) + .and_then(|visual_id| assets.visual_by_id(*visual_id)); + let node_count = visual.map_or(0, |visual| visual.model_nodes); + let model = visual + .and_then(|visual| visual.model_id) + .and_then(|model_id| assets.model_by_id(model_id)); + let parent_base = if is_ex_to { + i32::try_from(global_node_cursor) + .ok() + .and_then(|count| count.checked_sub(1)) + .ok_or(Unavailable::UnsupportedExToNodeMapping { + unit_component_index: component_index, + })? + } else { + 0 + }; + let mount_node = if is_root { + Some(0) + } else { + native_component_mount_node( + &tree, + &component_ids, + &first_global_nodes, + component_index, + draft.unit_components[component_index].parent_or_link, + ) + }; + let first_source_node = usize::from(is_ex_to); + for source_node_index in first_source_node..node_count { + global_mesh_states.push(model.and_then(|model| { + initial_control_mesh_state(model, source_node_index, parent_base, mount_node) + })); + } + let contribution = node_count.saturating_sub(first_source_node); + global_node_cursor = global_node_cursor + .checked_add(contribution) + .ok_or(Unavailable::ComponentAlignmentMismatch)?; + } + let mut devices = Vec::new(); let mut node_provider_status = MissionControlNodeProviderTableStatus::Available(Vec::new()); let mut has_control_resource = false; @@ -2896,6 +3485,9 @@ fn build_control_device_projection( if !has_control_resource { return Err(Unavailable::NoControlResource); } + if let MissionControlNodeProviderTableStatus::Available(rows) = &mut node_provider_status { + attach_initial_mesh_states_by_global_ordinal(rows, &global_mesh_states); + } Ok(ControlDeviceProjection { devices, node_provider_status, @@ -2936,11 +3528,76 @@ fn append_control_node_provider_rows( unit_component_index, source_row_index, source_row: source_row.clone(), + initial_amount_bits: source_row.max_volume.to_bits(), initial_type1_value_bits: 0x3f80_0000, + initial_mesh_state: None, }); } } +fn control_flags_from_node38_header(header_flags: u16) -> u32 { + let mut flags = 0; + if header_flags & 0x0200 != 0 { + flags |= 0x01; + } + if header_flags & 0x0100 != 0 { + flags |= 0x02; + } + if header_flags & 0x0400 != 0 { + flags |= 0x04; + } + if header_flags & 0x0001 != 0 && header_flags & 0x0080 == 0 { + flags |= 0x08; + } + flags +} + +fn native_mesh_parent_index( + parent_or_link_raw: u16, + parent_base: i32, + mount_node: Option<u32>, +) -> Option<i32> { + if parent_or_link_raw == 0 { + i32::try_from(mount_node?).ok() + } else { + let relative_parent = if parent_or_link_raw == u16::MAX { + -1 + } else { + i32::from(parent_or_link_raw) + }; + parent_base.checked_add(relative_parent) + } +} + +fn initial_control_mesh_state( + model: &fparkan_assets::PreparedModel, + source_node_index: usize, + parent_base: i32, + mount_node: Option<u32>, +) -> Option<MissionControlNodeInitialMeshState> { + let node_index = u32::try_from(source_node_index).ok()?; + let node = node38_metadata(&model.validated, NodeId(node_index))?; + let stage_prefix = (0..3_u8) + .take_while(|state| { + selected_slot(&model.validated, NodeId(node_index), Lod(*state), Group(0)).is_some() + }) + .count(); + Some(MissionControlNodeInitialMeshState { + parent_index: native_mesh_parent_index(node.parent_or_link_raw, parent_base, mount_node)?, + flags: control_flags_from_node38_header(node.header_flags), + stage_count: u32::try_from(stage_prefix.max(1)).ok()?, + }) +} + +fn attach_initial_mesh_states_by_global_ordinal( + provider_rows: &mut [MissionControlNodeProviderRow], + global_mesh_states: &[Option<MissionControlNodeInitialMeshState>], +) { + for (ordinal, row) in provider_rows.iter_mut().enumerate() { + row.initial_mesh_state = global_mesh_states.get(ordinal).copied().flatten(); + } +} + fn add_behavior_registered_object( distributor: &mut BehaviorDistributorState, mut object: BehaviorRegisteredObject, @@ -3432,10 +4089,78 @@ mod tests { name: [0; 32], }, }, + initial_amount_bits: 100.0_f32.to_bits(), initial_type1_value_bits, + initial_mesh_state: None, } } + fn synthetic_node38( + header_flags: u16, + parent_or_link: u16, + group0_states: [bool; 3], + ) -> [u8; 38] { + let mut node = [0xff; 38]; + node[0..2].copy_from_slice(&header_flags.to_le_bytes()); + node[2..4].copy_from_slice(&parent_or_link.to_le_bytes()); + node[4..6].copy_from_slice(&u16::MAX.to_le_bytes()); + node[6..8].copy_from_slice(&0_u16.to_le_bytes()); + for (state, present) in group0_states.into_iter().enumerate() { + let slot = if present { 0_u16 } else { u16::MAX }; + let offset = 8 + state * 10; + node[offset..offset + 2].copy_from_slice(&slot.to_le_bytes()); + } + node + } + + fn synthetic_model_asset(nodes: &[[u8; 38]]) -> fparkan_msh::ModelAsset { + let mut nodes_raw = Vec::with_capacity(nodes.len() * 38); + for node in nodes { + nodes_raw.extend_from_slice(node); + } + fparkan_msh::ModelAsset { + node_stride: 38, + node_count: nodes.len(), + nodes_raw, + bounding_sphere_center: [0.0; 3], + bounding_sphere_radius: 0.0, + slots: vec![fparkan_msh::Slot { + tri_start: 0, + tri_count: 0, + batch_start: 0, + batch_count: 0, + aabb_min: [0.0; 3], + aabb_max: [0.0; 3], + sphere_center: [0.0; 3], + sphere_radius: 0.0, + opaque: [0; 5], + }], + positions: Vec::new(), + normals: None, + uv0: None, + uv1: None, + indices: Vec::new(), + batches: Vec::new(), + node_names: None, + animation: None, + } + } + + fn attach_synthetic_model( + assets: &mut MissionAssets, + component_index: usize, + nodes: &[[u8; 38]], + ) { + let model_id = AssetId::<fparkan_assets::PreparedModel>::new(100 + component_index as u64); + assets.visuals[component_index].model_id = Some(model_id); + assets.models.push(fparkan_assets::PreparedModel { + id: model_id, + source: synthetic_resource_key(500 + component_index), + validated: synthetic_model_asset(nodes), + mesh_dependencies: Vec::new(), + }); + } + fn synthetic_control_fixture( source_types: &[Option<u32>], kinds: &[u32], @@ -4272,6 +4997,79 @@ mod tests { } #[test] + fn behavior_elapsed_seconds_preserve_native_qword_conversion_rounding() { + let vectors = [ + (1, 0x3a83_126f), + (1_001, 0x3f80_20c5), + (16_777_217, 0x4683_1270), + (16_777_219, 0x4683_1271), + (u32::MAX, 0x4a83_126f), + (u32::MAX - 1, 0x4a83_126f), + ]; + for (elapsed_ms, expected_bits) in vectors { + assert_eq!( + behavior_elapsed_seconds(elapsed_ms).to_bits(), + expected_bits, + "elapsed={elapsed_ms}" + ); + } + } + + #[test] + fn behavior_distributor_scheduler_requires_a_strictly_later_unsigned_time() { + let original = BehaviorWarmStartState { + first_time_ms: 100, + next_deadline_ms: 200, + cleared_words: [0x11; 5], + }; + let mut state = original; + let mut rng_state = 1; + + assert_eq!( + schedule_behavior_distributor_tick(&mut state, 200, &mut rng_state), + None + ); + assert_eq!(state, original); + assert_eq!(rng_state, 1); + + let elapsed = schedule_behavior_distributor_tick(&mut state, 201, &mut rng_state) + .expect("deadline is passed"); + assert_eq!(elapsed.to_bits(), behavior_elapsed_seconds(101).to_bits()); + assert_eq!(state.first_time_ms, 201); + assert_eq!(state.next_deadline_ms, 403); + assert_eq!(state.cleared_words, [0x11; 5]); + assert_eq!(rng_state, 0x0029_e2c0); + } + + #[test] + fn behavior_distributor_scheduler_wraps_elapsed_but_keeps_unsigned_deadline_order() { + let mut state = BehaviorWarmStartState { + first_time_ms: u32::MAX - 15, + next_deadline_ms: 5, + cleared_words: [0; 5], + }; + let mut rng_state = 1; + + assert_eq!( + schedule_behavior_distributor_tick(&mut state, 5, &mut rng_state), + None + ); + assert_eq!(state.next_deadline_ms, 5); + let elapsed = schedule_behavior_distributor_tick(&mut state, 6, &mut rng_state) + .expect("current time is unsigned-greater than deadline"); + assert_eq!(elapsed.to_bits(), behavior_elapsed_seconds(22).to_bits()); + assert_eq!(state.first_time_ms, 6); + + let before = state; + assert_eq!( + schedule_behavior_distributor_tick(&mut state, 1, &mut rng_state), + None, + "unsigned 1 is not strictly later than the current deadline" + ); + assert_eq!(state, before); + } + + #[test] fn mission_script_start_stops_before_warming_later_bundles() { fn push_u32(bytes: &mut Vec<u8>, value: u32) { bytes.extend_from_slice(&value.to_le_bytes()); @@ -4626,6 +5424,155 @@ mod tests { } #[test] + fn synthetic_node_provider_projection_joins_flat_mesh_metadata_by_global_ordinal() { + let mut controls = vec![ + Some(control_with_synthetic_node_data(0, Vec::new(), 3)), + Some(control_with_synthetic_node_data(1, Vec::new(), 3)), + ]; + controls[0] + .as_mut() + .expect("root component control") + .node_data + .as_mut() + .expect("root NDP") + .rows[0] + .max_volume = 0.0; + let (draft, mut assets, prototypes) = synthetic_control_fixture( + // Even if the root's registry prototype is typed EXTO, its model + // contributes every source node; only mounted EXTO rows skip node 0. + &[Some(PROTOTYPE_TYPE_EXTO), Some(PROTOTYPE_TYPE_EXTO)], + &[1, 1], + &[1, 0], + &[0, 1], + &[2, 3], + controls, + ); + attach_synthetic_model( + &mut assets, + 0, + &[ + synthetic_node38(0x0701, 0xffff, [true, true, false]), + synthetic_node38(0x0081, 0, [false, true, true]), + ], + ); + attach_synthetic_model( + &mut assets, + 1, + &[ + synthetic_node38(0, 0xffff, [true, false, false]), + synthetic_node38(0x0200, 0, [true, false, true]), + synthetic_node38(0x0400, 0xffff, [true, true, true]), + ], + ); + + let projection = build_control_device_projection( + 0, + &draft, + &assets, + Some(&(0..prototypes.len())), + &prototypes, + ) + .expect("synthetic Control projection"); + let MissionControlNodeProviderTableStatus::Available(rows) = + projection.node_provider_status + else { + panic!("synthetic provider rows should be available"); + }; + + assert_eq!(rows.len(), 5); + assert_eq!( + rows.iter() + .map(|row| (row.unit_component_index, row.source_row_index)) + .collect::<Vec<_>>(), + [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2)] + ); + assert_eq!( + rows.iter() + .map(|row| row.initial_mesh_state) + .collect::<Vec<_>>(), + [ + Some(MissionControlNodeInitialMeshState { + parent_index: -1, + flags: 0x0f, + stage_count: 2, + }), + Some(MissionControlNodeInitialMeshState { + parent_index: 0, + flags: 0, + stage_count: 1, + }), + // This row is still from the root NDP. The native global + // ordinal has moved on to the first non-root EXTO mesh node. + Some(MissionControlNodeInitialMeshState { + parent_index: 1, + flags: 1, + stage_count: 1, + }), + Some(MissionControlNodeInitialMeshState { + parent_index: 0, + flags: 4, + stage_count: 3, + }), + None, + ] + ); + assert!(rows[..4].iter().all(|row| row.initial_mesh_state.is_some())); + assert_eq!( + rows.iter() + .map(|row| row.initial_amount_bits) + .collect::<Vec<_>>(), + [ + 0.0_f32.to_bits(), + 101.0_f32.to_bits(), + 102.0_f32.to_bits(), + 101.0_f32.to_bits(), + 102.0_f32.to_bits(), + ] + ); + assert_eq!(rows[0].initial_type1_value_bits, 1.0_f32.to_bits()); + } + + #[test] + fn missing_initial_mesh_metadata_keeps_provider_query_available() { + let mut device = synthetic_effective_control_device( + 26, + 26, + 2.0_f32.to_bits(), + Some(3.0_f32.to_bits()), + None, + ); + device.key = 0; + device.descriptor.fixed_words[1] = 0; + let provider = synthetic_node_provider_row(0, 0, 2.0_f32.to_bits()); + assert_eq!(provider.initial_mesh_state, None); + let table = synthetic_control_device_table_with_providers( + MissionControlDeviceTableStatus::Available(vec![device]), + MissionControlNodeProviderTableStatus::Available(vec![provider]), + ); + + assert_eq!( + query_control_device_table_selector(&table, 0, 0xe00) + .expect("NDP query remains independent of the MSH projection"), + Some(12.0) + ); + } + + #[test] + fn native_mesh_metadata_maps_control_flags_and_parent_words() { + assert_eq!(control_flags_from_node38_header(0x0701), 0x0f); + assert_eq!(control_flags_from_node38_header(0x0781), 0x07); + + assert_eq!(native_mesh_parent_index(0xffff, 0, None), Some(-1)); + assert_eq!(native_mesh_parent_index(0, 0, Some(0)), Some(0)); + assert_eq!(native_mesh_parent_index(0xffff, 21, None), Some(20)); + assert_eq!(native_mesh_parent_index(1, 21, None), Some(22)); + assert_eq!(native_mesh_parent_index(0xfffe, 21, None), Some(65_555)); + assert_eq!(native_mesh_parent_index(0x8000, 21, None), Some(32_789)); + assert_eq!(native_mesh_parent_index(0, 21, Some(7)), Some(7)); + assert_eq!(native_mesh_parent_index(0, 21, None), None); + } + + #[test] fn missing_node_provider_does_not_hide_aggregate_queries() { let controls = vec![Some(synthetic_component_control( 0, @@ -5178,6 +6125,128 @@ mod tests { assert_eq!(root_node_data.rows.len(), 22); assert_eq!(ext_node_data.rows.len(), 4); assert_eq!(provider_rows.len(), 25); + assert_eq!(provider_rows[0].initial_amount_bits, 1.0_f32.to_bits()); + assert_eq!(provider_rows[22].initial_amount_bits, 6000.0_f32.to_bits()); + assert_eq!( + provider_rows[0].initial_amount_bits, + provider_rows[0].source_row.max_volume.to_bits() + ); + assert_eq!( + provider_rows[22].initial_amount_bits, + provider_rows[22].source_row.max_volume.to_bits() + ); + let mission_assets = &engine + .loaded + .as_ref() + .expect("loaded mission state") + .mission_assets; + let visual_root_node_count = mission_assets + .visual_by_id(mission_assets.object_visuals[0][0]) + .expect("root visual") + .model_nodes; + assert_eq!(visual_root_node_count, 22); + let assert_mesh_node = + |component_index: usize, + source_node_index: usize, + expected_header: u16, + expected_parent: u16, + expected_slots: [u16; 15], + expected_state: MissionControlNodeInitialMeshState| { + let visual_id = mission_assets.object_visuals[0][component_index]; + let visual = mission_assets + .visual_by_id(visual_id) + .expect("component visual"); + let model = mission_assets + .model_by_id(visual.model_id.expect("component model")) + .expect("prepared model"); + let offset = source_node_index * model.validated.node_stride; + let raw_flags = u16::from_le_bytes( + model.validated.nodes_raw[offset..offset + 2] + .try_into() + .expect("raw header flags"), + ); + let raw_parent = u16::from_le_bytes( + model.validated.nodes_raw[offset + 2..offset + 4] + .try_into() + .expect("raw parent"), + ); + let raw_slots = std::array::from_fn::<_, 15, _>(|slot| { + u16::from_le_bytes( + model.validated.nodes_raw[offset + 8 + slot * 2..offset + 10 + slot * 2] + .try_into() + .expect("raw slot word"), + ) + }); + let global_index = if component_index == 0 { + source_node_index + } else { + visual_root_node_count + source_node_index - 1 + }; + assert_eq!(raw_flags, expected_header); + assert_eq!(raw_parent, expected_parent); + assert_eq!(raw_slots, expected_slots); + assert_eq!( + provider_rows[global_index].initial_mesh_state, + Some(expected_state) + ); + }; + assert_mesh_node( + 0, + 0, + 0x0000, + 0xffff, + [0xffff; 15], + MissionControlNodeInitialMeshState { + parent_index: -1, + flags: 0, + stage_count: 1, + }, + ); + assert_mesh_node( + 0, + 1, + 0x0110, + 0x0000, + [ + 0x000b, 0x0025, 0x0026, 0xffff, 0xffff, 0x0013, 0x0027, 0x0028, 0xffff, 0xffff, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + ], + MissionControlNodeInitialMeshState { + parent_index: 0, + flags: 2, + stage_count: 2, + }, + ); + assert_mesh_node( + 5, + 1, + 0x0000, + 0x0000, + [ + 0x0000, 0x0001, 0x0002, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + ], + MissionControlNodeInitialMeshState { + parent_index: 9, + flags: 0, + stage_count: 1, + }, + ); + assert_mesh_node( + 5, + 2, + 0x0010, + 0x0001, + [ + 0x0004, 0x0007, 0x0008, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + ], + MissionControlNodeInitialMeshState { + parent_index: 22, + flags: 0, + stage_count: 1, + }, + ); let expected_provider_sources = (0..root_node_data.rows.len()) .map(|row| (0, row)) .chain((1..ext_node_data.rows.len()).map(|row| (5, row))) @@ -5192,6 +6261,9 @@ mod tests { assert!(provider_rows .iter() .all(|row| row.initial_type1_value_bits == 1.0_f32.to_bits())); + assert!(provider_rows + .iter() + .all(|row| row.initial_mesh_state.is_some())); assert_eq!( ( entries[9].factory_tag, @@ -5837,6 +6909,259 @@ mod tests { ); } + #[test] + #[ignore = "requires licensed corpus"] + fn licensed_autodemo_resource_ticks_use_queue_time_and_real_generator_profile() { + let root = licensed_root("IS"); + let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(root)); + let mut engine = create(EngineServices::new(vfs)).expect("engine"); + load_mission( + &mut engine, + MissionRequest { + key: "MISSIONS/Autodemo.00/data.tma".to_string(), + mode: MissionMode::AutoDemo, + }, + 100_000, + ) + .expect("load licensed AutoDemo"); + + let deadlines = loaded_mission_script_bundles(&engine) + .expect("script bundles") + .iter() + .map(|bundle| { + ( + bundle.clan_index, + bundle + .behavior_warm_start + .expect("full load warm-start") + .next_deadline_ms, + ) + }) + .collect::<Vec<_>>(); + assert_eq!(deadlines, [(0, 100_202), (1, 100_200)]); + assert_eq!( + advance_loaded_mission_resources(&mut engine, 100_000) + .expect("no due resource tick at warm start"), + 0 + ); + assert_eq!( + advance_loaded_mission_resources(&mut engine, 100_200) + .expect("strict deadline equality is not due"), + 0 + ); + + assert_eq!( + advance_loaded_mission_resources(&mut engine, 100_201).expect("clan 1 resource tick"), + 1 + ); + let first_totals = loaded_mission_script_bundles(&engine) + .expect("bundles after first tick") + .iter() + .find(|bundle| bundle.clan_index == 1) + .and_then(|bundle| bundle.behavior_warm_start) + .expect("clan 1 scheduler") + .cleared_words; + assert!( + f32::from_bits(first_totals[0]) > 0.0, + "clan 1's real prof_generator.var contributes power" + ); + assert_eq!( + advance_loaded_mission_resources(&mut engine, 100_202) + .expect("clan 0 deadline equality is not due"), + 0 + ); + + assert_eq!( + advance_loaded_mission_resources(&mut engine, 100_203).expect("clan 0 resource tick"), + 1 + ); + let second_totals = loaded_mission_script_bundles(&engine) + .expect("bundles after second tick") + .iter() + .find(|bundle| bundle.clan_index == 0) + .and_then(|bundle| bundle.behavior_warm_start) + .expect("clan 0 scheduler") + .cleared_words; + assert!( + f32::from_bits(second_totals[0]) > 0.0, + "clan 0's real prof_generator.var contributes power" + ); + + let first_tick_time = 100_500; + let deadlines = loaded_mission_script_bundles(&engine) + .expect("bundles after one tick per clan") + .iter() + .map(|bundle| { + bundle + .behavior_warm_start + .expect("full load warm-start") + .next_deadline_ms + }) + .collect::<Vec<_>>(); + assert!(deadlines.iter().all(|deadline| *deadline < first_tick_time)); + assert_eq!( + advance_loaded_mission_resources(&mut engine, first_tick_time) + .expect("second resource tick for each clan"), + 2 + ); + let totals_at_100500 = loaded_mission_script_bundles(&engine) + .expect("bundles at 100500") + .iter() + .map(|bundle| { + ( + bundle.clan_index, + bundle.behavior_warm_start.expect("full load warm-start"), + ) + }) + .collect::<Vec<_>>(); + for (clan, warm_start) in &totals_at_100500 { + assert_eq!(warm_start.first_time_ms, first_tick_time); + let elapsed = if *clan == 0 { 297 } else { 299 }; + assert_eq!( + warm_start.cleared_words[0], + (behavior_elapsed_seconds(elapsed) * 10.0).to_bits(), + "clan {clan} recomputes power availability from the elapsed interval" + ); + } + + assert_eq!( + advance_loaded_mission_resources(&mut engine, 101_000) + .expect("third resource tick for each clan"), + 2 + ); + let totals_at_101000 = loaded_mission_script_bundles(&engine) + .expect("bundles at 101000") + .iter() + .map(|bundle| { + ( + bundle.clan_index, + bundle.behavior_warm_start.expect("full load warm-start"), + ) + }) + .collect::<Vec<_>>(); + for (clan, warm_start) in &totals_at_101000 { + assert_eq!(warm_start.first_time_ms, 101_000); + assert_eq!( + warm_start.cleared_words[0], + 5.0_f32.to_bits(), + "clan {clan} replaces totals with the latest interval" + ); + let previous = totals_at_100500 + .iter() + .find(|(previous_clan, _)| previous_clan == clan) + .expect("same clan totals at previous tick") + .1; + assert_ne!(warm_start.cleared_words[0], previous.cleared_words[0]); + } + + assert!(loaded_mission_behavior_profiles(&engine) + .expect("loaded profiles") + .iter() + .filter(|profile| profile.class_flags == 0x8000_0002) + .all(|profile| profile.transfer_power_out_bits == 10.0_f32.to_bits())); + + for clan in [0, 1] { + let distributor = loaded_mission_behavior_distributors(&engine) + .expect("loaded distributors") + .iter() + .find(|distributor| distributor.clan_index == clan) + .expect("loaded clan distributor"); + assert_eq!(distributor.registered_objects.len(), 2); + let generator = loaded_mission_behavior_distributors(&engine) + .expect("loaded distributors") + .iter() + .find(|distributor| distributor.clan_index == clan) + .and_then(|distributor| { + distributor + .registered_objects + .iter() + .find(|object| object.class_flags == 0x8000_0002) + }) + .expect("licensed AutoDemo generator row"); + let profile = loaded_mission_behavior_profiles(&engine) + .expect("loaded Behavior profiles") + .iter() + .find(|profile| profile.handle == generator.handle) + .expect("generator profile"); + let totals = totals_at_101000 + .iter() + .find(|(candidate, _)| *candidate == clan) + .expect("generator clan totals") + .1 + .cleared_words; + println!( + "licensed AutoDemo Behavior tick: clan={clan} ObjectId={} profile={} Transfer_Power_Out={} PowerAvailable={} at queue times 100201/100203,100500,101000; registered rows={}", + generator.original_id.0, + profile.profile_entry.as_deref().unwrap_or("<defaults>"), + f32::from_bits(profile.transfer_power_out_bits), + f32::from_bits(totals[0]), + distributor.registered_objects.len(), + ); + } + + let second_plant = { + let loaded = engine.loaded.as_mut().expect("loaded mission state"); + let second = loaded + .behavior_distributors + .iter() + .find(|distributor| distributor.clan_index == 1) + .expect("clan 1 distributor"); + let plant = second + .registered_objects + .iter() + .find(|object| object.class_flags == 0x8000_0010) + .expect("clan 1 plant") + .clone(); + loaded + .control_device_tables + .retain(|table| table.handle != plant.handle); + plant + }; + assert_eq!(second_plant.class_flags, 0x8000_0010); + let before_distributors = loaded_mission_behavior_distributors(&engine) + .expect("rollback distributor snapshot") + .to_vec(); + let before_ore_states = loaded_mission_behavior_ore_states(&engine) + .expect("rollback ore snapshot") + .to_vec(); + let before_controls = loaded_mission_control_device_tables(&engine) + .expect("rollback Control snapshot") + .to_vec(); + let before_warm_starts = loaded_mission_script_bundles(&engine) + .expect("rollback bundles") + .iter() + .map(|bundle| bundle.behavior_warm_start) + .collect::<Vec<_>>(); + let before_rng = engine.behavior_rng_state; + let error = advance_loaded_mission_resources(&mut engine, 102_000) + .expect_err("missing clan 1 plant Control table fails after clan 0 stages a tick"); + assert!(matches!( + error, + EngineError::BehaviorDistributorTick { clan_index: 1, .. } + )); + assert_eq!( + loaded_mission_behavior_distributors(&engine), + Some(before_distributors.as_slice()) + ); + assert_eq!( + loaded_mission_behavior_ore_states(&engine), + Some(before_ore_states.as_slice()) + ); + assert_eq!( + loaded_mission_control_device_tables(&engine), + Some(before_controls.as_slice()) + ); + assert_eq!( + loaded_mission_script_bundles(&engine) + .expect("bundles after failed transaction") + .iter() + .map(|bundle| bundle.behavior_warm_start) + .collect::<Vec<_>>(), + before_warm_starts + ); + assert_eq!(engine.behavior_rng_state, before_rng); + } + fn behavior_test_object( slot: u32, share: f32, @@ -6075,6 +7400,237 @@ mod tests { } #[test] + fn behavior_allocation_matches_shortage_middle_surplus_and_equality_branches() { + let shortage = behavior_allocation(1.0, 6.0, 3.0).expect("shortage allocation"); + assert_eq!(shortage.priority.to_bits(), 0x3eaa_aaab); + assert_eq!(shortage.residual.to_bits(), 0); + assert_eq!(shortage.consumption.to_bits(), 1.0_f32.to_bits()); + + let middle = behavior_allocation(0.25, 0.375, 0.1875).expect("middle allocation"); + assert_eq!(middle.priority.to_bits(), 1.0_f32.to_bits()); + assert_eq!(middle.residual.to_bits(), 0x3eaa_aaab); + assert_eq!(middle.consumption.to_bits(), 1.0_f32.to_bits()); + + let surplus = behavior_allocation(2.0, 0.375, 0.1875).expect("surplus allocation"); + assert_eq!(surplus.priority.to_bits(), 1.0_f32.to_bits()); + assert_eq!(surplus.residual.to_bits(), 1.0_f32.to_bits()); + assert_eq!(surplus.consumption.to_bits(), 0x3e40_0000); + + let exact = behavior_allocation(0.375, 0.375, 0.1875).expect("exact allocation"); + assert_eq!(exact.priority.to_bits(), 1.0_f32.to_bits()); + assert_eq!(exact.residual.to_bits(), 1.0_f32.to_bits()); + assert_eq!(exact.consumption.to_bits(), 1.0_f32.to_bits()); + } + + fn behavior_tick_test_object( + world: &mut World, + original_id: u32, + class_flags: u32, + share: f32, + ) -> BehaviorRegisteredObject { + let original_id = OriginalObjectId(original_id); + let handle = construct_object( + world, + ObjectDraft { + original_id: Some(original_id), + }, + ) + .expect("construct Behavior tick object"); + register_object(world, handle).expect("register Behavior tick object"); + BehaviorRegisteredObject { + original_id, + handle, + selector: 0, + class_flags, + share, + native_tail: [0; 5], + } + } + + fn behavior_tick_test_control_table( + original_id: u32, + handle: ObjectHandle, + ) -> MissionControlDeviceTableState { + let device = synthetic_effective_control_device( + 19, + 19, + 0.75_f32.to_bits(), + Some(0.5_f32.to_bits()), + None, + ); + MissionControlDeviceTableState { + original_id: Some(OriginalObjectId(original_id)), + handle, + status: MissionControlDeviceTableStatus::Available(vec![device]), + node_provider_status: MissionControlNodeProviderTableStatus::Available(Vec::new()), + } + } + + #[test] + fn behavior_power_source_also_contributes_ore_demand() { + let mut world = new_world(WorldConfig); + let producer = behavior_tick_test_object(&mut world, 1, 0x8000_0002, 0.5); + let recipient = behavior_tick_test_object(&mut world, 2, 0x8000_0001, 0.5); + let mut distributor = BehaviorDistributorState { + clan_index: 0, + super_ai_visible: true, + registered_objects: vec![producer.clone(), recipient.clone()], + }; + let mut ore_states = [producer.clone(), recipient.clone()] + .into_iter() + .map(|object| BehaviorOreState { + original_id: object.original_id, + handle: object.handle, + class_flags: object.class_flags, + current_ore_bits: 1.0_f32.to_bits(), + maximum_ore_bits: 10.0_f32.to_bits(), + }) + .collect::<Vec<_>>(); + let profiles = [BehaviorProfileState { + original_id: OriginalObjectId(1), + handle: producer.handle, + class_flags: producer.class_flags, + profile_entry: None, + transfer_ore_off_board_bits: 0x40a0_0000, + transfer_power_out_bits: 4.0_f32.to_bits(), + }]; + let mut control_tables = vec![ + behavior_tick_test_control_table(1, producer.handle), + behavior_tick_test_control_table(2, recipient.handle), + ]; + + let totals = advance_behavior_distributor_tick( + &mut distributor, + 1.0, + &world, + &mut ore_states, + &profiles, + &mut control_tables, + ) + .expect("tick supported power source and generic receiver"); + + assert_eq!( + totals[4], + 18.0_f32.to_bits(), + "both native classes compute the non-source ore demand" + ); + } + + #[test] + fn behavior_ore_source_also_contributes_power_demand() { + let mut world = new_world(WorldConfig); + let producer = behavior_tick_test_object(&mut world, 3, 0x8000_0004, 1.0); + let mut distributor = BehaviorDistributorState { + clan_index: 0, + super_ai_visible: true, + registered_objects: vec![producer.clone()], + }; + let mut ore_states = [producer.clone()] + .into_iter() + .map(|object| BehaviorOreState { + original_id: object.original_id, + handle: object.handle, + class_flags: object.class_flags, + current_ore_bits: 0.25_f32.to_bits(), + maximum_ore_bits: 10.0_f32.to_bits(), + }) + .collect::<Vec<_>>(); + let profiles = [BehaviorProfileState { + original_id: OriginalObjectId(3), + handle: producer.handle, + class_flags: producer.class_flags, + profile_entry: None, + transfer_ore_off_board_bits: 4.0_f32.to_bits(), + transfer_power_out_bits: 0.0_f32.to_bits(), + }]; + let mut ore_device = synthetic_effective_control_device( + 26, + 26, + 1.0_f32.to_bits(), + Some(1.0_f32.to_bits()), + None, + ); + ore_device.key = 0; + let producer_table = MissionControlDeviceTableState { + original_id: Some(OriginalObjectId(3)), + handle: producer.handle, + status: MissionControlDeviceTableStatus::Available(vec![ + synthetic_effective_control_device( + 19, + 19, + 0.75_f32.to_bits(), + Some(0.5_f32.to_bits()), + None, + ), + ore_device, + ]), + node_provider_status: MissionControlNodeProviderTableStatus::Available(vec![ + synthetic_node_provider_row(0, 0, 1.0_f32.to_bits()), + ]), + }; + let mut control_tables = vec![producer_table]; + + let totals = advance_behavior_distributor_tick( + &mut distributor, + 1.0, + &world, + &mut ore_states, + &profiles, + &mut control_tables, + ) + .expect("tick supported ore source"); + + assert_eq!( + totals[3], + 0.375_f32.to_bits(), + "ore producers still query generic Control power demand" + ); + } + + #[test] + fn behavior_first_pass_clamps_tiny_deficits_and_overfull_stores() { + for (original_id, current, maximum, clamps) in [ + (4, 0.995_f32, 1.0_f32, true), + (5, 1.25, 1.0, true), + (6, 0.0, f32::from_bits(0x3c23_d70a), false), + ] { + let mut world = new_world(WorldConfig); + let object = behavior_tick_test_object(&mut world, original_id, 0x8000_0001, 0.5); + let mut distributor = BehaviorDistributorState { + clan_index: 0, + super_ai_visible: true, + registered_objects: vec![object.clone()], + }; + let mut ore_states = [BehaviorOreState { + original_id: object.original_id, + handle: object.handle, + class_flags: object.class_flags, + current_ore_bits: current.to_bits(), + maximum_ore_bits: maximum.to_bits(), + }]; + let mut control_tables = [MissionControlDeviceTableState { + original_id: Some(object.original_id), + handle: object.handle, + status: MissionControlDeviceTableStatus::Available(Vec::new()), + node_provider_status: MissionControlNodeProviderTableStatus::Available(Vec::new()), + }]; + + advance_behavior_distributor_tick( + &mut distributor, + 1.0, + &world, + &mut ore_states, + &[], + &mut control_tables, + ) + .expect("native low-deficit clamp path"); + + let expected = if clamps { maximum } else { current }; + assert_eq!(ore_states[0].current_ore_bits, expected.to_bits()); + } + } + + #[test] #[ignore = "requires licensed corpus"] fn licensed_campaign_preview_keeps_unsupported_init_without_partial_writes() { let root = licensed_root("IS"); 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 610e8db..efd9b08 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,9 @@ using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; -// Calls selected original x86 Behavior.dll, ArealMap.dll, and Control.dll paths -// against synthetic storage. Only host callbacks, GetSystemArealMap, and bounded -// vector backing are substituted; the tested module instructions remain installed code. +// Calls selected original x86 Behavior.dll, ArealMap.dll, AniMesh.dll, and Control.dll paths +// against synthetic storage. Only host callbacks, GetSystemArealMap/GetQueue IAT +// slots, and bounded vector backing are substituted; tested module code remains installed. internal static class BehaviorDistributorTickOracle { private const uint LoadWithAlteredSearchPath = 0x00000008; private const uint MemCommitReserve = 0x00003000; @@ -17,7 +17,9 @@ internal static class BehaviorDistributorTickOracle { private const string ExpectedBehaviorSha256 = "ddfbdbde07832358fe6e35e01c8dba9b58e7313789498b6049ed51d4ed9baf99"; private const string ExpectedControlSha256 = "bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e"; private const string ExpectedArealMapSha256 = "a25f9254ebb339d70e2e07c8121950191e9584ca0858d8e9c2e2b6c671edf6ea"; + private const string ExpectedAniMeshSha256 = "65659bf67f20e5be77d67a5b2f59968f61b94293143807fa59ca451c560c4f7e"; private const int TickRva = 0x19e80; + private const int DistributorScheduleRva = 0x1adb0; private const int AddObjectRva = 0x1aac0; private const int NormalizeRva = 0x1ac90; private const int IndexedPropertySetRva = 0x0b470; @@ -27,14 +29,25 @@ internal static class BehaviorDistributorTickOracle { private const int BehaviorVarBlockConstructorRva = 0x22d90; private const int BehaviorVarFieldRegisterRva = 0x22e20; private const int GetSystemArealMapIatRva = 0x59008; + private const int GetQueueIatRva = 0x59110; private const int ControlResourceDeviceGetterRva = 0x21d00; private const int ControlResourceAggregateQueryRva = 0x2b410; private const int ControlResourceAggregateSetRva = 0x2ba30; private const int ControlProviderInterfaceVtableRva = 0x3d254; private const int ControlProviderType1GetterRva = 0x0dc40; private const int ControlProviderRowConstructorRva = 0x0b240; + private const int ControlOwnerConstructorRva = 0x06bf0; + private const int ControlProviderInitialStateRva = 0x0f940; private const int ControlProviderAmountUpdateRva = 0x10f30; + private const int ControlProviderAmountDistributeRva = 0x10ba0; + private const int ControlProviderStagePropagationRva = 0x11130; + private const int ControlProviderStageUpdateRva = 0x11220; + private const int ControlContactRateUpdateRva = 0x12a40; + private const int ControlTimedUpdateRva = 0x0bcf0; private const int ArealMapUnitDatComponentBuilderRva = 0x14b90; + private const int AniMeshNodeMetadataQueryRva = 0x051f0; + private const int AniMeshNodeStageCountRva = 0x05840; + private const int AniMeshNodeStageSetRva = 0x05810; private const int ControlResourceDeviceConstructorRva = 0x22980; private const int ControlResourceComponentOverrideRva = 0x2d890; private const int ControlResourceCommonSetterRva = 0x21d50; @@ -66,6 +79,9 @@ internal static class BehaviorDistributorTickOracle { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void X87ControlWordReader(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void X87ControlWordWriter(); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void TickDelegate(IntPtr self, float deltaSeconds); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void NativeBehaviorSchedule(IntPtr self); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr QueueGetter(); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint QueueClockGetter(IntPtr self); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void NativeAddObject(IntPtr self, uint key); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeNormalize(IntPtr self, uint key); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void VectorInsert(IntPtr self, IntPtr source, uint count, uint position); @@ -91,15 +107,27 @@ internal static class BehaviorDistributorTickOracle { [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate float NativeControlResourceDeviceGet(IntPtr self, uint selector); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void NativeFastcallComponentBuilder(IntPtr owner, IntPtr node, uint parentId); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int NativeArealMapEvent(IntPtr owner, uint message, uint subcode, IntPtr descriptor); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int NativeAniMeshNodeMetadataQuery(IntPtr owner, uint nodeIndex, uint selector, IntPtr result); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint NativeAniMeshNodeStageCount(IntPtr owner, uint nodeIndex); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate IntPtr NativeControlResourceDeviceConstructor(IntPtr self); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate IntPtr NativeControlResourceComponentOverride(IntPtr self, int deviceIndex, IntPtr typedRecord); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int NativeControlAggregateQuery(IntPtr self, uint selector, IntPtr result); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int NativeControlAggregateSet(IntPtr self, uint selector, IntPtr value); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlProviderAmountUpdate(IntPtr self, int nodeIndex, float delta, uint animationFlag); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlProviderAmountDistribute(IntPtr self, float delta, uint mode, uint flags); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlContactRateUpdate(IntPtr self, float deltaSeconds); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlTimedUpdate(IntPtr self, float inputTime); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlProviderRowConstructor(IntPtr self, IntPtr sourceNdpRow); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate IntPtr NativeControlOwnerConstructor(IntPtr self, IntPtr host, uint classCode); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlProviderInitialState(IntPtr self); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void NativeControlNodeUpdateCallback(IntPtr self, uint nodeIndex, uint selector, uint valueBits); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlProviderStageUpdate(IntPtr self, int nodeIndex, uint updateEffects); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void NativeAniMeshStageTransitionCallback(IntPtr self, uint nodeIndex, uint visibleStage); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint NativeAniMeshNodeLifecycleCallback(IntPtr self, uint nodeIndex, uint selector, uint mask); private static readonly AreaMapGetter AreaMapGetterCallback = GetAreaMap; + private static readonly QueueGetter QueueGetterCallback = GetQueue; + private static readonly QueueClockGetter QueueClockGetterCallback = GetQueueTime; private static readonly VectorInsert VectorInsertCallback = InsertVector; private static readonly MapLookup MapLookupCallback = Lookup; private static readonly ObjectState ObjectStateCallback = GetObjectState; @@ -112,11 +140,28 @@ internal static class BehaviorDistributorTickOracle { private static readonly InterfaceSetProperty InterfaceSetCallback = SetInterfaceProperty; private static readonly NativeArealMapEvent ArealMapEventCallback = OnArealMapEvent; private static readonly NativeControlNodeUpdateCallback ControlNodeUpdateCallback = OnControlNodeUpdate; + private static readonly NativeAniMeshStageTransitionCallback AniMeshStageTransitionCallback = OnAniMeshStageTransition; + private static readonly NativeAniMeshNodeLifecycleCallback AniMeshNodeLifecycleCallback = OnAniMeshNodeLifecycle; + private static readonly NativeAniMeshNodeMetadataQuery AniMeshNodeMetadataQueryCallback = OnAniMeshNodeMetadataQuery; private static ArealMapFixture activeArealMap; private static int controlNodeUpdateCount; private static uint controlNodeUpdateIndex; private static uint controlNodeUpdateSelector; private static uint controlNodeUpdateValueBits; + private static readonly List<uint> controlNodeUpdateIndices = new List<uint>(); + private static readonly List<uint> controlNodeUpdateFlags = new List<uint>(); + private static readonly List<string> aniMeshStageTransitions = new List<string>(); + private static readonly List<string> aniMeshNodeLifecycleCallbacks = new List<string>(); + private static readonly List<string> aniMeshNodeMetadataQueries = new List<string>(); + private static readonly List<string> controlProviderCallbackTrace = new List<string>(); + private static NativeAniMeshStageTransitionCallback activeNativeAniMeshStageTransition; + private static NativeAniMeshNodeLifecycleCallback activeNativeAniMeshNodeLifecycle; + private static NativeAniMeshNodeMetadataQuery activeNativeAniMeshNodeMetadataQuery; + private static IntPtr activeControlProviderRows; + private static IntPtr activeAniMeshInterface; + private static bool aniMeshCallbackOwnerMismatch; + private static bool controlNodeUpdateOwnerMismatch; + private static bool nativeAniMeshStageCallbackMissing; private static IntPtr fastcallThunks; private static IntPtr queryObjectThunk; private static IntPtr getInterfacePropertyThunk; @@ -127,6 +172,7 @@ internal static class BehaviorDistributorTickOracle { private static X87ControlWordWriter x87ControlWordWriter; private static readonly NativeBehaviorProfileLoadCallback BehaviorProfileLoadCallback = CaptureBehaviorProfileLoad; private static readonly List<BehaviorProfileSelection> behaviorProfileSelections = new List<BehaviorProfileSelection>(); + private static Fixture activeQueueFixture; private sealed class BehaviorProfileSelection { public IntPtr Owner; @@ -162,12 +208,20 @@ internal static class BehaviorDistributorTickOracle { public readonly List<string> Calls = new List<string>(); } + private sealed class NativeProviderTable { + public IntPtr Owner; + public IntPtr Rows; + } + private sealed class Fixture : IDisposable { public IntPtr Distributor; public IntPtr Entries; public IntPtr VectorVtable; public IntPtr Manager; public IntPtr ManagerVtable; + public IntPtr Queue; + public IntPtr QueueVtable; + public uint QueueTime; public readonly List<IntPtr> Allocations = new List<IntPtr>(); public readonly Dictionary<uint, NativeObject> ByKey = new Dictionary<uint, NativeObject>(); public readonly List<string> Calls = new List<string>(); @@ -221,6 +275,8 @@ internal static class BehaviorDistributorTickOracle { Marshal.WriteInt32(Distributor, 0x20, keys.Length); Marshal.WriteInt32(Distributor, 0x24, capacity); Marshal.WriteIntPtr(Distributor, 0x28, Entries); + Marshal.WriteInt16(Distributor, 0x18, 3); + Marshal.WriteInt16(Distributor, 0x1a, 1); for (int i = 0; i < keys.Length; i++) { IntPtr entry = IntPtr.Add(Entries, i * 0x1c); Marshal.WriteInt32(entry, 0x00, unchecked((int)keys[i])); @@ -233,8 +289,16 @@ internal static class BehaviorDistributorTickOracle { Allocations.Add(value); return value; } + public void MakeQueue(uint time) { + QueueTime = time; + QueueVtable = Allocate(0x40); + Queue = Allocate(0x20); + Marshal.WriteIntPtr(Queue, 0, QueueVtable); + Marshal.WriteIntPtr(QueueVtable, 0x38, Marshal.GetFunctionPointerForDelegate(QueueClockGetterCallback)); + } public void Dispose() { active = null; + if (activeQueueFixture == this) activeQueueFixture = null; for (int i = Allocations.Count - 1; i >= 0; i--) Marshal.FreeHGlobal(Allocations[i]); Allocations.Clear(); } @@ -287,6 +351,16 @@ internal static class BehaviorDistributorTickOracle { } private static IntPtr GetAreaMap() { return active.Manager; } + private static IntPtr GetQueue() { + if (activeQueueFixture == null || activeQueueFixture.Queue == IntPtr.Zero) + throw new InvalidOperationException("native scheduler requested a queue without a fixture"); + return activeQueueFixture.Queue; + } + private static uint GetQueueTime(IntPtr self) { + if (activeQueueFixture == null || self != activeQueueFixture.Queue) + throw new InvalidOperationException("native scheduler queried an unexpected queue"); + return activeQueueFixture.QueueTime; + } private static int OnArealMapEvent(IntPtr owner, uint message, uint subcode, IntPtr descriptor) { ArealMapFixture fixture = activeArealMap; if (fixture == null) return 0; @@ -432,10 +506,45 @@ internal static class BehaviorDistributorTickOracle { return 1; } private static void OnControlNodeUpdate(IntPtr self, uint nodeIndex, uint selector, uint valueBits) { + if (activeAniMeshInterface != IntPtr.Zero && self != activeAniMeshInterface) + controlNodeUpdateOwnerMismatch = true; controlNodeUpdateCount++; controlNodeUpdateIndex = nodeIndex; controlNodeUpdateSelector = selector; controlNodeUpdateValueBits = valueBits; + controlNodeUpdateIndices.Add(nodeIndex); + controlProviderCallbackTrace.Add("amount:" + nodeIndex.ToString()); + if (activeControlProviderRows != IntPtr.Zero) + controlNodeUpdateFlags.Add(unchecked((uint)Marshal.ReadInt32(activeControlProviderRows, checked((int)nodeIndex * 0x2c + 0x28)))); + } + private static void OnAniMeshStageTransition(IntPtr self, uint nodeIndex, uint visibleStage) { + controlProviderCallbackTrace.Add("stage:" + nodeIndex.ToString() + ":" + visibleStage.ToString()); + aniMeshStageTransitions.Add(nodeIndex.ToString() + ":" + visibleStage.ToString()); + if (activeAniMeshInterface != IntPtr.Zero && self != activeAniMeshInterface) + aniMeshCallbackOwnerMismatch = true; + if (activeNativeAniMeshStageTransition == null) nativeAniMeshStageCallbackMissing = true; + else activeNativeAniMeshStageTransition(self, nodeIndex, visibleStage); + } + private static uint OnAniMeshNodeLifecycle(IntPtr self, uint nodeIndex, uint selector, uint mask) { + aniMeshNodeLifecycleCallbacks.Add(nodeIndex.ToString() + ":" + selector.ToString("x") + ":" + mask.ToString("x")); + controlProviderCallbackTrace.Add("lifecycle:" + nodeIndex.ToString() + ":" + selector.ToString("x") + ":" + mask.ToString("x")); + if (activeAniMeshInterface != IntPtr.Zero && self != activeAniMeshInterface) + aniMeshCallbackOwnerMismatch = true; + if (activeNativeAniMeshNodeLifecycle == null) { + nativeAniMeshStageCallbackMissing = true; + return 0; + } + return activeNativeAniMeshNodeLifecycle(self, nodeIndex, selector, mask); + } + private static int OnAniMeshNodeMetadataQuery(IntPtr self, uint nodeIndex, uint selector, IntPtr result) { + int nativeResult = activeNativeAniMeshNodeMetadataQuery(self, nodeIndex, selector, result); + int success = (nativeResult & 0xff) != 0 ? 1 : 0; + if (activeAniMeshInterface != IntPtr.Zero && self != activeAniMeshInterface) + aniMeshCallbackOwnerMismatch = true; + IntPtr value = success != 0 && result != IntPtr.Zero ? Marshal.ReadIntPtr(result) : IntPtr.Zero; + aniMeshNodeMetadataQueries.Add(nodeIndex.ToString() + ":" + selector.ToString("x") + ":" + + (value == IntPtr.Zero ? "none" : Hex(unchecked((uint)Marshal.ReadInt32(value))))); + return success; } private static float SequenceValue(float[] sequence, int index, float fallback) { if (sequence == null || sequence.Length == 0) return fallback; @@ -478,6 +587,11 @@ internal static class BehaviorDistributorTickOracle { if (!File.Exists(arealMapPath)) { Console.Error.WriteLine("Set FPARKAN_ORIGINAL_AREALMAP_DLL to the installed ArealMap.dll."); return 10; } string arealMapHash = Hash(arealMapPath); if (arealMapHash != ExpectedArealMapSha256) { Console.Error.WriteLine("Unexpected ArealMap.dll SHA-256: " + arealMapHash); return 11; } + string aniMeshPath = Environment.GetEnvironmentVariable("FPARKAN_ORIGINAL_ANIMESH_DLL"); + if (String.IsNullOrEmpty(aniMeshPath)) aniMeshPath = @"C:\GOG Games\Parkan - Iron Strategy\AniMesh.dll"; + if (!File.Exists(aniMeshPath)) { Console.Error.WriteLine("Set FPARKAN_ORIGINAL_ANIMESH_DLL to the installed AniMesh.dll."); return 13; } + string aniMeshHash = Hash(aniMeshPath); + if (aniMeshHash != ExpectedAniMeshSha256) { Console.Error.WriteLine("Unexpected AniMesh.dll SHA-256: " + aniMeshHash); return 14; } 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"); @@ -492,8 +606,15 @@ internal static class BehaviorDistributorTickOracle { Console.Error.WriteLine("LoadLibraryEx(ArealMap.dll) failed: " + Marshal.GetLastWin32Error()); FreeLibrary(module); FreeLibrary(controlModule); return 12; } + IntPtr aniMeshModule = LoadLibraryEx(aniMeshPath, IntPtr.Zero, LoadWithAlteredSearchPath); + if (aniMeshModule == IntPtr.Zero) { + Console.Error.WriteLine("LoadLibraryEx(AniMesh.dll) failed: " + Marshal.GetLastWin32Error()); + FreeLibrary(arealMapModule); FreeLibrary(module); FreeLibrary(controlModule); return 15; + } IntPtr import = IntPtr.Add(module, GetSystemArealMapIatRva); + IntPtr queueImport = IntPtr.Add(module, GetQueueIatRva); IntPtr originalImport = Marshal.ReadIntPtr(import); + IntPtr originalQueueImport = Marshal.ReadIntPtr(queueImport); uint oldProtection = 0; bool protectionChanged = false; bool thunksAllocated = false; @@ -513,8 +634,9 @@ internal static class BehaviorDistributorTickOracle { throw new InvalidOperationException("VirtualProtect(GetSystemArealMap IAT) failed: " + Marshal.GetLastWin32Error()); protectionChanged = true; Marshal.WriteIntPtr(import, Marshal.GetFunctionPointerForDelegate(AreaMapGetterCallback)); - RunSmokeCases(module, controlModule, arealMapModule); - Console.WriteLine("original native Behavior/ArealMap/Control oracle passed (Behavior Add 0x1aac0, normalize 0x1ac90, tick 0x19e80; ArealMap UnitDAT projection 0x14b90; Control INTO override 0x2d890; only synthetic host callbacks, GetSystemArealMap IAT, and bounded vector insertion are substituted; this does not compare Rust parity)."); + Marshal.WriteIntPtr(queueImport, Marshal.GetFunctionPointerForDelegate(QueueGetterCallback)); + RunSmokeCases(module, controlModule, arealMapModule, aniMeshModule); + Console.WriteLine("original native Behavior/ArealMap/Control oracle passed (Behavior Add 0x1aac0, normalize 0x1ac90, scheduler 0x1adb0, tick 0x19e80; ArealMap UnitDAT projection 0x14b90; Control INTO override 0x2d890, provider distribution 0x10ba0, class-4 update 0x12a40 and inactive timing baseline 0xbcf0; synthetic host callbacks, GetSystemArealMap/GetQueue IAT slots, and bounded vector insertion are substituted; Control provider selector vtable is original; no full Control update or Rust parity is claimed)."); return 0; } catch (Exception error) { @@ -524,10 +646,12 @@ internal static class BehaviorDistributorTickOracle { finally { if (protectionChanged) { Marshal.WriteIntPtr(import, originalImport); + Marshal.WriteIntPtr(queueImport, originalQueueImport); uint ignored; VirtualProtect(import, new UIntPtr((uint)IntPtr.Size), oldProtection, out ignored); } - GC.KeepAlive(AreaMapGetterCallback); GC.KeepAlive(VectorInsertCallback); GC.KeepAlive(x87ControlWordReader); GC.KeepAlive(x87ControlWordWriter); GC.KeepAlive(MapLookupCallback); + GC.KeepAlive(AreaMapGetterCallback); GC.KeepAlive(QueueGetterCallback); GC.KeepAlive(QueueClockGetterCallback); + GC.KeepAlive(VectorInsertCallback); GC.KeepAlive(x87ControlWordReader); GC.KeepAlive(x87ControlWordWriter); GC.KeepAlive(MapLookupCallback); GC.KeepAlive(ObjectStateCallback); GC.KeepAlive(ObjectClassCallback); GC.KeepAlive(ObjectQueryCallback); GC.KeepAlive(ObjectRateCallback); GC.KeepAlive(ObjectGetPropertyCallback); GC.KeepAlive(ObjectSetPropertyCallback); @@ -538,12 +662,13 @@ 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(arealMapModule); + FreeLibrary(aniMeshModule); FreeLibrary(module); FreeLibrary(controlModule); } } - private static void RunSmokeCases(IntPtr module, IntPtr controlModule, IntPtr arealMapModule) { + private static void RunSmokeCases(IntPtr module, IntPtr controlModule, IntPtr arealMapModule, IntPtr aniMeshModule) { ushort savedControlWord = CurrentX87ControlWord(); Console.WriteLine("x87-control-word-before=0x" + savedControlWord.ToString("x4") + " (x86 oracle process)"); try { @@ -552,9 +677,18 @@ internal static class BehaviorDistributorTickOracle { RunNativeAddCases(module); RunNativeNormalizeCases(module); RunNativeArealMapComponentBuilderCase(arealMapModule); + RunNativeAniMeshScaleLoadSnapshot(aniMeshModule); + RunNativeAniMeshNodeMetadataCases(aniMeshModule); + RunNativeControlProviderInitialStateCase(controlModule, aniMeshModule); RunNativeControlIntoOverrideCase(controlModule); RunNativeControlResourceDeviceCase(controlModule); RunNativeControlProviderLiveStateCase(controlModule); + RunNativeControlProviderStageArithmeticCase(controlModule, aniMeshModule); + RunNativeControlProviderHierarchyPropagationCase(controlModule, aniMeshModule); + RunNativeControlProviderVisibilityCase(controlModule, aniMeshModule); + RunNativeControlProviderDistributionCases(controlModule); + RunNativeControlContactRateUpdateCase(controlModule); + RunNativeControlTimedUpdateBaselineCases(controlModule); RunNativeControlAggregateResourceCases(controlModule); RunNativeBehaviorProfileMapCases(module); RunNativeBehaviorVarSyntheticCase(module); @@ -565,6 +699,19 @@ internal static class BehaviorDistributorTickOracle { } RunNativeIndexedPropertyCases(module); RunNativeOreInitializationCases(module); + ushort tickControlWord = CurrentX87ControlWord(); + try { + SetX87ControlWord(0x007f); + Expect(CurrentX87ControlWord() == 0x007f, "Behavior resource-distributor tick uses the measured game x87 control word"); + Console.WriteLine("native-behavior-tick-x87-control-word=0x" + CurrentX87ControlWord().ToString("x4")); + RunNativeBehaviorTickCases(module); + RunNativeBehaviorSchedulerCases(module); + } finally { + SetX87ControlWord(tickControlWord); + } + } + + private static void RunNativeBehaviorTickCases(IntPtr 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); @@ -579,6 +726,10 @@ internal static class BehaviorDistributorTickOracle { RunObjectCase(tick, 0x80000008, 0.5f, 0.0f, 3.0f, 0, 2.0f, "ore-80000008"); RunMixedOreCase(tick, "mixed-ore-producer-recipient", 1.0f, 0.5f); RunMixedOreCase(tick, "bounded-ore-store", 0.25f, 0.5f); + RunOreAllocationBranch(tick, "ore-allocation-middle", 0.25f, 2.0f, 0.25f, 0.625f, 1.75f, 0.5f); + RunOreAllocationBranch(tick, "ore-allocation-surplus", 2.0f, 3.0f, 0.25f, 0.625f, 2.625f, 0.625f); + RunOreAllocationBranch(tick, "ore-allocation-equality", 0.375f, 2.0f, 0.25f, 0.625f, 1.625f, 0.625f); + RunNativeOreClampCases(tick); RunWeightedOreCase(tick); RunMixedPowerCase(tick, "mixed-power-sufficient", 4.0f, 1.0f, 0.5f, 0.75f); RunMixedPowerCase(tick, "mixed-power-shortage", 0.125f, 1.0f, 0.5f, 0.75f); @@ -587,6 +738,62 @@ internal static class BehaviorDistributorTickOracle { RunSkippedCase(tick); } + private static void RunNativeBehaviorSchedulerCases(IntPtr module) { + NativeBehaviorSchedule schedule = (NativeBehaviorSchedule)Marshal.GetDelegateForFunctionPointer( + IntPtr.Add(module, DistributorScheduleRva), typeof(NativeBehaviorSchedule)); + uint[] elapsedVectors = { 1, 1001, 16777217, 16777219, 0xffffffff }; + uint[] expectedBits = { 0x3a83126f, 0x3f8020c5, 0x46831270, 0x46831271, 0x4a83126f }; + for (int i = 0; i < elapsedVectors.Length; i++) { + uint elapsed = elapsedVectors[i]; + uint now = unchecked(1u + elapsed); + RunNativeSchedulerSample(schedule, now, 1, 0, expectedBits[i], "elapsed-" + elapsed.ToString()); + } + + using (Fixture fixture = NewFixture()) { + NativeObject producer = fixture.AddObject(0x75, 0x80000002, 1.0f, 0.0f, 0.0f, 0); + fixture.MakeDistributor(producer.Key); + fixture.MakeQueue(10); + active = fixture; + activeQueueFixture = fixture; + Marshal.WriteInt32(fixture.Distributor, 0x10, 1); + Marshal.WriteInt32(fixture.Distributor, 0x14, 10); + Marshal.WriteInt32(fixture.Distributor, 0x30, unchecked((int)0x41200000)); + schedule(fixture.Distributor); + Expect(fixture.LookupCount == 0 && unchecked((uint)Marshal.ReadInt32(fixture.Distributor, 0x30)) == 0x41200000, + "scheduler equality with the deadline performs no resource tick or totals write"); + + fixture.QueueTime = 11; + schedule(fixture.Distributor); + uint deadlineTotal = unchecked((uint)Marshal.ReadInt32(fixture.Distributor, 0x30)); + Expect(fixture.LookupCount == 2 && deadlineTotal == 0x3c23d70b, + "scheduler ticks only after the deadline is strictly passed (lookups=" + fixture.LookupCount + + ", total=" + Hex(deadlineTotal) + ")"); + Console.WriteLine("scheduler-deadline: equality=skip; now=11 delta=0.01; lookups=" + fixture.LookupCount); + } + + RunNativeSchedulerSample(schedule, 0, 0xffffffff, 0, 0x3a83126f, "wrapped-elapsed-1"); + GC.KeepAlive(schedule); + } + + private static void RunNativeSchedulerSample( + NativeBehaviorSchedule schedule, uint now, uint firstTime, uint deadline, uint expectedTotalBits, string label) { + using (Fixture fixture = NewFixture()) { + NativeObject producer = fixture.AddObject(0x74, 0x80000002, 1.0f, 0.0f, 0.0f, 0); + fixture.MakeDistributor(producer.Key); + fixture.MakeQueue(now); + active = fixture; + activeQueueFixture = fixture; + Marshal.WriteInt32(fixture.Distributor, 0x10, unchecked((int)firstTime)); + Marshal.WriteInt32(fixture.Distributor, 0x14, unchecked((int)deadline)); + schedule(fixture.Distributor); + uint actual = unchecked((uint)Marshal.ReadInt32(fixture.Distributor, 0x30)); + Expect(actual == expectedTotalBits, + label + " native qword-to-f32 scheduler delta expected " + Hex(expectedTotalBits) + " got " + Hex(actual)); + Console.WriteLine("native-scheduler-" + label + ": now=" + now.ToString("x8") + " first=" + firstTime.ToString("x8") + + " total=" + Hex(actual) + " lookups=" + fixture.LookupCount); + } + } + private static void RunNativeControlResourceDeviceCase(IntPtr module) { Expect(CurrentX87ControlWord() == 0x007f, "Control selector 0x300 uses x87 control word 0x007f"); const uint key = 2; @@ -732,6 +939,594 @@ internal static class BehaviorDistributorTickOracle { } } + private static void RunNativeControlProviderStageArithmeticCase(IntPtr module, IntPtr aniMeshModule) { + NativeControlProviderStageUpdate updateStage = (NativeControlProviderStageUpdate) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(module, ControlProviderStageUpdateRva), typeof(NativeControlProviderStageUpdate)); + activeNativeAniMeshStageTransition = (NativeAniMeshStageTransitionCallback) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(aniMeshModule, AniMeshNodeStageSetRva), + typeof(NativeAniMeshStageTransitionCallback)); + activeNativeAniMeshNodeLifecycle = (NativeAniMeshNodeLifecycleCallback) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(aniMeshModule, 0x05500), + typeof(NativeAniMeshNodeLifecycleCallback)); + using (Fixture fixture = new Fixture()) { + const int rowCount = 9; + IntPtr owner = fixture.Allocate(0x664); + IntPtr rows = fixture.Allocate(rowCount * 0x2c); + IntPtr aniInterface = fixture.Allocate(0x1b0); + IntPtr aniVtable = fixture.Allocate(0x50); + IntPtr meshRows = fixture.Allocate(rowCount * 0x130); + Marshal.WriteIntPtr(aniInterface, 0, aniVtable); + Marshal.WriteIntPtr(aniInterface, 0x1a8, meshRows); + Marshal.WriteInt32(aniInterface, 0x1ac, rowCount); + for (int index = 0; index < rowCount; index++) + Marshal.WriteInt32(meshRows, index * 0x130 + 0x1c, -99); + Marshal.WriteIntPtr(aniVtable, 0x44, Marshal.GetFunctionPointerForDelegate(AniMeshStageTransitionCallback)); + Marshal.WriteIntPtr(aniVtable, 0x20, Marshal.GetFunctionPointerForDelegate(AniMeshNodeLifecycleCallback)); + Marshal.WriteIntPtr(owner, 0x20, aniInterface); + Marshal.WriteIntPtr(owner, 0x55c, rows); + Marshal.WriteInt32(owner, 0x560, rowCount); + + // Parent ratio .25 yields stage 3 of 4. Bit 4 inherits that ratio; + // bit 8 inherits the parent's stage and clamps it to the child's count. + WriteProviderStageRow(rows, 0, -1, 40.0f, 91.0f, 0.25f, 0, 4, 0x02); + WriteProviderStageRow(rows, 1, 0, 12.0f, 81.0f, 0.875f, 0, 5, 0x06); + WriteProviderStageRow(rows, 2, 0, 7.0f, 71.0f, 0.9f, 0, 2, 0x0a); + WriteProviderStageRow(rows, 3, 1, 3.0f, 31.0f, 0.1f, 0, 6, 0x0e); + // These independent rows distinguish the native ceiling operation + // from floor/round for fractional stage products. + WriteProviderStageRow(rows, 4, -1, 2.0f, 92.0f, 0.1f, 0, 3, 0x02); + WriteProviderStageRow(rows, 5, -1, 3.0f, 93.0f, 0.4f, 0, 3, 0x02); + WriteProviderStageRow(rows, 6, -1, 4.0f, 94.0f, 0.5f, 0, 3, 0x02); + WriteProviderStageRow(rows, 7, -1, 5.0f, 95.0f, 1.0f, 1, 3, 0x102); + WriteProviderStageRow(rows, 8, -1, 6.0f, 96.0f, 0.0f, 0, 3, 0x02); + + aniMeshStageTransitions.Clear(); + aniMeshNodeLifecycleCallbacks.Clear(); + controlProviderCallbackTrace.Clear(); + aniMeshCallbackOwnerMismatch = false; + controlNodeUpdateOwnerMismatch = false; + nativeAniMeshStageCallbackMissing = false; + activeAniMeshInterface = aniInterface; + updateStage(owner, 0, 0); // param2=false suppresses effect creation. + updateStage(owner, 1, 0); + updateStage(owner, 2, 0); + updateStage(owner, 3, 0); + for (int index = 4; index < rowCount; index++) updateStage(owner, index, 0); + + uint[] expectedStages = { 3, 3, 2, 3, 2, 1, 1, 0, 3 }; + uint[] expectedVisibleStages = { 3, 3, 1, 3, 2, 1, 1, 0, 2 }; + uint[] expectedAmounts = { 0x42200000, 0x41400000, 0x40e00000, 0x40400000, + 0x40000000, 0x40400000, 0x40800000, 0x40a00000, 0x40c00000 }; + for (int index = 0; index < rowCount; index++) { + IntPtr row = IntPtr.Add(rows, index * 0x2c); + IntPtr meshRow = IntPtr.Add(meshRows, index * 0x130); + Expect(unchecked((uint)Marshal.ReadInt32(row, 0x18)) == expectedStages[index], + "Control 0x11220 computes inherited stage for row " + index); + Expect(unchecked((uint)Marshal.ReadInt32(meshRow, 0x1c)) == expectedVisibleStages[index], + "AniMesh RVA 0x5810 receives the bounded visual stage for row " + index); + Expect(unchecked((uint)Marshal.ReadInt32(row, 0x08)) == expectedAmounts[index] && + unchecked((uint)Marshal.ReadInt32(row, 0x0c)) == expectedAmounts[index], + "Control 0x11220 retains amount and updates its processed snapshot for row " + index); + Expect((unchecked((uint)Marshal.ReadInt32(row, 0x28)) & 0x200) != 0, + "Control 0x11220 records a stage transition for row " + index); + } + Expect(unchecked((uint)Marshal.ReadInt32(rows, 0x14)) == 0x3e800000 && + unchecked((uint)Marshal.ReadInt32(rows, 0x2c + 0x14)) == 0x3e800000 && + unchecked((uint)Marshal.ReadInt32(rows, 3 * 0x2c + 0x14)) == 0x3e800000, + "Control flag 4 copies the parent type-1 ratio before stage calculation"); + Expect(String.Join(",", aniMeshStageTransitions.ToArray()) == "0:3,1:3,2:1,3:3,4:2,5:1,6:1,7:0,8:2" && + String.Join(",", aniMeshNodeLifecycleCallbacks.ToArray()) == "7:101:4" && !aniMeshCallbackOwnerMismatch && + !controlNodeUpdateOwnerMismatch && !nativeAniMeshStageCallbackMissing, + "Control stage and slot-0x20 callbacks reach the original AniMesh RVA 0x5810 in direct update order"); + Expect(String.Join(",", controlProviderCallbackTrace.ToArray()) == + "stage:0:3,stage:1:3,stage:2:1,stage:3:3,stage:4:2,stage:5:1,stage:6:1,lifecycle:7:101:4,stage:7:0,stage:8:2", + "AniMesh slot 0x20 receives its native node, selector, and mask arguments before stage publication"); + + Console.WriteLine("native-control-parent-stage-arithmetic: controlHash=" + ExpectedControlSha256 + + " rva=0x11220 bit4=ratio bit8=parent-stage ceil=[0.1,0.4,0.5,1,0]=>[2,1,1,0,3]" + + " callbacks=[0:3,1:3,2:1,3:3,4:2,5:1,6:1,lifecycle7:101:4,7:0,8:2]"); + activeAniMeshInterface = IntPtr.Zero; + activeNativeAniMeshStageTransition = null; + activeNativeAniMeshNodeLifecycle = null; + GC.KeepAlive(updateStage); + } + } + + private static void RunNativeControlProviderHierarchyPropagationCase(IntPtr module, IntPtr aniMeshModule) { + NativeControlProviderStageUpdate propagate = (NativeControlProviderStageUpdate) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(module, ControlProviderStagePropagationRva), typeof(NativeControlProviderStageUpdate)); + activeNativeAniMeshStageTransition = (NativeAniMeshStageTransitionCallback) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(aniMeshModule, AniMeshNodeStageSetRva), + typeof(NativeAniMeshStageTransitionCallback)); + activeNativeAniMeshNodeLifecycle = (NativeAniMeshNodeLifecycleCallback) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(aniMeshModule, 0x05500), + typeof(NativeAniMeshNodeLifecycleCallback)); + using (Fixture fixture = new Fixture()) { + NativeProviderTable table = CreateNativeProviderTable(fixture, module, + new float[] { 100.0f, 20.0f, 10.0f, 30.0f, 14.0f }, + new float[] { 25.0f, 10.0f, 5.0f, 12.0f, 7.0f }, + new byte[] { 0x02, 0x02, 0x02, 0x02, 0x02 }); + const int rowCount = 5; + int[] parents = { -1, 0, 1, 0, 0 }; + uint[] stages = { 4, 2, 3, 2, 2 }; + uint[] flags = { 0x02, 0x42, 0x02, 0x102, 0x02 }; + for (int index = 0; index < rowCount; index++) { + IntPtr row = IntPtr.Add(table.Rows, index * 0x2c); + WriteProviderStageRow(table.Rows, index, parents[index], ReadFloat(row, 0x08), + 123.0f + index, ReadFloat(row, 0x14), 0, stages[index], flags[index]); + } + + IntPtr aniInterface = fixture.Allocate(0x1b0); + IntPtr aniVtable = fixture.Allocate(0x50); + IntPtr meshRows = fixture.Allocate(rowCount * 0x130); + Marshal.WriteIntPtr(aniInterface, 0, aniVtable); + Marshal.WriteIntPtr(aniInterface, 0x1a8, meshRows); + Marshal.WriteInt32(aniInterface, 0x1ac, rowCount); + for (int index = 0; index < rowCount; index++) + Marshal.WriteInt32(meshRows, index * 0x130 + 0x1c, -99); + Marshal.WriteIntPtr(aniVtable, 0x20, Marshal.GetFunctionPointerForDelegate(AniMeshNodeLifecycleCallback)); + Marshal.WriteIntPtr(aniVtable, 0x34, Marshal.GetFunctionPointerForDelegate(ControlNodeUpdateCallback)); + Marshal.WriteIntPtr(aniVtable, 0x44, Marshal.GetFunctionPointerForDelegate(AniMeshStageTransitionCallback)); + Marshal.WriteIntPtr(table.Owner, 0x20, aniInterface); + + controlNodeUpdateCount = 0; + controlNodeUpdateIndices.Clear(); + controlNodeUpdateFlags.Clear(); + aniMeshStageTransitions.Clear(); + aniMeshNodeLifecycleCallbacks.Clear(); + controlProviderCallbackTrace.Clear(); + aniMeshCallbackOwnerMismatch = false; + controlNodeUpdateOwnerMismatch = false; + nativeAniMeshStageCallbackMissing = false; + activeControlProviderRows = table.Rows; + activeAniMeshInterface = aniInterface; + + propagate(table.Owner, 0, 0); + + IntPtr parent = table.Rows; + IntPtr protected40 = IntPtr.Add(table.Rows, 0x2c); + IntPtr grandchild = IntPtr.Add(table.Rows, 2 * 0x2c); + IntPtr protected100 = IntPtr.Add(table.Rows, 3 * 0x2c); + IntPtr sibling = IntPtr.Add(table.Rows, 4 * 0x2c); + IntPtr parentMeshRow = meshRows; + IntPtr bit40MeshRow = IntPtr.Add(meshRows, 0x130); + IntPtr grandchildMeshRow = IntPtr.Add(meshRows, 2 * 0x130); + IntPtr bit100MeshRow = IntPtr.Add(meshRows, 3 * 0x130); + IntPtr siblingMeshRow = IntPtr.Add(meshRows, 4 * 0x130); + Expect(ReadFloat(parent, 0x08) == 25.0f && ReadFloat(parent, 0x0c) == 25.0f && + unchecked((uint)Marshal.ReadInt32(parent, 0x18)) == 3, + "Control 0x11130 updates the parent stage and processed amount first"); + Expect(ReadFloat(protected40, 0x08) == 0.0f && ReadFloat(protected40, 0x14) == 0.0f && + unchecked((uint)Marshal.ReadInt32(protected40, 0x18)) == 0 && + (unchecked((uint)Marshal.ReadInt32(protected40, 0x28)) & 0x50) == 0x50, + "Protected bit 0x40 does not stop child depletion, while its depleted-stage early return remains visible"); + Expect(ReadFloat(grandchild, 0x08) == 0.0f && ReadFloat(grandchild, 0x0c) == 125.0f && + unchecked((uint)Marshal.ReadInt32(grandchild, 0x18)) == 0 && + (unchecked((uint)Marshal.ReadInt32(grandchild, 0x28)) & 0x90) == 0x90, + "Control 0x11130 drains a protected child's descendant but its inherited 0x80 flag preserves the depleted stage snapshot"); + Expect(ReadFloat(protected100, 0x08) == 0.0f && ReadFloat(protected100, 0x0c) == 0.0f && + unchecked((uint)Marshal.ReadInt32(protected100, 0x18)) == 2, + "Protected bit 0x100 does not stop child depletion or its later stage update"); + Expect(ReadFloat(sibling, 0x08) == 0.0f && ReadFloat(sibling, 0x0c) == 0.0f && + unchecked((uint)Marshal.ReadInt32(sibling, 0x18)) == 2 && + (unchecked((uint)Marshal.ReadInt32(sibling, 0x28)) & 0x100) != 0, + "An unprotected sibling retains the native damaged flag while updating its stage"); + Expect(unchecked((uint)Marshal.ReadInt32(parentMeshRow, 0x1c)) == 3 && + unchecked((uint)Marshal.ReadInt32(bit40MeshRow, 0x1c)) == unchecked((uint)-99) && + unchecked((uint)Marshal.ReadInt32(grandchildMeshRow, 0x1c)) == unchecked((uint)-99) && + unchecked((uint)Marshal.ReadInt32(bit100MeshRow, 0x1c)) == 1 && + unchecked((uint)Marshal.ReadInt32(siblingMeshRow, 0x1c)) == 1, + "ANI slot 0x44 reaches native AniMesh RVA 0x5810 for changed visible stages only"); + Expect(controlNodeUpdateCount == 4 && + String.Join(",", controlNodeUpdateIndices.ConvertAll(index => index.ToString()).ToArray()) == "1,2,3,4" && + String.Join(",", controlNodeUpdateFlags.ConvertAll(value => value.ToString("x")).ToArray()) == "42,82,102,102" && + !controlNodeUpdateOwnerMismatch, + "Control 0x11130 traverses descendants depth-first, checking callback owners and protected flags"); + Expect(String.Join(",", aniMeshStageTransitions.ToArray()) == "0:3,3:1,4:1" && + aniMeshNodeLifecycleCallbacks.Count == 0 && + !aniMeshCallbackOwnerMismatch && !nativeAniMeshStageCallbackMissing, + "Control descendant update preserves the native callback order and stage bounds"); + Expect(String.Join(",", controlProviderCallbackTrace.ToArray()) == + "stage:0:3,amount:1,amount:2,amount:3,stage:3:1,amount:4,stage:4:1", + "Control 0x11130 keeps amount, lifecycle, and visual-stage callbacks in native depth-first order"); + Expect(ReadFloat(table.Owner, 0x590) == 25.0f, + "Control 0x10f30 keeps the aggregate amount in sync after recursive child depletion"); + + Console.WriteLine("native-control-parent-propagation: controlHash=" + ExpectedControlSha256 + + " rva=0x11130 childOrder=[1,2,3,4] protected40/100=depleted bit40-stage-return=preserved" + + " callbacks=" + String.Join(",", controlProviderCallbackTrace.ToArray())); + activeControlProviderRows = IntPtr.Zero; + activeAniMeshInterface = IntPtr.Zero; + activeNativeAniMeshStageTransition = null; + activeNativeAniMeshNodeLifecycle = null; + GC.KeepAlive(propagate); + } + } + + private static void RunNativeControlProviderVisibilityCase(IntPtr controlModule, IntPtr aniMeshModule) { + NativeControlProviderStageUpdate updateStage = (NativeControlProviderStageUpdate) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(controlModule, ControlProviderStageUpdateRva), + typeof(NativeControlProviderStageUpdate)); + NativeAniMeshNodeMetadataQuery queryNode = (NativeAniMeshNodeMetadataQuery) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(aniMeshModule, AniMeshNodeMetadataQueryRva), + typeof(NativeAniMeshNodeMetadataQuery)); + NativeAniMeshNodeLifecycleCallback updateNodeLifecycle = (NativeAniMeshNodeLifecycleCallback) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(aniMeshModule, 0x05500), + typeof(NativeAniMeshNodeLifecycleCallback)); + NativeAniMeshStageTransitionCallback setNodeStage = (NativeAniMeshStageTransitionCallback) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(aniMeshModule, AniMeshNodeStageSetRva), + typeof(NativeAniMeshStageTransitionCallback)); + + using (Fixture fixture = NewFixture()) { + NativeProviderTable table = CreateNativeProviderTable(fixture, controlModule, + new float[] { 13.0f }, new float[] { 13.0f }, new byte[] { 0x00 }); + IntPtr descriptor = Marshal.ReadIntPtr(table.Rows); + Marshal.WriteInt32(descriptor, 0x08, FloatBits(0.03125f)); // source mobility per unit volume + Marshal.WriteInt32(table.Owner, 0x50, 9); // class 9 makes FUN_1000fca0 return after the visibility change + Marshal.WriteInt32(table.Owner, 0x530, FloatBits(100.0f)); + Marshal.WriteInt32(table.Owner, 0x534, FloatBits(200.0f)); + Marshal.WriteInt32(table.Owner, 0x538, FloatBits(300.0f)); + Marshal.WriteInt32(table.Owner, 0x4d8, FloatBits(40.0f)); + WriteProviderStageRow(table.Rows, 0, -1, 13.0f, 13.0f, 0.0f, 0, 3, 0x00); + Marshal.WriteInt32(table.Rows, 0x20, FloatBits(13.0f)); + + IntPtr aniInterface = fixture.Allocate(0x1b0); + IntPtr aniVtable = fixture.Allocate(0x50); + IntPtr meshRows = fixture.Allocate(0x130); + IntPtr nodeData = fixture.Allocate(0x26); + IntPtr slotData = fixture.Allocate(2 * 0x44); + IntPtr meshData = fixture.Allocate(3 * IntPtr.Size); + for (int word = 0; word < 19; word++) Marshal.WriteInt16(nodeData, word * 2, -1); + for (int stage = 0; stage < 3; stage++) + Marshal.WriteInt16(nodeData, 0x08 + stage * 5 * sizeof(ushort), 0); + // State 0,1,2 each expose slot 0; 0x11220 publishes visible stage 2 before 0x11920 queries it. + Marshal.WriteIntPtr(meshData, 0, nodeData); + Marshal.WriteIntPtr(meshData, 2 * IntPtr.Size, slotData); + Marshal.WriteIntPtr(aniInterface, 0, aniVtable); + Marshal.WriteIntPtr(aniInterface, 0x1a8, meshRows); + Marshal.WriteInt32(aniInterface, 0x1ac, 1); + Marshal.WriteInt32(aniInterface, 0x158, FloatBits(2.0f)); + Marshal.WriteInt32(aniInterface, 0x15c, FloatBits(3.0f)); + Marshal.WriteInt32(aniInterface, 0x160, FloatBits(5.0f)); + Marshal.WriteInt32(meshRows, 0x00, 0); // ANI model-instance ID used by FUN_10005780/57c0 + Marshal.WriteInt32(meshRows, 0x1c, 0); // current visible stage selects Node38 slot state 0 + Marshal.WriteIntPtr(meshRows, 0x12c, meshData); + Marshal.WriteInt32(slotData, 0x30, FloatBits(7.0f)); + Marshal.WriteInt32(slotData, 0x34, FloatBits(11.0f)); + Marshal.WriteInt32(slotData, 0x44 + 0x30, FloatBits(17.0f)); + Marshal.WriteInt32(slotData, 0x44 + 0x34, FloatBits(19.0f)); + + // Use the original ANI vtable entries exercised by FUN_10011920: + // node selector F/10, instance lookup/count, lifecycle flags, and visible stage. + activeNativeAniMeshNodeMetadataQuery = queryNode; + Marshal.WriteIntPtr(aniVtable, 0x0c, Marshal.GetFunctionPointerForDelegate(AniMeshNodeMetadataQueryCallback)); + activeNativeAniMeshNodeLifecycle = updateNodeLifecycle; + Marshal.WriteIntPtr(aniVtable, 0x20, Marshal.GetFunctionPointerForDelegate(AniMeshNodeLifecycleCallback)); + Marshal.WriteIntPtr(aniVtable, 0x38, IntPtr.Add(aniMeshModule, 0x05780)); + Marshal.WriteIntPtr(aniVtable, 0x3c, IntPtr.Add(aniMeshModule, 0x057c0)); + activeNativeAniMeshStageTransition = setNodeStage; + Marshal.WriteIntPtr(aniVtable, 0x44, Marshal.GetFunctionPointerForDelegate(AniMeshStageTransitionCallback)); + Marshal.WriteIntPtr(table.Owner, 0x20, aniInterface); + activeAniMeshInterface = aniInterface; + + IntPtr firstValueOut = fixture.Allocate(IntPtr.Size); + IntPtr secondValueOut = fixture.Allocate(IntPtr.Size); + Expect(NativeBoolean(queryNode(aniInterface, 0, 0x0f, firstValueOut)) == 1, + "AniMesh selector F reads the raw slot state through the original getter"); + IntPtr firstValue = Marshal.ReadIntPtr(firstValueOut); + Expect(ReadFloat(firstValue, 0) == 42.0f, + "AniMesh selector F scales slot+0x30 by both XY instance factors"); + Expect(NativeBoolean(queryNode(aniInterface, 0, 0x10, secondValueOut)) == 1, + "AniMesh selector 10 reads the second raw slot field through the original getter"); + IntPtr secondValue = Marshal.ReadIntPtr(secondValueOut); + Expect(firstValue == secondValue && ReadFloat(firstValue, 0) == 330.0f, + "AniMesh selectors F and 10 return the same scratch cell; the second query overwrites the first result"); + + activeControlProviderRows = table.Rows; + aniMeshNodeMetadataQueries.Clear(); + aniMeshNodeLifecycleCallbacks.Clear(); + aniMeshStageTransitions.Clear(); + controlProviderCallbackTrace.Clear(); + aniMeshCallbackOwnerMismatch = false; + nativeAniMeshStageCallbackMissing = false; + // At ratio zero, the native ceiling stage rule selects the depleted sentinel + // and reaches 0x11920's hide branch. Ratio one reopens that node. + updateStage(table.Owner, 0, 0); + IntPtr row = table.Rows; + IntPtr meshRow = meshRows; + Expect(unchecked((uint)Marshal.ReadInt32(row, 0x28)) == 0x220 && + unchecked((uint)Marshal.ReadInt32(row, 0x18)) == 3 && + unchecked((uint)Marshal.ReadInt32(meshRow, 0x14)) == 1 && + unchecked((uint)Marshal.ReadInt32(meshRow, 0x1c)) == 2, + "Control RVA 0x11920 hides an exhausted provider in both Control and the original AniMesh node state"); + Expect(String.Join(",", aniMeshNodeMetadataQueries.ToArray()) == "0:f:0x42280000,0:10:0x43a50000" && + !aniMeshCallbackOwnerMismatch && !nativeAniMeshStageCallbackMissing, + "Control RVA 0x11920 queries the shared AniMesh scratch cell before applying its aggregate changes"); + Console.WriteLine("native-control-provider-hide-values: row20=" + Float(ReadFloat(row, 0x20)) + + " totals=[" + Float(ReadFloat(table.Owner, 0x530)) + "," + Float(ReadFloat(table.Owner, 0x534)) + + "," + Float(ReadFloat(table.Owner, 0x538)) + "," + Float(ReadFloat(table.Owner, 0x4d8)) + + "] queries=[" + String.Join(",", aniMeshNodeMetadataQueries.ToArray()) + "]"); + Expect(ReadFloat(table.Owner, 0x530) == -230.0f && ReadFloat(table.Owner, 0x534) == -130.0f && + ReadFloat(table.Owner, 0x538) == 287.0f && FloatBits(ReadFloat(table.Owner, 0x4d8)) == FloatBits(42.6875f), + "Control RVA 0x11920 removes the aliased AniMesh value from aggregates and applies the volume adjustment"); + + Marshal.WriteInt32(row, 0x14, FloatBits(1.0f)); + updateStage(table.Owner, 0, 0); + Expect(unchecked((uint)Marshal.ReadInt32(row, 0x28)) == 0x200 && + unchecked((uint)Marshal.ReadInt32(row, 0x18)) == 0 && + unchecked((uint)Marshal.ReadInt32(meshRow, 0x14)) == 0 && + unchecked((uint)Marshal.ReadInt32(meshRow, 0x1c)) == 0, + "Control RVA 0x11920 shows the reopened provider and clears both Control and AniMesh visibility flags"); + Expect(ReadFloat(table.Owner, 0x530) == 100.0f && ReadFloat(table.Owner, 0x534) == 200.0f && + ReadFloat(table.Owner, 0x538) == 300.0f && FloatBits(ReadFloat(table.Owner, 0x4d8)) == FloatBits(40.0f), + "Control RVA 0x11920 restores provider aggregates on the paired show transition"); + Expect(String.Join(",", aniMeshNodeMetadataQueries.ToArray()) == + "0:f:0x42280000,0:10:0x43a50000,0:f:0x42280000,0:10:0x43a50000" && + String.Join(",", aniMeshNodeLifecycleCallbacks.ToArray()) == "0:100:1,0:101:5" && + String.Join(",", aniMeshStageTransitions.ToArray()) == "0:2,0:0", + "Native hide/show repeats the same F/10 queries and original AniMesh callbacks in order"); + + // The same native getter follows a new visible state: state 2 now selects + // the second MSH slot while state 0 still selects the first. + Marshal.WriteInt16(nodeData, 0x08 + 2 * 5 * sizeof(ushort), 1); + Marshal.WriteInt32(row, 0x14, FloatBits(0.0f)); + updateStage(table.Owner, 0, 0); + Expect(String.Join(",", aniMeshNodeMetadataQueries.ToArray()) == + "0:f:0x42280000,0:10:0x43a50000,0:f:0x42280000,0:10:0x43a50000," + + "0:f:0x42cc0000,0:10:0x440e8000" && + ReadFloat(table.Owner, 0x530) == -470.0f && ReadFloat(table.Owner, 0x534) == -370.0f && + ReadFloat(table.Owner, 0x538) == 287.0f && FloatBits(ReadFloat(table.Owner, 0x4d8)) == FloatBits(35.1875f), + "Control hide query follows visible state 2 and applies its different native mesh-slot value"); + Marshal.WriteInt32(row, 0x14, FloatBits(1.0f)); + updateStage(table.Owner, 0, 0); + Expect(String.Join(",", aniMeshNodeMetadataQueries.ToArray()) == + "0:f:0x42280000,0:10:0x43a50000,0:f:0x42280000,0:10:0x43a50000," + + "0:f:0x42cc0000,0:10:0x440e8000,0:f:0x42280000,0:10:0x43a50000" && + ReadFloat(table.Owner, 0x530) == -140.0f && ReadFloat(table.Owner, 0x534) == -40.0f && + ReadFloat(table.Owner, 0x538) == 300.0f && FloatBits(ReadFloat(table.Owner, 0x4d8)) == FloatBits(32.5f), + "Control show query returns to visible state 0 rather than reversing the prior state-2 contribution"); + Expect(String.Join(",", controlProviderCallbackTrace.ToArray()) == + "stage:0:2,lifecycle:0:100:1,stage:0:0,lifecycle:0:101:5," + + "stage:0:2,lifecycle:0:100:1,stage:0:0,lifecycle:0:101:5", + "Control and AniMesh visibility transitions preserve native callback order and arguments"); + Expect(!aniMeshCallbackOwnerMismatch && !nativeAniMeshStageCallbackMissing, + "Both visibility cycles preserve AniMesh callback owners and original function results"); + + Console.WriteLine("native-control-provider-visibility: controlHash=" + ExpectedControlSha256 + + " aniMeshHash=" + ExpectedAniMeshSha256 + " rva=0x11920 selectorF/10=same-scratch-cell " + + "visible-state-values=[42,330]=>[102,570] hide/show=stage-dependent"); + activeControlProviderRows = IntPtr.Zero; + activeAniMeshInterface = IntPtr.Zero; + activeNativeAniMeshNodeMetadataQuery = null; + activeNativeAniMeshStageTransition = null; + activeNativeAniMeshNodeLifecycle = null; + GC.KeepAlive(updateStage); + GC.KeepAlive(queryNode); + GC.KeepAlive(updateNodeLifecycle); + GC.KeepAlive(setNodeStage); + GC.KeepAlive(AniMeshNodeLifecycleCallback); + GC.KeepAlive(AniMeshStageTransitionCallback); + } + } + + private static void WriteProviderStageRow(IntPtr rows, int index, int parentIndex, + float amount, float processed, float normalized, uint currentStage, uint stageCount, uint flags) { + IntPtr row = IntPtr.Add(rows, index * 0x2c); + Marshal.WriteInt32(row, 0x04, parentIndex); + Marshal.WriteInt32(row, 0x08, FloatBits(amount)); + Marshal.WriteInt32(row, 0x0c, FloatBits(processed)); + Marshal.WriteInt32(row, 0x14, FloatBits(normalized)); + Marshal.WriteInt32(row, 0x18, unchecked((int)currentStage)); + Marshal.WriteInt32(row, 0x1c, unchecked((int)stageCount)); + Marshal.WriteInt32(row, 0x28, unchecked((int)flags)); + } + + private static NativeProviderTable CreateNativeProviderTable(Fixture fixture, IntPtr module, + float[] maxima, float[] amounts, byte[] rowFlags) { + Expect(maxima.Length == amounts.Length && maxima.Length == rowFlags.Length, + "native provider fixture arrays have matching lengths"); + NativeControlProviderRowConstructor construct = (NativeControlProviderRowConstructor) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(module, ControlProviderRowConstructorRva), + typeof(NativeControlProviderRowConstructor)); + NativeProviderTable table = new NativeProviderTable(); + table.Owner = fixture.Allocate(0x664); + table.Rows = fixture.Allocate(maxima.Length * 0x2c); + IntPtr providerInterface = IntPtr.Add(table.Owner, 4); + IntPtr providerVtable = IntPtr.Add(module, ControlProviderInterfaceVtableRva); + Marshal.WriteIntPtr(providerInterface, providerVtable); + Expect(Marshal.ReadIntPtr(providerVtable, 0x0c) == IntPtr.Add(module, ControlProviderType1GetterRva), + "native provider fixture uses the installed selector interface vtable"); + Marshal.WriteIntPtr(table.Owner, 0x55c, table.Rows); + Marshal.WriteInt32(table.Owner, 0x560, maxima.Length); + Marshal.WriteInt32(table.Owner, 0x548, FloatBits(1.0f)); + Marshal.WriteInt32(table.Owner, 0x660, FloatBits(1.0f)); + Marshal.WriteInt32(table.Owner, 0x550, 0xfffe); // Exclude the separate root-node depletion lifecycle. + Marshal.WriteInt32(table.Owner, 0x594, 0); + Marshal.WriteInt32(table.Owner, 0x598, 0); + Marshal.WriteInt32(table.Owner, 0x618, 0); + Marshal.WriteInt32(table.Owner, 0x386, 0); + + float totalMaximum = 0.0f; + float totalAmount = 0.0f; + for (int i = 0; i < maxima.Length; i++) { + IntPtr descriptor = fixture.Allocate(0x80); + IntPtr row = IntPtr.Add(table.Rows, i * 0x2c); + Marshal.WriteInt32(descriptor, 0x04, FloatBits(maxima[i])); + construct(row, descriptor); + Marshal.WriteInt32(row, 0x04, -1); // No component parent or stage chain. + Marshal.WriteInt32(row, 0x08, FloatBits(amounts[i])); + Marshal.WriteInt32(row, 0x10, 0); + Marshal.WriteInt32(row, 0x14, FloatBits(amounts[i] / maxima[i])); + Marshal.WriteInt32(row, 0x18, 0); + Marshal.WriteInt32(row, 0x1c, 0); + Marshal.WriteInt32(row, 0x24, -1); + Marshal.WriteByte(row, 0x28, rowFlags[i]); + totalMaximum += maxima[i]; + totalAmount += amounts[i]; + } + Marshal.WriteInt32(table.Owner, 0x58c, FloatBits(totalMaximum)); + Marshal.WriteInt32(table.Owner, 0x590, FloatBits(totalAmount)); + + IntPtr callbackObject = fixture.Allocate(IntPtr.Size); + IntPtr callbackVtable = fixture.Allocate(0x38); + Marshal.WriteIntPtr(callbackObject, 0, callbackVtable); + Marshal.WriteIntPtr(callbackVtable, 0x34, Marshal.GetFunctionPointerForDelegate(ControlNodeUpdateCallback)); + Marshal.WriteIntPtr(table.Owner, 0x20, callbackObject); + return table; + } + + private static float ReadNativeProviderAmount(NativeProviderTable table, int index) { + return ReadFloat(table.Rows, index * 0x2c + 0x08); + } + + private static byte ReadNativeProviderFlags(NativeProviderTable table, int index) { + return Marshal.ReadByte(table.Rows, index * 0x2c + 0x28); + } + + private static void RunNativeControlProviderDistributionCases(IntPtr module) { + NativeControlProviderAmountDistribute distribute = (NativeControlProviderAmountDistribute) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(module, ControlProviderAmountDistributeRva), + typeof(NativeControlProviderAmountDistribute)); + + using (Fixture fixture = NewFixture()) { + NativeProviderTable table = CreateNativeProviderTable(fixture, module, + new float[] { 30.0f, 60.0f, 50.0f }, new float[] { 10.0f, 20.0f, 0.0f }, + new byte[] { 0, 0, 0 }); + controlNodeUpdateCount = 0; + controlNodeUpdateIndices.Clear(); + distribute(table.Owner, 22.0f, 0, 0); + Expect(ReadNativeProviderAmount(table, 0) == 14.0f && + ReadNativeProviderAmount(table, 1) == 28.0f && + ReadNativeProviderAmount(table, 2) == 10.0f, + "Control native proportional amount distribution weights each row by its remaining capacity"); + Expect(controlNodeUpdateCount == 3 && controlNodeUpdateIndex == 2 && + controlNodeUpdateSelector == 0x200, + "Control proportional distribution publishes each row update through the existing native node callback"); + Expect(String.Join(",", controlNodeUpdateIndices.ConvertAll(index => index.ToString()).ToArray()) == "0,1,2", + "Control proportional distribution visits rows in ascending order"); + } + + using (Fixture fixture = NewFixture()) { + NativeProviderTable table = CreateNativeProviderTable(fixture, module, + new float[] { 30.0f, 60.0f, 50.0f }, new float[] { 10.0f, 20.0f, 30.0f }, + new byte[] { 0, 0, 0 }); + controlNodeUpdateIndices.Clear(); + distribute(table.Owner, -35.0f, 1, 0); + Expect(ReadNativeProviderAmount(table, 0) == 10.0f && + ReadNativeProviderAmount(table, 1) == 15.0f && + ReadNativeProviderAmount(table, 2) == 0.0f, + "Control native sequential withdrawal consumes rows in reverse order"); + Expect(String.Join(",", controlNodeUpdateIndices.ConvertAll(index => index.ToString()).ToArray()) == "2,1", + "Control sequential withdrawal calls the node updater from the last row backwards"); + } + + using (Fixture fixture = NewFixture()) { + NativeProviderTable table = CreateNativeProviderTable(fixture, module, + new float[] { 10.0f, 10.0f }, new float[] { 9.0f, 0.0f }, + new byte[] { 0, 0x10 }); + distribute(table.Owner, 10.0f, 1, 0); + Expect(ReadNativeProviderAmount(table, 0) == 10.0f && + ReadNativeProviderAmount(table, 1) == 0.0f && + (ReadNativeProviderFlags(table, 1) & 0x10) != 0, + "Control sequential distribution clips at active capacity and skips exhausted rows without revive"); + distribute(table.Owner, -20.0f, 1, 0); + Expect(ReadNativeProviderAmount(table, 0) == 0.0f && + (ReadNativeProviderFlags(table, 0) & 0x10) != 0, + "Control native depletion marks the row exhausted"); + distribute(table.Owner, 15.0f, 1, 1); + Expect(ReadNativeProviderAmount(table, 0) == 10.0f && + ReadNativeProviderAmount(table, 1) == 5.0f && + (ReadNativeProviderFlags(table, 0) & 0x10) == 0 && + (ReadNativeProviderFlags(table, 1) & 0x10) == 0, + "Control native revive flag admits exhausted rows and clears their exhausted flags when refilled"); + } + + using (Fixture fixture = NewFixture()) { + NativeProviderTable table = CreateNativeProviderTable(fixture, module, + new float[] { 33554432.0f, 10.0f }, new float[] { 16777216.0f, 2.0f }, + new byte[] { 0, 0 }); + controlNodeUpdateIndices.Clear(); + distribute(table.Owner, -1.0f, 0, 0); + uint firstBits = unchecked((uint)FloatBits(ReadNativeProviderAmount(table, 0))); + uint secondBits = unchecked((uint)FloatBits(ReadNativeProviderAmount(table, 1))); + uint totalBits = unchecked((uint)FloatBits(ReadFloat(table.Owner, 0x590))); + Expect(firstBits == unchecked((uint)FloatBits(16777214.0f)) && + secondBits == 0x3ffffffe && totalBits == unchecked((uint)FloatBits(16777216.0f)), + "Control proportional distribution preserves the native x87 add-then-subtract rounding at a 2^24 cancellation boundary; actual=[" + + Hex(firstBits) + "," + Hex(secondBits) + "] total=" + Hex(totalBits)); + } + + Console.WriteLine("native-control-provider-distribution: controlHash=" + ExpectedControlSha256 + + " rva=0x10ba0 providerVtable=0x3d254 selector3=0xdc40 proportional=[14,28,10]" + + " sequentialReverse=[10,15,0] cap/exhausted/revive=verified cancellation=2^24"); + GC.KeepAlive(distribute); + } + + private static void RunNativeControlContactRateUpdateCase(IntPtr module) { + NativeControlContactRateUpdate update = (NativeControlContactRateUpdate) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(module, ControlContactRateUpdateRva), + typeof(NativeControlContactRateUpdate)); + using (Fixture fixture = NewFixture()) { + NativeProviderTable table = CreateNativeProviderTable(fixture, module, + new float[] { 100.0f }, new float[] { 10.000001f }, new byte[] { 0 }); + IntPtr profile = fixture.Allocate(0x6c); + Marshal.WriteInt32(table.Owner, 0x50, 4); + Marshal.WriteInt32(table.Owner, 0x1a4, FloatBits(1.0f)); + Marshal.WriteIntPtr(table.Owner, 0x46c, profile); + Marshal.WriteInt32(profile, 0x68, FloatBits(1.0f)); + Marshal.WriteInt32(table.Owner, 0x4d8, FloatBits(1.0f)); + Marshal.WriteInt32(table.Owner, 0x354, FloatBits(1.0f)); + Marshal.WriteInt32(table.Owner, 0x358, FloatBits(1.0f)); + Marshal.WriteInt32(table.Owner, 0x1a8, FloatBits(1.0f)); + controlNodeUpdateCount = 0; + + update(table.Owner, 2.0f); + Expect(FloatBits(ReadNativeProviderAmount(table, 0)) == FloatBits(8.000001f) && + FloatBits(ReadFloat(table.Rows, 0x10)) == FloatBits(-2.0f) && + ReadFloat(table.Owner, 0x590) == 8.000001f, + "Control class-4 contact-rate update applies negative rate times elapsed seconds and publishes animation amount"); + const int expectedNormalizedBits = unchecked((int)0x3da3d70c); + Expect(Marshal.ReadByte(table.Owner, 0x598) == 0 && + FloatBits(ReadFloat(table.Owner, 0x588)) == expectedNormalizedBits && + controlNodeUpdateCount == 1 && controlNodeUpdateValueBits == unchecked((uint)expectedNormalizedBits), + "Control class-4 contact-rate update clears its dirty state after computing the aggregate and provider callback"); + Console.WriteLine("native-control-contact-rate-update: controlHash=" + ExpectedControlSha256 + + " rva=0x12a40 class=4 dt=2 rate=1 current=10.000001->8.000001 animation=-2 normalizedBits=0x" + + unchecked((uint)FloatBits(ReadFloat(table.Owner, 0x588))).ToString("x8") + " dirty=cleared"); + } + GC.KeepAlive(update); + } + + private static void RunNativeControlTimedUpdateBaselineCases(IntPtr module) { + NativeControlTimedUpdate update = (NativeControlTimedUpdate) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(module, ControlTimedUpdateRva), + typeof(NativeControlTimedUpdate)); + using (Fixture fixture = NewFixture()) { + IntPtr owner = fixture.Allocate(0x664); + controlNodeUpdateCount = 0; + update(owner, 0.5f); + Expect(controlNodeUpdateCount == 0 && ReadFloat(owner, 0xe8) == 0.5f && + ReadFloat(owner, 0xe4) == 0.0f && ReadFloat(owner, 0xec) == 0.0f && + ReadFloat(owner, 0xd8) == 0.0f && ReadFloat(owner, 0xdc) == 0.0f, + "Control timed update records the sub-threshold delta without entering its active callback path"); + update(owner, 1.0f); + Expect(controlNodeUpdateCount == 0 && ReadFloat(owner, 0xe8) == 1.0f && + ReadFloat(owner, 0xe4) == 1.0f && ReadFloat(owner, 0xec) == 1.0f && + ReadFloat(owner, 0xd8) == 1.0f && ReadFloat(owner, 0xdc) == 1.0f && + Marshal.ReadByte(owner, 0xe0) == 0, + "Control timed update accepts the one-unit boundary and synchronizes its baseline while e0 remains clear"); + update(owner, 2.0f); + Expect(controlNodeUpdateCount == 0 && ReadFloat(owner, 0xe8) == 1.0f && + ReadFloat(owner, 0xe4) == 2.0f && ReadFloat(owner, 0xec) == 2.0f && + ReadFloat(owner, 0xd8) == 2.0f && ReadFloat(owner, 0xdc) == 2.0f && + Marshal.ReadByte(owner, 0xe0) == 0, + "Control timed update keeps synchronizing accepted times without starting the active branch while e0 is clear"); + Console.WriteLine("native-control-timed-update-baseline: controlHash=" + ExpectedControlSha256 + + " rva=0xbcf0 sub-threshold=0.5 accepted=[1,2] e4/ec/d8/dc synchronized owner.e0=0 callback=none"); + } + GC.KeepAlive(update); + } + private static void RunNativeControlAggregateResourceCases(IntPtr module) { NativeControlAggregateQuery query = (NativeControlAggregateQuery)Marshal.GetDelegateForFunctionPointer( WriteStdCallToFastcallThunk(0x1c0, IntPtr.Add(module, ControlResourceAggregateQueryRva)), @@ -888,6 +1683,229 @@ internal static class BehaviorDistributorTickOracle { } } + private static void RunNativeAniMeshScaleLoadSnapshot(IntPtr module) { + uint[] actual = new uint[] { + unchecked((uint)Marshal.ReadInt32(IntPtr.Add(module, 0x26068))), + unchecked((uint)Marshal.ReadInt32(IntPtr.Add(module, 0x2606c))), + unchecked((uint)Marshal.ReadInt32(IntPtr.Add(module, 0x26070))) + }; + Expect(actual[0] == 0x3f800000 && actual[1] == 0x3f800000 && actual[2] == 0x3f800000, + "AniMesh module load initializes all three runtime scale globals to 1.0"); + Console.WriteLine("native-anim-mesh-scale-load-snapshot: aniMeshHash=" + ExpectedAniMeshSha256 + + " globals=[" + String.Join(",", Array.ConvertAll(actual, Hex)) + "]"); + } + + private static void RunNativeAniMeshNodeMetadataCases(IntPtr module) { + NativeAniMeshNodeMetadataQuery query = (NativeAniMeshNodeMetadataQuery)Marshal.GetDelegateForFunctionPointer( + IntPtr.Add(module, AniMeshNodeMetadataQueryRva), typeof(NativeAniMeshNodeMetadataQuery)); + NativeAniMeshNodeStageCount stageCount = (NativeAniMeshNodeStageCount)Marshal.GetDelegateForFunctionPointer( + IntPtr.Add(module, AniMeshNodeStageCountRva), typeof(NativeAniMeshNodeStageCount)); + + using (Fixture fixture = new Fixture()) { + IntPtr owner = fixture.Allocate(0x1b0); + IntPtr meshRows = fixture.Allocate(3 * 0x130); + IntPtr nodeData = fixture.Allocate(3 * 0x26); + IntPtr slotData = fixture.Allocate(3 * 0x44); + IntPtr meshData = fixture.Allocate(3 * IntPtr.Size); + IntPtr result = fixture.Allocate(IntPtr.Size); + Marshal.WriteIntPtr(meshData, 0, nodeData); + Marshal.WriteIntPtr(meshData, 2 * IntPtr.Size, slotData); + Marshal.WriteIntPtr(owner, 0x1a8, meshRows); + Marshal.WriteInt32(owner, 0x1ac, 3); + + ushort[] headerFlags = new ushort[] { 0x8201, 0x0180, 0x0400 }; + int[] rawParentIndices = new int[] { 3, 0, 1 }; + int[] runtimeParentIndices = new int[] { -1, 22, 7 }; + for (int nodeIndex = 0; nodeIndex < 3; nodeIndex++) { + IntPtr rawNode = IntPtr.Add(nodeData, nodeIndex * 0x26); + for (int word = 0; word < 19; word++) Marshal.WriteInt16(rawNode, word * 2, -1); + Marshal.WriteInt16(rawNode, 0, unchecked((short)headerFlags[nodeIndex])); + Marshal.WriteInt16(rawNode, 2, unchecked((short)rawParentIndices[nodeIndex])); + + IntPtr meshRow = IntPtr.Add(meshRows, nodeIndex * 0x130); + Marshal.WriteInt32(meshRow, 8, nodeIndex); + Marshal.WriteInt32(meshRow, 0x18, runtimeParentIndices[nodeIndex]); + Marshal.WriteIntPtr(meshRow, 0x12c, meshData); + } + + // Node 0: state0 present, state1 absent, state2 present. Native + // GetStateCount stops at the first missing state, so it returns 1. + WriteNode38Slot(nodeData, 0, 0, 0); + WriteNode38Slot(nodeData, 0, 2, 2); + // Node 1: the prefix is empty even though later states are present. + WriteNode38Slot(nodeData, 1, 1, 1); + WriteNode38Slot(nodeData, 1, 2, 2); + // Node 2: all three consecutive state slots are present. + WriteNode38Slot(nodeData, 2, 0, 0); + WriteNode38Slot(nodeData, 2, 1, 1); + WriteNode38Slot(nodeData, 2, 2, 2); + + for (uint nodeIndex = 0; nodeIndex < 3; nodeIndex++) { + Marshal.WriteIntPtr(result, IntPtr.Zero); + Expect(NativeBoolean(query(owner, nodeIndex, 0x0d, result)) == 1, + "AniMesh selector D returns runtime parent metadata"); + IntPtr parent = Marshal.ReadIntPtr(result); + Expect(runtimeParentIndices[nodeIndex] != rawParentIndices[nodeIndex], + "AniMesh runtime parent fixture differs from the raw Node38 parent"); + Expect(Marshal.ReadInt32(parent) == runtimeParentIndices[nodeIndex], + "AniMesh selector D copies the indexed global runtime parent, not the raw Node38 link"); + + Marshal.WriteIntPtr(result, IntPtr.Zero); + Expect(NativeBoolean(query(owner, nodeIndex, 0x0e, result)) == 1, + "AniMesh selector E returns the Node38 header word"); + IntPtr flags = Marshal.ReadIntPtr(result); + Expect(unchecked((uint)Marshal.ReadInt32(flags)) == headerFlags[nodeIndex], + "AniMesh selector E points to the indexed Node38 hdr0"); + } + + uint[] expectedStageCounts = new uint[] { 1, 0, 3 }; + for (uint nodeIndex = 0; nodeIndex < expectedStageCounts.Length; nodeIndex++) { + Expect(stageCount(owner, nodeIndex) == expectedStageCounts[nodeIndex], + "AniMesh stage count is the consecutive state0-2 prefix"); + } + Console.WriteLine("native-anim-mesh-control-node-metadata: aniMeshHash=" + ExpectedAniMeshSha256 + + " D=runtime-parent E=Node38-hdr0 stage-prefix=[1,0,3]"); + } + GC.KeepAlive(query); + GC.KeepAlive(stageCount); + } + + private static void RunNativeControlProviderInitialStateCase(IntPtr controlModule, IntPtr aniMeshModule) { + const int rowCount = 4; + NativeControlOwnerConstructor constructOwner = (NativeControlOwnerConstructor)Marshal.GetDelegateForFunctionPointer( + IntPtr.Add(controlModule, ControlOwnerConstructorRva), typeof(NativeControlOwnerConstructor)); + NativeControlProviderRowConstructor constructProviderRow = (NativeControlProviderRowConstructor) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(controlModule, ControlProviderRowConstructorRva), + typeof(NativeControlProviderRowConstructor)); + NativeControlProviderInitialState initialize = (NativeControlProviderInitialState) + Marshal.GetDelegateForFunctionPointer(IntPtr.Add(controlModule, ControlProviderInitialStateRva), + typeof(NativeControlProviderInitialState)); + using (Fixture fixture = NewFixture()) { + IntPtr owner = fixture.Allocate(0x664); + Expect(constructOwner(owner, IntPtr.Zero, 4) == owner, + "Control constructor initializes a synthetic class-4 owner without a host object"); + Expect(unchecked((uint)Marshal.ReadInt32(owner, 0x548)) == 0x3f800000 && + unchecked((uint)Marshal.ReadInt32(owner, 0x660)) == 0x3f800000, + "Control constructor starts both provider getter scale factors at 1.0"); + + IntPtr aniOwner = fixture.Allocate(0x1b0); + IntPtr aniVtable = fixture.Allocate(0x4c); + IntPtr meshRows = fixture.Allocate(rowCount * 0x130); + IntPtr nodeData = fixture.Allocate(rowCount * 0x26); + IntPtr slotData = fixture.Allocate(rowCount * 0x44); + IntPtr meshData = fixture.Allocate(3 * IntPtr.Size); + IntPtr providerRows = fixture.Allocate(rowCount * 0x2c); + Marshal.WriteIntPtr(meshData, 0, nodeData); + Marshal.WriteIntPtr(meshData, 2 * IntPtr.Size, slotData); + Marshal.WriteIntPtr(aniOwner, 0, aniVtable); + Marshal.WriteIntPtr(aniOwner, 0x1a8, meshRows); + Marshal.WriteInt32(aniOwner, 0x1ac, rowCount); + Marshal.WriteIntPtr(aniVtable, 0x0c, IntPtr.Add(aniMeshModule, AniMeshNodeMetadataQueryRva)); + Marshal.WriteIntPtr(aniVtable, 0x34, Marshal.GetFunctionPointerForDelegate(ControlNodeUpdateCallback)); + Marshal.WriteIntPtr(aniVtable, 0x48, IntPtr.Add(aniMeshModule, AniMeshNodeStageCountRva)); + + ushort[] headers = { 0x8201, 0x0180, 0x0400, 0x0001 }; + int[] rawParents = { 3, 0, 1, 0 }; + int[] runtimeParents = { -1, 22, 7, 11 }; + float[] sourceMaxima = { 30.0f, 60.0f, 50.0f, 0.0f }; + for (int nodeIndex = 0; nodeIndex < rowCount; nodeIndex++) { + IntPtr rawNode = IntPtr.Add(nodeData, nodeIndex * 0x26); + for (int word = 0; word < 19; word++) Marshal.WriteInt16(rawNode, word * 2, -1); + Marshal.WriteInt16(rawNode, 0, unchecked((short)headers[nodeIndex])); + Marshal.WriteInt16(rawNode, 2, unchecked((short)rawParents[nodeIndex])); + + IntPtr meshRow = IntPtr.Add(meshRows, nodeIndex * 0x130); + Marshal.WriteInt32(meshRow, 8, nodeIndex); + Marshal.WriteInt32(meshRow, 0x18, runtimeParents[nodeIndex]); + Marshal.WriteIntPtr(meshRow, 0x12c, meshData); + + IntPtr descriptor = fixture.Allocate(0x4c); + Marshal.WriteInt32(descriptor, 0x04, FloatBits(sourceMaxima[nodeIndex])); + constructProviderRow(IntPtr.Add(providerRows, nodeIndex * 0x2c), descriptor); + } + // Stage counts are the consecutive state-0/1/2 prefix; Control + // changes an empty prefix to one for its initial provider row. + WriteNode38Slot(nodeData, 0, 0, 0); + WriteNode38Slot(nodeData, 0, 2, 2); + WriteNode38Slot(nodeData, 1, 1, 1); + WriteNode38Slot(nodeData, 1, 2, 2); + WriteNode38Slot(nodeData, 2, 0, 0); + WriteNode38Slot(nodeData, 2, 1, 1); + WriteNode38Slot(nodeData, 2, 2, 2); + + Marshal.WriteIntPtr(owner, 0x20, aniOwner); + Marshal.WriteIntPtr(owner, 0x55c, providerRows); + Marshal.WriteInt32(owner, 0x560, rowCount); + IntPtr providerVtable = Marshal.ReadIntPtr(IntPtr.Add(owner, 4)); + Expect(providerVtable != IntPtr.Zero && + Marshal.ReadIntPtr(providerVtable, 0x0c) == IntPtr.Add(controlModule, ControlProviderType1GetterRva), + "Control constructor installs the original selector-3 provider vtable"); + + controlNodeUpdateCount = 0; + controlNodeUpdateIndices.Clear(); + initialize(owner); + uint[] expectedFlags = { 0x09, 0x02, 0x04, 0x08 }; + uint[] expectedStages = { 1, 1, 3, 1 }; + for (int nodeIndex = 0; nodeIndex < rowCount; nodeIndex++) { + IntPtr row = IntPtr.Add(providerRows, nodeIndex * 0x2c); + Console.WriteLine("native-control-f940-row=" + nodeIndex + " parent=" + Marshal.ReadInt32(row, 0x04) + + " amount=" + Hex(unchecked((uint)Marshal.ReadInt32(row, 0x08))) + + " processed=" + Hex(unchecked((uint)Marshal.ReadInt32(row, 0x0c))) + + " normalized=" + Hex(unchecked((uint)Marshal.ReadInt32(row, 0x14))) + + " stages=" + Hex(unchecked((uint)Marshal.ReadInt32(row, 0x1c))) + + " flags=" + Hex(unchecked((uint)Marshal.ReadInt32(row, 0x28)))); + uint expectedAmount = unchecked((uint)FloatBits(sourceMaxima[nodeIndex])); + Expect(Marshal.ReadInt32(row, 0x04) == runtimeParents[nodeIndex] && + unchecked((uint)Marshal.ReadInt32(row, 0x08)) == expectedAmount && + unchecked((uint)Marshal.ReadInt32(row, 0x0c)) == expectedAmount && + unchecked((uint)Marshal.ReadInt32(row, 0x14)) == 0x3f800000 && + unchecked((uint)Marshal.ReadInt32(row, 0x1c)) == expectedStages[nodeIndex] && + unchecked((uint)Marshal.ReadInt32(row, 0x28)) == expectedFlags[nodeIndex], + "Control f940 initializes row " + nodeIndex + " from AniMesh metadata and selector-3 amount"); + } + Expect(unchecked((uint)Marshal.ReadInt32(owner, 0x590)) == 0x430c0000 && + unchecked((uint)Marshal.ReadInt32(owner, 0x58c)) == 0x430c0000, + "Control f940 stores the sum of initial row amounts in both provider aggregates"); + Expect(controlNodeUpdateCount == rowCount && + String.Join(",", controlNodeUpdateIndices.ConvertAll(index => index.ToString()).ToArray()) == "0,1,2,3" && + controlNodeUpdateSelector == 0x200 && controlNodeUpdateValueBits == 0x3f800000, + "Control f940 notifies the host once per row in native append order"); + + // Selector 3 is the shared maximum getter. A non-unity owner scale + // exercises its native multiplication before the same initializer. + Marshal.WriteInt32(owner, 0x660, FloatBits(1.5f)); + Marshal.WriteInt32(owner, 0x548, FloatBits(0.5f)); + controlNodeUpdateCount = 0; + controlNodeUpdateIndices.Clear(); + initialize(owner); + uint[] scaledAmounts = { 0x41b40000, 0x42340000, 0x42160000, 0x00000000 }; + for (int nodeIndex = 0; nodeIndex < rowCount; nodeIndex++) { + IntPtr row = IntPtr.Add(providerRows, nodeIndex * 0x2c); + Expect(unchecked((uint)Marshal.ReadInt32(row, 0x08)) == scaledAmounts[nodeIndex] && + unchecked((uint)Marshal.ReadInt32(row, 0x0c)) == scaledAmounts[nodeIndex], + "Control f940 selector-3 scaled amount row " + nodeIndex); + } + Expect(unchecked((uint)Marshal.ReadInt32(owner, 0x590)) == 0x42d20000 && + unchecked((uint)Marshal.ReadInt32(owner, 0x58c)) == 0x42d20000, + "Control f940 aggregates its non-unity selector-3 results"); + Expect(controlNodeUpdateCount == rowCount && + String.Join(",", controlNodeUpdateIndices.ConvertAll(index => index.ToString()).ToArray()) == "0,1,2,3", + "Control f940 retains callback order for non-unity amounts"); + + Console.WriteLine("native-control-provider-initial-state: controlHash=" + ExpectedControlSha256 + + " rva=0xf940 selector3=0xdc40 rows=4 unity=[30,60,50,0] nonunity=[22.5,45,37.5,0]" + + " current=processed=sourceMax*owner660*owner548 ratio=1 parents=[-1,22,7,11]"); + GC.KeepAlive(constructOwner); + GC.KeepAlive(constructProviderRow); + GC.KeepAlive(initialize); + } + } + + private static void WriteNode38Slot(IntPtr nodeData, int nodeIndex, int state, ushort slotIndex) { + int wordIndex = nodeIndex * 19 + 4 + state * 5; + Marshal.WriteInt16(nodeData, wordIndex * 2, unchecked((short)slotIndex)); + } + private static void RunNativeControlIntoOverrideCase(IntPtr module) { NativeControlResourceComponentOverride applyOverride = (NativeControlResourceComponentOverride)Marshal.GetDelegateForFunctionPointer( IntPtr.Add(module, ControlResourceComponentOverrideRva), typeof(NativeControlResourceComponentOverride)); @@ -1641,6 +2659,58 @@ internal static class BehaviorDistributorTickOracle { } } + private static void RunOreAllocationBranch( + TickDelegate tick, string label, float rate, float stock, float recipientCurrent, float recipientMaximum, + float expectedProducerRemaining, float expectedRecipientResult) { + using (Fixture fixture = NewFixture()) { + NativeObject producer = fixture.AddObject(0x46, 0x80000004, 0.0f, rate, stock, 0); + producer.PropertyMetadata = FloatBits(10.0f); + NativeObject recipient = fixture.AddObject(0x47, 0x80000001, 0.0f, 0.0f, recipientCurrent, 0); + recipient.PropertyMetadata = FloatBits(recipientMaximum); + recipient.InterfaceSelector1 = 0.5f; + recipient.InterfaceSelector2 = 0.0f; + fixture.MakeDistributor(producer.Key, recipient.Key); + Marshal.WriteInt32(fixture.Entries, 0x04, FloatBits(1.0f)); + Marshal.WriteInt32(fixture.Entries, 0x1c + 0x04, FloatBits(0.5f)); + active = fixture; + tick(fixture.Distributor, 1.0f); + Console.WriteLine(label + ": totals=[" + Float(ReadFloat(fixture.Distributor, 0x30)) + "," + + Float(ReadFloat(fixture.Distributor, 0x34)) + "," + Float(ReadFloat(fixture.Distributor, 0x38)) + "," + + Float(ReadFloat(fixture.Distributor, 0x3c)) + "," + Float(ReadFloat(fixture.Distributor, 0x40)) + + "]; stored=[" + Float(producer.Property) + "," + Float(recipient.Property) + "] reads=" + producer.OreRateReads); + Expect(ReadFloat(fixture.Distributor, 0x34) == Math.Min(rate, stock) && + ReadFloat(fixture.Distributor, 0x40) == recipientMaximum - recipientCurrent && + producer.Property == expectedProducerRemaining && recipient.Property == expectedRecipientResult && + producer.OreRateReads == 2 && producer.Writes == 1 && recipient.Writes == 1 && fixture.LookupCount == 4, + label + " native allocation branch totals and two-pass reread"); + } + } + + private static void RunNativeOreClampCases(TickDelegate tick) { + float[][] states = { + new float[] { 0.995f, 1.0f, 1.0f }, + new float[] { 1.25f, 1.0f, 1.0f }, + new float[] { 0.0f, 0.01f, 0.0f } + }; + foreach (float[] state in states) { + float current = state[0]; + float maximum = state[1]; + float expected = state[2]; + using (Fixture fixture = NewFixture()) { + NativeObject item = fixture.AddObject(0x48, 0x80000001, 0.0f, 0.0f, current, 0); + item.PropertyMetadata = FloatBits(maximum); + item.InterfaceSelector2 = 0.0f; + fixture.MakeDistributor(item.Key); + active = fixture; + tick(fixture.Distributor, 1.0f); + Expect(item.Property == expected && item.Writes > 0 && fixture.LookupCount == 2, + "native first-pass ore clamp for CurrentOre=" + Float(current)); + Console.WriteLine("native-ore-clamp: current=" + Float(current) + " maximum=" + Float(maximum) + " result=" + + Float(item.Property) + " writes=" + item.Writes); + } + } + } + private static void RunMixedPowerCase(TickDelegate tick, string label, float powerRate, float recipientProperty, float selector1, float selector2) { using (Fixture fixture = NewFixture()) { NativeObject producer = fixture.AddObject(0x61, 0x80000002, powerRate, 0.0f, 1.0f, 0); |
