aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--adapters/fparkan-render-vulkan/src/asset_mesh.rs6
-rw-r--r--apps/fparkan-game/src/main.rs4
-rw-r--r--crates/fparkan-msh/src/lib.rs49
-rw-r--r--crates/fparkan-runtime/src/lib.rs19
-rw-r--r--crates/fparkan-runtime/src/mesh_collision.rs1
-rw-r--r--crates/fparkan-runtime/src/mission_events.rs103
-rw-r--r--docs/appendices/knowledge-boundaries.md4
-rw-r--r--docs/tomes/06-behavior.md18
8 files changed, 189 insertions, 15 deletions
diff --git a/adapters/fparkan-render-vulkan/src/asset_mesh.rs b/adapters/fparkan-render-vulkan/src/asset_mesh.rs
index e87a67eb..06872a26 100644
--- a/adapters/fparkan-render-vulkan/src/asset_mesh.rs
+++ b/adapters/fparkan-render-vulkan/src/asset_mesh.rs
@@ -1412,6 +1412,7 @@ mod tests {
batches,
triangle_descriptors: None,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: None,
}
}
@@ -1479,6 +1480,7 @@ mod tests {
],
triangle_descriptors: None,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: None,
};
@@ -1724,6 +1726,7 @@ mod tests {
batches: vec![batch(0, 3, 0), batch(3, 3, 0)],
triangle_descriptors: None,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: Some(ModelAnimation {
keys: vec![
AnimKey24 {
@@ -1785,6 +1788,7 @@ mod tests {
batches: Vec::new(),
triangle_descriptors: None,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: Some(ModelAnimation {
keys: vec![
AnimKey24 {
@@ -1893,6 +1897,7 @@ mod tests {
batches: vec![batch(0, 3, 0), batch(3, 3, 0)],
triangle_descriptors: None,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: Some(ModelAnimation {
keys: vec![AnimKey24 {
time: AnimationTime(0.0),
@@ -1986,6 +1991,7 @@ mod tests {
batches: vec![batch(0, 3, 0)],
triangle_descriptors: None,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: Some(ModelAnimation {
keys: vec![AnimKey24 {
time: AnimationTime(0.0),
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index 3f6932e0..cba38f81 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -13235,6 +13235,7 @@ mod tests {
}],
triangle_descriptors: None,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: Some(ModelAnimation {
keys: vec![
AnimKey24 {
@@ -13306,6 +13307,7 @@ mod tests {
}],
triangle_descriptors: None,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: Some(ModelAnimation {
keys: vec![AnimKey24 {
time: AnimationTime(0.0),
@@ -13360,6 +13362,7 @@ mod tests {
normal: [0, 32767, 0],
}]),
node_names: None,
+ hero_exit_points: Vec::new(),
animation: Some(ModelAnimation {
keys: vec![
AnimKey24 {
@@ -13508,6 +13511,7 @@ mod tests {
.collect(),
),
node_names: None,
+ hero_exit_points: Vec::new(),
animation: Some(ModelAnimation {
keys: vec![AnimKey24 {
time: AnimationTime(0.0),
diff --git a/crates/fparkan-msh/src/lib.rs b/crates/fparkan-msh/src/lib.rs
index f9d75554..334a6353 100644
--- a/crates/fparkan-msh/src/lib.rs
+++ b/crates/fparkan-msh/src/lib.rs
@@ -23,6 +23,8 @@ pub const STREAM_UV0: u32 = 5;
pub const STREAM_UV1: u32 = 18;
/// Optional type-16 stream. Its presence marks MSH vertex-colour data.
pub const STREAM_TYPE_16: u32 = 16;
+/// Model-local gameplay points and auxiliary vectors.
+pub const STREAM_GAMEPLAY_POINTS: u32 = 17;
/// Triangle index stream.
pub const STREAM_INDICES: u32 = 6;
/// Optional triangle-descriptor stream.
@@ -115,6 +117,8 @@ pub struct ModelAsset {
pub triangle_descriptors: Option<Vec<TriangleDescriptor>>,
/// Optional decoded node names.
pub node_names: Option<Vec<Option<String>>>,
+ /// Node-local points whose flags mark a hero exit.
+ pub hero_exit_points: Vec<(NodeId, [f32; 3])>,
/// Optional decoded node-animation streams.
pub animation: Option<ModelAnimation>,
}
@@ -1135,6 +1139,10 @@ fn parse_model_document(document: &NresDocument) -> Result<ModelAsset, MshError>
let node_names = read_optional_stream(document, STREAM_NAMES)?
.map(|raw| parse_res10_names(&raw.bytes, node_count))
.transpose()?;
+ let hero_exit_points = read_optional_stream(document, STREAM_GAMEPLAY_POINTS)?
+ .map(|raw| parse_hero_exit_points(&raw, node_count))
+ .transpose()?
+ .unwrap_or_default();
let animation = parse_optional_animation(document)?;
Ok(ModelAsset {
@@ -1153,10 +1161,47 @@ fn parse_model_document(document: &NresDocument) -> Result<ModelAsset, MshError>
batches,
triangle_descriptors,
node_names,
+ hero_exit_points,
animation,
})
}
+fn parse_hero_exit_points(
+ stream: &RawStream,
+ node_count: usize,
+) -> Result<Vec<(NodeId, [f32; 3])>, MshError> {
+ const POINT_BYTES: usize = 20;
+ let point_count = stream.attributes.attr1 as usize;
+ let pairs = stream.attributes.attr2 as usize;
+ if !stream.bytes.len().is_multiple_of(POINT_BYTES)
+ || (point_count as u64 + 2 * pairs as u64) != (stream.bytes.len() / POINT_BYTES) as u64
+ {
+ return Err(MshError::InvalidGeometry(
+ "invalid Res17 point table length".into(),
+ ));
+ }
+ let mut exits = Vec::new();
+ for point in stream.bytes.chunks_exact(POINT_BYTES).take(point_count) {
+ let flags = read_u32(point, 12)?;
+ if flags & 0x1000_4000 != 0x4000 {
+ continue;
+ }
+ let node = NodeId(read_u32(point, 16)?);
+ let position = [
+ read_f32(point, 0)?,
+ read_f32(point, 4)?,
+ read_f32(point, 8)?,
+ ];
+ if node.0 as usize >= node_count || !position.iter().all(|axis| axis.is_finite()) {
+ return Err(MshError::InvalidGeometry(
+ "invalid Res17 hero exit point".into(),
+ ));
+ }
+ exits.push((node, position));
+ }
+ Ok(exits)
+}
+
fn parse_optional_animation(document: &NresDocument) -> Result<Option<ModelAnimation>, MshError> {
let keys = read_optional_stream(document, STREAM_ANIMATION_KEYS)?;
let frame_map = read_optional_stream(document, STREAM_ANIMATION_FRAME_MAP)?;
@@ -2300,6 +2345,7 @@ mod tests {
batches: Vec::new(),
triangle_descriptors: None,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: Some(ModelAnimation {
keys: vec![
AnimKey24 {
@@ -2363,6 +2409,7 @@ mod tests {
batches: Vec::new(),
triangle_descriptors: None,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: Some(ModelAnimation {
keys: vec![
AnimKey24 {
@@ -2429,6 +2476,7 @@ mod tests {
batches: Vec::new(),
triangle_descriptors: None,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: Some(ModelAnimation {
keys: vec![
AnimKey24 {
@@ -3322,6 +3370,7 @@ mod tests {
indices,
batches,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: None,
triangle_descriptors: Some(
tri_flags
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index f0be9bad..a3114a53 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -2692,7 +2692,7 @@ pub fn frame_with_player_motion(
/// 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 mission_event_clock_approx=1 mission_tactical_ids_stub=1 mission_clan_roster_stub=1 mission_message_ui_stub=1 factory_orders_approx=1 mine_orders_approx=1 mission_patrol_approx=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 mission_tactical_ids_stub=1 mission_clan_roster_stub=1 mission_message_ui_stub=1 factory_orders_approx=1 mine_orders_approx=1 mission_patrol_approx=1 mission_hero_exit_approx=1";
/// Totals from a headless mission coverage run.
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -9267,6 +9267,7 @@ mod tests {
batches: Vec::new(),
triangle_descriptors: None,
node_names: None,
+ hero_exit_points: Vec::new(),
animation: None,
}
}
@@ -18067,6 +18068,22 @@ mod tests {
"{event:?}"
);
}
+ let active = Some(MissionScriptOutcome::Active);
+ assert_eq!(loaded_mission_script_outcome(&engine), active);
+ pose.position = [1175.335_f32, 1242.098, 112.0].map(f32::to_bits);
+ set_transform(&mut engine.world, cockpit.handle, pose).unwrap();
+ assert!(frame(&mut engine, 8_002).unwrap().mission_event.is_none());
+ assert_eq!(loaded_mission_script_outcome(&engine), active);
+ pose.position = [1175.335_f32, 1242.098, 79.0].map(f32::to_bits);
+ set_transform(&mut engine.world, cockpit.handle, pose).unwrap();
+ let event = frame(&mut engine, 8_003).unwrap().mission_event.unwrap();
+ assert!(event.stop.is_none(), "{event:?}");
+ assert_eq!(event.notices, [MissionNotice::Completed]);
+ assert_eq!(
+ loaded_mission_script_outcome(&engine),
+ Some(MissionScriptOutcome::Completed)
+ );
+ assert!(frame(&mut engine, 8_004).unwrap().mission_event.is_none());
}
#[test]
diff --git a/crates/fparkan-runtime/src/mesh_collision.rs b/crates/fparkan-runtime/src/mesh_collision.rs
index 6e9ae2d5..7783400e 100644
--- a/crates/fparkan-runtime/src/mesh_collision.rs
+++ b/crates/fparkan-runtime/src/mesh_collision.rs
@@ -451,6 +451,7 @@ mod tests {
batches,
triangle_descriptors: Some(triangle_descriptors),
node_names: None,
+ hero_exit_points: Vec::new(),
animation: None,
}
}
diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs
index 61624135..90cd1028 100644
--- a/crates/fparkan-runtime/src/mission_events.rs
+++ b/crates/fparkan-runtime/src/mission_events.rs
@@ -143,7 +143,8 @@ impl MissionObjectives {
#[derive(Default)]
pub(super) struct MissionEvents {
next_ms: u32,
- reported_stops: HashSet<usize>,
+ reported_stops: HashSet<(usize, usize)>,
+ inside_hero_exit: bool,
voiced_messages: HashSet<u32>,
placed_clan_objects: Vec<(ObjectHandle, u32)>,
objectives: MissionObjectives,
@@ -449,6 +450,57 @@ pub(super) fn on_communicator(
}
impl LoadedMissionState {
+ fn hero_in_teleport_exit(&self, world: &World) -> bool {
+ if self.boarding.is_some() || self.script_host_mode != super::MissionMode::SingleMission {
+ return false;
+ }
+ let hero = self.object_drafts.iter().find(|draft| {
+ draft.unit_dat_header_flags == Some(super::HERO_UNIT_CLASS)
+ && draft.raw_after_resource == 0
+ });
+ let Some(hero_position) = hero
+ .and_then(|draft| handle_by_original_id(world, draft.original_id?))
+ .and_then(|hero| transform_state(world, hero).ok())
+ .map(|pose| pose.position.map(f32::from_bits))
+ else {
+ return false;
+ };
+ self.object_drafts.iter().enumerate().any(|(index, draft)| {
+ if draft.unit_dat_header_flags != Some(MAIN_TELEPORT_CLASS) {
+ return false;
+ }
+ let hit = || {
+ let handle = handle_by_original_id(world, draft.original_id?)?;
+ let pose = transform_state(world, handle).ok()?;
+ let visual = self
+ .mission_assets
+ .visual_by_id(self.mission_assets.visual_for_object(index)?)?;
+ let model = &self.mission_assets.model_by_id(visual.model_id?)?.validated;
+ if model.hero_exit_points.is_empty() {
+ return Some(false);
+ }
+ let hierarchy = node38_sampled_hierarchy(model, 0)?;
+ let transform = LegacyIron3dEulerTransform {
+ translation: pose.position.map(f32::from_bits),
+ orientation_radians: pose.orientation.map(f32::from_bits),
+ };
+ Some(model.hero_exit_points.iter().any(|&(node, local)| {
+ let Some(center) = hierarchy.poses.get(node.0 as usize).and_then(|node_pose| {
+ transform.try_transform_scaled_point(
+ node_pose.transform_point(local),
+ pose.scale.map(f32::from_bits),
+ )
+ }) else {
+ return false;
+ };
+ // shortcut: static node poses and the ordinary Res17 volume until animated triggers are wired.
+ inside_exit_volume(center, hero_position)
+ }))
+ };
+ hit() == Some(true)
+ })
+ }
+
pub(super) fn tick_mission_event(
&mut self,
world: &World,
@@ -460,19 +512,24 @@ impl LoadedMissionState {
.script_bundles
.iter()
.find(|bundle| bundle.clan_index == 0 && bundle.behavior_warm_start.is_some())?;
+ let mut events = bundle.package.events.iter().enumerate();
+ let exit_event = events.clone().find(|(_, event)| {
+ event.name_raw == b"Hero_Teleported\0" && !event.instructions.is_empty()
+ });
+ let inside_exit = exit_event.is_some() && self.hero_in_teleport_exit(world);
+ let entered_exit = inside_exit && !self.mission_events.inside_hero_exit;
+ self.mission_events.inside_hero_exit = inside_exit;
// 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)| {
+ if entered_exit && self.script_outcome == super::MissionScriptOutcome::Active {
+ exit_event?
+ } else if self.mission_events.due(now_ms) {
+ events.find(|(_, event)| {
event.name_raw.split(|byte| *byte == 0).next() == Some(b"Mission")
- })?;
+ })?
+ } else {
+ return None;
+ };
let declarations = &self.script_varset.as_ref()?.declarations;
let state = self
.script_varset_states
@@ -679,7 +736,7 @@ impl LoadedMissionState {
);
let stop = execution
.err()
- .filter(|(index, _)| mission_events.reported_stops.insert(*index))
+ .filter(|(index, _)| mission_events.reported_stops.insert((event_index, *index)))
.map(|(instruction_index, reason)| MissionEventStop {
clan_index: bundle.clan_index,
script_path: bundle.script_path.clone(),
@@ -695,6 +752,10 @@ impl LoadedMissionState {
}
}
+fn inside_exit_volume([x, y, z]: [f32; 3], [px, py, pz]: [f32; 3]) -> bool {
+ (pz - z).abs() <= 3.0 && (px - x).powi(2) + (py - y).powi(2) <= 25.0
+}
+
fn capturer_chassis(chassis: &[u8; 32]) -> bool {
// shortcut: stock robot keys map to native size classes 1 and 2;
// query the effective Behavior controller when custom types are supported.
@@ -784,8 +845,8 @@ fn in_tactical_polygon(vertices: &[[f32; 3]], x: f32, y: f32) -> bool {
#[cfg(test)]
mod tests {
use super::{
- capturer_chassis, clan_object_classes, in_tactical_polygon, MissionEvents, MissionNotice,
- MissionObjectives,
+ capturer_chassis, clan_object_classes, in_tactical_polygon, inside_exit_volume,
+ MissionEvents, MissionNotice, MissionObjectives,
};
use fparkan_world::{
construct_object, new, register_object, request_delete, set_owner, ObjectDraft, OwnerId,
@@ -793,6 +854,20 @@ mod tests {
};
#[test]
+ fn exit_cylinder_includes_the_wall_and_caps() {
+ let center = [10., 20., 30.];
+ for (point, inside) in [
+ ([15., 20., 30.], true),
+ ([15.1, 20., 30.], false),
+ ([10., 20., 27.], true),
+ ([10., 20., 33.], true),
+ ([10., 20., 33.1], false),
+ ] {
+ assert_eq!(inside_exit_volume(center, point), inside);
+ }
+ }
+
+ #[test]
fn capturer_classes_are_tiny_and_light() {
for (key, expected) in [
(b"R_T_02", true),
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index 513df8f8..8f1c0140 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -90,6 +90,10 @@ authoring API без динамического подтверждения.
расход RNG и варианты других приказов ещё открыты.
`factory_spawn_failed` считает заказы, сорвавшиеся при создании робота.
+`mission_hero_exit_approx` отмечает обычную зону выхода главного телепорта
+в исходной позе узла. Движущиеся зоны, размеры из вспомогательных векторов
+и переход к следующей миссии ещё открыты.
+
`autodemo_camera_follow_approx` и `autodemo_camera_target_approx` отмечают
приближённое слежение и выбор размещённых юнитов с камерой через селектор AI.
Стратегический интерфейс и выбор вновь созданных юнитов ещё открыты.
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index a971ec91..295c8e78 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -2040,6 +2040,24 @@ FParkan выбирает ближайший дружественный варбÐ
через `0x1ac90`. Точные границы
срабатывания и открытие интерфейса МЦУ ещё исследуются.
+### Выход из миссии через телепорт
+
+Последняя подсказка «Телепорта» просит нырнуть под арку. Центр зоны
+под аркой задан в потоке `Res17` модели `FR_M_MTP.msh` и привязан к узлу
+модели. У обычной точки выхода с флагом `0x4000` радиус равен 5 единицам,
+а высота составляет по 3 единицы вверх и вниз от центра.
+
+В GOG-сборке `Behavior.dll` с указанным выше SHA-256 подготовка точек
+начинается по RVA `0x186b0`. Проверка цилиндра по RVA `0x22c80` включает
+стенку и обе крышки, что подтвердил прямой вызов функции из DLL. Ветвь
+по RVA `0x1914f` проверяет героя и передаёт событие выхода сценарию.
+
+FParkan пересчитывает центр по положению здания, его масштабу и
+исходной позе узла. Когда герой пешком входит в зону главного телепорта,
+движок вызывает `Hero_Teleported` из сценария миссии. В «Телепорте»
+команда сценария завершает миссию. Игра выводит «Миссия выполнена»
+в заголовке окна и ставит в очередь голосовое сообщение о победе.
+
### Месторождение и шахта
В «Полевом лагере» запас руды задан в конце TMA. Загрузчик MisLoad.dll