feat(runtime): project initial Control mesh metadata
Docs Deploy / Build and Deploy MkDocs (push) Successful in 35s

This commit is contained in:
Valentin Popov committed 2026-10-23 13:20:59 +04:00
1 parent ce8e65c8ae
commit 4e16902661
8 files changed
+655 -6

No files matched your search

Generated
+1
View File
@@ -630,6 +630,7 @@ name = "fparkan-runtime"
version = "0.1.0"
dependencies = [
"fparkan-assets",
"fparkan-msh",
"fparkan-path",
"fparkan-platform",
"fparkan-prototype",
+9 -3
View File
@@ -140,7 +140,10 @@ pub struct Node {
/// Raw fields of the standard 38-byte node layout that precede slot selection.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Node38Metadata {
/// Unassigned source link value at byte offset two.
/// Raw Node38 header/flag word at byte offset zero.
pub header_flags: u16,
/// Source-local parent word at byte offset two; `0xFFFF` is the native
/// sentinel before component rebasing.
pub parent_or_link_raw: u16,
/// Offset into the type-19 frame map, or `0xFFFF` for no map.
pub anim_map_start: u16,
@@ -431,6 +434,7 @@ pub fn node38_metadata(model: &ModelAsset, node: NodeId) -> Option<Node38Metadat
}
let offset = node_index.checked_mul(model.node_stride)?;
Some(Node38Metadata {
header_flags: read_u16(&model.nodes_raw, offset)?,
parent_or_link_raw: read_u16(&model.nodes_raw, offset + 2)?,
anim_map_start: read_u16(&model.nodes_raw, offset + 4)?,
fallback_key: read_u16(&model.nodes_raw, offset + 6)?,
@@ -441,8 +445,8 @@ pub fn node38_metadata(model: &ModelAsset, node: NodeId) -> Option<Node38Metadat
///
/// The legacy sampler uses this key when a node has no frame map or its current
/// frame falls outside that map. It is a static-pose input only; callers must
/// still recover animation state and the meaning of `parent_or_link_raw` before
/// assembling a runtime hierarchy. Its quaternion is converted to match native
/// assemble the runtime hierarchy separately and apply the component-specific
/// mapping of `parent_or_link_raw`. Its quaternion is converted to match native
/// AniMesh's quaternion-to-matrix convention.
#[must_use]
pub fn node38_fallback_pose(model: &ModelAsset, node: NodeId) -> Option<Pose> {
@@ -1412,6 +1416,7 @@ mod tests {
#[test]
fn standard_node_exposes_fallback_pose_and_unassigned_link() {
let mut node = node38([u16::MAX; 15]);
node[0..2].copy_from_slice(&0x8201_u16.to_le_bytes());
node[2..4].copy_from_slice(&7_u16.to_le_bytes());
node[4..6].copy_from_slice(&u16::MAX.to_le_bytes());
node[6..8].copy_from_slice(&0_u16.to_le_bytes());
@@ -1440,6 +1445,7 @@ mod tests {
assert_eq!(
node38_metadata(&model, NodeId(0)),
Some(Node38Metadata {
header_flags: 0x8201,
parent_or_link_raw: 7,
anim_map_start: u16::MAX,
fallback_key: 0,
+1
View File
@@ -7,6 +7,7 @@ repository.workspace = true
[dependencies]
fparkan-assets = { path = "../fparkan-assets" }
fparkan-msh = { path = "../fparkan-msh" }
fparkan-path = { path = "../fparkan-path" }
fparkan-platform = { path = "../fparkan-platform" }
fparkan-prototype = { path = "../fparkan-prototype" }
+444
View File
@@ -13,6 +13,7 @@ use fparkan_assets::{
PreparedControlNodeDataTable, PreparedControlTypedRecord, PreparedVisual, TerrainFormatError,
TerrainPreparationError, TerrainWorld, TmaProfile,
};
use fparkan_msh::{node38_metadata, selected_slot, Group, Lod, NodeId};
use fparkan_path::{normalize_relative, NormalizedPath, PathError, PathPolicy};
use fparkan_prototype::{
build_prototype_graph_report, unit_component_tree, PrototypeGraph, PrototypeGraphFailure,
@@ -210,10 +211,23 @@ pub struct EffectiveControlDevice {
pub descriptor_provenance: ControlDeviceRecordProvenance,
}
/// Initial Control metadata projected from one node in AniMesh's global table.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MissionControlNodeInitialMeshState {
/// Parent index in AniMesh's concatenated runtime-node table.
pub parent_index: i32,
/// Node38 header bits translated to the Control row's `+0x28` flags.
pub flags: u32,
/// Effective state count; an empty native state prefix is exposed as one.
pub stage_count: u32,
}
/// Initial row in the loaded global Control node-data provider.
///
/// The native table is indexed independently of MSH model nodes. Its rows are
/// appended in root/EXTO resource order and begin with a type-1 value of 1.0.
/// Mesh metadata uses the global row ordinal; `None` records that the matching
/// MSH projection was unavailable and does not affect provider queries.
#[derive(Clone, Debug, PartialEq)]
pub struct MissionControlNodeProviderRow {
/// NDP resource that contributed the row.
@@ -226,6 +240,8 @@ pub struct MissionControlNodeProviderRow {
pub source_row: PreparedControlNodeDataRow,
/// Initial native provider selector-1 value (`+0x14`) as raw bits.
pub initial_type1_value_bits: u32,
/// MSH state exposed at the same global ordinal, if the mesh projection exists.
pub initial_mesh_state: Option<MissionControlNodeInitialMeshState>,
}
/// Availability of the initial global Control node-data provider projection.
@@ -3256,6 +3272,57 @@ fn build_control_device_projection(
}
}
let mut global_mesh_states = Vec::new();
let mut global_node_cursor = 0_usize;
for component_index in active_components.iter().copied() {
let prototype =
prototype_for(component_index).ok_or(Unavailable::ComponentAlignmentMismatch)?;
let is_root = component_index == 0;
let is_ex_to = !is_root && prototype.source_type == Some(PROTOTYPE_TYPE_EXTO);
if !is_root && !is_ex_to {
continue;
}
let visual = object_visuals
.get(component_index)
.and_then(|visual_id| assets.visual_by_id(*visual_id));
let node_count = visual.map_or(0, |visual| visual.model_nodes);
let model = visual
.and_then(|visual| visual.model_id)
.and_then(|model_id| assets.model_by_id(model_id));
let parent_base = if is_ex_to {
i32::try_from(global_node_cursor)
.ok()
.and_then(|count| count.checked_sub(1))
.ok_or(Unavailable::UnsupportedExToNodeMapping {
unit_component_index: component_index,
})?
} else {
0
};
let mount_node = if is_root {
Some(0)
} else {
native_component_mount_node(
&tree,
&component_ids,
&first_global_nodes,
component_index,
draft.unit_components[component_index].parent_or_link,
)
};
let first_source_node = usize::from(is_ex_to);
for source_node_index in first_source_node..node_count {
global_mesh_states.push(model.and_then(|model| {
initial_control_mesh_state(model, source_node_index, parent_base, mount_node)
}));
}
let contribution = node_count.saturating_sub(first_source_node);
global_node_cursor = global_node_cursor
.checked_add(contribution)
.ok_or(Unavailable::ComponentAlignmentMismatch)?;
}
let mut devices = Vec::new();
let mut node_provider_status = MissionControlNodeProviderTableStatus::Available(Vec::new());
let mut has_control_resource = false;
@@ -3412,6 +3479,9 @@ fn build_control_device_projection(
if !has_control_resource {
return Err(Unavailable::NoControlResource);
}
if let MissionControlNodeProviderTableStatus::Available(rows) = &mut node_provider_status {
attach_initial_mesh_states_by_global_ordinal(rows, &global_mesh_states);
}
Ok(ControlDeviceProjection {
devices,
node_provider_status,
@@ -3453,10 +3523,74 @@ fn append_control_node_provider_rows(
source_row_index,
source_row: source_row.clone(),
initial_type1_value_bits: 0x3f80_0000,
initial_mesh_state: None,
});
}
}
fn control_flags_from_node38_header(header_flags: u16) -> u32 {
let mut flags = 0;
if header_flags & 0x0200 != 0 {
flags |= 0x01;
}
if header_flags & 0x0100 != 0 {
flags |= 0x02;
}
if header_flags & 0x0400 != 0 {
flags |= 0x04;
}
if header_flags & 0x0001 != 0 && header_flags & 0x0080 == 0 {
flags |= 0x08;
}
flags
}
fn native_mesh_parent_index(
parent_or_link_raw: u16,
parent_base: i32,
mount_node: Option<u32>,
) -> Option<i32> {
if parent_or_link_raw == 0 {
i32::try_from(mount_node?).ok()
} else {
let relative_parent = if parent_or_link_raw == u16::MAX {
-1
} else {
i32::from(parent_or_link_raw)
};
parent_base.checked_add(relative_parent)
}
}
fn initial_control_mesh_state(
model: &fparkan_assets::PreparedModel,
source_node_index: usize,
parent_base: i32,
mount_node: Option<u32>,
) -> Option<MissionControlNodeInitialMeshState> {
let node_index = u32::try_from(source_node_index).ok()?;
let node = node38_metadata(&model.validated, NodeId(node_index))?;
let stage_prefix = (0..3_u8)
.take_while(|state| {
selected_slot(&model.validated, NodeId(node_index), Lod(*state), Group(0)).is_some()
})
.count();
Some(MissionControlNodeInitialMeshState {
parent_index: native_mesh_parent_index(node.parent_or_link_raw, parent_base, mount_node)?,
flags: control_flags_from_node38_header(node.header_flags),
stage_count: u32::try_from(stage_prefix.max(1)).ok()?,
})
}
fn attach_initial_mesh_states_by_global_ordinal(
provider_rows: &mut [MissionControlNodeProviderRow],
global_mesh_states: &[Option<MissionControlNodeInitialMeshState>],
) {
for (ordinal, row) in provider_rows.iter_mut().enumerate() {
row.initial_mesh_state = global_mesh_states.get(ordinal).copied().flatten();
}
}
fn add_behavior_registered_object(
distributor: &mut BehaviorDistributorState,
mut object: BehaviorRegisteredObject,
@@ -3949,9 +4083,76 @@ mod tests {
},
},
initial_type1_value_bits,
initial_mesh_state: None,
}
}
fn synthetic_node38(
header_flags: u16,
parent_or_link: u16,
group0_states: [bool; 3],
) -> [u8; 38] {
let mut node = [0xff; 38];
node[0..2].copy_from_slice(&header_flags.to_le_bytes());
node[2..4].copy_from_slice(&parent_or_link.to_le_bytes());
node[4..6].copy_from_slice(&u16::MAX.to_le_bytes());
node[6..8].copy_from_slice(&0_u16.to_le_bytes());
for (state, present) in group0_states.into_iter().enumerate() {
let slot = if present { 0_u16 } else { u16::MAX };
let offset = 8 + state * 10;
node[offset..offset + 2].copy_from_slice(&slot.to_le_bytes());
}
node
}
fn synthetic_model_asset(nodes: &[[u8; 38]]) -> fparkan_msh::ModelAsset {
let mut nodes_raw = Vec::with_capacity(nodes.len() * 38);
for node in nodes {
nodes_raw.extend_from_slice(node);
}
fparkan_msh::ModelAsset {
node_stride: 38,
node_count: nodes.len(),
nodes_raw,
bounding_sphere_center: [0.0; 3],
bounding_sphere_radius: 0.0,
slots: vec![fparkan_msh::Slot {
tri_start: 0,
tri_count: 0,
batch_start: 0,
batch_count: 0,
aabb_min: [0.0; 3],
aabb_max: [0.0; 3],
sphere_center: [0.0; 3],
sphere_radius: 0.0,
opaque: [0; 5],
}],
positions: Vec::new(),
normals: None,
uv0: None,
uv1: None,
indices: Vec::new(),
batches: Vec::new(),
node_names: None,
animation: None,
}
}
fn attach_synthetic_model(
assets: &mut MissionAssets,
component_index: usize,
nodes: &[[u8; 38]],
) {
let model_id = AssetId::<fparkan_assets::PreparedModel>::new(100 + component_index as u64);
assets.visuals[component_index].model_id = Some(model_id);
assets.models.push(fparkan_assets::PreparedModel {
id: model_id,
source: synthetic_resource_key(500 + component_index),
validated: synthetic_model_asset(nodes),
mesh_dependencies: Vec::new(),
});
}
fn synthetic_control_fixture(
source_types: &[Option<u32>],
kinds: &[u32],
@@ -5214,6 +5415,134 @@ mod tests {
);
}
#[test]
fn synthetic_node_provider_projection_joins_flat_mesh_metadata_by_global_ordinal() {
let controls = vec![
Some(control_with_synthetic_node_data(0, Vec::new(), 3)),
Some(control_with_synthetic_node_data(1, Vec::new(), 3)),
];
let (draft, mut assets, prototypes) = synthetic_control_fixture(
// Even if the root's registry prototype is typed EXTO, its model
// contributes every source node; only mounted EXTO rows skip node 0.
&[Some(PROTOTYPE_TYPE_EXTO), Some(PROTOTYPE_TYPE_EXTO)],
&[1, 1],
&[1, 0],
&[0, 1],
&[2, 3],
controls,
);
attach_synthetic_model(
&mut assets,
0,
&[
synthetic_node38(0x0701, 0xffff, [true, true, false]),
synthetic_node38(0x0081, 0, [false, true, true]),
],
);
attach_synthetic_model(
&mut assets,
1,
&[
synthetic_node38(0, 0xffff, [true, false, false]),
synthetic_node38(0x0200, 0, [true, false, true]),
synthetic_node38(0x0400, 0xffff, [true, true, true]),
],
);
let projection = build_control_device_projection(
0,
&draft,
&assets,
Some(&(0..prototypes.len())),
&prototypes,
)
.expect("synthetic Control projection");
let MissionControlNodeProviderTableStatus::Available(rows) =
projection.node_provider_status
else {
panic!("synthetic provider rows should be available");
};
assert_eq!(rows.len(), 5);
assert_eq!(
rows.iter()
.map(|row| (row.unit_component_index, row.source_row_index))
.collect::<Vec<_>>(),
[(0, 0), (0, 1), (0, 2), (1, 1), (1, 2)]
);
assert_eq!(
rows.iter()
.map(|row| row.initial_mesh_state)
.collect::<Vec<_>>(),
[
Some(MissionControlNodeInitialMeshState {
parent_index: -1,
flags: 0x0f,
stage_count: 2,
}),
Some(MissionControlNodeInitialMeshState {
parent_index: 0,
flags: 0,
stage_count: 1,
}),
// This row is still from the root NDP. The native global
// ordinal has moved on to the first non-root EXTO mesh node.
Some(MissionControlNodeInitialMeshState {
parent_index: 1,
flags: 1,
stage_count: 1,
}),
Some(MissionControlNodeInitialMeshState {
parent_index: 0,
flags: 4,
stage_count: 3,
}),
None,
]
);
assert!(rows[..4].iter().all(|row| row.initial_mesh_state.is_some()));
}
#[test]
fn missing_initial_mesh_metadata_keeps_provider_query_available() {
let mut device = synthetic_effective_control_device(
26,
26,
2.0_f32.to_bits(),
Some(3.0_f32.to_bits()),
None,
);
device.key = 0;
device.descriptor.fixed_words[1] = 0;
let provider = synthetic_node_provider_row(0, 0, 2.0_f32.to_bits());
assert_eq!(provider.initial_mesh_state, None);
let table = synthetic_control_device_table_with_providers(
MissionControlDeviceTableStatus::Available(vec![device]),
MissionControlNodeProviderTableStatus::Available(vec![provider]),
);
assert_eq!(
query_control_device_table_selector(&table, 0, 0xe00)
.expect("NDP query remains independent of the MSH projection"),
Some(12.0)
);
}
#[test]
fn native_mesh_metadata_maps_control_flags_and_parent_words() {
assert_eq!(control_flags_from_node38_header(0x0701), 0x0f);
assert_eq!(control_flags_from_node38_header(0x0781), 0x07);
assert_eq!(native_mesh_parent_index(0xffff, 0, None), Some(-1));
assert_eq!(native_mesh_parent_index(0, 0, Some(0)), Some(0));
assert_eq!(native_mesh_parent_index(0xffff, 21, None), Some(20));
assert_eq!(native_mesh_parent_index(1, 21, None), Some(22));
assert_eq!(native_mesh_parent_index(0xfffe, 21, None), Some(65_555));
assert_eq!(native_mesh_parent_index(0x8000, 21, None), Some(32_789));
assert_eq!(native_mesh_parent_index(0, 21, Some(7)), Some(7));
assert_eq!(native_mesh_parent_index(0, 21, None), None);
}
#[test]
fn missing_node_provider_does_not_hide_aggregate_queries() {
let controls = vec![Some(synthetic_component_control(
@@ -5767,6 +6096,118 @@ mod tests {
assert_eq!(root_node_data.rows.len(), 22);
assert_eq!(ext_node_data.rows.len(), 4);
assert_eq!(provider_rows.len(), 25);
let mission_assets = &engine
.loaded
.as_ref()
.expect("loaded mission state")
.mission_assets;
let visual_root_node_count = mission_assets
.visual_by_id(mission_assets.object_visuals[0][0])
.expect("root visual")
.model_nodes;
assert_eq!(visual_root_node_count, 22);
let assert_mesh_node =
|component_index: usize,
source_node_index: usize,
expected_header: u16,
expected_parent: u16,
expected_slots: [u16; 15],
expected_state: MissionControlNodeInitialMeshState| {
let visual_id = mission_assets.object_visuals[0][component_index];
let visual = mission_assets
.visual_by_id(visual_id)
.expect("component visual");
let model = mission_assets
.model_by_id(visual.model_id.expect("component model"))
.expect("prepared model");
let offset = source_node_index * model.validated.node_stride;
let raw_flags = u16::from_le_bytes(
model.validated.nodes_raw[offset..offset + 2]
.try_into()
.expect("raw header flags"),
);
let raw_parent = u16::from_le_bytes(
model.validated.nodes_raw[offset + 2..offset + 4]
.try_into()
.expect("raw parent"),
);
let raw_slots = std::array::from_fn::<_, 15, _>(|slot| {
u16::from_le_bytes(
model.validated.nodes_raw[offset + 8 + slot * 2..offset + 10 + slot * 2]
.try_into()
.expect("raw slot word"),
)
});
let global_index = if component_index == 0 {
source_node_index
} else {
visual_root_node_count + source_node_index - 1
};
assert_eq!(raw_flags, expected_header);
assert_eq!(raw_parent, expected_parent);
assert_eq!(raw_slots, expected_slots);
assert_eq!(
provider_rows[global_index].initial_mesh_state,
Some(expected_state)
);
};
assert_mesh_node(
0,
0,
0x0000,
0xffff,
[0xffff; 15],
MissionControlNodeInitialMeshState {
parent_index: -1,
flags: 0,
stage_count: 1,
},
);
assert_mesh_node(
0,
1,
0x0110,
0x0000,
[
0x000b, 0x0025, 0x0026, 0xffff, 0xffff, 0x0013, 0x0027, 0x0028, 0xffff, 0xffff,
0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
],
MissionControlNodeInitialMeshState {
parent_index: 0,
flags: 2,
stage_count: 2,
},
);
assert_mesh_node(
5,
1,
0x0000,
0x0000,
[
0x0000, 0x0001, 0x0002, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
],
MissionControlNodeInitialMeshState {
parent_index: 9,
flags: 0,
stage_count: 1,
},
);
assert_mesh_node(
5,
2,
0x0010,
0x0001,
[
0x0004, 0x0007, 0x0008, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
],
MissionControlNodeInitialMeshState {
parent_index: 22,
flags: 0,
stage_count: 1,
},
);
let expected_provider_sources = (0..root_node_data.rows.len())
.map(|row| (0, row))
.chain((1..ext_node_data.rows.len()).map(|row| (5, row)))
@@ -5781,6 +6222,9 @@ mod tests {
assert!(provider_rows
.iter()
.all(|row| row.initial_type1_value_bits == 1.0_f32.to_bits()));
assert!(provider_rows
.iter()
.all(|row| row.initial_mesh_state.is_some()));
assert_eq!(
(
entries[9].factory_tag,
@@ -5,7 +5,7 @@ using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
// Calls selected original x86 Behavior.dll, ArealMap.dll, and Control.dll paths
// Calls selected original x86 Behavior.dll, ArealMap.dll, AniMesh.dll, and Control.dll paths
// against synthetic storage. Only host callbacks, GetSystemArealMap/GetQueue IAT
// slots, and bounded vector backing are substituted; tested module code remains installed.
internal static class BehaviorDistributorTickOracle {
@@ -17,6 +17,7 @@ internal static class BehaviorDistributorTickOracle {
private const string ExpectedBehaviorSha256 = "ddfbdbde07832358fe6e35e01c8dba9b58e7313789498b6049ed51d4ed9baf99";
private const string ExpectedControlSha256 = "bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e";
private const string ExpectedArealMapSha256 = "a25f9254ebb339d70e2e07c8121950191e9584ca0858d8e9c2e2b6c671edf6ea";
private const string ExpectedAniMeshSha256 = "65659bf67f20e5be77d67a5b2f59968f61b94293143807fa59ca451c560c4f7e";
private const int TickRva = 0x19e80;
private const int DistributorScheduleRva = 0x1adb0;
private const int AddObjectRva = 0x1aac0;
@@ -40,6 +41,8 @@ internal static class BehaviorDistributorTickOracle {
private const int ControlContactRateUpdateRva = 0x12a40;
private const int ControlTimedUpdateRva = 0x0bcf0;
private const int ArealMapUnitDatComponentBuilderRva = 0x14b90;
private const int AniMeshNodeMetadataQueryRva = 0x051f0;
private const int AniMeshNodeStageCountRva = 0x05840;
private const int ControlResourceDeviceConstructorRva = 0x22980;
private const int ControlResourceComponentOverrideRva = 0x2d890;
private const int ControlResourceCommonSetterRva = 0x21d50;
@@ -99,6 +102,8 @@ internal static class BehaviorDistributorTickOracle {
[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate float NativeControlResourceDeviceGet(IntPtr self, uint selector);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void NativeFastcallComponentBuilder(IntPtr owner, IntPtr node, uint parentId);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int NativeArealMapEvent(IntPtr owner, uint message, uint subcode, IntPtr descriptor);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int NativeAniMeshNodeMetadataQuery(IntPtr owner, uint nodeIndex, uint selector, IntPtr result);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint NativeAniMeshNodeStageCount(IntPtr owner, uint nodeIndex);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate IntPtr NativeControlResourceDeviceConstructor(IntPtr self);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate IntPtr NativeControlResourceComponentOverride(IntPtr self, int deviceIndex, IntPtr typedRecord);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int NativeControlAggregateQuery(IntPtr self, uint selector, IntPtr result);
@@ -522,6 +527,11 @@ internal static class BehaviorDistributorTickOracle {
if (!File.Exists(arealMapPath)) { Console.Error.WriteLine("Set FPARKAN_ORIGINAL_AREALMAP_DLL to the installed ArealMap.dll."); return 10; }
string arealMapHash = Hash(arealMapPath);
if (arealMapHash != ExpectedArealMapSha256) { Console.Error.WriteLine("Unexpected ArealMap.dll SHA-256: " + arealMapHash); return 11; }
string aniMeshPath = Environment.GetEnvironmentVariable("FPARKAN_ORIGINAL_ANIMESH_DLL");
if (String.IsNullOrEmpty(aniMeshPath)) aniMeshPath = @"C:\GOG Games\Parkan - Iron Strategy\AniMesh.dll";
if (!File.Exists(aniMeshPath)) { Console.Error.WriteLine("Set FPARKAN_ORIGINAL_ANIMESH_DLL to the installed AniMesh.dll."); return 13; }
string aniMeshHash = Hash(aniMeshPath);
if (aniMeshHash != ExpectedAniMeshSha256) { Console.Error.WriteLine("Unexpected AniMesh.dll SHA-256: " + aniMeshHash); return 14; }
IntPtr controlModule = LoadLibraryEx(controlPath, IntPtr.Zero, LoadWithAlteredSearchPath);
if (controlModule == IntPtr.Zero) { Console.Error.WriteLine("LoadLibraryEx(Control.dll) failed: " + Marshal.GetLastWin32Error()); return 9; }
string path = Environment.GetEnvironmentVariable("FPARKAN_ORIGINAL_BEHAVIOR_DLL");
@@ -536,6 +546,11 @@ internal static class BehaviorDistributorTickOracle {
Console.Error.WriteLine("LoadLibraryEx(ArealMap.dll) failed: " + Marshal.GetLastWin32Error());
FreeLibrary(module); FreeLibrary(controlModule); return 12;
}
IntPtr aniMeshModule = LoadLibraryEx(aniMeshPath, IntPtr.Zero, LoadWithAlteredSearchPath);
if (aniMeshModule == IntPtr.Zero) {
Console.Error.WriteLine("LoadLibraryEx(AniMesh.dll) failed: " + Marshal.GetLastWin32Error());
FreeLibrary(arealMapModule); FreeLibrary(module); FreeLibrary(controlModule); return 15;
}
IntPtr import = IntPtr.Add(module, GetSystemArealMapIatRva);
IntPtr queueImport = IntPtr.Add(module, GetQueueIatRva);
IntPtr originalImport = Marshal.ReadIntPtr(import);
@@ -560,7 +575,7 @@ internal static class BehaviorDistributorTickOracle {
protectionChanged = true;
Marshal.WriteIntPtr(import, Marshal.GetFunctionPointerForDelegate(AreaMapGetterCallback));
Marshal.WriteIntPtr(queueImport, Marshal.GetFunctionPointerForDelegate(QueueGetterCallback));
RunSmokeCases(module, controlModule, arealMapModule);
RunSmokeCases(module, controlModule, arealMapModule, aniMeshModule);
Console.WriteLine("original native Behavior/ArealMap/Control oracle passed (Behavior Add 0x1aac0, normalize 0x1ac90, scheduler 0x1adb0, tick 0x19e80; ArealMap UnitDAT projection 0x14b90; Control INTO override 0x2d890, provider distribution 0x10ba0, class-4 update 0x12a40 and inactive timing baseline 0xbcf0; synthetic host callbacks, GetSystemArealMap/GetQueue IAT slots, and bounded vector insertion are substituted; Control provider selector vtable is original; no full Control update or Rust parity is claimed).");
return 0;
}
@@ -587,12 +602,13 @@ internal static class BehaviorDistributorTickOracle {
throw new InvalidOperationException("VirtualFree(fastcall callback thunks) failed: " + Marshal.GetLastWin32Error());
if (x87ControlWordCell != IntPtr.Zero) { Marshal.FreeHGlobal(x87ControlWordCell); x87ControlWordCell = IntPtr.Zero; }
FreeLibrary(arealMapModule);
FreeLibrary(aniMeshModule);
FreeLibrary(module);
FreeLibrary(controlModule);
}
}
private static void RunSmokeCases(IntPtr module, IntPtr controlModule, IntPtr arealMapModule) {
private static void RunSmokeCases(IntPtr module, IntPtr controlModule, IntPtr arealMapModule, IntPtr aniMeshModule) {
ushort savedControlWord = CurrentX87ControlWord();
Console.WriteLine("x87-control-word-before=0x" + savedControlWord.ToString("x4") + " (x86 oracle process)");
try {
@@ -601,6 +617,7 @@ internal static class BehaviorDistributorTickOracle {
RunNativeAddCases(module);
RunNativeNormalizeCases(module);
RunNativeArealMapComponentBuilderCase(arealMapModule);
RunNativeAniMeshNodeMetadataCases(aniMeshModule);
RunNativeControlIntoOverrideCase(controlModule);
RunNativeControlResourceDeviceCase(controlModule);
RunNativeControlProviderLiveStateCase(controlModule);
@@ -1219,6 +1236,86 @@ internal static class BehaviorDistributorTickOracle {
}
}
private static void RunNativeAniMeshNodeMetadataCases(IntPtr module) {
NativeAniMeshNodeMetadataQuery query = (NativeAniMeshNodeMetadataQuery)Marshal.GetDelegateForFunctionPointer(
IntPtr.Add(module, AniMeshNodeMetadataQueryRva), typeof(NativeAniMeshNodeMetadataQuery));
NativeAniMeshNodeStageCount stageCount = (NativeAniMeshNodeStageCount)Marshal.GetDelegateForFunctionPointer(
IntPtr.Add(module, AniMeshNodeStageCountRva), typeof(NativeAniMeshNodeStageCount));
using (Fixture fixture = new Fixture()) {
IntPtr owner = fixture.Allocate(0x1b0);
IntPtr meshRows = fixture.Allocate(3 * 0x130);
IntPtr nodeData = fixture.Allocate(3 * 0x26);
IntPtr slotData = fixture.Allocate(3 * 0x44);
IntPtr meshData = fixture.Allocate(3 * IntPtr.Size);
IntPtr result = fixture.Allocate(IntPtr.Size);
Marshal.WriteIntPtr(meshData, 0, nodeData);
Marshal.WriteIntPtr(meshData, 2 * IntPtr.Size, slotData);
Marshal.WriteIntPtr(owner, 0x1a8, meshRows);
Marshal.WriteInt32(owner, 0x1ac, 3);
ushort[] headerFlags = new ushort[] { 0x8201, 0x0180, 0x0400 };
int[] rawParentIndices = new int[] { 3, 0, 1 };
int[] runtimeParentIndices = new int[] { -1, 22, 7 };
for (int nodeIndex = 0; nodeIndex < 3; nodeIndex++) {
IntPtr rawNode = IntPtr.Add(nodeData, nodeIndex * 0x26);
for (int word = 0; word < 19; word++) Marshal.WriteInt16(rawNode, word * 2, -1);
Marshal.WriteInt16(rawNode, 0, unchecked((short)headerFlags[nodeIndex]));
Marshal.WriteInt16(rawNode, 2, unchecked((short)rawParentIndices[nodeIndex]));
IntPtr meshRow = IntPtr.Add(meshRows, nodeIndex * 0x130);
Marshal.WriteInt32(meshRow, 8, nodeIndex);
Marshal.WriteInt32(meshRow, 0x18, runtimeParentIndices[nodeIndex]);
Marshal.WriteIntPtr(meshRow, 0x12c, meshData);
}
// Node 0: state0 present, state1 absent, state2 present. Native
// GetStateCount stops at the first missing state, so it returns 1.
WriteNode38Slot(nodeData, 0, 0, 0);
WriteNode38Slot(nodeData, 0, 2, 2);
// Node 1: the prefix is empty even though later states are present.
WriteNode38Slot(nodeData, 1, 1, 1);
WriteNode38Slot(nodeData, 1, 2, 2);
// Node 2: all three consecutive state slots are present.
WriteNode38Slot(nodeData, 2, 0, 0);
WriteNode38Slot(nodeData, 2, 1, 1);
WriteNode38Slot(nodeData, 2, 2, 2);
for (uint nodeIndex = 0; nodeIndex < 3; nodeIndex++) {
Marshal.WriteIntPtr(result, IntPtr.Zero);
Expect(NativeBoolean(query(owner, nodeIndex, 0x0d, result)) == 1,
"AniMesh selector D returns runtime parent metadata");
IntPtr parent = Marshal.ReadIntPtr(result);
Expect(runtimeParentIndices[nodeIndex] != rawParentIndices[nodeIndex],
"AniMesh runtime parent fixture differs from the raw Node38 parent");
Expect(Marshal.ReadInt32(parent) == runtimeParentIndices[nodeIndex],
"AniMesh selector D copies the indexed global runtime parent, not the raw Node38 link");
Marshal.WriteIntPtr(result, IntPtr.Zero);
Expect(NativeBoolean(query(owner, nodeIndex, 0x0e, result)) == 1,
"AniMesh selector E returns the Node38 header word");
IntPtr flags = Marshal.ReadIntPtr(result);
Expect(unchecked((uint)Marshal.ReadInt32(flags)) == headerFlags[nodeIndex],
"AniMesh selector E points to the indexed Node38 hdr0");
}
uint[] expectedStageCounts = new uint[] { 1, 0, 3 };
for (uint nodeIndex = 0; nodeIndex < expectedStageCounts.Length; nodeIndex++) {
Expect(stageCount(owner, nodeIndex) == expectedStageCounts[nodeIndex],
"AniMesh stage count is the consecutive state0-2 prefix");
}
Console.WriteLine("native-anim-mesh-control-node-metadata: aniMeshHash=" + ExpectedAniMeshSha256 +
" D=runtime-parent E=Node38-hdr0 stage-prefix=[1,0,3]");
}
GC.KeepAlive(query);
GC.KeepAlive(stageCount);
}
private static void WriteNode38Slot(IntPtr nodeData, int nodeIndex, int state, ushort slotIndex) {
int wordIndex = nodeIndex * 19 + 4 + state * 5;
Marshal.WriteInt16(nodeData, wordIndex * 2, unchecked((short)slotIndex));
}
private static void RunNativeControlIntoOverrideCase(IntPtr module) {
NativeControlResourceComponentOverride applyOverride = (NativeControlResourceComponentOverride)Marshal.GetDelegateForFunctionPointer(
IntPtr.Add(module, ControlResourceComponentOverrideRva), typeof(NativeControlResourceComponentOverride));
+8
View File
@@ -323,6 +323,14 @@ sequence определяется NDP: она не дополняется по
sidecar недоступен, запрос `0xe00` сообщает это отдельно, оставляя независимые
агрегатные selectors `1/2` доступными.
Поля `parent_index`, Control flags и начальный stage count для NDP-строк
проецируются из AniMesh по глобальному ordinal; точные правила, native ABI
векторы и лицензированная root/`EXTO` fixture описаны в
[техническом подразделе](script-vm.md#начальная-msh-часть-строки-provider).
Проверки подтверждают только начальный снимок: сборка runtime parent-ов
остаётся статическим выводом по RVA `AniMesh.dll+0xa460`, а последующие
изменения в полном Control/animation tick-е не проверялись.
Rust query обращается к загруженному объекту и поддерживает `0xe00` только для
текущего descriptor tag `26` с factory tag `26`; другие активные typed tags и
factory paths остаются явными границами. Этот запрос возвращает начальный
+69
View File
@@ -644,6 +644,75 @@ oracle вызывает оригинальные `FUN_10010ba0` (RVA `0x10ba0`),
вызовов в игре не установлены; эти связи остаются статическим выводом. Rust
продолжает читать начальные provider snapshots и не моделирует эти изменения.
### Начальная MSH-часть строки provider
`AniMesh.dll` (SHA-256
`65659bf67f20e5be77d67a5b2f59968f61b94293143807fa59ca451c560c4f7e`)
строит глобальную MSH-таблицу в `FUN_1000a460` (RVA `0xa460`). Для каждого
узла корневой модели добавляется его исходная запись; mounted `EXTO` начинает
с узла `1`; `INTO` в эту таблицу не добавляет. При чтении Node38 поле
`parent_or_link` — это беззнаковое `u16` из байтов `+2`, а не готовый индекс
глобальной таблицы.
Статические инструкции `0xa474..0xa49f` дают основу родительского индекса.
Для корня база равна нулю; для `EXTO` она равна старому размеру глобальной
таблицы минус один. Само значение трактуется так:
```text
raw == 0 -> mount_node
raw == 0xffff -> parent_base - 1
иначе -> parent_base + u32(raw)
```
Только `0xffff` служит sentinel-ом: остальные слова, включая `0xfffe`,
прибавляются как беззнаковые `u16`. Для примонтированного `EXTO` с базой `21`
слово `1` даёт parent `22`, а `0xffff` даёт `20`. `mount_node` выбирается из
уже построенной иерархии компонентов. Эта формула восстановлена по машинным
инструкциям загрузчика: `ADD EDI,EAX` в RVA `0xa7e3` прибавляет нормализованное
значение к базе перед записью parent по `0xa7e7`. Это не исполнение полного
загрузочного пути оригинальной игры.
`Control.dll` (SHA-256
`bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e`)
`FUN_1000f940` (RVA `0xf940`) получает три поля из AniMesh для того же
глобального ordinal. В x86 ABI oracle оригинального `AniMesh.dll`
`FUN_100051f0` (RVA `0x51f0`) с selector `0x0d` копирует runtime parent из
строки `+0x18` в общий scratch `DAT_10025e88` и возвращает адрес этой копии;
selector `0x0e` так же возвращает копию hdr0 Node38, а не адрес исходной записи.
Тест устанавливает raw parent words `[3, 0, 1]`, но runtime parents `[-1, 22, 7]`,
и проверяет, что selector D читает именно последние. hdr0 `[0x8201, 0x0180,
0x0400]` читается через полный 32-битный результат, поэтому старшие биты не
теряются.
Control переводит проверенные маски hdr0 в поле строки `+0x28`:
| Node38 hdr0 | Control bit |
| --- | --- |
| `hdr0 & 0x0200` | `0x01` |
| `hdr0 & 0x0100` | `0x02` |
| `hdr0 & 0x0400` | `0x04` |
| `(hdr0 & 1) != 0 && (hdr0 & 0x0080) == 0` | `0x08` |
`FUN_10005840` (RVA `0x5840`) возвращает число подряд присутствующих slots
состояний `0..2`: `[present, absent, present] -> 1`,
`[absent, present, present] -> 0`, `[present, present, present] -> 3`.
Пустой префикс в начальной строке Control становится одной доступной стадией,
поэтому Rust хранит `max(1, prefix_length)`. Slot проверяется через штатный
`selected_slot` с `Group(0)` (native LOD0), а не подсчётом всех ненулевых words.
Runtime временно собирает mesh-состояния в порядке AniMesh, затем сопоставляет
их с уже упорядоченными NDP provider-строками по общему ordinal. Избыточная NDP
строка или отсутствующий MSH asset получают `initial_mesh_state = None`;
совпадение по `(component_index, source_row_index)` не выполняется. Состояние
также не меняет существующий `0xe00` query: он читает начальное type-1 поле
`+0x14` provider-строки, равное `1.0` после нативного конструктора.
Native-часть этих ABI проверок воспроизводит
`behavior_distributor_tick_native_oracle.cs` на синтетически выделенной памяти
и оригинальном DLL с указанным SHA. Она подтверждает getters и layout, но не
создание реальных AniMesh rows при полной загрузке; licensed runtime test
отдельно проверяет реальные Node38 literals root/`EXTO` на `min_l_n1.dat`.
### Аргументы и обратный вызов Handler(30)
`resolve_handler30_with_values` сохраняет восстановленное ABI типов объявлений,
+23
View File
@@ -859,6 +859,29 @@ tag-26 ряда получается `1.0` provider × `1.0` coefficient × `1.0
`1.0`. Эти запросы используют начальные provider-значения после конструкторов,
а не результаты живого игрового тика.
У Control есть и начальные сведения о модели узла, но их таблица не совпадает
с NDP. Sidecar задаёт состав и порядок provider-строк, а поле type-1 `+0x14`
получает начальное значение `1.0` от нативного конструктора. AniMesh отдельно
собирает глобальный список MSH-узлов. При создании строки Control берёт
mesh-состояние по её порядковому номеру в общей таблице provider, а не пытается
угадать пару по локальному номеру строки sidecar-а. Например, после 22
корневых строк номер 22 указывает на первый глобальный узел присоединённой
`EXTO`-модели, который
происходит из её локального узла `1`.
В снимке это необязательное поле: `None` означает, что для данного номера не
удалось получить MSH-узел; исходные запросы к NDP от этого не исчезают. Поэтому
начальное значение и поза модели остаются отдельными частями состояния:
```rust
initial_mesh_state: Option<MissionControlNodeInitialMeshState>
```
Внутри снимка хранятся родительский индекс, переведённые флаги Control и число
начальных стадий. Узлы корневой модели добавляются все, а присоединённая `EXTO`
начинает с локального узла `1`. Это описывает исходную настройку: код пока не
переключает стадии в ходе игры и не исполняет полный Control tick.
После загрузки количество в строках может меняться. Контроллер распределяет
добавку либо пропорционально свободному месту, либо по очереди: при максимумах
`[30, 60, 50]`, текущих значениях `[10, 20, 0]` и добавке `22` первый способ