diff options
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/fparkan-runtime/src/autodemo_combat.rs | 55 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 36 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/player_status.rs | 25 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/projectile.rs | 127 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_patrol.rs | 20 |
5 files changed, 239 insertions, 24 deletions
diff --git a/crates/fparkan-runtime/src/autodemo_combat.rs b/crates/fparkan-runtime/src/autodemo_combat.rs index ddf83a50..5a864eb9 100644 --- a/crates/fparkan-runtime/src/autodemo_combat.rs +++ b/crates/fparkan-runtime/src/autodemo_combat.rs @@ -1,5 +1,5 @@ use super::{ - apply_projectile_hit, + apply_projectile_contact, autodemo::MOBILE_UNIT, player_weapon::prepare_unit_weapons, projectile::{load_projectile, unit_sphere}, @@ -46,6 +46,17 @@ pub enum AutoDemoCombatEvent { /// Unit removed from the world. target: ObjectHandle, }, + /// An autonomous shot changed a building part's health. + BuildingHit { + /// Owner of the weapon. + shooter: ObjectHandle, + /// Building struck by the projectile. + target: ObjectHandle, + /// Provider row associated with the struck part. + node: u32, + /// Remaining health of the part as raw f32 bits. + remaining_bits: u32, + }, } pub(super) struct AutoDemoCombat { @@ -269,13 +280,22 @@ impl AutoDemoCombat { let data = &self.projectiles[flight.projectile]; match data .volume - .map(|volume| apply_projectile_hit(engine, hit.handle, volume)) + .map(|volume| apply_projectile_contact(engine, hit, volume)) { Some(Ok(Some((_, true)))) => events.push(AutoDemoCombatEvent::Destroyed { shooter: flight.shooter, target: hit.handle, }), - Some(Ok(Some((_, false)))) => {} + Some(Ok(Some((remaining, false)))) => { + if let Some(node) = hit.building_node { + events.push(AutoDemoCombatEvent::BuildingHit { + shooter: flight.shooter, + target: hit.handle, + node, + remaining_bits: remaining.to_bits(), + }); + } + } _ => unavailable += 1, } } @@ -293,9 +313,10 @@ impl AutoDemoCombat { let targets = self.targets(&engine.world, &mission.mission_assets); for unit in &mut self.units { // shortcut: armed AI units defend their position while their Init is incomplete. - let guard = identity_metadata(&engine.world, unit.handle) + let owner = identity_metadata(&engine.world, unit.handle) .ok() - .and_then(|identity| identity.owner_id) + .and_then(|identity| identity.owner_id); + let guard = owner .is_some_and(|owner| self.guard_clans.get(usize::from(owner.0)) == Some(&true)); if mission.script_host_mode == super::MissionMode::SingleMission && !guard @@ -320,6 +341,30 @@ impl AutoDemoCombat { None } } + }) + .or_else(|| { + let (factory, index) = + mission.unit_patrol.as_ref()?.raid_factory(unit.handle)?; + let target_owner = identity_metadata(&engine.world, factory).ok()?.owner_id?; + if self + .hostile + .get(usize::from(owner?.0))? + .get(usize::from(target_owner.0)) + != Some(&true) + { + return None; + } + let state = transform_state(&engine.world, unit.handle).ok()?; + let (from, _) = unit_sphere(&mission.mission_assets, unit.index, state)?; + let target = transform_state(&engine.world, factory).ok()?; + let (to, _) = unit_sphere(&mission.mission_assets, index, target)?; + if (to[0] - from[0]).hypot(to[1] - from[1]) > FIRE_RANGE { + return None; + } + // shortcut: aim at the root bounds center until the native attack task selects a node. + projectile_terrain_hit(&mission.terrain, [from, to]) + .is_ok_and(|ground| ground.is_none()) + .then_some((factory, from, to)) }); for (slot, _, _) in unit.weapons.fire(aim.is_some(), now) { let (Some((target, from, to)), Some(projectile)) = (aim, unit.slots[slot]) else { diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index d5b1a254..d4155228 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -76,8 +76,8 @@ pub use production::{ order_factory_scheme, }; pub use projectile::{ - apply_projectile_hit, load_player_projectile, projectile_terrain_hit, projectile_unit_hit, - PlayerProjectile, ProjectileAssets, ProjectileContact, + apply_projectile_contact, apply_projectile_hit, load_player_projectile, projectile_terrain_hit, + projectile_unit_hit, PlayerProjectile, ProjectileAssets, ProjectileContact, }; pub use research::order_lab_research; @@ -2780,7 +2780,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 mission_hero_exit_approx=1 laboratory_research_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 laboratory_research_approx=1 building_projectile_approx=1"; /// Totals from a headless mission coverage run. #[derive(Clone, Debug, Eq, PartialEq)] @@ -2859,6 +2859,7 @@ pub fn simulate_mission_report( AutoDemoCombatEvent::Destroyed { .. } => { report.autodemo_first_destroyed_ms.get_or_insert(clock_ms) } + AutoDemoCombatEvent::BuildingHit { .. } => continue, }; } if let Some(event) = frame.mission_event { @@ -16577,6 +16578,7 @@ mod tests { .any(|(handle, _)| *handle == target)); first_destroyed.get_or_insert(now); } + AutoDemoCombatEvent::BuildingHit { .. } => {} } } for replacement in result.autodemo_reinforcements { @@ -18229,10 +18231,21 @@ mod tests { .position .map(f32::from_bits); let mut first_shot = None; + let mut first_building_hit = None; for now in (0..=300_000).step_by(100) { let step = frame(&mut engine, now).unwrap(); for event in step.autodemo_combat_events { - if let AutoDemoCombatEvent::Shot { shooter, .. } = event { + if let AutoDemoCombatEvent::BuildingHit { + target, + node, + remaining_bits, + .. + } = event + { + if target == factory { + first_building_hit.get_or_insert((now, node, remaining_bits)); + } + } else if let AutoDemoCombatEvent::Shot { shooter, .. } = event { assert_eq!( fparkan_world::identity_metadata(&engine.world, shooter) .unwrap() @@ -18244,17 +18257,24 @@ mod tests { .position .map(f32::from_bits); if (sx - x).hypot(sy - y) < 400.0 { - first_shot = Some(now); - break; + first_shot.get_or_insert(now); } } } - if first_shot.is_some() { + if first_building_hit.is_some() { break; } } assert!(first_shot.is_some(), "no shots on the player side"); - println!("first raid shot in range of the player factory: {first_shot:?} ms"); + let (now, node, _) = first_building_hit.expect("raid damages the factory"); + assert_ne!(node, 0); + assert!(transform_state(&engine.world, factory).is_ok()); + let (current, maximum) = player_status(&engine, hero.handle) + .unwrap() + .factory_health + .unwrap(); + assert!(current < maximum); + println!("raid first shot {first_shot:?} ms, factory damage at {now} ms on node {node}"); assert_eq!(transform_state(&engine.world, hero.handle).unwrap(), start); } diff --git a/crates/fparkan-runtime/src/player_status.rs b/crates/fparkan-runtime/src/player_status.rs index 52af212c..637f5254 100644 --- a/crates/fparkan-runtime/src/player_status.rs +++ b/crates/fparkan-runtime/src/player_status.rs @@ -1,5 +1,5 @@ use crate::{Engine, MissionControlNodeProviderTableStatus}; -use fparkan_world::{identity_metadata, ObjectHandle}; +use fparkan_world::{handle_by_original_id, identity_metadata, ObjectHandle}; /// Current values for the player's controlled unit and clan. #[derive(Clone, Copy, Debug, PartialEq)] @@ -10,6 +10,8 @@ pub struct PlayerStatus { pub ore_in_buffer: Option<f32>, /// Available power and total power demand. pub power: Option<(f32, f32)>, + /// Combined current and initial health of the clan's live factories. + pub factory_health: Option<(f32, f32)>, } /// Reads the values used by combat and the clan's current distributor. @@ -40,6 +42,26 @@ pub fn player_status(engine: &Engine, controlled: ObjectHandle) -> Option<Player .iter() .find(|bundle| bundle.clan_index == usize::from(owner.0)) .and_then(|bundle| bundle.behavior_warm_start); + let mut factory_health = (0.0, 0.0); + for (current, maximum) in mission.object_drafts.iter().filter_map(|draft| { + if draft.unit_dat_header_flags != Some(super::autodemo::PLANT_CLASS) { + return None; + } + let handle = handle_by_original_id(&engine.world, draft.original_id?)?; + if identity_metadata(&engine.world, handle).ok()?.owner_id != Some(owner) { + return None; + } + let table = mission + .control_device_tables + .iter() + .find(|table| table.handle == handle)?; + table + .node_provider_amount_bits + .zip(table.node_provider_maximum_amount_bits) + }) { + factory_health.0 += f32::from_bits(current); + factory_health.1 += f32::from_bits(maximum); + } Some(PlayerStatus { health_percent, ore_in_buffer: resources.map(|state| f32::from_bits(state.cleared_words[2])), @@ -47,6 +69,7 @@ pub fn player_status(engine: &Engine, controlled: ObjectHandle) -> Option<Player let [available, _, _, demand, _] = state.cleared_words.map(f32::from_bits); (available, demand) }), + factory_health: (factory_health.1 > 0.0).then_some(factory_health), }) } diff --git a/crates/fparkan-runtime/src/projectile.rs b/crates/fparkan-runtime/src/projectile.rs index af9e075e..7e177a17 100644 --- a/crates/fparkan-runtime/src/projectile.rs +++ b/crates/fparkan-runtime/src/projectile.rs @@ -1,8 +1,13 @@ use crate::{ apply_loaded_mission_control_node_delta, ControlResourceAccessError, Engine, MissionAssets, MissionControlNodeProviderTableStatus, TerrainWorld, CONTROL_CLASS_SOURCE_BULL, + UNIT_DAT_CONTROL_CLASS_HIGH_BIT, +}; +use fparkan_assets::{AssetManager, PreparedModel}; +use fparkan_msh::{ + node38_fallback_hierarchy, query_slot_segment, selected_slot, Group, Lod, NodeId, + SegmentQueryMasks, }; -use fparkan_assets::AssetManager; use fparkan_prototype::{resolve_prototype_all, PrototypeSource}; use fparkan_render::LegacyIron3dEulerTransform; use fparkan_resource::{resource_name, CachedResourceRepository}; @@ -169,9 +174,11 @@ pub fn projectile_terrain_hit( pub struct ProjectileContact { pub handle: ObjectHandle, pub fraction: f32, + /// Provider row identified by a building triangle hit. + pub building_node: Option<u32>, } -/// Finds the first other unit intersected by this flight segment. +/// Finds the first unit or building intersected by this flight segment. pub fn projectile_unit_hit( engine: &Engine, shooter: ObjectHandle, @@ -186,7 +193,8 @@ pub fn projectile_unit_hit( .enumerate() .filter_map(|(index, draft)| { let class = draft.unit_dat_header_flags?; - if class & 0x0100_0000 == 0 { + let building = class & UNIT_DAT_CONTROL_CLASS_HIGH_BIT != 0; + if !building && class & super::autodemo::MOBILE_UNIT == 0 { return None; } let handle = handle_by_original_id(&engine.world, draft.original_id?)?; @@ -195,8 +203,19 @@ pub fn projectile_unit_hit( } let state = transform_state(&engine.world, handle).ok()?; let (center, radius) = unit_sphere(&mission.mission_assets, index, state)?; - let fraction = segment_sphere_fraction(segment, center, radius)?; - Some(ProjectileContact { handle, fraction }) + let sphere_fraction = segment_sphere_fraction(segment, center, radius)?; + let (fraction, building_node) = if building { + let (fraction, node) = + building_triangle_hit(&mission.mission_assets, index, state, segment)?; + (fraction, Some(node)) + } else { + (sphere_fraction, None) + }; + Some(ProjectileContact { + handle, + fraction, + building_node, + }) }) .min_by(|a, b| a.fraction.total_cmp(&b.fraction)) } @@ -206,8 +225,7 @@ pub(super) fn unit_sphere( index: usize, state: fparkan_world::TransformState, ) -> Option<([f32; 3], f32)> { - let visual = assets.visual_by_id(*assets.visuals_for_object(index).first()?)?; - let model = &assets.model_by_id(visual.model_id?)?.validated; + let model = &root_model(assets, index)?.validated; let scale = state.scale.map(f32::from_bits); let transform = LegacyIron3dEulerTransform { translation: state.position.map(f32::from_bits), @@ -218,6 +236,101 @@ pub(super) fn unit_sphere( Some((center, radius)) } +fn root_model(assets: &MissionAssets, index: usize) -> Option<&PreparedModel> { + let visual = assets.visual_by_id(*assets.visuals_for_object(index).first()?)?; + assets.model_by_id(visual.model_id?) +} + +fn building_triangle_hit( + assets: &MissionAssets, + index: usize, + state: fparkan_world::TransformState, + segment: [[f32; 3]; 2], +) -> Option<(f32, u32)> { + let model = &root_model(assets, index)?.validated; + let root = LegacyIron3dEulerTransform { + translation: state.position.map(f32::from_bits), + orientation_radians: state.orientation.map(f32::from_bits), + } + .try_row_major()?; + let scale = state.scale.map(f32::from_bits); + let mut body_segment = segment; + for (local, point) in body_segment.iter_mut().zip(segment) { + let [x, y, z] = [point[0] - root[3], point[1] - root[7], point[2] - root[11]]; + for i in 0..3 { + local[i] = (root[i] * x + root[i + 4] * y + root[i + 8] * z) / scale[i]; + } + } + // shortcut: use root MSH fallback poses until combat shares live component transforms. + let poses = node38_fallback_hierarchy(model)?; + let squared_length: f32 = (0..3) + .map(|i| (segment[1][i] - segment[0][i]).powi(2)) + .sum(); + if squared_length == 0.0 { + return None; + } + poses + .poses + .into_iter() + .enumerate() + .filter_map(|(i, pose)| { + let node = NodeId(u32::try_from(i).ok()?); + let slot = selected_slot(model, node, Lod(0), Group(0))?; + let mut inverse = pose; + inverse.translation = [0.0; 3]; + for component in &mut inverse.rotation[..3] { + *component = -*component; + } + let endpoints = body_segment.map(|point| { + inverse.transform_point(std::array::from_fn(|axis| { + point[axis] - pose.translation[axis] + })) + }); + let hit = + query_slot_segment(model, node, slot, endpoints, SegmentQueryMasks::default()) + .ok()??; + let body_hit = pose.transform_point(hit.position); + let distance: f32 = (0..3) + .map(|axis| ((body_hit[axis] - body_segment[0][axis]) * scale[axis]).powi(2)) + .sum(); + Some(((distance / squared_length).sqrt(), node.0)) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)) +} + +/// Applies projectile damage to the contacted part of a building or unit. +pub fn apply_projectile_contact( + engine: &mut Engine, + contact: ProjectileContact, + volume: f32, +) -> Result<Option<(f32, bool)>, ControlResourceAccessError> { + let Some(key) = contact.building_node else { + return apply_projectile_hit(engine, contact.handle, volume); + }; + let row = engine.loaded.as_ref().and_then(|mission| { + let table = mission + .control_device_tables + .iter() + .find(|table| table.handle == contact.handle)?; + super::control_node_provider_row(table, key).ok() + }); + let Some(row) = row else { + return Ok(None); + }; + let remaining = f32::from_bits(row.current_amount_bits); + if !volume.is_finite() + || volume <= 0.0 + || !remaining.is_finite() + || remaining <= 0.0 + || row.current_flags.is_some_and(|flags| flags & 0x10 != 0) + { + return Ok(None); + } + // shortcut: keep per-node damage using the projectile NDP volume while armor and splash are open. + let updated = apply_loaded_mission_control_node_delta(engine, contact.handle, key, -volume)?; + Ok(updated.map(|_| ((remaining - volume).max(0.0), false))) +} + fn segment_sphere_fraction( [start, end]: [[f32; 3]; 2], center: [f32; 3], diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs index 6c30e566..cfbee245 100644 --- a/crates/fparkan-runtime/src/unit_patrol.rs +++ b/crates/fparkan-runtime/src/unit_patrol.rs @@ -27,6 +27,7 @@ struct PatrollingUnit { points: VecDeque<[f32; 2]>, retry_ms: u32, attack: Option<ObjectHandle>, + raid_factory: Option<(ObjectHandle, usize)>, } pub(super) struct PreparedPatrol { @@ -68,7 +69,7 @@ impl UnitPatrol { } let clan = &mission.clans[bundle.clan_index]; - let factories = drafts.iter().filter(|draft| { + let factories = drafts.iter().enumerate().filter(|(_, draft)| { draft.unit_dat_header_flags == Some(PLANT_CLASS) && mission .clans @@ -91,9 +92,9 @@ impl UnitPatrol { (draft.position[0] - target.position[0]) .hypot(draft.position[1] - target.position[1]) }; - if let Some(factory) = factories + if let Some((index, factory)) = factories .clone() - .min_by(|a, b| distance(a).total_cmp(&distance(b))) + .min_by(|(_, a), (_, b)| distance(a).total_cmp(&distance(b))) { ordered |= self.order( world, @@ -101,6 +102,9 @@ impl UnitPatrol { [factory.position[0], factory.position[1]], 60.0, ); + if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == handle) { + unit.raid_factory = Some((handles[index], index)); + } } } self.factory_raid_clans += usize::from(ordered); @@ -126,6 +130,7 @@ impl UnitPatrol { self.units .retain(|unit| transform_state(world, unit.handle).is_ok()); if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == handle) { + unit.raid_factory = None; if unit.center != center || unit.radius != radius { unit.center = center; unit.radius = radius; @@ -142,6 +147,7 @@ impl UnitPatrol { points: VecDeque::new(), retry_ms: 0, attack: None, + raid_factory: None, }); true } @@ -150,6 +156,13 @@ impl UnitPatrol { self.units.iter().any(|unit| unit.handle == handle) } + pub(super) fn raid_factory(&self, handle: ObjectHandle) -> Option<(ObjectHandle, usize)> { + self.units + .iter() + .find(|unit| unit.handle == handle)? + .raid_factory + } + pub(super) fn activate(&mut self, world: &World, handle: ObjectHandle) { if let Some(center) = self.center { self.order(world, handle, center, 150.0); @@ -180,6 +193,7 @@ impl UnitPatrol { points: VecDeque::new(), retry_ms: 0, attack: None, + raid_factory: None, }) .collect(); Some(Self { |
