aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--apps/fparkan-game/src/damage_visibility.rs22
-rw-r--r--apps/fparkan-game/src/debris.rs135
-rw-r--r--apps/fparkan-game/src/destruction_effects.rs14
-rw-r--r--apps/fparkan-game/src/main.rs9
-rw-r--r--crates/fparkan-runtime/src/destruction.rs47
-rw-r--r--crates/fparkan-runtime/src/lib.rs2
-rw-r--r--crates/fparkan-runtime/src/projectile.rs7
-rw-r--r--crates/fparkan-runtime/src/unit_combat.rs5
-rw-r--r--docs/appendices/knowledge-boundaries.md5
-rw-r--r--docs/tomes/06-behavior.md11
10 files changed, 189 insertions, 68 deletions
diff --git a/apps/fparkan-game/src/damage_visibility.rs b/apps/fparkan-game/src/damage_visibility.rs
index 5179d9f6..14d6a39b 100644
--- a/apps/fparkan-game/src/damage_visibility.rs
+++ b/apps/fparkan-game/src/damage_visibility.rs
@@ -12,6 +12,7 @@ pub(super) fn apply(
poses: &[Vec<Option<NodePoseBuffer>>],
mesh: &VulkanStaticMesh,
renderer: &mut VulkanSmokeRenderer,
+ fragment_is_visible: impl Fn(usize) -> bool,
) -> Result<(), String> {
for (object, node) in depleted_chassis_nodes(engine) {
let Some(component) = geometry
@@ -21,20 +22,20 @@ pub(super) fn apply(
else {
continue;
};
- let model = &component.model;
- if model.node_stride != 38
- || model.animation.is_none()
- || !poses
- .get(object)
- .and_then(|v| v.first())
- .is_some_and(Option::is_some)
+ if !poses
+ .get(object)
+ .and_then(|v| v.first())
+ .is_some_and(Option::is_some)
{
continue;
}
let Some(ranges) = node_draw_ranges(mesh, component, object, node) else {
continue;
};
- for range in ranges {
+ for range in ranges
+ .into_iter()
+ .filter(|&range| !fragment_is_visible(range))
+ {
renderer
.set_draw_range_index_count(range, 0)
.map_err(|error| format!("hide damaged chassis node {object}:{node}: {error}"))?;
@@ -43,12 +44,15 @@ pub(super) fn apply(
Ok(())
}
-fn node_draw_ranges(
+pub(super) fn node_draw_ranges(
mesh: &VulkanStaticMesh,
component: &DynamicComponentGeometry,
object: usize,
node: usize,
) -> Option<Vec<usize>> {
+ if component.model.node_stride != 38 || component.model.animation.is_none() {
+ return None;
+ }
let owner = u32::try_from(object.checked_add(1)?).ok()?;
let end = component.vertex_start.checked_add(component.vertex_count)?;
let vertices = component.vertex_start..end;
diff --git a/apps/fparkan-game/src/debris.rs b/apps/fparkan-game/src/debris.rs
index b67fb44d..b595b441 100644
--- a/apps/fparkan-game/src/debris.rs
+++ b/apps/fparkan-game/src/debris.rs
@@ -1,11 +1,12 @@
//! Reuse the dead unit's already uploaded component ranges as loose meshes.
-use super::DynamicComponentGeometry;
+use super::{damage_visibility::node_draw_ranges, DynamicComponentGeometry};
use fparkan_animation::Pose;
use fparkan_assets::TerrainWorld;
use fparkan_render_vulkan::{VulkanStaticMesh, VulkanStaticVertex};
-use fparkan_runtime::DebrisMotion;
+use fparkan_runtime::{DebrisMotion, DestroyedMesh};
use fparkan_terrain::SurfaceQuery;
+use std::ops::Range;
pub(super) struct MeshFragment {
center: [f32; 3],
@@ -16,6 +17,33 @@ pub(super) struct MeshFragment {
}
pub(super) fn capture(
+ destroyed: DestroyedMesh,
+ origin: [f32; 3],
+ geometry: &[Vec<Option<DynamicComponentGeometry>>],
+ mesh: &VulkanStaticMesh,
+ terrain: &TerrainWorld,
+) -> Vec<MeshFragment> {
+ match destroyed {
+ DestroyedMesh::Mounted { object_index } => {
+ capture_mounted(object_index, origin, geometry, mesh, terrain)
+ }
+ DestroyedMesh::ChassisNode {
+ object_index,
+ node,
+ hull_origin,
+ } => {
+ let root = geometry
+ .get(object_index)
+ .and_then(|parts| parts.first())
+ .and_then(Option::as_ref);
+ root.and_then(|root| capture_node(object_index, node, hull_origin, root, mesh, terrain))
+ .into_iter()
+ .collect()
+ }
+ }
+}
+
+fn capture_mounted(
object_index: usize,
hull: [f32; 3],
geometry: &[Vec<Option<DynamicComponentGeometry>>],
@@ -34,7 +62,6 @@ pub(super) fn capture(
.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()
@@ -44,39 +71,83 @@ pub(super) fn capture(
(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,
- })
+ capture_fragment(mesh, window, ranges, hull, terrain)
})
.collect()
}
+fn capture_node(
+ object: usize,
+ node: usize,
+ hull: [f32; 3],
+ root: &DynamicComponentGeometry,
+ mesh: &VulkanStaticMesh,
+ terrain: &TerrainWorld,
+) -> Option<MeshFragment> {
+ let ranges = node_draw_ranges(mesh, root, object, node)?;
+ if ranges.windows(2).any(|pair| pair[1] != pair[0] + 1) {
+ return None;
+ }
+ let first = mesh.draw_ranges.get(*ranges.first()?)?;
+ let last = mesh.draw_ranges.get(*ranges.last()?)?;
+ let index_end = last.first_index.checked_add(last.index_count)?;
+ let indices = mesh
+ .indices
+ .get(first.first_index as usize..index_end as usize)?;
+ let vertex_start = *indices.first()? as usize;
+ let vertex_end = vertex_start.checked_add(indices.len())?;
+ let window = vertex_start..vertex_end;
+ // The Node38 projector expands the selected batches in triangle order.
+ if !indices
+ .iter()
+ .map(|&index| index as usize)
+ .eq(window.clone())
+ {
+ return None;
+ }
+ capture_fragment(mesh, window, ranges, hull, terrain)
+}
+
+fn capture_fragment(
+ mesh: &VulkanStaticMesh,
+ window: Range<usize>,
+ ranges: Vec<usize>,
+ hull: [f32; 3],
+ terrain: &TerrainWorld,
+) -> Option<MeshFragment> {
+ if ranges.is_empty() {
+ return None;
+ }
+ let vertex_start = window.start;
+ let vertices = mesh.vertices.get(window)?;
+ 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,
+ vertices: vertices.to_vec(),
+ ranges,
+ })
+}
+
impl MeshFragment {
pub(super) fn draw(&self, elapsed: f32, mesh: &mut VulkanStaticMesh, terrain: &TerrainWorld) {
let pose = self.motion.pose(elapsed);
diff --git a/apps/fparkan-game/src/destruction_effects.rs b/apps/fparkan-game/src/destruction_effects.rs
index 97f7436a..5f05e2f9 100644
--- a/apps/fparkan-game/src/destruction_effects.rs
+++ b/apps/fparkan-game/src/destruction_effects.rs
@@ -13,7 +13,9 @@ use fparkan_fx::{
FxCommand, FxOpcode,
};
use fparkan_render_vulkan::{VulkanPointLight, VulkanStaticMesh};
-use fparkan_runtime::{unit_destruction_effect_sources, Engine, UnitDestructionEffect};
+use fparkan_runtime::{
+ unit_destruction_effect_sources, DestroyedMesh, Engine, UnitDestructionEffect,
+};
use std::{
collections::{BTreeMap, HashMap, HashSet},
path::{Path, PathBuf},
@@ -44,7 +46,7 @@ mod tests {
let position = [23.0, 45.0, 10.0];
effects.start(
vec![UnitDestructionEffect {
- object_index: None,
+ mesh: None,
position,
archive: "system.rlb".into(),
name: "explode_rbr_b.exp".into(),
@@ -244,10 +246,10 @@ impl DestructionEffects {
events: Vec<UnitDestructionEffect>,
now: u32,
mut audio: Option<&mut GameAudio>,
- mut capture_fragments: impl FnMut(usize, [f32; 3]) -> Vec<MeshFragment>,
+ mut capture_fragments: impl FnMut(DestroyedMesh, [f32; 3]) -> Vec<MeshFragment>,
) {
for UnitDestructionEffect {
- object_index,
+ mesh,
position,
archive,
name,
@@ -291,9 +293,9 @@ impl DestructionEffects {
effect: Arc::clone(effect),
clock,
position,
- fragments: object_index
+ fragments: mesh
.filter(|_| effect.fragments)
- .map_or_else(Vec::new, |index| capture_fragments(index, position)),
+ .map_or_else(Vec::new, |geometry| capture_fragments(geometry, position)),
});
}
}
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index 0d134277..ae1e80a5 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -11404,9 +11404,9 @@ impl StaticVulkanApp {
fparkan_runtime::take_unit_destruction_effects(engine),
control_clock_ms,
self.audio.as_mut(),
- |index, origin| {
+ |mesh, origin| {
debris::capture(
- index,
+ mesh,
origin,
&self.dynamic_component_geometry,
&self.mesh,
@@ -11967,6 +11967,11 @@ impl StaticVulkanApp {
&self.component_pose_buffers,
&self.mesh,
renderer,
+ |range| {
+ self.destruction_effects
+ .as_ref()
+ .is_some_and(|effects| effects.keeps_range(range))
+ },
)?;
}
if !self.removed_mission_roots.is_empty() || self.boarded_hero_index.is_some() {
diff --git a/crates/fparkan-runtime/src/destruction.rs b/crates/fparkan-runtime/src/destruction.rs
index 8fb3a1bf..7ed316da 100644
--- a/crates/fparkan-runtime/src/destruction.rs
+++ b/crates/fparkan-runtime/src/destruction.rs
@@ -6,10 +6,28 @@ use crate::{
};
use fparkan_world::{identity_metadata, transform_state};
+/// Geometry supplied by the destroyed object to its authored explosion.
+pub enum DestroyedMesh {
+ /// Mounted models after the loss of the whole chassis.
+ Mounted {
+ /// Prepared actor index.
+ object_index: usize,
+ },
+ /// One separated node of a still live chassis.
+ ChassisNode {
+ /// Prepared actor index.
+ object_index: usize,
+ /// Local node of the root model.
+ node: usize,
+ /// World position of the hull at impact.
+ hull_origin: [f32; 3],
+ },
+}
+
/// Position and attached EXPL resource of a destroyed chassis or building part.
pub struct UnitDestructionEffect {
- /// Prepared draft index for the destroyed actor when it has an authored layout.
- pub object_index: Option<usize>,
+ /// Prepared mesh to move when the effect requests built-in fragments.
+ pub mesh: Option<DestroyedMesh>,
/// World-space origin of the effect.
pub position: [f32; 3],
/// Archive containing the explosion description.
@@ -67,13 +85,30 @@ pub fn unit_destruction_effect_sources(
}
pub(super) fn part_effect(
+ engine: &Engine,
row: &MissionControlNodeProviderRow,
- position: [f32; 3],
+ contact: super::ProjectileContact,
) -> Option<UnitDestructionEffect> {
let (archive, name) = node_effect(row)?;
+ let mesh = match contact.node {
+ Some(super::ProjectileNode::Chassis(node))
+ if row.current_flags.is_some_and(|flags| flags & 2 == 0) =>
+ {
+ let id = identity_metadata(&engine.world, contact.handle)
+ .ok()?
+ .original_id?;
+ let hull = transform_state(&engine.world, contact.handle).ok()?;
+ Some(DestroyedMesh::ChassisNode {
+ object_index: id.0 as usize,
+ node: node as usize,
+ hull_origin: hull.position.map(f32::from_bits),
+ })
+ }
+ _ => None,
+ };
Some(UnitDestructionEffect {
- object_index: None,
- position,
+ mesh,
+ position: contact.position,
archive,
name,
})
@@ -104,7 +139,7 @@ pub(super) fn pending_effect(
.position
.map(f32::from_bits);
Some(UnitDestructionEffect {
- object_index,
+ mesh: object_index.map(|object_index| DestroyedMesh::Mounted { object_index }),
position,
archive,
name,
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 20613c00..1fcb00ae 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -80,7 +80,7 @@ pub use debris_motion::DebrisMotion;
mod destruction;
pub use destruction::{
collect_unit_destruction_effects, take_unit_destruction_effects,
- unit_destruction_effect_sources, UnitDestructionEffect,
+ unit_destruction_effect_sources, DestroyedMesh, UnitDestructionEffect,
};
mod flight_altitude;
mod ground_support;
diff --git a/crates/fparkan-runtime/src/projectile.rs b/crates/fparkan-runtime/src/projectile.rs
index 70c9ab77..d4f23243 100644
--- a/crates/fparkan-runtime/src/projectile.rs
+++ b/crates/fparkan-runtime/src/projectile.rs
@@ -313,7 +313,7 @@ pub fn apply_projectile_contact(
}
// shortcut: feed the projectile NDP volume into the native reduction while impact falloff is open.
let effect = (volume >= remaining && engine.destruction_effects.is_some())
- .then(|| super::destruction::part_effect(row, contact.position))
+ .then(|| super::destruction::part_effect(engine, row, contact))
.flatten();
let updated = apply_loaded_mission_control_node_delta(engine, contact.handle, key, -volume)?;
if updated.is_some() {
@@ -465,6 +465,9 @@ mod tests {
let effects = take_unit_destruction_effects(&mut engine);
assert_eq!(effects.len(), 1);
assert_eq!(effects[0].position, contact.position);
+ assert!(
+ matches!(effects[0].mesh, Some(crate::DestroyedMesh::ChassisNode { object_index: 14, node: key, .. }) if key == node as usize)
+ );
}
#[test]
@@ -515,7 +518,7 @@ mod tests {
panic!("expected one EXPL at the failed part");
};
assert_eq!(effect.position, contact.position);
- assert_eq!(effect.object_index, None);
+ assert!(effect.mesh.is_none());
assert_eq!(effect.name, "explode_frt_b.exp");
assert!(unit_destruction_effect_sources(&engine)
.any(|source| source == (effect.archive.clone(), effect.name.clone())));
diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs
index eaab747a..593570cf 100644
--- a/crates/fparkan-runtime/src/unit_combat.rs
+++ b/crates/fparkan-runtime/src/unit_combat.rs
@@ -911,9 +911,8 @@ mod tests {
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
- })
+ && matches!(event.mesh, Some(crate::DestroyedMesh::Mounted { object_index })
+ if drafts[object_index].original_id.map(|id| id.0) == retired.original_id)
&& event
.position
.iter()
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index dba6f69c..ae40be84 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -146,8 +146,9 @@ authoring API без динамического подтверждения.
`player_projectile_damage_approx` отмечает расчёт от исходного NDP снаряда
и немедленное удаление при гибели. Защита Control 27 уменьшает урон.
`player_projectile_hull_stub` остаётся для навесных моделей и живых поз.
-Исчерпанные узлы шасси без замещающей модели скрываются. Полёт отдельных
-частей, смена стадий, тени и влияние повреждений на движение ещё открыты.
+Исчерпанные узлы шасси без замещающей модели скрываются. `Op10` с пустой
+ссылкой запускает полёт такой детали по приближённой баллистике.
+Смена стадий, тени и влияние повреждений на движение ещё открыты.
Медузы уязвимы для этого урона и отвечают штатным `ba_a_03` с места.
Дальность, выбор цели и движение животных остаются в `unit_behavior_stub`.
Уничтожение корпуса запускает `Op1`, `Op2` и первый спрайт `Op3` типа 0
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index 4364b6b6..5edbfade 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -2736,11 +2736,12 @@ Simulation читает подготовленный input snapshot. Renderer н
даже если её слот уже занял другой объект.
Если FXID содержит `Op10` с пустой ссылкой на геометрию, FParkan
-берёт уже загруженные навесные детали машины. Поза в последнем кадре
-становится началом полёта. Например, башня продолжает полёт как отдельная
-модель, вращается и оседает на грунт. Скорость броска выбирается по размеру
-детали, а время показа берётся из заголовка FXID. Это приближение: смысл
-параметров `Op10` и правила отделения при попадании ещё открыты.
+берёт уже загруженную геометрию. При гибели корпуса это навесные детали,
+а при истощении секции шасси без замещающей модели это её собственные
+треугольники. Например, `exp_rbr_l` у гусеницы тяжёлого варбота содержит
+такой `Op10` и показывает обломок до шести секунд. Поза детали в последнем
+кадре становится началом полёта. Скорость броска выбирается по размеру
+детали. Смысл параметров `Op10` и точная баллистика ещё открыты.
В оригинале `Control.dll+0x10f30` при исчерпании корневого или критического
узла начинает процедуру уничтожения. В AutoDemo обработчик `0x10030`