aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime
diff options
context:
space:
mode:
Diffstat (limited to 'crates/fparkan-runtime')
-rw-r--r--crates/fparkan-runtime/src/lib.rs2166
-rw-r--r--crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs493
2 files changed, 2580 insertions, 79 deletions
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index a4985a6..b4c13df 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -1,14 +1,17 @@
#![forbid(unsafe_code)]
//! Runtime orchestration for mission loading and world stepping.
+#[cfg(test)]
+use fparkan_assets::PreparedControlResourcePair;
use fparkan_assets::{
decode_mission_land_path, decode_mission_payload, decode_nres_payload,
derive_mission_land_paths, extend_graph_report_with_visual_dependencies,
mission_script_bundle_bases, prepare_terrain_world, AssetError as AssetPreparationError,
- AssetId, AssetManager, BuildCategory, MissionAssetPlan, MissionDocument, MissionError,
- MissionTerrainPaths, NresError, PreparedComponentControl, PreparedControlEffectSection,
- PreparedControlTypedRecord, PreparedVisual, TerrainFormatError, TerrainPreparationError,
- TerrainWorld, TmaProfile,
+ AssetId, AssetManager, BehaviorProfileRates, BehaviorProfileVarError, BuildCategory,
+ MissionAssetPlan, MissionDocument, MissionError, MissionTerrainPaths, NresError,
+ PreparedComponentControl, PreparedControlEffectSection, PreparedControlNodeDataRow,
+ PreparedControlNodeDataTable, PreparedControlTypedRecord, PreparedVisual, TerrainFormatError,
+ TerrainPreparationError, TerrainWorld, TmaProfile,
};
use fparkan_path::{normalize_relative, NormalizedPath, PathError, PathPolicy};
use fparkan_prototype::{
@@ -28,6 +31,7 @@ use fparkan_world::{
step, transform_state, InputSnapshot, ObjectDraft, ObjectHandle, OriginalObjectId,
TransformState, World, WorldConfig, WorldSnapshot,
};
+use std::collections::HashMap;
use std::num::NonZeroUsize;
use std::sync::Arc;
@@ -151,6 +155,23 @@ pub struct BehaviorOreState {
pub maximum_ore_bits: u32,
}
+/// Initial Behavior rates loaded for one full Unit DAT mission object.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct BehaviorProfileState {
+ /// Stable identity from the source TMA object order.
+ pub original_id: OriginalObjectId,
+ /// Corresponding live Rust world object.
+ pub handle: ObjectHandle,
+ /// Class word recovered from the root Unit DAT header.
+ pub class_flags: u32,
+ /// Profile selected by the native class mapper; unknown classes use defaults.
+ pub profile_entry: Option<&'static str>,
+ /// Raw bits of `Transfer_Ore_OffBoard` after applying the profile.
+ pub transfer_ore_off_board_bits: u32,
+ /// Raw bits of `Transfer_Power_Out` after applying the profile.
+ pub transfer_power_out_bits: u32,
+}
+
/// Origin of a Control descriptor retained in the effective table projection.
#[derive(Clone, Debug, PartialEq)]
pub struct ControlDeviceRecordProvenance {
@@ -178,6 +199,8 @@ pub struct EffectiveControlDevice {
pub coefficient_bits: Option<[u32; 16]>,
/// Multiplier bits when the factory default is confirmed.
pub multiplier_bits: Option<u32>,
+ /// Class-9-only scale used by its selector-0 getter.
+ pub class9_selector0_scale_bits: Option<u32>,
/// Current native word at `+0x50` when it is known.
pub native_word_50_bits: Option<u32>,
/// Current raw descriptor, including typed values and string bytes.
@@ -188,6 +211,104 @@ pub struct EffectiveControlDevice {
pub descriptor_provenance: ControlDeviceRecordProvenance,
}
+/// 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.
+#[derive(Clone, Debug, PartialEq)]
+pub struct MissionControlNodeProviderRow {
+ /// NDP resource that contributed the row.
+ pub source: ResourceKey,
+ /// Unit DAT component that contributed the row.
+ pub unit_component_index: usize,
+ /// Index in that component's original NDP table.
+ pub source_row_index: usize,
+ /// Original NDP descriptor fields and provenance for this provider row.
+ pub source_row: PreparedControlNodeDataRow,
+ /// Initial native provider selector-1 value (`+0x14`) as raw bits.
+ pub initial_type1_value_bits: u32,
+}
+
+/// Availability of the initial global Control node-data provider projection.
+#[derive(Clone, Debug, PartialEq)]
+pub enum MissionControlNodeProviderTableStatus {
+ /// Rows in native append order, without padding to the MSH node count.
+ Available(Vec<MissionControlNodeProviderRow>),
+ /// Provider lookup is not modeled for this object's available inputs.
+ Unavailable(MissionControlNodeProviderTableUnavailableReason),
+}
+
+/// Why the global Control node-data provider could not be projected.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub enum MissionControlNodeProviderTableUnavailableReason {
+ /// A root or mounted EXTO Control resource has no resolved NDP sidecar.
+ MissingNodeData {
+ /// Unit DAT component needing the provider rows.
+ unit_component_index: usize,
+ /// Explicitly requested sidecar when the reference was known.
+ source: Option<ResourceKey>,
+ },
+ /// A mounted EXTO needs a first NDP row for the native skip-first path.
+ MissingExToRootRow { unit_component_index: usize },
+ /// The Control component traversal itself was incomplete.
+ DeviceTableUnavailable(MissionControlDeviceTableUnavailableReason),
+}
+
+/// Why a loaded Control resource query or write could not be represented.
+#[derive(Debug, Eq, PartialEq)]
+pub enum ControlResourceAccessError {
+ /// The requested world object handle is invalid, stale, or deleted.
+ World(fparkan_world::WorldError),
+ /// No mission is currently loaded.
+ MissionUnavailable,
+ /// The live object is not part of the loaded mission projection.
+ ObjectUnavailable { handle: ObjectHandle },
+ /// The object's Control table could not be completely projected.
+ TableUnavailable(MissionControlDeviceTableUnavailableReason),
+ /// The requested resource selector is not implemented for this operation.
+ UnsupportedSelector(u32),
+ /// A selected row has a factory class whose getter has not been checked.
+ UnsupportedFactoryTag { factory_tag: u32 },
+ /// A device index does not exist in the object's native Control table.
+ DeviceIndexOutOfRange {
+ /// Requested global Control device index.
+ device_index: usize,
+ /// Projected device count.
+ device_count: usize,
+ },
+ /// The node provider table could not be projected.
+ NodeProviderTableUnavailable(MissionControlNodeProviderTableUnavailableReason),
+ /// A device's native provider key exceeds the actual appended NDP rows.
+ NodeProviderKeyOutOfRange {
+ /// Current native device key, used directly as a provider row index.
+ key: u32,
+ /// Actual global provider row count.
+ row_count: usize,
+ },
+ /// A native tag has an e00 callback that has not been implemented here.
+ UnsupportedCurrentTag { tag: u32 },
+ /// A selected row lacks a value needed by the native getter or setter.
+ UnsupportedField {
+ factory_tag: u32,
+ field: &'static str,
+ },
+ /// A native float operand or intermediate is not finite.
+ NonFiniteValue {
+ factory_tag: u32,
+ field: &'static str,
+ },
+ /// A native float operand is subnormal and is outside the checked domain.
+ SubnormalValue {
+ factory_tag: u32,
+ field: &'static str,
+ },
+ /// A range probe places a nonzero arithmetic result outside normal f32 range.
+ UnsupportedFloatRange {
+ factory_tag: Option<u32>,
+ field: &'static str,
+ },
+}
+
/// Why the base Control device table could not be projected for an object.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MissionControlDeviceTableUnavailableReason {
@@ -244,6 +365,22 @@ pub struct MissionControlDeviceTableState {
pub handle: ObjectHandle,
/// Complete base projection, or an explicit unsupported boundary.
pub status: MissionControlDeviceTableStatus,
+ /// Initial global NDP provider rows used by indexed Control selectors.
+ pub node_provider_status: MissionControlNodeProviderTableStatus,
+}
+
+struct ControlDeviceProjection {
+ devices: Vec<EffectiveControlDevice>,
+ node_provider_status: MissionControlNodeProviderTableStatus,
+}
+
+#[derive(Clone, Copy)]
+struct PreparedBehaviorProfileState {
+ original_id: OriginalObjectId,
+ class_flags: u32,
+ profile_entry: Option<&'static str>,
+ transfer_ore_off_board_bits: u32,
+ transfer_power_out_bits: u32,
}
/// Resource distributor state associated with one TMA clan's constructed AI.
@@ -579,6 +716,7 @@ struct LoadedMissionState {
object_drafts: Vec<MissionObjectDraft>,
behavior_distributors: Vec<BehaviorDistributorState>,
behavior_ore_states: Vec<BehaviorOreState>,
+ behavior_profiles: Vec<BehaviorProfileState>,
control_device_tables: Vec<MissionControlDeviceTableState>,
script_bundles: Vec<MissionScriptBundle>,
script_varset: Option<MissionScriptVarSet>,
@@ -686,6 +824,15 @@ pub enum EngineError {
/// Source error.
source: AssetPreparationError,
},
+ /// A native Behavior profile could not be found or decoded.
+ BehaviorProfile {
+ /// Behavior profile archive path.
+ path: String,
+ /// Selected `.var` entry name.
+ entry: String,
+ /// Entry, field, or format diagnostic.
+ message: String,
+ },
/// World error.
World(fparkan_world::WorldError),
/// Reference movement input or terrain query failed.
@@ -808,6 +955,11 @@ impl std::fmt::Display for EngineError {
Self::AssetPreparation { mission, source } => {
write!(f, "{mission}: asset preparation failed: {source}")
}
+ Self::BehaviorProfile {
+ path,
+ entry,
+ message,
+ } => write!(f, "{path}:{entry}: Behavior profile failed: {message}"),
Self::World(source) => write!(f, "{source}"),
Self::Movement(message) => write!(f, "reference movement: {message}"),
Self::RegistrationTeardown {
@@ -841,6 +993,7 @@ impl std::error::Error for EngineError {
| Self::ScriptRuntime { .. }
| Self::Movement(_)
| Self::PrototypeGraph { .. }
+ | Self::BehaviorProfile { .. }
| Self::RegistrationTeardown { .. } => None,
}
}
@@ -1076,6 +1229,11 @@ fn load_mission_with_options(
.unwrap_or_default(),
})
.collect();
+ let prepared_behavior_profiles = if options.asset_scope == MissionAssetScope::Full {
+ prepare_behavior_profile_states(&vfs, &object_drafts)?
+ } else {
+ Vec::new()
+ };
let mut new_runtime_world = new_world(WorldConfig);
let mut handles = Vec::with_capacity(mission.objects.len());
for (index, object) in mission.objects.iter().enumerate() {
@@ -1092,6 +1250,20 @@ fn load_mission_with_options(
)?;
handles.push(handle);
}
+ let behavior_profiles = prepared_behavior_profiles
+ .into_iter()
+ .zip(&handles)
+ .filter_map(|(profile, handle)| {
+ profile.map(|profile| BehaviorProfileState {
+ original_id: profile.original_id,
+ handle: *handle,
+ class_flags: profile.class_flags,
+ profile_entry: profile.profile_entry,
+ transfer_ore_off_board_bits: profile.transfer_ore_off_board_bits,
+ transfer_power_out_bits: profile.transfer_power_out_bits,
+ })
+ })
+ .collect();
let mut registered_objects = 0;
for handle in &handles {
if options.fail_after_registered_objects == Some(registered_objects) {
@@ -1184,25 +1356,36 @@ fn load_mission_with_options(
.iter()
.zip(&handles)
.enumerate()
- .map(
- |(object_index, (draft, handle))| MissionControlDeviceTableState {
- original_id: draft.original_id,
- handle: *handle,
- status: build_control_device_table(
- object_index,
- draft,
- &mission_assets,
- prototype_graph
- .root_prototype_request_spans
- .get(object_index),
- &resolved_prototypes,
- )
- .map_or_else(
- MissionControlDeviceTableStatus::Unavailable,
- MissionControlDeviceTableStatus::Available,
- ),
- },
- )
+ .map(|(object_index, (draft, handle))| {
+ let projection = build_control_device_projection(
+ object_index,
+ draft,
+ &mission_assets,
+ prototype_graph
+ .root_prototype_request_spans
+ .get(object_index),
+ &resolved_prototypes,
+ );
+ match projection {
+ Ok(projection) => MissionControlDeviceTableState {
+ original_id: draft.original_id,
+ handle: *handle,
+ status: MissionControlDeviceTableStatus::Available(projection.devices),
+ node_provider_status: projection.node_provider_status,
+ },
+ Err(reason) => MissionControlDeviceTableState {
+ original_id: draft.original_id,
+ handle: *handle,
+ status: MissionControlDeviceTableStatus::Unavailable(reason.clone()),
+ node_provider_status:
+ MissionControlNodeProviderTableStatus::Unavailable(
+ MissionControlNodeProviderTableUnavailableReason::DeviceTableUnavailable(
+ reason,
+ ),
+ ),
+ },
+ }
+ })
.collect()
} else {
Vec::new()
@@ -1284,6 +1467,7 @@ fn load_mission_with_options(
object_drafts,
behavior_distributors,
behavior_ore_states,
+ behavior_profiles,
control_device_tables,
script_bundles: loaded_scripts.bundles,
script_varset: loaded_scripts.varset,
@@ -1576,6 +1760,15 @@ pub fn loaded_mission_behavior_ore_states(engine: &Engine) -> Option<&[BehaviorO
.map(|state| state.behavior_ore_states.as_slice())
}
+/// Returns profile-derived Behavior rates attached to full Unit DAT objects.
+#[must_use]
+pub fn loaded_mission_behavior_profiles(engine: &Engine) -> Option<&[BehaviorProfileState]> {
+ engine
+ .loaded
+ .as_ref()
+ .map(|state| state.behavior_profiles.as_slice())
+}
+
/// Returns the base Control device table projections for loaded mission objects.
#[must_use]
pub fn loaded_mission_control_device_tables(
@@ -1587,6 +1780,428 @@ pub fn loaded_mission_control_device_tables(
.map(|state| state.control_device_tables.as_slice())
}
+/// Queries native Control global-table selector 1 (weighted ratio) or 2 (sum).
+/// `Ok(None)` preserves the original false/no-result behavior for an empty or
+/// zero-denominator table. Other unsupported native paths are reported as errors.
+/// Inputs and intermediates must be finite and normal, or exact zero.
+///
+/// # Errors
+/// Returns an error for an invalid object handle, unavailable mission/table,
+/// unsupported selector or factory, missing state, or an unsupported float range.
+pub fn query_loaded_mission_control_resource(
+ engine: &Engine,
+ handle: ObjectHandle,
+ selector: u32,
+) -> Result<Option<f32>, ControlResourceAccessError> {
+ transform_state(&engine.world, handle).map_err(ControlResourceAccessError::World)?;
+ let loaded = engine
+ .loaded
+ .as_ref()
+ .ok_or(ControlResourceAccessError::MissionUnavailable)?;
+ let table = loaded
+ .control_device_tables
+ .iter()
+ .find(|table| table.handle == handle)
+ .ok_or(ControlResourceAccessError::ObjectUnavailable { handle })?;
+ query_control_device_table_resource(table, selector)
+}
+
+/// Queries one loaded Control device through its original factory getter.
+///
+/// Selector `0xe00` is currently modeled for current descriptor tag 26 with
+/// factory tag 26. The loaded NDP provider value is its initial native state;
+/// later Control updates are not synchronized into this snapshot.
+///
+/// # Errors
+/// Returns an error for an invalid handle, unavailable mission/table/provider,
+/// an out-of-range device/provider key, or a factory/tag/float path that is not
+/// supported by the current reconstruction.
+pub fn query_loaded_mission_control_device_selector(
+ engine: &Engine,
+ handle: ObjectHandle,
+ device_index: usize,
+ selector: u32,
+) -> Result<Option<f32>, ControlResourceAccessError> {
+ transform_state(&engine.world, handle).map_err(ControlResourceAccessError::World)?;
+ let loaded = engine
+ .loaded
+ .as_ref()
+ .ok_or(ControlResourceAccessError::MissionUnavailable)?;
+ let table = loaded
+ .control_device_tables
+ .iter()
+ .find(|table| table.handle == handle)
+ .ok_or(ControlResourceAccessError::ObjectUnavailable { handle })?;
+ query_control_device_table_selector(table, device_index, selector)
+}
+
+/// Queries the recovered Behavior resource selectors `0x1002` and `0x1005`.
+///
+/// Selector `0x1005` returns the loaded profile's `Transfer_Power_Out` value.
+/// Selector `0x1002` sums supported Control `0xe00` results in native table
+/// order, rounding each addition to `f32`, then multiplies by the profile's
+/// `Transfer_Ore_OffBoard` value. Unsupported table/query paths return an error.
+/// Profile and provider values are initial full-load snapshots; later damage,
+/// Control updates, and profile changes are not synchronized into this state.
+///
+/// # Errors
+/// Returns an error for an invalid handle, unavailable mission/profile/table,
+/// unsupported selector or Control query path, or an unsupported float range.
+pub fn query_loaded_mission_behavior_resource(
+ engine: &Engine,
+ handle: ObjectHandle,
+ selector: u32,
+) -> Result<f32, ControlResourceAccessError> {
+ transform_state(&engine.world, handle).map_err(ControlResourceAccessError::World)?;
+ let loaded = engine
+ .loaded
+ .as_ref()
+ .ok_or(ControlResourceAccessError::MissionUnavailable)?;
+ let profile = loaded
+ .behavior_profiles
+ .iter()
+ .find(|profile| profile.handle == handle)
+ .ok_or(ControlResourceAccessError::ObjectUnavailable { handle })?;
+ match selector {
+ 0x1005 => checked_control_float(
+ 0,
+ "Transfer_Power_Out",
+ f32::from_bits(profile.transfer_power_out_bits),
+ ),
+ 0x1002 => {
+ let table = loaded
+ .control_device_tables
+ .iter()
+ .find(|table| table.handle == handle)
+ .ok_or(ControlResourceAccessError::ObjectUnavailable { handle })?;
+ query_behavior_profile_ore_rate(table, profile.transfer_ore_off_board_bits)
+ }
+ _ => Err(ControlResourceAccessError::UnsupportedSelector(selector)),
+ }
+}
+
+/// Sets native Control global-table selector 1 on rows whose selector-0 value
+/// is positive. Validation is completed before any row is changed.
+///
+/// # Errors
+/// Returns an error for an invalid object handle, unavailable mission/table,
+/// missing state, a non-finite or subnormal value, or an unsupported float range.
+pub fn set_loaded_mission_control_multiplier(
+ engine: &mut Engine,
+ handle: ObjectHandle,
+ value: f32,
+) -> Result<(), ControlResourceAccessError> {
+ transform_state(&engine.world, handle).map_err(ControlResourceAccessError::World)?;
+ let loaded = engine
+ .loaded
+ .as_mut()
+ .ok_or(ControlResourceAccessError::MissionUnavailable)?;
+ let table = loaded
+ .control_device_tables
+ .iter_mut()
+ .find(|table| table.handle == handle)
+ .ok_or(ControlResourceAccessError::ObjectUnavailable { handle })?;
+ set_control_device_table_multiplier(table, value)
+}
+
+fn query_control_device_table_resource(
+ table: &MissionControlDeviceTableState,
+ selector: u32,
+) -> Result<Option<f32>, ControlResourceAccessError> {
+ if !matches!(selector, 1 | 2) {
+ return Err(ControlResourceAccessError::UnsupportedSelector(selector));
+ }
+ let entries = match &table.status {
+ MissionControlDeviceTableStatus::Available(entries) => entries,
+ MissionControlDeviceTableStatus::Unavailable(reason) => {
+ return Err(ControlResourceAccessError::TableUnavailable(reason.clone()));
+ }
+ };
+
+ let mut numerator = 0.0_f32;
+ let mut denominator = 0.0_f32;
+ for entry in entries.iter().filter(|entry| entry.descriptor.tag == 19) {
+ let base = control_device_selector_zero(entry)?;
+ if base < 0.0 {
+ return Ok(Some(if selector == 1 { 1.0 } else { base }));
+ }
+ if selector == 2 {
+ denominator = checked_control_sum(entry.factory_tag, "sum", denominator, base)?;
+ } else {
+ let multiplier = control_device_float(entry, entry.multiplier_bits, "multiplier")?;
+ let weighted = checked_control_product(
+ entry.factory_tag,
+ "weighted value",
+ control_device_coefficient(entry)?,
+ multiplier,
+ )?;
+ numerator = checked_control_sum(entry.factory_tag, "numerator", numerator, weighted)?;
+ denominator = checked_control_sum(entry.factory_tag, "denominator", denominator, base)?;
+ }
+ }
+
+ if selector == 2 {
+ return Ok((denominator > 0.0).then_some(denominator));
+ }
+ if denominator <= 0.0 {
+ return Ok(None);
+ }
+ checked_control_ratio("ratio", numerator, denominator).map(Some)
+}
+
+fn query_control_device_table_selector(
+ table: &MissionControlDeviceTableState,
+ device_index: usize,
+ selector: u32,
+) -> Result<Option<f32>, ControlResourceAccessError> {
+ if selector != 0xe00 {
+ return Err(ControlResourceAccessError::UnsupportedSelector(selector));
+ }
+ let devices = match &table.status {
+ MissionControlDeviceTableStatus::Available(devices) => devices,
+ MissionControlDeviceTableStatus::Unavailable(reason) => {
+ return Err(ControlResourceAccessError::TableUnavailable(reason.clone()));
+ }
+ };
+ let device =
+ devices
+ .get(device_index)
+ .ok_or(ControlResourceAccessError::DeviceIndexOutOfRange {
+ device_index,
+ device_count: devices.len(),
+ })?;
+ match device.descriptor.tag {
+ 26 => {}
+ 5 | 10 | 21 => {
+ return Err(ControlResourceAccessError::UnsupportedCurrentTag {
+ tag: device.descriptor.tag,
+ });
+ }
+ _ => return Ok(None),
+ }
+ if device.factory_tag != 26 {
+ return Err(ControlResourceAccessError::UnsupportedFactoryTag {
+ factory_tag: device.factory_tag,
+ });
+ }
+
+ let providers = match &table.node_provider_status {
+ MissionControlNodeProviderTableStatus::Available(providers) => providers,
+ MissionControlNodeProviderTableStatus::Unavailable(reason) => {
+ return Err(ControlResourceAccessError::NodeProviderTableUnavailable(
+ reason.clone(),
+ ));
+ }
+ };
+ let key = usize::try_from(device.key).map_err(|_| {
+ ControlResourceAccessError::NodeProviderKeyOutOfRange {
+ key: device.key,
+ row_count: providers.len(),
+ }
+ })?;
+ let provider =
+ providers
+ .get(key)
+ .ok_or(ControlResourceAccessError::NodeProviderKeyOutOfRange {
+ key: device.key,
+ row_count: providers.len(),
+ })?;
+ let provider_value = checked_control_float(
+ device.factory_tag,
+ "node provider value",
+ f32::from_bits(provider.initial_type1_value_bits),
+ )?;
+ let coefficient = control_device_coefficient(device)?;
+ let multiplier = control_device_float(device, device.multiplier_bits, "multiplier")?;
+ let provider_weighted = checked_control_product(
+ device.factory_tag,
+ "provider times coefficient",
+ provider_value,
+ coefficient,
+ )?;
+ checked_control_product(
+ device.factory_tag,
+ "then multiplier",
+ provider_weighted,
+ multiplier,
+ )
+ .map(Some)
+}
+
+fn query_behavior_profile_ore_rate(
+ table: &MissionControlDeviceTableState,
+ transfer_ore_off_board_bits: u32,
+) -> Result<f32, ControlResourceAccessError> {
+ let devices = match &table.status {
+ MissionControlDeviceTableStatus::Available(devices) => devices,
+ MissionControlDeviceTableStatus::Unavailable(reason) => {
+ return Err(ControlResourceAccessError::TableUnavailable(reason.clone()));
+ }
+ };
+ let mut total = 0.0_f32;
+ for (device_index, device) in devices.iter().enumerate() {
+ if device.descriptor.tag != 26 {
+ continue;
+ }
+ if let Some(value) = query_control_device_table_selector(table, device_index, 0xe00)? {
+ total = checked_control_sum(26, "Behavior resource sum", total, value)?;
+ }
+ }
+ checked_control_product(
+ 26,
+ "Transfer_Ore_OffBoard",
+ total,
+ checked_control_float(
+ 26,
+ "Transfer_Ore_OffBoard",
+ f32::from_bits(transfer_ore_off_board_bits),
+ )?,
+ )
+}
+
+fn set_control_device_table_multiplier(
+ table: &mut MissionControlDeviceTableState,
+ value: f32,
+) -> Result<(), ControlResourceAccessError> {
+ let entries = match &mut table.status {
+ MissionControlDeviceTableStatus::Available(entries) => entries,
+ MissionControlDeviceTableStatus::Unavailable(reason) => {
+ return Err(ControlResourceAccessError::TableUnavailable(reason.clone()));
+ }
+ };
+
+ let mut has_target = false;
+ let mut target_factory_tag = 0;
+ for entry in entries.iter() {
+ if entry.descriptor.tag != 19 {
+ continue;
+ }
+ let base = control_device_selector_zero(entry)?;
+ if base > 0.0 {
+ has_target = true;
+ target_factory_tag = entry.factory_tag;
+ }
+ }
+ if !has_target {
+ return Ok(());
+ }
+ checked_control_float(target_factory_tag, "multiplier", value)?;
+ for entry in entries
+ .iter_mut()
+ .filter(|entry| entry.descriptor.tag == 19)
+ {
+ if control_device_selector_zero(entry)? > 0.0 {
+ entry.multiplier_bits = Some(value.to_bits());
+ }
+ }
+ Ok(())
+}
+
+fn control_device_selector_zero(
+ entry: &EffectiveControlDevice,
+) -> Result<f32, ControlResourceAccessError> {
+ let value = match entry.factory_tag {
+ 9 => {
+ let coefficient = control_device_coefficient(entry)?;
+ let scale = control_device_float(
+ entry,
+ entry.class9_selector0_scale_bits,
+ "class-9 selector-0 scale",
+ )?;
+ checked_control_product(entry.factory_tag, "selector-0 value", coefficient, scale)?
+ }
+ 15 | 19 | 25 => control_device_coefficient(entry)?,
+ factory_tag => {
+ return Err(ControlResourceAccessError::UnsupportedFactoryTag { factory_tag });
+ }
+ };
+ checked_control_float(entry.factory_tag, "selector-0 value", value)
+}
+
+fn control_device_coefficient(
+ entry: &EffectiveControlDevice,
+) -> Result<f32, ControlResourceAccessError> {
+ let words = entry
+ .coefficient_bits
+ .ok_or(ControlResourceAccessError::UnsupportedField {
+ factory_tag: entry.factory_tag,
+ field: "coefficient",
+ })?;
+ control_device_float(entry, Some(words[0]), "coefficient")
+}
+
+fn control_device_float(
+ entry: &EffectiveControlDevice,
+ bits: Option<u32>,
+ field: &'static str,
+) -> Result<f32, ControlResourceAccessError> {
+ let bits = bits.ok_or(ControlResourceAccessError::UnsupportedField {
+ factory_tag: entry.factory_tag,
+ field,
+ })?;
+ checked_control_float(entry.factory_tag, field, f32::from_bits(bits))
+}
+
+fn checked_control_float(
+ factory_tag: u32,
+ field: &'static str,
+ value: f32,
+) -> Result<f32, ControlResourceAccessError> {
+ if !value.is_finite() {
+ return Err(ControlResourceAccessError::NonFiniteValue { factory_tag, field });
+ }
+ if value.is_subnormal() {
+ return Err(ControlResourceAccessError::SubnormalValue { factory_tag, field });
+ }
+ Ok(value)
+}
+
+fn checked_control_product(
+ factory_tag: u32,
+ field: &'static str,
+ lhs: f32,
+ rhs: f32,
+) -> Result<f32, ControlResourceAccessError> {
+ let range_probe = f64::from(lhs) * f64::from(rhs);
+ check_control_range_probe(Some(factory_tag), field, range_probe)?;
+ checked_control_float(factory_tag, field, lhs * rhs)
+}
+
+fn checked_control_ratio(
+ field: &'static str,
+ numerator: f32,
+ denominator: f32,
+) -> Result<f32, ControlResourceAccessError> {
+ let range_probe = f64::from(numerator) / f64::from(denominator);
+ check_control_range_probe(None, field, range_probe)?;
+ checked_control_float(0, field, numerator / denominator)
+}
+
+fn checked_control_sum(
+ factory_tag: u32,
+ field: &'static str,
+ lhs: f32,
+ rhs: f32,
+) -> Result<f32, ControlResourceAccessError> {
+ let range_probe = f64::from(lhs) + f64::from(rhs);
+ check_control_range_probe(Some(factory_tag), field, range_probe)?;
+ checked_control_float(factory_tag, field, lhs + rhs)
+}
+
+fn check_control_range_probe(
+ factory_tag: Option<u32>,
+ field: &'static str,
+ range_probe: f64,
+) -> Result<(), ControlResourceAccessError> {
+ let absolute = range_probe.abs();
+ let minimum_normal = f64::from(f32::MIN_POSITIVE);
+ let maximum = f64::from(f32::MAX);
+ if range_probe != 0.0 && (absolute < minimum_normal || absolute > maximum) {
+ return Err(ControlResourceAccessError::UnsupportedFloatRange { factory_tag, field });
+ }
+ Ok(())
+}
+
fn behavior_clan_for_selector(
selector: u32,
clan_count: usize,
@@ -1613,6 +2228,123 @@ fn native_behavior_ore_defaults(class_flags: u32) -> (u32, u32) {
}
}
+fn behavior_profile_entry_for_class(class_flags: u32) -> Option<&'static str> {
+ match class_flags {
+ 0x8000_0004 => Some("prof_mine.var"),
+ 0x8000_0008 => Some("prof_storage.var"),
+ 0x8000_0002 => Some("prof_generator.var"),
+ 0x8000_0010 => Some("prof_plant.var"),
+ 0x8000_0040 => Some("prof_angar.var"),
+ 0x8000_0200 => Some("prof_mtp.var"),
+ 0x8000_0400 => Some("prof_institute.var"),
+ 0x8001_0000 | 0x8002_0000 | 0x8004_0000 => Some("prof_bunker.var"),
+ 0x8010_0000 | 0x8020_0000 => Some("prof_tower.var"),
+ 0x0100_2000 => Some("prof_trn.var"),
+ 0x0100_4000 => Some("prof_bld.var"),
+ 0x0100_8000 => Some("prof_war.var"),
+ 0x0101_0000 => Some("prof_hq.var"),
+ 0x0102_0000 => Some("prof_hero.var"),
+ 0x2000_0000 => Some("prof_animal.var"),
+ _ => None,
+ }
+}
+
+fn prepare_behavior_profile_states(
+ vfs: &Arc<dyn Vfs>,
+ object_drafts: &[MissionObjectDraft],
+) -> Result<Vec<Option<PreparedBehaviorProfileState>>, EngineError> {
+ const DEFAULT_TRANSFER_ORE_OFF_BOARD_BITS: u32 = 0x40a0_0000;
+ const DEFAULT_TRANSFER_POWER_OUT_BITS: u32 = 0x42c8_0000;
+
+ let has_known_profile = object_drafts.iter().any(|draft| {
+ draft
+ .unit_dat_header_flags
+ .and_then(behavior_profile_entry_for_class)
+ .is_some()
+ });
+ let archive_path = has_known_profile
+ .then(|| normalize_engine_path("Behavior profile archive", "behpsp.res"))
+ .transpose()?;
+ let profile_archive = archive_path
+ .as_ref()
+ .map(|path| {
+ let bytes = read_vfs(vfs, path)?;
+ decode_nres_payload(bytes).map_err(|source| EngineError::Nres {
+ path: path.as_str().to_string(),
+ source,
+ })
+ })
+ .transpose()?;
+ let mut rates_by_entry = HashMap::<&'static str, BehaviorProfileRates>::new();
+ let mut states = Vec::with_capacity(object_drafts.len());
+
+ for draft in object_drafts {
+ let Some(class_flags) = draft.unit_dat_header_flags else {
+ states.push(None);
+ continue;
+ };
+ let Some(original_id) = draft.original_id else {
+ states.push(None);
+ continue;
+ };
+ let profile_entry = behavior_profile_entry_for_class(class_flags);
+ let (transfer_ore_off_board_bits, transfer_power_out_bits) = if let Some(entry_name) =
+ profile_entry
+ {
+ let rates = if let Some(rates) = rates_by_entry.get(entry_name) {
+ *rates
+ } else {
+ let path = archive_path
+ .as_ref()
+ .expect("known profiles require the profile archive path");
+ let archive = profile_archive
+ .as_ref()
+ .expect("known profiles require the decoded profile archive");
+ let entry_id =
+ archive
+ .find(entry_name)
+ .ok_or_else(|| EngineError::BehaviorProfile {
+ path: path.as_str().to_string(),
+ entry: entry_name.to_string(),
+ message: "entry was not found".to_string(),
+ })?;
+ let payload = archive
+ .payload(entry_id)
+ .map_err(|source| EngineError::Nres {
+ path: path.as_str().to_string(),
+ source,
+ })?;
+ let rates = fparkan_assets::decode_behavior_profile_rates(payload).map_err(
+ |source: BehaviorProfileVarError| EngineError::BehaviorProfile {
+ path: path.as_str().to_string(),
+ entry: entry_name.to_string(),
+ message: source.to_string(),
+ },
+ )?;
+ rates_by_entry.insert(entry_name, rates);
+ rates
+ };
+ (
+ rates.transfer_ore_off_board_bits,
+ rates.transfer_power_out_bits,
+ )
+ } else {
+ (
+ DEFAULT_TRANSFER_ORE_OFF_BOARD_BITS,
+ DEFAULT_TRANSFER_POWER_OUT_BITS,
+ )
+ };
+ states.push(Some(PreparedBehaviorProfileState {
+ original_id,
+ class_flags,
+ profile_entry,
+ transfer_ore_off_board_bits,
+ transfer_power_out_bits,
+ }));
+ }
+ Ok(states)
+}
+
fn initialize_behavior_ore_state(
original_id: OriginalObjectId,
handle: ObjectHandle,
@@ -1664,6 +2396,30 @@ fn native_component_target_index(
}
}
+fn native_component_mount_node(
+ tree: &[UnitComponentTreeNode],
+ component_ids: &[Option<u32>],
+ first_global_nodes: &[Option<u32>],
+ component_index: usize,
+ raw_local_index: i32,
+) -> Option<u32> {
+ tree.get(component_index)
+ .and_then(|node| node.parent_index)
+ .and_then(|parent_index| {
+ let parent_id = component_ids.get(parent_index).copied().flatten()?;
+ let parent_first = first_global_nodes
+ .get(parent_index)
+ .copied()
+ .flatten()
+ .unwrap_or(u32::MAX);
+ Some(
+ parent_first
+ .wrapping_add(raw_local_index as u32)
+ .wrapping_sub(u32::from(parent_id != 0)),
+ )
+ })
+}
+
fn native_into_table_target_index(
devices: &[EffectiveControlDevice],
parent_component_id: u32,
@@ -1770,6 +2526,7 @@ fn append_effective_control_device(
key,
coefficient_bits,
multiplier_bits,
+ class9_selector0_scale_bits: (descriptor.tag == 9).then_some(0x3f80_0000),
native_word_50_bits,
descriptor: descriptor.clone(),
factory_provenance: provenance.clone(),
@@ -1803,16 +2560,17 @@ fn control_factory_uses_common_setter(factory_tag: u32) -> bool {
}
fn native_control_factory_defaults(factory_tag: u32) -> (Option<u32>, Option<u32>) {
- let flags = match factory_tag {
- 1 | 4 => 0x200,
- 5 | 8 | 26 => 0x5,
- 10 => 0x2000,
- 17 | 19 => 0x20,
- _ => return (None, None),
- };
- (Some(0x3f80_0000), Some(flags))
+ match factory_tag {
+ 1 | 4 => (Some(0x3f80_0000), Some(0x200)),
+ 5 | 8 | 26 => (Some(0x3f80_0000), Some(0x5)),
+ 10 => (Some(0x3f80_0000), Some(0x2000)),
+ 17 | 19 => (Some(0x3f80_0000), Some(0x20)),
+ 9 | 15 | 25 => (Some(0x3f80_0000), None),
+ _ => (None, None),
+ }
}
+#[cfg(test)]
fn build_control_device_table(
object_index: usize,
draft: &MissionObjectDraft,
@@ -1820,6 +2578,17 @@ fn build_control_device_table(
prototype_span: Option<&std::ops::Range<usize>>,
prototypes: &[fparkan_prototype::EffectivePrototype],
) -> Result<Vec<EffectiveControlDevice>, MissionControlDeviceTableUnavailableReason> {
+ build_control_device_projection(object_index, draft, assets, prototype_span, prototypes)
+ .map(|projection| projection.devices)
+}
+
+fn build_control_device_projection(
+ object_index: usize,
+ draft: &MissionObjectDraft,
+ assets: &MissionAssets,
+ prototype_span: Option<&std::ops::Range<usize>>,
+ prototypes: &[fparkan_prototype::EffectivePrototype],
+) -> Result<ControlDeviceProjection, MissionControlDeviceTableUnavailableReason> {
use MissionControlDeviceTableUnavailableReason as Unavailable;
draft
@@ -1972,6 +2741,7 @@ fn build_control_device_table(
}
let mut devices = Vec::new();
+ let mut node_provider_status = MissionControlNodeProviderTableStatus::Available(Vec::new());
let mut has_control_resource = false;
for component_index in active_components {
let prototype =
@@ -2008,6 +2778,40 @@ fn build_control_device_table(
component_ids[component_index].ok_or(Unavailable::ComponentAlignmentMismatch)?;
let is_root = component_index == 0;
let is_ex_to = prototype.source_type == Some(PROTOTYPE_TYPE_EXTO);
+ let raw_local_index = draft.unit_components[component_index].parent_or_link;
+ let parent_component_id = tree
+ .get(component_index)
+ .and_then(|node| node.parent_index)
+ .and_then(|parent_index| component_ids.get(parent_index).copied().flatten())
+ .unwrap_or(u32::MAX);
+ let mount_node = if is_ex_to {
+ native_component_mount_node(
+ &tree,
+ &component_ids,
+ &first_global_nodes,
+ component_index,
+ raw_local_index,
+ )
+ } else {
+ None
+ };
+ if is_root {
+ append_control_node_provider_rows(
+ &mut node_provider_status,
+ component_index,
+ prototype.node_data_resource.as_ref(),
+ control.node_data.as_ref(),
+ false,
+ );
+ } else if is_ex_to && mount_node.is_some_and(|node| node != u32::MAX) {
+ append_control_node_provider_rows(
+ &mut node_provider_status,
+ component_index,
+ prototype.node_data_resource.as_ref(),
+ control.node_data.as_ref(),
+ true,
+ );
+ }
if is_root {
for (record_index, descriptor) in control.typed_records.iter().enumerate() {
append_effective_control_device(
@@ -2023,12 +2827,6 @@ fn build_control_device_table(
continue;
}
- let raw_local_index = draft.unit_components[component_index].parent_or_link;
- let parent_component_id = tree
- .get(component_index)
- .and_then(|node| node.parent_index)
- .and_then(|parent_index| component_ids.get(parent_index).copied().flatten())
- .unwrap_or(u32::MAX);
let native_target = native_component_target_index(
prototype.source_type,
&devices,
@@ -2037,25 +2835,6 @@ fn build_control_device_table(
);
match native_control_target_action(native_target) {
ControlTableTarget::Append => {
- let mount_node = if is_ex_to {
- tree.get(component_index)
- .and_then(|node| node.parent_index)
- .and_then(|parent_index| {
- let parent_id = component_ids.get(parent_index).copied().flatten()?;
- let parent_first = first_global_nodes
- .get(parent_index)
- .copied()
- .flatten()
- .unwrap_or(u32::MAX);
- Some(
- parent_first
- .wrapping_add(raw_local_index as u32)
- .wrapping_sub(u32::from(parent_id != 0)),
- )
- })
- } else {
- None
- };
let first_global_node = first_global_nodes.get(component_index).copied().flatten();
for (record_index, descriptor) in control.typed_records.iter().enumerate() {
let raw_key = descriptor.fixed_words[1];
@@ -2117,7 +2896,49 @@ fn build_control_device_table(
if !has_control_resource {
return Err(Unavailable::NoControlResource);
}
- Ok(devices)
+ Ok(ControlDeviceProjection {
+ devices,
+ node_provider_status,
+ })
+}
+
+fn append_control_node_provider_rows(
+ status: &mut MissionControlNodeProviderTableStatus,
+ unit_component_index: usize,
+ requested_source: Option<&ResourceKey>,
+ node_data: Option<&PreparedControlNodeDataTable>,
+ skip_first_row: bool,
+) {
+ let MissionControlNodeProviderTableStatus::Available(rows) = status else {
+ return;
+ };
+ let Some(node_data) = node_data else {
+ *status = MissionControlNodeProviderTableStatus::Unavailable(
+ MissionControlNodeProviderTableUnavailableReason::MissingNodeData {
+ unit_component_index,
+ source: requested_source.cloned(),
+ },
+ );
+ return;
+ };
+ if skip_first_row && node_data.rows.is_empty() {
+ *status = MissionControlNodeProviderTableStatus::Unavailable(
+ MissionControlNodeProviderTableUnavailableReason::MissingExToRootRow {
+ unit_component_index,
+ },
+ );
+ return;
+ }
+ let first_row = usize::from(skip_first_row);
+ for (source_row_index, source_row) in node_data.rows.iter().enumerate().skip(first_row) {
+ rows.push(MissionControlNodeProviderRow {
+ source: node_data.source.clone(),
+ unit_component_index,
+ source_row_index,
+ source_row: source_row.clone(),
+ initial_type1_value_bits: 0x3f80_0000,
+ });
+ }
}
fn add_behavior_registered_object(
@@ -2559,6 +3380,62 @@ mod tests {
}
}
+ fn synthetic_control_node_data_table(
+ index: usize,
+ row_count: usize,
+ ) -> PreparedControlNodeDataTable {
+ PreparedControlNodeDataTable {
+ source: synthetic_resource_key(300 + index),
+ rows: (0..row_count)
+ .map(|row_index| PreparedControlNodeDataRow {
+ raw_flags: u32::try_from(row_index).expect("row index fits u32"),
+ max_volume: (100 + row_index) as f32,
+ mobility_per_volume: (200 + row_index) as f32,
+ effect: PreparedControlResourcePair {
+ archive: [0; 32],
+ name: [0; 32],
+ },
+ })
+ .collect(),
+ }
+ }
+
+ fn control_with_synthetic_node_data(
+ index: usize,
+ typed_records: Vec<PreparedControlTypedRecord>,
+ row_count: usize,
+ ) -> PreparedComponentControl {
+ let mut control = synthetic_component_control(
+ index,
+ typed_records,
+ PreparedControlEffectSection::Parsed(Vec::new()),
+ );
+ control.node_data = Some(synthetic_control_node_data_table(index, row_count));
+ control
+ }
+
+ fn synthetic_node_provider_row(
+ component_index: usize,
+ source_row_index: usize,
+ initial_type1_value_bits: u32,
+ ) -> MissionControlNodeProviderRow {
+ MissionControlNodeProviderRow {
+ source: synthetic_resource_key(300 + component_index),
+ unit_component_index: component_index,
+ source_row_index,
+ source_row: PreparedControlNodeDataRow {
+ raw_flags: u32::try_from(source_row_index).expect("row index fits u32"),
+ max_volume: 100.0,
+ mobility_per_volume: 200.0,
+ effect: PreparedControlResourcePair {
+ archive: [0; 32],
+ name: [0; 32],
+ },
+ },
+ initial_type1_value_bits,
+ }
+ }
+
fn synthetic_control_fixture(
source_types: &[Option<u32>],
kinds: &[u32],
@@ -2624,8 +3501,11 @@ mod tests {
control_resource: controls[index]
.as_ref()
.map(|control| control.source.clone()),
+ node_data_resource: controls[index]
+ .as_ref()
+ .and_then(|control| control.node_data.as_ref())
+ .map(|node_data| node_data.source.clone()),
point_resource: None,
- node_data_resource: None,
bas_resource: None,
});
}
@@ -2678,6 +3558,632 @@ mod tests {
)
}
+ fn synthetic_control_projection(
+ source_types: &[Option<u32>],
+ kinds: &[u32],
+ child_counts: &[u32],
+ parent_or_links: &[i32],
+ model_nodes: &[usize],
+ controls: Vec<Option<PreparedComponentControl>>,
+ ) -> (
+ MissionControlDeviceTableStatus,
+ MissionControlNodeProviderTableStatus,
+ ) {
+ let (draft, assets, prototypes) = synthetic_control_fixture(
+ source_types,
+ kinds,
+ child_counts,
+ parent_or_links,
+ model_nodes,
+ controls,
+ );
+ let (status, node_provider_status) = match build_control_device_projection(
+ 0,
+ &draft,
+ &assets,
+ Some(&(0..prototypes.len())),
+ &prototypes,
+ ) {
+ Ok(projection) => (
+ MissionControlDeviceTableStatus::Available(projection.devices),
+ projection.node_provider_status,
+ ),
+ Err(reason) => (
+ MissionControlDeviceTableStatus::Unavailable(reason.clone()),
+ MissionControlNodeProviderTableStatus::Unavailable(
+ MissionControlNodeProviderTableUnavailableReason::DeviceTableUnavailable(
+ reason,
+ ),
+ ),
+ ),
+ };
+ (status, node_provider_status)
+ }
+
+ fn synthetic_effective_control_device(
+ factory_tag: u32,
+ descriptor_tag: u32,
+ coefficient_bits: u32,
+ multiplier_bits: Option<u32>,
+ class9_scale_bits: Option<u32>,
+ ) -> EffectiveControlDevice {
+ let descriptor = synthetic_control_record(descriptor_tag, 2, coefficient_bits, None);
+ let control = synthetic_component_control(
+ 0,
+ vec![descriptor.clone()],
+ PreparedControlEffectSection::Parsed(Vec::new()),
+ );
+ let provenance = control_device_record_provenance(0, 0, &control);
+ let mut coefficients = [0; 16];
+ coefficients[0] = coefficient_bits;
+ EffectiveControlDevice {
+ factory_tag,
+ component_id: 3,
+ key: 2,
+ coefficient_bits: Some(coefficients),
+ multiplier_bits,
+ class9_selector0_scale_bits: class9_scale_bits,
+ native_word_50_bits: None,
+ descriptor,
+ factory_provenance: provenance.clone(),
+ descriptor_provenance: provenance,
+ }
+ }
+
+ fn synthetic_control_device_table(
+ status: MissionControlDeviceTableStatus,
+ ) -> MissionControlDeviceTableState {
+ synthetic_control_device_table_with_providers(
+ status,
+ MissionControlNodeProviderTableStatus::Available(Vec::new()),
+ )
+ }
+
+ fn synthetic_control_device_table_with_providers(
+ status: MissionControlDeviceTableStatus,
+ node_provider_status: MissionControlNodeProviderTableStatus,
+ ) -> MissionControlDeviceTableState {
+ MissionControlDeviceTableState {
+ original_id: Some(OriginalObjectId(7)),
+ handle: ObjectHandle {
+ generation: 5,
+ slot: 7,
+ },
+ status,
+ node_provider_status,
+ }
+ }
+
+ #[test]
+ fn behavior_profile_selector_1002_sums_control_e00_rows_then_multiplies_profile_rate() {
+ let table = synthetic_control_device_table_with_providers(
+ MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 26,
+ 26,
+ 3.0_f32.to_bits(),
+ Some(4.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 5,
+ 5,
+ 100.0_f32.to_bits(),
+ Some(100.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 10,
+ 10,
+ 100.0_f32.to_bits(),
+ Some(100.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 21,
+ 21,
+ 100.0_f32.to_bits(),
+ Some(100.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 26,
+ 26,
+ 2.0_f32.to_bits(),
+ Some(2.0_f32.to_bits()),
+ None,
+ ),
+ ]),
+ MissionControlNodeProviderTableStatus::Available(
+ (0..3)
+ .map(|index| synthetic_node_provider_row(0, index, 2.0_f32.to_bits()))
+ .collect(),
+ ),
+ );
+ assert_eq!(
+ query_behavior_profile_ore_rate(&table, 1.5_f32.to_bits())
+ .expect("supported Behavior ore query")
+ .to_bits(),
+ 48.0_f32.to_bits()
+ );
+
+ let mut factory_mismatch = table.clone();
+ let MissionControlDeviceTableStatus::Available(devices) = &mut factory_mismatch.status
+ else {
+ unreachable!();
+ };
+ devices[0].factory_tag = 9;
+ assert_eq!(
+ query_behavior_profile_ore_rate(&factory_mismatch, 1.5_f32.to_bits()),
+ Err(ControlResourceAccessError::UnsupportedFactoryTag { factory_tag: 9 })
+ );
+
+ let unavailable =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Unavailable(
+ MissionControlDeviceTableUnavailableReason::NoControlResource,
+ ));
+ assert_eq!(
+ query_behavior_profile_ore_rate(&unavailable, 1.0_f32.to_bits()),
+ Err(ControlResourceAccessError::TableUnavailable(
+ MissionControlDeviceTableUnavailableReason::NoControlResource
+ ))
+ );
+ }
+
+ #[test]
+ fn control_resource_queries_filter_current_tag_and_use_factory_getters() {
+ let table =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 9,
+ 19,
+ 2.0_f32.to_bits(),
+ Some(3.0_f32.to_bits()),
+ Some(0.5_f32.to_bits()),
+ ),
+ synthetic_effective_control_device(
+ 19,
+ 9,
+ 100.0_f32.to_bits(),
+ Some(77.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 15,
+ 19,
+ 4.0_f32.to_bits(),
+ Some(0.5_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ 1.0_f32.to_bits(),
+ Some(4.0_f32.to_bits()),
+ None,
+ ),
+ ]));
+
+ assert_eq!(
+ query_control_device_table_resource(&table, 1)
+ .expect("selector 1")
+ .map(f32::to_bits),
+ Some(2.0_f32.to_bits())
+ );
+ assert_eq!(
+ query_control_device_table_resource(&table, 2)
+ .expect("selector 2")
+ .map(f32::to_bits),
+ Some(6.0_f32.to_bits())
+ );
+ assert_eq!(
+ query_control_device_table_resource(&table, 3),
+ Err(ControlResourceAccessError::UnsupportedSelector(3))
+ );
+ }
+
+ #[test]
+ fn control_resource_setter_updates_matching_rows_atomically_and_round_trips() {
+ let mut table =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 9,
+ 19,
+ 2.0_f32.to_bits(),
+ Some(3.0_f32.to_bits()),
+ Some(0.5_f32.to_bits()),
+ ),
+ synthetic_effective_control_device(
+ 19,
+ 9,
+ 100.0_f32.to_bits(),
+ Some(77.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 15,
+ 19,
+ 4.0_f32.to_bits(),
+ Some(0.5_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ 1.0_f32.to_bits(),
+ Some(4.0_f32.to_bits()),
+ None,
+ ),
+ ]));
+
+ set_control_device_table_multiplier(&mut table, 7.5).expect("setter 1");
+ let MissionControlDeviceTableStatus::Available(entries) = &table.status else {
+ panic!("synthetic table is available");
+ };
+ assert_eq!(
+ entries
+ .iter()
+ .map(|entry| entry.multiplier_bits)
+ .collect::<Vec<_>>(),
+ [
+ Some(7.5_f32.to_bits()),
+ Some(77.0_f32.to_bits()),
+ Some(7.5_f32.to_bits()),
+ Some(7.5_f32.to_bits())
+ ]
+ );
+ assert_eq!(
+ entries[0].class9_selector0_scale_bits,
+ Some(0.5_f32.to_bits())
+ );
+ assert_eq!(
+ query_control_device_table_resource(&table, 1)
+ .expect("updated selector 1")
+ .map(f32::to_bits),
+ Some(8.75_f32.to_bits())
+ );
+
+ let mut unsupported =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ 2.0_f32.to_bits(),
+ Some(1.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(12, 19, 1.0_f32.to_bits(), None, None),
+ ]));
+ assert_eq!(
+ set_control_device_table_multiplier(&mut unsupported, 2.0),
+ Err(ControlResourceAccessError::UnsupportedFactoryTag { factory_tag: 12 })
+ );
+ let MissionControlDeviceTableStatus::Available(entries) = &unsupported.status else {
+ panic!("synthetic table is available");
+ };
+ assert_eq!(entries[0].multiplier_bits, Some(1.0_f32.to_bits()));
+ }
+
+ #[test]
+ fn control_resource_queries_preserve_native_no_result_and_negative_rules() {
+ let empty =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(Vec::new()));
+ assert_eq!(query_control_device_table_resource(&empty, 1), Ok(None));
+ assert_eq!(query_control_device_table_resource(&empty, 2), Ok(None));
+ assert!(set_control_device_table_multiplier(&mut empty.clone(), f32::NAN).is_ok());
+
+ let zero_denominator =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ 0.0_f32.to_bits(),
+ Some(2.0_f32.to_bits()),
+ None,
+ ),
+ ]));
+ assert_eq!(
+ query_control_device_table_resource(&zero_denominator, 1),
+ Ok(None)
+ );
+ assert_eq!(
+ query_control_device_table_resource(&zero_denominator, 2),
+ Ok(None)
+ );
+
+ let nonmatching =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 19,
+ 9,
+ 4.0_f32.to_bits(),
+ Some(2.0_f32.to_bits()),
+ None,
+ ),
+ ]));
+ assert_eq!(
+ query_control_device_table_resource(&nonmatching, 1),
+ Ok(None)
+ );
+
+ let no_multiplier =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(19, 19, 2.0_f32.to_bits(), None, None),
+ ]));
+ assert_eq!(
+ query_control_device_table_resource(&no_multiplier, 2)
+ .expect("selector 2 does not read multiplier")
+ .map(f32::to_bits),
+ Some(2.0_f32.to_bits())
+ );
+
+ let negative =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(19, 19, (-1.0_f32).to_bits(), None, None),
+ ]));
+ assert_eq!(
+ query_control_device_table_resource(&negative, 1)
+ .expect("negative selector 1")
+ .map(f32::to_bits),
+ Some(1.0_f32.to_bits())
+ );
+ assert_eq!(
+ query_control_device_table_resource(&negative, 2)
+ .expect("negative selector 2")
+ .map(f32::to_bits),
+ Some((-1.0_f32).to_bits())
+ );
+
+ let rounded =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ 1.0_f32.to_bits(),
+ Some(16_777_216.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ 1.0_f32.to_bits(),
+ Some(1.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ 1.0_f32.to_bits(),
+ Some((-16_777_216.0_f32).to_bits()),
+ None,
+ ),
+ ]));
+ assert_eq!(
+ query_control_device_table_resource(&rounded, 1)
+ .expect("rounded selector 1")
+ .map(f32::to_bits),
+ Some(0.0_f32.to_bits())
+ );
+
+ let mut replaceable =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ 1.0_f32.to_bits(),
+ Some(f32::INFINITY.to_bits()),
+ None,
+ ),
+ ]));
+ set_control_device_table_multiplier(&mut replaceable, 2.0)
+ .expect("setter does not read the old multiplier");
+ let MissionControlDeviceTableStatus::Available(entries) = &replaceable.status else {
+ panic!("synthetic table is available");
+ };
+ assert_eq!(entries[0].multiplier_bits, Some(2.0_f32.to_bits()));
+ }
+
+ #[test]
+ fn control_resource_access_reports_unavailable_and_nonfinite_inputs() {
+ let unavailable =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Unavailable(
+ MissionControlDeviceTableUnavailableReason::NoControlResource,
+ ));
+ assert_eq!(
+ query_control_device_table_resource(&unavailable, 1),
+ Err(ControlResourceAccessError::TableUnavailable(
+ MissionControlDeviceTableUnavailableReason::NoControlResource
+ ))
+ );
+
+ let nonfinite =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ f32::INFINITY.to_bits(),
+ Some(1.0_f32.to_bits()),
+ None,
+ ),
+ ]));
+ assert!(matches!(
+ query_control_device_table_resource(&nonfinite, 1),
+ Err(ControlResourceAccessError::NonFiniteValue {
+ factory_tag: 19,
+ field: "coefficient"
+ })
+ ));
+
+ let subnormal =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(19, 19, 1, Some(1.0_f32.to_bits()), None),
+ ]));
+ assert!(matches!(
+ query_control_device_table_resource(&subnormal, 2),
+ Err(ControlResourceAccessError::SubnormalValue {
+ factory_tag: 19,
+ field: "coefficient"
+ })
+ ));
+
+ let mut finite =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ 1.0_f32.to_bits(),
+ Some(1.0_f32.to_bits()),
+ None,
+ ),
+ ]));
+ assert!(matches!(
+ set_control_device_table_multiplier(&mut finite, f32::INFINITY),
+ Err(ControlResourceAccessError::NonFiniteValue {
+ factory_tag: 19,
+ field: "multiplier"
+ })
+ ));
+
+ let underflowing_product =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ f32::MIN_POSITIVE.to_bits(),
+ Some(f32::MIN_POSITIVE.to_bits()),
+ None,
+ ),
+ ]));
+ assert!(matches!(
+ query_control_device_table_resource(&underflowing_product, 1),
+ Err(ControlResourceAccessError::UnsupportedFloatRange {
+ factory_tag: Some(19),
+ field: "weighted value"
+ })
+ ));
+
+ let underflowing_ratio =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ f32::MIN_POSITIVE.to_bits(),
+ Some(1.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 19,
+ 19,
+ f32::MAX.to_bits(),
+ Some(0.0_f32.to_bits()),
+ None,
+ ),
+ ]));
+ assert!(matches!(
+ query_control_device_table_resource(&underflowing_ratio, 1),
+ Err(ControlResourceAccessError::UnsupportedFloatRange {
+ factory_tag: None,
+ field: "ratio"
+ })
+ ));
+
+ let overflowing_sum =
+ synthetic_control_device_table(MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(19, 19, f32::MAX.to_bits(), None, None),
+ synthetic_effective_control_device(19, 19, f32::MAX.to_bits(), None, None),
+ ]));
+ assert!(matches!(
+ query_control_device_table_resource(&overflowing_sum, 2),
+ Err(ControlResourceAccessError::UnsupportedFloatRange {
+ factory_tag: Some(19),
+ field: "sum"
+ })
+ ));
+ }
+
+ #[test]
+ fn control_resource_api_checks_live_world_handle_before_loaded_state() {
+ let mut engine = create(EngineServices::default()).expect("engine");
+ let handle = construct_object(
+ &mut engine.world,
+ ObjectDraft {
+ original_id: Some(OriginalObjectId(4)),
+ },
+ )
+ .expect("live world object");
+ assert_eq!(
+ query_loaded_mission_control_resource(&engine, handle, 1),
+ Err(ControlResourceAccessError::MissionUnavailable)
+ );
+ assert_eq!(
+ query_loaded_mission_control_device_selector(&engine, handle, 0, 0xe00),
+ Err(ControlResourceAccessError::MissionUnavailable)
+ );
+ assert_eq!(
+ query_loaded_mission_behavior_resource(&engine, handle, 0x1005),
+ Err(ControlResourceAccessError::MissionUnavailable)
+ );
+
+ let stale = ObjectHandle {
+ generation: handle.generation.wrapping_add(1),
+ slot: handle.slot,
+ };
+ assert_eq!(
+ query_loaded_mission_control_resource(&engine, stale, 1),
+ Err(ControlResourceAccessError::World(
+ fparkan_world::WorldError::StaleHandle
+ ))
+ );
+ assert_eq!(
+ query_loaded_mission_control_device_selector(&engine, stale, 0, 0xe00),
+ Err(ControlResourceAccessError::World(
+ fparkan_world::WorldError::StaleHandle
+ ))
+ );
+ assert_eq!(
+ query_loaded_mission_behavior_resource(&engine, stale, 0x1005),
+ Err(ControlResourceAccessError::World(
+ fparkan_world::WorldError::StaleHandle
+ ))
+ );
+ assert_eq!(
+ set_loaded_mission_control_multiplier(&mut engine, stale, 2.0),
+ Err(ControlResourceAccessError::World(
+ fparkan_world::WorldError::StaleHandle
+ ))
+ );
+
+ fparkan_world::request_delete(&mut engine.world, handle).expect("delete object");
+ assert_eq!(
+ query_loaded_mission_control_resource(&engine, handle, 1),
+ Err(ControlResourceAccessError::World(
+ fparkan_world::WorldError::StaleHandle
+ ))
+ );
+ assert_eq!(
+ query_loaded_mission_control_device_selector(&engine, handle, 0, 0xe00),
+ Err(ControlResourceAccessError::World(
+ fparkan_world::WorldError::StaleHandle
+ ))
+ );
+ assert_eq!(
+ query_loaded_mission_behavior_resource(&engine, handle, 0x1005),
+ Err(ControlResourceAccessError::World(
+ fparkan_world::WorldError::StaleHandle
+ ))
+ );
+ }
+
+ #[test]
+ fn control_factory_multiplier_defaults_preserve_unknown_word_50() {
+ for factory_tag in [9, 15, 25] {
+ assert_eq!(
+ native_control_factory_defaults(factory_tag),
+ (Some(0x3f80_0000), None)
+ );
+ }
+ }
+
#[test]
fn native_basement_mode_uses_unit_header_gate_not_builds_path() {
assert_eq!(
@@ -3005,6 +4511,291 @@ mod tests {
}
#[test]
+ fn synthetic_node_provider_projection_keeps_native_rows_separate_from_mesh_keys() {
+ let controls = vec![
+ Some(control_with_synthetic_node_data(
+ 0,
+ vec![synthetic_control_record(26, 1, 2.0_f32.to_bits(), None)],
+ 2,
+ )),
+ Some(control_with_synthetic_node_data(
+ 1,
+ vec![synthetic_control_record(26, 0, 3.0_f32.to_bits(), None)],
+ 7,
+ )),
+ Some(control_with_synthetic_node_data(
+ 2,
+ vec![synthetic_control_record(26, 5, 4.0_f32.to_bits(), None)],
+ 3,
+ )),
+ Some(control_with_synthetic_node_data(
+ 3,
+ vec![synthetic_control_record(26, 0, 5.0_f32.to_bits(), None)],
+ 2,
+ )),
+ Some(control_with_synthetic_node_data(
+ 4,
+ vec![synthetic_control_record(26, 0, 6.0_f32.to_bits(), None)],
+ 6,
+ )),
+ Some(control_with_synthetic_node_data(
+ 5,
+ vec![synthetic_control_record(26, 1, 6.0_f32.to_bits(), None)],
+ 5,
+ )),
+ Some(control_with_synthetic_node_data(
+ 6,
+ vec![synthetic_control_record(26, 1, 7.0_f32.to_bits(), None)],
+ 4,
+ )),
+ ];
+ let (status, node_provider_status) = synthetic_control_projection(
+ &[
+ None,
+ Some(PROTOTYPE_TYPE_INTO),
+ Some(PROTOTYPE_TYPE_EXTO),
+ Some(PROTOTYPE_TYPE_EXTO),
+ Some(PROTOTYPE_TYPE_EXTO),
+ None,
+ None,
+ ],
+ &[1, 1, 1, 1, 1, 0, 1],
+ &[4, 0, 1, 0, 0, 1, 0],
+ &[0, -1, 2, 0, -1, 0, 0],
+ &[1, 1, 4, 2, 1, 1, 1],
+ controls,
+ );
+ let table = synthetic_control_device_table_with_providers(status, node_provider_status);
+ let MissionControlNodeProviderTableStatus::Available(rows) = &table.node_provider_status
+ else {
+ panic!(
+ "synthetic provider rows should be available: {:?}",
+ table.node_provider_status
+ );
+ };
+
+ // Root contributes all rows, INTO contributes none, and each mounted
+ // EXTO skips its local row zero. The EXTO with C4=FFFFFFFF contributes
+ // no provider rows. The kind-zero component and its child are absent
+ // from the native active-component walk.
+ 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), (2, 1), (2, 2), (3, 1)]
+ );
+ assert!(rows
+ .iter()
+ .all(|row| row.initial_type1_value_bits == 1.0_f32.to_bits()));
+
+ let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
+ panic!("synthetic devices should be available: {:?}", table.status);
+ };
+ assert_eq!(
+ devices.iter().map(|device| device.key).collect::<Vec<_>>(),
+ [1, u32::MAX, 5, 0, u32::MAX]
+ );
+ assert_eq!(
+ query_control_device_table_selector(&table, 0, 0xe00)
+ .expect("root tag-26 selector")
+ .map(f32::to_bits),
+ Some(2.0_f32.to_bits())
+ );
+ // Device keys still use the confirmed MSH mapping. The provider list
+ // is the real concatenated NDP row count, so no model-node padding or
+ // second key remap hides an out-of-range key.
+ assert_eq!(
+ query_control_device_table_selector(&table, 2, 0xe00),
+ Err(ControlResourceAccessError::NodeProviderKeyOutOfRange {
+ key: 5,
+ row_count: 5
+ })
+ );
+ assert_eq!(
+ query_control_device_table_selector(&table, 3, 0xe00),
+ Ok(Some(5.0))
+ );
+ assert_eq!(
+ query_control_device_table_selector(&table, 4, 0xe00),
+ Err(ControlResourceAccessError::NodeProviderKeyOutOfRange {
+ key: u32::MAX,
+ row_count: 5
+ })
+ );
+ }
+
+ #[test]
+ fn missing_node_provider_does_not_hide_aggregate_queries() {
+ let controls = vec![Some(synthetic_component_control(
+ 0,
+ vec![
+ synthetic_control_record(26, 0, 2.0_f32.to_bits(), None),
+ synthetic_control_record(19, 1, 4.0_f32.to_bits(), None),
+ ],
+ PreparedControlEffectSection::Parsed(Vec::new()),
+ ))];
+ let (status, node_provider_status) =
+ synthetic_control_projection(&[None], &[1], &[0], &[0], &[1], controls);
+ let table = synthetic_control_device_table_with_providers(status, node_provider_status);
+ assert!(matches!(
+ &table.node_provider_status,
+ MissionControlNodeProviderTableStatus::Unavailable(
+ MissionControlNodeProviderTableUnavailableReason::MissingNodeData {
+ unit_component_index: 0,
+ ..
+ }
+ )
+ ));
+ assert_eq!(
+ query_control_device_table_resource(&table, 1)
+ .expect("aggregate selector 1 remains available")
+ .map(f32::to_bits),
+ Some(1.0_f32.to_bits())
+ );
+ assert_eq!(
+ query_control_device_table_resource(&table, 2)
+ .expect("aggregate selector 2 remains available")
+ .map(f32::to_bits),
+ Some(4.0_f32.to_bits())
+ );
+ assert!(matches!(
+ query_control_device_table_selector(&table, 0, 0xe00),
+ Err(ControlResourceAccessError::NodeProviderTableUnavailable(_))
+ ));
+ }
+
+ #[test]
+ fn mounted_exto_requires_a_row_before_native_skip_first() {
+ let controls = vec![
+ Some(control_with_synthetic_node_data(
+ 0,
+ vec![synthetic_control_record(26, 0, 1.0_f32.to_bits(), None)],
+ 0,
+ )),
+ Some(control_with_synthetic_node_data(1, Vec::new(), 0)),
+ ];
+ let (_, node_provider_status) = synthetic_control_projection(
+ &[None, Some(PROTOTYPE_TYPE_EXTO)],
+ &[1, 1],
+ &[1, 0],
+ &[0, 0],
+ &[2, 2],
+ controls,
+ );
+ assert_eq!(
+ node_provider_status,
+ MissionControlNodeProviderTableStatus::Unavailable(
+ MissionControlNodeProviderTableUnavailableReason::MissingExToRootRow {
+ unit_component_index: 1,
+ }
+ )
+ );
+
+ // An empty root table is legal, and a mounted EXTO with exactly its
+ // root row skips that row and contributes an empty range.
+ let controls = vec![
+ Some(control_with_synthetic_node_data(
+ 0,
+ vec![synthetic_control_record(26, 0, 1.0_f32.to_bits(), None)],
+ 0,
+ )),
+ Some(control_with_synthetic_node_data(1, Vec::new(), 1)),
+ ];
+ let (_, node_provider_status) = synthetic_control_projection(
+ &[None, Some(PROTOTYPE_TYPE_EXTO)],
+ &[1, 1],
+ &[1, 0],
+ &[0, 0],
+ &[2, 2],
+ controls,
+ );
+ assert_eq!(
+ node_provider_status,
+ MissionControlNodeProviderTableStatus::Available(Vec::new())
+ );
+ }
+
+ #[test]
+ fn indexed_node_provider_query_handles_current_tags_and_factory_scope() {
+ let available = MissionControlNodeProviderTableStatus::Available(vec![
+ synthetic_node_provider_row(0, 0, 1.0_f32.to_bits()),
+ synthetic_node_provider_row(0, 1, 1.0_f32.to_bits()),
+ synthetic_node_provider_row(0, 2, 1.0_f32.to_bits()),
+ ]);
+ let table = synthetic_control_device_table_with_providers(
+ MissionControlDeviceTableStatus::Available(vec![
+ synthetic_effective_control_device(
+ 26,
+ 26,
+ 2.0_f32.to_bits(),
+ Some(3.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 26,
+ 19,
+ 4.0_f32.to_bits(),
+ Some(5.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 26,
+ 5,
+ 1.0_f32.to_bits(),
+ Some(1.0_f32.to_bits()),
+ None,
+ ),
+ synthetic_effective_control_device(
+ 9,
+ 26,
+ 1.0_f32.to_bits(),
+ Some(1.0_f32.to_bits()),
+ Some(0.5_f32.to_bits()),
+ ),
+ ]),
+ available,
+ );
+ assert_eq!(
+ query_control_device_table_selector(&table, 0, 0xe00)
+ .expect("tag-26 query")
+ .map(f32::to_bits),
+ Some(6.0_f32.to_bits())
+ );
+ assert_eq!(
+ query_control_device_table_selector(&table, 1, 0xe00),
+ Ok(None)
+ );
+ for tag in [5, 10, 21] {
+ let mut unsupported = table.clone();
+ let MissionControlDeviceTableStatus::Available(entries) = &mut unsupported.status
+ else {
+ unreachable!();
+ };
+ entries[1].descriptor.tag = tag;
+ assert_eq!(
+ query_control_device_table_selector(&unsupported, 1, 0xe00),
+ Err(ControlResourceAccessError::UnsupportedCurrentTag { tag })
+ );
+ }
+ assert_eq!(
+ query_control_device_table_selector(&table, 3, 0xe00),
+ Err(ControlResourceAccessError::UnsupportedFactoryTag { factory_tag: 9 })
+ );
+ assert_eq!(
+ query_control_device_table_selector(&table, 0, 1),
+ Err(ControlResourceAccessError::UnsupportedSelector(1))
+ );
+ assert_eq!(
+ query_control_device_table_selector(&table, 8, 0xe00),
+ Err(ControlResourceAccessError::DeviceIndexOutOfRange {
+ device_index: 8,
+ device_count: 4
+ })
+ );
+ }
+
+ #[test]
fn synthetic_into_builder_appends_all_rows_and_overrides_only_first_record() {
let append = synthetic_control_table(
&[None, Some(PROTOTYPE_TYPE_INTO)],
@@ -3217,27 +5008,47 @@ mod tests {
let land_path = decode_mission_land_path(&source_tma, TmaProfile::Strict)
.expect("source mission land path")
.raw;
- let mut overlay = MemoryVfs::default();
- overlay.insert(
- normalize_engine_path("test mission", "MISSIONS/TEST/MINE/data.tma")
- .expect("mission path"),
- Arc::from(single_unit_tma(&land_path)),
- );
- let vfs = Arc::new(OverlayVfs::from_layers(vec![
- Arc::new(overlay),
- Arc::new(DirectoryVfs::new(&root)),
- ]));
- let mut engine = create(EngineServices::new(vfs)).expect("engine");
- let loaded = load_mission(
- &mut engine,
- MissionRequest {
- key: "MISSIONS/TEST/MINE/data.tma".to_string(),
- mode: MissionMode::SingleMission,
- },
- 0,
- )
- .expect("full normal mission load");
- assert_eq!(loaded.object_count, 1);
+ // The TMA keeps its strict marker; only the Unit DAT class header is
+ // overridden in the in-memory VFS to exercise both native profiles.
+ let load_full_fixture = |class_flags: u32| {
+ let mut overlay = MemoryVfs::default();
+ overlay.insert(
+ normalize_engine_path("test mission", "MISSIONS/TEST/MINE/data.tma")
+ .expect("mission path"),
+ Arc::from(single_unit_tma(&land_path)),
+ );
+ let mut unit_dat = std::fs::read(root.join("UNITS/BUILDS/MINE/min_l_n1.dat"))
+ .expect("licensed Unit DAT");
+ let original_class_flags =
+ u32::from_le_bytes(unit_dat[4..8].try_into().expect("Unit DAT header word"));
+ assert_eq!(original_class_flags, 0x8000_0004);
+ if class_flags != original_class_flags {
+ unit_dat[4..8].copy_from_slice(&class_flags.to_le_bytes());
+ }
+ overlay.insert(
+ normalize_engine_path("test Unit DAT", "UNITS/BUILDS/MINE/min_l_n1.dat")
+ .expect("Unit DAT path"),
+ Arc::from(unit_dat),
+ );
+ let vfs = Arc::new(OverlayVfs::from_layers(vec![
+ Arc::new(overlay),
+ Arc::new(DirectoryVfs::new(&root)),
+ ]));
+ let mut engine = create(EngineServices::new(vfs)).expect("engine");
+ let loaded = load_mission(
+ &mut engine,
+ MissionRequest {
+ key: "MISSIONS/TEST/MINE/data.tma".to_string(),
+ mode: MissionMode::SingleMission,
+ },
+ 0,
+ )
+ .expect("full normal mission load");
+ assert_eq!(loaded.object_count, 1);
+ engine
+ };
+ let mut engine = load_full_fixture(0x8000_0002);
+ let mine_engine = load_full_fixture(0x8000_0004);
let draft = &loaded_mission_object_drafts(&engine).expect("object drafts")[0];
assert_eq!(draft.unit_components.len(), 6);
@@ -3245,6 +5056,19 @@ mod tests {
let tables = loaded_mission_control_device_tables(&engine).expect("Control tables");
assert_eq!(tables.len(), 1);
assert_eq!(tables[0].original_id, Some(OriginalObjectId(0)));
+ let control_handle = tables[0].handle;
+ assert_eq!(
+ query_loaded_mission_control_resource(&engine, control_handle, 1)
+ .expect("licensed selector 1")
+ .map(f32::to_bits),
+ Some(1.0_f32.to_bits())
+ );
+ assert_eq!(
+ query_loaded_mission_control_resource(&engine, control_handle, 2)
+ .expect("licensed selector 2")
+ .map(f32::to_bits),
+ Some(16.0_f32.to_bits())
+ );
let MissionControlDeviceTableStatus::Available(entries) = &tables[0].status else {
panic!(
"licensed mine table should be available: {:?}",
@@ -3260,6 +5084,13 @@ mod tests {
[19, 19, 9, 15, 12, 12, 13, 13, 26, 25, 21]
);
assert_eq!(
+ entries
+ .iter()
+ .map(|entry| entry.descriptor.tag)
+ .collect::<Vec<_>>(),
+ [19, 19, 9, 15, 12, 12, 13, 13, 26, 25, 21]
+ );
+ assert_eq!(
entries.iter().map(|entry| entry.key).collect::<Vec<_>>(),
[2, 2, 1, 1, 18, 21, 15, 16, 2, 1, 22]
);
@@ -3274,6 +5105,10 @@ mod tests {
(entries[0].multiplier_bits, entries[0].native_word_50_bits),
(Some(0x3f80_0000), Some(0x20))
);
+ for index in [2, 3, 9] {
+ assert_eq!(entries[index].multiplier_bits, Some(0x3f80_0000));
+ }
+ assert_eq!(entries[2].class9_selector0_scale_bits, Some(0x3f80_0000));
assert_eq!(
entries
.iter()
@@ -3283,6 +5118,81 @@ mod tests {
);
assert_eq!(entries[8].descriptor_provenance.typed_record_index, 8);
assert_eq!(
+ query_loaded_mission_control_device_selector(&engine, control_handle, 8, 0xe00)
+ .expect("licensed tag-26 selector")
+ .map(f32::to_bits),
+ Some(1.0_f32.to_bits())
+ );
+ let profiles = loaded_mission_behavior_profiles(&engine).expect("Behavior profiles");
+ assert_eq!(profiles.len(), 1);
+ assert_eq!(profiles[0].original_id, OriginalObjectId(0));
+ assert_eq!(profiles[0].handle, control_handle);
+ assert_eq!(profiles[0].class_flags, 0x8000_0002);
+ assert_eq!(profiles[0].profile_entry, Some("prof_generator.var"));
+ assert_eq!(profiles[0].transfer_ore_off_board_bits, 0);
+ assert_eq!(profiles[0].transfer_power_out_bits, 10.0_f32.to_bits());
+ assert_eq!(
+ query_loaded_mission_behavior_resource(&engine, control_handle, 0x1005)
+ .expect("licensed profile power-out rate")
+ .to_bits(),
+ 10.0_f32.to_bits()
+ );
+ assert_eq!(
+ query_loaded_mission_behavior_resource(&engine, control_handle, 0x1002)
+ .expect("licensed profile ore-off-board rate")
+ .to_bits(),
+ 0.0_f32.to_bits()
+ );
+ let mine_profile =
+ loaded_mission_behavior_profiles(&mine_engine).expect("mine Behavior profile")[0];
+ assert_eq!(mine_profile.class_flags, 0x8000_0004);
+ assert_eq!(mine_profile.profile_entry, Some("prof_mine.var"));
+ assert_eq!(mine_profile.transfer_ore_off_board_bits, 1.0_f32.to_bits());
+ assert_eq!(mine_profile.transfer_power_out_bits, 0.0_f32.to_bits());
+ assert_eq!(
+ query_loaded_mission_behavior_resource(&mine_engine, mine_profile.handle, 0x1002)
+ .expect("mine profile ore resource query")
+ .to_bits(),
+ 1.0_f32.to_bits()
+ );
+ let prepared_controls = &engine
+ .loaded
+ .as_ref()
+ .expect("loaded mission state")
+ .mission_assets
+ .object_component_controls[0];
+ let root_node_data = prepared_controls[0]
+ .as_ref()
+ .and_then(|control| control.node_data.as_ref())
+ .expect("root NDP sidecar");
+ let ext_node_data = prepared_controls[5]
+ .as_ref()
+ .and_then(|control| control.node_data.as_ref())
+ .expect("EXTO NDP sidecar");
+ let provider_rows = match &tables[0].node_provider_status {
+ MissionControlNodeProviderTableStatus::Available(rows) => rows,
+ MissionControlNodeProviderTableStatus::Unavailable(reason) => {
+ panic!("licensed provider table should be available: {reason:?}");
+ }
+ };
+ assert_eq!(root_node_data.rows.len(), 22);
+ assert_eq!(ext_node_data.rows.len(), 4);
+ assert_eq!(provider_rows.len(), 25);
+ 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)))
+ .collect::<Vec<_>>();
+ assert_eq!(
+ provider_rows
+ .iter()
+ .map(|row| (row.unit_component_index, row.source_row_index))
+ .collect::<Vec<_>>(),
+ expected_provider_sources
+ );
+ assert!(provider_rows
+ .iter()
+ .all(|row| row.initial_type1_value_bits == 1.0_f32.to_bits()));
+ assert_eq!(
(
entries[9].factory_tag,
entries[9].component_id,
@@ -3300,6 +5210,14 @@ mod tests {
(21, 5, 22)
);
assert_eq!(entries[10].descriptor.tag, 21);
+ set_loaded_mission_control_multiplier(&mut engine, control_handle, 2.5)
+ .expect("licensed setter 1");
+ assert_eq!(
+ query_loaded_mission_control_resource(&engine, control_handle, 1)
+ .expect("updated licensed selector 1")
+ .map(f32::to_bits),
+ Some(2.5_f32.to_bits())
+ );
}
#[test]
@@ -4037,6 +5955,48 @@ mod tests {
}
#[test]
+ fn behavior_profile_mapper_matches_native_classes_and_unknowns_keep_constructor_defaults() {
+ let mapped = [
+ (0x8000_0004, "prof_mine.var"),
+ (0x8000_0008, "prof_storage.var"),
+ (0x8000_0002, "prof_generator.var"),
+ (0x8000_0010, "prof_plant.var"),
+ (0x8000_0040, "prof_angar.var"),
+ (0x8000_0200, "prof_mtp.var"),
+ (0x8000_0400, "prof_institute.var"),
+ (0x8001_0000, "prof_bunker.var"),
+ (0x8002_0000, "prof_bunker.var"),
+ (0x8004_0000, "prof_bunker.var"),
+ (0x8010_0000, "prof_tower.var"),
+ (0x8020_0000, "prof_tower.var"),
+ (0x0100_2000, "prof_trn.var"),
+ (0x0100_4000, "prof_bld.var"),
+ (0x0100_8000, "prof_war.var"),
+ (0x0101_0000, "prof_hq.var"),
+ (0x0102_0000, "prof_hero.var"),
+ (0x2000_0000, "prof_animal.var"),
+ ];
+ for (class_flags, entry) in mapped {
+ assert_eq!(behavior_profile_entry_for_class(class_flags), Some(entry));
+ }
+ assert_eq!(behavior_profile_entry_for_class(0xdead_beef), None);
+
+ let vfs: Arc<dyn Vfs> = Arc::new(MemoryVfs::default());
+ let drafts = [basement_draft(Some(0xdead_beef), 0)];
+ let states = prepare_behavior_profile_states(&vfs, &drafts)
+ .expect("unknown profile class preserves native constructor defaults");
+ assert_eq!(states.len(), 1);
+ assert_eq!(
+ states[0].map(|state| (
+ state.profile_entry,
+ state.transfer_ore_off_board_bits,
+ state.transfer_power_out_bits,
+ )),
+ Some((None, 0x40a0_0000, 0x42c8_0000))
+ );
+ }
+
+ #[test]
fn behavior_distributor_normalize_matches_native_24_bit_vectors() {
let mut pinned = BehaviorDistributorState {
clan_index: 0,
@@ -4137,6 +6097,9 @@ mod tests {
assert!(loaded_mission_behavior_ore_states(&engine)
.expect("preview Behavior ore state")
.is_empty());
+ assert!(loaded_mission_behavior_profiles(&engine)
+ .expect("preview Behavior profiles")
+ .is_empty());
assert!(bundles
.iter()
.all(|bundle| bundle.behavior_warm_start.is_none()));
@@ -4171,6 +6134,51 @@ mod tests {
#[test]
#[ignore = "requires licensed corpus"]
+ fn malformed_known_behavior_profile_keeps_previous_mission_and_world() {
+ let root = licensed_root("IS");
+ let mut overlay = MemoryVfs::default();
+ overlay.insert(
+ normalize_engine_path("broken Behavior archive", "behpsp.res")
+ .expect("profile archive path"),
+ Arc::from(&b"bad!"[..]),
+ );
+ let vfs: Arc<dyn Vfs> = Arc::new(OverlayVfs::from_layers(vec![
+ Arc::new(overlay),
+ Arc::new(DirectoryVfs::new(&root)),
+ ]));
+ let mut engine = create(EngineServices::new(vfs)).expect("engine");
+ let request = || MissionRequest {
+ key: "MISSIONS/Autodemo.00/data.tma".to_string(),
+ mode: MissionMode::SingleMission,
+ };
+ load_mission_static_preview_roots(
+ &mut engine,
+ request(),
+ NonZeroUsize::new(1).expect("one root"),
+ )
+ .expect("static preview does not require Behavior profile parsing");
+ let previous_mission = loaded_mission(&engine).expect("loaded preview").clone();
+ let before = step_headless(&mut engine, InputSnapshot)
+ .expect("step preview world")
+ .snapshot
+ .objects;
+
+ let error = load_mission(&mut engine, request(), 0)
+ .expect_err("malformed profile archive prevents full mission load");
+ assert!(matches!(
+ error,
+ EngineError::Nres { ref path, .. } if path == "behpsp.res"
+ ));
+ assert_eq!(loaded_mission(&engine), Some(&previous_mission));
+ let after = step_headless(&mut engine, InputSnapshot)
+ .expect("step retained preview world")
+ .snapshot
+ .objects;
+ assert_eq!(before, after);
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
fn loaded_host_callback_uses_requested_mode_and_constructor_status() {
let root = licensed_root("IS");
let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(root));
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 5f5f139..610e8db 100644
--- a/crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs
+++ b/crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs
@@ -23,10 +23,17 @@ internal static class BehaviorDistributorTickOracle {
private const int IndexedPropertySetRva = 0x0b470;
private const int IndexedPropertyGetRva = 0x0b5b0;
private const int OreInitializationRva = 0x08790;
+ private const int BehaviorProfileMapRva = 0x08a80;
+ private const int BehaviorVarBlockConstructorRva = 0x22d90;
+ private const int BehaviorVarFieldRegisterRva = 0x22e20;
private const int GetSystemArealMapIatRva = 0x59008;
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 ControlProviderAmountUpdateRva = 0x10f30;
private const int ArealMapUnitDatComponentBuilderRva = 0x14b90;
private const int ControlResourceDeviceConstructorRva = 0x22980;
private const int ControlResourceComponentOverrideRva = 0x2d890;
@@ -41,6 +48,10 @@ internal static class BehaviorDistributorTickOracle {
private const int ControlResourceNoOpStringPairRva = 0x0bcd0;
private const int ControlResourceTag19VtableRva = 0x3c608;
private const int ControlResourceTag19StringPairNoOpRva = 0x0bcd0;
+ private const int BehaviorVarTableVtableRva = 0x591b0;
+ private const int BehaviorVarArrayLoadRva = 0x49fa0;
+ private const int BehaviorVarFieldBindRva = 0x49090;
+ private const int BehaviorVarApplyRva = 0x49170;
private const uint ResourceProperty = 0x02000100;
private static Fixture active;
@@ -70,11 +81,23 @@ internal static class BehaviorDistributorTickOracle {
[UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void IndexedPropertySet(IntPtr self, uint index, uint valueBits);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int IndexedPropertyGet(IntPtr self, uint index, IntPtr resultBits);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeOreInitialization(IntPtr self);
+ [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate int NativeBehaviorVarArrayLoad(IntPtr self, IntPtr bytes, IntPtr cursorOut);
+ [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeBehaviorVarFieldBind(IntPtr self, IntPtr typeName, IntPtr fieldName, IntPtr destination);
+ [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeBehaviorVarApply(IntPtr self);
+ [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeBehaviorProfileMap(IntPtr self);
+ [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeBehaviorVarBlockConstructor(IntPtr self);
+ [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeBehaviorVarFieldRegister(IntPtr self, IntPtr table);
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void NativeBehaviorProfileLoadCallback(IntPtr owner, uint selector, IntPtr archive, IntPtr entry);
[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.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 NativeControlProviderRowConstructor(IntPtr self, IntPtr sourceNdpRow);
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void NativeControlNodeUpdateCallback(IntPtr self, uint nodeIndex, uint selector, uint valueBits);
private static readonly AreaMapGetter AreaMapGetterCallback = GetAreaMap;
private static readonly VectorInsert VectorInsertCallback = InsertVector;
@@ -88,7 +111,12 @@ internal static class BehaviorDistributorTickOracle {
private static readonly InterfaceGetProperty InterfaceGetCallback = GetInterfaceProperty;
private static readonly InterfaceSetProperty InterfaceSetCallback = SetInterfaceProperty;
private static readonly NativeArealMapEvent ArealMapEventCallback = OnArealMapEvent;
+ private static readonly NativeControlNodeUpdateCallback ControlNodeUpdateCallback = OnControlNodeUpdate;
private static ArealMapFixture activeArealMap;
+ private static int controlNodeUpdateCount;
+ private static uint controlNodeUpdateIndex;
+ private static uint controlNodeUpdateSelector;
+ private static uint controlNodeUpdateValueBits;
private static IntPtr fastcallThunks;
private static IntPtr queryObjectThunk;
private static IntPtr getInterfacePropertyThunk;
@@ -97,6 +125,15 @@ internal static class BehaviorDistributorTickOracle {
private static IntPtr x87ControlWordCell;
private static X87ControlWordReader x87ControlWordReader;
private static X87ControlWordWriter x87ControlWordWriter;
+ private static readonly NativeBehaviorProfileLoadCallback BehaviorProfileLoadCallback = CaptureBehaviorProfileLoad;
+ private static readonly List<BehaviorProfileSelection> behaviorProfileSelections = new List<BehaviorProfileSelection>();
+
+ private sealed class BehaviorProfileSelection {
+ public IntPtr Owner;
+ public uint Selector;
+ public string Archive;
+ public string Entry;
+ }
private sealed class NativeObject {
public IntPtr Self;
@@ -394,6 +431,12 @@ internal static class BehaviorDistributorTickOracle {
active.Trace.Add("iface-set:" + item.Key.ToString("x8") + ":" + iid.ToString("x") + ":" + selector.ToString("x") + ":" + number.ToString("R", System.Globalization.CultureInfo.InvariantCulture));
return 1;
}
+ private static void OnControlNodeUpdate(IntPtr self, uint nodeIndex, uint selector, uint valueBits) {
+ controlNodeUpdateCount++;
+ controlNodeUpdateIndex = nodeIndex;
+ controlNodeUpdateSelector = selector;
+ controlNodeUpdateValueBits = valueBits;
+ }
private static float SequenceValue(float[] sequence, int index, float fallback) {
if (sequence == null || sequence.Length == 0) return fallback;
return sequence[Math.Min(index, sequence.Length - 1)];
@@ -489,6 +532,7 @@ internal static class BehaviorDistributorTickOracle {
GC.KeepAlive(ObjectQueryCallback); GC.KeepAlive(ObjectRateCallback);
GC.KeepAlive(ObjectGetPropertyCallback); GC.KeepAlive(ObjectSetPropertyCallback);
GC.KeepAlive(InterfaceGetCallback); GC.KeepAlive(InterfaceSetCallback);
+ GC.KeepAlive(ControlNodeUpdateCallback);
GC.KeepAlive(ArealMapEventCallback);
if (thunksAllocated && !VirtualFree(fastcallThunks, UIntPtr.Zero, MemRelease))
throw new InvalidOperationException("VirtualFree(fastcall callback thunks) failed: " + Marshal.GetLastWin32Error());
@@ -510,6 +554,11 @@ internal static class BehaviorDistributorTickOracle {
RunNativeArealMapComponentBuilderCase(arealMapModule);
RunNativeControlIntoOverrideCase(controlModule);
RunNativeControlResourceDeviceCase(controlModule);
+ RunNativeControlProviderLiveStateCase(controlModule);
+ RunNativeControlAggregateResourceCases(controlModule);
+ RunNativeBehaviorProfileMapCases(module);
+ RunNativeBehaviorVarSyntheticCase(module);
+ RunNativeBehaviorRealProfileCases(module);
} finally {
SetX87ControlWord(savedControlWord);
Console.WriteLine("x87-control-word-restored=0x" + CurrentX87ControlWord().ToString("x4"));
@@ -589,6 +638,212 @@ internal static class BehaviorDistributorTickOracle {
}
}
+ private static void RunNativeControlProviderLiveStateCase(IntPtr module) {
+ NativeControlProviderRowConstructor constructProviderRow = (NativeControlProviderRowConstructor)
+ Marshal.GetDelegateForFunctionPointer(IntPtr.Add(module, ControlProviderRowConstructorRva),
+ typeof(NativeControlProviderRowConstructor));
+ NativeControlProviderAmountUpdate update = (NativeControlProviderAmountUpdate)
+ Marshal.GetDelegateForFunctionPointer(IntPtr.Add(module, ControlProviderAmountUpdateRva),
+ typeof(NativeControlProviderAmountUpdate));
+ NativeControlResourceDeviceGet getter = (NativeControlResourceDeviceGet)
+ Marshal.GetDelegateForFunctionPointer(IntPtr.Add(module, ControlResourceDeviceGetterRva),
+ typeof(NativeControlResourceDeviceGet));
+
+ using (Fixture fixture = NewFixture()) {
+ IntPtr owner = fixture.Allocate(0x664);
+ IntPtr rows = fixture.Allocate(2 * 0x2c);
+ IntPtr ndpDescriptor = fixture.Allocate(0x4c);
+ IntPtr initializedRow = fixture.Allocate(0x2c);
+ constructProviderRow(initializedRow, ndpDescriptor);
+ uint[] initialWords = new uint[11];
+ for (int i = 0; i < initialWords.Length; i++)
+ initialWords[i] = unchecked((uint)Marshal.ReadInt32(initializedRow, i * 4));
+ uint[] expectedInitialWords = {
+ unchecked((uint)ndpDescriptor.ToInt32()), 0xffffffff, 0x3f800000,
+ 0x3f800000, 0, 0x3f800000, 0, 1, 0, 0xffffffff, 0
+ };
+ Expect(String.Join(",", initialWords) == String.Join(",", expectedInitialWords),
+ "Control native NDP provider row constructor initializes all eleven words and type-1 current to 1.0");
+
+ IntPtr providerInterface = IntPtr.Add(owner, 4);
+ IntPtr providerVtable = IntPtr.Add(module, ControlProviderInterfaceVtableRva);
+ IntPtr callbackObject = fixture.Allocate(IntPtr.Size);
+ IntPtr callbackVtable = fixture.Allocate(0x38);
+ IntPtr device = fixture.Allocate(0x94);
+ IntPtr row = IntPtr.Add(rows, 0x2c); // Keep the root row untouched.
+
+ Marshal.WriteIntPtr(providerInterface, providerVtable);
+ Marshal.WriteIntPtr(owner, 0x55c, rows);
+ Marshal.WriteInt32(owner, 0x548, FloatBits(1.0f));
+ Marshal.WriteInt32(owner, 0x590, FloatBits(40.0f));
+ Marshal.WriteInt32(owner, 0x660, FloatBits(1.0f));
+
+ Marshal.WriteIntPtr(row, 0x00, ndpDescriptor);
+ Marshal.WriteInt32(ndpDescriptor, 0x04, FloatBits(100.0f)); // Native selector 3 maximum.
+ Marshal.WriteInt32(row, 0x04, -1); // Root row has no parent node.
+ Marshal.WriteInt32(row, 0x08, FloatBits(40.0f));
+ Marshal.WriteInt32(row, 0x14, FloatBits(0.4f));
+
+ Marshal.WriteIntPtr(callbackObject, 0, callbackVtable);
+ Marshal.WriteIntPtr(callbackVtable, 0x34, Marshal.GetFunctionPointerForDelegate(ControlNodeUpdateCallback));
+ Marshal.WriteIntPtr(owner, 0x20, callbackObject);
+
+ Marshal.WriteInt32(device, 0x04, 1);
+ Marshal.WriteInt32(device, 0x4c, FloatBits(3.0f));
+ Marshal.WriteInt32(device, 0x54, FloatBits(2.0f));
+ Marshal.WriteIntPtr(device, 0x44, providerInterface);
+
+ controlNodeUpdateCount = 0;
+ update(owner, 1, 20.0f, 0);
+ Expect(ReadFloat(row, 0x08) == 60.0f && ReadFloat(row, 0x14) == 0.6f &&
+ ReadFloat(owner, 0x590) == 60.0f,
+ "Control native amount update clamps the node amount, updates the normalized provider value, and keeps the aggregate amount in sync");
+ Expect(controlNodeUpdateCount == 1 && controlNodeUpdateIndex == 1 &&
+ controlNodeUpdateSelector == 0x200 && controlNodeUpdateValueBits == unchecked((uint)FloatBits(0.6f)),
+ "Control native amount update publishes the normalized provider state through the existing node callback");
+ Expect(unchecked((uint)FloatBits(getter(device, 0x300))) ==
+ unchecked((uint)FloatBits(0.6f * 2.0f * 3.0f)),
+ "Control tag-26 selector 0x300 observes the updated NDP provider value through the native provider interface");
+
+ update(owner, 1, -10.0f, 0);
+ Expect(ReadFloat(row, 0x08) == 50.0f && ReadFloat(row, 0x14) == 0.5f &&
+ unchecked((uint)FloatBits(getter(device, 0x300))) == 0x40400000,
+ "Control native amount update is reversible and tag-26 selector 0x300 tracks the changed provider row");
+
+ update(owner, 1, 1000.0f, 0);
+ Expect(ReadFloat(row, 0x08) == 100.0f && ReadFloat(row, 0x14) == 1.0f &&
+ unchecked((uint)FloatBits(getter(device, 0x300))) == 0x40c00000,
+ "Control native amount update clamps the provider value at its native selector-3 maximum");
+
+ update(owner, 1, -200.0f, 0);
+ Expect(ReadFloat(row, 0x08) == 0.0f && ReadFloat(row, 0x14) == 0.0f &&
+ (unchecked((uint)Marshal.ReadInt32(row, 0x28)) & 0x10) != 0 &&
+ unchecked((uint)FloatBits(getter(device, 0x300))) == 0,
+ "Control native depletion sets the exhausted flag and selector 0x300 returns the live zero provider value");
+ Expect(controlNodeUpdateCount == 4 && controlNodeUpdateIndex == 1 &&
+ controlNodeUpdateSelector == 0x200 && controlNodeUpdateValueBits == 0,
+ "Control native node callback receives every normalized provider update through exhaustion");
+
+ Console.WriteLine("native-control-live-ndp-provider: controlHash=" + ExpectedControlSha256 +
+ " rowCtorRva=0xb240 initialType1=1 rowStride=0x2c node=1 max=100 amount=0..100 tag26Selector300=live");
+ GC.KeepAlive(constructProviderRow);
+ GC.KeepAlive(update);
+ GC.KeepAlive(getter);
+ }
+ }
+
+ private static void RunNativeControlAggregateResourceCases(IntPtr module) {
+ NativeControlAggregateQuery query = (NativeControlAggregateQuery)Marshal.GetDelegateForFunctionPointer(
+ WriteStdCallToFastcallThunk(0x1c0, IntPtr.Add(module, ControlResourceAggregateQueryRva)),
+ typeof(NativeControlAggregateQuery));
+ NativeControlAggregateSet set = (NativeControlAggregateSet)Marshal.GetDelegateForFunctionPointer(
+ WriteStdCallToFastcallThunk(0x200, IntPtr.Add(module, ControlResourceAggregateSetRva)),
+ typeof(NativeControlAggregateSet));
+ using (Fixture fixture = NewFixture()) {
+ IntPtr owner = fixture.Allocate(0x5b8);
+ IntPtr devices = fixture.Allocate(4 * IntPtr.Size);
+ IntPtr result = fixture.Allocate(sizeof(uint));
+ IntPtr value = fixture.Allocate(sizeof(uint));
+
+ IntPtr tag9Current19 = AddNativeControlAggregateDevice(fixture, module, 9, 19,
+ 0x120, ControlResourceTag9ConstructorRva, ControlResourceTag9VtableRva, 2.0f, 3.0f, 0.5f);
+ IntPtr tag19Current9 = AddNativeControlAggregateDevice(fixture, module, 19, 9,
+ 0x94, ControlResourceDeviceConstructorRva, ControlResourceTag19VtableRva, 100.0f, 77.0f, 1.0f);
+ IntPtr tag15Current19 = AddNativeControlAggregateDevice(fixture, module, 15, 19,
+ 0x98, ControlResourceTag15ConstructorRva, ControlResourceTag15VtableRva, 4.0f, 0.5f, 1.0f);
+ IntPtr tag19Current19 = AddNativeControlAggregateDevice(fixture, module, 19, 19,
+ 0x94, ControlResourceDeviceConstructorRva, ControlResourceTag19VtableRva, 1.0f, 4.0f, 1.0f);
+
+ Marshal.WriteIntPtr(devices, 0, tag9Current19);
+ Marshal.WriteIntPtr(devices, IntPtr.Size, tag19Current9);
+ Marshal.WriteIntPtr(devices, 2 * IntPtr.Size, tag15Current19);
+ Marshal.WriteIntPtr(devices, 3 * IntPtr.Size, tag19Current19);
+ Marshal.WriteIntPtr(owner, 0x5b0, devices);
+ Marshal.WriteInt32(owner, 0x5b4, 4);
+
+ Expect(NativeBoolean(query(owner, 1, result)) == 1 && unchecked((uint)Marshal.ReadInt32(result)) == 0x40000000,
+ "Control aggregate selector 1 includes descriptor-19 entries and dispatches their original factory vtables");
+ Expect(NativeBoolean(query(owner, 2, result)) == 1 && unchecked((uint)Marshal.ReadInt32(result)) == 0x40c00000,
+ "Control aggregate selector 2 sums base values for descriptor-19 entries");
+
+ Marshal.WriteInt32(value, 0, FloatBits(7.5f));
+ Expect(NativeBoolean(set(owner, 1, value)) == 1,
+ "Control aggregate setter selector 1 reports success for its recognized selector");
+ Expect(unchecked((uint)Marshal.ReadInt32(tag9Current19, 0x4c)) == 0x40f00000 &&
+ unchecked((uint)Marshal.ReadInt32(tag15Current19, 0x4c)) == 0x40f00000 &&
+ unchecked((uint)Marshal.ReadInt32(tag19Current19, 0x4c)) == 0x40f00000 &&
+ unchecked((uint)Marshal.ReadInt32(tag19Current9, 0x4c)) == FloatBits(77.0f),
+ "Control setter selector 1 updates matching positive devices regardless of factory class, and skips current descriptor tag 9");
+ Expect(NativeBoolean(query(owner, 1, result)) == 1 && unchecked((uint)Marshal.ReadInt32(result)) == 0x410c0000,
+ "Control aggregate selector 1 reflects updated per-device multipliers");
+
+ // Factory tag 9's virtual selector 0 includes +0x11c. A zero base keeps
+ // this selected descriptor out of the native setter's positive-only write.
+ Marshal.WriteInt32(tag9Current19, 0x11c, FloatBits(0.0f));
+ Marshal.WriteInt32(value, 0, FloatBits(9.0f));
+ Expect(NativeBoolean(set(owner, 1, value)) == 1 &&
+ unchecked((uint)Marshal.ReadInt32(tag9Current19, 0x4c)) == 0x40f00000,
+ "Control setter selector 1 leaves the multiplier unchanged when the original factory getter returns zero");
+
+ Marshal.WriteInt32(owner, 0x5b4, 0);
+ Marshal.WriteInt32(result, 0, unchecked((int)0x3f123456));
+ Expect(NativeBoolean(query(owner, 1, result)) == 0 && unchecked((uint)Marshal.ReadInt32(result)) == 0x3f123456,
+ "Control aggregate selector 1 reports no result and leaves output untouched when the table is empty");
+ Expect(NativeBoolean(query(owner, 2, result)) == 0 && unchecked((uint)Marshal.ReadInt32(result)) == 0x3f123456,
+ "Control aggregate selector 2 reports no result and leaves output untouched when the table is empty");
+ Expect(NativeBoolean(set(owner, 1, value)) == 1,
+ "Control aggregate setter selector 1 reports success when the table is empty");
+
+ // The aggregate accumulators spill back to float precision every row.
+ Marshal.WriteInt32(owner, 0x5b4, 3);
+ Marshal.WriteInt32(Marshal.ReadIntPtr(tag19Current9, 0x48), 0, 19);
+ Marshal.WriteInt32(tag9Current19, 0x54, FloatBits(1.0f));
+ Marshal.WriteInt32(tag9Current19, 0x4c, FloatBits(16777216.0f));
+ Marshal.WriteInt32(tag9Current19, 0x11c, FloatBits(1.0f));
+ Marshal.WriteInt32(tag19Current9, 0x54, FloatBits(1.0f));
+ Marshal.WriteInt32(tag19Current9, 0x4c, FloatBits(1.0f));
+ Marshal.WriteInt32(tag15Current19, 0x54, FloatBits(1.0f));
+ Marshal.WriteInt32(tag15Current19, 0x4c, FloatBits(-16777216.0f));
+ Expect(NativeBoolean(query(owner, 1, result)) == 1 && Marshal.ReadInt32(result) == 0,
+ "Control aggregate selector 1 rounds each accumulator to float after each row");
+
+ Marshal.WriteInt32(owner, 0x5b4, 1);
+ Marshal.WriteInt32(tag9Current19, 0x54, FloatBits(-1.0f));
+ Marshal.WriteInt32(tag9Current19, 0x4c, FloatBits(2.0f));
+ Marshal.WriteInt32(result, 0, unchecked((int)0x3f123456));
+ Expect(NativeBoolean(query(owner, 1, result)) == 1 && Marshal.ReadInt32(result) == FloatBits(1.0f),
+ "Control aggregate selector 1 returns one immediately when a selected base value is negative");
+ Expect(NativeBoolean(query(owner, 2, result)) == 1 && Marshal.ReadInt32(result) == FloatBits(-1.0f),
+ "Control aggregate selector 2 returns a selected negative base value immediately");
+
+ Console.WriteLine("native-control-global-resource-table: controlHash=" + ExpectedControlSha256 +
+ " getterRva=0x2b410 setterRva=0x2ba30 selectors=1,2 descriptorFilter=19" +
+ " factory19-descriptor9=excluded factory9-descriptor19-scale=0.5" +
+ " factory15-descriptor19=included initial=[2,6] multiplier=7.5 post-set-getter1=8.75" +
+ " empty=[false/unchanged,false/unchanged,set=true] rounding=0 negative=[1,-1]");
+ GC.KeepAlive(query);
+ GC.KeepAlive(set);
+ }
+ }
+
+ private static IntPtr AddNativeControlAggregateDevice(Fixture fixture, IntPtr module,
+ int factoryTag, int currentDescriptorTag, int objectSize, int constructorRva, int vtableRva,
+ float coefficient, float multiplier, float class9Scale) {
+ IntPtr device = fixture.Allocate(objectSize);
+ NativeControlResourceDeviceConstructor construct = (NativeControlResourceDeviceConstructor)Marshal.GetDelegateForFunctionPointer(
+ IntPtr.Add(module, constructorRva), typeof(NativeControlResourceDeviceConstructor));
+ IntPtr expectedVtable = IntPtr.Add(module, vtableRva);
+ Expect(construct(device) == device && Marshal.ReadIntPtr(device) == expectedVtable,
+ "native factory tag " + factoryTag + " constructor installs its original class vtable");
+ IntPtr descriptor = fixture.Allocate(sizeof(uint));
+ Marshal.WriteInt32(descriptor, 0, currentDescriptorTag);
+ Marshal.WriteIntPtr(device, 0x48, descriptor);
+ Marshal.WriteInt32(device, 0x4c, FloatBits(multiplier));
+ Marshal.WriteInt32(device, 0x54, FloatBits(coefficient));
+ if (factoryTag == 9) Marshal.WriteInt32(device, 0x11c, FloatBits(class9Scale));
+ return device;
+ }
+
private static void RunNativeArealMapComponentBuilderCase(IntPtr module) {
using (ArealMapFixture fixture = new ArealMapFixture()) {
fixture.OwnerVtable = fixture.Allocate(0x40);
@@ -863,6 +1118,243 @@ internal static class BehaviorDistributorTickOracle {
Console.WriteLine("native-behavior-ore-initialization: classes=80000004,80000008,01002000,01004000,01008000; defaults=verified");
}
+ private static void CaptureBehaviorProfileLoad(IntPtr owner, uint selector, IntPtr archive, IntPtr entry) {
+ behaviorProfileSelections.Add(new BehaviorProfileSelection {
+ Owner = owner,
+ Selector = selector,
+ Archive = Marshal.PtrToStringAnsi(archive),
+ Entry = Marshal.PtrToStringAnsi(entry)
+ });
+ }
+
+ private static void RunNativeBehaviorProfileMapCases(IntPtr module) {
+ NativeBehaviorProfileMap map = (NativeBehaviorProfileMap)Marshal.GetDelegateForFunctionPointer(
+ IntPtr.Add(module, BehaviorProfileMapRva), typeof(NativeBehaviorProfileMap));
+ string[][] cases = new string[][] {
+ new string[] { "80000004", "prof_mine.var" },
+ new string[] { "80000008", "prof_storage.var" },
+ new string[] { "80000002", "prof_generator.var" },
+ new string[] { "80000010", "prof_plant.var" },
+ new string[] { "80000040", "prof_angar.var" },
+ new string[] { "80000200", "prof_mtp.var" },
+ new string[] { "80000400", "prof_institute.var" },
+ new string[] { "80010000", "prof_bunker.var" },
+ new string[] { "80020000", "prof_bunker.var" },
+ new string[] { "80040000", "prof_bunker.var" },
+ new string[] { "80100000", "prof_tower.var" },
+ new string[] { "80200000", "prof_tower.var" },
+ new string[] { "01002000", "prof_trn.var" },
+ new string[] { "01004000", "prof_bld.var" },
+ new string[] { "01008000", "prof_war.var" },
+ new string[] { "01010000", "prof_hq.var" },
+ new string[] { "01020000", "prof_hero.var" },
+ new string[] { "20000000", "prof_animal.var" }
+ };
+ using (Fixture fixture = NewFixture()) {
+ IntPtr owner = fixture.Allocate(0x0b00);
+ IntPtr vtable = fixture.Allocate(0x68);
+ Marshal.WriteIntPtr(owner, vtable);
+ Marshal.WriteIntPtr(vtable, 0x64, Marshal.GetFunctionPointerForDelegate(BehaviorProfileLoadCallback));
+ foreach (string[] test in cases) {
+ behaviorProfileSelections.Clear();
+ Marshal.WriteInt32(owner, 0x0afc, unchecked((int)Convert.ToUInt32(test[0], 16)));
+ map(owner);
+ Expect(behaviorProfileSelections.Count == 1, "profile mapper callback count for class 0x" + test[0]);
+ BehaviorProfileSelection selection = behaviorProfileSelections[0];
+ Expect(selection.Owner == owner && selection.Selector == 2 && selection.Archive == "behpsp.res" &&
+ selection.Entry == test[1], "profile mapper result for class 0x" + test[0]);
+ }
+ string[] noMatch = new string[] { "deadbeef", "8000000c" };
+ foreach (string test in noMatch) {
+ behaviorProfileSelections.Clear();
+ Marshal.WriteInt32(owner, 0x0afc, unchecked((int)Convert.ToUInt32(test, 16)));
+ map(owner);
+ Expect(behaviorProfileSelections.Count == 0, "profile mapper leaves unknown/combined class 0x" + test + " unconfigured");
+ }
+ }
+ Console.WriteLine("native-behavior-profile-map: mapped-classes=" + cases.Length + " (including three bunker and two tower codes); unknown-and-combined=no callback");
+ }
+
+ private static void RunNativeBehaviorVarSyntheticCase(IntPtr module) {
+ NativeBehaviorVarArrayLoad load = (NativeBehaviorVarArrayLoad)Marshal.GetDelegateForFunctionPointer(
+ IntPtr.Add(module, BehaviorVarArrayLoadRva), typeof(NativeBehaviorVarArrayLoad));
+ NativeBehaviorVarFieldBind bind = (NativeBehaviorVarFieldBind)Marshal.GetDelegateForFunctionPointer(
+ IntPtr.Add(module, BehaviorVarFieldBindRva), typeof(NativeBehaviorVarFieldBind));
+ NativeBehaviorVarApply apply = (NativeBehaviorVarApply)Marshal.GetDelegateForFunctionPointer(
+ IntPtr.Add(module, BehaviorVarApplyRva), typeof(NativeBehaviorVarApply));
+ byte[] bytes = SerializeOneBehaviorVarField("Transfer_Ore_OffBoard", "float", 0x3f000000, 0x41200000);
+ using (Fixture fixture = NewFixture()) {
+ IntPtr table = fixture.Allocate(0x18);
+ IntPtr target = fixture.Allocate(sizeof(uint));
+ IntPtr input = fixture.Allocate(bytes.Length);
+ IntPtr cursorOut = fixture.Allocate(IntPtr.Size);
+ IntPtr fieldName = fixture.Allocate(32);
+ IntPtr typeName = fixture.Allocate(8);
+ CopyBytes(input, bytes);
+ WriteFixedAnsi(fieldName, 0, "Transfer_Ore_OffBoard", 32);
+ WriteFixedAnsi(typeName, 0, "float", 8);
+ Marshal.WriteIntPtr(table, IntPtr.Add(module, BehaviorVarTableVtableRva));
+ Marshal.WriteInt32(input, 0, 1);
+
+ Expect(load(table, input, cursorOut) == 1, "native .var parser accepts the synthetic one-row profile");
+ Expect(Marshal.ReadInt32(table, 4) == 1 && Marshal.ReadIntPtr(cursorOut) == IntPtr.Add(input, bytes.Length),
+ "native .var parser consumes the full synthetic profile");
+ bind(table, typeName, fieldName, target);
+ apply(table);
+ Expect(unchecked((uint)Marshal.ReadInt32(target)) == 0x41200000,
+ "native .var apply uses the second value blob after binding");
+ Console.WriteLine("native-behavior-var-synthetic: first=0x3f000000 second=0x41200000 applied=0x" +
+ unchecked((uint)Marshal.ReadInt32(target)).ToString("x8"));
+ }
+ }
+
+ private static void RunNativeBehaviorRealProfileCases(IntPtr module) {
+ string archivePath = Environment.GetEnvironmentVariable("FPARKAN_ORIGINAL_BEHAVIOR_PROFILE_RES");
+ if (String.IsNullOrEmpty(archivePath)) archivePath = @"C:\GOG Games\Parkan - Iron Strategy\behpsp.res";
+ if (!File.Exists(archivePath)) throw new FileNotFoundException(
+ "Set FPARKAN_ORIGINAL_BEHAVIOR_PROFILE_RES to the installed behpsp.res.", archivePath);
+ byte[] archiveBytes = File.ReadAllBytes(archivePath);
+ NativeBehaviorProfileMap map = (NativeBehaviorProfileMap)Marshal.GetDelegateForFunctionPointer(
+ IntPtr.Add(module, BehaviorProfileMapRva), typeof(NativeBehaviorProfileMap));
+ NativeBehaviorVarArrayLoad load = (NativeBehaviorVarArrayLoad)Marshal.GetDelegateForFunctionPointer(
+ IntPtr.Add(module, BehaviorVarArrayLoadRva), typeof(NativeBehaviorVarArrayLoad));
+ NativeBehaviorVarBlockConstructor construct = (NativeBehaviorVarBlockConstructor)Marshal.GetDelegateForFunctionPointer(
+ IntPtr.Add(module, BehaviorVarBlockConstructorRva), typeof(NativeBehaviorVarBlockConstructor));
+ NativeBehaviorVarFieldRegister register = (NativeBehaviorVarFieldRegister)Marshal.GetDelegateForFunctionPointer(
+ IntPtr.Add(module, BehaviorVarFieldRegisterRva), typeof(NativeBehaviorVarFieldRegister));
+ NativeBehaviorVarApply apply = (NativeBehaviorVarApply)Marshal.GetDelegateForFunctionPointer(
+ IntPtr.Add(module, BehaviorVarApplyRva), typeof(NativeBehaviorVarApply));
+
+ string selectedEntry = SelectBehaviorProfile(map, 0x80000004);
+ Expect(selectedEntry == "prof_mine.var", "mine profile is selected by native class mapper");
+ byte[] profile = ReadNresEntry(archiveBytes, selectedEntry);
+ Expect(ReadUInt32(profile, 0) == 27, "native mine profile contains all 27 rows");
+ uint expectedOreOffBoard = FindBehaviorVarSecondBlob(profile, "Transfer_Ore_OffBoard");
+ uint expectedPowerOut = FindBehaviorVarSecondBlob(profile, "Transfer_Power_Out");
+
+ using (Fixture fixture = NewFixture()) {
+ IntPtr table = fixture.Allocate(0x18);
+ IntPtr rawProfile = fixture.Allocate(profile.Length);
+ IntPtr cursorOut = fixture.Allocate(IntPtr.Size);
+ IntPtr block = fixture.Allocate(0x80);
+ CopyBytes(rawProfile, profile);
+ Marshal.WriteIntPtr(table, IntPtr.Add(module, BehaviorVarTableVtableRva));
+
+ Expect(load(table, rawProfile, cursorOut) == 1, "native parser accepts the licensed mine profile");
+ Expect(Marshal.ReadInt32(table, 4) == 27 && Marshal.ReadIntPtr(cursorOut) == IntPtr.Add(rawProfile, profile.Length),
+ "native parser consumes all rows in the licensed mine profile");
+ construct(block);
+ Expect(unchecked((uint)Marshal.ReadInt32(block, 0x58)) == 0x40a00000 &&
+ unchecked((uint)Marshal.ReadInt32(block, 0x60)) == 0x42c80000,
+ "native variable block starts with transfer defaults 5 and 100");
+ register(block, table);
+ apply(table);
+ Expect(unchecked((uint)Marshal.ReadInt32(block, 0x58)) == expectedOreOffBoard &&
+ unchecked((uint)Marshal.ReadInt32(block, 0x60)) == expectedPowerOut,
+ "native profile bind/apply copies second blobs into Transfer_Ore_OffBoard and Transfer_Power_Out");
+ Console.WriteLine("native-behavior-real-profile: class=80000004 entry=" + selectedEntry + " rows=27 Transfer_Ore_OffBoard=" +
+ Hex(expectedOreOffBoard) + " Transfer_Power_Out=" + Hex(expectedPowerOut) + "; native-bind-and-apply=verified");
+ }
+ }
+
+ private static string SelectBehaviorProfile(NativeBehaviorProfileMap map, uint classCode) {
+ using (Fixture fixture = NewFixture()) {
+ IntPtr owner = fixture.Allocate(0x0b00);
+ IntPtr vtable = fixture.Allocate(0x68);
+ Marshal.WriteIntPtr(owner, vtable);
+ Marshal.WriteIntPtr(vtable, 0x64, Marshal.GetFunctionPointerForDelegate(BehaviorProfileLoadCallback));
+ behaviorProfileSelections.Clear();
+ Marshal.WriteInt32(owner, 0x0afc, unchecked((int)classCode));
+ map(owner);
+ Expect(behaviorProfileSelections.Count == 1, "native mapper returned a single profile for class 0x" + classCode.ToString("x8"));
+ BehaviorProfileSelection selection = behaviorProfileSelections[0];
+ Expect(selection.Owner == owner && selection.Selector == 2 && selection.Archive == "behpsp.res",
+ "native mapper selected the behavior profile archive and selector");
+ return selection.Entry;
+ }
+ }
+
+ private static byte[] SerializeOneBehaviorVarField(string fieldName, string typeName, uint firstBits, uint secondBits) {
+ byte[] field = Encoding.ASCII.GetBytes(fieldName);
+ byte[] type = Encoding.ASCII.GetBytes(typeName);
+ using (MemoryStream stream = new MemoryStream()) using (BinaryWriter writer = new BinaryWriter(stream)) {
+ writer.Write((uint)1); // row count
+ writer.Write((uint)4); // value size
+ writer.Write((uint)3); // float type index
+ writer.Write((uint)0); // flags
+ writer.Write((uint)field.Length); writer.Write(field);
+ writer.Write((uint)type.Length); writer.Write(type);
+ writer.Write(firstBits); writer.Write(secondBits);
+ writer.Write((uint)0); writer.Write((uint)0); // trailing row metadata
+ return stream.ToArray();
+ }
+ }
+
+ private static byte[] ReadNresEntry(byte[] archive, string name) {
+ if (archive.Length < 16) throw new InvalidDataException("NRes archive is shorter than its header");
+ uint count = ReadUInt32(archive, 8);
+ if (count > Int32.MaxValue / 64) throw new InvalidDataException("NRes directory count is too large");
+ int directory = checked(archive.Length - (int)count * 64);
+ if (directory < 16) throw new InvalidDataException("NRes directory falls inside the header");
+ for (int index = 0; index < (int)count; index++) {
+ int record = checked(directory + index * 64);
+ int nameEnd = record + 20;
+ while (nameEnd < record + 56 && archive[nameEnd] != 0) nameEnd++;
+ string entryName = Encoding.ASCII.GetString(archive, record + 20, nameEnd - (record + 20));
+ if (!String.Equals(entryName, name, StringComparison.Ordinal)) continue;
+ uint size = ReadUInt32(archive, record + 12);
+ uint dataOffset = ReadUInt32(archive, record + 56);
+ if (size > Int32.MaxValue || dataOffset > Int32.MaxValue || dataOffset + size > archive.Length)
+ throw new InvalidDataException("NRes entry range is outside the archive");
+ byte[] data = new byte[(int)size];
+ Buffer.BlockCopy(archive, (int)dataOffset, data, 0, data.Length);
+ return data;
+ }
+ throw new InvalidDataException("NRes archive does not contain entry " + name);
+ }
+
+ private static uint FindBehaviorVarSecondBlob(byte[] profile, string fieldName) {
+ if (profile.Length < 4) throw new InvalidDataException("Behavior profile is shorter than its row count");
+ uint count = ReadUInt32(profile, 0);
+ if (count > 1024) throw new InvalidDataException("Behavior profile row count is unreasonable");
+ int cursor = 4;
+ for (int index = 0; index < (int)count; index++) {
+ EnsureRange(profile, cursor, 12);
+ uint size = ReadUInt32(profile, cursor);
+ if (size > Int32.MaxValue) throw new InvalidDataException("Behavior variable size is too large");
+ uint type = ReadUInt32(profile, cursor + 4);
+ cursor += 12;
+ uint fieldLength = ReadUInt32(profile, cursor);
+ if (fieldLength > Int32.MaxValue) throw new InvalidDataException("Behavior field name is too large");
+ cursor += 4; EnsureRange(profile, cursor, (int)fieldLength);
+ string name = Encoding.ASCII.GetString(profile, cursor, (int)fieldLength);
+ cursor += (int)fieldLength;
+ uint typeLength = ReadUInt32(profile, cursor);
+ if (typeLength > Int32.MaxValue) throw new InvalidDataException("Behavior variable type name is too large");
+ cursor += 4; EnsureRange(profile, cursor, (int)typeLength);
+ cursor += (int)typeLength;
+ EnsureRange(profile, cursor, checked((int)size * 2 + 8));
+ int secondBlob = checked(cursor + (int)size);
+ if (String.Equals(name, fieldName, StringComparison.Ordinal)) {
+ if (type != 3 || size != 4) throw new InvalidDataException("Expected float profile field " + fieldName);
+ return ReadUInt32(profile, secondBlob);
+ }
+ cursor = checked(cursor + (int)size * 2 + 8);
+ }
+ throw new InvalidDataException("Behavior profile does not contain field " + fieldName);
+ }
+
+ private static uint ReadUInt32(byte[] data, int offset) {
+ EnsureRange(data, offset, 4);
+ return unchecked((uint)(data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)));
+ }
+
+ private static void EnsureRange(byte[] data, int offset, int size) {
+ if (offset < 0 || size < 0 || offset > data.Length - size) throw new InvalidDataException("Behavior profile range is outside its input");
+ }
+
+ private static void CopyBytes(IntPtr destination, byte[] source) { Marshal.Copy(source, 0, destination, source.Length); }
+
private static ushort CurrentX87ControlWord() {
if (x87ControlWordReader == null || x87ControlWordCell == IntPtr.Zero)
throw new InvalidOperationException("x87 control-word reader is not initialized");
@@ -1276,6 +1768,7 @@ internal static class BehaviorDistributorTickOracle {
foreach (byte value in digest) hex.Append(value.ToString("x2")); return hex.ToString();
}
}
+ private static int NativeBoolean(int eax) { return eax & 0xff; }
private static void Expect(bool value, string message) { if (!value) throw new InvalidOperationException("original native oracle failed: " + message); }
private static void ExpectLookupOrder(Fixture fixture, params string[] keys) {
List<string> actual = new List<string>();