diff options
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 57 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/mission_events.rs | 42 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 5 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 9 |
4 files changed, 100 insertions, 13 deletions
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 845afa57..8f396629 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -17630,6 +17630,63 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] + fn licensed_constructor_checks_current_factory_and_hangar_owners() { + use fparkan_world::{identity_metadata, set_owner, OwnerId}; + + 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.02/data.tma".into(), + mode: MissionMode::SingleMission, + }, + MissionStartupInput { + queue_time_ms: 0, + research_creation_gate: false, + }, + ) + .unwrap(); + let initial = frame(&mut engine, 1).unwrap().mission_event.unwrap(); + assert!(initial.stop.is_none(), "{:?}", initial.stop); + assert!(!initial + .notices + .iter() + .any(|notice| matches!(notice, MissionNotice::ObjectiveComplete(0 | 2)))); + for (time, logic_id, objective_index) in [(2001, 0x8000_0001, 0), (4001, 0x8000_0003, 2)] { + let slot = engine + .loaded + .as_ref() + .unwrap() + .mission + .objects + .iter() + .position(|object| object.identity_or_clan_raw == logic_id) + .unwrap(); + let handle = mission_object_handle(&engine, OriginalObjectId(slot as u32)).unwrap(); + assert_eq!( + identity_metadata(&engine.world, handle).unwrap().owner_id, + Some(OwnerId(2)) + ); + set_owner(&mut engine.world, handle, Some(OwnerId(0))).unwrap(); + let event = frame(&mut engine, time).unwrap().mission_event.unwrap(); + assert!(event.stop.is_none(), "{:?}", event.stop); + assert!( + event + .notices + .contains(&MissionNotice::ObjectiveComplete(objective_index)), + "{:?}", + event.notices + ); + } + assert_eq!( + loaded_mission_script_outcome(&engine), + Some(MissionScriptOutcome::Active) + ); + } + + #[test] + #[ignore = "requires licensed corpus"] fn licensed_firing_range_reports_target_loss_and_completes_all_objectives() { let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(licensed_root("IS"))); let mut engine = create(EngineServices::new(vfs)).unwrap(); diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs index 098cf47d..35d9e7b7 100644 --- a/crates/fparkan-runtime/src/mission_events.rs +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -310,6 +310,17 @@ impl LoadedMissionState { let inside = tactical_area_contains(&self.mission, world, area, id); Ok(Some(u32::from(inside))) } + ScriptDispatchSelector::Handler(52) => { + let [id] = *instruction.references.as_slice() else { + return Err("Handler(52) requires one DWORD operand".into()); + }; + let Some(&VarSetDefault::Dword(id)) = values.get(id as usize) else { + return Err("Handler(52) requires one DWORD operand".into()); + }; + let clan = placed_logic_objects(&self.mission, world, id) + .find_map(|handle| identity_metadata(world, handle).ok()?.owner_id); + Ok(Some(clan.map_or(u32::MAX, |owner| u32::from(owner.0)))) + } ScriptDispatchSelector::Handler(30) => { let command = declarations .resolve_handler30_with_values(instruction, values) @@ -408,25 +419,34 @@ fn tactical_area_contains( ) -> bool { // MisLoad allocates a slot per path and selects the first record matching // the slot ID. Out-of-range IDs and unfilled slots yield an empty list. - if area as usize >= mission.paths.len() || id == u32::MAX { + if area as usize >= mission.paths.len() { return false; } let Some(path) = mission.paths.iter().find(|path| path.id as u32 == area) else { return false; }; - // shortcut: resolve placed objects through their TMA logic ID until the - // world assigns native logic IDs to units created during gameplay. - mission.objects.iter().enumerate().any(|(index, object)| { - object.identity_or_clan_raw == id - && handle_by_original_id(world, OriginalObjectId(index as u32)) - .and_then(|handle| transform_state(world, handle).ok()) - .is_some_and(|pose| { - let [x, y, _] = pose.position.map(f32::from_bits); - in_tactical_polygon(&path.points, x, y) - }) + placed_logic_objects(mission, world, id).any(|handle| { + transform_state(world, handle).is_ok_and(|pose| { + let [x, y, _] = pose.position.map(f32::from_bits); + in_tactical_polygon(&path.points, x, y) + }) }) } +fn placed_logic_objects<'a>( + mission: &'a super::MissionDocument, + world: &'a World, + id: u32, +) -> impl Iterator<Item = ObjectHandle> + 'a { + // shortcut: only TMA IDs, until the world assigns native IDs at runtime. + mission + .objects + .iter() + .enumerate() + .filter(move |(_, object)| id != u32::MAX && object.identity_or_clan_raw == id) + .filter_map(|(index, _)| handle_by_original_id(world, OriginalObjectId(index as u32))) +} + fn in_tactical_polygon(vertices: &[[f32; 3]], x: f32, y: f32) -> bool { let Some(&[mut previous_x, mut previous_y, _]) = vertices.last() else { return false; diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index 85962bf9..0c5a29c6 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -15,8 +15,9 @@ authoring API без динамического подтверждения. `script_mission_unsupported` считает первые остановки на новых инструкциях. Вещественные сравнения и переходы ещё открыты. -`mission_tactical_ids_stub` отмечает, что проверка тактических областей -учитывает только размещённые объекты. Логические ID созданных юнитов открыты. +`mission_tactical_ids_stub` отмечает, что тактические области и запрос клана +по логическому ID учитывают размещённые объекты. Назначение логических ID +новым юнитам ещё открыто. `mission_clan_roster_stub` отмечает, что счётчик видит исходную расстановку, смену владельца, удаление и подкрепления AutoDemo. Производство пока не создаёт объектов для этого счётчика. diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index 0158846b..82ffcd35 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -594,6 +594,15 @@ Tag выбирает конкретное правило. Для tag 1 запиÑ ### Исход миссии и состояние игры +«Конструктор» проверяет захват завода и ангара через `Handler(52)`: сценарий +передаёт логический ID здания и сравнивает текущий клан с кланом игрока. +ID остаётся прежним при смене владельца. Оригинал возвращает `0xffffffff`, +когда объект отсутствует. FParkan сопоставляет ID со вторым словом TMA после +имени ресурса и читает владельца из живого объекта мира. + +В сборке GOG этот обработчик находится в `ai.dll` по RVA `0xe0e4` +(SHA-256 `c19cd6cd31cd2896f8c4ba0f0e700dd3408aec8182daaf4863d98a7d233a2abc`). + Сообщение сценария об успехе или провале проходит ещё один рубеж — обратный вызов в игровое приложение. У этой границы есть собственные правила: в режиме отдельной миссии вызов может записать новый исход, а в автоматической демо-игре |
