aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-12-01 07:33:51 +0300
committerValentin Popov <valentin@popov.link>2026-12-01 07:33:51 +0300
commit777f48345c7faf891ac105fc4a831114914aff5d (patch)
treea9e550c582aa976d87e6c0ae4297e7c29e6e5526 /crates/fparkan-runtime/src
parent352026c1ce039443efc779876b27654d992bfff1 (diff)
downloadfparkan-777f48345c7faf891ac105fc4a831114914aff5d.tar.xz
fparkan-777f48345c7faf891ac105fc4a831114914aff5d.zip
fix(combat): charge the drive before refilling weapons
Read the resource multiplier from CTL when all authored states agree and price the latest local motion in the existing Control budget. A licensed AutoDemo flyer charges its weapons more slowly when the drive is drawing from the same supply. Control.dll oracle vectors, the AutoDemo window, and all 29 mission startup sweeps pass.
Diffstat (limited to 'crates/fparkan-runtime/src')
-rw-r--r--crates/fparkan-runtime/src/control_resources.rs35
-rw-r--r--crates/fparkan-runtime/src/lib.rs20
-rw-r--r--crates/fparkan-runtime/src/mobile_budget.rs196
3 files changed, 236 insertions, 15 deletions
diff --git a/crates/fparkan-runtime/src/control_resources.rs b/crates/fparkan-runtime/src/control_resources.rs
index e34a3dfc..0b1f853b 100644
--- a/crates/fparkan-runtime/src/control_resources.rs
+++ b/crates/fparkan-runtime/src/control_resources.rs
@@ -1,11 +1,11 @@
use crate::{
- control_profile, control_resource_budget_pass, repair_zone, ControlProfileReport, Engine,
- MissionControlDeviceTableStatus, MobileBudgetReport,
+ control_profile, control_resource_budget_pass_with_motion, mobile_budget::DriveMotion,
+ repair_zone, ControlProfileReport, Engine, MissionControlDeviceTableStatus, MobileBudgetReport,
};
-use fparkan_world::{transform_state, ObjectHandle};
+use fparkan_world::{transform_state, ObjectHandle, TransformState};
use std::collections::BTreeMap;
-/// Supported Control budgets; motion callbacks and global RNG ordering remain open.
+/// Supported Control budgets and per-owner resource clocks.
pub(super) struct Resources {
clocks: Vec<(ObjectHandle, ResourceClock)>,
rng: u32,
@@ -109,6 +109,8 @@ pub(super) fn tick(engine: &mut Engine, now_ms: u32) {
.expect("new Control resource clock")
.1
};
+ let frame_seconds = (now_ms as f32 - clock.frame_ms) * 0.001;
+ let previous_pose = clock.previous_pose.replace(pose);
// Control.dll+0x42480: default resource period; this is a separate RNG from Behavior.
let Some(seconds) = clock.step(now_ms as f32, true, 250.0, &mut state.rng) else {
continue;
@@ -160,7 +162,20 @@ pub(super) fn tick(engine: &mut Engine, now_ms: u32) {
}
}
}
- match control_resource_budget_pass(table, seconds) {
+ let motion = previous_pose.filter(|_| mobile_owner).and_then(|previous| {
+ let can_fly = table
+ .original_id
+ .and_then(|id| mission.unit_chassis_flags.get(&id.0))
+ .and_then(|flags| flags.can_fly)?;
+ DriveMotion::sample(
+ table,
+ &mission.mission_assets,
+ [previous, pose],
+ frame_seconds,
+ can_fly,
+ )
+ });
+ match control_resource_budget_pass_with_motion(table, seconds, motion) {
Ok(()) => {
state
.blocked_budgets
@@ -169,10 +184,11 @@ pub(super) fn tick(engine: &mut Engine, now_ms: u32) {
*state.mobile.ticks.entry(object).or_default() += 1;
if let MissionControlDeviceTableStatus::Available(devices) = &table.status {
for device in devices {
- if device.factory_tag == 5 && device.native_word_50_bits != Some(0) {
- state
- .mobile
- .stub(object, format!("motion_factory_{}", device.factory_tag));
+ if motion.is_none()
+ && device.factory_tag == 5
+ && device.native_word_50_bits != Some(0)
+ {
+ state.mobile.stub(object, "motion_factory_5".into());
}
if matches!(device.factory_tag, 2 | 30)
&& f32::from_bits(device.descriptor.fixed_words[8]) != 0.0
@@ -220,6 +236,7 @@ pub(super) fn tick(engine: &mut Engine, now_ms: u32) {
#[derive(Default)]
struct ResourceClock {
frame_ms: f32,
+ previous_pose: Option<TransformState>,
resource_ms: f32,
forced: u32,
alarm: control_profile::DamageAlarm,
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 5f3f436e..0ac5197f 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -4496,10 +4496,18 @@ fn control_resource_budget_pass(
table: &mut MissionControlDeviceTableState,
delta_time_seconds: f32,
) -> Result<(), ControlResourceAccessError> {
+ control_resource_budget_pass_with_motion(table, delta_time_seconds, None)
+}
+
+fn control_resource_budget_pass_with_motion(
+ table: &mut MissionControlDeviceTableState,
+ delta_time_seconds: f32,
+ motion: Option<mobile_budget::DriveMotion>,
+) -> Result<(), ControlResourceAccessError> {
let delta_time_seconds =
checked_control_float(0, "Control resource interval", delta_time_seconds)?;
let mut updated = table.clone();
- control_resource_budget_pass_inner(&mut updated, delta_time_seconds)?;
+ control_resource_budget_pass_inner(&mut updated, delta_time_seconds, motion)?;
*table = updated;
Ok(())
}
@@ -4507,6 +4515,7 @@ fn control_resource_budget_pass(
fn control_resource_budget_pass_inner(
table: &mut MissionControlDeviceTableState,
delta_time_seconds: f32,
+ motion: Option<mobile_budget::DriveMotion>,
) -> Result<(), ControlResourceAccessError> {
let device_count = match &table.status {
MissionControlDeviceTableStatus::Available(devices) => devices.len(),
@@ -4534,7 +4543,12 @@ fn control_resource_budget_pass_inner(
let mut positive_rate_sum = 0.0_f32;
for index in 0..device_count {
let device = control_budget_device(table, index)?;
- let rate = control_device_resource_rate(table, &device, delta_time_seconds)?;
+ let rate = match motion {
+ Some(motion) if device.factory_tag == 5 => {
+ motion.rate(table, device, delta_time_seconds)?
+ }
+ _ => control_device_resource_rate(table, device, delta_time_seconds)?,
+ };
if rate > 0.0 {
positive_rate_sum = checked_control_sum(
device.factory_tag,
@@ -8381,6 +8395,7 @@ mod tests {
PreparedComponentControl {
source: synthetic_resource_key(940),
native_profile_words: [0; 27],
+ uniform_drive_factor_bits: None,
model_node_count: 3,
bindings: Vec::new(),
timeline_rows: Vec::new(),
@@ -8888,6 +8903,7 @@ mod tests {
PreparedComponentControl {
source: synthetic_resource_key(100 + index),
native_profile_words: [0; 27],
+ uniform_drive_factor_bits: None,
model_node_count: 0,
bindings: Vec::new(),
timeline_rows: Vec::new(),
diff --git a/crates/fparkan-runtime/src/mobile_budget.rs b/crates/fparkan-runtime/src/mobile_budget.rs
index ee643cb1..06dc251e 100644
--- a/crates/fparkan-runtime/src/mobile_budget.rs
+++ b/crates/fparkan-runtime/src/mobile_budget.rs
@@ -4,8 +4,8 @@ use crate::{
checked_control_float, checked_control_product, checked_control_ratio, checked_control_sum,
control_budget_device, control_device_budget_active_provider_value,
control_device_budget_coefficient, control_device_budget_descriptor_float,
- ControlResourceAccessError, EffectiveControlDevice, MissionControlDeviceTableState,
- MissionControlDeviceTableStatus,
+ ControlResourceAccessError, EffectiveControlDevice, MissionAssets,
+ MissionControlDeviceTableState, MissionControlDeviceTableStatus, TransformState,
};
use std::collections::BTreeMap;
@@ -168,11 +168,91 @@ pub(super) fn passive_device_rate(
}
pub(super) fn unmodeled_motion_rate() -> f32 {
- // shortcut: Control motion vectors and +0x154 are not supplied by the
- // temporary movement controller. Resources counts this omission per owner.
+ // shortcut: omit demand where the live CTL state has not been recovered.
0.0
}
+#[derive(Clone, Copy)]
+pub(super) struct DriveMotion {
+ local_speed: f32,
+ profile_limit: f32,
+ state_factor: f32,
+}
+
+impl DriveMotion {
+ pub(super) fn sample(
+ table: &MissionControlDeviceTableState,
+ assets: &MissionAssets,
+ [previous, current]: [TransformState; 2],
+ frame_seconds: f32,
+ can_fly: bool,
+ ) -> Option<Self> {
+ let object = table.original_id?.0 as usize;
+ let profile = table.owner_profile.as_ref()?;
+ let control = assets
+ .object_component_controls
+ .get(object)?
+ .get(profile.unit_component_index)?
+ .as_ref()?;
+ let state_factor = f32::from_bits(control.uniform_drive_factor_bits?);
+ let limits = profile.original_words[6..9]
+ .iter()
+ .map(|&word| f32::from_bits(word));
+ let profile_limit = largest_component(limits)?;
+ let [dx, dy, dz] = std::array::from_fn(|axis| {
+ f32::from_bits(current.position[axis]) - f32::from_bits(previous.position[axis])
+ });
+ let (sin, cos) = f32::from_bits(current.orientation[2]).sin_cos();
+ // shortcut: use the frame's realized displacement until native motion publishes its local vector.
+ let local_speed = largest_component([
+ (cos * dx + sin * dy) / frame_seconds,
+ (-sin * dx + cos * dy) / frame_seconds,
+ if can_fly { dz / frame_seconds } else { 0.0 },
+ ])?;
+ (profile_limit > 0.0 && state_factor.is_finite() && !state_factor.is_subnormal()).then_some(
+ Self {
+ local_speed,
+ profile_limit,
+ state_factor,
+ },
+ )
+ }
+
+ pub(super) fn rate(
+ self,
+ table: &MissionControlDeviceTableState,
+ device: &EffectiveControlDevice,
+ seconds: f32,
+ ) -> Result<f32, ControlResourceAccessError> {
+ if control_device_budget_active_provider_value(table, device)?.is_none() {
+ return Ok(0.0);
+ }
+ self.demand(
+ control_device_budget_descriptor_float(device, 8, "drive rate")?,
+ seconds,
+ )
+ }
+
+ fn demand(self, descriptor_rate: f32, seconds: f32) -> Result<f32, ControlResourceAccessError> {
+ let fraction =
+ checked_control_ratio("drive speed fraction", self.local_speed, self.profile_limit)?;
+ let rate = checked_control_product(5, "drive nominal demand", fraction, descriptor_rate)?;
+ let rate = checked_control_product(5, "drive state demand", rate, self.state_factor)?;
+ Ok(-checked_control_product(
+ 5,
+ "drive interval demand",
+ rate,
+ seconds,
+ )?)
+ }
+}
+
+fn largest_component(values: impl IntoIterator<Item = f32>) -> Option<f32> {
+ values.into_iter().try_fold(0.0_f32, |largest, value| {
+ (value.is_finite() && !value.is_subnormal()).then(|| largest.max(value.abs()))
+ })
+}
+
pub(super) fn read(
mission: &crate::LoadedMissionState,
handle: crate::ObjectHandle,
@@ -283,6 +363,24 @@ mod tests {
use super::*;
#[test]
+ fn drive_demand_uses_largest_local_axis_and_the_ctl_factor() {
+ let profile_limit = largest_component([5.0, 14.0, 7.0]).unwrap();
+ for (velocity, state_factor, seconds, expected) in [
+ ([0.0, -7.0, 2.0], 0.8, 0.25, 0xbe80_0000),
+ ([-14.0, 1.0, 2.0], 1.0, 0.5, 0xbfa0_0000),
+ ([1.0, 2.0, -7.0], 1.0, 1.0, 0xbfa0_0000),
+ ([0.0, -7.0, 2.0], 0.0, 0.25, 0x8000_0000),
+ ] {
+ let motion = DriveMotion {
+ local_speed: largest_component(velocity).unwrap(),
+ profile_limit,
+ state_factor,
+ };
+ assert_eq!(motion.demand(2.5, seconds).unwrap().to_bits(), expected);
+ }
+ }
+
+ #[test]
fn native_weapon_budget_refills_disabled_devices_and_can_go_negative() {
// GOG Control.dll +0x29a40 / +0x29a90, x87 CW 0x007f.
for (capacity, amount, dt, upkeep, allocation, active, rate, charge, multiplier) in [
@@ -337,6 +435,96 @@ mod tests {
#[test]
#[ignore = "requires licensed corpus"]
+ fn licensed_autodemo_flyer_uses_its_drive_budget_in_motion() {
+ use crate::{
+ create, frame, load_gameplay_mission, EngineServices, MissionMode, MissionRequest,
+ MissionStartupInput,
+ };
+ use fparkan_vfs::DirectoryVfs;
+ use std::sync::Arc;
+
+ let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap();
+ let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap();
+ load_gameplay_mission(
+ &mut engine,
+ MissionRequest {
+ key: "MISSIONS/Autodemo.00/data.tma".into(),
+ mode: MissionMode::AutoDemo,
+ },
+ MissionStartupInput {
+ queue_time_ms: 0,
+ research_creation_gate: false,
+ },
+ None,
+ )
+ .unwrap();
+ engine.autodemo_combat = None;
+ let mission = engine.loaded.as_ref().unwrap();
+ let flyer = mission
+ .control_device_tables
+ .iter()
+ .position(|table| table.original_id == Some(fparkan_world::OriginalObjectId(2)))
+ .unwrap();
+ let handle = mission.control_device_tables[flyer].handle;
+ let start = fparkan_world::transform_state(&engine.world, handle)
+ .unwrap()
+ .position;
+ let mut drive_spent = false;
+ for now in (0..=6_000).step_by(100) {
+ frame(&mut engine, now).unwrap();
+ let mission = engine.loaded.as_ref().unwrap();
+ drive_spent |=
+ f32::from_bits(mission.control_device_tables[flyer].current_output_rate_5e0_bits)
+ > 0.0;
+ }
+ let end = fparkan_world::transform_state(&engine.world, handle)
+ .unwrap()
+ .position;
+ assert_ne!(start, end);
+ let stubs = &engine
+ .loaded
+ .as_ref()
+ .unwrap()
+ .control_resources
+ .mobile
+ .stubs;
+ assert!(!stubs.contains_key(&(2, "motion_factory_5".into())));
+ assert!(drive_spent, "motion must draw from the budget");
+
+ let mut at_rest = engine.loaded.as_ref().unwrap().control_device_tables[flyer].clone();
+ let MissionControlDeviceTableStatus::Available(devices) = &mut at_rest.status else {
+ panic!("stock flyer has a complete Control table");
+ };
+ for device in devices.iter_mut().filter(|device| device.factory_tag == 2) {
+ device.weapon_charge_bits = Some(0);
+ }
+ let mut in_motion = at_rest.clone();
+ crate::control_resource_budget_pass(&mut at_rest, 0.5).unwrap();
+ crate::control_resource_budget_pass_with_motion(
+ &mut in_motion,
+ 0.5,
+ Some(DriveMotion {
+ local_speed: 10.0,
+ profile_limit: 10.0,
+ state_factor: 1.0,
+ }),
+ )
+ .unwrap();
+ let charge = |table: &MissionControlDeviceTableState| {
+ let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
+ panic!("stock flyer has a complete Control table");
+ };
+ let weapon = devices
+ .iter()
+ .find(|device| device.factory_tag == 2)
+ .unwrap();
+ f32::from_bits(weapon.weapon_charge_bits.unwrap())
+ };
+ assert!(charge(&in_motion) < charge(&at_rest));
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
fn licensed_stock_lasers_wait_for_charge_and_recover_from_the_unit_budget() {
use crate::{
create, frame, load_gameplay_mission, EngineServices, MissionMode, MissionRequest,