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:
Rbanh committed 2026-07-12 00:24:06 -04:00
1 parent 0553a85220
commit 0798aa5d57
169 files changed
+27098 -3469

No files matched your search

+65 -2
View File
@@ -210,6 +210,13 @@ fn build_gltf_manifest(
});
}
let default_animation_clip_id = record.import_settings.default_animation_clip_id.clone();
validate_default_animation_clip(
default_animation_clip_id.as_deref(),
&clips,
&mut diagnostics,
);
let runtime_supported = animation_roots.len() <= 1;
if !runtime_supported {
let roots = animation_roots
@@ -232,6 +239,7 @@ fn build_gltf_manifest(
schema_version: ANIMATION_MANIFEST_SCHEMA_VERSION,
asset_id: record.id.as_string(),
label: record.label.clone(),
default_animation_clip_id,
source: AnimationManifestSource {
path: record.path.clone(),
format,
@@ -313,15 +321,22 @@ fn build_fbx_manifest(
})
.collect::<Vec<_>>();
let (runtime_supported, diagnostics) = fbx_runtime_support(
let (runtime_supported, mut diagnostics) = fbx_runtime_support(
scene.anim_stacks.as_ref().len(),
scene.skin_deformers.as_ref().len(),
);
let default_animation_clip_id = record.import_settings.default_animation_clip_id.clone();
validate_default_animation_clip(
default_animation_clip_id.as_deref(),
&clips,
&mut diagnostics,
);
Ok(AnimationManifest {
schema_version: ANIMATION_MANIFEST_SCHEMA_VERSION,
asset_id: record.id.as_string(),
label: record.label.clone(),
default_animation_clip_id,
source: AnimationManifestSource {
path: record.path.clone(),
format,
@@ -335,6 +350,27 @@ fn build_fbx_manifest(
})
}
fn validate_default_animation_clip(
default_clip_id: Option<&str>,
clips: &[AnimationClipRecord],
diagnostics: &mut Vec<AnimationImportDiagnostic>,
) {
let Some(default_clip_id) = default_clip_id.filter(|id| !id.trim().is_empty()) else {
return;
};
if clips.iter().any(|clip| clip.id == default_clip_id) {
return;
}
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Error,
code: "animation.default_clip_missing".into(),
message: format!(
"configured default animation clip `{default_clip_id}` no longer exists in the imported source"
),
repair: "Choose an existing Default animation in Model Import Settings, or select Imported rest pose, then reimport.".into(),
});
}
fn fbx_runtime_support(
animation_count: usize,
skin_count: usize,
@@ -696,7 +732,8 @@ mod tests {
let second = build_animation_manifest(&record).unwrap();
assert_eq!(first, second);
assert_eq!(first.schema_version, 2);
assert_eq!(first.schema_version, ANIMATION_MANIFEST_SCHEMA_VERSION);
assert!(first.default_animation_clip_id.is_none());
assert!(first.runtime_supported);
assert_eq!(first.source.dependencies.len(), 1);
assert_eq!(first.skeletons.len(), 1);
@@ -717,6 +754,32 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn explicit_default_clip_is_stable_and_stale_ids_are_diagnostic() {
let root =
std::env::temp_dir().join(format!("blacksite-animation-default-{}", Uuid::new_v4()));
let path = write_animated_gltf(&root);
let mut record = fixture_record(&path);
record.import_settings.default_animation_clip_id =
Some("animation:clip:0:idle_loop".into());
let manifest = build_animation_manifest(&record).unwrap();
assert_eq!(
manifest.default_animation_clip_id.as_deref(),
Some("animation:clip:0:idle_loop")
);
assert!(manifest.diagnostics.is_empty());
record.import_settings.default_animation_clip_id = Some("animation:clip:99:removed".into());
let stale = build_animation_manifest(&record).unwrap();
assert!(stale.diagnostics.iter().any(|diagnostic| {
diagnostic.code == "animation.default_clip_missing"
&& diagnostic.severity == AnimationDiagnosticSeverity::Error
}));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn exact_signature_changes_with_joint_path_or_bind_pose() {
let identity = identity_matrix_bytes();
+10
View File
@@ -27,8 +27,12 @@ impl Default for AssetId {
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum ModelPlacementMode {
/// Place renderable content through the appropriate normalized renderer. Imports containing
/// skins or animation route to `SkinnedMeshRenderer`; unrigged, non-animated content routes to
/// `StaticMeshRenderer`.
#[default]
StaticAsset,
/// Instantiate the complete source scene as a generic imported model.
SceneInstance,
}
@@ -61,6 +65,10 @@ pub struct ImportSettings {
pub static_mesh_manifest_path: Option<String>,
#[serde(default)]
pub animation_manifest_path: Option<String>,
/// Stable animation clip sub-asset ID used as this model's edit-mode rest presentation.
/// `None` preserves the imported node pose and never guesses a clip.
#[serde(default)]
pub default_animation_clip_id: Option<String>,
}
impl Default for ImportSettings {
@@ -74,6 +82,7 @@ impl Default for ImportSettings {
material_policy: MaterialImportPolicy::default(),
static_mesh_manifest_path: None,
animation_manifest_path: None,
default_animation_clip_id: None,
}
}
}
@@ -336,6 +345,7 @@ mod tests {
schema_version: ANIMATION_MANIFEST_SCHEMA_VERSION,
asset_id: id.as_string(),
label: "Moved Model".into(),
default_animation_clip_id: None,
source: AnimationManifestSource {
path: old_path.clone(),
format: "glb".into(),
+353 -17
View File
@@ -524,6 +524,7 @@ fn empty_snapshot_for_asset(asset: &EditorAsset, translation: Vec3) -> EditorEnt
primitive: None,
brush: None,
static_mesh_renderer: None,
skinned_mesh_renderer: None,
material: None,
material_override: None,
rigid_body: None,
@@ -542,8 +543,18 @@ fn empty_snapshot_for_asset(asset: &EditorAsset, translation: Vec3) -> EditorEnt
post_process_volume: None,
team_spawn: None,
objective: None,
navigation_bounds: None,
navigation_obstacle: None,
navigation_area: None,
navigation_link: None,
hierarchy_sibling_index: 0,
editor_visibility: EditorVisibility::default(),
inspector_order: None,
component_states: None,
children: Vec::new(),
}
}
@@ -672,17 +683,33 @@ pub fn spawn_asset_at(world: &mut World, asset: &EditorAsset, translation: Vec3)
record.import_settings.placement_mode,
ModelPlacementMode::StaticAsset
) {
if let Some(renderer) = static_mesh_renderer_for_asset(world, path) {
let collider = record
.import_settings
.generate_collider
.then(|| static_mesh_collider_for_renderer(&renderer));
apply_static_mesh_placement_mode(
&mut snapshot,
renderer,
collider,
record.import_settings.hierarchy_mode,
);
if let Some((renderer, requires_skinned_renderer)) =
static_mesh_renderer_for_asset(world, path)
{
if requires_skinned_renderer {
apply_skinned_mesh_placement_mode_with_materials(
&mut snapshot,
renderer.materials.clone(),
);
match default_animation_controller_for_record(&record) {
Ok(controller) => snapshot.animation_controller = controller,
Err(error) => warn!(
"Default animation was not applied while placing {}: {error}",
record.path
),
}
} else {
let collider = record
.import_settings
.generate_collider
.then(|| static_mesh_collider_for_renderer(&renderer));
apply_static_mesh_placement_mode(
&mut snapshot,
renderer,
collider,
record.import_settings.hierarchy_mode,
);
}
} else {
warn!(
"Static mesh placement fell back to SceneRoot for {} because no renderer manifest was available",
@@ -760,6 +787,11 @@ pub fn spawn_subasset_at(
.parts
.iter()
.find(|part| part_effective_id_for_selection(part) == *sub_asset_id)?;
let part_requires_skinned_renderer = manifest.metadata.animation_count > 0
|| part.skinned
|| (manifest.schema_version < 2
&& crate::assets::gltf_skinned_primitive_labels(parent_path)
.contains(&part.mesh_label));
let mesh_ref = shared::EditorAssetRef::new(
manifest.asset_id.clone(),
@@ -784,6 +816,10 @@ pub fn spawn_subasset_at(
id: shared::ComponentInstanceId::new("slot:0"),
name: label.clone(),
mesh: mesh_ref.clone(),
material_slot_id: shared::ComponentInstanceId::new(format!(
"slot:{}",
part_effective_id_for_selection(part)
)),
material,
local_transform: part.local_transform,
visible: true,
@@ -800,6 +836,7 @@ pub fn spawn_subasset_at(
primitive: None,
brush: None,
static_mesh_renderer: Some(shared::StaticMeshRenderer::single(slot)),
skinned_mesh_renderer: None,
material: None,
material_override: None,
rigid_body: None,
@@ -818,11 +855,41 @@ pub fn spawn_subasset_at(
post_process_volume: None,
team_spawn: None,
objective: None,
navigation_bounds: None,
navigation_obstacle: None,
navigation_area: None,
navigation_link: None,
hierarchy_sibling_index: 0,
editor_visibility: EditorVisibility::default(),
inspector_order: None,
component_states: None,
children: Vec::new(),
};
snapshot.transform.scale *= record.import_settings.scale;
if part_requires_skinned_renderer {
snapshot.actor_kind = ActorKind::SkinnedMesh;
snapshot.static_mesh_renderer = None;
snapshot.skinned_mesh_renderer = Some(shared::SkinnedMeshRenderer {
materials: crate::assets::static_mesh::renderer_materials_from_manifest(
&manifest,
&record.import_settings,
),
..shared::SkinnedMeshRenderer::new(parent_path.clone())
.with_asset_id(record.id.as_string())
});
match default_animation_controller_for_record(&record) {
Ok(controller) => snapshot.animation_controller = controller,
Err(error) => warn!(
"Default animation was not applied while placing {}: {error}",
record.path
),
}
return Some(spawn_with_history(world, snapshot));
}
if record.import_settings.generate_collider {
snapshot.rigid_body = Some(RigidBodyDesc::default());
snapshot.collider = Some(ColliderDesc::static_mesh(vec![mesh_ref]));
@@ -840,6 +907,7 @@ pub struct AnimationClipAuthoringData {
pub skeleton: shared::EditorAssetRef,
pub skeleton_signature: shared::AnimationSkeletonSignature,
pub state: shared::AnimationStateDesc,
pub renderer_materials: shared::RendererMaterialSet,
}
pub fn animation_clip_authoring_data(
@@ -905,6 +973,18 @@ pub fn animation_clip_authoring_data(
let clip_ref = shared::EditorAssetRef::new(asset_id, clip.id.clone(), clip.label.clone())
.with_source_path(parent_path);
let state_id = animation_state_id(&clip.label, clip.source_index);
let renderer_materials = record
.import_settings
.static_mesh_manifest_path
.as_deref()
.and_then(|path| load_static_mesh_manifest(path).ok())
.map(|render_manifest| {
crate::assets::static_mesh::renderer_materials_from_manifest(
&render_manifest,
&record.import_settings,
)
})
.unwrap_or_default();
Ok(AnimationClipAuthoringData {
model_asset_id: record.id.as_string(),
model_path: parent_path.clone(),
@@ -920,6 +1000,7 @@ pub fn animation_clip_authoring_data(
speed: 1.0,
range: shared::AnimationPlaybackRange::default(),
},
renderer_materials,
})
}
@@ -957,7 +1038,7 @@ pub fn animation_skeleton_signature_for_ref(
pub fn compatible_animation_skeleton_for_model(
world: &World,
model: &ModelRef,
model: &shared::SkinnedMeshRenderer,
signature: &shared::AnimationSkeletonSignature,
) -> Result<shared::EditorAssetRef, String> {
let record = world
@@ -1017,6 +1098,82 @@ fn animation_state_id(label: &str, source_index: usize) -> String {
}
}
fn default_animation_controller_for_record(
record: &crate::asset_db::AssetRecord,
) -> Result<Option<shared::AnimationControllerDesc>, String> {
let Some(manifest_path) = record.import_settings.animation_manifest_path.as_deref() else {
return Ok(None);
};
let manifest = load_animation_manifest(manifest_path)?;
if manifest.default_animation_clip_id != record.import_settings.default_animation_clip_id {
return Err(
"model import settings and generated animation manifest disagree; reimport the model"
.into(),
);
}
let Some(default_clip_id) = manifest
.default_animation_clip_id
.as_deref()
.filter(|id| !id.trim().is_empty())
else {
return Ok(None);
};
if !manifest.runtime_supported {
return Err(format!(
"configured clip `{default_clip_id}` belongs to a model unsupported by the animation runtime"
));
}
let clip = manifest
.clips
.iter()
.find(|clip| clip.id == default_clip_id)
.ok_or_else(|| {
format!(
"configured clip `{default_clip_id}` is missing from {manifest_path}; choose an existing clip or Imported rest pose"
)
})?;
let signature = clip.target_skeleton_signature.as_ref().ok_or_else(|| {
format!(
"configured clip `{}` has no uniquely resolved target skeleton",
clip.label
)
})?;
let skeleton = manifest
.skeletons
.iter()
.find(|skeleton| &skeleton.signature == signature)
.ok_or_else(|| {
format!(
"configured clip `{}` targets skeleton `{}` but no exact match exists",
clip.label, signature.0
)
})?;
let state_id = animation_state_id(&clip.label, clip.source_index);
let source_path = manifest.source.path.clone();
let asset_id = manifest.asset_id.clone();
Ok(Some(shared::AnimationControllerDesc {
skeleton: Some(
shared::EditorAssetRef::new(
asset_id.clone(),
skeleton.id.clone(),
skeleton.label.clone(),
)
.with_source_path(&source_path),
),
states: vec![shared::AnimationStateDesc {
id: state_id.clone(),
label: clip.label.clone(),
clip: shared::EditorAssetRef::new(asset_id, clip.id.clone(), clip.label.clone())
.with_source_path(source_path),
looping: true,
speed: 1.0,
range: shared::AnimationPlaybackRange::default(),
}],
default_state: state_id,
..default()
}))
}
fn spawn_animation_clip_at(
world: &mut World,
selection: &AssetSelection,
@@ -1035,7 +1192,7 @@ fn spawn_animation_clip_at(
let default_state = authored.state.id.clone();
let snapshot = EditorEntitySnapshot {
actor_id: None,
actor_kind: ActorKind::ImportedModel,
actor_kind: ActorKind::SkinnedMesh,
actor_name: None,
name: Some(authored.model_label),
transform: Transform {
@@ -1046,6 +1203,11 @@ fn spawn_animation_clip_at(
primitive: None,
brush: None,
static_mesh_renderer: None,
skinned_mesh_renderer: Some(shared::SkinnedMeshRenderer {
materials: authored.renderer_materials,
..shared::SkinnedMeshRenderer::new(authored.model_path)
.with_asset_id(authored.model_asset_id)
}),
material: None,
material_override: None,
rigid_body: None,
@@ -1061,7 +1223,7 @@ fn spawn_animation_clip_at(
audio_source: None,
audio_listener: None,
player_spawn: false,
model: Some(ModelRef::new(authored.model_path).with_asset_id(authored.model_asset_id)),
model: None,
prefab: None,
prefab_instance: None,
weapon_spawn: None,
@@ -1069,8 +1231,18 @@ fn spawn_animation_clip_at(
post_process_volume: None,
team_spawn: None,
objective: None,
navigation_bounds: None,
navigation_obstacle: None,
navigation_area: None,
navigation_link: None,
hierarchy_sibling_index: 0,
editor_visibility: EditorVisibility::default(),
inspector_order: None,
component_states: None,
children: Vec::new(),
};
Some(spawn_with_history(world, snapshot))
@@ -1118,6 +1290,7 @@ fn apply_static_mesh_placement_mode(
primitive: None,
brush: None,
static_mesh_renderer: Some(shared::StaticMeshRenderer::single(entry)),
skinned_mesh_renderer: None,
material: None,
material_override: None,
rigid_body: collider.as_ref().map(|_| RigidBodyDesc::default()),
@@ -1136,8 +1309,18 @@ fn apply_static_mesh_placement_mode(
post_process_volume: None,
team_spawn: None,
objective: None,
navigation_bounds: None,
navigation_obstacle: None,
navigation_area: None,
navigation_link: None,
hierarchy_sibling_index: index as i32,
editor_visibility: EditorVisibility::default(),
inspector_order: None,
component_states: None,
children: Vec::new(),
}
})
@@ -1146,6 +1329,35 @@ fn apply_static_mesh_placement_mode(
}
}
#[cfg(test)]
fn apply_skinned_mesh_placement_mode(snapshot: &mut EditorEntitySnapshot) {
apply_skinned_mesh_placement_mode_with_materials(
snapshot,
shared::RendererMaterialSet::default(),
);
}
fn apply_skinned_mesh_placement_mode_with_materials(
snapshot: &mut EditorEntitySnapshot,
materials: shared::RendererMaterialSet,
) {
let Some(model) = snapshot.model.take() else {
return;
};
snapshot.actor_kind = ActorKind::SkinnedMesh;
snapshot.static_mesh_renderer = None;
snapshot.skinned_mesh_renderer = Some(shared::SkinnedMeshRenderer {
asset_id: model.asset_id,
path: model.path,
scene_index: model.scene_index,
materials,
});
// Triangle-mesh colliders are a static-geometry concern. Animated collision must be authored
// explicitly (capsules, hitboxes, or another gameplay-specific representation).
snapshot.rigid_body = None;
snapshot.collider = None;
}
fn static_mesh_collider_for_renderer(renderer: &shared::StaticMeshRenderer) -> ColliderDesc {
ColliderDesc::static_mesh(
renderer
@@ -1177,14 +1389,26 @@ fn part_effective_material_id_for_selection(
fn static_mesh_renderer_for_asset(
world: &mut World,
path: &str,
) -> Option<shared::StaticMeshRenderer> {
) -> Option<(shared::StaticMeshRenderer, bool)> {
let mut manifest_path = None;
if let Some(mut registry) = world.get_resource_mut::<AssetRegistry>() {
let mut renderer = None;
if let Some(record) = find_asset_mut_by_path(&mut registry, path) {
match super::refresh_model_artifacts(record) {
Ok(manifest) => {
renderer = Some(renderer_from_manifest(&manifest, &record.import_settings));
let requires_skinned_renderer = manifest.metadata.animation_count > 0
|| manifest.metadata.skin_count > 0
|| manifest.parts.iter().any(|part| part.skinned);
let mut authored_renderer =
renderer_from_manifest(&manifest, &record.import_settings);
if requires_skinned_renderer {
authored_renderer.materials =
crate::assets::static_mesh::renderer_materials_from_manifest(
&manifest,
&record.import_settings,
);
}
renderer = Some((authored_renderer, requires_skinned_renderer));
registry.index_dirty = true;
}
Err(error) => {
@@ -1207,7 +1431,17 @@ fn static_mesh_renderer_for_asset(
let registry = world.get_resource::<AssetRegistry>()?;
let record = find_asset_by_path(registry, path)?;
let manifest = load_static_mesh_manifest(&manifest_path).ok()?;
Some(renderer_from_manifest(&manifest, &record.import_settings))
let requires_skinned_renderer = manifest.metadata.animation_count > 0
|| manifest.metadata.skin_count > 0
|| manifest.parts.iter().any(|part| part.skinned);
let mut renderer = renderer_from_manifest(&manifest, &record.import_settings);
if requires_skinned_renderer {
renderer.materials = crate::assets::static_mesh::renderer_materials_from_manifest(
&manifest,
&record.import_settings,
);
}
Some((renderer, requires_skinned_renderer))
}
pub fn import_external_assets(paths: &[PathBuf]) -> Result<usize, String> {
@@ -1348,4 +1582,106 @@ mod tests {
);
assert!(world.resource::<crate::history::EditorHistory>().can_undo());
}
#[test]
fn skinned_model_placement_replaces_static_and_generic_model_renderers() {
let asset = EditorAsset {
label: "Hero".into(),
path: Some("assets/models/hero.glb".into()),
folder_path: "assets/models".into(),
kind: EditorAssetKind::Model,
};
let mut snapshot = snapshot_for_asset(&asset, Vec3::ZERO).unwrap();
snapshot.model.as_mut().unwrap().asset_id = "hero-id".into();
snapshot.static_mesh_renderer = Some(shared::StaticMeshRenderer::default());
snapshot.rigid_body = Some(RigidBodyDesc::default());
snapshot.collider = Some(ColliderDesc::static_cuboid(Vec3::ONE));
apply_skinned_mesh_placement_mode(&mut snapshot);
assert_eq!(snapshot.actor_kind, ActorKind::SkinnedMesh);
assert!(snapshot.model.is_none());
assert!(snapshot.static_mesh_renderer.is_none());
assert!(snapshot.rigid_body.is_none());
assert!(snapshot.collider.is_none());
assert_eq!(
snapshot.skinned_mesh_renderer,
Some(
shared::SkinnedMeshRenderer::new("assets/models/hero.glb").with_asset_id("hero-id")
)
);
}
#[test]
fn model_default_clip_builds_one_explicit_controller_state() {
let key = Uuid::new_v4();
let manifest_path =
std::env::temp_dir().join(format!("blacksite-default-animation-{key}.animation.ron"));
let asset_id = key.to_string();
let signature = shared::AnimationSkeletonSignature::new("rig-signature");
let clip_id = shared::animation_clip_sub_asset_id(8, "Standing");
let manifest = shared::AnimationManifest {
schema_version: shared::ANIMATION_MANIFEST_SCHEMA_VERSION,
asset_id: asset_id.clone(),
label: "Robot".into(),
default_animation_clip_id: Some(clip_id.clone()),
source: shared::AnimationManifestSource {
path: "assets/models/robot.glb".into(),
format: "glb".into(),
fingerprint: shared::AnimationSourceFingerprint {
byte_len: 1,
modified_unix_secs: 0,
content_hash: "fixture".into(),
},
dependencies: Vec::new(),
},
runtime_supported: true,
skeletons: vec![shared::AnimationSkeletonRecord {
id: shared::animation_skeleton_sub_asset_id(0, "Rig"),
label: "Rig".into(),
source_index: 0,
signature: signature.clone(),
joint_paths: vec!["Root".into()],
}],
clips: vec![shared::AnimationClipRecord {
id: clip_id.clone(),
label: "Standing".into(),
source_index: 8,
duration_seconds: 0.4,
target_skeleton_signature: Some(signature),
events: Vec::new(),
}],
diagnostics: Vec::new(),
};
std::fs::write(
&manifest_path,
ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default()).unwrap(),
)
.unwrap();
let record = AssetRecord {
id: AssetId(key),
path: "assets/models/robot.glb".into(),
label: "Robot".into(),
kind_tag: "Model".into(),
import_settings: crate::asset_db::ImportSettings {
animation_manifest_path: Some(manifest_path.to_string_lossy().into_owned()),
default_animation_clip_id: Some(clip_id.clone()),
..Default::default()
},
dependencies: Vec::new(),
};
let controller = default_animation_controller_for_record(&record)
.unwrap()
.expect("explicit default should produce a controller");
assert_eq!(controller.default_state, "standing");
assert_eq!(controller.states.len(), 1);
assert_eq!(controller.states[0].clip.sub_asset_id, clip_id);
assert_eq!(
controller.skeleton.unwrap().sub_asset_id,
shared::animation_skeleton_sub_asset_id(0, "Rig")
);
std::fs::remove_file(manifest_path).unwrap();
}
}
+100 -10
View File
@@ -2,10 +2,13 @@
use bevy::prelude::*;
use bevy_egui::egui;
use shared::{LevelObject, MaterialAsset, MaterialDesc};
use shared::{
ComponentInstanceId, LevelObject, MaterialAsset, MaterialDesc, MaterialRef,
RendererMaterialSlot,
};
use crate::assets::{EditorAsset, EditorAssetKind, EditorAssets};
use crate::history::set_material_group_with_history;
use crate::history::{reflected_component_transaction, set_material_group_with_history};
use crate::ui::inspector::property_row;
pub fn load_material_asset(catalog_path: &str) -> Result<MaterialAsset, String> {
@@ -28,18 +31,105 @@ pub fn apply_material_asset_to_selection(
.path
.clone()
.ok_or_else(|| format!("Material has no source path: {}", asset.label))?;
let desc = material_desc_from_asset(&path)?;
let changes = crate::ui::helpers::selected_level_entities(world, selected)
.into_iter()
.filter(|entity| world.get::<LevelObject>(*entity).is_some())
.map(|entity| (entity, desc.clone()))
.collect::<Vec<_>>();
set_material_group_with_history(world, changes);
let record = world
.get_resource::<crate::asset_db::AssetRegistry>()
.and_then(|registry| crate::asset_db::find_asset_by_path(registry, &path))
.ok_or_else(|| format!("Material is missing from the asset registry: {path}"))?;
let sub_asset_id = if shared::MaterialInstanceAsset::load_from_path(&path).is_ok() {
"material:instance"
} else {
"material:source"
};
let material_ref = MaterialRef::new(
shared::EditorAssetRef::new(record.id.as_string(), sub_asset_id, asset.label.clone())
.with_source_path(path.clone()),
);
let desc = material_desc_from_asset(&path).ok();
let entities = crate::ui::helpers::selected_level_entities(world, selected);
let mut renderer_changes = 0usize;
let mut legacy_changes = Vec::new();
for entity in entities {
if world.get::<LevelObject>(entity).is_none() {
continue;
}
if let Some(mut renderer) = world.get::<shared::StaticMeshRenderer>(entity).cloned() {
ensure_static_material_slots(&mut renderer);
for slot in &mut renderer.materials.slots {
slot.material = Some(material_ref.clone());
}
reflected_component_transaction(
world,
entity,
"Assign Material Slots",
shared::AUTHORING_COMPONENT_STATIC_MESH_RENDERER,
shared::COMPONENT_STATIC_MESH_RENDERER,
move |world, entity| {
world.entity_mut(entity).insert(renderer);
Ok(())
},
)?;
renderer_changes += 1;
continue;
}
if let Some(mut renderer) = world.get::<shared::SkinnedMeshRenderer>(entity).cloned() {
if renderer.materials.slots.is_empty() {
return Err(format!(
"Skinned renderer `{}` has no imported material slots; reimport its model",
renderer.path
));
}
for slot in &mut renderer.materials.slots {
slot.material = Some(material_ref.clone());
}
reflected_component_transaction(
world,
entity,
"Assign Material Slots",
shared::AUTHORING_COMPONENT_SKINNED_MESH_RENDERER,
shared::COMPONENT_SKINNED_MESH_RENDERER,
move |world, entity| {
world.entity_mut(entity).insert(renderer);
Ok(())
},
)?;
renderer_changes += 1;
continue;
}
if let Some(desc) = desc.as_ref() {
legacy_changes.push((entity, desc.clone()));
}
}
if !legacy_changes.is_empty() {
set_material_group_with_history(world, legacy_changes);
}
if renderer_changes == 0 && desc.is_none() {
return Err("No selected renderable actor accepts this material".into());
}
world.resource_mut::<crate::scene_io::SceneIo>().status =
format!("Applied material {}", asset.label);
format!("Applied shared material {}", asset.label);
Ok(())
}
fn ensure_static_material_slots(renderer: &mut shared::StaticMeshRenderer) {
for part in &mut renderer.slots {
if part.material_slot_id.0.trim().is_empty() {
part.material_slot_id = if part.id.0.trim().is_empty() {
ComponentInstanceId::new("slot:legacy")
} else {
ComponentInstanceId::new(format!("slot:{}", part.id.0))
};
}
if renderer.materials.slot(&part.material_slot_id).is_none() {
renderer.materials.slots.push(RendererMaterialSlot {
id: part.material_slot_id.clone(),
name: part.name.clone(),
source_material: part.material.clone().map(MaterialRef::new),
material: None,
});
}
}
}
pub fn material_asset_picker_ui(
world: &mut World,
ui: &mut egui::Ui,
+45 -7
View File
@@ -119,10 +119,10 @@ pub fn assign_animation_clip_operator(
selection: AssetSelection,
entity: Entity,
) -> bool {
let availability = if world.get::<shared::ModelRef>(entity).is_some() {
let availability = if world.get::<shared::SkinnedMeshRenderer>(entity).is_some() {
OperatorAvailability::Ready
} else {
OperatorAvailability::Disabled("Select an authored imported-model actor".to_string())
OperatorAvailability::Disabled("Select an authored skinned-mesh actor".to_string())
};
let label = format!("Assign Animation Clip {}", selection.display_label());
run_immediate_operator(
@@ -133,9 +133,9 @@ pub fn assign_animation_clip_operator(
move |world| {
let authored = animation_clip_authoring_data(world, &selection)?;
let model = world
.get::<shared::ModelRef>(entity)
.get::<shared::SkinnedMeshRenderer>(entity)
.cloned()
.ok_or_else(|| "Selected actor has no ModelRef".to_string())?;
.ok_or_else(|| "Selected actor has no SkinnedMeshRenderer".to_string())?;
let mut controller = world
.get::<shared::AnimationControllerDesc>(entity)
.cloned()
@@ -197,7 +197,7 @@ mod tests {
animation_clip_sub_asset_id, animation_skeleton_sub_asset_id, ActorKind,
AnimationClipRecord, AnimationControllerDesc, AnimationManifest, AnimationManifestSource,
AnimationSkeletonRecord, AnimationSkeletonSignature, AnimationSourceFingerprint,
AudioSourceDesc, LevelObject, MaterialDesc, ModelRef, PrimitiveShape,
AudioSourceDesc, LevelObject, MaterialDesc, PrimitiveShape, SkinnedMeshRenderer,
ANIMATION_MANIFEST_SCHEMA_VERSION,
};
@@ -222,6 +222,7 @@ mod tests {
schema_version: ANIMATION_MANIFEST_SCHEMA_VERSION,
asset_id: asset_id.as_string(),
label: "Operator Fixture".into(),
default_animation_clip_id: None,
source: AnimationManifestSource {
path: model_path.clone(),
format: "glb".into(),
@@ -301,6 +302,43 @@ mod tests {
assert_undo_redo_round_trip(&mut world, 0, 1, authored_count);
}
#[test]
fn animation_clip_placement_creates_only_the_skinned_renderer_path() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
world.init_resource::<SelectedEntity>();
let (manifest_path, record, selection) = animation_fixture();
world.insert_resource(AssetRegistry {
records: vec![record],
index_dirty: false,
});
let harness = OperatorInvariantHarness::capture(&mut world);
assert!(place_subasset_operator(
&mut world,
selection,
Vec3::new(1.0, 2.0, 3.0),
));
let entity = world
.query_filtered::<Entity, With<LevelObject>>()
.single(&world)
.unwrap();
assert_eq!(
world.get::<ActorKind>(entity),
Some(&ActorKind::SkinnedMesh)
);
assert!(world.get::<SkinnedMeshRenderer>(entity).is_some());
assert!(world.get::<AnimationControllerDesc>(entity).is_some());
assert!(world.get::<shared::ModelRef>(entity).is_none());
assert!(world.get::<shared::StaticMeshRenderer>(entity).is_none());
harness.assert_committed(&mut world, 1, 1);
assert_undo_redo_round_trip(&mut world, 0, 1, authored_count);
let _ = std::fs::remove_file(manifest_path);
}
#[test]
fn audio_clip_assignment_is_one_undoable_operator() {
let mut world = World::new();
@@ -363,8 +401,8 @@ mod tests {
let entity = world
.spawn((
LevelObject,
ActorKind::ImportedModel,
ModelRef::new(model_path),
ActorKind::SkinnedMesh,
SkinnedMeshRenderer::new(model_path),
))
.id();
let harness = OperatorInvariantHarness::capture(&mut world);
+180 -28
View File
@@ -14,9 +14,12 @@ use serde::{Deserialize, Serialize};
use crate::asset_db::{
AssetRecord, ImportSettings, MaterialImportPolicy, ModelHierarchyMode, ModelPlacementMode,
};
use shared::{ComponentInstanceId, EditorAssetRef, StaticMeshRenderer, StaticMeshRendererEntry};
use shared::{
ComponentInstanceId, EditorAssetRef, MaterialRef, RendererMaterialSet, RendererMaterialSlot,
StaticMeshRenderer, StaticMeshRendererEntry,
};
pub const STATIC_MESH_MANIFEST_SCHEMA: u32 = 1;
pub const STATIC_MESH_MANIFEST_SCHEMA: u32 = 3;
pub const STATIC_MESH_ARTIFACT_DIR: &str = "assets/meshes/generated";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -80,6 +83,10 @@ pub struct StaticMeshPart {
pub source_node: Option<String>,
pub source_mesh: Option<String>,
pub source_material: Option<String>,
/// Whether the source primitive is bound to a skin and therefore must never become a static
/// renderer slot.
#[serde(default)]
pub skinned: bool,
}
pub fn static_mesh_manifest_path(asset_id: &str) -> String {
@@ -94,6 +101,17 @@ pub fn material_id_from_label(label: &str) -> String {
format!("material:{}", stable_sub_asset_slug(label))
}
fn gltf_draw_id(node_index: Option<usize>, mesh_index: usize, primitive_index: usize) -> String {
let node = node_index
.map(|index| index.to_string())
.unwrap_or_else(|| "unbound".into());
format!("draw:scene0:node{node}:mesh{mesh_index}:primitive{primitive_index}")
}
fn fbx_draw_id(node_index: usize, material_index: usize) -> String {
format!("draw:scene0:node{node_index}:material{material_index}")
}
fn stable_sub_asset_slug(label: &str) -> String {
let mut slug = String::new();
for ch in label.chars() {
@@ -151,38 +169,106 @@ pub fn renderer_from_manifest(
MaterialImportPolicy::SourceMaterials
);
StaticMeshRenderer {
let parts: Vec<_> = manifest
.parts
.iter()
.filter(|part| !part.skinned && manifest.metadata.animation_count == 0)
.map(|part| StaticMeshRendererEntry {
id: ComponentInstanceId::new(part_effective_id(part)),
name: part.name.clone(),
mesh: EditorAssetRef::new(
manifest.asset_id.clone(),
part_effective_id(part),
part.name.clone(),
),
material_slot_id: ComponentInstanceId::new(material_slot_id(part)),
material: use_source_materials
.then(|| {
part_effective_material_id(part).map(|id| {
EditorAssetRef::new(
manifest.asset_id.clone(),
id,
part.material_slot_name.clone(),
)
})
})
.flatten(),
local_transform: part.local_transform,
visible: true,
cast_shadows: true,
receive_shadows: true,
})
.collect();
let materials = RendererMaterialSet {
slots: manifest
.parts
.iter()
.map(|part| StaticMeshRendererEntry {
id: ComponentInstanceId::new(part_effective_id(part)),
name: part.name.clone(),
mesh: EditorAssetRef::new(
manifest.asset_id.clone(),
part_effective_id(part),
part.name.clone(),
),
material: use_source_materials
.filter(|part| !part.skinned && manifest.metadata.animation_count == 0)
.map(|part| RendererMaterialSlot {
id: ComponentInstanceId::new(material_slot_id(part)),
name: part.material_slot_name.clone(),
source_material: use_source_materials
.then(|| {
part_effective_material_id(part).map(|id| {
EditorAssetRef::new(
MaterialRef::new(EditorAssetRef::new(
manifest.asset_id.clone(),
id,
part.material_slot_name.clone(),
)
))
})
})
.flatten(),
local_transform: part.local_transform,
visible: true,
cast_shadows: true,
receive_shadows: true,
material: None,
})
.collect(),
orphaned_assignments: Vec::new(),
};
StaticMeshRenderer {
slots: parts,
materials,
}
}
/// Builds the shared material slots for a full imported hierarchy. Unlike static renderer
/// construction this intentionally includes skin-bound and rigid animated draw bindings.
pub fn renderer_materials_from_manifest(
manifest: &StaticMeshManifest,
settings: &ImportSettings,
) -> RendererMaterialSet {
let use_source_materials = matches!(
settings.material_policy,
MaterialImportPolicy::SourceMaterials
);
RendererMaterialSet {
slots: manifest
.parts
.iter()
.map(|part| RendererMaterialSlot {
id: ComponentInstanceId::new(material_slot_id(part)),
name: part.material_slot_name.clone(),
source_material: use_source_materials
.then(|| {
part_effective_material_id(part).map(|id| {
MaterialRef::new(EditorAssetRef::new(
manifest.asset_id.clone(),
id,
part.material_slot_name.clone(),
))
})
})
.flatten(),
material: None,
})
.collect(),
orphaned_assignments: Vec::new(),
}
}
fn material_slot_id(part: &StaticMeshPart) -> String {
format!("slot:{}", part_effective_id(part))
}
fn part_effective_id(part: &StaticMeshPart) -> String {
if part.id.trim().is_empty() {
part_id_from_label(&part.mesh_label)
@@ -255,23 +341,23 @@ fn build_gltf_manifest(
.or_else(|| gltf.document.scenes().next())
{
for node in scene.nodes() {
collect_gltf_node_parts(node, Mat4::IDENTITY, &mut parts);
collect_gltf_node_parts(node, Mat4::IDENTITY, "", &mut parts);
}
} else {
for mesh in gltf.document.meshes() {
collect_gltf_mesh_parts(None, None, mesh, Mat4::IDENTITY, &mut parts);
collect_gltf_mesh_parts(None, None, None, mesh, Mat4::IDENTITY, false, &mut parts);
}
}
if gltf.document.animations().count() > 0 {
warnings.push(
"Animations are recorded as metadata; use Scene Instance placement for playback."
"Animations are recorded as metadata; animated placement uses SkinnedMeshRenderer."
.into(),
);
}
if gltf.document.skins().count() > 0 {
warnings.push(
"Skins are recorded as metadata; skinned playback stays on the Scene Instance path."
"Skinned primitives are excluded from StaticMeshRenderer and use SkinnedMeshRenderer."
.into(),
);
}
@@ -306,29 +392,44 @@ fn build_gltf_manifest(
fn collect_gltf_node_parts(
node: gltf::Node<'_>,
parent_transform: Mat4,
parent_path: &str,
parts: &mut Vec<StaticMeshPart>,
) {
let local = Mat4::from_cols_array_2d(&node.transform().matrix());
let world_transform = parent_transform * local;
let segment = node
.name()
.map(str::to_string)
.unwrap_or_else(|| format!("Node{}", node.index()));
let node_path = if parent_path.is_empty() {
segment
} else {
format!("{parent_path}/{segment}")
};
let skinned = node.skin().is_some();
if let Some(mesh) = node.mesh() {
collect_gltf_mesh_parts(
node.name().map(str::to_string),
Some(node.index()),
Some(node_path.clone()),
mesh,
world_transform,
skinned,
parts,
);
}
for child in node.children() {
collect_gltf_node_parts(child, world_transform, parts);
collect_gltf_node_parts(child, world_transform, &node_path, parts);
}
}
fn collect_gltf_mesh_parts(
node_name: Option<String>,
node_index: Option<usize>,
node_path: Option<String>,
mesh: gltf::Mesh<'_>,
transform: Mat4,
skinned: bool,
parts: &mut Vec<StaticMeshPart>,
) {
let mesh_index = mesh.index();
@@ -359,9 +460,11 @@ fn collect_gltf_mesh_parts(
.clone()
.or_else(|| mesh_name.clone())
.unwrap_or_else(|| format!("Mesh {mesh_index}"));
let source_node = node_index.map(|index| format!("Node{index}"));
let source_node = node_path
.clone()
.or_else(|| node_index.map(|index| format!("Node{index}")));
parts.push(StaticMeshPart {
id: part_id_from_label(&mesh_label),
id: gltf_draw_id(node_index, mesh_index, primitive_index),
name: format!("{name} / Primitive {primitive_index}"),
material_id: material_label
.as_ref()
@@ -373,6 +476,7 @@ fn collect_gltf_mesh_parts(
source_node,
source_mesh: Some(format!("Mesh{mesh_index}")),
source_material: Some(material_name),
skinned,
});
}
}
@@ -405,6 +509,7 @@ fn build_fbx_manifest(
if mesh.num_vertices == 0 || mesh.faces.as_ref().is_empty() {
continue;
}
let skinned = !mesh.skin_deformers.as_ref().is_empty();
let mut groups: Vec<(usize, Vec<u32>)> =
group_faces_by_material(mesh).into_iter().collect();
@@ -428,7 +533,7 @@ fn build_fbx_manifest(
};
let mesh_label = FbxAssetLabel::Mesh(node_index * 1000 + material_index).to_string();
parts.push(StaticMeshPart {
id: part_id_from_label(&mesh_label),
id: fbx_draw_id(node_index, material_index),
name: format!("{node_name} / Material {material_index}"),
material_id: material_label
.as_ref()
@@ -440,19 +545,20 @@ fn build_fbx_manifest(
source_node: Some(format!("Node{node_index}")),
source_mesh: Some(format!("Mesh{node_index}")),
source_material: Some(material_name),
skinned,
});
}
}
if !scene.anim_stacks.as_ref().is_empty() {
warnings.push(
"Animations are recorded as metadata; use Scene Instance placement for playback."
"Animations are recorded as metadata; animated placement uses SkinnedMeshRenderer."
.into(),
);
}
if !scene.skin_deformers.as_ref().is_empty() {
warnings.push(
"Skins are recorded as metadata; skinned playback stays on the Scene Instance path."
"Skinned primitives are excluded from StaticMeshRenderer and use SkinnedMeshRenderer."
.into(),
);
}
@@ -554,6 +660,7 @@ fn resolve_dependency(source_path: &str, uri: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::asset_db::AssetId;
fn test_manifest() -> StaticMeshManifest {
StaticMeshManifest {
@@ -597,6 +704,7 @@ mod tests {
source_node: Some("Node0".into()),
source_mesh: Some("Mesh0".into()),
source_material: Some("Wood".into()),
skinned: false,
}],
warnings: Vec::new(),
}
@@ -645,4 +753,48 @@ mod tests {
assert!(renderer.slots[0].material.is_none());
}
#[test]
fn renderer_from_manifest_excludes_skinned_primitives() {
let mut manifest = test_manifest();
manifest.parts[0].skinned = true;
let renderer = renderer_from_manifest(&manifest, &ImportSettings::default());
assert!(renderer.slots.is_empty());
}
#[test]
fn renderer_from_manifest_excludes_node_animated_geometry() {
let mut manifest = test_manifest();
manifest.metadata.animation_count = 1;
let renderer = renderer_from_manifest(&manifest, &ImportSettings::default());
assert!(renderer.slots.is_empty());
}
#[test]
fn committed_rigged_fixture_never_builds_static_renderer_slots() {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../assets/models/robot_expressive.glb")
.to_string_lossy()
.into_owned();
let record = AssetRecord {
id: AssetId::new(),
path,
label: "Robot Expressive".into(),
kind_tag: "Model".into(),
import_settings: ImportSettings::default(),
dependencies: Vec::new(),
};
let manifest = build_static_mesh_manifest(&record).unwrap();
let renderer = renderer_from_manifest(&manifest, &record.import_settings);
assert!(manifest.metadata.skin_count > 0);
assert!(manifest.metadata.animation_count > 0);
assert!(manifest.parts.iter().any(|part| part.skinned));
assert!(renderer.slots.is_empty());
}
}
+65 -3
View File
@@ -21,6 +21,10 @@ use crate::infra::EditorOnly;
pub(crate) const THUMB_SIZE: u32 = 128;
pub(crate) const THUMBNAIL_LAYER: usize = 31;
const THUMBNAIL_VERTICAL_FOV: f32 = 40.0_f32.to_radians();
const THUMBNAIL_HALF_VERTICAL_FOV: f32 = THUMBNAIL_VERTICAL_FOV * 0.5;
const SCENE_FRAME_PADDING: f32 = 1.35;
const MATERIAL_SPHERE_FRAME_PADDING: f32 = 1.28;
const MESH_WARMUP_FRAMES: u8 = 12;
const POST_ATTACH_FRAMES: u8 = 8;
const RENDER_FRAMES: u8 = 3;
@@ -61,6 +65,25 @@ struct ActiveModelThumbnail {
framed: bool,
frames_remaining: u8,
wait_frames: u32,
framing: ThumbnailFraming,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ThumbnailFraming {
SceneBounds,
MaterialSphere,
}
impl ThumbnailFraming {
fn for_source(source: &ThumbnailJobSource) -> Self {
match source {
ThumbnailJobSource::SourceMaterial { .. }
| ThumbnailJobSource::MaterialAsset { .. } => Self::MaterialSphere,
ThumbnailJobSource::Model { .. } | ThumbnailJobSource::MeshSubAsset { .. } => {
Self::SceneBounds
}
}
}
}
pub struct ThumbnailStudioPlugin;
@@ -143,7 +166,7 @@ fn setup_thumbnail_studio(mut commands: Commands, mut images: ResMut<Assets<Imag
RenderTarget::Image(render_image.clone().into()),
Transform::from_xyz(2.0, 1.4, 2.0).looking_at(Vec3::new(0.0, 0.5, 0.0), Vec3::Y),
Projection::Perspective(PerspectiveProjection {
fov: 40.0_f32.to_radians(),
fov: THUMBNAIL_VERTICAL_FOV,
..default()
}),
))
@@ -229,6 +252,7 @@ fn process_thumbnail_studio(
&mesh3d,
&mesh_storage,
&mut camera_transforms,
active.framing,
) {
active.framed = true;
active.post_attach_frames = 0;
@@ -322,6 +346,7 @@ fn process_thumbnail_studio(
.id();
let label = job.source.label().to_string();
let framing = ThumbnailFraming::for_source(&job.source);
let content_spawned = spawn_thumbnail_job_content(
&mut commands,
&mut mesh_storage,
@@ -350,6 +375,7 @@ fn process_thumbnail_studio(
framed: false,
frames_remaining: 0,
wait_frames: 0,
framing,
},
"no renderable meshes",
true,
@@ -369,6 +395,7 @@ fn process_thumbnail_studio(
framed: false,
frames_remaining: 0,
wait_frames: 0,
framing,
});
}
@@ -588,6 +615,7 @@ fn frame_thumbnail_scene(
meshes: &Query<&Mesh3d>,
mesh_assets: &Assets<Mesh>,
camera_transforms: &mut Query<&mut Transform, With<ThumbnailStudioCamera>>,
framing: ThumbnailFraming,
) -> bool {
let mut entities = Vec::new();
collect_descendants(root, children, &mut entities);
@@ -633,8 +661,7 @@ fn frame_thumbnail_scene(
}
let center = (min + max) * 0.5;
let radius = (max - min).length().max(0.25) * 0.5;
let distance = radius / (20.0_f32.to_radians()).tan() * 1.35;
let distance = thumbnail_camera_distance(min, max, framing);
let eye = center + Vec3::new(1.0, 0.75, 1.0).normalize() * distance;
if let Ok(mut transform) = camera_transforms.single_mut() {
@@ -644,6 +671,20 @@ fn frame_thumbnail_scene(
true
}
fn thumbnail_camera_distance(min: Vec3, max: Vec3, framing: ThumbnailFraming) -> f32 {
let bounds_size = max - min;
let (radius, padding) = match framing {
ThumbnailFraming::SceneBounds => {
(bounds_size.length().max(0.25) * 0.5, SCENE_FRAME_PADDING)
}
ThumbnailFraming::MaterialSphere => (
bounds_size.max_element().max(0.5) * 0.5,
MATERIAL_SPHERE_FRAME_PADDING,
),
};
radius / THUMBNAIL_HALF_VERTICAL_FOV.tan() * padding
}
fn collect_descendants(entity: Entity, children: &Query<&Children>, out: &mut Vec<Entity>) {
out.push(entity);
let Ok(child_list) = children.get(entity) else {
@@ -673,3 +714,24 @@ fn aabb_corners(aabb: &Aabb3d) -> [Vec3; 8] {
pub fn model_file_exists(catalog_path: &str) -> bool {
Path::new(catalog_path).is_file()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn material_sphere_framing_fills_more_of_the_thumbnail_with_padding() {
let sphere_radius = 0.65;
let min = Vec3::splat(-sphere_radius);
let max = Vec3::splat(sphere_radius);
let scene_distance = thumbnail_camera_distance(min, max, ThumbnailFraming::SceneBounds);
let material_distance =
thumbnail_camera_distance(min, max, ThumbnailFraming::MaterialSphere);
let projected_radius_fraction =
sphere_radius / (material_distance * THUMBNAIL_HALF_VERTICAL_FOV.tan());
assert!(material_distance < scene_distance * 0.6);
assert!((0.75..0.82).contains(&projected_radius_fraction));
}
}
+54 -3
View File
@@ -3,9 +3,10 @@ use std::path::PathBuf;
use bevy::prelude::*;
use shared::{
ActorId, ActorKind, ActorName, AnimationControllerDesc, AudioListenerDesc, AudioSourceDesc,
BrushDesc, ColliderDesc, EditorVisibility, InspectorOrder, LightDesc, MaterialDesc,
MaterialOverride, ModelRef, ObjectiveMarker, PhysicsBody, PostProcessVolumeDesc,
PrefabInstance, PrefabRef, Primitive, RigidBodyDesc, SceneComposition, StaticMeshRenderer,
AuthoringComponentStates, BrushDesc, ColliderDesc, EditorVisibility, InspectorOrder, LightDesc,
MaterialDesc, MaterialOverride, ModelRef, NavigationArea, NavigationBounds, NavigationLink,
NavigationObstacle, ObjectiveMarker, PhysicsBody, PostProcessVolumeDesc, PrefabInstance,
PrefabRef, Primitive, RigidBodyDesc, SceneComposition, SkinnedMeshRenderer, StaticMeshRenderer,
TeamSpawn, TriggerVolume, WeaponSpawn,
};
#[derive(Debug, Clone)]
@@ -18,6 +19,7 @@ pub struct EditorEntitySnapshot {
pub primitive: Option<Primitive>,
pub brush: Option<BrushDesc>,
pub static_mesh_renderer: Option<StaticMeshRenderer>,
pub skinned_mesh_renderer: Option<SkinnedMeshRenderer>,
pub material: Option<MaterialDesc>,
pub material_override: Option<MaterialOverride>,
pub rigid_body: Option<RigidBodyDesc>,
@@ -36,11 +38,52 @@ pub struct EditorEntitySnapshot {
pub post_process_volume: Option<PostProcessVolumeDesc>,
pub team_spawn: Option<TeamSpawn>,
pub objective: Option<ObjectiveMarker>,
pub navigation_bounds: Option<NavigationBounds>,
pub navigation_obstacle: Option<NavigationObstacle>,
pub navigation_area: Option<NavigationArea>,
pub navigation_link: Option<NavigationLink>,
pub hierarchy_sibling_index: i32,
pub editor_visibility: EditorVisibility,
pub inspector_order: Option<InspectorOrder>,
pub component_states: Option<AuthoringComponentStates>,
pub children: Vec<EditorEntitySnapshot>,
}
/// One reflected component value used by registry-driven editor transactions.
/// `component_id` is stable; `type_path` is retained only to resolve Bevy's
/// reflection adapter for this build.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReflectedComponentValue {
pub component_id: String,
pub type_path: String,
pub ron: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComponentDelta {
pub component_id: String,
pub type_path: String,
pub before: Option<ReflectedComponentValue>,
pub after: Option<ReflectedComponentValue>,
}
/// An atomic add/remove/reset/paste operation. Requirements, dependent removals,
/// and the derived ActorKind hint can be represented as additional deltas.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComponentTransaction {
pub entity: Entity,
pub label: &'static str,
pub deltas: Vec<ComponentDelta>,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct NavigationComponentState {
pub bounds: Option<NavigationBounds>,
pub obstacle: Option<NavigationObstacle>,
pub area: Option<NavigationArea>,
pub link: Option<NavigationLink>,
}
#[derive(Debug, Clone)]
pub struct SiblingChange {
pub entity: Entity,
@@ -174,6 +217,11 @@ pub enum EditorCommand {
old: Option<PostProcessVolumeDesc>,
new: PostProcessVolumeDesc,
},
SetNavigation {
entity: Entity,
old: NavigationComponentState,
new: NavigationComponentState,
},
SetTransformGroup {
entities: Vec<Entity>,
olds: Vec<Transform>,
@@ -239,6 +287,7 @@ pub enum EditorCommand {
entity: Entity,
snapshot: EditorEntitySnapshot,
},
ComponentTransaction(ComponentTransaction),
}
impl EditorCommand {
@@ -266,6 +315,7 @@ impl EditorCommand {
EditorCommand::ApplyBrushCsg { .. } => "Brush CSG",
EditorCommand::SetStaticMeshRenderer { .. } => "Set Static Mesh Renderer",
EditorCommand::SetPostProcessVolume { .. } => "Set Post Process Volume",
EditorCommand::SetNavigation { .. } => "Set Navigation",
EditorCommand::SetTransformGroup { .. } => "Move Selection",
EditorCommand::Reparent { .. } => "Reparent",
EditorCommand::SetActorKind { .. } => "Set Actor Kind",
@@ -283,6 +333,7 @@ impl EditorCommand {
} => "Unpack Prefab Layer",
EditorCommand::AddComponent { .. } => "Add Component",
EditorCommand::RemoveComponent { .. } => "Remove Component",
EditorCommand::ComponentTransaction(transaction) => transaction.label,
}
}
}
+511 -8
View File
@@ -1,14 +1,20 @@
use std::collections::HashSet;
use bevy::ecs::reflect::ReflectComponent;
use bevy::prelude::*;
use bevy::reflect::serde::{TypedReflectDeserializer, TypedReflectSerializer};
use bevy::reflect::std_traits::ReflectDefault;
use bevy::world_serialization::WorldInstance;
use serde::de::DeserializeSeed;
use shared::{
infer_actor_kind, ActorId, ActorKind, ActorName, AnimationControllerDesc, AudioListenerDesc,
AudioSourceDesc, BrushDesc, ColliderDesc, EditorVisibility, HierarchySiblingIndex,
HydratedPrefabMember, HydratedPrefabReady, InspectorOrder, LevelObject, LightDesc,
MaterialDesc, MaterialOverride, ModelRef, ObjectiveMarker, PhysicsBody, PlayerSpawn,
AudioSourceDesc, AuthoringComponentStates, BrushDesc, ColliderDesc, EditorVisibility,
HierarchySiblingIndex, HydratedPrefabMember, HydratedPrefabReady, InspectorOrder, LevelObject,
LightDesc, MaterialDesc, MaterialOverride, ModelRef, NavigationArea, NavigationBounds,
NavigationLink, NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn,
PostProcessVolumeDesc, PrefabHydrationBlocked, PrefabInstance, PrefabRef, Primitive,
RigidBodyDesc, SceneComposition, StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn,
RigidBodyDesc, SceneComposition, SkinnedMeshRenderer, StaticMeshRenderer, TeamSpawn,
TriggerVolume, WeaponSpawn,
};
use crate::scene_io::{SceneIo, SceneIoRequest};
@@ -22,7 +28,10 @@ use crate::ui::selection_ops::is_mutable_level_object;
use crate::ui::{egui_captures_keyboard_from_world, UiState};
mod commands;
pub use commands::{EditorCommand, EditorEntitySnapshot, PrefabEditState, SiblingChange};
pub use commands::{
ComponentDelta, ComponentTransaction, EditorCommand, EditorEntitySnapshot,
NavigationComponentState, PrefabEditState, ReflectedComponentValue, SiblingChange,
};
#[derive(Resource, Debug, Default)]
pub struct EditorHistory {
@@ -138,6 +147,7 @@ pub fn snapshot_entity(world: &World, entity: Entity) -> Option<EditorEntitySnap
primitive: entity_ref.get::<Primitive>().cloned(),
brush: entity_ref.get::<BrushDesc>().cloned(),
static_mesh_renderer: entity_ref.get::<StaticMeshRenderer>().cloned(),
skinned_mesh_renderer: entity_ref.get::<SkinnedMeshRenderer>().cloned(),
material: entity_ref.get::<MaterialDesc>().cloned(),
material_override: entity_ref.get::<MaterialOverride>().cloned(),
rigid_body: entity_ref.get::<RigidBodyDesc>().cloned(),
@@ -156,6 +166,10 @@ pub fn snapshot_entity(world: &World, entity: Entity) -> Option<EditorEntitySnap
post_process_volume: entity_ref.get::<PostProcessVolumeDesc>().cloned(),
team_spawn: entity_ref.get::<TeamSpawn>().cloned(),
objective: entity_ref.get::<ObjectiveMarker>().cloned(),
navigation_bounds: entity_ref.get::<NavigationBounds>().cloned(),
navigation_obstacle: entity_ref.get::<NavigationObstacle>().cloned(),
navigation_area: entity_ref.get::<NavigationArea>().cloned(),
navigation_link: entity_ref.get::<NavigationLink>().cloned(),
hierarchy_sibling_index: entity_ref
.get::<HierarchySiblingIndex>()
.map(|index| index.0)
@@ -164,6 +178,8 @@ pub fn snapshot_entity(world: &World, entity: Entity) -> Option<EditorEntitySnap
.get::<EditorVisibility>()
.copied()
.unwrap_or_default(),
inspector_order: entity_ref.get::<InspectorOrder>().cloned(),
component_states: entity_ref.get::<AuthoringComponentStates>().cloned(),
children,
})
}
@@ -204,6 +220,9 @@ fn spawn_snapshot_with_parent(
if let Some(renderer) = &snapshot.static_mesh_renderer {
entity_mut.insert(renderer.clone());
}
if let Some(renderer) = &snapshot.skinned_mesh_renderer {
entity_mut.insert(renderer.clone());
}
if let Some(material) = &snapshot.material {
entity_mut.insert(material.clone());
}
@@ -258,8 +277,26 @@ fn spawn_snapshot_with_parent(
if let Some(objective) = &snapshot.objective {
entity_mut.insert(objective.clone());
}
if let Some(bounds) = &snapshot.navigation_bounds {
entity_mut.insert(bounds.clone());
}
if let Some(obstacle) = &snapshot.navigation_obstacle {
entity_mut.insert(obstacle.clone());
}
if let Some(area) = &snapshot.navigation_area {
entity_mut.insert(area.clone());
}
if let Some(link) = &snapshot.navigation_link {
entity_mut.insert(link.clone());
}
entity_mut.insert(HierarchySiblingIndex(snapshot.hierarchy_sibling_index));
entity_mut.insert(snapshot.editor_visibility);
if let Some(order) = &snapshot.inspector_order {
entity_mut.insert(order.clone());
}
if let Some(states) = &snapshot.component_states {
entity_mut.insert(states.clone());
}
if let Some(parent) = parent {
entity_mut.insert(ChildOf(parent));
}
@@ -561,6 +598,31 @@ pub fn set_post_process_volume_with_history(
);
}
pub fn navigation_component_state(world: &World, entity: Entity) -> NavigationComponentState {
NavigationComponentState {
bounds: world.get::<NavigationBounds>(entity).cloned(),
obstacle: world.get::<NavigationObstacle>(entity).cloned(),
area: world.get::<NavigationArea>(entity).cloned(),
link: world.get::<NavigationLink>(entity).cloned(),
}
}
pub fn set_navigation_with_history(
world: &mut World,
entity: Entity,
new: NavigationComponentState,
) {
if !is_mutable_level_object(world, entity) {
return;
}
let old = navigation_component_state(world, entity);
if old == new {
return;
}
apply_navigation_state(world, entity, &new);
push_history(world, EditorCommand::SetNavigation { entity, old, new });
}
pub fn set_physics_with_history(world: &mut World, entity: Entity, new: PhysicsBody) {
if !is_mutable_level_object(world, entity) {
return;
@@ -818,6 +880,7 @@ pub fn group_selection_with_history(world: &mut World, entities: &[Entity]) {
primitive: None,
brush: None,
static_mesh_renderer: None,
skinned_mesh_renderer: None,
material: None,
material_override: None,
rigid_body: None,
@@ -836,8 +899,18 @@ pub fn group_selection_with_history(world: &mut World, entities: &[Entity]) {
post_process_volume: None,
team_spawn: None,
objective: None,
navigation_bounds: None,
navigation_obstacle: None,
navigation_area: None,
navigation_link: None,
hierarchy_sibling_index: next_sibling_index(world, None),
editor_visibility: EditorVisibility::default(),
inspector_order: None,
component_states: None,
children: Vec::new(),
};
let group = spawn_snapshot(world, &snapshot);
@@ -868,6 +941,7 @@ pub fn create_empty_child_with_history(world: &mut World, parent: Entity) {
primitive: None,
brush: None,
static_mesh_renderer: None,
skinned_mesh_renderer: None,
material: None,
material_override: None,
rigid_body: None,
@@ -886,8 +960,18 @@ pub fn create_empty_child_with_history(world: &mut World, parent: Entity) {
post_process_volume: None,
team_spawn: None,
objective: None,
navigation_bounds: None,
navigation_obstacle: None,
navigation_area: None,
navigation_link: None,
hierarchy_sibling_index: next_sibling_index(world, Some(parent)),
editor_visibility: EditorVisibility::default(),
inspector_order: None,
component_states: None,
children: Vec::new(),
};
let entity = spawn_snapshot_with_parent(world, &snapshot, Some(parent));
@@ -1235,6 +1319,215 @@ pub fn apply_actor_kind(world: &mut World, entity: Entity, kind: ActorKind) {
}
}
pub const ACTOR_KIND_COMPONENT_ID: &str = "core.actor_kind";
pub const ACTOR_KIND_TYPE_PATH: &str = "shared::components::ActorKind";
/// Captures any reflected component without adding a typed history branch.
pub fn capture_reflected_component(
world: &World,
entity: Entity,
component_id: &str,
type_path: &str,
) -> Result<Option<ReflectedComponentValue>, String> {
let entity_ref = world
.get_entity(entity)
.map_err(|_| format!("entity {entity:?} no longer exists"))?;
let app_registry = world
.get_resource::<AppTypeRegistry>()
.ok_or_else(|| "AppTypeRegistry is unavailable".to_string())?;
let type_registry = app_registry.read();
let registration = type_registry
.get_with_type_path(type_path)
.ok_or_else(|| format!("component type `{type_path}` is not registered"))?;
let reflect_component = registration
.data::<ReflectComponent>()
.ok_or_else(|| format!("component `{type_path}` has no ReflectComponent adapter"))?;
let Some(value) = reflect_component.reflect(entity_ref) else {
return Ok(None);
};
let ron = ron::ser::to_string(&TypedReflectSerializer::new(value, &type_registry))
.map_err(|error| format!("could not serialize `{type_path}`: {error}"))?;
Ok(Some(ReflectedComponentValue {
component_id: component_id.to_string(),
type_path: type_path.to_string(),
ron,
}))
}
/// Applies or removes one reflected component value.
pub fn apply_reflected_component(
world: &mut World,
entity: Entity,
type_path: &str,
value: Option<&ReflectedComponentValue>,
) -> Result<(), String> {
if world.get_entity(entity).is_err() {
return Err(format!("entity {entity:?} no longer exists"));
}
world.resource_scope(|world, app_registry: Mut<AppTypeRegistry>| {
let type_registry = app_registry.read();
let registration = type_registry
.get_with_type_path(type_path)
.ok_or_else(|| format!("component type `{type_path}` is not registered"))?;
let reflect_component = registration
.data::<ReflectComponent>()
.cloned()
.ok_or_else(|| format!("component `{type_path}` has no ReflectComponent adapter"))?;
match value {
Some(value) => {
if value.type_path != type_path {
return Err(format!(
"clipboard type `{}` does not match `{type_path}`",
value.type_path
));
}
let mut deserializer = ron::de::Deserializer::from_str(&value.ron)
.map_err(|error| error.to_string())?;
let reflected = TypedReflectDeserializer::new(registration, &type_registry)
.deserialize(&mut deserializer)
.map_err(|error| error.to_string())?;
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(),
&type_registry,
);
}
}
None => reflect_component.remove(&mut world.entity_mut(entity)),
}
Ok(())
})
}
/// Inserts the reflected `Default` for a registered authoring component.
pub fn apply_reflected_default(
world: &mut World,
entity: Entity,
type_path: &str,
) -> Result<(), String> {
world.resource_scope(|world, app_registry: Mut<AppTypeRegistry>| {
let type_registry = app_registry.read();
let registration = type_registry
.get_with_type_path(type_path)
.ok_or_else(|| format!("component type `{type_path}` is not registered"))?;
let reflect_component = registration
.data::<ReflectComponent>()
.cloned()
.ok_or_else(|| format!("component `{type_path}` has no ReflectComponent adapter"))?;
let default = registration
.data::<ReflectDefault>()
.ok_or_else(|| format!("component `{type_path}` has no reflected Default"))?
.default();
let exists = reflect_component.reflect(world.entity(entity)).is_some();
if exists {
reflect_component.apply(world.entity_mut(entity), default.as_ref());
} else {
reflect_component.insert(
&mut world.entity_mut(entity),
default.as_ref(),
&type_registry,
);
}
Ok(())
})
}
pub fn sync_actor_kind_hint(world: &mut World, entity: Entity) {
let kind = world
.get_entity(entity)
.ok()
.and_then(infer_actor_kind)
.unwrap_or(ActorKind::Empty);
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
entity_mut.insert(kind);
}
}
/// Executes one atomic reflected component edit and records all changed values,
/// including the derived ActorKind presentation hint, as a single history item.
pub fn reflected_component_transaction(
world: &mut World,
entity: Entity,
label: &'static str,
component_id: &str,
type_path: &str,
edit: impl FnOnce(&mut World, Entity) -> Result<(), String>,
) -> Result<(), String> {
if !is_mutable_level_object(world, entity) {
return Err("actor is not editable".to_string());
}
let tracked = [
(component_id, type_path),
(ACTOR_KIND_COMPONENT_ID, ACTOR_KIND_TYPE_PATH),
];
let before = tracked
.iter()
.map(|(id, path)| capture_reflected_component(world, entity, id, path))
.collect::<Result<Vec<_>, _>>()?;
if let Err(error) = edit(world, entity) {
for ((_, path), value) in tracked.iter().zip(before.iter()) {
let _ = apply_reflected_component(world, entity, path, value.as_ref());
}
return Err(error);
}
sync_actor_kind_hint(world, entity);
let after = tracked
.iter()
.map(|(id, path)| capture_reflected_component(world, entity, id, path))
.collect::<Result<Vec<_>, _>>()?;
let deltas = tracked
.iter()
.zip(before)
.zip(after)
.filter_map(|(((id, path), before), after)| {
(before != after).then(|| ComponentDelta {
component_id: (*id).to_string(),
type_path: (*path).to_string(),
before,
after,
})
})
.collect::<Vec<_>>();
if !deltas.is_empty() {
push_history(
world,
EditorCommand::ComponentTransaction(ComponentTransaction {
entity,
label,
deltas,
}),
);
}
Ok(())
}
fn apply_component_transaction(
world: &mut World,
transaction: &ComponentTransaction,
use_after: bool,
) {
for delta in &transaction.deltas {
let value = if use_after {
delta.after.as_ref()
} else {
delta.before.as_ref()
};
if let Err(error) =
apply_reflected_component(world, transaction.entity, &delta.type_path, value)
{
world.resource_mut::<EditorHistory>().status = format!(
"{} partially failed for {}: {error}",
transaction.label, delta.component_id
);
break;
}
}
}
pub fn set_scene_composition_with_history(world: &mut World, new: SceneComposition) {
let old = world.resource::<SceneComposition>().clone();
if old == new {
@@ -1372,6 +1665,9 @@ fn undo_command(world: &mut World, command: &mut EditorCommand) {
EditorCommand::SetPostProcessVolume { entity, old, .. } => {
apply_post_process_volume(world, *entity, old);
}
EditorCommand::SetNavigation { entity, old, .. } => {
apply_navigation_state(world, *entity, old);
}
EditorCommand::SetPhysics { entity, old, .. } => {
apply_physics(world, *entity, old);
}
@@ -1485,6 +1781,9 @@ fn undo_command(world: &mut World, command: &mut EditorCommand) {
EditorCommand::RemoveComponent { entity, snapshot } => {
apply_authored_components(world, *entity, snapshot);
}
EditorCommand::ComponentTransaction(transaction) => {
apply_component_transaction(world, transaction, false);
}
}
}
@@ -1573,6 +1872,9 @@ fn redo_command(world: &mut World, command: &mut EditorCommand) {
entity_mut.insert(new.clone());
}
}
EditorCommand::SetNavigation { entity, new, .. } => {
apply_navigation_state(world, *entity, new);
}
EditorCommand::SetPhysics { entity, new, .. } => {
if let Ok(mut entity_mut) = world.get_entity_mut(*entity) {
entity_mut.insert(new.clone());
@@ -1706,6 +2008,9 @@ fn redo_command(world: &mut World, command: &mut EditorCommand) {
EditorCommand::RemoveComponent { entity, snapshot } => {
remove_authored_components(world, *entity, snapshot);
}
EditorCommand::ComponentTransaction(transaction) => {
apply_component_transaction(world, transaction, true);
}
}
}
@@ -1862,6 +2167,45 @@ fn apply_post_process_volume(
}
}
fn apply_navigation_state(world: &mut World, entity: Entity, state: &NavigationComponentState) {
let has_navigation = state.bounds.is_some()
|| state.obstacle.is_some()
|| state.area.is_some()
|| state.link.is_some();
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
entity_mut
.remove::<NavigationBounds>()
.remove::<NavigationObstacle>()
.remove::<NavigationArea>()
.remove::<NavigationLink>();
if let Some(value) = &state.bounds {
entity_mut.insert(value.clone());
}
if let Some(value) = &state.obstacle {
entity_mut.insert(value.clone());
}
if let Some(value) = &state.area {
entity_mut.insert(value.clone());
}
if let Some(value) = &state.link {
entity_mut.insert(value.clone());
}
if has_navigation {
entity_mut.insert(ActorKind::Navigation);
}
}
if !has_navigation {
let fallback = world
.get_entity(entity)
.ok()
.and_then(infer_actor_kind)
.unwrap_or(ActorKind::Empty);
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
entity_mut.insert(fallback);
}
}
}
fn apply_physics(world: &mut World, entity: Entity, physics: &Option<PhysicsBody>) {
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
match physics {
@@ -1986,6 +2330,9 @@ fn apply_authored_components(world: &mut World, entity: Entity, snapshot: &Edito
if let Some(v) = &snapshot.static_mesh_renderer {
entity_mut.insert(v.clone());
}
if let Some(v) = &snapshot.skinned_mesh_renderer {
entity_mut.insert(v.clone());
}
if let Some(v) = &snapshot.material {
entity_mut.insert(v.clone());
}
@@ -2040,6 +2387,24 @@ fn apply_authored_components(world: &mut World, entity: Entity, snapshot: &Edito
if let Some(v) = &snapshot.objective {
entity_mut.insert(v.clone());
}
if let Some(v) = &snapshot.navigation_bounds {
entity_mut.insert(v.clone());
}
if let Some(v) = &snapshot.navigation_obstacle {
entity_mut.insert(v.clone());
}
if let Some(v) = &snapshot.navigation_area {
entity_mut.insert(v.clone());
}
if let Some(v) = &snapshot.navigation_link {
entity_mut.insert(v.clone());
}
if let Some(v) = &snapshot.inspector_order {
entity_mut.insert(v.clone());
}
if let Some(v) = &snapshot.component_states {
entity_mut.insert(v.clone());
}
}
}
@@ -2061,6 +2426,9 @@ fn remove_authored_components(world: &mut World, entity: Entity, snapshot: &Edit
if snapshot.static_mesh_renderer.is_some() {
entity_mut.remove::<StaticMeshRenderer>();
}
if snapshot.skinned_mesh_renderer.is_some() {
entity_mut.remove::<SkinnedMeshRenderer>();
}
if snapshot.material.is_some() {
entity_mut.remove::<MaterialDesc>();
}
@@ -2115,6 +2483,24 @@ fn remove_authored_components(world: &mut World, entity: Entity, snapshot: &Edit
if snapshot.objective.is_some() {
entity_mut.remove::<ObjectiveMarker>();
}
if snapshot.navigation_bounds.is_some() {
entity_mut.remove::<NavigationBounds>();
}
if snapshot.navigation_obstacle.is_some() {
entity_mut.remove::<NavigationObstacle>();
}
if snapshot.navigation_area.is_some() {
entity_mut.remove::<NavigationArea>();
}
if snapshot.navigation_link.is_some() {
entity_mut.remove::<NavigationLink>();
}
if snapshot.inspector_order.is_some() {
entity_mut.remove::<InspectorOrder>();
}
if snapshot.component_states.is_some() {
entity_mut.remove::<AuthoringComponentStates>();
}
}
if removed_dedicated_audio_kind {
let fallback = world
@@ -2383,6 +2769,88 @@ mod tests {
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
#[derive(Component, Reflect, Default, Debug, Clone, PartialEq)]
#[reflect(Component, Default)]
struct StaticExtensionFixture {
value: u32,
}
#[test]
fn reflected_extension_component_transaction_round_trips_atomically() {
let mut app = App::new();
app.register_type::<ActorKind>()
.register_type::<StaticExtensionFixture>();
let world = app.world_mut();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let entity = world
.spawn((LevelObject, ActorKind::Light, Transform::default()))
.id();
let type_path = std::any::type_name::<StaticExtensionFixture>();
reflected_component_transaction(
world,
entity,
"Add Fixture",
"game.static_extension_fixture",
type_path,
|world, entity| {
world
.entity_mut(entity)
.insert(StaticExtensionFixture { value: 42 });
Ok(())
},
)
.unwrap();
assert_eq!(
world.get::<StaticExtensionFixture>(entity).unwrap().value,
42
);
assert_eq!(world.get::<ActorKind>(entity), Some(&ActorKind::Empty));
assert_eq!(world.resource::<EditorHistory>().undo_depth(), 1);
apply_command_undo(world);
assert!(world.get::<StaticExtensionFixture>(entity).is_none());
assert_eq!(world.get::<ActorKind>(entity), Some(&ActorKind::Light));
apply_command_redo(world);
assert_eq!(
world.get::<StaticExtensionFixture>(entity).unwrap().value,
42
);
assert_eq!(world.get::<ActorKind>(entity), Some(&ActorKind::Empty));
}
#[test]
fn snapshots_preserve_component_order_and_independent_active_state() {
let mut world = World::new();
let mut order = InspectorOrder::default();
order.component_ids = vec![shared::AUTHORING_COMPONENT_LIGHT.to_string()];
let mut states = AuthoringComponentStates::default();
states.set_component_active(shared::COMPONENT_LIGHT_DESC, false);
let entity = world
.spawn((
LevelObject,
ActorKind::Light,
Transform::default(),
LightDesc::default(),
order.clone(),
states.clone(),
))
.id();
let snapshot = snapshot_entity(&world, entity).unwrap();
world.entity_mut(entity).despawn();
let restored = spawn_snapshot(&mut world, &snapshot);
assert_eq!(world.get::<InspectorOrder>(restored), Some(&order));
assert_eq!(
world.get::<AuthoringComponentStates>(restored),
Some(&states)
);
}
fn animation_controller(state_id: &str, crossfade_seconds: f32) -> AnimationControllerDesc {
AnimationControllerDesc {
skeleton: Some(
@@ -2420,7 +2888,7 @@ mod tests {
let entity = world
.spawn((
LevelObject,
ActorKind::ImportedModel,
ActorKind::SkinnedMesh,
Transform::IDENTITY,
old.clone(),
))
@@ -2439,6 +2907,36 @@ mod tests {
assert_eq!(world.get::<AnimationControllerDesc>(entity), Some(&new));
}
#[test]
fn navigation_component_history_round_trips_and_preserves_kind() {
let mut world = World::new();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let entity = world
.spawn((LevelObject, ActorKind::Empty, Transform::IDENTITY))
.id();
let bounds = NavigationBounds::default();
set_navigation_with_history(
&mut world,
entity,
NavigationComponentState {
bounds: Some(bounds.clone()),
..Default::default()
},
);
assert_eq!(world.get::<NavigationBounds>(entity), Some(&bounds));
assert_eq!(world.get::<ActorKind>(entity), Some(&ActorKind::Navigation));
apply_command_undo(&mut world);
assert!(world.get::<NavigationBounds>(entity).is_none());
assert_eq!(world.get::<ActorKind>(entity), Some(&ActorKind::Empty));
apply_command_redo(&mut world);
assert_eq!(world.get::<NavigationBounds>(entity), Some(&bounds));
assert_eq!(world.get::<ActorKind>(entity), Some(&ActorKind::Navigation));
}
#[test]
fn undoing_a_new_animation_controller_removes_the_component() {
let mut world = World::new();
@@ -2446,7 +2944,7 @@ mod tests {
world.init_resource::<SceneIo>();
let controller = animation_controller("idle", 0.2);
let entity = world
.spawn((LevelObject, ActorKind::ImportedModel, Transform::IDENTITY))
.spawn((LevelObject, ActorKind::SkinnedMesh, Transform::IDENTITY))
.id();
set_animation_controller_with_history(&mut world, entity, controller.clone());
@@ -2467,9 +2965,10 @@ mod tests {
let source = world
.spawn((
LevelObject,
ActorKind::ImportedModel,
ActorKind::SkinnedMesh,
Name::new("Animated Robot"),
Transform::from_xyz(1.0, 2.0, 3.0),
SkinnedMeshRenderer::new("assets/models/robot.glb").with_asset_id("robot-asset"),
controller.clone(),
))
.id();
@@ -2486,6 +2985,10 @@ mod tests {
world.get::<Name>(respawned).map(Name::as_str),
Some("Animated Robot")
);
assert_eq!(
world.get::<SkinnedMeshRenderer>(respawned),
Some(&SkinnedMeshRenderer::new("assets/models/robot.glb").with_asset_id("robot-asset"))
);
}
#[test]
+13 -4
View File
@@ -6,7 +6,10 @@ use bevy::window::WindowRef;
use game::player::PlayerCamera;
use protocol::PlayerInputIntent;
use settings::SimTuning;
use shared::{inspector_component_active, InspectorOrder, PlayerSpawn, COMPONENT_PLAYER_SPAWN};
use shared::{
authoring_component_active, AuthoringComponentStates, InspectorOrder, PlayerSpawn,
COMPONENT_PLAYER_SPAWN,
};
use sim::{Crouching, Grounded, JumpState, Player, PlayerVelocity};
use crate::render_target::ViewportRenderTarget;
@@ -66,10 +69,16 @@ fn bootstrap_player_on_play(world: &mut World) {
.unwrap_or_else(|| SimTuning::from_physics(&settings::PhysicsSettings::default()));
let spawn = world
.query_filtered::<(&Transform, Option<&InspectorOrder>), With<PlayerSpawn>>()
.query_filtered::<(
&Transform,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
), With<PlayerSpawn>>()
.iter(world)
.filter(|(_, order)| inspector_component_active(*order, COMPONENT_PLAYER_SPAWN))
.map(|(transform, _)| transform)
.filter(|(_, states, legacy_order)| {
authoring_component_active(*states, *legacy_order, COMPONENT_PLAYER_SPAWN)
})
.map(|(transform, _, _)| transform)
.next()
.copied()
.unwrap_or_else(default_player_spawn);
+5 -1
View File
@@ -377,7 +377,11 @@ fn apply_project_settings_changes(
settings: Res<ProjectSettings>,
tuning: ResMut<settings::SimTuning>,
scene_suns: Query<
(&shared::LightDesc, Option<&shared::InspectorOrder>),
(
&shared::LightDesc,
Option<&shared::AuthoringComponentStates>,
Option<&shared::InspectorOrder>,
),
With<shared::LevelObject>,
>,
project_suns: Query<(&mut DirectionalLight, &mut Visibility), With<shared::ProjectSun>>,
+112 -48
View File
@@ -6,17 +6,19 @@ use bevy::ecs::system::SystemState;
use bevy::prelude::*;
use bevy::window::PrimaryWindow;
use bevy::world_serialization::serde::WorldDeserializer;
use bevy::world_serialization::{DynamicWorld, DynamicWorldBuilder, WorldInstance};
use bevy::world_serialization::{DynamicWorld, DynamicWorldBuilder, WorldFilter, WorldInstance};
use scene::{document::SceneDocument, strip_schema_version, validate_level_text};
use serde::de::DeserializeSeed;
use shared::{
infer_actor_kind, validate_actor, ActorId, ActorKind, ActorName, ActorValidationError,
AnimationControllerDesc, AudioListenerDesc, AudioSourceDesc, BrushDesc, ColliderDesc,
EditorVisibility, HierarchySiblingIndex, HydratedPrefabMember, HydratedPrefabReady,
InspectorOrder, LevelObject, LightDesc, MaterialDesc, MaterialOverride, ModelRef,
ObjectiveMarker, PhysicsBody, PlayerSpawn, PostProcessVolumeDesc, PrefabHydrationBlocked,
PrefabInstance, PrefabRef, Primitive, RigidBodyDesc, SceneComposition, StaticMeshRenderer,
TeamSpawn, TriggerVolume, WeaponSpawn,
AuthoringComponentStates, EditorVisibility, HierarchySiblingIndex, HydratedPrefabMember,
HydratedPrefabReady, InspectorOrder, LevelObject, LightDesc, PrefabHydrationBlocked,
PrefabInstance, PrefabRef, SceneComposition,
};
#[cfg(test)]
use shared::{
AnimationControllerDesc, AudioSourceDesc, BrushDesc, ColliderDesc, SkinnedMeshRenderer,
};
use crate::assets::{import_external_assets, EditorAssets, IMPORTABLE_ASSET_EXTENSIONS};
@@ -1006,6 +1008,27 @@ fn format_actor_validation(err: ActorValidationError) -> String {
ActorValidationError::ImportedModelHasStaticMeshRenderer => {
"Save failed: ImportedModel actor cannot have StaticMeshRenderer".into()
}
ActorValidationError::SkinnedMeshMissingRenderer => {
"Save failed: SkinnedMesh actor requires SkinnedMeshRenderer".into()
}
ActorValidationError::SkinnedMeshInvalidRenderer => {
"Save failed: SkinnedMeshRenderer requires a model source path".into()
}
ActorValidationError::SkinnedMeshHasPrimitive => {
"Save failed: SkinnedMesh actor cannot have Primitive".into()
}
ActorValidationError::SkinnedMeshHasStaticMeshRenderer => {
"Save failed: SkinnedMesh actor cannot have StaticMeshRenderer".into()
}
ActorValidationError::SkinnedMeshHasModelRef => {
"Save failed: SkinnedMesh actor cannot have ModelRef".into()
}
ActorValidationError::SkinnedMeshRendererActorKindMismatch => {
"Save failed: SkinnedMeshRenderer requires ActorKind::SkinnedMesh".into()
}
ActorValidationError::ConflictingGeometrySources => {
"Save failed: actor has more than one primary geometry source component".into()
}
ActorValidationError::LightMissingLightDesc => {
"Save failed: Light actor requires LightDesc".into()
}
@@ -1048,8 +1071,9 @@ fn format_actor_validation(err: ActorValidationError) -> String {
ActorValidationError::AudioListenerInvalidEarGap => {
"Save failed: audio listener ear gap must be positive and finite".into()
}
ActorValidationError::AnimationControllerMissingModelRef => {
"Save failed: animation controller requires ModelRef on the same actor".into()
ActorValidationError::AnimationControllerMissingSkinnedMeshRenderer => {
"Save failed: animation controller requires SkinnedMeshRenderer on the same actor"
.into()
}
ActorValidationError::AnimationControllerMissingSkeleton => {
"Save failed: animation controller requires an assigned skeleton".into()
@@ -1093,6 +1117,9 @@ fn format_actor_validation(err: ActorValidationError) -> String {
ActorValidationError::PostProcessVolumeInvalidOverrideScalar => {
"Save failed: post-process volume override contains invalid scalar".into()
}
ActorValidationError::InvalidNavigation(message) => {
format!("Save failed: invalid navigation authoring: {message}")
}
}
}
@@ -1179,39 +1206,26 @@ fn serialize_entities_inner_with_resources(
let result = (|| {
let ron = {
let registry = world.resource::<AppTypeRegistry>().read();
let mut component_filter = WorldFilter::deny_all()
.allow::<Name>()
.allow::<Transform>()
.allow::<ChildOf>()
.allow::<LevelObject>()
.allow::<ActorId>()
.allow::<ActorName>()
.allow::<HierarchySiblingIndex>()
.allow::<EditorVisibility>();
let component_registry = world
.get_resource::<crate::ui::component_registry::EditorComponentRegistry>()
.cloned()
.unwrap_or_default();
for descriptor in &component_registry.descriptors {
if let Some(registration) = registry.get_with_type_path(descriptor.type_name) {
component_filter = component_filter.allow_by_id(registration.type_id());
}
}
let builder = DynamicWorldBuilder::from_world(world, &registry)
.deny_all()
.allow_component::<Name>()
.allow_component::<Transform>()
.allow_component::<ChildOf>()
.allow_component::<LevelObject>()
.allow_component::<ActorId>()
.allow_component::<ActorName>()
.allow_component::<ActorKind>()
.allow_component::<InspectorOrder>()
.allow_component::<Primitive>()
.allow_component::<BrushDesc>()
.allow_component::<StaticMeshRenderer>()
.allow_component::<MaterialDesc>()
.allow_component::<MaterialOverride>()
.allow_component::<RigidBodyDesc>()
.allow_component::<ColliderDesc>()
.allow_component::<PhysicsBody>()
.allow_component::<LightDesc>()
.allow_component::<AnimationControllerDesc>()
.allow_component::<AudioSourceDesc>()
.allow_component::<AudioListenerDesc>()
.allow_component::<PlayerSpawn>()
.allow_component::<ModelRef>()
.allow_component::<PrefabRef>()
.allow_component::<PrefabInstance>()
.allow_component::<WeaponSpawn>()
.allow_component::<TriggerVolume>()
.allow_component::<PostProcessVolumeDesc>()
.allow_component::<TeamSpawn>()
.allow_component::<ObjectiveMarker>()
.allow_component::<HierarchySiblingIndex>()
.allow_component::<EditorVisibility>()
.with_component_filter(component_filter)
.extract_entities(entities.into_iter());
let scene = if include_scene_resources {
builder
@@ -1781,7 +1795,14 @@ fn finalize_scene_load(world: &mut World) {
let mut state: SystemState<(
Res<settings::ProjectSettings>,
Query<(&LightDesc, Option<&InspectorOrder>), With<LevelObject>>,
Query<
(
&LightDesc,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
),
With<LevelObject>,
>,
Query<(&mut DirectionalLight, &mut Visibility), With<shared::ProjectSun>>,
)> = SystemState::new(world);
@@ -1801,10 +1822,8 @@ fn backfill_missing_actor_kinds(world: &mut World) {
let Ok(entity_ref) = world.get_entity(entity) else {
continue;
};
if entity_ref.get::<ActorKind>().is_some() {
continue;
}
if let Some(kind) = infer_actor_kind(entity_ref) {
let current = entity_ref.get::<ActorKind>().copied();
if let Some(kind) = infer_actor_kind(entity_ref).filter(|kind| current != Some(*kind)) {
world.entity_mut(entity).insert(kind);
}
}
@@ -1856,6 +1875,12 @@ mod tests {
struct NoAssetLoads;
#[derive(Component, Reflect, Default)]
#[reflect(Component, Default)]
struct RegisteredSceneExtension {
value: u32,
}
impl LoadFromPath for NoAssetLoads {
fn load_from_path_erased(
&mut self,
@@ -1866,6 +1891,43 @@ mod tests {
}
}
#[test]
fn registry_registered_extension_is_included_in_scene_persistence() {
let mut app = App::new();
app.register_type::<Name>()
.register_type::<Transform>()
.register_type::<LevelObject>()
.register_type::<ActorKind>()
.register_type::<SceneComposition>()
.register_type::<RegisteredSceneExtension>();
let mut component_registry =
crate::ui::component_registry::EditorComponentRegistry::default();
let mut descriptor = component_registry.descriptors[0].clone();
descriptor.id = "game.registered_scene_extension";
descriptor.type_name = std::any::type_name::<RegisteredSceneExtension>();
descriptor.display_name = "Registered Scene Extension";
descriptor.recommended = &[];
descriptor.conflicts_with = &[];
component_registry.register(descriptor).unwrap();
app.insert_resource(component_registry);
app.insert_resource(SceneComposition::default());
let entity = app
.world_mut()
.spawn((
Name::new("Extension"),
Transform::default(),
LevelObject,
ActorKind::Empty,
RegisteredSceneExtension { value: 73 },
))
.id();
let text = serialize_entities_inner(app.world_mut(), vec![entity]).unwrap();
assert!(text.contains(std::any::type_name::<RegisteredSceneExtension>()));
assert!(text.contains("value: 73") || text.contains("value:73"));
}
#[test]
fn restored_recovery_remains_available_until_save_or_discard() {
let authored = PathBuf::from("assets/levels/authored.scn.ron");
@@ -2152,8 +2214,8 @@ mod tests {
Transform::IDENTITY,
LevelObject,
ActorId::new("animated-model"),
ActorKind::ImportedModel,
ModelRef::new(source_path),
ActorKind::SkinnedMesh,
SkinnedMeshRenderer::new(source_path),
controller.clone(),
AnimationPlayer::default(),
AnimationGraphHandle::default(),
@@ -2171,6 +2233,8 @@ mod tests {
let decoded: AnimationControllerDesc = ron::from_str(&component.ron).unwrap();
assert_eq!(decoded, controller);
assert!(text.contains("shared::animation::SkinnedMeshRenderer"));
assert!(!text.contains("shared::components::ModelRef"));
assert!(!text.contains("AnimationPlayer"));
assert!(!text.contains("AnimationGraphHandle"));
assert!(!text.contains("AnimationTransitions"));
+11 -6
View File
@@ -5,7 +5,7 @@ mod transform;
use bevy::prelude::*;
use bevy_egui::egui;
use egui_phosphor_icons::icons;
use shared::{ActorId, ActorKind, ActorName, HydratedPrefabMember, LevelObject};
use shared::{infer_actor_kind, ActorId, ActorKind, ActorName, HydratedPrefabMember, LevelObject};
use crate::ext::extensibility::ActorInspectorSectionRegistry;
use crate::ui::inspector;
@@ -29,9 +29,8 @@ pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity
return;
}
let kind = entity_ref
.get::<ActorKind>()
.copied()
let kind = infer_actor_kind(entity_ref)
.or_else(|| entity_ref.get::<ActorKind>().copied())
.unwrap_or(ActorKind::Empty);
egui::Frame::new()
@@ -111,6 +110,7 @@ pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity
match kind {
ActorKind::StaticMesh
| ActorKind::SkinnedMesh
| ActorKind::Brush
| ActorKind::ImportedModel
| ActorKind::Light
@@ -123,7 +123,8 @@ pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity
| ActorKind::TeamSpawn
| ActorKind::Objective
| ActorKind::AudioSource
| ActorKind::AudioListener => {
| ActorKind::AudioListener
| ActorKind::Navigation => {
inspector::authoring_inspector_ui(world, ui, entity);
}
}
@@ -139,7 +140,10 @@ pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity
fn actor_icon(kind: ActorKind) -> egui_phosphor_icons::Icon {
match kind {
ActorKind::StaticMesh | ActorKind::Brush | ActorKind::ImportedModel => icons::CUBE,
ActorKind::StaticMesh
| ActorKind::SkinnedMesh
| ActorKind::Brush
| ActorKind::ImportedModel => icons::CUBE,
ActorKind::Light => icons::LIGHTBULB,
ActorKind::PrefabAnchor => icons::PACKAGE,
ActorKind::PlayerSpawn => icons::PERSON_SIMPLE_RUN,
@@ -149,6 +153,7 @@ fn actor_icon(kind: ActorKind) -> egui_phosphor_icons::Icon {
ActorKind::TeamSpawn | ActorKind::Objective => icons::FLAG,
ActorKind::AudioSource => icons::SPEAKER_HIGH,
ActorKind::AudioListener => icons::HEADPHONES,
ActorKind::Navigation => icons::PATH,
ActorKind::Empty => icons::CIRCLE,
}
}
+4 -3
View File
@@ -7,7 +7,7 @@ use bevy_egui::egui;
use egui_phosphor_icons::icons;
use shared::{
AnimationClipRecord, AnimationControllerDesc, AnimationManifest, AnimationSkeletonRecord,
AnimationStateDesc, EditorAssetRef, ModelRef, COMPONENT_ANIMATION_CONTROLLER_DESC,
AnimationStateDesc, EditorAssetRef, SkinnedMeshRenderer, COMPONENT_ANIMATION_CONTROLLER_DESC,
};
use crate::assets::animation::load_animation_manifest;
@@ -656,8 +656,8 @@ fn manifest_summary(ui: &mut egui::Ui, manifest: &Result<AnimationManifest, Stri
fn manifest_for_actor(world: &World, entity: Entity) -> Result<AnimationManifest, String> {
let model = world
.get::<ModelRef>(entity)
.ok_or_else(|| "actor has no ModelRef".to_string())?;
.get::<SkinnedMeshRenderer>(entity)
.ok_or_else(|| "actor has no SkinnedMeshRenderer".to_string())?;
let registry = world
.get_resource::<AssetRegistry>()
.ok_or_else(|| "asset registry is unavailable".to_string())?;
@@ -878,6 +878,7 @@ mod tests {
schema_version: 1,
asset_id: "model-id".into(),
label: "Robot".into(),
default_animation_clip_id: None,
source: AnimationManifestSource {
path: "assets/models/robot.glb".into(),
format: "glb".into(),
File diff suppressed because it is too large. Load diff
+10 -1
View File
@@ -3,7 +3,7 @@
use std::collections::HashSet;
use bevy::prelude::*;
use shared::MaterialAsset;
use shared::{MaterialAsset, MaterialInstanceAsset};
use crate::asset_db::ImportSettings;
use crate::assets::{AssetSelection, ASSETS_ROOT, BUILTINS_FOLDER};
@@ -48,6 +48,7 @@ pub struct AssetBrowserUiState {
pub(crate) pending_delete: Option<AssetDeleteRequest>,
pub(crate) import_draft: Option<ImportSettingsDraft>,
pub(crate) material_draft: Option<MaterialAssetDraft>,
pub(crate) material_instance_draft: Option<MaterialInstanceAssetDraft>,
}
#[derive(Debug, Clone)]
@@ -71,6 +72,13 @@ pub(crate) struct MaterialAssetDraft {
pub(crate) error: Option<String>,
}
#[derive(Debug, Clone)]
pub(crate) struct MaterialInstanceAssetDraft {
pub(crate) path: String,
pub(crate) asset: MaterialInstanceAsset,
pub(crate) error: Option<String>,
}
impl Default for AssetBrowserUiState {
fn default() -> Self {
let mut expanded_folders = HashSet::new();
@@ -89,6 +97,7 @@ impl Default for AssetBrowserUiState {
pending_delete: None,
import_draft: None,
material_draft: None,
material_instance_draft: None,
}
}
}
+571 -4
View File
@@ -1,6 +1,12 @@
//! Editor-visible component registry for actor inspector palettes.
use std::collections::{HashMap, HashSet};
use bevy::ecs::reflect::ReflectComponent;
use bevy::prelude::*;
use bevy::reflect::std_traits::ReflectDefault;
use bevy::reflect::GetTypeRegistration;
use bevy_egui::egui;
use egui_phosphor_icons::icons;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -9,6 +15,7 @@ pub enum EditorComponentCategory {
Rendering,
Animation,
Audio,
Navigation,
Physics,
Gameplay,
Volumes,
@@ -17,6 +24,8 @@ pub enum EditorComponentCategory {
#[derive(Debug, Clone)]
pub struct EditorComponentDescriptor {
/// Stable editor/protocol identity. This must not be a Rust type path.
pub id: &'static str,
pub type_name: &'static str,
pub display_name: &'static str,
pub category: EditorComponentCategory,
@@ -35,6 +44,266 @@ pub struct EditorComponentDescriptor {
#[derive(Resource, Debug, Clone)]
pub struct EditorComponentRegistry {
pub descriptors: Vec<EditorComponentDescriptor>,
inspectors: HashMap<&'static str, ComponentInspectorFn>,
}
pub type ComponentInspectorFn = fn(&mut World, &mut egui::Ui, Entity);
impl EditorComponentRegistry {
/// Registers a statically linked component extension.
///
/// Stable ids and reflected type paths are both unique. Returning an error
/// here prevents a game/editor extension from silently shadowing a built-in.
pub fn register(&mut self, descriptor: EditorComponentDescriptor) -> Result<(), String> {
if self
.descriptors
.iter()
.any(|existing| existing.id == descriptor.id)
{
return Err(format!(
"duplicate authoring component id `{}`",
descriptor.id
));
}
if self
.descriptors
.iter()
.any(|existing| existing.type_name == descriptor.type_name)
{
return Err(format!(
"component type `{}` is already registered",
descriptor.type_name
));
}
self.descriptors.push(descriptor);
Ok(())
}
pub fn register_with_inspector(
&mut self,
descriptor: EditorComponentDescriptor,
inspector: ComponentInspectorFn,
) -> Result<(), String> {
let type_name = descriptor.type_name;
self.register(descriptor)?;
self.inspectors.insert(type_name, inspector);
Ok(())
}
pub fn inspector(&self, type_name: &str) -> Option<ComponentInspectorFn> {
self.inspectors.get(type_name).copied()
}
/// Hard lifecycle requirements keyed by stable component IDs. Keeping this
/// lookup in the registry removes requirement policy from inspector code.
pub fn required_component_ids(
&self,
descriptor: &EditorComponentDescriptor,
) -> &'static [&'static str] {
match descriptor.id {
shared::AUTHORING_COMPONENT_ANIMATION_CONTROLLER => {
&[shared::AUTHORING_COMPONENT_SKINNED_MESH_RENDERER]
}
_ => &[],
}
}
pub fn present_dependents(
&self,
world: &World,
entity: Entity,
required_id: &str,
) -> Vec<&EditorComponentDescriptor> {
self.descriptors
.iter()
.filter(|descriptor| {
self.required_component_ids(descriptor)
.contains(&required_id)
&& self.component_present(world, entity, descriptor.type_name)
})
.collect()
}
pub fn by_id(&self, id: &str) -> Option<&EditorComponentDescriptor> {
self.descriptors
.iter()
.find(|descriptor| descriptor.id == id)
}
pub fn by_type_name(&self, type_name: &str) -> Option<&EditorComponentDescriptor> {
self.descriptors
.iter()
.find(|descriptor| descriptor.type_name == type_name)
}
pub fn stable_id_for_type<'a>(&self, type_name: &'a str) -> &'a str {
self.by_type_name(type_name)
.map(|descriptor| descriptor.id)
.unwrap_or(type_name)
}
pub fn ensure_component_order(&self, order: &mut shared::InspectorOrder, present: &[&str]) {
for type_name in present {
let component_id = self.stable_id_for_type(type_name);
if !order
.component_ids
.iter()
.any(|existing| existing == component_id)
{
order.component_ids.push(component_id.to_string());
}
}
order.component_type_names.clear();
}
pub fn ordered_components<'a>(
&self,
order: &shared::InspectorOrder,
present: &[&'a str],
) -> Vec<&'a str> {
let mut ordered = Vec::new();
for component_id in &order.component_ids {
if let Some(type_name) = present
.iter()
.find(|type_name| self.stable_id_for_type(type_name) == component_id)
{
ordered.push(*type_name);
}
}
for legacy_type_name in &order.component_type_names {
if let Some(type_name) = present
.iter()
.find(|type_name| **type_name == legacy_type_name)
{
if !ordered.contains(type_name) {
ordered.push(*type_name);
}
}
}
for type_name in present {
if !ordered.contains(type_name) {
ordered.push(*type_name);
}
}
ordered
}
pub fn move_component(
&self,
order: &mut shared::InspectorOrder,
type_name: &str,
offset: isize,
present: &[&str],
) -> bool {
self.ensure_component_order(order, present);
let component_id = self.stable_id_for_type(type_name);
let Some(index) = order
.component_ids
.iter()
.position(|existing| existing == component_id)
else {
return false;
};
let target =
(index as isize + offset).clamp(0, order.component_ids.len() as isize - 1) as usize;
if index == target {
return false;
}
let item = order.component_ids.remove(index);
order.component_ids.insert(target, item);
true
}
pub fn component_present(&self, world: &World, entity: Entity, type_name: &str) -> bool {
let Ok(entity_ref) = world.get_entity(entity) else {
return false;
};
let Some(app_registry) = world.get_resource::<AppTypeRegistry>() else {
return false;
};
let type_registry = app_registry.read();
type_registry
.get_with_type_path(type_name)
.and_then(|registration| registration.data::<ReflectComponent>())
.is_some_and(|component| component.contains(entity_ref))
}
/// Validates registry metadata against Bevy reflection before the first
/// inspector frame. This is also the contract test used by extensions.
pub fn validate(&self, world: &World) -> Result<(), Vec<String>> {
let Some(app_registry) = world.get_resource::<AppTypeRegistry>() else {
return Err(vec!["AppTypeRegistry is unavailable".to_string()]);
};
let type_registry = app_registry.read();
let mut errors = Vec::new();
let mut ids = HashSet::new();
let mut type_names = HashSet::new();
for descriptor in &self.descriptors {
if descriptor.id.trim().is_empty() {
errors.push(format!(
"{} has an empty stable id",
descriptor.display_name
));
} else if !ids.insert(descriptor.id) {
errors.push(format!("duplicate stable id `{}`", descriptor.id));
}
if !type_names.insert(descriptor.type_name) {
errors.push(format!(
"duplicate reflected type `{}`",
descriptor.type_name
));
}
match type_registry.get_with_type_path(descriptor.type_name) {
Some(registration) if registration.data::<ReflectComponent>().is_none() => errors
.push(format!(
"`{}` is registered without ReflectComponent",
descriptor.type_name
)),
None => errors.push(format!(
"reflected component `{}` is not registered",
descriptor.type_name
)),
Some(registration)
if descriptor.addable && registration.data::<ReflectDefault>().is_none() =>
{
errors.push(format!(
"addable component `{}` has no reflected Default",
descriptor.type_name
));
}
Some(_) => {}
}
for relation in descriptor
.recommended
.iter()
.chain(descriptor.conflicts_with.iter())
{
if !self
.descriptors
.iter()
.any(|candidate| candidate.type_name == *relation)
{
errors.push(format!(
"{} references unregistered component `{relation}`",
descriptor.id
));
}
}
for required_id in self.required_component_ids(descriptor) {
if self.by_id(required_id).is_none() {
errors.push(format!(
"{} requires unknown stable component id `{required_id}`",
descriptor.id
));
}
}
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
impl Default for EditorComponentRegistry {
@@ -42,6 +311,7 @@ impl Default for EditorComponentRegistry {
Self {
descriptors: vec![
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_STATIC_MESH_RENDERER,
type_name: "shared::components::StaticMeshRenderer",
display_name: "Static Mesh Renderer",
category: EditorComponentCategory::Rendering,
@@ -56,11 +326,35 @@ impl Default for EditorComponentRegistry {
conflicts_with: &[
"shared::components::Primitive",
"shared::components::BrushDesc",
"shared::animation::SkinnedMeshRenderer",
],
hydration_effect:
"Hydrates into generated mesh children and material bindings.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_SKINNED_MESH_RENDERER,
type_name: "shared::animation::SkinnedMeshRenderer",
display_name: "Skinned Mesh Renderer",
category: EditorComponentCategory::Rendering,
addable: false,
removable: true,
reorderable: true,
hidden: false,
icon: icons::PERSON_SIMPLE_RUN.as_str(),
description:
"Renders rigged geometry while preserving its imported joints and skin bindings.",
search_terms: &["mesh", "renderer", "skinned", "skeletal", "rigged", "joints"],
recommended: &["shared::animation::AnimationControllerDesc"],
conflicts_with: &[
"shared::components::Primitive",
"shared::components::BrushDesc",
"shared::components::StaticMeshRenderer",
],
hydration_effect:
"Hydrates through a dedicated scene root containing Bevy skinned meshes and joints.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_BRUSH,
type_name: "shared::components::BrushDesc",
display_name: "Brush",
category: EditorComponentCategory::Authoring,
@@ -75,10 +369,12 @@ impl Default for EditorComponentRegistry {
conflicts_with: &[
"shared::components::Primitive",
"shared::components::StaticMeshRenderer",
"shared::animation::SkinnedMeshRenderer",
],
hydration_effect: "Hydrates into generated brush mesh children.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_MATERIAL,
type_name: "shared::components::MaterialDesc",
display_name: "Authoring Material",
category: EditorComponentCategory::Rendering,
@@ -94,6 +390,7 @@ impl Default for EditorComponentRegistry {
hydration_effect: "Hydrates into Bevy material assets for renderable actors.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_RIGID_BODY,
type_name: "shared::components::RigidBodyDesc",
display_name: "Rigid Body",
category: EditorComponentCategory::Physics,
@@ -109,6 +406,7 @@ impl Default for EditorComponentRegistry {
hydration_effect: "Hydrates into runtime Avian rigid-body state.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_COLLIDER,
type_name: "shared::components::ColliderDesc",
display_name: "Collider",
category: EditorComponentCategory::Physics,
@@ -124,6 +422,7 @@ impl Default for EditorComponentRegistry {
hydration_effect: "Hydrates into runtime Avian collider state.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_LIGHT,
type_name: "shared::components::LightDesc",
display_name: "Light",
category: EditorComponentCategory::Rendering,
@@ -139,6 +438,7 @@ impl Default for EditorComponentRegistry {
hydration_effect: "Hydrates into runtime Bevy light components.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_ANIMATION_CONTROLLER,
type_name: "shared::animation::AnimationControllerDesc",
display_name: "Animation Controller",
category: EditorComponentCategory::Animation,
@@ -149,12 +449,13 @@ impl Default for EditorComponentRegistry {
icon: icons::FILM_SLATE.as_str(),
description: "Authors named animation states for an imported model rig.",
search_terms: &["animation", "controller", "state", "clip", "skeleton", "rig"],
recommended: &[],
recommended: &["shared::animation::SkinnedMeshRenderer"],
conflicts_with: &[],
hydration_effect:
"Hydrates into a Bevy animation graph and player bound to the imported model.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_AUDIO_SOURCE,
type_name: "shared::components::AudioSourceDesc",
display_name: "Audio Source",
category: EditorComponentCategory::Audio,
@@ -171,6 +472,7 @@ impl Default for EditorComponentRegistry {
"Hydrates into runtime Bevy audio voices with bus and attenuation control.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_AUDIO_LISTENER,
type_name: "shared::components::AudioListenerDesc",
display_name: "Audio Listener",
category: EditorComponentCategory::Audio,
@@ -187,6 +489,7 @@ impl Default for EditorComponentRegistry {
"The highest-priority enabled listener becomes the runtime listener.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_PRIMITIVE,
type_name: "shared::components::Primitive",
display_name: "Primitive",
category: EditorComponentCategory::Authoring,
@@ -201,11 +504,13 @@ impl Default for EditorComponentRegistry {
conflicts_with: &[
"shared::components::StaticMeshRenderer",
"shared::components::BrushDesc",
"shared::animation::SkinnedMeshRenderer",
],
hydration_effect:
"Hydrates into generated primitive render and collision data.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_PLAYER_SPAWN,
type_name: "shared::components::PlayerSpawn",
display_name: "Player Spawn",
category: EditorComponentCategory::Gameplay,
@@ -222,6 +527,7 @@ impl Default for EditorComponentRegistry {
"Used by PIE/session startup; no saved runtime player is created.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_WEAPON_SPAWN,
type_name: "shared::components::WeaponSpawn",
display_name: "Weapon Spawn",
category: EditorComponentCategory::Gameplay,
@@ -237,6 +543,7 @@ impl Default for EditorComponentRegistry {
hydration_effect: "Hydrates into gameplay spawn metadata.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_TRIGGER_VOLUME,
type_name: "shared::components::TriggerVolume",
display_name: "Trigger Volume",
category: EditorComponentCategory::Volumes,
@@ -252,6 +559,7 @@ impl Default for EditorComponentRegistry {
hydration_effect: "Hydrates into gameplay trigger queries and visualizers.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_TEAM_SPAWN,
type_name: "shared::components::TeamSpawn",
display_name: "Team Spawn",
category: EditorComponentCategory::Gameplay,
@@ -267,6 +575,7 @@ impl Default for EditorComponentRegistry {
hydration_effect: "Hydrates into gameplay spawn metadata.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_OBJECTIVE,
type_name: "shared::components::ObjectiveMarker",
display_name: "Objective Marker",
category: EditorComponentCategory::Gameplay,
@@ -282,6 +591,7 @@ impl Default for EditorComponentRegistry {
hydration_effect: "Hydrates into gameplay objective metadata.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_POST_PROCESS_VOLUME,
type_name: "shared::components::PostProcessVolumeDesc",
display_name: "Post-Process Volume",
category: EditorComponentCategory::Volumes,
@@ -298,6 +608,215 @@ impl Default for EditorComponentRegistry {
"Affects active camera rendering when the camera is inside the volume.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_NAVIGATION_BOUNDS,
type_name: "shared::navigation::NavigationBounds",
display_name: "Navigation Bounds",
category: EditorComponentCategory::Navigation,
addable: true,
removable: true,
reorderable: true,
hidden: false,
icon: icons::PATH.as_str(),
description: "Defines the world region and agent profile for a navigation bake.",
search_terms: &["navigation", "navmesh", "bounds", "agent", "bake"],
recommended: &[],
conflicts_with: &[
"shared::navigation::NavigationObstacle",
"shared::navigation::NavigationArea",
"shared::navigation::NavigationLink",
],
hydration_effect: "Feeds the generated navigation artifact; no render component is hydrated.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_NAVIGATION_OBSTACLE,
type_name: "shared::navigation::NavigationObstacle",
display_name: "Navigation Obstacle",
category: EditorComponentCategory::Navigation,
addable: true,
removable: true,
reorderable: true,
hidden: false,
icon: icons::SELECTION_SLASH.as_str(),
description: "Carves an axis-aligned blocked volume from overlapping bakes.",
search_terms: &["navigation", "navmesh", "obstacle", "block", "carve"],
recommended: &[],
conflicts_with: &[
"shared::navigation::NavigationBounds",
"shared::navigation::NavigationArea",
"shared::navigation::NavigationLink",
],
hydration_effect: "Contributes a deterministic unwalkable volume during bake.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_NAVIGATION_AREA,
type_name: "shared::navigation::NavigationArea",
display_name: "Navigation Area",
category: EditorComponentCategory::Navigation,
addable: true,
removable: true,
reorderable: true,
hidden: false,
icon: icons::POLYGON.as_str(),
description: "Labels a walkable or blocked navigation area and traversal cost.",
search_terms: &["navigation", "navmesh", "area", "cost", "walkable"],
recommended: &[],
conflicts_with: &[
"shared::navigation::NavigationBounds",
"shared::navigation::NavigationObstacle",
"shared::navigation::NavigationLink",
],
hydration_effect: "Stores area metadata and blocked-volume contribution in the bake artifact.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_NAVIGATION_LINK,
type_name: "shared::navigation::NavigationLink",
display_name: "Navigation Link",
category: EditorComponentCategory::Navigation,
addable: true,
removable: true,
reorderable: true,
hidden: false,
icon: icons::LINK.as_str(),
description: "Connects otherwise isolated navigation regions with an explicit traversal.",
search_terms: &["navigation", "navmesh", "link", "jump", "door", "ladder"],
recommended: &[],
conflicts_with: &[
"shared::navigation::NavigationBounds",
"shared::navigation::NavigationObstacle",
"shared::navigation::NavigationArea",
],
hydration_effect: "Adds a validated directed or bidirectional runtime path connection.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_LEGACY_PHYSICS_BODY,
type_name: "shared::components::PhysicsBody",
display_name: "Legacy Physics Body",
category: EditorComponentCategory::Physics,
addable: false,
removable: true,
reorderable: true,
hidden: false,
icon: icons::SPHERE.as_str(),
description: "Legacy combined physics authoring retained for scene compatibility.",
search_terms: &["legacy", "physics", "body"],
recommended: &[],
conflicts_with: &[],
hydration_effect: "Hydrates through the compatibility physics path.",
},
EditorComponentDescriptor {
id: "prefab.instance",
type_name: "shared::components::PrefabInstance",
display_name: "Prefab Instance",
category: EditorComponentCategory::Authoring,
addable: false,
removable: false,
reorderable: true,
hidden: false,
icon: icons::PACKAGE.as_str(),
description: "Stores a linked prefab instance and its overrides.",
search_terms: &["prefab", "instance", "link"],
recommended: &[],
conflicts_with: &[],
hydration_effect: "Hydrates linked prefab members beneath this anchor.",
},
EditorComponentDescriptor {
id: "prefab.reference",
type_name: "shared::components::PrefabRef",
display_name: "Prefab Reference",
category: EditorComponentCategory::Authoring,
addable: false,
removable: false,
reorderable: false,
hidden: true,
icon: icons::PACKAGE.as_str(),
description: "Stable source reference owned by a prefab anchor.",
search_terms: &["prefab", "reference"],
recommended: &[],
conflicts_with: &[],
hydration_effect: "Resolves the prefab source asset.",
},
EditorComponentDescriptor {
id: "render.imported_model",
type_name: "shared::components::ModelRef",
display_name: "Imported Model Reference",
category: EditorComponentCategory::Rendering,
addable: false,
removable: false,
reorderable: false,
hidden: true,
icon: icons::CUBE_TRANSPARENT.as_str(),
description: "Legacy full-scene imported model reference.",
search_terms: &["model", "imported", "scene"],
recommended: &[],
conflicts_with: &[],
hydration_effect: "Hydrates the referenced imported model scene.",
},
EditorComponentDescriptor {
id: "render.material_override_legacy",
type_name: "shared::components::MaterialOverride",
display_name: "Legacy Material Override",
category: EditorComponentCategory::Rendering,
addable: false,
removable: false,
reorderable: false,
hidden: true,
icon: icons::PALETTE.as_str(),
description: "Legacy renderer material slot overrides retained for migration.",
search_terms: &["material", "override", "legacy"],
recommended: &[],
conflicts_with: &[],
hydration_effect: "Applies compatibility material overrides.",
},
EditorComponentDescriptor {
id: "render.project_sun",
type_name: "shared::components::ProjectSun",
display_name: "Project Sun",
category: EditorComponentCategory::Rendering,
addable: false,
removable: false,
reorderable: true,
hidden: false,
icon: icons::SUN.as_str(),
description: "Marks the scene light that overrides the project sun.",
search_terms: &["sun", "directional", "project"],
recommended: &[],
conflicts_with: &[],
hydration_effect: "Selects the authored directional project light.",
},
EditorComponentDescriptor {
id: "core.actor_kind",
type_name: "shared::components::ActorKind",
display_name: "Actor Kind Hint",
category: EditorComponentCategory::Editor,
addable: false,
removable: false,
reorderable: false,
hidden: true,
icon: icons::TAG.as_str(),
description: "Compatibility and presentation hint derived from primary components.",
search_terms: &["actor", "kind", "hint"],
recommended: &[],
conflicts_with: &[],
hydration_effect: "No runtime effect; validation uses component composition.",
},
EditorComponentDescriptor {
id: "editor.component_states",
type_name: "shared::components::AuthoringComponentStates",
display_name: "Authoring Component States",
category: EditorComponentCategory::Editor,
addable: false,
removable: false,
reorderable: false,
hidden: true,
icon: icons::TOGGLE_LEFT.as_str(),
description: "Stores persisted component enable state independently of inspector layout.",
search_terms: &["editor", "active", "enabled"],
recommended: &[],
conflicts_with: &[],
hydration_effect: "Controls whether opted-in authoring components hydrate.",
},
EditorComponentDescriptor {
id: "editor.inspector_order",
type_name: "shared::components::InspectorOrder",
display_name: "Inspector Order",
category: EditorComponentCategory::Editor,
@@ -306,14 +825,62 @@ impl Default for EditorComponentRegistry {
reorderable: false,
hidden: true,
icon: icons::LIST_BULLETS.as_str(),
description: "Stores editor-only component ordering and active-state metadata.",
description: "Stores editor-only component card ordering.",
search_terms: &["editor", "order"],
recommended: &[],
conflicts_with: &[],
hydration_effect:
"Controls editor presentation and authoring component active state.",
hydration_effect: "Controls editor presentation only; runtime active state is stored separately.",
},
],
inspectors: HashMap::new(),
}
}
}
/// Registers one statically linked game/editor component with reflection,
/// lifecycle metadata, and its editor inspector in a single call.
pub fn register_authoring_component<T>(
app: &mut App,
descriptor: EditorComponentDescriptor,
inspector: ComponentInspectorFn,
) -> Result<(), String>
where
T: Component + Reflect + GetTypeRegistration,
{
app.register_type::<T>();
if !app.world().contains_resource::<EditorComponentRegistry>() {
app.init_resource::<EditorComponentRegistry>();
}
app.world_mut()
.resource_mut::<EditorComponentRegistry>()
.register_with_inspector(descriptor, inspector)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn built_in_registry_is_unique_and_reflectable() {
let mut app = App::new();
app.add_plugins(shared::SharedTypesPlugin)
.init_resource::<EditorComponentRegistry>();
app.world()
.resource::<EditorComponentRegistry>()
.validate(app.world())
.unwrap();
}
#[test]
fn static_extensions_cannot_shadow_stable_ids_or_types() {
let mut registry = EditorComponentRegistry::default();
let mut duplicate = registry.descriptors[0].clone();
duplicate.type_name = "game::editor_ext::StaticFixture";
assert!(registry.register(duplicate).is_err());
let mut duplicate = registry.descriptors[0].clone();
duplicate.id = "game.static_fixture";
assert!(registry.register(duplicate).is_err());
}
}
+33
View File
@@ -91,6 +91,7 @@ pub fn light_snapshot(name: &str, translation: Vec3) -> EditorEntitySnapshot {
primitive: None,
brush: None,
static_mesh_renderer: None,
skinned_mesh_renderer: None,
material: None,
material_override: None,
rigid_body: None,
@@ -109,8 +110,18 @@ pub fn light_snapshot(name: &str, translation: Vec3) -> EditorEntitySnapshot {
post_process_volume: None,
team_spawn: None,
objective: None,
navigation_bounds: None,
navigation_obstacle: None,
navigation_area: None,
navigation_link: None,
hierarchy_sibling_index: 0,
editor_visibility: shared::EditorVisibility::default(),
inspector_order: None,
component_states: None,
children: Vec::new(),
}
}
@@ -142,6 +153,7 @@ pub fn ensure_player_spawn_for_edit(world: &mut World) -> Entity {
primitive: None,
brush: None,
static_mesh_renderer: None,
skinned_mesh_renderer: None,
material: None,
material_override: None,
rigid_body: None,
@@ -160,8 +172,18 @@ pub fn ensure_player_spawn_for_edit(world: &mut World) -> Entity {
post_process_volume: None,
team_spawn: None,
objective: None,
navigation_bounds: None,
navigation_obstacle: None,
navigation_area: None,
navigation_link: None,
hierarchy_sibling_index: 0,
editor_visibility: shared::EditorVisibility::default(),
inspector_order: None,
component_states: None,
children: Vec::new(),
},
)
@@ -233,6 +255,7 @@ pub fn create_scene_sun_override_from_project_settings(world: &mut World) -> Ent
primitive: None,
brush: None,
static_mesh_renderer: None,
skinned_mesh_renderer: None,
material: None,
material_override: None,
rigid_body: None,
@@ -251,8 +274,18 @@ pub fn create_scene_sun_override_from_project_settings(world: &mut World) -> Ent
post_process_volume: None,
team_spawn: None,
objective: None,
navigation_bounds: None,
navigation_obstacle: None,
navigation_area: None,
navigation_link: None,
hierarchy_sibling_index: 0,
editor_visibility: shared::EditorVisibility::default(),
inspector_order: None,
component_states: None,
children: Vec::new(),
},
)
+12 -1
View File
@@ -4,6 +4,7 @@ use bevy::prelude::*;
use shared::{
ActorKind, AuthoringLightKind, EditorVisibility, HierarchySiblingIndex, HydratedPrefabMember,
LevelObject, LightDesc, ModelRef, PhysicsBody, PlayerSpawn, PrefabInstance,
SkinnedMeshRenderer,
};
use super::helpers::{entity_name, is_level_object, HierarchyNodeKind};
@@ -203,7 +204,10 @@ fn actor_kind_sort_key(world: &World, entity: Entity) -> u8 {
.copied()
.map(|kind| match kind {
ActorKind::Empty => 0,
ActorKind::Brush | ActorKind::StaticMesh | ActorKind::ImportedModel => 1,
ActorKind::Brush
| ActorKind::StaticMesh
| ActorKind::SkinnedMesh
| ActorKind::ImportedModel => 1,
ActorKind::Light => 2,
ActorKind::AudioSource | ActorKind::AudioListener => 3,
ActorKind::PrefabAnchor => 3,
@@ -213,6 +217,7 @@ fn actor_kind_sort_key(world: &World, entity: Entity) -> u8 {
ActorKind::PostProcessVolume => 6,
ActorKind::TeamSpawn => 7,
ActorKind::Objective => 8,
ActorKind::Navigation => 6,
})
.unwrap_or(9)
}
@@ -464,6 +469,7 @@ pub fn actor_kind_icon(kind: ActorKind) -> &'static str {
ActorKind::Empty => icons::FOLDER.as_str(),
ActorKind::Brush => icons::CUBE.as_str(),
ActorKind::StaticMesh => icons::CUBE.as_str(),
ActorKind::SkinnedMesh => icons::PERSON_SIMPLE_RUN.as_str(),
ActorKind::ImportedModel => icons::CUBE_TRANSPARENT.as_str(),
ActorKind::Light => icons::LIGHTBULB.as_str(),
ActorKind::AudioSource => icons::SPEAKER_HIGH.as_str(),
@@ -475,6 +481,7 @@ pub fn actor_kind_icon(kind: ActorKind) -> &'static str {
ActorKind::PostProcessVolume => icons::CAMERA.as_str(),
ActorKind::TeamSpawn => icons::FLAG.as_str(),
ActorKind::Objective => icons::TARGET.as_str(),
ActorKind::Navigation => icons::PATH.as_str(),
}
}
@@ -534,6 +541,10 @@ pub fn entity_matches_filter(world: &World, entity: Entity, filter_lower: &str)
.is_some()
.then_some("spawn"),
world.get::<ModelRef>(entity).is_some().then_some("model"),
world
.get::<SkinnedMeshRenderer>(entity)
.is_some()
.then_some("skinned model"),
world
.get::<PhysicsBody>(entity)
.is_some()
File diff suppressed because it is too large. Load diff
+38
View File
@@ -158,6 +158,44 @@ pub fn top_menu_bar(
crate::rendering_diagnostics::spawn_post_process_volume_at_camera(world);
ui.close();
}
ui.separator();
ui.menu_button("Navigation", |ui| {
use super::navigation_inspector::{
spawn_navigation_actor, NavigationActorType,
};
for (label, actor_type) in [
("Create Bounds", NavigationActorType::Bounds),
("Create Obstacle", NavigationActorType::Obstacle),
("Create Area", NavigationActorType::Area),
("Create Link", NavigationActorType::Link),
] {
if menu_item(ui, label, None, true).clicked() {
spawn_navigation_actor(world, actor_type);
ui.close();
}
}
ui.separator();
let selected_bounds =
selected.as_slice().iter().copied().find(|entity| {
world.get::<shared::NavigationBounds>(*entity).is_some()
});
if menu_item(ui, "Bake Selected Bounds", None, selected_bounds.is_some())
.clicked()
{
if let Some(entity) = selected_bounds {
super::navigation_inspector::bake_bounds(world, entity);
}
ui.close();
}
if menu_item(ui, "Test Selected Path", None, selected_bounds.is_some())
.clicked()
{
if let Some(entity) = selected_bounds {
super::navigation_inspector::query_preview(world, entity);
}
ui.close();
}
});
});
ui.menu_button("Build", |ui| {
+18 -1
View File
@@ -3,7 +3,7 @@ mod animation_inspector;
mod asset_browser;
mod audio_inspector;
mod build;
mod component_registry;
pub mod component_registry;
mod diagnostics;
mod dock_tabs;
mod fonts;
@@ -14,6 +14,7 @@ pub mod hierarchy_state;
pub(crate) mod inspector;
mod layout;
mod menu;
pub(crate) mod navigation_inspector;
mod play_controls;
mod post_process_volume_ui;
mod scene_tabs;
@@ -294,6 +295,7 @@ impl Plugin for EditorUiPlugin {
.init_resource::<inspector::InspectorClipboard>()
.init_resource::<inspector::InspectorPanelState>()
.init_resource::<animation_inspector::AnimationInspectorState>()
.init_resource::<navigation_inspector::NavigationEditorState>()
.init_resource::<ViewportUiState>()
.init_resource::<LayoutSaveTimer>()
.add_systems(
@@ -301,6 +303,7 @@ impl Plugin for EditorUiPlugin {
init_hierarchy_panel_from_prefs
.after(crate::project_io::load_user_preferences_on_startup),
)
.add_systems(Startup, validate_editor_component_registry)
.add_systems(
Startup,
apply_ui_state_from_prefs
@@ -312,11 +315,25 @@ impl Plugin for EditorUiPlugin {
(
hierarchy_state::tick_hierarchy_prefs_save,
build::tick_build_job,
navigation_inspector::sync_navigation_state,
),
);
}
}
fn validate_editor_component_registry(world: &mut World) {
let errors = world
.resource::<component_registry::EditorComponentRegistry>()
.validate(world)
.err();
if let Some(errors) = errors {
panic!(
"invalid authoring component registry:\n{}",
errors.join("\n")
);
}
}
fn apply_ui_state_from_prefs(mut ui_state: ResMut<UiState>, prefs: Res<UserPreferences>) {
*ui_state = UiState::from_prefs(&prefs);
}
@@ -0,0 +1,765 @@
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use bevy::prelude::*;
use bevy_egui::egui;
use egui_phosphor_icons::icons;
use scene::navigation::{
aabb_overlaps, bake_navigation, geometry_overlaps_bounds, navigation_geometry_from_parts,
navigation_source_fingerprint, point_in_aabb, read_navigation_artifact,
write_navigation_artifact, NavigationAreaInput, NavigationBakeArtifact, NavigationBakeInput,
NavigationLinkInput, NavigationVolumeInput,
};
use shared::{
ActorId, BrushDesc, NavigationArea, NavigationBounds, NavigationLink, NavigationObstacle,
Primitive, COMPONENT_NAVIGATION_AREA, COMPONENT_NAVIGATION_BOUNDS, COMPONENT_NAVIGATION_LINK,
COMPONENT_NAVIGATION_OBSTACLE,
};
use crate::history::{set_navigation_with_history, NavigationComponentState};
use crate::project_io::ProjectWorkspace;
use crate::scene_io::SceneIo;
use crate::ui::inspector::{
apply_component_card_response, component_card, component_card_context, property_row,
ComponentCardOptions,
};
use crate::ui::theme::{ERROR, SUCCESS, TEXT_DIM, WARNING};
use crate::viewport::{editor_spawn_ground_position, snap_translation, ViewportSettings};
#[derive(Resource, Debug, Clone)]
pub struct NavigationEditorState {
pub bounds_entity: Option<Entity>,
pub artifact: Option<NavigationBakeArtifact>,
pub preview_start: Vec3,
pub preview_end: Vec3,
pub preview_path: Vec<Vec3>,
pub status: String,
pub error: bool,
pub show_mesh: bool,
observed_fingerprint: Option<String>,
auto_bake_attempt: Option<String>,
debounce_elapsed: f32,
}
impl Default for NavigationEditorState {
fn default() -> Self {
Self {
bounds_entity: None,
artifact: None,
preview_start: Vec3::new(-4.0, 0.0, 0.0),
preview_end: Vec3::new(4.0, 0.0, 0.0),
preview_path: Vec::new(),
status: "Not baked".into(),
error: false,
show_mesh: true,
observed_fingerprint: None,
auto_bake_attempt: None,
debounce_elapsed: 0.0,
}
}
}
pub fn navigation_bounds_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
let Some(mut bounds) = world.get::<NavigationBounds>(entity).cloned() else {
return;
};
let original = bounds.clone();
let mut preview_start = world.resource::<NavigationEditorState>().preview_start;
let mut preview_end = world.resource::<NavigationEditorState>().preview_end;
let mut show_mesh = world.resource::<NavigationEditorState>().show_mesh;
let status = world.resource::<NavigationEditorState>().status.clone();
let status_error = world.resource::<NavigationEditorState>().error;
let current = build_input(world, entity, &bounds).ok();
let stale = current.as_ref().is_some_and(|input| {
world
.resource::<NavigationEditorState>()
.artifact
.as_ref()
.is_none_or(|artifact| artifact.is_stale_for(input))
});
let mut bake = false;
let mut preview = false;
let card = component_card_context(
world,
entity,
ComponentCardOptions::removable(
COMPONENT_NAVIGATION_BOUNDS,
"Navigation Bounds",
icons::PATH,
),
);
let response = component_card(ui, &card, |ui| {
property_row(ui, "Half extents", |ui| {
vec3_editor(ui, &mut bounds.half_extents, 0.1)
});
property_row(ui, "Agent ID", |ui| {
ui.text_edit_singleline(&mut bounds.agent.id)
});
property_row(ui, "Radius / height", |ui| {
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut bounds.agent.radius).speed(0.01));
ui.add(egui::DragValue::new(&mut bounds.agent.height).speed(0.01))
})
.response
});
property_row(ui, "Climb / slope", |ui| {
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut bounds.agent.max_climb).speed(0.01));
ui.add(
egui::DragValue::new(&mut bounds.agent.max_slope_deg)
.speed(0.25)
.suffix(" deg"),
)
})
.response
});
property_row(ui, "Voxel detail", |ui| {
ui.horizontal(|ui| {
ui.add(
egui::DragValue::new(&mut bounds.agent.cell_size_fraction)
.speed(0.1)
.range(1.0..=12.0),
);
ui.add(
egui::DragValue::new(&mut bounds.agent.cell_height_fraction)
.speed(0.1)
.range(1.0..=24.0),
)
})
.response
});
property_row(ui, "Artifact", |ui| {
ui.text_edit_singleline(&mut bounds.artifact_path)
});
property_row(ui, "Auto bake", |ui| {
ui.checkbox(&mut bounds.auto_bake, "Debounced")
});
ui.separator();
ui.horizontal(|ui| {
bake = ui
.button(format!("{} Bake", icons::HAMMER.as_str()))
.on_hover_text("Bake deterministic navigation artifact")
.clicked();
preview = ui
.add_enabled(
!stale,
egui::Button::new(format!("{} Test Path", icons::PATH.as_str())),
)
.on_hover_text("Query the baked artifact using the game runtime API")
.clicked();
ui.checkbox(&mut show_mesh, "Overlay");
});
let status_color = if status_error {
ERROR
} else if stale {
WARNING
} else {
SUCCESS
};
ui.colored_label(
status_color,
if stale {
format!("Stale: {status}")
} else {
status.clone()
},
);
property_row(ui, "Path start", |ui| {
vec3_editor(ui, &mut preview_start, 0.1)
});
property_row(ui, "Path end", |ui| vec3_editor(ui, &mut preview_end, 0.1));
if let Some(input) = current.as_ref() {
ui.label(
egui::RichText::new(format!(
"{} obstacles {} areas {} links",
input.obstacles.len(),
input.areas.len(),
input.links.len()
))
.small()
.color(TEXT_DIM),
);
}
});
apply_component_card_response(world, entity, response);
if bounds != original {
set_navigation_with_history(
world,
entity,
NavigationComponentState {
bounds: Some(bounds.clone()),
..Default::default()
},
);
}
{
let mut state = world.resource_mut::<NavigationEditorState>();
state.preview_start = preview_start;
state.preview_end = preview_end;
state.show_mesh = show_mesh;
}
if bake {
bake_bounds(world, entity);
}
if preview {
query_preview(world, entity);
}
}
pub fn navigation_obstacle_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
let Some(mut value) = world.get::<NavigationObstacle>(entity).cloned() else {
return;
};
let original = value.clone();
let card = component_card_context(
world,
entity,
ComponentCardOptions::removable(
COMPONENT_NAVIGATION_OBSTACLE,
"Navigation Obstacle",
icons::SELECTION_SLASH,
),
);
let response = component_card(ui, &card, |ui| {
property_row(ui, "Half extents", |ui| {
vec3_editor(ui, &mut value.half_extents, 0.05)
});
property_row(ui, "Runtime", |ui| {
ui.checkbox(&mut value.dynamic, "Dynamic obstacle")
});
if value.dynamic {
ui.colored_label(
WARNING,
"Dynamic carving is not baked in navigation v1; this volume remains a static bake input.",
);
}
});
apply_component_card_response(world, entity, response);
if value != original {
set_navigation_with_history(
world,
entity,
NavigationComponentState {
obstacle: Some(value),
..Default::default()
},
);
}
}
pub fn navigation_area_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
let Some(mut value) = world.get::<NavigationArea>(entity).cloned() else {
return;
};
let original = value.clone();
let card = component_card_context(
world,
entity,
ComponentCardOptions::removable(
COMPONENT_NAVIGATION_AREA,
"Navigation Area",
icons::POLYGON,
),
);
let response = component_card(ui, &card, |ui| {
property_row(ui, "Area ID", |ui| ui.text_edit_singleline(&mut value.id));
property_row(ui, "Half extents", |ui| {
vec3_editor(ui, &mut value.half_extents, 0.05)
});
property_row(ui, "Cost", |ui| {
ui.add(
egui::DragValue::new(&mut value.cost)
.speed(0.05)
.range(0.05..=100.0),
)
});
property_row(ui, "Walkable", |ui| {
ui.checkbox(&mut value.walkable, "Enabled")
});
});
apply_component_card_response(world, entity, response);
if value != original {
set_navigation_with_history(
world,
entity,
NavigationComponentState {
area: Some(value),
..Default::default()
},
);
}
}
pub fn navigation_link_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
let Some(mut value) = world.get::<NavigationLink>(entity).cloned() else {
return;
};
let original = value.clone();
let card = component_card_context(
world,
entity,
ComponentCardOptions::removable(COMPONENT_NAVIGATION_LINK, "Navigation Link", icons::LINK),
);
let response = component_card(ui, &card, |ui| {
property_row(ui, "Start", |ui| vec3_editor(ui, &mut value.start, 0.05));
property_row(ui, "End", |ui| vec3_editor(ui, &mut value.end, 0.05));
property_row(ui, "Direction", |ui| {
ui.checkbox(&mut value.bidirectional, "Bidirectional")
});
property_row(ui, "Cost", |ui| {
ui.add(
egui::DragValue::new(&mut value.cost)
.speed(0.05)
.range(0.05..=100.0),
)
});
property_row(ui, "Enabled", |ui| {
ui.checkbox(&mut value.enabled, "Active")
});
});
apply_component_card_response(world, entity, response);
if value != original {
set_navigation_with_history(
world,
entity,
NavigationComponentState {
link: Some(value),
..Default::default()
},
);
}
}
pub fn bake_bounds(world: &mut World, entity: Entity) {
let Some(bounds) = world.get::<NavigationBounds>(entity).cloned() else {
set_status(
world,
"Bake failed: selected actor has no Navigation Bounds",
true,
);
return;
};
let input = match build_input(world, entity, &bounds) {
Ok(input) => input,
Err(error) => {
set_status(world, format!("Bake failed: {error}"), true);
return;
}
};
let artifact = match bake_navigation(&input) {
Ok(artifact) => artifact,
Err(error) => {
set_status(world, format!("Bake failed: {error}"), true);
return;
}
};
let path = match artifact_path(world, &bounds.artifact_path) {
Ok(path) => path,
Err(error) => {
set_status(world, format!("Bake failed: {error}"), true);
return;
}
};
if let Err(error) = write_navigation_artifact(&path, &artifact) {
set_status(world, format!("Bake failed: {error}"), true);
return;
}
let polygon_count: usize = artifact
.mesh
.layers
.iter()
.map(|layer| layer.polygons.len())
.sum();
let mut state = world.resource_mut::<NavigationEditorState>();
state.bounds_entity = Some(entity);
state.artifact = Some(artifact);
state.preview_path.clear();
state.error = false;
state.status = format!("Baked {polygon_count} polygons to {}", bounds.artifact_path);
}
pub fn query_preview(world: &mut World, entity: Entity) {
let (artifact, start, end) = {
let state = world.resource::<NavigationEditorState>();
(
state.artifact.clone(),
state.preview_start,
state.preview_end,
)
};
let Some(artifact) = artifact else {
set_status(world, "Path test failed: bake navigation first", true);
return;
};
let runtime = match game::navigation::NavigationRuntime::from_artifact(artifact) {
Ok(runtime) => runtime,
Err(error) => {
set_status(world, format!("Path test failed: {error}"), true);
return;
}
};
match runtime.query(start, end) {
Ok(path) => {
let mut state = world.resource_mut::<NavigationEditorState>();
state.bounds_entity = Some(entity);
state.preview_path = path.points;
state.error = false;
state.status = format!(
"Path {:.2} m, {} waypoints{}",
path.length,
state.preview_path.len(),
path.used_link_actor_id
.as_deref()
.map(|id| format!(", link {id}"))
.unwrap_or_default()
);
}
Err(error) => set_status(world, format!("Path test failed: {error}"), true),
}
}
fn build_input(
world: &mut World,
bounds_entity: Entity,
bounds: &NavigationBounds,
) -> Result<NavigationBakeInput, String> {
let active_path = world
.resource::<SceneIo>()
.active_path
.as_ref()
.cloned()
.ok_or_else(|| "save the scene before baking navigation".to_string())?;
let project_root = Path::new(&world.resource::<ProjectWorkspace>().root);
let source_scene = active_path
.strip_prefix(project_root)
.unwrap_or(&active_path)
.to_string_lossy()
.replace('\\', "/");
let bounds_actor_id = actor_id(world, bounds_entity)?;
let bounds_transform = world_transform(world, bounds_entity);
let center = bounds_transform.translation.to_array();
let half_extents = world_aabb_half_extents(bounds_transform, bounds.half_extents).to_array();
let mut obstacles = Vec::new();
let mut obstacle_query = world.query::<(Entity, &NavigationObstacle)>();
for (entity, obstacle) in obstacle_query.iter(world) {
let value = NavigationVolumeInput {
actor_id: actor_id(world, entity)?,
center: world_position(world, entity).to_array(),
half_extents: world_aabb_half_extents(
world_transform(world, entity),
obstacle.half_extents,
)
.to_array(),
};
if aabb_overlaps(center, half_extents, value.center, value.half_extents) {
obstacles.push(value);
}
}
obstacles.sort_by(|a, b| a.actor_id.cmp(&b.actor_id));
let mut areas = Vec::new();
let mut area_query = world.query::<(Entity, &NavigationArea)>();
for (entity, area) in area_query.iter(world) {
let value = NavigationAreaInput {
actor_id: actor_id(world, entity)?,
id: area.id.clone(),
center: world_position(world, entity).to_array(),
half_extents: world_aabb_half_extents(
world_transform(world, entity),
area.half_extents,
)
.to_array(),
cost: area.cost,
walkable: area.walkable,
};
if aabb_overlaps(center, half_extents, value.center, value.half_extents) {
areas.push(value);
}
}
areas.sort_by(|a, b| a.actor_id.cmp(&b.actor_id));
let mut links = Vec::new();
let mut link_query = world.query::<(Entity, &NavigationLink)>();
for (entity, link) in link_query.iter(world) {
let transform = world_transform(world, entity);
let value = NavigationLinkInput {
actor_id: actor_id(world, entity)?,
start: transform.transform_point(link.start).to_array(),
end: transform.transform_point(link.end).to_array(),
bidirectional: link.bidirectional,
cost: link.cost,
enabled: link.enabled,
};
if point_in_aabb(value.start, center, half_extents)
|| point_in_aabb(value.end, center, half_extents)
{
links.push(value);
}
}
links.sort_by(|a, b| a.actor_id.cmp(&b.actor_id));
let mut geometry = Vec::new();
let mut geometry_query = world.query::<(Entity, Option<&Primitive>, Option<&BrushDesc>)>();
for (entity, primitive, brush) in geometry_query.iter(world) {
if primitive.is_none() && brush.is_none() {
continue;
}
let transform = world_transform(world, entity);
let Some(value) = navigation_geometry_from_parts(
actor_id(world, entity)?,
transform.translation.to_array(),
transform.rotation.to_array(),
transform.scale.to_array(),
primitive,
brush,
) else {
continue;
};
if geometry_overlaps_bounds(&value, center, half_extents) {
geometry.push(value);
}
}
geometry.sort_by(|a, b| a.actor_id.cmp(&b.actor_id));
Ok(NavigationBakeInput {
source_scene,
bounds_actor_id,
center,
half_extents,
agent: bounds.agent.clone(),
geometry,
obstacles,
areas,
links,
})
}
fn actor_id(world: &World, entity: Entity) -> Result<String, String> {
world
.get::<ActorId>(entity)
.map(|id| id.0.clone())
.filter(|id| !id.trim().is_empty())
.ok_or_else(|| format!("navigation actor {entity:?} requires a stable ActorId"))
}
fn world_transform(world: &World, entity: Entity) -> Transform {
let mut chain = Vec::new();
let mut current = entity;
let mut visited = HashSet::new();
while visited.insert(current) {
chain.push(world.get::<Transform>(current).copied().unwrap_or_default());
let Some(parent) = world.get::<ChildOf>(current).map(ChildOf::parent) else {
break;
};
current = parent;
}
if world.get::<ChildOf>(current).is_some() {
return Transform::default();
}
let mut chain = chain.into_iter().rev();
let root = chain.next().unwrap_or_default();
chain
.fold(GlobalTransform::from(root), |global, local| {
global.mul_transform(local)
})
.compute_transform()
}
fn world_position(world: &World, entity: Entity) -> Vec3 {
world_transform(world, entity).translation
}
fn world_aabb_half_extents(transform: Transform, local_half_extents: Vec3) -> Vec3 {
let half = transform.scale.abs() * local_half_extents;
let x = transform.rotation * Vec3::X;
let y = transform.rotation * Vec3::Y;
let z = transform.rotation * Vec3::Z;
x.abs() * half.x + y.abs() * half.y + z.abs() * half.z
}
fn artifact_path(world: &World, authored: &str) -> Result<PathBuf, String> {
let relative = Path::new(authored);
if relative.is_absolute()
|| relative
.components()
.any(|component| matches!(component, std::path::Component::ParentDir))
{
return Err("navigation artifact path must stay inside the project".into());
}
if !authored
.replace('\\', "/")
.starts_with("assets/navigation/generated/")
{
return Err("navigation artifacts must be under assets/navigation/generated/".into());
}
Ok(Path::new(&world.resource::<ProjectWorkspace>().root).join(relative))
}
fn set_status(world: &mut World, message: impl Into<String>, error: bool) {
let message = message.into();
let mut state = world.resource_mut::<NavigationEditorState>();
state.status.clone_from(&message);
state.error = error;
if error {
state.preview_path.clear();
}
world.resource_mut::<SceneIo>().set_status(message);
}
fn vec3_editor(ui: &mut egui::Ui, value: &mut Vec3, speed: f64) -> egui::Response {
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut value.x).speed(speed));
ui.add(egui::DragValue::new(&mut value.y).speed(speed));
ui.add(egui::DragValue::new(&mut value.z).speed(speed))
})
.response
}
#[derive(Debug, Clone, Copy)]
pub enum NavigationActorType {
Bounds,
Obstacle,
Area,
Link,
}
pub fn spawn_navigation_actor(world: &mut World, actor_type: NavigationActorType) -> Entity {
let rect = world.resource::<crate::ui::UiState>().viewport_rect;
let settings = world.resource::<ViewportSettings>().clone();
let translation = snap_translation(editor_spawn_ground_position(world, rect), &settings);
let (name, bounds, obstacle, area, link) = match actor_type {
NavigationActorType::Bounds => (
"Navigation Bounds",
Some(NavigationBounds::default()),
None,
None,
None,
),
NavigationActorType::Obstacle => (
"Navigation Obstacle",
None,
Some(NavigationObstacle::default()),
None,
None,
),
NavigationActorType::Area => (
"Navigation Area",
None,
None,
Some(NavigationArea::default()),
None,
),
NavigationActorType::Link => (
"Navigation Link",
None,
None,
None,
Some(NavigationLink::default()),
),
};
let mut snapshot =
super::helpers::primitive_snapshot(name, shared::PrimitiveShape::Box, translation);
snapshot.actor_kind = shared::ActorKind::Navigation;
snapshot.primitive = None;
snapshot.material = None;
snapshot.physics = None;
snapshot.collider = None;
snapshot.rigid_body = None;
snapshot.navigation_bounds = bounds;
snapshot.navigation_obstacle = obstacle;
snapshot.navigation_area = area;
snapshot.navigation_link = link;
crate::history::spawn_with_history(world, snapshot)
}
pub fn sync_navigation_state(world: &mut World) {
let selected = world.resource::<crate::selection::SelectedEntity>().0;
let Some(entity) = selected.filter(|entity| world.get::<NavigationBounds>(*entity).is_some())
else {
return;
};
let Some(bounds) = world.get::<NavigationBounds>(entity).cloned() else {
return;
};
let input = match build_input(world, entity, &bounds) {
Ok(input) => input,
Err(_) => return,
};
let fingerprint = navigation_source_fingerprint(&input);
let changed_bounds = world.resource::<NavigationEditorState>().bounds_entity != Some(entity);
if changed_bounds {
let loaded = artifact_path(world, &bounds.artifact_path)
.ok()
.and_then(|path| read_navigation_artifact(&path).ok());
let mut state = world.resource_mut::<NavigationEditorState>();
state.bounds_entity = Some(entity);
state.artifact = loaded;
state.preview_path.clear();
state.observed_fingerprint = None;
state.auto_bake_attempt = None;
state.debounce_elapsed = 0.0;
}
let delta = world.resource::<Time>().delta_secs();
let mut should_bake = false;
{
let mut state = world.resource_mut::<NavigationEditorState>();
if state.observed_fingerprint.as_deref() != Some(&fingerprint) {
state.observed_fingerprint = Some(fingerprint.clone());
state.auto_bake_attempt = None;
state.debounce_elapsed = 0.0;
}
let stale = state
.artifact
.as_ref()
.is_none_or(|artifact| artifact.source_fingerprint != fingerprint);
if stale {
state.debounce_elapsed += delta;
if !state.error {
state.status = "Authored navigation changed; rebake required".into();
}
should_bake = bounds.auto_bake
&& state.debounce_elapsed >= 0.75
&& state.auto_bake_attempt.as_deref() != Some(&fingerprint);
if should_bake {
state.auto_bake_attempt = Some(fingerprint.clone());
}
} else if state.status == "Not baked"
|| state.status == "Authored navigation changed; rebake required"
{
state.status = format!("Current: {}", bounds.artifact_path);
state.error = false;
}
}
if should_bake {
bake_bounds(world, entity);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn world_transform_uses_current_authored_parent_chain() {
let mut world = World::new();
let parent = world.spawn(Transform::from_xyz(4.0, 0.0, 0.0)).id();
let child = world
.spawn((Transform::from_xyz(0.0, 0.0, 2.0), ChildOf(parent)))
.id();
world
.entity_mut(child)
.insert(Transform::from_xyz(0.0, 0.0, 3.0));
assert_eq!(
world_transform(&world, child).translation,
Vec3::new(4.0, 0.0, 3.0)
);
}
}
+19
View File
@@ -141,6 +141,25 @@ fn left_toolbar(world: &mut World, ui: &mut egui::Ui) {
if icon_button(ui, icons::PENCIL_SIMPLE_LINE, "Draw brush (B)").clicked() {
start_draw_brush_tool(world);
}
let selected_navigation_bounds = world
.resource::<crate::selection::SelectedEntity>()
.0
.filter(|entity| world.get::<shared::NavigationBounds>(*entity).is_some());
let navigation_tip = if selected_navigation_bounds.is_some() {
"Bake selected navigation bounds"
} else {
"Create navigation bounds"
};
if icon_button(ui, icons::PATH, navigation_tip).clicked() {
if let Some(entity) = selected_navigation_bounds {
super::navigation_inspector::bake_bounds(world, entity);
} else {
super::navigation_inspector::spawn_navigation_actor(
world,
super::navigation_inspector::NavigationActorType::Bounds,
);
}
}
toolbar_separator(ui);
+2 -2
View File
@@ -875,7 +875,7 @@ fn viewport_asset_drop_ui(
.as_slice()
.iter()
.copied()
.find(|entity| world.get::<shared::ModelRef>(*entity).is_some())
.find(|entity| world.get::<shared::SkinnedMeshRenderer>(*entity).is_some())
{
assign_animation_clip_operator(world, selection, entity);
} else {
@@ -1011,7 +1011,7 @@ fn asset_drag_descriptor(
} if selected
.as_slice()
.iter()
.any(|entity| world.get::<shared::ModelRef>(*entity).is_some()) =>
.any(|entity| world.get::<shared::SkinnedMeshRenderer>(*entity).is_some()) =>
{
"Assign clip to animated actor"
}
+20 -2
View File
@@ -16,8 +16,8 @@ use bevy::shader::ShaderRef;
use shared::{
ActorKind, AudioListenerDesc, AudioSourceDesc, AuthoringLightKind, ColliderDesc, LevelObject,
LightDesc, ModelRef, ObjectiveMarker, PhysicsBody, PlayerSpawn, PostProcessVolumeDesc,
PrefabInstance, PrefabRef, Primitive, RaytracingExcluded, StaticMeshRenderer, TeamSpawn,
TriggerVolume, WeaponSpawn,
PrefabInstance, PrefabRef, Primitive, RaytracingExcluded, SkinnedMeshRenderer,
StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn,
};
use crate::camera::EditorCamera;
@@ -203,6 +203,7 @@ struct ActorIconComponents {
light_kind: Option<AuthoringLightKind>,
has_primitive: bool,
has_static_mesh_renderer: bool,
has_skinned_mesh_renderer: bool,
has_model_ref: bool,
has_prefab_ref: bool,
has_prefab_instance: bool,
@@ -386,6 +387,7 @@ fn sync_actor_icons(
),
(With<LevelObject>, Without<EditorOnly>),
>,
skinned_meshes: Query<(), With<SkinnedMeshRenderer>>,
audio: Query<(Has<AudioSourceDesc>, Has<AudioListenerDesc>)>,
physics: Query<(), Or<(With<PhysicsBody>, With<ColliderDesc>)>>,
) {
@@ -419,6 +421,7 @@ fn sync_actor_icons(
has_primitive,
has_static_mesh_renderer: static_mesh_renderer
.is_some_and(has_resolved_static_mesh_slot),
has_skinned_mesh_renderer: skinned_meshes.contains(target),
has_model_ref,
has_prefab_ref,
has_prefab_instance,
@@ -489,6 +492,7 @@ fn sync_actor_icons(
has_primitive,
has_static_mesh_renderer: static_mesh_renderer
.is_some_and(has_resolved_static_mesh_slot),
has_skinned_mesh_renderer: skinned_meshes.contains(target),
has_model_ref,
has_prefab_ref,
has_prefab_instance,
@@ -637,6 +641,16 @@ fn icon_for_actor_components(components: ActorIconComponents) -> ActorIconSpec {
warning
}
}
ActorKind::SkinnedMesh => {
if components.has_skinned_mesh_renderer {
ActorIconSpec {
image: ActorIconImage::Mesh,
category: ActorIconCategory::Mesh,
}
} else {
warning
}
}
ActorKind::ImportedModel => {
if components.has_model_ref {
ActorIconSpec {
@@ -752,6 +766,10 @@ fn icon_for_actor_components(components: ActorIconComponents) -> ActorIconSpec {
warning
}
}
ActorKind::Navigation => ActorIconSpec {
image: ActorIconImage::GameMarker,
category: ActorIconCategory::Volume,
},
ActorKind::Empty => {
if components.has_physics {
ActorIconSpec {
+11
View File
@@ -374,6 +374,7 @@ fn brush_snapshot_from_convex_points(
primitive: None,
brush: Some(brush),
static_mesh_renderer: None,
skinned_mesh_renderer: None,
material: Some(MaterialDesc::default()),
material_override: None,
rigid_body: None,
@@ -392,8 +393,18 @@ fn brush_snapshot_from_convex_points(
post_process_volume: None,
team_spawn: None,
objective: None,
navigation_bounds: None,
navigation_obstacle: None,
navigation_area: None,
navigation_link: None,
hierarchy_sibling_index: 0,
editor_visibility: EditorVisibility::default(),
inspector_order: None,
component_states: None,
children: Vec::new(),
})
}
@@ -290,14 +290,33 @@ fn solari_geometry_summary(world: &World, ui: &mut egui::Ui) {
ui.separator();
ui.heading("Solari raytracing scene");
ui.label(format!(
"Project meshes: {} tagged, {} eligible, {} Solari-compatible assets, {} unsupported, {} excluded helpers, {} outside level roots",
"Project meshes: {} tagged, {} eligible, {} Solari-compatible assets, {} unsupported, {} deformed safely omitted, {} excluded helpers, {} outside level roots",
stats.tagged_meshes,
stats.project_meshes,
stats.compatible_mesh_assets,
stats.unsupported_meshes,
stats.deformed_meshes_excluded,
stats.excluded_meshes,
stats.missing_level_root_meshes
));
if stats.surface_material_meshes > 0 {
ui.label(format!(
"Surface ABI materials: {} meshes, {} missing an active evaluator generation",
stats.surface_material_meshes, stats.surface_materials_missing_evaluator
));
}
if stats.deformed_meshes_excluded > 0 {
ui.colored_label(
egui::Color32::from_rgb(255, 180, 100),
"Skinned/morphed meshes are omitted from Solari until dynamic deformed BLAS is available; no bind-pose proxy is traced.",
);
}
if stats.surface_materials_missing_evaluator > 0 {
ui.colored_label(
egui::Color32::from_rgb(255, 140, 140),
"Surface meshes without a validated evaluator are omitted instead of using an approximate ray-tracing material.",
);
}
if stats.incompatible_mesh_assets > 0 {
ui.colored_label(
egui::Color32::from_rgb(255, 180, 100),
@@ -457,6 +476,7 @@ pub fn spawn_post_process_volume_at_camera(world: &mut World) {
primitive: None,
brush: None,
static_mesh_renderer: None,
skinned_mesh_renderer: None,
material: None,
material_override: None,
rigid_body: None,
@@ -475,8 +495,18 @@ pub fn spawn_post_process_volume_at_camera(world: &mut World) {
post_process_volume: Some(PostProcessVolumeDesc::default()),
team_spawn: None,
objective: None,
navigation_bounds: None,
navigation_obstacle: None,
navigation_area: None,
navigation_link: None,
hierarchy_sibling_index: 0,
editor_visibility: EditorVisibility::default(),
inspector_order: None,
component_states: None,
children: Vec::new(),
};
spawn_with_history(world, snapshot);
+133 -4
View File
@@ -5,8 +5,9 @@ use bevy::ecs::system::SystemParam;
use bevy::prelude::*;
use shared::{
AudioListenerDesc, AudioSourceDesc, AuthoringLightKind, ColliderDesc, ColliderShapeDesc,
LevelObject, LightDesc, ModelRef, ObjectiveMarker, PhysicsBody, PlayerSpawn,
PostProcessVolumeDesc, PrefabRef, ProjectSun, RaytracingExcluded, TeamSpawn, TriggerVolume,
LevelObject, LightDesc, ModelRef, NavigationArea, NavigationBounds, NavigationLink,
NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn, PostProcessVolumeDesc,
PrefabRef, ProjectSun, RaytracingExcluded, SkinnedMeshRenderer, TeamSpawn, TriggerVolume,
WeaponSpawn,
};
use sim::tuning::{EYE_OFFSET_STAND, PLAYER_LENGTH, PLAYER_RADIUS};
@@ -107,7 +108,15 @@ struct VisualizerTargetQueries<'w, 's> {
lights: Query<'w, 's, Entity, (With<LevelObject>, With<LightDesc>)>,
spawns: Query<'w, 's, Entity, (With<LevelObject>, With<PlayerSpawn>)>,
prefabs: Query<'w, 's, Entity, (With<LevelObject>, With<PrefabRef>)>,
models: Query<'w, 's, Entity, (With<LevelObject>, With<ModelRef>)>,
models: Query<
'w,
's,
Entity,
(
With<LevelObject>,
Or<(With<ModelRef>, With<SkinnedMeshRenderer>)>,
),
>,
players: Query<'w, 's, Entity, With<Player>>,
cameras: Query<'w, 's, Entity, With<PlayerCamera>>,
project_suns: Query<'w, 's, Entity, With<ProjectSun>>,
@@ -127,6 +136,7 @@ impl Plugin for EditorVisualizersPlugin {
draw_audio_visualizers,
draw_split_collider_visualizers,
draw_post_process_volume_gizmos,
draw_navigation_visualizers,
)
.chain()
.run_if(scene_tools_active)
@@ -135,6 +145,119 @@ impl Plugin for EditorVisualizersPlugin {
}
}
fn draw_navigation_visualizers(
state: Res<crate::ui::navigation_inspector::NavigationEditorState>,
mut gizmos: Gizmos,
bounds: Query<(&NavigationBounds, &GlobalTransform), With<LevelObject>>,
obstacles: Query<(&NavigationObstacle, &GlobalTransform), With<LevelObject>>,
areas: Query<(&NavigationArea, &GlobalTransform), With<LevelObject>>,
links: Query<(&NavigationLink, &GlobalTransform), With<LevelObject>>,
) {
for (value, global) in &bounds {
let (_, rotation, center) = global.to_scale_rotation_translation();
draw_box(
&mut gizmos,
center,
rotation,
value.half_extents,
Color::srgba(0.12, 0.82, 0.78, 0.72),
);
}
for (value, global) in &obstacles {
let (_, rotation, center) = global.to_scale_rotation_translation();
draw_box(
&mut gizmos,
center,
rotation,
value.half_extents,
Color::srgba(1.0, 0.28, 0.22, 0.78),
);
}
for (value, global) in &areas {
let (_, rotation, center) = global.to_scale_rotation_translation();
let color = if value.walkable {
Color::srgba(0.32, 0.72, 1.0, 0.62)
} else {
Color::srgba(1.0, 0.55, 0.18, 0.72)
};
draw_box(&mut gizmos, center, rotation, value.half_extents, color);
}
for (value, global) in &links {
let start = global.transform_point(value.start);
let end = global.transform_point(value.end);
let color = if value.enabled {
Color::srgba(0.95, 0.78, 0.22, 0.95)
} else {
Color::srgba(0.48, 0.48, 0.5, 0.55)
};
gizmos.line(start, end, color);
gizmos
.sphere(Isometry3d::from_translation(start), 0.11, color)
.resolution(12);
gizmos
.sphere(Isometry3d::from_translation(end), 0.11, color)
.resolution(12);
}
if state.show_mesh {
if let Some(artifact) = &state.artifact {
for layer in &artifact.mesh.layers {
for polygon in &layer.polygons {
for index in 0..polygon.vertices.len() {
let a_index = polygon.vertices[index] as usize;
let b_index =
polygon.vertices[(index + 1) % polygon.vertices.len()] as usize;
let Some(a) = navigation_vertex(layer, a_index) else {
continue;
};
let Some(b) = navigation_vertex(layer, b_index) else {
continue;
};
gizmos.line(
a + Vec3::Y * 0.025,
b + Vec3::Y * 0.025,
Color::srgba(0.08, 0.9, 0.72, 0.7),
);
}
}
}
}
}
for edge in state.preview_path.windows(2) {
gizmos.line(
edge[0] + Vec3::Y * 0.08,
edge[1] + Vec3::Y * 0.08,
Color::srgba(0.98, 0.88, 0.2, 1.0),
);
}
if let Some(start) = state.preview_path.first().copied() {
gizmos
.sphere(
Isometry3d::from_translation(start + Vec3::Y * 0.08),
0.16,
Color::srgba(0.2, 1.0, 0.55, 1.0),
)
.resolution(14);
}
if let Some(end) = state.preview_path.last().copied() {
gizmos
.sphere(
Isometry3d::from_translation(end + Vec3::Y * 0.08),
0.16,
Color::srgba(1.0, 0.28, 0.22, 1.0),
)
.resolution(14);
}
}
fn navigation_vertex(layer: &polyanya::Layer, index: usize) -> Option<Vec3> {
let vertex = layer.vertices.get(index)?;
let height = layer.height.get(index).copied().unwrap_or_default();
let coords = vertex.coords + layer.offset;
Some(Vec3::new(coords.x, height, coords.y))
}
fn draw_audio_visualizers(
viewport_mode: Res<EditorViewportMode>,
settings: Res<EditorVisualizationSettings>,
@@ -399,7 +522,13 @@ fn draw_visualizers(
lights: Query<(Entity, &LightDesc, &GlobalTransform), With<LevelObject>>,
spawns: Query<(Entity, &GlobalTransform), (With<LevelObject>, With<PlayerSpawn>)>,
prefabs: Query<(Entity, &GlobalTransform), (With<LevelObject>, With<PrefabRef>)>,
models: Query<(Entity, &GlobalTransform), (With<LevelObject>, With<ModelRef>)>,
models: Query<
(Entity, &GlobalTransform),
(
With<LevelObject>,
Or<(With<ModelRef>, With<SkinnedMeshRenderer>)>,
),
>,
players: Query<(Entity, &GlobalTransform), With<Player>>,
cameras: Query<(Entity, &GlobalTransform), With<PlayerCamera>>,
project_suns: Query<(Entity, &GlobalTransform), With<ProjectSun>>,