diff options
| author | Valentin Popov <valentin@popov.link> | 2026-11-14 04:42:05 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-11-14 04:42:05 +0300 |
| commit | 796a64e61643936e3b4517eb365e95639e68aaa5 (patch) | |
| tree | 3b871386c87d5e7a7e39c1f810c59c6cb5e35552 /crates | |
| parent | 5f4eecaad3bfdf025e93f5c7276b0ba3f9b6db49 (diff) | |
| download | fparkan-796a64e61643936e3b4517eb365e95639e68aaa5.tar.xz fparkan-796a64e61643936e3b4517eb365e95639e68aaa5.zip | |
feat(runtime): dispatch the periodic Mission script event
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 63 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/mission_events.rs | 98 | ||||
| -rw-r--r-- | crates/fparkan-script/src/lib.rs | 159 |
3 files changed, 304 insertions, 16 deletions
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 186e4f73..1fa80aa5 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -43,10 +43,13 @@ use std::sync::Arc; mod autodemo; mod mesh_collision; +mod mission_events; pub use autodemo::{autodemo_camera, AutoDemoCamera, AutoDemoView}; pub use fparkan_assets::MissionAssets; pub use mesh_collision::{query_building_segment_world, BuildingMeshHit, BuildingMeshNode}; +use mission_events::MissionEvents; +pub use mission_events::{MissionEventStop, MissionEventTick}; const MISSION_DECODED_PAYLOAD_CACHE_ENTRIES: usize = 256; const MAX_MISSION_AI_RECORD_SLOTS: usize = 1_000_000; @@ -1254,6 +1257,8 @@ pub struct LoadedMission { pub struct FrameResult { /// Snapshot. pub snapshot: WorldSnapshot, + /// Periodic script event attempted on this step, if due. + pub mission_event: Option<MissionEventTick>, } /// Engine. @@ -1285,6 +1290,7 @@ struct LoadedMissionState { script_varset: Option<MissionScriptVarSet>, script_init_states: Vec<MissionScriptInitState>, script_varset_states: Vec<MissionScriptVarSetState>, + mission_events: MissionEvents, script_host_mode: MissionMode, script_host_status: u32, script_outcome: MissionScriptOutcome, @@ -2203,6 +2209,7 @@ fn load_mission_with_options( script_varset: loaded_scripts.varset, script_init_states: loaded_scripts.init_states, script_varset_states: loaded_scripts.varset_states, + mission_events: MissionEvents::default(), script_host_mode: request.mode, // Fresh IGame construction seeds this field with 5; this is not the // later status-4 transition performed after native game initialization. @@ -2230,8 +2237,8 @@ fn prepare_first_preview_assets<R: ResourceRepository>( /// Steps the world and due Behavior resource distributors at an explicit queue clock. /// /// Resource updates are prepared before queued world commands and deferred deletion, -/// and published only after the world step succeeds. This does not yet execute the -/// separate Control clock, movement, or general mission script handlers. +/// and published only after the world step succeeds. The periodic script event +/// then updates the active clan's varset through its supported numeric prefix. /// /// # Errors /// @@ -2247,7 +2254,14 @@ pub fn step_headless( if let Some(resources) = resources { resources.apply(engine); } - Ok(FrameResult { snapshot }) + let mission_event = engine + .loaded + .as_mut() + .and_then(|state| state.tick_mission_event(queue_time_ms)); + Ok(FrameResult { + snapshot, + mission_event, + }) } /// Steps rendered mode with the same queue-clock semantics as [`step_headless`]. @@ -2261,10 +2275,10 @@ pub fn frame(engine: &mut Engine, queue_time_ms: u32) -> Result<FrameResult, Eng /// Coverage entries for the subsystems still absent from the mission loop. pub const SIMULATION_COVERAGE: &str = - "sim_coverage research_startup_gate_stub=1 mission_handlers_stub=1 unit_behavior_stub=1 render_object_lifecycle_stub=1 render_winding_change_stub=1"; + "sim_coverage research_startup_gate_stub=1 mission_handlers_stub=1 unit_behavior_stub=1 render_object_lifecycle_stub=1 render_winding_change_stub=1 mission_event_clock_approx=1"; /// Totals from a headless mission coverage run. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq)] pub struct SimulationReport { /// Number of completed steps. pub ticks: u64, @@ -2272,6 +2286,10 @@ pub struct SimulationReport { pub live_objects: usize, /// World events processed over the run. pub world_events: u64, + /// Number of periodic event dispatches, including empty events. + pub mission_events: u64, + /// Distinct uncovered periodic event instructions. + pub mission_event_stops: Vec<MissionEventStop>, } /// Steps a freshly loaded mission from queue time zero at 60 Hz for coverage. @@ -2289,6 +2307,8 @@ pub fn simulate_mission_report( ticks: 0, live_objects: loaded_mission(engine).map_or(0, |mission| mission.registered_objects), world_events: 0, + mission_events: 0, + mission_event_stops: Vec::new(), }; let steps = (u64::from(duration_ms) * 60).div_ceil(1000); for tick in 1..=steps { @@ -2297,6 +2317,10 @@ pub fn simulate_mission_report( report.ticks = tick; report.live_objects = frame.snapshot.objects.len(); report.world_events += frame.snapshot.events.len() as u64; + if let Some(event) = frame.mission_event { + report.mission_events += 1; + report.mission_event_stops.extend(event.stop); + } } Ok(report) } @@ -17033,6 +17057,35 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] + fn licensed_firing_range_reports_first_periodic_instruction() { + let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(licensed_root("IS"))); + let mut engine = create(EngineServices::new(vfs)).unwrap(); + load_mission_with_init_stubs( + &mut engine, + MissionRequest { + key: "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.01/data.tma".into(), + mode: MissionMode::SingleMission, + }, + MissionStartupInput { + queue_time_ms: 0, + research_creation_gate: false, + }, + ) + .unwrap(); + let first = frame(&mut engine, 5).unwrap().mission_event.unwrap(); + let stop = first.stop.unwrap(); + assert_eq!( + (stop.clan_index, stop.event_index, stop.instruction_index), + (0, 2, 0) + ); + assert_eq!(stop.reason, "Handler(32)"); + assert!(frame(&mut engine, 2_004).unwrap().mission_event.is_none()); + let next = frame(&mut engine, 2_005).unwrap().mission_event.unwrap(); + assert!(next.stop.is_none()); + } + + #[test] + #[ignore = "requires licensed corpus"] fn licensed_campaign_full_load_applies_literals_then_single_handler43_rolls_back() { let root = licensed_root("IS"); let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(root)); diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs new file mode 100644 index 00000000..e1177c7a --- /dev/null +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -0,0 +1,98 @@ +use super::LoadedMissionState; +use std::collections::HashSet; + +/// First encounter with an uncovered periodic script instruction. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct MissionEventStop { + /// Clan owning the event's varset. + pub clan_index: usize, + /// Compiled script path. + pub script_path: String, + /// Index in the package's event table. + pub event_index: usize, + /// Index of the instruction in that event. + pub instruction_index: usize, + /// Unsupported opcode, operand, or expression. + pub reason: String, +} + +/// One invocation of the active clan's periodic `Mission` event. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct MissionEventTick { + /// An uncovered instruction encountered for the first time, if any. + pub stop: Option<MissionEventStop>, +} + +#[derive(Default)] +pub(super) struct MissionEvents { + next_ms: u32, + reported_stops: HashSet<usize>, +} + +impl MissionEvents { + fn due(&mut self, now_ms: u32) -> bool { + if now_ms < self.next_ms { + return false; + } + self.next_ms = now_ms.wrapping_add(2_000); + true + } +} + +impl LoadedMissionState { + pub(super) fn tick_mission_event(&mut self, now_ms: u32) -> Option<MissionEventTick> { + // shortcut: use the local clan (0 in the observed standalone modes), + // until runtime has the original active-clan selector. + let bundle = self + .script_bundles + .iter() + .find(|bundle| bundle.clan_index == 0 && bundle.behavior_warm_start.is_some())?; + // shortcut: use the caller's queue clock until the AI wall clock is wired. + if !self.mission_events.due(now_ms) { + return None; + } + let (event_index, event) = + bundle + .package + .events + .iter() + .enumerate() + .find(|(_, event)| { + event.name_raw.split(|byte| *byte == 0).next() == Some(b"Mission") + })?; + let declarations = &self.script_varset.as_ref()?.declarations; + let state = self + .script_varset_states + .iter_mut() + .find(|state| state.clan_index == bundle.clan_index)?; + let stop = declarations + .execute_mission_prefix(event, bundle.formula_table.as_ref(), &mut state.values) + .err() + .filter(|(index, _)| self.mission_events.reported_stops.insert(*index)) + .map(|(instruction_index, reason)| MissionEventStop { + clan_index: bundle.clan_index, + script_path: bundle.script_path.clone(), + event_index, + instruction_index, + reason, + }); + Some(MissionEventTick { stop }) + } +} + +#[cfg(test)] +mod tests { + use super::MissionEvents; + + #[test] + fn deadline_is_inclusive_and_reschedules_from_current_sample_without_catch_up() { + let mut events = MissionEvents::default(); + assert!(events.due(0)); + assert!(!events.due(0)); + assert!(!events.due(1_999)); + assert!(events.due(2_000)); + assert!(events.due(10_123)); + assert!(!events.due(12_122)); + assert!(events.due(12_123)); + } +} diff --git a/crates/fparkan-script/src/lib.rs b/crates/fparkan-script/src/lib.rs index 33da97bf..f6700c14 100644 --- a/crates/fparkan-script/src/lib.rs +++ b/crates/fparkan-script/src/lib.rs @@ -3,7 +3,7 @@ //! //! This module preserves the layout proven by the GOG `ai.dll` reader. It //! deliberately does not implement a general bytecode VM. It contains a -//! narrow resolver for confirmed `Init` handlers and bounded FML expressions. +//! narrow executor for confirmed event instructions and bounded FML expressions. use fparkan_binary::{checked_allocation_len, Cursor, DecodeError, Limits}; use std::sync::Arc; @@ -876,7 +876,23 @@ impl VarSet { Err(error) => Err(ScriptInitResolveError::Handler19(error)), } } - ScriptDispatchSelector::Sentinel if instruction.header_words[3] == 6 => { + ScriptDispatchSelector::Sentinel => { + self.resolve_assignment(instruction, formulas, values) + } + found => Ok(InitInstructionResolution::Unsupported( + ScriptInitResolveError::UnsupportedSelector { found }, + )), + } + } + + fn resolve_assignment( + &self, + instruction: &ScriptInstruction, + formulas: Option<&FormulaTable>, + values: &[VarSetDefault], + ) -> Result<InitInstructionResolution, ScriptInitResolveError> { + match instruction.header_words[3] { + 6 => { let index = instruction.header_words[1]; let target = self.declarations.get(index as usize).ok_or( ScriptInitResolveError::VarSetIndexOutOfBounds { @@ -894,14 +910,7 @@ impl VarSet { value, }])) } - ScriptDispatchSelector::Sentinel => { - if instruction.header_words[3] != u32::MAX { - return Ok(InitInstructionResolution::Unsupported( - ScriptInitResolveError::UnsupportedFormulaControlWord { - found: instruction.header_words[3], - }, - )); - } + u32::MAX => { if instruction.header_words[2] != u32::MAX { return Ok(InitInstructionResolution::Unsupported( ScriptInitResolveError::UnsupportedFormulaCopySource { @@ -974,11 +983,78 @@ impl VarSet { }])) } found => Ok(InitInstructionResolution::Unsupported( - ScriptInitResolveError::UnsupportedSelector { found }, + ScriptInitResolveError::UnsupportedFormulaControlWord { found }, )), } } + /// Executes the numeric prefix of a periodic event against its live cells. + /// Returns the index and reason for the first unsupported instruction. + /// + /// # Errors + /// + /// Returns the stop location for an unsupported opcode, operand or expression. + pub fn execute_mission_prefix( + &self, + event: &ScriptEvent, + formulas: Option<&FormulaTable>, + values: &mut [VarSetDefault], + ) -> Result<(), (usize, String)> { + let mut conditions = Vec::new(); + for (index, instruction) in event.instructions.iter().enumerate() { + let active = conditions.last().copied().unwrap_or(true); + let control = instruction.header_words[3]; + match control { + 0 => { + let condition = if active { + mission_condition(instruction, values) + .ok_or_else(|| (index, "unsupported comparison operands".into()))? + } else { + false + }; + conditions.push(condition); + continue; + } + 1 => { + conditions.pop(); + continue; + } + 2 => continue, + _ => {} + } + // The VM gates ordinary actions and branches. Immediate writes + // have their own switch case and still run inside a false branch. + if !active && matches!(control, u32::MAX | 3..=5) { + continue; + } + if control == 5 { + break; + } + if instruction.dispatch_selector() != ScriptDispatchSelector::Sentinel { + return Err((index, format!("{:?}", instruction.dispatch_selector()))); + } + match self + .resolve_assignment(instruction, formulas, values) + .map_err(|error| (index, error.to_string()))? + { + InitInstructionResolution::Executed(writes) => { + for write in writes { + *values.get_mut(write.index as usize).ok_or_else(|| { + ( + index, + format!("varset index {} is out of bounds", write.index), + ) + })? = write.value; + } + } + InitInstructionResolution::Unsupported(error) => { + return Err((index, error.to_string())) + } + } + } + Ok(()) + } + /// Resolves the fixed-width, corpus-proven operands of GOG `Handler(15)`. /// /// Static analysis of `ai.dll` at `0x10008054` shows four DWORD slots, @@ -1544,6 +1620,26 @@ fn varset_value_as_f32(type_name: VarSetType, value: VarSetDefault) -> Option<f3 } } +fn mission_condition(instruction: &ScriptInstruction, values: &[VarSetDefault]) -> Option<bool> { + let [lhs, rhs] = *instruction.references.as_slice() else { + return None; + }; + let (&VarSetDefault::Dword(lhs), &VarSetDefault::Dword(rhs)) = + (values.get(lhs as usize)?, values.get(rhs as usize)?) + else { + return None; + }; + match instruction.header_words[4] { + 0 => Some(lhs < rhs), + 1 => Some(lhs == rhs), + 2 => Some(lhs > rhs), + 3 => Some(lhs <= rhs), + 4 => Some(lhs >= rhs), + 5 => Some(lhs != rhs), + _ => None, + } +} + fn varset_value_matches_type(type_name: VarSetType, value: VarSetDefault) -> bool { matches!( (type_name, value), @@ -2031,6 +2127,47 @@ mod tests { } } + #[test] + fn mission_prefix_skips_false_actions_but_applies_an_immediate_write() { + let varset = parse_varset(b"VAR(DWORD, lhs, 0)\nVAR(DWORD, rhs, 1)\n").unwrap(); + let instruction = + |handler, dest, source, control, comparison, references: Vec<u32>| ScriptInstruction { + header_words: [ + handler, + dest, + source, + control, + comparison, + references.len() as u32, + u32::MAX, + ], + references, + }; + let compare = instruction(u32::MAX, u32::MAX, u32::MAX, 0, 1, vec![0, 1]); + let close = instruction(u32::MAX, u32::MAX, u32::MAX, 1, 6, vec![]); + let action = instruction(32, 0, u32::MAX, u32::MAX, 6, vec![0, 1]); + let event = ScriptEvent { + name_len: 7, + name_raw: b"Mission\0".to_vec(), + event_word: 0, + instructions: vec![ + compare.clone(), + instruction(u32::MAX, 0, 1, 6, 6, vec![]), + compare, + action.clone(), + close.clone(), + close, + action, + ], + }; + let mut values = [VarSetDefault::Dword(0), VarSetDefault::Dword(1)]; + assert_eq!( + varset.execute_mission_prefix(&event, None, &mut values), + Err((6, "Handler(32)".into())) + ); + assert_eq!(values, [VarSetDefault::Dword(1); 2]); + } + fn init_formula_assignment(target: u32, formula: u32) -> ScriptInstruction { ScriptInstruction { header_words: [u32::MAX, target, u32::MAX, u32::MAX, 6, 0, formula], |
