Build production-ready editor authoring workflows
CI / Format, lint, test, build (push) Waiting to run
CI / Format, lint, test, build (push) Waiting to run
This commit is contained in:
1 parent
cc1fa6ea3b
commit
0553a85220
163 files changed
+34547
-1565
No files matched your search
@@ -15,9 +15,13 @@ hot-reload = ["dep:hot-lib-reloader", "game_hot/dylib"]
|
||||
avian3d.workspace = true
|
||||
bevy.workspace = true
|
||||
bevy_ufbx.workspace = true
|
||||
cpal = "0.17.3"
|
||||
game_hot = { path = "../game_hot" }
|
||||
hot-lib-reloader = { version = "0.8.2", optional = true }
|
||||
protocol.workspace = true
|
||||
ron = "0.12"
|
||||
scene.workspace = true
|
||||
serde.workspace = true
|
||||
shared.workspace = true
|
||||
sim.workspace = true
|
||||
settings.workspace = true
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,919 @@
|
||||
//! Runtime audio hydration, bus controls, listener resolution, and diagnostics.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use bevy::audio::{
|
||||
AudioPlayer, AudioSink, AudioSinkPlayback, AudioSource, PlaybackMode, PlaybackSettings,
|
||||
SpatialAudioSink, SpatialListener, SpatialScale, Volume,
|
||||
};
|
||||
use bevy::prelude::*;
|
||||
use cpal::traits::{DeviceTrait, HostTrait};
|
||||
use settings::{
|
||||
AudioSettings, ProjectSettings, AUDIO_BUS_MASTER_ID, AUDIO_GAIN_DB_MAX, AUDIO_GAIN_DB_MIN,
|
||||
};
|
||||
use shared::{
|
||||
asset_server_path, inspector_component_active, ActorId, AudioAttenuationDesc,
|
||||
AudioListenerDesc, AudioRolloff, AudioSourceDesc, InspectorOrder, LevelObject,
|
||||
COMPONENT_AUDIO_LISTENER_DESC, COMPONENT_AUDIO_SOURCE_DESC,
|
||||
};
|
||||
use sim::{PlayerCamera, SimEnabled};
|
||||
|
||||
/// Runtime override for an authored project bus. `None` preserves the project value.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct AudioBusOverride {
|
||||
pub gain_db: Option<f32>,
|
||||
pub muted: Option<bool>,
|
||||
}
|
||||
|
||||
/// Mutable runtime mixer state used by gameplay and options menus.
|
||||
#[derive(Resource, Debug, Clone, Default)]
|
||||
pub struct AudioBusRuntime {
|
||||
overrides: HashMap<String, AudioBusOverride>,
|
||||
}
|
||||
|
||||
impl AudioBusRuntime {
|
||||
pub fn set_gain_db(&mut self, bus_id: impl Into<String>, gain_db: f32) -> Result<(), String> {
|
||||
if !gain_db.is_finite() {
|
||||
return Err("audio bus gain must be finite".into());
|
||||
}
|
||||
self.overrides.entry(bus_id.into()).or_default().gain_db =
|
||||
Some(gain_db.clamp(AUDIO_GAIN_DB_MIN, AUDIO_GAIN_DB_MAX));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_muted(&mut self, bus_id: impl Into<String>, muted: bool) {
|
||||
self.overrides.entry(bus_id.into()).or_default().muted = Some(muted);
|
||||
}
|
||||
|
||||
pub fn clear_bus(&mut self, bus_id: &str) {
|
||||
self.overrides.remove(bus_id);
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.overrides.clear();
|
||||
}
|
||||
|
||||
pub fn bus_override(&self, bus_id: &str) -> Option<AudioBusOverride> {
|
||||
self.overrides.get(bus_id).copied()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AudioDeviceStatus {
|
||||
Unknown,
|
||||
Available,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
/// User-facing audio backend and codec capability snapshot.
|
||||
#[derive(Resource, Debug, Clone)]
|
||||
pub struct AudioRuntimeDiagnostics {
|
||||
pub status: AudioDeviceStatus,
|
||||
pub backend: String,
|
||||
pub output_device: Option<String>,
|
||||
pub message: String,
|
||||
pub codecs: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for AudioRuntimeDiagnostics {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
status: AudioDeviceStatus::Unknown,
|
||||
backend: String::new(),
|
||||
output_device: None,
|
||||
message: "Audio output has not been probed yet.".into(),
|
||||
codecs: vec![
|
||||
"Ogg Vorbis".into(),
|
||||
"WAV".into(),
|
||||
"MP3".into(),
|
||||
"FLAC".into(),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug, Clone, Copy, Default)]
|
||||
pub struct ActiveAudioListener(pub Option<Entity>);
|
||||
|
||||
#[derive(Component, Debug, Clone, PartialEq)]
|
||||
struct RuntimeAudioSourceState {
|
||||
descriptor: AudioSourceDesc,
|
||||
desired_playing: bool,
|
||||
paused_by_sim: bool,
|
||||
}
|
||||
|
||||
#[derive(Component, Debug, Clone, Copy, PartialEq)]
|
||||
struct ManagedAudioListener {
|
||||
ear_gap: f32,
|
||||
}
|
||||
|
||||
#[derive(Component, Debug, Clone)]
|
||||
pub struct AuthoredAudioVoice {
|
||||
pub source: Entity,
|
||||
pub bus: String,
|
||||
pub source_gain_db: f32,
|
||||
pub mix_weight: f32,
|
||||
pub spatial: bool,
|
||||
pub attenuation: AudioAttenuationDesc,
|
||||
pub looping: bool,
|
||||
}
|
||||
|
||||
/// Runtime adapter for scene-authored audio descriptors.
|
||||
pub struct GameAudioPlugin;
|
||||
|
||||
impl Plugin for GameAudioPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<AudioBusRuntime>()
|
||||
.init_resource::<AudioRuntimeDiagnostics>()
|
||||
.init_resource::<ActiveAudioListener>()
|
||||
.add_systems(PostStartup, probe_audio_output)
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
reconcile_audio_listener,
|
||||
reconcile_audio_sources,
|
||||
update_voice_mix,
|
||||
cleanup_finished_voices,
|
||||
)
|
||||
.chain(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn probe_audio_output(mut diagnostics: ResMut<AudioRuntimeDiagnostics>) {
|
||||
let host = cpal::default_host();
|
||||
diagnostics.backend = host.id().name().to_string();
|
||||
match host.default_output_device() {
|
||||
Some(device) => {
|
||||
let name = device
|
||||
.description()
|
||||
.map(|description| description.name().to_string())
|
||||
.unwrap_or_else(|error| format!("Unknown device ({error})"));
|
||||
diagnostics.status = AudioDeviceStatus::Available;
|
||||
diagnostics.output_device = Some(name.clone());
|
||||
diagnostics.message = format!("Audio output ready on {name}.");
|
||||
}
|
||||
None => {
|
||||
diagnostics.status = AudioDeviceStatus::Unavailable;
|
||||
diagnostics.output_device = None;
|
||||
diagnostics.message = "No default audio output device is available.".into();
|
||||
warn!("{}", diagnostics.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the effective linear gain for a bus including parent buses and runtime overrides.
|
||||
pub fn effective_bus_gain_linear(
|
||||
settings: &AudioSettings,
|
||||
runtime: &AudioBusRuntime,
|
||||
requested_bus: &str,
|
||||
) -> f32 {
|
||||
let mut current = if settings.bus(requested_bus).is_some() {
|
||||
requested_bus
|
||||
} else {
|
||||
AUDIO_BUS_MASTER_ID
|
||||
};
|
||||
let mut visited = HashSet::new();
|
||||
let mut gain_db = 0.0;
|
||||
|
||||
while visited.insert(current.to_string()) {
|
||||
let Some(bus) = settings.bus(current) else {
|
||||
break;
|
||||
};
|
||||
let runtime_override = runtime.bus_override(current).unwrap_or_default();
|
||||
if runtime_override.muted.unwrap_or(bus.muted) {
|
||||
return 0.0;
|
||||
}
|
||||
gain_db += runtime_override.gain_db.unwrap_or(bus.gain_db);
|
||||
let Some(parent) = bus.parent.as_deref() else {
|
||||
break;
|
||||
};
|
||||
current = parent;
|
||||
}
|
||||
|
||||
db_to_linear(gain_db)
|
||||
}
|
||||
|
||||
pub fn db_to_linear(db: f32) -> f32 {
|
||||
if db <= AUDIO_GAIN_DB_MIN {
|
||||
0.0
|
||||
} else {
|
||||
10.0_f32.powf(db / 20.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Equal-power 2D/spatial voice weights for a continuous authored blend.
|
||||
pub fn audio_voice_mix(spatial_blend: f32) -> Vec<(bool, f32)> {
|
||||
let blend = spatial_blend.clamp(0.0, 1.0);
|
||||
if blend <= f32::EPSILON {
|
||||
vec![(false, 1.0)]
|
||||
} else if blend >= 1.0 - f32::EPSILON {
|
||||
vec![(true, 1.0)]
|
||||
} else {
|
||||
vec![(false, (1.0 - blend).sqrt()), (true, blend.sqrt())]
|
||||
}
|
||||
}
|
||||
|
||||
/// Authored attenuation curve, normalized to full gain at `min_distance` and silence at max.
|
||||
pub fn attenuation_gain(desc: &AudioAttenuationDesc, distance: f32) -> f32 {
|
||||
if !distance.is_finite() {
|
||||
return 0.0;
|
||||
}
|
||||
let min = desc.min_distance.max(0.001);
|
||||
let max = desc.max_distance.max(min + 0.001);
|
||||
if distance <= min {
|
||||
return 1.0;
|
||||
}
|
||||
if distance >= max {
|
||||
return 0.0;
|
||||
}
|
||||
let t = ((distance - min) / (max - min)).clamp(0.0, 1.0);
|
||||
let factor = desc.rolloff_factor.max(0.001);
|
||||
match desc.rolloff {
|
||||
AudioRolloff::Linear => (1.0 - t).powf(factor),
|
||||
AudioRolloff::Inverse => ((1.0 - t) / (1.0 + factor * 4.0 * t)).clamp(0.0, 1.0),
|
||||
AudioRolloff::Exponential => ((distance / min).powf(-factor) * (1.0 - t)).clamp(0.0, 1.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Coordinate scale used only for rodio's left/right spatial panning.
|
||||
///
|
||||
/// Rodio also applies an inverse-square distance gain. Keeping every audible point inside its
|
||||
/// unity-distance zone preserves the interaural panning ratio while leaving the authored
|
||||
/// attenuation curve as the sole distance-gain authority.
|
||||
pub fn spatial_panning_scale(desc: &AudioAttenuationDesc, ear_gap: f32) -> f32 {
|
||||
const RODIO_UNITY_ZONE_FRACTION: f32 = 0.25;
|
||||
|
||||
let audible_radius = if desc.max_distance.is_finite() {
|
||||
desc.max_distance.max(0.001)
|
||||
} else {
|
||||
0.001
|
||||
};
|
||||
let ear_gap = if ear_gap.is_finite() {
|
||||
ear_gap.max(0.001)
|
||||
} else {
|
||||
0.001
|
||||
};
|
||||
(RODIO_UNITY_ZONE_FRACTION / (audible_radius + ear_gap * 0.5)).max(f32::MIN_POSITIVE)
|
||||
}
|
||||
|
||||
fn reconcile_audio_listener(world: &mut World) {
|
||||
let enabled = world.resource::<SimEnabled>().0;
|
||||
let mut candidates = Vec::new();
|
||||
{
|
||||
let mut query = world.query_filtered::<(
|
||||
Entity,
|
||||
&AudioListenerDesc,
|
||||
Option<&ActorId>,
|
||||
Option<&InspectorOrder>,
|
||||
), With<LevelObject>>();
|
||||
for (entity, desc, actor_id, order) in query.iter(world) {
|
||||
if desc.enabled && inspector_component_active(order, COMPONENT_AUDIO_LISTENER_DESC) {
|
||||
candidates.push((
|
||||
entity,
|
||||
*desc,
|
||||
actor_id.map(|id| id.0.clone()).unwrap_or_default(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates.sort_by(|a, b| {
|
||||
b.1.priority
|
||||
.cmp(&a.1.priority)
|
||||
.then_with(|| a.2.cmp(&b.2))
|
||||
.then_with(|| a.0.to_bits().cmp(&b.0.to_bits()))
|
||||
});
|
||||
|
||||
let selected = if enabled {
|
||||
candidates
|
||||
.first()
|
||||
.map(|(entity, desc, _)| (*entity, desc.ear_gap))
|
||||
.or_else(|| {
|
||||
let mut query = world.query_filtered::<Entity, With<PlayerCamera>>();
|
||||
query
|
||||
.iter(world)
|
||||
.min_by_key(|entity| entity.to_bits())
|
||||
.map(|entity| (entity, 0.2))
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let mut managed_query = world.query::<(Entity, &ManagedAudioListener)>();
|
||||
let managed: Vec<(Entity, ManagedAudioListener)> = managed_query
|
||||
.iter(world)
|
||||
.map(|(entity, listener)| (entity, *listener))
|
||||
.collect();
|
||||
for (entity, _) in managed {
|
||||
if selected.is_none_or(|(selected, _)| selected != entity) {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut
|
||||
.remove::<SpatialListener>()
|
||||
.remove::<ManagedAudioListener>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((entity, ear_gap)) = selected {
|
||||
let ear_gap = ear_gap.max(0.001);
|
||||
let is_current = world
|
||||
.get::<ManagedAudioListener>(entity)
|
||||
.is_some_and(|listener| listener.ear_gap == ear_gap)
|
||||
&& world.get::<SpatialListener>(entity).is_some();
|
||||
if !is_current {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.insert((
|
||||
SpatialListener::new(ear_gap),
|
||||
ManagedAudioListener { ear_gap },
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let selected_entity = selected.map(|(entity, _)| entity);
|
||||
let mut active = world.resource_mut::<ActiveAudioListener>();
|
||||
if active.0 != selected_entity {
|
||||
active.0 = selected_entity;
|
||||
}
|
||||
}
|
||||
|
||||
fn reconcile_audio_sources(world: &mut World) {
|
||||
let sim_enabled = world.resource::<SimEnabled>().0;
|
||||
let mut sources = Vec::new();
|
||||
{
|
||||
let mut query = world.query_filtered::<(
|
||||
Entity,
|
||||
&AudioSourceDesc,
|
||||
Option<&InspectorOrder>,
|
||||
), With<LevelObject>>();
|
||||
for (entity, desc, order) in query.iter(world) {
|
||||
if inspector_component_active(order, COMPONENT_AUDIO_SOURCE_DESC) {
|
||||
sources.push((entity, desc.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let source_ids: HashSet<Entity> = sources.iter().map(|(entity, _)| *entity).collect();
|
||||
let mut voice_query = world.query::<&AuthoredAudioVoice>();
|
||||
let mut voiced_sources: HashSet<Entity> =
|
||||
voice_query.iter(world).map(|voice| voice.source).collect();
|
||||
let mut state_query = world.query_filtered::<Entity, With<RuntimeAudioSourceState>>();
|
||||
let stale: Vec<Entity> = state_query
|
||||
.iter(world)
|
||||
.filter(|entity| !source_ids.contains(entity))
|
||||
.collect();
|
||||
for entity in stale {
|
||||
stop_voice_entities(world, entity);
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.remove::<RuntimeAudioSourceState>();
|
||||
}
|
||||
}
|
||||
|
||||
for (entity, descriptor) in sources {
|
||||
let prior = world.get::<RuntimeAudioSourceState>(entity).cloned();
|
||||
let mut state = prior.clone().unwrap_or_else(|| RuntimeAudioSourceState {
|
||||
descriptor: descriptor.clone(),
|
||||
desired_playing: descriptor.autoplay,
|
||||
paused_by_sim: false,
|
||||
});
|
||||
if state.descriptor != descriptor {
|
||||
let autoplay_changed = state.descriptor.autoplay != descriptor.autoplay;
|
||||
stop_voice_entities(world, entity);
|
||||
voiced_sources.remove(&entity);
|
||||
state.descriptor = descriptor.clone();
|
||||
if autoplay_changed {
|
||||
state.desired_playing = descriptor.autoplay;
|
||||
}
|
||||
}
|
||||
|
||||
if !sim_enabled {
|
||||
if !state.paused_by_sim {
|
||||
set_source_paused(world, entity, true);
|
||||
state.paused_by_sim = true;
|
||||
}
|
||||
} else {
|
||||
if state.paused_by_sim {
|
||||
set_source_paused(world, entity, false);
|
||||
state.paused_by_sim = false;
|
||||
}
|
||||
if state.desired_playing && !voiced_sources.contains(&entity) {
|
||||
if let Err(error) = spawn_source_voices(world, entity, &descriptor) {
|
||||
warn!("Could not start authored audio source {entity:?}: {error}");
|
||||
state.desired_playing = false;
|
||||
} else {
|
||||
voiced_sources.insert(entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
if prior.as_ref() != Some(&state) {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.insert(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_source_voices(
|
||||
world: &mut World,
|
||||
source: Entity,
|
||||
descriptor: &AudioSourceDesc,
|
||||
) -> Result<(), String> {
|
||||
let clip = descriptor
|
||||
.clip
|
||||
.as_ref()
|
||||
.ok_or_else(|| "no audio clip is assigned".to_string())?;
|
||||
let source_path = clip
|
||||
.source_path
|
||||
.as_deref()
|
||||
.filter(|path| !path.trim().is_empty())
|
||||
.ok_or_else(|| "audio clip has no runtime source path".to_string())?;
|
||||
let asset_server = world.resource::<AssetServer>().clone();
|
||||
let handle: Handle<AudioSource> = asset_server.load(asset_server_path(source_path));
|
||||
let mode = if descriptor.looping {
|
||||
PlaybackMode::Loop
|
||||
} else {
|
||||
PlaybackMode::Once
|
||||
};
|
||||
let ear_gap = active_listener_ear_gap(world);
|
||||
let panning_scale = spatial_panning_scale(&descriptor.attenuation, ear_gap);
|
||||
|
||||
for (spatial, mix_weight) in audio_voice_mix(descriptor.spatial_blend) {
|
||||
let child = world
|
||||
.spawn((
|
||||
Name::new(if spatial {
|
||||
"Authored Spatial Audio Voice"
|
||||
} else {
|
||||
"Authored 2D Audio Voice"
|
||||
}),
|
||||
Transform::IDENTITY,
|
||||
AudioPlayer::new(handle.clone()),
|
||||
PlaybackSettings {
|
||||
mode,
|
||||
volume: Volume::Linear(0.0),
|
||||
speed: descriptor.pitch,
|
||||
paused: false,
|
||||
muted: false,
|
||||
spatial,
|
||||
spatial_scale: spatial.then(|| SpatialScale::new(panning_scale)),
|
||||
start_position: None,
|
||||
duration: None,
|
||||
},
|
||||
AuthoredAudioVoice {
|
||||
source,
|
||||
bus: descriptor.bus.clone(),
|
||||
source_gain_db: descriptor.gain_db,
|
||||
mix_weight,
|
||||
spatial,
|
||||
attenuation: descriptor.attenuation,
|
||||
looping: descriptor.looping,
|
||||
},
|
||||
ChildOf(source),
|
||||
))
|
||||
.id();
|
||||
trace!("Spawned authored audio voice {child:?} for {source:?}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn active_listener_ear_gap(world: &World) -> f32 {
|
||||
world
|
||||
.resource::<ActiveAudioListener>()
|
||||
.0
|
||||
.and_then(|entity| world.get::<ManagedAudioListener>(entity))
|
||||
.map(|listener| listener.ear_gap)
|
||||
.unwrap_or(0.2)
|
||||
}
|
||||
|
||||
fn voice_entities(world: &mut World, source: Entity) -> Vec<Entity> {
|
||||
let mut query = world.query::<(Entity, &AuthoredAudioVoice)>();
|
||||
query
|
||||
.iter(world)
|
||||
.filter_map(|(entity, voice)| (voice.source == source).then_some(entity))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn stop_voice_entities(world: &mut World, source: Entity) {
|
||||
for entity in voice_entities(world, source) {
|
||||
if let Some(sink) = world.get::<AudioSink>(entity) {
|
||||
sink.stop();
|
||||
}
|
||||
if let Some(sink) = world.get::<SpatialAudioSink>(entity) {
|
||||
sink.stop();
|
||||
}
|
||||
if let Ok(entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.despawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_source_paused(world: &mut World, source: Entity, paused: bool) {
|
||||
for entity in voice_entities(world, source) {
|
||||
if let Some(mut settings) = world.get_mut::<PlaybackSettings>(entity) {
|
||||
settings.paused = paused;
|
||||
}
|
||||
if let Some(sink) = world.get::<AudioSink>(entity) {
|
||||
if paused {
|
||||
sink.pause();
|
||||
} else {
|
||||
sink.play();
|
||||
}
|
||||
}
|
||||
if let Some(sink) = world.get::<SpatialAudioSink>(entity) {
|
||||
if paused {
|
||||
sink.pause();
|
||||
} else {
|
||||
sink.play();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts an authored source through the same runtime adapter used by autoplay.
|
||||
pub fn play_authored_audio_source(world: &mut World, source: Entity) -> Result<(), String> {
|
||||
let descriptor = world
|
||||
.get::<AudioSourceDesc>(source)
|
||||
.cloned()
|
||||
.ok_or_else(|| "entity has no AudioSourceDesc".to_string())?;
|
||||
stop_voice_entities(world, source);
|
||||
let sim_enabled = world.resource::<SimEnabled>().0;
|
||||
let state = RuntimeAudioSourceState {
|
||||
descriptor: descriptor.clone(),
|
||||
desired_playing: true,
|
||||
paused_by_sim: !sim_enabled,
|
||||
};
|
||||
world.entity_mut(source).insert(state);
|
||||
if sim_enabled {
|
||||
spawn_source_voices(world, source, &descriptor)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stops an authored source and disables replay until another explicit play or autoplay change.
|
||||
pub fn stop_authored_audio_source(world: &mut World, source: Entity) {
|
||||
stop_voice_entities(world, source);
|
||||
if let Some(mut state) = world.get_mut::<RuntimeAudioSourceState>(source) {
|
||||
state.desired_playing = false;
|
||||
state.paused_by_sim = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears PIE-owned playback/listeners so the next session starts from authored state.
|
||||
pub fn reset_authored_audio_runtime(world: &mut World) {
|
||||
let mut query = world.query_filtered::<Entity, With<RuntimeAudioSourceState>>();
|
||||
let sources: Vec<Entity> = query.iter(world).collect();
|
||||
for source in sources {
|
||||
stop_voice_entities(world, source);
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(source) {
|
||||
entity_mut.remove::<RuntimeAudioSourceState>();
|
||||
}
|
||||
}
|
||||
let mut listener_query = world.query_filtered::<Entity, With<ManagedAudioListener>>();
|
||||
let listeners: Vec<Entity> = listener_query.iter(world).collect();
|
||||
for listener in listeners {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(listener) {
|
||||
entity_mut
|
||||
.remove::<SpatialListener>()
|
||||
.remove::<ManagedAudioListener>();
|
||||
}
|
||||
}
|
||||
world.resource_mut::<ActiveAudioListener>().0 = None;
|
||||
}
|
||||
|
||||
fn update_voice_mix(world: &mut World) {
|
||||
let project_audio = world.resource::<ProjectSettings>().audio.clone();
|
||||
let bus_runtime = world.resource::<AudioBusRuntime>().clone();
|
||||
let listener_position = world
|
||||
.resource::<ActiveAudioListener>()
|
||||
.0
|
||||
.and_then(|entity| world.get::<GlobalTransform>(entity))
|
||||
.map(GlobalTransform::translation);
|
||||
let listener_ear_gap = active_listener_ear_gap(world);
|
||||
let mut query = world.query::<(Entity, &AuthoredAudioVoice, Option<&GlobalTransform>)>();
|
||||
let voices: Vec<(Entity, AuthoredAudioVoice, Option<Vec3>)> = query
|
||||
.iter(world)
|
||||
.map(|(entity, voice, transform)| {
|
||||
(
|
||||
entity,
|
||||
voice.clone(),
|
||||
transform.map(GlobalTransform::translation),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
for (entity, voice, source_position) in voices {
|
||||
if voice.spatial {
|
||||
let scale = spatial_panning_scale(&voice.attenuation, listener_ear_gap);
|
||||
let desired = SpatialScale::new(scale);
|
||||
if let Some(mut settings) = world.get_mut::<PlaybackSettings>(entity) {
|
||||
if settings
|
||||
.spatial_scale
|
||||
.is_none_or(|current| current.0 != desired.0)
|
||||
{
|
||||
settings.spatial_scale = Some(desired);
|
||||
}
|
||||
}
|
||||
}
|
||||
let bus_gain = effective_bus_gain_linear(&project_audio, &bus_runtime, &voice.bus);
|
||||
let attenuation = if voice.spatial {
|
||||
match (listener_position, source_position) {
|
||||
(Some(listener), Some(source)) => {
|
||||
attenuation_gain(&voice.attenuation, listener.distance(source))
|
||||
}
|
||||
_ => 0.0,
|
||||
}
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let gain = db_to_linear(voice.source_gain_db) * bus_gain * voice.mix_weight * attenuation;
|
||||
if let Some(mut sink) = world.get_mut::<AudioSink>(entity) {
|
||||
sink.set_volume(Volume::Linear(gain));
|
||||
}
|
||||
if let Some(mut sink) = world.get_mut::<SpatialAudioSink>(entity) {
|
||||
sink.set_volume(Volume::Linear(gain));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cleanup_finished_voices(world: &mut World) {
|
||||
let mut query = world.query::<(Entity, &AuthoredAudioVoice)>();
|
||||
let voices: Vec<(Entity, Entity, bool)> = query
|
||||
.iter(world)
|
||||
.map(|(entity, voice)| (entity, voice.source, voice.looping))
|
||||
.collect();
|
||||
let mut completed_sources = HashSet::new();
|
||||
for (entity, source, looping) in voices {
|
||||
if looping {
|
||||
continue;
|
||||
}
|
||||
let finished = world
|
||||
.get::<AudioSink>(entity)
|
||||
.is_some_and(AudioSinkPlayback::empty)
|
||||
|| world
|
||||
.get::<SpatialAudioSink>(entity)
|
||||
.is_some_and(AudioSinkPlayback::empty);
|
||||
if finished {
|
||||
if let Ok(entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.despawn();
|
||||
}
|
||||
completed_sources.insert(source);
|
||||
}
|
||||
}
|
||||
for source in completed_sources {
|
||||
if voice_entities(world, source).is_empty() {
|
||||
if let Some(mut state) = world.get_mut::<RuntimeAudioSourceState>(source) {
|
||||
state.desired_playing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bevy::asset::{AssetApp, AssetPlugin};
|
||||
use settings::{AudioBusSettings, AUDIO_BUS_MUSIC_ID, AUDIO_BUS_SFX_ID};
|
||||
use shared::{EditorAssetRef, AUDIO_CLIP_SUB_ASSET_ID};
|
||||
|
||||
#[test]
|
||||
fn bus_gain_accumulates_parents_and_runtime_overrides() {
|
||||
let settings = AudioSettings::default();
|
||||
let mut runtime = AudioBusRuntime::default();
|
||||
runtime.set_gain_db(AUDIO_BUS_MASTER_ID, -6.0).unwrap();
|
||||
runtime.set_gain_db(AUDIO_BUS_MUSIC_ID, -6.0).unwrap();
|
||||
let gain = effective_bus_gain_linear(&settings, &runtime, AUDIO_BUS_MUSIC_ID);
|
||||
assert!((gain - db_to_linear(-12.0)).abs() < 0.0001);
|
||||
runtime.set_muted(AUDIO_BUS_MASTER_ID, true);
|
||||
assert_eq!(
|
||||
effective_bus_gain_linear(&settings, &runtime, AUDIO_BUS_MUSIC_ID),
|
||||
0.0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_bus_falls_back_to_master() {
|
||||
let mut settings = AudioSettings::default();
|
||||
settings.bus_mut(AUDIO_BUS_MASTER_ID).unwrap().gain_db = -3.0;
|
||||
assert!(
|
||||
(effective_bus_gain_linear(&settings, &AudioBusRuntime::default(), "missing")
|
||||
- db_to_linear(-3.0))
|
||||
.abs()
|
||||
< 0.0001
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spatial_blend_is_equal_power_and_keeps_endpoint_voice_counts() {
|
||||
assert_eq!(audio_voice_mix(0.0), vec![(false, 1.0)]);
|
||||
assert_eq!(audio_voice_mix(1.0), vec![(true, 1.0)]);
|
||||
let mixed = audio_voice_mix(0.5);
|
||||
assert_eq!(mixed.len(), 2);
|
||||
let power: f32 = mixed.iter().map(|(_, weight)| weight * weight).sum();
|
||||
assert!((power - 1.0).abs() < 0.0001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attenuation_is_full_inside_min_and_silent_at_max() {
|
||||
for rolloff in [
|
||||
AudioRolloff::Linear,
|
||||
AudioRolloff::Inverse,
|
||||
AudioRolloff::Exponential,
|
||||
] {
|
||||
let desc = AudioAttenuationDesc {
|
||||
min_distance: 2.0,
|
||||
max_distance: 10.0,
|
||||
rolloff,
|
||||
rolloff_factor: 1.0,
|
||||
};
|
||||
assert_eq!(attenuation_gain(&desc, 1.0), 1.0);
|
||||
assert_eq!(attenuation_gain(&desc, 10.0), 0.0);
|
||||
assert!(attenuation_gain(&desc, 5.0) > 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panning_scale_keeps_rodio_distance_gain_neutral_in_authored_radius() {
|
||||
let attenuation = AudioAttenuationDesc {
|
||||
min_distance: 1.0,
|
||||
max_distance: 25.0,
|
||||
rolloff: AudioRolloff::Inverse,
|
||||
rolloff_factor: 1.0,
|
||||
};
|
||||
let ear_gap = 0.2;
|
||||
let scale = spatial_panning_scale(&attenuation, ear_gap);
|
||||
|
||||
// Rodio's distance gain remains 1.0 while each ear is at most one rodio unit away.
|
||||
let furthest_audible_ear = (attenuation.max_distance + ear_gap * 0.5) * scale;
|
||||
assert!(scale.is_finite() && scale > 0.0);
|
||||
assert!(furthest_audible_ear <= 0.25 + f32::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_reconciliation_does_not_reinsert_runtime_components() {
|
||||
let mut world = World::new();
|
||||
world.insert_resource(SimEnabled(true));
|
||||
world.insert_resource(ActiveAudioListener::default());
|
||||
let listener = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
ActorId("audio-listener".into()),
|
||||
AudioListenerDesc::default(),
|
||||
))
|
||||
.id();
|
||||
let source = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
AudioSourceDesc {
|
||||
autoplay: false,
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
.id();
|
||||
|
||||
reconcile_audio_listener(&mut world);
|
||||
reconcile_audio_sources(&mut world);
|
||||
world.clear_trackers();
|
||||
reconcile_audio_listener(&mut world);
|
||||
reconcile_audio_sources(&mut world);
|
||||
|
||||
assert!(!world
|
||||
.entity(listener)
|
||||
.get_ref::<ManagedAudioListener>()
|
||||
.unwrap()
|
||||
.is_changed());
|
||||
assert!(!world
|
||||
.entity(source)
|
||||
.get_ref::<RuntimeAudioSourceState>()
|
||||
.unwrap()
|
||||
.is_changed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authored_audio_hydrates_and_reset_removes_all_runtime_state() {
|
||||
let mut app = App::new();
|
||||
app.add_plugins((MinimalPlugins, AssetPlugin::default()))
|
||||
.init_asset::<AudioSource>()
|
||||
.insert_resource(SimEnabled(true))
|
||||
.init_resource::<ActiveAudioListener>();
|
||||
let listener = app
|
||||
.world_mut()
|
||||
.spawn((
|
||||
LevelObject,
|
||||
ActorId("audio-listener".into()),
|
||||
AudioListenerDesc::default(),
|
||||
Transform::IDENTITY,
|
||||
))
|
||||
.id();
|
||||
let source = app
|
||||
.world_mut()
|
||||
.spawn((
|
||||
LevelObject,
|
||||
Transform::from_xyz(0.0, 0.0, -2.0),
|
||||
AudioSourceDesc {
|
||||
clip: Some(
|
||||
EditorAssetRef::new("audio-id", AUDIO_CLIP_SUB_ASSET_ID, "Tone")
|
||||
.with_source_path("audio/tone.ogg"),
|
||||
),
|
||||
spatial_blend: 0.5,
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
.id();
|
||||
|
||||
reconcile_audio_listener(app.world_mut());
|
||||
reconcile_audio_sources(app.world_mut());
|
||||
|
||||
assert_eq!(
|
||||
app.world().resource::<ActiveAudioListener>().0,
|
||||
Some(listener)
|
||||
);
|
||||
assert!(app.world().get::<SpatialListener>(listener).is_some());
|
||||
assert!(app.world().get::<RuntimeAudioSourceState>(source).is_some());
|
||||
let voices = voice_entities(app.world_mut(), source);
|
||||
assert_eq!(voices.len(), 2);
|
||||
assert!(voices
|
||||
.iter()
|
||||
.all(|voice| app.world().get::<AudioPlayer>(*voice).is_some()));
|
||||
|
||||
reset_authored_audio_runtime(app.world_mut());
|
||||
|
||||
assert_eq!(app.world().resource::<ActiveAudioListener>().0, None);
|
||||
assert!(app.world().get::<SpatialListener>(listener).is_none());
|
||||
assert!(app.world().get::<RuntimeAudioSourceState>(source).is_none());
|
||||
assert!(voice_entities(app.world_mut(), source).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_selection_prefers_priority_then_stable_actor_id() {
|
||||
let mut world = World::new();
|
||||
world.insert_resource(SimEnabled(true));
|
||||
world.insert_resource(ActiveAudioListener::default());
|
||||
let low_priority = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
ActorId("listener-low".into()),
|
||||
AudioListenerDesc {
|
||||
priority: 1,
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
.id();
|
||||
let tied_later = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
ActorId("listener-z".into()),
|
||||
AudioListenerDesc {
|
||||
priority: 10,
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
.id();
|
||||
let tied_first = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
ActorId("listener-a".into()),
|
||||
AudioListenerDesc {
|
||||
priority: 10,
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
.id();
|
||||
|
||||
reconcile_audio_listener(&mut world);
|
||||
assert_eq!(world.resource::<ActiveAudioListener>().0, Some(tied_first));
|
||||
assert_ne!(
|
||||
world.resource::<ActiveAudioListener>().0,
|
||||
Some(low_priority)
|
||||
);
|
||||
|
||||
world
|
||||
.get_mut::<AudioListenerDesc>(tied_first)
|
||||
.unwrap()
|
||||
.enabled = false;
|
||||
reconcile_audio_listener(&mut world);
|
||||
assert_eq!(world.resource::<ActiveAudioListener>().0, Some(tied_later));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bus_cycle_is_defensively_bounded_at_runtime() {
|
||||
let settings = AudioSettings {
|
||||
buses: vec![
|
||||
AudioBusSettings {
|
||||
id: AUDIO_BUS_MASTER_ID.into(),
|
||||
label: "Master".into(),
|
||||
parent: Some(AUDIO_BUS_SFX_ID.into()),
|
||||
gain_db: 0.0,
|
||||
muted: false,
|
||||
},
|
||||
AudioBusSettings {
|
||||
id: AUDIO_BUS_SFX_ID.into(),
|
||||
label: "SFX".into(),
|
||||
parent: Some(AUDIO_BUS_MASTER_ID.into()),
|
||||
gain_db: 0.0,
|
||||
muted: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
assert_eq!(
|
||||
effective_bus_gain_linear(&settings, &AudioBusRuntime::default(), AUDIO_BUS_SFX_ID),
|
||||
1.0
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use bevy::app::PluginGroupBuilder;
|
||||
use bevy::asset::AssetPlugin;
|
||||
use bevy::log::{LogPlugin, DEFAULT_FILTER};
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::{CompositeAlphaMode, PresentMode, WindowMode, WindowPlugin};
|
||||
|
||||
@@ -40,6 +41,13 @@ fn find_assets_directory(start: Option<PathBuf>) -> Option<String> {
|
||||
|
||||
pub fn default_plugins(title: impl Into<String>) -> PluginGroupBuilder {
|
||||
DefaultPlugins
|
||||
.set(LogPlugin {
|
||||
// Blacksite intentionally replaces Bevy's `.scn.ron` loader with a
|
||||
// schema-aware loader. Keep the expected registration warning out
|
||||
// of normal startup logs; RUST_LOG still overrides this filter.
|
||||
filter: format!("{DEFAULT_FILTER}bevy_asset::server::loaders=error"),
|
||||
..default()
|
||||
})
|
||||
.set(WindowPlugin {
|
||||
primary_window: Some(primary_window(title)),
|
||||
..default()
|
||||
|
||||
+74
-11
@@ -8,8 +8,14 @@
|
||||
)
|
||||
)]
|
||||
|
||||
pub mod animation;
|
||||
pub mod audio;
|
||||
pub mod editor_ext;
|
||||
pub mod launch;
|
||||
mod scene_bootstrap;
|
||||
mod schema_world_loader;
|
||||
|
||||
pub use scene_bootstrap::ProjectDefaultLevelRoot;
|
||||
|
||||
pub mod player {
|
||||
//! Player types re-exported from the stable sim crate.
|
||||
@@ -42,6 +48,13 @@ pub struct GameRenderBootstrap {
|
||||
pub defer_player_camera_fx: bool,
|
||||
}
|
||||
|
||||
/// Scene-startup controls for a host that embeds [`GamePlugin`].
|
||||
#[derive(Resource, Debug, Clone, Copy, Default)]
|
||||
pub struct GameSceneBootstrap {
|
||||
/// The host owns initial scene materialization instead of the standalone runtime.
|
||||
pub defer_default_level: bool,
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "hot-reload"))]
|
||||
mod systems {
|
||||
pub use game_hot::{
|
||||
@@ -112,7 +125,21 @@ fn game_input_enabled(enabled: Res<GameInputEnabled>) -> bool {
|
||||
enabled.0
|
||||
}
|
||||
|
||||
fn register_game_systems(app: &mut App, defer_player_camera_fx: bool) {
|
||||
fn register_level_bootstrap(app: &mut App, defer_default_level: bool) {
|
||||
if defer_default_level {
|
||||
// SceneIo owns editor startup and retains the generated arena as its
|
||||
// failure fallback until the authored document is materialized.
|
||||
app.add_systems(Startup, systems::spawn_level);
|
||||
} else {
|
||||
app.add_systems(Startup, scene_bootstrap::spawn_project_default_level);
|
||||
}
|
||||
}
|
||||
|
||||
fn register_game_systems(
|
||||
app: &mut App,
|
||||
render_bootstrap: GameRenderBootstrap,
|
||||
scene_bootstrap: GameSceneBootstrap,
|
||||
) {
|
||||
app.add_systems(
|
||||
FixedUpdate,
|
||||
(
|
||||
@@ -143,13 +170,10 @@ fn register_game_systems(app: &mut App, defer_player_camera_fx: bool) {
|
||||
)
|
||||
.add_systems(
|
||||
Startup,
|
||||
(
|
||||
systems::apply_ambient_light,
|
||||
systems::spawn_sun,
|
||||
systems::spawn_level,
|
||||
)
|
||||
.chain(),
|
||||
(systems::apply_ambient_light, systems::spawn_sun).chain(),
|
||||
);
|
||||
|
||||
register_level_bootstrap(app, scene_bootstrap.defer_default_level);
|
||||
app.add_systems(
|
||||
Update,
|
||||
(
|
||||
@@ -158,7 +182,7 @@ fn register_game_systems(app: &mut App, defer_player_camera_fx: bool) {
|
||||
),
|
||||
);
|
||||
|
||||
if !defer_player_camera_fx {
|
||||
if !render_bootstrap.defer_player_camera_fx {
|
||||
app.add_systems(
|
||||
PostStartup,
|
||||
(
|
||||
@@ -175,21 +199,29 @@ pub struct GamePlugin;
|
||||
|
||||
impl Plugin for GamePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
let defer_player_camera_fx = app
|
||||
let render_bootstrap = app
|
||||
.world()
|
||||
.get_resource::<GameRenderBootstrap>()
|
||||
.is_some_and(|bootstrap| bootstrap.defer_player_camera_fx);
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
let scene_bootstrap = app
|
||||
.world()
|
||||
.get_resource::<GameSceneBootstrap>()
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
|
||||
app.register_type::<GameInputEnabled>()
|
||||
.init_resource::<GameInputEnabled>()
|
||||
.init_resource::<GameInputFocused>()
|
||||
.add_plugins(schema_world_loader::SchemaWorldAssetPlugin)
|
||||
.add_plugins((ProjectSettingsPlugin, SimPlugin, bevy_ufbx::FbxPlugin))
|
||||
.add_plugins((audio::GameAudioPlugin, animation::GameAnimationPlugin))
|
||||
.add_plugins(game_hot::SolariRenderingPlugin)
|
||||
.add_plugins(game_hot::AutoExposureRenderingPlugin)
|
||||
.add_plugins(game_hot::FullscreenEffectsPlugin)
|
||||
.insert_resource(ClearColor(Color::srgb(0.0, 0.0, 0.0)));
|
||||
|
||||
register_game_systems(app, defer_player_camera_fx);
|
||||
register_game_systems(app, render_bootstrap, scene_bootstrap);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,3 +229,34 @@ impl Plugin for GamePlugin {
|
||||
pub fn on_hot_reload(world: &mut World) {
|
||||
game_hot::on_hot_reload(world);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod startup_tests {
|
||||
use super::*;
|
||||
use bevy::asset::AssetPlugin;
|
||||
use bevy::world_serialization::WorldSerializationPlugin;
|
||||
|
||||
#[test]
|
||||
fn deferred_bootstrap_leaves_default_level_loading_to_the_host() {
|
||||
let mut app = App::new();
|
||||
app.add_plugins((
|
||||
MinimalPlugins,
|
||||
AssetPlugin::default(),
|
||||
WorldSerializationPlugin,
|
||||
));
|
||||
app.insert_resource(settings::ProjectSettings::default());
|
||||
register_level_bootstrap(&mut app, true);
|
||||
|
||||
app.update();
|
||||
|
||||
let world = app.world_mut();
|
||||
let mut runtime_roots =
|
||||
world.query_filtered::<Entity, With<scene_bootstrap::ProjectDefaultLevelRoot>>();
|
||||
assert_eq!(runtime_roots.iter(world).count(), 0);
|
||||
let mut fallback = world.query_filtered::<Entity, With<shared::LevelObject>>();
|
||||
assert!(
|
||||
fallback.iter(world).next().is_some(),
|
||||
"the editor fallback arena remains available until SceneIo loads"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Standalone project-scene bootstrap.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy::world_serialization::DynamicWorld;
|
||||
use settings::ProjectSettings;
|
||||
|
||||
/// Runtime root for the standalone project's configured default level.
|
||||
#[derive(Component, Debug)]
|
||||
pub struct ProjectDefaultLevelRoot;
|
||||
|
||||
pub(crate) fn spawn_project_default_level(
|
||||
mut commands: Commands,
|
||||
asset_server: Res<AssetServer>,
|
||||
settings: Res<ProjectSettings>,
|
||||
existing: Query<(), With<ProjectDefaultLevelRoot>>,
|
||||
) {
|
||||
if !existing.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let configured_path = settings.default_level.trim();
|
||||
if configured_path.is_empty() {
|
||||
error!("Project default_level is empty; standalone scene startup was skipped");
|
||||
return;
|
||||
}
|
||||
|
||||
let asset_path = shared::asset_server_path(configured_path);
|
||||
let handle: Handle<DynamicWorld> = asset_server.load(asset_path.clone());
|
||||
commands.spawn((
|
||||
Name::new(format!("Project Default Level ({configured_path})")),
|
||||
ProjectDefaultLevelRoot,
|
||||
DynamicWorldRoot(handle),
|
||||
));
|
||||
info!("Loading project default level {configured_path} ({asset_path})");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bevy::asset::AssetPlugin;
|
||||
use bevy::world_serialization::WorldSerializationPlugin;
|
||||
|
||||
fn test_app(default_level: &str) -> App {
|
||||
let mut app = App::new();
|
||||
app.add_plugins((
|
||||
MinimalPlugins,
|
||||
AssetPlugin::default(),
|
||||
WorldSerializationPlugin,
|
||||
));
|
||||
app.insert_resource(ProjectSettings {
|
||||
default_level: default_level.to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
app
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standalone_bootstrap_uses_the_project_default_level() {
|
||||
let mut app = test_app("assets/levels/editor_scene.scn.ron");
|
||||
app.add_systems(Startup, spawn_project_default_level);
|
||||
|
||||
app.update();
|
||||
|
||||
let world = app.world_mut();
|
||||
let mut roots = world.query_filtered::<&DynamicWorldRoot, With<ProjectDefaultLevelRoot>>();
|
||||
let root = roots.single(world).expect("one standalone scene root");
|
||||
let path = world
|
||||
.resource::<AssetServer>()
|
||||
.get_path(root.0.id())
|
||||
.expect("default level handle retains its asset path");
|
||||
assert_eq!(path.to_string(), "levels/editor_scene.scn.ron");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_default_level_does_not_create_a_runtime_root() {
|
||||
let mut app = test_app(" ");
|
||||
app.add_systems(Startup, spawn_project_default_level);
|
||||
|
||||
app.update();
|
||||
|
||||
let world = app.world_mut();
|
||||
let mut roots = world.query_filtered::<Entity, With<ProjectDefaultLevelRoot>>();
|
||||
assert_eq!(roots.iter(world).count(), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Runtime adapter for versioned Blacksite `.scn.ron` assets.
|
||||
|
||||
use std::io;
|
||||
|
||||
use bevy::asset::{io::Reader, AssetApp, AssetLoader, LoadContext};
|
||||
use bevy::ecs::reflect::AppTypeRegistry;
|
||||
use bevy::prelude::*;
|
||||
use bevy::reflect::{TypePath, TypeRegistryArc};
|
||||
use bevy::world_serialization::{serde::WorldDeserializer, DynamicWorld};
|
||||
use serde::de::DeserializeSeed;
|
||||
|
||||
pub(super) struct SchemaWorldAssetPlugin;
|
||||
|
||||
impl Plugin for SchemaWorldAssetPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
// Register after Bevy's stock loader so versioned Blacksite scenes use
|
||||
// this adapter while retaining the standard DynamicWorld asset type.
|
||||
app.init_asset_loader::<SchemaWorldAssetLoader>();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, TypePath)]
|
||||
struct SchemaWorldAssetLoader {
|
||||
type_registry: TypeRegistryArc,
|
||||
}
|
||||
|
||||
impl FromWorld for SchemaWorldAssetLoader {
|
||||
fn from_world(world: &mut World) -> Self {
|
||||
Self {
|
||||
type_registry: world.resource::<AppTypeRegistry>().0.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AssetLoader for SchemaWorldAssetLoader {
|
||||
type Asset = DynamicWorld;
|
||||
type Settings = ();
|
||||
type Error = io::Error;
|
||||
|
||||
async fn load(
|
||||
&self,
|
||||
reader: &mut dyn Reader,
|
||||
_settings: &Self::Settings,
|
||||
load_context: &mut LoadContext<'_>,
|
||||
) -> Result<Self::Asset, Self::Error> {
|
||||
let mut bytes = Vec::new();
|
||||
reader.read_to_end(&mut bytes).await?;
|
||||
let text = std::str::from_utf8(&bytes).map_err(invalid_scene)?;
|
||||
let body = normalized_world_body(text)?;
|
||||
let mut deserializer = ron::de::Deserializer::from_str(&body).map_err(invalid_scene)?;
|
||||
let world_deserializer = WorldDeserializer {
|
||||
type_registry: &self.type_registry.read(),
|
||||
load_from_path: load_context,
|
||||
};
|
||||
world_deserializer
|
||||
.deserialize(&mut deserializer)
|
||||
.map_err(|error| invalid_scene(deserializer.span_error(error)))
|
||||
}
|
||||
|
||||
fn extensions(&self) -> &[&str] {
|
||||
&["scn.ron"]
|
||||
}
|
||||
}
|
||||
|
||||
fn normalized_world_body(text: &str) -> Result<String, io::Error> {
|
||||
scene::validate_level_text(text).map_err(invalid_scene)?;
|
||||
let migrated = scene::migrate_scene_text(text).map_err(invalid_scene)?;
|
||||
scene::strip_schema_version(&migrated).map_err(invalid_scene)
|
||||
}
|
||||
|
||||
fn invalid_scene(error: impl std::fmt::Display) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, error.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::normalized_world_body;
|
||||
use super::SchemaWorldAssetPlugin;
|
||||
use bevy::asset::{AssetPlugin, AssetServer, Assets, LoadState};
|
||||
use bevy::prelude::*;
|
||||
use bevy::world_serialization::{DynamicWorld, WorldSerializationPlugin};
|
||||
|
||||
#[test]
|
||||
fn versioned_world_assets_are_validated_and_unwrapped_for_bevy() {
|
||||
let body = normalized_world_body(
|
||||
r#"(schema_version: 2, resources: {}, entities: {
|
||||
1: (components: { "shared::components::LevelObject": () }),
|
||||
})"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(body.starts_with("(resources:"));
|
||||
assert!(!body.contains("schema_version"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_hierarchy_is_rejected_before_world_deserialization() {
|
||||
let error = normalized_world_body(
|
||||
r#"(schema_version: 2, resources: {}, entities: {
|
||||
1: (components: { "bevy_ecs::hierarchy::ChildOf": (9) }),
|
||||
})"#,
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("missing hierarchy parent `9`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asset_server_loads_the_committed_versioned_prefab_fixture() {
|
||||
let assets = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets");
|
||||
let mut app = App::new();
|
||||
app.add_plugins(MinimalPlugins)
|
||||
.add_plugins(AssetPlugin {
|
||||
file_path: assets.to_string_lossy().into_owned(),
|
||||
..default()
|
||||
})
|
||||
.add_plugins(WorldSerializationPlugin)
|
||||
.register_type::<Name>()
|
||||
.register_type::<Transform>()
|
||||
.register_type::<shared::LevelObject>()
|
||||
.register_type::<shared::ActorId>()
|
||||
.register_type::<shared::ActorKind>()
|
||||
.register_type::<shared::EditorVisibility>()
|
||||
.register_type::<shared::PrefabInstance>()
|
||||
.register_type::<shared::PrefabRef>()
|
||||
.add_plugins(SchemaWorldAssetPlugin);
|
||||
|
||||
let handle: Handle<DynamicWorld> = app
|
||||
.world()
|
||||
.resource::<AssetServer>()
|
||||
.load("prefabs/example_variant.scn.ron");
|
||||
for _ in 0..200 {
|
||||
app.update();
|
||||
if app
|
||||
.world()
|
||||
.resource::<Assets<DynamicWorld>>()
|
||||
.get(&handle)
|
||||
.is_some()
|
||||
{
|
||||
return;
|
||||
}
|
||||
if matches!(
|
||||
app.world()
|
||||
.resource::<AssetServer>()
|
||||
.load_state(handle.id()),
|
||||
LoadState::Failed(_)
|
||||
) {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
|
||||
panic!(
|
||||
"versioned prefab fixture did not load: {:?}",
|
||||
app.world()
|
||||
.resource::<AssetServer>()
|
||||
.load_state(handle.id())
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user