diff options
| author | Valentin Popov <valentin@popov.link> | 2026-11-26 06:21:39 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-11-26 06:21:39 +0300 |
| commit | f0a92313d0628eda8e163ab0608ce8fcbedaad95 (patch) | |
| tree | 203c15e66a577e621b88c28428e01a55d9fac37c | |
| parent | 8f1ba615bf1e393698eae7624073c1ad9f54c02b (diff) | |
| download | fparkan-f0a92313d0628eda8e163ab0608ce8fcbedaad95.tar.xz fparkan-f0a92313d0628eda8e163ab0608ce8fcbedaad95.zip | |
feat(combat): show detached assemblies after chassis destruction
| -rw-r--r-- | apps/fparkan-game/src/debris.rs | 106 | ||||
| -rw-r--r-- | apps/fparkan-game/src/destruction_effects.rs | 52 | ||||
| -rw-r--r-- | apps/fparkan-game/src/main.rs | 37 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/debris_motion.rs | 85 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/destruction.rs | 14 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 2 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_combat.rs | 21 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 4 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 7 |
9 files changed, 301 insertions, 27 deletions
diff --git a/apps/fparkan-game/src/debris.rs b/apps/fparkan-game/src/debris.rs new file mode 100644 index 00000000..b67fb44d --- /dev/null +++ b/apps/fparkan-game/src/debris.rs @@ -0,0 +1,106 @@ +//! Reuse the dead unit's already uploaded component ranges as loose meshes. + +use super::DynamicComponentGeometry; +use fparkan_animation::Pose; +use fparkan_assets::TerrainWorld; +use fparkan_render_vulkan::{VulkanStaticMesh, VulkanStaticVertex}; +use fparkan_runtime::DebrisMotion; +use fparkan_terrain::SurfaceQuery; + +pub(super) struct MeshFragment { + center: [f32; 3], + motion: DebrisMotion, + vertex_start: usize, + vertices: Vec<VulkanStaticVertex>, + pub(super) ranges: Vec<usize>, +} + +pub(super) fn capture( + object_index: usize, + hull: [f32; 3], + geometry: &[Vec<Option<DynamicComponentGeometry>>], + mesh: &VulkanStaticMesh, + terrain: &TerrainWorld, +) -> Vec<MeshFragment> { + let Some(components) = geometry.get(object_index) else { + return Vec::new(); + }; + let Ok(owner_scope) = u32::try_from(object_index + 1) else { + return Vec::new(); + }; + components + .iter() + .skip(1) + .flatten() + .filter_map(|component| { + let window = component.vertex_start..component.vertex_start + component.vertex_count; + let vertices = mesh.vertices.get(window.clone())?; + let ranges: Vec<_> = mesh + .draw_ranges + .iter() + .enumerate() + .filter_map(|(i, range)| { + let vertex = *mesh.indices.get(range.first_index as usize)? as usize; + (range.owner_scope == owner_scope && window.contains(&vertex)).then_some(i) + }) + .collect(); + if ranges.is_empty() { + return None; + } + let mut min = [f32::INFINITY; 3]; + let mut max = [f32::NEG_INFINITY; 3]; + for vertex in vertices { + for i in 0..3 { + min[i] = min[i].min(vertex.position[i]); + max[i] = max[i].max(vertex.position[i]); + } + } + let center = std::array::from_fn(|i| (min[i] + max[i]) * 0.5); + let radius = (0..3) + .map(|i| (max[i] - center[i]).powi(2)) + .sum::<f32>() + .sqrt(); + let floor = terrain + .height_at([center[0], center[1]]) + .ok() + .flatten() + .unwrap_or(hull[2]); + let motion = DebrisMotion::new(center, hull, radius, floor + max[2] - center[2])?; + Some(MeshFragment { + center, + motion, + vertex_start: component.vertex_start, + vertices: vertices.to_vec(), + ranges, + }) + }) + .collect() +} + +impl MeshFragment { + pub(super) fn draw(&self, elapsed: f32, mesh: &mut VulkanStaticMesh, terrain: &TerrainWorld) { + let pose = self.motion.pose(elapsed); + let [x, y, _] = pose.translation; + let rotate = Pose { + translation: [0.0; 3], + ..pose + }; + let vertices = &mut mesh.vertices[self.vertex_start..][..self.vertices.len()]; + for (dst, src) in vertices.iter_mut().zip(&self.vertices) { + *dst = *src; + dst.position = + pose.transform_point(std::array::from_fn(|i| src.position[i] - self.center[i])); + dst.normal = rotate.transform_point(src.normal); + } + if let Ok(Some(floor)) = terrain.height_at([x, y]) { + let bottom = vertices + .iter() + .map(|vertex| vertex.position[2]) + .fold(f32::INFINITY, f32::min); + let lift = (floor - bottom).max(0.0); + for vertex in vertices { + vertex.position[2] += lift; + } + } + } +} diff --git a/apps/fparkan-game/src/destruction_effects.rs b/apps/fparkan-game/src/destruction_effects.rs index e4e0ac1a..b73d5985 100644 --- a/apps/fparkan-game/src/destruction_effects.rs +++ b/apps/fparkan-game/src/destruction_effects.rs @@ -2,11 +2,11 @@ use super::{ ambient_effect_pipeline_state, ambient_effect_vertex_rgb, append_effect_material_animation, - append_environment_range, audio::GameAudio, environment_vertex_with_alpha, - native_command_phase, prepare_effect_material, quad_indices, EnvironmentGpuRange, - MaterialAnimationBinding, PreparedEffectMaterial, StaticPreviewScene, + append_environment_range, audio::GameAudio, debris::MeshFragment, + environment_vertex_with_alpha, native_command_phase, prepare_effect_material, quad_indices, + EnvironmentGpuRange, MaterialAnimationBinding, PreparedEffectMaterial, StaticPreviewScene, }; -use fparkan_assets::{decode_explosion_effect, load_resource_entry_bytes_from_root}; +use fparkan_assets::{decode_explosion_effect, load_resource_entry_bytes_from_root, TerrainWorld}; use fparkan_fx::{ ambient_op3::evaluate_op3_type0_command, ambient_sound::Op2SoundCommand, clock::FxInstanceClock, decode_fxid, environment::evaluate_op1_point_light_with_basis, @@ -15,7 +15,7 @@ use fparkan_fx::{ use fparkan_render_vulkan::{VulkanPointLight, VulkanStaticMesh}; use fparkan_runtime::{unit_destruction_effect_sources, Engine, UnitDestructionEffect}; use std::{ - collections::{BTreeMap, HashMap}, + collections::{BTreeMap, HashMap, HashSet}, path::{Path, PathBuf}, sync::Arc, }; @@ -27,6 +27,7 @@ struct Explosion { lights: Vec<FxCommand>, sound: Option<Op2SoundCommand>, sprite_pool: Option<usize>, + fragments: bool, } #[cfg(test)] @@ -43,12 +44,14 @@ mod tests { let position = [23.0, 45.0, 10.0]; effects.start( vec![UnitDestructionEffect { + object_index: None, position, archive: "system.rlb".into(), name: "explode_rbr_b.exp".into(), }], 100, None, + |_, _| Vec::new(), ); let mut lights = Vec::new(); let mut mesh = VulkanStaticMesh { @@ -61,6 +64,7 @@ mod tests { assert_eq!(lights[0].position, position); assert_eq!(lights[0].range, 15.0); assert!(effects.active[0].effect.sound.is_some()); + assert!(effects.active[0].effect.fragments); lights.clear(); effects.sample(1_300, &mut lights, &mut mesh, &mut [], [0.0; 3]); assert!((lights[0].range - 10.0).abs() < 0.0001); @@ -102,7 +106,13 @@ impl Explosion { command.opcode == FxOpcode::Op3 && command.raw_body.starts_with(&[0; 4]) }) .map(|(index, command)| (index, command.clone())); - (!lights.is_empty() || sound.is_some() || sprite.is_some()).then_some(( + let fragments = fx.commands().iter().any(|command| { + command.opcode == FxOpcode::Op10 + && command.resource_refs.first().is_some_and(|reference| { + reference.archive_name().is_empty() && reference.resource_name().is_empty() + }) + }); + (!lights.is_empty() || sound.is_some() || sprite.is_some() || fragments).then_some(( Self { duration: header.duration_seconds, flags: header.flags, @@ -110,6 +120,7 @@ impl Explosion { lights, sound, sprite_pool: None, + fragments, }, sprite, )) @@ -120,6 +131,7 @@ struct ActiveExplosion { effect: Arc<Explosion>, clock: FxInstanceClock, position: [f32; 3], + fragments: Vec<MeshFragment>, } struct BlastSpritePool { @@ -139,6 +151,7 @@ pub(super) struct DestructionEffects { cache: HashMap<(String, String), Option<Arc<Explosion>>>, active: Vec<ActiveExplosion>, sprites: Vec<BlastSpritePool>, + visible_fragments: HashSet<usize>, } impl DestructionEffects { @@ -148,6 +161,7 @@ impl DestructionEffects { cache: HashMap::new(), active: Vec::new(), sprites: Vec::new(), + visible_fragments: HashSet::new(), } } @@ -230,8 +244,10 @@ impl DestructionEffects { events: Vec<UnitDestructionEffect>, now: u32, mut audio: Option<&mut GameAudio>, + mut capture_fragments: impl FnMut(usize, [f32; 3]) -> Vec<MeshFragment>, ) { for UnitDestructionEffect { + object_index, position, archive, name, @@ -275,6 +291,9 @@ impl DestructionEffects { effect: Arc::clone(effect), clock, position, + fragments: object_index + .filter(|_| effect.fragments) + .map_or_else(Vec::new, |index| capture_fragments(index, position)), }); } } @@ -325,6 +344,27 @@ impl DestructionEffects { }); } + pub(super) fn draw_fragments( + &mut self, + now: u32, + mesh: &mut VulkanStaticMesh, + terrain: &TerrainWorld, + ) { + self.visible_fragments.clear(); + for active in &self.active { + if let Some(elapsed) = active.clock.elapsed_seconds(now as f32) { + for fragment in &active.fragments { + fragment.draw(elapsed, mesh, terrain); + self.visible_fragments.extend(&fragment.ranges); + } + } + } + } + + pub(super) fn keeps_range(&self, index: usize) -> bool { + self.visible_fragments.contains(&index) + } + pub(super) fn inactive_ranges(&self) -> impl Iterator<Item = usize> + '_ { self.sprites .iter() diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index ce5b178f..2888502e 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -8,6 +8,7 @@ mod camera_capture; mod chassis_animation; #[cfg(windows)] mod control_effects; +mod debris; mod destruction_effects; use control_effects::{ activate_firing_flashes, advance_control_effect_instances, owner_control_capacity, @@ -11362,6 +11363,24 @@ impl StaticVulkanApp { .map_or_else(HashMap::new, |frame| { live_placements(&mut self.mission_render_roots, &frame.snapshot) }); + if let (Some(engine), Some(effects)) = + (&mut self.mission_engine, &mut self.destruction_effects) + { + effects.start( + fparkan_runtime::take_unit_destruction_effects(engine), + control_clock_ms, + self.audio.as_mut(), + |index, origin| { + debris::capture( + index, + origin, + &self.dynamic_component_geometry, + &self.mesh, + &self.terrain, + ) + }, + ); + } update_dynamic_component_geometry( &self.dynamic_component_geometry, &self.component_pose_buffers, @@ -11471,14 +11490,7 @@ impl StaticVulkanApp { &self.removed_mission_roots, ); let mut control_vulkan_lights = active_control_point_lights(&control_point_lights); - if let (Some(engine), Some(effects)) = - (&mut self.mission_engine, &mut self.destruction_effects) - { - effects.start( - fparkan_runtime::take_unit_destruction_effects(engine), - control_clock_ms, - self.audio.as_mut(), - ); + if let Some(effects) = &mut self.destruction_effects { effects.sample( control_clock_ms, &mut control_vulkan_lights, @@ -11486,6 +11498,7 @@ impl StaticVulkanApp { &mut self.material_animations, self.view_camera.position, ); + effects.draw_fragments(control_clock_ms, &mut self.mesh, &self.terrain); } let effect_updates = update_ambient_effect_geometry( &mut self.ambient_effect_slots, @@ -11915,8 +11928,12 @@ impl StaticVulkanApp { if !self.removed_mission_roots.is_empty() || self.boarded_hero_index.is_some() { for (index, range) in self.mesh.draw_ranges.iter().enumerate() { if range.owner_scope.checked_sub(1).is_some_and(|owner| { - self.removed_mission_roots.contains(&(owner as usize)) - || self.boarded_hero_index == Some(owner as usize) + self.boarded_hero_index == Some(owner as usize) + || (self.removed_mission_roots.contains(&(owner as usize)) + && !self + .destruction_effects + .as_ref() + .is_some_and(|effects| effects.keeps_range(index))) }) { renderer .set_draw_range_index_count(index, 0) diff --git a/crates/fparkan-runtime/src/debris_motion.rs b/crates/fparkan-runtime/src/debris_motion.rs new file mode 100644 index 00000000..286bc2b1 --- /dev/null +++ b/crates/fparkan-runtime/src/debris_motion.rs @@ -0,0 +1,85 @@ +//! Ballistic presentation of a detached mesh assembly. + +use fparkan_animation::Pose; + +const GRAVITY: f32 = 9.81; + +/// A visual fragment travelling from its last attached center. +pub struct DebrisMotion { + center: [f32; 3], + outward: [f32; 2], + launch_speed: f32, + angular_speed: f32, + landing_seconds: f32, +} + +impl DebrisMotion { + /// Launches a fragment outward with enough energy to lift it one radius. + pub fn new(center: [f32; 3], hull: [f32; 3], radius: f32, floor_center: f32) -> Option<Self> { + if !center + .into_iter() + .chain(hull) + .chain([radius, floor_center]) + .all(f32::is_finite) + || radius <= 0.0 + { + return None; + } + let [x, y] = [center[0] - hull[0], center[1] - hull[1]]; + let length = x.hypot(y); + let outward = if length > f32::EPSILON { + [x / length, y / length] + } else { + [0.0, 1.0] + }; + let launch_speed = (2.0 * GRAVITY * radius).sqrt(); + let height = (center[2] - floor_center).max(0.0); + let landing_seconds = + (launch_speed + (launch_speed.powi(2) + 2.0 * GRAVITY * height).sqrt()) / GRAVITY; + Some(Self { + center, + outward, + launch_speed, + angular_speed: launch_speed / radius, + landing_seconds, + }) + } + + /// Returns the new center and rotation. Rotation and travel stop at landing. + pub fn pose(&self, elapsed_seconds: f32) -> Pose { + let time = elapsed_seconds.clamp(0.0, self.landing_seconds); + let travel = self.launch_speed * time; + let [x, y] = self.outward; + let (sin, cos) = (0.5 * self.angular_speed * time).sin_cos(); + Pose { + translation: [ + self.center[0] + x * travel, + self.center[1] + y * travel, + self.center[2] + travel - 0.5 * GRAVITY * time.powi(2), + ], + rotation: [y * sin, -x * sin, 0.0, cos], + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fragment_begins_attached_and_stops_on_landing() { + let center = [2.0, 5.0, 4.0]; + let motion = DebrisMotion::new(center, [0.0, 5.0, 0.0], 1.0, 1.0).unwrap(); + assert_eq!( + motion.pose(0.0), + Pose { + translation: center, + ..Pose::default() + } + ); + assert!(motion.pose(0.2).translation[0] > center[0]); + assert!(motion.pose(0.2).translation[2] > center[2]); + assert_eq!(motion.pose(4.0), motion.pose(6.0)); + assert!((motion.pose(4.0).translation[2] - 1.0).abs() < 0.00001); + } +} diff --git a/crates/fparkan-runtime/src/destruction.rs b/crates/fparkan-runtime/src/destruction.rs index 38a4e38f..89688de5 100644 --- a/crates/fparkan-runtime/src/destruction.rs +++ b/crates/fparkan-runtime/src/destruction.rs @@ -1,10 +1,12 @@ //! Presentation events for projectile damage that destroys a unit. use crate::{autodemo::MOBILE_UNIT, Engine, MissionControlDeviceTableState, ObjectHandle}; -use fparkan_world::transform_state; +use fparkan_world::{identity_metadata, transform_state}; /// Position and attached EXPL resource of a chassis at lethal contact. pub struct UnitDestructionEffect { + /// Prepared draft index for the destroyed actor when it has an authored layout. + pub object_index: Option<usize>, /// World-space origin of the destroyed chassis. pub position: [f32; 3], /// Archive containing the explosion description. @@ -60,11 +62,21 @@ pub(super) fn pending_effect( .iter() .find(|table| table.handle == handle)?; let (archive, name) = root_effect(table)?; + let object_index = identity_metadata(&engine.world, handle) + .ok() + .and_then(|identity| identity.original_id) + .and_then(|id| { + mission + .object_drafts + .iter() + .position(|draft| draft.original_id == Some(id)) + }); let position = transform_state(&engine.world, handle) .ok()? .position .map(f32::from_bits); Some(UnitDestructionEffect { + object_index, position, archive, name, diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 1ed90b32..b27c0090 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -75,6 +75,8 @@ mod clan_script_init; mod clan_targeting; mod construction; mod construction_site; +mod debris_motion; +pub use debris_motion::DebrisMotion; mod destruction; pub use destruction::{ collect_unit_destruction_effects, take_unit_destruction_effects, diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs index f1e86aab..60123dcd 100644 --- a/crates/fparkan-runtime/src/unit_combat.rs +++ b/crates/fparkan-runtime/src/unit_combat.rs @@ -825,14 +825,6 @@ mod tests { .iter() .find(|event| matches!(event, AutoDemoCombatEvent::Destroyed { .. })) { - assert!(destruction_effects.iter().any(|event| { - event.archive == "system.rlb" - && event.name == "explode_rbr_b.exp" - && event - .position - .iter() - .all(|coordinate| coordinate.is_finite()) - })); assert!(identity_metadata(&engine.world, *target).is_err()); let ((_, retired), total) = combat .report @@ -842,7 +834,18 @@ mod tests { object.slot == target.slot && object.generation == target.generation }) .expect("removed target is still reported"); - assert!(retired.original_id.is_some()); + let drafts = &engine.loaded.as_ref().unwrap().object_drafts; + assert!(destruction_effects.iter().any(|event| { + event.archive == "system.rlb" + && event.name == "explode_rbr_b.exp" + && event.object_index.is_some_and(|index| { + drafts[index].original_id.map(|id| id.0) == retired.original_id + }) + && event + .position + .iter() + .all(|coordinate| coordinate.is_finite()) + })); assert_eq!(total.first_ms, now); assert_eq!(total.count, 1); assert!(observed_shots > 0); diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index ce1c7cc2..d937c8b7 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -146,7 +146,9 @@ Behavior: самостоятельная защита до получения п `player_projectile_damage_approx` отмечает урон по корневому NDP и немедленное удаление. Уничтожение корпуса запускает `Op1`, `Op2` и первый спрайт `Op3` типа 0 из `EXPL` версии 1. Остальные версии и неподдержанные источники отмечает -`unit_destruction_effect_stub`. Частицы и отделение обломков пока открыты. +`unit_destruction_effect_stub`. При `Op10` с пустой ссылкой навесные +модели летят по приближённой баллистике после гибели корпуса. +Параметры `Op10`, частицы и отстрел отдельных узлов открыты. `player_projectile_hull_stub` и `player_weapon_fx_stub` отмечают проверку по сфере вместо узлов у машин и открытые эффекты выстрела. `projectile_trail_approx` отмечает слои следа `Op5` с одной лентой на слой. Разбиение ленты на части и фазы материала остаются открыты. diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index fb07b730..94c567c1 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -2686,6 +2686,13 @@ Simulation читает подготовленный input snapshot. Renderer н и затухает за 2,4 секунды. Эффект остаётся на месте гибели машины, даже если её слот уже занял другой объект. +Если FXID содержит `Op10` с пустой ссылкой на геометрию, FParkan +берёт уже загруженные навесные детали машины. Поза в последнем кадре +становится началом полёта. Например, башня продолжает полёт как отдельная +модель, вращается и оседает на грунт. Скорость броска выбирается по размеру +детали, а время показа берётся из заголовка FXID. Это приближение: смысл +параметров `Op10` и правила отделения при попадании ещё открыты. + В оригинале `Control.dll+0x10f30` при исчерпании корневого узла начинает отдельную процедуру уничтожения. Точная формула урона, проверка отдельных частей юнита и фазы разрушения ещё открыты. |
