From 85474bcd60f66b610985c90a697351837208528b Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Wed, 25 Nov 2026 19:41:17 +0400 Subject: fix(ai): advance clan cycles when units register Advance the signed AI deadline by 1400 ms when an active clan receives a new unit. Connect production, construction, mines, reinforcements and ownership transfers through the shared spawn path. Preserve negative deadlines and count registration notifications per clan. Move the common spawn code and result type out of AutoDemo without changing its public API. Native ai.dll calls cover duplicate and missing IDs, the disabled guard, both registration kinds, negative deadlines and unchanged RNG. A live original warbot registration confirms the same advance. Workspace checks, the licensed stock factory timing test and all 29 900-second reports pass; a stock mission-28 window runs through successive factory outputs. Initial clock phase, complete RNG ordering and full G7 chronology remain open. --- crates/fparkan-runtime/src/autodemo.rs | 61 +-------------- crates/fparkan-runtime/src/clan_ai_events.rs | 6 +- crates/fparkan-runtime/src/clan_clock.rs | 108 +++++++++++++++++++++++++-- crates/fparkan-runtime/src/construction.rs | 2 +- crates/fparkan-runtime/src/lib.rs | 10 +-- crates/fparkan-runtime/src/mining.rs | 6 +- crates/fparkan-runtime/src/mission_events.rs | 8 ++ crates/fparkan-runtime/src/production.rs | 11 ++- crates/fparkan-runtime/src/unit_spawn.rs | 63 ++++++++++++++++ 9 files changed, 193 insertions(+), 82 deletions(-) create mode 100644 crates/fparkan-runtime/src/unit_spawn.rs (limited to 'crates/fparkan-runtime') diff --git a/crates/fparkan-runtime/src/autodemo.rs b/crates/fparkan-runtime/src/autodemo.rs index 15338b0f..fe0bfd19 100644 --- a/crates/fparkan-runtime/src/autodemo.rs +++ b/crates/fparkan-runtime/src/autodemo.rs @@ -2,14 +2,14 @@ use super::{ component_cockpit, mission_object_handle, normalize_engine_path, read_vfs, Engine, EngineError, MissionControlDeviceTableState, MissionMode, StartingCockpit, World, WorldSnapshot, }; +use crate::unit_spawn::{spawn_prepared_unit, SpawnedUnit}; use fparkan_path::{normalize_relative, NormalizedPath, PathPolicy}; use fparkan_prototype::decode_unit_dat; use fparkan_render::{LegacyIron3dEulerTransform, RawCameraTransform}; use fparkan_terrain::{SurfaceQuery, TerrainWorld}; use fparkan_vfs::{Vfs, VfsError}; use fparkan_world::{ - construct_replacement, handle_by_original_id, identity_metadata, register_object, set_owner, - set_transform, transform_state, ObjectDraft, ObjectHandle, OwnerId, TransformState, + handle_by_original_id, identity_metadata, transform_state, ObjectHandle, OwnerId, }; use std::sync::Arc; @@ -47,17 +47,6 @@ pub(super) struct LiveReinforcements { controls: Vec, } -/// A reserve model activated with a newly registered world object. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct SpawnedUnit { - /// Prepared scene object index. - pub object_index: usize, - /// New world handle. - pub handle: ObjectHandle, - /// Clan receiving the replacement. - pub clan: u16, -} - /// A unit created by AutoDemo's replacement policy. pub type AutoDemoReinforcement = SpawnedUnit; @@ -175,52 +164,6 @@ impl LiveReinforcements { } } -pub(super) fn spawn_prepared_unit( - world: &mut World, - mission: &mut super::LoadedMissionState, - index: usize, - clan: u16, - position: [f32; 3], - mut table: MissionControlDeviceTableState, -) -> Result { - let draft = &mission.object_drafts[index]; - let handle = construct_replacement( - world, - ObjectDraft { - original_id: draft.original_id, - }, - )?; - let pose = TransformState { - position: position.map(f32::to_bits), - orientation: draft.orientation_raw.map(f32::to_bits), - scale: draft.scale.map(f32::to_bits), - }; - if let Err(error) = set_transform(world, handle, pose) - .and_then(|()| set_owner(world, handle, Some(OwnerId(clan)))) - .and_then(|()| register_object(world, handle)) - { - fparkan_world::request_delete(world, handle)?; - return Err(error.into()); - } - mission - .control_device_tables - .retain(|table| transform_state(world, table.handle).is_ok()); - mission - .behavior_control_groupings - .retain(|group| transform_state(world, group.handle).is_ok()); - table.handle = handle; - mission - .behavior_control_groupings - .push(super::project_mission_behavior_control_grouping(&table)); - mission.control_device_tables.push(table); - mission.mission_events.register_unit( - world, - handle, - draft.unit_dat_header_flags.expect("mobile reserve"), - ); - Ok(handle) -} - pub(super) fn plan_reinforcements( vfs: &Arc, mission: &super::MissionDocument, diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index fcb35ca7..be2d46fe 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -1575,7 +1575,11 @@ impl ClanAiEvents { } } - pub(super) fn clock_ticks(&self) -> impl Iterator + '_ { + pub(super) fn advance_for_registration(&mut self, clan: usize) -> u64 { + self.clocks.advance_for_registration(clan) + } + + pub(super) fn clock_ticks(&self) -> impl Iterator + '_ { self.clocks.ticks() } diff --git a/crates/fparkan-runtime/src/clan_clock.rs b/crates/fparkan-runtime/src/clan_clock.rs index 3a9a1a4f..f3ae89a8 100644 --- a/crates/fparkan-runtime/src/clan_clock.rs +++ b/crates/fparkan-runtime/src/clan_clock.rs @@ -1,18 +1,20 @@ use std::collections::BTreeMap; struct Clock { - deadline_ms: u32, + deadline_ms: i64, seconds: u32, ticks: u64, + registrations: u64, } impl Default for Clock { fn default() -> Self { Self { - // shortcut: the initial phase and registration's 1400 ms advance remain unwired. + // shortcut: keep the initial phase until a stock-start native comparison establishes it. deadline_ms: 7_000, seconds: 0, ticks: 0, + registrations: 0, } } } @@ -24,11 +26,11 @@ impl ClanClocks { /// ai.dll RVA 0x17ae: equality is not due; a late callback runs one cycle. pub(super) fn tick(&mut self, clan: usize, elapsed_ms: u32, rng: &mut u32) -> Option { let clock = self.0.entry(clan).or_default(); - if elapsed_ms <= clock.deadline_ms { + if i64::from(elapsed_ms) <= clock.deadline_ms { return None; } let jitter = crate::behavior_clock::next_crt_rand(rng) % 1_000; - clock.deadline_ms = elapsed_ms.wrapping_add(7_000 + jitter); + clock.deadline_ms = i64::from(elapsed_ms.wrapping_add(7_000 + jitter)); clock.seconds = clock.seconds.wrapping_add(7); clock.ticks += 1; if clock.ticks == 1 { @@ -37,8 +39,47 @@ impl ClanClocks { Some(clock.seconds) } - pub(super) fn ticks(&self) -> impl Iterator + '_ { - self.0.iter().map(|(&clan, clock)| (clan, clock.ticks)) + pub(super) fn advance_for_registration(&mut self, clan: usize) -> u64 { + let clock = self.0.entry(clan).or_default(); + clock.deadline_ms = clock.deadline_ms.wrapping_sub(1_400); + clock.registrations += 1; + clock.registrations + } + + pub(super) fn ticks(&self) -> impl Iterator + '_ { + self.0 + .iter() + .map(|(&clan, clock)| (clan, clock.ticks, clock.registrations)) + } +} + +impl crate::LoadedMissionState { + pub(super) fn note_clan_registration( + &mut self, + owner: fparkan_world::OwnerId, + unit: fparkan_world::ObjectHandle, + ) { + let clan = usize::from(owner.0); + if !self + .mission + .clans + .get(clan) + .is_some_and(|entry| entry.mode == 2) + || !self.script_bundles.iter().any(|bundle| { + bundle.clan_index == clan + && bundle.behavior_warm_start.is_some() + && bundle.package.events.iter().any(|event| { + event.name_raw == b"Problems0\0" && !event.instructions.is_empty() + }) + }) + { + return; + } + let count = self.clan_ai_events.advance_for_registration(clan); + eprintln!( + "script_clan_unit_registered clan={clan} unit={} generation={} count={count}", + unit.slot, unit.generation + ); } } @@ -69,6 +110,59 @@ mod tests { assert_eq!(clocks.tick(1, 100_000, &mut rng), Some(7)); assert_eq!(clocks.0[&1].deadline_ms, 107_041); assert_eq!(clocks.tick(1, 100_000, &mut rng), None); - assert_eq!(clocks.ticks().collect::>(), [(1, 1)]); + assert_eq!(clocks.ticks().collect::>(), [(1, 1, 0)]); + } + + #[test] + fn native_registration_shift_accumulates_and_a_negative_deadline_is_due() { + let mut clocks = ClanClocks::default(); + clocks.0.entry(1).or_default().deadline_ms = 8_000; + assert_eq!(clocks.advance_for_registration(1), 1); + assert_eq!(clocks.0[&1].deadline_ms, 6_600); + assert_eq!(clocks.advance_for_registration(1), 2); + assert_eq!(clocks.0[&1].deadline_ms, 5_200); + clocks.0.get_mut(&1).unwrap().deadline_ms = 500; + clocks.advance_for_registration(1); + assert_eq!(clocks.0[&1].deadline_ms, -900); + let mut rng = 1; + assert_eq!(clocks.tick(1, 0, &mut rng), Some(7)); + assert_eq!(clocks.0[&1].deadline_ms, 7_041); + assert_eq!(rng, 2_745_024); + assert_eq!(clocks.ticks().collect::>(), [(1, 1, 3)]); + } + + #[test] + #[ignore = "requires licensed mission resources"] + fn licensed_stock_factory_registration_brings_the_next_ai_cycle_forward() { + 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/Single.01/data.tma".into(), + mode: MissionMode::SingleMission, + }, + MissionStartupInput { + queue_time_ms: 0, + research_creation_gate: false, + }, + None, + ) + .unwrap(); + for now_ms in (0..=28_000).step_by(100) { + frame(&mut engine, now_ms).unwrap(); + } + let loaded = engine.loaded.as_ref().unwrap(); + assert_eq!( + loaded.clan_ai_events.clock_ticks().collect::>(), + [(1, 4, 1)] + ); + assert!(loaded.clan_ai_events.stops().next().is_none()); } } diff --git a/crates/fparkan-runtime/src/construction.rs b/crates/fparkan-runtime/src/construction.rs index 2061b446..f7925d05 100644 --- a/crates/fparkan-runtime/src/construction.rs +++ b/crates/fparkan-runtime/src/construction.rs @@ -1,4 +1,4 @@ -use crate::autodemo::spawn_prepared_unit; +use crate::unit_spawn::spawn_prepared_unit; use crate::{LoadedMissionState, MissionScriptBundle}; use fparkan_path::ResourceName; use fparkan_script::ScriptDispatchSelector; diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index b810eda8..c2c25634 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -80,10 +80,9 @@ mod script_time; mod unit_combat; mod unit_patrol; mod unit_size_class; +mod unit_spawn; -pub use autodemo::{ - autodemo_camera, AutoDemoCamera, AutoDemoReinforcement, AutoDemoView, SpawnedUnit, -}; +pub use autodemo::{autodemo_camera, AutoDemoCamera, AutoDemoReinforcement, AutoDemoView}; pub use boarding::{ board_friendly_warbot, disembark_warbot, player_vehicle, select_boarding_target, }; @@ -111,6 +110,7 @@ pub use projectile::{ }; pub use research::order_lab_research; pub use unit_combat::{AutoDemoCombatEvent, AutoDemoProjectileType}; +pub use unit_spawn::SpawnedUnit; const MISSION_DECODED_PAYLOAD_CACHE_ENTRIES: usize = 256; const MAX_MISSION_AI_RECORD_SLOTS: usize = 1_000_000; @@ -2917,8 +2917,8 @@ pub struct SimulationReport { pub mission_event_stops: Vec, /// Uncovered clan AI instructions and the number of invocations they stopped. pub clan_ai_event_stops: Vec<(MissionEventStop, u64)>, - /// Executed AI clock cycles by clan; initial phase and full RNG ordering remain approximate. - pub clan_ai_clock_ticks: Vec<(usize, u64)>, + /// Clan index, executed AI cycles and new registrations; initial phase and RNG order remain approximate. + pub clan_ai_clock_ticks: Vec<(usize, u64, u64)>, /// Calls to stubbed research policy or status, grouped by clan and handler. pub clan_research_status_stubs: Vec<(usize, u8, u64)>, pub clan_research_catalogs: Vec<(usize, usize, u32, u64)>, diff --git a/crates/fparkan-runtime/src/mining.rs b/crates/fparkan-runtime/src/mining.rs index 61266b9d..c3be7e07 100644 --- a/crates/fparkan-runtime/src/mining.rs +++ b/crates/fparkan-runtime/src/mining.rs @@ -1,7 +1,7 @@ use super::{ - add_behavior_registered_object, - autodemo::{spawn_prepared_unit, SpawnedUnit}, - behavior_ore_index_for_handle, BehaviorOreState, BehaviorRegisteredObject, Engine, EngineError, + add_behavior_registered_object, behavior_ore_index_for_handle, + unit_spawn::{spawn_prepared_unit, SpawnedUnit}, + BehaviorOreState, BehaviorRegisteredObject, Engine, EngineError, MissionControlDeviceTableState, MissionObjectDraft, StartingCockpit, }; use fparkan_assets::ExtraRecord28; diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs index 7d84eb68..db37851f 100644 --- a/crates/fparkan-runtime/src/mission_events.rs +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -444,6 +444,11 @@ pub fn capture_neutral_warbot( .min_by(|a, b| a.0.total_cmp(&b.0)); if let Some((_, handle, original_id)) = candidate { set_owner(&mut engine.world, handle, Some(player_owner))?; + engine + .loaded + .as_mut() + .expect("loaded mission") + .note_clan_registration(player_owner, handle); return Ok(Some(original_id)); } Ok(None) @@ -553,6 +558,9 @@ impl LoadedMissionState { class: u32, ) -> Result<(), EngineError> { set_owner(world, handle, Some(new_owner))?; + if former_owner != new_owner { + self.note_clan_registration(new_owner, handle); + } if has_behavior_registration_key(class) { let distributors = &mut self.behavior_distributors; if let Some(previous) = distributors.get_mut(usize::from(former_owner.0)) { diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs index 2375cf9d..a6752712 100644 --- a/crates/fparkan-runtime/src/production.rs +++ b/crates/fparkan-runtime/src/production.rs @@ -1,14 +1,13 @@ use super::{ - autodemo::{ - reinforcement_position, spawn_prepared_unit, SpawnedUnit, MOBILE_UNIT, PLANT_CLASS, - }, + autodemo::{reinforcement_position, MOBILE_UNIT, PLANT_CLASS}, behavior_ore_index_for_handle, mission_events::on_communicator, normalize_engine_path, query_behavior_profile_ore_rate, research::{load_clan_table, RESEARCHED}, - set_control_device_table_selector, BehaviorOreState, Engine, EngineError, LoadedMissionState, - MissionControlDeviceTableState, MissionControlDeviceTableStatus, MissionObjectDraft, - StartingCockpit, World, + set_control_device_table_selector, + unit_spawn::{spawn_prepared_unit, SpawnedUnit}, + BehaviorOreState, Engine, EngineError, LoadedMissionState, MissionControlDeviceTableState, + MissionControlDeviceTableStatus, MissionObjectDraft, StartingCockpit, World, }; use fparkan_assets::ResearchTrfDocument; use fparkan_path::NormalizedPath; diff --git a/crates/fparkan-runtime/src/unit_spawn.rs b/crates/fparkan-runtime/src/unit_spawn.rs new file mode 100644 index 00000000..4fd9e31e --- /dev/null +++ b/crates/fparkan-runtime/src/unit_spawn.rs @@ -0,0 +1,63 @@ +use crate::{EngineError, LoadedMissionState, MissionControlDeviceTableState}; +use fparkan_world::{ + construct_replacement, register_object, set_owner, set_transform, transform_state, ObjectDraft, + ObjectHandle, OwnerId, TransformState, World, +}; + +/// A reserve model activated with a newly registered world object. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct SpawnedUnit { + /// Prepared scene object index. + pub object_index: usize, + /// New world handle. + pub handle: ObjectHandle, + /// Clan receiving the replacement. + pub clan: u16, +} + +pub(super) fn spawn_prepared_unit( + world: &mut World, + mission: &mut LoadedMissionState, + index: usize, + clan: u16, + position: [f32; 3], + mut table: MissionControlDeviceTableState, +) -> Result { + let draft = &mission.object_drafts[index]; + let handle = construct_replacement( + world, + ObjectDraft { + original_id: draft.original_id, + }, + )?; + let pose = TransformState { + position: position.map(f32::to_bits), + orientation: draft.orientation_raw.map(f32::to_bits), + scale: draft.scale.map(f32::to_bits), + }; + if let Err(error) = set_transform(world, handle, pose) + .and_then(|()| set_owner(world, handle, Some(OwnerId(clan)))) + .and_then(|()| register_object(world, handle)) + { + fparkan_world::request_delete(world, handle)?; + return Err(error.into()); + } + mission + .control_device_tables + .retain(|table| transform_state(world, table.handle).is_ok()); + mission + .behavior_control_groupings + .retain(|group| transform_state(world, group.handle).is_ok()); + table.handle = handle; + mission + .behavior_control_groupings + .push(crate::project_mission_behavior_control_grouping(&table)); + mission.control_device_tables.push(table); + mission.mission_events.register_unit( + world, + handle, + draft.unit_dat_header_flags.expect("prepared reserve"), + ); + mission.note_clan_registration(OwnerId(clan), handle); + Ok(handle) +} -- cgit v1.2.3