//! Building geometry queries shared by walking and the preview camera. use super::{ damage_visibility::{building_provider_rows, visible_node_stage}, multiply_row_major, rotate_unit_vector, StaticVulkanApp, }; use fparkan_animation::NodePoseBuffer; use fparkan_msh::{selected_slot, Group, Lod, ModelAsset, NodeId, SlotId}; use fparkan_render::LegacyIron3dEulerTransform; use fparkan_render_vulkan::{ node38_pose, node38_pose_from_hierarchy, node38_pose_relative_to_root, node38_pose_relative_to_root_from_hierarchy, VulkanNodePose, }; use fparkan_runtime::{ loaded_mission_control_device_tables, query_building_segment_world, BuildingMeshNode, }; use std::sync::Arc; #[derive(Clone)] pub(super) struct BuildingCollisionBinding { pub(super) object_index: usize, pub(super) component_index: usize, pub(super) model_source: String, pub(super) model: Arc, pub(super) root_transform: LegacyIron3dEulerTransform, pub(super) owner_scale: [f32; 3], pub(super) mounted: bool, pub(super) selected_nodes: Vec<(NodeId, SlotId)>, } pub(super) fn building_collision_binding( object_index: usize, component_index: usize, model_source: String, model: Arc, root_transform: LegacyIron3dEulerTransform, owner_scale: [f32; 3], mounted: bool, ) -> Result { let context = || { format!( "building collision object {object_index} component {component_index} model {model_source}" ) }; if model.node_stride != 38 || model.node_count == 0 || model.animation.is_none() { return Err(format!("{} has no complete Node38 pose data", context())); } if model.triangle_descriptors.is_none() { return Err(format!("{} has no type-7 collision descriptors", context())); } if root_transform.try_row_major().is_none() || !owner_scale.iter().all(|value| value.is_finite()) || owner_scale.contains(&0.0) { return Err(format!("{} has an invalid world transform", context())); } let first_node = usize::from(mounted); let mut selected_nodes = Vec::new(); for node_index in first_node..model.node_count { let node = NodeId( u32::try_from(node_index) .map_err(|_| format!("{} node index exceeds u32", context()))?, ); let Some(slot) = selected_slot(&model, node, Lod(0), Group(0)) else { continue; }; let slot_index = usize::try_from(slot.0) .map_err(|_| format!("{} node {} has an invalid slot id", context(), node.0))?; let slot_data = model.slots.get(slot_index).ok_or_else(|| { format!( "{} node {} selects missing slot {}", context(), node.0, slot.0 ) })?; let batch_start = usize::from(slot_data.batch_start); let batch_end = batch_start .checked_add(usize::from(slot_data.batch_count)) .ok_or_else(|| format!("{} node {} batch range overflows", context(), node.0))?; let batches = model.batches.get(batch_start..batch_end).ok_or_else(|| { format!( "{} node {} batch range {batch_start}..{batch_end} is invalid", context(), node.0 ) })?; if batches.iter().any(|batch| batch.index_count != 0) || selected_slot(&model, node, Lod(1), Group(0)).is_some() { selected_nodes.push((node, slot)); } } Ok(BuildingCollisionBinding { object_index, component_index, model_source, model, root_transform, owner_scale, mounted, selected_nodes, }) } pub(super) fn building_collision_nodes( binding: &BuildingCollisionBinding, pose_buffer: Option<&NodePoseBuffer>, mount_pose: Option, visible_stage: impl Fn(usize) -> u32, ) -> Result, String> { let context = || { format!( "building collision object {} component {} model {}", binding.object_index, binding.component_index, binding.model_source ) }; if binding.mounted != mount_pose.is_some() { return Err(format!( "{} has {} mount pose, expected {}", context(), if mount_pose.is_some() { "a" } else { "no" }, if binding.mounted { "a" } else { "no" } )); } binding .selected_nodes .iter() .filter_map(|&(node, intact)| { let slot = if selected_slot(&binding.model, node, Lod(1), Group(0)).is_some() { let stage = u8::try_from(visible_stage(node.0 as usize)).ok()?; selected_slot(&binding.model, node, Lod(stage), Group(0))? } else { intact }; Some((node, slot)) }) .map(|(node, slot)| { let node_index = usize::try_from(node.0).map_err(|_| format!("{} node id is invalid", context()))?; let pose = match (pose_buffer, binding.mounted) { (Some(hierarchy), true) => { node38_pose_relative_to_root_from_hierarchy(hierarchy, node_index) } (Some(hierarchy), false) => node38_pose_from_hierarchy(hierarchy, node_index), (None, true) => node38_pose_relative_to_root(&binding.model, None, node_index), (None, false) => node38_pose(&binding.model, None, node_index), } .ok_or_else(|| format!("{} node {} has no current Node38 pose", context(), node.0))?; let world_from_node = component_node_world_matrix( binding.root_transform, binding.owner_scale, mount_pose, pose, ) .ok_or_else(|| format!("{} node {} has an invalid world matrix", context(), node.0))?; Ok(BuildingMeshNode { node, slot, world_from_node, }) }) .collect() } fn component_node_world_matrix( root_transform: LegacyIron3dEulerTransform, owner_scale: [f32; 3], mount_pose: Option, node_pose: VulkanNodePose, ) -> Option<[f32; 16]> { if !owner_scale .iter() .chain(node_pose.translation.iter()) .chain(node_pose.rotation.iter()) .chain(mount_pose.iter().flat_map(|pose| pose.translation.iter())) .chain(mount_pose.iter().flat_map(|pose| pose.rotation.iter())) .all(|value| value.is_finite()) { return None; } let pose_matrix = |pose: VulkanNodePose| { let [x, y, z] = [ rotate_unit_vector([1.0, 0.0, 0.0], pose.rotation), rotate_unit_vector([0.0, 1.0, 0.0], pose.rotation), rotate_unit_vector([0.0, 0.0, 1.0], pose.rotation), ]; [ x[0], y[0], z[0], pose.translation[0], x[1], y[1], z[1], pose.translation[1], x[2], y[2], z[2], pose.translation[2], 0.0, 0.0, 0.0, 1.0, ] }; let scale = [ owner_scale[0], 0.0, 0.0, 0.0, 0.0, owner_scale[1], 0.0, 0.0, 0.0, 0.0, owner_scale[2], 0.0, 0.0, 0.0, 0.0, 1.0, ]; let mut world = multiply_row_major(root_transform.try_row_major()?, scale); if let Some(mount) = mount_pose { world = multiply_row_major(world, pose_matrix(mount)); } world = multiply_row_major(world, pose_matrix(node_pose)); world.iter().all(|value| value.is_finite()).then_some(world) } impl StaticVulkanApp { pub(super) fn building_segment_blocked( &self, world_segment: [[f32; 3]; 2], ) -> Result { Ok(self.building_segment_hit(world_segment, false)?.is_some()) } pub(super) fn building_segment_hit( &self, world_segment: [[f32; 3]; 2], nearest: bool, ) -> Result, String> { let mut best = None; let tables = self .mission_engine .as_ref() .and_then(loaded_mission_control_device_tables) .unwrap_or_default(); for binding in &self.building_collision_bindings { if binding.selected_nodes.is_empty() || self.removed_mission_roots.contains(&binding.object_index) { continue; } let pose_buffer = self .component_pose_buffers .get(binding.object_index) .and_then(|components| components.get(binding.component_index)) .and_then(Option::as_ref); let mount_pose = self .component_mount_poses .get(binding.object_index) .and_then(|components| components.get(binding.component_index)) .copied() .flatten(); let providers = building_provider_rows(tables, binding.object_index); let nodes = building_collision_nodes(binding, pose_buffer, mount_pose, |node| { visible_node_stage(providers, binding.component_index, node) })?; if let Some(hit) = query_building_segment_world(&binding.model, &nodes, world_segment) .map_err(|error| { format!( "query building collision object {} component {} model {}: {error}", binding.object_index, binding.component_index, binding.model_source ) })? { if !nearest { return Ok(Some(hit.position)); } if best.is_none_or(|(distance, _)| hit.distance_squared < distance) { best = Some((hit.distance_squared, hit.position)); } } } Ok(best.map(|(_, position)| position)) } pub(super) fn resolve_player_building_step( &self, mut step: fparkan_runtime::PlayerMotionStep, ) -> Result<(fparkan_runtime::PlayerMotionStep, bool), String> { if let Some(probe) = step.floor_probe() { let crossing_cut = if self.terrain.basement_foundation().is_some() { let [start, end] = step.sweep.expect("walking floor probe"); let support = |[x, y, _]: [f32; 3]| { self.terrain .support_plane_at([x, y]) .map_err(|err| err.to_string()) }; let previous = support(start)?.map(|plane| plane.height); let next = support(end)?; step = step.with_scene_terrain(previous, next); previous.is_none() || next.is_none() } else { false }; let mesh_floor = self .building_segment_hit(probe, true)? .map(|point| point[2]); let terrain_exit = step.terrain_exit_floor(); let previous_mesh = if mesh_floor.is_some() || terrain_exit.is_some() { self.building_segment_hit( step.previous_floor_probe().expect("walking floor probe"), true, )? .map(|point| point[2]) } else { None }; let mut floor = mesh_floor.map(|height| (height, false)); if let Some(height) = terrain_exit { if mesh_floor.is_none_or(|mesh| mesh < height) && (crossing_cut || previous_mesh.is_some()) && !self.building_segment_blocked([ [probe[0][0], probe[0][1], height + 0.02], probe[0], ])? { floor = Some((height, true)); } } if let Some((height, terrain)) = floor { step = if terrain { step.with_terrain_floor(height, previous_mesh) } else { step.with_building_floor(height, previous_mesh) }; if let Some(segments) = step.floor_sweeps() { for segment in segments.into_iter().filter(|[from, to]| from != to) { if self.building_segment_blocked(segment)? { return Ok((step, true)); } } } return Ok((step, false)); } } let blocked = match step.sweep { Some(segment) => self.building_segment_blocked(segment)?, None => false, }; Ok((step, blocked)) } } #[cfg(test)] #[derive(Default)] pub(crate) struct WalkRoute { filtered_x: f32, } #[cfg(test)] impl WalkRoute { pub(crate) fn toward( &mut self, pose: fparkan_world::TransformState, target: [f32; 2], max_step: f32, ) -> fparkan_runtime::PlayerMotion { use std::f32::consts::{PI, TAU}; let [x, y, _] = pose.position.map(f32::from_bits); let [dx, dy] = [target[0] - x, target[1] - y]; let yaw = f32::from_bits(pose.orientation[2]); let wanted = (-dx).atan2(dy); let turn = (yaw - wanted + PI).rem_euclid(TAU) - PI; // Convert the desired heading to ordinary mouse input at 100% sensitivity. let axis = (turn / (TAU * 0.15)).clamp(-1.0, 1.0); let previous = self.filtered_x * 0.05; let mouse_x = (axis / 0.006 - previous) / 0.95; self.filtered_x = if mouse_x == 0.0 { 0.0 } else { mouse_x * 0.95 + previous }; let walk_time = dx.hypot(dy).min(max_step) / 14.0; let can_walk = turn.abs() <= (TAU * 0.15).min(50.0 * walk_time); fparkan_runtime::PlayerMotion { mouse_x, movement: [0.0, f32::from(can_walk)], delta_seconds: if can_walk { walk_time } else { 0.03 }, ..Default::default() } } } #[cfg(test)] mod tests { use crate::tests::clock_test_app; use crate::*; #[test] #[ignore = "requires licensed corpus"] fn licensed_constructor_walks_to_factory_cabin_and_back() { let root = std::path::PathBuf::from( std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed root"), ); let args = Args::parse(&[ "--root".into(), root.to_string_lossy().into_owned(), "--mission".into(), "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.02/data.tma".into(), ]) .unwrap(); let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(&root)))).unwrap(); let loaded = load_requested_mission(&mut engine, &args).unwrap(); let terrain = loaded_terrain(&engine).unwrap(); let assets = loaded_mission_assets(&engine).unwrap(); let drafts = loaded_mission_object_drafts(&engine).unwrap(); let footprints = mission_basement_footprints(assets, &drafts[..loaded.object_count]).unwrap(); let foundation = build_basement_foundations( terrain.source_mesh().unwrap(), &footprints .iter() .map(MissionBasementFootprint::contours) .collect::>(), ) .unwrap(); let adjusted = apply_basement_placement_deltas(drafts, &footprints, &foundation.placements).unwrap(); let factory = &adjusted[0]; let root_transform = LegacyIron3dEulerTransform { translation: factory.position, orientation_radians: factory.orientation_raw, }; let scale = factory.scale; let visual = assets.visual_by_id(factory.visual_ids[0]).unwrap(); let model = Arc::new( assets .model_by_id(visual.model_id.unwrap()) .unwrap() .validated .clone(), ); let control = assets.object_component_controls[0][0] .as_ref() .unwrap() .clone(); let hierarchy = node38_fallback_hierarchy(&model).unwrap(); let route = std::iter::once([320.0, 790.0]) .chain( [67, 66, 65, 58, 59, 37, 36, 6, 7, 25, 35, 28, 31].map(|index| { let point = &model.hallway.points[index]; let local = hierarchy.poses[point.node.0 as usize].transform_point(point.position); let [x, y, _] = root_transform .try_transform_scaled_point(local, scale) .unwrap(); [x, y] }), ) .collect::>(); let (mut app, _) = clock_test_app(None); app.terrain = Arc::new( terrain .clone() .with_basement_foundation(foundation) .unwrap(), ); app.building_collision_bindings.push( building_collision_binding( 0, 0, "factory".into(), model.clone(), root_transform, scale, false, ) .unwrap(), ); app.component_pose_buffers = vec![vec![None]]; let cockpit = starting_cockpit(&engine).unwrap(); let pose = |frame: FrameResult| { frame .snapshot .transforms .into_iter() .find(|(handle, _)| *handle == cockpit.handle) .unwrap() .1 }; let mut now = 0; let mut hero = pose(step_mission_frame(&mut engine, now).unwrap()); let mut input = super::WalkRoute::default(); let [spawn_x, spawn_y, spawn_z] = hero.position.map(f32::from_bits); let spawn_clearance = spawn_z - app.terrain.height_at([spawn_x, spawn_y]).unwrap().unwrap(); let mut door_blends = Vec::new(); let mut footstep_surfaces = [false; 2]; for (index, [x, y]) in route .iter() .chain(route.iter().rev().skip(1)) .copied() .enumerate() { let mut stalled = 0; loop { let [hx, hy, hz] = hero.position.map(f32::from_bits); let distance = (x - hx).hypot(y - hy); if distance <= 0.04 { break; } let mut node_times: Vec<_> = fparkan_runtime::initial_component_node_times( model.node_count, &control.bindings, ) .unwrap() .into_iter() .map(|time| time.map(|time| time.0)) .collect(); fparkan_runtime::sample_proximity_doors( &control, &model, root_transform, scale, [hx, hy, hz + 0.5], 0.1, &mut door_blends, &mut node_times, ); let factory_handle = mission_object_handle(&engine, fparkan_world::OriginalObjectId(0)).unwrap(); fparkan_runtime::sample_capture_barrier( &engine, factory_handle, &control, &mut node_times, ); let times: Vec<_> = node_times .into_iter() .map(|time| time.map(AnimationTime)) .collect(); app.component_pose_buffers[0][0] = node38_sampled_hierarchy_at_times(&model, ×); let motion = plan_player_motion_with_collision( &engine, cockpit, input.toward(hero, [x, y], 0.8), |step| { app.resolve_player_building_step(step) .map_err(EngineError::Movement) }, ) .unwrap() .unwrap(); now += 100; let frame = frame_with_player_motion(&mut engine, now, cockpit, motion, false).unwrap(); if let Some(footstep) = frame.player_footstep { footstep_surfaces[usize::from(footstep.building_floor)] = true; } let moved = pose(frame); stalled = if moved.position == hero.position { stalled + 1 } else { 0 }; assert!( stalled < 20, "blocked before waypoint {index} [{x}, {y}] at [{hx}, {hy}, {hz}]" ); assert!(now < 150_000, "walk stalled before waypoint {index}"); hero = moved; } if index + 1 == route.len() { let z = f32::from_bits(hero.position[2]); assert!(z < factory.position[2] - 4.0, "factory cabin at {z}"); assert_eq!(app.terrain.height_at([x, y]).unwrap(), None); assert_eq!( fparkan_runtime::capture_building_with_notice(&mut engine, cockpit).unwrap(), Some(( fparkan_world::OriginalObjectId(0), fparkan_runtime::MissionNotice::BuildingCaptured { neutral: true } )) ); now += 17; step_mission_frame(&mut engine, now).unwrap(); now += 500; step_mission_frame(&mut engine, now).unwrap(); } } let [x, y, z] = hero.position.map(f32::from_bits); assert_eq!(footstep_surfaces, [true, true]); let ground = app.terrain.height_at([x, y]).unwrap().unwrap(); assert!( (z - ground - spawn_clearance).abs() < 0.02, "factory exit clearance {}, stock outdoor clearance {spawn_clearance}", z - ground ); } #[test] #[ignore = "requires licensed corpus"] fn licensed_firing_range_keeps_clearance_across_bridge() { let root = std::path::PathBuf::from( std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed root"), ); let args = Args::parse(&[ "--root".into(), root.to_string_lossy().into_owned(), "--mission".into(), "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.01/data.tma".into(), ]) .unwrap(); let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(&root)))).unwrap(); load_requested_mission(&mut engine, &args).unwrap(); let assets = loaded_mission_assets(&engine).unwrap(); let (mut app, _) = clock_test_app(None); for (i, draft) in loaded_mission_object_drafts(&engine) .unwrap() .iter() .enumerate() .filter(|(i, _)| [23, 24].contains(i)) { let visual = assets.visual_by_id(draft.visual_ids[0]).unwrap(); let model = Arc::new( assets .model_by_id(visual.model_id.unwrap()) .unwrap() .validated .clone(), ); let transform = LegacyIron3dEulerTransform { translation: draft.position, orientation_radians: draft.orientation_raw, }; let binding = building_collision_binding( i, 0, "bridge".into(), model, transform, draft.scale, false, ) .unwrap(); app.component_pose_buffers.resize_with(i + 1, || vec![None]); app.component_pose_buffers[i][0] = assets.object_component_controls[i][0] .as_ref() .and_then(|control| { static_preview_component_pose_buffer(&binding.model, &control.bindings, None) .unwrap() }); app.building_collision_bindings.push(binding); } let transform = app.building_collision_bindings[0].root_transform; let terrain = loaded_terrain(&engine).unwrap().clone(); let cockpit = starting_cockpit(&engine).unwrap(); let mut now = 0; let pose = |frame: FrameResult| { frame .snapshot .transforms .into_iter() .find(|(handle, _)| *handle == cockpit.handle) .unwrap() .1 }; let mut hero = pose(step_mission_frame(&mut engine, now).unwrap()); let mut input = super::WalkRoute::default(); let [x, y, z] = hero.position.map(f32::from_bits); let clearance = z - terrain.height_at([x, y]).unwrap().unwrap(); let waypoints = [-42.0, -34.0, 36.0, 115.0, 198.0]; for dy in waypoints { let [x, y, _] = transform .try_transform_scaled_point([0.0, dy, 0.0], [1.0; 3]) .unwrap(); for index in 0..900 { let [hx, hy, hz] = hero.position.map(f32::from_bits); let distance = (x - hx).hypot(y - hy); if distance < 0.03 { let support = app .building_segment_hit([[hx, hy, hz], [hx, hy, hz - 2.0]], true) .unwrap() .map_or_else( || terrain.height_at([hx, hy]).unwrap().unwrap(), |point| point[2], ); assert!( (hz - support - clearance).abs() < 0.01, "clearance at waypoint {dy}: {}", hz - support ); break; } assert!(index < 899, "blocked for waypoint {dy}: {hx}, {hy}, {hz}"); let step = plan_player_motion_with_collision( &engine, cockpit, input.toward(hero, [x, y], 0.8), |step| { app.resolve_player_building_step(step) .map_err(EngineError::Movement) }, ) .unwrap() .unwrap(); now += 100; hero = pose(frame_with_player_motion(&mut engine, now, cockpit, step, false).unwrap()); let new_z = f32::from_bits(hero.position[2]); assert!( (new_z - hz).abs() < 0.3, "height jump at {hx} {hy}: {hz} -> {new_z}" ); } } } }