//! Apply the directional Control field before hull resistance. use crate::{ control_device_budget_coefficient, control_device_selector_zero, fixed_words_ascii_c_string, projectile::{segment_point, segment_sphere_entrance, unit_sphere}, turret_aim::hull_local_point, weapon_pose::WeaponPoses, Engine, LoadedMissionState, MissionAssets, MissionControlDeviceTableStatus, MissionObjectDraft, ProjectileContact, }; use fparkan_render::LegacyIron3dEulerTransform; use fparkan_world::{transform_state, TransformState}; /// One shield pulse triggered on the side that intercepted a projectile. pub struct ShieldImpact { /// The owning object draft, which determines the effect instance pool. pub object_index: usize, /// Authored archive and resource name of the protection device. pub source: (String, String), /// World matrix centered on the shield and directed toward the contact. pub world_from_effect: [[f32; 4]; 4], } /// Sphere entrances before the first physical collision, in travel order. pub(super) fn shield_crossings( engine: &Engine, shooter: crate::ObjectHandle, segment: [[f32; 3]; 2], stop: Option, ) -> Vec { let Some(mission) = &engine.loaded else { return Vec::new(); }; let passenger = mission.boarding.map(|boarding| boarding.hero.handle); let mut crossings: Vec<_> = mission .control_device_tables .iter() .filter_map(|table| { if table.handle == shooter || passenger == Some(table.handle) { return None; } let MissionControlDeviceTableStatus::Available(devices) = &table.status else { return None; }; if !devices.iter().any(|device| device.factory_tag == 9) { return None; } let pose = transform_state(&engine.world, table.handle).ok()?; let index = table.original_id?.0 as usize; let (center, radius) = contact_sphere(mission, index, pose)?; let fraction = segment_sphere_entrance(segment, center, radius)?; stop.is_none_or(|limit| fraction < limit) .then(|| ProjectileContact { handle: table.handle, fraction, position: segment_point(segment, fraction), node: None, }) }) .collect(); crossings.sort_by(|a, b| a.fraction.total_cmp(&b.fraction)); crossings } fn contact_sphere( mission: &LoadedMissionState, index: usize, pose: TransformState, ) -> Option<([f32; 3], f32)> { mission .shield_spheres .get(index) .copied() .flatten() .and_then(|sphere| world_sphere(sphere, pose)) .or_else(|| unit_sphere(&mission.mission_assets, index, pose)) } pub(super) fn prepare_shield_spheres( assets: &MissionAssets, drafts: &[MissionObjectDraft], ) -> Vec> { drafts .iter() .enumerate() .map(|(index, draft)| { let controls = assets.object_component_controls.get(index)?; if draft.unit_dat_header_flags != Some(crate::boarding::WARBOT_CLASS) || !controls .iter() .flatten() .flat_map(|control| &control.typed_records) .any(|record| record.tag == 9) { return None; } let poses = WeaponPoses::new(draft, assets, index); enclosing_sphere(&poses.initial_model_spheres(assets, index)) }) .collect() } /// Enables collection of transient shield pulses for the presentation layer. pub fn collect_shield_impacts(engine: &mut Engine) { engine.shield_impacts = Some(Vec::new()); } /// Drains shield pulses accumulated since the last presentation update. pub fn take_shield_impacts(engine: &mut Engine) -> Vec { engine .shield_impacts .as_mut() .map_or_else(Vec::new, std::mem::take) } /// Finds authored shield effects for placed units and prepared spawn slots. pub fn shield_effect_sources( engine: &Engine, ) -> impl Iterator + '_ { engine.loaded.iter().flat_map(|mission| { mission .mission_assets .object_component_controls .iter() .enumerate() .flat_map(|(object, controls)| { shield_effects_for_components(controls).map(move |key| (object, key)) }) }) } pub(super) fn shield_effects_for_components( controls: &[Option], ) -> impl Iterator + '_ { controls.iter().flatten().flat_map(|control| { control .typed_records .iter() .filter(|record| record.tag == 9) .filter_map(|record| shield_effect_source(&record.fixed_words)) }) } fn shield_effect_source(words: &[u32; 44]) -> Option<(String, String)> { let archive = fixed_words_ascii_c_string(&words[27..35])?; let name = fixed_words_ascii_c_string(&words[35..43])?; (!archive.is_empty() && !name.is_empty()).then_some((archive, name)) } pub(super) fn absorb(engine: &mut Engine, hit: ProjectileContact, volume: f32) -> f32 { if !volume.is_finite() || volume <= 0.0 { return volume; } let Some(mission) = engine.loaded.as_mut() else { return volume; }; let Some(table_index) = mission .control_device_tables .iter() .position(|table| table.handle == hit.handle) else { return volume; }; let Some(index) = mission.control_device_tables[table_index] .original_id .map(|id| id.0 as usize) else { return volume; }; let Ok(pose) = transform_state(&engine.world, hit.handle) else { return volume; }; let Some((center, radius)) = contact_sphere(mission, index, pose) else { return volume; }; let shield_pose = TransformState { position: center.map(f32::to_bits), scale: [1.0_f32.to_bits(); 3], ..pose }; let Some(sector) = hull_local_point(shield_pose, hit.position).and_then(contact_sector) else { return volume; }; let MissionControlDeviceTableStatus::Available(devices) = &mut mission.control_device_tables[table_index].status else { return volume; }; let Some(strength) = devices.iter().rfind(|device| device.factory_tag == 21) else { return volume; }; let Ok(multiplier) = control_device_budget_coefficient(strength, sector) else { return volume; }; let Some(shield) = devices.iter_mut().rfind(|device| device.factory_tag == 9) else { return volume; }; let Ok(base) = control_device_selector_zero(shield) else { return volume; }; let (Some(values), Some(deltas)) = ( &mut shield.class9_values_bits, &mut shield.class9_deltas_bits, ) else { return volume; }; let fraction = f32::from_bits(values[sector]); let capacity = base * fraction * multiplier; if !capacity.is_finite() || capacity <= 0.0 { return volume; } let (remaining, strength_left) = intercept(volume, capacity); // The projectile callback writes the remaining power through Control+0x2ca80. let delta = (strength_left / multiplier - base * fraction) / base; let updated = (fraction + delta).clamp(0.0, 1.0); values[sector] = updated.to_bits(); deltas[sector] = (f32::from_bits(deltas[sector]) + (updated - fraction)).to_bits(); if let Some(impacts) = engine.shield_impacts.as_mut() { if let Some(source) = shield_effect_source(&shield.descriptor.fixed_words) { let offset = std::array::from_fn(|axis| hit.position[axis] - center[axis]); impacts.push(ShieldImpact { object_index: index, source, world_from_effect: effect_transform(center, offset, radius), }); } } remaining } pub(super) fn world_sphere( (center, radius): ([f32; 3], f32), pose: TransformState, ) -> Option<([f32; 3], f32)> { let scale = pose.scale.map(f32::from_bits); let transform = LegacyIron3dEulerTransform { translation: pose.position.map(f32::from_bits), orientation_radians: pose.orientation.map(f32::from_bits), }; Some(( transform.try_transform_scaled_point(center, scale)?, radius * scale.into_iter().map(f32::abs).fold(0.0, f32::max), )) } pub(super) fn enclosing_sphere(parts: &[([f32; 3], f32)]) -> Option<([f32; 3], f32)> { // AniMesh+0x9510 weights centers by the authored radii. A second pass // puts even the most distant part inside the result. let weight: f32 = parts.iter().map(|(_, radius)| radius).sum(); if weight <= 0.0 { return None; } let center = std::array::from_fn(|axis| { parts .iter() .map(|(point, radius)| point[axis] * radius) .sum::() / weight }); let radius = parts .iter() .map(|(point, radius)| { let distance_sq: f32 = (0..3) .map(|axis| (center[axis] - point[axis]).powi(2)) .sum(); distance_sq.sqrt() + radius }) .fold(0.0, f32::max); Some((center, radius)) } fn effect_transform(center: [f32; 3], [x, y, z]: [f32; 3], radius: f32) -> [[f32; 4]; 4] { // Control+0x2c844 builds X from the incident side of the sphere, Y in the // horizontal plane, and Z as their cross product. let horizontal = x.hypot(y); let length = horizontal.hypot(z); let [nx, ny, nz] = [x / length, y / length, z / length]; let [tx, ty] = if horizontal > 0.0 { [-y / horizontal, x / horizontal] } else { [1.0, 0.0] }; [ [radius * nx, radius * tx, -radius * nz * ty, center[0]], [radius * ny, radius * ty, radius * nz * tx, center[1]], [radius * nz, 0.0, radius * (nx * ty - ny * tx), center[2]], [0.0, 0.0, 0.0, 1.0], ] } fn contact_sector([x, y, z]: [f32; 3]) -> Option { if ![x, y, z].into_iter().all(f32::is_finite) || [x, y, z] == [0.0; 3] { return None; } Some(if y.abs() >= x.abs().max(z.abs()) { usize::from(y < 0.0) } else if x.abs() >= z.abs() { 2 + usize::from(x < 0.0) } else { 4 + usize::from(z < 0.0) }) } fn intercept(volume: f32, capacity: f32) -> (f32, f32) { ((volume - capacity).max(0.0), (capacity - volume).max(0.0)) } #[cfg(test)] mod tests { use super::*; #[test] fn enclosing_sphere_uses_radii_to_weight_the_center() { let parts = [([0.0; 3], 2.0), ([6.0, 0.0, 0.0], 1.0)]; assert_eq!(enclosing_sphere(&parts), Some(([2.0, 0.0, 0.0], 5.0))); assert_eq!(enclosing_sphere(&[]), None); } #[test] fn shield_spends_strength_before_dealing_hull_damage() { assert_eq!(intercept(899.0, 3040.0), (0.0, 2141.0)); assert_eq!(intercept(220.0, 235.0), (0.0, 15.0)); assert_eq!(intercept(235.0, 235.0), (0.0, 0.0)); assert_eq!(intercept(260.0, 235.0), (25.0, 0.0)); assert_eq!(intercept(260.0, 0.0), (260.0, 0.0)); assert_eq!(contact_sector([1.0, 1.0, 1.0]), Some(0)); assert_eq!(contact_sector([1.0, -2.0, 1.0]), Some(1)); assert_eq!(contact_sector([-2.0, 0.2, 1.0]), Some(3)); assert_eq!(contact_sector([-1.0, 0.2, -2.0]), Some(5)); } #[test] #[ignore = "requires licensed corpus"] fn licensed_autodemo_grazing_shot_can_pierce_a_field_and_miss_the_body() { use crate::{ create, load_gameplay_mission, projectile::segment_sphere_fraction, projectile_terrain_hit, projectile_unit_hit, EngineServices, MissionMode, MissionRequest, MissionStartupInput, PlayerProjectile, ProjectileFlightHit, }; use fparkan_vfs::DirectoryVfs; use fparkan_world::{handle_by_original_id, OriginalObjectId}; use std::sync::Arc; let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus"); let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap(); load_gameplay_mission( &mut engine, MissionRequest { key: "MISSIONS/Autodemo.00/data.tma".into(), mode: MissionMode::AutoDemo, }, MissionStartupInput { queue_time_ms: 0, research_creation_gate: false, }, None, ) .unwrap(); let target = handle_by_original_id(&engine.world, OriginalObjectId(0)).unwrap(); let shooter = handle_by_original_id(&engine.world, OriginalObjectId(1)).unwrap(); let pose = transform_state(&engine.world, target).unwrap(); let mission = engine.loaded.as_ref().unwrap(); let table = mission .control_device_tables .iter() .find(|table| table.handle == target) .unwrap(); let health_before = table.node_provider_amount_bits; let MissionControlDeviceTableStatus::Available(devices) = &table.status else { panic!("stock shield and resistance devices"); }; let shield = devices .iter() .rfind(|device| device.factory_tag == 9) .unwrap(); let resistance = devices .iter() .rfind(|device| device.factory_tag == 21) .unwrap(); let (center, radius) = contact_sphere(mission, 0, pose).unwrap(); let (hull_center, hull_radius) = unit_sphere(&mission.mission_assets, 0, pose).unwrap(); let (segment, crossing) = (0..2) .flat_map(|axis| (-10..=10).flat_map(move |a| (-10..=10).map(move |b| (axis, a, b)))) .find_map(|(axis, a, b)| { let mut line = center; line[1 - axis] += a as f32 * radius / 10.0; line[2] += b as f32 * radius / 10.0; let mut segment = [line; 2]; segment[0][axis] -= radius * 2.0; segment[1][axis] += radius * 2.0; segment_sphere_fraction(segment, hull_center, hull_radius)?; let crossings = shield_crossings(&engine, shooter, segment, None); let [crossing] = crossings.as_slice() else { return None; }; (crossing.handle == target && crossing.fraction < 0.5 && projectile_unit_hit(&engine, shooter, segment).is_none() && projectile_terrain_hit(&mission.terrain, segment) .ok()? .is_none()) .then_some((segment, *crossing)) }) .expect( "a stock shot crosses the field and chassis sphere while missing all triangles", ); let shield_pose = TransformState { position: center.map(f32::to_bits), scale: [1.0_f32.to_bits(); 3], ..pose }; let sector = contact_sector(hull_local_point(shield_pose, crossing.position).unwrap()).unwrap(); let capacity = control_device_selector_zero(shield).unwrap() * control_device_budget_coefficient(resistance, sector).unwrap(); assert!(capacity > 0.0); let direction = std::array::from_fn(|i| segment[1][i] - segment[0][i]); let speed = direction .into_iter() .map(|axis| axis * axis) .sum::() .sqrt(); let launch = |volume| { PlayerProjectile::new(segment[0], direction, speed, 2_000, 0) .unwrap() .with_volume(Some(volume)) }; collect_shield_impacts(&mut engine); let stopped = launch(capacity * 0.5) .advance_in_world(&mut engine, shooter, 500) .unwrap(); assert!(matches!(stopped.hit, Some(ProjectileFlightHit::Shield))); assert!(!stopped.flying); assert!(stopped.segment.unwrap()[1] .into_iter() .zip(crossing.position) .all(|(actual, expected)| (actual - expected).abs() < 0.001)); assert_eq!(take_shield_impacts(&mut engine).len(), 1); let mut flight = launch(capacity * 0.5 + 20.0); let pierced = flight.advance_in_world(&mut engine, shooter, 500).unwrap(); assert!(pierced.flying && pierced.hit.is_none()); assert!((pierced.volume.unwrap() - 20.0).abs() < 0.001); assert_eq!(take_shield_impacts(&mut engine).len(), 1); let tail = flight .advance_in_world(&mut engine, shooter, 1_000) .unwrap(); assert!(tail.flying && tail.hit.is_none()); assert_eq!(tail.volume, pierced.volume); assert!(take_shield_impacts(&mut engine).is_empty()); let table = engine .loaded .as_ref() .unwrap() .control_device_tables .iter() .find(|table| table.handle == target) .unwrap(); assert_eq!(table.node_provider_amount_bits, health_before); } #[test] #[ignore = "requires licensed corpus"] fn licensed_autodemo_shield_blocks_and_then_exposes_one_sector() { use crate::{ apply_projectile_impact, create, load_gameplay_mission, EngineServices, MissionMode, MissionRequest, MissionStartupInput, ProjectileImpact, }; use fparkan_vfs::DirectoryVfs; use std::sync::Arc; let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus"); let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap(); load_gameplay_mission( &mut engine, MissionRequest { key: "MISSIONS/Autodemo.00/data.tma".into(), mode: MissionMode::AutoDemo, }, MissionStartupInput { queue_time_ms: 0, research_creation_gate: false, }, None, ) .unwrap(); let mission = engine.loaded.as_ref().unwrap(); let (contact, sector, capacity, health) = mission .control_device_tables .iter() .find_map(|table| { let MissionControlDeviceTableStatus::Available(devices) = &table.status else { return None; }; let shield = devices.iter().rfind(|device| device.factory_tag == 9)?; let strength = devices.iter().rfind(|device| device.factory_tag == 21)?; let pose = transform_state(&engine.world, table.handle).ok()?; let index = table.original_id?.0 as usize; let (center, _) = world_sphere(mission.shield_spheres[index]?, pose)?; let (hull_center, _) = unit_sphere(&mission.mission_assets, index, pose)?; let position = std::array::from_fn(|axis| (center[axis] + hull_center[axis]) * 0.5); let at = |origin: [f32; 3]| TransformState { position: origin.map(f32::to_bits), scale: [1.0_f32.to_bits(); 3], ..pose }; let sector = hull_local_point(at(center), position).and_then(contact_sector)?; let hull_sector = hull_local_point(at(hull_center), position).and_then(contact_sector)?; if sector == hull_sector { return None; } let capacity = control_device_selector_zero(shield).ok()? * f32::from_bits(shield.class9_values_bits?[sector]) * control_device_budget_coefficient(strength, sector).ok()?; if capacity <= 0.0 { return None; } let hit = ProjectileContact { handle: table.handle, fraction: 0.5, position, node: None, }; Some((hit, sector, capacity, table.node_provider_amount_bits?)) }) .expect("stock shield whose assembled center changes the selected sector"); // Headless combat and rendering must spend charge from the same side. assert_eq!( apply_projectile_impact(&mut engine, contact, capacity * 0.25).unwrap(), ProjectileImpact::ShieldAbsorbed ); collect_shield_impacts(&mut engine); let (center, radius) = engine.loaded.as_ref().unwrap().shield_spheres[0] .expect("stock AutoDemo warbot enclosure"); assert!(center[2] > 0.0 && radius > 6.0); assert_eq!( apply_projectile_impact(&mut engine, contact, capacity * 0.25).unwrap(), ProjectileImpact::ShieldAbsorbed ); let impacts = take_shield_impacts(&mut engine); let [impact] = impacts.as_slice() else { panic!("charged sector starts one shield effect"); }; assert!(shield_effect_sources(&engine) .any(|(object, source)| object == impact.object_index && source == impact.source)); assert!(impact .world_from_effect .into_iter() .flatten() .all(f32::is_finite)); let table = engine .loaded .as_ref() .unwrap() .control_device_tables .iter() .find(|table| table.handle == contact.handle) .unwrap(); assert_eq!(table.node_provider_amount_bits, Some(health)); let MissionControlDeviceTableStatus::Available(devices) = &table.status else { panic!("missing shield devices"); }; let shield = devices .iter() .rfind(|device| device.factory_tag == 9) .unwrap(); let charges = shield.class9_values_bits.unwrap().map(f32::from_bits); let mut expected = [1.0; 6]; expected[sector] = 0.5; assert!(charges .iter() .zip(expected) .all(|(a, b)| (a - b).abs() < 1e-6)); assert!((absorb(&mut engine, contact, capacity * 0.5 + 20.0) - 20.0).abs() < 0.001); assert_eq!(take_shield_impacts(&mut engine).len(), 1); assert_eq!(absorb(&mut engine, contact, capacity * 0.5), capacity * 0.5); assert!(take_shield_impacts(&mut engine).is_empty()); } }