aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--apps/fparkan-game/src/audio.rs58
-rw-r--r--apps/fparkan-game/src/main.rs6
-rw-r--r--apps/fparkan-game/src/projectile_sound.rs91
-rw-r--r--crates/fparkan-runtime/src/lib.rs7
-rw-r--r--crates/fparkan-runtime/src/unit_combat.rs9
-rw-r--r--docs/appendices/knowledge-boundaries.md4
-rw-r--r--docs/tomes/06-behavior.md5
7 files changed, 146 insertions, 34 deletions
diff --git a/apps/fparkan-game/src/audio.rs b/apps/fparkan-game/src/audio.rs
index ec64df1e..256a88d2 100644
--- a/apps/fparkan-game/src/audio.rs
+++ b/apps/fparkan-game/src/audio.rs
@@ -16,7 +16,7 @@ use rodio::source::{ChannelVolume, SeekError};
use rodio::{
ChannelCount, Decoder, DeviceSinkBuilder, MixerDeviceSink, Player, SampleRate, Source,
};
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, BTreeSet};
use std::io::Cursor;
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -31,6 +31,13 @@ const AMBIENT_NIGHT_LENGTH: f32 = 1.1;
const AMBIENT_MIN_DELAY_SECONDS: f32 = 10.0;
const AMBIENT_DELAY_VARIANTS: u32 = 10;
+#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
+pub(crate) enum ControlSoundId {
+ Effect(usize),
+ PlayerProjectile(usize),
+ AutonomousProjectile(u64, usize),
+}
+
/// Position and orientation of the listener in world coordinates.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Listener {
@@ -631,7 +638,7 @@ pub(crate) struct GameAudio {
mission_voice: Player,
mission_cfg: NormalizedPath,
weather_loop: NativeSpatialPlayer,
- control_sounds: BTreeMap<usize, NativeSpatialPlayer>,
+ control_sounds: BTreeMap<ControlSoundId, NativeSpatialPlayer>,
one_shots: Vec<SpatialOneShot>,
library: AudioLibrary,
ambience: AmbienceScheduler,
@@ -855,7 +862,7 @@ impl GameAudio {
/// loop or another instance using the same sample.
pub(crate) fn handle_control_sound(
&mut self,
- id: usize,
+ id: ControlSoundId,
event: &SoundEvent,
) -> Result<(), AudioError> {
validate_point(event.position, "Control emitter")?;
@@ -879,7 +886,7 @@ impl GameAudio {
if let Some(previous) = self.control_sounds.insert(id, voice.player) {
previous.stop();
}
- eprintln!("control_sound_start id={id} resource={}:{} loop={} position={:?} range={}/{} frequency={}", event.archive, event.name, event.action == SoundAction::StartLoop, event.position, event.min_distance, event.max_distance, event.frequency_ratio);
+ eprintln!("control_sound_start id={id:?} resource={}:{} loop={} position={:?} range={}/{} frequency={}", event.archive, event.name, event.action == SoundAction::StartLoop, event.position, event.min_distance, event.max_distance, event.frequency_ratio);
}
SoundAction::SetLoopVolume => {
if let Some(player) = self.control_sounds.get(&id) {
@@ -896,14 +903,25 @@ impl GameAudio {
Ok(())
}
- pub(crate) fn stop_control_sound(&mut self, id: usize) {
+ pub(crate) fn stop_control_sound(&mut self, id: ControlSoundId) {
if let Some(player) = self.control_sounds.remove(&id) {
player.stop();
- eprintln!("control_sound_stop id={id}");
+ eprintln!("control_sound_stop id={id:?}");
}
}
- pub(crate) fn control_sound_is_playing(&self, id: usize) -> bool {
+ pub(crate) fn stop_finished_projectile_sounds(&mut self, live: &BTreeSet<u64>) {
+ self.control_sounds.retain(|id, player| {
+ if matches!(*id, ControlSoundId::AutonomousProjectile(flight, _) if !live.contains(&flight)) {
+ player.stop();
+ eprintln!("control_sound_stop id={id:?}");
+ return false;
+ }
+ true
+ });
+ }
+
+ pub(crate) fn control_sound_is_playing(&self, id: ControlSoundId) -> bool {
self.control_sounds
.get(&id)
.is_some_and(|player| !player.empty())
@@ -1983,13 +2001,13 @@ mod tests {
action: SoundAction::StartLoop,
};
audio
- .handle_control_sound(0, &machine)
+ .handle_control_sound(ControlSoundId::Effect(0), &machine)
.expect("first machine");
audio
- .handle_control_sound(1, &machine)
+ .handle_control_sound(ControlSoundId::Effect(1), &machine)
.expect("second machine");
- assert!(audio.control_sound_is_playing(0));
- assert!(audio.control_sound_is_playing(1));
+ assert!(audio.control_sound_is_playing(ControlSoundId::Effect(0)));
+ assert!(audio.control_sound_is_playing(ControlSoundId::Effect(1)));
assert!(!audio.weather_loop.empty());
audio.set_paused(true);
assert!(audio
@@ -2003,11 +2021,23 @@ mod tests {
.all(|player| !player.is_paused()));
machine.action = SoundAction::StopLoop;
audio
- .handle_control_sound(0, &machine)
+ .handle_control_sound(ControlSoundId::Effect(0), &machine)
.expect("stop one machine");
- assert!(!audio.control_sound_is_playing(0));
- assert!(audio.control_sound_is_playing(1));
+ assert!(!audio.control_sound_is_playing(ControlSoundId::Effect(0)));
+ assert!(audio.control_sound_is_playing(ControlSoundId::Effect(1)));
assert!(!audio.weather_loop.empty());
+ machine.action = SoundAction::StartLoop;
+ let manual = ControlSoundId::PlayerProjectile(1);
+ let expired = ControlSoundId::AutonomousProjectile(1, 0);
+ let flying = ControlSoundId::AutonomousProjectile(2, 0);
+ for id in [manual, expired, flying] {
+ audio.handle_control_sound(id, &machine).unwrap();
+ }
+ audio.stop_finished_projectile_sounds(&BTreeSet::from([2]));
+ assert!(!audio.control_sound_is_playing(expired));
+ for id in [ControlSoundId::Effect(1), manual, flying] {
+ assert!(audio.control_sound_is_playing(id));
+ }
audio
.update_listener([10.0, 20.0, 30.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0])
.expect("move listener");
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index 8d5c0c68..6f050780 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -11682,9 +11682,11 @@ impl StaticVulkanApp {
projectile_sound::update(
audio,
&mut self.projectile_draws,
- self.control_sound_slots.len(),
+ &self.autodemo_draws,
+ self.mission_engine.as_ref(),
)?;
for (id, sound) in self.control_sound_slots.iter_mut().enumerate() {
+ let id = audio::ControlSoundId::Effect(id);
let slot = &mut sound.effect;
if self
.removed_mission_roots
@@ -11731,7 +11733,7 @@ impl StaticVulkanApp {
) {
audio
.handle_control_sound(id, &event)
- .map_err(|error| format!("play Control sound {id}: {error}"))?;
+ .map_err(|error| format!("play Control sound {id:?}: {error}"))?;
}
}
}
diff --git a/apps/fparkan-game/src/projectile_sound.rs b/apps/fparkan-game/src/projectile_sound.rs
index d8eef2ef..bdb3eed6 100644
--- a/apps/fparkan-game/src/projectile_sound.rs
+++ b/apps/fparkan-game/src/projectile_sound.rs
@@ -1,7 +1,7 @@
-//! Spatial Op2 engine loops owned by live player projectiles.
+//! Spatial Op2 engine loops owned by live projectiles.
use super::{
- audio::GameAudio,
+ audio::{ControlSoundId, GameAudio},
control_matrix_from_columns, control_row_points, control_type4_effect_local_matrix,
matrix_to_row_major, multiply_row_major,
projectile_render::{flight_basis, ProjectileDraw, ProjectileEffect},
@@ -10,7 +10,8 @@ use fparkan_fx::{
ambient_sound::{Op2SoundCommand, Op2SoundState},
clock::{FxInstanceClock, FxPhaseProvider},
};
-use fparkan_runtime::{PlayerProjectile, ProjectileAssets};
+use fparkan_runtime::{autonomous_projectile_flights, Engine, PlayerProjectile, ProjectileAssets};
+use std::collections::BTreeSet;
pub(super) struct EngineSound {
command: Op2SoundCommand,
@@ -92,15 +93,55 @@ impl EngineSound {
playing,
)
}
+
+ fn update(
+ &self,
+ audio: &mut GameAudio,
+ id: ControlSoundId,
+ flight: &PlayerProjectile,
+ ) -> Result<(), String> {
+ if let Some(event) = self.sample(flight, audio.control_sound_is_playing(id)) {
+ audio
+ .handle_control_sound(id, &event)
+ .map_err(|error| format!("play projectile engine sound: {error}"))?;
+ }
+ Ok(())
+ }
}
pub(super) fn update(
audio: &mut GameAudio,
draws: &mut [Option<ProjectileDraw>],
- first_sound_id: usize,
+ autonomous_draws: &[Option<ProjectileDraw>],
+ engine: Option<&Engine>,
+) -> Result<(), String> {
+ update_player(audio, draws)?;
+ let mut live = BTreeSet::new();
+ for (flight_id, projectile, flight) in
+ engine.into_iter().flat_map(autonomous_projectile_flights)
+ {
+ let Some(draw) = autonomous_draws.get(projectile).and_then(Option::as_ref) else {
+ continue;
+ };
+ for (index, sound) in draw.engine_sounds.iter().enumerate() {
+ live.insert(flight_id);
+ sound.update(
+ audio,
+ ControlSoundId::AutonomousProjectile(flight_id, index),
+ &flight,
+ )?;
+ }
+ }
+ audio.stop_finished_projectile_sounds(&live);
+ Ok(())
+}
+
+fn update_player(
+ audio: &mut GameAudio,
+ draws: &mut [Option<ProjectileDraw>],
) -> Result<(), String> {
// Manual projectile slots keep their indices until collision or expiry.
- let mut id = first_sound_id;
+ let mut index = 0;
for draw in draws
.iter_mut()
.flatten()
@@ -111,19 +152,14 @@ pub(super) fn update(
let replaced = born_ms != instance.sound_born_ms;
instance.sound_born_ms = born_ms;
for sound in &draw.engine_sounds {
+ let id = ControlSoundId::PlayerProjectile(index);
if replaced {
audio.stop_control_sound(id);
}
- if let Some(event) = instance
- .flight
- .as_ref()
- .and_then(|flight| sound.sample(flight, audio.control_sound_is_playing(id)))
- {
- audio
- .handle_control_sound(id, &event)
- .map_err(|error| format!("play projectile engine sound: {error}"))?;
+ if let Some(flight) = &instance.flight {
+ sound.update(audio, id, flight)?;
}
- id += 1;
+ index += 1;
}
}
}
@@ -172,4 +208,31 @@ mod tests {
assert!((next.position[0] - start.position[0] - 7.0).abs() < 0.0001);
assert_eq!(&next.position[1..], &[20.0, 30.0]);
}
+
+ #[test]
+ #[ignore = "requires licensed projectile and effect resources"]
+ fn licensed_warbot_missile_engines_start_in_flight() {
+ let root = PathBuf::from(std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap());
+ let engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(&root)))).unwrap();
+ for name in ["bm_l_01", "bm_m_01"] {
+ let missile = load_player_projectile(&engine, "objects.rlb", name).unwrap();
+ let effects = initial_effects(&root, &missile, name);
+ let sounds = prepare(&missile, &effects);
+ let [sound] = sounds.as_slice() else {
+ panic!("expected one engine loop for {name}");
+ };
+ let flight = PlayerProjectile::new(
+ [10.0, 20.0, 30.0],
+ [1.0, 0.0, 0.0],
+ missile.speed,
+ missile.lifetime_ms,
+ 100,
+ )
+ .unwrap();
+ let event = sound.sample(&flight, false).unwrap();
+ assert_eq!(event.name, "eng_mis.wav");
+ assert_eq!(event.action, SoundAction::StartLoop);
+ assert!(event.position[0] < flight.position[0]);
+ }
+ }
}
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 1a9eb405..cdd8d35a 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -3459,6 +3459,13 @@ pub fn autonomous_weapon_effects(engine: &Engine) -> &[(String, String)] {
pub fn autodemo_projectiles(
engine: &Engine,
) -> impl Iterator<Item = (usize, PlayerProjectile)> + '_ {
+ autonomous_projectile_flights(engine).map(|(_, projectile, pose)| (projectile, pose))
+}
+
+/// Active autonomous flights with IDs stable across combat steps and pool reuse.
+pub fn autonomous_projectile_flights(
+ engine: &Engine,
+) -> impl Iterator<Item = (u64, usize, PlayerProjectile)> + '_ {
engine
.autodemo_combat
.iter()
diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs
index 2d6a3715..1ebbac2a 100644
--- a/crates/fparkan-runtime/src/unit_combat.rs
+++ b/crates/fparkan-runtime/src/unit_combat.rs
@@ -95,6 +95,7 @@ pub(super) struct AutoDemoCombat {
projectiles: Vec<AutoDemoProjectileType>,
weapon_effects: Vec<(String, String)>,
flights: Vec<Flight>,
+ next_flight_id: u64,
finished_segments: Vec<(usize, [[f32; 3]; 2])>,
pose_failures: super::WeaponPoseReport,
pub(super) report: CombatReport,
@@ -130,6 +131,7 @@ impl Unit {
}
struct Flight {
+ id: u64,
shooter: ObjectHandle,
shooter_identity: CombatObject,
projectile: usize,
@@ -171,6 +173,7 @@ impl AutoDemoCombat {
projectiles: Vec::new(),
weapon_effects: Vec::new(),
flights: Vec::new(),
+ next_flight_id: 0,
finished_segments: Vec::new(),
pose_failures: super::WeaponPoseReport::default(),
report: CombatReport::default(),
@@ -320,10 +323,10 @@ impl AutoDemoCombat {
.aim(component)
}
- pub(super) fn flights(&self) -> impl Iterator<Item = (usize, PlayerProjectile)> + '_ {
+ pub(super) fn flights(&self) -> impl Iterator<Item = (u64, usize, PlayerProjectile)> + '_ {
self.flights
.iter()
- .map(|flight| (flight.projectile, flight.pose))
+ .map(|flight| (flight.id, flight.projectile, flight.pose))
}
pub(super) fn segments(&self) -> impl Iterator<Item = (usize, [[f32; 3]; 2])> + '_ {
@@ -701,12 +704,14 @@ impl AutoDemoCombat {
PlayerProjectile::new(from, direction, data.speed, data.lifetime_ms, now)
{
self.flights.push(Flight {
+ id: self.next_flight_id,
shooter: unit.handle,
shooter_identity: shooter,
projectile,
pose,
segment: None,
});
+ self.next_flight_id += 1;
self.report
.shot(shooter, CombatObject::read(&engine.world, target), now);
events.push(AutoDemoCombatEvent::Shot {
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index f6ba78f7..5419073c 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -404,8 +404,8 @@ Raw queue clock задаёт фазу волн отдельно от времеÐ
Звук пуска снаряда поддерживает начальную безусловную группу CTL
с разовой Op2 при фазе 0. Подключены смена режима времени на 1
-при подготовке выстрела и петля двигателя ракеты игрока в режиме 5.
-Условные группы Control и петли автономных снарядов остаются открытыми.
+при подготовке выстрела и петли двигателей ракет в режиме 5.
+Условные группы Control и петли с меняющейся скоростью остаются открытыми.
Control Op1 воспроизводит добавки к RGBA и радиусу двумя сохраняемыми RNG-потоками.
Seeds просмотра `1/1` и общий порядок других FX ещё не совпадают с оригиналом;
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index 2219cce8..ad7a3e92 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -2782,6 +2782,11 @@ Simulation читает подготовленный input snapshot. Renderer н
`H_eng_missile.wav` на 0,40465 единицы позади центра. Источник следует
за ракетой и останавливается при столкновении или истечении её времени
жизни. Вызов DLL подтвердил фазы при скоростях 0, 7 и 70.
+У лёгкой и средней ракеты варбота `bm_l_01` и `bm_m_01` начальная
+группа CTL подключает `eng_mis.wav` с тем же режимом времени.
+Каждая ракета ИИ сохраняет собственный источник звука в течение полёта.
+Две выпущенные одновременно ракеты звучат независимо, а попадание одной
+останавливает только её двигатель.
У лазера вертолёта звук привязан к узлу орудия строкой типа 3.
В начале цикла четвёртое слово записи орудия выбирает группу CTL