Build renderer and material component foundations
Add dedicated skinned rendering, pose restoration, shared Material and Material Instance slots, registry-driven components, Surface/Solari integration, transactional schema upgrades, navigation authoring, documentation, and evaluation evidence.
This commit is contained in:
1 parent
0553a85220
commit
0798aa5d57
169 files changed
+27098
-3469
No files matched your search
+398
-34
@@ -1,6 +1,6 @@
|
||||
//! Runtime adapter for scene-authored animation controllers.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -12,11 +12,14 @@ use bevy::animation::{
|
||||
RepeatAnimation,
|
||||
};
|
||||
use bevy::gltf::GltfAssetLabel;
|
||||
use bevy::mesh::morph::MorphWeights;
|
||||
use bevy::mesh::skinning::{SkinnedMesh, SkinnedMeshInverseBindposes};
|
||||
use bevy::prelude::*;
|
||||
use bevy::world_serialization::WorldInstanceReady;
|
||||
use shared::{
|
||||
animation_clip_source_index, asset_server_path, AnimationControllerDesc, AnimationEventDesc,
|
||||
AnimationManifest, AnimationStateDesc, HydratedModelRoot, ANIMATION_ARTIFACT_DIR,
|
||||
AnimationManifest, AnimationStateDesc, HydratedSkinnedMeshRoot, ANIMATION_ARTIFACT_DIR,
|
||||
ANIMATION_MANIFEST_SCHEMA_VERSION,
|
||||
};
|
||||
use sim::SimEnabled;
|
||||
|
||||
@@ -114,6 +117,29 @@ pub struct AuthoredAnimationRuntime {
|
||||
last_event_time: Option<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct SkinnedPoseBaselineEntry {
|
||||
entity: Entity,
|
||||
transform: Option<Transform>,
|
||||
morph_weights: Option<MorphWeights>,
|
||||
}
|
||||
|
||||
/// Imported rest-pose state captured before Blacksite starts authored animation playback.
|
||||
///
|
||||
/// This component is runtime-only. It is replaced whenever a new hydrated hierarchy becomes
|
||||
/// ready, so renderer reloads cannot restore values onto an older scene generation.
|
||||
#[derive(Component, Debug, Clone)]
|
||||
pub struct SkinnedPoseBaseline {
|
||||
pub root: Entity,
|
||||
entries: Vec<SkinnedPoseBaselineEntry>,
|
||||
}
|
||||
|
||||
impl SkinnedPoseBaseline {
|
||||
pub fn entry_count(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Editor-only transient preview request consumed by the shared runtime adapter.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AnimationPreviewRequest {
|
||||
@@ -163,10 +189,14 @@ impl Plugin for GameAnimationPlugin {
|
||||
fn attach_controller_when_model_ready(
|
||||
ready: On<WorldInstanceReady>,
|
||||
mut commands: Commands,
|
||||
roots: Query<&HydratedModelRoot>,
|
||||
roots: Query<&HydratedSkinnedMeshRoot>,
|
||||
controllers: Query<&AnimationControllerDesc>,
|
||||
children: Query<&Children>,
|
||||
players: Query<Entity, With<AnimationPlayer>>,
|
||||
transforms: Query<&Transform>,
|
||||
morph_weights: Query<&MorphWeights>,
|
||||
skinned_meshes: Query<(Entity, &SkinnedMesh)>,
|
||||
inverse_bindposes: Option<Res<Assets<SkinnedMeshInverseBindposes>>>,
|
||||
asset_server: Res<AssetServer>,
|
||||
mut graphs: ResMut<Assets<AnimationGraph>>,
|
||||
mut diagnostics: ResMut<AnimationRuntimeDiagnostics>,
|
||||
@@ -175,6 +205,18 @@ fn attach_controller_when_model_ready(
|
||||
let Ok(root) = roots.get(ready.entity) else {
|
||||
return;
|
||||
};
|
||||
let subtree = std::iter::once(ready.entity)
|
||||
.chain(children.iter_descendants(ready.entity))
|
||||
.collect::<HashSet<_>>();
|
||||
let baseline = capture_pose_baseline(ready.entity, &subtree, &transforms, &morph_weights);
|
||||
commands.entity(root.owner).insert(baseline);
|
||||
validate_skinned_bindings(
|
||||
root.owner,
|
||||
&subtree,
|
||||
&skinned_meshes,
|
||||
inverse_bindposes.as_deref(),
|
||||
&mut diagnostics,
|
||||
);
|
||||
let Ok(controller) = controllers.get(root.owner) else {
|
||||
return;
|
||||
};
|
||||
@@ -182,7 +224,7 @@ fn attach_controller_when_model_ready(
|
||||
diagnostics.push(
|
||||
Some(root.owner),
|
||||
"animation.player_missing",
|
||||
"The hydrated model contains no AnimationPlayer. Verify that the selected glTF scene contains an animated hierarchy.",
|
||||
"The hydrated skinned mesh contains no AnimationPlayer. Verify that the selected glTF scene contains an animated hierarchy.",
|
||||
);
|
||||
return;
|
||||
};
|
||||
@@ -199,6 +241,75 @@ fn attach_controller_when_model_ready(
|
||||
);
|
||||
}
|
||||
|
||||
fn capture_pose_baseline(
|
||||
root: Entity,
|
||||
subtree: &HashSet<Entity>,
|
||||
transforms: &Query<&Transform>,
|
||||
morph_weights: &Query<&MorphWeights>,
|
||||
) -> SkinnedPoseBaseline {
|
||||
let mut entities = subtree.iter().copied().collect::<Vec<_>>();
|
||||
entities.sort_by_key(|entity| entity.to_bits());
|
||||
let entries = entities
|
||||
.into_iter()
|
||||
.filter_map(|entity| {
|
||||
let transform = transforms.get(entity).ok().copied();
|
||||
let morph_weights = morph_weights.get(entity).ok().cloned();
|
||||
(transform.is_some() || morph_weights.is_some()).then_some(SkinnedPoseBaselineEntry {
|
||||
entity,
|
||||
transform,
|
||||
morph_weights,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
SkinnedPoseBaseline { root, entries }
|
||||
}
|
||||
|
||||
fn validate_skinned_bindings(
|
||||
actor: Entity,
|
||||
subtree: &HashSet<Entity>,
|
||||
skinned_meshes: &Query<(Entity, &SkinnedMesh)>,
|
||||
inverse_bindposes: Option<&Assets<SkinnedMeshInverseBindposes>>,
|
||||
diagnostics: &mut AnimationRuntimeDiagnostics,
|
||||
) {
|
||||
for (mesh_entity, skin) in skinned_meshes.iter() {
|
||||
if !subtree.contains(&mesh_entity) {
|
||||
continue;
|
||||
}
|
||||
if let Some(inverse_bindposes) = inverse_bindposes {
|
||||
let Some(bindposes) = inverse_bindposes.get(&skin.inverse_bindposes) else {
|
||||
diagnostics.push(
|
||||
Some(actor),
|
||||
"animation.inverse_bindposes_missing",
|
||||
format!(
|
||||
"Skinned mesh {mesh_entity} has no loaded inverse-bind-pose asset; the imported hierarchy was preserved but cannot be validated."
|
||||
),
|
||||
);
|
||||
continue;
|
||||
};
|
||||
if skin.joints.len() != bindposes.len() {
|
||||
diagnostics.push(
|
||||
Some(actor),
|
||||
"animation.skin_binding_count_mismatch",
|
||||
format!(
|
||||
"Skinned mesh {mesh_entity} has {} joints but {} inverse bind poses. Re-export the rig and reimport the model.",
|
||||
skin.joints.len(),
|
||||
bindposes.len()
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(joint) = skin.joints.iter().find(|joint| !subtree.contains(joint)) {
|
||||
diagnostics.push(
|
||||
Some(actor),
|
||||
"animation.skin_joint_outside_hierarchy",
|
||||
format!(
|
||||
"Skinned mesh {mesh_entity} references joint {joint} outside its hydrated hierarchy. Re-export the rig as one scene hierarchy."
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn reconcile_changed_controllers(
|
||||
mut commands: Commands,
|
||||
@@ -209,7 +320,7 @@ fn reconcile_changed_controllers(
|
||||
Changed<AnimationControllerDesc>,
|
||||
)>,
|
||||
>,
|
||||
roots: Query<(Entity, &HydratedModelRoot)>,
|
||||
roots: Query<(Entity, &HydratedSkinnedMeshRoot)>,
|
||||
children: Query<&Children>,
|
||||
players: Query<Entity, With<AnimationPlayer>>,
|
||||
asset_server: Res<AssetServer>,
|
||||
@@ -266,6 +377,9 @@ fn configure_runtime(
|
||||
Some(controller.default_crossfade_seconds),
|
||||
)
|
||||
});
|
||||
commands.queue(move |world: &mut World| {
|
||||
restore_pose_baseline(world, actor);
|
||||
});
|
||||
commands.entity(player).insert((
|
||||
AnimationGraphHandle(graph.clone()),
|
||||
AnimationTransitions::new(),
|
||||
@@ -298,6 +412,7 @@ fn clear_failed_runtime_configuration(commands: &mut Commands, actor: Entity, pl
|
||||
if let Some(mut animation_player) = world.get_mut::<AnimationPlayer>(player) {
|
||||
animation_player.stop_all();
|
||||
}
|
||||
restore_pose_baseline(world, actor);
|
||||
if let Ok(mut player_entity) = world.get_entity_mut(player) {
|
||||
player_entity
|
||||
.remove::<AnimationGraphHandle>()
|
||||
@@ -468,7 +583,17 @@ fn load_runtime_animation_manifest(
|
||||
let path = runtime_animation_manifest_path(assets_root, asset_id);
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|error| format!("could not read {}: {error}", path.display()))?;
|
||||
ron::from_str(&text).map_err(|error| format!("could not parse {}: {error}", path.display()))
|
||||
let manifest: AnimationManifest = ron::from_str(&text)
|
||||
.map_err(|error| format!("could not parse {}: {error}", path.display()))?;
|
||||
if manifest.schema_version != ANIMATION_MANIFEST_SCHEMA_VERSION {
|
||||
return Err(format!(
|
||||
"animation manifest {} uses schema {} but runtime requires {}; reimport the source model",
|
||||
path.display(),
|
||||
manifest.schema_version,
|
||||
ANIMATION_MANIFEST_SCHEMA_VERSION
|
||||
));
|
||||
}
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
fn process_animation_state_requests(
|
||||
@@ -550,8 +675,18 @@ fn sync_authored_animation_playback(
|
||||
.request
|
||||
.as_ref()
|
||||
.filter(|request| request.actor == actor);
|
||||
let should_run = sim_enabled.0 || preview_request.is_some();
|
||||
if !should_run {
|
||||
let desired_state = preview_request
|
||||
.map(|request| request.state_id.as_str())
|
||||
.or(runtime.desired_state.as_deref())
|
||||
.or((!controller.default_state.trim().is_empty())
|
||||
.then_some(controller.default_state.as_str()))
|
||||
.map(str::to_owned);
|
||||
let sampling_edit_rest = !sim_enabled.0
|
||||
&& preview_request.is_none()
|
||||
&& runtime.active_state.is_none()
|
||||
&& desired_state.is_some();
|
||||
let should_evaluate = sim_enabled.0 || preview_request.is_some() || sampling_edit_rest;
|
||||
if !should_evaluate {
|
||||
if runtime.active_state.is_some() {
|
||||
player.pause_all();
|
||||
runtime.paused_by_sim = true;
|
||||
@@ -572,12 +707,6 @@ fn sync_authored_animation_playback(
|
||||
.unwrap_or_default()
|
||||
});
|
||||
|
||||
let desired_state = preview_request
|
||||
.map(|request| request.state_id.as_str())
|
||||
.or(runtime.desired_state.as_deref())
|
||||
.or((!controller.default_state.trim().is_empty())
|
||||
.then_some(controller.default_state.as_str()))
|
||||
.map(str::to_owned);
|
||||
let Some(desired_state) = desired_state else {
|
||||
continue;
|
||||
};
|
||||
@@ -600,7 +729,7 @@ fn sync_authored_animation_playback(
|
||||
};
|
||||
|
||||
if runtime.active_state.as_deref() != Some(desired_state.as_str()) {
|
||||
let crossfade = if preview_request.is_some() {
|
||||
let crossfade = if preview_request.is_some() || sampling_edit_rest {
|
||||
0.0
|
||||
} else {
|
||||
runtime
|
||||
@@ -830,23 +959,49 @@ fn crossed_animation_events<'a>(
|
||||
crossed
|
||||
}
|
||||
|
||||
fn cleanup_stale_animation_runtimes(
|
||||
mut commands: Commands,
|
||||
controllers: Query<(), With<AnimationControllerDesc>>,
|
||||
runtimes: Query<(Entity, &AuthoredAnimationRuntime)>,
|
||||
mut players: Query<&mut AnimationPlayer>,
|
||||
) {
|
||||
for (actor, runtime) in &runtimes {
|
||||
if controllers.get(actor).is_ok() && players.get(runtime.player).is_ok() {
|
||||
continue;
|
||||
fn cleanup_stale_animation_runtimes(world: &mut World) {
|
||||
let runtimes = world
|
||||
.query::<(Entity, &AuthoredAnimationRuntime)>()
|
||||
.iter(world)
|
||||
.map(|(actor, runtime)| (actor, runtime.player))
|
||||
.collect::<Vec<_>>();
|
||||
let stale = runtimes
|
||||
.into_iter()
|
||||
.filter(|(actor, player)| {
|
||||
let controller_exists = world.get::<AnimationControllerDesc>(*actor).is_some();
|
||||
let player_exists = world.get::<AnimationPlayer>(*player).is_some();
|
||||
!controller_exists || !player_exists
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for (actor, player) in stale {
|
||||
if let Some(mut animation_player) = world.get_mut::<AnimationPlayer>(player) {
|
||||
animation_player.stop_all();
|
||||
}
|
||||
if let Ok(mut player) = players.get_mut(runtime.player) {
|
||||
player.stop_all();
|
||||
commands
|
||||
.entity(runtime.player)
|
||||
.remove::<SuspendedAnimationTransitions>();
|
||||
if let Ok(mut player_entity) = world.get_entity_mut(player) {
|
||||
player_entity.remove::<SuspendedAnimationTransitions>();
|
||||
}
|
||||
restore_pose_baseline(world, actor);
|
||||
if let Ok(mut actor_entity) = world.get_entity_mut(actor) {
|
||||
actor_entity.remove::<AuthoredAnimationRuntime>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_pose_baseline(world: &mut World, actor: Entity) {
|
||||
let Some(baseline) = world.get::<SkinnedPoseBaseline>(actor).cloned() else {
|
||||
return;
|
||||
};
|
||||
for entry in baseline.entries {
|
||||
if let Some(transform) = entry.transform {
|
||||
if let Some(mut current) = world.get_mut::<Transform>(entry.entity) {
|
||||
*current = transform;
|
||||
}
|
||||
}
|
||||
if let Some(morph_weights) = entry.morph_weights {
|
||||
if let Some(mut current) = world.get_mut::<MorphWeights>(entry.entity) {
|
||||
*current = morph_weights;
|
||||
}
|
||||
}
|
||||
commands.entity(actor).remove::<AuthoredAnimationRuntime>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -919,8 +1074,15 @@ pub fn stop_animation_preview(world: &mut World) {
|
||||
animation_player.stop_all();
|
||||
}
|
||||
}
|
||||
restore_pose_baseline(world, actor);
|
||||
let edit_rest_state = world
|
||||
.get::<AnimationControllerDesc>(actor)
|
||||
.map(|controller| controller.default_state.clone())
|
||||
.filter(|state| !state.trim().is_empty());
|
||||
if let Some(mut runtime) = world.get_mut::<AuthoredAnimationRuntime>(actor) {
|
||||
runtime.active_state = None;
|
||||
runtime.desired_state = edit_rest_state;
|
||||
runtime.requested_crossfade_seconds = Some(0.0);
|
||||
runtime.paused_by_sim = false;
|
||||
runtime.applied_preview_revision = None;
|
||||
runtime.last_event_time = None;
|
||||
@@ -943,10 +1105,15 @@ pub fn reset_authored_animation_runtime(world: &mut World) {
|
||||
if let Some(mut animation_player) = world.get_mut::<AnimationPlayer>(player) {
|
||||
animation_player.stop_all();
|
||||
}
|
||||
restore_pose_baseline(world, actor);
|
||||
let edit_rest_state = world
|
||||
.get::<AnimationControllerDesc>(actor)
|
||||
.map(|controller| controller.default_state.clone())
|
||||
.filter(|state| !state.trim().is_empty());
|
||||
if let Some(mut runtime) = world.get_mut::<AuthoredAnimationRuntime>(actor) {
|
||||
runtime.active_state = None;
|
||||
runtime.desired_state = None;
|
||||
runtime.requested_crossfade_seconds = None;
|
||||
runtime.desired_state = edit_rest_state;
|
||||
runtime.requested_crossfade_seconds = Some(0.0);
|
||||
runtime.paused_by_sim = false;
|
||||
runtime.applied_preview_revision = None;
|
||||
runtime.last_event_time = None;
|
||||
@@ -960,7 +1127,7 @@ mod tests {
|
||||
use bevy::asset::{AssetApp, AssetPlugin};
|
||||
use shared::{
|
||||
AnimationClipRecord, AnimationManifestSource, AnimationPlaybackRange,
|
||||
AnimationSourceFingerprint, EditorAssetRef, ANIMATION_MANIFEST_SCHEMA_VERSION,
|
||||
AnimationSourceFingerprint, EditorAssetRef,
|
||||
};
|
||||
|
||||
fn state(id: &str, index: usize) -> AnimationStateDesc {
|
||||
@@ -1094,6 +1261,7 @@ mod tests {
|
||||
schema_version: ANIMATION_MANIFEST_SCHEMA_VERSION,
|
||||
asset_id: state.clip.asset_id.clone(),
|
||||
label: "Moved Model".into(),
|
||||
default_animation_clip_id: None,
|
||||
source: AnimationManifestSource {
|
||||
path: "assets/models/relocated.glb".into(),
|
||||
format: "glb".into(),
|
||||
@@ -1144,7 +1312,7 @@ mod tests {
|
||||
let actor = app.world_mut().spawn_empty().id();
|
||||
let root = app
|
||||
.world_mut()
|
||||
.spawn((HydratedModelRoot { owner: actor }, ChildOf(actor)))
|
||||
.spawn((HydratedSkinnedMeshRoot { owner: actor }, ChildOf(actor)))
|
||||
.id();
|
||||
let stale_node = AnimationNodeIndex::new(0);
|
||||
let mut animation_player = AnimationPlayer::default();
|
||||
@@ -1362,6 +1530,202 @@ mod tests {
|
||||
.all_paused());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_mode_samples_and_pauses_the_explicit_default_state() {
|
||||
let (mut app, actor, player, _) = runtime_test_app(false);
|
||||
|
||||
app.update();
|
||||
|
||||
assert_eq!(
|
||||
app.world()
|
||||
.get::<AuthoredAnimationRuntime>(actor)
|
||||
.and_then(|runtime| runtime.active_state.as_deref()),
|
||||
Some("idle")
|
||||
);
|
||||
assert!(app
|
||||
.world()
|
||||
.get::<AnimationPlayer>(player)
|
||||
.is_some_and(AnimationPlayer::all_paused));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_preview_restores_transform_and_morph_baseline_before_resampling() {
|
||||
let mut app = App::new();
|
||||
app.init_resource::<AnimationPreviewRuntime>();
|
||||
let baseline_transform = Transform::from_xyz(1.0, 2.0, 3.0);
|
||||
let baseline_morph = MorphWeights::new(vec![0.1, 0.9], None).unwrap();
|
||||
let target = app
|
||||
.world_mut()
|
||||
.spawn((
|
||||
Transform::from_xyz(9.0, 8.0, 7.0),
|
||||
MorphWeights::new(vec![0.8, 0.2], None).unwrap(),
|
||||
))
|
||||
.id();
|
||||
let node = AnimationNodeIndex::new(0);
|
||||
let mut animation_player = AnimationPlayer::default();
|
||||
animation_player.start(node);
|
||||
let player = app.world_mut().spawn(animation_player).id();
|
||||
let actor = app
|
||||
.world_mut()
|
||||
.spawn(AnimationControllerDesc {
|
||||
states: vec![state("idle", 0)],
|
||||
default_state: "idle".into(),
|
||||
..Default::default()
|
||||
})
|
||||
.id();
|
||||
app.world_mut().entity_mut(actor).insert((
|
||||
SkinnedPoseBaseline {
|
||||
root: target,
|
||||
entries: vec![SkinnedPoseBaselineEntry {
|
||||
entity: target,
|
||||
transform: Some(baseline_transform),
|
||||
morph_weights: Some(baseline_morph),
|
||||
}],
|
||||
},
|
||||
AuthoredAnimationRuntime {
|
||||
player,
|
||||
graph: Handle::default(),
|
||||
state_nodes: HashMap::from([("idle".into(), node)]),
|
||||
active_state: Some("idle".into()),
|
||||
desired_state: Some("idle".into()),
|
||||
requested_crossfade_seconds: None,
|
||||
paused_by_sim: false,
|
||||
applied_preview_revision: None,
|
||||
metadata_by_state: HashMap::new(),
|
||||
last_event_time: None,
|
||||
},
|
||||
));
|
||||
set_animation_preview(
|
||||
app.world_mut(),
|
||||
AnimationPreviewRequest {
|
||||
actor,
|
||||
state_id: "idle".into(),
|
||||
seek_seconds: Some(0.7),
|
||||
playing: true,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
stop_animation_preview(app.world_mut());
|
||||
|
||||
assert_eq!(
|
||||
app.world().get::<Transform>(target),
|
||||
Some(&baseline_transform)
|
||||
);
|
||||
assert_eq!(
|
||||
app.world().get::<MorphWeights>(target).unwrap().weights(),
|
||||
&[0.1, 0.9]
|
||||
);
|
||||
assert!(app
|
||||
.world()
|
||||
.get::<AnimationPlayer>(player)
|
||||
.unwrap()
|
||||
.playing_animations()
|
||||
.next()
|
||||
.is_none());
|
||||
let runtime = app.world().get::<AuthoredAnimationRuntime>(actor).unwrap();
|
||||
assert!(runtime.active_state.is_none());
|
||||
assert_eq!(runtime.desired_state.as_deref(), Some("idle"));
|
||||
assert_eq!(runtime.requested_crossfade_seconds, Some(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_controller_restores_baseline_and_clears_runtime() {
|
||||
let mut world = World::new();
|
||||
let target = world.spawn(Transform::from_xyz(9.0, 0.0, 0.0)).id();
|
||||
let player = world.spawn(AnimationPlayer::default()).id();
|
||||
let actor = world
|
||||
.spawn((
|
||||
SkinnedPoseBaseline {
|
||||
root: target,
|
||||
entries: vec![SkinnedPoseBaselineEntry {
|
||||
entity: target,
|
||||
transform: Some(Transform::from_xyz(1.0, 0.0, 0.0)),
|
||||
morph_weights: None,
|
||||
}],
|
||||
},
|
||||
AuthoredAnimationRuntime {
|
||||
player,
|
||||
graph: Handle::default(),
|
||||
state_nodes: HashMap::new(),
|
||||
active_state: Some("idle".into()),
|
||||
desired_state: Some("idle".into()),
|
||||
requested_crossfade_seconds: None,
|
||||
paused_by_sim: false,
|
||||
applied_preview_revision: None,
|
||||
metadata_by_state: HashMap::new(),
|
||||
last_event_time: None,
|
||||
},
|
||||
))
|
||||
.id();
|
||||
|
||||
cleanup_stale_animation_runtimes(&mut world);
|
||||
|
||||
assert_eq!(world.get::<Transform>(target).unwrap().translation, Vec3::X);
|
||||
assert!(world.get::<AuthoredAnimationRuntime>(actor).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_skin_records_are_validated_independently_against_shared_joints() {
|
||||
let mut world = World::new();
|
||||
let actor = world.spawn_empty().id();
|
||||
let root = world.spawn_empty().id();
|
||||
let joint = world.spawn_empty().id();
|
||||
let mut inverse_bindposes = Assets::<SkinnedMeshInverseBindposes>::default();
|
||||
let first_bindposes =
|
||||
inverse_bindposes.add(SkinnedMeshInverseBindposes::from(vec![Mat4::IDENTITY]));
|
||||
let second_bindposes =
|
||||
inverse_bindposes.add(SkinnedMeshInverseBindposes::from(vec![Mat4::IDENTITY]));
|
||||
let first_mesh = world
|
||||
.spawn(SkinnedMesh {
|
||||
inverse_bindposes: first_bindposes,
|
||||
joints: vec![joint],
|
||||
})
|
||||
.id();
|
||||
let second_mesh = world
|
||||
.spawn(SkinnedMesh {
|
||||
inverse_bindposes: second_bindposes,
|
||||
joints: vec![joint],
|
||||
})
|
||||
.id();
|
||||
let subtree = HashSet::from([root, joint, first_mesh, second_mesh]);
|
||||
let mut diagnostics = AnimationRuntimeDiagnostics::default();
|
||||
let mut query_state =
|
||||
bevy::ecs::system::SystemState::<Query<(Entity, &SkinnedMesh)>>::new(&mut world);
|
||||
|
||||
{
|
||||
let skins = query_state.get(&world).unwrap();
|
||||
validate_skinned_bindings(
|
||||
actor,
|
||||
&subtree,
|
||||
&skins,
|
||||
Some(&inverse_bindposes),
|
||||
&mut diagnostics,
|
||||
);
|
||||
}
|
||||
assert!(diagnostics.entries().next().is_none());
|
||||
|
||||
world
|
||||
.get_mut::<SkinnedMesh>(second_mesh)
|
||||
.unwrap()
|
||||
.joints
|
||||
.push(joint);
|
||||
{
|
||||
let skins = query_state.get(&world).unwrap();
|
||||
validate_skinned_bindings(
|
||||
actor,
|
||||
&subtree,
|
||||
&skins,
|
||||
Some(&inverse_bindposes),
|
||||
&mut diagnostics,
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
diagnostics.latest().map(|diagnostic| diagnostic.code),
|
||||
Some("animation.skin_binding_count_mismatch")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_state_request_is_rejected_without_message_side_effect() {
|
||||
let mut app = App::new();
|
||||
|
||||
@@ -12,9 +12,9 @@ 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,
|
||||
asset_server_path, authoring_component_active, ActorId, AudioAttenuationDesc,
|
||||
AudioListenerDesc, AudioRolloff, AudioSourceDesc, AuthoringComponentStates, InspectorOrder,
|
||||
LevelObject, COMPONENT_AUDIO_LISTENER_DESC, COMPONENT_AUDIO_SOURCE_DESC,
|
||||
};
|
||||
use sim::{PlayerCamera, SimEnabled};
|
||||
|
||||
@@ -265,10 +265,13 @@ fn reconcile_audio_listener(world: &mut World) {
|
||||
Entity,
|
||||
&AudioListenerDesc,
|
||||
Option<&ActorId>,
|
||||
Option<&AuthoringComponentStates>,
|
||||
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) {
|
||||
for (entity, desc, actor_id, states, legacy_order) in query.iter(world) {
|
||||
if desc.enabled
|
||||
&& authoring_component_active(states, legacy_order, COMPONENT_AUDIO_LISTENER_DESC)
|
||||
{
|
||||
candidates.push((
|
||||
entity,
|
||||
*desc,
|
||||
@@ -343,10 +346,11 @@ fn reconcile_audio_sources(world: &mut World) {
|
||||
let mut query = world.query_filtered::<(
|
||||
Entity,
|
||||
&AudioSourceDesc,
|
||||
Option<&AuthoringComponentStates>,
|
||||
Option<&InspectorOrder>,
|
||||
), With<LevelObject>>();
|
||||
for (entity, desc, order) in query.iter(world) {
|
||||
if inspector_component_active(order, COMPONENT_AUDIO_SOURCE_DESC) {
|
||||
for (entity, desc, states, legacy_order) in query.iter(world) {
|
||||
if authoring_component_active(states, legacy_order, COMPONENT_AUDIO_SOURCE_DESC) {
|
||||
sources.push((entity, desc.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ pub mod animation;
|
||||
pub mod audio;
|
||||
pub mod editor_ext;
|
||||
pub mod launch;
|
||||
pub mod navigation;
|
||||
mod scene_bootstrap;
|
||||
mod schema_world_loader;
|
||||
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
use std::path::Path;
|
||||
|
||||
use bevy::prelude::Vec3;
|
||||
use nav_glam::{Vec2 as NavVec2, Vec3 as NavVec3};
|
||||
use polyanya::Mesh;
|
||||
use scene::navigation::{read_navigation_artifact, NavigationBakeArtifact, NavigationLinkInput};
|
||||
|
||||
/// Loaded navigation artifact and its baked Polyanya acceleration data.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NavigationRuntime {
|
||||
artifact: NavigationBakeArtifact,
|
||||
mesh: Mesh,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct NavigationPath {
|
||||
pub points: Vec<Vec3>,
|
||||
pub length: f32,
|
||||
pub used_link_actor_id: Option<String>,
|
||||
}
|
||||
|
||||
impl NavigationRuntime {
|
||||
pub fn from_artifact(artifact: NavigationBakeArtifact) -> Result<Self, String> {
|
||||
if artifact.mesh.layers.is_empty()
|
||||
|| artifact
|
||||
.mesh
|
||||
.layers
|
||||
.iter()
|
||||
.all(|layer| layer.polygons.is_empty())
|
||||
{
|
||||
return Err("navigation artifact contains no walkable polygons; rebake it".into());
|
||||
}
|
||||
let mesh = artifact.runtime_mesh();
|
||||
Ok(Self { artifact, mesh })
|
||||
}
|
||||
|
||||
pub fn load(path: &Path) -> Result<Self, String> {
|
||||
Self::from_artifact(read_navigation_artifact(path)?)
|
||||
}
|
||||
|
||||
pub fn artifact(&self) -> &NavigationBakeArtifact {
|
||||
&self.artifact
|
||||
}
|
||||
|
||||
pub fn query(&self, start: Vec3, end: Vec3) -> Result<NavigationPath, String> {
|
||||
if !start.is_finite() || !end.is_finite() {
|
||||
return Err("navigation query endpoints must be finite".into());
|
||||
}
|
||||
|
||||
let mut best = self.direct_path(start, end).ok().map(|path| Candidate {
|
||||
path,
|
||||
weighted_cost: 0.0,
|
||||
});
|
||||
if let Some(candidate) = best.as_mut() {
|
||||
candidate.weighted_cost = candidate.path.length;
|
||||
}
|
||||
|
||||
for link in self.artifact.links.iter().filter(|link| link.enabled) {
|
||||
self.consider_link(start, end, link, false, &mut best);
|
||||
if link.bidirectional {
|
||||
self.consider_link(start, end, link, true, &mut best);
|
||||
}
|
||||
}
|
||||
|
||||
best.map(|candidate| candidate.path).ok_or_else(|| {
|
||||
"no navigation path connects the requested endpoints; inspect islands or add a link"
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn validate_links(&self) -> Vec<String> {
|
||||
let mut findings = Vec::new();
|
||||
for link in self.artifact.links.iter().filter(|link| link.enabled) {
|
||||
for (label, endpoint) in [("start", link.start), ("end", link.end)] {
|
||||
let point = NavVec2::new(endpoint[0], endpoint[2]);
|
||||
let Some(closest) = self.mesh.get_closest_point(point) else {
|
||||
findings.push(format!(
|
||||
"navigation link {} {label} endpoint is not near a walkable polygon",
|
||||
link.actor_id
|
||||
));
|
||||
continue;
|
||||
};
|
||||
if closest.position().distance(point) > self.artifact.agent.radius * 2.0 {
|
||||
findings.push(format!(
|
||||
"navigation link {} {label} endpoint is farther than two agent radii from the mesh",
|
||||
link.actor_id
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
fn consider_link(
|
||||
&self,
|
||||
start: Vec3,
|
||||
end: Vec3,
|
||||
link: &NavigationLinkInput,
|
||||
reverse: bool,
|
||||
best: &mut Option<Candidate>,
|
||||
) {
|
||||
let (entry, exit) = if reverse {
|
||||
(vec3(link.end), vec3(link.start))
|
||||
} else {
|
||||
(vec3(link.start), vec3(link.end))
|
||||
};
|
||||
let (Ok(mut first), Ok(second)) =
|
||||
(self.direct_path(start, entry), self.direct_path(exit, end))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
append_distinct(&mut first.points, entry);
|
||||
append_distinct(&mut first.points, exit);
|
||||
for point in second.points.into_iter().skip(1) {
|
||||
append_distinct(&mut first.points, point);
|
||||
}
|
||||
let link_length = entry.distance(exit);
|
||||
first.length += link_length + second.length;
|
||||
first.used_link_actor_id = Some(link.actor_id.clone());
|
||||
let weighted_cost = first.length + link_length * (link.cost - 1.0);
|
||||
if best
|
||||
.as_ref()
|
||||
.is_none_or(|candidate| weighted_cost < candidate.weighted_cost)
|
||||
{
|
||||
*best = Some(Candidate {
|
||||
path: first,
|
||||
weighted_cost,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn direct_path(&self, start: Vec3, end: Vec3) -> Result<NavigationPath, String> {
|
||||
let start2 = NavVec2::new(start.x, start.z);
|
||||
let end2 = NavVec2::new(end.x, end.z);
|
||||
let path = self.mesh.path(start2, end2).ok_or_else(|| {
|
||||
"navigation endpoints are outside the same reachable mesh island".to_string()
|
||||
})?;
|
||||
let length = path.length;
|
||||
let nav_start = NavVec3::new(start.x, start.y, start.z);
|
||||
let nav_end = NavVec3::new(end.x, end.y, end.z);
|
||||
let mut points = vec![start];
|
||||
for point in path.path_with_height(nav_start, nav_end, &self.mesh) {
|
||||
append_distinct(&mut points, Vec3::new(point.x, point.y, point.z));
|
||||
}
|
||||
append_distinct(&mut points, end);
|
||||
Ok(NavigationPath {
|
||||
points,
|
||||
length,
|
||||
used_link_actor_id: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct Candidate {
|
||||
path: NavigationPath,
|
||||
weighted_cost: f32,
|
||||
}
|
||||
|
||||
fn append_distinct(points: &mut Vec<Vec3>, point: Vec3) {
|
||||
if points
|
||||
.last()
|
||||
.is_none_or(|last| last.distance_squared(point) > 1.0e-8)
|
||||
{
|
||||
points.push(point);
|
||||
}
|
||||
}
|
||||
|
||||
fn vec3(value: [f32; 3]) -> Vec3 {
|
||||
Vec3::from_array(value)
|
||||
}
|
||||
|
||||
pub fn query_navigation_path(
|
||||
artifact_path: &Path,
|
||||
start: Vec3,
|
||||
end: Vec3,
|
||||
) -> Result<NavigationPath, String> {
|
||||
NavigationRuntime::load(artifact_path)?.query(start, end)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use scene::navigation::{
|
||||
bake_navigation, NavigationBakeInput, NavigationLinkInput, NavigationVolumeInput,
|
||||
};
|
||||
use shared::NavigationAgentProfile;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn input() -> NavigationBakeInput {
|
||||
NavigationBakeInput {
|
||||
source_scene: "assets/levels/navigation_showcase.scn.ron".into(),
|
||||
bounds_actor_id: "bounds".into(),
|
||||
center: [0.0, 0.0, 0.0],
|
||||
half_extents: [6.0, 2.0, 6.0],
|
||||
agent: NavigationAgentProfile {
|
||||
min_region_size: 1,
|
||||
merge_region_size: 2,
|
||||
..Default::default()
|
||||
},
|
||||
geometry: Vec::new(),
|
||||
obstacles: vec![NavigationVolumeInput {
|
||||
actor_id: "wall".into(),
|
||||
center: [0.0, 0.5, 0.0],
|
||||
half_extents: [0.5, 1.0, 4.5],
|
||||
}],
|
||||
areas: Vec::new(),
|
||||
links: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_query_routes_on_the_baked_mesh() {
|
||||
let runtime = NavigationRuntime::from_artifact(bake_navigation(&input()).unwrap()).unwrap();
|
||||
let path = runtime
|
||||
.query(Vec3::new(-4.0, 0.0, -5.0), Vec3::new(4.0, 0.0, -5.0))
|
||||
.unwrap();
|
||||
assert!(path.length >= 8.0);
|
||||
assert!(path.points.len() >= 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_link_can_connect_isolated_regions() {
|
||||
let mut input = input();
|
||||
input.obstacles[0].half_extents[2] = 6.0;
|
||||
input.links.push(NavigationLinkInput {
|
||||
actor_id: "door-link".into(),
|
||||
start: [-1.0, 0.0, 0.0],
|
||||
end: [1.0, 0.0, 0.0],
|
||||
bidirectional: true,
|
||||
cost: 1.0,
|
||||
enabled: true,
|
||||
});
|
||||
let runtime = NavigationRuntime::from_artifact(bake_navigation(&input).unwrap()).unwrap();
|
||||
let path = runtime
|
||||
.query(Vec3::new(-4.0, 0.0, 0.0), Vec3::new(4.0, 0.0, 0.0))
|
||||
.unwrap();
|
||||
assert_eq!(path.used_link_actor_id.as_deref(), Some("door-link"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_link_endpoint_is_reported_with_actor_identity() {
|
||||
let mut input = input();
|
||||
input.links.push(NavigationLinkInput {
|
||||
actor_id: "bad-link".into(),
|
||||
start: [100.0, 0.0, 100.0],
|
||||
end: [0.0, 0.0, 0.0],
|
||||
bidirectional: false,
|
||||
cost: 1.0,
|
||||
enabled: true,
|
||||
});
|
||||
let runtime = NavigationRuntime::from_artifact(bake_navigation(&input).unwrap()).unwrap();
|
||||
assert!(runtime
|
||||
.validate_links()
|
||||
.iter()
|
||||
.any(|finding| finding.contains("bad-link start")));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user