feat(runtime): recompute loaded Control owner profiles
Docs Deploy / Build and Deploy MkDocs (push) Successful in 1m5s
Docs Deploy / Build and Deploy MkDocs (push) Successful in 1m5s
This commit is contained in:
5 files changed
+1145
-109
No files matched your search
@@ -517,6 +517,9 @@ pub struct MissionControlOwnerProfile {
|
||||
MissionControlOwnerProfileLoadProjection,
|
||||
MissionControlOwnerProfileLoadProjectionUnavailableReason,
|
||||
>,
|
||||
/// FCA0 status after FAC0, recorded separately from the FAC0 result.
|
||||
/// Native class 9 returns `Ok(())` without changing the prepared copy.
|
||||
pub fca0_projection: Result<(), MissionControlOwnerProfileFca0UnavailableReason>,
|
||||
}
|
||||
|
||||
/// Initial Control FAC0 load-time values for one owner profile.
|
||||
@@ -547,6 +550,20 @@ pub enum MissionControlOwnerProfileLoadProjectionUnavailableReason {
|
||||
MissingProfileCacheOnInto,
|
||||
}
|
||||
|
||||
/// Why the initial Control FCA0 profile projection is unavailable.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum MissionControlOwnerProfileFca0UnavailableReason {
|
||||
/// Rust could not project the native Control class for this owner.
|
||||
MissingNativeControlClass,
|
||||
/// A non-class-9 FCA0 route requires a completed FAC0 result; class 9
|
||||
/// returns before this result is inspected.
|
||||
Fac0Unavailable(MissionControlOwnerProfileLoadProjectionUnavailableReason),
|
||||
/// The original current-tag E00 query failed with a typed reason.
|
||||
QueryUnavailable(Arc<ControlResourceAccessError>),
|
||||
/// An input or intermediate float is outside the supported domain.
|
||||
UnsupportedFloat { field: &'static str },
|
||||
}
|
||||
|
||||
struct ControlDeviceProjection {
|
||||
devices: Vec<EffectiveControlDevice>,
|
||||
owner_profile: Option<MissionControlOwnerProfile>,
|
||||
@@ -1592,12 +1609,13 @@ fn load_mission_with_options(
|
||||
prototype_span,
|
||||
&resolved_prototypes,
|
||||
);
|
||||
let projection = build_control_device_projection(
|
||||
let projection = build_control_device_projection_with_class(
|
||||
object_index,
|
||||
draft,
|
||||
&mission_assets,
|
||||
prototype_span,
|
||||
&resolved_prototypes,
|
||||
native_control_class,
|
||||
);
|
||||
match projection {
|
||||
Ok(projection) => MissionControlDeviceTableState {
|
||||
@@ -2068,10 +2086,13 @@ pub fn query_loaded_mission_control_resource(
|
||||
|
||||
/// 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 query reads the current provider, coefficient, and
|
||||
/// multiplier in the CPU projection. Explicit Control update calls can change
|
||||
/// those values; the mission clock does not advance them automatically.
|
||||
/// Selector `0xe00` is modeled for current descriptor tags 5 and 26 with
|
||||
/// factory tags 5 and 26. Both common factory readers use the device key to
|
||||
/// read the current provider value and multiply it by coefficient 0. Only
|
||||
/// current tag 26 also multiplies by `M`; current tag 5 ignores `M` and
|
||||
/// descriptor word 8 for this selector. Explicit Control update calls can
|
||||
/// change current provider or multiplier values; the mission clock does not
|
||||
/// advance them automatically.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error for an invalid handle, unavailable mission/table/provider,
|
||||
@@ -2764,7 +2785,14 @@ fn control_node_provider_row(
|
||||
table: &MissionControlDeviceTableState,
|
||||
key: u32,
|
||||
) -> Result<&MissionControlNodeProviderRow, ControlResourceAccessError> {
|
||||
let rows = match &table.node_provider_status {
|
||||
control_node_provider_row_from_status(&table.node_provider_status, key)
|
||||
}
|
||||
|
||||
fn control_node_provider_row_from_status(
|
||||
status: &MissionControlNodeProviderTableStatus,
|
||||
key: u32,
|
||||
) -> Result<&MissionControlNodeProviderRow, ControlResourceAccessError> {
|
||||
let rows = match status {
|
||||
MissionControlNodeProviderTableStatus::Available(rows) => rows,
|
||||
MissionControlNodeProviderTableStatus::Unavailable(reason) => {
|
||||
return Err(ControlResourceAccessError::NodeProviderTableUnavailable(
|
||||
@@ -3187,7 +3215,14 @@ fn control_device_provider_value(
|
||||
table: &MissionControlDeviceTableState,
|
||||
device: &EffectiveControlDevice,
|
||||
) -> Result<f32, ControlResourceAccessError> {
|
||||
let provider = control_node_provider_row(table, device.key)?;
|
||||
control_device_provider_value_from_status(&table.node_provider_status, device)
|
||||
}
|
||||
|
||||
fn control_device_provider_value_from_status(
|
||||
status: &MissionControlNodeProviderTableStatus,
|
||||
device: &EffectiveControlDevice,
|
||||
) -> Result<f32, ControlResourceAccessError> {
|
||||
let provider = control_node_provider_row_from_status(status, device.key)?;
|
||||
checked_control_float(
|
||||
device.factory_tag,
|
||||
"node provider value",
|
||||
@@ -4154,62 +4189,47 @@ fn query_control_device_table_selector(
|
||||
device_index,
|
||||
device_count: devices.len(),
|
||||
})?;
|
||||
query_control_device_selector(device, &table.node_provider_status)
|
||||
}
|
||||
|
||||
fn query_control_device_selector(
|
||||
device: &EffectiveControlDevice,
|
||||
provider_status: &MissionControlNodeProviderTableStatus,
|
||||
) -> Result<Option<f32>, ControlResourceAccessError> {
|
||||
match device.descriptor.tag {
|
||||
26 => {}
|
||||
5 | 10 | 21 => {
|
||||
5 | 26 => {}
|
||||
10 | 21 => {
|
||||
return Err(ControlResourceAccessError::UnsupportedCurrentTag {
|
||||
tag: device.descriptor.tag,
|
||||
});
|
||||
}
|
||||
_ => return Ok(None),
|
||||
}
|
||||
if device.factory_tag != 26 {
|
||||
if !matches!(device.factory_tag, 5 | 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.current_type1_value_bits),
|
||||
)?;
|
||||
let provider_value = control_device_provider_value_from_status(provider_status, device)?;
|
||||
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)
|
||||
if device.descriptor.tag == 26 {
|
||||
let multiplier = control_device_float(device, device.multiplier_bits, "multiplier")?;
|
||||
checked_control_product(
|
||||
device.factory_tag,
|
||||
"then multiplier",
|
||||
provider_weighted,
|
||||
multiplier,
|
||||
)
|
||||
.map(Some)
|
||||
} else {
|
||||
Ok(Some(provider_weighted))
|
||||
}
|
||||
}
|
||||
|
||||
fn set_control_device_table_selector(
|
||||
@@ -5029,6 +5049,155 @@ fn project_control_load_profile(
|
||||
})
|
||||
}
|
||||
|
||||
fn control_fca0_float(
|
||||
value: f32,
|
||||
field: &'static str,
|
||||
) -> Result<f32, MissionControlOwnerProfileFca0UnavailableReason> {
|
||||
checked_control_float(0, field, value)
|
||||
.map_err(|_| MissionControlOwnerProfileFca0UnavailableReason::UnsupportedFloat { field })
|
||||
}
|
||||
|
||||
fn control_fca0_product(
|
||||
lhs: f32,
|
||||
rhs: f32,
|
||||
field: &'static str,
|
||||
) -> Result<f32, MissionControlOwnerProfileFca0UnavailableReason> {
|
||||
checked_control_product(0, field, lhs, rhs)
|
||||
.map_err(|_| MissionControlOwnerProfileFca0UnavailableReason::UnsupportedFloat { field })
|
||||
}
|
||||
|
||||
fn control_fca0_sum(
|
||||
lhs: f32,
|
||||
rhs: f32,
|
||||
field: &'static str,
|
||||
) -> Result<f32, MissionControlOwnerProfileFca0UnavailableReason> {
|
||||
checked_control_sum(0, field, lhs, rhs)
|
||||
.map_err(|_| MissionControlOwnerProfileFca0UnavailableReason::UnsupportedFloat { field })
|
||||
}
|
||||
|
||||
fn control_fca0_ratio(
|
||||
numerator: f32,
|
||||
denominator: f32,
|
||||
field: &'static str,
|
||||
) -> Result<f32, MissionControlOwnerProfileFca0UnavailableReason> {
|
||||
checked_control_ratio(field, numerator, denominator)
|
||||
.map_err(|_| MissionControlOwnerProfileFca0UnavailableReason::UnsupportedFloat { field })
|
||||
}
|
||||
|
||||
fn control_fca0_clamp_to_profile_cap(
|
||||
value: f32,
|
||||
cap: f32,
|
||||
field: &'static str,
|
||||
) -> Result<f32, MissionControlOwnerProfileFca0UnavailableReason> {
|
||||
let value = control_fca0_float(value, field)?;
|
||||
let cap = control_fca0_float(cap, field)?;
|
||||
let magnitude = if value < 0.0 { -value } else { value };
|
||||
Ok(if magnitude > cap {
|
||||
if value < 0.0 {
|
||||
-cap
|
||||
} else {
|
||||
cap
|
||||
}
|
||||
} else {
|
||||
value
|
||||
})
|
||||
}
|
||||
|
||||
fn project_control_owner_profile_fca0(
|
||||
native_class: Option<MissionControlClassProjection>,
|
||||
original_words: &[u32; 27],
|
||||
current_words: &[u32; 27],
|
||||
fac0_projection: &Result<
|
||||
MissionControlOwnerProfileLoadProjection,
|
||||
MissionControlOwnerProfileLoadProjectionUnavailableReason,
|
||||
>,
|
||||
devices: &[EffectiveControlDevice],
|
||||
provider_status: &MissionControlNodeProviderTableStatus,
|
||||
) -> Result<[u32; 27], MissionControlOwnerProfileFca0UnavailableReason> {
|
||||
use MissionControlOwnerProfileFca0UnavailableReason as Unavailable;
|
||||
|
||||
if native_class.is_some_and(|class| class.class_id == 9) {
|
||||
return Ok(*current_words);
|
||||
}
|
||||
if native_class.is_none() {
|
||||
return Err(Unavailable::MissingNativeControlClass);
|
||||
}
|
||||
if let Err(reason) = fac0_projection {
|
||||
return Err(Unavailable::Fac0Unavailable(reason.clone()));
|
||||
}
|
||||
|
||||
let mut e00_sum = 0.0_f32;
|
||||
for device_index in (0..devices.len()).rev() {
|
||||
if devices[device_index].descriptor.tag != 5 {
|
||||
continue;
|
||||
}
|
||||
if let Some(value) = query_control_device_selector(&devices[device_index], provider_status)
|
||||
.map_err(|error| Unavailable::QueryUnavailable(Arc::new(error)))?
|
||||
{
|
||||
e00_sum = control_fca0_sum(e00_sum, value, "FCA0 reverse E00 sum")?;
|
||||
}
|
||||
}
|
||||
|
||||
// The canonical owner constructor initializes +0x1a8, +0x354, and +0x358
|
||||
// to 1.0; the traced event-4 loader does not overwrite these fields.
|
||||
let owner_scalar = 1.0_f32;
|
||||
let owner_mean = control_fca0_sum(1.0, 1.0, "FCA0 owner scalar mean")?;
|
||||
let owner_mean = control_fca0_product(owner_mean, 0.5, "FCA0 owner scalar mean")?;
|
||||
let weight = control_fca0_product(owner_mean, e00_sum, "FCA0 weighted E00 sum")?;
|
||||
let ratio = control_fca0_ratio(
|
||||
control_fca0_float(f32::from_bits(current_words[26]), "current profile word 26")?,
|
||||
control_fca0_float(
|
||||
f32::from_bits(original_words[26]),
|
||||
"original profile word 26",
|
||||
)?,
|
||||
"FCA0 profile word 26 ratio",
|
||||
)?;
|
||||
let factor_a = control_fca0_product(
|
||||
control_fca0_sum(ratio, 1.0, "FCA0 factor A")?,
|
||||
0.5,
|
||||
"FCA0 factor A",
|
||||
)?;
|
||||
let factor_b = control_fca0_sum(
|
||||
control_fca0_product(ratio, 0.75, "FCA0 factor B")?,
|
||||
0.25,
|
||||
"FCA0 factor B",
|
||||
)?;
|
||||
|
||||
let mut current_words = *current_words;
|
||||
for index in 6..9 {
|
||||
let original = control_fca0_float(
|
||||
f32::from_bits(original_words[index]),
|
||||
"original profile words 6..8",
|
||||
)?;
|
||||
let owner_scaled =
|
||||
control_fca0_product(owner_scalar, original, "FCA0 first profile triple")?;
|
||||
let weighted = control_fca0_product(owner_scaled, weight, "FCA0 first profile triple")?;
|
||||
let factored = control_fca0_product(weighted, factor_a, "FCA0 first profile triple")?;
|
||||
current_words[index] =
|
||||
control_fca0_clamp_to_profile_cap(factored, original, "FCA0 first profile triple")?
|
||||
.to_bits();
|
||||
}
|
||||
for index in 9..12 {
|
||||
let original = control_fca0_float(
|
||||
f32::from_bits(original_words[index]),
|
||||
"original profile words 9..11",
|
||||
)?;
|
||||
let weighted = control_fca0_product(weight, original, "FCA0 second profile triple")?;
|
||||
let factored = control_fca0_product(weighted, factor_b, "FCA0 second profile triple")?;
|
||||
current_words[index] =
|
||||
control_fca0_sum(factored, factored, "FCA0 doubled second profile triple")?.to_bits();
|
||||
}
|
||||
for index in 0..3 {
|
||||
let original = control_fca0_float(
|
||||
f32::from_bits(original_words[index]),
|
||||
"original profile words 0..2",
|
||||
)?;
|
||||
current_words[index] =
|
||||
control_fca0_sum(original, original, "FCA0 doubled profile words")?.to_bits();
|
||||
}
|
||||
Ok(current_words)
|
||||
}
|
||||
|
||||
fn behavior_clan_for_selector(
|
||||
selector: u32,
|
||||
clan_count: usize,
|
||||
@@ -5476,12 +5645,33 @@ fn build_control_device_table(
|
||||
.map(|projection| projection.devices)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
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> {
|
||||
let native_class =
|
||||
native_control_class_for_root(draft.unit_dat_header_flags, prototype_span, prototypes);
|
||||
build_control_device_projection_with_class(
|
||||
object_index,
|
||||
draft,
|
||||
assets,
|
||||
prototype_span,
|
||||
prototypes,
|
||||
native_class,
|
||||
)
|
||||
}
|
||||
|
||||
fn build_control_device_projection_with_class(
|
||||
object_index: usize,
|
||||
draft: &MissionObjectDraft,
|
||||
assets: &MissionAssets,
|
||||
prototype_span: Option<&std::ops::Range<usize>>,
|
||||
prototypes: &[fparkan_prototype::EffectivePrototype],
|
||||
native_control_class: Option<MissionControlClassProjection>,
|
||||
) -> Result<ControlDeviceProjection, MissionControlDeviceTableUnavailableReason> {
|
||||
use MissionControlDeviceTableUnavailableReason as Unavailable;
|
||||
|
||||
@@ -5892,6 +6082,20 @@ fn build_control_device_projection(
|
||||
),
|
||||
),
|
||||
};
|
||||
let fca0_projection = match project_control_owner_profile_fca0(
|
||||
native_control_class,
|
||||
&original_words,
|
||||
¤t_words,
|
||||
&load_projection,
|
||||
&devices,
|
||||
&node_provider_status,
|
||||
) {
|
||||
Ok(projected_words) => {
|
||||
current_words = projected_words;
|
||||
Ok(())
|
||||
}
|
||||
Err(reason) => Err(reason),
|
||||
};
|
||||
MissionControlOwnerProfile {
|
||||
source,
|
||||
unit_component_index,
|
||||
@@ -5899,6 +6103,7 @@ fn build_control_device_projection(
|
||||
original_words,
|
||||
current_words,
|
||||
load_projection,
|
||||
fca0_projection,
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -7302,8 +7507,10 @@ mod tests {
|
||||
);
|
||||
assert_eq!(device.tag26_extra_rate_bits, Some(0));
|
||||
device.tag26_extra_rate_bits = Some(0.3_f32.to_bits());
|
||||
device.multiplier_bits = Some(17.0_f32.to_bits());
|
||||
|
||||
let replacement = synthetic_control_record(19, 99, 0x30, None);
|
||||
let mut replacement = synthetic_control_record(5, 99, 3.0_f32.to_bits(), None);
|
||||
replacement.fixed_words[8] = 13.0_f32.to_bits();
|
||||
let control = synthetic_component_control(
|
||||
1,
|
||||
vec![replacement.clone()],
|
||||
@@ -7312,8 +7519,28 @@ mod tests {
|
||||
apply_effective_control_override(&mut device, &replacement, 1, 0, &control);
|
||||
|
||||
assert_eq!(device.factory_tag, 26);
|
||||
assert_eq!(device.descriptor.tag, 19);
|
||||
assert_eq!(device.key, 2, "INTO preserves the original provider key");
|
||||
assert_eq!(device.descriptor.tag, 5);
|
||||
assert_eq!(device.coefficient_bits.unwrap()[0], 3.0_f32.to_bits());
|
||||
assert_eq!(device.multiplier_bits, Some(17.0_f32.to_bits()));
|
||||
assert_eq!(device.descriptor.fixed_words[8], 13.0_f32.to_bits());
|
||||
assert_eq!(device.tag26_extra_rate_bits, Some(0.3_f32.to_bits()));
|
||||
|
||||
let table = synthetic_control_device_table_with_providers(
|
||||
MissionControlDeviceTableStatus::Available(vec![device]),
|
||||
MissionControlNodeProviderTableStatus::Available(vec![
|
||||
synthetic_node_provider_row(0, 0, 1.0_f32.to_bits()),
|
||||
synthetic_node_provider_row(0, 1, 2.0_f32.to_bits()),
|
||||
synthetic_node_provider_row(0, 2, 7.0_f32.to_bits()),
|
||||
]),
|
||||
);
|
||||
assert_eq!(
|
||||
query_control_device_table_selector(&table, 0, 0xe00)
|
||||
.expect("factory-26/current-tag-5 E00 query")
|
||||
.map(f32::to_bits),
|
||||
Some(21.0_f32.to_bits()),
|
||||
"tag-5 E00 uses current coefficient and provider value, without multiplier M or descriptor word 8"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -9719,6 +9946,7 @@ mod tests {
|
||||
root.node_data.as_mut().unwrap().rows[0].mobility_per_volume = 2.0;
|
||||
let (mut draft, mut assets, prototypes) =
|
||||
synthetic_control_fixture(&[None], &[1], &[0], &[0], &[1], vec![Some(root)]);
|
||||
draft.unit_dat_header_flags = Some(UNIT_DAT_CONTROL_CLASS_HIGH_BIT);
|
||||
attach_synthetic_model(&mut assets, 0, &[synthetic_node38(0, 0, [true; 3])]);
|
||||
assets.models[0].validated.slots[0].opaque =
|
||||
[7.0_f32.to_bits(), 11.0_f32.to_bits(), 0, 0, 0];
|
||||
@@ -9747,10 +9975,272 @@ mod tests {
|
||||
assert_eq!(load.row_20_bits, [41.25_f32.to_bits()]);
|
||||
assert_eq!(profile.original_words[26], 1000.0_f32.to_bits());
|
||||
assert_eq!(profile.current_words[26], 980.75_f32.to_bits());
|
||||
assert_eq!(profile.fca0_projection, Ok(()));
|
||||
assert_eq!(
|
||||
profile.current_words[..26],
|
||||
profile.original_words[..26],
|
||||
"FAC0 changes only mutable profile word 26"
|
||||
"FAC0 changes only word 26 in this tag-19-only fixture; FCA0 has no E00 contribution"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_control_fca0_late_float_failure_preserves_fac0_copy() {
|
||||
let native_class = MissionControlClassProjection {
|
||||
class_id: 3,
|
||||
source: MissionControlClassSource::UnitDatHighBit { header_flags: 0 },
|
||||
};
|
||||
|
||||
for (failure, coefficient, profile_word2, expected_error) in [
|
||||
(
|
||||
"nonfinite coefficient during E00 query",
|
||||
f32::INFINITY,
|
||||
0.0,
|
||||
Err(
|
||||
MissionControlOwnerProfileFca0UnavailableReason::QueryUnavailable(Arc::new(
|
||||
ControlResourceAccessError::NonFiniteValue {
|
||||
factory_tag: 5,
|
||||
field: "coefficient",
|
||||
},
|
||||
)),
|
||||
),
|
||||
),
|
||||
(
|
||||
"overflow in final profile-word doubling",
|
||||
1.0,
|
||||
f32::MAX,
|
||||
Err(
|
||||
MissionControlOwnerProfileFca0UnavailableReason::UnsupportedFloat {
|
||||
field: "FCA0 doubled profile words",
|
||||
},
|
||||
),
|
||||
),
|
||||
] {
|
||||
let mut cache_record = synthetic_control_record(27, 0, 2.0_f32.to_bits(), None);
|
||||
cache_record.fixed_words[7] = 0.0_f32.to_bits();
|
||||
let mut device_record = synthetic_control_record(5, 0, coefficient.to_bits(), None);
|
||||
device_record.fixed_words[7] = 5.25_f32.to_bits();
|
||||
let mut root =
|
||||
control_with_synthetic_node_data(0, vec![cache_record, device_record], 1);
|
||||
root.native_profile_words[0] = 1.0_f32.to_bits();
|
||||
root.native_profile_words[2] = profile_word2.to_bits();
|
||||
root.native_profile_words[26] = 1000.0_f32.to_bits();
|
||||
root.node_data.as_mut().unwrap().rows[0].mobility_per_volume = 2.0;
|
||||
let (mut draft, mut assets, prototypes) =
|
||||
synthetic_control_fixture(&[None], &[1], &[0], &[0], &[1], vec![Some(root)]);
|
||||
attach_synthetic_model(&mut assets, 0, &[synthetic_node38(0, 0, [true; 3])]);
|
||||
assets.models[0].validated.slots[0].opaque =
|
||||
[7.0_f32.to_bits(), 11.0_f32.to_bits(), 0, 0, 0];
|
||||
draft.scale = [2.0, 3.0, 5.0];
|
||||
|
||||
let projection = build_control_device_projection_with_class(
|
||||
0,
|
||||
&draft,
|
||||
&assets,
|
||||
Some(&(0..prototypes.len())),
|
||||
&prototypes,
|
||||
Some(native_class),
|
||||
)
|
||||
.expect("base device and FAC0 projections");
|
||||
let profile = projection
|
||||
.owner_profile
|
||||
.expect("native component-zero profile");
|
||||
assert!(profile.load_projection.is_ok());
|
||||
assert_eq!(profile.current_words[26], 980.75_f32.to_bits());
|
||||
assert_eq!(profile.fca0_projection, expected_error, "{failure}");
|
||||
assert_eq!(
|
||||
profile.current_words[..26],
|
||||
profile.original_words[..26],
|
||||
"{failure} must not publish any partial FCA0 words"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fca0_load_profile_matches_native_combined_vector() {
|
||||
let mut original_words = [0_u32; 27];
|
||||
original_words[0] = 1.25_f32.to_bits();
|
||||
original_words[1] = (-2.5_f32).to_bits();
|
||||
original_words[2] = 3.0_f32.to_bits();
|
||||
original_words[6] = 1.0_f32.to_bits();
|
||||
original_words[7] = (-2.0_f32).to_bits();
|
||||
original_words[8] = 10.0_f32.to_bits();
|
||||
original_words[9] = 2.0_f32.to_bits();
|
||||
original_words[10] = (-3.0_f32).to_bits();
|
||||
original_words[11] = 0.5_f32.to_bits();
|
||||
original_words[26] = 4.0_f32.to_bits();
|
||||
for index in [3, 4, 5].into_iter().chain(12..26) {
|
||||
original_words[index] = f32::NAN.to_bits();
|
||||
}
|
||||
let mut current_words = original_words;
|
||||
current_words[26] = 6.0_f32.to_bits();
|
||||
let fac0_projection = Ok(MissionControlOwnerProfileLoadProjection {
|
||||
aggregate_530_bits: 0,
|
||||
aggregate_534_bits: 0,
|
||||
aggregate_538_bits: 0,
|
||||
row_20_bits: vec![0; 3],
|
||||
});
|
||||
let mut device = synthetic_effective_control_device(
|
||||
5,
|
||||
5,
|
||||
2.0_f32.to_bits(),
|
||||
Some(17.0_f32.to_bits()),
|
||||
None,
|
||||
);
|
||||
device.key = 2;
|
||||
device.descriptor.fixed_words[8] = 7.0_f32.to_bits();
|
||||
let mut second_device = synthetic_effective_control_device(
|
||||
5,
|
||||
5,
|
||||
0.5_f32.to_bits(),
|
||||
Some(17.0_f32.to_bits()),
|
||||
None,
|
||||
);
|
||||
second_device.key = 0;
|
||||
second_device.descriptor.fixed_words[8] = 7.0_f32.to_bits();
|
||||
let devices = vec![device, second_device];
|
||||
let provider_status = MissionControlNodeProviderTableStatus::Available(vec![
|
||||
synthetic_node_provider_row(0, 0, (-1.5_f32).to_bits()),
|
||||
synthetic_node_provider_row(0, 1, 123.0_f32.to_bits()),
|
||||
synthetic_node_provider_row(0, 2, 3.0_f32.to_bits()),
|
||||
]);
|
||||
let mut expected = current_words;
|
||||
expected[0] = 2.5_f32.to_bits();
|
||||
expected[1] = (-5.0_f32).to_bits();
|
||||
expected[2] = 6.0_f32.to_bits();
|
||||
expected[6] = 1.0_f32.to_bits();
|
||||
// The native signed-cap comparison turns this negative result into +2.
|
||||
expected[7] = 2.0_f32.to_bits();
|
||||
expected[8] = 10.0_f32.to_bits();
|
||||
expected[9] = 28.875_f32.to_bits();
|
||||
expected[10] = (-43.3125_f32).to_bits();
|
||||
expected[11] = 7.21875_f32.to_bits();
|
||||
for class_id in [0, 3, 4] {
|
||||
assert_eq!(
|
||||
project_control_owner_profile_fca0(
|
||||
Some(MissionControlClassProjection {
|
||||
class_id,
|
||||
source: MissionControlClassSource::UnitDatHighBit { header_flags: 0 },
|
||||
}),
|
||||
&original_words,
|
||||
¤t_words,
|
||||
&fac0_projection,
|
||||
&devices,
|
||||
&provider_status,
|
||||
),
|
||||
Ok(expected),
|
||||
"native class {class_id} follows FCA0 unless it is class 9"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fca0_load_profile_uses_reverse_device_order_for_e00_sum() {
|
||||
let mut original_words = [0_u32; 27];
|
||||
original_words[6] = 2.0_f32.to_bits();
|
||||
original_words[26] = 1.0_f32.to_bits();
|
||||
let current_words = original_words;
|
||||
let fac0_projection = Ok(MissionControlOwnerProfileLoadProjection {
|
||||
aggregate_530_bits: 0,
|
||||
aggregate_534_bits: 0,
|
||||
aggregate_538_bits: 0,
|
||||
row_20_bits: vec![0; 3],
|
||||
});
|
||||
let mut first = synthetic_effective_control_device(
|
||||
5,
|
||||
5,
|
||||
1.0_f32.to_bits(),
|
||||
Some(1.0_f32.to_bits()),
|
||||
None,
|
||||
);
|
||||
first.key = 2;
|
||||
let mut second = first.clone();
|
||||
second.key = 0;
|
||||
let mut third = first.clone();
|
||||
third.key = 1;
|
||||
let devices = vec![first, second, third];
|
||||
let provider_status = MissionControlNodeProviderTableStatus::Available(vec![
|
||||
synthetic_node_provider_row(0, 0, 1.0_f32.to_bits()),
|
||||
synthetic_node_provider_row(0, 1, (-16_777_216.0_f32).to_bits()),
|
||||
synthetic_node_provider_row(0, 2, 16_777_216.0_f32.to_bits()),
|
||||
]);
|
||||
let class = MissionControlClassProjection {
|
||||
class_id: 3,
|
||||
source: MissionControlClassSource::UnitDatHighBit { header_flags: 0 },
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
project_control_owner_profile_fca0(
|
||||
Some(class),
|
||||
&original_words,
|
||||
¤t_words,
|
||||
&fac0_projection,
|
||||
&devices,
|
||||
&provider_status,
|
||||
),
|
||||
Ok(current_words),
|
||||
"reverse E00 order sums to one, so profile word 6 remains capped at two"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fca0_class9_returns_before_profile_or_device_inputs() {
|
||||
let original_words = [f32::NAN.to_bits(); 27];
|
||||
let current_words = [0x7f80_0000; 27];
|
||||
let fac0_projection = Err(
|
||||
MissionControlOwnerProfileLoadProjectionUnavailableReason::UnknownModelMapping {
|
||||
global_node_ordinal: None,
|
||||
},
|
||||
);
|
||||
let provider_status = MissionControlNodeProviderTableStatus::Unavailable(
|
||||
MissionControlNodeProviderTableUnavailableReason::MissingNodeData {
|
||||
unit_component_index: 0,
|
||||
source: None,
|
||||
},
|
||||
);
|
||||
let class9 = MissionControlClassProjection {
|
||||
class_id: 9,
|
||||
source: MissionControlClassSource::RootPrototypeFourCc { source_type: 0 },
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
project_control_owner_profile_fca0(
|
||||
Some(class9),
|
||||
&original_words,
|
||||
¤t_words,
|
||||
&fac0_projection,
|
||||
&[],
|
||||
&provider_status,
|
||||
),
|
||||
Ok(current_words)
|
||||
);
|
||||
assert_eq!(
|
||||
project_control_owner_profile_fca0(
|
||||
None,
|
||||
&original_words,
|
||||
¤t_words,
|
||||
&fac0_projection,
|
||||
&[],
|
||||
&provider_status,
|
||||
),
|
||||
Err(MissionControlOwnerProfileFca0UnavailableReason::MissingNativeControlClass)
|
||||
);
|
||||
assert_eq!(
|
||||
project_control_owner_profile_fca0(
|
||||
Some(MissionControlClassProjection {
|
||||
class_id: 4,
|
||||
source: class9.source,
|
||||
}),
|
||||
&original_words,
|
||||
¤t_words,
|
||||
&fac0_projection,
|
||||
&[],
|
||||
&provider_status,
|
||||
),
|
||||
Err(MissionControlOwnerProfileFca0UnavailableReason::Fac0Unavailable(
|
||||
MissionControlOwnerProfileLoadProjectionUnavailableReason::UnknownModelMapping {
|
||||
global_node_ordinal: None,
|
||||
}
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10514,6 +11004,72 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn factory5_e00_uses_provider_times_coefficient_only() {
|
||||
let mut device = synthetic_effective_control_device(
|
||||
5,
|
||||
5,
|
||||
3.0_f32.to_bits(),
|
||||
Some(17.0_f32.to_bits()),
|
||||
None,
|
||||
);
|
||||
device.descriptor.fixed_words[8] = 13.0_f32.to_bits();
|
||||
let table = synthetic_control_device_table_with_providers(
|
||||
MissionControlDeviceTableStatus::Available(vec![device]),
|
||||
MissionControlNodeProviderTableStatus::Available(vec![
|
||||
synthetic_node_provider_row(0, 0, 1.0_f32.to_bits()),
|
||||
synthetic_node_provider_row(0, 1, 2.0_f32.to_bits()),
|
||||
synthetic_node_provider_row(0, 2, 7.0_f32.to_bits()),
|
||||
]),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
query_control_device_table_selector(&table, 0, 0xe00)
|
||||
.expect("factory-5 E00 query")
|
||||
.map(f32::to_bits),
|
||||
Some(21.0_f32.to_bits()),
|
||||
"E00 uses the provider row and coefficient, without the multiplier or descriptor word 8"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn e00_common_reader_covers_current_tags_and_both_factories() {
|
||||
let devices = [(5, 5), (5, 26), (26, 5), (26, 26)]
|
||||
.into_iter()
|
||||
.map(|(current_tag, factory_tag)| {
|
||||
let mut device = synthetic_effective_control_device(
|
||||
factory_tag,
|
||||
current_tag,
|
||||
3.0_f32.to_bits(),
|
||||
Some(17.0_f32.to_bits()),
|
||||
None,
|
||||
);
|
||||
device.descriptor.fixed_words[8] = 13.0_f32.to_bits();
|
||||
device
|
||||
})
|
||||
.collect();
|
||||
let table = synthetic_control_device_table_with_providers(
|
||||
MissionControlDeviceTableStatus::Available(devices),
|
||||
MissionControlNodeProviderTableStatus::Available(vec![
|
||||
synthetic_node_provider_row(0, 0, 1.0_f32.to_bits()),
|
||||
synthetic_node_provider_row(0, 1, 2.0_f32.to_bits()),
|
||||
synthetic_node_provider_row(0, 2, 7.0_f32.to_bits()),
|
||||
]),
|
||||
);
|
||||
|
||||
for (device_index, (current_tag, factory_tag)) in
|
||||
[(5, 5), (5, 26), (26, 5), (26, 26)].into_iter().enumerate()
|
||||
{
|
||||
let expected = if current_tag == 5 { 21.0 } else { 357.0 };
|
||||
assert_eq!(
|
||||
query_control_device_table_selector(&table, device_index, 0xe00)
|
||||
.expect("shared E00 factory getter"),
|
||||
Some(expected),
|
||||
"current tag {current_tag}, factory tag {factory_tag}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_mesh_metadata_maps_control_flags_and_parent_words() {
|
||||
assert_eq!(control_flags_from_node38_header(0x0701), 0x0f);
|
||||
@@ -10670,7 +11226,7 @@ mod tests {
|
||||
query_control_device_table_selector(&table, 1, 0xe00),
|
||||
Ok(None)
|
||||
);
|
||||
for tag in [5, 10, 21] {
|
||||
for tag in [10, 21] {
|
||||
let mut unsupported = table.clone();
|
||||
let MissionControlDeviceTableStatus::Available(entries) = &mut unsupported.status
|
||||
else {
|
||||
@@ -10682,6 +11238,16 @@ mod tests {
|
||||
Err(ControlResourceAccessError::UnsupportedCurrentTag { tag })
|
||||
);
|
||||
}
|
||||
let mut current_tag5_factory9 = table.clone();
|
||||
let MissionControlDeviceTableStatus::Available(entries) = &mut current_tag5_factory9.status
|
||||
else {
|
||||
unreachable!();
|
||||
};
|
||||
entries[3].descriptor.tag = 5;
|
||||
assert_eq!(
|
||||
query_control_device_table_selector(¤t_tag5_factory9, 3, 0xe00),
|
||||
Err(ControlResourceAccessError::UnsupportedFactoryTag { factory_tag: 9 })
|
||||
);
|
||||
assert_eq!(
|
||||
query_control_device_table_selector(&table, 3, 0xe00),
|
||||
Err(ControlResourceAccessError::UnsupportedFactoryTag { factory_tag: 9 })
|
||||
@@ -10982,6 +11548,19 @@ mod tests {
|
||||
.owner_profile
|
||||
.as_ref()
|
||||
.expect("loaded root owner profile");
|
||||
let fca0_target_indices = [0, 1, 2, 6, 7, 8, 9, 10, 11];
|
||||
let fca0_target_words = fca0_target_indices.map(|index| owner_profile.current_words[index]);
|
||||
println!(
|
||||
"licensed mine FCA0: class={:?} projection={:?} indices={fca0_target_indices:?} targets={:08x?}",
|
||||
mine_control_before[0].native_control_class,
|
||||
owner_profile.fca0_projection,
|
||||
fca0_target_words,
|
||||
);
|
||||
assert_eq!(owner_profile.fca0_projection, Ok(()));
|
||||
assert_eq!(
|
||||
fca0_target_words,
|
||||
[0x4000_0000, 0x4000_0000, 0x4000_0000, 0, 0, 0, 0, 0, 0,]
|
||||
);
|
||||
assert_eq!(owner_profile.unit_component_index, 0);
|
||||
assert_eq!(owner_profile.native_component_id, 0);
|
||||
assert_eq!(owner_profile.source, root_control.source);
|
||||
@@ -11035,10 +11614,14 @@ mod tests {
|
||||
assert_eq!(mine_fac0.row_20_bits.len(), 25);
|
||||
assert_eq!(owner_profile.original_words[26], 0x7f7f_ffff);
|
||||
assert_eq!(owner_profile.current_words[26], 0x7f7f_ffff);
|
||||
assert_eq!(
|
||||
&owner_profile.current_words[..26],
|
||||
&root_control.native_profile_words[..26]
|
||||
);
|
||||
for index in 0..26 {
|
||||
if !fca0_target_indices.contains(&index) {
|
||||
assert_eq!(
|
||||
owner_profile.current_words[index], owner_profile.original_words[index],
|
||||
"FCA0 leaves profile word {index} unchanged"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_ne!(
|
||||
root_control.native_profile_words, child_control.native_profile_words,
|
||||
"the licensed child CTLD has its own profile words"
|
||||
|
||||
@@ -15,6 +15,7 @@ internal static class BehaviorDistributorTickOracle {
|
||||
private const uint PageExecuteReadWrite = 0x40;
|
||||
private const uint MemRelease = 0x00008000;
|
||||
private const uint PageReadWrite = 0x04;
|
||||
private const uint PageNoAccess = 0x01;
|
||||
private const string ExpectedBehaviorSha256 = "ddfbdbde07832358fe6e35e01c8dba9b58e7313789498b6049ed51d4ed9baf99";
|
||||
private const string ExpectedControlSha256 = "bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e";
|
||||
private const string ExpectedArealMapSha256 = "a25f9254ebb339d70e2e07c8121950191e9584ca0858d8e9c2e2b6c671edf6ea";
|
||||
@@ -82,10 +83,12 @@ internal static class BehaviorDistributorTickOracle {
|
||||
private const int ControlResourceTag19VtableRva = 0x3c608;
|
||||
private const int ControlResourceTag19StringPairNoOpRva = 0x0bcd0;
|
||||
private const int ControlProfileFac0Rva = 0x0fac0;
|
||||
private const int ControlProfileFca0Rva = 0x0fca0;
|
||||
private const int ControlProfileOwnerConstructorRva = 0x31490;
|
||||
private const int ControlProfileDeviceVtableRva = 0x3d1b4;
|
||||
private const int ControlProfileDeviceCountRva = 0x08830;
|
||||
private const int ControlProfileDeviceQueryRva = 0x2bb40;
|
||||
private const int ControlResourceTag5VtableRva = 0x3cdf8;
|
||||
private const int AniMeshComponentFirstRva = 0x05780;
|
||||
private const int AniMeshComponentCountRva = 0x057c0;
|
||||
private const int BehaviorVarTableVtableRva = 0x591b0;
|
||||
@@ -150,6 +153,8 @@ internal static class BehaviorDistributorTickOracle {
|
||||
[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.StdCall)] private delegate uint NativeControlOwnerDeviceQuery(IntPtr ownerInterface, uint deviceIndex, uint selector, IntPtr result);
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlDeviceBind(IntPtr device, IntPtr owner, IntPtr provider, IntPtr model);
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeAniMeshNodeConstructor(IntPtr self, IntPtr model, IntPtr source, uint component, IntPtr meshData);
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlProviderAmountUpdate(IntPtr self, int nodeIndex, float delta, uint animationFlag);
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlProviderAmountDistribute(IntPtr self, float delta, uint mode, uint flags);
|
||||
@@ -700,7 +705,7 @@ internal static class BehaviorDistributorTickOracle {
|
||||
Marshal.WriteIntPtr(import, Marshal.GetFunctionPointerForDelegate(AreaMapGetterCallback));
|
||||
Marshal.WriteIntPtr(queueImport, Marshal.GetFunctionPointerForDelegate(QueueGetterCallback));
|
||||
RunSmokeCases(module, controlModule, arealMapModule, aniMeshModule);
|
||||
Console.WriteLine("original native Behavior/ArealMap/Control oracle passed (Behavior Add 0x1aac0, normalize 0x1ac90, scheduler 0x1adb0, tick 0x19e80; ArealMap UnitDAT projection 0x14b90; Control INTO override 0x2d890, FAC0 load profile 0xfac0, provider distribution 0x10ba0, class-4 update 0x12a40 and bounded class-10 active clock 0xbcf0; FAC0 uses synthetic backing with original AniMesh and Control query methods; other host callbacks, GetSystemArealMap/GetQueue IAT slots, and bounded vector insertion are substituted; no full UnitDAT loading or gameplay parity is claimed).");
|
||||
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, FAC0 initial profile 0xfac0, FCA0 initial profile 0xfca0, provider distribution 0x10ba0, class-4 update 0x12a40 and bounded class-10 active clock 0xbcf0; FAC0/FCA0 use synthetic backing with original AniMesh and Control query methods; other host callbacks, GetSystemArealMap/GetQueue IAT slots, and bounded vector insertion are substituted; no full UnitDAT loading or gameplay parity is claimed).");
|
||||
return 0;
|
||||
}
|
||||
catch (Exception error) {
|
||||
@@ -2801,6 +2806,7 @@ internal static class BehaviorDistributorTickOracle {
|
||||
RunFac0NegativeClamp(controlModule, aniMeshModule, constructOwner, fac0, findFirst, countMatches);
|
||||
RunFac0NullAndSignedZeroCases(controlModule, aniMeshModule, constructOwner, fac0);
|
||||
RunFac0OrderedCase(controlModule, aniMeshModule, constructOwner, fac0);
|
||||
RunNativeControlFca0LoadCases(controlModule, constructOwner);
|
||||
Expect(CurrentX87ControlWord() == 0x007f, "FAC0 vectors use x87 control word 0x007f");
|
||||
Console.WriteLine("native-control-fac0-load: controlHash=" + ExpectedControlSha256 +
|
||||
" aniMeshHash=" + ExpectedAniMeshSha256 + " rva=0x0fac0 cw=0x" +
|
||||
@@ -2847,11 +2853,11 @@ internal static class BehaviorDistributorTickOracle {
|
||||
private static IntPtr CreateFac0Owner(Fixture fixture, IntPtr controlModule,
|
||||
NativeControlOwnerConstructor constructOwner, IntPtr ani, uint originalWord26,
|
||||
float[] descriptorMobility, float[] mutableAmounts, bool hasCache, float cacheC,
|
||||
uint[] deviceKeys, float[] deviceValues) {
|
||||
uint[] deviceKeys, float[] deviceValues, uint classCode = 4) {
|
||||
Expect(descriptorMobility.Length == mutableAmounts.Length, "FAC0 provider fixture lengths");
|
||||
Expect(deviceKeys.Length == deviceValues.Length, "FAC0 device fixture lengths");
|
||||
IntPtr owner = fixture.Allocate(0x700);
|
||||
Expect(constructOwner(owner, IntPtr.Zero, 4) == owner, "original Control owner constructor 0x31490");
|
||||
Expect(constructOwner(owner, IntPtr.Zero, classCode) == owner, "original Control owner constructor 0x31490");
|
||||
IntPtr deviceInterface = IntPtr.Add(owner, 0x0c);
|
||||
IntPtr deviceVtable = Marshal.ReadIntPtr(deviceInterface);
|
||||
Expect(deviceVtable == IntPtr.Add(controlModule, ControlProfileDeviceVtableRva) &&
|
||||
@@ -2898,6 +2904,237 @@ internal static class BehaviorDistributorTickOracle {
|
||||
return owner;
|
||||
}
|
||||
|
||||
private static IntPtr CreateFca0Owner(Fixture fixture, IntPtr controlModule,
|
||||
NativeControlOwnerConstructor constructOwner, int rowCount, int deviceCapacity) {
|
||||
float[] rowDefaults = new float[rowCount];
|
||||
IntPtr owner = CreateFac0Owner(fixture, controlModule, constructOwner, IntPtr.Zero,
|
||||
FloatBitsUnsigned(4.0f), rowDefaults, rowDefaults, false, 0.0f,
|
||||
new uint[0], new float[0], 3);
|
||||
IntPtr deviceInterface = IntPtr.Add(owner, 0x0c);
|
||||
Expect(Marshal.ReadIntPtr(owner, 0x38) == deviceInterface,
|
||||
"FCA0 owner+0x38 uses its canonical owner+0x0c interface");
|
||||
IntPtr providerInterface = IntPtr.Add(owner, 4);
|
||||
IntPtr providerVtable = Marshal.ReadIntPtr(providerInterface);
|
||||
Expect(providerVtable == IntPtr.Add(controlModule, ControlProviderInterfaceVtableRva) &&
|
||||
Marshal.ReadIntPtr(providerVtable, 0x0c) == IntPtr.Add(controlModule, ControlProviderType1GetterRva),
|
||||
"FCA0 binder receives owner+4 with the original FUN_1000dc40 provider slot");
|
||||
Marshal.WriteIntPtr(owner, 0x5bc, fixture.Allocate(Math.Max(1, deviceCapacity) * IntPtr.Size));
|
||||
Marshal.WriteInt32(owner, 0x5c0, 0);
|
||||
Marshal.WriteInt32(owner, 0x5c4, deviceCapacity);
|
||||
return owner;
|
||||
}
|
||||
|
||||
private static IntPtr CreateFca0Factory5Device(Fixture fixture, IntPtr controlModule,
|
||||
NativeControlDeviceFactory createDevice, NativeControlDeviceBind bindDevice, IntPtr owner,
|
||||
uint key, float coefficient, float descriptorWord8, int ordinal) {
|
||||
IntPtr deviceArrayBeforeFactory = Marshal.ReadIntPtr(owner, 0x5bc);
|
||||
int countBeforeFactory = Marshal.ReadInt32(owner, 0x5c0);
|
||||
int capacityBeforeFactory = Marshal.ReadInt32(owner, 0x5c4);
|
||||
Expect(ordinal == countBeforeFactory,
|
||||
"factory-5 ordinal matches the owner device count before append " + ordinal);
|
||||
Expect(capacityBeforeFactory > countBeforeFactory + 1,
|
||||
"factory-5 fixture reserves a spare device-vector slot before appending ordinal " + ordinal);
|
||||
IntPtr record = fixture.Allocate(0xc0);
|
||||
Marshal.WriteInt32(record, 0, 5);
|
||||
Marshal.WriteInt32(record, 4, unchecked((int)key));
|
||||
Marshal.WriteInt32(record, 0x18, -1);
|
||||
Marshal.WriteInt32(record, 0x20, FloatBits(descriptorWord8));
|
||||
for (int i = 0; i < 16; i++)
|
||||
Marshal.WriteInt32(record, 0x2c + i * 4, FloatBits(i == 0 ? coefficient : 0.0f));
|
||||
Marshal.WriteInt32(record, 0xac, 0);
|
||||
Marshal.WriteInt32(record, 0xb0, 0);
|
||||
Expect(createDevice(owner, 0, 0, record) == IntPtr.Add(record, 0xb4),
|
||||
"original Control factory-5 dispatch 0x2d4b0 consumes its typed record");
|
||||
Expect(Marshal.ReadIntPtr(owner, 0x5bc) == deviceArrayBeforeFactory,
|
||||
"factory-5 append keeps the owner device-vector pointer captured before construction");
|
||||
Expect(Marshal.ReadInt32(owner, 0x5c0) == countBeforeFactory + 1,
|
||||
"factory-5 append advances the owner device count before reading the captured array");
|
||||
IntPtr device = Marshal.ReadIntPtr(deviceArrayBeforeFactory, ordinal * IntPtr.Size);
|
||||
Expect(device != IntPtr.Zero, "original factory-5 publishes its device at the expected ordinal");
|
||||
IntPtr deviceVtable = Marshal.ReadIntPtr(device);
|
||||
Expect(deviceVtable == IntPtr.Add(controlModule, ControlResourceTag5VtableRva) &&
|
||||
Marshal.ReadIntPtr(deviceVtable, 0x10) == IntPtr.Add(controlModule, ControlResourceDeviceGetterRva) &&
|
||||
Marshal.ReadIntPtr(deviceVtable, 0x1c) == IntPtr.Add(controlModule, ControlResourceCommonSetterRva),
|
||||
"factory-5 vtable uses the original reader 0x21d00 and setter 0x21d50");
|
||||
Expect(Marshal.ReadIntPtr(device, 0x48) == record && Marshal.ReadInt32(device, 4) == unchecked((int)key) &&
|
||||
Marshal.ReadInt32(device, 0x50) == 5 && Marshal.ReadInt32(device, 0x4c) == FloatBits(1.0f),
|
||||
"factory-5 current descriptor, key, and constructor defaults");
|
||||
bindDevice(device, owner, IntPtr.Add(owner, 4), IntPtr.Zero);
|
||||
Expect(Marshal.ReadIntPtr(device, 0x3c) == owner && Marshal.ReadIntPtr(device, 0x44) == IntPtr.Add(owner, 4) &&
|
||||
Marshal.ReadIntPtr(device, 0x40) == IntPtr.Zero,
|
||||
"original binder 0x21990 binds owner and owner+4 with a null model");
|
||||
Console.WriteLine("native-control-fca0-factory5: ordinal=" + ordinal + " key=" + key +
|
||||
" coefficient0=" + Float((uint)FloatBits(coefficient)) + " descriptor+0x20=" + Float((uint)FloatBits(descriptorWord8)) +
|
||||
" model=null vtable=0x3cdf8");
|
||||
return device;
|
||||
}
|
||||
|
||||
private static float QueryFca0E00(IntPtr controlModule, NativeControlOwnerDeviceQuery query,
|
||||
Fixture fixture, IntPtr owner, uint ordinal) {
|
||||
IntPtr ownerInterface = IntPtr.Add(owner, 0x0c);
|
||||
IntPtr ownerVtable = Marshal.ReadIntPtr(ownerInterface);
|
||||
Expect(Marshal.ReadIntPtr(ownerVtable, 0x18) == IntPtr.Add(controlModule, ControlProfileDeviceQueryRva),
|
||||
"owner device query table resolves to original FUN_1002bb40");
|
||||
IntPtr result = fixture.Allocate(sizeof(uint));
|
||||
Expect((query(ownerInterface, ordinal, 0x0e00, result) & 0xff) == 1,
|
||||
"original owner query returns selector E00 for factory-5 device " + ordinal);
|
||||
return ReadFloat(result, 0);
|
||||
}
|
||||
|
||||
private static void RunNativeControlFca0LoadCases(IntPtr controlModule,
|
||||
NativeControlOwnerConstructor constructOwner) {
|
||||
NativeControlProfileFac0 fca0 = (NativeControlProfileFac0)Marshal.GetDelegateForFunctionPointer(
|
||||
WriteStdCallToFastcallOneArgThunk(0x4c0, IntPtr.Add(controlModule, ControlProfileFca0Rva)),
|
||||
typeof(NativeControlProfileFac0));
|
||||
NativeControlOwnerDeviceQuery query = (NativeControlOwnerDeviceQuery)Marshal.GetDelegateForFunctionPointer(
|
||||
WriteStdCallFourArgsToFastcallThunk(0x500, IntPtr.Add(controlModule, ControlProfileDeviceQueryRva)),
|
||||
typeof(NativeControlOwnerDeviceQuery));
|
||||
NativeControlDeviceFactory createDevice = (NativeControlDeviceFactory)Marshal.GetDelegateForFunctionPointer(
|
||||
IntPtr.Add(controlModule, ControlResourceTag26ConstructorRva), typeof(NativeControlDeviceFactory));
|
||||
NativeControlDeviceBind bindDevice = (NativeControlDeviceBind)Marshal.GetDelegateForFunctionPointer(
|
||||
IntPtr.Add(controlModule, 0x21990), typeof(NativeControlDeviceBind));
|
||||
Expect(CurrentX87ControlWord() == 0x007f, "FCA0 vectors start with the game x87 control word");
|
||||
|
||||
using (Fixture fixture = NewFixture()) {
|
||||
IntPtr owner = CreateFca0Owner(fixture, controlModule, constructOwner, 3, 2);
|
||||
Marshal.WriteInt32(owner, 0x1a8, FloatBits(17.0f));
|
||||
Marshal.WriteInt32(owner, 0x354, FloatBits(1.0f));
|
||||
Marshal.WriteInt32(owner, 0x358, FloatBits(1.0f));
|
||||
IntPtr rows = Marshal.ReadIntPtr(owner, 0x55c);
|
||||
Marshal.WriteInt32(rows, 2 * 0x2c + 0x14, FloatBits(7.0f));
|
||||
IntPtr device = CreateFca0Factory5Device(fixture, controlModule, createDevice, bindDevice,
|
||||
owner, 2, 3.0f, 13.0f, 0);
|
||||
Marshal.WriteInt32(device, 0x4c, FloatBits(17.0f));
|
||||
float value = QueryFca0E00(controlModule, query, fixture, owner, 0);
|
||||
Expect(unchecked((uint)FloatBits(value)) == 0x41a80000,
|
||||
"E00 uses provider key 2 value 7 times coefficient 3, ignoring M=17 and descriptor word8=13");
|
||||
Console.WriteLine("native-control-fca0-reader-aligned: class=3 factory=5 ordinal=0 providerKey=2 type1=0x40e00000" +
|
||||
" coefficient0=0x40400000 device+4c(M)=0x41880000 descriptorWord8=13 E00=21 raw=0x" +
|
||||
unchecked((uint)FloatBits(value)).ToString("x8"));
|
||||
}
|
||||
|
||||
using (Fixture fixture = NewFixture()) {
|
||||
IntPtr owner = CreateFca0Owner(fixture, controlModule, constructOwner, 3, 3);
|
||||
IntPtr rows = Marshal.ReadIntPtr(owner, 0x55c);
|
||||
Marshal.WriteInt32(rows, 0x14, FloatBits(-1.5f));
|
||||
Marshal.WriteInt32(rows, 0x2c + 0x14, FloatBits(123.0f));
|
||||
Marshal.WriteInt32(rows, 2 * 0x2c + 0x14, FloatBits(3.0f));
|
||||
Marshal.WriteInt32(owner, 0x1a8, FloatBits(1.0f));
|
||||
Marshal.WriteInt32(owner, 0x354, FloatBits(1.0f));
|
||||
Marshal.WriteInt32(owner, 0x358, FloatBits(1.0f));
|
||||
IntPtr profile = Marshal.ReadIntPtr(owner, 0x46c);
|
||||
float[] words = { 1.25f, -2.5f, 3.0f };
|
||||
for (int i = 0; i < words.Length; i++) Marshal.WriteInt32(profile, i * 4, FloatBits(words[i]));
|
||||
Marshal.WriteInt32(profile, 6 * 4, FloatBits(1.0f));
|
||||
Marshal.WriteInt32(profile, 7 * 4, FloatBits(-2.0f));
|
||||
Marshal.WriteInt32(profile, 8 * 4, FloatBits(10.0f));
|
||||
Marshal.WriteInt32(profile, 9 * 4, FloatBits(2.0f));
|
||||
Marshal.WriteInt32(profile, 10 * 4, FloatBits(-3.0f));
|
||||
Marshal.WriteInt32(profile, 11 * 4, FloatBits(0.5f));
|
||||
Marshal.WriteInt32(profile, 26 * 4, FloatBits(4.0f));
|
||||
Marshal.WriteInt32(owner, 0x4d8, FloatBits(6.0f));
|
||||
CreateFca0Factory5Device(fixture, controlModule, createDevice, bindDevice, owner, 2, 2.0f, 7.0f, 0);
|
||||
CreateFca0Factory5Device(fixture, controlModule, createDevice, bindDevice, owner, 0, 0.5f, 7.0f, 1);
|
||||
float first = QueryFca0E00(controlModule, query, fixture, owner, 0);
|
||||
float second = QueryFca0E00(controlModule, query, fixture, owner, 1);
|
||||
Expect(unchecked((uint)FloatBits(first)) == 0x40c00000 &&
|
||||
unchecked((uint)FloatBits(second)) == 0xbf400000,
|
||||
"canonical FCA0 E00 samples use provider keys 2 and 0");
|
||||
fca0(owner);
|
||||
Expect(CurrentX87ControlWord() == 0x007f, "FCA0 canonical vector retains CW=0x007f");
|
||||
int[] offsets = { 0x470, 0x474, 0x478, 0x488, 0x48c, 0x490, 0x494, 0x498, 0x49c };
|
||||
uint[] expected = {
|
||||
0x40200000, 0xc0a00000, 0x40c00000, 0x3f800000, 0x40000000,
|
||||
0x41200000, 0x41e70000, 0xc22d4000, 0x40e70000
|
||||
};
|
||||
for (int i = 0; i < offsets.Length; i++)
|
||||
Expect(ReadFac0Word(owner, offsets[i]) == expected[i],
|
||||
"canonical FCA0 owner+0x" + offsets[i].ToString("x") + " raw word " + Hex(expected[i]));
|
||||
Expect(ReadFac0Word(owner, 0x4d8) == FloatBitsUnsigned(6.0f),
|
||||
"FCA0 leaves its current word-26 ratio input unchanged");
|
||||
Console.WriteLine("native-control-fca0-canonical-default: class=3 devices=[i0:key2:E00=0x40c00000,i1:key0:E00=0xbf400000]" +
|
||||
" scalar+1a8=0x3f800000 means+354/+358=0x3f800000 ratio=6/4 outputs=[470=40200000,474=c0a00000,478=40c00000" +
|
||||
",488=3f800000,48c=40000000,490=41200000,494=41e70000,498=c22d4000,49c=40e70000]");
|
||||
}
|
||||
|
||||
using (Fixture fixture = NewFixture()) {
|
||||
IntPtr owner = CreateFca0Owner(fixture, controlModule, constructOwner, 3, 4);
|
||||
IntPtr rows = Marshal.ReadIntPtr(owner, 0x55c);
|
||||
Marshal.WriteInt32(rows, 0x14, FloatBits(1.0f));
|
||||
Marshal.WriteInt32(rows, 0x2c + 0x14, FloatBits(-16777216.0f));
|
||||
Marshal.WriteInt32(rows, 2 * 0x2c + 0x14, FloatBits(16777216.0f));
|
||||
Marshal.WriteInt32(owner, 0x1a8, FloatBits(1.0f));
|
||||
Marshal.WriteInt32(owner, 0x354, FloatBits(1.0f));
|
||||
Marshal.WriteInt32(owner, 0x358, FloatBits(1.0f));
|
||||
IntPtr profile = Marshal.ReadIntPtr(owner, 0x46c);
|
||||
Marshal.WriteInt32(profile, 6 * 4, FloatBits(2.0f));
|
||||
Marshal.WriteInt32(profile, 26 * 4, FloatBits(1.0f));
|
||||
Marshal.WriteInt32(owner, 0x4d8, FloatBits(1.0f));
|
||||
CreateFca0Factory5Device(fixture, controlModule, createDevice, bindDevice, owner, 2, 1.0f, 1.0f, 0);
|
||||
CreateFca0Factory5Device(fixture, controlModule, createDevice, bindDevice, owner, 0, 1.0f, 1.0f, 1);
|
||||
CreateFca0Factory5Device(fixture, controlModule, createDevice, bindDevice, owner, 1, 1.0f, 1.0f, 2);
|
||||
float[] samples = {
|
||||
QueryFca0E00(controlModule, query, fixture, owner, 0),
|
||||
QueryFca0E00(controlModule, query, fixture, owner, 1),
|
||||
QueryFca0E00(controlModule, query, fixture, owner, 2)
|
||||
};
|
||||
Expect(unchecked((uint)FloatBits(samples[0])) == 0x4b800000 &&
|
||||
unchecked((uint)FloatBits(samples[1])) == 0x3f800000 &&
|
||||
unchecked((uint)FloatBits(samples[2])) == 0xcb800000,
|
||||
"reverse-order vector E00 values");
|
||||
float forward = 0.0f;
|
||||
for (int i = 0; i < samples.Length; i++)
|
||||
forward = BitConverter.ToSingle(BitConverter.GetBytes(forward + samples[i]), 0);
|
||||
float reverse = 0.0f;
|
||||
for (int i = samples.Length - 1; i >= 0; i--)
|
||||
reverse = BitConverter.ToSingle(BitConverter.GetBytes(reverse + samples[i]), 0);
|
||||
Expect(unchecked((uint)FloatBits(forward)) == 0x00000000 &&
|
||||
unchecked((uint)FloatBits(reverse)) == 0x3f800000,
|
||||
"single-precision forward sum is zero while native reverse-order sum is one");
|
||||
fca0(owner);
|
||||
Expect(ReadFac0Word(owner, 0x488) == 0x40000000,
|
||||
"FCA0 owner+0x488 uses reverse E00 sum one times original word 6 two");
|
||||
Console.WriteLine("native-control-fca0-reverse: device-array=[16777216,1,-16777216]" +
|
||||
" reverse-visits=[-16777216,1,16777216] forward=0x00000000 reverse=0x3f800000 owner+488=0x40000000");
|
||||
}
|
||||
|
||||
int pageSize = Environment.SystemPageSize;
|
||||
IntPtr guarded = VirtualAlloc(IntPtr.Zero, new UIntPtr((uint)(pageSize * 2)), MemCommitReserve, PageReadWrite);
|
||||
if (guarded == IntPtr.Zero)
|
||||
throw new InvalidOperationException("VirtualAlloc class-9 FCA0 guard pages error=" + Marshal.GetLastWin32Error());
|
||||
try {
|
||||
for (int i = 0; i < pageSize; i++) Marshal.WriteByte(guarded, i, 0xa5);
|
||||
IntPtr owner = IntPtr.Add(guarded, pageSize - 0x100);
|
||||
Marshal.WriteIntPtr(owner, 0x38, IntPtr.Zero);
|
||||
Marshal.WriteInt32(owner, 0x50, 9);
|
||||
byte[] before = new byte[pageSize];
|
||||
Marshal.Copy(guarded, before, 0, pageSize);
|
||||
uint oldProtect;
|
||||
if (!VirtualProtect(IntPtr.Add(guarded, pageSize), new UIntPtr((uint)pageSize), PageNoAccess, out oldProtect))
|
||||
throw new InvalidOperationException("VirtualProtect class-9 FCA0 guard page error=" + Marshal.GetLastWin32Error());
|
||||
fca0(owner);
|
||||
byte[] after = new byte[pageSize];
|
||||
Marshal.Copy(guarded, after, 0, pageSize);
|
||||
bool unchanged = true;
|
||||
for (int i = 0; i < before.Length; i++) unchanged &= before[i] == after[i];
|
||||
Expect(unchanged && Marshal.ReadInt32(owner, 0x50) == 9,
|
||||
"class 9 FCA0 returns without reading inaccessible profile/output memory or writing owner state");
|
||||
Console.WriteLine("native-control-fca0-class9: owner+50=9 profile/output page is PAGE_NOACCESS; returned without fault or writes");
|
||||
} finally {
|
||||
VirtualFree(guarded, UIntPtr.Zero, MemRelease);
|
||||
}
|
||||
|
||||
Expect(CurrentX87ControlWord() == 0x007f, "FCA0 vectors retain x87 control word 0x007f");
|
||||
Console.WriteLine("native-control-fca0-load: controlHash=" + ExpectedControlSha256 +
|
||||
" rva=0x0fca0 cw=0x" + CurrentX87ControlWord().ToString("x4") +
|
||||
" original owner/factory5/binder/provider/query/reader/setter paths");
|
||||
GC.KeepAlive(fca0);
|
||||
GC.KeepAlive(query);
|
||||
GC.KeepAlive(createDevice);
|
||||
GC.KeepAlive(bindDevice);
|
||||
GC.KeepAlive(constructOwner);
|
||||
}
|
||||
|
||||
private static uint ReadFac0Word(IntPtr address, int offset) {
|
||||
return unchecked((uint)Marshal.ReadInt32(address, offset));
|
||||
}
|
||||
|
||||
@@ -569,23 +569,52 @@ resource-device значения во время игры.
|
||||
и mirror-варианты передают свой transform-вектор setter-у; это отдельная
|
||||
граница, как и более поздние placement/tick.
|
||||
|
||||
Полный Rust loader теперь вызывает FAC0 при построении
|
||||
`build_control_device_projection` и публикует результат в
|
||||
`MissionControlOwnerProfile::load_projection`. Игнорируемый corpus-тест
|
||||
`full_load_builds_effective_control_device_table_for_mine_unit_dat` на лицензированном
|
||||
`min_l_n1.dat` проверяет 11 устройств, все 25 соответствий provider ordinal
|
||||
модели и упорядоченные значения `row +0x20`. Его агрегаты —
|
||||
`0x470833fc/0x4897e712/0x4d9452cb` для `+0x530/+0x534/+0x538`; исходный и
|
||||
начальный mutable word `26` равны `0x7f7fffff`. Это подтверждает Rust full-load
|
||||
результат на оригинальных ресурсах, но не совпадение с полным нативным load
|
||||
оригинала. Поведение позже при placement/tick и физический смысл raw-полей
|
||||
остаётся неизвестным. Точные RVA, owner layout и векторы приведены в
|
||||
[описании изолированного прохода FAC0](script-vm.md#изолированный-проход-fac0).
|
||||
Полный Rust loader теперь выполняет FAC0, затем FCA0 при построении
|
||||
`build_control_device_projection_with_class`. `MissionControlOwnerProfile::load_projection`
|
||||
сохраняет отдельный результат FAC0, а `fca0_projection` — статус следующего
|
||||
прохода. FCA0 проверяет класс **владельца** `owner +0x50`: класс `9` сразу
|
||||
возвращает неизменённую копию; это не условие по device factory tag `9`. Любой
|
||||
известный класс, отличный от `9`, включая `0`, проходит общий расчёт. В Rust
|
||||
`MissingNativeControlClass` означает, что проекция не восстановила метаданные
|
||||
класса, а не то, что оригинальная DLL не содержит класс. `Fac0Unavailable`
|
||||
применяется только к не-классу-9 ветви, потому что класс `9` выходит до проверки
|
||||
FAC0.
|
||||
|
||||
Остаётся сравнить этот полный mine load с original loader при тех же входных
|
||||
данных и продолжить трассировку `LoadControlSystem`, `LoadPhysicalModel`,
|
||||
`CreateCollManager` и collision objects, если потребуется связать profile words
|
||||
с shapes, contacts или реакцией на движение.
|
||||
FCA0 суммирует selector `0xe00` в обратном порядке по устройствам с текущим
|
||||
descriptor tag `5`. Изолированный x86-вектор исполняет оригинальный reader
|
||||
`0x21d00` и FCA0. Статическая проверка двух factory vtables подтверждает общий
|
||||
reader `0x21d00` и setter `0x21d50` для tags `5`/`26`; provider getter `0x0dc40`
|
||||
использует `owner +4`, а canonical `QueryInterface(0x204)` задаёт
|
||||
`owner +0x38 -> owner +0x0c`.
|
||||
В каноническом constructor/event-4 пути scalar `+0x1a8` и means `+0x354/+0x358`
|
||||
равны `1.0`. На исходном Control.dll с SHA-256
|
||||
`bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e` FCA0
|
||||
подтверждена по RVA `0x0fca0` при x87 control word `0x007f`. Слова
|
||||
`[0,1,2,6,7,8,9,10,11]` в canonical-default векторе имеют биты
|
||||
`40200000 c0a00000 40c00000 3f800000 40000000 41200000 41e70000 c22d4000 40e70000`.
|
||||
|
||||
Лицензированный тест `full_load_builds_effective_control_device_table_for_mine_unit_dat`
|
||||
настоящего `min_l_n1.dat` теперь проверяет class `3`, `fca0_projection = Ok(())`,
|
||||
11 устройств и все 25 provider rows. Его девять target words
|
||||
`[0,1,2,6,7,8,9,10,11]` равны
|
||||
`40000000 40000000 40000000 00000000 00000000 00000000 00000000 00000000 00000000`;
|
||||
word `26` после FAC0 остаётся `0x7f7fffff`, а оригинальный блок, FAC0 агрегаты
|
||||
`0x470833fc/0x4897e712/0x4d9452cb` и 25 значений строк сохраняются. Это Rust
|
||||
full-load результат на оригинальных ресурсах, а не сравнение полного native
|
||||
Unit DAT loader-а или gameplay. Rust helper поддерживает только конечные входы
|
||||
и промежуточные значения домена `normal-or-zero`; прочие битовые случаи остаются
|
||||
вне заявленного диапазона.
|
||||
|
||||
Полный динамический жизненный цикл после начальной загрузки не подтверждён:
|
||||
поздние изменения owner scalar/means, activation, игровые часы, Control tick и
|
||||
placement не сведены в одну проверенную трассу и не включены в Rust-проекцию.
|
||||
Отдельные constructor, setter и loader-пути уже прослежены; физические единицы
|
||||
слов профиля и накопителей остаются неизвестны. Для закрытия границы нужны
|
||||
динамическая трассировка и сравнение полного Unit DAT load с оригинальным
|
||||
loader-ом при одинаковых ресурсах и условиях.
|
||||
Подробные RVA, QI/provider layout, арифметика и пределы векторов приведены в
|
||||
[описании изолированного прохода FAC0](script-vm.md#изолированный-проход-fac0)
|
||||
и [разборе FCA0](script-vm.md#изолированный-проход-fca0).
|
||||
|
||||
## DirectPlay wire
|
||||
|
||||
|
||||
@@ -1105,15 +1105,143 @@ scales `[1, 1, 1]`. Это подтверждено только для обыч
|
||||
rebind; отдельные AddNewObject/mirror scale setters и более поздние placement/
|
||||
tick пути в этот вывод не входят.
|
||||
|
||||
Теперь полный Rust loader вызывает FAC0 в `build_control_device_projection`
|
||||
после сборки provider rows и устройств. Игнорируемый тест
|
||||
`full_load_builds_effective_control_device_table_for_mine_unit_dat` прогнан на
|
||||
лицензированном `min_l_n1.dat`: он проверяет 11 устройств, сопоставление всех
|
||||
25 provider rows и весь упорядоченный вектор `row +0x20`. Агрегаты mine равны
|
||||
`+0x530 = 0x470833fc`, `+0x534 = 0x4897e712`, `+0x538 = 0x4d9452cb`; исходное и
|
||||
начальное mutable word `26` оба равны `0x7f7fffff`. Это измеренный результат
|
||||
Rust loader-а на оригинальных ресурсах, но не сравнение полного load результата
|
||||
с оригинальным loader-ом. Имена и физические единицы полей остаются неизвестны.
|
||||
Теперь полный Rust loader вызывает FAC0 и затем FCA0 в
|
||||
`build_control_device_projection_with_class`, после сборки provider rows и устройств.
|
||||
`MissionControlOwnerProfile::load_projection` и `fca0_projection` хранят
|
||||
отдельные статусы этих проходов. Игнорируемый тест
|
||||
`full_load_builds_effective_control_device_table_for_mine_unit_dat` на
|
||||
лицензированном `min_l_n1.dat` проверяет 11 устройств, 25 provider rows, весь
|
||||
упорядоченный вектор `row +0x20`, три FAC0 агрегата и результат FCA0. Агрегаты
|
||||
mine равны `+0x530 = 0x470833fc`, `+0x534 = 0x4897e712`,
|
||||
`+0x538 = 0x4d9452cb`; исходное и начальное mutable word `26` оба равны
|
||||
`0x7f7fffff`. Девять слов FCA0 по индексам `[0,1,2,6,7,8,9,10,11]` равны
|
||||
`[40000000,40000000,40000000,00000000,00000000,00000000,00000000,00000000,00000000]`.
|
||||
Это измеренный результат Rust loader-а на оригинальных ресурсах, но не
|
||||
сравнение полного load результата с оригинальным loader-ом. Имена и физические
|
||||
единицы полей остаются неизвестны.
|
||||
|
||||
#### Изолированный проход FCA0
|
||||
|
||||
`Control.dll` SHA-256
|
||||
`bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e`
|
||||
вызывает `FUN_1000fca0` (RVA `0x0fca0`) после `FUN_1000f940` и `FUN_1000fac0`
|
||||
в каноническом обработчике event `4/null`. Входной класс Control читается из
|
||||
`owner +0x50`. Первая проверка FCA0 (`0xfca6`) немедленно возвращается при
|
||||
классе `9`; после этой проверки для такого класса нет чтений или записей
|
||||
профиля, таблицы либо модели. Это класс владельца, а не factory tag отдельного
|
||||
устройства. Все известные классы, отличные от `9`, включая `0`, входят в общий
|
||||
путь; отсутствие класса в Rust проекции выдаёт `MissingNativeControlClass` и не
|
||||
означает, что его нет в оригинальном объекте. `Fac0Unavailable` относится
|
||||
только к этому общему, не-классу-9 пути: класс `9` завершает FCA0 до проверки
|
||||
FAC0.
|
||||
|
||||
На каноническом Unit DAT пути host получает `QueryInterface(0x204)` и передаёт
|
||||
результат в `owner +0x38`. Проверенная цепочка через Agent и CBuilding приводит
|
||||
к интерфейсу `owner +0x0c`; его vtable `0x3d1b4` имеет count slot `+0x0c ->
|
||||
0x8830`, query slot `+0x18 -> 0x2bb40` и getter текущего descriptor tag
|
||||
`+0x20 -> 0x2c390`. Этот интерфейс уже привязан до FAC0/FCA0.
|
||||
|
||||
Функция `0x2bb40` выбирает E00 reader `0x100` для текущего tag `5` и reader
|
||||
`0x300` для текущего tag `26`. У factory `5` vtable `0x3cdf8`, у factory `26`
|
||||
vtable `0x3ce38`; обе таблицы указывают на общий `FUN_10021d00` в slot `+0x10`
|
||||
и `FUN_10021d50` в slot `+0x1c`. Factory `26` в dispatch `0x2d4b0` также
|
||||
использует конструктор `0x20800`, как и factory `5`. Поэтому все четыре пары
|
||||
current tag/factory tag `(5,5)`, `(5,26)`, `(26,5)` и `(26,26)` используют
|
||||
доказанные методы. E00 для текущего tag `5` считает
|
||||
`coefficient[0] * provider.current_type1`; он не использует `M` по `+0x4c` и
|
||||
descriptor word `8`. Текущий tag `26` тем же общим reader-ом дополнительно
|
||||
умножает на `M`. Это правило не меняет отдельные callbacks бюджета или запись
|
||||
factory-26 selector `0x500`.
|
||||
|
||||
FCA0 передаёт в owner query порядковый номер `i`; query `0x2bb40` находит
|
||||
устройство `i` и вызывает его reader. Уже reader `FUN_10021d00` получает provider
|
||||
key из поля устройства `+0x04`. Provider getter `FUN_1000dc40` (RVA `0x0dc40`)
|
||||
получает `this = owner +4`, читает таблицу по `owner +0x55c`, а ключ выбирает
|
||||
строку `table + key*0x2c`; текущее type-1 значение находится по `+0x14` строки.
|
||||
Индекс устройства и ключ provider row — разные значения с разными задачами.
|
||||
|
||||
Конструктор owner `FUN_10006bf0` (RVA `0x6bf0`) задаёт scalar `+0x1a8 = 1.0`
|
||||
и вызывает `FUN_10014260`, который записывает `1.0` в `+0x354/+0x358`.
|
||||
Проверенные ветви канонического event `4/null` и FAC0 не меняют эти три поля
|
||||
до FCA0. Это подтверждённые defaults начального прохода; значения после
|
||||
activation, update или иных host writes здесь не проверялись.
|
||||
|
||||
Для любого не-класса-9 пути начинается нулевая сумма. Устройства посещаются в
|
||||
обратном порядке; только текущий descriptor tag `5` отправляется в selector
|
||||
`0xe00`. При успешном native query его `f32`-результат прибавляется к сумме и
|
||||
сразу сохраняется обратно в `f32` stack slot:
|
||||
|
||||
```text
|
||||
sum = 0.0f
|
||||
for i = device_count - 1 down to 0:
|
||||
if current_tag(i) == 5 and query(i, 0xe00) succeeds:
|
||||
sum = f32(sum + e00(i))
|
||||
```
|
||||
|
||||
Затем из `+0x354/+0x358` вычисляется mean и `weight = mean * sum`. Отношение
|
||||
`r = current[26] / original[26]` задаёт два сохранённых в `f32` коэффициента:
|
||||
`factorA = (r + 1) * 0.5` и `factorB = r * 0.75 + 0.25`. Упрощённая запись ниже
|
||||
сохраняет порядок зависимостей, но не показывает границы x87 spill:
|
||||
|
||||
```text
|
||||
for i in 6..9:
|
||||
value = owner[0x1a8] * original[i]
|
||||
value = value * weight
|
||||
value = value * factorA
|
||||
cap = original[i]
|
||||
if cap < abs(value):
|
||||
value = -cap if value < 0 else cap
|
||||
current[i] = value
|
||||
|
||||
for i in 9..12:
|
||||
value = original[i] * weight
|
||||
value = value * factorB
|
||||
current[i] = value + value
|
||||
|
||||
for i in 0..3:
|
||||
current[i] = original[i] + original[i]
|
||||
```
|
||||
|
||||
В первом триплете scalar умножается на слова `6..8`, затем результат умножается
|
||||
на `weight` и `factorA`; промежуточные значения слов `6` и `7` сохраняются в
|
||||
f32 slots между операциями, а слово `8` дольше остаётся в x87. Во втором
|
||||
триплете сначала умножаются исходное слово и `weight`, затем `factorB`, затем
|
||||
значение удваивается; первые два промежуточных произведения сохраняются, третье
|
||||
остаётся в x87. После этих триплетов слова `0..2` удваиваются из исходного блока.
|
||||
Точные spill-границы видны в RVA `0xfca0..0xfef9`. Native-векторы исполнялись
|
||||
при x87 control word `0x007f`.
|
||||
|
||||
Ограничитель срабатывает, когда исходный cap с сохранённым знаком меньше
|
||||
`abs(value)`. Тогда ветвь проверяет `value < 0`: при отрицательном значении
|
||||
результат равен `-cap`, иначе — `cap`; в `else` входят и `+0`, и `-0`.
|
||||
Поскольку cap сохраняет знак оригинального слова, отрицательная граница может
|
||||
развернуть знак результата.
|
||||
|
||||
Построенный helper считает из копии, уже подготовленной FAC0; исходный массив
|
||||
профиля остаётся отдельным. Его результат публикуется только при полном успехе,
|
||||
поэтому ошибка FCA0 не оставляет частично записанных слов. В публичной модели
|
||||
`load_projection` остаётся результатом FAC0, а `fca0_projection` хранит только
|
||||
статус FCA0. Rust ограничивает эту арифметику конечными normal-or-zero входами
|
||||
и промежуточными значениями: NaN, бесконечности, subnormal и промежуточные
|
||||
результаты вне поддерживаемого диапазона f32 отклоняются. Это граница модели
|
||||
Rust, а не доказательство того, что оригинал не принимает такие биты.
|
||||
|
||||
Оригинальная FCA0 и методы DLL дали следующий canonical-default x86-вектор на
|
||||
синтетической backing-памяти: класс `3`, E00 `[6, -0.75]`, scalar и оба mean
|
||||
равны `1`, `current[26]/original[26] = 6/4`. Слова
|
||||
`[0,1,2,6,7,8,9,10,11]` после прохода равны:
|
||||
|
||||
```text
|
||||
40200000 c0a00000 40c00000 3f800000 40000000 41200000 41e70000 c22d4000 40e70000
|
||||
```
|
||||
|
||||
Этот вектор подтверждает функцию на оригинальной DLL и выбранных getter-ах, но
|
||||
не выполняет полный native Unit DAT loader или игровой цикл. Licensed mine-тест
|
||||
отдельно проверяет Rust full-load: class `3`, `fca0_projection = Ok(())`, все
|
||||
11 устройств и 25 provider rows; слова `[0,1,2,6,7,8,9,10,11]` равны
|
||||
`40000000 40000000 40000000 00000000 00000000 00000000 00000000 00000000 00000000`.
|
||||
FAC0 агрегаты и строки сохраняются. Поздние динамические scalar/mean, activation,
|
||||
Control tick, placement и сравнение полного native load остаются открытыми.
|
||||
|
||||
#### Входной класс Control при загрузке Unit DAT
|
||||
|
||||
|
||||
+87
-28
@@ -717,33 +717,89 @@ Rust full-loader теста на оригинальных ресурсах. Ве
|
||||
`None`, без дочернего fallback или синтетических нулей. Точные native writes и
|
||||
открытые вопросы о смысле полей приведены в [техническом разборе загрузки CTLD](../appendices/script-vm.md#профиль-владельца-control-при-загрузке-ctld).
|
||||
|
||||
Изолированный x86-вектор подтвердил общий проход `Control.dll!FUN_1000fca0`
|
||||
(RVA `0x0fac0`): расчёт начинает с исходного profile word 26, а затем пишет
|
||||
производное значение в изменяемую копию и заполняет три поля-накопителя
|
||||
владельца, а также `+0x20` каждой строки provider. Для этого выбираются два
|
||||
сырых слова `Slot68` через `Node38` state 0 / LOD 0, учитываются cache tag 27 и
|
||||
устройства таблицы.
|
||||
Смысл слов `Slot68` и итоговых чисел не установлен; мы не называем их массой
|
||||
или площадью.
|
||||
Изолированный x86-вектор подтвердил общий проход `Control.dll!FUN_1000fac0`
|
||||
(RVA `0x0fac0`): этот шаг FAC0 начинает с исходного profile word 26, затем
|
||||
заполняет три накопителя владельца и поле `+0x20` provider rows. Для него
|
||||
выбираются два сырых слова `Slot68` через `Node38` state 0 / LOD 0, учитываются
|
||||
cache tag 27 и устройства таблицы. Смысл `Slot68` и итоговых чисел не
|
||||
установлен; мы не называем их массой или площадью.
|
||||
|
||||
Rust повторяет эту формулу изолированным helper-ом, и его тест совпадает с
|
||||
оригинальным кодом на синтетических векторах при x87 control word `0x007f`.
|
||||
В обычной цепочке загрузки AniMesh начинает с масштабов `[1, 1, 1]`, а вызванные
|
||||
до FAC0 обработчики привязки модели, FX и collision-компонентов эти поля не
|
||||
меняют. Поэтому загрузчик использует подтверждённые значения конструктора, а
|
||||
не scale из TMA. Теперь `build_control_device_projection` выполняет FAC0 после
|
||||
сборки provider rows и списка устройств и публикует результат вместе с копией
|
||||
профиля владельца.
|
||||
Для обычной начальной загрузки AniMesh создаёт scale `[1, 1, 1]`. Проверенные
|
||||
обработчики модели, FX и столкновений до FAC0 его не меняют. Поэтому первый
|
||||
проход получает значения конструктора, а не scale, записанный в TMA. Отдельные
|
||||
маршруты создания и последующее размещение объекта остаются другими путями.
|
||||
|
||||
### Начальная FCA0-проекция профиля
|
||||
|
||||
После FAC0 оригинальная Control выполняет второй проход FCA0 и обновляет только
|
||||
выбранные слова отдельной изменяемой копии. Условие раннего выхода проверяет
|
||||
**класс владельца Control**: класс `9` сразу пропускает FCA0. Это не тег
|
||||
фабрики отдельного устройства `9`: в
|
||||
лицензированном mine-профиле есть устройство с factory tag `9`, но класс
|
||||
владельца равен `3`, поэтому FCA0 выполняется. Любой известный класс, отличный
|
||||
от `9`, включая `0`, идёт по общему пути. Если Rust не смог вывести класс из
|
||||
ресурсной цепочки, он возвращает отдельный статус; это означает отсутствие
|
||||
проекции в Rust, а не отсутствие класса в оригинальной DLL.
|
||||
|
||||
На начальном пути конструктор задаёт scalar и два средних значения как `1.0`.
|
||||
Устройства читаются с конца списка;
|
||||
в сумму попадают только записи с текущим descriptor tag `5`. Их `0xe00`
|
||||
значение использует ключ устройства и `current_type1` соответствующей строки
|
||||
provider. Читатели фабрик `5` и `26` общие; для текущего tag `5` формула
|
||||
`coefficient[0] * provider.current_type1` не использует ни multiplier `M`, ни
|
||||
descriptor word `8`. Ветки current tag `26` дополнительно умножают на `M`, но
|
||||
не участвуют в сумме FCA0, которая фильтрует текущий tag `5`.
|
||||
|
||||
Упрощённая карта зависимостей показывает, почему важен порядок обхода и какие
|
||||
слова меняются; строки формул сами по себе не задают порядок native-вычислений:
|
||||
|
||||
```text
|
||||
sum = 0
|
||||
for index in reverse(0..device_count):
|
||||
if current_tag(index) == 5:
|
||||
sum = f32(sum + query_e00(index))
|
||||
|
||||
mean = (mean_a + mean_b) * 0.5
|
||||
weight = mean * sum
|
||||
r = current[26] / original[26]
|
||||
A = (r + 1) * 0.5
|
||||
B = r * 0.75 + 0.25
|
||||
current[0..3] = 2 * original[0..3]
|
||||
current[6..9] = native_signed_cap(original[6..9] * scalar * weight * A)
|
||||
current[9..12] = 2 * (original[9..12] * weight * B)
|
||||
```
|
||||
|
||||
Порядок x87 операций и spill границы приведены в техническом описании. Нативный
|
||||
ограничитель срабатывает, когда исходный cap с сохранённым знаком меньше
|
||||
`abs(value)`. Тогда проверяется `value < 0`: отрицательное значение даёт `-cap`,
|
||||
иначе возвращается `cap`; ветвь `else` включает `+0` и `-0`. Поэтому
|
||||
отрицательный cap способен изменить знак выхода.
|
||||
Здесь в query передаётся порядковый номер устройства; его getter уже сам
|
||||
использует ключ устройства для выбора строки provider. Точный порядок чтений,
|
||||
промежуточных записей и проверки приведён в
|
||||
[техническом разборе FCA0](../appendices/script-vm.md#изолированный-проход-fca0).
|
||||
|
||||
Rust хранит исходные слова отдельно, считает кандидата из копии после FAC0 и
|
||||
публикует слова FCA0 только после полного успеха. Статус `load_projection`
|
||||
остаётся результатом FAC0, а `fca0_projection` отдельно сообщает исход
|
||||
следующего прохода; ошибка FCA0 сохраняет уже подготовленную FAC0-копию.
|
||||
Обычный путь подтверждён при x87 control word `0x007f` для конечных normal-or-zero
|
||||
входов и промежуточных значений. Реализация не утверждает поддержку
|
||||
денормализованных, NaN, бесконечных или выходящих за диапазон промежуточных
|
||||
значений.
|
||||
|
||||
Оригинальная FCA0 и выбранные getters совпали на изолированном x86-векторе;
|
||||
точные raw bits, module hash, вызовы и ABI приведены в технической главе.
|
||||
|
||||
Игнорируемый corpus-тест полного загрузчика на оригинальном
|
||||
`UNITS/BUILDS/MINE/min_l_n1.dat` подтверждает сопоставление всех 25 provider
|
||||
rows с начальными узлами и проекцию 11 устройств. Для профиля mine получены
|
||||
агрегаты `+0x530 = 0x470833fc`, `+0x534 = 0x4897e712` и
|
||||
`+0x538 = 0x4d9452cb`; тест сверяет также все 25 значений строк. Это результат
|
||||
Rust loader-а на лицензированных данных, а не сравнение с полным native load
|
||||
оригинала. Смысл слов `Slot68` и итоговых чисел по-прежнему неизвестен. Точные
|
||||
входы, вектор и границы приведены в
|
||||
[техническом разборе загрузки CTLD](../appendices/script-vm.md#изолированный-проход-fac0).
|
||||
`UNITS/BUILDS/MINE/min_l_n1.dat` теперь проверяет class `3`, успешный статус FCA0,
|
||||
все 11 устройств, 25 provider rows, FAC0 snapshots и девять выходных слов.
|
||||
Для mine-профиля первый триплет FCA0 даёт `[2, 2, 2]`, два следующих — нули;
|
||||
не все целевые слова обязаны отличаться от исходных. Тест также сохраняет все
|
||||
11 устройств, 25 provider rows и результаты FAC0. Это проверка Rust loader-а
|
||||
на оригинальных лицензированных ресурсах, а не сравнение полного native Unit
|
||||
DAT load или gameplay. Поздние изменения means/scalar, activation, tick и
|
||||
placement остаются отдельными открытыми вопросами.
|
||||
|
||||
Для tag `19` фабрика создаёт объект с его исходными классом и vtable. Базовый
|
||||
конструктор `FUN_100218b0` задаёт multiplier `+0x4c = 1.0`. Override через
|
||||
@@ -940,10 +996,13 @@ Preview не загружает профили.
|
||||
`FUN_100198e0` (RVA `0x198e0`) суммирует их успешные `0xe00` запросы. FParkan
|
||||
делает то же для загруженной таблицы в её исходном порядке и затем умножает
|
||||
сумму на профильный `Transfer_Ore_OffBoard`. Записи tag `5`, `10` и `21` в общей
|
||||
таблице в этот список не попадают. Запрос `0xe00` проходит по ключу устройства
|
||||
в исходную provider-таблицу и пока поддержан только для текущего descriptor
|
||||
tag `26` с factory tag `26`; для него результат равен
|
||||
`provider * fixed_words[11] * multiplier`. Лицензированный тест загружает
|
||||
таблице в этот список не попадают. Это фильтр самого `0x1002`, а не ограничение
|
||||
доступности общего Control-запроса `0xe00`: он поддержан для текущих descriptor
|
||||
tags `5` и `26` с factory tags `5` и `26`. Owner query получает порядковый
|
||||
номер устройства; getter использует ключ этого устройства, чтобы выбрать строку
|
||||
provider. Для current tag `5` значение равно `coefficient[0] * provider`, без
|
||||
множителя `M` и descriptor word `8`; для current tag `26` результат равен
|
||||
`provider * coefficient[0] * M`. Лицензированный тест загружает
|
||||
оригинальные CTL/NDP и полную миссию с этим Unit DAT. В установленном
|
||||
`min_l_n1.dat` class word равен `0x80000004`, поэтому исходный прогон выбирает
|
||||
`prof_mine.var`. Для проверки другого отображения второй прогон оставляет тот же
|
||||
|
||||
Reference in new issue
Block a user