diff options
Diffstat (limited to 'apps/fparkan-game/src/main.rs')
| -rw-r--r-- | apps/fparkan-game/src/main.rs | 338 |
1 files changed, 79 insertions, 259 deletions
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index a090802c..3f1fbaa6 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -19,6 +19,11 @@ mod mission_notices; mod mission_pause; mod motion_effects; mod player_collision; +#[cfg(test)] +use fparkan_runtime::query_building_segment_world; +#[cfg(test)] +use player_collision::building_collision_nodes; +use player_collision::{building_collision_binding, BuildingCollisionBinding}; mod player_fire; mod player_footsteps; mod projectile_render; @@ -82,8 +87,10 @@ use fparkan_fx::{advance_native_fx_random_state, decode_fxid, FxCommand, FxDocum use fparkan_material::{MaterialAnimationBlock, MaterialKey}; use fparkan_msh::{ node38_fallback_hierarchy, node38_sampled_hierarchy, node38_sampled_hierarchy_at_times, - selected_slot, Group, Lod, ModelAsset, NodeId, SlotId, + ModelAsset, }; +#[cfg(test)] +use fparkan_msh::{NodeId, SlotId}; use fparkan_path::{normalize_relative, PathPolicy, ResourceName}; use fparkan_platform_winit::{window_native_handles, WinitWindow, WinitWindowPlan}; use fparkan_prototype::{unit_component_tree, PROTOTYPE_TYPE_EXTO}; @@ -114,11 +121,11 @@ use fparkan_runtime::{ load_mission_static_preview_roots, loaded_mission_assets, loaded_mission_object_drafts, loaded_terrain, mission_object_handle, order_lab_research, plan_player_motion_with_collision, player_vehicle, prepared_warbot_weapons, projectile_terrain_hit, projectile_unit_hit, - query_building_segment_world, simulate_mission_report, starting_cockpit, - starting_player_weapons, AutoDemoCamera, AutoDemoView, BuildingMeshNode, Engine, EngineError, - EngineServices, FrameResult, LoadedMission, MissionAssets, MissionEventStop, MissionMode, - MissionObjectDraft, MissionRequest, MissionStartupInput, PlayerMotion, PlayerProjectile, - PlayerWeapons, ProjectileImpact, StartingCockpit, SIMULATION_COVERAGE, + simulate_mission_report, starting_cockpit, starting_player_weapons, AutoDemoCamera, + AutoDemoView, Engine, EngineError, EngineServices, FrameResult, LoadedMission, MissionAssets, + MissionEventStop, MissionMode, MissionObjectDraft, MissionRequest, MissionStartupInput, + PlayerMotion, PlayerProjectile, PlayerWeapons, ProjectileImpact, StartingCockpit, + SIMULATION_COVERAGE, }; #[cfg(test)] use fparkan_runtime::{load_mission_with_init_stubs, plan_player_motion}; @@ -4877,208 +4884,6 @@ fn live_placements( placements } -#[derive(Clone)] -struct BuildingCollisionBinding { - object_index: usize, - component_index: usize, - model_source: String, - model: Arc<ModelAsset>, - root_transform: LegacyIron3dEulerTransform, - owner_scale: [f32; 3], - mounted: bool, - selected_nodes: Vec<(NodeId, SlotId)>, -} - -fn building_collision_binding( - object_index: usize, - component_index: usize, - model_source: String, - model: Arc<ModelAsset>, - root_transform: LegacyIron3dEulerTransform, - owner_scale: [f32; 3], - mounted: bool, -) -> Result<BuildingCollisionBinding, String> { - 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_nodes.push((node, slot)); - } - } - Ok(BuildingCollisionBinding { - object_index, - component_index, - model_source, - model, - root_transform, - owner_scale, - mounted, - selected_nodes, - }) -} - -fn building_collision_nodes( - binding: &BuildingCollisionBinding, - pose_buffer: Option<&NodePoseBuffer>, - mount_pose: Option<VulkanNodePose>, -) -> Result<Vec<BuildingMeshNode>, 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() - .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: *node, - slot: *slot, - world_from_node, - }) - }) - .collect() -} - -fn component_node_world_matrix( - root_transform: LegacyIron3dEulerTransform, - owner_scale: [f32; 3], - mount_pose: Option<VulkanNodePose>, - 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) -} - #[derive(Clone, Debug)] struct DynamicShadowCaster { caster_index: usize, @@ -10713,52 +10518,6 @@ impl StaticVulkanApp { projectile_render::sample_autonomous(&mut self.autodemo_draws, engine); } - fn building_segment_blocked(&self, world_segment: [[f32; 3]; 2]) -> Result<bool, String> { - Ok(self.building_segment_hit(world_segment, false)?.is_some()) - } - - fn building_segment_hit( - &self, - world_segment: [[f32; 3]; 2], - nearest: bool, - ) -> Result<Option<[f32; 3]>, String> { - let mut best = None; - 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 nodes = building_collision_nodes(binding, pose_buffer, mount_pose)?; - 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)) - } - fn sample_frame_clock(&mut self) -> FrameClockSample { if let Some(target_ms) = self.control_clock_target_ms { let time_ms = @@ -13648,6 +13407,62 @@ mod tests { } #[test] + fn building_movement_query_follows_the_visible_damage_stage() { + let mut model = collision_fixture_model(false); + model.nodes_raw[56..58].copy_from_slice(&1_u16.to_le_bytes()); + model.slots.push(Slot { + tri_start: 1, + batch_start: 1, + aabb_min: [6.0, 0.0, -2.0], + aabb_max: [10.0, 0.0, 2.0], + sphere_center: [8.0, 0.0, 0.0], + ..model.slots[0].clone() + }); + let damaged_positions = model + .positions + .iter() + .map(|&[x, y, z]| [x + 8.0, y, z]) + .collect::<Vec<_>>(); + model.positions.extend(damaged_positions); + model.indices.extend([0, 1, 2]); + model.batches.push(Batch { + index_start: 3, + base_vertex: 3, + ..model.batches[0].clone() + }); + let descriptors = model.triangle_descriptors.as_mut().unwrap(); + descriptors.push(descriptors[0].clone()); + let binding = building_collision_binding( + 0, + 0, + "wall damage stage".into(), + Arc::new(model), + LegacyIron3dEulerTransform { + translation: [0.0; 3], + orientation_radians: [0.0; 3], + }, + [1.0; 3], + false, + ) + .unwrap(); + let poses = node38_sampled_hierarchy(&binding.model, 0).unwrap(); + let traverse = [[0.0, 1.0, 0.0], [0.0, -1.0, 0.0]]; + let intact = building_collision_nodes(&binding, Some(&poses), None, |_| 0).unwrap(); + assert!( + query_building_segment_world(&binding.model, &intact, traverse) + .unwrap() + .is_some() + ); + let damaged = building_collision_nodes(&binding, Some(&poses), None, |_| 1).unwrap(); + assert_eq!(damaged[0].slot, SlotId(1)); + assert!( + query_building_segment_world(&binding.model, &damaged, traverse) + .unwrap() + .is_none() + ); + } + + #[test] fn mounted_static_building_binding_matches_renderer_and_hides_root_node() { let model = collision_fixture_model(true); let binding = building_collision_binding( @@ -13692,7 +13507,7 @@ mod tests { translation: [5.0, 7.0, 11.0], rotation: [0.0, 0.0, 0.38268343, 0.9238795], }; - let nodes = building_collision_nodes(&binding, Some(&hierarchy), Some(mount)) + let nodes = building_collision_nodes(&binding, Some(&hierarchy), Some(mount), |_| 0) .expect("mounted collision matrices"); assert_eq!(nodes.len(), 1); assert_eq!(nodes[0].node, fparkan_msh::NodeId(1)); @@ -13859,7 +13674,7 @@ mod tests { let hierarchy = static_preview_component_pose_buffer(&model, &[], None) .expect("fixture static preview pose") .expect("fixture Node38 pose"); - let nodes = building_collision_nodes(&binding, Some(&hierarchy), None) + let nodes = building_collision_nodes(&binding, Some(&hierarchy), None, |_| 0) .expect("small-scale collision matrix"); assert!(query_building_segment_world( &binding.model, @@ -14242,9 +14057,13 @@ mod tests { let hierarchy = app.component_pose_buffers[4][0] .as_ref() .expect("PLANT current root pose"); - let plant_nodes = - building_collision_nodes(&plant, Some(hierarchy), app.component_mount_poses[4][0]) - .expect("PLANT current collision nodes"); + let plant_nodes = building_collision_nodes( + &plant, + Some(hierarchy), + app.component_mount_poses[4][0], + |_| 0, + ) + .expect("PLANT current collision nodes"); let plant_node = plant_nodes .iter() .copied() @@ -14408,6 +14227,7 @@ mod tests { &plant, Some(open_hierarchy), app.component_mount_poses[4][0], + |_| 0, ) .expect("sampled PLANT collision nodes"); assert!( |
