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
+401
-4
@@ -1,12 +1,17 @@
|
||||
//! Actor kind inference (migration only) and save-time validation.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
|
||||
use bevy::ecs::world::EntityRef;
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::{
|
||||
brush_math::validate_brush, ActorKind, BrushDesc, LevelObject, LightDesc, ModelRef,
|
||||
ObjectiveMarker, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive,
|
||||
StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn,
|
||||
animation_clip_source_index, animation_skeleton_source_index, brush_math::validate_brush,
|
||||
ActorKind, AnimationControllerDesc, AudioListenerDesc, AudioSourceDesc, BrushDesc, LevelObject,
|
||||
LightDesc, ModelRef, ObjectiveMarker, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance,
|
||||
PrefabRef, Primitive, StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn,
|
||||
AUDIO_CLIP_SUB_ASSET_ID,
|
||||
};
|
||||
|
||||
/// One-shot deterministic kind from authoring components (scene migration only).
|
||||
@@ -45,6 +50,12 @@ pub fn infer_actor_kind(entity: EntityRef<'_>) -> Option<ActorKind> {
|
||||
if entity.get::<PrefabRef>().is_some() || entity.get::<PrefabInstance>().is_some() {
|
||||
return Some(ActorKind::PrefabAnchor);
|
||||
}
|
||||
if entity.get::<AudioSourceDesc>().is_some() {
|
||||
return Some(ActorKind::AudioSource);
|
||||
}
|
||||
if entity.get::<AudioListenerDesc>().is_some() {
|
||||
return Some(ActorKind::AudioListener);
|
||||
}
|
||||
Some(ActorKind::Empty)
|
||||
}
|
||||
|
||||
@@ -72,6 +83,27 @@ pub enum ActorValidationError {
|
||||
PostProcessVolumeInvalidBlendDistance,
|
||||
PostProcessVolumeInvalidOverrideScalar,
|
||||
PostProcessVolumeMissingDesc,
|
||||
AudioSourceMissingDesc,
|
||||
AudioSourceMissingClip,
|
||||
AudioSourceInvalidClipReference,
|
||||
AudioSourceInvalidGain,
|
||||
AudioSourceInvalidPitch,
|
||||
AudioSourceInvalidSpatialBlend,
|
||||
AudioSourceInvalidAttenuation,
|
||||
AudioSourceMissingBus,
|
||||
AudioListenerMissingDesc,
|
||||
AudioListenerInvalidEarGap,
|
||||
AnimationControllerMissingModelRef,
|
||||
AnimationControllerMissingSkeleton,
|
||||
AnimationControllerInvalidSkeletonReference,
|
||||
AnimationControllerEmptyStateId,
|
||||
AnimationControllerDuplicateStateId,
|
||||
AnimationControllerInvalidClipReference,
|
||||
AnimationControllerInvalidStateSpeed,
|
||||
AnimationControllerInvalidStateRange,
|
||||
AnimationControllerInvalidCrossfade,
|
||||
AnimationControllerMissingDefaultState,
|
||||
AnimationControllerUnknownDefaultState,
|
||||
}
|
||||
|
||||
fn is_finite_positive(v: f32) -> bool {
|
||||
@@ -96,6 +128,19 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
|
||||
return Err(ActorValidationError::MissingTransform);
|
||||
}
|
||||
|
||||
if let Some(source) = entity.get::<AudioSourceDesc>() {
|
||||
validate_audio_source(source)?;
|
||||
}
|
||||
if let Some(listener) = entity.get::<AudioListenerDesc>() {
|
||||
validate_audio_listener(listener)?;
|
||||
}
|
||||
if let Some(controller) = entity.get::<AnimationControllerDesc>() {
|
||||
if entity.get::<ModelRef>().is_none() {
|
||||
return Err(ActorValidationError::AnimationControllerMissingModelRef);
|
||||
}
|
||||
validate_animation_controller(controller)?;
|
||||
}
|
||||
|
||||
match kind {
|
||||
ActorKind::Brush => {
|
||||
let Some(brush) = entity.get::<BrushDesc>() else {
|
||||
@@ -190,6 +235,16 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
|
||||
}
|
||||
}
|
||||
}
|
||||
ActorKind::AudioSource => {
|
||||
if entity.get::<AudioSourceDesc>().is_none() {
|
||||
return Err(ActorValidationError::AudioSourceMissingDesc);
|
||||
}
|
||||
}
|
||||
ActorKind::AudioListener => {
|
||||
if entity.get::<AudioListenerDesc>().is_none() {
|
||||
return Err(ActorValidationError::AudioListenerMissingDesc);
|
||||
}
|
||||
}
|
||||
ActorKind::Empty
|
||||
| ActorKind::PrefabAnchor
|
||||
| ActorKind::PlayerSpawn
|
||||
@@ -202,10 +257,111 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_audio_source(source: &AudioSourceDesc) -> Result<(), ActorValidationError> {
|
||||
let Some(clip) = source.clip.as_ref() else {
|
||||
return Err(ActorValidationError::AudioSourceMissingClip);
|
||||
};
|
||||
if !clip.is_resolved() || clip.sub_asset_id != AUDIO_CLIP_SUB_ASSET_ID {
|
||||
return Err(ActorValidationError::AudioSourceInvalidClipReference);
|
||||
}
|
||||
if !source.gain_db.is_finite()
|
||||
|| !(settings::AUDIO_GAIN_DB_MIN..=settings::AUDIO_GAIN_DB_MAX).contains(&source.gain_db)
|
||||
{
|
||||
return Err(ActorValidationError::AudioSourceInvalidGain);
|
||||
}
|
||||
if !is_finite_positive(source.pitch) {
|
||||
return Err(ActorValidationError::AudioSourceInvalidPitch);
|
||||
}
|
||||
if !source.spatial_blend.is_finite() || !(0.0..=1.0).contains(&source.spatial_blend) {
|
||||
return Err(ActorValidationError::AudioSourceInvalidSpatialBlend);
|
||||
}
|
||||
let attenuation = source.attenuation;
|
||||
if !is_finite_non_negative(attenuation.min_distance)
|
||||
|| !attenuation.max_distance.is_finite()
|
||||
|| attenuation.max_distance <= attenuation.min_distance
|
||||
|| !is_finite_non_negative(attenuation.rolloff_factor)
|
||||
{
|
||||
return Err(ActorValidationError::AudioSourceInvalidAttenuation);
|
||||
}
|
||||
if source.bus.trim().is_empty() {
|
||||
return Err(ActorValidationError::AudioSourceMissingBus);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_audio_listener(listener: &AudioListenerDesc) -> Result<(), ActorValidationError> {
|
||||
if !is_finite_positive(listener.ear_gap) {
|
||||
return Err(ActorValidationError::AudioListenerInvalidEarGap);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_animation_controller(
|
||||
controller: &AnimationControllerDesc,
|
||||
) -> Result<(), ActorValidationError> {
|
||||
let Some(skeleton) = controller.skeleton.as_ref() else {
|
||||
return Err(ActorValidationError::AnimationControllerMissingSkeleton);
|
||||
};
|
||||
if !skeleton.is_resolved() || animation_skeleton_source_index(&skeleton.sub_asset_id).is_none()
|
||||
{
|
||||
return Err(ActorValidationError::AnimationControllerInvalidSkeletonReference);
|
||||
}
|
||||
|
||||
let mut state_ids = HashSet::with_capacity(controller.states.len());
|
||||
for state in &controller.states {
|
||||
if state.id.trim().is_empty() {
|
||||
return Err(ActorValidationError::AnimationControllerEmptyStateId);
|
||||
}
|
||||
if !state_ids.insert(state.id.as_str()) {
|
||||
return Err(ActorValidationError::AnimationControllerDuplicateStateId);
|
||||
}
|
||||
let clip_source_is_gltf = state
|
||||
.clip
|
||||
.source_path
|
||||
.as_deref()
|
||||
.and_then(|path| Path::new(path).extension())
|
||||
.and_then(|extension| extension.to_str())
|
||||
.is_some_and(|extension| {
|
||||
extension.eq_ignore_ascii_case("gltf") || extension.eq_ignore_ascii_case("glb")
|
||||
});
|
||||
if !state.clip.is_resolved()
|
||||
|| animation_clip_source_index(&state.clip.sub_asset_id).is_none()
|
||||
|| !clip_source_is_gltf
|
||||
{
|
||||
return Err(ActorValidationError::AnimationControllerInvalidClipReference);
|
||||
}
|
||||
if !state.speed.is_finite() || state.speed <= 0.0 {
|
||||
return Err(ActorValidationError::AnimationControllerInvalidStateSpeed);
|
||||
}
|
||||
if !is_finite_non_negative(state.range.start_seconds)
|
||||
|| state
|
||||
.range
|
||||
.end_seconds
|
||||
.is_some_and(|end| !end.is_finite() || end < 0.0 || end < state.range.start_seconds)
|
||||
{
|
||||
return Err(ActorValidationError::AnimationControllerInvalidStateRange);
|
||||
}
|
||||
}
|
||||
|
||||
if !is_finite_non_negative(controller.default_crossfade_seconds) {
|
||||
return Err(ActorValidationError::AnimationControllerInvalidCrossfade);
|
||||
}
|
||||
if controller.default_state.trim().is_empty() {
|
||||
return Err(ActorValidationError::AnimationControllerMissingDefaultState);
|
||||
}
|
||||
if !state_ids.contains(controller.default_state.as_str()) {
|
||||
return Err(ActorValidationError::AnimationControllerUnknownDefaultState);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::PostProcessVolumeDesc;
|
||||
use crate::{
|
||||
animation_clip_sub_asset_id, animation_skeleton_sub_asset_id, AnimationPlaybackRange,
|
||||
AnimationStateDesc, EditorAssetRef, PostProcessVolumeDesc,
|
||||
};
|
||||
|
||||
fn level_entity(world: &mut World, bundle: impl Bundle) -> Entity {
|
||||
world
|
||||
@@ -213,6 +369,40 @@ mod tests {
|
||||
.id()
|
||||
}
|
||||
|
||||
fn audio_source() -> AudioSourceDesc {
|
||||
AudioSourceDesc {
|
||||
clip: Some(
|
||||
crate::EditorAssetRef::new("audio-id", AUDIO_CLIP_SUB_ASSET_ID, "Tone")
|
||||
.with_source_path("assets/audio/tone.ogg"),
|
||||
),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn animation_controller() -> AnimationControllerDesc {
|
||||
AnimationControllerDesc {
|
||||
skeleton: Some(
|
||||
EditorAssetRef::new("model-id", animation_skeleton_sub_asset_id(0, "Rig"), "Rig")
|
||||
.with_source_path("assets/models/animated.glb"),
|
||||
),
|
||||
states: vec![AnimationStateDesc {
|
||||
id: "idle".into(),
|
||||
label: "Idle".into(),
|
||||
clip: EditorAssetRef::new(
|
||||
"model-id",
|
||||
animation_clip_sub_asset_id(0, "Idle"),
|
||||
"Idle",
|
||||
)
|
||||
.with_source_path("assets/models/animated.glb"),
|
||||
looping: true,
|
||||
speed: 1.0,
|
||||
range: AnimationPlaybackRange::default(),
|
||||
}],
|
||||
default_state: "idle".into(),
|
||||
default_crossfade_seconds: 0.2,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_static_mesh_ok() {
|
||||
let mut world = World::new();
|
||||
@@ -318,4 +508,211 @@ mod tests {
|
||||
Err(ActorValidationError::PostProcessVolumeInvalidHalfExtents)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn infers_and_validates_audio_source_and_listener_actors() {
|
||||
let mut world = World::new();
|
||||
let source = level_entity(&mut world, audio_source());
|
||||
let listener = level_entity(&mut world, AudioListenerDesc::default());
|
||||
|
||||
assert_eq!(
|
||||
infer_actor_kind(world.entity(source)),
|
||||
Some(ActorKind::AudioSource)
|
||||
);
|
||||
assert_eq!(
|
||||
infer_actor_kind(world.entity(listener)),
|
||||
Some(ActorKind::AudioListener)
|
||||
);
|
||||
world.entity_mut(source).insert(ActorKind::AudioSource);
|
||||
world.entity_mut(listener).insert(ActorKind::AudioListener);
|
||||
assert!(validate_actor(world.entity(source)).is_ok());
|
||||
assert!(validate_actor(world.entity(listener)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_source_requires_a_stable_clip_reference() {
|
||||
let mut world = World::new();
|
||||
let entity = level_entity(
|
||||
&mut world,
|
||||
(ActorKind::AudioSource, AudioSourceDesc::default()),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AudioSourceMissingClip)
|
||||
);
|
||||
|
||||
world.entity_mut(entity).insert(AudioSourceDesc {
|
||||
clip: Some(crate::EditorAssetRef::new("audio-id", "mesh:0", "Wrong")),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AudioSourceInvalidClipReference)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_scalar_and_attenuation_ranges_are_validated() {
|
||||
let mut world = World::new();
|
||||
let entity = level_entity(
|
||||
&mut world,
|
||||
(
|
||||
ActorKind::AudioSource,
|
||||
AudioSourceDesc {
|
||||
spatial_blend: 1.5,
|
||||
..audio_source()
|
||||
},
|
||||
),
|
||||
);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AudioSourceInvalidSpatialBlend)
|
||||
);
|
||||
|
||||
let listener = level_entity(
|
||||
&mut world,
|
||||
(
|
||||
ActorKind::AudioListener,
|
||||
AudioListenerDesc {
|
||||
ear_gap: 0.0,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(listener)),
|
||||
Err(ActorValidationError::AudioListenerInvalidEarGap)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn animation_controller_requires_model_and_resolved_skeleton() {
|
||||
let mut world = World::new();
|
||||
let entity = level_entity(
|
||||
&mut world,
|
||||
(ActorKind::ImportedModel, animation_controller()),
|
||||
);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AnimationControllerMissingModelRef)
|
||||
);
|
||||
|
||||
world
|
||||
.entity_mut(entity)
|
||||
.insert(ModelRef::new("assets/models/animated.glb"));
|
||||
let mut controller = animation_controller();
|
||||
controller.skeleton = None;
|
||||
world.entity_mut(entity).insert(controller);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AnimationControllerMissingSkeleton)
|
||||
);
|
||||
|
||||
let mut controller = animation_controller();
|
||||
controller.skeleton = Some(EditorAssetRef::new("model-id", "mesh:0", "Wrong"));
|
||||
world.entity_mut(entity).insert(controller);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AnimationControllerInvalidSkeletonReference)
|
||||
);
|
||||
|
||||
world.entity_mut(entity).insert(animation_controller());
|
||||
assert!(validate_actor(world.entity(entity)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn animation_controller_validates_state_identity_and_clip_reference() {
|
||||
let mut world = World::new();
|
||||
let entity = level_entity(
|
||||
&mut world,
|
||||
(
|
||||
ActorKind::ImportedModel,
|
||||
ModelRef::new("assets/models/animated.glb"),
|
||||
animation_controller(),
|
||||
),
|
||||
);
|
||||
|
||||
let mut controller = animation_controller();
|
||||
controller.states[0].id = " ".into();
|
||||
world.entity_mut(entity).insert(controller);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AnimationControllerEmptyStateId)
|
||||
);
|
||||
|
||||
let mut controller = animation_controller();
|
||||
controller.states.push(controller.states[0].clone());
|
||||
world.entity_mut(entity).insert(controller);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AnimationControllerDuplicateStateId)
|
||||
);
|
||||
|
||||
let mut controller = animation_controller();
|
||||
controller.states[0].clip =
|
||||
EditorAssetRef::new("model-id", animation_clip_sub_asset_id(0, "Idle"), "Idle")
|
||||
.with_source_path("assets/models/animated.fbx");
|
||||
world.entity_mut(entity).insert(controller);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AnimationControllerInvalidClipReference)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn animation_controller_validates_playback_ranges_and_default_state() {
|
||||
let mut world = World::new();
|
||||
let entity = level_entity(
|
||||
&mut world,
|
||||
(
|
||||
ActorKind::ImportedModel,
|
||||
ModelRef::new("assets/models/animated.glb"),
|
||||
animation_controller(),
|
||||
),
|
||||
);
|
||||
|
||||
let mut controller = animation_controller();
|
||||
controller.states[0].speed = 0.0;
|
||||
world.entity_mut(entity).insert(controller);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AnimationControllerInvalidStateSpeed)
|
||||
);
|
||||
|
||||
let mut controller = animation_controller();
|
||||
controller.states[0].range = AnimationPlaybackRange {
|
||||
start_seconds: 1.0,
|
||||
end_seconds: Some(0.5),
|
||||
};
|
||||
world.entity_mut(entity).insert(controller);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AnimationControllerInvalidStateRange)
|
||||
);
|
||||
|
||||
let mut controller = animation_controller();
|
||||
controller.default_crossfade_seconds = f32::NAN;
|
||||
world.entity_mut(entity).insert(controller);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AnimationControllerInvalidCrossfade)
|
||||
);
|
||||
|
||||
let mut controller = animation_controller();
|
||||
controller.default_state.clear();
|
||||
world.entity_mut(entity).insert(controller);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AnimationControllerMissingDefaultState)
|
||||
);
|
||||
|
||||
let mut controller = animation_controller();
|
||||
controller.default_state = "missing".into();
|
||||
world.entity_mut(entity).insert(controller);
|
||||
assert_eq!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::AnimationControllerUnknownDefaultState)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//! Persistent animation authoring data and generated import-manifest contract.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::EditorAssetRef;
|
||||
|
||||
pub const ANIMATION_MANIFEST_SCHEMA_VERSION: u32 = 2;
|
||||
pub const ANIMATION_ARTIFACT_DIR: &str = "assets/animations/generated";
|
||||
pub const ANIMATION_CLIP_SUB_ASSET_PREFIX: &str = "animation:clip:";
|
||||
pub const ANIMATION_SKELETON_SUB_ASSET_PREFIX: &str = "animation:skeleton:";
|
||||
pub const COMPONENT_ANIMATION_CONTROLLER_DESC: &str = "shared::animation::AnimationControllerDesc";
|
||||
|
||||
const DEFAULT_CROSSFADE_SECONDS: f32 = 0.2;
|
||||
const DEFAULT_PLAYBACK_SPEED: f32 = 1.0;
|
||||
|
||||
pub fn animation_clip_sub_asset_id(source_index: usize, label: &str) -> String {
|
||||
animation_sub_asset_id(ANIMATION_CLIP_SUB_ASSET_PREFIX, source_index, label)
|
||||
}
|
||||
|
||||
pub fn animation_skeleton_sub_asset_id(source_index: usize, label: &str) -> String {
|
||||
animation_sub_asset_id(ANIMATION_SKELETON_SUB_ASSET_PREFIX, source_index, label)
|
||||
}
|
||||
|
||||
pub fn animation_clip_source_index(sub_asset_id: &str) -> Option<usize> {
|
||||
animation_source_index(sub_asset_id, ANIMATION_CLIP_SUB_ASSET_PREFIX)
|
||||
}
|
||||
|
||||
pub fn animation_skeleton_source_index(sub_asset_id: &str) -> Option<usize> {
|
||||
animation_source_index(sub_asset_id, ANIMATION_SKELETON_SUB_ASSET_PREFIX)
|
||||
}
|
||||
|
||||
fn animation_sub_asset_id(prefix: &str, source_index: usize, label: &str) -> String {
|
||||
let slug = stable_slug(label);
|
||||
if slug.is_empty() {
|
||||
format!("{prefix}{source_index}:unnamed")
|
||||
} else {
|
||||
format!("{prefix}{source_index}:{slug}")
|
||||
}
|
||||
}
|
||||
|
||||
fn animation_source_index(sub_asset_id: &str, prefix: &str) -> Option<usize> {
|
||||
sub_asset_id
|
||||
.strip_prefix(prefix)?
|
||||
.split_once(':')?
|
||||
.0
|
||||
.parse()
|
||||
.ok()
|
||||
}
|
||||
|
||||
fn stable_slug(label: &str) -> String {
|
||||
let mut slug = String::new();
|
||||
for character in label.chars() {
|
||||
if character.is_ascii_alphanumeric() {
|
||||
slug.push(character.to_ascii_lowercase());
|
||||
} else if !slug.ends_with('_') {
|
||||
slug.push('_');
|
||||
}
|
||||
}
|
||||
slug.trim_matches('_').to_string()
|
||||
}
|
||||
|
||||
/// Exact identity of an imported skeleton's ordered joint paths and bind-pose structure.
|
||||
#[derive(Reflect, Default, Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AnimationSkeletonSignature(pub String);
|
||||
|
||||
impl AnimationSkeletonSignature {
|
||||
pub fn new(signature: impl Into<String>) -> Self {
|
||||
Self(signature.into())
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.trim().is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Authored playback window inside an imported clip.
|
||||
#[derive(Reflect, Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AnimationPlaybackRange {
|
||||
#[serde(default)]
|
||||
pub start_seconds: f32,
|
||||
/// `None` plays to the imported clip duration.
|
||||
#[serde(default)]
|
||||
pub end_seconds: Option<f32>,
|
||||
}
|
||||
|
||||
impl Default for AnimationPlaybackRange {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
start_seconds: 0.0,
|
||||
end_seconds: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One normalized event marker imported with an animation clip.
|
||||
#[derive(Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AnimationEventDesc {
|
||||
pub id: String,
|
||||
pub time_seconds: f32,
|
||||
#[serde(default)]
|
||||
pub payload: Option<String>,
|
||||
}
|
||||
|
||||
/// One stable, gameplay-addressable state in the v1 single-layer controller.
|
||||
#[derive(Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AnimationStateDesc {
|
||||
/// Stable runtime key. Display labels are not gameplay identifiers.
|
||||
pub id: String,
|
||||
#[serde(default)]
|
||||
pub label: String,
|
||||
pub clip: EditorAssetRef,
|
||||
#[serde(default = "default_true")]
|
||||
pub looping: bool,
|
||||
#[serde(default = "default_playback_speed")]
|
||||
pub speed: f32,
|
||||
#[serde(default)]
|
||||
pub range: AnimationPlaybackRange,
|
||||
}
|
||||
|
||||
impl Default for AnimationStateDesc {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: String::new(),
|
||||
label: String::new(),
|
||||
clip: EditorAssetRef::default(),
|
||||
looping: true,
|
||||
speed: DEFAULT_PLAYBACK_SPEED,
|
||||
range: AnimationPlaybackRange::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Scene-authored single-layer animation controller.
|
||||
///
|
||||
/// Bevy graph, player, transition, and instantiated-world state are derived at runtime.
|
||||
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AnimationControllerDesc {
|
||||
#[serde(default)]
|
||||
pub skeleton: Option<EditorAssetRef>,
|
||||
#[serde(default)]
|
||||
pub states: Vec<AnimationStateDesc>,
|
||||
/// Stable state ID selected when the hydrated model becomes ready.
|
||||
#[serde(default)]
|
||||
pub default_state: String,
|
||||
#[serde(default = "default_crossfade_seconds")]
|
||||
pub default_crossfade_seconds: f32,
|
||||
}
|
||||
|
||||
impl Default for AnimationControllerDesc {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
skeleton: None,
|
||||
states: Vec::new(),
|
||||
default_state: String::new(),
|
||||
default_crossfade_seconds: DEFAULT_CROSSFADE_SECONDS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AnimationControllerDesc {
|
||||
pub fn state(&self, id: &str) -> Option<&AnimationStateDesc> {
|
||||
self.states.iter().find(|state| state.id == id)
|
||||
}
|
||||
|
||||
pub fn state_mut(&mut self, id: &str) -> Option<&mut AnimationStateDesc> {
|
||||
self.states.iter_mut().find(|state| state.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_playback_speed() -> f32 {
|
||||
DEFAULT_PLAYBACK_SPEED
|
||||
}
|
||||
|
||||
fn default_crossfade_seconds() -> f32 {
|
||||
DEFAULT_CROSSFADE_SECONDS
|
||||
}
|
||||
|
||||
/// Versioned generated artifact for one imported model source.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AnimationManifest {
|
||||
pub schema_version: u32,
|
||||
pub asset_id: String,
|
||||
pub label: String,
|
||||
pub source: AnimationManifestSource,
|
||||
/// Whether this source format can hydrate the extracted animation data at runtime.
|
||||
pub runtime_supported: bool,
|
||||
#[serde(default)]
|
||||
pub skeletons: Vec<AnimationSkeletonRecord>,
|
||||
#[serde(default)]
|
||||
pub clips: Vec<AnimationClipRecord>,
|
||||
#[serde(default)]
|
||||
pub diagnostics: Vec<AnimationImportDiagnostic>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AnimationManifestSource {
|
||||
pub path: String,
|
||||
pub format: String,
|
||||
pub fingerprint: AnimationSourceFingerprint,
|
||||
#[serde(default)]
|
||||
pub dependencies: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AnimationSourceFingerprint {
|
||||
pub byte_len: u64,
|
||||
pub modified_unix_secs: u64,
|
||||
/// BLAKE3 hash of the source file bytes.
|
||||
pub content_hash: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AnimationSkeletonRecord {
|
||||
/// Stable imported sub-asset ID used by [`EditorAssetRef`].
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub source_index: usize,
|
||||
pub signature: AnimationSkeletonSignature,
|
||||
/// Normalized root-to-joint target paths in source joint order.
|
||||
pub joint_paths: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AnimationClipRecord {
|
||||
/// Stable imported sub-asset ID used by [`EditorAssetRef`].
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub source_index: usize,
|
||||
pub duration_seconds: f32,
|
||||
#[serde(default)]
|
||||
pub target_skeleton_signature: Option<AnimationSkeletonSignature>,
|
||||
#[serde(default)]
|
||||
pub events: Vec<AnimationEventDesc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum AnimationDiagnosticSeverity {
|
||||
Info,
|
||||
Warning,
|
||||
Error,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AnimationImportDiagnostic {
|
||||
pub severity: AnimationDiagnosticSeverity,
|
||||
pub code: String,
|
||||
pub message: String,
|
||||
pub repair: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn controller_defaults_are_single_layer_and_non_destructive() {
|
||||
let controller = AnimationControllerDesc::default();
|
||||
assert!(controller.skeleton.is_none());
|
||||
assert!(controller.states.is_empty());
|
||||
assert!(controller.default_state.is_empty());
|
||||
assert_eq!(controller.default_crossfade_seconds, 0.2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authored_controller_round_trips_stable_refs_and_playback_settings() {
|
||||
let controller = AnimationControllerDesc {
|
||||
skeleton: Some(EditorAssetRef::new(
|
||||
"model-id",
|
||||
animation_skeleton_sub_asset_id(0, "Rig"),
|
||||
"Rig",
|
||||
)),
|
||||
states: vec![AnimationStateDesc {
|
||||
id: "locomotion.idle".into(),
|
||||
label: "Idle".into(),
|
||||
clip: EditorAssetRef::new(
|
||||
"model-id",
|
||||
animation_clip_sub_asset_id(2, "Idle"),
|
||||
"Idle",
|
||||
),
|
||||
looping: true,
|
||||
speed: 0.75,
|
||||
range: AnimationPlaybackRange {
|
||||
start_seconds: 0.1,
|
||||
end_seconds: Some(1.2),
|
||||
},
|
||||
}],
|
||||
default_state: "locomotion.idle".into(),
|
||||
default_crossfade_seconds: 0.15,
|
||||
};
|
||||
|
||||
let encoded = ron::to_string(&controller).unwrap();
|
||||
let decoded: AnimationControllerDesc = ron::from_str(&encoded).unwrap();
|
||||
assert_eq!(decoded, controller);
|
||||
assert_eq!(decoded.state("locomotion.idle"), decoded.states.first());
|
||||
assert!(decoded.state("missing").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subasset_ids_encode_source_indices_deterministically() {
|
||||
let clip = animation_clip_sub_asset_id(7, "Idle Loop");
|
||||
let skeleton = animation_skeleton_sub_asset_id(3, "Hero Rig");
|
||||
assert_eq!(clip, "animation:clip:7:idle_loop");
|
||||
assert_eq!(skeleton, "animation:skeleton:3:hero_rig");
|
||||
assert_eq!(animation_clip_source_index(&clip), Some(7));
|
||||
assert_eq!(animation_skeleton_source_index(&skeleton), Some(3));
|
||||
assert_eq!(animation_clip_source_index(&skeleton), None);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,41 @@ impl ActorId {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable scene-document identity and its authored subscene references.
|
||||
///
|
||||
/// This is persisted as a reflected scene resource. Cross-scene ownership never
|
||||
/// depends on runtime [`Entity`] identifiers.
|
||||
#[derive(Resource, Reflect, Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Resource, Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SceneComposition {
|
||||
pub scene_id: String,
|
||||
#[serde(default)]
|
||||
pub subscenes: Vec<SubsceneReference>,
|
||||
}
|
||||
|
||||
/// One stable, project-relative reference in a [`SceneComposition`].
|
||||
#[derive(Reflect, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SubsceneReference {
|
||||
pub id: String,
|
||||
pub path: String,
|
||||
#[serde(default = "default_true")]
|
||||
pub visible: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub locked: bool,
|
||||
}
|
||||
|
||||
impl Default for SubsceneReference {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: String::new(),
|
||||
path: String::new(),
|
||||
visible: true,
|
||||
locked: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// User-facing actor display name, separate from Bevy's runtime [`Name`].
|
||||
#[derive(Component, Reflect, Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -162,6 +197,11 @@ pub const COMPONENT_OBJECTIVE_MARKER: &str = "shared::components::ObjectiveMarke
|
||||
pub const COMPONENT_PREFAB_INSTANCE: &str = "shared::components::PrefabInstance";
|
||||
pub const COMPONENT_POST_PROCESS_VOLUME: &str = "shared::components::PostProcessVolumeDesc";
|
||||
pub const COMPONENT_PROJECT_SUN: &str = "shared::components::ProjectSun";
|
||||
pub const COMPONENT_AUDIO_SOURCE_DESC: &str = "shared::components::AudioSourceDesc";
|
||||
pub const COMPONENT_AUDIO_LISTENER_DESC: &str = "shared::components::AudioListenerDesc";
|
||||
|
||||
/// Stable imported sub-asset identifier used by authored audio clip references.
|
||||
pub const AUDIO_CLIP_SUB_ASSET_ID: &str = "audio:source";
|
||||
|
||||
/// Reference to an imported content-browser asset or sub-asset.
|
||||
#[derive(Reflect, Default, Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -205,6 +245,135 @@ impl EditorAssetRef {
|
||||
}
|
||||
}
|
||||
|
||||
/// Distance curve used by an authored spatial audio source.
|
||||
#[derive(Reflect, Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum AudioRolloff {
|
||||
Linear,
|
||||
#[default]
|
||||
Inverse,
|
||||
Exponential,
|
||||
}
|
||||
|
||||
/// Serializable distance attenuation parameters for spatial audio playback.
|
||||
#[derive(Reflect, Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AudioAttenuationDesc {
|
||||
/// Radius in meters inside which the source plays at full gain.
|
||||
#[serde(default = "default_audio_min_distance")]
|
||||
pub min_distance: f32,
|
||||
/// Radius in meters at which distance attenuation reaches silence.
|
||||
#[serde(default = "default_audio_max_distance")]
|
||||
pub max_distance: f32,
|
||||
#[serde(default)]
|
||||
pub rolloff: AudioRolloff,
|
||||
/// Curve strength. `1.0` is the neutral authored value.
|
||||
#[serde(default = "default_audio_rolloff_factor")]
|
||||
pub rolloff_factor: f32,
|
||||
}
|
||||
|
||||
impl Default for AudioAttenuationDesc {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
min_distance: default_audio_min_distance(),
|
||||
max_distance: default_audio_max_distance(),
|
||||
rolloff: AudioRolloff::default(),
|
||||
rolloff_factor: default_audio_rolloff_factor(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_audio_min_distance() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
fn default_audio_max_distance() -> f32 {
|
||||
25.0
|
||||
}
|
||||
|
||||
fn default_audio_rolloff_factor() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
fn default_audio_pitch() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
fn default_audio_spatial_blend() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
fn default_audio_bus() -> String {
|
||||
settings::AUDIO_BUS_SFX_ID.to_string()
|
||||
}
|
||||
|
||||
fn default_audio_ear_gap() -> f32 {
|
||||
0.2
|
||||
}
|
||||
|
||||
/// Scene-authored audio source. Runtime playback components are derived from this descriptor.
|
||||
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AudioSourceDesc {
|
||||
#[serde(default)]
|
||||
pub clip: Option<EditorAssetRef>,
|
||||
/// Source gain in decibels before bus gain is applied.
|
||||
#[serde(default)]
|
||||
pub gain_db: f32,
|
||||
#[serde(default = "default_audio_pitch")]
|
||||
pub pitch: f32,
|
||||
#[serde(default)]
|
||||
pub looping: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub autoplay: bool,
|
||||
/// Continuous authored blend where `0.0` is 2D and `1.0` is fully spatial.
|
||||
#[serde(default = "default_audio_spatial_blend")]
|
||||
pub spatial_blend: f32,
|
||||
#[serde(default)]
|
||||
pub attenuation: AudioAttenuationDesc,
|
||||
/// Stable project audio bus ID.
|
||||
#[serde(default = "default_audio_bus")]
|
||||
pub bus: String,
|
||||
}
|
||||
|
||||
impl Default for AudioSourceDesc {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
clip: None,
|
||||
gain_db: 0.0,
|
||||
pitch: default_audio_pitch(),
|
||||
looping: false,
|
||||
autoplay: true,
|
||||
spatial_blend: default_audio_spatial_blend(),
|
||||
attenuation: AudioAttenuationDesc::default(),
|
||||
bus: default_audio_bus(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Scene-authored spatial listener. Runtime selection resolves enabled listeners by priority.
|
||||
#[derive(Component, Reflect, Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AudioListenerDesc {
|
||||
#[serde(default = "default_true")]
|
||||
pub enabled: bool,
|
||||
#[serde(default)]
|
||||
pub priority: i32,
|
||||
/// Distance in meters between the listener's virtual ears.
|
||||
#[serde(default = "default_audio_ear_gap")]
|
||||
pub ear_gap: f32,
|
||||
}
|
||||
|
||||
impl Default for AudioListenerDesc {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
priority: 0,
|
||||
ear_gap: default_audio_ear_gap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Marker for entities that belong to editable/savable level data.
|
||||
#[derive(Component, Reflect, Default, Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
#[reflect(Component, Default, Debug, Serialize, Deserialize)]
|
||||
@@ -769,6 +938,9 @@ impl Default for MaterialDesc {
|
||||
#[derive(Component, Reflect, Default, Debug, Clone, Serialize, Deserialize)]
|
||||
#[reflect(Component, Default, Debug, Serialize, Deserialize)]
|
||||
pub struct ModelRef {
|
||||
/// Stable asset-registry UUID. Empty only for legacy or unresolved references.
|
||||
#[serde(default)]
|
||||
pub asset_id: String,
|
||||
/// Asset path relative to `assets/`, e.g. `models/foo.glb` or `models/foo.fbx`.
|
||||
pub path: String,
|
||||
/// Scene index within the model file (`#SceneN` for FBX; glTF scene index otherwise).
|
||||
@@ -778,11 +950,17 @@ pub struct ModelRef {
|
||||
impl ModelRef {
|
||||
pub fn new(path: impl Into<String>) -> Self {
|
||||
Self {
|
||||
asset_id: String::new(),
|
||||
path: path.into(),
|
||||
scene_index: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_asset_id(mut self, asset_id: impl Into<String>) -> Self {
|
||||
self.asset_id = asset_id.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Asset-server path for FBX `#SceneN` labels (see `bevy_ufbx`).
|
||||
pub fn fbx_scene_asset_path(path: &str, scene_index: usize) -> String {
|
||||
format!("{path}#Scene{scene_index}")
|
||||
@@ -791,7 +969,7 @@ impl ModelRef {
|
||||
|
||||
/// Reflectable reference to a saved `.scn.ron` dynamic scene under `assets/`.
|
||||
/// Hydration turns this into a `DynamicWorldRoot`.
|
||||
#[derive(Component, Reflect, Default, Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Component, Reflect, Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Component, Default, Debug, Serialize, Deserialize)]
|
||||
pub struct PrefabRef {
|
||||
/// Asset path relative to `assets/`, e.g. "prefabs/foo.scn.ron".
|
||||
@@ -805,7 +983,7 @@ impl PrefabRef {
|
||||
}
|
||||
|
||||
/// Marks a placed prefab instance with stable registry identity.
|
||||
#[derive(Component, Reflect, Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[derive(Component, Reflect, Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Component, Default, Debug, Serialize, Deserialize)]
|
||||
pub struct PrefabInstance {
|
||||
/// Stable asset registry UUID string.
|
||||
@@ -950,7 +1128,7 @@ pub struct ObjectiveMarker {
|
||||
pub struct HierarchySiblingIndex(pub i32);
|
||||
|
||||
/// Authoring visibility saved with the scene; hydration maps this to ECS [`Visibility`].
|
||||
#[derive(Component, Reflect, Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
#[derive(Component, Reflect, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Component, Default, Debug, Serialize, Deserialize)]
|
||||
pub struct EditorVisibility {
|
||||
pub visible: bool,
|
||||
@@ -978,6 +1156,8 @@ pub enum ActorKind {
|
||||
PostProcessVolume,
|
||||
TeamSpawn,
|
||||
Objective,
|
||||
AudioSource,
|
||||
AudioListener,
|
||||
}
|
||||
|
||||
/// Inspector upper bound for point/spot [`LightDesc::intensity`] (lumens).
|
||||
@@ -1251,7 +1431,10 @@ impl Default for PhysicsBody {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ModelRef;
|
||||
use super::{
|
||||
AudioListenerDesc, AudioRolloff, AudioSourceDesc, EditorAssetRef, ModelRef,
|
||||
AUDIO_CLIP_SUB_ASSET_ID,
|
||||
};
|
||||
use bevy::light::light_consts;
|
||||
|
||||
#[test]
|
||||
@@ -1275,4 +1458,41 @@ mod tests {
|
||||
"models/foo.fbx#Scene2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_model_ref_without_asset_id_remains_readable() {
|
||||
let model: ModelRef = ron::from_str(
|
||||
r#"(
|
||||
path: "assets/models/legacy.glb",
|
||||
scene_index: 2,
|
||||
)"#,
|
||||
)
|
||||
.expect("legacy ModelRef should deserialize");
|
||||
|
||||
assert!(model.asset_id.is_empty());
|
||||
assert_eq!(model.path, "assets/models/legacy.glb");
|
||||
assert_eq!(model.scene_index, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_authoring_descriptors_round_trip() {
|
||||
let source = AudioSourceDesc {
|
||||
clip: Some(
|
||||
EditorAssetRef::new("clip-id", AUDIO_CLIP_SUB_ASSET_ID, "Alarm")
|
||||
.with_source_path("assets/audio/alarm.ogg"),
|
||||
),
|
||||
gain_db: -3.0,
|
||||
pitch: 0.9,
|
||||
looping: true,
|
||||
..Default::default()
|
||||
};
|
||||
let serialized = ron::to_string(&(source.clone(), AudioListenerDesc::default())).unwrap();
|
||||
let (parsed_source, parsed_listener): (AudioSourceDesc, AudioListenerDesc) =
|
||||
ron::from_str(&serialized).unwrap();
|
||||
|
||||
assert_eq!(parsed_source, source);
|
||||
assert_eq!(parsed_listener, AudioListenerDesc::default());
|
||||
assert_eq!(parsed_source.attenuation.rolloff, AudioRolloff::Inverse);
|
||||
assert_eq!(parsed_source.bus, settings::AUDIO_BUS_SFX_ID);
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,10 @@ use lights::{hydrate_lights, reconcile_missing_runtime_lights};
|
||||
use materials::hydrate_materials;
|
||||
pub use materials::material_from_desc;
|
||||
use models::hydrate_models;
|
||||
pub use models::HydratedModelRoot;
|
||||
use physics::hydrate_physics;
|
||||
use prefabs::hydrate_prefabs;
|
||||
use prefabs::{hydrate_prefabs, tag_hydrated_prefab_members};
|
||||
pub use prefabs::{HydratedPrefabMember, HydratedPrefabReady, PrefabHydrationBlocked};
|
||||
use primitives::{hydrate_primitives, primitive_mesh};
|
||||
use static_meshes::{
|
||||
hydrate_static_mesh_renderers, spawn_static_mesh_parts, HydratedStaticMeshPart,
|
||||
@@ -47,6 +49,8 @@ pub struct HydrationPlugin;
|
||||
impl Plugin for HydrationPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<StaticMeshArtifactCache>()
|
||||
.add_observer(tag_hydrated_prefab_members)
|
||||
.add_observer(crate::prefab_overrides::apply_prefab_overrides_on_ready)
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
|
||||
@@ -6,7 +6,13 @@ use bevy::prelude::*;
|
||||
|
||||
use crate::{asset_server_path, LevelObject, ModelRef};
|
||||
|
||||
use super::strip::despawn_generated_children;
|
||||
use super::static_meshes::static_mesh_source_path;
|
||||
|
||||
/// Runtime root generated for one authored [`ModelRef`].
|
||||
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct HydratedModelRoot {
|
||||
pub owner: Entity,
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub fn hydrate_models(
|
||||
@@ -16,21 +22,194 @@ pub fn hydrate_models(
|
||||
(Entity, &ModelRef),
|
||||
(With<LevelObject>, Or<(Added<ModelRef>, Changed<ModelRef>)>),
|
||||
>,
|
||||
children: Query<&Children>,
|
||||
generated_roots: Query<(Entity, &HydratedModelRoot)>,
|
||||
) {
|
||||
for (entity, model) in &models {
|
||||
if let Ok(child_list) = children.get(entity) {
|
||||
despawn_generated_children(&mut commands, entity, child_list);
|
||||
for (root, generated) in &generated_roots {
|
||||
if generated.owner == entity {
|
||||
commands.entity(root).despawn();
|
||||
}
|
||||
}
|
||||
|
||||
// Remove roots created by the legacy hydration path without touching authored children.
|
||||
commands.entity(entity).remove::<WorldAssetRoot>();
|
||||
|
||||
let path = asset_server_path(&model.path);
|
||||
let resolved_path = if model.asset_id.trim().is_empty() {
|
||||
model.path.clone()
|
||||
} else {
|
||||
match static_mesh_source_path(&model.asset_id) {
|
||||
Ok(path) => path,
|
||||
Err(error) => {
|
||||
warn!(
|
||||
"ModelRef {} could not resolve stable asset {}: {error}; falling back to cached path {}",
|
||||
entity,
|
||||
model.asset_id,
|
||||
model.path
|
||||
);
|
||||
model.path.clone()
|
||||
}
|
||||
}
|
||||
};
|
||||
let path = asset_server_path(&resolved_path);
|
||||
let handle = if path.ends_with(".fbx") {
|
||||
asset_server.load(ModelRef::fbx_scene_asset_path(&path, model.scene_index))
|
||||
} else {
|
||||
asset_server.load(GltfAssetLabel::Scene(model.scene_index).from_asset(path))
|
||||
};
|
||||
commands.entity(entity).insert(WorldAssetRoot(handle));
|
||||
commands.spawn((
|
||||
Name::new("Hydrated Imported Model Root"),
|
||||
HydratedModelRoot { owner: entity },
|
||||
WorldAssetRoot(handle),
|
||||
ChildOf(entity),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bevy::asset::{AssetApp, AssetPlugin};
|
||||
use bevy::prelude::WorldAsset;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
struct TestManifest(PathBuf);
|
||||
|
||||
impl Drop for TestManifest {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_test_manifest(asset_id: &str, source_path: &str) -> TestManifest {
|
||||
let path = PathBuf::from(super::super::static_meshes::static_mesh_manifest_path(
|
||||
asset_id,
|
||||
));
|
||||
std::fs::create_dir_all(path.parent().expect("manifest has a parent directory"))
|
||||
.expect("generated static mesh directory should be writable");
|
||||
std::fs::write(
|
||||
&path,
|
||||
format!(
|
||||
r#"(
|
||||
source: (path: "{source_path}"),
|
||||
parts: [],
|
||||
)"#
|
||||
),
|
||||
)
|
||||
.expect("test static mesh manifest should be writable");
|
||||
TestManifest(path)
|
||||
}
|
||||
|
||||
fn hydration_app() -> App {
|
||||
let mut app = App::new();
|
||||
app.add_plugins((MinimalPlugins, AssetPlugin::default()))
|
||||
.init_asset::<WorldAsset>()
|
||||
.add_systems(Update, hydrate_models);
|
||||
app
|
||||
}
|
||||
|
||||
fn generated_roots(world: &mut World, owner: Entity) -> Vec<Entity> {
|
||||
world
|
||||
.query::<(Entity, &HydratedModelRoot)>()
|
||||
.iter(world)
|
||||
.filter_map(|(entity, generated)| (generated.owner == owner).then_some(entity))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hydration_preserves_arbitrary_authored_children() {
|
||||
let mut app = hydration_app();
|
||||
let owner = app
|
||||
.world_mut()
|
||||
.spawn((LevelObject, ModelRef::new("assets/models/first.glb")))
|
||||
.id();
|
||||
let authored_child = app
|
||||
.world_mut()
|
||||
.spawn((Name::new("Authored Child"), ChildOf(owner)))
|
||||
.id();
|
||||
|
||||
app.update();
|
||||
|
||||
assert!(app.world().get_entity(authored_child).is_ok());
|
||||
assert_eq!(
|
||||
app.world().get::<ChildOf>(authored_child).unwrap().parent(),
|
||||
owner
|
||||
);
|
||||
assert_eq!(generated_roots(app.world_mut(), owner).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_ref_change_replaces_only_the_generated_root() {
|
||||
let mut app = hydration_app();
|
||||
let owner = app
|
||||
.world_mut()
|
||||
.spawn((LevelObject, ModelRef::new("assets/models/first.glb")))
|
||||
.id();
|
||||
let authored_child = app
|
||||
.world_mut()
|
||||
.spawn((Name::new("Authored Child"), ChildOf(owner)))
|
||||
.id();
|
||||
|
||||
app.update();
|
||||
let first_root = generated_roots(app.world_mut(), owner)
|
||||
.into_iter()
|
||||
.next()
|
||||
.unwrap();
|
||||
|
||||
app.world_mut().get_mut::<ModelRef>(owner).unwrap().path =
|
||||
"assets/models/second.glb".into();
|
||||
app.update();
|
||||
|
||||
let roots = generated_roots(app.world_mut(), owner);
|
||||
assert_eq!(roots.len(), 1);
|
||||
assert_ne!(roots[0], first_root);
|
||||
assert!(app.world().get_entity(first_root).is_err());
|
||||
assert!(app.world().get_entity(authored_child).is_ok());
|
||||
assert_eq!(
|
||||
app.world().get::<ChildOf>(authored_child).unwrap().parent(),
|
||||
owner
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_asset_id_resolves_relocated_model_source_from_manifest() {
|
||||
const ASSET_ID: &str = "34b80e75-f00c-4ead-91cb-54bd9b66ad55";
|
||||
const CACHED_PATH: &str = "assets/models/stale_cached_path.glb";
|
||||
const MANIFEST_PATH: &str = "assets/models/relocated/source.glb";
|
||||
let _manifest = write_test_manifest(ASSET_ID, MANIFEST_PATH);
|
||||
let mut app = hydration_app();
|
||||
let owner = app
|
||||
.world_mut()
|
||||
.spawn((
|
||||
LevelObject,
|
||||
ModelRef {
|
||||
asset_id: ASSET_ID.into(),
|
||||
path: CACHED_PATH.into(),
|
||||
scene_index: 3,
|
||||
},
|
||||
))
|
||||
.id();
|
||||
|
||||
app.update();
|
||||
|
||||
let root_entity = generated_roots(app.world_mut(), owner)
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("stable model reference should create a hydrated root");
|
||||
let root = app
|
||||
.world()
|
||||
.get::<WorldAssetRoot>(root_entity)
|
||||
.expect("generated root should retain its world asset handle");
|
||||
let loaded_path = app
|
||||
.world()
|
||||
.resource::<AssetServer>()
|
||||
.get_path(root.0.id())
|
||||
.expect("world asset handle should retain its resolved source path");
|
||||
|
||||
assert_eq!(loaded_path.path(), Path::new("models/relocated/source.glb"));
|
||||
assert_eq!(loaded_path.label(), Some("Scene3"));
|
||||
assert_ne!(
|
||||
loaded_path.path(),
|
||||
Path::new("models/stale_cached_path.glb")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,28 @@
|
||||
|
||||
use bevy::prelude::DynamicWorldRoot;
|
||||
use bevy::prelude::*;
|
||||
use bevy::world_serialization::{WorldInstanceReady, WorldInstanceSpawner};
|
||||
|
||||
use crate::{LevelObject, PrefabInstance, PrefabRef};
|
||||
|
||||
use crate::asset_server_path;
|
||||
|
||||
/// Runtime ownership for entities spawned from a linked prefab source.
|
||||
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct HydratedPrefabMember {
|
||||
pub instance_root: Entity,
|
||||
}
|
||||
|
||||
/// Runtime marker that the linked prefab instance finished spawning.
|
||||
#[derive(Component, Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct HydratedPrefabReady;
|
||||
|
||||
/// Runtime-only guard used by editor recovery when a prefab source is invalid.
|
||||
#[derive(Component, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PrefabHydrationBlocked {
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub fn hydrate_prefabs(
|
||||
mut commands: Commands,
|
||||
@@ -23,21 +40,89 @@ pub fn hydrate_prefabs(
|
||||
(Entity, &PrefabInstance),
|
||||
(
|
||||
With<LevelObject>,
|
||||
Without<PrefabHydrationBlocked>,
|
||||
Or<(Added<PrefabInstance>, Changed<PrefabInstance>)>,
|
||||
),
|
||||
>,
|
||||
) {
|
||||
for (entity, prefab) in &prefabs {
|
||||
commands.entity(entity).insert(DynamicWorldRoot(
|
||||
asset_server.load(asset_server_path(&prefab.path)),
|
||||
commands.entity(entity).insert(PrefabInstance::new(
|
||||
format!("legacy:{}", prefab.path),
|
||||
prefab.path.clone(),
|
||||
));
|
||||
}
|
||||
|
||||
for (entity, instance) in &prefab_instances {
|
||||
let path = asset_server_path(&instance.source_path);
|
||||
commands.entity(entity).insert((
|
||||
PrefabRef::new(instance.source_path.clone()),
|
||||
DynamicWorldRoot(asset_server.load(path)),
|
||||
));
|
||||
commands
|
||||
.entity(entity)
|
||||
.remove::<HydratedPrefabReady>()
|
||||
.insert((
|
||||
PrefabRef::new(instance.source_path.clone()),
|
||||
DynamicWorldRoot(asset_server.load(path)),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tag_hydrated_prefab_members(
|
||||
ready: On<WorldInstanceReady>,
|
||||
prefab_roots: Query<(), With<PrefabInstance>>,
|
||||
instance_spawner: Res<WorldInstanceSpawner>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
if prefab_roots.get(ready.entity).is_err() {
|
||||
return;
|
||||
}
|
||||
for member in instance_spawner.iter_instance_entities(ready.instance_id) {
|
||||
commands.entity(member).insert(HydratedPrefabMember {
|
||||
instance_root: ready.entity,
|
||||
});
|
||||
}
|
||||
commands.entity(ready.entity).insert(HydratedPrefabReady);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bevy::asset::AssetPlugin;
|
||||
use bevy::world_serialization::{DynamicWorld, WorldSerializationPlugin};
|
||||
|
||||
#[test]
|
||||
fn spawned_prefab_entities_receive_runtime_ownership() {
|
||||
let mut app = App::new();
|
||||
app.add_plugins((AssetPlugin::default(), WorldSerializationPlugin))
|
||||
.register_type::<crate::LevelObject>()
|
||||
.register_type::<crate::ActorId>()
|
||||
.add_observer(tag_hydrated_prefab_members);
|
||||
|
||||
let mut source = World::new();
|
||||
source.spawn((crate::LevelObject, crate::ActorId::new("child")));
|
||||
let dynamic_world = DynamicWorld::from_world_with(
|
||||
&source,
|
||||
&app.world().resource::<AppTypeRegistry>().read(),
|
||||
);
|
||||
let handle = app
|
||||
.world_mut()
|
||||
.resource_mut::<Assets<DynamicWorld>>()
|
||||
.add(dynamic_world);
|
||||
let root = app
|
||||
.world_mut()
|
||||
.spawn((
|
||||
PrefabInstance::new("prefab", "assets/prefabs/test.scn.ron"),
|
||||
DynamicWorldRoot(handle),
|
||||
))
|
||||
.id();
|
||||
|
||||
app.update();
|
||||
|
||||
let world = app.world_mut();
|
||||
let members: Vec<_> = world
|
||||
.query::<(Entity, &HydratedPrefabMember)>()
|
||||
.iter(world)
|
||||
.map(|(entity, owner)| (entity, owner.instance_root))
|
||||
.collect();
|
||||
assert_eq!(members.len(), 1);
|
||||
assert_eq!(members[0].1, root);
|
||||
assert!(world.get::<HydratedPrefabReady>(root).is_some());
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,9 @@ use serde::Deserialize;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::{
|
||||
asset_server_path, inspector_component_active, ColliderDesc, ColliderShapeDesc, EditorAssetRef,
|
||||
InspectorOrder, LevelObject, MaterialDesc, MaterialOverride, StaticMeshRenderer,
|
||||
StaticMeshRendererEntry, COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC,
|
||||
asset_server_path, inspector_component_active, standard_material_asset_path, ColliderDesc,
|
||||
ColliderShapeDesc, EditorAssetRef, InspectorOrder, LevelObject, MaterialDesc, MaterialOverride,
|
||||
StaticMeshRenderer, StaticMeshRendererEntry, COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC,
|
||||
COMPONENT_STATIC_MESH_RENDERER,
|
||||
};
|
||||
|
||||
@@ -318,7 +318,7 @@ fn material_for_entry(
|
||||
if let Some(material_ref) = entry.material.as_ref() {
|
||||
if let Some(resolved_material) = artifact_cache.resolve_material(material_ref) {
|
||||
let source_path = asset_server_path(&resolved_material.source_path);
|
||||
return asset_server.load(labeled_asset_path(
|
||||
return asset_server.load(standard_material_asset_path(
|
||||
&source_path,
|
||||
&resolved_material.material_label,
|
||||
));
|
||||
@@ -331,7 +331,7 @@ fn material_for_entry(
|
||||
|
||||
if let Some(label) = resolved.material_label.as_deref() {
|
||||
let source_path = asset_server_path(&resolved.source_path);
|
||||
return asset_server.load(labeled_asset_path(&source_path, label));
|
||||
return asset_server.load(standard_material_asset_path(&source_path, label));
|
||||
}
|
||||
|
||||
materials.add(StandardMaterial::default())
|
||||
@@ -361,6 +361,18 @@ pub fn static_mesh_manifest_path(asset_id: &str) -> String {
|
||||
format!("{STATIC_MESH_ARTIFACT_DIR}/{asset_id}.static_mesh.ron")
|
||||
}
|
||||
|
||||
pub(super) fn static_mesh_source_path(asset_id: &str) -> Result<String, String> {
|
||||
let path = static_mesh_manifest_path(asset_id);
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|error| format!("could not read {path}: {error}"))?;
|
||||
let manifest: StaticMeshResolveManifest =
|
||||
ron::from_str(&text).map_err(|error| format!("could not parse {path}: {error}"))?;
|
||||
if manifest.source.path.trim().is_empty() {
|
||||
return Err(format!("static mesh manifest {path} has no source path"));
|
||||
}
|
||||
Ok(manifest.source.path)
|
||||
}
|
||||
|
||||
fn part_id_from_label(label: &str) -> String {
|
||||
format!("mesh:{}", stable_sub_asset_slug(label))
|
||||
}
|
||||
|
||||
@@ -30,11 +30,3 @@ pub fn strip_hydrated(entity_commands: &mut EntityCommands<'_>) {
|
||||
.remove::<RigidBody>()
|
||||
.remove::<Collider>();
|
||||
}
|
||||
|
||||
/// Despawns all child entities (e.g. prior `WorldAssetRoot` instance hierarchy).
|
||||
pub fn despawn_generated_children(commands: &mut Commands, entity: Entity, children: &Children) {
|
||||
for child in children.iter() {
|
||||
commands.entity(child).despawn();
|
||||
}
|
||||
commands.entity(entity).remove::<Children>();
|
||||
}
|
||||
@@ -5,23 +5,32 @@
|
||||
//! from them by hydration systems in both the game and editor.
|
||||
|
||||
mod actor;
|
||||
mod animation;
|
||||
pub mod brush_math;
|
||||
mod components;
|
||||
mod hydration;
|
||||
mod material_asset;
|
||||
mod post_process_effect_asset;
|
||||
mod prefab_overrides;
|
||||
mod rendering_profile_asset;
|
||||
|
||||
pub use actor::{infer_actor_kind, validate_actor, ActorValidationError};
|
||||
pub use animation::*;
|
||||
pub use components::*;
|
||||
pub use hydration::{
|
||||
cascade_config_from_rendering, flush_level_object_hydration, material_from_desc,
|
||||
strip_hydrated, strip_hydrated_entity, HydrationPlugin,
|
||||
strip_hydrated, strip_hydrated_entity, HydratedModelRoot, HydratedPrefabMember,
|
||||
HydratedPrefabReady, HydrationPlugin, PrefabHydrationBlocked,
|
||||
};
|
||||
pub use material_asset::{
|
||||
MaterialAsset, ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset,
|
||||
};
|
||||
pub use post_process_effect_asset::{PostProcessEffectAsset, PostProcessEffectKind};
|
||||
pub use prefab_overrides::{
|
||||
apply_prefab_overrides_on_ready, decode_prefab_overrides, encode_prefab_overrides,
|
||||
PrefabActorPath, PrefabComponentOverride, PrefabOverrides, PrefabPropertyOverride,
|
||||
PrefabStructuralOverride, PREFAB_OVERRIDE_FORMAT_VERSION,
|
||||
};
|
||||
pub use rendering_profile_asset::RenderingProfileAsset;
|
||||
|
||||
/// Converts catalog-style paths (`assets/models/foo.fbx`) to Bevy AssetServer paths.
|
||||
@@ -33,6 +42,23 @@ pub fn asset_server_path(catalog_path: &str) -> String {
|
||||
.unwrap_or(normalized)
|
||||
}
|
||||
|
||||
/// Returns the typed [`StandardMaterial`] asset path for a source material label.
|
||||
///
|
||||
/// Bevy's glTF loader owns `#MaterialN` as a `GltfMaterial`; the PBR extension
|
||||
/// publishes its renderable conversion under the nested `#MaterialN/std` label.
|
||||
/// Other model loaders, including `bevy_ufbx`, expose `StandardMaterial` at the
|
||||
/// original label.
|
||||
pub fn standard_material_asset_path(asset_path: &str, material_label: &str) -> String {
|
||||
let lower_path = asset_path.to_ascii_lowercase();
|
||||
let gltf_source = lower_path.ends_with(".gltf") || lower_path.ends_with(".glb");
|
||||
let label = if gltf_source && !material_label.ends_with("/std") {
|
||||
format!("{material_label}/std")
|
||||
} else {
|
||||
material_label.to_string()
|
||||
};
|
||||
format!("{asset_path}#{label}")
|
||||
}
|
||||
|
||||
use bevy::prelude::*;
|
||||
|
||||
/// Registers all reflectable authoring types and installs hydration systems.
|
||||
@@ -43,11 +69,22 @@ impl Plugin for SharedTypesPlugin {
|
||||
app.register_type::<ActorKind>()
|
||||
.register_type::<ActorId>()
|
||||
.register_type::<ActorName>()
|
||||
.register_type::<SceneComposition>()
|
||||
.register_type::<SubsceneReference>()
|
||||
.register_type::<HierarchySiblingIndex>()
|
||||
.register_type::<InspectorOrder>()
|
||||
.register_type::<InspectorComponentState>()
|
||||
.register_type::<ComponentInstanceId>()
|
||||
.register_type::<EditorAssetRef>()
|
||||
.register_type::<AnimationSkeletonSignature>()
|
||||
.register_type::<AnimationPlaybackRange>()
|
||||
.register_type::<AnimationEventDesc>()
|
||||
.register_type::<AnimationStateDesc>()
|
||||
.register_type::<AnimationControllerDesc>()
|
||||
.register_type::<AudioSourceDesc>()
|
||||
.register_type::<AudioListenerDesc>()
|
||||
.register_type::<AudioAttenuationDesc>()
|
||||
.register_type::<AudioRolloff>()
|
||||
.register_type::<EditorVisibility>()
|
||||
.register_type::<LevelObject>()
|
||||
.register_type::<RaytracingExcluded>()
|
||||
@@ -93,3 +130,36 @@ impl Plugin for SharedTypesPlugin {
|
||||
.add_plugins(HydrationPlugin);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::standard_material_asset_path;
|
||||
|
||||
#[test]
|
||||
fn gltf_standard_material_paths_use_pbr_conversion_label() {
|
||||
assert_eq!(
|
||||
standard_material_asset_path("models/robot.gltf", "Material3"),
|
||||
"models/robot.gltf#Material3/std"
|
||||
);
|
||||
assert_eq!(
|
||||
standard_material_asset_path("models/robot.GLB", "DefaultMaterial"),
|
||||
"models/robot.GLB#DefaultMaterial/std"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_gltf_material_paths_keep_loader_label() {
|
||||
assert_eq!(
|
||||
standard_material_asset_path("models/robot.fbx", "Material3"),
|
||||
"models/robot.fbx#Material3"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_gltf_material_label_is_not_suffixed_twice() {
|
||||
assert_eq!(
|
||||
standard_material_asset_path("models/robot.glb", "Material3/std"),
|
||||
"models/robot.glb#Material3/std"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,705 @@
|
||||
//! Versioned prefab override data and runtime application.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use bevy::ecs::reflect::ReflectComponent;
|
||||
use bevy::prelude::*;
|
||||
use bevy::reflect::serde::TypedReflectDeserializer;
|
||||
use bevy::reflect::{GetPath, ParsedPath, ReflectPath};
|
||||
use bevy::world_serialization::{WorldInstanceReady, WorldInstanceSpawner};
|
||||
use serde::de::DeserializeSeed;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{ActorId, EditorVisibility, HydratedPrefabMember, MaterialDesc, PrefabInstance};
|
||||
|
||||
pub const PREFAB_OVERRIDE_FORMAT_VERSION: u32 = 2;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
pub struct PrefabActorPath {
|
||||
#[serde(default)]
|
||||
pub instance_chain: Vec<String>,
|
||||
pub actor_id: String,
|
||||
}
|
||||
|
||||
impl PrefabActorPath {
|
||||
pub fn direct(actor_id: impl Into<String>) -> Self {
|
||||
Self {
|
||||
instance_chain: Vec::new(),
|
||||
actor_id: actor_id.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn belongs_to_layer(&self, instance_chain: &[String]) -> bool {
|
||||
self.instance_chain == instance_chain
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct PrefabPropertyOverride {
|
||||
pub target: PrefabActorPath,
|
||||
pub component_type: String,
|
||||
/// Bevy reflection path within the component, such as `base_color.r`.
|
||||
pub property_path: String,
|
||||
/// Full component value observed when the override was created.
|
||||
pub base_component_ron: String,
|
||||
/// Full component value containing the overridden property.
|
||||
pub value_component_ron: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct PrefabComponentOverride {
|
||||
pub target: PrefabActorPath,
|
||||
pub component_type: String,
|
||||
/// Source component value, or `None` when this component was locally added.
|
||||
pub base_component_ron: Option<String>,
|
||||
/// Replacement component value, or `None` to remove the source component.
|
||||
pub value_component_ron: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum PrefabStructuralOverride {
|
||||
RemoveChild {
|
||||
target: PrefabActorPath,
|
||||
base_subtree_revision: String,
|
||||
},
|
||||
ReparentChild {
|
||||
target: PrefabActorPath,
|
||||
base_parent: Option<PrefabActorPath>,
|
||||
new_parent: Option<PrefabActorPath>,
|
||||
/// Source transform observed when the structural override was authored.
|
||||
#[serde(default)]
|
||||
base_transform_ron: Option<String>,
|
||||
/// Local transform after reparenting, preserving the authored world-space pose.
|
||||
#[serde(default)]
|
||||
local_transform_ron: Option<String>,
|
||||
},
|
||||
AttachLocalChild {
|
||||
local_actor_id: String,
|
||||
parent: PrefabActorPath,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct PrefabOverrides {
|
||||
#[serde(default = "default_format_version")]
|
||||
pub format_version: u32,
|
||||
#[serde(default)]
|
||||
pub source_revision: Option<String>,
|
||||
/// Legacy anchor override retained for wire compatibility. New authoring does not emit it.
|
||||
#[serde(default)]
|
||||
pub transform: Option<Transform>,
|
||||
/// Legacy anchor override retained for wire compatibility. New authoring does not emit it.
|
||||
#[serde(default)]
|
||||
pub material: Option<MaterialDesc>,
|
||||
/// V1 direct-child visibility overrides, keyed by ActorId.
|
||||
#[serde(default)]
|
||||
pub child_visibility: HashMap<String, bool>,
|
||||
#[serde(default)]
|
||||
pub properties: Vec<PrefabPropertyOverride>,
|
||||
#[serde(default)]
|
||||
pub components: Vec<PrefabComponentOverride>,
|
||||
#[serde(default)]
|
||||
pub structural: Vec<PrefabStructuralOverride>,
|
||||
}
|
||||
|
||||
impl Default for PrefabOverrides {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
format_version: PREFAB_OVERRIDE_FORMAT_VERSION,
|
||||
source_revision: None,
|
||||
transform: None,
|
||||
material: None,
|
||||
child_visibility: HashMap::new(),
|
||||
properties: Vec::new(),
|
||||
components: Vec::new(),
|
||||
structural: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const fn default_format_version() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
pub fn decode_prefab_overrides(instance: &PrefabInstance) -> Result<PrefabOverrides, String> {
|
||||
instance.overrides_ron.as_ref().map_or_else(
|
||||
|| Ok(PrefabOverrides::default()),
|
||||
|text| {
|
||||
let overrides: PrefabOverrides = ron::from_str(text)
|
||||
.map_err(|error| format!("invalid prefab override data: {error}"))?;
|
||||
validate_prefab_overrides_payload(&overrides)?;
|
||||
Ok(overrides)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn validate_prefab_overrides_payload(overrides: &PrefabOverrides) -> Result<(), String> {
|
||||
if !(1..=PREFAB_OVERRIDE_FORMAT_VERSION).contains(&overrides.format_version) {
|
||||
return Err(format!(
|
||||
"unsupported prefab override format version {}",
|
||||
overrides.format_version
|
||||
));
|
||||
}
|
||||
for property in &overrides.properties {
|
||||
ron::from_str::<ron::Value>(&property.base_component_ron).map_err(|error| {
|
||||
format!(
|
||||
"invalid base value for `{}`: {error}",
|
||||
property.component_type
|
||||
)
|
||||
})?;
|
||||
ron::from_str::<ron::Value>(&property.value_component_ron).map_err(|error| {
|
||||
format!(
|
||||
"invalid override value for `{}`: {error}",
|
||||
property.component_type
|
||||
)
|
||||
})?;
|
||||
ParsedPath::parse(&property.property_path).map_err(|error| {
|
||||
format!(
|
||||
"invalid property path `{}`: {error}",
|
||||
property.property_path
|
||||
)
|
||||
})?;
|
||||
}
|
||||
for component in &overrides.components {
|
||||
for value in [
|
||||
component.base_component_ron.as_deref(),
|
||||
component.value_component_ron.as_deref(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
ron::from_str::<ron::Value>(value).map_err(|error| {
|
||||
format!(
|
||||
"invalid component value for `{}`: {error}",
|
||||
component.component_type
|
||||
)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
for structural in &overrides.structural {
|
||||
if let PrefabStructuralOverride::ReparentChild {
|
||||
base_transform_ron,
|
||||
local_transform_ron,
|
||||
..
|
||||
} = structural
|
||||
{
|
||||
for value in [
|
||||
base_transform_ron.as_deref(),
|
||||
local_transform_ron.as_deref(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
ron::from_str::<Transform>(value)
|
||||
.map_err(|error| format!("invalid reparent transform: {error}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn encode_prefab_overrides(overrides: &PrefabOverrides) -> Result<Option<String>, String> {
|
||||
if overrides == &PrefabOverrides::default() {
|
||||
Ok(None)
|
||||
} else {
|
||||
ron::to_string(overrides)
|
||||
.map(Some)
|
||||
.map_err(|error| format!("could not encode prefab overrides: {error}"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_prefab_overrides_on_ready(
|
||||
ready: On<WorldInstanceReady>,
|
||||
roots: Query<&PrefabInstance>,
|
||||
owners: Query<&HydratedPrefabMember>,
|
||||
actor_ids: Query<&ActorId>,
|
||||
instance_spawner: Res<WorldInstanceSpawner>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
let members: HashMap<String, Entity> = instance_spawner
|
||||
.iter_instance_entities(ready.instance_id)
|
||||
.filter_map(|entity| {
|
||||
actor_ids
|
||||
.get(entity)
|
||||
.ok()
|
||||
.map(|actor_id| (actor_id.0.clone(), entity))
|
||||
})
|
||||
.collect();
|
||||
if members.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut current = ready.entity;
|
||||
let mut instance_chain = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
while seen.insert(current) {
|
||||
if let Ok(instance) = roots.get(current) {
|
||||
match decode_prefab_overrides(instance) {
|
||||
Ok(overrides) => {
|
||||
let members = members.clone();
|
||||
let chain = instance_chain.clone();
|
||||
let owner_root = current;
|
||||
commands.queue(move |world: &mut World| {
|
||||
if let Err(error) =
|
||||
apply_override_layer(world, owner_root, &chain, &members, &overrides)
|
||||
{
|
||||
warn!("Could not apply prefab overrides: {error}");
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(error) => warn!("Skipping malformed prefab overrides: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
let Ok(owner) = owners.get(current) else {
|
||||
break;
|
||||
};
|
||||
let Ok(actor_id) = actor_ids.get(current) else {
|
||||
break;
|
||||
};
|
||||
instance_chain.insert(0, actor_id.0.clone());
|
||||
current = owner.instance_root;
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_override_layer(
|
||||
world: &mut World,
|
||||
owner_root: Entity,
|
||||
instance_chain: &[String],
|
||||
members: &HashMap<String, Entity>,
|
||||
overrides: &PrefabOverrides,
|
||||
) -> Result<(), String> {
|
||||
let mut errors = Vec::new();
|
||||
if instance_chain.is_empty() {
|
||||
for (actor_id, visible) in &overrides.child_visibility {
|
||||
if let Some(entity) = members.get(actor_id).copied() {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.insert(EditorVisibility { visible: *visible });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for structural in &overrides.structural {
|
||||
if !matches!(structural, PrefabStructuralOverride::ReparentChild { .. }) {
|
||||
continue;
|
||||
}
|
||||
if let Err(error) =
|
||||
apply_structural_override(world, owner_root, instance_chain, members, structural)
|
||||
{
|
||||
errors.push(error);
|
||||
}
|
||||
}
|
||||
|
||||
for component in &overrides.components {
|
||||
if !component.target.belongs_to_layer(instance_chain) {
|
||||
continue;
|
||||
}
|
||||
let Some(entity) = members.get(&component.target.actor_id).copied() else {
|
||||
continue;
|
||||
};
|
||||
if let Err(error) = apply_component_override(world, entity, component) {
|
||||
errors.push(error);
|
||||
}
|
||||
}
|
||||
for property in &overrides.properties {
|
||||
if !property.target.belongs_to_layer(instance_chain) {
|
||||
continue;
|
||||
}
|
||||
let Some(entity) = members.get(&property.target.actor_id).copied() else {
|
||||
continue;
|
||||
};
|
||||
if let Err(error) = apply_property_override(world, entity, property) {
|
||||
errors.push(error);
|
||||
}
|
||||
}
|
||||
for structural in &overrides.structural {
|
||||
if matches!(structural, PrefabStructuralOverride::ReparentChild { .. }) {
|
||||
continue;
|
||||
}
|
||||
if let Err(error) =
|
||||
apply_structural_override(world, owner_root, instance_chain, members, structural)
|
||||
{
|
||||
errors.push(error);
|
||||
}
|
||||
}
|
||||
if errors.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(errors.join("; "))
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_component_override(
|
||||
world: &mut World,
|
||||
entity: Entity,
|
||||
component: &PrefabComponentOverride,
|
||||
) -> Result<(), String> {
|
||||
if world.get_entity(entity).is_err() {
|
||||
return Err(format!(
|
||||
"component override target {:?} no longer exists",
|
||||
entity
|
||||
));
|
||||
}
|
||||
world.resource_scope(|world, registry: Mut<AppTypeRegistry>| {
|
||||
let registry = registry.read();
|
||||
let registration = registry
|
||||
.get_with_type_path(&component.component_type)
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"component type `{}` is not registered",
|
||||
component.component_type
|
||||
)
|
||||
})?;
|
||||
let reflect_component = registration
|
||||
.data::<ReflectComponent>()
|
||||
.cloned()
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"component `{}` is not reflectable",
|
||||
component.component_type
|
||||
)
|
||||
})?;
|
||||
match component.value_component_ron.as_deref() {
|
||||
Some(value) => {
|
||||
let reflected = deserialize_component(value, registration, ®istry)?;
|
||||
let exists = reflect_component.reflect(world.entity(entity)).is_some();
|
||||
if exists {
|
||||
reflect_component.apply(world.entity_mut(entity), reflected.as_ref());
|
||||
} else {
|
||||
reflect_component.insert(
|
||||
&mut world.entity_mut(entity),
|
||||
reflected.as_ref(),
|
||||
®istry,
|
||||
);
|
||||
}
|
||||
}
|
||||
None => reflect_component.remove(&mut world.entity_mut(entity)),
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn apply_property_override(
|
||||
world: &mut World,
|
||||
entity: Entity,
|
||||
property: &PrefabPropertyOverride,
|
||||
) -> Result<(), String> {
|
||||
if world.get_entity(entity).is_err() {
|
||||
return Err(format!(
|
||||
"property override target {:?} no longer exists",
|
||||
entity
|
||||
));
|
||||
}
|
||||
world.resource_scope(|world, registry: Mut<AppTypeRegistry>| {
|
||||
let registry = registry.read();
|
||||
let registration = registry
|
||||
.get_with_type_path(&property.component_type)
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"component type `{}` is not registered",
|
||||
property.component_type
|
||||
)
|
||||
})?;
|
||||
let reflect_component = registration
|
||||
.data::<ReflectComponent>()
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("component `{}` is not reflectable", property.component_type))?;
|
||||
let reflected =
|
||||
deserialize_component(&property.value_component_ron, registration, ®istry)?;
|
||||
let path = ParsedPath::parse(&property.property_path).map_err(|error| {
|
||||
format!(
|
||||
"invalid property path `{}`: {error}",
|
||||
property.property_path
|
||||
)
|
||||
})?;
|
||||
let source_value = path.reflect_element(reflected.as_ref()).map_err(|error| {
|
||||
format!(
|
||||
"override value path `{}` failed: {error}",
|
||||
property.property_path
|
||||
)
|
||||
})?;
|
||||
let mut target_component = reflect_component
|
||||
.reflect_mut(world.entity_mut(entity))
|
||||
.ok_or_else(|| format!("target is missing component `{}`", property.component_type))?;
|
||||
let target_value = target_component.reflect_path_mut(&path).map_err(|error| {
|
||||
format!(
|
||||
"target property path `{}` failed: {error}",
|
||||
property.property_path
|
||||
)
|
||||
})?;
|
||||
target_value
|
||||
.try_apply(source_value)
|
||||
.map_err(|error| format!("could not apply `{}`: {error}", property.property_path))
|
||||
})
|
||||
}
|
||||
|
||||
fn deserialize_component(
|
||||
text: &str,
|
||||
registration: &bevy::reflect::TypeRegistration,
|
||||
registry: &bevy::reflect::TypeRegistry,
|
||||
) -> Result<Box<dyn PartialReflect>, String> {
|
||||
let mut deserializer =
|
||||
ron::de::Deserializer::from_str(text).map_err(|error| error.to_string())?;
|
||||
TypedReflectDeserializer::new(registration, registry)
|
||||
.deserialize(&mut deserializer)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn apply_structural_override(
|
||||
world: &mut World,
|
||||
owner_root: Entity,
|
||||
instance_chain: &[String],
|
||||
members: &HashMap<String, Entity>,
|
||||
structural: &PrefabStructuralOverride,
|
||||
) -> Result<(), String> {
|
||||
match structural {
|
||||
PrefabStructuralOverride::RemoveChild { target, .. }
|
||||
if target.belongs_to_layer(instance_chain) =>
|
||||
{
|
||||
if let Some(entity) = members.get(&target.actor_id).copied() {
|
||||
if let Ok(entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.despawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
PrefabStructuralOverride::ReparentChild {
|
||||
target,
|
||||
new_parent,
|
||||
local_transform_ron,
|
||||
..
|
||||
} if target.belongs_to_layer(instance_chain) => {
|
||||
let Some(entity) = members.get(&target.actor_id).copied() else {
|
||||
return Ok(());
|
||||
};
|
||||
let parent = match new_parent {
|
||||
Some(parent) if !parent.belongs_to_layer(instance_chain) => {
|
||||
return Err(format!(
|
||||
"reparent target `{}` crosses a prefab layer",
|
||||
parent.actor_id
|
||||
));
|
||||
}
|
||||
Some(parent) => members
|
||||
.get(&parent.actor_id)
|
||||
.copied()
|
||||
.ok_or_else(|| format!("reparent target `{}` is missing", parent.actor_id))?,
|
||||
None => owner_root,
|
||||
};
|
||||
if world.get_entity(parent).is_err() {
|
||||
return Err(format!(
|
||||
"reparent target for `{}` no longer exists",
|
||||
target.actor_id
|
||||
));
|
||||
}
|
||||
if hierarchy_would_cycle(world, entity, parent) {
|
||||
return Err(format!(
|
||||
"reparent override for `{}` would create a hierarchy cycle",
|
||||
target.actor_id
|
||||
));
|
||||
}
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.insert(ChildOf(parent));
|
||||
if let Some(transform) = local_transform_ron
|
||||
.as_deref()
|
||||
.and_then(|ron| ron::from_str::<Transform>(ron).ok())
|
||||
{
|
||||
entity_mut.insert(transform);
|
||||
}
|
||||
}
|
||||
}
|
||||
PrefabStructuralOverride::AttachLocalChild {
|
||||
local_actor_id,
|
||||
parent,
|
||||
} if parent.belongs_to_layer(instance_chain) => {
|
||||
let Some(parent_entity) = members.get(&parent.actor_id).copied() else {
|
||||
return Ok(());
|
||||
};
|
||||
let local = world
|
||||
.query::<(Entity, &ActorId, Option<&HydratedPrefabMember>)>()
|
||||
.iter(world)
|
||||
.find_map(|(entity, actor_id, hydrated)| {
|
||||
(hydrated.is_none() && actor_id.0 == *local_actor_id && entity != owner_root)
|
||||
.then_some(entity)
|
||||
});
|
||||
if let Some(local) = local {
|
||||
world.entity_mut(local).insert(ChildOf(parent_entity));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn hierarchy_would_cycle(world: &World, entity: Entity, parent: Entity) -> bool {
|
||||
let mut current = Some(parent);
|
||||
let mut seen = HashSet::new();
|
||||
while let Some(candidate) = current {
|
||||
if candidate == entity || !seen.insert(candidate) {
|
||||
return true;
|
||||
}
|
||||
current = world.get::<ChildOf>(candidate).map(ChildOf::parent);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bevy::asset::AssetPlugin;
|
||||
use bevy::world_serialization::{DynamicWorld, DynamicWorldRoot, WorldSerializationPlugin};
|
||||
|
||||
#[test]
|
||||
fn legacy_override_payload_decodes_with_v1_version() {
|
||||
let instance = PrefabInstance {
|
||||
overrides_ron: Some("(child_visibility:{\"child\":false})".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
let overrides = decode_prefab_overrides(&instance).unwrap();
|
||||
assert_eq!(overrides.format_version, 1);
|
||||
assert_eq!(overrides.child_visibility.get("child"), Some(&false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_actor_paths_are_distinct() {
|
||||
let first = PrefabActorPath {
|
||||
instance_chain: vec!["left".to_string()],
|
||||
actor_id: "mesh".to_string(),
|
||||
};
|
||||
let second = PrefabActorPath {
|
||||
instance_chain: vec!["right".to_string()],
|
||||
actor_id: "mesh".to_string(),
|
||||
};
|
||||
assert_ne!(first, second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_inner_override_payload_is_rejected_during_decode() {
|
||||
let mut instance = PrefabInstance::new("prefab", "assets/prefabs/test.scn.ron");
|
||||
instance.overrides_ron = Some(
|
||||
ron::to_string(&PrefabOverrides {
|
||||
properties: vec![PrefabPropertyOverride {
|
||||
target: PrefabActorPath::direct("mesh"),
|
||||
component_type: std::any::type_name::<MaterialDesc>().to_string(),
|
||||
property_path: "roughness".to_string(),
|
||||
base_component_ron: "not ron".to_string(),
|
||||
value_component_ron: ron::to_string(&MaterialDesc::default()).unwrap(),
|
||||
}],
|
||||
..default()
|
||||
})
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let error = decode_prefab_overrides(&instance).unwrap_err();
|
||||
assert!(error.contains("invalid base value"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_runtime_applies_property_override_without_editor_plugin() {
|
||||
let mut app = App::new();
|
||||
app.add_plugins(MinimalPlugins)
|
||||
.add_plugins(AssetPlugin::default())
|
||||
.add_plugins(bevy::pbr::MaterialPlugin::<StandardMaterial>::default())
|
||||
.init_asset::<Mesh>()
|
||||
.add_plugins(WorldSerializationPlugin)
|
||||
.insert_resource(settings::ProjectSettings::default())
|
||||
.add_plugins(crate::SharedTypesPlugin);
|
||||
|
||||
let base = MaterialDesc::default();
|
||||
let mut value = base.clone();
|
||||
value.roughness = 0.18;
|
||||
let overrides = PrefabOverrides {
|
||||
properties: vec![PrefabPropertyOverride {
|
||||
target: PrefabActorPath::direct("mesh"),
|
||||
component_type: std::any::type_name::<MaterialDesc>().to_string(),
|
||||
property_path: "roughness".to_string(),
|
||||
base_component_ron: ron::to_string(&base).unwrap(),
|
||||
value_component_ron: ron::to_string(&value).unwrap(),
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut source = World::new();
|
||||
source.spawn((ActorId::new("mesh"), base));
|
||||
let dynamic_world = DynamicWorld::from_world_with(
|
||||
&source,
|
||||
&app.world().resource::<AppTypeRegistry>().read(),
|
||||
);
|
||||
let handle = app
|
||||
.world_mut()
|
||||
.resource_mut::<Assets<DynamicWorld>>()
|
||||
.add(dynamic_world);
|
||||
let mut instance = PrefabInstance::new("prefab", "assets/prefabs/test.scn.ron");
|
||||
instance.overrides_ron = encode_prefab_overrides(&overrides).unwrap();
|
||||
app.world_mut().spawn((instance, DynamicWorldRoot(handle)));
|
||||
|
||||
app.update();
|
||||
|
||||
let world = app.world_mut();
|
||||
let (_, material) = world
|
||||
.query::<(&ActorId, &MaterialDesc)>()
|
||||
.single(world)
|
||||
.expect("shared runtime should spawn one overridden source actor");
|
||||
assert_eq!(material.roughness, 0.18);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_applies_valid_operations_after_an_independent_operation_error() {
|
||||
let mut app = App::new();
|
||||
app.add_plugins(MinimalPlugins)
|
||||
.add_plugins(AssetPlugin::default())
|
||||
.add_plugins(bevy::pbr::MaterialPlugin::<StandardMaterial>::default())
|
||||
.init_asset::<Mesh>()
|
||||
.add_plugins(WorldSerializationPlugin)
|
||||
.insert_resource(settings::ProjectSettings::default())
|
||||
.add_plugins(crate::SharedTypesPlugin);
|
||||
|
||||
let transform = Transform::default();
|
||||
let mut moved = transform;
|
||||
moved.translation.x = 5.0;
|
||||
let material = MaterialDesc::default();
|
||||
let mut edited_material = material.clone();
|
||||
edited_material.roughness = 0.09;
|
||||
let overrides = PrefabOverrides {
|
||||
properties: vec![
|
||||
PrefabPropertyOverride {
|
||||
target: PrefabActorPath::direct("mesh"),
|
||||
component_type: std::any::type_name::<Transform>().to_string(),
|
||||
property_path: "translation".to_string(),
|
||||
base_component_ron: ron::to_string(&transform).unwrap(),
|
||||
value_component_ron: ron::to_string(&moved).unwrap(),
|
||||
},
|
||||
PrefabPropertyOverride {
|
||||
target: PrefabActorPath::direct("mesh"),
|
||||
component_type: std::any::type_name::<MaterialDesc>().to_string(),
|
||||
property_path: "roughness".to_string(),
|
||||
base_component_ron: ron::to_string(&material).unwrap(),
|
||||
value_component_ron: ron::to_string(&edited_material).unwrap(),
|
||||
},
|
||||
],
|
||||
..default()
|
||||
};
|
||||
|
||||
let mut source = World::new();
|
||||
source.spawn((ActorId::new("mesh"), material));
|
||||
let dynamic_world = DynamicWorld::from_world_with(
|
||||
&source,
|
||||
&app.world().resource::<AppTypeRegistry>().read(),
|
||||
);
|
||||
let handle = app
|
||||
.world_mut()
|
||||
.resource_mut::<Assets<DynamicWorld>>()
|
||||
.add(dynamic_world);
|
||||
let mut instance = PrefabInstance::new("prefab", "assets/prefabs/test.scn.ron");
|
||||
instance.overrides_ron = encode_prefab_overrides(&overrides).unwrap();
|
||||
app.world_mut().spawn((instance, DynamicWorldRoot(handle)));
|
||||
|
||||
app.update();
|
||||
|
||||
let world = app.world_mut();
|
||||
let (_, material) = world
|
||||
.query::<(&ActorId, &MaterialDesc)>()
|
||||
.single(world)
|
||||
.unwrap();
|
||||
assert_eq!(material.roughness, 0.09);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user