feat: complete M2 content workspace and inspector

This commit is contained in:
Rbanh committed 2026-07-17 23:40:49 -04:00
1 parent 931f561e7f
commit cf6eaba534
438 files changed
+59749 -19043

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,67 @@
//! Editor-owned live Material and Material Instance values.
use std::collections::HashMap;
use bevy::prelude::Resource;
use shared::{MaterialAsset, MaterialInstanceAsset, MaterialRef};
#[derive(Debug, Clone)]
pub enum LiveMaterialDocument {
Material(MaterialAsset),
Instance(MaterialInstanceAsset),
}
#[derive(Debug, Clone)]
pub struct LiveMaterialDocumentEntry {
pub revision: u64,
pub document: LiveMaterialDocument,
}
#[derive(Resource, Default, Debug)]
pub struct LiveMaterialDocumentOverlay {
documents: HashMap<String, LiveMaterialDocumentEntry>,
}
impl LiveMaterialDocumentOverlay {
pub fn update_material(
&mut self,
asset_id: impl Into<String>,
revision: u64,
asset: MaterialAsset,
) {
self.documents.insert(
asset_id.into(),
LiveMaterialDocumentEntry {
revision,
document: LiveMaterialDocument::Material(asset),
},
);
}
pub fn update_instance(
&mut self,
asset_id: impl Into<String>,
revision: u64,
instance: MaterialInstanceAsset,
) {
self.documents.insert(
asset_id.into(),
LiveMaterialDocumentEntry {
revision,
document: LiveMaterialDocument::Instance(instance),
},
);
}
pub fn remove(&mut self, asset_id: &str) {
self.documents.remove(asset_id);
}
pub fn revision_for_asset(&self, asset_id: &str) -> Option<u64> {
self.documents.get(asset_id).map(|entry| entry.revision)
}
pub(crate) fn get(&self, reference: &MaterialRef) -> Option<&LiveMaterialDocumentEntry> {
self.documents.get(&reference.0.asset_id)
}
}
@@ -0,0 +1,138 @@
use super::*;
#[derive(Resource, Default)]
pub struct SurfaceMaterialCache {
pub(super) handles: HashMap<MaterialRef, Handle<SurfaceMaterial>>,
pub(super) standard_handles: HashMap<MaterialRef, Handle<StandardMaterial>>,
pub(super) revisions: HashMap<MaterialRef, u64>,
pub(super) standard_only: HashMap<MaterialRef, u64>,
pub(super) instance_bases: HashMap<MaterialRef, MaterialRef>,
pub(super) failed_revisions: HashMap<MaterialRef, u64>,
pub(super) disk_generation: u64,
}
impl SurfaceMaterialCache {
/// Invalidates disk-backed project materials after an explicit save or watcher event.
/// Interactive edits use `LiveMaterialDocumentOverlay`, so synchronization never needs to
/// stat or reparse authored files for every bound entity on every frame.
pub fn invalidate_disk_documents(&mut self) {
self.disk_generation = self.disk_generation.wrapping_add(1);
self.failed_revisions.clear();
}
pub(super) fn disk_generation(&self) -> u64 {
self.disk_generation
}
pub(super) fn revision_for_handles(
&self,
standard: Option<&MeshMaterial3d<StandardMaterial>>,
surface: Option<&MeshMaterial3d<SurfaceMaterial>>,
) -> u64 {
if let Some(handle) = standard {
if let Some((reference, _)) = self
.standard_handles
.iter()
.find(|(_, cached)| cached.id() == handle.0.id())
{
return self
.standard_only
.get(reference)
.copied()
.unwrap_or_default();
}
}
if let Some(handle) = surface {
if let Some((reference, _)) = self
.handles
.iter()
.find(|(_, cached)| cached.id() == handle.0.id())
{
return self.revisions.get(reference).copied().unwrap_or_default();
}
}
0
}
}
#[derive(Resource, Default)]
pub(super) struct MaterialPropertyBlockCache {
pub(super) entries: HashMap<(Entity, String), PropertyBlockCacheEntry>,
}
pub(super) enum PropertyBlockHandle {
Standard(Handle<StandardMaterial>),
Surface(Handle<SurfaceMaterial>),
}
pub(super) struct PropertyBlockCacheEntry {
pub(super) revision: u64,
pub(super) handle: PropertyBlockHandle,
}
#[derive(Resource, Default, Debug, Clone)]
pub struct DefaultGridMaterialHandles {
pub surface: Option<Handle<SurfaceMaterial>>,
pub emergency_standard: Option<Handle<StandardMaterial>>,
}
pub(super) enum BuiltRendererMaterial {
Standard(Box<StandardMaterial>),
Surface(Box<SurfaceMaterial>),
}
#[derive(Resource, Default, Debug, Clone)]
pub struct SurfaceDiagnostics(pub Vec<String>);
pub(super) fn record_diagnostic(diagnostics: &mut Vec<String>, message: String) {
if diagnostics.iter().any(|existing| existing == &message) {
return;
}
const MAX_DIAGNOSTICS: usize = 256;
if diagnostics.len() == MAX_DIAGNOSTICS {
diagnostics.remove(0);
}
diagnostics.push(message);
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SurfaceEvaluatorRecord {
pub shader_id: u32,
pub evaluator_source: String,
pub revision: u64,
pub alpha_mode: shared::MaterialAlphaMode,
}
/// Active, validated evaluator generation consumed by both raster and Solari render worlds.
#[derive(Resource, ExtractResource, Default, Debug, Clone)]
pub struct SurfaceEvaluatorRegistry {
pub evaluators: HashMap<u32, SurfaceEvaluatorRecord>,
}
pub struct SurfaceMaterialPlugin;
impl Plugin for SurfaceMaterialPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(MaterialPlugin::<SurfaceMaterial>::default())
.add_plugins(MaterialPlugin::<TerrainLayerMaterial>::default())
.init_resource::<SurfaceMaterialCache>()
.init_resource::<LiveMaterialDocumentOverlay>()
.init_resource::<TerrainLayerMaterialCache>()
.init_resource::<SurfaceDiagnostics>()
.init_resource::<SurfaceEvaluatorRegistry>()
.init_resource::<DefaultGridMaterialHandles>()
.init_resource::<MaterialPropertyBlockCache>()
.init_resource::<shared::ProjectContentDefaults>()
.add_systems(
Update,
(
(
sync_surface_material_bindings,
apply_material_property_blocks,
)
.chain(),
sync_terrain_layer_material_bindings,
),
);
}
}
@@ -0,0 +1,229 @@
use super::*;
pub(super) fn pack_schema_values(
extension: &mut SurfaceExtension,
schema: &ShaderSchemaAsset,
inputs: &shared::MaterialInputSet,
instance: Option<&MaterialInstanceAsset>,
asset_server: &AssetServer,
runtime_catalog: Option<&RuntimeContentCatalog>,
) -> Result<(), String> {
let mut numeric_index = 0usize;
let mut texture_index = 0usize;
for property in &schema.schema.inputs {
if property.texture.is_some()
|| matches!(property.property_type, ShaderPropertyType::Texture)
{
if texture_index >= SURFACE_TEXTURE_SLOTS {
return Err(format!(
"surface schema exceeds {SURFACE_TEXTURE_SLOTS} textures"
));
}
let binding = instance
.and_then(|instance| {
instance
.overrides
.textures
.iter()
.find(|value| value.name == property.name)
})
.or_else(|| {
inputs
.textures
.iter()
.find(|value| value.name == property.name)
});
let handle = binding
.and_then(|binding| binding.texture.as_ref())
.and_then(|reference| {
runtime_texture_spec(
runtime_catalog,
reference,
property.texture.as_ref().is_some_and(|texture| {
texture.semantic == shared::TextureSemantic::Color
}),
)
})
.map(|spec| shared::load_runtime_texture(asset_server, &spec));
extension.set_texture(texture_index, handle);
texture_index += 1;
}
if matches!(property.property_type, ShaderPropertyType::Texture) {
continue;
}
if numeric_index >= SURFACE_PARAMETER_LANES {
return Err(format!(
"surface schema exceeds {SURFACE_PARAMETER_LANES} parameter lanes"
));
}
let value = instance
.and_then(|instance| {
instance
.overrides
.values
.iter()
.find(|value| value.name == property.name)
})
.or_else(|| {
inputs
.values
.iter()
.find(|value| value.name == property.name)
})
.map(|value| &value.value)
.or(property.default_value.as_ref());
extension.uniform.params[numeric_index] = value
.map(|value| parameter_lane(value, &property.property_type))
.transpose()?
.unwrap_or(Vec4::ZERO);
numeric_index += 1;
}
Ok(())
}
pub(super) fn load_runtime_content_catalog() -> Option<RuntimeContentCatalog> {
let source = fs::read_to_string("assets/content.catalog.ron").ok()?;
ron::from_str(&source).ok()
}
pub(super) fn runtime_texture_path(
catalog: Option<&RuntimeContentCatalog>,
reference: &shared::EditorAssetRef,
) -> Option<String> {
catalog
.and_then(|catalog| {
catalog
.records
.iter()
.find(|record| record.id.as_string() == reference.asset_id)
})
.and_then(|record| record.texture.as_ref())
.and_then(|runtime| runtime.processed_path.clone())
.or_else(|| reference.source_path.clone())
}
pub(super) fn runtime_texture_spec(
catalog: Option<&RuntimeContentCatalog>,
reference: &shared::EditorAssetRef,
fallback_srgb: bool,
) -> Option<shared::RuntimeTextureLoadSpec> {
catalog
.and_then(|catalog| catalog.texture_load_spec(reference))
.or_else(|| {
reference
.source_path
.as_ref()
.map(|path| shared::RuntimeTextureLoadSpec {
path: path.clone(),
is_srgb: fallback_srgb,
filter: shared::TextureFilter::Linear,
wrap: shared::TextureWrap::Repeat,
anisotropy: 8,
})
})
}
pub(super) fn packed_runtime_texture_spec(
catalog: Option<&RuntimeContentCatalog>,
inputs: &MaterialInputSet,
instance: Option<&MaterialInstanceAsset>,
material: &MaterialRef,
) -> Result<Option<shared::RuntimeTextureLoadSpec>, String> {
let Some(catalog) = catalog else {
return Ok(None);
};
let Some(path) = catalog
.records
.iter()
.find(|record| record.id.as_string() == material.0.asset_id)
.and_then(|record| record.material.as_ref())
.and_then(|runtime| runtime.packed_arm_path.clone())
else {
return Ok(None);
};
let mut source_specs = ["occlusion", "roughness", "metallic"]
.into_iter()
.filter_map(|name| {
instance
.and_then(|instance| instance.overrides.texture(name))
.or_else(|| inputs.texture(name))
.and_then(|binding| binding.texture.as_ref())
.and_then(|reference| catalog.texture_load_spec(reference))
});
let Some(first) = source_specs.next() else {
return Ok(None);
};
if source_specs.any(|spec| {
spec.filter != first.filter
|| spec.wrap != first.wrap
|| spec.anisotropy != first.anisotropy
}) {
return Err("packed AO/roughness/metallic textures must use matching filter, wrap, and anisotropy settings".into());
}
Ok(Some(shared::RuntimeTextureLoadSpec {
path,
is_srgb: false,
filter: first.filter,
wrap: first.wrap,
anisotropy: first.anisotropy,
}))
}
pub(super) fn apply_runtime_texture_paths(
resolved: &mut MaterialDesc,
inputs: &MaterialInputSet,
instance: Option<&MaterialInstanceAsset>,
material: &MaterialRef,
catalog: Option<&RuntimeContentCatalog>,
) {
let binding = |name: &str| {
instance
.and_then(|instance| instance.overrides.texture(name))
.or_else(|| inputs.texture(name))
.and_then(|binding| binding.texture.as_ref())
.and_then(|reference| runtime_texture_path(catalog, reference))
};
resolved.base_color_texture = binding("base_color");
resolved.normal_map_texture = binding("normal");
resolved.emissive_texture = binding("emissive");
let packed_arm = catalog
.and_then(|catalog| {
catalog
.records
.iter()
.find(|record| record.id.as_string() == material.0.asset_id)
})
.and_then(|record| record.material.as_ref())
.and_then(|runtime| runtime.packed_arm_path.clone());
resolved.metallic_roughness_texture = packed_arm.clone();
resolved.occlusion_texture = packed_arm;
}
pub(super) fn parameter_lane(
value: &MaterialParameterValue,
property_type: &ShaderPropertyType,
) -> Result<Vec4, String> {
match (value, property_type) {
(MaterialParameterValue::Bool(value), ShaderPropertyType::Bool) => {
Ok(Vec4::new(u32::from(*value) as f32, 0.0, 0.0, 0.0))
}
(MaterialParameterValue::Float(value), ShaderPropertyType::Float { .. }) => {
Ok(Vec4::new(*value, 0.0, 0.0, 0.0))
}
(MaterialParameterValue::Vec2(value), ShaderPropertyType::Vec2) => {
Ok(Vec4::new(value.x, value.y, 0.0, 0.0))
}
(MaterialParameterValue::Vec3(value), ShaderPropertyType::Vec3) => Ok(value.extend(0.0)),
(MaterialParameterValue::Color(value), ShaderPropertyType::Color) => {
Ok(Vec4::new(value.r, value.g, value.b, value.a))
}
(MaterialParameterValue::Enum(value), ShaderPropertyType::Enum { options }) => {
let index = options
.iter()
.position(|option| option == value)
.ok_or_else(|| format!("enum value `{value}` is not declared by the schema"))?;
Ok(Vec4::new(index as f32, 0.0, 0.0, 0.0))
}
_ => Err("material value does not match shader schema type".into()),
}
}
@@ -0,0 +1,523 @@
use super::*;
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
pub(super) fn apply_material_property_blocks(
mut commands: Commands,
asset_server: Res<AssetServer>,
owners: Query<&MaterialPropertyBlocks>,
bindings: Query<(
Entity,
&HydratedMaterialSlotBinding,
Option<&MeshMaterial3d<StandardMaterial>>,
Option<&MeshMaterial3d<SurfaceMaterial>>,
)>,
mut standard_materials: ResMut<Assets<StandardMaterial>>,
mut surface_materials: ResMut<Assets<SurfaceMaterial>>,
surface_cache: Res<SurfaceMaterialCache>,
mut cache: ResMut<MaterialPropertyBlockCache>,
mut diagnostics: ResMut<SurfaceDiagnostics>,
) {
let mut active = HashSet::new();
for (entity, binding, standard_handle, surface_handle) in &bindings {
let Ok(blocks) = owners.get(binding.owner) else {
continue;
};
let Some(block) = blocks
.slots
.iter()
.find(|block| block.slot_id == binding.slot_id)
else {
continue;
};
let revision = property_block_revision(
block,
standard_handle,
surface_handle,
surface_cache.revision_for_handles(standard_handle, surface_handle),
);
let key = (binding.owner, binding.slot_id.0.clone());
active.insert(key.clone());
let cached = cache
.entries
.get(&key)
.filter(|entry| entry.revision == revision);
let handle = if let Some(entry) = cached {
match &entry.handle {
PropertyBlockHandle::Standard(handle) => {
PropertyBlockHandle::Standard(handle.clone())
}
PropertyBlockHandle::Surface(handle) => {
PropertyBlockHandle::Surface(handle.clone())
}
}
} else if let Some(source) = surface_handle
.and_then(|handle| surface_materials.get(&handle.0))
.cloned()
{
let mut material = source;
let application =
apply_standard_property_block(&mut material.base, block, &asset_server, true)
.and_then(|()| {
binding
.selection
.project_reference()
.map_or(Ok(()), |reference| {
apply_surface_property_block(
&mut material,
reference,
block,
&asset_server,
)
})
});
if let Err(error) = application {
record_diagnostic(
&mut diagnostics.0,
format!(
"material property block for {} was ignored: {error}",
binding.slot_id.0
),
);
continue;
}
let handle = cache
.entries
.get(&key)
.and_then(|entry| match &entry.handle {
PropertyBlockHandle::Surface(handle) => Some(handle.clone()),
PropertyBlockHandle::Standard(_) => None,
});
if let Some(handle) = handle {
if let Some(mut existing) = surface_materials.get_mut(&handle) {
*existing = material;
}
PropertyBlockHandle::Surface(handle)
} else {
PropertyBlockHandle::Surface(surface_materials.add(material))
}
} else if let Some(source) = standard_handle
.and_then(|handle| standard_materials.get(&handle.0))
.cloned()
{
let mut material = source;
if let Err(error) =
apply_standard_property_block(&mut material, block, &asset_server, false)
{
record_diagnostic(
&mut diagnostics.0,
format!(
"material property block for {} was ignored: {error}",
binding.slot_id.0
),
);
continue;
}
let handle = cache
.entries
.get(&key)
.and_then(|entry| match &entry.handle {
PropertyBlockHandle::Standard(handle) => Some(handle.clone()),
PropertyBlockHandle::Surface(_) => None,
});
if let Some(handle) = handle {
if let Some(mut existing) = standard_materials.get_mut(&handle) {
*existing = material;
}
PropertyBlockHandle::Standard(handle)
} else {
PropertyBlockHandle::Standard(standard_materials.add(material))
}
} else {
continue;
};
match &handle {
PropertyBlockHandle::Standard(handle) => {
commands
.entity(entity)
.try_remove::<MeshMaterial3d<SurfaceMaterial>>()
.try_insert(MeshMaterial3d(handle.clone()));
}
PropertyBlockHandle::Surface(handle) => {
commands
.entity(entity)
.try_remove::<MeshMaterial3d<StandardMaterial>>()
.try_insert(MeshMaterial3d(handle.clone()));
}
}
cache
.entries
.insert(key, PropertyBlockCacheEntry { revision, handle });
}
cache.entries.retain(|key, entry| {
if active.contains(key) {
return true;
}
match &entry.handle {
PropertyBlockHandle::Standard(handle) => {
standard_materials.remove(handle.id());
}
PropertyBlockHandle::Surface(handle) => {
surface_materials.remove(handle.id());
}
}
false
});
}
pub(super) fn property_block_revision(
block: &MaterialPropertyBlock,
standard: Option<&MeshMaterial3d<StandardMaterial>>,
surface: Option<&MeshMaterial3d<SurfaceMaterial>>,
base_revision: u64,
) -> u64 {
let mut hasher = DefaultHasher::new();
format!("{block:?}").hash(&mut hasher);
standard.map(|handle| handle.0.id()).hash(&mut hasher);
surface.map(|handle| handle.0.id()).hash(&mut hasher);
base_revision.hash(&mut hasher);
hasher.finish()
}
pub(super) fn apply_standard_property_block(
material: &mut StandardMaterial,
block: &MaterialPropertyBlock,
asset_server: &AssetServer,
allow_custom: bool,
) -> Result<(), String> {
validate_standard_property_block(block, allow_custom)?;
for parameter in &block.parameters {
match (
parameter.name.to_ascii_lowercase().as_str(),
&parameter.value,
) {
("base_color" | "albedo", MaterialParameterValue::Color(value)) => {
material.base_color = value.to_color()
}
("metallic", MaterialParameterValue::Float(value)) => material.metallic = *value,
("roughness", MaterialParameterValue::Float(value)) => {
material.perceptual_roughness = *value
}
("emissive", MaterialParameterValue::Color(value)) => {
material.emissive = value.to_color().into()
}
_ => continue,
}
}
for texture in &block.textures {
let handle = texture
.texture
.as_ref()
.and_then(|reference| reference.source_path.as_deref())
.map(asset_server_path)
.map(|path| asset_server.load(path));
match texture.name.to_ascii_lowercase().as_str() {
"base_color" | "albedo" => material.base_color_texture = handle,
"normal" | "normal_map" => material.normal_map_texture = handle,
"metallic_roughness" => material.metallic_roughness_texture = handle,
"emissive" => material.emissive_texture = handle,
_ => continue,
}
}
Ok(())
}
pub(super) fn validate_standard_property_block(
block: &MaterialPropertyBlock,
allow_custom: bool,
) -> Result<(), String> {
validate_standard_property_block_at(Path::new("."), block, allow_custom)
}
/// Validates a runtime block against the material path selected for editor promotion.
///
/// The editor passes the resolved project root so relative texture references are checked without
/// relying on process working-directory state. Custom properties are accepted only when the
/// selected material has an active Surface evaluator and its schema declares them.
pub fn validate_property_block_for_promotion(
project_root: &Path,
block: &MaterialPropertyBlock,
schema: Option<&ShaderSchemaAsset>,
custom_surface: bool,
) -> Result<(), String> {
validate_standard_property_block_at(project_root, block, custom_surface)?;
if custom_surface {
validate_surface_property_block(schema, block)?;
}
Ok(())
}
pub(super) fn validate_standard_property_block_at(
project_root: &Path,
block: &MaterialPropertyBlock,
allow_custom: bool,
) -> Result<(), String> {
let mut parameter_names = HashSet::new();
for parameter in &block.parameters {
if !parameter_names.insert(parameter.name.as_str()) {
return Err(format!(
"parameter `{}` is assigned more than once",
parameter.name
));
}
let name = parameter.name.to_ascii_lowercase();
let valid = match (name.as_str(), &parameter.value) {
("base_color" | "albedo" | "emissive", MaterialParameterValue::Color(value)) => {
[value.r, value.g, value.b, value.a]
.into_iter()
.all(f32::is_finite)
}
("metallic" | "roughness", MaterialParameterValue::Float(value)) => {
value.is_finite() && (0.0..=1.0).contains(value)
}
("base_color" | "albedo" | "emissive" | "metallic" | "roughness", _) => false,
_ if allow_custom => true,
_ => {
return Err(format!(
"parameter `{}` is not supported by Standard materials",
parameter.name
));
}
};
if !valid {
return Err(format!(
"parameter `{}` has an invalid type or value",
parameter.name
));
}
}
let mut texture_names = HashSet::new();
for texture in &block.textures {
if !texture_names.insert(texture.name.as_str()) {
return Err(format!(
"texture `{}` is assigned more than once",
texture.name
));
}
let name = texture.name.to_ascii_lowercase();
if !matches!(
name.as_str(),
"base_color" | "albedo" | "normal" | "normal_map" | "metallic_roughness" | "emissive"
) && !allow_custom
{
return Err(format!(
"texture `{}` is not supported by Standard materials",
texture.name
));
}
if let Some(reference) = texture.texture.as_ref() {
let path = reference
.source_path
.as_deref()
.ok_or_else(|| format!("texture `{}` has no loadable source path", texture.name))?;
let path = Path::new(path);
let resolved = if path.is_absolute() {
path.to_path_buf()
} else {
project_root.join(path)
};
if !resolved.is_file() {
return Err(format!(
"texture `{}` is missing at {}",
texture.name,
path.display()
));
}
}
}
Ok(())
}
pub(super) fn apply_surface_property_block(
material: &mut SurfaceMaterial,
reference: &MaterialRef,
block: &MaterialPropertyBlock,
asset_server: &AssetServer,
) -> Result<(), String> {
let path = reference
.0
.source_path
.as_deref()
.ok_or_else(|| "base material has no loadable path".to_string())?;
let (mut asset, mut instance) = match MaterialAsset::load_from_path(path) {
Ok(asset) => (asset, None),
Err(_) => {
let instance = MaterialInstanceAsset::load_from_path(path)?;
let base_path = instance
.base
.0
.source_path
.as_deref()
.ok_or_else(|| "material instance base has no loadable path".to_string())?;
(MaterialAsset::load_from_path(base_path)?, Some(instance))
}
};
let schema_path = asset
.shader_ref
.as_ref()
.and_then(|reference| reference.source_path.as_deref())
.or(asset.shader.schema_path.as_deref());
let schema = schema_path
.map(ShaderSchemaAsset::load_from_path)
.transpose()?;
validate_surface_property_block(schema.as_ref(), block)?;
merge_surface_property_block(&mut asset, &mut instance, block);
if let Some(schema) = schema.as_ref() {
let runtime_catalog = load_runtime_content_catalog();
pack_schema_values(
&mut material.extension,
schema,
&asset.inputs,
instance.as_ref(),
asset_server,
runtime_catalog.as_ref(),
)?;
}
let mut resolved = MaterialDesc::default();
asset.inputs.apply_to_material_desc(&mut resolved);
if let Some(instance) = instance.as_ref() {
instance.apply_to(&mut resolved);
}
material.extension.uniform.uv_transforms.fill(Vec4::new(
resolved.uv_tiling.x,
resolved.uv_tiling.y,
resolved.uv_offset.x,
resolved.uv_offset.y,
));
Ok(())
}
pub(super) fn merge_surface_property_block(
asset: &mut MaterialAsset,
instance: &mut Option<MaterialInstanceAsset>,
block: &MaterialPropertyBlock,
) {
if let Some(instance) = instance.as_mut() {
instance.merge_overrides(block.parameters.clone(), block.textures.clone());
} else {
merge_material_input_overrides(&mut asset.inputs, block);
}
}
pub(super) fn merge_material_input_overrides(
inputs: &mut shared::MaterialInputSet,
block: &MaterialPropertyBlock,
) {
for parameter in &block.parameters {
if let Some(existing) = inputs
.values
.iter_mut()
.find(|value| value.name == parameter.name)
{
*existing = parameter.clone();
} else {
inputs.values.push(parameter.clone());
}
}
for texture in &block.textures {
if let Some(existing) = inputs
.textures
.iter_mut()
.find(|value| value.name == texture.name)
{
*existing = texture.clone();
} else {
inputs.textures.push(texture.clone());
}
}
}
pub(super) fn validate_surface_property_block(
schema: Option<&ShaderSchemaAsset>,
block: &MaterialPropertyBlock,
) -> Result<(), String> {
for parameter in &block.parameters {
if matches!(
parameter.name.to_ascii_lowercase().as_str(),
"base_color" | "albedo" | "emissive" | "metallic" | "roughness"
) {
continue;
}
let property = schema
.and_then(|schema| {
schema
.schema
.inputs
.iter()
.find(|property| property.name == parameter.name)
})
.ok_or_else(|| {
format!(
"parameter `{}` is not declared by the Surface schema",
parameter.name
)
})?;
if matches!(property.property_type, ShaderPropertyType::Texture) {
return Err(format!(
"parameter `{}` targets a texture property",
parameter.name
));
}
parameter_lane(&parameter.value, &property.property_type)?;
if !parameter_value_is_finite(&parameter.value) {
return Err(format!(
"parameter `{}` contains a non-finite value",
parameter.name
));
}
if let (MaterialParameterValue::Float(value), ShaderPropertyType::Float { min, max }) =
(&parameter.value, &property.property_type)
{
if !value.is_finite()
|| min.is_some_and(|min| *value < min)
|| max.is_some_and(|max| *value > max)
{
return Err(format!(
"parameter `{}` is outside its declared finite range",
parameter.name
));
}
}
}
for texture in &block.textures {
if matches!(
texture.name.to_ascii_lowercase().as_str(),
"base_color" | "albedo" | "normal" | "normal_map" | "metallic_roughness" | "emissive"
) {
continue;
}
let property = schema
.and_then(|schema| {
schema
.schema
.inputs
.iter()
.find(|property| property.name == texture.name)
})
.ok_or_else(|| {
format!(
"texture `{}` is not declared by the Surface schema",
texture.name
)
})?;
if !matches!(property.property_type, ShaderPropertyType::Texture) {
return Err(format!(
"texture `{}` targets a non-texture property",
texture.name
));
}
}
Ok(())
}
pub(super) fn parameter_value_is_finite(value: &MaterialParameterValue) -> bool {
match value {
MaterialParameterValue::Bool(_) | MaterialParameterValue::Enum(_) => true,
MaterialParameterValue::Float(value) => value.is_finite(),
MaterialParameterValue::Vec2(value) => value.is_finite(),
MaterialParameterValue::Vec3(value) => value.is_finite(),
MaterialParameterValue::Color(value) => [value.r, value.g, value.b, value.a]
.into_iter()
.all(f32::is_finite),
}
}
@@ -0,0 +1,541 @@
use super::*;
pub(super) fn resolve_material_desc(
reference: &MaterialRef,
path: &str,
live_documents: &LiveMaterialDocumentOverlay,
) -> Result<MaterialDesc, String> {
let (asset, instance) = match live_documents.get(reference) {
Some(LiveMaterialDocumentEntry {
document: LiveMaterialDocument::Material(asset),
..
}) => (asset.clone(), None),
Some(LiveMaterialDocumentEntry {
document: LiveMaterialDocument::Instance(instance),
..
}) => (
live_base_material(&instance.base, live_documents)?,
Some(instance.clone()),
),
None => return shared::load_resolved_material_from_path(path).map(|(desc, _)| desc),
};
let mut resolved = MaterialDesc {
shader: asset.shader.clone(),
..Default::default()
};
asset.inputs.apply_to_material_desc(&mut resolved);
if let Some(instance) = instance.as_ref() {
instance.apply_to(&mut resolved);
}
Ok(resolved)
}
pub(super) fn material_live_revision(
reference: &MaterialRef,
live_documents: &LiveMaterialDocumentOverlay,
) -> Option<u64> {
let entry = live_documents.get(reference)?;
let base_revision = match &entry.document {
LiveMaterialDocument::Material(_) => None,
LiveMaterialDocument::Instance(instance) => live_documents
.get(&instance.base)
.map(|base| base.revision.rotate_left(1)),
};
Some(base_revision.map_or(entry.revision, |base| entry.revision ^ base))
}
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
pub(super) fn sync_surface_material_bindings(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut shaders: ResMut<Assets<Shader>>,
mut standard_materials: ResMut<Assets<StandardMaterial>>,
mut surface_materials: ResMut<Assets<SurfaceMaterial>>,
mut cache: ResMut<SurfaceMaterialCache>,
live_documents: Res<LiveMaterialDocumentOverlay>,
mut default_grid: ResMut<DefaultGridMaterialHandles>,
content_defaults: Res<shared::ProjectContentDefaults>,
mut diagnostics: ResMut<SurfaceDiagnostics>,
mut evaluator_registry: ResMut<SurfaceEvaluatorRegistry>,
bindings: Query<(
Entity,
&HydratedMaterialSlotBinding,
Option<&MeshMaterial3d<StandardMaterial>>,
Option<&MeshMaterial3d<SurfaceMaterial>>,
)>,
) {
let default_grid_handle = ensure_default_grid_material(
&mut shaders,
&mut standard_materials,
&mut surface_materials,
&mut default_grid,
&mut evaluator_registry,
);
for (entity, binding, standard_handle, surface_handle) in &bindings {
if matches!(
binding.selection,
HydratedMaterialSelection::ImportedSource { .. }
) {
continue;
}
let reference = binding
.selection
.project_reference()
.or(content_defaults.default_material.as_ref());
let Some(reference) = reference else {
queue_default_grid_binding(&mut commands, entity, default_grid_handle.clone());
continue;
};
let Some(path) = reference.0.source_path.as_deref() else {
record_diagnostic(
&mut diagnostics.0,
format!(
"material {} has no loadable source path; using {DEFAULT_GRID_LABEL}",
reference.0.label
),
);
queue_default_grid_binding(&mut commands, entity, default_grid_handle.clone());
continue;
};
let live_revision = material_live_revision(reference, &live_documents).or_else(|| {
cache
.instance_bases
.get(reference)
.and_then(|base| live_documents.get(base))
.map(|entry| entry.revision.rotate_left(1))
});
let revision = live_revision
.map(|revision| revision | (1_u64 << 63))
.unwrap_or_else(|| cache.disk_generation());
if cache.failed_revisions.get(reference) == Some(&revision) {
queue_default_grid_binding(&mut commands, entity, default_grid_handle.clone());
continue;
}
if cache.standard_only.get(reference) == Some(&revision) {
if let Some(handle) = cache.standard_handles.get(reference).cloned() {
if standard_handle.is_none_or(|current| current.0 != handle)
|| surface_handle.is_some()
{
commands
.entity(entity)
.try_remove::<MeshMaterial3d<SurfaceMaterial>>()
.try_insert(MeshMaterial3d(handle));
}
}
continue;
}
let stale = cache.revisions.get(reference) != Some(&revision);
let handle = if !stale {
cache.handles.get(reference).cloned()
} else {
None
};
let handle = match handle {
Some(handle) => handle,
None => match build_surface_material(
reference,
path,
&live_documents,
&asset_server,
&mut shaders,
&mut evaluator_registry,
) {
Ok((BuiltRendererMaterial::Surface(material), base_reference)) => {
let material = *material;
if let Some(base_reference) = base_reference {
cache
.instance_bases
.insert(reference.clone(), base_reference);
} else {
cache.instance_bases.remove(reference);
}
cache.standard_only.remove(reference);
cache.standard_handles.remove(reference);
cache.failed_revisions.remove(reference);
if let Some(existing) = cache.handles.get(reference).cloned() {
if let Some(mut slot) = surface_materials.get_mut(&existing) {
*slot = material;
}
existing
} else {
let handle = surface_materials.add(material);
cache.handles.insert(reference.clone(), handle.clone());
handle
}
}
Ok((BuiltRendererMaterial::Standard(material), base_reference)) => {
let material = *material;
if let Some(base_reference) = base_reference {
cache
.instance_bases
.insert(reference.clone(), base_reference);
} else {
cache.instance_bases.remove(reference);
}
// Plain Material assets stay on Bevy's StandardMaterial path, while still
// sharing one live-updated handle across every renderer slot.
// Never adopt the renderer's current handle here: hydration starts every
// surface on one singleton emergency handle, so adopting it would make
// unrelated Materials overwrite each other. Cache one handle per reference.
let handle = cache
.standard_handles
.get(reference)
.cloned()
.unwrap_or_else(|| standard_materials.add(material.clone()));
if let Some(mut slot) = standard_materials.get_mut(&handle) {
*slot = material;
}
cache.handles.remove(reference);
cache.revisions.remove(reference);
cache
.standard_handles
.insert(reference.clone(), handle.clone());
cache.standard_only.insert(reference.clone(), revision);
cache.failed_revisions.remove(reference);
evaluator_registry
.evaluators
.remove(&stable_shader_id(reference));
if standard_handle.is_none_or(|current| current.0 != handle)
|| surface_handle.is_some()
{
commands
.entity(entity)
.try_remove::<MeshMaterial3d<SurfaceMaterial>>()
.try_insert(MeshMaterial3d(handle));
}
continue;
}
Err(error) => {
cache.failed_revisions.insert(reference.clone(), revision);
record_diagnostic(
&mut diagnostics.0,
format!(
"material {} could not build Surface ABI: {error}; using {DEFAULT_GRID_LABEL}",
reference.0.label
),
);
queue_default_grid_binding(&mut commands, entity, default_grid_handle.clone());
continue;
}
},
};
cache.revisions.insert(reference.clone(), revision);
if surface_handle.is_none_or(|current| current.0 != handle) {
commands
.entity(entity)
.try_remove::<MeshMaterial3d<StandardMaterial>>()
.try_insert(MeshMaterial3d(handle));
}
}
}
pub(super) fn queue_default_grid_binding(
commands: &mut Commands,
entity: Entity,
handle: Handle<SurfaceMaterial>,
) {
commands
.entity(entity)
.try_remove::<MeshMaterial3d<StandardMaterial>>()
.try_insert(MeshMaterial3d(handle));
}
pub(super) fn ensure_default_grid_material(
shaders: &mut Assets<Shader>,
standard_materials: &mut Assets<StandardMaterial>,
surface_materials: &mut Assets<SurfaceMaterial>,
handles: &mut DefaultGridMaterialHandles,
evaluator_registry: &mut SurfaceEvaluatorRegistry,
) -> Handle<SurfaceMaterial> {
if let Some(handle) = handles.surface.as_ref() {
return handle.clone();
}
validate_surface_evaluator(DEFAULT_GRID_EVALUATOR)
.expect("embedded DefaultGrid evaluator must remain valid");
let shader_id = AssetId::<Shader>::Uuid {
uuid: DEFAULT_GRID_SHADER_UUID,
};
shaders
.insert(
shader_id,
Shader::from_wgsl(
compose_surface_shader(DEFAULT_GRID_EVALUATOR),
"builtin://default-grid.wgsl",
),
)
.expect("reserved DefaultGrid shader ID must be replaceable");
evaluator_registry.evaluators.insert(
DEFAULT_GRID_SHADER_ID,
SurfaceEvaluatorRecord {
shader_id: DEFAULT_GRID_SHADER_ID,
evaluator_source: DEFAULT_GRID_EVALUATOR.to_string(),
revision: evaluator_revision(DEFAULT_GRID_EVALUATOR),
alpha_mode: shared::MaterialAlphaMode::Opaque,
},
);
let emergency = standard_materials.add(StandardMaterial {
base_color: Color::srgb(0.46, 0.46, 0.46),
perceptual_roughness: 0.86,
cull_mode: None,
..default()
});
let material = SurfaceMaterial {
base: StandardMaterial {
base_color: Color::WHITE,
perceptual_roughness: 0.86,
cull_mode: None,
..default()
},
extension: SurfaceExtension {
uniform: SurfaceUniform {
shader_id: DEFAULT_GRID_SHADER_ID,
..default()
},
shader: Handle::Uuid(DEFAULT_GRID_SHADER_UUID, Default::default()),
..default()
},
};
let handle = surface_materials.add(material);
handles.emergency_standard = Some(emergency);
handles.surface = Some(handle.clone());
handle
}
pub(super) fn build_surface_material(
reference: &MaterialRef,
path: &str,
live_documents: &LiveMaterialDocumentOverlay,
asset_server: &AssetServer,
shaders: &mut Assets<Shader>,
evaluator_registry: &mut SurfaceEvaluatorRegistry,
) -> Result<(BuiltRendererMaterial, Option<MaterialRef>), String> {
let (asset, instance, base_reference) = match live_documents.get(reference) {
Some(LiveMaterialDocumentEntry {
document: LiveMaterialDocument::Material(asset),
..
}) => (asset.clone(), None, None),
Some(LiveMaterialDocumentEntry {
document: LiveMaterialDocument::Instance(instance),
..
}) => {
if instance.schema_version != MATERIAL_INSTANCE_SCHEMA_VERSION {
return Err(format!(
"unsupported material-instance schema {}",
instance.schema_version
));
}
(
live_base_material(&instance.base, live_documents)?,
Some(instance.clone()),
Some(instance.base.clone()),
)
}
None => match MaterialAsset::load_from_path(path) {
Ok(asset) => (asset, None, None),
Err(_) => {
let instance = MaterialInstanceAsset::load_from_path(path)?;
if instance.schema_version != MATERIAL_INSTANCE_SCHEMA_VERSION {
return Err(format!(
"unsupported material-instance schema {}",
instance.schema_version
));
}
let base_reference = instance.base.clone();
(
live_base_material(&base_reference, live_documents)?,
Some(instance),
Some(base_reference),
)
}
},
};
let mut resolved = shared::MaterialDesc {
shader: asset.shader.clone(),
..Default::default()
};
asset.inputs.apply_to_material_desc(&mut resolved);
if let Some(instance) = instance.as_ref() {
instance.apply_to(&mut resolved);
}
let runtime_catalog = load_runtime_content_catalog();
apply_runtime_texture_paths(
&mut resolved,
&asset.inputs,
instance.as_ref(),
reference,
runtime_catalog.as_ref(),
);
let schema_path = asset
.shader_ref
.as_ref()
.and_then(|reference| reference.source_path.as_deref())
.or(asset.shader.schema_path.as_deref());
let schema = schema_path
.map(ShaderSchemaAsset::load_from_path)
.transpose()?;
let evaluator_source = schema
.as_ref()
.and_then(|schema| schema.wgsl_path.as_deref())
.map(fs::read_to_string)
.transpose()
.map_err(|error| format!("could not read surface WGSL: {error}"))?;
// Hydration deliberately attaches the singleton emergency StandardMaterial first so geometry
// stays visible before this resolver runs. Its neutral values must never become the base of an
// assigned project Material.
let runtime_binding = |name: &str| {
instance
.as_ref()
.and_then(|instance| instance.overrides.texture(name))
.or_else(|| asset.inputs.texture(name))
};
let base_color_spec = runtime_binding("base_color")
.and_then(|binding| binding.texture.as_ref())
.and_then(|reference| runtime_texture_spec(runtime_catalog.as_ref(), reference, true));
let normal_spec = runtime_binding("normal")
.and_then(|binding| binding.texture.as_ref())
.and_then(|reference| runtime_texture_spec(runtime_catalog.as_ref(), reference, false));
let emissive_spec = runtime_binding("emissive")
.and_then(|binding| binding.texture.as_ref())
.and_then(|reference| runtime_texture_spec(runtime_catalog.as_ref(), reference, true));
let packed_spec = packed_runtime_texture_spec(
runtime_catalog.as_ref(),
&asset.inputs,
instance.as_ref(),
reference,
)?;
let specs = [base_color_spec, normal_spec, emissive_spec, packed_spec]
.into_iter()
.flatten()
.map(|spec| (spec.path.clone(), spec))
.collect::<HashMap<_, _>>();
let mut base =
shared::material_from_desc_with_texture_loader(asset_server, &resolved, |path| {
specs.get(path).map_or_else(
|| asset_server.load(asset_server_path(path)),
|spec| shared::load_runtime_texture(asset_server, spec),
)
});
base.alpha_mode = match asset.render_state.alpha_mode {
shared::MaterialAlphaMode::Opaque => AlphaMode::Opaque,
shared::MaterialAlphaMode::Cutout => AlphaMode::Mask(asset.render_state.alpha_cutoff),
};
base.cull_mode =
(!asset.render_state.double_sided).then_some(bevy::render::render_resource::Face::Back);
let Some(evaluator) = evaluator_source.as_deref() else {
return Ok((
BuiltRendererMaterial::Standard(Box::new(base)),
base_reference,
));
};
validate_surface_evaluator(evaluator)?;
let runtime_shader_id = stable_shader_id(reference);
let evaluator_source_revision = evaluator_revision(evaluator);
let shader_changed = evaluator_registry
.evaluators
.get(&runtime_shader_id)
.is_none_or(|record| record.revision != evaluator_source_revision);
evaluator_registry.evaluators.insert(
runtime_shader_id,
SurfaceEvaluatorRecord {
shader_id: runtime_shader_id,
evaluator_source: evaluator.to_string(),
revision: evaluator_source_revision,
alpha_mode: asset.render_state.alpha_mode,
},
);
let virtual_path = format!("generated://surface/{}.wgsl", reference.0.asset_id);
let shader_uuid = shader_uuid_for_material(reference);
let shader_id = AssetId::<Shader>::Uuid { uuid: shader_uuid };
if shader_changed || shaders.get(shader_id).is_none() {
shaders
.insert(
shader_id,
Shader::from_wgsl(compose_surface_shader(evaluator), virtual_path),
)
.map_err(|error| format!("could not replace generated surface shader: {error}"))?;
}
let shader = Handle::Uuid(shader_uuid, Default::default());
let mut extension = SurfaceExtension {
shader,
..default()
};
extension.uniform.alpha_cutoff = asset.render_state.alpha_cutoff;
extension.uniform.shader_id = runtime_shader_id;
if let Some(schema) = schema.as_ref() {
pack_schema_values(
&mut extension,
schema,
&asset.inputs,
instance.as_ref(),
asset_server,
runtime_catalog.as_ref(),
)?;
}
extension.uniform.uv_transforms.fill(Vec4::new(
resolved.uv_tiling.x,
resolved.uv_tiling.y,
resolved.uv_offset.x,
resolved.uv_offset.y,
));
Ok((
BuiltRendererMaterial::Surface(Box::new(ExtendedMaterial { base, extension })),
base_reference,
))
}
pub(super) fn live_base_material(
reference: &MaterialRef,
live_documents: &LiveMaterialDocumentOverlay,
) -> Result<MaterialAsset, String> {
match live_documents.get(reference) {
Some(LiveMaterialDocumentEntry {
document: LiveMaterialDocument::Material(asset),
..
}) => Ok(asset.clone()),
Some(LiveMaterialDocumentEntry {
document: LiveMaterialDocument::Instance(_),
..
}) => Err("nested Material Instances are not supported".to_string()),
None => {
let base_path = reference
.0
.source_path
.as_deref()
.ok_or_else(|| "material instance base has no loadable path".to_string())?;
MaterialAsset::load_from_path(base_path)
}
}
}
pub(super) fn stable_shader_id(reference: &MaterialRef) -> u32 {
let mut hash = 0x811c9dc5u32;
for byte in reference.0.asset_id.bytes() {
hash ^= u32::from(byte);
hash = hash.wrapping_mul(0x01000193);
}
hash
}
pub(super) fn evaluator_revision(source: &str) -> u64 {
let mut hash = 0xcbf29ce484222325u64;
for byte in source.bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x100000001b3);
}
hash
}
pub(super) fn shader_uuid_for_material(reference: &MaterialRef) -> uuid::Uuid {
if let Ok(source) = uuid::Uuid::parse_str(&reference.0.asset_id) {
let mixed = source.as_u128() ^ 0x7f8c_4e90_f9ab_4f28_9b44_47c1_b2d5_5ac1u128;
return uuid::Uuid::from_u128(mixed);
}
let mut bytes = [0u8; 16];
for (index, byte) in reference.0.asset_id.bytes().enumerate() {
bytes[index % 16] = bytes[index % 16].wrapping_mul(31).wrapping_add(byte);
}
uuid::Uuid::from_bytes(bytes)
}
@@ -0,0 +1,131 @@
use super::*;
#[derive(ShaderType, Reflect, Debug, Clone, Copy, PartialEq)]
pub struct SurfaceUniform {
pub shader_id: u32,
pub flags: u32,
pub alpha_cutoff: f32,
pub abi_version: u32,
pub params: [Vec4; SURFACE_PARAMETER_LANES],
pub uv_transforms: [Vec4; SURFACE_TEXTURE_SLOTS],
}
impl Default for SurfaceUniform {
fn default() -> Self {
Self {
shader_id: 0,
flags: 0,
alpha_cutoff: 0.5,
abi_version: SURFACE_ABI_VERSION,
params: [Vec4::ZERO; SURFACE_PARAMETER_LANES],
uv_transforms: [Vec4::new(1.0, 1.0, 0.0, 0.0); SURFACE_TEXTURE_SLOTS],
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SurfaceExtensionKey {
shader: AssetId<Shader>,
}
impl From<&SurfaceExtension> for SurfaceExtensionKey {
fn from(extension: &SurfaceExtension) -> Self {
Self {
shader: extension.shader.id(),
}
}
}
#[derive(Asset, AsBindGroup, Reflect, Debug, Clone, Default)]
#[bind_group_data(SurfaceExtensionKey)]
pub struct SurfaceExtension {
#[uniform(100)]
pub uniform: SurfaceUniform,
#[texture(101)]
#[sampler(102)]
pub texture0: Option<Handle<Image>>,
#[texture(103)]
#[sampler(104)]
pub texture1: Option<Handle<Image>>,
#[texture(105)]
#[sampler(106)]
pub texture2: Option<Handle<Image>>,
#[texture(107)]
#[sampler(108)]
pub texture3: Option<Handle<Image>>,
#[texture(109)]
#[sampler(110)]
pub texture4: Option<Handle<Image>>,
#[texture(111)]
#[sampler(112)]
pub texture5: Option<Handle<Image>>,
#[texture(113)]
#[sampler(114)]
pub texture6: Option<Handle<Image>>,
#[texture(115)]
#[sampler(116)]
pub texture7: Option<Handle<Image>>,
#[reflect(ignore)]
pub shader: Handle<Shader>,
}
impl SurfaceExtension {
pub fn set_texture(&mut self, index: usize, handle: Option<Handle<Image>>) {
match index {
0 => self.texture0 = handle,
1 => self.texture1 = handle,
2 => self.texture2 = handle,
3 => self.texture3 = handle,
4 => self.texture4 = handle,
5 => self.texture5 = handle,
6 => self.texture6 = handle,
7 => self.texture7 = handle,
_ => {}
}
}
}
impl MaterialExtension for SurfaceExtension {
fn fragment_shader() -> ShaderRef {
DEFAULT_SURFACE_SHADER_PATH.into()
}
fn deferred_fragment_shader() -> ShaderRef {
DEFAULT_SURFACE_SHADER_PATH.into()
}
fn specialize(
_pipeline: &MaterialExtensionPipeline,
descriptor: &mut RenderPipelineDescriptor,
_layout: &MeshVertexBufferLayoutRef,
key: MaterialExtensionKey<Self>,
) -> Result<(), SpecializedMeshPipelineError> {
if let (AssetId::Uuid { uuid }, Some(fragment)) =
(key.bind_group_data.shader, descriptor.fragment.as_mut())
{
// The evaluator fragment owns forward and deferred shading, but ordinary depth,
// normal, and motion-vector prepasses must retain Bevy's standard prepass shader.
// Substituting the evaluator there calls `deferred_output()` without a
// `DEFERRED_PREPASS` output attachment and fails shader validation at runtime.
if surface_evaluator_owns_fragment(&fragment.shader_defs) {
fragment.shader = Handle::Uuid(uuid, Default::default());
}
}
Ok(())
}
}
pub(super) fn surface_evaluator_owns_fragment(shader_defs: &[ShaderDefVal]) -> bool {
!shader_def_enabled(shader_defs, "PREPASS_PIPELINE")
|| shader_def_enabled(shader_defs, "DEFERRED_PREPASS")
}
pub(super) fn shader_def_enabled(shader_defs: &[ShaderDefVal], expected: &str) -> bool {
shader_defs.iter().any(|shader_def| match shader_def {
ShaderDefVal::Bool(name, enabled) => name == expected && *enabled,
ShaderDefVal::Int(name, value) => name == expected && *value != 0,
ShaderDefVal::UInt(name, value) => name == expected && *value != 0,
})
}
pub type SurfaceMaterial = ExtendedMaterial<StandardMaterial, SurfaceExtension>;
@@ -0,0 +1,229 @@
use super::*;
use bevy::ecs::system::SystemParam;
#[derive(SystemParam)]
pub(super) struct TerrainMaterialResources<'w> {
asset_server: Res<'w, AssetServer>,
materials: ResMut<'w, Assets<TerrainLayerMaterial>>,
cache: ResMut<'w, TerrainLayerMaterialCache>,
surface_cache: Res<'w, SurfaceMaterialCache>,
live_documents: Res<'w, LiveMaterialDocumentOverlay>,
diagnostics: ResMut<'w, SurfaceDiagnostics>,
}
pub(super) fn sync_terrain_layer_material_bindings(
mut commands: Commands,
resources: TerrainMaterialResources,
bindings: TerrainMaterialBindings,
) {
let TerrainMaterialResources {
asset_server,
mut materials,
mut cache,
surface_cache,
live_documents,
mut diagnostics,
} = resources;
for (entity, binding) in &bindings {
if binding.layers.is_empty() {
continue;
}
let revision = terrain_layer_revision(
&binding.layers,
&live_documents,
surface_cache.disk_generation(),
);
let cached = cache
.0
.get(&binding.owner)
.filter(|entry| entry.layers == binding.layers && entry.revision == revision)
.map(|entry| entry.handle.clone());
let handle = cached.unwrap_or_else(|| {
let material = build_terrain_layer_material(
&asset_server,
&binding.layers,
&live_documents,
&mut diagnostics.0,
);
let handle = cache
.0
.get(&binding.owner)
.map(|entry| entry.handle.clone())
.filter(|handle| {
materials
.get_mut(handle)
.map(|mut slot| {
*slot = material.clone();
})
.is_some()
})
.unwrap_or_else(|| materials.add(material));
cache.0.insert(
binding.owner,
TerrainLayerCacheEntry {
layers: binding.layers.clone(),
handle: handle.clone(),
revision,
},
);
handle
});
queue_terrain_material_binding(&mut commands, entity, handle);
}
}
pub(super) fn queue_terrain_material_binding(
commands: &mut Commands,
entity: Entity,
handle: Handle<TerrainLayerMaterial>,
) {
// Generated render entities can be removed by a scene switch after this system's query
// but before deferred commands apply. That lifecycle race is expected and must not abort
// the editor while opening another scene.
commands
.entity(entity)
.try_remove::<MeshMaterial3d<StandardMaterial>>()
.try_insert(MeshMaterial3d(handle));
}
pub(super) fn terrain_layer_revision(
layers: &[TerrainMaterialLayer],
live_documents: &LiveMaterialDocumentOverlay,
disk_generation: u64,
) -> u64 {
let mut hash = 0xcbf29ce484222325u64;
for layer in layers {
for byte in layer.uv_scale.to_bits().to_le_bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x100000001b3);
}
let Some(reference) = layer.material.as_ref() else {
hash ^= u64::MAX;
continue;
};
for byte in reference.asset_id.bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x100000001b3);
}
let revision = material_live_revision(&MaterialRef(reference.clone()), live_documents)
.unwrap_or(disk_generation);
for byte in revision.to_le_bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x100000001b3);
}
}
hash
}
pub(super) fn build_terrain_layer_material(
asset_server: &AssetServer,
layers: &[TerrainMaterialLayer],
live_documents: &LiveMaterialDocumentOverlay,
diagnostics: &mut Vec<String>,
) -> TerrainLayerMaterial {
let mut extension = TerrainLayerExtension::default();
for (index, layer) in layers.iter().take(TERRAIN_MATERIAL_LAYER_LIMIT).enumerate() {
extension.uniform.uv_scales[index] = layer.uv_scale;
let desc = resolve_terrain_layer(layer, index, live_documents, diagnostics);
let color = desc.base_color.to_color().to_linear();
extension.uniform.base_colors[index] =
Vec4::new(color.red, color.green, color.blue, color.alpha);
extension.uniform.properties[index] = Vec4::new(
desc.metallic,
desc.roughness,
f32::from(desc.normal_map_texture.is_some()),
1.0,
);
extension.uniform.base_texture_enabled[index] =
f32::from(desc.base_color_texture.is_some());
let base_color = desc
.base_color_texture
.as_deref()
.map(|path| asset_server.load(asset_server_path(path)));
let normal = desc
.normal_map_texture
.as_deref()
.map(|path| asset_server.load(asset_server_path(path)));
match index {
0 => {
extension.base_color0 = base_color;
extension.normal0 = normal;
}
1 => {
extension.base_color1 = base_color;
extension.normal1 = normal;
}
2 => {
extension.base_color2 = base_color;
extension.normal2 = normal;
}
3 => {
extension.base_color3 = base_color;
extension.normal3 = normal;
}
_ => {}
}
}
TerrainLayerMaterial {
base: StandardMaterial {
base_color: Color::WHITE,
perceptual_roughness: 1.0,
// Terrain is intentionally absent from the Solari acceleration structure until its
// ray-tracing evaluator exists, so keep the layer blend in the raster forward pass.
opaque_render_method: OpaqueRendererMethod::Forward,
..default()
},
extension,
}
}
pub(super) fn resolve_terrain_layer(
layer: &TerrainMaterialLayer,
index: usize,
live_documents: &LiveMaterialDocumentOverlay,
diagnostics: &mut Vec<String>,
) -> MaterialDesc {
let Some(reference) = layer.material.as_ref() else {
record_diagnostic(
diagnostics,
format!(
"terrain material layer {} is unassigned; using visible fallback",
index + 1
),
);
return terrain_layer_fallback();
};
let Some(path) = reference.source_path.as_deref() else {
record_diagnostic(
diagnostics,
format!(
"terrain material layer {} ({}) has no loadable source path; using visible fallback",
index + 1,
reference.label
),
);
return terrain_layer_fallback();
};
match resolve_material_desc(&MaterialRef(reference.clone()), path, live_documents) {
Ok(desc) => desc,
Err(error) => {
record_diagnostic(
diagnostics,
format!(
"terrain material layer {} ({}) could not resolve: {error}; using visible fallback",
index + 1,
reference.label
),
);
terrain_layer_fallback()
}
}
}
pub(super) fn terrain_layer_fallback() -> MaterialDesc {
MaterialDesc {
base_color: shared::ColorDesc::srgb(0.24, 0.29, 0.25),
roughness: 0.92,
..Default::default()
}
}
@@ -0,0 +1,76 @@
use super::*;
#[derive(ShaderType, Reflect, Debug, Clone, Copy, PartialEq)]
pub struct TerrainLayerUniform {
pub base_colors: [Vec4; TERRAIN_MATERIAL_LAYER_LIMIT],
/// Metallic, perceptual roughness, normal-map enabled, layer enabled.
pub properties: [Vec4; TERRAIN_MATERIAL_LAYER_LIMIT],
pub uv_scales: Vec4,
pub base_texture_enabled: Vec4,
}
impl Default for TerrainLayerUniform {
fn default() -> Self {
Self {
base_colors: [Vec4::ONE; TERRAIN_MATERIAL_LAYER_LIMIT],
properties: [Vec4::new(0.0, 0.9, 0.0, 0.0); TERRAIN_MATERIAL_LAYER_LIMIT],
uv_scales: Vec4::splat(8.0),
base_texture_enabled: Vec4::ZERO,
}
}
}
#[derive(Asset, AsBindGroup, Reflect, Debug, Clone, Default)]
pub struct TerrainLayerExtension {
#[uniform(100)]
pub uniform: TerrainLayerUniform,
#[texture(101)]
#[sampler(102)]
pub base_color0: Option<Handle<Image>>,
#[texture(103)]
#[sampler(104)]
pub normal0: Option<Handle<Image>>,
#[texture(105)]
#[sampler(106)]
pub base_color1: Option<Handle<Image>>,
#[texture(107)]
#[sampler(108)]
pub normal1: Option<Handle<Image>>,
#[texture(109)]
#[sampler(110)]
pub base_color2: Option<Handle<Image>>,
#[texture(111)]
#[sampler(112)]
pub normal2: Option<Handle<Image>>,
#[texture(113)]
#[sampler(114)]
pub base_color3: Option<Handle<Image>>,
#[texture(115)]
#[sampler(116)]
pub normal3: Option<Handle<Image>>,
}
impl MaterialExtension for TerrainLayerExtension {
fn fragment_shader() -> ShaderRef {
TERRAIN_LAYER_SHADER_PATH.into()
}
fn deferred_fragment_shader() -> ShaderRef {
TERRAIN_LAYER_SHADER_PATH.into()
}
}
pub type TerrainLayerMaterial = ExtendedMaterial<StandardMaterial, TerrainLayerExtension>;
#[derive(Debug, Clone)]
pub(super) struct TerrainLayerCacheEntry {
pub(super) layers: Vec<TerrainMaterialLayer>,
pub(super) handle: Handle<TerrainLayerMaterial>,
pub(super) revision: u64,
}
#[derive(Resource, Default)]
pub(super) struct TerrainLayerMaterialCache(pub(super) HashMap<Entity, TerrainLayerCacheEntry>);
pub(super) type TerrainMaterialBindings<'w, 's> =
Query<'w, 's, (Entity, &'static HydratedTerrainMaterialBinding)>;
@@ -0,0 +1,727 @@
use super::*;
use crate::surface_abi::surface_evaluator_owns_fragment;
use bevy::ecs::world::CommandQueue;
fn live_material_app() -> App {
let mut app = App::new();
app.add_plugins((MinimalPlugins, AssetPlugin::default()))
.init_resource::<Assets<Shader>>()
.init_resource::<Assets<StandardMaterial>>()
.init_resource::<Assets<SurfaceMaterial>>()
.init_resource::<SurfaceMaterialCache>()
.init_resource::<LiveMaterialDocumentOverlay>()
.init_resource::<DefaultGridMaterialHandles>()
.init_resource::<shared::ProjectContentDefaults>()
.init_resource::<SurfaceDiagnostics>()
.init_resource::<SurfaceEvaluatorRegistry>()
.add_systems(Update, sync_surface_material_bindings);
app
}
fn authored_standard_material(label: &str, color: shared::ColorDesc) -> MaterialAsset {
MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: label.into(),
shader: shared::ShaderRefDesc::default(),
shader_ref: None,
render_state: shared::MaterialRenderState::default(),
inputs: shared::MaterialInputSet::from_material_desc(&MaterialDesc {
base_color: color,
roughness: 0.4,
..Default::default()
}),
provenance: None,
}
}
#[test]
fn stale_generated_terrain_binding_is_nonfatal_during_scene_switch() {
let mut world = World::new();
let entity = world.spawn_empty().id();
let mut queue = CommandQueue::default();
let mut commands = Commands::new(&mut queue, &world);
queue_terrain_material_binding(&mut commands, entity, Handle::default());
world.entity_mut(entity).despawn();
queue.apply(&mut world);
assert!(world.get_entity(entity).is_err());
}
#[test]
fn rejects_resource_bindings_and_missing_entry() {
assert!(validate_surface_evaluator("fn nope() {}").is_err());
assert!(validate_surface_evaluator(
"@group(0) @binding(0) var t: texture_2d<f32>; fn evaluate() {}"
)
.is_err());
for compute_incompatible in [
"dpdx(input.uv0.x)",
"dpdy(input.uv0.y)",
"fwidth(input.uv0.x)",
"discard",
"workgroupBarrier()",
"subgroupAdd(1u)",
] {
let source = format!(
"fn evaluate(input: SurfaceInput, params: SurfaceParams, samples: SurfaceSamples) -> Surface {{ let invalid = {compute_incompatible}; return surface_default(); }}"
);
assert!(
validate_surface_evaluator(&source).is_err(),
"accepted compute-incompatible evaluator: {compute_incompatible}"
);
}
assert!(validate_surface_evaluator(
"fn evaluate(input: SurfaceInput, params: SurfaceParams, samples: SurfaceSamples) -> Surface { return missing_symbol; }"
)
.is_err());
}
#[test]
fn accepts_surface_only_module_and_composes_wrapper() {
let source = "fn evaluate(input: SurfaceInput, params: SurfaceParams, samples: SurfaceSamples) -> Surface { return surface_default(); }";
validate_surface_evaluator(source).unwrap();
let composed = compose_surface_shader(source);
assert!(composed.contains(source));
assert!(composed.contains("@fragment"));
}
#[test]
fn embedded_default_grid_is_uv_independent_and_surface_valid() {
validate_surface_evaluator(DEFAULT_GRID_EVALUATOR).unwrap();
assert!(DEFAULT_GRID_EVALUATOR.contains("world_position"));
assert!(DEFAULT_GRID_EVALUATOR.contains("0.5"));
assert!(DEFAULT_GRID_EVALUATOR.contains("4.0"));
assert!(!DEFAULT_GRID_EVALUATOR.contains("uv0"));
}
#[test]
fn assigned_standard_material_replaces_emergency_values() {
let path = std::env::temp_dir().join(format!(
"blacksite-assigned-material-{}-{}.material.ron",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let authored_color = shared::ColorDesc::srgb(0.25, 0.0, 1.0);
let asset = MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: "Purple Chrome".into(),
shader: shared::ShaderRefDesc::default(),
shader_ref: None,
render_state: shared::MaterialRenderState::default(),
inputs: shared::MaterialInputSet::from_material_desc(&MaterialDesc {
base_color: authored_color,
metallic: 0.93,
roughness: 0.17,
..Default::default()
}),
provenance: None,
};
std::fs::write(
&path,
ron::ser::to_string_pretty(&asset, ron::ser::PrettyConfig::default()).unwrap(),
)
.unwrap();
let mut app = App::new();
app.add_plugins((MinimalPlugins, AssetPlugin::default()))
.init_resource::<Assets<Shader>>()
.init_resource::<Assets<StandardMaterial>>()
.init_resource::<Assets<SurfaceMaterial>>()
.init_resource::<SurfaceMaterialCache>()
.init_resource::<LiveMaterialDocumentOverlay>()
.init_resource::<DefaultGridMaterialHandles>()
.init_resource::<shared::ProjectContentDefaults>()
.init_resource::<SurfaceDiagnostics>()
.init_resource::<SurfaceEvaluatorRegistry>()
.add_systems(Update, sync_surface_material_bindings);
let emergency = app
.world_mut()
.resource_mut::<Assets<StandardMaterial>>()
.add(StandardMaterial {
base_color: Color::srgb(0.46, 0.46, 0.46),
metallic: 0.0,
perceptual_roughness: 0.86,
..Default::default()
});
let reference = MaterialRef::new(
shared::EditorAssetRef::new("purple-chrome", "material:source", "Purple Chrome")
.with_source_path(path.to_string_lossy()),
);
let draw = app
.world_mut()
.spawn((
HydratedMaterialSlotBinding {
owner: Entity::PLACEHOLDER,
slot_id: shared::ComponentInstanceId::new("slot:primitive:surface"),
selection: HydratedMaterialSelection::Project {
reference,
layer: shared::HydratedMaterialLayer::Actor,
},
},
MeshMaterial3d(emergency.clone()),
))
.id();
app.update();
let resolved = app
.world()
.get::<MeshMaterial3d<StandardMaterial>>(draw)
.unwrap();
assert_ne!(
resolved.0, emergency,
"assigned Materials must detach from the singleton emergency handle"
);
let materials = app.world().resource::<Assets<StandardMaterial>>();
let material = materials.get(&resolved.0).unwrap();
assert_eq!(material.base_color, authored_color.to_color());
assert_eq!(material.metallic, 0.93);
assert_eq!(material.perceptual_roughness, 0.17);
let emergency_material = materials.get(&emergency).unwrap();
assert_eq!(emergency_material.base_color, Color::srgb(0.46, 0.46, 0.46));
assert_eq!(emergency_material.metallic, 0.0);
assert_eq!(emergency_material.perceptual_roughness, 0.86);
assert!(app.world().resource::<SurfaceDiagnostics>().0.is_empty());
std::fs::remove_file(path).unwrap();
}
#[test]
fn live_material_edits_persist_across_frames_and_reuse_the_handle() {
let mut app = live_material_app();
let reference = MaterialRef::new(
shared::EditorAssetRef::new("live-material", "material:source", "Live Material")
.with_source_path("assets/materials/live_material.ron"),
);
let first_color = shared::ColorDesc::srgb(0.8, 0.1, 0.05);
app.world_mut()
.resource_mut::<LiveMaterialDocumentOverlay>()
.update_material(
reference.0.asset_id.clone(),
1,
authored_standard_material("Live Material", first_color),
);
let emergency = app
.world_mut()
.resource_mut::<Assets<StandardMaterial>>()
.add(StandardMaterial::default());
let draw = app
.world_mut()
.spawn((
HydratedMaterialSlotBinding {
owner: Entity::PLACEHOLDER,
slot_id: shared::ComponentInstanceId::new("slot:primitive:surface"),
selection: HydratedMaterialSelection::Project {
reference: reference.clone(),
layer: shared::HydratedMaterialLayer::Actor,
},
},
MeshMaterial3d(emergency),
))
.id();
app.update();
let handle = app
.world()
.get::<MeshMaterial3d<StandardMaterial>>(draw)
.unwrap()
.0
.clone();
assert_eq!(
app.world()
.resource::<Assets<StandardMaterial>>()
.get(&handle)
.unwrap()
.base_color,
first_color.to_color()
);
let second_color = shared::ColorDesc::srgb(0.05, 0.15, 0.9);
app.world_mut()
.resource_mut::<LiveMaterialDocumentOverlay>()
.update_material(
reference.0.asset_id.clone(),
2,
authored_standard_material("Live Material", second_color),
);
app.update();
app.update();
assert_eq!(
app.world()
.get::<MeshMaterial3d<StandardMaterial>>(draw)
.unwrap()
.0,
handle,
"ordinary live edits must mutate the cached handle instead of rehydrating geometry"
);
assert_eq!(
app.world()
.resource::<Assets<StandardMaterial>>()
.get(&handle)
.unwrap()
.base_color,
second_color.to_color(),
"disk-backed state must not overwrite the live document on a later frame"
);
}
#[test]
fn live_base_material_changes_flow_through_direct_instances() {
let mut app = live_material_app();
let base_reference = MaterialRef::new(
shared::EditorAssetRef::new("live-base", "material:source", "Live Base")
.with_source_path("assets/materials/live_base.ron"),
);
let instance_reference = MaterialRef::new(
shared::EditorAssetRef::new("live-instance", "material:instance", "Live Instance")
.with_source_path("assets/materials/live_instance.ron"),
);
let first_color = shared::ColorDesc::srgb(0.7, 0.2, 0.1);
{
let mut overlay = app
.world_mut()
.resource_mut::<LiveMaterialDocumentOverlay>();
overlay.update_material(
base_reference.0.asset_id.clone(),
1,
authored_standard_material("Live Base", first_color),
);
overlay.update_instance(
instance_reference.0.asset_id.clone(),
1,
MaterialInstanceAsset {
schema_version: shared::MATERIAL_INSTANCE_SCHEMA_VERSION,
label: "Live Instance".into(),
base: base_reference.clone(),
overrides: shared::MaterialInputSet {
values: vec![shared::MaterialParameter {
name: "metallic".into(),
value: MaterialParameterValue::Float(0.75),
}],
textures: Vec::new(),
},
},
);
}
let emergency = app
.world_mut()
.resource_mut::<Assets<StandardMaterial>>()
.add(StandardMaterial::default());
let draw = app
.world_mut()
.spawn((
HydratedMaterialSlotBinding {
owner: Entity::PLACEHOLDER,
slot_id: shared::ComponentInstanceId::new("slot:body"),
selection: HydratedMaterialSelection::Project {
reference: instance_reference,
layer: shared::HydratedMaterialLayer::Actor,
},
},
MeshMaterial3d(emergency),
))
.id();
app.update();
let handle = app
.world()
.get::<MeshMaterial3d<StandardMaterial>>(draw)
.unwrap()
.0
.clone();
let second_color = shared::ColorDesc::srgb(0.1, 0.25, 0.85);
app.world_mut()
.resource_mut::<LiveMaterialDocumentOverlay>()
.update_material(
base_reference.0.asset_id.clone(),
2,
authored_standard_material("Live Base", second_color),
);
app.update();
app.update();
let materials = app.world().resource::<Assets<StandardMaterial>>();
let resolved = materials.get(&handle).unwrap();
assert_eq!(resolved.base_color, second_color.to_color());
assert_eq!(resolved.metallic, 0.75);
assert_eq!(
app.world()
.get::<MeshMaterial3d<StandardMaterial>>(draw)
.unwrap()
.0,
handle
);
}
#[test]
fn property_block_revision_is_stable_and_changes_with_values() {
let mut block = MaterialPropertyBlock {
slot_id: shared::ComponentInstanceId::new("slot:body"),
parameters: vec![shared::MaterialParameter {
name: "roughness".into(),
value: MaterialParameterValue::Float(0.25),
}],
textures: Vec::new(),
};
let first = property_block_revision(&block, None, None, 7);
assert_eq!(first, property_block_revision(&block, None, None, 7));
block.parameters[0].value = MaterialParameterValue::Float(0.8);
assert_ne!(first, property_block_revision(&block, None, None, 7));
assert_ne!(first, property_block_revision(&block, None, None, 8));
}
#[test]
fn invalid_standard_property_blocks_are_rejected_before_mutation() {
let mut block = MaterialPropertyBlock {
slot_id: shared::ComponentInstanceId::new("slot:body"),
parameters: vec![shared::MaterialParameter {
name: "unsupported".into(),
value: MaterialParameterValue::Float(0.25),
}],
textures: Vec::new(),
};
assert!(validate_standard_property_block(&block, false).is_err());
assert!(validate_standard_property_block(&block, true).is_ok());
block.parameters[0] = shared::MaterialParameter {
name: "roughness".into(),
value: MaterialParameterValue::Float(1.25),
};
assert!(validate_standard_property_block(&block, false).is_err());
block.parameters[0].value = MaterialParameterValue::Color(shared::ColorDesc::default());
assert!(validate_standard_property_block(&block, false).is_err());
}
#[test]
fn surface_property_block_overrides_existing_instance_value() {
let property = shared::MaterialParameter {
name: "tint_strength".into(),
value: MaterialParameterValue::Float(0.9),
};
let block = MaterialPropertyBlock {
slot_id: shared::ComponentInstanceId::new("slot:body"),
parameters: vec![property.clone()],
textures: Vec::new(),
};
let schema = ShaderSchemaAsset {
schema_version: shared::SURFACE_SHADER_SCHEMA_VERSION,
label: "Tint".into(),
kind: shared::MaterialShaderKind::Custom,
wgsl_path: None,
schema: shared::MaterialInputSchema {
groups: vec![shared::MaterialInputGroupDesc {
id: "surface".into(),
display_name: "Surface".into(),
..Default::default()
}],
inputs: vec![shared::ShaderPropertyDesc {
name: "tint_strength".into(),
display_name: "Tint strength".into(),
group: "surface".into(),
order: 0,
property_type: ShaderPropertyType::Float {
min: Some(0.0),
max: Some(1.0),
},
default_value: Some(MaterialParameterValue::Float(0.0)),
texture: None,
tooltip: String::new(),
advanced: false,
presentation: Default::default(),
}],
},
};
validate_standard_property_block(&block, true).unwrap();
validate_surface_property_block(Some(&schema), &block).unwrap();
let mut asset = MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: "Base".into(),
shader: shared::ShaderRefDesc::default(),
shader_ref: None,
render_state: shared::MaterialRenderState::default(),
inputs: shared::MaterialInputSet::from_material_desc(&MaterialDesc {
parameters: vec![shared::MaterialParameter {
name: "tint_strength".into(),
value: MaterialParameterValue::Float(0.1),
}],
..Default::default()
}),
provenance: None,
};
let mut instance = Some(MaterialInstanceAsset {
schema_version: MATERIAL_INSTANCE_SCHEMA_VERSION,
label: "Variant".into(),
base: MaterialRef::new(shared::EditorAssetRef::new(
"base-id",
"material:base",
"Base",
)),
overrides: shared::MaterialInputSet {
values: vec![shared::MaterialParameter {
name: "tint_strength".into(),
value: MaterialParameterValue::Float(0.4),
}],
textures: Vec::new(),
},
});
merge_surface_property_block(&mut asset, &mut instance, &block);
assert_eq!(
instance.unwrap().overrides.values,
vec![property],
"runtime block must be stronger than the selected Material Instance"
);
assert_eq!(
asset
.inputs
.values
.iter()
.find(|value| value.name == "tint_strength")
.unwrap()
.value,
MaterialParameterValue::Float(0.1),
"promotion/runtime overrides must not mutate the shared base asset"
);
}
#[test]
fn standard_property_blocks_are_owner_local_and_reuse_cached_handles() {
let mut app = App::new();
app.add_plugins(MinimalPlugins)
.add_plugins(AssetPlugin::default())
.init_resource::<Assets<StandardMaterial>>()
.init_resource::<Assets<SurfaceMaterial>>()
.init_resource::<SurfaceMaterialCache>()
.init_resource::<MaterialPropertyBlockCache>()
.init_resource::<SurfaceDiagnostics>()
.add_systems(Update, apply_material_property_blocks);
let base = app
.world_mut()
.resource_mut::<Assets<StandardMaterial>>()
.add(StandardMaterial {
perceptual_roughness: 0.5,
..Default::default()
});
let slot = shared::ComponentInstanceId::new("slot:body");
let spawn_owner = |world: &mut World, roughness: f32| {
world
.spawn(MaterialPropertyBlocks {
slots: vec![MaterialPropertyBlock {
slot_id: slot.clone(),
parameters: vec![shared::MaterialParameter {
name: "roughness".into(),
value: MaterialParameterValue::Float(roughness),
}],
textures: Vec::new(),
}],
})
.id()
};
let owner_a = spawn_owner(app.world_mut(), 0.2);
let owner_b = spawn_owner(app.world_mut(), 0.8);
let spawn_draw = |world: &mut World, owner| {
world
.spawn((
HydratedMaterialSlotBinding {
owner,
slot_id: slot.clone(),
selection: HydratedMaterialSelection::Inherit,
},
MeshMaterial3d(base.clone()),
))
.id()
};
let draw_a = spawn_draw(app.world_mut(), owner_a);
let draw_b = spawn_draw(app.world_mut(), owner_b);
app.update();
let handle_a = app
.world()
.get::<MeshMaterial3d<StandardMaterial>>(draw_a)
.unwrap()
.0
.clone();
let handle_b = app
.world()
.get::<MeshMaterial3d<StandardMaterial>>(draw_b)
.unwrap()
.0
.clone();
assert_ne!(handle_a, handle_b);
assert_ne!(handle_a, base);
assert_ne!(handle_b, base);
let materials = app.world().resource::<Assets<StandardMaterial>>();
assert_eq!(materials.get(&base).unwrap().perceptual_roughness, 0.5);
assert_eq!(materials.get(&handle_a).unwrap().perceptual_roughness, 0.2);
assert_eq!(materials.get(&handle_b).unwrap().perceptual_roughness, 0.8);
assert_eq!(
app.world()
.resource::<MaterialPropertyBlockCache>()
.entries
.len(),
2
);
let material_count = materials.len();
app.update();
assert_eq!(
app.world()
.get::<MeshMaterial3d<StandardMaterial>>(draw_a)
.unwrap()
.0,
handle_a
);
assert_eq!(
app.world()
.get::<MeshMaterial3d<StandardMaterial>>(draw_b)
.unwrap()
.0,
handle_b
);
assert_eq!(
app.world().resource::<Assets<StandardMaterial>>().len(),
material_count,
"steady property-block application must not grow material handles"
);
}
#[test]
fn invalid_property_block_keeps_base_visible_with_one_diagnostic() {
let mut app = App::new();
app.add_plugins(MinimalPlugins)
.add_plugins(AssetPlugin::default())
.init_resource::<Assets<StandardMaterial>>()
.init_resource::<Assets<SurfaceMaterial>>()
.init_resource::<SurfaceMaterialCache>()
.init_resource::<MaterialPropertyBlockCache>()
.init_resource::<SurfaceDiagnostics>()
.add_systems(Update, apply_material_property_blocks);
let base = app
.world_mut()
.resource_mut::<Assets<StandardMaterial>>()
.add(StandardMaterial::default());
let slot_id = shared::ComponentInstanceId::new("slot:body");
let owner = app
.world_mut()
.spawn(MaterialPropertyBlocks {
slots: vec![MaterialPropertyBlock {
slot_id: slot_id.clone(),
parameters: vec![shared::MaterialParameter {
name: "unsupported".into(),
value: MaterialParameterValue::Float(0.5),
}],
textures: Vec::new(),
}],
})
.id();
let draw = app
.world_mut()
.spawn((
HydratedMaterialSlotBinding {
owner,
slot_id,
selection: HydratedMaterialSelection::Inherit,
},
MeshMaterial3d(base.clone()),
))
.id();
app.update();
app.update();
assert_eq!(
app.world()
.get::<MeshMaterial3d<StandardMaterial>>(draw)
.unwrap()
.0,
base
);
let diagnostics = &app.world().resource::<SurfaceDiagnostics>().0;
assert_eq!(diagnostics.len(), 1);
assert!(diagnostics[0].contains("unsupported"));
}
#[test]
fn abi_limits_are_stable() {
assert_eq!(SURFACE_PARAMETER_LANES, 16);
assert_eq!(SURFACE_TEXTURE_SLOTS, 8);
assert_eq!(std::mem::size_of::<SurfaceUniform>(), 400);
}
#[test]
fn material_extensions_leave_non_deferred_prepasses_to_standard_material() {
assert!(matches!(
<SurfaceExtension as MaterialExtension>::prepass_fragment_shader(),
ShaderRef::Default
));
assert!(matches!(
<TerrainLayerExtension as MaterialExtension>::prepass_fragment_shader(),
ShaderRef::Default
));
assert!(!surface_evaluator_owns_fragment(&[
"PREPASS_PIPELINE".into(),
"NORMAL_PREPASS".into(),
]));
assert!(surface_evaluator_owns_fragment(&[
"PREPASS_PIPELINE".into(),
"DEFERRED_PREPASS".into(),
]));
assert!(surface_evaluator_owns_fragment(&[]));
}
#[test]
fn terrain_layer_builder_packs_project_material_values() {
let mut app = App::new();
app.add_plugins((MinimalPlugins, AssetPlugin::default()));
let asset_server = app.world().resource::<AssetServer>();
let materials_root =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/materials");
let layers = [
TerrainMaterialLayer {
material: Some(
shared::EditorAssetRef::new("concrete", "material:source", "Concrete")
.with_source_path(materials_root.join("concrete.ron").display().to_string()),
),
uv_scale: 6.0,
},
TerrainMaterialLayer {
material: Some(
shared::EditorAssetRef::new("tint", "material:source", "Surface Tint")
.with_source_path(
materials_root
.join("surface_tint.ron")
.display()
.to_string(),
),
),
uv_scale: 10.0,
},
];
let mut diagnostics = Vec::new();
let live_documents = LiveMaterialDocumentOverlay::default();
let material =
build_terrain_layer_material(asset_server, &layers, &live_documents, &mut diagnostics);
assert!(diagnostics.is_empty(), "{diagnostics:?}");
assert_eq!(material.extension.uniform.uv_scales.x, 6.0);
assert_eq!(material.extension.uniform.uv_scales.y, 10.0);
assert_eq!(material.extension.uniform.properties[0].w, 1.0);
assert_eq!(material.extension.uniform.properties[1].w, 1.0);
assert_eq!(
material.base.opaque_render_method,
OpaqueRendererMethod::Forward
);
assert_ne!(
material.extension.uniform.base_colors[0],
material.extension.uniform.base_colors[1]
);
}
@@ -0,0 +1,81 @@
use super::*;
pub fn validate_surface_evaluator(source: &str) -> Result<(), String> {
if !source.contains("fn evaluate(") {
return Err("surface WGSL must define `fn evaluate(`".into());
}
for forbidden in [
"@group",
"@binding",
"@vertex",
"@fragment",
"@compute",
"var<",
"rayQuery",
"dpdx",
"dpdy",
"fwidth",
"discard",
"Barrier",
"subgroup",
"textureStore",
"atomic",
] {
if source.contains(forbidden) {
return Err(format!(
"surface WGSL uses forbidden construct `{forbidden}`"
));
}
}
let validation_source = format!("{EVALUATOR_VALIDATION_PRELUDE}\n{source}");
let module = naga::front::wgsl::parse_str(&validation_source)
.map_err(|error| format!("surface WGSL syntax error: {error}"))?;
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::empty(),
)
.validate(&module)
.map_err(|error| format!("surface WGSL validation error: {error}"))?;
Ok(())
}
pub(super) const EVALUATOR_VALIDATION_PRELUDE: &str = r#"
struct SurfaceInput {
uv0: vec2<f32>,
world_position: vec3<f32>,
world_normal: vec3<f32>,
}
struct SurfaceParams { lanes: array<vec4<f32>, 16>, }
struct SurfaceSamples { values: array<vec4<f32>, 8>, }
struct Surface {
base_color: vec4<f32>,
normal_ts: vec3<f32>,
emissive: vec3<f32>,
metallic: f32,
perceptual_roughness: f32,
reflectance: f32,
occlusion: f32,
model: u32,
}
fn surface_default() -> Surface {
var surface: Surface;
surface.base_color = vec4<f32>(1.0);
surface.normal_ts = vec3<f32>(0.0, 0.0, 1.0);
surface.emissive = vec3<f32>(0.0);
surface.metallic = 0.0;
surface.perceptual_roughness = 0.5;
surface.reflectance = 0.5;
surface.occlusion = 1.0;
surface.model = 0u;
return surface;
}
"#;
pub fn compose_surface_shader(evaluator: &str) -> String {
format!(
"{}\n{}\n{}",
include_str!("../surface_header.wgsl"),
evaluator,
include_str!("../surface_footer.wgsl")
)
}
+12
View File
@@ -0,0 +1,12 @@
# Content pipeline subtree rules
- This crate owns UI-independent asset, import, catalog, transaction, watcher, and processing
behavior.
- Preserve transaction atomicity, byte-identical rollback, stable identity, reference repair,
derived-artifact ownership, managed-path protection, watcher suppression, and deterministic
restart behavior.
- Prefer focused tests here over heavy editor tests.
- Never depend on the editor crate.
- Keep GPU and rendering requirements out of headless paths.
- A defect in one content operation may justify one bounded sibling-operation invariant audit, not
an unlimited repository audit.
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "content_pipeline"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "UI-independent Blacksite content discovery, registry, and transaction pipeline"
[dependencies]
blake3 = "1"
bevy.workspace = true
bevy_ufbx.workspace = true
basis-universal = "0.3.1"
gltf = { version = "1.4", features = ["extras"] }
image = "0.25.10"
notify = "6.1"
ron = "0.8"
serde.workspace = true
serde_json = "1"
shared.workspace = true
walkdir = "2.5"
uuid = { version = "1", features = ["v4"] }
ufbx = "0.9"
[dev-dependencies]
+912
View File
@@ -0,0 +1,912 @@
//! Generated animation artifacts for imported model sources.
use std::collections::BTreeSet;
use std::fs;
use std::path::Path;
use serde::Deserialize;
use shared::{
animation_clip_sub_asset_id, animation_skeleton_sub_asset_id, AnimationClipRecord,
AnimationDiagnosticSeverity, AnimationEventDesc, AnimationImportDiagnostic, AnimationManifest,
AnimationManifestSource, AnimationSkeletonRecord, AnimationSkeletonSignature,
AnimationSourceFingerprint, ANIMATION_ARTIFACT_DIR, ANIMATION_MANIFEST_SCHEMA_VERSION,
};
use crate::fingerprint::write_pretty_ron_if_changed;
use shared::AssetRecord;
pub fn animation_manifest_path(asset_id: &str) -> String {
format!("{ANIMATION_ARTIFACT_DIR}/{asset_id}.animation.ron")
}
pub fn refresh_animation_artifact(record: &mut AssetRecord) -> Result<AnimationManifest, String> {
let (manifest, path) = plan_animation_artifact(record)?;
if write_pretty_ron_if_changed(&path, &manifest)
.map_err(|error| format!("could not publish animation manifest {path}: {error}"))?
{
bevy::log::info!(
"Animation manifest refreshed: source={} artifact={} skeletons={} clips={} runtime_supported={}",
record.path,
path,
manifest.skeletons.len(),
manifest.clips.len(),
manifest.runtime_supported
);
}
Ok(manifest)
}
pub fn plan_animation_artifact(
record: &mut AssetRecord,
) -> Result<(AnimationManifest, String), String> {
let mut manifest = build_animation_manifest(record)?;
manifest.source.dependencies.sort();
manifest.source.dependencies.dedup();
let path = animation_manifest_path(&record.id.as_string());
record.model_import_mut().animation_manifest_path = Some(path.clone());
record
.dependencies
.extend(manifest.source.dependencies.iter().cloned());
record.dependencies.sort();
record.dependencies.dedup();
Ok((manifest, path))
}
pub fn load_animation_manifest(path: &str) -> Result<AnimationManifest, String> {
let text =
fs::read_to_string(path).map_err(|error| format!("could not read {path}: {error}"))?;
ron::from_str(&text).map_err(|error| format!("could not parse {path}: {error}"))
}
pub fn build_animation_manifest(record: &AssetRecord) -> Result<AnimationManifest, String> {
let bytes = fs::read(&record.path)
.map_err(|error| format!("could not read {}: {error}", record.path))?;
let fingerprint = source_fingerprint(&bytes);
let format = source_format(&record.path)?;
match format.as_str() {
"gltf" | "glb" => build_gltf_manifest(record, format, fingerprint, &bytes),
"fbx" => build_fbx_manifest(record, format, fingerprint, &bytes),
_ => Err(format!("unsupported animation source format `{format}`")),
}
}
#[derive(Debug, Clone)]
struct SkeletonCandidate {
compatible_nodes: BTreeSet<usize>,
signature: AnimationSkeletonSignature,
}
fn build_gltf_manifest(
record: &AssetRecord,
format: String,
fingerprint: AnimationSourceFingerprint,
bytes: &[u8],
) -> Result<AnimationManifest, String> {
let gltf = gltf::Gltf::from_slice(bytes)
.map_err(|error| format!("could not parse glTF {}: {error}", record.path))?;
let base = Path::new(&record.path).parent();
let buffers = gltf::import_buffers(&gltf.document, base, gltf.blob.clone())
.map_err(|error| format!("could not load glTF buffers for {}: {error}", record.path))?;
let mut dependencies = gltf
.document
.buffers()
.filter_map(|buffer| match buffer.source() {
gltf::buffer::Source::Uri(uri) if !uri.starts_with("data:") => {
Some(resolve_dependency(&record.path, uri))
}
_ => None,
})
.collect::<Vec<_>>();
dependencies.sort();
dependencies.dedup();
let node_identity_names = gltf
.document
.nodes()
.map(|node| bevy_node_segment(node.name(), node.index()))
.collect::<Vec<_>>();
let readable_node_names = gltf
.document
.nodes()
.map(|node| normalized_node_segment(node.name(), node.index()))
.collect::<Vec<_>>();
let mut parents = vec![None; node_identity_names.len()];
for node in gltf.document.nodes() {
for child in node.children() {
parents[child.index()] = Some(node.index());
}
}
let mut skeletons = Vec::new();
let mut candidates = Vec::new();
for skin in gltf.document.skins() {
let source_index = skin.index();
let label = skin
.name()
.filter(|name| !name.trim().is_empty())
.map(str::to_string)
.unwrap_or_else(|| format!("Skeleton {source_index}"));
let joint_indices = skin.joints().map(|joint| joint.index()).collect::<Vec<_>>();
let joint_identity_paths = joint_indices
.iter()
.map(|index| node_path_segments(*index, &node_identity_names, &parents))
.collect::<Vec<_>>();
let joint_paths = joint_indices
.iter()
.map(|index| node_path(*index, &readable_node_names, &parents))
.collect::<Vec<_>>();
let bind_poses = skin
.reader(|buffer| Some(buffers[buffer.index()].0.as_slice()))
.read_inverse_bind_matrices()
.map(|matrices| matrices.map(gltf_matrix_bytes).collect::<Vec<_>>())
.unwrap_or_else(|| vec![identity_matrix_bytes(); joint_paths.len()]);
let signature = skeleton_signature(&joint_identity_paths, &bind_poses);
let mut compatible_nodes = joint_indices.into_iter().collect::<BTreeSet<_>>();
if let Some(root) = skin.skeleton() {
compatible_nodes.insert(root.index());
}
candidates.push(SkeletonCandidate {
compatible_nodes,
signature: signature.clone(),
});
skeletons.push(AnimationSkeletonRecord {
id: animation_skeleton_sub_asset_id(source_index, &label),
label,
source_index,
signature,
joint_paths,
});
}
let mut diagnostics = Vec::new();
let mut clips = Vec::new();
let mut animation_roots = BTreeSet::new();
for animation in gltf.document.animations() {
let source_index = animation.index();
let label = animation
.name()
.filter(|name| !name.trim().is_empty())
.map(str::to_string)
.unwrap_or_else(|| format!("Animation {source_index}"));
let mut duration_seconds = 0.0_f32;
let mut target_nodes = BTreeSet::new();
for channel in animation.channels() {
let target_index = channel.target().node().index();
target_nodes.insert(target_index);
animation_roots.insert(top_level_node(target_index, &parents));
if let Some(inputs) = channel
.reader(|buffer| Some(buffers[buffer.index()].0.as_slice()))
.read_inputs()
{
for input in inputs {
if input.is_finite() {
duration_seconds = duration_seconds.max(input);
}
}
}
}
let target_skeleton_signature = matching_skeleton_signature(&target_nodes, &candidates);
if !candidates.is_empty() && target_skeleton_signature.is_none() {
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Warning,
code: "animation.clip_skeleton_unresolved".into(),
message: format!(
"clip `{label}` does not target a uniquely identifiable imported skeleton"
),
repair: "Export the clip with channels targeting one skeleton, or split unrelated rigs into separate glTF assets.".into(),
});
}
let events = gltf_animation_events(&animation, duration_seconds, &label, &mut diagnostics);
clips.push(AnimationClipRecord {
id: animation_clip_sub_asset_id(source_index, &label),
label,
source_index,
duration_seconds,
target_skeleton_signature,
events,
});
}
let default_animation_clip_id = record.model_import().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
.iter()
.map(|index| format!("`{}` (node {index})", node_identity_names[*index]))
.collect::<Vec<_>>()
.join(", ");
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Error,
code: "animation.multiple_roots_unsupported".into(),
message: format!(
"animation channels target {} distinct top-level roots ({roots}); Bevy requires a separate AnimationPlayer for each root",
animation_roots.len()
),
repair: "Split the source into one animated rig per glTF asset, or export every clip under one common top-level root, then reimport.".into(),
});
}
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,
fingerprint,
dependencies,
},
runtime_supported,
skeletons,
clips,
diagnostics,
})
}
fn build_fbx_manifest(
record: &AssetRecord,
format: String,
fingerprint: AnimationSourceFingerprint,
bytes: &[u8],
) -> Result<AnimationManifest, String> {
let scene = ufbx::load_memory(
bytes,
ufbx::LoadOpts {
target_unit_meters: 1.0,
target_axes: ufbx::CoordinateAxes::right_handed_y_up(),
..Default::default()
},
)
.map_err(|error| format!("could not parse FBX {}: {error:?}", record.path))?;
let mut skeletons = Vec::new();
for (source_index, skin) in scene.skin_deformers.as_ref().iter().enumerate() {
let label = if skin.element.name.is_empty() {
format!("Skeleton {source_index}")
} else {
skin.element.name.to_string()
};
let mut joint_identity_paths = Vec::new();
let mut joint_paths = Vec::new();
let mut bind_poses = Vec::new();
for cluster in skin.clusters.as_ref() {
let Some(bone) = cluster.bone_node.as_ref() else {
continue;
};
let segments = fbx_node_path_segments(bone.as_ref());
joint_paths.push(segments.join("/"));
joint_identity_paths.push(segments);
bind_poses.push(fbx_matrix_bytes(&cluster.bind_to_world));
}
let signature = skeleton_signature(&joint_identity_paths, &bind_poses);
skeletons.push(AnimationSkeletonRecord {
id: animation_skeleton_sub_asset_id(source_index, &label),
label,
source_index,
signature,
joint_paths,
});
}
let fallback_signature = (skeletons.len() == 1).then(|| skeletons[0].signature.clone());
let clips = scene
.anim_stacks
.as_ref()
.iter()
.enumerate()
.map(|(source_index, stack)| {
let label = if stack.element.name.is_empty() {
format!("Animation {source_index}")
} else {
stack.element.name.to_string()
};
AnimationClipRecord {
id: animation_clip_sub_asset_id(source_index, &label),
label,
source_index,
duration_seconds: (stack.time_end - stack.time_begin).max(0.0) as f32,
target_skeleton_signature: fallback_signature.clone(),
events: Vec::new(),
}
})
.collect::<Vec<_>>();
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.model_import().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,
fingerprint,
dependencies: Vec::new(),
},
runtime_supported,
skeletons,
clips,
diagnostics,
})
}
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,
) -> (bool, Vec<AnimationImportDiagnostic>) {
let mut diagnostics = Vec::new();
if animation_count > 0 || skin_count > 0 {
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Error,
code: "animation.fbx_runtime_unsupported".into(),
message: format!(
"FBX contains {animation_count} animation stack(s) and {skin_count} skin deformer(s), but Blacksite's current FBX loader cannot build a runtime skeleton or clips"
),
repair: "Export the animated source as glTF 2.0 (.glb or .gltf). Keep FBX only for static mesh import until hierarchy, SkinnedMesh, and AnimationClip conversion are implemented.".into(),
});
}
(false, diagnostics)
}
#[derive(Debug, Default, Deserialize)]
struct GltfAnimationExtras {
#[serde(default)]
blacksite_events: Vec<GltfAnimationEvent>,
}
#[derive(Debug, Deserialize)]
struct GltfAnimationEvent {
id: String,
time_seconds: f32,
#[serde(default)]
payload: Option<String>,
}
fn gltf_animation_events(
animation: &gltf::Animation<'_>,
duration_seconds: f32,
clip_label: &str,
diagnostics: &mut Vec<AnimationImportDiagnostic>,
) -> Vec<AnimationEventDesc> {
let Some(raw) = animation.extras().as_ref() else {
return Vec::new();
};
let extras = match serde_json::from_str::<GltfAnimationExtras>(raw.get()) {
Ok(extras) => extras,
Err(error) => {
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Warning,
code: "animation.events_invalid".into(),
message: format!("clip `{clip_label}` has invalid animation event metadata: {error}"),
repair: "Use an animation extras object with `blacksite_events` entries containing `id`, `time_seconds`, and optional string `payload`.".into(),
});
return Vec::new();
}
};
let mut events = Vec::new();
for event in extras.blacksite_events {
let valid_time = event.time_seconds.is_finite()
&& event.time_seconds >= 0.0
&& event.time_seconds <= duration_seconds;
if event.id.trim().is_empty() || !valid_time {
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Warning,
code: "animation.event_out_of_range".into(),
message: format!(
"clip `{clip_label}` contains an event with an empty ID or time outside 0..={duration_seconds:.3}s"
),
repair: "Give every event a stable non-empty ID and place it within the imported clip duration.".into(),
});
continue;
}
events.push(AnimationEventDesc {
id: event.id,
time_seconds: event.time_seconds,
payload: event.payload,
});
}
events.sort_by(|left, right| {
left.time_seconds
.total_cmp(&right.time_seconds)
.then(left.id.cmp(&right.id))
.then(left.payload.cmp(&right.payload))
});
events
}
fn matching_skeleton_signature(
target_nodes: &BTreeSet<usize>,
candidates: &[SkeletonCandidate],
) -> Option<AnimationSkeletonSignature> {
let scored = candidates
.iter()
.map(|candidate| {
(
candidate
.compatible_nodes
.intersection(target_nodes)
.count(),
candidate,
)
})
.filter(|(score, _)| *score > 0)
.collect::<Vec<_>>();
let best_score = scored.iter().map(|(score, _)| *score).max()?;
let mut best = scored
.into_iter()
.filter(|(score, _)| *score == best_score)
.map(|(_, candidate)| candidate);
let candidate = best.next()?;
best.all(|other| other.signature == candidate.signature)
.then(|| candidate.signature.clone())
}
fn node_path(index: usize, names: &[String], parents: &[Option<usize>]) -> String {
node_path_segments(index, names, parents).join("/")
}
fn node_path_segments(index: usize, names: &[String], parents: &[Option<usize>]) -> Vec<String> {
let mut segments = Vec::new();
let mut current = Some(index);
while let Some(node_index) = current {
segments.push(names[node_index].clone());
current = parents[node_index];
}
segments.reverse();
segments
}
fn top_level_node(index: usize, parents: &[Option<usize>]) -> usize {
let mut current = index;
while let Some(parent) = parents[current] {
current = parent;
}
current
}
fn bevy_node_segment(name: Option<&str>, index: usize) -> String {
name.map(str::to_string)
.unwrap_or_else(|| format!("GltfNode{index}"))
}
fn normalized_node_segment(name: Option<&str>, index: usize) -> String {
name.map(str::trim)
.filter(|name| !name.is_empty())
.map(|name| name.replace(['/', '\\'], "_"))
.unwrap_or_else(|| format!("Node{index}"))
}
fn fbx_node_path_segments(node: &ufbx::Node) -> Vec<String> {
let mut segments = Vec::new();
let mut current = Some(node);
while let Some(node) = current {
segments.push(normalized_node_segment(
(!node.element.name.is_empty()).then(|| node.element.name.as_ref()),
node.element.element_id as usize,
));
current = node.parent.as_ref().map(|parent| parent.as_ref());
}
segments.reverse();
segments
}
fn skeleton_signature(
joint_path_segments: &[Vec<String>],
bind_pose_bytes: &[Vec<u8>],
) -> AnimationSkeletonSignature {
let mut hasher = blake3::Hasher::new();
hasher.update(b"blacksite-animation-skeleton-v2\0");
hasher.update(&(joint_path_segments.len() as u64).to_le_bytes());
for path in joint_path_segments {
hasher.update(&(path.len() as u64).to_le_bytes());
for segment in path {
let bytes = segment.as_bytes();
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
}
}
hasher.update(&(bind_pose_bytes.len() as u64).to_le_bytes());
for bytes in bind_pose_bytes {
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
}
AnimationSkeletonSignature::new(hasher.finalize().to_hex().to_string())
}
fn gltf_matrix_bytes(matrix: [[f32; 4]; 4]) -> Vec<u8> {
matrix
.into_iter()
.flatten()
.flat_map(f32::to_le_bytes)
.collect()
}
fn identity_matrix_bytes() -> Vec<u8> {
gltf_matrix_bytes([
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
])
}
fn fbx_matrix_bytes(matrix: &ufbx::Matrix) -> Vec<u8> {
[
matrix.m00, matrix.m10, matrix.m20, matrix.m01, matrix.m11, matrix.m21, matrix.m02,
matrix.m12, matrix.m22, matrix.m03, matrix.m13, matrix.m23,
]
.into_iter()
.flat_map(f64::to_le_bytes)
.collect()
}
fn source_fingerprint(bytes: &[u8]) -> AnimationSourceFingerprint {
AnimationSourceFingerprint::from_bytes(bytes)
}
fn source_format(path: &str) -> Result<String, String> {
Path::new(path)
.extension()
.and_then(|extension| extension.to_str())
.map(|extension| extension.to_ascii_lowercase())
.ok_or_else(|| format!("asset path `{path}` has no extension"))
}
fn resolve_dependency(source_path: &str, uri: &str) -> String {
Path::new(source_path)
.parent()
.unwrap_or_else(|| Path::new(""))
.join(uri)
.to_string_lossy()
.replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
use shared::{AssetId, AssetImportSettings, ImportSettings};
use uuid::Uuid;
fn fixture_record(path: &Path) -> AssetRecord {
AssetRecord {
id: AssetId(Uuid::nil()),
path: path.to_string_lossy().replace('\\', "/"),
label: "Animated Hero".into(),
kind: shared::AssetKind::Model,
source_fingerprint: None,
import_settings: AssetImportSettings::Model(ImportSettings::default()),
dependencies: Vec::new(),
}
}
fn write_animated_gltf(root: &Path) -> std::path::PathBuf {
fs::create_dir_all(root).unwrap();
let mut buffer = Vec::new();
for value in [0.0_f32, 1.25] {
buffer.extend_from_slice(&value.to_le_bytes());
}
for value in [0.0_f32, 0.0, 0.0, 1.0, 0.0, 0.38268343, 0.0, 0.9238795] {
buffer.extend_from_slice(&value.to_le_bytes());
}
fs::write(root.join("animated.bin"), buffer).unwrap();
let gltf = r#"{
"asset":{"version":"2.0"},
"scene":0,
"scenes":[{"nodes":[0]}],
"nodes":[{"name":"Armature","children":[1]},{"name":"Hip"}],
"skins":[{"name":"Hero Rig","skeleton":0,"joints":[1]}],
"buffers":[{"uri":"animated.bin","byteLength":40}],
"bufferViews":[
{"buffer":0,"byteOffset":0,"byteLength":8},
{"buffer":0,"byteOffset":8,"byteLength":32}
],
"accessors":[
{"bufferView":0,"componentType":5126,"count":2,"type":"SCALAR","min":[0.0],"max":[1.25]},
{"bufferView":1,"componentType":5126,"count":2,"type":"VEC4"}
],
"animations":[{
"name":"Idle Loop",
"samplers":[{"input":0,"output":1,"interpolation":"LINEAR"}],
"channels":[{"sampler":0,"target":{"node":1,"path":"rotation"}}],
"extras":{"blacksite_events":[{"id":"footstep.left","time_seconds":0.5,"payload":"stone"}]}
}]
}"#;
let path = root.join("animated.gltf");
fs::write(&path, gltf).unwrap();
path
}
fn write_multi_root_animated_gltf(root: &Path) -> std::path::PathBuf {
fs::create_dir_all(root).unwrap();
let mut buffer = Vec::new();
for value in [0.0_f32, 1.0] {
buffer.extend_from_slice(&value.to_le_bytes());
}
for value in [0.0_f32, 0.0, 0.0, 1.0, 0.0, 0.38268343, 0.0, 0.9238795] {
buffer.extend_from_slice(&value.to_le_bytes());
}
fs::write(root.join("multi-root.bin"), buffer).unwrap();
let gltf = r#"{
"asset":{"version":"2.0"},
"scene":0,
"scenes":[{"nodes":[0,2]}],
"nodes":[
{"name":"Character A","children":[1]},
{"name":"Joint A"},
{"name":"Character B","children":[3]},
{"name":"Joint B"}
],
"buffers":[{"uri":"multi-root.bin","byteLength":40}],
"bufferViews":[
{"buffer":0,"byteOffset":0,"byteLength":8},
{"buffer":0,"byteOffset":8,"byteLength":32}
],
"accessors":[
{"bufferView":0,"componentType":5126,"count":2,"type":"SCALAR","min":[0.0],"max":[1.0]},
{"bufferView":1,"componentType":5126,"count":2,"type":"VEC4"}
],
"animations":[{
"name":"Two Players Required",
"samplers":[
{"input":0,"output":1,"interpolation":"LINEAR"},
{"input":0,"output":1,"interpolation":"LINEAR"}
],
"channels":[
{"sampler":0,"target":{"node":1,"path":"rotation"}},
{"sampler":1,"target":{"node":3,"path":"rotation"}}
]
}]
}"#;
let path = root.join("multi-root.gltf");
fs::write(&path, gltf).unwrap();
path
}
#[test]
fn animation_manifest_path_uses_registry_uuid() {
assert_eq!(
animation_manifest_path("abc"),
"assets/animations/generated/abc.animation.ron"
);
}
#[test]
fn gltf_extraction_is_deterministic_and_preserves_duration_events_and_signature() {
let root = std::env::temp_dir().join(format!("blacksite-animation-{}", Uuid::new_v4()));
let path = write_animated_gltf(&root);
let record = fixture_record(&path);
let first = build_animation_manifest(&record).unwrap();
let second = build_animation_manifest(&record).unwrap();
assert_eq!(first, second);
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);
assert_eq!(first.clips.len(), 1);
assert_eq!(first.skeletons[0].id, "animation:skeleton:0:hero_rig");
assert!(!first.skeletons[0].signature.is_empty());
assert_eq!(first.clips[0].id, "animation:clip:0:idle_loop");
assert_eq!(first.clips[0].duration_seconds, 1.25);
assert_eq!(
first.clips[0].target_skeleton_signature,
Some(first.skeletons[0].signature.clone())
);
assert_eq!(first.clips[0].events.len(), 1);
assert_eq!(first.clips[0].events[0].id, "footstep.left");
assert_eq!(first.clips[0].events[0].time_seconds, 0.5);
assert_eq!(first.diagnostics, Vec::new());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn legacy_mtime_metadata_does_not_rewrite_equivalent_animation_manifest() {
let root =
std::env::temp_dir().join(format!("blacksite-animation-legacy-{}", Uuid::new_v4()));
let path = write_animated_gltf(&root);
let manifest = build_animation_manifest(&fixture_record(&path)).unwrap();
let canonical =
ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default()).unwrap();
let marker = format!("byte_len: {},", manifest.source.fingerprint.byte_len);
let legacy = canonical.replacen(
&marker,
&format!("{marker}\n modified_unix_secs: 123456,"),
1,
);
assert_ne!(legacy, canonical);
let artifact = root.join("legacy.animation.ron");
fs::write(&artifact, &legacy).unwrap();
assert!(!write_pretty_ron_if_changed(&artifact, &manifest).unwrap());
assert_eq!(fs::read_to_string(&artifact).unwrap(), legacy);
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.model_import_mut().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.model_import_mut().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();
let first = skeleton_signature(
&[vec!["Armature".into(), "Hip".into()]],
std::slice::from_ref(&identity),
);
let renamed = skeleton_signature(
&[vec!["Armature".into(), "Pelvis".into()]],
std::slice::from_ref(&identity),
);
let mut changed_pose = identity;
changed_pose[0] ^= 1;
let rebound = skeleton_signature(&[vec!["Armature".into(), "Hip".into()]], &[changed_pose]);
assert_ne!(first, renamed);
assert_ne!(first, rebound);
}
#[test]
fn exact_signature_preserves_bevy_node_bytes_and_segment_boundaries() {
let identity = identity_matrix_bytes();
let slash_in_name = vec![vec!["Armature".into(), "Hip/Joint".into()]];
let slash_as_boundary = vec![vec!["Armature/Hip".into(), "Joint".into()]];
assert_eq!(slash_in_name[0].join("/"), slash_as_boundary[0].join("/"));
assert_ne!(
skeleton_signature(&slash_in_name, std::slice::from_ref(&identity)),
skeleton_signature(&slash_as_boundary, std::slice::from_ref(&identity))
);
let backslash = vec![vec!["Armature".into(), "Hip\\Joint".into()]];
assert_eq!(
normalized_node_segment(Some("Hip/Joint"), 1),
normalized_node_segment(Some("Hip\\Joint"), 1)
);
assert_ne!(
skeleton_signature(&slash_in_name, std::slice::from_ref(&identity)),
skeleton_signature(&backslash, std::slice::from_ref(&identity))
);
assert_eq!(bevy_node_segment(Some(" /Joint "), 7), " /Joint ");
assert_eq!(bevy_node_segment(None, 7), "GltfNode7");
}
#[test]
fn gltf_with_multiple_animation_roots_is_runtime_unsupported() {
let root =
std::env::temp_dir().join(format!("blacksite-animation-multi-root-{}", Uuid::new_v4()));
let path = write_multi_root_animated_gltf(&root);
let manifest = build_animation_manifest(&fixture_record(&path)).unwrap();
assert!(!manifest.runtime_supported);
let diagnostic = manifest
.diagnostics
.iter()
.find(|diagnostic| diagnostic.code == "animation.multiple_roots_unsupported")
.expect("multi-root glTF should include an actionable blocking diagnostic");
assert_eq!(diagnostic.severity, AnimationDiagnosticSeverity::Error);
assert!(diagnostic.message.contains("2 distinct top-level roots"));
assert!(diagnostic.repair.contains("one common top-level root"));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn animated_or_skinned_fbx_is_runtime_unsupported_with_repair_guidance() {
let (supported, diagnostics) = fbx_runtime_support(2, 1);
assert!(!supported);
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].severity, AnimationDiagnosticSeverity::Error);
assert_eq!(diagnostics[0].code, "animation.fbx_runtime_unsupported");
assert!(diagnostics[0].repair.contains("glTF 2.0"));
let (supported, diagnostics) = fbx_runtime_support(0, 0);
assert!(!supported);
assert!(diagnostics.is_empty());
}
#[test]
fn committed_robot_fixture_exposes_a_skin_and_multiple_named_states() {
let path =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/models/robot_expressive.glb");
let manifest = build_animation_manifest(&fixture_record(&path)).unwrap();
assert!(manifest.runtime_supported);
assert_eq!(manifest.skeletons.len(), 2);
assert_eq!(manifest.skeletons[0].id, "animation:skeleton:0:skeleton_0");
assert_eq!(manifest.skeletons[1].id, "animation:skeleton:1:skeleton_1");
assert!(manifest
.skeletons
.iter()
.all(|skeleton| skeleton.joint_paths.len() == 43));
let signature = &manifest.skeletons[0].signature;
assert!(manifest
.skeletons
.iter()
.all(|skeleton| &skeleton.signature == signature));
assert_eq!(manifest.clips.len(), 14);
for expected in ["Idle", "Walking", "Running", "Jump", "Wave"] {
assert!(
manifest.clips.iter().any(|clip| clip.label == expected),
"missing expected fixture clip {expected}"
);
}
assert!(manifest
.clips
.iter()
.all(|clip| clip.duration_seconds.is_finite() && clip.duration_seconds > 0.0));
assert!(manifest
.clips
.iter()
.all(|clip| { clip.target_skeleton_signature.as_ref() == Some(signature) }));
assert!(manifest.diagnostics.is_empty());
}
}
+111
View File
@@ -0,0 +1,111 @@
use std::fs;
use std::path::Path;
use serde::de::DeserializeOwned;
use serde::Serialize;
use shared::AssetSourceFingerprint;
pub fn fingerprint_file(path: impl AsRef<Path>) -> Result<AssetSourceFingerprint, String> {
let path = path.as_ref();
let bytes = fs::read(path)
.map_err(|error| format!("could not read imported source {}: {error}", path.display()))?;
Ok(AssetSourceFingerprint::from_bytes(&bytes))
}
/// Writes canonical pretty RON only when the parsed document changes semantically.
///
/// Equivalent existing bytes, including custom formatting and final-newline policy, stay intact.
pub fn write_pretty_ron_if_changed<T>(path: impl AsRef<Path>, value: &T) -> Result<bool, String>
where
T: DeserializeOwned + PartialEq + Serialize,
{
let path = path.as_ref();
if fs::read_to_string(path)
.ok()
.and_then(|text| ron::from_str::<T>(&text).ok())
.is_some_and(|existing| existing == *value)
{
return Ok(false);
}
let text = ron::ser::to_string_pretty(value, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize RON: {error}"))?;
if fs::read(path).ok().as_deref() == Some(text.as_bytes()) {
return Ok(false);
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
}
fs::write(path, text)
.map_err(|error| format!("could not write {}: {error}", path.display()))?;
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
use std::fs::{File, FileTimes};
use std::time::{Duration, SystemTime};
use uuid::Uuid;
#[derive(Debug, Deserialize, PartialEq, Serialize)]
struct Fixture {
count: u32,
label: String,
}
fn fixture_path(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!(
"blacksite-fingerprint-{name}-{}.ron",
Uuid::new_v4()
))
}
#[test]
fn metadata_only_drift_does_not_change_content_identity() {
let path = fixture_path("mtime");
fs::write(&path, b"stable source bytes").unwrap();
let before = fingerprint_file(&path).unwrap();
File::options()
.write(true)
.open(&path)
.unwrap()
.set_times(
FileTimes::new().set_modified(SystemTime::now() + Duration::from_secs(86_400)),
)
.unwrap();
assert_eq!(fingerprint_file(&path).unwrap(), before);
fs::remove_file(path).unwrap();
}
#[test]
fn same_size_byte_change_updates_content_identity() {
let path = fixture_path("same-size");
fs::write(&path, b"source-a").unwrap();
let before = fingerprint_file(&path).unwrap();
fs::write(&path, b"source-b").unwrap();
let after = fingerprint_file(&path).unwrap();
assert_eq!(before.byte_len, after.byte_len);
assert_ne!(before.content_hash, after.content_hash);
fs::remove_file(path).unwrap();
}
#[test]
fn equivalent_ron_preserves_exact_existing_bytes() {
let path = fixture_path("semantic");
let existing = b"( label: \"stable\", count: 7, )\n\n";
fs::write(&path, existing).unwrap();
let value = Fixture {
count: 7,
label: "stable".into(),
};
assert!(!write_pretty_ron_if_changed(&path, &value).unwrap());
assert_eq!(fs::read(&path).unwrap(), existing);
fs::remove_file(path).unwrap();
}
}
File diff suppressed because it is too large. Load diff
+868
View File
@@ -0,0 +1,868 @@
//! UI-independent project content discovery and publication.
use serde::{Deserialize, Serialize};
use shared::{
AssetKind, AssetRecord, AssetRegistryDocument, AssetSourceFingerprint, ComponentInstanceId,
MaterialImportPolicy, ModelMaterialSelection, ModelMaterialSlotSelection,
RuntimeContentCatalog,
};
use std::collections::{HashMap, HashSet};
use std::ffi::OsStr;
use std::fs;
use std::path::{Component, Path, PathBuf};
use walkdir::{DirEntry, WalkDir};
pub mod animation;
mod fingerprint;
mod import;
mod pbr_grouping;
pub mod static_mesh;
mod texture;
mod transaction;
mod trash;
mod watcher;
pub use fingerprint::*;
pub use import::*;
pub use pbr_grouping::*;
pub use texture::*;
pub use transaction::*;
pub use trash::*;
pub use watcher::*;
pub const ASSETS_DIRECTORY: &str = "assets";
pub const REGISTRY_PATH: &str = "assets/.index/registry.ron";
pub const RUNTIME_CATALOG_PATH: &str = "assets/content.catalog.ron";
const MANAGED_DIRECTORIES: &[&str] = &[".index", ".thumbnails", ".trash", ".import-cache"];
const MANAGED_PATH_PREFIXES: &[&str] = &[
"meshes/generated",
"animations/generated",
"navigation/generated",
];
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ContentDiagnostic {
pub path: String,
pub message: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProcessingReport {
pub discovered: usize,
pub added: usize,
pub moved: usize,
pub removed: usize,
pub changed: bool,
pub diagnostics: Vec<ContentDiagnostic>,
}
#[derive(Debug, Clone)]
pub struct ProcessedContent {
pub registry: AssetRegistryDocument,
pub runtime_catalog: RuntimeContentCatalog,
pub report: ProcessingReport,
}
/// One imported file whose current bytes match more than one missing registry record. Automatic
/// reconciliation must stop so the editor can ask which stable identity actually moved.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ExternalMoveConflict {
pub new_path: String,
pub candidate_paths: Vec<String>,
pub kind: AssetKind,
pub fingerprint: AssetSourceFingerprint,
}
pub fn find_ambiguous_external_moves(
project_root: &Path,
previous: &AssetRegistryDocument,
) -> Result<Vec<ExternalMoveConflict>, String> {
let assets_root = project_root.join(ASSETS_DIRECTORY);
if !assets_root.is_dir() {
return Err(format!(
"project has no assets directory: {}",
assets_root.display()
));
}
let mut discovered = Vec::new();
for entry in WalkDir::new(&assets_root)
.follow_links(false)
.into_iter()
.filter_entry(|entry| should_descend(entry, &assets_root))
{
let entry = entry.map_err(|error| format!("content scan failed: {error}"))?;
if !entry.file_type().is_file() {
continue;
}
let kind = classify_asset_file(entry.path());
if !kind.is_imported_source() {
continue;
}
let relative = entry
.path()
.strip_prefix(project_root)
.map_err(|error| format!("content path escaped project: {error}"))?;
let path = relative.to_string_lossy().replace('\\', "/");
let bytes = fs::read(entry.path())
.map_err(|error| format!("could not fingerprint {path}: {error}"))?;
discovered.push((path, kind, AssetSourceFingerprint::from_bytes(&bytes)));
}
let current_paths = discovered
.iter()
.map(|(path, _, _)| path.clone())
.collect::<HashSet<_>>();
let previous_paths = previous
.records
.iter()
.map(|record| record.path.as_str())
.collect::<HashSet<_>>();
let mut conflicts = Vec::new();
for (new_path, kind, fingerprint) in discovered {
if previous_paths.contains(new_path.as_str()) {
continue;
}
let mut candidate_paths = previous
.records
.iter()
.filter(|record| {
!current_paths.contains(record.path.as_str())
&& record.kind == kind
&& record.source_fingerprint.as_ref() == Some(&fingerprint)
})
.map(|record| record.path.clone())
.collect::<Vec<_>>();
candidate_paths.sort();
candidate_paths.dedup();
if candidate_paths.len() > 1 {
conflicts.push(ExternalMoveConflict {
new_path,
candidate_paths,
kind,
fingerprint,
});
}
}
conflicts.sort_by(|left, right| left.new_path.cmp(&right.new_path));
Ok(conflicts)
}
pub fn is_managed_path(relative_to_assets: &Path) -> bool {
let managed_directory = relative_to_assets
.components()
.next()
.is_some_and(|component| {
let Component::Normal(name) = component else {
return false;
};
MANAGED_DIRECTORIES
.iter()
.any(|managed| name == OsStr::new(managed))
});
let normalized = relative_to_assets.to_string_lossy().replace('\\', "/");
managed_directory
|| MANAGED_PATH_PREFIXES.iter().any(|prefix| {
normalized == *prefix
|| normalized
.strip_prefix(prefix)
.is_some_and(|suffix| suffix.starts_with('/'))
})
}
/// Validates a user-selected project content path without consulting the filesystem.
pub fn validate_asset_path(path: &Path) -> Result<(), String> {
if path.is_absolute() {
return Err("content paths must be project-relative".into());
}
let mut components = path.components();
if components.next() != Some(Component::Normal(OsStr::new(ASSETS_DIRECTORY))) {
return Err("content paths must be located under `assets/`".into());
}
let remainder = components.collect::<PathBuf>();
if remainder.as_os_str().is_empty() {
return Ok(());
}
if remainder.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) {
return Err("content paths cannot escape `assets/`".into());
}
if is_managed_path(&remainder) {
return Err("engine-managed content directories cannot be edited".into());
}
Ok(())
}
/// Classifies an asset by its filename/schema suffix rather than its containing folder.
pub fn classify_asset(path: &Path) -> AssetKind {
let name = path
.file_name()
.and_then(OsStr::to_str)
.unwrap_or_default()
.to_ascii_lowercase();
if name.ends_with(".material-instance.ron") {
return AssetKind::MaterialInstance;
}
if name.ends_with(".material.ron") {
return AssetKind::Material;
}
if name.ends_with(".scn.ron") {
return AssetKind::Level;
}
if name.ends_with(".prefab.ron") {
return AssetKind::Prefab;
}
if name.ends_with(".post-process.ron") {
return AssetKind::PostProcessEffect;
}
if name.ends_with(".rendering-profile.ron") {
return AssetKind::RenderingProfile;
}
if name.ends_with(".shader-schema.ron") {
return AssetKind::ShaderSchema;
}
match path
.extension()
.and_then(OsStr::to_str)
.unwrap_or_default()
.to_ascii_lowercase()
.as_str()
{
"gltf" | "glb" | "fbx" => AssetKind::Model,
"png" | "jpg" | "jpeg" | "webp" | "ktx2" | "dds" | "tga" | "exr" | "hdr" => {
AssetKind::Texture
}
"ogg" | "oga" | "spx" | "wav" | "mp3" | "flac" => AssetKind::AudioClip,
"mat" | "material" => AssetKind::Material,
_ => AssetKind::Unknown,
}
}
/// Adds schema-based classification for authored RON assets whose filename is user-controlled.
pub fn classify_asset_file(path: &Path) -> AssetKind {
let path_kind = classify_asset(path);
if path_kind != AssetKind::Unknown && !path.to_string_lossy().ends_with(".scn.ron") {
return path_kind;
}
if path.extension().and_then(OsStr::to_str) != Some("ron") {
return path_kind;
}
let Ok(source) = fs::read_to_string(path) else {
return path_kind;
};
if ron::from_str::<shared::MaterialInstanceAsset>(&source).is_ok() {
return AssetKind::MaterialInstance;
}
if ron::from_str::<shared::MaterialAsset>(&source).is_ok() {
return AssetKind::Material;
}
if ron::from_str::<shared::ShaderSchemaAsset>(&source).is_ok() {
return AssetKind::ShaderSchema;
}
if ron::from_str::<shared::RenderingProfileAsset>(&source).is_ok() {
return AssetKind::RenderingProfile;
}
if ron::from_str::<shared::PostProcessEffectAsset>(&source).is_ok() {
return AssetKind::PostProcessEffect;
}
path_kind
}
fn should_descend(entry: &DirEntry, assets_root: &Path) -> bool {
if entry.file_type().is_symlink() {
return false;
}
entry
.path()
.strip_prefix(assets_root)
.ok()
.is_none_or(|relative| !is_managed_path(relative))
}
pub fn scan_project(
project_root: &Path,
previous: &AssetRegistryDocument,
) -> Result<ProcessedContent, String> {
let assets_root = project_root.join(ASSETS_DIRECTORY);
if !assets_root.is_dir() {
return Err(format!(
"project has no assets directory: {}",
assets_root.display()
));
}
let mut discovered = Vec::new();
let mut diagnostics = Vec::new();
let previous_kinds = previous
.records
.iter()
.map(|record| (record.path.as_str(), record.kind))
.collect::<HashMap<_, _>>();
for entry in WalkDir::new(&assets_root)
.follow_links(false)
.into_iter()
.filter_entry(|entry| should_descend(entry, &assets_root))
{
let entry = entry.map_err(|error| format!("content scan failed: {error}"))?;
if !entry.file_type().is_file() {
continue;
}
let relative = entry
.path()
.strip_prefix(project_root)
.map_err(|error| format!("content path escaped project: {error}"))?;
let path = relative.to_string_lossy().replace('\\', "/");
let mut kind = classify_asset_file(entry.path());
if matches!(kind, AssetKind::Level | AssetKind::Unknown) {
kind = previous_kinds.get(path.as_str()).copied().unwrap_or(kind);
}
if kind == AssetKind::Unknown {
continue;
}
let fingerprint = if kind.is_imported_source() {
match fs::read(entry.path()) {
Ok(bytes) => Some(AssetSourceFingerprint::from_bytes(&bytes)),
Err(error) => {
diagnostics.push(ContentDiagnostic {
path: path.clone(),
message: format!("could not fingerprint imported source: {error}"),
});
None
}
}
} else {
None
};
discovered.push((path, kind, fingerprint));
}
let mut by_path = previous
.records
.iter()
.cloned()
.map(|record| (record.path.clone(), record))
.collect::<HashMap<_, _>>();
let current_paths = discovered
.iter()
.map(|(path, _, _)| path.clone())
.collect::<HashSet<_>>();
let mut records = Vec::with_capacity(discovered.len());
let mut report = ProcessingReport {
discovered: discovered.len(),
diagnostics,
..Default::default()
};
for (path, kind, fingerprint) in discovered {
let label = Path::new(&path)
.file_stem()
.and_then(OsStr::to_str)
.unwrap_or("Asset")
.to_string();
let mut record = by_path.remove(&path);
if record.is_none() {
if let Some(fingerprint) = fingerprint.as_ref() {
let mut candidates = by_path
.iter()
.filter(|(old_path, record)| {
!current_paths.contains(*old_path)
&& record.kind == kind
&& record.source_fingerprint.as_ref() == Some(fingerprint)
})
.map(|(old_path, _)| old_path.clone())
.collect::<Vec<_>>();
candidates.sort();
match candidates.as_slice() {
[candidate] => record = by_path.remove(candidate),
[] => {}
_ => {
return Err(format!(
"ambiguous external move for {path}: source fingerprint matches {}; resolve the stable identity in the editor Content Browser before refreshing or running headless processing",
candidates.join(", ")
));
}
}
}
}
if let Some(existing) = record.as_mut() {
if existing.path != path {
report.moved += 1;
}
existing.path = path;
existing.label = label;
existing.kind = kind;
existing.source_fingerprint = fingerprint;
} else {
report.added += 1;
record = Some(AssetRecord {
id: shared::AssetId::new(),
path,
label,
kind,
source_fingerprint: fingerprint,
import_settings: shared::AssetImportSettings::for_kind(kind),
dependencies: Vec::new(),
});
}
let mut record = record.expect("record is initialized");
migrate_legacy_model_material_policy(project_root, &mut record, &mut report.diagnostics);
records.push(record);
}
report.removed = by_path.len();
records.sort_by(|left, right| left.path.cmp(&right.path));
let registry = AssetRegistryDocument {
schema_version: shared::ASSET_REGISTRY_SCHEMA_VERSION,
defaults: previous.defaults.clone(),
records,
};
report.changed = &registry != previous;
let runtime_catalog = RuntimeContentCatalog::from(&registry);
Ok(ProcessedContent {
registry,
runtime_catalog,
report,
})
}
#[derive(Deserialize)]
struct ModelManifestSlotView {
#[serde(default)]
parts: Vec<ModelManifestPartView>,
}
#[derive(Deserialize)]
struct ModelManifestPartView {
#[serde(default)]
id: String,
#[serde(default)]
material_id: Option<String>,
#[serde(default)]
material_label: Option<String>,
}
fn migrate_legacy_model_material_policy(
project_root: &Path,
record: &mut AssetRecord,
diagnostics: &mut Vec<ContentDiagnostic>,
) {
if record.kind != AssetKind::Model {
return;
}
if record.model_import().material_policy != MaterialImportPolicy::AuthoringOverride {
return;
}
let Some(manifest_path) = record.model_import().static_mesh_manifest_path.as_deref() else {
diagnostics.push(ContentDiagnostic {
path: record.path.clone(),
message: "legacy Authoring Override needs a regenerated model manifest before per-slot migration"
.into(),
});
return;
};
let path = project_root.join(manifest_path);
let manifest = fs::read_to_string(&path)
.map_err(|error| format!("could not read {}: {error}", path.display()))
.and_then(|source| {
ron::from_str::<ModelManifestSlotView>(&source)
.map_err(|error| format!("could not parse {}: {error}", path.display()))
});
let manifest = match manifest {
Ok(manifest) => manifest,
Err(message) => {
diagnostics.push(ContentDiagnostic {
path: record.path.clone(),
message,
});
return;
}
};
let mut migrated = record.model_import().material_slots.clone();
for part in manifest.parts {
if part.material_id.is_none() && part.material_label.is_none() {
continue;
}
if part.id.trim().is_empty() {
diagnostics.push(ContentDiagnostic {
path: record.path.clone(),
message: "legacy material policy cannot migrate a model part with no stable ID; regenerate its manifest in the editor"
.into(),
});
return;
}
let slot_id = ComponentInstanceId::new(format!("slot:{}", part.id));
if !migrated
.iter()
.any(|selection| selection.slot_id == slot_id)
{
migrated.push(ModelMaterialSlotSelection {
slot_id,
selection: ModelMaterialSelection::Default,
});
}
}
migrated.sort_by(|left, right| left.slot_id.0.cmp(&right.slot_id.0));
record.model_import_mut().material_slots = migrated;
record.model_import_mut().material_policy = MaterialImportPolicy::SourceMaterials;
}
pub fn serialize_registry(document: &AssetRegistryDocument) -> Result<Vec<u8>, String> {
ron::ser::to_string_pretty(document, ron::ser::PrettyConfig::default())
.map(|source| source.into_bytes())
.map_err(|error| format!("could not serialize asset registry: {error}"))
}
pub fn serialize_runtime_catalog(catalog: &RuntimeContentCatalog) -> Result<Vec<u8>, String> {
ron::ser::to_string_pretty(catalog, ron::ser::PrettyConfig::default())
.map(|source| source.into_bytes())
.map_err(|error| format!("could not serialize runtime catalog: {error}"))
}
/// Publishes the editor registry and stripped runtime catalog as one rollback-capable pair.
pub fn publish_content_documents(
project_root: &Path,
document: &AssetRegistryDocument,
) -> Result<(), String> {
let runtime = RuntimeContentCatalog::from(document);
publish_content_documents_with_catalog(project_root, document, &runtime)
}
pub fn publish_content_documents_with_catalog(
project_root: &Path,
document: &AssetRegistryDocument,
runtime: &RuntimeContentCatalog,
) -> Result<(), String> {
let registry_path = project_root.join(REGISTRY_PATH);
let runtime_path = project_root.join(RUNTIME_CATALOG_PATH);
let original_registry = fs::read(&registry_path).ok();
let original_runtime = fs::read(&runtime_path).ok();
let registry_bytes = serialize_registry(document)?;
let runtime_bytes = serialize_runtime_catalog(runtime)?;
if let Err(error) = write_if_changed(&registry_path, &registry_bytes)
.and_then(|_| write_if_changed(&runtime_path, &runtime_bytes))
{
restore_published_file(&registry_path, original_registry.as_deref());
restore_published_file(&runtime_path, original_runtime.as_deref());
return Err(format!("content catalog publication rolled back: {error}"));
}
Ok(())
}
fn restore_published_file(path: &Path, bytes: Option<&[u8]>) {
if let Some(bytes) = bytes {
let _ = fs::write(path, bytes);
} else {
let _ = fs::remove_file(path);
}
}
pub fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<bool, String> {
if fs::read(path).ok().as_deref() == Some(bytes) {
return Ok(false);
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
}
let temporary = path.with_extension("tmp");
fs::write(&temporary, bytes)
.map_err(|error| format!("could not stage {}: {error}", path.display()))?;
fs::rename(&temporary, path)
.map_err(|error| format!("could not publish {}: {error}", path.display()))?;
Ok(true)
}
#[derive(Debug, Clone)]
pub struct PlannedModelArtifacts {
pub record: shared::AssetRecord,
pub static_manifest: static_mesh::StaticMeshManifest,
pub static_path: std::path::PathBuf,
pub static_bytes: Vec<u8>,
pub animation_path: std::path::PathBuf,
pub animation_bytes: Vec<u8>,
}
pub fn plan_model_artifacts(record: &shared::AssetRecord) -> Result<PlannedModelArtifacts, String> {
plan_model_artifacts_at(std::path::Path::new("."), record)
}
pub fn plan_model_artifacts_at(
project_root: &std::path::Path,
record: &shared::AssetRecord,
) -> Result<PlannedModelArtifacts, String> {
let source_path = record.path.clone();
let mut planned_record = record.clone();
planned_record.path = project_root
.join(&source_path)
.to_string_lossy()
.into_owned();
let (static_manifest, static_path) =
static_mesh::plan_static_mesh_artifact(&mut planned_record)
.map_err(|error| format!("static mesh processor failed: {error}"))?;
let (mut animation_manifest, animation_path) =
animation::plan_animation_artifact(&mut planned_record)
.map_err(|error| format!("animation processor failed: {error}"))?;
let mut static_manifest = static_manifest;
static_manifest.source.path.clone_from(&source_path);
animation_manifest.source.path.clone_from(&source_path);
for dependency in &mut static_manifest.source.dependencies {
*dependency = project_catalog_path(project_root, dependency);
}
for dependency in &mut animation_manifest.source.dependencies {
*dependency = project_catalog_path(project_root, dependency);
}
planned_record.path = source_path;
planned_record.dependencies = static_manifest.source.dependencies.clone();
planned_record
.dependencies
.extend(animation_manifest.source.dependencies.iter().cloned());
planned_record.dependencies.sort();
planned_record.dependencies.dedup();
let pretty = ron::ser::PrettyConfig::default();
let static_bytes = ron::ser::to_string_pretty(&static_manifest, pretty.clone())
.map(|source| format!("{source}\n").into_bytes())
.map_err(|error| format!("could not serialize static mesh artifact: {error}"))?;
let animation_bytes = ron::ser::to_string_pretty(&animation_manifest, pretty)
.map(|source| format!("{source}\n").into_bytes())
.map_err(|error| format!("could not serialize animation artifact: {error}"))?;
Ok(PlannedModelArtifacts {
record: planned_record,
static_manifest,
static_path: project_root.join(static_path),
static_bytes,
animation_path: project_root.join(animation_path),
animation_bytes,
})
}
fn project_catalog_path(project_root: &std::path::Path, path: &str) -> String {
let path = std::path::Path::new(path);
let relative = path.strip_prefix(project_root).unwrap_or(path);
relative.to_string_lossy().replace('\\', "/")
}
pub fn publish_model_artifacts(plan: &PlannedModelArtifacts) -> Result<(), String> {
let original_static = std::fs::read(&plan.static_path).ok();
let original_animation = std::fs::read(&plan.animation_path).ok();
let result = write_if_changed(&plan.static_path, &plan.static_bytes)
.and_then(|_| write_if_changed(&plan.animation_path, &plan.animation_bytes));
if let Err(error) = result {
restore_artifact(&plan.static_path, original_static.as_deref());
restore_artifact(&plan.animation_path, original_animation.as_deref());
return Err(format!("model artifact publication rolled back: {error}"));
}
Ok(())
}
fn restore_artifact(path: &std::path::Path, bytes: Option<&[u8]>) {
if let Some(bytes) = bytes {
let _ = std::fs::write(path, bytes);
} else {
let _ = std::fs::remove_file(path);
}
}
/// Refreshes both generated contracts derived from one imported model source.
pub fn refresh_model_artifacts(
record: &mut shared::AssetRecord,
) -> Result<static_mesh::StaticMeshManifest, String> {
let plan = plan_model_artifacts(record)?;
publish_model_artifacts(&plan)?;
*record = plan.record.clone();
Ok(plan.static_manifest)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classification_is_folder_independent() {
assert_eq!(
classify_asset(Path::new("assets/Anything/hero.glb")),
AssetKind::Model
);
assert_eq!(
classify_asset(Path::new("assets/Props/Office/wall.material.ron")),
AssetKind::Material
);
}
#[test]
fn managed_and_escaping_paths_are_rejected() {
assert!(validate_asset_path(Path::new("assets/Props/Office")).is_ok());
assert!(validate_asset_path(Path::new("assets/.index/registry.ron")).is_err());
assert!(validate_asset_path(Path::new("assets/meshes/generated/a.ron")).is_err());
assert!(validate_asset_path(Path::new("../outside")).is_err());
}
#[test]
fn registry_publication_always_updates_the_runtime_catalog() {
let root = std::env::temp_dir().join(format!(
"blacksite-content-publish-{}",
shared::AssetId::new().as_string()
));
let document = AssetRegistryDocument {
records: vec![AssetRecord {
id: shared::AssetId::new(),
path: "assets/Props/a.png".into(),
label: "A".into(),
kind: AssetKind::Texture,
source_fingerprint: None,
import_settings: shared::AssetImportSettings::for_kind(AssetKind::Texture),
dependencies: Vec::new(),
}],
..Default::default()
};
publish_content_documents(&root, &document).unwrap();
let runtime: RuntimeContentCatalog =
ron::from_str(&fs::read_to_string(root.join(RUNTIME_CATALOG_PATH)).unwrap()).unwrap();
assert_eq!(runtime.records[0].path, "assets/Props/a.png");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn headless_scan_migrates_legacy_authoring_override_to_stable_slots() {
let root = std::env::temp_dir().join(format!(
"blacksite-content-policy-migration-{}",
shared::AssetId::new().as_string()
));
fs::create_dir_all(root.join("assets/meshes/generated")).unwrap();
fs::write(root.join("assets/chair.fbx"), b"chair").unwrap();
fs::write(
root.join("assets/meshes/generated/chair.ron"),
"(parts:[(id:\"draw:0\",material_id:Some(\"material:0\"))])",
)
.unwrap();
let previous = AssetRegistryDocument {
records: vec![AssetRecord {
id: shared::AssetId::new(),
path: "assets/chair.fbx".into(),
label: "Chair".into(),
kind: AssetKind::Model,
source_fingerprint: Some(AssetSourceFingerprint::from_bytes(b"chair")),
import_settings: shared::AssetImportSettings::Model(shared::ImportSettings {
material_policy: MaterialImportPolicy::AuthoringOverride,
static_mesh_manifest_path: Some("assets/meshes/generated/chair.ron".into()),
..Default::default()
}),
dependencies: Vec::new(),
}],
..Default::default()
};
let processed = scan_project(&root, &previous).unwrap();
let settings = processed.registry.records[0].model_import();
assert_eq!(
settings.material_policy,
MaterialImportPolicy::SourceMaterials
);
assert_eq!(settings.material_slots.len(), 1);
assert_eq!(settings.material_slots[0].slot_id.0, "slot:draw:0");
assert!(matches!(
settings.material_slots[0].selection,
ModelMaterialSelection::Default
));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn scan_refuses_ambiguous_external_moves_instead_of_replacing_stable_identity() {
let root = std::env::temp_dir().join(format!(
"blacksite-content-ambiguous-move-{}",
shared::AssetId::new().as_string()
));
fs::create_dir_all(root.join("assets/New")).unwrap();
fs::write(root.join("assets/New/desk.png"), b"duplicate pixels").unwrap();
let fingerprint = AssetSourceFingerprint::from_bytes(b"duplicate pixels");
let previous = AssetRegistryDocument {
records: ["assets/OldA/desk.png", "assets/OldB/desk.png"]
.into_iter()
.map(|path| AssetRecord {
id: shared::AssetId::new(),
path: path.into(),
label: "Desk".into(),
kind: AssetKind::Texture,
source_fingerprint: Some(fingerprint.clone()),
import_settings: shared::AssetImportSettings::for_kind(AssetKind::Texture),
dependencies: Vec::new(),
})
.collect(),
..Default::default()
};
let conflicts = find_ambiguous_external_moves(&root, &previous).unwrap();
assert_eq!(conflicts.len(), 1);
assert_eq!(conflicts[0].new_path, "assets/New/desk.png");
assert_eq!(
conflicts[0].candidate_paths,
["assets/OldA/desk.png", "assets/OldB/desk.png"]
);
let error = scan_project(&root, &previous).unwrap_err();
assert!(error.contains("ambiguous external move"));
assert!(error.contains("assets/OldA/desk.png"));
assert!(error.contains("assets/OldB/desk.png"));
assert!(error.contains("Content Browser"));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn scan_preserves_unique_imported_source_ids_across_external_moves() {
let root = std::env::temp_dir().join(format!(
"blacksite-content-unique-moves-{}",
shared::AssetId::new().as_string()
));
fs::create_dir_all(root.join("assets/New")).unwrap();
let fixtures = [
("model.glb", AssetKind::Model, b"model bytes".as_slice()),
(
"texture.png",
AssetKind::Texture,
b"texture bytes".as_slice(),
),
("audio.ogg", AssetKind::AudioClip, b"audio bytes".as_slice()),
];
let mut expected = Vec::new();
let mut records = Vec::new();
for (name, kind, bytes) in fixtures {
fs::write(root.join("assets/New").join(name), bytes).unwrap();
let id = shared::AssetId::new();
expected.push((format!("assets/New/{name}"), id.clone()));
records.push(AssetRecord {
id,
path: format!("assets/Old/{name}"),
label: name.into(),
kind,
source_fingerprint: Some(AssetSourceFingerprint::from_bytes(bytes)),
import_settings: shared::AssetImportSettings::for_kind(kind),
dependencies: Vec::new(),
});
}
let previous = AssetRegistryDocument {
records,
..Default::default()
};
let processed = scan_project(&root, &previous).unwrap();
assert_eq!(processed.report.moved, 3);
for (path, id) in expected {
assert_eq!(
processed
.registry
.records
.iter()
.find(|record| record.path == path)
.map(|record| &record.id),
Some(&id)
);
}
fs::remove_dir_all(root).unwrap();
}
}
+302
View File
@@ -0,0 +1,302 @@
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum PbrTextureRole {
BaseColor,
Normal,
Roughness,
Metallic,
Occlusion,
PackedOrm,
Height,
Unknown,
}
impl PbrTextureRole {
pub const ALL: [Self; 8] = [
Self::BaseColor,
Self::Normal,
Self::Roughness,
Self::Metallic,
Self::Occlusion,
Self::PackedOrm,
Self::Height,
Self::Unknown,
];
pub const fn label(self) -> &'static str {
match self {
Self::BaseColor => "Base color",
Self::Normal => "Normal",
Self::Roughness => "Roughness",
Self::Metallic => "Metallic",
Self::Occlusion => "Occlusion",
Self::PackedOrm => "Packed ORM/ARM",
Self::Height => "Height",
Self::Unknown => "Unresolved",
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum PbrMatchConfidence {
High,
Medium,
Low,
Unresolved,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DetectedPbrTexture {
pub path: PathBuf,
pub group_key: String,
pub role: PbrTextureRole,
pub confidence: PbrMatchConfidence,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DetectedPbrGroup {
pub key: String,
pub textures: Vec<DetectedPbrTexture>,
}
pub fn detect_pbr_texture_groups(
paths: impl IntoIterator<Item = PathBuf>,
) -> Vec<DetectedPbrGroup> {
let mut groups: BTreeMap<String, Vec<DetectedPbrTexture>> = BTreeMap::new();
for path in paths {
if !is_texture_path(&path) {
continue;
}
let (group_key, role, confidence) = classify_texture_name(&path);
groups
.entry(group_key.clone())
.or_default()
.push(DetectedPbrTexture {
path,
group_key,
role,
confidence,
});
}
groups
.into_iter()
.map(|(key, mut textures)| {
textures.sort_by(|left, right| left.path.cmp(&right.path));
DetectedPbrGroup { key, textures }
})
.collect()
}
fn classify_texture_name(path: &Path) -> (String, PbrTextureRole, PbrMatchConfidence) {
let stem = path
.file_stem()
.and_then(|stem| stem.to_str())
.unwrap_or("texture")
.to_ascii_lowercase();
let mut tokens: Vec<&str> = stem
.split(|character: char| !character.is_ascii_alphanumeric())
.filter(|token| !token.is_empty())
.collect();
while tokens
.last()
.is_some_and(|token| is_resolution_token(token))
{
tokens.pop();
}
let joined = tokens.join("_");
let aliases: &[(&[&str], PbrTextureRole, PbrMatchConfidence)] = &[
(
&["occlusion", "roughness", "metallic"],
PbrTextureRole::PackedOrm,
PbrMatchConfidence::High,
),
(
&["base", "color"],
PbrTextureRole::BaseColor,
PbrMatchConfidence::High,
),
(
&["ambient", "occlusion"],
PbrTextureRole::Occlusion,
PbrMatchConfidence::High,
),
(
&["metallic", "roughness"],
PbrTextureRole::PackedOrm,
PbrMatchConfidence::Medium,
),
(
&["basecolor"],
PbrTextureRole::BaseColor,
PbrMatchConfidence::High,
),
(
&["albedo"],
PbrTextureRole::BaseColor,
PbrMatchConfidence::High,
),
(
&["diffuse"],
PbrTextureRole::BaseColor,
PbrMatchConfidence::High,
),
(
&["diff"],
PbrTextureRole::BaseColor,
PbrMatchConfidence::Medium,
),
(
&["normal"],
PbrTextureRole::Normal,
PbrMatchConfidence::High,
),
(
&["nor", "gl"],
PbrTextureRole::Normal,
PbrMatchConfidence::High,
),
(
&["nor", "dx"],
PbrTextureRole::Normal,
PbrMatchConfidence::High,
),
(&["nrm"], PbrTextureRole::Normal, PbrMatchConfidence::Medium),
(
&["roughness"],
PbrTextureRole::Roughness,
PbrMatchConfidence::High,
),
(
&["rough"],
PbrTextureRole::Roughness,
PbrMatchConfidence::Medium,
),
(
&["metallic"],
PbrTextureRole::Metallic,
PbrMatchConfidence::High,
),
(
&["metalness"],
PbrTextureRole::Metallic,
PbrMatchConfidence::High,
),
(
&["metal"],
PbrTextureRole::Metallic,
PbrMatchConfidence::Medium,
),
(
&["occlusion"],
PbrTextureRole::Occlusion,
PbrMatchConfidence::High,
),
(&["ao"], PbrTextureRole::Occlusion, PbrMatchConfidence::High),
(
&["orm"],
PbrTextureRole::PackedOrm,
PbrMatchConfidence::High,
),
(
&["arm"],
PbrTextureRole::PackedOrm,
PbrMatchConfidence::High,
),
(
&["height"],
PbrTextureRole::Height,
PbrMatchConfidence::High,
),
(
&["displacement"],
PbrTextureRole::Height,
PbrMatchConfidence::High,
),
(
&["disp"],
PbrTextureRole::Height,
PbrMatchConfidence::Medium,
),
(&["n"], PbrTextureRole::Normal, PbrMatchConfidence::Low),
(&["r"], PbrTextureRole::Roughness, PbrMatchConfidence::Low),
(&["m"], PbrTextureRole::Metallic, PbrMatchConfidence::Low),
];
for (suffix, role, confidence) in aliases {
if tokens.ends_with(suffix) {
let base_len = tokens.len().saturating_sub(suffix.len());
let group = tokens[..base_len].join("_");
return (
if group.is_empty() {
joined.clone()
} else {
group
},
*role,
*confidence,
);
}
}
(
joined,
PbrTextureRole::Unknown,
PbrMatchConfidence::Unresolved,
)
}
fn is_resolution_token(token: &str) -> bool {
token
.strip_suffix('k')
.is_some_and(|number| matches!(number, "1" | "2" | "4" | "8" | "16"))
}
fn is_texture_path(path: &Path) -> bool {
matches!(
path.extension()
.and_then(|extension| extension.to_str())
.unwrap_or_default()
.to_ascii_lowercase()
.as_str(),
"png" | "jpg" | "jpeg" | "webp" | "ktx2" | "dds" | "tga" | "exr" | "hdr"
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn poly_haven_suffixes_form_one_high_confidence_group() {
let groups = detect_pbr_texture_groups([
"assets/metal_office_desk_diff_2k.jpg".into(),
"assets/metal_office_desk_nor_gl_2k.jpg".into(),
"assets/metal_office_desk_arm_2k.jpg".into(),
]);
assert_eq!(groups.len(), 1);
assert_eq!(groups[0].key, "metal_office_desk");
assert!(groups[0]
.textures
.iter()
.any(|texture| texture.role == PbrTextureRole::BaseColor));
assert!(groups[0]
.textures
.iter()
.any(|texture| texture.role == PbrTextureRole::Normal));
assert!(groups[0]
.textures
.iter()
.any(|texture| texture.role == PbrTextureRole::PackedOrm));
}
#[test]
fn unknown_images_remain_visible_for_manual_resolution() {
let groups = detect_pbr_texture_groups(["assets/wood_preview.png".into()]);
assert_eq!(groups[0].textures[0].role, PbrTextureRole::Unknown);
assert_eq!(
groups[0].textures[0].confidence,
PbrMatchConfidence::Unresolved
);
}
}
+963
View File
@@ -0,0 +1,963 @@
//! Normalized static mesh artifacts generated from model source files.
use std::fs;
use std::path::Path;
use bevy::gltf::GltfAssetLabel;
use bevy::prelude::*;
use bevy_ufbx::label::FbxAssetLabel;
use bevy_ufbx::mesh::group_faces_by_material;
use bevy_ufbx::texture::external_texture_paths;
use bevy_ufbx::utils::convert_matrix;
use serde::{Deserialize, Serialize};
use shared::{
AssetRecord, ImportSettings, MaterialImportPolicy, ModelHierarchyMode, ModelMaterialSelection,
ModelPlacementMode,
};
use shared::{
AssetSourceFingerprint, ComponentInstanceId, EditorAssetRef, MaterialSlot, MaterialSlotSet,
ModelMaterialSlotSelection, OrphanedModelMaterialSelection, StaticMeshRenderer,
StaticMeshRendererEntry,
};
use crate::fingerprint::{fingerprint_file, write_pretty_ron_if_changed};
pub const STATIC_MESH_MANIFEST_SCHEMA: u32 = 4;
pub const STATIC_MESH_ARTIFACT_DIR: &str = "assets/meshes/generated";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshManifest {
pub schema_version: u32,
pub asset_id: String,
pub label: String,
pub source: StaticMeshSource,
pub import: StaticMeshImportSnapshot,
pub metadata: StaticMeshMetadata,
pub parts: Vec<StaticMeshPart>,
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshSource {
pub path: String,
pub format: String,
pub fingerprint: StaticMeshSourceFingerprint,
pub dependencies: Vec<String>,
}
pub type StaticMeshSourceFingerprint = AssetSourceFingerprint;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshImportSnapshot {
pub scale: f32,
pub generate_collider: bool,
pub lod0_only: bool,
pub placement_mode: ModelPlacementMode,
pub hierarchy_mode: ModelHierarchyMode,
#[serde(default, skip_serializing_if = "material_policy_is_default")]
pub material_policy: MaterialImportPolicy,
#[serde(default)]
pub material_slots: Vec<shared::ModelMaterialSlotSelection>,
#[serde(default)]
pub orphaned_material_slots: Vec<shared::OrphanedModelMaterialSelection>,
}
fn material_policy_is_default(policy: &MaterialImportPolicy) -> bool {
*policy == MaterialImportPolicy::SourceMaterials
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshMetadata {
pub mesh_count: usize,
pub material_count: usize,
pub node_count: usize,
pub animation_count: usize,
pub skin_count: usize,
pub light_count: usize,
pub camera_count: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshPart {
#[serde(default)]
pub id: String,
pub name: String,
pub mesh_label: String,
#[serde(default)]
pub material_id: Option<String>,
pub material_slot_name: String,
pub material_label: Option<String>,
pub local_transform: Transform,
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 {
format!("{STATIC_MESH_ARTIFACT_DIR}/{asset_id}.static_mesh.ron")
}
pub fn part_id_from_label(label: &str) -> String {
format!("mesh:{}", stable_sub_asset_slug(label))
}
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() {
if ch.is_ascii_alphanumeric() {
slug.push(ch.to_ascii_lowercase());
} else if !slug.ends_with('_') {
slug.push('_');
}
}
slug.trim_matches('_').to_string()
}
pub fn refresh_static_mesh_artifact(
record: &mut AssetRecord,
) -> Result<StaticMeshManifest, String> {
let (manifest, path) = plan_static_mesh_artifact(record)?;
if write_pretty_ron_if_changed(&path, &manifest)
.map_err(|error| format!("could not publish static mesh manifest {path}: {error}"))?
{
info!(
"Static mesh manifest refreshed: source={} artifact={} parts={}",
record.path,
path,
manifest.parts.len()
);
}
Ok(manifest)
}
pub fn plan_static_mesh_artifact(
record: &mut AssetRecord,
) -> Result<(StaticMeshManifest, String), String> {
let mut manifest = build_static_mesh_manifest(record)?;
reconcile_model_material_slots(&manifest, record.model_import_mut());
manifest.import.material_policy = MaterialImportPolicy::SourceMaterials;
manifest.import.material_slots = record.model_import().material_slots.clone();
manifest.import.orphaned_material_slots = record.model_import().orphaned_material_slots.clone();
let path = static_mesh_manifest_path(&record.id.as_string());
record.model_import_mut().static_mesh_manifest_path = Some(path.clone());
manifest.source.dependencies.sort();
manifest.source.dependencies.dedup();
record.dependencies = manifest.source.dependencies.clone();
Ok((manifest, path))
}
pub fn load_static_mesh_manifest(path: &str) -> Result<StaticMeshManifest, String> {
let text = fs::read_to_string(path).map_err(|err| format!("could not read {path}: {err}"))?;
ron::from_str(&text).map_err(|err| format!("could not parse {path}: {err}"))
}
pub fn renderer_from_manifest(
manifest: &StaticMeshManifest,
_settings: &ImportSettings,
) -> 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)),
local_transform: part.local_transform,
visible: true,
cast_shadows: true,
receive_shadows: true,
})
.collect();
let materials = MaterialSlotSet {
slots: manifest
.parts
.iter()
.filter(|part| !part.skinned && manifest.metadata.animation_count == 0)
.map(|part| MaterialSlot {
id: ComponentInstanceId::new(material_slot_id(part)),
name: part.material_slot_name.clone(),
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,
) -> MaterialSlotSet {
MaterialSlotSet {
slots: manifest
.parts
.iter()
.map(|part| MaterialSlot {
id: ComponentInstanceId::new(material_slot_id(part)),
name: part.material_slot_name.clone(),
material: None,
})
.collect(),
orphaned_assignments: Vec::new(),
}
}
pub fn material_selection<'a>(
settings: &'a ImportSettings,
slot_id: &str,
) -> &'a ModelMaterialSelection {
settings
.material_slots
.iter()
.find(|entry| entry.slot_id.0 == slot_id)
.map(|entry| &entry.selection)
.unwrap_or(&ModelMaterialSelection::Source)
}
fn reconcile_model_material_slots(manifest: &StaticMeshManifest, settings: &mut ImportSettings) {
let names = manifest
.parts
.iter()
.map(|part| (material_slot_id(part), part.material_slot_name.clone()))
.collect::<std::collections::BTreeMap<_, _>>();
if settings.material_policy == MaterialImportPolicy::AuthoringOverride {
for slot_id in names.keys() {
if !settings
.material_slots
.iter()
.any(|selection| selection.slot_id.0 == *slot_id)
{
settings.material_slots.push(ModelMaterialSlotSelection {
slot_id: ComponentInstanceId::new(slot_id.clone()),
selection: ModelMaterialSelection::Default,
});
}
}
}
settings.material_policy = MaterialImportPolicy::SourceMaterials;
let mut retained = Vec::with_capacity(settings.material_slots.len());
for selection in settings.material_slots.drain(..) {
if names.contains_key(&selection.slot_id.0) {
retained.push(selection);
} else if let ModelMaterialSelection::Project(material) = selection.selection {
settings
.orphaned_material_slots
.push(OrphanedModelMaterialSelection {
slot_id: selection.slot_id,
last_known_name: "Removed imported material slot".into(),
material,
});
}
}
retained.sort_by(|left, right| left.slot_id.0.cmp(&right.slot_id.0));
settings.material_slots = retained;
settings
.orphaned_material_slots
.retain(|orphan| !names.contains_key(&orphan.slot_id.0));
settings
.orphaned_material_slots
.sort_by(|left, right| left.slot_id.0.cmp(&right.slot_id.0));
}
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)
} else {
part.id.clone()
}
}
fn build_static_mesh_manifest(record: &AssetRecord) -> Result<StaticMeshManifest, String> {
let format = source_format(&record.path)?;
let fingerprint = fingerprint_file(&record.path)?;
let import = StaticMeshImportSnapshot {
scale: record.model_import().scale,
generate_collider: record.model_import().generate_collider,
lod0_only: record.model_import().lod0_only,
placement_mode: record.model_import().placement_mode,
hierarchy_mode: record.model_import().hierarchy_mode,
material_policy: MaterialImportPolicy::SourceMaterials,
material_slots: record.model_import().material_slots.clone(),
orphaned_material_slots: record.model_import().orphaned_material_slots.clone(),
};
let mut manifest = match format.as_str() {
"gltf" | "glb" => build_gltf_manifest(record, format, fingerprint, import)?,
"fbx" => build_fbx_manifest(record, format, fingerprint, import)?,
_ => return Err(format!("unsupported static mesh source format `{format}`")),
};
if manifest.parts.is_empty() {
manifest
.warnings
.push("No renderable static mesh parts were found.".into());
}
Ok(manifest)
}
fn build_gltf_manifest(
record: &AssetRecord,
format: String,
fingerprint: StaticMeshSourceFingerprint,
import: StaticMeshImportSnapshot,
) -> Result<StaticMeshManifest, String> {
let gltf = gltf::Gltf::open(&record.path)
.map_err(|err| format!("could not parse glTF {}: {err}", record.path))?;
let mut parts = Vec::new();
let mut dependencies = Vec::new();
let mut warnings = Vec::new();
for buffer in gltf.document.buffers() {
if let gltf::buffer::Source::Uri(uri) = buffer.source() {
dependencies.push(resolve_dependency(&record.path, uri));
}
}
for image in gltf.document.images() {
if let gltf::image::Source::Uri { uri, .. } = image.source() {
dependencies.push(resolve_dependency(&record.path, uri));
}
}
if let Some(scene) = gltf
.document
.default_scene()
.or_else(|| gltf.document.scenes().next())
{
for node in scene.nodes() {
collect_gltf_node_parts(node, Mat4::IDENTITY, "", &mut parts);
}
} else {
for mesh in gltf.document.meshes() {
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; animated placement uses SkinnedMeshRenderer."
.into(),
);
}
if gltf.document.skins().count() > 0 {
warnings.push(
"Skinned primitives are excluded from StaticMeshRenderer and use SkinnedMeshRenderer."
.into(),
);
}
parts.sort_by(|a, b| a.mesh_label.cmp(&b.mesh_label).then(a.name.cmp(&b.name)));
Ok(StaticMeshManifest {
schema_version: STATIC_MESH_MANIFEST_SCHEMA,
asset_id: record.id.as_string(),
label: record.label.clone(),
source: StaticMeshSource {
path: record.path.clone(),
format,
fingerprint,
dependencies,
},
import,
metadata: StaticMeshMetadata {
mesh_count: gltf.document.meshes().count(),
material_count: gltf.document.materials().count(),
node_count: gltf.document.nodes().count(),
animation_count: gltf.document.animations().count(),
skin_count: gltf.document.skins().count(),
light_count: 0,
camera_count: gltf.document.cameras().count(),
},
parts,
warnings,
})
}
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, &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();
let mesh_name = mesh.name().map(str::to_string);
for primitive in mesh.primitives() {
let primitive_index = primitive.index();
let mesh_label = GltfAssetLabel::Primitive {
mesh: mesh_index,
primitive: primitive_index,
}
.to_string();
let material = primitive.material();
let material_label = material
.index()
.map(|index| {
GltfAssetLabel::Material {
index,
is_scale_inverted: false,
}
.to_string()
})
.or_else(|| Some(GltfAssetLabel::DefaultMaterial.to_string()));
let material_name = material
.name()
.map(str::to_string)
.unwrap_or_else(|| "Default Material".into());
let name = node_name
.clone()
.or_else(|| mesh_name.clone())
.unwrap_or_else(|| format!("Mesh {mesh_index}"));
let source_node = node_path
.clone()
.or_else(|| node_index.map(|index| format!("Node{index}")));
parts.push(StaticMeshPart {
id: gltf_draw_id(node_index, mesh_index, primitive_index),
name: format!("{name} / Primitive {primitive_index}"),
material_id: material_label
.as_ref()
.map(|label| material_id_from_label(label)),
mesh_label,
material_slot_name: material_name.clone(),
material_label,
local_transform: Transform::from_matrix(transform),
source_node,
source_mesh: Some(format!("Mesh{mesh_index}")),
source_material: Some(material_name),
skinned,
});
}
}
fn build_fbx_manifest(
record: &AssetRecord,
format: String,
fingerprint: StaticMeshSourceFingerprint,
import: StaticMeshImportSnapshot,
) -> Result<StaticMeshManifest, String> {
let bytes =
fs::read(&record.path).map_err(|err| format!("could not read {}: {err}", record.path))?;
let scene = ufbx::load_memory(
&bytes,
ufbx::LoadOpts {
target_unit_meters: 1.0,
target_axes: ufbx::CoordinateAxes::right_handed_y_up(),
filename: ufbx::StringOpt::Ref(&record.path),
..Default::default()
},
)
.map_err(|err| format!("could not parse FBX {}: {err:?}", record.path))?;
let mut parts = Vec::new();
let mut warnings = Vec::new();
for (node_index, node) in scene.nodes.as_ref().iter().enumerate() {
let Some(mesh_ref) = node.mesh.as_ref() else {
continue;
};
let mesh = mesh_ref.as_ref();
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();
groups.sort_by_key(|(material_index, _)| *material_index);
for (material_index, indices) in groups {
if indices.is_empty() {
continue;
}
let material = mesh.materials.get(material_index).map(|mat| mat.as_ref());
let material_label = material
.and_then(|mat| fbx_material_label(&scene, mat.element.element_id))
.or_else(|| Some(FbxAssetLabel::DefaultMaterial.to_string()));
let material_name = material
.map(|mat| mat.element.name.to_string())
.filter(|name| !name.is_empty())
.unwrap_or_else(|| "Default Material".into());
let node_name = if node.element.name.is_empty() {
format!("Node {node_index}")
} else {
node.element.name.to_string()
};
let mesh_label = FbxAssetLabel::Mesh(node_index * 1000 + material_index).to_string();
parts.push(StaticMeshPart {
id: fbx_draw_id(node_index, material_index),
name: format!("{node_name} / Material {material_index}"),
material_id: material_label
.as_ref()
.map(|label| material_id_from_label(label)),
mesh_label,
material_slot_name: material_name.clone(),
material_label,
local_transform: Transform::from_matrix(convert_matrix(&node.geometry_to_world)),
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; animated placement uses SkinnedMeshRenderer."
.into(),
);
}
if !scene.skin_deformers.as_ref().is_empty() {
warnings.push(
"Skinned primitives are excluded from StaticMeshRenderer and use SkinnedMeshRenderer."
.into(),
);
}
parts.sort_by(|a, b| a.mesh_label.cmp(&b.mesh_label).then(a.name.cmp(&b.name)));
Ok(StaticMeshManifest {
schema_version: STATIC_MESH_MANIFEST_SCHEMA,
asset_id: record.id.as_string(),
label: record.label.clone(),
source: StaticMeshSource {
path: record.path.clone(),
format,
fingerprint,
dependencies: fbx_dependencies(&record.path, &scene)?,
},
import,
metadata: StaticMeshMetadata {
mesh_count: scene.meshes.as_ref().len(),
material_count: scene.materials.as_ref().len(),
node_count: scene.nodes.as_ref().len(),
animation_count: scene.anim_stacks.as_ref().len(),
skin_count: scene.skin_deformers.as_ref().len(),
light_count: scene.lights.as_ref().len(),
camera_count: scene.cameras.as_ref().len(),
},
parts,
warnings,
})
}
fn fbx_material_label(scene: &ufbx::Scene, element_id: u32) -> Option<String> {
if element_id == 0 {
return None;
}
scene
.materials
.as_ref()
.iter()
.position(|material| material.element.element_id == element_id)
.map(|index| FbxAssetLabel::Material(index).to_string())
}
fn fbx_dependencies(source_path: &str, scene: &ufbx::Scene) -> Result<Vec<String>, String> {
let path = Path::new(source_path);
let parent = path.parent().unwrap_or_else(|| Path::new(""));
external_texture_paths(scene)
.map_err(|errors| {
format!(
"unsafe FBX texture reference(s) in {source_path}: {}",
errors
.into_iter()
.map(|error| error.to_string())
.collect::<Vec<_>>()
.join("; ")
)
})
.map(|paths| {
paths
.into_iter()
.map(|relative| parent.join(relative).to_string_lossy().replace('\\', "/"))
.collect()
})
}
fn source_format(path: &str) -> Result<String, String> {
Path::new(path)
.extension()
.and_then(|ext| ext.to_str())
.map(|ext| ext.to_ascii_lowercase())
.ok_or_else(|| format!("asset path `{path}` has no extension"))
}
fn resolve_dependency(source_path: &str, uri: &str) -> String {
if uri.starts_with("data:") || uri.contains("://") {
return uri.to_string();
}
Path::new(source_path)
.parent()
.unwrap_or_else(|| Path::new(""))
.join(uri)
.to_string_lossy()
.replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
use shared::{AssetId, MaterialRef};
fn test_manifest() -> StaticMeshManifest {
StaticMeshManifest {
schema_version: STATIC_MESH_MANIFEST_SCHEMA,
asset_id: "asset-1".into(),
label: "Crate".into(),
source: StaticMeshSource {
path: "assets/models/crate.glb".into(),
format: "glb".into(),
fingerprint: StaticMeshSourceFingerprint {
byte_len: 42,
content_hash: "a".repeat(64),
},
dependencies: Vec::new(),
},
import: StaticMeshImportSnapshot {
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: ModelPlacementMode::StaticAsset,
hierarchy_mode: ModelHierarchyMode::SingleActor,
material_policy: MaterialImportPolicy::SourceMaterials,
material_slots: Vec::new(),
orphaned_material_slots: Vec::new(),
},
metadata: StaticMeshMetadata {
mesh_count: 1,
material_count: 1,
node_count: 1,
animation_count: 0,
skin_count: 0,
light_count: 0,
camera_count: 0,
},
parts: vec![StaticMeshPart {
id: "mesh:mesh0_primitive0".into(),
name: "Crate / Primitive 0".into(),
mesh_label: "Mesh0/Primitive0".into(),
material_id: Some("material:material0".into()),
material_slot_name: "Wood".into(),
material_label: Some("Material0".into()),
local_transform: Transform::from_xyz(1.0, 2.0, 3.0),
source_node: Some("Node0".into()),
source_mesh: Some("Mesh0".into()),
source_material: Some("Wood".into()),
skinned: false,
}],
warnings: Vec::new(),
}
}
#[test]
fn static_mesh_manifest_path_uses_asset_id() {
assert_eq!(
static_mesh_manifest_path("abc"),
"assets/meshes/generated/abc.static_mesh.ron"
);
}
#[test]
fn renderer_from_manifest_preserves_labels_and_collider_policy() {
let manifest = test_manifest();
let settings = ImportSettings {
generate_collider: true,
..Default::default()
};
let renderer = renderer_from_manifest(&manifest, &settings);
assert_eq!(renderer.slots.len(), 1);
let entry = &renderer.slots[0];
assert_eq!(entry.mesh.asset_id, manifest.asset_id);
assert_eq!(entry.mesh.sub_asset_id, "mesh:mesh0_primitive0");
assert!(renderer.materials.slots[0].material.is_none());
}
#[test]
fn model_slot_selection_remains_asset_owned() {
let manifest = test_manifest();
let project = MaterialRef::new(
EditorAssetRef::new("project-material", "", "Paint")
.with_source_path("assets/Props/paint.material.ron"),
);
let mut settings = ImportSettings::default();
settings
.material_slots
.push(shared::ModelMaterialSlotSelection {
slot_id: ComponentInstanceId::new("slot:mesh:mesh0_primitive0"),
selection: ModelMaterialSelection::Project(project.clone()),
});
let renderer = renderer_from_manifest(&manifest, &settings);
assert!(renderer.materials.slots[0].material.is_none());
assert_eq!(
material_selection(&settings, "slot:mesh:mesh0_primitive0"),
&ModelMaterialSelection::Project(project)
);
settings.material_slots[0].selection = ModelMaterialSelection::Default;
let renderer = renderer_from_manifest(&manifest, &settings);
assert!(renderer.materials.slots[0].material.is_none());
assert_eq!(
material_selection(&settings, "slot:mesh:mesh0_primitive0"),
&ModelMaterialSelection::Default
);
}
#[test]
fn removed_project_selection_becomes_an_orphan() {
let manifest = test_manifest();
let material = MaterialRef::new(EditorAssetRef::new("paint", "", "Paint"));
let mut settings = ImportSettings::default();
settings
.material_slots
.push(shared::ModelMaterialSlotSelection {
slot_id: ComponentInstanceId::new("slot:removed"),
selection: ModelMaterialSelection::Project(material.clone()),
});
reconcile_model_material_slots(&manifest, &mut settings);
assert!(settings.material_slots.is_empty());
assert_eq!(settings.orphaned_material_slots.len(), 1);
assert_eq!(settings.orphaned_material_slots[0].material, material);
}
#[test]
fn schema_v3_manifest_without_hash_migrates_to_content_fingerprint() {
let root = std::env::temp_dir().join(format!(
"blacksite-static-mesh-legacy-{}",
uuid::Uuid::new_v4()
));
fs::create_dir_all(&root).unwrap();
let path = root.join("legacy.static_mesh.ron");
let expected = test_manifest();
let canonical =
ron::ser::to_string_pretty(&expected, ron::ser::PrettyConfig::default()).unwrap();
let legacy = canonical
.replacen("schema_version: 4", "schema_version: 3", 1)
.lines()
.filter(|line| !line.contains("content_hash:"))
.collect::<Vec<_>>()
.join("\n");
fs::write(&path, legacy).unwrap();
assert!(write_pretty_ron_if_changed(&path, &expected).unwrap());
assert_eq!(
load_static_mesh_manifest(&path.to_string_lossy()).unwrap(),
expected
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn equivalent_static_manifest_preserves_existing_formatting_and_newline() {
let root = std::env::temp_dir().join(format!(
"blacksite-static-mesh-semantic-{}",
uuid::Uuid::new_v4()
));
fs::create_dir_all(&root).unwrap();
let path = root.join("stable.static_mesh.ron");
let manifest = test_manifest();
let exact = format!(
"{}\n\n",
ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default()).unwrap()
);
fs::write(&path, &exact).unwrap();
assert!(!write_pretty_ron_if_changed(&path, &manifest).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), exact);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn renderer_from_manifest_can_select_default_per_slot() {
let manifest = test_manifest();
let settings = ImportSettings {
material_slots: vec![ModelMaterialSlotSelection {
slot_id: ComponentInstanceId::new(format!(
"slot:{}",
part_effective_id(&manifest.parts[0])
)),
selection: ModelMaterialSelection::Default,
}],
..Default::default()
};
let renderer = renderer_from_manifest(&manifest, &settings);
assert!(renderer.materials.slots[0].material.is_none());
assert_eq!(
material_selection(&settings, &renderer.materials.slots[0].id.0),
&ModelMaterialSelection::Default
);
}
#[test]
fn legacy_whole_model_policy_migrates_to_explicit_default_slots() {
let manifest = test_manifest();
let mut settings = ImportSettings {
material_policy: MaterialImportPolicy::AuthoringOverride,
..Default::default()
};
reconcile_model_material_slots(&manifest, &mut settings);
assert_eq!(
settings.material_policy,
MaterialImportPolicy::SourceMaterials
);
assert_eq!(settings.material_slots.len(), 1);
assert!(matches!(
settings.material_slots[0].selection,
ModelMaterialSelection::Default
));
}
#[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: shared::AssetKind::Model,
source_fingerprint: None,
import_settings: shared::AssetImportSettings::Model(ImportSettings::default()),
dependencies: Vec::new(),
};
let manifest = build_static_mesh_manifest(&record).unwrap();
let renderer = renderer_from_manifest(&manifest, record.model_import());
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());
}
#[test]
fn committed_fbx_records_sibling_texture_dependencies() {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../assets/models/painted_wooden_chair_02_2k.fbx")
.to_string_lossy()
.into_owned();
let record = AssetRecord {
id: AssetId::new(),
path,
label: "Painted Chair".into(),
kind: shared::AssetKind::Model,
source_fingerprint: None,
import_settings: shared::AssetImportSettings::Model(ImportSettings::default()),
dependencies: Vec::new(),
};
let manifest = build_static_mesh_manifest(&record).unwrap();
assert_eq!(manifest.source.dependencies.len(), 3);
assert!(manifest
.source
.dependencies
.iter()
.all(|path| path.contains("assets/models/textures/painted_wooden_chair_02_")));
}
}
+978
View File
@@ -0,0 +1,978 @@
//! Deterministic, GPU-free texture processing for editor, watcher, CI, and packaging.
use image::{imageops::FilterType, Rgba, RgbaImage};
use shared::{
resolves_srgb, AssetKind, AssetRecord, AssetRegistryDocument, MaterialAsset, MaterialInputSet,
MaterialInstanceAsset, MaterialRuntimeData, MaterialTextureBinding, NormalMapConvention,
TextureAssetSemantic, TextureChannel, TextureColorSpace, TextureCompression,
TextureImportSettings, TextureMipmapMode, TextureRuntimeData,
};
use std::path::{Path, PathBuf};
pub const TEXTURE_PROCESSOR_VERSION: u32 = 1;
#[derive(Debug, Clone)]
pub struct TextureArtifactPlan {
pub output_path: PathBuf,
pub output_bytes: Vec<u8>,
pub runtime: TextureRuntimeData,
pub reused: bool,
}
#[derive(Debug, Clone)]
pub struct MaterialArtifactPlan {
pub output_path: PathBuf,
pub output_bytes: Vec<u8>,
pub runtime: MaterialRuntimeData,
pub reused: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MaterialPackingSignature(pub String);
pub fn plan_texture_artifact(
project_root: &Path,
record: &AssetRecord,
) -> Result<TextureArtifactPlan, String> {
if record.kind != AssetKind::Texture {
return Err(format!("{} is not a Texture asset", record.path));
}
let source_path = project_root.join(&record.path);
let source_bytes = std::fs::read(&source_path)
.map_err(|error| format!("could not read texture {}: {error}", source_path.display()))?;
let mut settings = record
.texture_import()
.cloned()
.ok_or_else(|| format!("{} has no Texture import settings", record.path))?;
normalize_texture_settings(&record.path, &mut settings);
let settings_bytes = ron::ser::to_string(&settings)
.map_err(|error| format!("could not hash Texture import settings: {error}"))?;
let mut hasher = blake3::Hasher::new();
hasher.update(&source_bytes);
hasher.update(settings_bytes.as_bytes());
hasher.update(&TEXTURE_PROCESSOR_VERSION.to_le_bytes());
let processing_key = hasher.finalize().to_hex()[..24].to_string();
let is_srgb = resolves_srgb(&settings);
let extension = match settings.compression {
TextureCompression::Uastc | TextureCompression::Auto => "basis",
TextureCompression::Uncompressed => "ktx2",
};
let relative_output = PathBuf::from(format!(
"assets/.import-cache/runtime/textures/{}/{processing_key}/texture.{extension}",
record.id.as_string()
));
let output_path = project_root.join(&relative_output);
let runtime = TextureRuntimeData {
source_path: record.path.clone(),
processed_path: Some(normalize_path(&relative_output)),
processing_key: Some(processing_key),
settings,
is_srgb,
};
if output_path.is_file() {
return Ok(TextureArtifactPlan {
output_path,
output_bytes: Vec::new(),
runtime,
reused: true,
});
}
let mut image = image::load_from_memory(&source_bytes)
.map_err(|error| format!("could not decode texture {}: {error}", record.path))?
.to_rgba8();
image = resize_to_limit(image, runtime.settings.max_dimension);
if runtime.settings.semantic == TextureAssetSemantic::Normal
&& runtime.settings.normal_map_convention == NormalMapConvention::DirectX
{
flip_normal_green(&mut image);
}
let output_bytes = match runtime.settings.compression {
TextureCompression::Uastc | TextureCompression::Auto => {
let mip_count =
requested_mip_count(image.width(), image.height(), runtime.settings.mipmaps);
encode_uastc(&image, is_srgb, mip_count > 1)?
}
TextureCompression::Uncompressed => {
let mips = generate_mips(&image, runtime.settings.mipmaps);
encode_uncompressed_ktx2(&mips, is_srgb)?
}
};
Ok(TextureArtifactPlan {
output_path,
output_bytes,
runtime,
reused: false,
})
}
pub fn publish_texture_artifact(plan: &TextureArtifactPlan) -> Result<bool, String> {
if plan.reused {
return Ok(false);
}
crate::write_if_changed(&plan.output_path, &plan.output_bytes)
}
pub fn plan_material_artifact(
project_root: &Path,
record: &AssetRecord,
registry: &AssetRegistryDocument,
) -> Result<Option<MaterialArtifactPlan>, String> {
if !matches!(
record.kind,
AssetKind::Material | AssetKind::MaterialInstance
) {
return Ok(None);
}
let inputs = load_resolved_material_inputs(project_root, record)?;
let scalar_bindings = [
assigned_texture(&inputs, "occlusion"),
assigned_texture(&inputs, "roughness"),
assigned_texture(&inputs, "metallic"),
];
if scalar_bindings.iter().all(|binding| binding.is_none()) {
return Ok(None);
}
let signature = material_packing_signature_from_inputs(project_root, registry, &inputs)?;
let processing_key = signature.0;
let relative_output = PathBuf::from(format!(
"assets/.import-cache/runtime/materials/{}/{}-arm.basis",
record.id.as_string(),
processing_key
));
let output_path = project_root.join(&relative_output);
if output_path.is_file() {
return Ok(Some(MaterialArtifactPlan {
output_path,
output_bytes: Vec::new(),
runtime: MaterialRuntimeData {
packed_arm_path: Some(normalize_path(&relative_output)),
processing_key: Some(processing_key),
},
reused: true,
}));
}
let loaded = scalar_bindings
.iter()
.map(|binding| {
(*binding)
.map(|binding| load_binding_image(project_root, registry, binding))
.transpose()
})
.collect::<Result<Vec<_>, _>>()?;
let (width, height) = loaded
.iter()
.flatten()
.map(|(_, image)| (image.width(), image.height()))
.next()
.ok_or_else(|| format!("{} has packed inputs but no readable Texture", record.path))?;
let loaded = loaded
.into_iter()
.map(|entry| {
entry.map(|(bytes, image)| {
let image = if image.width() == width && image.height() == height {
image
} else {
image::imageops::resize(&image, width, height, FilterType::Lanczos3)
};
(bytes, image)
})
})
.collect::<Vec<_>>();
let mut packed = RgbaImage::new(width, height);
for y in 0..height {
for x in 0..width {
let ao = sample_scalar(loaded[0].as_ref(), scalar_bindings[0], x, y, 255);
let roughness = sample_scalar(loaded[1].as_ref(), scalar_bindings[1], x, y, 255);
let metallic = sample_scalar(loaded[2].as_ref(), scalar_bindings[2], x, y, 0);
packed.put_pixel(x, y, Rgba([ao, roughness, metallic, 255]));
}
}
Ok(Some(MaterialArtifactPlan {
output_path,
output_bytes: encode_uastc(&packed, false, true)?,
runtime: MaterialRuntimeData {
packed_arm_path: Some(normalize_path(&relative_output)),
processing_key: Some(processing_key),
},
reused: false,
}))
}
pub fn publish_material_artifact(plan: &MaterialArtifactPlan) -> Result<bool, String> {
if plan.reused {
return Ok(false);
}
crate::write_if_changed(&plan.output_path, &plan.output_bytes)
}
pub fn material_packing_signature(
project_root: &Path,
record: &AssetRecord,
registry: &AssetRegistryDocument,
) -> Result<Option<MaterialPackingSignature>, String> {
if !matches!(
record.kind,
AssetKind::Material | AssetKind::MaterialInstance
) {
return Ok(None);
}
let inputs = load_resolved_material_inputs(project_root, record)?;
if ["occlusion", "roughness", "metallic"]
.into_iter()
.all(|name| assigned_texture(&inputs, name).is_none())
{
return Ok(None);
}
material_packing_signature_from_inputs(project_root, registry, &inputs).map(Some)
}
fn material_packing_signature_from_inputs(
project_root: &Path,
registry: &AssetRegistryDocument,
inputs: &MaterialInputSet,
) -> Result<MaterialPackingSignature, String> {
let mut hasher = blake3::Hasher::new();
hasher.update(&TEXTURE_PROCESSOR_VERSION.to_le_bytes());
for name in ["occlusion", "roughness", "metallic"] {
hasher.update(name.as_bytes());
let Some(binding) = assigned_texture(inputs, name) else {
hasher.update(b"unassigned");
continue;
};
hasher.update(format!("{:?}", binding.channel).as_bytes());
let (path, bytes, settings) = binding_source(project_root, registry, binding)?;
hasher.update(path.as_bytes());
hasher.update(blake3::hash(&bytes).as_bytes());
let settings = ron::ser::to_string(&settings)
.map_err(|error| format!("could not hash Texture import settings: {error}"))?;
hasher.update(settings.as_bytes());
}
Ok(MaterialPackingSignature(
hasher.finalize().to_hex()[..24].to_string(),
))
}
fn assigned_texture<'a>(
inputs: &'a MaterialInputSet,
name: &str,
) -> Option<&'a MaterialTextureBinding> {
inputs
.texture(name)
.filter(|binding| binding.texture.is_some())
}
pub fn apply_material_plan_to_catalog(
catalog: &mut shared::RuntimeContentCatalog,
asset_id: &shared::AssetId,
plan: &MaterialArtifactPlan,
) -> Result<(), String> {
let record = catalog
.records
.iter_mut()
.find(|record| &record.id == asset_id)
.ok_or_else(|| format!("runtime catalog is missing Material asset {asset_id:?}"))?;
record.material = Some(plan.runtime.clone());
Ok(())
}
pub fn apply_texture_plan_to_catalog(
catalog: &mut shared::RuntimeContentCatalog,
asset_id: &shared::AssetId,
plan: &TextureArtifactPlan,
) -> Result<(), String> {
let record = catalog
.records
.iter_mut()
.find(|record| &record.id == asset_id)
.ok_or_else(|| format!("runtime catalog is missing Texture asset {asset_id:?}"))?;
record.texture = Some(plan.runtime.clone());
Ok(())
}
pub fn normalize_texture_settings(path: &str, settings: &mut TextureImportSettings) {
if settings.semantic == TextureAssetSemantic::Auto {
settings.semantic = infer_texture_semantic(path);
}
if settings.color_space == TextureColorSpace::Auto {
settings.color_space = match settings.semantic {
TextureAssetSemantic::Color | TextureAssetSemantic::Ui => TextureColorSpace::Srgb,
TextureAssetSemantic::Auto
| TextureAssetSemantic::Normal
| TextureAssetSemantic::MaskData
| TextureAssetSemantic::Hdr => TextureColorSpace::Linear,
};
}
if settings.compression == TextureCompression::Auto {
settings.compression = if settings.semantic == TextureAssetSemantic::Hdr {
TextureCompression::Uncompressed
} else {
TextureCompression::Uastc
};
}
settings.anisotropy = settings.anisotropy.clamp(1, 16);
settings.max_dimension = settings.max_dimension.filter(|dimension| *dimension > 0);
}
pub fn infer_texture_semantic(path: &str) -> TextureAssetSemantic {
let lowercase = path.to_ascii_lowercase();
if lowercase.ends_with(".hdr") || lowercase.ends_with(".exr") {
TextureAssetSemantic::Hdr
} else if ["_normal", "_nor", "_nrm", "normal.", "nor_gl", "nor_dx"]
.iter()
.any(|marker| lowercase.contains(marker))
{
TextureAssetSemantic::Normal
} else if [
"_arm",
"_orm",
"_rma",
"_mask",
"_rough",
"_metal",
"_ao",
"occlusion",
"height",
]
.iter()
.any(|marker| lowercase.contains(marker))
{
TextureAssetSemantic::MaskData
} else {
TextureAssetSemantic::Color
}
}
fn resize_to_limit(image: RgbaImage, max_dimension: Option<u32>) -> RgbaImage {
let Some(limit) = max_dimension else {
return image;
};
let largest = image.width().max(image.height());
if largest <= limit {
return image;
}
let scale = limit as f64 / largest as f64;
let width = ((image.width() as f64 * scale).round() as u32).max(1);
let height = ((image.height() as f64 * scale).round() as u32).max(1);
image::imageops::resize(&image, width, height, FilterType::Lanczos3)
}
pub fn load_resolved_material_inputs(
project_root: &Path,
record: &AssetRecord,
) -> Result<MaterialInputSet, String> {
let path = project_root.join(&record.path);
match record.kind {
AssetKind::Material => Ok(load_ron::<MaterialAsset>(&path)?.inputs),
AssetKind::MaterialInstance => {
let instance = load_ron::<MaterialInstanceAsset>(&path)?;
let base_path = instance
.base
.0
.source_path
.as_deref()
.ok_or_else(|| format!("{} has no loadable base Material path", record.path))?;
let mut inputs = load_ron::<MaterialAsset>(&project_root.join(base_path))?.inputs;
merge_input_sets(&mut inputs, &instance.overrides);
Ok(inputs)
}
_ => Err(format!("{} is not a Material asset", record.path)),
}
}
/// Returns direct Material Instance consumers of one base Material.
///
/// Blacksite currently supports direct-base instances only, so this is the complete dependency
/// closure for a base Material packing change.
pub fn direct_material_instance_dependents(
project_root: &Path,
registry: &AssetRegistryDocument,
base: &AssetRecord,
) -> Vec<AssetRecord> {
registry
.records
.iter()
.filter(|record| record.kind == AssetKind::MaterialInstance)
.filter_map(|record| {
let instance =
load_ron::<MaterialInstanceAsset>(&project_root.join(&record.path)).ok()?;
reference_targets_record(&instance.base.0, base).then(|| record.clone())
})
.collect()
}
/// Returns project Materials and direct Material Instances whose effective inputs reference a
/// Texture through its stable registry identity (with source path as a guarded legacy fallback).
pub fn material_dependents_of_texture(
project_root: &Path,
registry: &AssetRegistryDocument,
texture: &AssetRecord,
) -> Vec<AssetRecord> {
registry
.records
.iter()
.filter(|record| {
matches!(
record.kind,
AssetKind::Material | AssetKind::MaterialInstance
)
})
.filter_map(|record| {
let inputs = load_resolved_material_inputs(project_root, record).ok()?;
inputs
.textures
.iter()
.filter_map(|binding| binding.texture.as_ref())
.any(|reference| reference_targets_record(reference, texture))
.then(|| record.clone())
})
.collect()
}
fn reference_targets_record(reference: &shared::EditorAssetRef, record: &AssetRecord) -> bool {
(!reference.asset_id.is_empty() && reference.asset_id == record.id.as_string())
|| reference.source_path.as_deref() == Some(record.path.as_str())
}
fn load_ron<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T, String> {
let source = std::fs::read_to_string(path)
.map_err(|error| format!("could not read {}: {error}", path.display()))?;
ron::from_str(&source).map_err(|error| format!("invalid RON in {}: {error}", path.display()))
}
fn merge_input_sets(base: &mut MaterialInputSet, overrides: &MaterialInputSet) {
for value in &overrides.values {
if let Some(existing) = base
.values
.iter_mut()
.find(|entry| entry.name == value.name)
{
*existing = value.clone();
} else {
base.values.push(value.clone());
}
}
for texture in &overrides.textures {
if let Some(existing) = base
.textures
.iter_mut()
.find(|entry| entry.name == texture.name)
{
*existing = texture.clone();
} else {
base.textures.push(texture.clone());
}
}
}
fn load_binding_image(
project_root: &Path,
registry: &AssetRegistryDocument,
binding: &MaterialTextureBinding,
) -> Result<(Vec<u8>, RgbaImage), String> {
let (_, bytes, _) = binding_source(project_root, registry, binding)?;
let image = image::load_from_memory(&bytes)
.map_err(|error| format!("could not decode Texture for {}: {error}", binding.name))?
.to_rgba8();
Ok((bytes, image))
}
fn binding_source(
project_root: &Path,
registry: &AssetRegistryDocument,
binding: &MaterialTextureBinding,
) -> Result<(String, Vec<u8>, TextureImportSettings), String> {
let reference = binding
.texture
.as_ref()
.ok_or_else(|| format!("Material input {} is unassigned", binding.name))?;
let record = registry.records.iter().find(|record| {
record.id.as_string() == reference.asset_id
|| reference
.source_path
.as_deref()
.is_some_and(|path| record.path == path)
});
let path = record
.map(|record| record.path.clone())
.or_else(|| reference.source_path.clone())
.ok_or_else(|| format!("Texture {} has no project path", reference.label))?;
let bytes = std::fs::read(project_root.join(&path))
.map_err(|error| format!("could not read Texture {path}: {error}"))?;
let mut settings = record
.and_then(|record| record.texture_import().cloned())
.unwrap_or_default();
normalize_texture_settings(&path, &mut settings);
Ok((path, bytes, settings))
}
fn sample_scalar(
image: Option<&(Vec<u8>, RgbaImage)>,
binding: Option<&MaterialTextureBinding>,
x: u32,
y: u32,
fallback: u8,
) -> u8 {
let (Some((_, image)), Some(binding)) = (image, binding) else {
return fallback;
};
let pixel = image.get_pixel(x, y).0;
match binding.channel {
TextureChannel::R | TextureChannel::Rgb | TextureChannel::Rgba => pixel[0],
TextureChannel::G => pixel[1],
TextureChannel::B => pixel[2],
TextureChannel::A => pixel[3],
}
}
fn flip_normal_green(image: &mut RgbaImage) {
for pixel in image.pixels_mut() {
pixel.0[1] = 255_u8.saturating_sub(pixel.0[1]);
}
}
fn requested_mip_count(width: u32, height: u32, mode: TextureMipmapMode) -> u32 {
if mode != TextureMipmapMode::Generate {
return 1;
}
width.max(height).ilog2() + 1
}
fn generate_mips(image: &RgbaImage, mode: TextureMipmapMode) -> Vec<RgbaImage> {
let mut levels = vec![image.clone()];
if mode != TextureMipmapMode::Generate {
return levels;
}
while levels
.last()
.is_some_and(|level| level.width() > 1 || level.height() > 1)
{
let previous = levels.last().expect("mip chain has a base level");
let width = (previous.width() / 2).max(1);
let height = (previous.height() / 2).max(1);
levels.push(image::imageops::resize(
previous,
width,
height,
FilterType::Lanczos3,
));
}
levels
}
fn encode_uastc(
image: &RgbaImage,
is_srgb: bool,
generate_mipmaps: bool,
) -> Result<Vec<u8>, String> {
let mut params = basis_universal::CompressorParams::new();
params.set_basis_format(basis_universal::BasisTextureFormat::UASTC4x4);
params.set_uastc_quality_level(basis_universal::UASTC_QUALITY_DEFAULT);
params.set_generate_mipmaps(generate_mipmaps);
params.set_print_status_to_stdout(false);
params.set_color_space(if is_srgb {
basis_universal::ColorSpace::Srgb
} else {
basis_universal::ColorSpace::Linear
});
params
.source_image_mut(0)
.init(image.as_raw(), image.width(), image.height(), 4);
let mut compressor = basis_universal::Compressor::new(4);
// SAFETY: the image is tightly packed RGBA8 and all compressor parameters above are valid.
unsafe {
compressor.init(&params);
compressor
.process()
.map_err(|error| format!("UASTC compression failed: {error:?}"))?;
}
Ok(compressor.basis_file().to_vec())
}
fn encode_uncompressed_ktx2(mips: &[RgbaImage], is_srgb: bool) -> Result<Vec<u8>, String> {
let Some(base) = mips.first() else {
return Err("cannot encode an empty mip chain".into());
};
let level_count = u32::try_from(mips.len()).map_err(|_| "too many mip levels".to_string())?;
let dfd = rgba8_data_format_descriptor(is_srgb);
let header_len = 80_usize;
let level_index_len = mips.len() * 24;
let dfd_offset = header_len + level_index_len;
let data_offset = align_to(dfd_offset + dfd.len(), 8);
let mut level_offsets = Vec::with_capacity(mips.len());
let mut cursor = data_offset;
for level in mips {
cursor = align_to(cursor, 8);
level_offsets.push(cursor);
cursor += level.as_raw().len();
}
let mut bytes = Vec::with_capacity(cursor);
bytes.extend_from_slice(&[
0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A,
]);
push_u32(&mut bytes, if is_srgb { 43 } else { 37 });
push_u32(&mut bytes, 1);
push_u32(&mut bytes, base.width());
push_u32(&mut bytes, base.height());
push_u32(&mut bytes, 0);
push_u32(&mut bytes, 0);
push_u32(&mut bytes, 1);
push_u32(&mut bytes, level_count);
push_u32(&mut bytes, 0);
push_u32(
&mut bytes,
u32::try_from(dfd_offset).map_err(|_| "KTX2 is too large".to_string())?,
);
push_u32(&mut bytes, u32::try_from(dfd.len()).unwrap_or(u32::MAX));
push_u32(&mut bytes, 0);
push_u32(&mut bytes, 0);
push_u64(&mut bytes, 0);
push_u64(&mut bytes, 0);
for (level, offset) in mips.iter().zip(&level_offsets) {
push_u64(
&mut bytes,
u64::try_from(*offset).map_err(|_| "KTX2 is too large".to_string())?,
);
push_u64(&mut bytes, level.as_raw().len() as u64);
push_u64(&mut bytes, level.as_raw().len() as u64);
}
bytes.extend_from_slice(&dfd);
bytes.resize(data_offset, 0);
for (level, offset) in mips.iter().zip(level_offsets) {
bytes.resize(offset, 0);
bytes.extend_from_slice(level.as_raw());
}
Ok(bytes)
}
fn rgba8_data_format_descriptor(is_srgb: bool) -> Vec<u8> {
let mut dfd = Vec::with_capacity(92);
push_u32(&mut dfd, 92);
push_u16(&mut dfd, 0);
push_u16(&mut dfd, 0);
push_u16(&mut dfd, 2);
push_u16(&mut dfd, 88);
dfd.extend_from_slice(&[1, 1, if is_srgb { 2 } else { 1 }, 0]);
dfd.extend_from_slice(&[0, 0, 0, 0]);
dfd.extend_from_slice(&[4, 0, 0, 0, 0, 0, 0, 0]);
for (bit_offset, channel) in [(0_u16, 0_u8), (8, 1), (16, 2), (24, 15)] {
push_u16(&mut dfd, bit_offset);
dfd.extend_from_slice(&[7, channel]);
dfd.extend_from_slice(&[0, 0, 0, 0]);
push_u32(&mut dfd, 0);
push_u32(&mut dfd, 255);
}
dfd
}
fn align_to(value: usize, alignment: usize) -> usize {
value.div_ceil(alignment) * alignment
}
fn push_u16(bytes: &mut Vec<u8>, value: u16) {
bytes.extend_from_slice(&value.to_le_bytes());
}
fn push_u32(bytes: &mut Vec<u8>, value: u32) {
bytes.extend_from_slice(&value.to_le_bytes());
}
fn push_u64(bytes: &mut Vec<u8>, value: u64) {
bytes.extend_from_slice(&value.to_le_bytes());
}
fn normalize_path(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
use image::Rgba;
use shared::{
AssetId, AssetImportSettings, EditorAssetRef, MaterialParameter, MaterialParameterValue,
MaterialRef, ShaderRefDesc,
};
use uuid::Uuid;
fn test_root(name: &str) -> PathBuf {
std::env::temp_dir().join(format!(
"blacksite-texture-{name}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
))
}
fn record(id: u128, path: &str, kind: AssetKind) -> AssetRecord {
AssetRecord {
id: AssetId(Uuid::from_u128(id)),
path: path.into(),
label: path.into(),
kind,
source_fingerprint: None,
import_settings: if kind == AssetKind::Texture {
AssetImportSettings::Texture(TextureImportSettings::default())
} else {
AssetImportSettings::None
},
dependencies: Vec::new(),
}
}
fn material(label: &str, texture: Option<EditorAssetRef>, metallic: f32) -> MaterialAsset {
MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: label.into(),
shader: ShaderRefDesc::default(),
shader_ref: None,
render_state: Default::default(),
provenance: None,
inputs: MaterialInputSet {
values: vec![MaterialParameter {
name: "metallic".into(),
value: MaterialParameterValue::Float(metallic),
}],
textures: texture
.map(|texture| MaterialTextureBinding {
name: "metallic".into(),
texture: Some(texture),
channel: TextureChannel::B,
})
.into_iter()
.collect(),
},
}
}
fn write_ron(path: &Path, value: &impl serde::Serialize) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(
path,
ron::ser::to_string_pretty(value, ron::ser::PrettyConfig::default()).unwrap(),
)
.unwrap();
}
#[test]
fn infers_poly_haven_texture_roles() {
assert_eq!(
infer_texture_semantic("metal_office_desk_diff_2k.jpg"),
TextureAssetSemantic::Color
);
assert_eq!(
infer_texture_semantic("metal_office_desk_nor_gl_2k.png"),
TextureAssetSemantic::Normal
);
assert_eq!(
infer_texture_semantic("metal_office_desk_arm_2k.jpg"),
TextureAssetSemantic::MaskData
);
}
#[test]
fn normal_y_conversion_is_exact() {
let mut image = RgbaImage::from_pixel(1, 1, Rgba([1, 64, 3, 255]));
flip_normal_green(&mut image);
assert_eq!(image.get_pixel(0, 0).0, [1, 191, 3, 255]);
}
#[test]
fn uncompressed_ktx2_contains_all_mips() {
let image = RgbaImage::from_pixel(4, 2, Rgba([1, 2, 3, 4]));
let mips = generate_mips(&image, TextureMipmapMode::Generate);
let encoded = encode_uncompressed_ktx2(&mips, false).expect("KTX2 should encode");
assert_eq!(
&encoded[..12],
&[0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A]
);
assert_eq!(u32::from_le_bytes(encoded[40..44].try_into().unwrap()), 3);
}
#[test]
fn existing_texture_artifact_is_reused_before_source_decode() {
let root = test_root("texture-reuse");
let texture = record(21, "assets/textures/cached.png", AssetKind::Texture);
let source_bytes = b"intentionally not an image";
std::fs::create_dir_all(root.join("assets/textures")).unwrap();
std::fs::write(root.join(&texture.path), source_bytes).unwrap();
let mut settings = texture.texture_import().cloned().unwrap();
normalize_texture_settings(&texture.path, &mut settings);
let settings_bytes = ron::ser::to_string(&settings).unwrap();
let mut hasher = blake3::Hasher::new();
hasher.update(source_bytes);
hasher.update(settings_bytes.as_bytes());
hasher.update(&TEXTURE_PROCESSOR_VERSION.to_le_bytes());
let processing_key = &hasher.finalize().to_hex()[..24];
let output = root.join(format!(
"assets/.import-cache/runtime/textures/{}/{processing_key}/texture.basis",
texture.id.as_string()
));
std::fs::create_dir_all(output.parent().unwrap()).unwrap();
std::fs::write(&output, b"cached artifact").unwrap();
let plan = plan_texture_artifact(&root, &texture).unwrap();
assert!(plan.reused);
assert!(plan.output_bytes.is_empty());
assert_eq!(plan.output_path, output);
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn packing_signature_ignores_owner_and_scalar_multipliers() {
let root = test_root("signature");
let texture = record(1, "assets/textures/arm.bin", AssetKind::Texture);
std::fs::create_dir_all(root.join("assets/textures")).unwrap();
std::fs::write(root.join(&texture.path), b"stable packed source").unwrap();
let texture_ref = EditorAssetRef::new(texture.id.as_string(), "texture:source", "ARM")
.with_source_path(&texture.path);
let first = record(2, "assets/materials/first.ron", AssetKind::Material);
let second = record(3, "assets/materials/second.ron", AssetKind::Material);
write_ron(
&root.join(&first.path),
&material("First", Some(texture_ref.clone()), 0.1),
);
write_ron(
&root.join(&second.path),
&material("Second", Some(texture_ref), 0.9),
);
let registry = AssetRegistryDocument {
records: vec![texture, first.clone(), second.clone()],
..Default::default()
};
assert_eq!(
material_packing_signature(&root, &first, &registry).unwrap(),
material_packing_signature(&root, &second, &registry).unwrap(),
"owner identity and scalar multipliers must not invalidate identical packed data"
);
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn unassigned_scalar_texture_rows_do_not_request_packing() {
let root = test_root("unassigned-packing");
let material_record = record(22, "assets/materials/plain.ron", AssetKind::Material);
let mut authored = material("Plain", None, 0.5);
authored.inputs.textures.push(MaterialTextureBinding {
name: "occlusion".into(),
texture: None,
channel: TextureChannel::R,
});
write_ron(&root.join(&material_record.path), &authored);
let registry = AssetRegistryDocument {
records: vec![material_record.clone()],
..Default::default()
};
assert!(
material_packing_signature(&root, &material_record, &registry)
.unwrap()
.is_none()
);
assert!(plan_material_artifact(&root, &material_record, &registry)
.unwrap()
.is_none());
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn existing_material_artifact_is_reused_before_texture_decode() {
let root = test_root("material-reuse");
let texture = record(31, "assets/textures/arm.bin", AssetKind::Texture);
let material_record = record(32, "assets/materials/cached.ron", AssetKind::Material);
std::fs::create_dir_all(root.join("assets/textures")).unwrap();
std::fs::write(root.join(&texture.path), b"intentionally not an image").unwrap();
let texture_ref = EditorAssetRef::new(texture.id.as_string(), "texture:source", "ARM")
.with_source_path(&texture.path);
write_ron(
&root.join(&material_record.path),
&material("Cached", Some(texture_ref), 1.0),
);
let registry = AssetRegistryDocument {
records: vec![texture, material_record.clone()],
..Default::default()
};
let signature = material_packing_signature(&root, &material_record, &registry)
.unwrap()
.unwrap();
let output = root.join(format!(
"assets/.import-cache/runtime/materials/{}/{}-arm.basis",
material_record.id.as_string(),
signature.0
));
std::fs::create_dir_all(output.parent().unwrap()).unwrap();
std::fs::write(&output, b"cached artifact").unwrap();
let plan = plan_material_artifact(&root, &material_record, &registry)
.unwrap()
.unwrap();
assert!(plan.reused);
assert!(plan.output_bytes.is_empty());
assert_eq!(plan.output_path, output);
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn dependency_closure_uses_stable_material_and_texture_references() {
let root = test_root("dependencies");
let texture = record(11, "assets/textures/arm.bin", AssetKind::Texture);
let base = record(12, "assets/materials/base.ron", AssetKind::Material);
let instance = record(
13,
"assets/materials/base_instance.ron",
AssetKind::MaterialInstance,
);
let unrelated = record(14, "assets/materials/unrelated.ron", AssetKind::Material);
let texture_ref = EditorAssetRef::new(texture.id.as_string(), "texture:source", "ARM")
.with_source_path(&texture.path);
write_ron(
&root.join(&base.path),
&material("Base", Some(texture_ref), 1.0),
);
write_ron(
&root.join(&unrelated.path),
&material("Unrelated", None, 1.0),
);
write_ron(
&root.join(&instance.path),
&MaterialInstanceAsset {
schema_version: shared::MATERIAL_INSTANCE_SCHEMA_VERSION,
label: "Base Instance".into(),
base: MaterialRef::new(
EditorAssetRef::new(base.id.as_string(), "material:source", "Base")
.with_source_path(&base.path),
),
overrides: MaterialInputSet::default(),
},
);
let registry = AssetRegistryDocument {
records: vec![texture.clone(), base.clone(), instance.clone(), unrelated],
..Default::default()
};
assert_eq!(
direct_material_instance_dependents(&root, &registry, &base)
.into_iter()
.map(|record| record.id)
.collect::<Vec<_>>(),
vec![instance.id.clone()]
);
let dependents = material_dependents_of_texture(&root, &registry, &texture)
.into_iter()
.map(|record| record.id)
.collect::<Vec<_>>();
assert!(dependents.contains(&base.id));
assert!(dependents.contains(&instance.id));
assert_eq!(dependents.len(), 2);
std::fs::remove_dir_all(root).unwrap();
}
}
File diff suppressed because it is too large. Load diff
+605
View File
@@ -0,0 +1,605 @@
use crate::{
serialize_registry, serialize_runtime_catalog, validate_asset_path, write_if_changed,
REGISTRY_PATH, RUNTIME_CATALOG_PATH,
};
use serde::{Deserialize, Serialize};
use shared::{AssetRecord, AssetRegistryDocument};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
const TRASH_ROOT: &str = "assets/.trash";
const TRASH_MANIFEST: &str = ".blacksite-trash.ron";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TrashManifest {
pub schema_version: u32,
pub batch_id: String,
pub original_paths: Vec<String>,
#[serde(default)]
pub derived_paths: Vec<String>,
pub records: Vec<AssetRecord>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TrashBatchSummary {
pub path: PathBuf,
pub batch_id: String,
pub original_paths: Vec<String>,
}
pub fn trash_content(
project_root: &Path,
original_paths: &[PathBuf],
registry: &mut AssetRegistryDocument,
) -> Result<TrashBatchSummary, String> {
let originals = normalize_originals(project_root, original_paths)?;
let batch_id = trash_batch_id();
let batch_path = PathBuf::from(TRASH_ROOT).join(&batch_id);
let absolute_batch = project_root.join(&batch_path);
fs::create_dir_all(&absolute_batch)
.map_err(|error| format!("could not create {}: {error}", absolute_batch.display()))?;
let records = registry
.records
.iter()
.filter(|record| originals.iter().any(|path| descendant(&record.path, path)))
.cloned()
.collect::<Vec<_>>();
let derived_paths = collect_derived_paths(project_root, &records, &originals)?;
let manifest = TrashManifest {
schema_version: 2,
batch_id: batch_id.clone(),
original_paths: originals.clone(),
derived_paths,
records,
};
let original_registry = registry.clone();
let registry_path = project_root.join(REGISTRY_PATH);
let original_registry_bytes = fs::read(&registry_path).ok();
let runtime_path = project_root.join(RUNTIME_CATALOG_PATH);
let original_runtime_bytes = fs::read(&runtime_path).ok();
let mut moved = Vec::new();
let result: Result<(), String> = (|| {
for original in &originals {
let source = project_root.join(original);
let destination = absolute_batch.join(original);
if let Some(parent) = destination.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
}
fs::rename(&source, &destination).map_err(|error| {
format!(
"could not move {} to {}: {error}",
source.display(),
destination.display()
)
})?;
moved.push((source, destination));
}
for derived in &manifest.derived_paths {
let source = project_root.join(derived);
let destination = absolute_batch.join(derived);
if let Some(parent) = destination.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
}
fs::rename(&source, &destination).map_err(|error| {
format!(
"could not move derived artifact {} to trash: {error}",
source.display()
)
})?;
moved.push((source, destination));
}
let manifest_ron = ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize trash manifest: {error}"))?;
fs::write(absolute_batch.join(TRASH_MANIFEST), manifest_ron)
.map_err(|error| format!("could not write trash manifest: {error}"))?;
registry
.records
.retain(|record| !originals.iter().any(|path| descendant(&record.path, path)));
write_if_changed(&registry_path, &serialize_registry(registry)?)?;
write_runtime_catalog(&runtime_path, registry)?;
Ok(())
})();
if let Err(error) = result {
rollback_moves(moved);
restore_registry(&registry_path, original_registry_bytes.as_deref());
restore_registry(&runtime_path, original_runtime_bytes.as_deref());
*registry = original_registry;
let _ = fs::remove_dir_all(&absolute_batch);
return Err(format!("trash transaction rolled back: {error}"));
}
Ok(TrashBatchSummary {
path: batch_path,
batch_id,
original_paths: originals,
})
}
pub fn list_trash_batches(project_root: &Path) -> Result<Vec<TrashBatchSummary>, String> {
let root = project_root.join(TRASH_ROOT);
if !root.exists() {
return Ok(Vec::new());
}
let mut batches = Vec::new();
for entry in fs::read_dir(&root)
.map_err(|error| format!("could not inspect {}: {error}", root.display()))?
{
let entry = entry.map_err(|error| format!("could not inspect trash entry: {error}"))?;
if !entry
.file_type()
.map_err(|error| format!("could not inspect trash entry: {error}"))?
.is_dir()
{
continue;
}
let absolute = entry.path();
let manifest = load_or_infer_manifest(&absolute)?;
batches.push(TrashBatchSummary {
path: PathBuf::from(TRASH_ROOT).join(&manifest.batch_id),
batch_id: manifest.batch_id,
original_paths: manifest.original_paths,
});
}
batches.sort_by(|left, right| right.batch_id.cmp(&left.batch_id));
Ok(batches)
}
pub fn restore_trash_batch(
project_root: &Path,
batch_path: &Path,
registry: &mut AssetRegistryDocument,
) -> Result<TrashBatchSummary, String> {
let normalized_batch = normalize(batch_path);
if !normalized_batch.starts_with("assets/.trash/") {
return Err("restore path must identify a managed trash batch".into());
}
let absolute_batch = project_root.join(batch_path);
let manifest = load_or_infer_manifest(&absolute_batch)?;
for original in &manifest.original_paths {
validate_asset_path(Path::new(original))?;
if project_root.join(original).exists() {
return Err(format!("restore collision: {original} already exists"));
}
if !trashed_source(&absolute_batch, original).exists() {
return Err(format!("trash batch is missing {original}"));
}
}
for derived in &manifest.derived_paths {
validate_derived_path(Path::new(derived))?;
if project_root.join(derived).exists() {
return Err(format!("restore collision: {derived} already exists"));
}
if !trashed_source(&absolute_batch, derived).exists() {
return Err(format!("trash batch is missing derived artifact {derived}"));
}
}
for record in &manifest.records {
if registry
.records
.iter()
.any(|existing| existing.path == record.path || existing.id == record.id)
{
return Err(format!(
"registry collision prevents restoring {}",
record.path
));
}
}
let original_registry = registry.clone();
let registry_path = project_root.join(REGISTRY_PATH);
let original_registry_bytes = fs::read(&registry_path).ok();
let runtime_path = project_root.join(RUNTIME_CATALOG_PATH);
let original_runtime_bytes = fs::read(&runtime_path).ok();
let mut moved = Vec::new();
let result: Result<(), String> = (|| {
for original in &manifest.original_paths {
let source = trashed_source(&absolute_batch, original);
let destination = project_root.join(original);
if let Some(parent) = destination.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
}
fs::rename(&source, &destination).map_err(|error| {
format!(
"could not restore {} to {}: {error}",
source.display(),
destination.display()
)
})?;
moved.push((source, destination));
}
for derived in &manifest.derived_paths {
let source = trashed_source(&absolute_batch, derived);
let destination = project_root.join(derived);
if let Some(parent) = destination.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
}
fs::rename(&source, &destination).map_err(|error| {
format!(
"could not restore derived artifact {} to {}: {error}",
source.display(),
destination.display()
)
})?;
moved.push((source, destination));
}
registry.records.extend(manifest.records.iter().cloned());
registry
.records
.sort_by(|left, right| left.path.cmp(&right.path));
write_if_changed(&registry_path, &serialize_registry(registry)?)?;
write_runtime_catalog(&runtime_path, registry)?;
Ok(())
})();
if let Err(error) = result {
rollback_moves(moved);
restore_registry(&registry_path, original_registry_bytes.as_deref());
restore_registry(&runtime_path, original_runtime_bytes.as_deref());
*registry = original_registry;
return Err(format!("restore transaction rolled back: {error}"));
}
let _ = fs::remove_dir_all(&absolute_batch);
Ok(TrashBatchSummary {
path: batch_path.to_path_buf(),
batch_id: manifest.batch_id,
original_paths: manifest.original_paths,
})
}
fn normalize_originals(project_root: &Path, paths: &[PathBuf]) -> Result<Vec<String>, String> {
if paths.is_empty() {
return Err("no content paths were selected for trash".into());
}
let mut originals: Vec<String> = Vec::new();
for path in paths {
validate_asset_path(path)?;
let normalized = normalize(path);
if !project_root.join(path).exists() {
return Err(format!("content path does not exist: {}", path.display()));
}
if originals
.iter()
.any(|parent| descendant(&normalized, parent))
{
continue;
}
originals.retain(|child| !descendant(child, &normalized));
originals.push(normalized);
}
originals.sort();
Ok(originals)
}
fn load_or_infer_manifest(batch: &Path) -> Result<TrashManifest, String> {
let manifest_path = batch.join(TRASH_MANIFEST);
if let Ok(text) = fs::read_to_string(&manifest_path) {
return ron::from_str(&text).map_err(|error| {
format!(
"invalid trash manifest {}: {error}",
manifest_path.display()
)
});
}
let batch_id = batch
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("legacy")
.to_string();
let scan_root = if batch.join("assets").is_dir() {
batch.join("assets")
} else {
batch.to_path_buf()
};
let mut original_paths = Vec::new();
for entry in fs::read_dir(&scan_root)
.map_err(|error| format!("could not inspect legacy trash batch: {error}"))?
{
let entry =
entry.map_err(|error| format!("could not inspect legacy trash item: {error}"))?;
if entry.file_name() == TRASH_MANIFEST {
continue;
}
original_paths.push(format!("assets/{}", entry.file_name().to_string_lossy()));
}
original_paths.sort();
Ok(TrashManifest {
schema_version: 0,
batch_id,
original_paths,
derived_paths: Vec::new(),
records: Vec::new(),
})
}
fn collect_derived_paths(
project_root: &Path,
records: &[AssetRecord],
originals: &[String],
) -> Result<Vec<String>, String> {
let mut derived = Vec::new();
for record in records {
let Some(settings) = record.import_settings.model() else {
continue;
};
for path in [
settings.static_mesh_manifest_path.as_deref(),
settings.animation_manifest_path.as_deref(),
]
.into_iter()
.flatten()
{
validate_derived_path(Path::new(path))?;
if originals.iter().any(|original| descendant(path, original)) {
continue;
}
let absolute = project_root.join(path);
let Ok(metadata) = fs::symlink_metadata(&absolute) else {
continue;
};
if metadata.file_type().is_symlink() {
return Err(format!(
"derived artifact may not be a symlink: {}",
absolute.display()
));
}
if metadata.is_file() {
derived.push(path.to_string());
}
}
}
derived.sort();
derived.dedup();
Ok(derived)
}
fn validate_derived_path(path: &Path) -> Result<(), String> {
if validate_asset_path(path).is_ok() {
return Ok(());
}
if path.is_absolute()
|| path.components().any(|component| {
matches!(
component,
std::path::Component::ParentDir
| std::path::Component::RootDir
| std::path::Component::Prefix(_)
)
})
{
return Err("derived artifact paths must remain project-relative".into());
}
let normalized = normalize(path);
if descendant(&normalized, "assets/meshes/generated")
|| descendant(&normalized, "assets/animations/generated")
{
Ok(())
} else {
Err(format!(
"unsupported derived artifact path outside generated manifest roots: {normalized}"
))
}
}
fn trashed_source(batch: &Path, original: &str) -> PathBuf {
let preserved = batch.join(original);
if preserved.exists() {
preserved
} else {
batch.join(original.strip_prefix("assets/").unwrap_or(original))
}
}
fn rollback_moves(moved: Vec<(PathBuf, PathBuf)>) {
for (source, destination) in moved.into_iter().rev() {
if let Some(parent) = source.parent() {
let _ = fs::create_dir_all(parent);
}
let _ = fs::rename(destination, source);
}
}
fn restore_registry(path: &Path, bytes: Option<&[u8]>) {
if let Some(bytes) = bytes {
let _ = fs::write(path, bytes);
} else {
let _ = fs::remove_file(path);
}
}
fn write_runtime_catalog(path: &Path, registry: &AssetRegistryDocument) -> Result<(), String> {
let catalog = shared::RuntimeContentCatalog::from(registry);
write_if_changed(path, &serialize_runtime_catalog(&catalog)?)?;
Ok(())
}
fn trash_batch_id() -> String {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| format!("{}-{:09}", duration.as_secs(), duration.subsec_nanos()))
.unwrap_or_else(|_| "now".into())
}
fn normalize(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
fn descendant(path: &str, parent: &str) -> bool {
path == parent
|| path
.strip_prefix(parent)
.is_some_and(|suffix| suffix.starts_with('/'))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn trash_and_restore_preserve_bytes_and_registry_ids() {
let root = std::env::temp_dir().join(format!(
"blacksite-trash-{}",
shared::AssetId::new().as_string()
));
fs::create_dir_all(root.join("assets/Props")).unwrap();
fs::create_dir_all(root.join("assets/.index")).unwrap();
fs::write(root.join("assets/Props/box.png"), b"asset bytes").unwrap();
let record = AssetRecord {
id: shared::AssetId::new(),
path: "assets/Props/box.png".into(),
label: "Box".into(),
kind: shared::AssetKind::Texture,
source_fingerprint: None,
import_settings: shared::AssetImportSettings::for_kind(shared::AssetKind::Texture),
dependencies: Vec::new(),
};
let mut registry = AssetRegistryDocument {
records: vec![record.clone()],
..Default::default()
};
fs::write(
root.join(REGISTRY_PATH),
serialize_registry(&registry).unwrap(),
)
.unwrap();
let batch = trash_content(
&root,
&[PathBuf::from("assets/Props/box.png")],
&mut registry,
)
.unwrap();
assert!(!root.join("assets/Props/box.png").exists());
assert!(registry.records.is_empty());
restore_trash_batch(&root, &batch.path, &mut registry).unwrap();
assert_eq!(
fs::read(root.join("assets/Props/box.png")).unwrap(),
b"asset bytes"
);
assert_eq!(registry.records, vec![record]);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn trash_and_restore_include_model_derived_manifests() {
let root = std::env::temp_dir().join(format!(
"blacksite-trash-derived-{}",
shared::AssetId::new().as_string()
));
fs::create_dir_all(root.join("assets/Props")).unwrap();
fs::create_dir_all(root.join("assets/meshes/generated")).unwrap();
fs::create_dir_all(root.join("assets/animations/generated")).unwrap();
fs::create_dir_all(root.join("assets/.index")).unwrap();
fs::write(root.join("assets/Props/desk.glb"), b"model bytes").unwrap();
fs::write(
root.join("assets/meshes/generated/desk.static_mesh.ron"),
b"static manifest",
)
.unwrap();
fs::write(
root.join("assets/animations/generated/desk.animation.ron"),
b"animation manifest",
)
.unwrap();
let mut record = AssetRecord {
id: shared::AssetId::new(),
path: "assets/Props/desk.glb".into(),
label: "Desk".into(),
kind: shared::AssetKind::Model,
source_fingerprint: None,
import_settings: shared::AssetImportSettings::Model(shared::ImportSettings::default()),
dependencies: Vec::new(),
};
record.model_import_mut().static_mesh_manifest_path =
Some("assets/meshes/generated/desk.static_mesh.ron".into());
record.model_import_mut().animation_manifest_path =
Some("assets/animations/generated/desk.animation.ron".into());
let mut registry = AssetRegistryDocument {
records: vec![record.clone()],
..Default::default()
};
fs::write(
root.join(REGISTRY_PATH),
serialize_registry(&registry).unwrap(),
)
.unwrap();
let batch = trash_content(
&root,
&[PathBuf::from("assets/Props/desk.glb")],
&mut registry,
)
.unwrap();
assert!(!root.join("assets/Props/desk.glb").exists());
assert!(!root
.join("assets/meshes/generated/desk.static_mesh.ron")
.exists());
assert!(!root
.join("assets/animations/generated/desk.animation.ron")
.exists());
let manifest: TrashManifest = ron::from_str(
&fs::read_to_string(root.join(&batch.path).join(TRASH_MANIFEST)).unwrap(),
)
.unwrap();
assert_eq!(manifest.schema_version, 2);
assert_eq!(
manifest.derived_paths,
vec![
"assets/animations/generated/desk.animation.ron",
"assets/meshes/generated/desk.static_mesh.ron",
]
);
restore_trash_batch(&root, &batch.path, &mut registry).unwrap();
assert_eq!(
fs::read(root.join("assets/Props/desk.glb")).unwrap(),
b"model bytes"
);
assert_eq!(
fs::read(root.join("assets/meshes/generated/desk.static_mesh.ron")).unwrap(),
b"static manifest"
);
assert_eq!(
fs::read(root.join("assets/animations/generated/desk.animation.ron")).unwrap(),
b"animation manifest"
);
assert_eq!(registry.records, vec![record]);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn restore_collision_keeps_trash_untouched() {
let root = std::env::temp_dir().join(format!(
"blacksite-trash-{}",
shared::AssetId::new().as_string()
));
fs::create_dir_all(root.join("assets/Props")).unwrap();
fs::create_dir_all(root.join("assets/.index")).unwrap();
fs::write(root.join("assets/Props/box.png"), b"original").unwrap();
let mut registry = AssetRegistryDocument::default();
fs::write(
root.join(REGISTRY_PATH),
serialize_registry(&registry).unwrap(),
)
.unwrap();
let batch = trash_content(
&root,
&[PathBuf::from("assets/Props/box.png")],
&mut registry,
)
.unwrap();
fs::write(root.join("assets/Props/box.png"), b"external").unwrap();
assert!(restore_trash_batch(&root, &batch.path, &mut registry).is_err());
assert_eq!(
fs::read(root.join("assets/Props/box.png")).unwrap(),
b"external"
);
assert!(root.join(&batch.path).join("assets/Props/box.png").exists());
fs::remove_dir_all(root).unwrap();
}
}
+187
View File
@@ -0,0 +1,187 @@
//! Debounced project-content watching shared by editor hosts and automation.
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver};
use std::time::{Duration, Instant};
#[derive(Debug, Default)]
pub struct DebouncedContentChanges {
paths: BTreeSet<PathBuf>,
last_change: Option<Instant>,
suppressed: usize,
}
impl DebouncedContentChanges {
pub fn begin_transaction(&mut self) {
self.suppressed += 1;
}
pub fn end_transaction(&mut self) {
self.suppressed = self.suppressed.saturating_sub(1);
}
pub fn record(&mut self, path: PathBuf, now: Instant) {
if self.suppressed == 0 {
self.paths.insert(path);
self.last_change = Some(now);
}
}
pub fn take_ready(&mut self, now: Instant, debounce: Duration) -> Vec<PathBuf> {
if self.suppressed > 0
|| self
.last_change
.is_none_or(|last_change| now.duration_since(last_change) < debounce)
{
return Vec::new();
}
self.last_change = None;
std::mem::take(&mut self.paths).into_iter().collect()
}
}
pub struct ContentWatchService {
_watcher: RecommendedWatcher,
events: Receiver<notify::Result<notify::Event>>,
changes: DebouncedContentChanges,
assets_root: PathBuf,
suppressed_paths: BTreeMap<PathBuf, Instant>,
}
impl ContentWatchService {
pub fn watch_project(project_root: &Path) -> Result<Self, String> {
let (sender, events) = mpsc::channel();
let mut watcher = notify::recommended_watcher(move |event| {
let _ = sender.send(event);
})
.map_err(|error| format!("could not create content watcher: {error}"))?;
let assets = project_root.join(crate::ASSETS_DIRECTORY);
watcher
.watch(&assets, RecursiveMode::Recursive)
.map_err(|error| format!("could not watch {}: {error}", assets.display()))?;
Ok(Self {
_watcher: watcher,
events,
changes: DebouncedContentChanges::default(),
assets_root: assets,
suppressed_paths: BTreeMap::new(),
})
}
pub fn begin_transaction(&mut self) {
self.changes.begin_transaction();
}
pub fn end_transaction(&mut self) {
while self.events.try_recv().is_ok() {}
self.changes.end_transaction();
}
/// Ignores watcher noise for one host-authored file while direct runtime consumers observe
/// its new revision. This prevents an inline Material slider edit from starting a full project
/// processing pass without hiding unrelated external changes.
pub fn suppress_path(&mut self, path: &Path, duration: Duration) {
let path = if path.is_absolute() {
path.to_path_buf()
} else {
self.assets_root
.parent()
.unwrap_or(&self.assets_root)
.join(path)
};
self.suppressed_paths
.insert(path, Instant::now() + duration);
}
/// Drains host events and returns one deterministic path set after the debounce window.
pub fn poll(&mut self, debounce: Duration) -> Result<Vec<PathBuf>, String> {
let now = Instant::now();
self.suppressed_paths.retain(|_, deadline| *deadline >= now);
while let Ok(event) = self.events.try_recv() {
let event = event.map_err(|error| format!("content watch failed: {error}"))?;
for path in event.paths {
if self
.suppressed_paths
.get(&path)
.is_some_and(|deadline| *deadline >= now)
{
continue;
}
if self.is_user_content_path(&path) {
self.changes.record(path, now);
}
}
}
Ok(self.changes.take_ready(now, debounce))
}
fn is_user_content_path(&self, path: &Path) -> bool {
is_user_content_path(&self.assets_root, path)
}
}
fn is_user_content_path(assets_root: &Path, path: &Path) -> bool {
let Ok(relative) = path.strip_prefix(assets_root) else {
return false;
};
!crate::is_managed_path(relative)
&& relative != Path::new("content.catalog.ron")
&& relative
.extension()
.and_then(|extension| extension.to_str())
!= Some("tmp")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debounce_deduplicates_and_transaction_suppression_discards_noise() {
let start = Instant::now();
let mut changes = DebouncedContentChanges::default();
changes.record(PathBuf::from("assets/a.png"), start);
changes.record(PathBuf::from("assets/a.png"), start);
assert!(changes
.take_ready(start, Duration::from_millis(50))
.is_empty());
assert_eq!(
changes.take_ready(start + Duration::from_millis(51), Duration::from_millis(50)),
vec![PathBuf::from("assets/a.png")]
);
changes.begin_transaction();
changes.record(PathBuf::from("assets/internal.ron"), start);
changes.end_transaction();
assert!(changes
.take_ready(start + Duration::from_secs(1), Duration::ZERO)
.is_empty());
}
#[test]
fn watcher_ignores_managed_and_generated_publication_noise() {
let root = Path::new("/project/assets");
assert!(is_user_content_path(
root,
Path::new("/project/assets/Props/a.png")
));
assert!(!is_user_content_path(
root,
Path::new("/project/assets/.index/registry.ron")
));
assert!(!is_user_content_path(
root,
Path::new("/project/assets/content.catalog.ron")
));
assert!(!is_user_content_path(
root,
Path::new("/project/assets/meshes/generated/model.static_mesh.ron")
));
assert!(!is_user_content_path(
root,
Path::new("/project/assets/Props/a.tmp")
));
}
}
+21
View File
@@ -0,0 +1,21 @@
# Editor subtree rules
- Define an explicit interaction-state matrix before implementing new editor UI behavior.
- Keep egui rendering thin. Move selection models, transaction planning, path rewriting, material
resolution, import review, and reusable logic into lightweight modules or crates.
- Test an invariant in its lightest owning crate; do not put it in `editor` merely because the UI
calls it.
- A small UI change does not justify full-workspace testing.
- Use `cargo check -p editor --lib` through the development lane in the fast loop unless a binary
target is directly affected.
- Use focused editor tests only for editor-owned behavior.
- Use named native scenarios for interaction and visual acceptance.
- Do not use all-features or hot-reload/dynamic-linking combinations for ordinary editor QA unless
that feature is under test.
- Screenshots alone do not establish UX completion; exercise the interaction.
- Reuse established editor components and visual language instead of creating bespoke panel
controls.
- Treat sustainable extension seams and debt-at-the-point-of-change as a feature requirement.
Inspector and Content Browser shells dispatch; they do not own domain behavior. Do not grow a
frozen-baseline module, and run `scripts/codex/architecture_audit.py check` after structural UI
changes.
+2
View File
@@ -26,11 +26,13 @@ hot-reload = ["game/hot-reload", "dep:hot-lib-reloader", "dep:notify"]
avian3d.workspace = true
bevy = { workspace = true, default-features = true, features = ["bevy_remote"] }
bevy_solari.workspace = true
blacksite_surface.workspace = true
bevy_egui.workspace = true
bevy-inspector-egui.workspace = true
egui_dock.workspace = true
egui_phosphor_icons.workspace = true
bevy_ufbx.workspace = true
content_pipeline.workspace = true
ufbx = "0.9"
game.workspace = true
polyanya.workspace = true
@@ -0,0 +1,93 @@
Copyright 2010-2024 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+2 -903
View File
@@ -1,904 +1,3 @@
//! Generated animation artifacts for imported model sources.
//! Compatibility re-exports for UI-independent animation artifact processing.
use std::collections::BTreeSet;
use std::fs;
use std::path::Path;
use serde::Deserialize;
use shared::{
animation_clip_sub_asset_id, animation_skeleton_sub_asset_id, AnimationClipRecord,
AnimationDiagnosticSeverity, AnimationEventDesc, AnimationImportDiagnostic, AnimationManifest,
AnimationManifestSource, AnimationSkeletonRecord, AnimationSkeletonSignature,
AnimationSourceFingerprint, ANIMATION_ARTIFACT_DIR, ANIMATION_MANIFEST_SCHEMA_VERSION,
};
use crate::asset_db::AssetRecord;
use crate::assets::fingerprint::write_pretty_ron_if_changed;
pub fn animation_manifest_path(asset_id: &str) -> String {
format!("{ANIMATION_ARTIFACT_DIR}/{asset_id}.animation.ron")
}
pub fn refresh_animation_artifact(record: &mut AssetRecord) -> Result<AnimationManifest, String> {
let mut manifest = build_animation_manifest(record)?;
manifest.source.dependencies.sort();
manifest.source.dependencies.dedup();
let path = animation_manifest_path(&record.id.as_string());
record.import_settings.animation_manifest_path = Some(path.clone());
record
.dependencies
.extend(manifest.source.dependencies.iter().cloned());
record.dependencies.sort();
record.dependencies.dedup();
if write_pretty_ron_if_changed(&path, &manifest)
.map_err(|error| format!("could not publish animation manifest {path}: {error}"))?
{
bevy::log::info!(
"Animation manifest refreshed: source={} artifact={} skeletons={} clips={} runtime_supported={}",
record.path,
path,
manifest.skeletons.len(),
manifest.clips.len(),
manifest.runtime_supported
);
}
Ok(manifest)
}
pub fn load_animation_manifest(path: &str) -> Result<AnimationManifest, String> {
let text =
fs::read_to_string(path).map_err(|error| format!("could not read {path}: {error}"))?;
ron::from_str(&text).map_err(|error| format!("could not parse {path}: {error}"))
}
pub fn build_animation_manifest(record: &AssetRecord) -> Result<AnimationManifest, String> {
let bytes = fs::read(&record.path)
.map_err(|error| format!("could not read {}: {error}", record.path))?;
let fingerprint = source_fingerprint(&bytes);
let format = source_format(&record.path)?;
match format.as_str() {
"gltf" | "glb" => build_gltf_manifest(record, format, fingerprint, &bytes),
"fbx" => build_fbx_manifest(record, format, fingerprint, &bytes),
_ => Err(format!("unsupported animation source format `{format}`")),
}
}
#[derive(Debug, Clone)]
struct SkeletonCandidate {
compatible_nodes: BTreeSet<usize>,
signature: AnimationSkeletonSignature,
}
fn build_gltf_manifest(
record: &AssetRecord,
format: String,
fingerprint: AnimationSourceFingerprint,
bytes: &[u8],
) -> Result<AnimationManifest, String> {
let gltf = gltf::Gltf::from_slice(bytes)
.map_err(|error| format!("could not parse glTF {}: {error}", record.path))?;
let base = Path::new(&record.path).parent();
let buffers = gltf::import_buffers(&gltf.document, base, gltf.blob.clone())
.map_err(|error| format!("could not load glTF buffers for {}: {error}", record.path))?;
let mut dependencies = gltf
.document
.buffers()
.filter_map(|buffer| match buffer.source() {
gltf::buffer::Source::Uri(uri) if !uri.starts_with("data:") => {
Some(resolve_dependency(&record.path, uri))
}
_ => None,
})
.collect::<Vec<_>>();
dependencies.sort();
dependencies.dedup();
let node_identity_names = gltf
.document
.nodes()
.map(|node| bevy_node_segment(node.name(), node.index()))
.collect::<Vec<_>>();
let readable_node_names = gltf
.document
.nodes()
.map(|node| normalized_node_segment(node.name(), node.index()))
.collect::<Vec<_>>();
let mut parents = vec![None; node_identity_names.len()];
for node in gltf.document.nodes() {
for child in node.children() {
parents[child.index()] = Some(node.index());
}
}
let mut skeletons = Vec::new();
let mut candidates = Vec::new();
for skin in gltf.document.skins() {
let source_index = skin.index();
let label = skin
.name()
.filter(|name| !name.trim().is_empty())
.map(str::to_string)
.unwrap_or_else(|| format!("Skeleton {source_index}"));
let joint_indices = skin.joints().map(|joint| joint.index()).collect::<Vec<_>>();
let joint_identity_paths = joint_indices
.iter()
.map(|index| node_path_segments(*index, &node_identity_names, &parents))
.collect::<Vec<_>>();
let joint_paths = joint_indices
.iter()
.map(|index| node_path(*index, &readable_node_names, &parents))
.collect::<Vec<_>>();
let bind_poses = skin
.reader(|buffer| Some(buffers[buffer.index()].0.as_slice()))
.read_inverse_bind_matrices()
.map(|matrices| matrices.map(gltf_matrix_bytes).collect::<Vec<_>>())
.unwrap_or_else(|| vec![identity_matrix_bytes(); joint_paths.len()]);
let signature = skeleton_signature(&joint_identity_paths, &bind_poses);
let mut compatible_nodes = joint_indices.into_iter().collect::<BTreeSet<_>>();
if let Some(root) = skin.skeleton() {
compatible_nodes.insert(root.index());
}
candidates.push(SkeletonCandidate {
compatible_nodes,
signature: signature.clone(),
});
skeletons.push(AnimationSkeletonRecord {
id: animation_skeleton_sub_asset_id(source_index, &label),
label,
source_index,
signature,
joint_paths,
});
}
let mut diagnostics = Vec::new();
let mut clips = Vec::new();
let mut animation_roots = BTreeSet::new();
for animation in gltf.document.animations() {
let source_index = animation.index();
let label = animation
.name()
.filter(|name| !name.trim().is_empty())
.map(str::to_string)
.unwrap_or_else(|| format!("Animation {source_index}"));
let mut duration_seconds = 0.0_f32;
let mut target_nodes = BTreeSet::new();
for channel in animation.channels() {
let target_index = channel.target().node().index();
target_nodes.insert(target_index);
animation_roots.insert(top_level_node(target_index, &parents));
if let Some(inputs) = channel
.reader(|buffer| Some(buffers[buffer.index()].0.as_slice()))
.read_inputs()
{
for input in inputs {
if input.is_finite() {
duration_seconds = duration_seconds.max(input);
}
}
}
}
let target_skeleton_signature = matching_skeleton_signature(&target_nodes, &candidates);
if !candidates.is_empty() && target_skeleton_signature.is_none() {
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Warning,
code: "animation.clip_skeleton_unresolved".into(),
message: format!(
"clip `{label}` does not target a uniquely identifiable imported skeleton"
),
repair: "Export the clip with channels targeting one skeleton, or split unrelated rigs into separate glTF assets.".into(),
});
}
let events = gltf_animation_events(&animation, duration_seconds, &label, &mut diagnostics);
clips.push(AnimationClipRecord {
id: animation_clip_sub_asset_id(source_index, &label),
label,
source_index,
duration_seconds,
target_skeleton_signature,
events,
});
}
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
.iter()
.map(|index| format!("`{}` (node {index})", node_identity_names[*index]))
.collect::<Vec<_>>()
.join(", ");
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Error,
code: "animation.multiple_roots_unsupported".into(),
message: format!(
"animation channels target {} distinct top-level roots ({roots}); Bevy requires a separate AnimationPlayer for each root",
animation_roots.len()
),
repair: "Split the source into one animated rig per glTF asset, or export every clip under one common top-level root, then reimport.".into(),
});
}
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,
fingerprint,
dependencies,
},
runtime_supported,
skeletons,
clips,
diagnostics,
})
}
fn build_fbx_manifest(
record: &AssetRecord,
format: String,
fingerprint: AnimationSourceFingerprint,
bytes: &[u8],
) -> Result<AnimationManifest, String> {
let scene = ufbx::load_memory(
bytes,
ufbx::LoadOpts {
target_unit_meters: 1.0,
target_axes: ufbx::CoordinateAxes::right_handed_y_up(),
..Default::default()
},
)
.map_err(|error| format!("could not parse FBX {}: {error:?}", record.path))?;
let mut skeletons = Vec::new();
for (source_index, skin) in scene.skin_deformers.as_ref().iter().enumerate() {
let label = if skin.element.name.is_empty() {
format!("Skeleton {source_index}")
} else {
skin.element.name.to_string()
};
let mut joint_identity_paths = Vec::new();
let mut joint_paths = Vec::new();
let mut bind_poses = Vec::new();
for cluster in skin.clusters.as_ref() {
let Some(bone) = cluster.bone_node.as_ref() else {
continue;
};
let segments = fbx_node_path_segments(bone.as_ref());
joint_paths.push(segments.join("/"));
joint_identity_paths.push(segments);
bind_poses.push(fbx_matrix_bytes(&cluster.bind_to_world));
}
let signature = skeleton_signature(&joint_identity_paths, &bind_poses);
skeletons.push(AnimationSkeletonRecord {
id: animation_skeleton_sub_asset_id(source_index, &label),
label,
source_index,
signature,
joint_paths,
});
}
let fallback_signature = (skeletons.len() == 1).then(|| skeletons[0].signature.clone());
let clips = scene
.anim_stacks
.as_ref()
.iter()
.enumerate()
.map(|(source_index, stack)| {
let label = if stack.element.name.is_empty() {
format!("Animation {source_index}")
} else {
stack.element.name.to_string()
};
AnimationClipRecord {
id: animation_clip_sub_asset_id(source_index, &label),
label,
source_index,
duration_seconds: (stack.time_end - stack.time_begin).max(0.0) as f32,
target_skeleton_signature: fallback_signature.clone(),
events: Vec::new(),
}
})
.collect::<Vec<_>>();
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,
fingerprint,
dependencies: Vec::new(),
},
runtime_supported,
skeletons,
clips,
diagnostics,
})
}
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,
) -> (bool, Vec<AnimationImportDiagnostic>) {
let mut diagnostics = Vec::new();
if animation_count > 0 || skin_count > 0 {
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Error,
code: "animation.fbx_runtime_unsupported".into(),
message: format!(
"FBX contains {animation_count} animation stack(s) and {skin_count} skin deformer(s), but Blacksite's current FBX loader cannot build a runtime skeleton or clips"
),
repair: "Export the animated source as glTF 2.0 (.glb or .gltf). Keep FBX only for static mesh import until hierarchy, SkinnedMesh, and AnimationClip conversion are implemented.".into(),
});
}
(false, diagnostics)
}
#[derive(Debug, Default, Deserialize)]
struct GltfAnimationExtras {
#[serde(default)]
blacksite_events: Vec<GltfAnimationEvent>,
}
#[derive(Debug, Deserialize)]
struct GltfAnimationEvent {
id: String,
time_seconds: f32,
#[serde(default)]
payload: Option<String>,
}
fn gltf_animation_events(
animation: &gltf::Animation<'_>,
duration_seconds: f32,
clip_label: &str,
diagnostics: &mut Vec<AnimationImportDiagnostic>,
) -> Vec<AnimationEventDesc> {
let Some(raw) = animation.extras().as_ref() else {
return Vec::new();
};
let extras = match serde_json::from_str::<GltfAnimationExtras>(raw.get()) {
Ok(extras) => extras,
Err(error) => {
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Warning,
code: "animation.events_invalid".into(),
message: format!("clip `{clip_label}` has invalid animation event metadata: {error}"),
repair: "Use an animation extras object with `blacksite_events` entries containing `id`, `time_seconds`, and optional string `payload`.".into(),
});
return Vec::new();
}
};
let mut events = Vec::new();
for event in extras.blacksite_events {
let valid_time = event.time_seconds.is_finite()
&& event.time_seconds >= 0.0
&& event.time_seconds <= duration_seconds;
if event.id.trim().is_empty() || !valid_time {
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Warning,
code: "animation.event_out_of_range".into(),
message: format!(
"clip `{clip_label}` contains an event with an empty ID or time outside 0..={duration_seconds:.3}s"
),
repair: "Give every event a stable non-empty ID and place it within the imported clip duration.".into(),
});
continue;
}
events.push(AnimationEventDesc {
id: event.id,
time_seconds: event.time_seconds,
payload: event.payload,
});
}
events.sort_by(|left, right| {
left.time_seconds
.total_cmp(&right.time_seconds)
.then(left.id.cmp(&right.id))
.then(left.payload.cmp(&right.payload))
});
events
}
fn matching_skeleton_signature(
target_nodes: &BTreeSet<usize>,
candidates: &[SkeletonCandidate],
) -> Option<AnimationSkeletonSignature> {
let scored = candidates
.iter()
.map(|candidate| {
(
candidate
.compatible_nodes
.intersection(target_nodes)
.count(),
candidate,
)
})
.filter(|(score, _)| *score > 0)
.collect::<Vec<_>>();
let best_score = scored.iter().map(|(score, _)| *score).max()?;
let mut best = scored
.into_iter()
.filter(|(score, _)| *score == best_score)
.map(|(_, candidate)| candidate);
let candidate = best.next()?;
best.all(|other| other.signature == candidate.signature)
.then(|| candidate.signature.clone())
}
fn node_path(index: usize, names: &[String], parents: &[Option<usize>]) -> String {
node_path_segments(index, names, parents).join("/")
}
fn node_path_segments(index: usize, names: &[String], parents: &[Option<usize>]) -> Vec<String> {
let mut segments = Vec::new();
let mut current = Some(index);
while let Some(node_index) = current {
segments.push(names[node_index].clone());
current = parents[node_index];
}
segments.reverse();
segments
}
fn top_level_node(index: usize, parents: &[Option<usize>]) -> usize {
let mut current = index;
while let Some(parent) = parents[current] {
current = parent;
}
current
}
fn bevy_node_segment(name: Option<&str>, index: usize) -> String {
name.map(str::to_string)
.unwrap_or_else(|| format!("GltfNode{index}"))
}
fn normalized_node_segment(name: Option<&str>, index: usize) -> String {
name.map(str::trim)
.filter(|name| !name.is_empty())
.map(|name| name.replace(['/', '\\'], "_"))
.unwrap_or_else(|| format!("Node{index}"))
}
fn fbx_node_path_segments(node: &ufbx::Node) -> Vec<String> {
let mut segments = Vec::new();
let mut current = Some(node);
while let Some(node) = current {
segments.push(normalized_node_segment(
(!node.element.name.is_empty()).then(|| node.element.name.as_ref()),
node.element.element_id as usize,
));
current = node.parent.as_ref().map(|parent| parent.as_ref());
}
segments.reverse();
segments
}
fn skeleton_signature(
joint_path_segments: &[Vec<String>],
bind_pose_bytes: &[Vec<u8>],
) -> AnimationSkeletonSignature {
let mut hasher = blake3::Hasher::new();
hasher.update(b"blacksite-animation-skeleton-v2\0");
hasher.update(&(joint_path_segments.len() as u64).to_le_bytes());
for path in joint_path_segments {
hasher.update(&(path.len() as u64).to_le_bytes());
for segment in path {
let bytes = segment.as_bytes();
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
}
}
hasher.update(&(bind_pose_bytes.len() as u64).to_le_bytes());
for bytes in bind_pose_bytes {
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
}
AnimationSkeletonSignature::new(hasher.finalize().to_hex().to_string())
}
fn gltf_matrix_bytes(matrix: [[f32; 4]; 4]) -> Vec<u8> {
matrix
.into_iter()
.flatten()
.flat_map(f32::to_le_bytes)
.collect()
}
fn identity_matrix_bytes() -> Vec<u8> {
gltf_matrix_bytes([
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
])
}
fn fbx_matrix_bytes(matrix: &ufbx::Matrix) -> Vec<u8> {
[
matrix.m00, matrix.m10, matrix.m20, matrix.m01, matrix.m11, matrix.m21, matrix.m02,
matrix.m12, matrix.m22, matrix.m03, matrix.m13, matrix.m23,
]
.into_iter()
.flat_map(f64::to_le_bytes)
.collect()
}
fn source_fingerprint(bytes: &[u8]) -> AnimationSourceFingerprint {
AnimationSourceFingerprint::from_bytes(bytes)
}
fn source_format(path: &str) -> Result<String, String> {
Path::new(path)
.extension()
.and_then(|extension| extension.to_str())
.map(|extension| extension.to_ascii_lowercase())
.ok_or_else(|| format!("asset path `{path}` has no extension"))
}
fn resolve_dependency(source_path: &str, uri: &str) -> String {
Path::new(source_path)
.parent()
.unwrap_or_else(|| Path::new(""))
.join(uri)
.to_string_lossy()
.replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::asset_db::{AssetId, ImportSettings};
use uuid::Uuid;
fn fixture_record(path: &Path) -> AssetRecord {
AssetRecord {
id: AssetId(Uuid::nil()),
path: path.to_string_lossy().replace('\\', "/"),
label: "Animated Hero".into(),
kind_tag: "Model".into(),
source_fingerprint: None,
import_settings: ImportSettings::default(),
dependencies: Vec::new(),
}
}
fn write_animated_gltf(root: &Path) -> std::path::PathBuf {
fs::create_dir_all(root).unwrap();
let mut buffer = Vec::new();
for value in [0.0_f32, 1.25] {
buffer.extend_from_slice(&value.to_le_bytes());
}
for value in [0.0_f32, 0.0, 0.0, 1.0, 0.0, 0.38268343, 0.0, 0.9238795] {
buffer.extend_from_slice(&value.to_le_bytes());
}
fs::write(root.join("animated.bin"), buffer).unwrap();
let gltf = r#"{
"asset":{"version":"2.0"},
"scene":0,
"scenes":[{"nodes":[0]}],
"nodes":[{"name":"Armature","children":[1]},{"name":"Hip"}],
"skins":[{"name":"Hero Rig","skeleton":0,"joints":[1]}],
"buffers":[{"uri":"animated.bin","byteLength":40}],
"bufferViews":[
{"buffer":0,"byteOffset":0,"byteLength":8},
{"buffer":0,"byteOffset":8,"byteLength":32}
],
"accessors":[
{"bufferView":0,"componentType":5126,"count":2,"type":"SCALAR","min":[0.0],"max":[1.25]},
{"bufferView":1,"componentType":5126,"count":2,"type":"VEC4"}
],
"animations":[{
"name":"Idle Loop",
"samplers":[{"input":0,"output":1,"interpolation":"LINEAR"}],
"channels":[{"sampler":0,"target":{"node":1,"path":"rotation"}}],
"extras":{"blacksite_events":[{"id":"footstep.left","time_seconds":0.5,"payload":"stone"}]}
}]
}"#;
let path = root.join("animated.gltf");
fs::write(&path, gltf).unwrap();
path
}
fn write_multi_root_animated_gltf(root: &Path) -> std::path::PathBuf {
fs::create_dir_all(root).unwrap();
let mut buffer = Vec::new();
for value in [0.0_f32, 1.0] {
buffer.extend_from_slice(&value.to_le_bytes());
}
for value in [0.0_f32, 0.0, 0.0, 1.0, 0.0, 0.38268343, 0.0, 0.9238795] {
buffer.extend_from_slice(&value.to_le_bytes());
}
fs::write(root.join("multi-root.bin"), buffer).unwrap();
let gltf = r#"{
"asset":{"version":"2.0"},
"scene":0,
"scenes":[{"nodes":[0,2]}],
"nodes":[
{"name":"Character A","children":[1]},
{"name":"Joint A"},
{"name":"Character B","children":[3]},
{"name":"Joint B"}
],
"buffers":[{"uri":"multi-root.bin","byteLength":40}],
"bufferViews":[
{"buffer":0,"byteOffset":0,"byteLength":8},
{"buffer":0,"byteOffset":8,"byteLength":32}
],
"accessors":[
{"bufferView":0,"componentType":5126,"count":2,"type":"SCALAR","min":[0.0],"max":[1.0]},
{"bufferView":1,"componentType":5126,"count":2,"type":"VEC4"}
],
"animations":[{
"name":"Two Players Required",
"samplers":[
{"input":0,"output":1,"interpolation":"LINEAR"},
{"input":0,"output":1,"interpolation":"LINEAR"}
],
"channels":[
{"sampler":0,"target":{"node":1,"path":"rotation"}},
{"sampler":1,"target":{"node":3,"path":"rotation"}}
]
}]
}"#;
let path = root.join("multi-root.gltf");
fs::write(&path, gltf).unwrap();
path
}
#[test]
fn animation_manifest_path_uses_registry_uuid() {
assert_eq!(
animation_manifest_path("abc"),
"assets/animations/generated/abc.animation.ron"
);
}
#[test]
fn gltf_extraction_is_deterministic_and_preserves_duration_events_and_signature() {
let root = std::env::temp_dir().join(format!("blacksite-animation-{}", Uuid::new_v4()));
let path = write_animated_gltf(&root);
let record = fixture_record(&path);
let first = build_animation_manifest(&record).unwrap();
let second = build_animation_manifest(&record).unwrap();
assert_eq!(first, second);
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);
assert_eq!(first.clips.len(), 1);
assert_eq!(first.skeletons[0].id, "animation:skeleton:0:hero_rig");
assert!(!first.skeletons[0].signature.is_empty());
assert_eq!(first.clips[0].id, "animation:clip:0:idle_loop");
assert_eq!(first.clips[0].duration_seconds, 1.25);
assert_eq!(
first.clips[0].target_skeleton_signature,
Some(first.skeletons[0].signature.clone())
);
assert_eq!(first.clips[0].events.len(), 1);
assert_eq!(first.clips[0].events[0].id, "footstep.left");
assert_eq!(first.clips[0].events[0].time_seconds, 0.5);
assert_eq!(first.diagnostics, Vec::new());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn legacy_mtime_metadata_does_not_rewrite_equivalent_animation_manifest() {
let root =
std::env::temp_dir().join(format!("blacksite-animation-legacy-{}", Uuid::new_v4()));
let path = write_animated_gltf(&root);
let manifest = build_animation_manifest(&fixture_record(&path)).unwrap();
let canonical =
ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default()).unwrap();
let marker = format!("byte_len: {},", manifest.source.fingerprint.byte_len);
let legacy = canonical.replacen(
&marker,
&format!("{marker}\n modified_unix_secs: 123456,"),
1,
);
assert_ne!(legacy, canonical);
let artifact = root.join("legacy.animation.ron");
fs::write(&artifact, &legacy).unwrap();
assert!(!write_pretty_ron_if_changed(&artifact, &manifest).unwrap());
assert_eq!(fs::read_to_string(&artifact).unwrap(), legacy);
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();
let first = skeleton_signature(
&[vec!["Armature".into(), "Hip".into()]],
std::slice::from_ref(&identity),
);
let renamed = skeleton_signature(
&[vec!["Armature".into(), "Pelvis".into()]],
std::slice::from_ref(&identity),
);
let mut changed_pose = identity;
changed_pose[0] ^= 1;
let rebound = skeleton_signature(&[vec!["Armature".into(), "Hip".into()]], &[changed_pose]);
assert_ne!(first, renamed);
assert_ne!(first, rebound);
}
#[test]
fn exact_signature_preserves_bevy_node_bytes_and_segment_boundaries() {
let identity = identity_matrix_bytes();
let slash_in_name = vec![vec!["Armature".into(), "Hip/Joint".into()]];
let slash_as_boundary = vec![vec!["Armature/Hip".into(), "Joint".into()]];
assert_eq!(slash_in_name[0].join("/"), slash_as_boundary[0].join("/"));
assert_ne!(
skeleton_signature(&slash_in_name, std::slice::from_ref(&identity)),
skeleton_signature(&slash_as_boundary, std::slice::from_ref(&identity))
);
let backslash = vec![vec!["Armature".into(), "Hip\\Joint".into()]];
assert_eq!(
normalized_node_segment(Some("Hip/Joint"), 1),
normalized_node_segment(Some("Hip\\Joint"), 1)
);
assert_ne!(
skeleton_signature(&slash_in_name, std::slice::from_ref(&identity)),
skeleton_signature(&backslash, std::slice::from_ref(&identity))
);
assert_eq!(bevy_node_segment(Some(" /Joint "), 7), " /Joint ");
assert_eq!(bevy_node_segment(None, 7), "GltfNode7");
}
#[test]
fn gltf_with_multiple_animation_roots_is_runtime_unsupported() {
let root =
std::env::temp_dir().join(format!("blacksite-animation-multi-root-{}", Uuid::new_v4()));
let path = write_multi_root_animated_gltf(&root);
let manifest = build_animation_manifest(&fixture_record(&path)).unwrap();
assert!(!manifest.runtime_supported);
let diagnostic = manifest
.diagnostics
.iter()
.find(|diagnostic| diagnostic.code == "animation.multiple_roots_unsupported")
.expect("multi-root glTF should include an actionable blocking diagnostic");
assert_eq!(diagnostic.severity, AnimationDiagnosticSeverity::Error);
assert!(diagnostic.message.contains("2 distinct top-level roots"));
assert!(diagnostic.repair.contains("one common top-level root"));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn animated_or_skinned_fbx_is_runtime_unsupported_with_repair_guidance() {
let (supported, diagnostics) = fbx_runtime_support(2, 1);
assert!(!supported);
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].severity, AnimationDiagnosticSeverity::Error);
assert_eq!(diagnostics[0].code, "animation.fbx_runtime_unsupported");
assert!(diagnostics[0].repair.contains("glTF 2.0"));
let (supported, diagnostics) = fbx_runtime_support(0, 0);
assert!(!supported);
assert!(diagnostics.is_empty());
}
#[test]
fn committed_robot_fixture_exposes_a_skin_and_multiple_named_states() {
let path =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/models/robot_expressive.glb");
let manifest = build_animation_manifest(&fixture_record(&path)).unwrap();
assert!(manifest.runtime_supported);
assert_eq!(manifest.skeletons.len(), 2);
assert_eq!(manifest.skeletons[0].id, "animation:skeleton:0:skeleton_0");
assert_eq!(manifest.skeletons[1].id, "animation:skeleton:1:skeleton_1");
assert!(manifest
.skeletons
.iter()
.all(|skeleton| skeleton.joint_paths.len() == 43));
let signature = &manifest.skeletons[0].signature;
assert!(manifest
.skeletons
.iter()
.all(|skeleton| &skeleton.signature == signature));
assert_eq!(manifest.clips.len(), 14);
for expected in ["Idle", "Walking", "Running", "Jump", "Wave"] {
assert!(
manifest.clips.iter().any(|clip| clip.label == expected),
"missing expected fixture clip {expected}"
);
}
assert!(manifest
.clips
.iter()
.all(|clip| clip.duration_seconds.is_finite() && clip.duration_seconds > 0.0));
assert!(manifest
.clips
.iter()
.all(|clip| { clip.target_skeleton_signature.as_ref() == Some(signature) }));
assert!(manifest.diagnostics.is_empty());
}
}
pub use content_pipeline::animation::*;
+111 -429
View File
@@ -1,277 +1,63 @@
//! Project asset registry (stable IDs + import metadata). Phase 5 foundation.
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use shared::AssetSourceFingerprint;
use std::collections::{HashMap, HashSet};
use shared::{
parse_asset_registry, AssetRegistryDocument, ProjectContentDefaults,
ASSET_REGISTRY_SCHEMA_VERSION,
};
pub use shared::{
AssetId, AssetKind, AssetRecord, ImportSettings, MaterialImportPolicy, ModelHierarchyMode,
ModelMaterialSelection, ModelMaterialSlotSelection, ModelPlacementMode,
};
use std::path::Path;
#[cfg(test)]
use uuid::Uuid;
use crate::assets::fingerprint::{fingerprint_file, write_pretty_ron_if_changed};
use crate::assets::fingerprint::fingerprint_file;
/// Stable asset identity for dependency tracking and prefab references.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct AssetId(pub Uuid);
impl AssetId {
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn as_string(&self) -> String {
self.0.to_string()
}
#[derive(Resource, Debug)]
pub struct AssetRegistry {
pub schema_version: u32,
pub defaults: ProjectContentDefaults,
pub records: Vec<AssetRecord>,
pub index_dirty: bool,
pub migration_required: bool,
}
impl Default for AssetId {
fn default() -> Self {
Self::new()
}
}
#[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,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum ModelHierarchyMode {
#[default]
SingleActor,
SourceHierarchy,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum MaterialImportPolicy {
#[default]
SourceMaterials,
AuthoringOverride,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ImportSettings {
pub scale: f32,
pub generate_collider: bool,
pub lod0_only: bool,
#[serde(default)]
pub placement_mode: ModelPlacementMode,
#[serde(default)]
pub hierarchy_mode: ModelHierarchyMode,
#[serde(default)]
pub material_policy: MaterialImportPolicy,
#[serde(default)]
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 {
impl Default for AssetRegistry {
fn default() -> Self {
Self {
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: ModelPlacementMode::default(),
hierarchy_mode: ModelHierarchyMode::default(),
material_policy: MaterialImportPolicy::default(),
static_mesh_manifest_path: None,
animation_manifest_path: None,
default_animation_clip_id: None,
schema_version: ASSET_REGISTRY_SCHEMA_VERSION,
defaults: ProjectContentDefaults::default(),
records: Vec::new(),
index_dirty: false,
migration_required: false,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AssetRecord {
pub id: AssetId,
pub path: String,
pub label: String,
pub kind_tag: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_fingerprint: Option<AssetSourceFingerprint>,
#[serde(default)]
pub import_settings: ImportSettings,
#[serde(default)]
pub dependencies: Vec<String>,
}
#[derive(Resource, Debug, Default)]
pub struct AssetRegistry {
pub records: Vec<AssetRecord>,
pub index_dirty: bool,
impl AssetRegistry {
pub fn document(&self) -> AssetRegistryDocument {
AssetRegistryDocument {
schema_version: self.schema_version,
defaults: self.defaults.clone(),
records: self.records.clone(),
}
}
}
pub struct AssetDbPlugin;
impl Plugin for AssetDbPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(load_registry())
.add_systems(Update, sync_registry_from_browser);
let registry = load_registry();
app.insert_resource(registry.defaults.clone())
.insert_resource(registry);
}
}
fn sync_registry_from_browser(
assets: Res<crate::assets::EditorAssets>,
mut registry: ResMut<AssetRegistry>,
) {
if !assets.is_changed() {
return;
}
let previous_records = std::mem::take(&mut registry.records);
let mut existing: HashMap<String, AssetRecord> = previous_records
.iter()
.cloned()
.map(|record| (record.path.clone(), record))
.collect();
let current_paths = assets
.assets
.iter()
.filter_map(|asset| asset.path.clone())
.collect::<HashSet<_>>();
let mut next_records = Vec::new();
let mut seen_paths = HashMap::new();
for asset in &assets.assets {
let Some(path) = asset.path.clone() else {
continue;
};
if path.is_empty() || seen_paths.contains_key(&path) {
continue;
}
seen_paths.insert(path.clone(), ());
let kind_tag = format!("{:?}", asset.kind);
let source_fingerprint = if imported_source_kind(&kind_tag) {
match fingerprint_file(&path) {
Ok(fingerprint) => Some(fingerprint),
Err(error) => {
warn!("Imported source fingerprint failed for {path}: {error}");
None
}
}
} else {
None
};
let mut record = if let Some(mut prior) = existing.remove(&path).or_else(|| {
source_fingerprint.as_ref().and_then(|fingerprint| {
take_uniquely_moved_import_record(
&mut existing,
&current_paths,
&kind_tag,
fingerprint,
)
})
}) {
if prior.path != path {
info!(
"Asset registry preserved imported source identity {} across move {} -> {}",
prior.id.as_string(),
prior.path,
path
);
prior.path = path.clone();
}
prior.label = asset.label.clone();
prior.kind_tag = kind_tag.clone();
prior
} else {
AssetRecord {
id: AssetId::new(),
path: path.clone(),
label: asset.label.clone(),
kind_tag: kind_tag.clone(),
source_fingerprint: None,
import_settings: ImportSettings::default(),
dependencies: Vec::new(),
}
};
if imported_source_kind(&kind_tag) {
if let Some(source_fingerprint) = source_fingerprint {
record.source_fingerprint = Some(source_fingerprint);
}
} else {
record.source_fingerprint = None;
}
if record.kind_tag == "Model" {
if let Err(error) = super::refresh_model_artifacts(&mut record) {
warn!(
"Model artifact refresh failed for {} (asset id {}): {error}",
record.path,
record.id.as_string()
);
}
}
next_records.push(record);
}
sort_registry_records(&mut next_records);
let changed = previous_records != next_records;
registry.records = next_records;
if changed {
registry.index_dirty = true;
}
if registry.index_dirty {
if let Err(error) = save_registry(&registry) {
warn!("Asset registry save failed: {error}");
} else {
registry.index_dirty = false;
}
}
}
fn imported_source_kind(kind_tag: &str) -> bool {
matches!(kind_tag, "Model" | "Texture" | "AudioClip")
}
fn sort_registry_records(records: &mut [AssetRecord]) {
records.sort_by(|left, right| left.path.cmp(&right.path));
}
fn take_uniquely_moved_import_record(
existing: &mut HashMap<String, AssetRecord>,
current_paths: &HashSet<String>,
kind_tag: &str,
fingerprint: &AssetSourceFingerprint,
) -> Option<AssetRecord> {
if !imported_source_kind(kind_tag) {
return None;
}
let candidates = existing
.iter()
.filter_map(|(old_path, record)| {
if current_paths.contains(old_path) || record.kind_tag != kind_tag {
return None;
}
recorded_source_fingerprint(record)
.is_some_and(|prior| prior == *fingerprint)
.then(|| old_path.clone())
})
.collect::<Vec<_>>();
if candidates.len() != 1 {
return None;
}
existing.remove(&candidates[0])
}
fn recorded_source_fingerprint(record: &AssetRecord) -> Option<AssetSourceFingerprint> {
record.source_fingerprint.clone().or_else(|| {
let manifest_path = record.import_settings.animation_manifest_path.as_deref()?;
super::animation::load_animation_manifest(manifest_path)
.ok()
.map(|manifest| manifest.source.fingerprint)
})
fn imported_source_kind(kind: AssetKind) -> bool {
kind.is_imported_source()
}
pub fn find_asset_by_path(registry: &AssetRegistry, path: &str) -> Option<AssetRecord> {
@@ -305,27 +91,37 @@ pub fn ensure_asset_record(
path: impl Into<String>,
label: impl Into<String>,
kind_tag: impl Into<String>,
) -> Result<AssetRecord, String> {
ensure_asset_record_at(registry, Path::new("."), path, label, kind_tag)
}
pub fn ensure_asset_record_at(
registry: &mut AssetRegistry,
project_root: &Path,
path: impl Into<String>,
label: impl Into<String>,
kind_tag: impl Into<String>,
) -> Result<AssetRecord, String> {
let path = path.into();
if let Some(record) = find_asset_by_path(registry, &path) {
return Ok(record);
}
let kind_tag = kind_tag.into();
let source_fingerprint = imported_source_kind(&kind_tag)
.then(|| fingerprint_file(&path).ok())
let kind = AssetKind::from_legacy_tag(&kind_tag.into());
let source_fingerprint = imported_source_kind(kind)
.then(|| fingerprint_file(project_root.join(&path)).ok())
.flatten();
let record = AssetRecord {
id: AssetId::new(),
id: shared::AssetId::new(),
path,
label: label.into(),
kind_tag,
kind,
source_fingerprint,
import_settings: ImportSettings::default(),
import_settings: shared::AssetImportSettings::for_kind(kind),
dependencies: Vec::new(),
};
registry.records.push(record.clone());
registry.index_dirty = true;
if let Err(error) = save_registry(registry) {
if let Err(error) = save_registry_at(registry, project_root) {
registry.records.pop();
return Err(error);
}
@@ -345,10 +141,10 @@ pub fn update_import_settings(
else {
return false;
};
if record.import_settings == settings {
if record.import_settings.model() == Some(&settings) {
return false;
}
record.import_settings = settings;
record.import_settings = settings.into();
registry.index_dirty = true;
true
}
@@ -358,19 +154,29 @@ pub fn registry_index_path() -> &'static str {
}
pub fn save_registry(registry: &AssetRegistry) -> Result<(), String> {
write_pretty_ron_if_changed(registry_index_path(), &registry.records).map(|_| ())
save_registry_at(registry, Path::new("."))
}
pub fn save_registry_at(registry: &AssetRegistry, project_root: &Path) -> Result<(), String> {
content_pipeline::publish_content_documents(project_root, &registry.document())
}
pub fn load_registry() -> AssetRegistry {
let path = registry_index_path();
match std::fs::read_to_string(path) {
Ok(text) => {
let records: Vec<AssetRecord> = ron::from_str(&text).unwrap_or_default();
AssetRegistry {
records,
Ok(text) => match parse_asset_registry(&text) {
Ok(loaded) => AssetRegistry {
schema_version: loaded.document.schema_version,
defaults: loaded.document.defaults,
records: loaded.document.records,
index_dirty: false,
migration_required: loaded.migration_required,
},
Err(error) => {
warn!("Asset registry load failed: {error}");
AssetRegistry::default()
}
}
},
Err(_) => AssetRegistry::default(),
}
}
@@ -378,188 +184,64 @@ pub fn load_registry() -> AssetRegistry {
#[cfg(test)]
mod tests {
use super::*;
use shared::{
AnimationManifest, AnimationManifestSource, AnimationSourceFingerprint,
ANIMATION_MANIFEST_SCHEMA_VERSION,
};
#[test]
fn imported_source_policy_covers_model_texture_and_audio_only() {
for kind in ["Model", "Texture", "AudioClip"] {
assert!(imported_source_kind(kind), "missing imported kind {kind}");
for kind in [AssetKind::Model, AssetKind::Texture, AssetKind::AudioClip] {
assert!(imported_source_kind(kind), "missing imported kind {kind:?}");
}
for kind in ["Material", "Level", "Prefab", "PostProcessEffect"] {
for kind in [
AssetKind::Material,
AssetKind::Level,
AssetKind::Prefab,
AssetKind::PostProcessEffect,
] {
assert!(
!imported_source_kind(kind),
"authored kind {kind} was hashed"
"authored kind {kind:?} was hashed"
);
}
}
#[test]
fn registry_publication_order_is_stable_across_discovery_orders() {
let records = [
("assets/textures/z.png", "Texture"),
("assets/audio/a.ogg", "AudioClip"),
("assets/models/m.glb", "Model"),
]
.into_iter()
.map(|(path, kind_tag)| AssetRecord {
id: AssetId::new(),
path: path.into(),
label: path.into(),
kind_tag: kind_tag.into(),
source_fingerprint: None,
import_settings: ImportSettings::default(),
dependencies: Vec::new(),
})
.collect::<Vec<_>>();
let mut forward = records.clone();
let mut reverse = records.into_iter().rev().collect::<Vec<_>>();
sort_registry_records(&mut forward);
sort_registry_records(&mut reverse);
assert_eq!(forward, reverse);
fn shared_classification_preserves_schema_classified_material_instance_kind() {
let root = std::env::temp_dir().join(format!(
"blacksite-browser-material-instance-{}",
uuid::Uuid::new_v4()
));
std::fs::create_dir_all(&root).unwrap();
let path = root.join("user_named_variant.ron");
let instance = shared::MaterialInstanceAsset {
schema_version: shared::MATERIAL_INSTANCE_SCHEMA_VERSION,
label: "User Named Variant".into(),
base: shared::MaterialRef::new(shared::EditorAssetRef::new(
"base-id",
"material:source",
"Base",
)),
overrides: shared::MaterialInputSet::default(),
};
std::fs::write(&path, ron::ser::to_string(&instance).unwrap()).unwrap();
assert_eq!(
forward
.iter()
.map(|record| record.path.as_str())
.collect::<Vec<_>>(),
[
"assets/audio/a.ogg",
"assets/models/m.glb",
"assets/textures/z.png",
]
content_pipeline::classify_asset_file(&path),
AssetKind::MaterialInstance
);
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn legacy_registry_record_loads_without_forcing_a_new_identity() {
let source = r#"(
id: ("00000000-0000-0000-0000-000000000000"),
path: "assets/textures/legacy.png",
label: "Legacy",
kind_tag: "Texture",
)"#;
let record: AssetRecord = ron::from_str(source).unwrap();
let source = r#"[(id:("00000000-0000-0000-0000-000000000000"),path:"assets/textures/legacy.png",label:"Legacy",kind_tag:"Texture")]"#;
let loaded = parse_asset_registry(source).unwrap();
let record = &loaded.document.records[0];
assert_eq!(record.id, AssetId(Uuid::nil()));
assert!(record.source_fingerprint.is_none());
assert_eq!(record.import_settings, ImportSettings::default());
}
#[test]
fn content_match_preserves_every_imported_source_kind_across_move() {
let fingerprint = AssetSourceFingerprint::from_bytes(b"stable imported bytes");
for kind in ["Model", "Texture", "AudioClip"] {
let record = AssetRecord {
id: AssetId::new(),
path: format!("assets/old/{kind}"),
label: kind.into(),
kind_tag: kind.into(),
source_fingerprint: Some(fingerprint.clone()),
import_settings: ImportSettings::default(),
dependencies: Vec::new(),
};
let expected_id = record.id.clone();
let mut existing = HashMap::from([(record.path.clone(), record)]);
let moved = take_uniquely_moved_import_record(
&mut existing,
&HashSet::new(),
kind,
&fingerprint,
)
.expect("unique content identity should preserve the record");
assert_eq!(moved.id, expected_id);
assert!(existing.is_empty());
}
}
fn moved_model_fixture(bytes: &[u8]) -> (std::path::PathBuf, std::path::PathBuf, AssetRecord) {
let key = Uuid::new_v4();
let source_path = std::env::temp_dir().join(format!("blacksite-moved-model-{key}.glb"));
let manifest_path =
std::env::temp_dir().join(format!("blacksite-moved-model-{key}.animation.ron"));
std::fs::write(&source_path, bytes).unwrap();
let id = AssetId::new();
let old_path = format!("assets/models/old-{key}.glb");
let manifest = AnimationManifest {
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(),
fingerprint: AnimationSourceFingerprint {
byte_len: bytes.len() as u64,
content_hash: blake3::hash(bytes).to_hex().to_string(),
},
dependencies: Vec::new(),
},
runtime_supported: true,
skeletons: Vec::new(),
clips: 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,
path: old_path,
label: "Moved Model".into(),
kind_tag: "Model".into(),
source_fingerprint: None,
import_settings: ImportSettings {
animation_manifest_path: Some(manifest_path.to_string_lossy().into_owned()),
..Default::default()
},
dependencies: Vec::new(),
};
(source_path, manifest_path, record)
}
#[test]
fn unique_content_match_preserves_model_record_across_move() {
let (source_path, manifest_path, record) = moved_model_fixture(b"stable model bytes");
let expected_id = record.id.clone();
let mut existing = HashMap::from([(record.path.clone(), record)]);
let fingerprint = fingerprint_file(&source_path).unwrap();
let moved = take_uniquely_moved_import_record(
&mut existing,
&HashSet::new(),
"Model",
&fingerprint,
)
.expect("unique moved model should retain its registry record");
assert_eq!(moved.id, expected_id);
assert!(existing.is_empty());
let _ = std::fs::remove_file(source_path);
let _ = std::fs::remove_file(manifest_path);
}
#[test]
fn existing_source_path_is_not_reconciled_as_a_copy_move() {
let (source_path, manifest_path, record) = moved_model_fixture(b"copied model bytes");
let old_path = record.path.clone();
let mut existing = HashMap::from([(old_path.clone(), record)]);
let current_paths = HashSet::from([old_path]);
let fingerprint = fingerprint_file(&source_path).unwrap();
let moved =
take_uniquely_moved_import_record(&mut existing, &current_paths, "Model", &fingerprint);
assert!(moved.is_none());
assert_eq!(existing.len(), 1);
let _ = std::fs::remove_file(source_path);
let _ = std::fs::remove_file(manifest_path);
assert_eq!(
record.import_settings,
shared::AssetImportSettings::for_kind(AssetKind::Texture)
);
assert_eq!(record.kind, AssetKind::Texture);
assert!(loaded.migration_required);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,548 @@
use super::*;
#[derive(Resource)]
pub(super) struct EditorContentWatch {
root: PathBuf,
service: Mutex<Option<content_pipeline::ContentWatchService>>,
}
#[derive(Resource, Default)]
pub(super) struct ExternalContentRefreshQueue {
active: Option<ExternalContentRefreshJob>,
pending: Option<PendingExternalContentRefresh>,
}
pub(super) struct ExternalContentRefreshJob {
handle: std::thread::JoinHandle<Result<(shared::AssetRegistryDocument, String), String>>,
}
pub(super) struct PendingExternalContentRefresh {
root: PathBuf,
changed_path_count: usize,
status_prefix: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ExternalMoveRepairChoice {
Preserve(String),
RegisterNew,
}
#[derive(Debug, Clone)]
pub(crate) struct ExternalMoveRepairReview {
pub(crate) root: PathBuf,
pub(crate) previous: shared::AssetRegistryDocument,
pub(crate) conflicts: Vec<content_pipeline::ExternalMoveConflict>,
pub(crate) choices: Vec<Option<ExternalMoveRepairChoice>>,
pub(crate) open: bool,
}
#[derive(Resource, Debug, Default, Clone)]
pub(crate) struct PendingExternalMoveRepair {
pub(crate) review: Option<ExternalMoveRepairReview>,
}
impl Plugin for EditorAssetsPlugin {
fn build(&self, app: &mut App) {
let root = PathBuf::from(
&app.world()
.resource::<crate::project_io::ProjectWorkspace>()
.root,
);
let service = match content_pipeline::ContentWatchService::watch_project(&root) {
Ok(service) => Some(service),
Err(error) => {
warn!("Live content watching is unavailable: {error}");
None
}
};
app.init_resource::<EditorAssets>()
.init_resource::<PendingExternalMoveRepair>()
.init_resource::<ExternalContentRefreshQueue>()
.insert_resource(EditorContentWatch {
root,
service: Mutex::new(service),
})
.init_resource::<crate::assets::prefab_overrides::PrefabHealthCache>()
.add_observer(crate::assets::prefab_overrides::invalidate_prefab_health_on_ready)
.add_systems(
Update,
(
refresh_assets_on_settings_change,
crate::assets::prefab_overrides::guard_prefab_reimports,
),
)
.add_systems(Startup, refresh_content_on_startup)
.add_systems(
Update,
(poll_content_watcher, drive_external_content_refresh).chain(),
);
}
}
pub(crate) fn begin_content_watch_transaction(world: &World) {
let Some(watcher) = world.get_resource::<EditorContentWatch>() else {
return;
};
if let Ok(mut service) = watcher.service.lock() {
if let Some(service) = service.as_mut() {
service.begin_transaction();
}
}
}
pub(crate) fn end_content_watch_transaction(world: &World) {
let Some(watcher) = world.get_resource::<EditorContentWatch>() else {
return;
};
if let Ok(mut service) = watcher.service.lock() {
if let Some(service) = service.as_mut() {
service.end_transaction();
}
}
}
pub(crate) fn suppress_content_watch_path(world: &World, path: &Path) {
let Some(watcher) = world.get_resource::<EditorContentWatch>() else {
return;
};
if let Ok(mut service) = watcher.service.lock() {
if let Some(service) = service.as_mut() {
service.suppress_path(path, Duration::from_millis(750));
}
}
}
pub(super) fn poll_content_watcher(world: &mut World) {
let Some(watcher) = world.get_resource::<EditorContentWatch>() else {
return;
};
let root = watcher.root.clone();
let changes = {
let Ok(mut service) = watcher.service.lock() else {
return;
};
let Some(service) = service.as_mut() else {
return;
};
match service.poll(Duration::from_millis(150)) {
Ok(changes) => changes,
Err(error) => {
warn!("Content watcher failed: {error}");
return;
}
}
};
if changes.is_empty() {
return;
}
if let Some(mut cache) = world.get_resource_mut::<blacksite_surface::SurfaceMaterialCache>() {
cache.invalidate_disk_documents();
}
if let Err(error) =
process_or_queue_content_refresh(world, root, changes.len(), "Live content refresh")
{
world.resource_mut::<crate::scene_io::SceneIo>().status =
format!("Live content refresh failed: {error}");
}
}
pub(super) fn refresh_content_on_startup(world: &mut World) {
let root = world
.get_resource::<crate::project_io::ProjectWorkspace>()
.map(|workspace| PathBuf::from(&workspace.root))
.unwrap_or_else(|| PathBuf::from("."));
if let Err(error) = process_or_queue_content_refresh(world, root, 0, "Startup content refresh")
{
warn!("Startup content refresh failed: {error}");
}
}
pub(super) fn process_or_queue_content_refresh(
world: &mut World,
root: PathBuf,
changed_path_count: usize,
status_prefix: &str,
) -> Result<(), String> {
let previous = world.resource::<AssetRegistry>().document();
if queue_external_move_repair(world, root.clone(), previous.clone())? {
world.resource_mut::<EditorAssets>().refresh();
crate::assets::invalidate_on_catalog_refresh(world);
return Ok(());
}
let mut queue = world.resource_mut::<ExternalContentRefreshQueue>();
if queue.active.is_some() {
let pending = queue
.pending
.get_or_insert_with(|| PendingExternalContentRefresh {
root: root.clone(),
changed_path_count: 0,
status_prefix: status_prefix.to_string(),
});
pending.root = root;
pending.changed_path_count = pending
.changed_path_count
.saturating_add(changed_path_count);
pending.status_prefix = status_prefix.to_string();
return Ok(());
}
let status_prefix = status_prefix.to_string();
let handle = std::thread::spawn(move || {
process_content_refresh(&root, &previous, changed_path_count, &status_prefix)
});
queue.active = Some(ExternalContentRefreshJob { handle });
Ok(())
}
pub(super) fn drive_external_content_refresh(world: &mut World) {
let completed = {
let mut queue = world.resource_mut::<ExternalContentRefreshQueue>();
if queue
.active
.as_ref()
.is_some_and(|job| job.handle.is_finished())
{
queue.active.take()
} else {
None
}
};
let Some(job) = completed else {
return;
};
match job
.handle
.join()
.unwrap_or_else(|_| Err("content refresh worker panicked".into()))
{
Ok((document, status)) => {
apply_processed_content(world, document);
if let Some(mut scene_io) = world.get_resource_mut::<crate::scene_io::SceneIo>() {
scene_io.status = status;
}
}
Err(error) => {
if let Some(mut scene_io) = world.get_resource_mut::<crate::scene_io::SceneIo>() {
scene_io.status = format!("Content refresh failed: {error}");
}
}
}
let pending = world
.resource_mut::<ExternalContentRefreshQueue>()
.pending
.take();
if let Some(pending) = pending {
let _ = process_or_queue_content_refresh(
world,
pending.root,
pending.changed_path_count,
&pending.status_prefix,
);
}
}
#[cfg(test)]
pub(super) fn process_content_refresh_for_test(
world: &mut World,
root: PathBuf,
) -> Result<(), String> {
world.init_resource::<ExternalContentRefreshQueue>();
process_or_queue_content_refresh(world, root, 0, "Startup content refresh")?;
for _ in 0..1_000 {
drive_external_content_refresh(world);
let queue = world.resource::<ExternalContentRefreshQueue>();
if queue.active.is_none() && queue.pending.is_none() {
return Ok(());
}
std::thread::sleep(std::time::Duration::from_millis(1));
}
Err("content refresh worker did not finish within one second".into())
}
pub(super) fn queue_external_move_repair(
world: &mut World,
root: PathBuf,
previous: shared::AssetRegistryDocument,
) -> Result<bool, String> {
let conflicts = content_pipeline::find_ambiguous_external_moves(&root, &previous)?;
if conflicts.is_empty() {
return Ok(false);
}
let count = conflicts.len();
world.resource_mut::<PendingExternalMoveRepair>().review = Some(ExternalMoveRepairReview {
root,
previous,
choices: vec![None; count],
conflicts,
open: true,
});
if let Some(mut scene_io) = world.get_resource_mut::<crate::scene_io::SceneIo>() {
scene_io.status = format!(
"{count} ambiguous external move(s) require identity repair in the Content Browser"
);
}
Ok(true)
}
pub(crate) fn refresh_content_browser(world: &mut World) {
let root = world
.get_resource::<crate::project_io::ProjectWorkspace>()
.map(|workspace| PathBuf::from(&workspace.root))
.unwrap_or_else(|| PathBuf::from("."));
match process_or_queue_content_refresh(world, root, 0, "Manual content refresh") {
Ok(()) => {}
Err(error) => {
if let Some(mut scene_io) = world.get_resource_mut::<crate::scene_io::SceneIo>() {
scene_io.status = format!("Manual content refresh failed: {error}");
}
}
}
}
pub(super) fn process_content_refresh(
root: &Path,
previous: &shared::AssetRegistryDocument,
changed_path_count: usize,
status_prefix: &str,
) -> Result<(shared::AssetRegistryDocument, String), String> {
let mut processed = content_pipeline::scan_project(root, previous)?;
let current_ids = processed
.registry
.records
.iter()
.map(|record| record.id.as_string())
.collect::<HashSet<_>>();
let removed_paths = previous
.records
.iter()
.filter(|record| !current_ids.contains(&record.id.as_string()))
.map(|record| PathBuf::from(&record.path))
.collect::<Vec<_>>();
let removed_usages = if removed_paths.is_empty() {
Vec::new()
} else {
content_pipeline::find_reference_usages(root, &removed_paths, previous)
.map_err(|error| format!("could not inspect removed-asset usages: {error}"))?
};
let mut model_plans = Vec::new();
for record in processed
.registry
.records
.iter_mut()
.filter(|record| record.kind == shared::AssetKind::Model)
{
let plan = crate::assets::plan_model_artifacts_at(root, record)
.map_err(|error| format!("model processing failed for {}: {error}", record.path))?;
*record = plan.record.clone();
model_plans.push(plan);
}
processed.runtime_catalog = shared::RuntimeContentCatalog::from(&processed.registry);
let mut texture_plans = Vec::new();
for record in processed
.registry
.records
.iter()
.filter(|record| record.kind == shared::AssetKind::Texture)
{
let plan = content_pipeline::plan_texture_artifact(root, record)
.map_err(|error| format!("Texture processing failed for {}: {error}", record.path))?;
content_pipeline::apply_texture_plan_to_catalog(
&mut processed.runtime_catalog,
&record.id,
&plan,
)?;
texture_plans.push(plan);
}
let mut material_plans = Vec::new();
for record in processed.registry.records.iter().filter(|record| {
matches!(
record.kind,
shared::AssetKind::Material | shared::AssetKind::MaterialInstance
)
}) {
if let Some(plan) =
content_pipeline::plan_material_artifact(root, record, &processed.registry)?
{
content_pipeline::apply_material_plan_to_catalog(
&mut processed.runtime_catalog,
&record.id,
&plan,
)?;
material_plans.push(plan);
}
}
let mut publication_paths = model_plans
.iter()
.flat_map(|plan| [plan.static_path.clone(), plan.animation_path.clone()])
.collect::<Vec<_>>();
publication_paths.extend(texture_plans.iter().map(|plan| plan.output_path.clone()));
publication_paths.extend(material_plans.iter().map(|plan| plan.output_path.clone()));
publication_paths.push(root.join(content_pipeline::REGISTRY_PATH));
publication_paths.push(root.join(content_pipeline::RUNTIME_CATALOG_PATH));
publication_paths.sort();
publication_paths.dedup();
let backups = publication_paths
.iter()
.map(|path| (path.clone(), fs::read(path).ok()))
.collect::<Vec<_>>();
let publication = (|| {
for plan in &model_plans {
crate::assets::publish_model_artifacts(plan)?;
}
for plan in &texture_plans {
content_pipeline::publish_texture_artifact(plan)?;
}
for plan in &material_plans {
content_pipeline::publish_material_artifact(plan)?;
}
content_pipeline::publish_content_documents_with_catalog(
root,
&processed.registry,
&processed.runtime_catalog,
)
})();
if let Err(error) = publication {
for (path, bytes) in &backups {
if let Some(bytes) = bytes {
let _ = fs::write(path, bytes);
} else {
let _ = fs::remove_file(path);
}
}
return Err(format!("content publication rolled back: {error}"));
}
let mut status = format!(
"{status_prefix}: {changed_path_count} changed path(s), {} model artifact set(s), {} Texture artifact(s), {} packed Material artifact(s), {} added, {} moved, {} removed",
model_plans.len(),
texture_plans.len(),
material_plans.len(),
processed.report.added,
processed.report.moved,
processed.report.removed
);
if !removed_usages.is_empty() {
let documents = removed_usages
.iter()
.map(|usage| usage.document.display().to_string())
.collect::<BTreeSet<_>>()
.into_iter()
.take(3)
.collect::<Vec<_>>()
.join(", ");
status.push_str(&format!(
"; {} reference(s) now unresolved in {}",
removed_usages.len(),
documents
));
}
Ok((processed.registry, status))
}
pub(super) fn apply_processed_content(world: &mut World, document: shared::AssetRegistryDocument) {
if world.contains_resource::<crate::asset_documents::AuthoredAssetDocumentStore>() {
crate::asset_documents::adopt_external_registry_document(world, &document);
} else {
let mut registry = world.resource_mut::<AssetRegistry>();
registry.schema_version = document.schema_version;
registry.defaults = document.defaults;
registry.records = document.records;
registry.index_dirty = false;
registry.migration_required = false;
}
world.resource_mut::<EditorAssets>().refresh();
crate::assets::invalidate_on_catalog_refresh(world);
}
pub(crate) fn commit_external_move_repairs(world: &mut World) -> Result<(), String> {
let review = world
.resource::<PendingExternalMoveRepair>()
.review
.clone()
.ok_or_else(|| "no external move repair is pending".to_string())?;
if review.choices.iter().any(Option::is_none) {
return Err("choose an identity for every ambiguous external move".into());
}
let current_registry = world.resource::<AssetRegistry>().document();
if current_registry != review.previous {
return Err("asset registry changed after the external move review opened".into());
}
let current_conflicts =
content_pipeline::find_ambiguous_external_moves(&review.root, &review.previous)?;
if current_conflicts != review.conflicts {
let count = current_conflicts.len();
world.resource_mut::<PendingExternalMoveRepair>().review = (!current_conflicts.is_empty())
.then(|| ExternalMoveRepairReview {
root: review.root,
previous: current_registry,
choices: vec![None; count],
conflicts: current_conflicts,
open: true,
});
return Err("external files changed after review; inspect the refreshed conflicts".into());
}
let repaired = registry_after_external_move_repairs(&review)?;
let (document, status) =
process_content_refresh(&review.root, &repaired, 0, "External move repair")?;
apply_processed_content(world, document);
world.resource_mut::<PendingExternalMoveRepair>().review = None;
world.resource_mut::<crate::scene_io::SceneIo>().status = status;
Ok(())
}
pub(super) fn registry_after_external_move_repairs(
review: &ExternalMoveRepairReview,
) -> Result<shared::AssetRegistryDocument, String> {
if review.choices.len() != review.conflicts.len() || review.choices.iter().any(Option::is_none)
{
return Err("choose an identity for every ambiguous external move".into());
}
let mut repaired = review.previous.clone();
let mut preserved = HashSet::new();
for (conflict, choice) in review.conflicts.iter().zip(review.choices.iter()) {
if let Some(ExternalMoveRepairChoice::Preserve(old_path)) = choice {
if !conflict.candidate_paths.contains(old_path) {
return Err(format!(
"selected identity {old_path} is not a candidate for {}",
conflict.new_path
));
}
if !preserved.insert(old_path.clone()) {
return Err(format!(
"stable identity {old_path} cannot be assigned to more than one new path"
));
}
let record = repaired
.records
.iter_mut()
.find(|record| record.path == *old_path)
.ok_or_else(|| format!("candidate registry record disappeared: {old_path}"))?;
record.path.clone_from(&conflict.new_path);
}
}
let candidate_paths = review
.conflicts
.iter()
.flat_map(|conflict| conflict.candidate_paths.iter())
.cloned()
.collect::<HashSet<_>>();
for record in &mut repaired.records {
if candidate_paths.contains(&record.path) && !preserved.contains(&record.path) {
record.source_fingerprint = None;
}
}
Ok(repaired)
}
pub(super) fn refresh_assets_on_settings_change(
settings: Res<settings::ProjectSettings>,
mut assets: ResMut<EditorAssets>,
) {
if settings.is_changed() {
assets.refresh();
}
}
+2 -113
View File
@@ -1,114 +1,3 @@
use std::fs;
use std::path::Path;
//! Compatibility re-exports for the shared content-pipeline fingerprint helpers.
use serde::de::DeserializeOwned;
use serde::Serialize;
use shared::AssetSourceFingerprint;
pub(crate) fn fingerprint_file(path: impl AsRef<Path>) -> Result<AssetSourceFingerprint, String> {
let path = path.as_ref();
let bytes = fs::read(path)
.map_err(|error| format!("could not read imported source {}: {error}", path.display()))?;
Ok(AssetSourceFingerprint::from_bytes(&bytes))
}
/// Writes canonical pretty RON only when the parsed document changes semantically.
///
/// Equivalent existing bytes, including custom formatting and final-newline policy, stay intact.
pub(crate) fn write_pretty_ron_if_changed<T>(
path: impl AsRef<Path>,
value: &T,
) -> Result<bool, String>
where
T: DeserializeOwned + PartialEq + Serialize,
{
let path = path.as_ref();
if fs::read_to_string(path)
.ok()
.and_then(|text| ron::from_str::<T>(&text).ok())
.is_some_and(|existing| existing == *value)
{
return Ok(false);
}
let text = ron::ser::to_string_pretty(value, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize RON: {error}"))?;
if fs::read(path).ok().as_deref() == Some(text.as_bytes()) {
return Ok(false);
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
}
fs::write(path, text)
.map_err(|error| format!("could not write {}: {error}", path.display()))?;
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
use std::fs::{File, FileTimes};
use std::time::{Duration, SystemTime};
use uuid::Uuid;
#[derive(Debug, Deserialize, PartialEq, Serialize)]
struct Fixture {
count: u32,
label: String,
}
fn fixture_path(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!(
"blacksite-fingerprint-{name}-{}.ron",
Uuid::new_v4()
))
}
#[test]
fn metadata_only_drift_does_not_change_content_identity() {
let path = fixture_path("mtime");
fs::write(&path, b"stable source bytes").unwrap();
let before = fingerprint_file(&path).unwrap();
File::options()
.write(true)
.open(&path)
.unwrap()
.set_times(
FileTimes::new().set_modified(SystemTime::now() + Duration::from_secs(86_400)),
)
.unwrap();
assert_eq!(fingerprint_file(&path).unwrap(), before);
fs::remove_file(path).unwrap();
}
#[test]
fn same_size_byte_change_updates_content_identity() {
let path = fixture_path("same-size");
fs::write(&path, b"source-a").unwrap();
let before = fingerprint_file(&path).unwrap();
fs::write(&path, b"source-b").unwrap();
let after = fingerprint_file(&path).unwrap();
assert_eq!(before.byte_len, after.byte_len);
assert_ne!(before.content_hash, after.content_hash);
fs::remove_file(path).unwrap();
}
#[test]
fn equivalent_ron_preserves_exact_existing_bytes() {
let path = fixture_path("semantic");
let existing = b"( label: \"stable\", count: 7, )\n\n";
fs::write(&path, existing).unwrap();
let value = Fixture {
count: 7,
label: "stable".into(),
};
assert!(!write_pretty_ron_if_changed(&path, &value).unwrap());
assert_eq!(fs::read(&path).unwrap(), existing);
fs::remove_file(path).unwrap();
}
}
pub(crate) use content_pipeline::fingerprint_file;
+6 -563
View File
@@ -1,564 +1,7 @@
//! External asset bundle inspection and transactional import.
//! Editor-facing re-exports of the shared UI-independent content importer.
use std::collections::BTreeMap;
use std::fs;
use std::path::{Component, Path, PathBuf};
use bevy_ufbx::texture::external_texture_paths;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FbxDependencyInspection {
pub relative_paths: Vec<String>,
pub resolved_paths: Vec<PathBuf>,
pub missing_paths: Vec<PathBuf>,
}
/// Parses every external FBX texture reference without loading it through Bevy.
pub(crate) fn inspect_fbx_dependencies(source: &Path) -> Result<FbxDependencyInspection, String> {
let bytes = fs::read(source)
.map_err(|error| format!("could not read FBX {}: {error}", source.display()))?;
let filename_hint = source.to_string_lossy();
let scene = ufbx::load_memory(
&bytes,
ufbx::LoadOpts {
target_unit_meters: 1.0,
target_axes: ufbx::CoordinateAxes::right_handed_y_up(),
filename: ufbx::StringOpt::Ref(&filename_hint),
..Default::default()
},
)
.map_err(|error| format!("could not parse FBX {}: {error:?}", source.display()))?;
let relative_paths = external_texture_paths(&scene).map_err(|errors| {
format!(
"unsafe FBX texture reference(s) in {}: {}",
source.display(),
errors
.into_iter()
.map(|error| error.to_string())
.collect::<Vec<_>>()
.join("; ")
)
})?;
let source_root = source.parent().unwrap_or_else(|| Path::new(""));
let canonical_root = fs::canonicalize(source_root).map_err(|error| {
format!(
"could not resolve FBX source directory {}: {error}",
source_root.display()
)
})?;
let mut resolved_paths = Vec::new();
let mut missing_paths = Vec::new();
for relative_path in &relative_paths {
let resolved = source_root.join(relative_path);
if !resolved.is_file() {
missing_paths.push(resolved.clone());
resolved_paths.push(resolved);
continue;
}
let canonical = fs::canonicalize(&resolved).map_err(|error| {
format!(
"could not resolve FBX dependency {}: {error}",
resolved.display()
)
})?;
if !canonical.starts_with(&canonical_root) {
return Err(format!(
"FBX dependency {} resolves outside source directory {}",
resolved.display(),
source_root.display()
));
}
resolved_paths.push(resolved);
}
missing_paths.sort();
Ok(FbxDependencyInspection {
relative_paths,
resolved_paths,
missing_paths,
})
}
/// Returns one stable browser-facing error for all missing FBX source textures.
pub(crate) fn validate_fbx_dependencies(source: &Path) -> Result<(), String> {
let inspection = inspect_fbx_dependencies(source)?;
if inspection.missing_paths.is_empty() {
return Ok(());
}
Err(format!(
"missing {} FBX source texture(s): {}",
inspection.missing_paths.len(),
inspection
.missing_paths
.iter()
.map(|path| path.to_string_lossy().replace('\\', "/"))
.collect::<Vec<_>>()
.join(", ")
))
}
/// Copies an FBX and every referenced external texture as one staged filesystem transaction.
pub fn copy_fbx_bundle(source: &Path, dest_dir: &Path) -> Result<(), String> {
let inspection = inspect_fbx_dependencies(source)?;
if !inspection.missing_paths.is_empty() {
return Err(format!(
"FBX import is missing {} required texture(s): {}",
inspection.missing_paths.len(),
inspection
.missing_paths
.iter()
.map(|path| path.display().to_string())
.collect::<Vec<_>>()
.join(", ")
));
}
let file_name = source
.file_name()
.ok_or_else(|| "FBX import path has no file name".to_string())?;
let mut entries = BTreeMap::new();
entries.insert(PathBuf::from(file_name), source.to_path_buf());
for (relative, resolved) in inspection
.relative_paths
.iter()
.zip(inspection.resolved_paths.iter())
{
let relative = PathBuf::from(relative);
if let Some(existing) = entries.insert(relative.clone(), resolved.clone()) {
if existing != *resolved {
return Err(format!(
"FBX import maps multiple source files to {}",
relative.display()
));
}
}
}
copy_bundle_transactionally(&entries, dest_dir)
}
fn copy_bundle_transactionally(
entries: &BTreeMap<PathBuf, PathBuf>,
dest_dir: &Path,
) -> Result<(), String> {
fs::create_dir_all(dest_dir)
.map_err(|error| format!("could not create {}: {error}", dest_dir.display()))?;
let canonical_dest_dir = fs::canonicalize(dest_dir).map_err(|error| {
format!(
"could not resolve FBX import destination {}: {error}",
dest_dir.display()
)
})?;
for relative in entries.keys() {
validate_bundle_relative_path(relative)?;
validate_existing_destination_parents(dest_dir, &canonical_dest_dir, relative)?;
let target = dest_dir.join(relative);
if target.is_dir() {
return Err(format!(
"FBX import target {} is an existing directory",
target.display()
));
}
}
let stage_root = dest_dir.join(format!(".blacksite-import-{}", uuid::Uuid::new_v4()));
let staged_root = stage_root.join("new");
let backup_root = stage_root.join("backup");
let stage_result = (|| {
for (relative, source) in entries {
let staged = staged_root.join(relative);
if let Some(parent) = staged.parent() {
fs::create_dir_all(parent).map_err(|error| {
format!(
"could not create import staging {}: {error}",
parent.display()
)
})?;
}
fs::copy(source, &staged).map_err(|error| {
format!(
"could not stage FBX bundle file {} as {}: {error}",
source.display(),
relative.display()
)
})?;
}
commit_staged_bundle(
entries,
dest_dir,
&canonical_dest_dir,
&staged_root,
&backup_root,
)
})();
let cleanup_result = fs::remove_dir_all(&stage_root);
match (stage_result, cleanup_result) {
(Err(error), _) => Err(error),
(Ok(()), Ok(())) => Ok(()),
(Ok(()), Err(error)) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
(Ok(()), Err(error)) => {
bevy::log::warn!(
"FBX bundle imported but staging cleanup failed for {}: {error}",
stage_root.display()
);
Ok(())
}
}
}
fn validate_bundle_relative_path(relative: &Path) -> Result<(), String> {
if relative.as_os_str().is_empty()
|| !relative
.components()
.all(|component| matches!(component, Component::Normal(_)))
{
return Err(format!(
"FBX import target path {} is not a safe relative path",
relative.display()
));
}
Ok(())
}
fn validate_existing_destination_parents(
dest_dir: &Path,
canonical_dest_dir: &Path,
relative: &Path,
) -> Result<(), String> {
let mut current = dest_dir.to_path_buf();
let Some(parent) = relative.parent() else {
return Ok(());
};
for component in parent.components() {
let Component::Normal(segment) = component else {
return Err(format!(
"FBX import target path {} is not a safe relative path",
relative.display()
));
};
current.push(segment);
let metadata = match fs::symlink_metadata(&current) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => break,
Err(error) => {
return Err(format!(
"could not inspect FBX import target {}: {error}",
current.display()
));
}
};
if metadata.file_type().is_symlink() {
return Err(format!(
"FBX import target parent {} is a symbolic link",
current.display()
));
}
if !metadata.is_dir() {
return Err(format!(
"FBX import target parent {} is not a directory",
current.display()
));
}
let canonical = fs::canonicalize(&current).map_err(|error| {
format!(
"could not resolve FBX import target parent {}: {error}",
current.display()
)
})?;
if !canonical.starts_with(canonical_dest_dir) {
return Err(format!(
"FBX import target parent {} resolves outside destination {}",
current.display(),
dest_dir.display()
));
}
}
Ok(())
}
fn commit_staged_bundle(
entries: &BTreeMap<PathBuf, PathBuf>,
dest_dir: &Path,
canonical_dest_dir: &Path,
staged_root: &Path,
backup_root: &Path,
) -> Result<(), String> {
let mut installed = Vec::new();
let mut backups = Vec::new();
for relative in entries.keys() {
let target = dest_dir.join(relative);
let staged = staged_root.join(relative);
if let Some(parent) = target.parent() {
if let Err(error) = fs::create_dir_all(parent) {
return rollback_bundle(
&installed,
&backups,
format!(
"could not create import target {}: {error}",
parent.display()
),
);
}
let canonical_parent = match fs::canonicalize(parent) {
Ok(canonical_parent) => canonical_parent,
Err(error) => {
return rollback_bundle(
&installed,
&backups,
format!(
"could not resolve import target {}: {error}",
parent.display()
),
);
}
};
if !canonical_parent.starts_with(canonical_dest_dir) {
return rollback_bundle(
&installed,
&backups,
format!(
"FBX import target {} resolves outside destination {}",
parent.display(),
dest_dir.display()
),
);
}
}
if target.exists() {
let backup = backup_root.join(relative);
if let Some(parent) = backup.parent() {
if let Err(error) = fs::create_dir_all(parent) {
return rollback_bundle(
&installed,
&backups,
format!(
"could not create import backup {}: {error}",
parent.display()
),
);
}
}
if let Err(error) = fs::rename(&target, &backup) {
return rollback_bundle(
&installed,
&backups,
format!(
"could not back up import target {}: {error}",
target.display()
),
);
}
backups.push((backup, target.clone()));
}
if let Err(error) = fs::rename(&staged, &target) {
return rollback_bundle(
&installed,
&backups,
format!(
"could not publish import target {}: {error}",
target.display()
),
);
}
installed.push(target);
}
Ok(())
}
fn rollback_bundle(
installed: &[PathBuf],
backups: &[(PathBuf, PathBuf)],
cause: String,
) -> Result<(), String> {
let mut rollback_errors = Vec::new();
for target in installed.iter().rev() {
if let Err(error) = fs::remove_file(target) {
if error.kind() != std::io::ErrorKind::NotFound {
rollback_errors.push(format!("remove {}: {error}", target.display()));
}
}
}
for (backup, target) in backups.iter().rev() {
if let Err(error) = fs::rename(backup, target) {
rollback_errors.push(format!(
"restore {} to {}: {error}",
backup.display(),
target.display()
));
}
}
if rollback_errors.is_empty() {
Err(cause)
} else {
Err(format!(
"{cause}; rollback also failed: {}",
rollback_errors.join("; ")
))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_root(label: &str) -> PathBuf {
std::env::temp_dir().join(format!("blacksite-fbx-{label}-{}", uuid::Uuid::new_v4()))
}
fn committed_chair_bytes() -> Vec<u8> {
fs::read(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../assets/models/painted_wooden_chair_02_2k.fbx"),
)
.unwrap()
}
fn replace_equal_length(bytes: &mut [u8], from: &[u8], to: &[u8]) -> usize {
assert_eq!(from.len(), to.len());
let mut count = 0;
let mut offset = 0;
while let Some(index) = bytes[offset..]
.windows(from.len())
.position(|window| window == from)
{
let start = offset + index;
bytes[start..start + from.len()].copy_from_slice(to);
offset = start + from.len();
count += 1;
}
count
}
fn write_textures(root: &Path, folder: &str) {
let folder = root.join(folder);
fs::create_dir_all(&folder).unwrap();
for name in [
"painted_wooden_chair_02_diff_2k.jpg",
"painted_wooden_chair_02_nor_gl_2k.exr",
"painted_wooden_chair_02_rough_2k.exr",
] {
fs::write(folder.join(name), name.as_bytes()).unwrap();
}
}
#[test]
fn committed_chair_reports_one_stable_missing_dependency_state() {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../assets/models/painted_wooden_chair_02_2k.fbx");
let error = validate_fbx_dependencies(&path).unwrap_err();
assert!(error.starts_with("missing 3 FBX source texture(s):"));
assert_eq!(error.matches("painted_wooden_chair_02_").count(), 3);
}
#[test]
fn sibling_texture_bundle_is_copied_with_relative_layout() {
let root = temp_root("sibling");
let source_root = root.join("source");
let destination = root.join("destination");
fs::create_dir_all(&source_root).unwrap();
let source = source_root.join("chair.fbx");
fs::write(&source, committed_chair_bytes()).unwrap();
write_textures(&source_root, "textures");
copy_fbx_bundle(&source, &destination).unwrap();
assert!(destination.join("chair.fbx").is_file());
assert!(destination
.join("textures/painted_wooden_chair_02_diff_2k.jpg")
.is_file());
assert!(!destination.read_dir().unwrap().any(|entry| entry
.unwrap()
.file_name()
.to_string_lossy()
.starts_with(".blacksite-import-")));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn fbm_texture_bundle_is_copied_with_relative_layout() {
let root = temp_root("fbm");
let source_root = root.join("source");
let destination = root.join("destination");
fs::create_dir_all(&source_root).unwrap();
let source = source_root.join("chair.fbx");
let mut bytes = committed_chair_bytes();
assert!(replace_equal_length(&mut bytes, b"textures/", b"test.fbm/") > 0);
fs::write(&source, bytes).unwrap();
write_textures(&source_root, "test.fbm");
copy_fbx_bundle(&source, &destination).unwrap();
assert!(destination
.join("test.fbm/painted_wooden_chair_02_diff_2k.jpg")
.is_file());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn traversal_reference_is_rejected_before_destination_changes() {
let root = temp_root("traversal");
let source_root = root.join("source");
let destination = root.join("destination");
fs::create_dir_all(&source_root).unwrap();
fs::create_dir_all(&destination).unwrap();
let source = source_root.join("chair.fbx");
let mut bytes = committed_chair_bytes();
assert!(replace_equal_length(&mut bytes, b"textures/", b"../evil//") > 0);
fs::write(&source, bytes).unwrap();
fs::write(destination.join("chair.fbx"), b"original").unwrap();
let error = copy_fbx_bundle(&source, &destination).unwrap_err();
assert!(error.contains("parent traversal"));
assert_eq!(
fs::read(destination.join("chair.fbx")).unwrap(),
b"original"
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn missing_bundle_preserves_existing_destination() {
let root = temp_root("missing");
let source_root = root.join("source");
let destination = root.join("destination");
fs::create_dir_all(&source_root).unwrap();
fs::create_dir_all(&destination).unwrap();
let source = source_root.join("chair.fbx");
fs::write(&source, committed_chair_bytes()).unwrap();
fs::write(destination.join("chair.fbx"), b"original").unwrap();
let error = copy_fbx_bundle(&source, &destination).unwrap_err();
assert!(error.contains("missing 3 required texture(s)"));
assert_eq!(
fs::read(destination.join("chair.fbx")).unwrap(),
b"original"
);
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn destination_symlink_escape_is_rejected_before_external_changes() {
use std::os::unix::fs::symlink;
let root = temp_root("destination-symlink");
let source_root = root.join("source");
let destination = root.join("destination");
let outside = root.join("outside");
fs::create_dir_all(&source_root).unwrap();
fs::create_dir_all(&destination).unwrap();
fs::create_dir_all(&outside).unwrap();
let source = source_root.join("chair.fbx");
fs::write(&source, committed_chair_bytes()).unwrap();
write_textures(&source_root, "textures");
symlink(&outside, destination.join("textures")).unwrap();
let error = copy_fbx_bundle(&source, &destination).unwrap_err();
assert!(error.contains("symbolic link"));
assert!(!destination.join("chair.fbx").exists());
assert!(!outside.join("painted_wooden_chair_02_diff_2k.jpg").exists());
fs::remove_dir_all(root).unwrap();
}
}
pub use content_pipeline::{
extract_gltf_materials, find_matching_extracted_material, plan_fbx_material_extraction,
plan_gltf_material_extraction, plan_model_material_extraction, validate_fbx_dependencies,
ExtractedGltfMaterial, PlannedGltfMaterial,
};
+18 -4
View File
@@ -3,8 +3,7 @@
use bevy::prelude::*;
use bevy_egui::egui;
use shared::{
ComponentInstanceId, LevelObject, MaterialAsset, MaterialDesc, MaterialRef,
RendererMaterialSlot,
ComponentInstanceId, LevelObject, MaterialAsset, MaterialDesc, MaterialRef, MaterialSlot,
};
use crate::assets::{EditorAsset, EditorAssetKind, EditorAssets};
@@ -92,6 +91,22 @@ pub fn apply_material_asset_to_selection(
renderer_changes += 1;
continue;
}
if let Some(mut primitive) = world.get::<shared::Primitive>(entity).cloned() {
primitive.surface.material = Some(material_ref.clone());
reflected_component_transaction(
world,
entity,
"Assign Primitive Material",
shared::AUTHORING_COMPONENT_PRIMITIVE,
shared::COMPONENT_PRIMITIVE,
move |world, entity| {
world.entity_mut(entity).insert(primitive);
Ok(())
},
)?;
renderer_changes += 1;
continue;
}
if let Some(desc) = desc.as_ref() {
legacy_changes.push((entity, desc.clone()));
}
@@ -117,10 +132,9 @@ pub(crate) fn ensure_static_material_slots(renderer: &mut shared::StaticMeshRend
};
}
if renderer.materials.slot(&part.material_slot_id).is_none() {
renderer.materials.slots.push(RendererMaterialSlot {
renderer.materials.slots.push(MaterialSlot {
id: part.material_slot_id.clone(),
name: part.name.clone(),
source_material: part.material.clone().map(MaterialRef::new),
material: None,
});
}
+11 -19
View File
@@ -12,26 +12,18 @@ pub mod static_mesh;
pub mod thumbnails;
pub use catalog::*;
pub use import::{
extract_gltf_materials, find_matching_extracted_material, plan_fbx_material_extraction,
plan_gltf_material_extraction, plan_model_material_extraction, ExtractedGltfMaterial,
PlannedGltfMaterial,
};
pub use thumbnails::{
draw_asset_cell_with, gltf_skinned_primitive_labels, invalidate_on_catalog_refresh, kind_icon,
prefetch_asset_thumbnails, prefetch_folder_thumbnails, AssetThumbnailCache,
gltf_skinned_primitive_labels, invalidate_on_catalog_refresh, kind_icon,
prefetch_asset_thumbnails, prefetch_folder_thumbnails, retry_thumbnail, AssetThumbnailCache,
ThumbnailCacheSnapshot, ThumbnailState, ThumbnailStudio, ThumbnailsPlugin,
};
/// Refreshes both generated contracts derived from one imported model source.
pub fn refresh_model_artifacts(
record: &mut asset_db::AssetRecord,
) -> Result<static_mesh::StaticMeshManifest, String> {
let static_mesh = static_mesh::refresh_static_mesh_artifact(record);
let animation = animation::refresh_animation_artifact(record);
match (static_mesh, animation) {
(Ok(static_mesh), Ok(_)) => Ok(static_mesh),
(Err(static_error), Ok(_)) => Err(format!("static mesh processor failed: {static_error}")),
(Ok(_), Err(animation_error)) => {
Err(format!("animation processor failed: {animation_error}"))
}
(Err(static_error), Err(animation_error)) => Err(format!(
"static mesh processor failed: {static_error}; animation processor failed: {animation_error}"
)),
}
}
pub use content_pipeline::{
plan_model_artifacts, plan_model_artifacts_at, publish_model_artifacts,
refresh_model_artifacts, PlannedModelArtifacts,
};
+13 -8
View File
@@ -263,12 +263,12 @@ mod tests {
id: asset_id,
path: model_path.clone(),
label: "Operator Fixture".into(),
kind_tag: "Model".into(),
kind: shared::AssetKind::Model,
source_fingerprint: None,
import_settings: ImportSettings {
import_settings: shared::AssetImportSettings::Model(ImportSettings {
animation_manifest_path: Some(path.to_string_lossy().into_owned()),
..Default::default()
},
}),
dependencies: Vec::new(),
};
let selection = AssetSelection::SubAsset {
@@ -313,6 +313,7 @@ mod tests {
world.insert_resource(AssetRegistry {
records: vec![record],
index_dirty: false,
..Default::default()
});
let harness = OperatorInvariantHarness::capture(&mut world);
@@ -351,12 +352,13 @@ mod tests {
id: AssetId::new(),
path: path.clone(),
label: "Impact".into(),
kind_tag: "AudioClip".into(),
kind: shared::AssetKind::AudioClip,
source_fingerprint: None,
import_settings: Default::default(),
dependencies: Vec::new(),
}],
index_dirty: false,
..Default::default()
});
let entity = world
.spawn((
@@ -398,6 +400,7 @@ mod tests {
world.insert_resource(AssetRegistry {
records: vec![record],
index_dirty: false,
..Default::default()
});
let entity = world
.spawn((
@@ -483,13 +486,14 @@ mod tests {
let fixture = shared::MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: "Concrete".into(),
shader: None,
shader: shared::ShaderRefDesc::default(),
shader_ref: None,
render_state: Default::default(),
material: MaterialDesc {
provenance: None,
inputs: shared::MaterialInputSet::from_material_desc(&MaterialDesc {
roughness: 0.85,
..Default::default()
},
}),
};
std::fs::write(
&material_path,
@@ -502,12 +506,13 @@ mod tests {
id: AssetId::new(),
path: material_path.clone(),
label: "Concrete".into(),
kind_tag: "Material".into(),
kind: shared::AssetKind::Material,
source_fingerprint: None,
import_settings: Default::default(),
dependencies: Vec::new(),
}],
index_dirty: false,
..Default::default()
});
let first = world.spawn((LevelObject, MaterialDesc::default())).id();
let second = world.spawn((LevelObject, MaterialDesc::default())).id();
+2 -854
View File
@@ -1,855 +1,3 @@
//! Normalized static mesh artifacts generated from model source files.
//! Compatibility re-exports for UI-independent static-mesh artifact processing.
use std::fs;
use std::path::Path;
use bevy::gltf::GltfAssetLabel;
use bevy::prelude::*;
use bevy_ufbx::label::FbxAssetLabel;
use bevy_ufbx::mesh::group_faces_by_material;
use bevy_ufbx::texture::external_texture_paths;
use bevy_ufbx::utils::convert_matrix;
use serde::{Deserialize, Serialize};
use crate::asset_db::{
AssetRecord, ImportSettings, MaterialImportPolicy, ModelHierarchyMode, ModelPlacementMode,
};
use shared::{
AssetSourceFingerprint, ComponentInstanceId, EditorAssetRef, MaterialRef, RendererMaterialSet,
RendererMaterialSlot, StaticMeshRenderer, StaticMeshRendererEntry,
};
use crate::assets::fingerprint::{fingerprint_file, write_pretty_ron_if_changed};
pub const STATIC_MESH_MANIFEST_SCHEMA: u32 = 4;
pub const STATIC_MESH_ARTIFACT_DIR: &str = "assets/meshes/generated";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshManifest {
pub schema_version: u32,
pub asset_id: String,
pub label: String,
pub source: StaticMeshSource,
pub import: StaticMeshImportSnapshot,
pub metadata: StaticMeshMetadata,
pub parts: Vec<StaticMeshPart>,
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshSource {
pub path: String,
pub format: String,
pub fingerprint: StaticMeshSourceFingerprint,
pub dependencies: Vec<String>,
}
pub type StaticMeshSourceFingerprint = AssetSourceFingerprint;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshImportSnapshot {
pub scale: f32,
pub generate_collider: bool,
pub lod0_only: bool,
pub placement_mode: ModelPlacementMode,
pub hierarchy_mode: ModelHierarchyMode,
pub material_policy: MaterialImportPolicy,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshMetadata {
pub mesh_count: usize,
pub material_count: usize,
pub node_count: usize,
pub animation_count: usize,
pub skin_count: usize,
pub light_count: usize,
pub camera_count: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshPart {
#[serde(default)]
pub id: String,
pub name: String,
pub mesh_label: String,
#[serde(default)]
pub material_id: Option<String>,
pub material_slot_name: String,
pub material_label: Option<String>,
pub local_transform: Transform,
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 {
format!("{STATIC_MESH_ARTIFACT_DIR}/{asset_id}.static_mesh.ron")
}
pub fn part_id_from_label(label: &str) -> String {
format!("mesh:{}", stable_sub_asset_slug(label))
}
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() {
if ch.is_ascii_alphanumeric() {
slug.push(ch.to_ascii_lowercase());
} else if !slug.ends_with('_') {
slug.push('_');
}
}
slug.trim_matches('_').to_string()
}
pub fn refresh_static_mesh_artifact(
record: &mut AssetRecord,
) -> Result<StaticMeshManifest, String> {
let mut manifest = build_static_mesh_manifest(record)?;
let path = static_mesh_manifest_path(&record.id.as_string());
record.import_settings.static_mesh_manifest_path = Some(path.clone());
manifest.source.dependencies.sort();
manifest.source.dependencies.dedup();
record.dependencies = manifest.source.dependencies.clone();
if write_pretty_ron_if_changed(&path, &manifest)
.map_err(|error| format!("could not publish static mesh manifest {path}: {error}"))?
{
info!(
"Static mesh manifest refreshed: source={} artifact={} parts={}",
record.path,
path,
manifest.parts.len()
);
}
Ok(manifest)
}
pub fn load_static_mesh_manifest(path: &str) -> Result<StaticMeshManifest, String> {
let text = fs::read_to_string(path).map_err(|err| format!("could not read {path}: {err}"))?;
ron::from_str(&text).map_err(|err| format!("could not parse {path}: {err}"))
}
pub fn renderer_from_manifest(
manifest: &StaticMeshManifest,
settings: &ImportSettings,
) -> StaticMeshRenderer {
let use_source_materials = matches!(
settings.material_policy,
MaterialImportPolicy::SourceMaterials
);
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()
.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| {
MaterialRef::new(EditorAssetRef::new(
manifest.asset_id.clone(),
id,
part.material_slot_name.clone(),
))
})
})
.flatten(),
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)
} else {
part.id.clone()
}
}
fn part_effective_material_id(part: &StaticMeshPart) -> Option<String> {
part.material_id.clone().or_else(|| {
part.material_label
.as_ref()
.map(|label| material_id_from_label(label))
})
}
fn build_static_mesh_manifest(record: &AssetRecord) -> Result<StaticMeshManifest, String> {
let format = source_format(&record.path)?;
let fingerprint = fingerprint_file(&record.path)?;
let import = StaticMeshImportSnapshot {
scale: record.import_settings.scale,
generate_collider: record.import_settings.generate_collider,
lod0_only: record.import_settings.lod0_only,
placement_mode: record.import_settings.placement_mode,
hierarchy_mode: record.import_settings.hierarchy_mode,
material_policy: record.import_settings.material_policy,
};
let mut manifest = match format.as_str() {
"gltf" | "glb" => build_gltf_manifest(record, format, fingerprint, import)?,
"fbx" => build_fbx_manifest(record, format, fingerprint, import)?,
_ => return Err(format!("unsupported static mesh source format `{format}`")),
};
if manifest.parts.is_empty() {
manifest
.warnings
.push("No renderable static mesh parts were found.".into());
}
Ok(manifest)
}
fn build_gltf_manifest(
record: &AssetRecord,
format: String,
fingerprint: StaticMeshSourceFingerprint,
import: StaticMeshImportSnapshot,
) -> Result<StaticMeshManifest, String> {
let gltf = gltf::Gltf::open(&record.path)
.map_err(|err| format!("could not parse glTF {}: {err}", record.path))?;
let mut parts = Vec::new();
let mut dependencies = Vec::new();
let mut warnings = Vec::new();
for buffer in gltf.document.buffers() {
if let gltf::buffer::Source::Uri(uri) = buffer.source() {
dependencies.push(resolve_dependency(&record.path, uri));
}
}
for image in gltf.document.images() {
if let gltf::image::Source::Uri { uri, .. } = image.source() {
dependencies.push(resolve_dependency(&record.path, uri));
}
}
if let Some(scene) = gltf
.document
.default_scene()
.or_else(|| gltf.document.scenes().next())
{
for node in scene.nodes() {
collect_gltf_node_parts(node, Mat4::IDENTITY, "", &mut parts);
}
} else {
for mesh in gltf.document.meshes() {
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; animated placement uses SkinnedMeshRenderer."
.into(),
);
}
if gltf.document.skins().count() > 0 {
warnings.push(
"Skinned primitives are excluded from StaticMeshRenderer and use SkinnedMeshRenderer."
.into(),
);
}
parts.sort_by(|a, b| a.mesh_label.cmp(&b.mesh_label).then(a.name.cmp(&b.name)));
Ok(StaticMeshManifest {
schema_version: STATIC_MESH_MANIFEST_SCHEMA,
asset_id: record.id.as_string(),
label: record.label.clone(),
source: StaticMeshSource {
path: record.path.clone(),
format,
fingerprint,
dependencies,
},
import,
metadata: StaticMeshMetadata {
mesh_count: gltf.document.meshes().count(),
material_count: gltf.document.materials().count(),
node_count: gltf.document.nodes().count(),
animation_count: gltf.document.animations().count(),
skin_count: gltf.document.skins().count(),
light_count: 0,
camera_count: gltf.document.cameras().count(),
},
parts,
warnings,
})
}
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, &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();
let mesh_name = mesh.name().map(str::to_string);
for primitive in mesh.primitives() {
let primitive_index = primitive.index();
let mesh_label = GltfAssetLabel::Primitive {
mesh: mesh_index,
primitive: primitive_index,
}
.to_string();
let material = primitive.material();
let material_label = material
.index()
.map(|index| {
GltfAssetLabel::Material {
index,
is_scale_inverted: false,
}
.to_string()
})
.or_else(|| Some(GltfAssetLabel::DefaultMaterial.to_string()));
let material_name = material
.name()
.map(str::to_string)
.unwrap_or_else(|| "Default Material".into());
let name = node_name
.clone()
.or_else(|| mesh_name.clone())
.unwrap_or_else(|| format!("Mesh {mesh_index}"));
let source_node = node_path
.clone()
.or_else(|| node_index.map(|index| format!("Node{index}")));
parts.push(StaticMeshPart {
id: gltf_draw_id(node_index, mesh_index, primitive_index),
name: format!("{name} / Primitive {primitive_index}"),
material_id: material_label
.as_ref()
.map(|label| material_id_from_label(label)),
mesh_label,
material_slot_name: material_name.clone(),
material_label,
local_transform: Transform::from_matrix(transform),
source_node,
source_mesh: Some(format!("Mesh{mesh_index}")),
source_material: Some(material_name),
skinned,
});
}
}
fn build_fbx_manifest(
record: &AssetRecord,
format: String,
fingerprint: StaticMeshSourceFingerprint,
import: StaticMeshImportSnapshot,
) -> Result<StaticMeshManifest, String> {
let bytes =
fs::read(&record.path).map_err(|err| format!("could not read {}: {err}", record.path))?;
let scene = ufbx::load_memory(
&bytes,
ufbx::LoadOpts {
target_unit_meters: 1.0,
target_axes: ufbx::CoordinateAxes::right_handed_y_up(),
filename: ufbx::StringOpt::Ref(&record.path),
..Default::default()
},
)
.map_err(|err| format!("could not parse FBX {}: {err:?}", record.path))?;
let mut parts = Vec::new();
let mut warnings = Vec::new();
for (node_index, node) in scene.nodes.as_ref().iter().enumerate() {
let Some(mesh_ref) = node.mesh.as_ref() else {
continue;
};
let mesh = mesh_ref.as_ref();
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();
groups.sort_by_key(|(material_index, _)| *material_index);
for (material_index, indices) in groups {
if indices.is_empty() {
continue;
}
let material = mesh.materials.get(material_index).map(|mat| mat.as_ref());
let material_label = material
.and_then(|mat| fbx_material_label(&scene, mat.element.element_id))
.or_else(|| Some(FbxAssetLabel::DefaultMaterial.to_string()));
let material_name = material
.map(|mat| mat.element.name.to_string())
.filter(|name| !name.is_empty())
.unwrap_or_else(|| "Default Material".into());
let node_name = if node.element.name.is_empty() {
format!("Node {node_index}")
} else {
node.element.name.to_string()
};
let mesh_label = FbxAssetLabel::Mesh(node_index * 1000 + material_index).to_string();
parts.push(StaticMeshPart {
id: fbx_draw_id(node_index, material_index),
name: format!("{node_name} / Material {material_index}"),
material_id: material_label
.as_ref()
.map(|label| material_id_from_label(label)),
mesh_label,
material_slot_name: material_name.clone(),
material_label,
local_transform: Transform::from_matrix(convert_matrix(&node.geometry_to_world)),
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; animated placement uses SkinnedMeshRenderer."
.into(),
);
}
if !scene.skin_deformers.as_ref().is_empty() {
warnings.push(
"Skinned primitives are excluded from StaticMeshRenderer and use SkinnedMeshRenderer."
.into(),
);
}
parts.sort_by(|a, b| a.mesh_label.cmp(&b.mesh_label).then(a.name.cmp(&b.name)));
Ok(StaticMeshManifest {
schema_version: STATIC_MESH_MANIFEST_SCHEMA,
asset_id: record.id.as_string(),
label: record.label.clone(),
source: StaticMeshSource {
path: record.path.clone(),
format,
fingerprint,
dependencies: fbx_dependencies(&record.path, &scene)?,
},
import,
metadata: StaticMeshMetadata {
mesh_count: scene.meshes.as_ref().len(),
material_count: scene.materials.as_ref().len(),
node_count: scene.nodes.as_ref().len(),
animation_count: scene.anim_stacks.as_ref().len(),
skin_count: scene.skin_deformers.as_ref().len(),
light_count: scene.lights.as_ref().len(),
camera_count: scene.cameras.as_ref().len(),
},
parts,
warnings,
})
}
fn fbx_material_label(scene: &ufbx::Scene, element_id: u32) -> Option<String> {
if element_id == 0 {
return None;
}
scene
.materials
.as_ref()
.iter()
.position(|material| material.element.element_id == element_id)
.map(|index| FbxAssetLabel::Material(index).to_string())
}
fn fbx_dependencies(source_path: &str, scene: &ufbx::Scene) -> Result<Vec<String>, String> {
let path = Path::new(source_path);
let parent = path.parent().unwrap_or_else(|| Path::new(""));
external_texture_paths(scene)
.map_err(|errors| {
format!(
"unsafe FBX texture reference(s) in {source_path}: {}",
errors
.into_iter()
.map(|error| error.to_string())
.collect::<Vec<_>>()
.join("; ")
)
})
.map(|paths| {
paths
.into_iter()
.map(|relative| parent.join(relative).to_string_lossy().replace('\\', "/"))
.collect()
})
}
fn source_format(path: &str) -> Result<String, String> {
Path::new(path)
.extension()
.and_then(|ext| ext.to_str())
.map(|ext| ext.to_ascii_lowercase())
.ok_or_else(|| format!("asset path `{path}` has no extension"))
}
fn resolve_dependency(source_path: &str, uri: &str) -> String {
if uri.starts_with("data:") || uri.contains("://") {
return uri.to_string();
}
Path::new(source_path)
.parent()
.unwrap_or_else(|| Path::new(""))
.join(uri)
.to_string_lossy()
.replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::asset_db::AssetId;
fn test_manifest() -> StaticMeshManifest {
StaticMeshManifest {
schema_version: STATIC_MESH_MANIFEST_SCHEMA,
asset_id: "asset-1".into(),
label: "Crate".into(),
source: StaticMeshSource {
path: "assets/models/crate.glb".into(),
format: "glb".into(),
fingerprint: StaticMeshSourceFingerprint {
byte_len: 42,
content_hash: "a".repeat(64),
},
dependencies: Vec::new(),
},
import: StaticMeshImportSnapshot {
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: ModelPlacementMode::StaticAsset,
hierarchy_mode: ModelHierarchyMode::SingleActor,
material_policy: MaterialImportPolicy::SourceMaterials,
},
metadata: StaticMeshMetadata {
mesh_count: 1,
material_count: 1,
node_count: 1,
animation_count: 0,
skin_count: 0,
light_count: 0,
camera_count: 0,
},
parts: vec![StaticMeshPart {
id: "mesh:mesh0_primitive0".into(),
name: "Crate / Primitive 0".into(),
mesh_label: "Mesh0/Primitive0".into(),
material_id: Some("material:material0".into()),
material_slot_name: "Wood".into(),
material_label: Some("Material0".into()),
local_transform: Transform::from_xyz(1.0, 2.0, 3.0),
source_node: Some("Node0".into()),
source_mesh: Some("Mesh0".into()),
source_material: Some("Wood".into()),
skinned: false,
}],
warnings: Vec::new(),
}
}
#[test]
fn static_mesh_manifest_path_uses_asset_id() {
assert_eq!(
static_mesh_manifest_path("abc"),
"assets/meshes/generated/abc.static_mesh.ron"
);
}
#[test]
fn renderer_from_manifest_preserves_labels_and_collider_policy() {
let manifest = test_manifest();
let settings = ImportSettings {
generate_collider: true,
..Default::default()
};
let renderer = renderer_from_manifest(&manifest, &settings);
assert_eq!(renderer.slots.len(), 1);
let entry = &renderer.slots[0];
assert_eq!(entry.mesh.asset_id, manifest.asset_id);
assert_eq!(entry.mesh.sub_asset_id, "mesh:mesh0_primitive0");
assert_eq!(
entry
.material
.as_ref()
.map(|material| material.sub_asset_id.as_str()),
Some("material:material0")
);
}
#[test]
fn schema_v3_manifest_without_hash_migrates_to_content_fingerprint() {
let root = std::env::temp_dir().join(format!(
"blacksite-static-mesh-legacy-{}",
uuid::Uuid::new_v4()
));
fs::create_dir_all(&root).unwrap();
let path = root.join("legacy.static_mesh.ron");
let expected = test_manifest();
let canonical =
ron::ser::to_string_pretty(&expected, ron::ser::PrettyConfig::default()).unwrap();
let legacy = canonical
.replacen("schema_version: 4", "schema_version: 3", 1)
.lines()
.filter(|line| !line.contains("content_hash:"))
.collect::<Vec<_>>()
.join("\n");
fs::write(&path, legacy).unwrap();
assert!(write_pretty_ron_if_changed(&path, &expected).unwrap());
assert_eq!(
load_static_mesh_manifest(&path.to_string_lossy()).unwrap(),
expected
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn equivalent_static_manifest_preserves_existing_formatting_and_newline() {
let root = std::env::temp_dir().join(format!(
"blacksite-static-mesh-semantic-{}",
uuid::Uuid::new_v4()
));
fs::create_dir_all(&root).unwrap();
let path = root.join("stable.static_mesh.ron");
let manifest = test_manifest();
let exact = format!(
"{}\n\n",
ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default()).unwrap()
);
fs::write(&path, &exact).unwrap();
assert!(!write_pretty_ron_if_changed(&path, &manifest).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), exact);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn renderer_from_manifest_can_ignore_source_materials() {
let manifest = test_manifest();
let settings = ImportSettings {
material_policy: MaterialImportPolicy::AuthoringOverride,
..Default::default()
};
let renderer = renderer_from_manifest(&manifest, &settings);
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(),
source_fingerprint: None,
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());
}
#[test]
fn committed_fbx_records_sibling_texture_dependencies() {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../assets/models/painted_wooden_chair_02_2k.fbx")
.to_string_lossy()
.into_owned();
let record = AssetRecord {
id: AssetId::new(),
path,
label: "Painted Chair".into(),
kind_tag: "Model".into(),
source_fingerprint: None,
import_settings: ImportSettings::default(),
dependencies: Vec::new(),
};
let manifest = build_static_mesh_manifest(&record).unwrap();
assert_eq!(manifest.source.dependencies.len(), 3);
assert!(manifest
.source
.dependencies
.iter()
.all(|path| path.contains("assets/models/textures/painted_wooden_chair_02_")));
}
}
pub use content_pipeline::static_mesh::*;
+128 -124
View File
@@ -3,12 +3,12 @@
use std::collections::{HashMap, HashSet};
use std::path::Path;
use bevy::asset::LoadState;
use bevy::asset::{AssetId, LoadState};
use bevy::prelude::*;
use bevy_egui::{egui, EguiPrimaryContextPass, EguiTextureHandle, EguiUserTextures};
use egui_phosphor_icons::icons;
use super::sources::gltf::{gltf_base_color_texture_path, validate_gltf_dependencies};
use super::sources::gltf::validate_gltf_dependencies;
use super::studio::{model_file_exists, ThumbnailStudio};
use super::ThumbnailJobSource;
use crate::assets::{
@@ -31,6 +31,7 @@ struct ThumbnailFailure {
#[derive(Resource, Default)]
pub struct AssetThumbnailCache {
pub texture_ids: HashMap<String, egui::TextureId>,
registered_images: HashMap<String, AssetId<Image>>,
pending: HashMap<String, Handle<Image>>,
pub(crate) studio_pending: HashSet<String>,
failed: HashMap<String, ThumbnailFailure>,
@@ -64,11 +65,15 @@ impl AssetThumbnailCache {
None
}
pub fn retry(&mut self, key: &str) {
/// Clears one thumbnail and returns the image registration when this key was its last owner.
/// The caller must remove that registration from `EguiUserTextures` after releasing the cache
/// borrow.
pub fn retry(&mut self, key: &str) -> Option<AssetId<Image>> {
self.failed.remove(key);
self.pending.remove(key);
self.studio_pending.remove(key);
self.texture_ids.remove(key);
self.release_registered_image(key)
}
pub fn request_texture(&mut self, key: String, path: String, asset_server: &AssetServer) {
@@ -88,13 +93,7 @@ impl AssetThumbnailCache {
self.pending.insert(key, handle);
}
pub fn request_model(
&mut self,
key: String,
model_path: String,
asset_server: &AssetServer,
studio: &mut ThumbnailStudio,
) {
pub fn request_model(&mut self, key: String, model_path: String, studio: &mut ThumbnailStudio) {
if matches!(
self.state(&key),
Some(ThumbnailState::Ready | ThumbnailState::Pending)
@@ -109,11 +108,6 @@ impl AssetThumbnailCache {
return;
}
if let Some(texture_path) = gltf_base_color_texture_path(&model_path) {
self.request_texture(key, texture_path, asset_server);
return;
}
if studio.enqueue(key.clone(), model_path) {
self.studio_pending.insert(key);
}
@@ -263,10 +257,7 @@ impl AssetThumbnailCache {
) {
self.studio_pending.remove(key);
self.failed.remove(key);
let texture_id = textures
.image_id(&image)
.unwrap_or_else(|| textures.add_image(EguiTextureHandle::Strong(image)));
self.texture_ids.insert(key.to_string(), texture_id);
self.register_thumbnail(key, image, textures);
}
pub(crate) fn mark_studio_failed(&mut self, key: &str, reason: &str, retryable: bool) {
@@ -281,12 +272,48 @@ impl AssetThumbnailCache {
);
}
pub fn invalidate_all(&mut self) {
/// Invalidates every cache entry and returns each distinct Egui image registration exactly
/// once so the world-level invalidation path can relinquish GPU ownership.
pub fn invalidate_all(&mut self) -> Vec<AssetId<Image>> {
self.texture_ids.clear();
self.pending.clear();
self.studio_pending.clear();
self.failed.clear();
self.prefetched_folder = None;
self.registered_images
.drain()
.map(|(_, image)| image)
.collect::<HashSet<_>>()
.into_iter()
.collect()
}
fn register_thumbnail(
&mut self,
key: &str,
image: Handle<Image>,
textures: &mut EguiUserTextures,
) {
let image_id = image.id();
if self.registered_images.get(key).copied() != Some(image_id) {
if let Some(previous) = self.release_registered_image(key) {
textures.remove_image(previous);
}
self.registered_images.insert(key.to_string(), image_id);
}
let texture_id = textures
.image_id(image_id)
.unwrap_or_else(|| textures.add_image(EguiTextureHandle::Strong(image)));
self.texture_ids.insert(key.to_string(), texture_id);
}
fn release_registered_image(&mut self, key: &str) -> Option<AssetId<Image>> {
let image = self.registered_images.remove(key)?;
(!self
.registered_images
.values()
.any(|registered| *registered == image))
.then_some(image)
}
pub fn snapshot(&self) -> ThumbnailCacheSnapshot {
@@ -335,10 +362,7 @@ fn register_loaded_thumbnails(
for (key, handle) in ready {
cache.pending.remove(&key);
cache.failed.remove(&key);
let texture_id = textures
.image_id(&handle)
.unwrap_or_else(|| textures.add_image(EguiTextureHandle::Strong(handle)));
cache.texture_ids.insert(key, texture_id);
cache.register_thumbnail(&key, handle, &mut textures);
}
}
@@ -359,99 +383,6 @@ pub fn kind_icon(kind: &EditorAssetKind) -> egui_phosphor_icons::Icon {
}
}
pub fn draw_asset_cell_with(
ui: &mut egui::Ui,
asset: &EditorAsset,
texture_id: Option<egui::TextureId>,
pending: bool,
failed: Option<&str>,
selected: bool,
thumbnail_size: f32,
) -> egui::Response {
let thumb_size = thumbnail_size.clamp(48.0, 112.0);
let cell_size = egui::vec2(thumb_size + 20.0, thumb_size + 30.0);
let (rect, response) = ui.allocate_exact_size(cell_size, egui::Sense::click_and_drag());
let fill = if selected {
crate::ui::theme::SELECTION_BG_MUTED
} else if response.hovered() {
crate::ui::theme::ELEVATED_BG
} else {
crate::ui::theme::WIDGET_BG
};
ui.painter().rect(
rect,
4.0,
fill,
egui::Stroke::new(
1.0,
if selected {
crate::ui::theme::ACCENT_HOVER
} else {
crate::ui::theme::BORDER
},
),
egui::StrokeKind::Inside,
);
let thumb_rect = egui::Rect::from_min_size(
rect.min + egui::vec2(10.0, 8.0),
egui::vec2(thumb_size, thumb_size),
);
if let Some(texture_id) = texture_id {
ui.painter().image(
texture_id,
thumb_rect,
egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
egui::Color32::WHITE,
);
} else if pending {
ui.painter().text(
thumb_rect.center(),
egui::Align2::CENTER_CENTER,
icons::CIRCLE_NOTCH.as_str(),
egui::FontId::new(24.0, egui::FontFamily::Name("phosphor-regular".into())),
crate::ui::theme::TEXT_DIM,
);
} else if failed.is_some() {
ui.painter().text(
thumb_rect.center(),
egui::Align2::CENTER_CENTER,
icons::WARNING_CIRCLE.as_str(),
egui::FontId::new(24.0, egui::FontFamily::Name("phosphor-regular".into())),
crate::ui::theme::TEXT_DIM,
);
} else {
let icon = kind_icon(&asset.kind);
ui.painter().text(
thumb_rect.center(),
egui::Align2::CENTER_CENTER,
icon.as_str(),
egui::FontId::new(28.0, egui::FontFamily::Name("phosphor-regular".into())),
crate::ui::theme::TEXT,
);
}
ui.painter().text(
egui::pos2(rect.center().x, rect.max.y - 6.0),
egui::Align2::CENTER_BOTTOM,
asset.label.as_str(),
egui::FontId::new(11.0, egui::FontFamily::Proportional),
if selected {
crate::ui::theme::TEXT_SELECTED
} else {
crate::ui::theme::TEXT
},
);
if let Some(reason) = failed {
response.on_hover_text(reason)
} else {
response
}
}
#[derive(Clone)]
pub struct ThumbnailCacheSnapshot {
pub texture_ids: HashMap<String, egui::TextureId>,
@@ -533,9 +464,7 @@ pub fn prefetch_folder_thumbnails(world: &mut World, folder: &str) {
for (key, path, kind) in requests {
match kind {
EditorAssetKind::Texture => cache.request_texture(key, path, &asset_server),
EditorAssetKind::Model => {
cache.request_model(key, path, &asset_server, &mut studio)
}
EditorAssetKind::Model => cache.request_model(key, path, &mut studio),
EditorAssetKind::Material => {
cache.request_material_asset(key, path, &mut studio)
}
@@ -567,9 +496,7 @@ pub fn prefetch_asset_thumbnails(world: &mut World, assets: &[EditorAsset]) {
for (key, path, kind) in requests {
match kind {
EditorAssetKind::Texture => cache.request_texture(key, path, &asset_server),
EditorAssetKind::Model => {
cache.request_model(key, path, &asset_server, &mut studio)
}
EditorAssetKind::Model => cache.request_model(key, path, &mut studio),
EditorAssetKind::Material => {
cache.request_material_asset(key, path, &mut studio)
}
@@ -580,8 +507,23 @@ pub fn prefetch_asset_thumbnails(world: &mut World, assets: &[EditorAsset]) {
});
}
/// Evicts one thumbnail while releasing the backing Egui image if no other cache key shares it.
pub fn retry_thumbnail(world: &mut World, key: &str) {
let registration = world.resource_mut::<AssetThumbnailCache>().retry(key);
if let Some(registration) = registration {
if let Some(mut textures) = world.get_resource_mut::<EguiUserTextures>() {
textures.remove_image(registration);
}
}
}
pub fn invalidate_on_catalog_refresh(world: &mut World) {
world.resource_mut::<AssetThumbnailCache>().invalidate_all();
let registrations = world.resource_mut::<AssetThumbnailCache>().invalidate_all();
if let Some(mut textures) = world.get_resource_mut::<EguiUserTextures>() {
for registration in registrations {
textures.remove_image(registration);
}
}
if !world.contains_resource::<ThumbnailStudio>() {
return;
}
@@ -644,4 +586,66 @@ mod tests {
assert_eq!(reason, format!("missing texture: {path}"));
assert!(cache.pending.is_empty());
}
#[test]
fn poly_haven_desk_model_queues_geometry_instead_of_its_albedo_texture() {
let model_path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../assets/Furniture/Office/metal_office_desk_2k.gltf")
.to_string_lossy()
.into_owned();
let mut cache = AssetThumbnailCache::default();
let mut studio = ThumbnailStudio::for_test();
cache.request_model("model:desk".into(), model_path.clone(), &mut studio);
let jobs = studio.queued_jobs_for_test();
assert_eq!(jobs.len(), 1);
assert_eq!(jobs[0].cache_key, "model:desk");
assert!(matches!(
&jobs[0].source,
ThumbnailJobSource::Model { model_path: queued } if queued == &model_path
));
assert!(!jobs[0].source.label().contains("_diff_"));
}
#[test]
fn endurance_guard_repeated_thumbnail_replacement_and_invalidation_release_egui_images() {
let mut cache = AssetThumbnailCache::default();
let mut textures = EguiUserTextures::default();
let mut images = Assets::<Image>::default();
for revision in 0..32 {
let image = images.add(Image::default());
let image_id = image.id();
cache.complete_studio_thumbnail("material:shared", image, &mut textures);
assert!(textures.image_id(image_id).is_some(), "revision {revision}");
assert_eq!(cache.registered_images.len(), 1);
}
let registrations = cache.invalidate_all();
assert_eq!(registrations.len(), 1);
for registration in registrations {
assert!(textures.remove_image(registration).is_some());
}
assert!(cache.registered_images.is_empty());
assert!(cache.texture_ids.is_empty());
}
#[test]
fn endurance_guard_shared_thumbnail_image_is_released_only_after_the_last_key() {
let mut cache = AssetThumbnailCache::default();
let mut textures = EguiUserTextures::default();
let mut images = Assets::<Image>::default();
let image = images.add(Image::default());
let image_id = image.id();
cache.complete_studio_thumbnail("first", image.clone(), &mut textures);
cache.complete_studio_thumbnail("second", image, &mut textures);
assert!(cache.retry("first").is_none());
assert!(textures.image_id(image_id).is_some());
let registration = cache.retry("second").expect("last owner releases image");
assert_eq!(registration, image_id);
textures.remove_image(registration);
assert!(textures.image_id(image_id).is_none());
}
}
+4 -4
View File
@@ -1,4 +1,4 @@
//! Unified asset thumbnail pipeline (texture fast-path + model studio).
//! Unified asset thumbnail pipeline (typed texture loads + model render studio).
use bevy::prelude::*;
@@ -8,9 +8,9 @@ mod sources;
mod studio;
pub use cache::{
draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_asset_thumbnails,
prefetch_folder_thumbnails, AssetThumbnailCache, AssetThumbnailsPlugin, ThumbnailCacheSnapshot,
ThumbnailState,
invalidate_on_catalog_refresh, kind_icon, prefetch_asset_thumbnails,
prefetch_folder_thumbnails, retry_thumbnail, AssetThumbnailCache, AssetThumbnailsPlugin,
ThumbnailCacheSnapshot, ThumbnailState,
};
pub use job::{ThumbnailJob, ThumbnailJobSource};
pub use sources::{
@@ -1,35 +1,8 @@
//! glTF/GLB fast-path texture extraction for asset browser thumbnails.
//! glTF/GLB dependency validation and thumbnail source inspection.
use std::collections::HashSet;
use std::path::Path;
/// Returns an asset-server path for the first base-color texture referenced by a glTF/GLB file.
///
/// Embedded GLB buffers are skipped so callers can fall back to the render studio.
pub fn gltf_base_color_texture_path(model_asset_path: &str) -> Option<String> {
let model_path = Path::new(model_asset_path);
if !is_gltf_path(model_path) {
return None;
}
let (document, ..) = gltf::import(model_path).ok()?;
for material in document.materials() {
let Some(tex_info) = material.pbr_metallic_roughness().base_color_texture() else {
continue;
};
let texture = document.textures().nth(tex_info.texture().index())?;
let image = document.images().nth(texture.source().index())?;
let uri = match image.source() {
gltf::image::Source::Uri { uri, .. } => uri,
gltf::image::Source::View { .. } => continue,
};
if let Some(path) = resolve_texture_uri(model_path, uri) {
return Some(path);
}
}
None
}
/// Verifies local external buffers and images before Bevy starts an async glTF load.
pub fn validate_gltf_dependencies(model_asset_path: &str) -> Result<(), String> {
let model_path = Path::new(model_asset_path);
@@ -99,15 +72,6 @@ fn is_gltf_path(path: &Path) -> bool {
.is_some_and(|ext| matches!(ext.to_ascii_lowercase().as_str(), "gltf" | "glb"))
}
fn resolve_texture_uri(model_path: &Path, uri: &str) -> Option<String> {
if uri.starts_with("data:") {
return None;
}
let model_dir = model_path.parent()?;
let texture_path = model_dir.join(uri);
normalize_asset_path(&texture_path)
}
fn normalize_asset_path(path: &Path) -> Option<String> {
let raw = path.to_string_lossy().replace('\\', "/");
if raw.starts_with("assets/") {
@@ -124,7 +88,6 @@ fn normalize_asset_path(path: &Path) -> Option<String> {
mod tests {
use super::*;
use std::fs;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
#[test]
@@ -135,15 +98,6 @@ mod tests {
);
}
#[test]
fn resolve_texture_uri_relative_to_model() {
let model = PathBuf::from("assets/models/chair.gltf");
assert_eq!(
resolve_texture_uri(&model, "textures/chair_albedo.png"),
Some("assets/models/textures/chair_albedo.png".into())
);
}
#[test]
fn dependency_validation_reports_missing_external_buffer() {
let nonce = SystemTime::now()
@@ -129,6 +129,24 @@ impl ThumbnailStudio {
active_root: self.active.take().map(|active| active.root),
}
}
#[cfg(test)]
pub(crate) fn for_test() -> Self {
Self {
camera: Entity::PLACEHOLDER,
render_image: Handle::default(),
_lights: Vec::new(),
queue: VecDeque::new(),
active: None,
cooldown_frames: 0,
render_pipeline_warmed: false,
}
}
#[cfg(test)]
pub(crate) fn queued_jobs_for_test(&self) -> Vec<ThumbnailJob> {
self.queue.iter().cloned().collect()
}
}
pub struct StudioCleanup {
+32 -1
View File
@@ -20,6 +20,37 @@ fn make_editor_only_non_pickable(
editor_only: Query<Entity, Added<EditorOnly>>,
) {
for entity in &editor_only {
commands.entity(entity).insert(Pickable::IGNORE);
// Editor helpers can be created and retired within the same update (for
// example while a thumbnail studio refreshes). A regular deferred
// insert panics if another system queued the despawn first.
commands.entity(entity).try_insert(Pickable::IGNORE);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn despawn_added_editor_only(
mut commands: Commands,
editor_only: Query<Entity, Added<EditorOnly>>,
) {
for entity in &editor_only {
commands.entity(entity).despawn();
}
}
#[test]
fn same_frame_helper_retirement_does_not_panic_during_pickable_tagging() {
let mut app = App::new();
app.add_plugins(EditorInfraPlugin).add_systems(
Update,
despawn_added_editor_only.before(make_editor_only_non_pickable),
);
let helper = app.world_mut().spawn(EditorOnly).id();
app.update();
assert!(app.world().get_entity(helper).is_err());
}
}
+3
View File
@@ -22,6 +22,7 @@ pub use ext::extensibility;
pub use ext::hot_reload;
pub use play::net_editor;
pub use play::state;
pub use project::asset_documents;
pub use project::collaboration;
pub use project::diagnostics_bundle;
pub use project::launcher;
@@ -74,6 +75,7 @@ use operators::OperatorPlugin;
use physics_placement::PhysicsPlacementPlugin;
use play::audio_preview::AudioPreviewPlugin;
use play::PlaySessionPlugin;
use project::asset_documents::AuthoredAssetDocumentsPlugin;
use project::collaboration::CollaborationPlugin;
use project::native_dialog::NativeDialogPlugin;
use project::samples::SampleCatalogPlugin;
@@ -108,6 +110,7 @@ impl PluginGroup for EditorPluginGroup {
.add(scene_schema::SceneSchemaPlugin)
.add(net_editor::NetEditorPlugin)
.add(AssetDbPlugin)
.add(AuthoredAssetDocumentsPlugin)
.add(OperatorPlugin)
.add(ExtensibilityPlugin)
.add(SettingsUiPlugin)
@@ -0,0 +1,51 @@
//! Editor-owned authored asset documents and explicit save boundaries.
//!
//! Interactive UI mutates these documents and live runtime handles only. Source publication,
//! collaboration checks, watcher suppression, and derived processing happen exclusively here.
use std::collections::{HashMap, VecDeque};
use std::fs;
use std::path::{Path, PathBuf};
use std::thread::JoinHandle;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use bevy::prelude::*;
use blacksite_surface::LiveMaterialDocument;
use serde::{Deserialize, Serialize};
use shared::{
AssetId, AssetKind, AssetRegistryDocument, MaterialAsset, MaterialInstanceAsset,
ModelImportSettings, ProjectContentDefaults, RuntimeContentCatalog, TextureImportSettings,
};
use crate::asset_db::{AssetRecord, AssetRegistry};
use crate::assets::EditorAssets;
use crate::project::collaboration::{
publish_authored_file, FileRevision, FileSnapshot, FileWriteIntent,
};
use crate::project_io::ProjectWorkspace;
use crate::scene::recovery::{atomic_write, default_state_root};
use crate::scene_io::{SceneIo, SceneIoRequest};
mod processing_impact;
pub use processing_impact::DerivedProcessingImpact;
use processing_impact::{instance_impact, material_impact};
#[path = "asset_documents/document_store/live_updates.rs"]
mod live_updates;
#[path = "asset_documents/document_store/processing.rs"]
mod processing;
#[path = "asset_documents/document_store/publication.rs"]
mod publication;
#[path = "asset_documents/document_store/recovery.rs"]
mod recovery;
#[path = "asset_documents/document_store/service.rs"]
mod service;
#[path = "asset_documents/document_store/store.rs"]
mod store;
pub use live_updates::*;
use processing::*;
pub use publication::*;
pub use recovery::*;
pub use service::*;
pub use store::*;
@@ -0,0 +1,111 @@
use super::*;
/// Applies one interactive Material edit to both the authored document and the renderer overlay.
/// No filesystem, watcher, Git, thumbnail, or derived-processing work is performed here.
pub fn update_material_document(
world: &mut World,
key: &AuthoredAssetDocumentKey,
asset: MaterialAsset,
) {
let revision = {
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
store.update_material(key, asset.clone());
store
.documents
.get(key)
.map(|document| document.revision)
.unwrap_or_default()
};
if let Some(mut overlay) =
world.get_resource_mut::<blacksite_surface::LiveMaterialDocumentOverlay>()
{
overlay.update_material(key.asset_id.clone(), revision, asset);
}
}
/// Applies one interactive Material Instance edit to the same live authority as Materials.
pub fn update_material_instance_document(
world: &mut World,
key: &AuthoredAssetDocumentKey,
instance: MaterialInstanceAsset,
) {
let revision = {
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
store.update_material_instance(key, instance.clone());
store
.documents
.get(key)
.map(|document| document.revision)
.unwrap_or_default()
};
if let Some(mut overlay) =
world.get_resource_mut::<blacksite_surface::LiveMaterialDocumentOverlay>()
{
overlay.update_instance(key.asset_id.clone(), revision, instance);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn material(label: &str) -> MaterialAsset {
MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: label.into(),
shader: Default::default(),
shader_ref: None,
render_state: Default::default(),
provenance: None,
inputs: Default::default(),
}
}
#[test]
fn live_edit_marks_one_document_dirty_without_writing_or_queueing_processing() {
let path = std::env::temp_dir().join(format!(
"blacksite-live-edit-no-publish-{}.material.ron",
uuid::Uuid::new_v4()
));
std::fs::write(&path, b"disk baseline").unwrap();
let key = AuthoredAssetDocumentKey::new(
"live-edit-material",
AuthoredAssetDocumentKind::Material,
);
let mut store = AuthoredAssetDocumentStore::default();
store.documents.insert(
key.clone(),
AuthoredAssetDocument::new(
key.clone(),
path.to_string_lossy().into_owned(),
AuthoredAssetValue::Material(material("Clean")),
FileSnapshot::capture(&path).unwrap(),
),
);
let mut world = World::new();
world.insert_resource(store);
world.init_resource::<ContentProcessingQueue>();
world.init_resource::<blacksite_surface::LiveMaterialDocumentOverlay>();
update_material_document(&mut world, &key, material("Live edit"));
assert_eq!(std::fs::read(&path).unwrap(), b"disk baseline");
let snapshot = world
.resource::<AuthoredAssetDocumentStore>()
.snapshot(&key)
.unwrap();
assert!(snapshot.dirty);
assert_eq!(snapshot.state, AuthoredDocumentState::Dirty);
let queue = world.resource::<ContentProcessingQueue>();
assert!(queue.pending.is_empty());
assert!(queue.active.is_none());
assert_eq!(
world
.resource::<blacksite_surface::LiveMaterialDocumentOverlay>()
.revision_for_asset(&key.asset_id),
Some(1)
);
std::fs::remove_file(path).unwrap();
}
}
@@ -0,0 +1,304 @@
use super::*;
pub(super) fn enqueue_processing(world: &mut World, key: &AuthoredAssetDocumentKey, revision: u64) {
let root = project_root(world);
let registry = world
.resource::<AuthoredAssetDocumentStore>()
.registry_clean
.clone()
.unwrap_or_else(|| world.resource::<AssetRegistry>().document());
let request = match key.kind {
AuthoredAssetDocumentKind::Material | AuthoredAssetDocumentKind::MaterialInstance => {
let Some(record) = registry
.records
.iter()
.find(|record| record.id.as_string() == key.asset_id)
.cloned()
else {
return;
};
ProcessingRequest::Material {
key: key.clone(),
revision,
root,
record,
registry,
}
}
AuthoredAssetDocumentKind::TextureImportSettings => {
let Some(record) = registry
.records
.iter()
.find(|record| record.id.as_string() == key.asset_id)
.cloned()
else {
return;
};
ProcessingRequest::Texture {
key: key.clone(),
revision,
root,
record,
registry,
}
}
AuthoredAssetDocumentKind::ModelImportSettings => {
let Some(record) = registry
.records
.iter()
.find(|record| record.id.as_string() == key.asset_id)
.cloned()
else {
return;
};
ProcessingRequest::Model {
key: key.clone(),
revision,
root,
record,
registry,
}
}
AuthoredAssetDocumentKind::ProjectContentDefaults => ProcessingRequest::Defaults {
key: key.clone(),
revision,
root,
registry,
},
};
let mut queue = world.resource_mut::<ContentProcessingQueue>();
queue.pending.retain(|pending| pending.key() != key);
queue.pending.push_back(request);
}
pub(super) fn drive_content_processing(world: &mut World) {
let completed = {
let mut queue = world.resource_mut::<ContentProcessingQueue>();
if queue
.active
.as_ref()
.is_some_and(|job| job.handle.is_finished())
{
queue.active.take()
} else {
None
}
};
if let Some(job) = completed {
let result = job
.handle
.join()
.unwrap_or_else(|_| Err("content processing worker panicked".into()));
finish_processing(world, job.key, job.revision, result);
}
let request = {
let mut queue = world.resource_mut::<ContentProcessingQueue>();
if queue.active.is_none() {
queue.pending.pop_front()
} else {
None
}
};
let Some(request) = request else {
return;
};
let key = request.key().clone();
let revision = request.revision();
if let Some(document) = world
.resource_mut::<AuthoredAssetDocumentStore>()
.documents
.get_mut(&key)
{
document.processing = DerivedProcessingState::Processing;
}
let handle = std::thread::spawn(move || process_request(request));
world.resource_mut::<ContentProcessingQueue>().active = Some(ActiveProcessingJob {
key,
revision,
handle,
});
}
pub(super) fn process_request(request: ProcessingRequest) -> Result<ProcessingOutput, String> {
match request {
ProcessingRequest::Material {
root,
record,
registry,
..
} => {
let mut runtime = runtime_catalog_with_previous_artifacts(&root, &registry);
let mut affected = vec![record.clone()];
if record.kind == AssetKind::Material {
affected.extend(content_pipeline::direct_material_instance_dependents(
&root, &registry, &record,
));
}
for affected_record in affected {
if let Some(plan) =
content_pipeline::plan_material_artifact(&root, &affected_record, &registry)?
{
content_pipeline::publish_material_artifact(&plan)?;
content_pipeline::apply_material_plan_to_catalog(
&mut runtime,
&affected_record.id,
&plan,
)?;
}
}
Ok(ProcessingOutput::RuntimeCatalog(runtime))
}
ProcessingRequest::Texture {
root,
record,
registry,
..
} => {
let mut runtime = runtime_catalog_with_previous_artifacts(&root, &registry);
let plan = content_pipeline::plan_texture_artifact(&root, &record)?;
content_pipeline::publish_texture_artifact(&plan)?;
content_pipeline::apply_texture_plan_to_catalog(&mut runtime, &record.id, &plan)?;
for material in
content_pipeline::material_dependents_of_texture(&root, &registry, &record)
{
if let Some(plan) =
content_pipeline::plan_material_artifact(&root, &material, &registry)?
{
content_pipeline::publish_material_artifact(&plan)?;
content_pipeline::apply_material_plan_to_catalog(
&mut runtime,
&material.id,
&plan,
)?;
}
}
Ok(ProcessingOutput::RuntimeCatalog(runtime))
}
ProcessingRequest::Model {
root,
record,
mut registry,
..
} => {
let plan = content_pipeline::plan_model_artifacts_at(&root, &record)?;
content_pipeline::publish_model_artifacts(&plan)?;
if let Some(current) = registry
.records
.iter_mut()
.find(|entry| entry.id == record.id)
{
*current = plan.record.clone();
}
let runtime = runtime_catalog_with_previous_artifacts(&root, &registry);
Ok(ProcessingOutput::Model { registry, runtime })
}
ProcessingRequest::Defaults { root, registry, .. } => Ok(ProcessingOutput::RuntimeCatalog(
runtime_catalog_with_previous_artifacts(&root, &registry),
)),
}
}
pub(super) fn runtime_catalog_with_previous_artifacts(
root: &Path,
registry: &AssetRegistryDocument,
) -> RuntimeContentCatalog {
let mut runtime = RuntimeContentCatalog::from(registry);
let previous = fs::read_to_string(root.join(content_pipeline::RUNTIME_CATALOG_PATH))
.ok()
.and_then(|source| ron::from_str::<RuntimeContentCatalog>(&source).ok());
if let Some(previous) = previous {
for record in &mut runtime.records {
if let Some(old) = previous.records.iter().find(|old| old.id == record.id) {
if old.texture.is_some() {
record.texture.clone_from(&old.texture);
}
if old.material.is_some() {
record.material.clone_from(&old.material);
}
}
}
}
runtime
}
pub(super) fn finish_processing(
world: &mut World,
key: AuthoredAssetDocumentKey,
revision: u64,
result: Result<ProcessingOutput, String>,
) {
let current_revision = world
.resource::<AuthoredAssetDocumentStore>()
.documents
.get(&key)
.map(|document| document.revision);
if current_revision != Some(revision) {
return;
}
match result {
Ok(output) => {
let root = project_root(world);
let (runtime, processed_registry) = match output {
ProcessingOutput::RuntimeCatalog(runtime) => (runtime, None),
ProcessingOutput::Model { registry, runtime } => (runtime, Some(registry)),
};
let catalog_path = root.join(content_pipeline::RUNTIME_CATALOG_PATH);
crate::assets::suppress_content_watch_path(world, &catalog_path);
if processed_registry.is_some() {
crate::assets::suppress_content_watch_path(
world,
&root.join(content_pipeline::REGISTRY_PATH),
);
}
let publication = (|| {
if let Some(registry) = processed_registry.as_ref() {
let registry_path = root.join(content_pipeline::REGISTRY_PATH);
let bytes = content_pipeline::serialize_registry(registry)?;
content_pipeline::write_if_changed(&registry_path, &bytes)?;
}
let bytes = content_pipeline::serialize_runtime_catalog(&runtime)?;
content_pipeline::write_if_changed(&catalog_path, &bytes).map(|_| ())
})();
if publication.is_ok() {
if let Some(registry) = processed_registry.as_ref() {
let registry_path = root.join(content_pipeline::REGISTRY_PATH);
let snapshot = FileSnapshot::capture(&registry_path)
.unwrap_or_else(|_| FileSnapshot::missing());
{
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
store.registry_clean = Some(registry.clone());
store.registry_snapshot = Some(snapshot);
}
apply_registry_to_world(world, registry);
reapply_unsaved_registry_overlays(world);
}
}
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
let document = store
.documents
.get_mut(&key)
.expect("processing document exists");
match publication {
Ok(()) => {
document.processing = DerivedProcessingState::Idle;
document.error = None;
}
Err(error) => {
document.processing = DerivedProcessingState::Failed;
document.error = Some(error);
}
}
}
Err(error) => {
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
if let Some(document) = store.documents.get_mut(&key) {
document.processing = DerivedProcessingState::Failed;
document.error = Some(error.clone());
}
world
.resource_mut::<SceneIo>()
.set_status(format!("Derived asset processing failed: {error}"));
}
}
}
@@ -0,0 +1,456 @@
use super::*;
pub fn request_contextual_save(world: &mut World) {
let active_dirty = world
.resource::<AuthoredAssetDocumentStore>()
.active
.as_ref()
.and_then(|key| {
world
.resource::<AuthoredAssetDocumentStore>()
.documents
.get(key)
})
.is_some_and(AuthoredAssetDocument::dirty);
if active_dirty {
world
.resource_mut::<AuthoredAssetDocumentStore>()
.request_save(AssetSaveRequest::Active);
} else if world
.get_resource::<settings::ProjectSettingsIo>()
.is_some_and(|io| io.dirty)
{
match crate::settings_ui::save_project_settings_if_dirty(world) {
Ok(_) => world
.resource_mut::<SceneIo>()
.set_status("Saved project settings"),
Err(error) => world
.resource_mut::<SceneIo>()
.set_status(format!("Save project settings failed: {error}")),
}
} else {
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Save);
}
}
pub fn request_save_all(world: &mut World) {
if let Err(error) = crate::settings_ui::save_project_settings_if_dirty(world) {
world
.resource_mut::<SceneIo>()
.set_status(format!("Save All project settings failed: {error}"));
return;
}
world
.resource_mut::<AuthoredAssetDocumentStore>()
.request_save(AssetSaveRequest::All);
crate::scene_io::request_scene_save_all(world);
}
pub fn save_all_authored_assets(world: &mut World) -> Result<usize, String> {
if !world.contains_resource::<AuthoredAssetDocumentStore>() {
return Ok(0);
}
save_documents(world, AssetSaveRequest::All)
}
pub fn discard_all_authored_assets(world: &mut World) {
if !world.contains_resource::<AuthoredAssetDocumentStore>() {
return;
}
let keys = world
.resource::<AuthoredAssetDocumentStore>()
.documents
.keys()
.cloned()
.collect::<Vec<_>>();
for key in &keys {
discard_document_recovery(world, key);
}
world
.resource_mut::<AuthoredAssetDocumentStore>()
.discard_all();
let clean_materials = world
.resource::<AuthoredAssetDocumentStore>()
.documents
.iter()
.filter_map(|(key, document)| match &document.clean {
AuthoredAssetValue::Material(asset) => Some((
key.asset_id.clone(),
document.revision,
LiveMaterialDocument::Material(asset.clone()),
)),
AuthoredAssetValue::MaterialInstance(instance) => Some((
key.asset_id.clone(),
document.revision,
LiveMaterialDocument::Instance(instance.clone()),
)),
_ => None,
})
.collect::<Vec<_>>();
if let Some(mut overlay) =
world.get_resource_mut::<blacksite_surface::LiveMaterialDocumentOverlay>()
{
for (asset_id, revision, document) in clean_materials {
match document {
LiveMaterialDocument::Material(asset) => {
overlay.update_material(asset_id, revision, asset);
}
LiveMaterialDocument::Instance(instance) => {
overlay.update_instance(asset_id, revision, instance);
}
}
}
}
if let Some(clean) = world
.resource::<AuthoredAssetDocumentStore>()
.registry_clean
.clone()
{
apply_registry_to_world(world, &clean);
}
}
pub(super) fn drive_asset_save_requests(world: &mut World) {
let request = world
.resource_mut::<AuthoredAssetDocumentStore>()
.pending_save
.take();
let Some(request) = request else {
return;
};
match save_documents(world, request) {
Ok(0) => world
.resource_mut::<SceneIo>()
.set_status("No dirty asset documents to save"),
Ok(count) => world
.resource_mut::<SceneIo>()
.set_status(format!("Saved {count} asset document(s)")),
Err(error) => world.resource_mut::<SceneIo>().set_status(error),
}
}
pub(super) fn save_documents(
world: &mut World,
request: AssetSaveRequest,
) -> Result<usize, String> {
let keys = {
let store = world.resource::<AuthoredAssetDocumentStore>();
match request {
AssetSaveRequest::Active => store
.active
.iter()
.filter(|key| {
store
.documents
.get(*key)
.is_some_and(AuthoredAssetDocument::dirty)
})
.cloned()
.collect::<Vec<_>>(),
AssetSaveRequest::All => store
.documents
.iter()
.filter(|(_, document)| document.dirty())
.map(|(key, _)| key.clone())
.collect::<Vec<_>>(),
}
};
if keys.is_empty() {
return Ok(0);
}
let mut registry_keys = Vec::new();
let mut saved = 0;
for key in keys {
if matches!(
key.kind,
AuthoredAssetDocumentKind::ModelImportSettings
| AuthoredAssetDocumentKind::TextureImportSettings
| AuthoredAssetDocumentKind::ProjectContentDefaults
) {
registry_keys.push(key);
continue;
}
save_file_document(world, &key)?;
saved += 1;
}
if !registry_keys.is_empty() {
saved += save_registry_documents(world, &registry_keys)?;
}
Ok(saved)
}
pub(super) fn save_file_document(
world: &mut World,
key: &AuthoredAssetDocumentKey,
) -> Result<(), String> {
let (path, clean, value, snapshot, revision) = {
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
let document = store
.documents
.get_mut(key)
.ok_or_else(|| "authored asset document disappeared before save".to_string())?;
document.state = AuthoredDocumentState::Saving;
(
document.path.clone(),
document.clean.clone(),
document.current.clone(),
document.disk_snapshot.clone(),
document.revision,
)
};
let processing_impact = derived_processing_impact(&clean, &value);
let (bytes, intent) = match &value {
AuthoredAssetValue::Material(asset) => (
ron::ser::to_string_pretty(asset, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize Material {path}: {error}"))?
.into_bytes(),
FileWriteIntent::Material,
),
AuthoredAssetValue::MaterialInstance(asset) => (
ron::ser::to_string_pretty(asset, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize Material Instance {path}: {error}"))?
.into_bytes(),
FileWriteIntent::MaterialInstance,
),
_ => return Err("registry-backed document used the file-document save path".into()),
};
crate::assets::suppress_content_watch_path(world, Path::new(&path));
match publish_authored_file(world, Path::new(&path), &bytes, &snapshot, intent) {
Ok(disk_snapshot) => {
let label = match &value {
AuthoredAssetValue::Material(asset) => asset.label.as_str(),
AuthoredAssetValue::MaterialInstance(asset) => asset.label.as_str(),
_ => "",
}
.to_string();
{
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
let document = store.documents.get_mut(key).expect("saved document exists");
document.clean = value;
document.disk_snapshot = disk_snapshot;
document.state = AuthoredDocumentState::Clean;
document.processing = if processing_impact == DerivedProcessingImpact::None {
DerivedProcessingState::Idle
} else {
DerivedProcessingState::Queued
};
document.error = None;
document.changed_at = None;
}
if let Some(asset) = world
.resource_mut::<EditorAssets>()
.assets
.iter_mut()
.find(|asset| asset.path.as_deref() == Some(path.as_str()))
{
asset.label = label;
}
discard_document_recovery(world, key);
if processing_impact != DerivedProcessingImpact::None {
enqueue_processing(world, key, revision);
}
Ok(())
}
Err(error) => {
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
let document = store
.documents
.get_mut(key)
.expect("failed document exists");
document.state = if error.contains("changed outside") || error.contains("read-only") {
AuthoredDocumentState::ExternalConflict
} else {
AuthoredDocumentState::SaveFailed
};
document.error = Some(error.clone());
Err(error)
}
}
}
pub(super) fn save_registry_documents(
world: &mut World,
keys: &[AuthoredAssetDocumentKey],
) -> Result<usize, String> {
let root = project_root(world);
let path = root.join(content_pipeline::REGISTRY_PATH);
let (mut document, snapshot) = {
let store = world.resource::<AuthoredAssetDocumentStore>();
(
store
.registry_clean
.clone()
.unwrap_or_else(|| world.resource::<AssetRegistry>().document()),
store
.registry_snapshot
.clone()
.unwrap_or_else(FileSnapshot::missing),
)
};
for key in keys {
let store = world.resource::<AuthoredAssetDocumentStore>();
let authored = store
.documents
.get(key)
.ok_or_else(|| "registry-backed document disappeared before save".to_string())?;
apply_registry_value(&mut document, key, &authored.current)?;
}
let bytes = content_pipeline::serialize_registry(&document)?;
crate::assets::suppress_content_watch_path(world, &path);
let intent = FileWriteIntent::AssetRegistry;
let disk_snapshot = match publish_authored_file(world, &path, &bytes, &snapshot, intent) {
Ok(snapshot) => snapshot,
Err(error) => {
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
for key in keys {
if let Some(authored) = store.documents.get_mut(key) {
authored.state = AuthoredDocumentState::ExternalConflict;
authored.error = Some(error.clone());
}
}
return Err(error);
}
};
let impacts = {
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
let impacts = keys
.iter()
.filter_map(|key| {
store.documents.get(key).map(|document| {
(
key.clone(),
derived_processing_impact(&document.clean, &document.current),
)
})
})
.collect::<HashMap<_, _>>();
store.registry_clean = Some(document.clone());
store.registry_snapshot = Some(disk_snapshot.clone());
for key in keys {
if let Some(authored) = store.documents.get_mut(key) {
authored.clean = authored.current.clone();
authored.disk_snapshot = disk_snapshot.clone();
authored.state = AuthoredDocumentState::Clean;
authored.processing = if impacts.get(key).copied().unwrap_or_default()
== DerivedProcessingImpact::None
{
DerivedProcessingState::Idle
} else {
DerivedProcessingState::Queued
};
authored.error = None;
authored.changed_at = None;
}
}
impacts
};
apply_registry_to_world(world, &document);
reapply_unsaved_registry_overlays(world);
for key in keys {
discard_document_recovery(world, key);
let revision = world
.resource::<AuthoredAssetDocumentStore>()
.documents
.get(key)
.map(|document| document.revision)
.unwrap_or_default();
if impacts.get(key).copied().unwrap_or_default() != DerivedProcessingImpact::None {
enqueue_processing(world, key, revision);
}
}
Ok(keys.len())
}
pub(super) fn derived_processing_impact(
clean: &AuthoredAssetValue,
current: &AuthoredAssetValue,
) -> DerivedProcessingImpact {
match (clean, current) {
(AuthoredAssetValue::Material(clean), AuthoredAssetValue::Material(current)) => {
material_impact(clean, current)
}
(
AuthoredAssetValue::MaterialInstance(clean),
AuthoredAssetValue::MaterialInstance(current),
) => instance_impact(clean, current),
(
AuthoredAssetValue::TextureImportSettings(_),
AuthoredAssetValue::TextureImportSettings(_),
) => DerivedProcessingImpact::TextureAndDependents,
(
AuthoredAssetValue::ModelImportSettings(_),
AuthoredAssetValue::ModelImportSettings(_),
) => DerivedProcessingImpact::ModelArtifacts,
(
AuthoredAssetValue::ProjectContentDefaults(_),
AuthoredAssetValue::ProjectContentDefaults(_),
) => DerivedProcessingImpact::CatalogDefaults,
_ => DerivedProcessingImpact::None,
}
}
pub(super) fn apply_registry_value(
document: &mut AssetRegistryDocument,
key: &AuthoredAssetDocumentKey,
value: &AuthoredAssetValue,
) -> Result<(), String> {
match value {
AuthoredAssetValue::ModelImportSettings(settings) => {
let record = document
.records
.iter_mut()
.find(|record| record.id.as_string() == key.asset_id)
.ok_or_else(|| format!("registry is missing model {}", key.asset_id))?;
record.import_settings = settings.clone().into();
}
AuthoredAssetValue::TextureImportSettings(settings) => {
let record = document
.records
.iter_mut()
.find(|record| record.id.as_string() == key.asset_id)
.ok_or_else(|| format!("registry is missing Texture {}", key.asset_id))?;
record.import_settings = settings.clone().into();
}
AuthoredAssetValue::ProjectContentDefaults(defaults) => {
document.defaults = defaults.clone();
}
_ => return Err("file-backed document used the registry save path".into()),
}
Ok(())
}
pub(super) fn apply_registry_to_world(world: &mut World, document: &AssetRegistryDocument) {
{
let mut registry = world.resource_mut::<AssetRegistry>();
registry.schema_version = document.schema_version;
registry.defaults = document.defaults.clone();
registry.records = document.records.clone();
registry.index_dirty = false;
registry.migration_required = false;
}
*world.resource_mut::<ProjectContentDefaults>() = document.defaults.clone();
}
pub(super) fn reapply_unsaved_registry_overlays(world: &mut World) {
let overlays = world
.resource::<AuthoredAssetDocumentStore>()
.documents
.iter()
.filter(|(key, document)| {
document.dirty()
&& matches!(
key.kind,
AuthoredAssetDocumentKind::ModelImportSettings
| AuthoredAssetDocumentKind::TextureImportSettings
| AuthoredAssetDocumentKind::ProjectContentDefaults
)
})
.map(|(key, document)| (key.clone(), document.current.clone()))
.collect::<Vec<_>>();
let mut effective = world.resource::<AssetRegistry>().document();
for (key, value) in overlays {
let _ = apply_registry_value(&mut effective, &key, &value);
}
apply_registry_to_world(world, &effective);
}
@@ -0,0 +1,608 @@
use super::*;
pub(super) fn tick_asset_recovery(world: &mut World) {
let (ready, stale) = {
let now = Instant::now();
let store = world.resource::<AuthoredAssetDocumentStore>();
let ready = store
.documents
.values()
.filter(|document| {
document.dirty()
&& document.recovery_revision != Some(document.revision)
&& document
.changed_at
.is_some_and(|changed| now.duration_since(changed) >= RECOVERY_IDLE)
})
.map(|document| document.key.clone())
.collect::<Vec<_>>();
let stale = stale_recovery_keys(store);
(ready, stale)
};
for key in stale {
if let Err(error) = remove_document_recovery(world, &key) {
if let Some(document) = world
.resource_mut::<AuthoredAssetDocumentStore>()
.documents
.get_mut(&key)
{
document.error = Some(format!("Recovery cleanup failed: {error}"));
}
continue;
}
if let Some(document) = world
.resource_mut::<AuthoredAssetDocumentStore>()
.documents
.get_mut(&key)
{
document.recovery_revision = None;
}
}
for key in ready {
if let Err(error) = write_document_recovery(world, &key) {
if let Some(document) = world
.resource_mut::<AuthoredAssetDocumentStore>()
.documents
.get_mut(&key)
{
document.error = Some(format!("Recovery snapshot failed: {error}"));
}
}
}
}
fn stale_recovery_keys(store: &AuthoredAssetDocumentStore) -> Vec<AuthoredAssetDocumentKey> {
store
.documents
.values()
.filter(|document| !document.dirty() && document.recovery_revision.is_some())
.map(|document| document.key.clone())
.collect()
}
pub(super) fn write_document_recovery(
world: &mut World,
key: &AuthoredAssetDocumentKey,
) -> Result<(), String> {
let root = project_root(world);
let state_root =
default_state_root().ok_or_else(|| "editor state directory is unavailable".to_string())?;
let (envelope, revision) = {
let store = world.resource::<AuthoredAssetDocumentStore>();
let document = store
.documents
.get(key)
.ok_or_else(|| "recovery document is missing".to_string())?;
(
RecoveryEnvelope {
key: key.clone(),
path: document.path.clone(),
baseline_revision: revision_label(&document.disk_snapshot.revision),
value: document.current.clone(),
},
document.revision,
)
};
let directory = recovery_directory(&state_root, &root, key);
fs::create_dir_all(&directory)
.map_err(|error| format!("could not create {}: {error}", directory.display()))?;
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis();
let path = directory.join(format!("recovery-{timestamp:020}.ron"));
let bytes = ron::ser::to_string_pretty(&envelope, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize asset recovery: {error}"))?;
atomic_write(&path, bytes.as_bytes())?;
prune_recovery(&directory)?;
if let Some(document) = world
.resource_mut::<AuthoredAssetDocumentStore>()
.documents
.get_mut(key)
{
document.recovery_revision = Some(revision);
}
Ok(())
}
pub(super) fn discover_asset_recovery(world: &mut World) {
let root = project_root(world);
let Some(state_root) = default_state_root() else {
return;
};
let base = state_root
.join("asset-recovery")
.join(blake3::hash(normalize_path(&root.to_string_lossy()).as_bytes()).to_hex());
let Ok(entries) = fs::read_dir(base) else {
return;
};
let mut recovered = Vec::new();
for directory in entries.filter_map(Result::ok).map(|entry| entry.path()) {
let Ok(files) = fs::read_dir(directory) else {
continue;
};
let latest = files
.filter_map(Result::ok)
.map(|entry| entry.path())
.max_by_key(|path| path.file_name().map(|name| name.to_os_string()));
if let Some(envelope) = latest
.and_then(|path| fs::read_to_string(path).ok())
.and_then(|source| ron::from_str::<RecoveryEnvelope>(&source).ok())
{
if !recovery_requires_prompt(
load_clean_recovery_value(world, &envelope).as_ref(),
&envelope.value,
) {
let _ = remove_document_recovery(world, &envelope.key);
continue;
}
recovered.push(envelope);
}
}
if !recovered.is_empty() {
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
store.pending_recovery = recovered;
store.recovery_prompt_open = true;
}
}
fn recovery_requires_prompt(
clean: Option<&AuthoredAssetValue>,
recovered: &AuthoredAssetValue,
) -> bool {
clean != Some(recovered)
}
pub fn asset_recovery_modal(world: &mut World, ctx: &bevy_egui::egui::Context) {
let open = world
.resource::<AuthoredAssetDocumentStore>()
.recovery_prompt_open;
if !open {
return;
}
let pending = world
.resource::<AuthoredAssetDocumentStore>()
.pending_recovery
.clone();
let mut restore = false;
let mut discard = false;
let mut review = false;
let mut restore_one = None;
let mut discard_one = None;
let reviewing = world
.resource::<AuthoredAssetDocumentStore>()
.recovery_reviewing;
bevy_egui::egui::Modal::new(bevy_egui::egui::Id::new("asset_document_recovery")).show(ctx, |ui| {
ui.heading("Unsaved asset recovery");
ui.label("Blacksite found editor-local asset edits that were never written to project source files.");
bevy_egui::egui::ScrollArea::vertical()
.max_height(180.0)
.show(ui, |ui| {
for envelope in &pending {
ui.horizontal(|ui| {
ui.strong(envelope.key.kind.slug());
ui.monospace(&envelope.path);
if reviewing {
if ui.small_button("Restore").clicked() {
restore_one = Some(envelope.key.clone());
}
if ui.small_button("Discard").clicked() {
discard_one = Some(envelope.key.clone());
}
}
});
}
});
ui.horizontal(|ui| {
restore = ui.button("Restore All").clicked();
review = ui.button("Review").clicked();
discard = ui.button("Discard All").clicked();
});
});
if let Some(key) = restore_one {
restore_pending_recovery_key(world, &key, true);
} else if let Some(key) = discard_one {
restore_pending_recovery_key(world, &key, false);
} else if review {
world
.resource_mut::<AuthoredAssetDocumentStore>()
.recovery_reviewing = true;
} else if restore {
restore_pending_recovery(world);
} else if discard {
discard_pending_recovery(world);
}
}
pub(crate) fn reload_registry_documents_after_file_conflict(
world: &mut World,
) -> Result<String, String> {
let root = project_root(world);
let path = root.join(content_pipeline::REGISTRY_PATH);
let source = fs::read_to_string(&path)
.map_err(|error| format!("could not read {}: {error}", path.display()))?;
let loaded = shared::parse_asset_registry(&source)?;
let snapshot = FileSnapshot::from_loaded_bytes(&path, source.as_bytes());
let registry_kinds = [
AuthoredAssetDocumentKind::ModelImportSettings,
AuthoredAssetDocumentKind::TextureImportSettings,
AuthoredAssetDocumentKind::ProjectContentDefaults,
];
let keys = world
.resource::<AuthoredAssetDocumentStore>()
.documents
.keys()
.filter(|key| registry_kinds.contains(&key.kind))
.cloned()
.collect::<Vec<_>>();
for key in &keys {
discard_document_recovery(world, key);
}
{
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
for key in &keys {
store.documents.remove(key);
}
store
.path_index
.retain(|_, key| !registry_kinds.contains(&key.kind));
store.registry_clean = Some(loaded.document.clone());
store.registry_snapshot = Some(snapshot);
}
apply_registry_to_world(world, &loaded.document);
Ok(format!("Reloaded asset registry from {}", path.display()))
}
pub(crate) fn adopt_external_registry_document(
world: &mut World,
document: &AssetRegistryDocument,
) {
if !world.contains_resource::<AuthoredAssetDocumentStore>() {
apply_registry_to_world(world, document);
return;
}
let path = project_root(world).join(content_pipeline::REGISTRY_PATH);
let snapshot = FileSnapshot::capture(&path).unwrap_or_else(|_| FileSnapshot::missing());
{
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
store.registry_clean = Some(document.clone());
store.registry_snapshot = Some(snapshot);
}
apply_registry_to_world(world, document);
reapply_unsaved_registry_overlays(world);
}
pub(super) fn restore_pending_recovery(world: &mut World) {
let pending = {
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
store.recovery_prompt_open = false;
std::mem::take(&mut store.pending_recovery)
};
for envelope in pending {
restore_recovery_envelope(world, envelope);
}
reapply_unsaved_registry_overlays(world);
}
pub(super) fn restore_pending_recovery_key(
world: &mut World,
key: &AuthoredAssetDocumentKey,
restore: bool,
) {
let envelope = {
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
let Some(index) = store
.pending_recovery
.iter()
.position(|envelope| &envelope.key == key)
else {
return;
};
let envelope = store.pending_recovery.remove(index);
if store.pending_recovery.is_empty() {
store.recovery_prompt_open = false;
store.recovery_reviewing = false;
}
envelope
};
if restore {
restore_recovery_envelope(world, envelope);
reapply_unsaved_registry_overlays(world);
} else {
discard_document_recovery(world, &envelope.key);
}
}
pub(super) fn restore_recovery_envelope(world: &mut World, envelope: RecoveryEnvelope) {
let snapshot_path = source_path_for_recovery(world, &envelope);
let snapshot =
FileSnapshot::capture(&snapshot_path).unwrap_or_else(|_| FileSnapshot::missing());
let state = if revision_label(&snapshot.revision) == envelope.baseline_revision {
AuthoredDocumentState::Dirty
} else {
AuthoredDocumentState::ExternalConflict
};
let clean =
load_clean_recovery_value(world, &envelope).unwrap_or_else(|| envelope.value.clone());
let mut document =
AuthoredAssetDocument::new(envelope.key.clone(), envelope.path.clone(), clean, snapshot);
document.current = envelope.value;
document.revision = 1;
document.state = state;
document.changed_at = Some(Instant::now());
if state == AuthoredDocumentState::ExternalConflict {
document.error = Some("Source changed since this recovery snapshot was created".into());
}
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
store
.path_index
.insert(normalize_path(&document.path), envelope.key.clone());
store.documents.insert(envelope.key.clone(), document);
store.active = Some(envelope.key);
}
pub(super) fn discard_pending_recovery(world: &mut World) {
let keys = {
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
store.recovery_prompt_open = false;
store.recovery_reviewing = false;
std::mem::take(&mut store.pending_recovery)
.into_iter()
.map(|envelope| envelope.key)
.collect::<Vec<_>>()
};
for key in keys {
discard_document_recovery(world, &key);
}
}
pub(super) fn load_clean_recovery_value(
world: &World,
envelope: &RecoveryEnvelope,
) -> Option<AuthoredAssetValue> {
match envelope.key.kind {
AuthoredAssetDocumentKind::Material => MaterialAsset::load_from_path(&envelope.path)
.ok()
.map(AuthoredAssetValue::Material),
AuthoredAssetDocumentKind::MaterialInstance => {
MaterialInstanceAsset::load_from_path(&envelope.path)
.ok()
.map(AuthoredAssetValue::MaterialInstance)
}
AuthoredAssetDocumentKind::ModelImportSettings => world
.resource::<AssetRegistry>()
.records
.iter()
.find(|record| record.id.as_string() == envelope.key.asset_id)
.map(|record| AuthoredAssetValue::ModelImportSettings(record.model_import().clone())),
AuthoredAssetDocumentKind::TextureImportSettings => world
.resource::<AssetRegistry>()
.records
.iter()
.find(|record| record.id.as_string() == envelope.key.asset_id)
.and_then(|record| record.texture_import().cloned())
.map(AuthoredAssetValue::TextureImportSettings),
AuthoredAssetDocumentKind::ProjectContentDefaults => {
Some(AuthoredAssetValue::ProjectContentDefaults(
world.resource::<AssetRegistry>().defaults.clone(),
))
}
}
}
pub(super) fn source_path_for_recovery(world: &World, envelope: &RecoveryEnvelope) -> PathBuf {
match envelope.key.kind {
AuthoredAssetDocumentKind::Material | AuthoredAssetDocumentKind::MaterialInstance => {
PathBuf::from(&envelope.path)
}
_ => project_root(world).join(content_pipeline::REGISTRY_PATH),
}
}
pub(super) fn discard_document_recovery(world: &World, key: &AuthoredAssetDocumentKey) {
let _ = remove_document_recovery(world, key);
}
fn remove_document_recovery(world: &World, key: &AuthoredAssetDocumentKey) -> Result<(), String> {
let Some(state_root) = default_state_root() else {
return Ok(());
};
let directory = recovery_directory(&state_root, &project_root(world), key);
match fs::remove_dir_all(&directory) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(format!("could not remove {}: {error}", directory.display())),
}
}
pub(super) fn recovery_directory(
state_root: &Path,
project_root: &Path,
key: &AuthoredAssetDocumentKey,
) -> PathBuf {
let project = blake3::hash(normalize_path(&project_root.to_string_lossy()).as_bytes());
state_root
.join("asset-recovery")
.join(project.to_hex())
.join(format!("{}-{}", key.kind.slug(), key.asset_id))
}
pub(super) fn prune_recovery(directory: &Path) -> Result<(), String> {
let mut files = fs::read_dir(directory)
.map_err(|error| format!("could not read {}: {error}", directory.display()))?
.filter_map(Result::ok)
.map(|entry| entry.path())
.collect::<Vec<_>>();
files.sort();
let remove = files.len().saturating_sub(RECOVERY_GENERATIONS);
for path in files.into_iter().take(remove) {
fs::remove_file(&path)
.map_err(|error| format!("could not prune {}: {error}", path.display()))?;
}
Ok(())
}
pub(super) fn revision_label(revision: &FileRevision) -> String {
match revision {
FileRevision::Missing => "missing".into(),
FileRevision::Present(hash) => hash.iter().map(|byte| format!("{byte:02x}")).collect(),
}
}
pub(super) fn project_root(world: &World) -> PathBuf {
world
.get_resource::<ProjectWorkspace>()
.map(|workspace| PathBuf::from(&workspace.root))
.unwrap_or_else(|| PathBuf::from("."))
}
pub(super) fn normalize_path(path: &str) -> String {
path.replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
fn material(label: &str) -> MaterialAsset {
MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: label.into(),
shader: Default::default(),
shader_ref: None,
render_state: Default::default(),
provenance: None,
inputs: Default::default(),
}
}
#[test]
fn dirty_state_is_derived_from_the_clean_document() {
let key = AuthoredAssetDocumentKey::new("material-id", AuthoredAssetDocumentKind::Material);
let mut store = AuthoredAssetDocumentStore::default();
store.documents.insert(
key.clone(),
AuthoredAssetDocument::new(
key.clone(),
"assets/materials/test.ron".into(),
AuthoredAssetValue::Material(material("Clean")),
FileSnapshot::missing(),
),
);
store.update_material(&key, material("Dirty"));
assert!(store.snapshot(&key).unwrap().dirty);
assert_eq!(store.active_key(), Some(&key));
store.update_material(&key, material("Clean"));
assert!(!store.snapshot(&key).unwrap().dirty);
assert_eq!(
store.snapshot(&key).unwrap().state,
AuthoredDocumentState::Clean
);
assert!(store
.documents
.get(&key)
.is_some_and(|document| document.recovery_revision.is_none()));
}
#[test]
fn returning_to_clean_marks_an_existing_recovery_for_cleanup() {
let key = AuthoredAssetDocumentKey::new("material-id", AuthoredAssetDocumentKind::Material);
let mut store = AuthoredAssetDocumentStore::default();
store.documents.insert(
key.clone(),
AuthoredAssetDocument::new(
key.clone(),
"assets/materials/test.ron".into(),
AuthoredAssetValue::Material(material("Clean")),
FileSnapshot::missing(),
),
);
store.update_material(&key, material("Dirty"));
let document = store.documents.get_mut(&key).unwrap();
document.recovery_revision = Some(document.revision);
store.update_material(&key, material("Clean"));
assert_eq!(stale_recovery_keys(&store), vec![key]);
}
#[test]
fn recovery_equal_to_authoritative_source_never_prompts() {
let clean = AuthoredAssetValue::Material(material("Clean"));
let dirty = AuthoredAssetValue::Material(material("Dirty"));
assert!(!recovery_requires_prompt(Some(&clean), &clean));
assert!(recovery_requires_prompt(Some(&clean), &dirty));
assert!(recovery_requires_prompt(None, &dirty));
}
#[test]
fn dirty_documents_survive_switching_active_context() {
let first = AuthoredAssetDocumentKey::new("first", AuthoredAssetDocumentKind::Material);
let second = AuthoredAssetDocumentKey::new("second", AuthoredAssetDocumentKind::Material);
let mut store = AuthoredAssetDocumentStore::default();
for key in [&first, &second] {
store.documents.insert(
key.clone(),
AuthoredAssetDocument::new(
key.clone(),
format!("assets/{key:?}.ron"),
AuthoredAssetValue::Material(material("Clean")),
FileSnapshot::missing(),
),
);
}
store.update_material(&first, material("First dirty"));
store.update_material(&second, material("Second dirty"));
assert_eq!(store.dirty_count(), 2);
assert_eq!(store.active_key(), Some(&second));
}
#[test]
fn registry_patch_updates_only_the_selected_record() {
let first_id = AssetId::new();
let second_id = AssetId::new();
let mut document = AssetRegistryDocument {
records: vec![
AssetRecord {
id: first_id.clone(),
path: "assets/first.glb".into(),
label: "First".into(),
kind: AssetKind::Model,
source_fingerprint: None,
import_settings: ModelImportSettings::default().into(),
dependencies: Vec::new(),
},
AssetRecord {
id: second_id.clone(),
path: "assets/second.glb".into(),
label: "Second".into(),
kind: AssetKind::Model,
source_fingerprint: None,
import_settings: ModelImportSettings::default().into(),
dependencies: Vec::new(),
},
],
..Default::default()
};
let changed = ModelImportSettings {
scale: 2.0,
..Default::default()
};
apply_registry_value(
&mut document,
&AuthoredAssetDocumentKey::new(
first_id.as_string(),
AuthoredAssetDocumentKind::ModelImportSettings,
),
&AuthoredAssetValue::ModelImportSettings(changed),
)
.unwrap();
assert_eq!(document.records[0].model_import().scale, 2.0);
assert_eq!(document.records[1].model_import().scale, 1.0);
}
}
@@ -0,0 +1,320 @@
use super::*;
#[derive(Resource, Default)]
pub struct ContentProcessingQueue {
pub(super) pending: VecDeque<ProcessingRequest>,
pub(super) active: Option<ActiveProcessingJob>,
}
#[derive(Debug, Clone)]
pub(super) enum ProcessingRequest {
Material {
key: AuthoredAssetDocumentKey,
revision: u64,
root: PathBuf,
record: AssetRecord,
registry: AssetRegistryDocument,
},
Texture {
key: AuthoredAssetDocumentKey,
revision: u64,
root: PathBuf,
record: AssetRecord,
registry: AssetRegistryDocument,
},
Model {
key: AuthoredAssetDocumentKey,
revision: u64,
root: PathBuf,
record: AssetRecord,
registry: AssetRegistryDocument,
},
Defaults {
key: AuthoredAssetDocumentKey,
revision: u64,
root: PathBuf,
registry: AssetRegistryDocument,
},
}
impl ProcessingRequest {
pub(super) fn key(&self) -> &AuthoredAssetDocumentKey {
match self {
Self::Material { key, .. }
| Self::Texture { key, .. }
| Self::Model { key, .. }
| Self::Defaults { key, .. } => key,
}
}
pub(super) fn revision(&self) -> u64 {
match self {
Self::Material { revision, .. }
| Self::Texture { revision, .. }
| Self::Model { revision, .. }
| Self::Defaults { revision, .. } => *revision,
}
}
}
pub(super) struct ActiveProcessingJob {
pub(super) key: AuthoredAssetDocumentKey,
pub(super) revision: u64,
pub(super) handle: JoinHandle<Result<ProcessingOutput, String>>,
}
pub(super) enum ProcessingOutput {
RuntimeCatalog(RuntimeContentCatalog),
Model {
registry: AssetRegistryDocument,
runtime: RuntimeContentCatalog,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(super) struct RecoveryEnvelope {
pub(super) key: AuthoredAssetDocumentKey,
pub(super) path: String,
pub(super) baseline_revision: String,
pub(super) value: AuthoredAssetValue,
}
pub struct AuthoredAssetDocumentsPlugin;
impl Plugin for AuthoredAssetDocumentsPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<AuthoredAssetDocumentStore>()
.init_resource::<ContentProcessingQueue>()
.add_systems(Startup, discover_asset_recovery)
.add_systems(
Update,
(
drive_asset_save_requests,
drive_content_processing,
tick_asset_recovery,
)
.chain(),
);
}
}
pub fn ensure_material_document(
world: &mut World,
path: &str,
fallback_label: &str,
) -> AuthoredAssetDocumentKey {
ensure_file_document(world, path, AuthoredAssetDocumentKind::Material, || {
MaterialAsset::load_from_path(path)
.map(AuthoredAssetValue::Material)
.unwrap_or_else(|_| {
AuthoredAssetValue::Material(MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: fallback_label.to_string(),
shader: Default::default(),
shader_ref: None,
render_state: shared::MaterialRenderState::default(),
provenance: None,
inputs: shared::MaterialInputSet::default(),
})
})
})
}
pub fn ensure_material_instance_document(
world: &mut World,
path: &str,
fallback_label: &str,
) -> AuthoredAssetDocumentKey {
ensure_file_document(
world,
path,
AuthoredAssetDocumentKind::MaterialInstance,
|| {
MaterialInstanceAsset::load_from_path(path)
.map(AuthoredAssetValue::MaterialInstance)
.unwrap_or_else(|_| {
AuthoredAssetValue::MaterialInstance(MaterialInstanceAsset {
schema_version: shared::MATERIAL_INSTANCE_SCHEMA_VERSION,
label: fallback_label.to_string(),
base: Default::default(),
overrides: Default::default(),
})
})
},
)
}
pub(crate) fn reload_file_document_after_conflict(
world: &mut World,
path: &Path,
kind: AuthoredAssetDocumentKind,
) -> Result<String, String> {
let normalized = normalize_path(&path.to_string_lossy());
let key = world
.resource::<AuthoredAssetDocumentStore>()
.path_index
.get(&normalized)
.filter(|key| key.kind == kind)
.cloned()
.ok_or_else(|| "the conflicted asset document is no longer open".to_string())?;
discard_document_recovery(world, &key);
{
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
store.documents.remove(&key);
store.path_index.remove(&normalized);
if store.active.as_ref() == Some(&key) {
store.active = None;
}
}
if let Some(mut overlay) =
world.get_resource_mut::<blacksite_surface::LiveMaterialDocumentOverlay>()
{
overlay.remove(&key.asset_id);
}
if let Some(mut cache) = world.get_resource_mut::<blacksite_surface::SurfaceMaterialCache>() {
cache.invalidate_disk_documents();
}
Ok(format!("Reloaded {} from disk", path.display()))
}
pub(crate) fn adopt_material_conflict_save_as(
world: &mut World,
original_path: &Path,
catalog_path: &str,
kind: AuthoredAssetDocumentKind,
) -> Result<String, String> {
let original = normalize_path(&original_path.to_string_lossy());
if let Some(key) = world
.resource::<AuthoredAssetDocumentStore>()
.path_index
.get(&original)
.filter(|key| key.kind == kind)
.cloned()
{
discard_document_recovery(world, &key);
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
store.documents.remove(&key);
store.path_index.remove(&original);
if store.active.as_ref() == Some(&key) {
store.active = None;
}
}
match kind {
AuthoredAssetDocumentKind::Material => {
ensure_material_document(world, catalog_path, "Material copy");
}
AuthoredAssetDocumentKind::MaterialInstance => {
ensure_material_instance_document(world, catalog_path, "Material Instance copy");
}
_ => return Err("Save As adoption requires a Material document".into()),
}
Ok(format!("Saved material copy to {catalog_path}"))
}
pub(super) fn ensure_file_document(
world: &mut World,
path: &str,
kind: AuthoredAssetDocumentKind,
load: impl FnOnce() -> AuthoredAssetValue,
) -> AuthoredAssetDocumentKey {
let normalized = normalize_path(path);
if let Some(key) = world
.resource::<AuthoredAssetDocumentStore>()
.path_index
.get(&normalized)
.filter(|key| key.kind == kind)
.cloned()
{
return key;
}
let asset_id = world
.resource::<AssetRegistry>()
.records
.iter()
.find(|record| normalize_path(&record.path) == normalized)
.map(|record| record.id.as_string())
.unwrap_or_else(|| format!("path:{}", blake3::hash(normalized.as_bytes()).to_hex()));
let key = AuthoredAssetDocumentKey::new(asset_id, kind);
let snapshot =
FileSnapshot::capture(Path::new(path)).unwrap_or_else(|_| FileSnapshot::missing());
let document = AuthoredAssetDocument::new(key.clone(), normalized.clone(), load(), snapshot);
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
store.path_index.insert(normalized, key.clone());
store.documents.insert(key.clone(), document);
key
}
pub fn ensure_model_import_document(
world: &mut World,
record: &AssetRecord,
) -> AuthoredAssetDocumentKey {
ensure_registry_document(
world,
record.id.clone(),
&record.path,
AuthoredAssetDocumentKind::ModelImportSettings,
AuthoredAssetValue::ModelImportSettings(record.model_import().clone()),
)
}
pub fn ensure_texture_import_document(
world: &mut World,
record: &AssetRecord,
) -> AuthoredAssetDocumentKey {
ensure_registry_document(
world,
record.id.clone(),
&record.path,
AuthoredAssetDocumentKind::TextureImportSettings,
AuthoredAssetValue::TextureImportSettings(
record.texture_import().cloned().unwrap_or_default(),
),
)
}
pub fn ensure_content_defaults_document(world: &mut World) -> AuthoredAssetDocumentKey {
let defaults = world.resource::<AssetRegistry>().defaults.clone();
ensure_registry_document(
world,
AssetId(uuid::Uuid::nil()),
content_pipeline::REGISTRY_PATH,
AuthoredAssetDocumentKind::ProjectContentDefaults,
AuthoredAssetValue::ProjectContentDefaults(defaults),
)
}
pub(super) fn ensure_registry_document(
world: &mut World,
asset_id: AssetId,
logical_path: &str,
kind: AuthoredAssetDocumentKind,
value: AuthoredAssetValue,
) -> AuthoredAssetDocumentKey {
let key = AuthoredAssetDocumentKey::new(asset_id.as_string(), kind);
if world
.resource::<AuthoredAssetDocumentStore>()
.documents
.contains_key(&key)
{
return key;
}
let root = project_root(world);
let registry_path = root.join(content_pipeline::REGISTRY_PATH);
let snapshot =
FileSnapshot::capture(&registry_path).unwrap_or_else(|_| FileSnapshot::missing());
let registry = world.resource::<AssetRegistry>().document();
let document = AuthoredAssetDocument::new(
key.clone(),
normalize_path(logical_path),
value,
snapshot.clone(),
);
let mut store = world.resource_mut::<AuthoredAssetDocumentStore>();
store.registry_clean.get_or_insert(registry);
store.registry_snapshot.get_or_insert(snapshot);
store
.path_index
.insert(normalize_path(logical_path), key.clone());
store.documents.insert(key.clone(), document);
key
}
@@ -0,0 +1,338 @@
use super::*;
pub(super) const RECOVERY_IDLE: Duration = Duration::from_secs(2);
pub(super) const RECOVERY_GENERATIONS: usize = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AuthoredAssetDocumentKind {
Material,
MaterialInstance,
ModelImportSettings,
TextureImportSettings,
ProjectContentDefaults,
}
impl AuthoredAssetDocumentKind {
pub(super) fn slug(self) -> &'static str {
match self {
Self::Material => "material",
Self::MaterialInstance => "material-instance",
Self::ModelImportSettings => "model-import",
Self::TextureImportSettings => "texture-import",
Self::ProjectContentDefaults => "content-defaults",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AuthoredAssetDocumentKey {
pub asset_id: String,
pub kind: AuthoredAssetDocumentKind,
}
impl AuthoredAssetDocumentKey {
pub(super) fn new(asset_id: impl Into<String>, kind: AuthoredAssetDocumentKind) -> Self {
Self {
asset_id: asset_id.into(),
kind,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum AuthoredDocumentState {
#[default]
Clean,
Dirty,
Saving,
ExternalConflict,
SaveFailed,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum DerivedProcessingState {
#[default]
Idle,
Queued,
Processing,
Failed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(super) enum AuthoredAssetValue {
Material(MaterialAsset),
MaterialInstance(MaterialInstanceAsset),
ModelImportSettings(ModelImportSettings),
TextureImportSettings(TextureImportSettings),
ProjectContentDefaults(ProjectContentDefaults),
}
impl PartialEq for AuthoredAssetValue {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Material(left), Self::Material(right)) => left == right,
(Self::MaterialInstance(left), Self::MaterialInstance(right)) => left == right,
(Self::ModelImportSettings(left), Self::ModelImportSettings(right)) => left == right,
(Self::TextureImportSettings(left), Self::TextureImportSettings(right)) => {
left == right
}
(Self::ProjectContentDefaults(left), Self::ProjectContentDefaults(right)) => {
left == right
}
_ => false,
}
}
}
#[derive(Debug, Clone)]
pub(super) struct AuthoredAssetDocument {
pub(super) key: AuthoredAssetDocumentKey,
pub(super) path: String,
pub(super) clean: AuthoredAssetValue,
pub(super) current: AuthoredAssetValue,
pub(super) disk_snapshot: FileSnapshot,
pub(super) revision: u64,
pub(super) state: AuthoredDocumentState,
pub(super) processing: DerivedProcessingState,
pub(super) error: Option<String>,
pub(super) changed_at: Option<Instant>,
pub(super) recovery_revision: Option<u64>,
}
impl AuthoredAssetDocument {
pub(super) fn new(
key: AuthoredAssetDocumentKey,
path: String,
value: AuthoredAssetValue,
disk_snapshot: FileSnapshot,
) -> Self {
Self {
key,
path,
clean: value.clone(),
current: value,
disk_snapshot,
revision: 0,
state: AuthoredDocumentState::Clean,
processing: DerivedProcessingState::Idle,
error: None,
changed_at: None,
recovery_revision: None,
}
}
pub(super) fn dirty(&self) -> bool {
self.current != self.clean
}
pub(super) fn mark_edited(&mut self) {
self.revision = self.revision.wrapping_add(1);
self.state = AuthoredDocumentState::Dirty;
self.error = None;
self.changed_at = Some(Instant::now());
}
pub(super) fn refresh_state_from_value(&mut self) {
if self.dirty() {
self.mark_edited();
} else {
self.state = AuthoredDocumentState::Clean;
self.error = None;
self.changed_at = None;
}
}
}
#[derive(Debug, Clone)]
pub struct AuthoredDocumentSnapshot {
pub key: AuthoredAssetDocumentKey,
pub path: String,
pub state: AuthoredDocumentState,
pub processing: DerivedProcessingState,
pub dirty: bool,
pub error: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssetSaveRequest {
Active,
All,
}
#[derive(Resource, Debug, Default)]
pub struct AuthoredAssetDocumentStore {
pub(super) documents: HashMap<AuthoredAssetDocumentKey, AuthoredAssetDocument>,
pub(super) path_index: HashMap<String, AuthoredAssetDocumentKey>,
pub(super) active: Option<AuthoredAssetDocumentKey>,
pub(super) pending_save: Option<AssetSaveRequest>,
pub(super) registry_clean: Option<AssetRegistryDocument>,
pub(super) registry_snapshot: Option<FileSnapshot>,
pub(super) pending_recovery: Vec<RecoveryEnvelope>,
pub(super) recovery_prompt_open: bool,
pub(super) recovery_reviewing: bool,
}
impl AuthoredAssetDocumentStore {
pub fn active_key(&self) -> Option<&AuthoredAssetDocumentKey> {
self.active.as_ref()
}
pub fn set_active_scene(&mut self) {
self.active = None;
}
pub fn request_save(&mut self, request: AssetSaveRequest) {
self.pending_save = Some(request);
}
pub fn dirty_count(&self) -> usize {
self.documents
.values()
.filter(|document| document.dirty())
.count()
}
pub fn has_dirty_documents(&self) -> bool {
self.dirty_count() > 0
}
pub fn has_pending_or_failed_processing(&self) -> bool {
self.documents.values().any(|document| {
matches!(
document.processing,
DerivedProcessingState::Queued
| DerivedProcessingState::Processing
| DerivedProcessingState::Failed
)
})
}
pub fn snapshot_for_path(&self, path: &str) -> Option<AuthoredDocumentSnapshot> {
let key = self.path_index.get(&normalize_path(path))?;
self.snapshot(key)
}
pub fn snapshot(&self, key: &AuthoredAssetDocumentKey) -> Option<AuthoredDocumentSnapshot> {
let document = self.documents.get(key)?;
Some(AuthoredDocumentSnapshot {
key: key.clone(),
path: document.path.clone(),
state: document.state,
processing: document.processing,
dirty: document.dirty(),
error: document.error.clone(),
})
}
pub fn material(&self, key: &AuthoredAssetDocumentKey) -> Option<&MaterialAsset> {
match &self.documents.get(key)?.current {
AuthoredAssetValue::Material(asset) => Some(asset),
_ => None,
}
}
pub fn material_instance(
&self,
key: &AuthoredAssetDocumentKey,
) -> Option<&MaterialInstanceAsset> {
match &self.documents.get(key)?.current {
AuthoredAssetValue::MaterialInstance(asset) => Some(asset),
_ => None,
}
}
pub fn model_import(&self, key: &AuthoredAssetDocumentKey) -> Option<&ModelImportSettings> {
match &self.documents.get(key)?.current {
AuthoredAssetValue::ModelImportSettings(settings) => Some(settings),
_ => None,
}
}
pub fn texture_import(&self, key: &AuthoredAssetDocumentKey) -> Option<&TextureImportSettings> {
match &self.documents.get(key)?.current {
AuthoredAssetValue::TextureImportSettings(settings) => Some(settings),
_ => None,
}
}
pub fn content_defaults(
&self,
key: &AuthoredAssetDocumentKey,
) -> Option<&ProjectContentDefaults> {
match &self.documents.get(key)?.current {
AuthoredAssetValue::ProjectContentDefaults(defaults) => Some(defaults),
_ => None,
}
}
pub fn update_material(&mut self, key: &AuthoredAssetDocumentKey, asset: MaterialAsset) {
self.update_value(key, AuthoredAssetValue::Material(asset));
}
pub fn update_material_instance(
&mut self,
key: &AuthoredAssetDocumentKey,
asset: MaterialInstanceAsset,
) {
self.update_value(key, AuthoredAssetValue::MaterialInstance(asset));
}
pub fn update_model_import(
&mut self,
key: &AuthoredAssetDocumentKey,
settings: ModelImportSettings,
) {
self.update_value(key, AuthoredAssetValue::ModelImportSettings(settings));
}
pub fn update_texture_import(
&mut self,
key: &AuthoredAssetDocumentKey,
settings: TextureImportSettings,
) {
self.update_value(key, AuthoredAssetValue::TextureImportSettings(settings));
}
pub fn update_content_defaults(
&mut self,
key: &AuthoredAssetDocumentKey,
defaults: ProjectContentDefaults,
) {
self.update_value(key, AuthoredAssetValue::ProjectContentDefaults(defaults));
}
pub(super) fn update_value(
&mut self,
key: &AuthoredAssetDocumentKey,
value: AuthoredAssetValue,
) {
let Some(document) = self.documents.get_mut(key) else {
return;
};
if document.current == value {
self.active = Some(key.clone());
return;
}
document.current = value;
document.refresh_state_from_value();
self.active = Some(key.clone());
}
pub fn discard(&mut self, key: &AuthoredAssetDocumentKey) -> bool {
let Some(document) = self.documents.get_mut(key) else {
return false;
};
document.current = document.clean.clone();
document.state = AuthoredDocumentState::Clean;
document.error = None;
document.changed_at = None;
true
}
pub fn discard_all(&mut self) {
let keys = self.documents.keys().cloned().collect::<Vec<_>>();
for key in keys {
self.discard(&key);
}
}
}
@@ -0,0 +1,134 @@
//! Derived-processing classification for authored document saves.
use shared::{
EditorAssetRef, MaterialAsset, MaterialInputSet, MaterialInstanceAsset, TextureChannel,
};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum DerivedProcessingImpact {
#[default]
None,
MaterialPacking,
TextureAndDependents,
ModelArtifacts,
CatalogDefaults,
}
pub fn material_impact(clean: &MaterialAsset, current: &MaterialAsset) -> DerivedProcessingImpact {
if packing_bindings(&clean.inputs) != packing_bindings(&current.inputs) {
DerivedProcessingImpact::MaterialPacking
} else {
DerivedProcessingImpact::None
}
}
pub fn instance_impact(
clean: &MaterialInstanceAsset,
current: &MaterialInstanceAsset,
) -> DerivedProcessingImpact {
if clean.base != current.base
|| packing_bindings(&clean.overrides) != packing_bindings(&current.overrides)
{
DerivedProcessingImpact::MaterialPacking
} else {
DerivedProcessingImpact::None
}
}
fn packing_bindings(
inputs: &MaterialInputSet,
) -> Vec<(String, Option<EditorAssetRef>, TextureChannel)> {
["occlusion", "roughness", "metallic"]
.into_iter()
.map(|name| {
let binding = inputs.texture(name);
(
name.to_string(),
binding.and_then(|binding| binding.texture.clone()),
binding.map(|binding| binding.channel).unwrap_or_default(),
)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use shared::{MaterialParameter, MaterialParameterValue, MaterialTextureBinding};
#[test]
fn scalar_values_do_not_require_material_repacking() {
let clean = MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: "Test".into(),
shader: Default::default(),
shader_ref: None,
render_state: Default::default(),
provenance: None,
inputs: Default::default(),
};
let mut current = clean.clone();
current.inputs.values.push(MaterialParameter {
name: "roughness".into(),
value: MaterialParameterValue::Float(0.25),
});
assert_eq!(
material_impact(&clean, &current),
DerivedProcessingImpact::None
);
}
#[test]
fn render_state_and_color_changes_do_not_require_material_repacking() {
let clean = MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: "Test".into(),
shader: Default::default(),
shader_ref: None,
render_state: Default::default(),
provenance: None,
inputs: Default::default(),
};
let mut current = clean.clone();
current.render_state.double_sided = true;
current.inputs.values.push(MaterialParameter {
name: "base_color".into(),
value: MaterialParameterValue::Color(shared::ColorDesc::srgb(0.2, 0.3, 0.4)),
});
assert_eq!(
material_impact(&clean, &current),
DerivedProcessingImpact::None
);
}
#[test]
fn arm_texture_or_channel_changes_require_one_material_pack() {
let clean = MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: "Test".into(),
shader: Default::default(),
shader_ref: None,
render_state: Default::default(),
provenance: None,
inputs: Default::default(),
};
let mut current = clean.clone();
current.inputs.textures.push(MaterialTextureBinding {
name: "roughness".into(),
texture: Some(EditorAssetRef::new("arm", "texture:source", "ARM")),
channel: TextureChannel::G,
});
assert_eq!(
material_impact(&clean, &current),
DerivedProcessingImpact::MaterialPacking
);
let mut channel_change = current.clone();
channel_change.inputs.textures[0].channel = TextureChannel::R;
assert_eq!(
material_impact(&current, &channel_change),
DerivedProcessingImpact::MaterialPacking
);
}
}
+30 -7
View File
@@ -285,6 +285,7 @@ pub(crate) enum FileWriteIntent {
Scene { tab_id: u64, entity_count: usize },
Material,
MaterialInstance,
AssetRegistry,
ProjectSettings,
PrefabSource { instance_root: Entity },
PrefabSourceHistory { instance_root: Entity },
@@ -297,6 +298,7 @@ impl FileWriteIntent {
Self::Scene { .. } => "scene",
Self::Material => "material",
Self::MaterialInstance => "material instance",
Self::AssetRegistry => "asset registry settings",
Self::ProjectSettings => "project settings",
Self::PrefabSource { .. } => "prefab source",
Self::PrefabSourceHistory { .. } => "prefab source history",
@@ -452,7 +454,7 @@ pub(crate) fn file_status_indicator_ui(
let fill = egui::Color32::from_rgba_unmultiplied(color.r(), color.g(), color.b(), 18);
let response = egui::Frame::new()
.fill(fill)
.stroke(egui::Stroke::new(1.0, color.linear_multiply(0.55)))
.stroke(egui::Stroke::new(1.0_f32, color.linear_multiply(0.55)))
.corner_radius(2.0)
.inner_margin(egui::Margin::symmetric(5, 1))
.show(ui, |ui| {
@@ -679,7 +681,7 @@ pub(crate) fn file_conflict_modal(world: &mut World, ctx: &egui::Context) {
ui.add_space(10.0);
egui::Frame::new()
.fill(crate::ui::theme::PANEL_BG_DARK)
.stroke(egui::Stroke::new(1.0, crate::ui::theme::BORDER))
.stroke(egui::Stroke::new(1.0_f32, crate::ui::theme::BORDER))
.corner_radius(3.0)
.inner_margin(egui::Margin::same(9))
.show(ui, |ui| {
@@ -850,7 +852,16 @@ fn resolve_conflict_reload(world: &mut World, conflict: &PendingFileConflict) {
crate::scene_io::reload_scene_after_file_conflict(world, *tab_id, &conflict.path)
}
FileWriteIntent::Material | FileWriteIntent::MaterialInstance => {
crate::ui::reload_material_after_file_conflict(world, &conflict.path, &conflict.intent)
let kind = match conflict.intent {
FileWriteIntent::Material => {
crate::asset_documents::AuthoredAssetDocumentKind::Material
}
_ => crate::asset_documents::AuthoredAssetDocumentKind::MaterialInstance,
};
crate::asset_documents::reload_file_document_after_conflict(world, &conflict.path, kind)
}
FileWriteIntent::AssetRegistry => {
crate::asset_documents::reload_registry_documents_after_file_conflict(world)
}
FileWriteIntent::ProjectSettings => {
crate::settings_ui::reload_project_settings_after_file_conflict(world, &conflict.path)
@@ -973,14 +984,23 @@ fn finish_conflict_save_as(
*entity_count,
),
FileWriteIntent::Material | FileWriteIntent::MaterialInstance => {
crate::ui::adopt_material_conflict_save_as(
let kind = match conflict.intent {
FileWriteIntent::Material => {
crate::asset_documents::AuthoredAssetDocumentKind::Material
}
_ => crate::asset_documents::AuthoredAssetDocumentKind::MaterialInstance,
};
crate::asset_documents::adopt_material_conflict_save_as(
world,
&conflict.path,
material_catalog_path.expect("validated material path"),
disk_snapshot,
&conflict.intent,
&material_catalog_path.expect("validated material path"),
kind,
)
}
FileWriteIntent::AssetRegistry => Ok(format!(
"Saved asset registry recovery copy to {}; active registry and dirty documents unchanged",
destination.display()
)),
FileWriteIntent::ProjectSettings => {
crate::settings_ui::project_settings_conflict_copy_saved(world);
Ok(format!(
@@ -1616,8 +1636,11 @@ mod tests {
assets: Vec::new(),
current_folder: "assets".into(),
selected: None,
selections: Vec::new(),
selection_anchor: None,
dragging: None,
status: String::new(),
catalog_revision: 1,
};
let mut world = World::new();
world.insert_resource(workspace);
+5 -12
View File
@@ -201,7 +201,7 @@ fn project_launcher_ui(world: &mut World, context: &egui::Context, state: &mut P
fn launcher_actions(world: &mut World, ui: &mut egui::Ui, state: &mut ProjectLauncherUi) {
egui::Frame::new()
.fill(PANEL_BG_DARK)
.stroke(egui::Stroke::new(1.0, BORDER))
.stroke(egui::Stroke::new(1.0_f32, BORDER))
.inner_margin(egui::Margin::same(16))
.show(ui, |ui| {
ui.set_min_height(455.0);
@@ -303,7 +303,7 @@ fn recent_projects(world: &mut World, ui: &mut egui::Ui, state: &mut ProjectLaun
if state.recents.is_empty() {
egui::Frame::new()
.fill(PANEL_BG)
.stroke(egui::Stroke::new(1.0, BORDER))
.stroke(egui::Stroke::new(1.0_f32, BORDER))
.inner_margin(egui::Margin::same(16))
.show(ui, |ui| {
ui.label(egui::RichText::new("No valid recent projects").color(TEXT));
@@ -322,7 +322,7 @@ fn recent_projects(world: &mut World, ui: &mut egui::Ui, state: &mut ProjectLaun
for summary in recents {
let response = egui::Frame::new()
.fill(PANEL_BG)
.stroke(egui::Stroke::new(1.0, BORDER))
.stroke(egui::Stroke::new(1.0_f32, BORDER))
.inner_margin(egui::Margin::same(14))
.show(ui, |ui| {
ui.horizontal(|ui| {
@@ -363,7 +363,7 @@ fn recent_projects(world: &mut World, ui: &mut egui::Ui, state: &mut ProjectLaun
ui.painter().rect_stroke(
response.response.rect,
0.0,
egui::Stroke::new(1.0, SELECTION),
egui::Stroke::new(1.0_f32, SELECTION),
egui::StrokeKind::Inside,
);
}
@@ -666,14 +666,7 @@ pub fn scaffold_sandbox_project(destination: &Path, name: &str) -> Result<Projec
"audio".into(),
],
default_level: default_level.to_string(),
asset_roots: vec![
"assets/audio".into(),
"assets/levels".into(),
"assets/materials".into(),
"assets/meshes".into(),
"assets/models".into(),
"assets/textures".into(),
],
asset_roots: vec!["assets".into()],
..ProjectSettings::default()
};
let manifest_text = save_project_settings_to_string(&manifest)
+1
View File
@@ -1,5 +1,6 @@
//! Project workspace I/O, settings UI, and recent-level sync.
pub mod asset_documents;
pub mod collaboration;
pub mod diagnostics_bundle;
pub mod launcher;
+3 -5
View File
@@ -131,11 +131,9 @@ pub fn session_resume_window(world: &mut World, ctx: &egui::Context) {
return;
};
egui::Window::new("Recover Editor Session")
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
.show(ctx, |ui| {
egui::Modal::new(egui::Id::new("recover_editor_session")).show(ctx, |ui| {
ui.heading("Recover Editor Session");
ui.add_space(4.0);
ui.label("The previous editor session did not close cleanly.");
ui.small("The safe startup scene is active. Resume only the last authored scene; modal tools and dirty preview state are never restored.");
ui.monospace(scene.display().to_string());
+112 -1
View File
@@ -129,6 +129,8 @@ fn draw_project_settings_form(
}
ui.separator();
draw_content_defaults(world, ui);
ui.collapsing("Global Illumination", |ui| {
egui::ComboBox::from_label("GiMode")
.selected_text(format!("{:?}", draft.rendering.gi_mode))
@@ -268,7 +270,10 @@ fn draw_project_settings_form(
for (index, bus) in draft.audio.buses.iter_mut().enumerate() {
egui::Frame::new()
.fill(egui::Color32::from_rgb(24, 26, 29))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(53, 57, 63)))
.stroke(egui::Stroke::new(
1.0_f32,
egui::Color32::from_rgb(53, 57, 63),
))
.corner_radius(4.0)
.inner_margin(8.0)
.show(ui, |ui| {
@@ -441,6 +446,84 @@ fn draw_project_settings_form(
}
}
fn draw_content_defaults(world: &mut World, ui: &mut egui::Ui) {
let document_key = crate::asset_documents::ensure_content_defaults_document(world);
let mut defaults = world
.resource::<crate::asset_documents::AuthoredAssetDocumentStore>()
.content_defaults(&document_key)
.cloned()
.unwrap_or_default();
let current = defaults.default_material.clone();
let materials = world
.resource::<crate::asset_db::AssetRegistry>()
.records
.iter()
.filter(|record| {
matches!(
record.kind,
shared::AssetKind::Material | shared::AssetKind::MaterialInstance
)
})
.cloned()
.collect::<Vec<_>>();
let selected_label = current
.as_ref()
.map(|reference| reference.0.label.as_str())
.unwrap_or(blacksite_surface::DEFAULT_GRID_LABEL);
let mut next = current.clone();
ui.collapsing("Content", |ui| {
ui.label("Default material");
egui::ComboBox::from_id_salt("project_default_material")
.selected_text(selected_label)
.show_ui(ui, |ui| {
if ui
.selectable_label(next.is_none(), blacksite_surface::DEFAULT_GRID_LABEL)
.clicked()
{
next = None;
}
for record in &materials {
let selected = next
.as_ref()
.is_some_and(|reference| reference.0.asset_id == record.id.as_string());
if ui.selectable_label(selected, &record.label).clicked() {
let sub_asset_id = if record.kind == shared::AssetKind::MaterialInstance {
"material:instance"
} else {
"material:source"
};
next = Some(shared::MaterialRef::new(
shared::EditorAssetRef::new(
record.id.as_string(),
sub_asset_id,
record.label.clone(),
)
.with_source_path(record.path.clone()),
));
}
}
});
ui.small("Clear restores the immutable engine Default Grid fallback.");
if ui
.add_enabled(next.is_some(), egui::Button::new("Clear"))
.clicked()
{
next = None;
}
});
if next == current {
return;
}
defaults.default_material = next;
world
.resource_mut::<crate::asset_documents::AuthoredAssetDocumentStore>()
.update_content_defaults(&document_key, defaults.clone());
world
.resource_mut::<crate::asset_db::AssetRegistry>()
.defaults = defaults.clone();
*world.resource_mut::<shared::ProjectContentDefaults>() = defaults;
}
fn persist_project_settings(
world: &mut World,
settings: &ProjectSettings,
@@ -458,6 +541,34 @@ fn persist_project_settings(
Ok((snapshot, source))
}
pub fn save_project_settings_if_dirty(world: &mut World) -> Result<bool, String> {
if !world
.get_resource::<ProjectSettingsIo>()
.is_some_and(|io| io.dirty)
{
return Ok(false);
}
let settings = world.resource::<ProjectSettings>().clone();
let expected = {
let io = world.resource::<ProjectSettingsIo>();
io.loaded_source
.as_deref()
.map(|source| FileSnapshot::from_loaded_bytes(Path::new(&io.path), source.as_bytes()))
.unwrap_or_else(FileSnapshot::missing)
};
let (snapshot, source) = persist_project_settings(world, &settings, &expected)?;
{
let mut io = world.resource_mut::<ProjectSettingsIo>();
io.dirty = false;
io.loaded_source = Some(source);
}
if let Some(mut panel) = world.get_resource_mut::<ProjectSettingsPanel>() {
panel.disk_snapshot = Some(snapshot);
panel.save_error = None;
}
Ok(true)
}
fn read_project_settings_document(
path: &Path,
) -> Result<(ProjectSettings, String, FileSnapshot), String> {
+62 -10
View File
@@ -103,6 +103,16 @@ impl ShutdownCoordinator {
}
}
#[cfg(test)]
pub(crate) fn arm_shutdown_save_for_test(world: &mut World) {
world.init_resource::<ShutdownCoordinator>();
world
.resource_mut::<ShutdownCoordinator>()
.set_intent_for_test(ShutdownIntent::Saving {
source: ShutdownSource::Programmatic,
});
}
/// Emitted once when the guarded dialog chooses `Save All`.
///
/// Scene persistence owns the actual save sequence and must finish it with
@@ -145,7 +155,7 @@ pub fn request_project_switch(world: &mut World) -> bool {
/// Resolve the dirty-scene confirmation through the shared coordinator.
pub fn resolve_shutdown_decision(world: &mut World, decision: ShutdownDecision) -> bool {
let (save_request, status) = {
let (save_request, discard_assets, status) = {
let Some(mut coordinator) = world.get_resource_mut::<ShutdownCoordinator>() else {
return false;
};
@@ -157,6 +167,7 @@ pub fn resolve_shutdown_decision(world: &mut World, decision: ShutdownDecision)
coordinator.intent = ShutdownIntent::Saving { source };
(
Some(source),
false,
Some("Saving all modified scene tabs before shutdown"),
)
}
@@ -165,24 +176,37 @@ pub fn resolve_shutdown_decision(world: &mut World, decision: ShutdownDecision)
source,
require_clean_scenes: false,
};
(None, None)
(None, true, None)
}
ShutdownDecision::Cancel => {
coordinator.intent = ShutdownIntent::Idle;
(
None,
false,
Some("Shutdown cancelled; unsaved scene tabs retained"),
)
}
}
};
if discard_assets {
crate::asset_documents::discard_all_authored_assets(world);
}
if let Some(status) = status {
if let Some(mut scene_io) = world.get_resource_mut::<SceneIo>() {
scene_io.set_status(status);
}
}
if let Some(source) = save_request {
if let Err(error) = crate::settings_ui::save_project_settings_if_dirty(world) {
complete_shutdown_save(world, ShutdownSaveOutcome::Failed(error));
return true;
}
if let Err(error) = crate::asset_documents::save_all_authored_assets(world) {
complete_shutdown_save(world, ShutdownSaveOutcome::Failed(error));
return true;
}
world.write_message(ShutdownSaveAllRequested { source });
}
true
@@ -191,7 +215,9 @@ pub fn resolve_shutdown_decision(world: &mut World, decision: ShutdownDecision)
/// Finish the save-all handoff. A reported success is authorized only after
/// every scene tab is observably clean.
pub fn complete_shutdown_save(world: &mut World, outcome: ShutdownSaveOutcome) -> bool {
let scenes_are_clean = !scene_has_unsaved_changes(world);
let documents_are_clean = !scene_has_unsaved_changes(world)
&& !asset_documents_have_unsaved_changes(world)
&& !project_settings_have_unsaved_changes(world);
let Some(mut coordinator) = world.get_resource_mut::<ShutdownCoordinator>() else {
return false;
};
@@ -200,7 +226,7 @@ pub fn complete_shutdown_save(world: &mut World, outcome: ShutdownSaveOutcome) -
};
match outcome {
ShutdownSaveOutcome::Saved if scenes_are_clean => {
ShutdownSaveOutcome::Saved if documents_are_clean => {
coordinator.intent = ShutdownIntent::Authorized {
source,
require_clean_scenes: true,
@@ -210,8 +236,10 @@ pub fn complete_shutdown_save(world: &mut World, outcome: ShutdownSaveOutcome) -
}
ShutdownSaveOutcome::Saved => {
coordinator.intent = ShutdownIntent::Idle;
coordinator.last_blocker =
Some("Save All completed while unsaved scene tabs remain".into());
coordinator.last_blocker = Some(
"Save All completed while unsaved scenes, assets, or project settings remain"
.into(),
);
false
}
ShutdownSaveOutcome::Cancelled => {
@@ -271,7 +299,7 @@ fn drive_shutdown(world: &mut World) {
| ShutdownIntent::Saving { .. }
| ShutdownIntent::ExitSent { .. } => {}
ShutdownIntent::WaitingForBroker { source } => {
let unsaved_count = unsaved_scene_count(world);
let unsaved_count = unsaved_document_count(world);
if unsaved_count == 0 {
world.resource_mut::<ShutdownCoordinator>().intent = ShutdownIntent::Authorized {
source,
@@ -289,10 +317,10 @@ fn drive_shutdown(world: &mut World) {
"quitting"
};
let description = if unsaved_count == 1 {
format!("One scene tab has unsaved changes. Save it before {action}?")
format!("One editor document has unsaved changes. Save it before {action}?")
} else {
format!(
"{unsaved_count} scene tabs have unsaved changes. Save all before {action}?"
"{unsaved_count} editor documents have unsaved changes. Save all before {action}?"
)
};
let title = if source == ShutdownSource::SwitchProject {
@@ -339,7 +367,11 @@ pub(crate) fn finalize_authorized_shutdown(world: &mut World) {
};
(source, require_clean_scenes)
};
if require_clean_scenes && scene_has_unsaved_changes(world) {
if require_clean_scenes
&& (scene_has_unsaved_changes(world)
|| asset_documents_have_unsaved_changes(world)
|| project_settings_have_unsaved_changes(world))
{
world.resource_mut::<ShutdownCoordinator>().intent =
ShutdownIntent::WaitingForBroker { source };
return;
@@ -386,6 +418,26 @@ fn unsaved_scene_count(world: &World) -> usize {
}
}
fn unsaved_document_count(world: &World) -> usize {
unsaved_scene_count(world)
+ world
.get_resource::<crate::asset_documents::AuthoredAssetDocumentStore>()
.map_or(0, |store| store.dirty_count())
+ usize::from(project_settings_have_unsaved_changes(world))
}
fn asset_documents_have_unsaved_changes(world: &World) -> bool {
world
.get_resource::<crate::asset_documents::AuthoredAssetDocumentStore>()
.is_some_and(|store| store.has_dirty_documents())
}
fn project_settings_have_unsaved_changes(world: &World) -> bool {
world
.get_resource::<settings::ProjectSettingsIo>()
.is_some_and(|io| io.dirty)
}
fn decision_from_dialog(result: rfd::MessageDialogResult) -> ShutdownDecision {
match result {
rfd::MessageDialogResult::Custom(label) if label == SAVE_ALL_LABEL => {
+53 -2
View File
@@ -1,7 +1,7 @@
//! Shared HDR render-to-texture helpers for editor viewport panels.
use bevy::prelude::*;
use bevy::render::render_resource::TextureFormat;
use bevy::render::render_resource::{Extent3d, TextureFormat};
/// Offscreen render target displayed by the primary editor viewport.
#[derive(Debug, Clone)]
@@ -13,16 +13,33 @@ pub struct ViewportTarget {
#[derive(Resource, Default, Debug, Clone)]
pub struct ViewportRenderTarget(pub Option<ViewportTarget>);
/// Allocates or reuses an HDR offscreen color target when the panel size changes.
/// Allocates or resizes the HDR offscreen color target when the panel size changes.
///
/// The asset identity remains stable across ordinary panel resizing. Besides avoiding needless
/// camera and bind-group churn, this prevents Egui's strong image registration from retaining one
/// full-resolution HDR target for every splitter movement.
pub fn ensure_hdr_panel_target(
physical_size: UVec2,
last_size: &mut Option<UVec2>,
current: Option<&Handle<Image>>,
images: &mut Assets<Image>,
) -> Option<Handle<Image>> {
if *last_size == Some(physical_size) {
return None;
}
*last_size = Some(physical_size);
if let Some(current) = current {
if let Some(mut image) = images.get_mut(current) {
image.resize(Extent3d {
width: physical_size.x,
height: physical_size.y,
depth_or_array_layers: 1,
});
return None;
}
}
Some(images.add(Image::new_target_texture(
physical_size.x,
physical_size.y,
@@ -33,3 +50,37 @@ pub fn ensure_hdr_panel_target(
/// Standard HDR format for editor panel render targets.
pub const PANEL_TARGET_FORMAT: TextureFormat = TextureFormat::Rgba16Float;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn repeated_panel_resize_reuses_one_hdr_image_asset() {
let mut images = Assets::<Image>::default();
let mut last_size = None;
let initial =
ensure_hdr_panel_target(UVec2::new(1920, 1080), &mut last_size, None, &mut images)
.expect("first size allocates the viewport target");
let initial_id = initial.id();
for width in [1600, 1280, 900, 1280, 1600, 1920] {
assert!(
ensure_hdr_panel_target(
UVec2::new(width, 1080),
&mut last_size,
Some(&initial),
&mut images,
)
.is_none(),
"resize should mutate the existing image"
);
assert_eq!(initial.id(), initial_id);
assert_eq!(
images.get(&initial).expect("target remains live").width(),
width
);
assert_eq!(images.len(), 1);
}
}
}
+77 -19
View File
@@ -24,7 +24,10 @@ use shared::{
AnimationControllerDesc, AudioSourceDesc, BrushDesc, ColliderDesc, SkinnedMeshRenderer,
};
use crate::assets::{import_external_assets, EditorAssets, IMPORTABLE_ASSET_EXTENSIONS};
use crate::assets::{
plan_external_assets_import_at, EditorAssets, ExternalAssetImportPlan,
IMPORTABLE_ASSET_EXTENSIONS,
};
use crate::history::{clear_level_objects, snapshot_entity, EditorHistory};
use crate::native_dialog::NativeDialogBroker;
use crate::project::collaboration::{publish_authored_file, FileSnapshot, FileWriteIntent};
@@ -48,7 +51,7 @@ pub enum SceneIoRequest {
Open,
Save,
SaveAs,
ImportAssets,
ImportAssets { destination: String },
ExportSelection,
SaveSelectionAsPrefab,
SwitchProject,
@@ -63,6 +66,15 @@ pub enum SceneIoRequest {
ReloadComposition,
}
#[derive(Debug, Clone)]
pub struct PlannedAssetImportReview {
pub plan: ExternalAssetImportPlan,
pub previous_status: String,
}
#[derive(Resource, Debug, Default, Clone)]
pub struct PendingAssetImportReview(pub Option<PlannedAssetImportReview>);
#[derive(Debug, Clone)]
pub struct SceneTab {
pub id: u64,
@@ -235,6 +247,7 @@ struct RecoveryClock {
#[derive(Resource, Debug, Default)]
struct SceneSaveAllTransaction {
start_requested: bool,
shutdown_requested: bool,
active: Option<SaveAllRun>,
}
@@ -256,6 +269,7 @@ pub struct SceneIoPlugin;
impl Plugin for SceneIoPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<SceneIo>()
.init_resource::<PendingAssetImportReview>()
.init_resource::<SceneComposition>()
.init_resource::<RecoveryClock>()
.init_resource::<SceneSaveAllTransaction>()
@@ -280,9 +294,17 @@ fn receive_shutdown_save_all_requests(
) {
if requests.read().next().is_some() {
transaction.start_requested = true;
transaction.shutdown_requested = true;
}
}
/// Save every dirty scene tab without entering the guarded shutdown flow.
pub fn request_scene_save_all(world: &mut World) {
let mut transaction = world.resource_mut::<SceneSaveAllTransaction>();
transaction.start_requested = true;
transaction.shutdown_requested = false;
}
fn load_startup_scene(world: &mut World) {
let active_path = world.resource::<SceneIo>().active_path.clone();
let default_path = PathBuf::from(
@@ -353,7 +375,7 @@ fn process_scene_io_requests(world: &mut World) {
SceneIoRequest::Save => save_active_or_prompt(world),
SceneIoRequest::SaveAs => save_with_dialog(world),
SceneIoRequest::Open => open_with_dialog(world),
SceneIoRequest::ImportAssets => import_with_dialog(world),
SceneIoRequest::ImportAssets { destination } => import_with_dialog(world, destination),
SceneIoRequest::ExportSelection => export_selection_with_dialog(world),
SceneIoRequest::SaveSelectionAsPrefab => save_selection_as_prefab(world),
SceneIoRequest::SwitchProject => {
@@ -1095,7 +1117,13 @@ fn finish_save_all_without_run(world: &mut World, outcome: ShutdownSaveOutcome)
ShutdownSaveOutcome::Cancelled => "Save All cancelled; editor remains open".to_string(),
ShutdownSaveOutcome::Failed(error) => format!("Save All failed: {error}"),
};
complete_shutdown_save(world, outcome);
let shutdown_requested = {
let mut transaction = world.resource_mut::<SceneSaveAllTransaction>();
std::mem::take(&mut transaction.shutdown_requested)
};
if shutdown_requested {
complete_shutdown_save(world, outcome);
}
world.resource_mut::<SceneIo>().set_status(status);
}
@@ -1411,23 +1439,51 @@ fn open_with_dialog(world: &mut World) -> String {
}
}
fn import_with_dialog(world: &mut World) -> String {
fn import_with_dialog(world: &mut World, destination: String) -> String {
let destination = if destination == crate::assets::BUILTINS_FOLDER {
crate::assets::ASSETS_ROOT.to_string()
} else {
destination
};
let previous_status = world.resource::<SceneIo>().status.clone();
let request = world.resource::<NativeDialogBroker>().request(
|| {
rfd::FileDialog::new()
.add_filter("Editor assets", IMPORTABLE_ASSET_EXTENSIONS)
.pick_files()
},
|world, paths| {
move |world, paths| {
let status = match paths {
None => "Import cancelled".to_string(),
Some(paths) => match import_external_assets(&paths) {
Ok(count) => {
world.resource_mut::<EditorAssets>().refresh();
format!("Imported {count} asset(s)")
None => previous_status.clone(),
Some(paths) => {
let project_root = world
.resource::<crate::project_io::ProjectWorkspace>()
.root
.clone();
match plan_external_assets_import_at(
Path::new(&project_root),
&paths,
Path::new(&destination),
) {
Ok(plan) => {
let count = plan.imported_count();
let conflicts = plan.conflicts.len();
world.resource_mut::<PendingAssetImportReview>().0 =
Some(PlannedAssetImportReview {
plan,
previous_status: previous_status.clone(),
});
if conflicts == 0 {
format!("Review {count} planned asset import(s)")
} else {
format!(
"Review {count} planned import(s) with {conflicts} conflict(s)"
)
}
}
Err(err) => format!("Import planning failed: {err}"),
}
Err(err) => format!("Import failed: {err}"),
},
}
};
world.resource_mut::<SceneIo>().set_status(status);
},
@@ -2665,17 +2721,22 @@ fn update_window_title(
workspace: Res<crate::project_io::ProjectWorkspace>,
settings: Res<settings::ProjectSettings>,
settings_io: Res<settings::ProjectSettingsIo>,
asset_documents: Res<crate::asset_documents::AuthoredAssetDocumentStore>,
mut window: Single<&mut Window, With<PrimaryWindow>>,
) {
if !io.is_changed()
&& !workspace.is_changed()
&& !settings.is_changed()
&& !settings_io.is_changed()
&& !asset_documents.is_changed()
{
return;
}
window.title = crate::project_io::window_title(&io, &workspace, &settings);
if asset_documents.has_dirty_documents() {
window.title.push_str(" [assets*]");
}
}
#[cfg(test)]
@@ -2687,7 +2748,6 @@ mod tests {
use bevy::world_serialization::{
DynamicWorldRoot, WorldInstanceSpawner, WorldSerializationPlugin,
};
struct NoAssetLoads;
#[derive(Component, Reflect, Default)]
@@ -2742,12 +2802,10 @@ mod tests {
}
fn arm_shutdown_save(world: &mut World) {
world.init_resource::<crate::shutdown::ShutdownCoordinator>();
world
.resource_mut::<crate::shutdown::ShutdownCoordinator>()
.set_intent_for_test(crate::shutdown::ShutdownIntent::Saving {
source: crate::shutdown::ShutdownSource::Programmatic,
});
.resource_mut::<SceneSaveAllTransaction>()
.shutdown_requested = true;
crate::shutdown::arm_shutdown_save_for_test(world);
}
fn prepare_saved_dirty_checkpoint_scene(app: &mut App, root: &Path) -> PathBuf {
+6 -1
View File
@@ -34,10 +34,15 @@ pub(crate) fn ensure_viewport_render_target(
mut last_size: Local<Option<UVec2>>,
) {
let Some(physical_size) = panel_physical_size(&window, ui_state.viewport_rect) else {
target.0 = None;
*last_size = None;
return;
};
if let Some(handle) = ensure_hdr_panel_target(physical_size, &mut last_size, &mut images) {
let current = target.0.as_ref().map(|target| &target.image);
if let Some(handle) =
ensure_hdr_panel_target(physical_size, &mut last_size, current, &mut images)
{
target.0 = Some(ViewportTarget { image: handle });
}
}
@@ -0,0 +1,63 @@
//! Testable Inspector body containment geometry.
use bevy_egui::egui;
pub(super) fn configure_component_scroll_style(style: &mut egui::Style) {
let scroll = &mut style.spacing.scroll;
scroll.floating = true;
scroll.bar_width = 8.0;
scroll.floating_width = 3.0;
scroll.floating_allocated_width = 4.0;
scroll.content_margin.right = 4;
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct InspectorBodyLayout {
pub body: egui::Rect,
pub clip: egui::Rect,
}
impl InspectorBodyLayout {
pub(super) fn contained(available: egui::Rect, parent_clip: egui::Rect) -> Option<Self> {
let clip = available.intersect(parent_clip);
(available.is_positive() && clip.is_positive()).then_some(Self {
body: available,
clip,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn penpot_component_body_never_paints_above_fixed_header() {
let header_bottom = 96.0;
let available =
egui::Rect::from_min_max(egui::pos2(400.0, header_bottom), egui::pos2(1040.0, 900.0));
let parent_clip =
egui::Rect::from_min_max(egui::pos2(400.0, 48.0), egui::pos2(1040.0, 860.0));
let layout = InspectorBodyLayout::contained(available, parent_clip).unwrap();
assert_eq!(layout.body.top(), header_bottom);
assert!(layout.clip.top() >= header_bottom);
assert_eq!(layout.clip.bottom(), 860.0);
}
#[test]
fn penpot_component_body_rejects_empty_intersection_after_resize() {
let available = egui::Rect::from_min_max(egui::pos2(0.0, 120.0), egui::pos2(200.0, 200.0));
let parent_clip = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(200.0, 100.0));
assert!(InspectorBodyLayout::contained(available, parent_clip).is_none());
}
#[test]
fn component_scrollbar_keeps_a_stable_content_width_when_overflow_changes() {
let mut style = egui::Style::default();
configure_component_scroll_style(&mut style);
assert!(style.spacing.scroll.floating);
assert_eq!(style.spacing.scroll.floating_allocated_width, 4.0);
assert_eq!(style.spacing.scroll.content_margin.right, 4);
}
}
+103 -40
View File
@@ -1,5 +1,6 @@
//! Actor-centric inspector (authoring components only).
mod layout;
mod transform;
use bevy::prelude::*;
@@ -13,11 +14,31 @@ use crate::ui::selection_ops::is_linked_read_only;
use crate::ui::theme::{panel_heading, BORDER, SELECTION, TEXT, TEXT_DIM, WIDGET_BG};
use crate::ui::widgets::phosphor_icon;
use layout::{configure_component_scroll_style, InspectorBodyLayout};
use transform::transform_inspector_ui;
const COMPACT_ACTOR_HEADER_WIDTH: f32 = 360.0;
pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
let actor_widget_key = stable_actor_widget_key(world, entity);
ui.push_id(("actor_inspector", actor_widget_key.as_str()), |ui| {
draw_actor_inspector_contents(world, ui, entity, &actor_widget_key);
});
}
fn stable_actor_widget_key(world: &World, entity: Entity) -> String {
world
.get::<ActorId>(entity)
.map(|actor_id| format!("actor:{}", actor_id.0))
.unwrap_or_else(|| format!("runtime:{entity:?}"))
}
fn draw_actor_inspector_contents(
world: &mut World,
ui: &mut egui::Ui,
entity: Entity,
actor_widget_key: &str,
) {
let linked_read_only = is_linked_read_only(world, entity);
let prefab_member = world.get::<HydratedPrefabMember>(entity).is_some();
let Some(entity_ref) = world.get_entity(entity).ok() else {
@@ -35,7 +56,7 @@ pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity
egui::Frame::new()
.fill(WIDGET_BG)
.stroke(egui::Stroke::new(1.0, BORDER))
.stroke(egui::Stroke::new(1.0_f32, BORDER))
.corner_radius(egui::CornerRadius::same(4))
.inner_margin(egui::Margin::symmetric(8, 8))
.show(ui, |ui| {
@@ -94,48 +115,73 @@ pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity
}
if prefab_member {
egui::ScrollArea::vertical()
.auto_shrink([false, false])
.show(ui, |ui| {
crate::assets::prefab_overrides::prefab_member_inspector_ui(world, ui, entity);
});
component_scroll_region(ui, actor_widget_key, true, |ui| {
crate::assets::prefab_overrides::prefab_member_inspector_ui(world, ui, entity);
});
return;
}
ui.add_enabled_ui(!linked_read_only, |ui| {
component_scroll_region(ui, actor_widget_key, !linked_read_only, |ui| {
transform_inspector_ui(world, ui, entity);
match kind {
ActorKind::StaticMesh
| ActorKind::SkinnedMesh
| ActorKind::Brush
| ActorKind::Terrain
| ActorKind::ImportedModel
| ActorKind::Light
| ActorKind::Empty
| ActorKind::PrefabAnchor
| ActorKind::PlayerSpawn
| ActorKind::WeaponSpawn
| ActorKind::TriggerVolume
| ActorKind::PostProcessVolume
| ActorKind::TeamSpawn
| ActorKind::Objective
| ActorKind::AudioSource
| ActorKind::AudioListener
| ActorKind::Navigation => {
inspector::authoring_inspector_ui(world, ui, entity);
}
}
world.resource_scope(|world, registry: Mut<ActorInspectorSectionRegistry>| {
registry.draw_sections(world, ui, entity);
});
inspector::add_component_footer(world, ui, entity);
});
inspector::property_block_promotion_review_ui(world, ui.ctx());
}
fn component_scroll_region(
ui: &mut egui::Ui,
actor_widget_key: &str,
enabled: bool,
add_contents: impl FnOnce(&mut egui::Ui),
) {
let available = ui.available_rect_before_wrap();
let Some(layout) = InspectorBodyLayout::contained(available, ui.clip_rect()) else {
return;
};
ui.allocate_rect(layout.body, egui::Sense::hover());
let mut body = ui.new_child(
egui::UiBuilder::new()
.max_rect(layout.body)
.layout(egui::Layout::top_down(egui::Align::Min)),
);
body.set_clip_rect(layout.clip);
// A solid scrollbar changes the component body's available width when content crosses the
// vertical overflow threshold. That can flip responsive component cards between layouts while
// the user resizes the Inspector. Keep the scrollbar floating and reserve only a stable, small
// interaction rail so every component receives the same width at every height.
configure_component_scroll_style(body.style_mut());
body.add_enabled_ui(enabled, |ui| {
egui::ScrollArea::vertical()
.id_salt(("actor_component_scroll", actor_widget_key))
.auto_shrink([false, false])
.show(ui, |ui| {
transform_inspector_ui(world, ui, entity);
match kind {
ActorKind::StaticMesh
| ActorKind::SkinnedMesh
| ActorKind::Brush
| ActorKind::Terrain
| ActorKind::ImportedModel
| ActorKind::Light
| ActorKind::Empty
| ActorKind::PrefabAnchor
| ActorKind::PlayerSpawn
| ActorKind::WeaponSpawn
| ActorKind::TriggerVolume
| ActorKind::PostProcessVolume
| ActorKind::TeamSpawn
| ActorKind::Objective
| ActorKind::AudioSource
| ActorKind::AudioListener
| ActorKind::Navigation => {
inspector::authoring_inspector_ui(world, ui, entity);
}
}
world.resource_scope(|world, registry: Mut<ActorInspectorSectionRegistry>| {
registry.draw_sections(world, ui, entity);
});
inspector::add_component_footer(world, ui, entity);
});
.show(ui, add_contents);
});
}
@@ -164,7 +210,7 @@ pub fn draw_multi_actor_inspector(world: &mut World, ui: &mut egui::Ui, entities
if entities.is_empty() {
egui::Frame::new()
.fill(WIDGET_BG)
.stroke(egui::Stroke::new(1.0, BORDER))
.stroke(egui::Stroke::new(1.0_f32, BORDER))
.corner_radius(egui::CornerRadius::same(4))
.inner_margin(egui::Margin::symmetric(10, 10))
.show(ui, |ui| {
@@ -182,7 +228,7 @@ pub fn draw_multi_actor_inspector(world: &mut World, ui: &mut egui::Ui, entities
egui::Frame::new()
.fill(WIDGET_BG)
.stroke(egui::Stroke::new(1.0, BORDER))
.stroke(egui::Stroke::new(1.0_f32, BORDER))
.corner_radius(egui::CornerRadius::same(4))
.inner_margin(egui::Margin::symmetric(10, 10))
.show(ui, |ui| {
@@ -203,3 +249,20 @@ pub fn draw_multi_actor_inspector(world: &mut World, ui: &mut egui::Ui, entities
});
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn inspector_widget_identity_survives_runtime_entity_replacement() {
let mut world = World::new();
let first = world.spawn(ActorId::new("persistent-actor")).id();
let first_key = stable_actor_widget_key(&world, first);
world.despawn(first);
let replacement = world.spawn(ActorId::new("persistent-actor")).id();
assert_eq!(first_key, stable_actor_widget_key(&world, replacement));
assert_eq!(first_key, "actor:persistent-actor");
}
}
@@ -11,7 +11,10 @@ use crate::ui::inspector::{
};
use crate::ui::theme::TEXT_DIM;
const WIDE_TRANSFORM_ROW_WIDTH: f32 = 360.0;
/// Minimum component-body width that can contain the label and all three fixed axis controls.
/// The Inspector's 420 px dock floor leaves a narrower component body, so it must use the wrapped
/// two-line form instead of clipping the Z field beyond the Inspector edge.
const WIDE_TRANSFORM_ROW_WIDTH: f32 = 440.0;
const TRANSFORM_LABEL_WIDTH: f32 = 124.0;
const AXIS_FIELD_WIDTH: f32 = 76.0;
@@ -22,11 +25,10 @@ pub fn transform_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Enti
let old = transform;
let mut changed = false;
let card = component_card_context(
world,
entity,
ComponentCardOptions::fixed(COMPONENT_TRANSFORM, "Transform", icons::ARROWS_OUT_CARDINAL),
);
let mut options =
ComponentCardOptions::fixed(COMPONENT_TRANSFORM, "Transform", icons::ARROWS_OUT_CARDINAL);
options.summary = "Position · Rotation · Scale";
let card = component_card_context(world, entity, options);
let card_response = component_card(ui, &card, |ui| {
if transform_row(ui, "Position", &mut transform.translation, 0.1) {
changed = true;
@@ -61,7 +63,7 @@ pub fn transform_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Enti
fn transform_row(ui: &mut egui::Ui, label: &str, value: &mut Vec3, speed: f64) -> bool {
let mut changed = false;
if ui.available_width() < WIDE_TRANSFORM_ROW_WIDTH {
if transform_row_is_compact(ui.available_width()) {
ui.vertical(|ui| {
ui.label(label);
ui.horizontal_wrapped(|ui| {
@@ -84,6 +86,10 @@ fn transform_row(ui: &mut egui::Ui, label: &str, value: &mut Vec3, speed: f64) -
changed
}
fn transform_row_is_compact(width: f32) -> bool {
width + f32::EPSILON < WIDE_TRANSFORM_ROW_WIDTH
}
fn axis_drag(ui: &mut egui::Ui, axis: &str, value: &mut f32, speed: f64) -> bool {
ui.horizontal(|ui| {
ui.label(egui::RichText::new(axis).color(axis_color(axis)).strong());
@@ -107,3 +113,15 @@ fn axis_color(axis: &str) -> egui::Color32 {
_ => TEXT_DIM,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn transform_rows_wrap_at_the_inspector_floor_without_clipping_z() {
assert!(transform_row_is_compact(364.0));
assert!(transform_row_is_compact(420.0));
assert!(!transform_row_is_compact(584.0));
}
}
+2 -2
View File
@@ -676,7 +676,7 @@ fn manifest_for_actor(world: &World, entity: Entity) -> Result<AnimationManifest
.or_else(|| without_assets.and_then(|path| find_asset_by_path(registry, path)))
.ok_or_else(|| format!("model `{}` is not indexed", model.path))?;
let path = record
.import_settings
.model_import()
.animation_manifest_path
.as_deref()
.ok_or_else(|| format!("model `{}` has no animation manifest", model.path))?;
@@ -705,7 +705,7 @@ fn referenced_clip_manifests(
let Some(record) = find_asset_by_id(registry, asset_id) else {
continue;
};
let Some(path) = record.import_settings.animation_manifest_path.as_deref() else {
let Some(path) = record.model_import().animation_manifest_path.as_deref() else {
continue;
};
if let Ok(manifest) = load_animation_manifest(path) {
+5 -1
View File
@@ -1,5 +1,9 @@
mod panel;
mod state;
pub use panel::*;
pub use panel::asset_browser_ui;
pub(crate) use panel::{
begin_actor_material_extraction, draw_asset_import_review_modal, top_level_asset_details_panel,
validate_material_conflict_destination,
};
pub use state::AssetBrowserUiState;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,439 @@
use super::*;
pub(super) fn detail_row(ui: &mut egui::Ui, label: &str, value: &str) {
ui.horizontal_wrapped(|ui| {
ui.label(egui::RichText::new(label).color(TEXT_DIM));
ui.add(egui::Label::new(value).wrap().selectable(false));
});
}
pub(super) fn details_panel(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
) {
ui.label(panel_heading("Details"));
ui.separator();
let selections = world.resource::<EditorAssets>().selections.clone();
if selections.len() > 1 {
let has_authored_content = !selected_content_paths(world).is_empty();
ui.label(panel_heading(&format!(
"{} items selected",
selections.len()
)));
ui.small(
egui::RichText::new("Batch file operations apply to every selected item.")
.color(TEXT_DIM),
);
ui.add_space(6.0);
for selection in selections.iter().take(12) {
ui.add(egui::Label::new(selection.display_label()).truncate());
}
if selections.len() > 12 {
ui.small(format!("…and {} more", selections.len() - 12));
}
ui.separator();
if ui
.add_enabled(
has_authored_content,
egui::Button::new("Duplicate Selection"),
)
.clicked()
{
duplicate_selection(world);
}
if ui
.add_enabled(
has_authored_content,
egui::Button::new("Move Selection To Trash"),
)
.clicked()
{
request_delete_for_selection(world);
}
return;
}
let selection = world.resource::<EditorAssets>().selected.clone();
if let Some(AssetSelection::Folder(path)) = selection {
ui.label(panel_heading(
Path::new(&path)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or(&path),
));
detail_row(ui, "Path", &path);
ui.separator();
if ui.button("Open Folder").clicked() {
navigate_content_folder(world, path);
}
} else if let Some(selection @ AssetSelection::SubAsset { .. }) = selection {
subasset_details_panel(world, ui, selected_entities, &selection);
} else if let Some(asset) = world.resource::<EditorAssets>().selected_asset().cloned() {
top_level_asset_details_panel(world, ui, selected_entities, &asset);
} else {
ui.label(egui::RichText::new("No asset selected").color(TEXT_DIM));
}
}
pub(crate) fn top_level_asset_details_panel(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
asset: &EditorAsset,
) {
asset_details_header(world, ui, asset);
ui.add_space(8.0);
detail_row(ui, "Path", asset.path.as_deref().unwrap_or("Built-in"));
detail_row(ui, "Folder", asset.folder_path.as_str());
if asset.path.is_none() && asset.label == blacksite_surface::DEFAULT_GRID_LABEL {
ui.separator();
ui.label(egui::RichText::new("Engine built-in · read-only").color(TEXT_DIM));
ui.small("World-space tri-planar checker used when no valid project material resolves.");
return;
}
if let Some(path) = asset.path.as_deref() {
if let Some(record) = world
.get_resource::<crate::asset_db::AssetRegistry>()
.and_then(|registry| find_asset_by_path(registry, path))
{
detail_row(ui, "Asset ID", &record.id.as_string());
if matches!(asset.kind, EditorAssetKind::Model) {
let settings = record.model_import();
ui.separator();
ui.label(panel_heading("Import Settings"));
import_settings_editor(world, ui, asset, path, settings);
if let Some(manifest) = settings.static_mesh_manifest_path.as_deref() {
detail_row(ui, "Static mesh artifact", manifest);
}
}
if matches!(asset.kind, EditorAssetKind::Texture) {
if let Some(settings) = record.texture_import() {
ui.separator();
ui.label(panel_heading("Texture Properties"));
texture_import_settings_editor(world, ui, path, &record, settings);
}
}
if !record.dependencies.is_empty() {
ui.separator();
let missing_count = record
.dependencies
.iter()
.filter(|dependency| !dependency_path(dependency).is_file())
.count();
ui.horizontal_wrapped(|ui| {
ui.label(panel_heading("Dependencies"));
if missing_count > 0 {
let optional = !model_uses_source_materials(&record);
ui.small(
egui::RichText::new(if optional {
format!("{missing_count} missing | override")
} else {
format!("{missing_count} missing")
})
.color(if optional {
WARNING
} else {
ERROR
}),
);
}
});
for dep in &record.dependencies {
let exists = dependency_path(dep).is_file();
ui.horizontal(|ui| {
ui.label(
egui::RichText::new(if exists {
icons::CHECK_CIRCLE.as_str()
} else {
icons::WARNING_CIRCLE.as_str()
})
.font(egui::FontId::new(
12.0,
egui::FontFamily::Name(PHOSPHOR.into()),
))
.color(if exists {
SUCCESS
} else {
WARNING
}),
);
ui.add(egui::Label::new(dep).truncate()).on_hover_text(dep);
});
}
}
}
detail_row(
ui,
"Size",
file_size(path).map(format_bytes).as_deref().unwrap_or("-"),
);
detail_row(
ui,
"Modified",
modified_time(path)
.map(format_modified)
.as_deref()
.unwrap_or("-"),
);
if matches!(asset.kind, EditorAssetKind::Material) {
ui.separator();
ui.label(panel_heading("Material"));
crate::ui::design_system::scope(ui, |ui| {
if MaterialInstanceAsset::load_from_path(path).is_ok() {
material_instance_asset_editor(world, ui, asset, path, true);
} else {
material_asset_editor(world, ui, asset, path, true);
}
});
}
if matches!(asset.kind, EditorAssetKind::AudioClip) {
detail_row(ui, "Format", audio_format_label(path));
let previewing = world
.resource::<crate::play::audio_preview::AudioPreviewState>()
.clip_path
.as_deref()
== Some(path);
ui.horizontal_wrapped(|ui| {
if ui
.add_enabled(
!previewing,
egui::Button::new(format!("{} Audition", icons::PLAY.as_str())),
)
.clicked()
{
if let Err(error) =
crate::play::audio_preview::audition_audio_asset(world, asset)
{
world.resource_mut::<SceneIo>().status =
format!("Audio audition failed: {error}");
}
}
if ui
.add_enabled(
previewing,
egui::Button::new(format!("{} Stop", icons::STOP.as_str())),
)
.clicked()
{
crate::play::audio_preview::stop_audio_preview(world);
}
});
}
}
ui.separator();
asset_action_buttons(world, ui, selected_entities, asset);
}
pub(super) fn asset_details_header(world: &World, ui: &mut egui::Ui, asset: &EditorAsset) {
ui.horizontal_wrapped(|ui| {
ui.label(
egui::RichText::new(kind_icon(&asset.kind).as_str())
.font(egui::FontId::new(
30.0,
egui::FontFamily::Name(PHOSPHOR.into()),
))
.color(ACCENT),
);
ui.vertical(|ui| {
ui.strong(asset.label.as_str());
ui.small(egui::RichText::new(kind_label(&asset.kind)).color(TEXT_DIM));
if let (Some(state), Some(path)) = (
world.get_resource::<CollaborationState>(),
asset.path.as_deref(),
) {
let status = state.file_status(Path::new(path));
let _ = file_status_indicator_ui(ui, &status, Path::new(path));
}
if let Some(snapshot) = asset.path.as_deref().and_then(|path| {
world
.get_resource::<crate::asset_documents::AuthoredAssetDocumentStore>()
.and_then(|store| store.snapshot_for_path(path))
}) {
if snapshot.dirty {
ui.small(egui::RichText::new("UNSAVED").color(WARNING).strong());
}
}
});
});
}
pub(super) fn subasset_details_panel(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
selection: &AssetSelection,
) {
let Some(embedded) = embedded_asset_for_selection(world, selection) else {
ui.colored_label(egui::Color32::YELLOW, "Embedded asset is not available.");
return;
};
let AssetSelection::SubAsset {
parent_path,
sub_asset_id,
..
} = selection
else {
return;
};
ui.horizontal_wrapped(|ui| {
ui.label(
egui::RichText::new(subasset_icon(embedded.kind).as_str())
.font(egui::FontId::new(
30.0,
egui::FontFamily::Name(PHOSPHOR.into()),
))
.color(ACCENT),
);
ui.vertical(|ui| {
ui.strong(embedded.label.as_str());
ui.small(egui::RichText::new(subasset_kind_label(embedded.kind)).color(TEXT_DIM));
});
});
ui.add_space(8.0);
detail_row(ui, "Parent", parent_path);
detail_row(ui, "ID", sub_asset_id);
detail_row(ui, "Source", &embedded.detail);
ui.separator();
match embedded.kind {
AssetSubAssetKind::Mesh => {
if embedded.requires_skinned_hierarchy {
if ui.button("Place Skinned Model At Origin").clicked() {
place_subasset_operator(world, selection.clone(), Vec3::ZERO);
}
} else if ui.button("Place At Origin").clicked() {
place_subasset_operator(world, selection.clone(), Vec3::ZERO);
}
}
AssetSubAssetKind::Texture => {
if ui.button("Apply Texture To Selection").clicked() {
if let Some(asset) =
texture_asset_from_subasset_selection(world, &Some(selection.clone()))
{
apply_texture_operator(world, asset, selected_entities);
}
}
}
AssetSubAssetKind::Material => {
let status = if embedded.detail.contains("Authoring Override") {
"Authoring Override is active; this source material is not assigned."
} else {
"Source material is assigned through static mesh renderer slots."
};
ui.small(egui::RichText::new(status).color(TEXT_DIM));
}
AssetSubAssetKind::Skeleton => {
ui.small(
egui::RichText::new("Skeleton metadata is generated from the model source.")
.color(TEXT_DIM),
);
}
AssetSubAssetKind::AnimationClip => {
let animated_actor = selected_entities
.as_slice()
.iter()
.copied()
.find(|entity| world.get::<shared::SkinnedMeshRenderer>(*entity).is_some());
let action = if animated_actor.is_some() {
"Assign To Selected Actor"
} else {
"Create Animated Actor"
};
if ui.button(action).clicked() {
if let Some(entity) = animated_actor {
assign_animation_clip_operator(world, selection.clone(), entity);
} else {
place_subasset_operator(world, selection.clone(), Vec3::ZERO);
}
}
}
}
if ui.button("Select Parent Asset").clicked() {
world
.resource_mut::<EditorAssets>()
.select(AssetSelection::File(parent_path.clone()));
}
}
pub(super) fn dependency_path(reference: &str) -> PathBuf {
let path = Path::new(reference);
if path.starts_with("assets") {
path.to_path_buf()
} else {
Path::new("assets").join(path)
}
}
pub(super) fn asset_action_buttons(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
asset: &EditorAsset,
) {
ui.horizontal_wrapped(|ui| {
if matches!(asset.kind, EditorAssetKind::Texture) && ui.button("Apply Texture").clicked() {
apply_texture_operator(world, asset.clone(), selected_entities);
}
if asset.path.is_some()
&& matches!(asset.kind, EditorAssetKind::Material)
&& ui.button("Apply Material").clicked()
{
apply_material_operator(world, asset.clone(), selected_entities);
}
if matches!(
asset.kind,
EditorAssetKind::Primitive(_)
| EditorAssetKind::Light(_)
| EditorAssetKind::Model
| EditorAssetKind::AudioClip
| EditorAssetKind::Prefab
) && ui.button("Place At Origin").clicked()
{
place_asset_operator(world, asset.clone(), Vec3::ZERO);
}
if matches!(asset.kind, EditorAssetKind::Level) && ui.button("Open Scene").clicked() {
open_level_asset(world, asset);
}
if matches!(asset.kind, EditorAssetKind::Model)
&& has_embedded_assets(world, asset)
&& ui.button("Toggle Contents").clicked()
{
if let Some(path) = asset.path.as_ref() {
toggle_asset_expanded(world, path);
}
}
if matches!(asset.kind, EditorAssetKind::Model) && ui.button("Reimport").clicked() {
reimport_asset(world, asset);
}
if asset.path.is_some() && ui.button("Move To Trash").clicked() {
request_delete_for_asset(world, asset);
}
});
}
pub(super) fn open_level_asset(world: &mut World, asset: &EditorAsset) {
let Some(path) = asset.path.as_deref() else {
return;
};
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::OpenPath(PathBuf::from(path)));
}
pub(super) fn activate_content_asset(world: &mut World, asset: &EditorAsset) {
world
.resource_mut::<EditorAssets>()
.select(AssetSelection::from_asset(asset));
match asset.kind {
EditorAssetKind::Level => open_level_asset(world, asset),
EditorAssetKind::Model if has_embedded_assets(world, asset) => {
if let Some(path) = asset.path.as_deref() {
toggle_asset_expanded(world, path);
}
}
_ => {
world.resource_mut::<AssetBrowserUiState>().show_details = true;
}
}
}
@@ -0,0 +1,374 @@
use super::*;
#[derive(Clone)]
pub(super) struct AssetBrowserStateSnapshot {
pub(super) search: String,
pub(super) view: AssetBrowserView,
pub(super) sort: AssetSort,
pub(super) kind_filter: AssetKindFilter,
pub(super) thumbnail_size: f32,
pub(super) recursive: bool,
pub(super) show_details: bool,
pub(super) details_width: f32,
}
pub(super) fn state_snapshot(state: &AssetBrowserUiState) -> AssetBrowserStateSnapshot {
AssetBrowserStateSnapshot {
search: state.search.clone(),
view: state.view,
sort: state.sort,
kind_filter: state.kind_filter,
thumbnail_size: state.thumbnail_size,
recursive: state.recursive,
show_details: state.show_details,
details_width: state.details_width,
}
}
pub(super) fn embedded_assets_for_asset(world: &World, asset: &EditorAsset) -> Vec<EmbeddedAsset> {
if !matches!(asset.kind, EditorAssetKind::Model) {
return Vec::new();
}
let Some(parent_path) = asset.path.as_ref() else {
return Vec::new();
};
let Some(record) = world
.get_resource::<crate::asset_db::AssetRegistry>()
.and_then(|registry| find_asset_by_path(registry, parent_path))
else {
return Vec::new();
};
let mut embedded = Vec::new();
let settings = record.model_import();
let static_manifest = settings
.static_mesh_manifest_path
.as_deref()
.and_then(|path| load_static_mesh_manifest(path).ok());
let legacy_skinned_primitives = static_manifest
.as_ref()
.filter(|manifest| manifest.schema_version < 2)
.map(|_| crate::assets::gltf_skinned_primitive_labels(parent_path.as_str()))
.unwrap_or_default();
if let Some(manifest) = static_manifest.as_ref() {
for part in &manifest.parts {
let mesh_id = part_effective_id(part);
let material_label = part.material_label.clone();
let requires_skinned_hierarchy = manifest.metadata.animation_count > 0
|| part.skinned
|| legacy_skinned_primitives.contains(&part.mesh_label);
embedded.push(EmbeddedAsset {
selection: AssetSelection::SubAsset {
parent_path: parent_path.clone(),
sub_asset_id: mesh_id,
label: part.name.clone(),
kind: AssetSubAssetKind::Mesh,
source_path: None,
},
label: part.name.clone(),
kind: AssetSubAssetKind::Mesh,
detail: if requires_skinned_hierarchy {
"Skinned | dedicated renderer".to_string()
} else {
part.source_mesh
.clone()
.unwrap_or_else(|| part.mesh_label.clone())
},
texture_path: None,
thumbnail_key: subasset_thumbnail_key(
parent_path,
AssetSubAssetKind::Mesh,
&part_effective_id(part),
),
mesh_label: Some(part.mesh_label.clone()),
material_label,
requires_skinned_hierarchy,
});
}
let mut material_ids = HashSet::new();
for part in &manifest.parts {
let Some(material_id) = part_effective_material_id(part) else {
continue;
};
if !material_ids.insert(material_id.clone()) {
continue;
}
let label = if part.material_slot_name.trim().is_empty() {
part.material_label
.clone()
.unwrap_or_else(|| "Source Material".to_string())
} else {
part.material_slot_name.clone()
};
let source_used = manifest.parts.iter().any(|candidate| {
part_effective_material_id(candidate).as_deref() == Some(material_id.as_str())
&& matches!(
crate::assets::static_mesh::material_selection(
settings,
&format!("slot:{}", part_effective_id(candidate)),
),
ModelMaterialSelection::Source
)
});
embedded.push(EmbeddedAsset {
selection: AssetSelection::SubAsset {
parent_path: parent_path.clone(),
sub_asset_id: material_id,
label: label.clone(),
kind: AssetSubAssetKind::Material,
source_path: None,
},
label,
kind: AssetSubAssetKind::Material,
detail: if source_used {
"Embedded source material · active model default".to_string()
} else {
"Embedded source material · available".to_string()
},
texture_path: None,
thumbnail_key: subasset_thumbnail_key(
parent_path,
AssetSubAssetKind::Material,
&part_effective_material_id(part).unwrap_or_else(|| {
material_id_from_label(
part.material_label
.as_deref()
.unwrap_or(&part.material_slot_name),
)
}),
),
mesh_label: None,
material_label: part.material_label.clone(),
requires_skinned_hierarchy: false,
});
}
let mut texture_paths = HashSet::new();
for dependency in &manifest.source.dependencies {
if !is_texture_path(dependency) || !texture_paths.insert(dependency.clone()) {
continue;
}
let label = Path::new(dependency)
.file_stem()
.and_then(|stem| stem.to_str())
.unwrap_or(dependency)
.to_string();
embedded.push(EmbeddedAsset {
selection: AssetSelection::SubAsset {
parent_path: parent_path.clone(),
sub_asset_id: format!("texture:{}", stable_subasset_slug(dependency)),
label: label.clone(),
kind: AssetSubAssetKind::Texture,
source_path: Some(dependency.clone()),
},
label,
kind: AssetSubAssetKind::Texture,
detail: dependency.clone(),
texture_path: Some(dependency.clone()),
thumbnail_key: subasset_thumbnail_key(
parent_path,
AssetSubAssetKind::Texture,
&stable_subasset_slug(dependency),
),
mesh_label: None,
material_label: None,
requires_skinned_hierarchy: false,
});
}
}
let animation_manifest = settings
.animation_manifest_path
.as_deref()
.and_then(|path| load_animation_manifest(path).ok());
if let Some(manifest) = animation_manifest {
for skeleton in manifest.skeletons {
let signature = skeleton.signature.0;
let signature_short = signature.get(..8).unwrap_or(&signature);
embedded.push(EmbeddedAsset {
selection: AssetSelection::SubAsset {
parent_path: parent_path.clone(),
sub_asset_id: skeleton.id.clone(),
label: skeleton.label.clone(),
kind: AssetSubAssetKind::Skeleton,
source_path: Some(parent_path.clone()),
},
label: skeleton.label,
kind: AssetSubAssetKind::Skeleton,
detail: format!(
"{} joints | rig {}",
skeleton.joint_paths.len(),
signature_short
),
texture_path: None,
thumbnail_key: subasset_thumbnail_key(
parent_path,
AssetSubAssetKind::Skeleton,
&skeleton.id,
),
mesh_label: None,
material_label: None,
requires_skinned_hierarchy: false,
});
}
for clip in manifest.clips {
let event_suffix = if clip.events.is_empty() {
String::new()
} else {
format!(" | {} events", clip.events.len())
};
embedded.push(EmbeddedAsset {
selection: AssetSelection::SubAsset {
parent_path: parent_path.clone(),
sub_asset_id: clip.id.clone(),
label: clip.label.clone(),
kind: AssetSubAssetKind::AnimationClip,
source_path: Some(parent_path.clone()),
},
label: clip.label,
kind: AssetSubAssetKind::AnimationClip,
detail: format!("{:.2}s{event_suffix}", clip.duration_seconds),
texture_path: None,
thumbnail_key: subasset_thumbnail_key(
parent_path,
AssetSubAssetKind::AnimationClip,
&clip.id,
),
mesh_label: None,
material_label: None,
requires_skinned_hierarchy: false,
});
}
}
embedded
}
pub(super) fn texture_asset_from_subasset_selection(
world: &World,
selection: &Option<AssetSelection>,
) -> Option<EditorAsset> {
let Some(AssetSelection::SubAsset {
label,
kind: AssetSubAssetKind::Texture,
source_path: Some(path),
..
}) = selection
else {
return None;
};
if let Some(asset) = world
.resource::<EditorAssets>()
.assets
.iter()
.find(|asset| asset.path.as_deref() == Some(path.as_str()))
{
return Some(asset.clone());
}
Some(EditorAsset {
label: label.clone(),
path: Some(path.clone()),
folder_path: Path::new(path)
.parent()
.map(|parent| parent.to_string_lossy().replace('\\', "/"))
.unwrap_or_else(|| ASSETS_ROOT.to_string()),
kind: EditorAssetKind::Texture,
})
}
pub(super) fn model_uses_source_materials(record: &crate::asset_db::AssetRecord) -> bool {
let settings = record.model_import();
let Some(manifest_path) = settings.static_mesh_manifest_path.as_deref() else {
return true;
};
let Ok(manifest) = load_static_mesh_manifest(manifest_path) else {
return true;
};
manifest.parts.iter().any(|part| {
part_effective_material_id(part).is_some()
&& matches!(
crate::assets::static_mesh::material_selection(
settings,
&format!("slot:{}", part_effective_id(part)),
),
ModelMaterialSelection::Source
)
})
}
pub(super) fn embedded_asset_for_selection(
world: &World,
selection: &AssetSelection,
) -> Option<EmbeddedAsset> {
let AssetSelection::SubAsset { parent_path, .. } = selection else {
return None;
};
let asset = world
.resource::<EditorAssets>()
.assets
.iter()
.find(|asset| asset.path.as_deref() == Some(parent_path.as_str()))?
.clone();
embedded_assets_for_asset(world, &asset)
.into_iter()
.find(|embedded| &embedded.selection == selection)
}
pub(super) fn has_embedded_assets(world: &World, asset: &EditorAsset) -> bool {
!embedded_assets_for_asset(world, asset).is_empty()
}
pub(super) fn part_effective_id(part: &crate::assets::static_mesh::StaticMeshPart) -> String {
if part.id.trim().is_empty() {
part_id_from_label(&part.mesh_label)
} else {
part.id.clone()
}
}
pub(super) fn part_effective_material_id(
part: &crate::assets::static_mesh::StaticMeshPart,
) -> Option<String> {
part.material_id.clone().or_else(|| {
part.material_label
.as_ref()
.map(|label| material_id_from_label(label))
})
}
pub(super) fn is_texture_path(path: &str) -> bool {
Path::new(path)
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
matches!(
extension.to_ascii_lowercase().as_str(),
"png" | "jpg" | "jpeg" | "webp" | "ktx2"
)
})
}
pub(super) fn stable_subasset_slug(label: &str) -> String {
let mut slug = String::new();
for ch in label.chars() {
if ch.is_ascii_alphanumeric() {
slug.push(ch.to_ascii_lowercase());
} else if !slug.ends_with('_') {
slug.push('_');
}
}
slug.trim_matches('_').to_string()
}
pub(super) fn subasset_thumbnail_key(
parent_path: &str,
kind: AssetSubAssetKind,
sub_asset_id: &str,
) -> String {
format!(
"subasset:{}#{}:{}",
parent_path,
subasset_kind_label(kind).to_ascii_lowercase(),
sub_asset_id
)
}
@@ -0,0 +1,544 @@
use super::*;
pub(super) fn begin_new_folder(world: &mut World, parent: String) {
world
.resource_mut::<AssetBrowserUiState>()
.pending_path_edit = Some(ContentPathEdit {
kind: ContentPathEditKind::NewFolder { parent },
name: "New Folder".into(),
});
}
pub(super) fn create_material_here(world: &mut World, folder: &str) {
if let Err(error) =
crate::ui::material_library::create_material_asset_in(world, Path::new(folder))
{
world.resource_mut::<SceneIo>().status = error;
}
}
pub(super) fn begin_rename(world: &mut World) {
if world.resource::<EditorAssets>().selections.len() > 1 {
world.resource_mut::<SceneIo>().status = "Rename requires one selected item".into();
return;
}
let Some(source) = selected_content_path(world) else {
world.resource_mut::<SceneIo>().status = "Select an asset or folder to rename".into();
return;
};
let name = Path::new(&source)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("Asset")
.to_string();
world
.resource_mut::<AssetBrowserUiState>()
.pending_path_edit = Some(ContentPathEdit {
kind: ContentPathEditKind::Rename { source },
name,
});
}
pub(super) fn set_content_clipboard(world: &mut World, cut: bool) {
let sources = selected_content_paths(world);
if sources.is_empty() {
world.resource_mut::<SceneIo>().status = "Select an asset or folder first".into();
return;
}
world.resource_mut::<AssetBrowserUiState>().clipboard = Some(ContentClipboard {
sources: sources.clone(),
cut,
});
world.resource_mut::<SceneIo>().status = format!(
"{} {} item(s)",
if cut { "Cut" } else { "Copied" },
sources.len()
);
}
pub(super) fn duplicate_selection(world: &mut World) {
let sources = selected_content_paths(world);
if sources.is_empty() {
world.resource_mut::<SceneIo>().status = "Select an asset or folder to duplicate".into();
return;
}
let operations = sources
.into_iter()
.map(|source| {
let source_path = Path::new(&source);
let parent = source_path
.parent()
.unwrap_or_else(|| Path::new(ASSETS_ROOT));
content_pipeline::ContentOperation::Copy {
source: source.clone().into(),
destination: unique_copy_destination(parent, source_path),
}
})
.collect();
queue_content_operations(world, operations, false, false);
}
pub(super) fn paste_content_clipboard(world: &mut World) {
let destination_folder = world.resource::<EditorAssets>().current_folder.clone();
paste_content_clipboard_into(world, &destination_folder);
}
pub(super) fn paste_content_clipboard_into(world: &mut World, destination_folder: &str) {
let Some(clipboard) = world.resource::<AssetBrowserUiState>().clipboard.clone() else {
return;
};
let mut reserved = HashSet::new();
let operations: Vec<_> = clipboard
.sources
.iter()
.filter_map(|source| {
let source_path = Path::new(source);
if clipboard.cut && source_path.parent() == Some(Path::new(destination_folder)) {
return None;
}
let destination = paste_destination(
Path::new(destination_folder),
source_path,
clipboard.cut,
&mut reserved,
);
Some(if clipboard.cut {
content_pipeline::ContentOperation::Move {
source: source.clone().into(),
destination,
}
} else {
content_pipeline::ContentOperation::Copy {
source: source.clone().into(),
destination,
}
})
})
.collect();
if operations.is_empty() {
world.resource_mut::<SceneIo>().status = "Content is already in this folder".into();
return;
}
queue_content_operations(world, operations, clipboard.cut, false);
}
pub(super) fn paste_destination(
parent: &Path,
source: &Path,
cut: bool,
reserved: &mut HashSet<PathBuf>,
) -> PathBuf {
let direct = parent.join(source.file_name().unwrap_or_default());
if cut {
// Moves keep their intended filename. Existing or duplicate targets must remain visible as
// review collisions instead of silently turning a move into a renamed copy.
return direct;
}
if !direct.exists() && reserved.insert(direct.clone()) {
return direct;
}
let mut candidate = unique_copy_destination(parent, source);
while !reserved.insert(candidate.clone()) {
candidate = unique_copy_destination(parent, &candidate);
}
candidate
}
pub(super) fn unique_copy_destination(parent: &Path, source: &Path) -> PathBuf {
let name = source
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("Asset");
let (stem, suffix) = name
.split_once('.')
.map_or((name, ""), |(stem, suffix)| (stem, suffix));
for index in 1.. {
let marker = if index == 1 {
"_copy".into()
} else {
format!("_copy_{index}")
};
let candidate_name = if suffix.is_empty() {
format!("{stem}{marker}")
} else {
format!("{stem}{marker}.{suffix}")
};
let candidate = parent.join(candidate_name);
if !candidate.exists() {
return candidate;
}
}
unreachable!()
}
pub(super) fn draw_path_edit_modal(world: &mut World, ctx: &egui::Context) {
let Some(mut edit) = world
.resource::<AssetBrowserUiState>()
.pending_path_edit
.clone()
else {
return;
};
let title = match edit.kind {
ContentPathEditKind::Rename { .. } => "Rename Content",
ContentPathEditKind::NewFolder { .. } => "Create Folder",
};
let mut apply = false;
let mut cancel = false;
egui::Window::new(title)
.collapsible(false)
.resizable(false)
.show(ctx, |ui| {
ui.label("Name");
let response = ui.add_sized([300.0, 24.0], egui::TextEdit::singleline(&mut edit.name));
let valid = valid_content_name(&edit.name);
if !valid {
ui.colored_label(
crate::ui::theme::ERROR,
"Use a normal file/folder name without slashes.",
);
}
ui.horizontal(|ui| {
apply = ui.add_enabled(valid, egui::Button::new("Apply")).clicked()
|| (valid
&& response.lost_focus()
&& ui.input(|input| input.key_pressed(egui::Key::Enter)));
cancel = ui.button("Cancel").clicked();
});
});
if cancel {
world
.resource_mut::<AssetBrowserUiState>()
.pending_path_edit = None;
} else if apply {
let operation = match &edit.kind {
ContentPathEditKind::Rename { source } => {
let source_path = Path::new(source);
let destination = source_path
.parent()
.unwrap_or_else(|| Path::new(ASSETS_ROOT))
.join(&edit.name);
content_pipeline::ContentOperation::Move {
source: source.into(),
destination,
}
}
ContentPathEditKind::NewFolder { parent } => {
content_pipeline::ContentOperation::CreateFolder {
path: Path::new(parent).join(&edit.name),
}
}
};
if queue_content_operations(world, vec![operation], false, false) {
world
.resource_mut::<AssetBrowserUiState>()
.pending_path_edit = None;
}
} else {
world
.resource_mut::<AssetBrowserUiState>()
.pending_path_edit = Some(edit);
}
}
pub(super) fn valid_content_name(name: &str) -> bool {
let trimmed = name.trim();
!trimmed.is_empty()
&& !matches!(trimmed, "." | "..")
&& !trimmed.contains(['/', '\\'])
&& !trimmed.starts_with('.')
}
pub(super) fn queue_content_operations(
world: &mut World,
operations: Vec<content_pipeline::ContentOperation>,
clear_cut_clipboard: bool,
clear_drag: bool,
) -> bool {
if operations.is_empty() {
return false;
}
let document = world
.resource::<crate::asset_db::AssetRegistry>()
.document();
let preview = match content_pipeline::preview_transaction(Path::new("."), operations, &document)
{
Ok(preview) => preview,
Err(error) => {
world.resource_mut::<SceneIo>().status =
format!("Content operation preview failed: {error}");
return false;
}
};
let operation_count = preview.operations.len();
let affected_count = preview.affected_asset_ids.len();
let rewrite_count = preview.reference_rewrites.len();
let mut guarded_paths = HashSet::new();
for operation in &preview.operations {
if let content_pipeline::ContentOperation::Move { source, .. }
| content_pipeline::ContentOperation::Copy { source, .. } = operation
{
guarded_paths.insert(source.clone());
}
}
guarded_paths.extend(
preview
.reference_rewrites
.iter()
.map(|rewrite| rewrite.document.clone()),
);
let mut guarded_paths = guarded_paths
.into_iter()
.map(|path| {
content_pipeline::tree_fingerprint(&path).map(|fingerprint| (path, fingerprint))
})
.collect::<Result<Vec<_>, _>>()
.map_err(|error| {
world.resource_mut::<SceneIo>().status =
format!("Content operation guard failed: {error}");
});
let Ok(ref mut guarded_paths) = guarded_paths else {
return false;
};
guarded_paths.sort_by(|left, right| left.0.cmp(&right.0));
let browser_snapshot = capture_content_browser_snapshot(world);
world
.resource_mut::<AssetBrowserUiState>()
.pending_content_transaction = Some(PendingContentTransaction {
preview,
guarded_paths: std::mem::take(guarded_paths),
clear_cut_clipboard,
clear_drag,
browser_snapshot,
});
world.resource_mut::<SceneIo>().status = format!(
"Review {operation_count} content operation(s): {affected_count} asset ID(s), {rewrite_count} cached reference rewrite(s)"
);
true
}
pub(super) fn draw_content_transaction_modal(world: &mut World, ctx: &egui::Context) {
let Some(pending) = world
.resource::<AssetBrowserUiState>()
.pending_content_transaction
.clone()
else {
return;
};
let mut cancel = false;
let mut commit = false;
let collaboration_statuses =
content_transaction_collaboration_statuses(world, &pending.preview);
let has_collaboration_blocker = collaboration_statuses
.iter()
.any(|(_, _, _, blocked)| *blocked);
let externally_changed = pending
.guarded_paths
.iter()
.filter(|(path, expected)| {
content_pipeline::tree_fingerprint(path).as_deref() != Ok(expected.as_str())
})
.map(|(path, _)| path.clone())
.collect::<Vec<_>>();
egui::Window::new("Review Content Operation")
.collapsible(false)
.resizable(true)
.default_width(660.0)
.min_width(520.0)
.show(ctx, |ui| {
ui.small(
egui::RichText::new(
"Filesystem paths, registry identity, generated catalog entries, and cached project references commit together or roll back together.",
)
.color(TEXT_DIM),
);
ui.separator();
egui::ScrollArea::vertical()
.max_height(260.0)
.show(ui, |ui| {
for operation in &pending.preview.operations {
ui.label(content_operation_summary(operation));
}
});
ui.separator();
ui.label(format!(
"Affected registered assets: {}",
pending.preview.affected_asset_ids.len()
));
ui.label(format!(
"Cached reference documents to rewrite: {}",
pending.preview.reference_rewrites.len()
));
for rewrite in pending.preview.reference_rewrites.iter().take(8) {
ui.small(format!(
"{}: {} → {}",
rewrite.document.display(),
rewrite.from,
rewrite.to
));
}
if pending.preview.reference_rewrites.len() > 8 {
ui.small(format!(
"…and {} more",
pending.preview.reference_rewrites.len() - 8
));
}
if !pending.preview.collisions.is_empty() {
ui.separator();
ui.colored_label(ERROR, "Resolve these path collisions before committing:");
for collision in &pending.preview.collisions {
ui.small(collision.display().to_string());
}
}
if !collaboration_statuses.is_empty() {
ui.separator();
ui.label("Source-control / ownership state");
for (path, label, tooltip, blocked) in &collaboration_statuses {
ui.horizontal(|ui| {
ui.small(path.display().to_string());
ui.colored_label(if *blocked { ERROR } else { WARNING }, label)
.on_hover_text(tooltip);
});
}
}
if !externally_changed.is_empty() {
ui.separator();
ui.colored_label(
ERROR,
"Content changed after this preview. Cancel and review the operation again:",
);
for path in &externally_changed {
ui.small(path.display().to_string());
}
}
ui.separator();
ui.horizontal(|ui| {
cancel = ui.button("Cancel").clicked();
commit = ui
.add_enabled(
pending.preview.is_committable()
&& !has_collaboration_blocker
&& externally_changed.is_empty(),
egui::Button::new("Commit Transaction"),
)
.clicked();
});
});
if cancel {
restore_cancelled_content_transaction(world, &pending);
world
.resource_mut::<AssetBrowserUiState>()
.pending_content_transaction = None;
} else if commit {
let operations = pending.preview.operations.clone();
if commit_content_operations_internal(world, operations, true) {
if pending.clear_cut_clipboard {
world.resource_mut::<AssetBrowserUiState>().clipboard = None;
}
if pending.clear_drag {
world.resource_mut::<EditorAssets>().clear_drag();
}
world
.resource_mut::<AssetBrowserUiState>()
.pending_content_transaction = None;
}
}
}
pub(super) fn capture_content_browser_snapshot(world: &World) -> ContentBrowserSnapshot {
let assets = world.resource::<EditorAssets>();
ContentBrowserSnapshot {
current_folder: assets.current_folder.clone(),
selected: assets.selected.clone(),
selections: assets.selections.clone(),
selection_anchor: assets.selection_anchor.clone(),
dragging: assets.dragging.clone(),
asset_status: assets.status.clone(),
scene_status: world.resource::<SceneIo>().status.clone(),
}
}
pub(super) fn restore_cancelled_content_transaction(
world: &mut World,
pending: &PendingContentTransaction,
) {
let snapshot = &pending.browser_snapshot;
{
let mut assets = world.resource_mut::<EditorAssets>();
assets.current_folder.clone_from(&snapshot.current_folder);
assets.selected.clone_from(&snapshot.selected);
assets.selections.clone_from(&snapshot.selections);
assets
.selection_anchor
.clone_from(&snapshot.selection_anchor);
assets.dragging = if pending.clear_drag {
None
} else {
snapshot.dragging.clone()
};
assets.status.clone_from(&snapshot.asset_status);
}
world
.resource_mut::<SceneIo>()
.status
.clone_from(&snapshot.scene_status);
}
pub(super) fn content_transaction_collaboration_statuses(
world: &World,
preview: &content_pipeline::ContentTransactionPreview,
) -> Vec<(PathBuf, String, String, bool)> {
let Some(collaboration) = world.get_resource::<CollaborationState>() else {
return Vec::new();
};
let mut paths = HashSet::new();
for operation in &preview.operations {
if let content_pipeline::ContentOperation::Move { source, .. }
| content_pipeline::ContentOperation::Copy { source, .. } = operation
{
paths.insert(source.clone());
}
}
paths.extend(
preview
.reference_rewrites
.iter()
.map(|rewrite| rewrite.document.clone()),
);
let mut statuses = paths
.into_iter()
.filter_map(|path| {
let status = collaboration.file_status(&path);
let indicator = status.indicator()?;
let label = indicator.label.to_string();
let blocked = status.readonly || status.locked_by_other || label == "CONFLICT";
let tooltip = status.tooltip(&path);
Some((path, label, tooltip, blocked))
})
.collect::<Vec<_>>();
statuses.sort_by(|left, right| left.0.cmp(&right.0));
statuses
}
pub(super) fn content_operation_summary(operation: &content_pipeline::ContentOperation) -> String {
match operation {
content_pipeline::ContentOperation::CreateFolder { path } => {
format!("Create folder {}", path.display())
}
content_pipeline::ContentOperation::Move {
source,
destination,
} => format!("Move {} → {}", source.display(), destination.display()),
content_pipeline::ContentOperation::Copy {
source,
destination,
} => format!("Copy {} → {}", source.display(), destination.display()),
content_pipeline::ContentOperation::WriteFile { path, bytes } => {
format!("Create asset {} ({} bytes)", path.display(), bytes.len())
}
content_pipeline::ContentOperation::ReplaceFile { path, bytes, .. } => {
format!("Replace asset {} ({} bytes)", path.display(), bytes.len())
}
}
}
@@ -0,0 +1,567 @@
use super::*;
pub(super) fn content_empty_space(
world: &mut World,
response: egui::Response,
current_folder: &str,
visible_order: &[AssetSelection],
) {
if response.clicked() || response.secondary_clicked() {
world.resource_mut::<EditorAssets>().clear_selection();
}
response.context_menu(|ui| {
empty_space_context_menu(world, ui, current_folder, visible_order);
});
}
#[expect(
clippy::too_many_arguments,
reason = "asset grid rendering keeps immediate-mode UI inputs explicit"
)]
pub(super) fn asset_grid(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
selected: &Option<AssetSelection>,
folders: &[FolderSnapshot],
assets: &[AssetRow],
cache_snapshot: &ThumbnailCacheSnapshot,
thumbnail_size: f32,
visible_order: &[AssetSelection],
) {
let thumb_size = thumbnail_size.clamp(48.0, 112.0);
let cell_width = thumb_size + 20.0;
let gap = 6.0;
let columns = ((ui.available_width() + gap) / (cell_width + gap))
.floor()
.max(1.0) as usize;
for folder_row in folders.chunks(columns) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing = egui::vec2(gap, gap);
for folder in folder_row {
let selection = AssetSelection::Folder(folder.path.clone());
let is_selected = world.resource::<EditorAssets>().is_selected(&selection);
let response = draw_folder_cell(ui, folder, thumbnail_size, is_selected);
handle_asset_drop_to_folder(world, ui, &response, &folder.path);
if response.secondary_clicked() {
prepare_context_menu_selection(world, selection.clone());
}
if response.double_clicked() {
navigate_content_folder(world, folder.path.clone());
} else if response.clicked() {
apply_content_click_selection(world, ui, selection.clone(), visible_order);
}
if response.drag_started() {
world
.resource_mut::<EditorAssets>()
.start_drag(selection.clone());
}
response.context_menu(|ui| folder_context_menu(world, ui, folder));
}
});
}
for asset_row in assets.chunks(columns) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing = egui::vec2(gap, gap);
for row in asset_row {
draw_asset_grid_item(
world,
ui,
selected_entities,
selected,
row,
cache_snapshot,
thumbnail_size,
visible_order,
);
}
});
for row in asset_row {
if row.asset.path.as_deref().is_some_and(|path| {
world
.resource::<AssetBrowserUiState>()
.expanded_assets
.contains(path)
}) {
embedded_asset_shelf(
world,
ui,
selected_entities,
selected,
&row.asset,
cache_snapshot,
thumbnail_size,
);
}
}
}
}
pub(super) fn handle_asset_drop_to_folder(
world: &mut World,
ui: &egui::Ui,
response: &egui::Response,
destination_folder: &str,
) {
if !response.hovered() || !ui.input(|input| input.pointer.any_released()) {
return;
}
let dragging = world
.resource::<EditorAssets>()
.dragging_selection()
.cloned();
let Some(dragging) = dragging else {
return;
};
let sources = if world.resource::<EditorAssets>().is_selected(&dragging) {
selected_content_paths(world)
} else {
dragging
.parent_path()
.map(|path| vec![path.to_string()])
.unwrap_or_default()
};
let operations: Vec<_> = sources
.into_iter()
.filter_map(|source| {
let file_name = Path::new(&source).file_name()?;
let destination = Path::new(destination_folder).join(file_name);
(destination.as_path() != Path::new(&source)).then_some(
content_pipeline::ContentOperation::Move {
source: PathBuf::from(source),
destination,
},
)
})
.collect();
if !operations.is_empty() {
queue_content_operations(world, operations, false, true);
}
}
#[expect(
clippy::too_many_arguments,
reason = "asset rows keep selection, thumbnail, and visible-order UI inputs explicit"
)]
pub(super) fn draw_asset_grid_item(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
_selected: &Option<AssetSelection>,
row: &AssetRow,
cache_snapshot: &ThumbnailCacheSnapshot,
thumbnail_size: f32,
visible_order: &[AssetSelection],
) {
let selection = &row.selection;
let asset = &row.asset;
let is_selected = world.resource::<EditorAssets>().is_selected(selection);
let failure = cache_snapshot.failure_reason(asset);
let has_children = has_embedded_assets(world, asset);
let document_status = asset.path.as_deref().and_then(|path| {
world
.get_resource::<crate::asset_documents::AuthoredAssetDocumentStore>()
.and_then(|store| store.snapshot_for_path(path))
});
let response = draw_asset_card(
ui,
asset,
cache_snapshot.texture_for(asset),
cache_snapshot.is_pending(asset),
failure,
is_selected,
thumbnail_size,
AssetCardStatus::for_document(
document_status.as_ref(),
document_status.as_ref().is_some_and(|status| status.dirty),
failure.is_some(),
),
);
if has_children {
let expanded = asset.path.as_deref().is_some_and(|path| {
world
.resource::<AssetBrowserUiState>()
.expanded_assets
.contains(path)
});
let icon = if expanded {
icons::CARET_DOWN
} else {
icons::CARET_RIGHT
};
let button_rect = egui::Rect::from_min_size(
response.rect.min + egui::vec2(6.0, 6.0),
egui::vec2(18.0, 18.0),
);
let expand_response = ui.interact(
button_rect,
egui::Id::new((
"asset_expand",
asset.path.as_deref().unwrap_or(&asset.label),
)),
egui::Sense::click(),
);
ui.painter().rect(
button_rect,
3.0,
if expand_response.hovered() {
ELEVATED_BG
} else {
WIDGET_BG.linear_multiply(1.15)
},
egui::Stroke::new(1.0_f32, BORDER),
egui::StrokeKind::Inside,
);
ui.painter().text(
button_rect.center(),
egui::Align2::CENTER_CENTER,
icon.as_str(),
egui::FontId::new(11.0, egui::FontFamily::Name(PHOSPHOR.into())),
TEXT,
);
if expand_response.clicked() {
if let Some(path) = asset.path.as_ref() {
toggle_asset_expanded(world, path);
}
}
}
if response.double_clicked() {
if failure.is_some() {
let key = crate::assets::asset_cache_key(asset);
crate::assets::retry_thumbnail(world, &key);
} else {
activate_content_asset(world, asset);
}
} else if response.clicked() {
apply_content_click_selection(world, ui, selection.clone(), visible_order);
}
if response.drag_started() {
world
.resource_mut::<EditorAssets>()
.start_drag(selection.clone());
}
if response.secondary_clicked() {
prepare_context_menu_selection(world, selection.clone());
}
response.context_menu(|ui| {
asset_context_menu(world, ui, asset, selected_entities);
});
}
pub(super) fn embedded_asset_shelf(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
selected: &Option<AssetSelection>,
parent_asset: &EditorAsset,
cache_snapshot: &ThumbnailCacheSnapshot,
thumbnail_size: f32,
) {
let embedded = embedded_assets_for_asset(world, parent_asset);
if embedded.is_empty() {
return;
}
prefetch_embedded_thumbnails(world, parent_asset, &embedded);
let parent_texture = cache_snapshot.texture_for(parent_asset);
ui.add_space(4.0);
egui::Frame::new()
.fill(WIDGET_BG.linear_multiply(0.72))
.stroke(egui::Stroke::new(1.0_f32, BORDER.linear_multiply(0.85)))
.corner_radius(egui::CornerRadius::same(4))
.inner_margin(egui::Margin::symmetric(8, 5))
.show(ui, |ui| {
ui.set_min_width(ui.available_width());
ui.horizontal(|ui| {
ui.label(icon_text(icons::TREE_STRUCTURE, 13.0).color(TEXT_DIM));
ui.small(
egui::RichText::new(format!("{} contents", parent_asset.label)).color(TEXT_DIM),
);
});
egui::ScrollArea::horizontal()
.id_salt(format!(
"embedded_shelf_{}",
parent_asset.path.as_deref().unwrap_or(&parent_asset.label)
))
.max_height(thumbnail_size.clamp(48.0, 88.0) + 56.0)
.auto_shrink([false, true])
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing = egui::vec2(7.0, 5.0);
for embedded_asset in &embedded {
draw_embedded_asset_cell(
world,
ui,
selected_entities,
selected,
embedded_asset,
cache_snapshot,
parent_texture,
thumbnail_size,
);
}
});
});
});
ui.add_space(4.0);
}
pub(super) fn prefetch_embedded_thumbnails(
world: &mut World,
parent_asset: &EditorAsset,
embedded: &[EmbeddedAsset],
) {
let Some(parent_path) = parent_asset.path.clone() else {
return;
};
let asset_server = world.resource::<AssetServer>().clone();
let requests: Vec<EmbeddedAsset> = embedded.to_vec();
world.resource_scope(|world, mut cache: Mut<AssetThumbnailCache>| {
world.resource_scope(|_world, mut studio: Mut<crate::assets::ThumbnailStudio>| {
for embedded_asset in &requests {
match embedded_asset.kind {
AssetSubAssetKind::Mesh => {
let Some(mesh_label) = embedded_asset.mesh_label.clone() else {
continue;
};
cache.request_mesh_subasset(
embedded_asset.thumbnail_key.clone(),
parent_path.clone(),
mesh_label,
embedded_asset.material_label.clone(),
embedded_asset.requires_skinned_hierarchy,
&mut studio,
);
}
AssetSubAssetKind::Material => {
let Some(material_label) = embedded_asset.material_label.clone() else {
continue;
};
cache.request_source_material(
embedded_asset.thumbnail_key.clone(),
parent_path.clone(),
material_label,
&mut studio,
);
}
AssetSubAssetKind::Texture => {
let Some(texture_path) = embedded_asset.texture_path.clone() else {
continue;
};
cache.request_texture(
embedded_asset.thumbnail_key.clone(),
texture_path,
&asset_server,
);
}
AssetSubAssetKind::Skeleton | AssetSubAssetKind::AnimationClip => {}
}
}
});
});
}
#[expect(
clippy::too_many_arguments,
reason = "embedded asset rendering keeps immediate-mode UI inputs explicit"
)]
pub(super) fn draw_embedded_asset_cell(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
selected: &Option<AssetSelection>,
embedded: &EmbeddedAsset,
cache_snapshot: &ThumbnailCacheSnapshot,
_parent_texture: Option<egui::TextureId>,
thumbnail_size: f32,
) {
let selected = selected.as_ref() == Some(&embedded.selection);
let texture_id = cache_snapshot
.texture_for_key(&embedded.thumbnail_key)
.or_else(|| {
embedded
.texture_path
.as_deref()
.and_then(|path| thumbnail_for_path(world, cache_snapshot, path))
});
let pending = cache_snapshot.is_pending_key(&embedded.thumbnail_key);
let failure = cache_snapshot.failure_reason_for_key(&embedded.thumbnail_key);
let failed = failure.is_some();
let thumb_size = thumbnail_size.clamp(44.0, 64.0);
let cell_size = egui::vec2(104.0, thumb_size + 50.0);
let (rect, response) = ui.allocate_exact_size(cell_size, egui::Sense::click_and_drag());
let response = if embedded.requires_skinned_hierarchy {
response.on_hover_text(
"Skinned primitives place through the dedicated renderer so their joint hierarchy remains intact.",
)
} else {
response
};
let response = if let Some(reason) = failure {
response.on_hover_text(reason)
} else {
response
};
let fill = if selected {
crate::ui::theme::SELECTION_BG_MUTED
} else if response.hovered() {
WIDGET_BG.linear_multiply(1.2)
} else {
WIDGET_BG
};
ui.painter().rect(
rect,
4.0,
fill,
egui::Stroke::new(1.0_f32, if selected { ACCENT } else { BORDER }),
egui::StrokeKind::Inside,
);
let thumb_rect = egui::Rect::from_min_size(
egui::pos2(rect.center().x - thumb_size * 0.5, rect.min.y + 8.0),
egui::vec2(thumb_size, thumb_size),
);
if let Some(texture_id) = texture_id {
ui.painter().image(
texture_id,
thumb_rect,
egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
egui::Color32::WHITE,
);
} else {
ui.painter().rect(
thumb_rect,
4.0,
ELEVATED_BG.linear_multiply(0.6),
egui::Stroke::new(1.0_f32, BORDER),
egui::StrokeKind::Inside,
);
let icon = if pending {
icons::CIRCLE_NOTCH
} else if failed {
icons::WARNING_CIRCLE
} else {
subasset_icon(embedded.kind)
};
ui.painter().text(
thumb_rect.center(),
egui::Align2::CENTER_CENTER,
icon.as_str(),
egui::FontId::new(24.0, egui::FontFamily::Name(PHOSPHOR.into())),
TEXT,
);
}
let label = compact_subasset_label(embedded);
let detail = compact_text(&embedded.detail, 18);
let label_pos = egui::pos2(rect.center().x, thumb_rect.max.y + 7.0);
ui.painter().text(
label_pos,
egui::Align2::CENTER_TOP,
label.as_str(),
egui::FontId::new(12.0, egui::FontFamily::Proportional),
if selected {
crate::ui::theme::TEXT_SELECTED
} else {
TEXT
},
);
ui.painter().text(
label_pos + egui::vec2(0.0, 17.0),
egui::Align2::CENTER_TOP,
format!("{} | {}", subasset_kind_label(embedded.kind), detail),
egui::FontId::new(10.0, egui::FontFamily::Proportional),
TEXT_DIM,
);
if response.clicked() {
world
.resource_mut::<EditorAssets>()
.select(embedded.selection.clone());
}
if response.secondary_clicked() {
prepare_context_menu_selection(world, embedded.selection.clone());
}
if response.drag_started() && embedded.kind != AssetSubAssetKind::Skeleton {
world
.resource_mut::<EditorAssets>()
.start_drag(embedded.selection.clone());
}
response.context_menu(|ui| {
subasset_context_menu(world, ui, embedded, selected_entities);
});
}
pub(super) fn compact_subasset_label(embedded: &EmbeddedAsset) -> String {
let base = match embedded.kind {
AssetSubAssetKind::Mesh => embedded
.label
.split_once(" / ")
.map(|(head, _)| head)
.unwrap_or(&embedded.label),
AssetSubAssetKind::Material
| AssetSubAssetKind::Texture
| AssetSubAssetKind::Skeleton
| AssetSubAssetKind::AnimationClip => embedded.label.as_str(),
};
compact_text(base, 16)
}
pub(super) fn compact_text(text: &str, max_chars: usize) -> String {
let mut chars = text.chars();
let mut compact = String::new();
for _ in 0..max_chars {
let Some(ch) = chars.next() else {
return text.to_string();
};
compact.push(ch);
}
if chars.next().is_some() {
compact.push_str("...");
}
compact
}
pub(super) fn thumbnail_for_path(
world: &World,
cache_snapshot: &ThumbnailCacheSnapshot,
path: &str,
) -> Option<egui::TextureId> {
let assets = world.resource::<EditorAssets>();
assets
.assets
.iter()
.find(|asset| asset.path.as_deref() == Some(path))
.and_then(|asset| cache_snapshot.texture_for(asset))
}
pub(super) fn toggle_asset_expanded(world: &mut World, path: &str) {
let mut state = world.resource_mut::<AssetBrowserUiState>();
if !state.expanded_assets.insert(path.to_string()) {
state.expanded_assets.remove(path);
}
}
pub(super) fn subasset_icon(kind: AssetSubAssetKind) -> Icon {
match kind {
AssetSubAssetKind::Mesh => icons::CUBE,
AssetSubAssetKind::Material => icons::PALETTE,
AssetSubAssetKind::Texture => icons::IMAGE,
AssetSubAssetKind::Skeleton => icons::BONE,
AssetSubAssetKind::AnimationClip => icons::FILM_STRIP,
}
}
pub(super) fn subasset_kind_label(kind: AssetSubAssetKind) -> &'static str {
match kind {
AssetSubAssetKind::Mesh => "Mesh",
AssetSubAssetKind::Material => "Material",
AssetSubAssetKind::Texture => "Texture",
AssetSubAssetKind::Skeleton => "Skeleton",
AssetSubAssetKind::AnimationClip => "Animation Clip",
}
}
@@ -0,0 +1,566 @@
use super::*;
pub(super) fn import_settings_editor(
world: &mut World,
ui: &mut egui::Ui,
_asset: &EditorAsset,
path: &str,
current: &ImportSettings,
) {
let material_slots = current
.static_mesh_manifest_path
.as_deref()
.and_then(|manifest_path| load_static_mesh_manifest(manifest_path).ok())
.map(|manifest| {
manifest
.parts
.into_iter()
.map(|part| {
let part_id = if part.id.trim().is_empty() {
part_id_from_label(&part.mesh_label)
} else {
part.id
};
(
shared::ComponentInstanceId::new(format!("slot:{part_id}")),
part.material_slot_name,
part.material_id.is_some() || part.material_label.is_some(),
)
})
.collect::<Vec<_>>()
})
.unwrap_or_default();
let project_materials = world
.resource::<AssetRegistry>()
.records
.iter()
.filter(|record| {
matches!(
record.kind,
AssetKind::Material | AssetKind::MaterialInstance
)
})
.map(|record| {
(
record.label.clone(),
MaterialRef::new(
EditorAssetRef::new(record.id.as_string(), "", record.label.clone())
.with_source_path(record.path.clone()),
),
)
})
.collect::<Vec<_>>();
if Path::new(path)
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
matches!(
extension.to_ascii_lowercase().as_str(),
"gltf" | "glb" | "fbx"
)
})
&& ui.button("Extract Editable Materials Here").clicked()
{
begin_gltf_material_extraction(world, path);
}
let animation_clip_options = current
.animation_manifest_path
.as_deref()
.and_then(|manifest_path| load_animation_manifest(manifest_path).ok())
.map(|manifest| {
manifest
.clips
.into_iter()
.map(|clip| (clip.id, clip.label))
.collect::<Vec<_>>()
})
.unwrap_or_default();
let registry_record = world
.resource::<AssetRegistry>()
.records
.iter()
.find(|record| record.path == path)
.cloned()
.expect("model details require a registry record");
let document_key =
crate::asset_documents::ensure_model_import_document(world, &registry_record);
let mut draft_settings = world
.resource::<crate::asset_documents::AuthoredAssetDocumentStore>()
.model_import(&document_key)
.cloned()
.unwrap_or_else(|| current.clone());
let original_settings = draft_settings.clone();
if let Some(snapshot) = world
.resource::<crate::asset_documents::AuthoredAssetDocumentStore>()
.snapshot(&document_key)
{
authored_document_status_ui(ui, &snapshot);
}
let mut locate_material_path = None;
ui.add(egui::Slider::new(&mut draft_settings.scale, 0.01..=10.0).text("Scale"));
ui.checkbox(&mut draft_settings.generate_collider, "Generate collider");
ui.checkbox(&mut draft_settings.lod0_only, "LOD0 only");
egui::ComboBox::from_id_salt("model_placement_mode")
.selected_text(match draft_settings.placement_mode {
ModelPlacementMode::StaticAsset => "Renderable Asset (Auto)",
ModelPlacementMode::SceneInstance => "Scene Instance",
})
.show_ui(ui, |ui| {
ui.selectable_value(
&mut draft_settings.placement_mode,
ModelPlacementMode::StaticAsset,
"Renderable Asset (Auto)",
);
ui.selectable_value(
&mut draft_settings.placement_mode,
ModelPlacementMode::SceneInstance,
"Scene Instance",
);
});
egui::ComboBox::from_id_salt("model_hierarchy_mode")
.selected_text(match draft_settings.hierarchy_mode {
ModelHierarchyMode::SingleActor => "One Actor",
ModelHierarchyMode::SourceHierarchy => "Source Hierarchy",
})
.show_ui(ui, |ui| {
ui.selectable_value(
&mut draft_settings.hierarchy_mode,
ModelHierarchyMode::SingleActor,
"One Actor",
);
ui.selectable_value(
&mut draft_settings.hierarchy_mode,
ModelHierarchyMode::SourceHierarchy,
"Source Hierarchy",
);
});
if !material_slots.is_empty() {
ui.separator();
ui.label(egui::RichText::new("Model Material Slots").strong());
ui.horizontal(|ui| {
if ui.small_button("All Source").clicked() {
draft_settings.material_slots = material_slots
.iter()
.map(|(slot_id, _, _)| ModelMaterialSlotSelection {
slot_id: slot_id.clone(),
selection: ModelMaterialSelection::Source,
})
.collect();
}
if ui.small_button("All Default").clicked() {
draft_settings.material_slots = material_slots
.iter()
.map(|(slot_id, _, _)| ModelMaterialSlotSelection {
slot_id: slot_id.clone(),
selection: ModelMaterialSelection::Default,
})
.collect();
}
});
for (slot_id, name, source_valid) in &material_slots {
let selection = draft_settings
.material_slots
.iter()
.find(|entry| entry.slot_id == *slot_id)
.map(|entry| entry.selection.clone())
.unwrap_or_default();
let selected_text = match &selection {
ModelMaterialSelection::Source if *source_valid => "Source".to_string(),
ModelMaterialSelection::Source => "Source (missing → DefaultGrid)".to_string(),
ModelMaterialSelection::Project(reference) => reference.0.label.clone(),
ModelMaterialSelection::Default => {
"Default (project fallback → DefaultGrid)".to_string()
}
};
ui.horizontal(|ui| {
ui.vertical(|ui| {
ui.label(name);
ui.small(format!("{} · source {}", slot_id.0, if *source_valid { "valid" } else { "missing" }));
});
egui::ComboBox::from_id_salt(("model_material_slot", &slot_id.0))
.selected_text(selected_text)
.show_ui(ui, |ui| {
let mut chosen = None;
if ui.selectable_label(matches!(selection, ModelMaterialSelection::Source), "Source").clicked() {
chosen = Some(ModelMaterialSelection::Source);
}
for (label, reference) in &project_materials {
let selected = matches!(&selection, ModelMaterialSelection::Project(current) if current == reference);
if ui.selectable_label(selected, label).clicked() {
chosen = Some(ModelMaterialSelection::Project(reference.clone()));
}
}
if ui.selectable_label(matches!(selection, ModelMaterialSelection::Default), "Default (project fallback → DefaultGrid)").clicked() {
chosen = Some(ModelMaterialSelection::Default);
}
if let Some(selection) = chosen {
if let Some(entry) = draft_settings.material_slots.iter_mut().find(|entry| entry.slot_id == *slot_id) {
entry.selection = selection;
} else {
draft_settings.material_slots.push(ModelMaterialSlotSelection { slot_id: slot_id.clone(), selection });
}
}
});
if let ModelMaterialSelection::Project(reference) = &selection {
let source_path = reference.0.source_path.clone();
if ui
.add_enabled(source_path.is_some(), egui::Button::new("Locate"))
.on_disabled_hover_text("The referenced project Material has no content path")
.clicked()
{
locate_material_path = source_path;
}
}
if !matches!(selection, ModelMaterialSelection::Source)
&& ui.small_button("Clear").clicked()
{
set_model_material_slot_selection(
&mut draft_settings,
slot_id,
ModelMaterialSelection::Source,
);
}
});
}
let mut orphan_to_clear = None;
for orphan in &draft_settings.orphaned_material_slots {
ui.horizontal(|ui| {
ui.colored_label(
WARNING,
format!(
"Orphaned {} → {}",
orphan.slot_id.0, orphan.material.0.label
),
);
let source_path = orphan.material.0.source_path.clone();
if ui
.add_enabled(source_path.is_some(), egui::Button::new("Locate"))
.on_disabled_hover_text("The referenced project Material has no content path")
.clicked()
{
locate_material_path = source_path;
}
if ui.small_button("Clear Orphan").clicked() {
orphan_to_clear = Some(orphan.slot_id.clone());
}
});
}
if let Some(slot_id) = orphan_to_clear {
clear_orphaned_model_material_selection(&mut draft_settings, &slot_id);
}
ui.small("Precedence: scene slot → model slot → imported source → project default → DefaultGrid.");
}
if !animation_clip_options.is_empty() {
let selected_default = draft_settings
.default_animation_clip_id
.as_deref()
.and_then(|id| {
animation_clip_options
.iter()
.find(|(clip_id, _)| clip_id == id)
.map(|(_, label)| label.as_str())
})
.unwrap_or_else(|| {
if draft_settings.default_animation_clip_id.is_some() {
"Missing clip"
} else {
"Imported rest pose"
}
});
egui::ComboBox::from_id_salt("model_default_animation_clip")
.selected_text(selected_default)
.show_ui(ui, |ui| {
ui.selectable_value(
&mut draft_settings.default_animation_clip_id,
None,
"Imported rest pose",
);
for (clip_id, label) in &animation_clip_options {
ui.selectable_value(
&mut draft_settings.default_animation_clip_id,
Some(clip_id.clone()),
label,
);
}
});
ui.small("Default animation is sampled and paused in edit mode; no clip is guessed.");
}
if draft_settings != original_settings {
world
.resource_mut::<crate::asset_documents::AuthoredAssetDocumentStore>()
.update_model_import(&document_key, draft_settings);
}
if let Some(path) = locate_material_path {
locate_content_asset(world, &path);
}
}
pub(super) fn set_model_material_slot_selection(
settings: &mut ImportSettings,
slot_id: &shared::ComponentInstanceId,
selection: ModelMaterialSelection,
) {
if let Some(entry) = settings
.material_slots
.iter_mut()
.find(|entry| entry.slot_id == *slot_id)
{
entry.selection = selection;
} else {
settings.material_slots.push(ModelMaterialSlotSelection {
slot_id: slot_id.clone(),
selection,
});
}
}
pub(super) fn clear_orphaned_model_material_selection(
settings: &mut ImportSettings,
slot_id: &shared::ComponentInstanceId,
) -> bool {
let previous_len = settings.orphaned_material_slots.len();
settings
.orphaned_material_slots
.retain(|orphan| orphan.slot_id != *slot_id);
settings.orphaned_material_slots.len() != previous_len
}
pub(super) fn texture_import_settings_editor(
world: &mut World,
ui: &mut egui::Ui,
path: &str,
record: &crate::asset_db::AssetRecord,
current: &TextureImportSettings,
) {
let document_key = crate::asset_documents::ensure_texture_import_document(world, record);
let mut draft_settings = world
.resource::<crate::asset_documents::AuthoredAssetDocumentStore>()
.texture_import(&document_key)
.cloned()
.unwrap_or_else(|| current.clone());
let original_settings = draft_settings.clone();
if let Some(snapshot) = world
.resource::<crate::asset_documents::AuthoredAssetDocumentStore>()
.snapshot(&document_key)
{
authored_document_status_ui(ui, &snapshot);
}
egui::Grid::new(("texture_import_settings", path))
.num_columns(2)
.spacing([12.0, 6.0])
.show(ui, |ui| {
ui.label("Semantic");
egui::ComboBox::from_id_salt(("texture_semantic", path))
.selected_text(texture_semantic_label(draft_settings.semantic))
.show_ui(ui, |ui| {
for (value, label) in [
(TextureAssetSemantic::Auto, "Auto"),
(TextureAssetSemantic::Color, "Color"),
(TextureAssetSemantic::Normal, "Normal"),
(TextureAssetSemantic::MaskData, "Mask / Data"),
(TextureAssetSemantic::Ui, "UI"),
(TextureAssetSemantic::Hdr, "HDR"),
] {
ui.selectable_value(&mut draft_settings.semantic, value, label);
}
});
ui.end_row();
ui.label("Color space");
egui::ComboBox::from_id_salt(("texture_color_space", path))
.selected_text(match draft_settings.color_space {
TextureColorSpace::Auto => "Auto",
TextureColorSpace::Srgb => "sRGB",
TextureColorSpace::Linear => "Linear",
})
.show_ui(ui, |ui| {
ui.selectable_value(
&mut draft_settings.color_space,
TextureColorSpace::Auto,
"Auto",
);
ui.selectable_value(
&mut draft_settings.color_space,
TextureColorSpace::Srgb,
"sRGB",
);
ui.selectable_value(
&mut draft_settings.color_space,
TextureColorSpace::Linear,
"Linear",
);
});
ui.end_row();
ui.label("Mipmaps");
egui::ComboBox::from_id_salt(("texture_mipmaps", path))
.selected_text(match draft_settings.mipmaps {
TextureMipmapMode::Generate => "Generate",
TextureMipmapMode::PreserveSource => "Preserve Source",
TextureMipmapMode::None => "None",
})
.show_ui(ui, |ui| {
ui.selectable_value(
&mut draft_settings.mipmaps,
TextureMipmapMode::Generate,
"Generate",
);
ui.selectable_value(
&mut draft_settings.mipmaps,
TextureMipmapMode::PreserveSource,
"Preserve Source",
);
ui.selectable_value(
&mut draft_settings.mipmaps,
TextureMipmapMode::None,
"None",
);
});
ui.end_row();
ui.label("Compression");
egui::ComboBox::from_id_salt(("texture_compression", path))
.selected_text(match draft_settings.compression {
TextureCompression::Auto => "Auto",
TextureCompression::Uastc => "Basis UASTC",
TextureCompression::Uncompressed => "Uncompressed KTX2",
})
.show_ui(ui, |ui| {
ui.selectable_value(
&mut draft_settings.compression,
TextureCompression::Auto,
"Auto",
);
ui.selectable_value(
&mut draft_settings.compression,
TextureCompression::Uastc,
"Basis UASTC",
);
ui.selectable_value(
&mut draft_settings.compression,
TextureCompression::Uncompressed,
"Uncompressed KTX2",
);
});
ui.end_row();
ui.label("Maximum size");
ui.horizontal(|ui| {
let mut enabled = draft_settings.max_dimension.is_some();
if ui.checkbox(&mut enabled, "").changed() {
draft_settings.max_dimension = enabled.then_some(2048);
}
if let Some(dimension) = draft_settings.max_dimension.as_mut() {
ui.add(egui::DragValue::new(dimension).range(1..=16_384));
} else {
ui.weak("No limit");
}
});
ui.end_row();
});
ui.collapsing("Sampling", |ui| {
egui::Grid::new(("texture_sampling", path))
.num_columns(2)
.spacing([12.0, 6.0])
.show(ui, |ui| {
ui.label("Filtering");
egui::ComboBox::from_id_salt(("texture_filter", path))
.selected_text(match draft_settings.filter {
TextureFilter::Nearest => "Nearest",
TextureFilter::Linear => "Linear",
})
.show_ui(ui, |ui| {
ui.selectable_value(
&mut draft_settings.filter,
TextureFilter::Nearest,
"Nearest",
);
ui.selectable_value(
&mut draft_settings.filter,
TextureFilter::Linear,
"Linear",
);
});
ui.end_row();
ui.label("Wrapping");
egui::ComboBox::from_id_salt(("texture_wrap", path))
.selected_text(match draft_settings.wrap {
TextureWrap::Repeat => "Repeat",
TextureWrap::Clamp => "Clamp",
TextureWrap::Mirror => "Mirror",
})
.show_ui(ui, |ui| {
ui.selectable_value(
&mut draft_settings.wrap,
TextureWrap::Repeat,
"Repeat",
);
ui.selectable_value(&mut draft_settings.wrap, TextureWrap::Clamp, "Clamp");
ui.selectable_value(
&mut draft_settings.wrap,
TextureWrap::Mirror,
"Mirror",
);
});
ui.end_row();
ui.label("Anisotropy");
ui.add(egui::Slider::new(&mut draft_settings.anisotropy, 1..=16));
ui.end_row();
});
});
if matches!(
draft_settings.semantic,
TextureAssetSemantic::Auto | TextureAssetSemantic::Normal
) {
ui.horizontal(|ui| {
ui.label("Normal convention");
ui.selectable_value(
&mut draft_settings.normal_map_convention,
NormalMapConvention::OpenGl,
"OpenGL (+Y)",
);
ui.selectable_value(
&mut draft_settings.normal_map_convention,
NormalMapConvention::DirectX,
"DirectX (-Y → +Y)",
);
});
}
let mut normalized = draft_settings.clone();
content_pipeline::normalize_texture_settings(path, &mut normalized);
ui.small(format!(
"Processed as {} · {} · {}",
texture_semantic_label(normalized.semantic),
if shared::resolves_srgb(&normalized) {
"sRGB"
} else {
"Linear"
},
match normalized.compression {
TextureCompression::Uastc => "Basis UASTC",
TextureCompression::Uncompressed => "KTX2",
TextureCompression::Auto => "Auto",
}
));
if draft_settings != original_settings {
world
.resource_mut::<crate::asset_documents::AuthoredAssetDocumentStore>()
.update_texture_import(&document_key, draft_settings);
}
}
pub(super) fn texture_semantic_label(semantic: TextureAssetSemantic) -> &'static str {
match semantic {
TextureAssetSemantic::Auto => "Auto",
TextureAssetSemantic::Color => "Color",
TextureAssetSemantic::Normal => "Normal",
TextureAssetSemantic::MaskData => "Mask / Data",
TextureAssetSemantic::Ui => "UI",
TextureAssetSemantic::Hdr => "HDR",
}
}
@@ -0,0 +1,406 @@
use super::*;
#[expect(
clippy::too_many_arguments,
reason = "asset list rendering shares explicit grid/list selection and thumbnail inputs"
)]
pub(super) fn asset_list(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
selected: &Option<AssetSelection>,
folders: &[FolderSnapshot],
assets: &[AssetRow],
cache_snapshot: &ThumbnailCacheSnapshot,
visible_order: &[AssetSelection],
) {
if ui.available_width() < COMPACT_LIST_WIDTH {
compact_asset_list(
world,
ui,
selected_entities,
selected,
folders,
assets,
cache_snapshot,
visible_order,
);
return;
}
ui.horizontal(|ui| {
ui.add_sized([236.0, 18.0], egui::Label::new("Name"));
ui.add_sized([80.0, 18.0], egui::Label::new("Type"));
ui.add_sized([72.0, 18.0], egui::Label::new("Size"));
ui.add_sized([88.0, 18.0], egui::Label::new("Modified"));
ui.label("Path");
});
for folder in folders {
let selection = AssetSelection::Folder(folder.path.clone());
let is_selected = world.resource::<EditorAssets>().is_selected(&selection);
let row_frame = egui::Frame::new()
.fill(if is_selected {
crate::ui::theme::SELECTION_BG_MUTED
} else {
WIDGET_BG.linear_multiply(0.9)
})
.inner_margin(egui::Margin::symmetric(6, 3))
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.add_sized([20.0, 20.0], egui::Label::new(""));
ui.label(icon_text(icons::FOLDER, 14.0).color(TEXT_DIM));
ui.add_sized(
[196.0, 20.0],
egui::Button::selectable(is_selected, folder.name.as_str()),
)
})
.inner
});
let response = row_frame.response.interact(egui::Sense::click_and_drag());
if response.double_clicked() {
navigate_content_folder(world, folder.path.clone());
} else if response.clicked() {
apply_content_click_selection(world, ui, selection.clone(), visible_order);
}
if response.drag_started() {
world
.resource_mut::<EditorAssets>()
.start_drag(selection.clone());
}
if response.secondary_clicked() {
prepare_context_menu_selection(world, selection);
}
response.context_menu(|ui| folder_context_menu(world, ui, folder));
}
for row in assets {
draw_asset_list_item(world, ui, selected_entities, selected, row, visible_order);
if row.asset.path.as_deref().is_some_and(|path| {
world
.resource::<AssetBrowserUiState>()
.expanded_assets
.contains(path)
}) {
embedded_asset_shelf(
world,
ui,
selected_entities,
selected,
&row.asset,
cache_snapshot,
56.0,
);
}
}
}
pub(super) fn draw_asset_list_item(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
_selected: &Option<AssetSelection>,
row: &AssetRow,
visible_order: &[AssetSelection],
) {
let has_children = has_embedded_assets(world, &row.asset);
let expanded = row.asset.path.as_deref().is_some_and(|path| {
world
.resource::<AssetBrowserUiState>()
.expanded_assets
.contains(path)
});
let is_selected = world.resource::<EditorAssets>().is_selected(&row.selection);
let document_status = asset_document_status(world, row.asset.path.as_deref());
let status = AssetCardStatus::for_document(
document_status.as_ref(),
document_status
.as_ref()
.is_some_and(|snapshot| snapshot.dirty),
false,
);
let row_frame = egui::Frame::new()
.fill(if is_selected {
crate::ui::theme::SELECTION_BG_MUTED
} else {
WIDGET_BG.linear_multiply(0.9)
})
.stroke(egui::Stroke::new(
1.0_f32,
if is_selected { ACCENT } else { BORDER },
))
.inner_margin(egui::Margin::symmetric(6, 3))
.show(ui, |ui| {
ui.horizontal(|ui| {
if has_children {
let icon = if expanded {
icons::CARET_DOWN
} else {
icons::CARET_RIGHT
};
if ui
.add_sized(
[20.0, 20.0],
egui::Button::new(icon_text(icon, 12.0)).frame(false),
)
.clicked()
{
if let Some(path) = row.asset.path.as_ref() {
toggle_asset_expanded(world, path);
}
}
} else {
ui.add_sized([20.0, 20.0], egui::Label::new(""));
}
ui.label(icon_text(kind_icon(&row.asset.kind), 14.0).color(TEXT_DIM));
let response = ui.add_sized(
[176.0, 20.0],
egui::Button::selectable(is_selected, row.asset.label.as_str()),
);
draw_asset_status_marker(ui, status);
ui.add_sized([80.0, 20.0], egui::Label::new(kind_label(&row.asset.kind)));
ui.add_sized(
[72.0, 20.0],
egui::Label::new(
row.file_size
.map(format_bytes)
.unwrap_or_else(|| "-".to_string()),
),
);
ui.add_sized(
[88.0, 20.0],
egui::Label::new(
row.modified
.map(format_modified)
.unwrap_or_else(|| "-".to_string()),
),
);
ui.add(
egui::Label::new(row.asset.path.as_deref().unwrap_or("Built-in")).truncate(),
);
ui.menu_button(icon_text(icons::DOTS_THREE_VERTICAL, 13.0), |ui| {
asset_context_menu(world, ui, &row.asset, selected_entities);
});
response
})
.inner
});
let response = row_frame.response.interact(egui::Sense::click_and_drag());
if response.double_clicked() {
activate_content_asset(world, &row.asset);
} else if response.clicked() {
apply_content_click_selection(world, ui, row.selection.clone(), visible_order);
}
if response.drag_started() {
world
.resource_mut::<EditorAssets>()
.start_drag(row.selection.clone());
}
if response.secondary_clicked() {
prepare_context_menu_selection(world, row.selection.clone());
}
response.context_menu(|ui| {
asset_context_menu(world, ui, &row.asset, selected_entities);
});
}
pub(super) fn asset_document_status(
world: &World,
path: Option<&str>,
) -> Option<crate::asset_documents::AuthoredDocumentSnapshot> {
path.and_then(|path| {
world
.get_resource::<crate::asset_documents::AuthoredAssetDocumentStore>()
.and_then(|store| store.snapshot_for_path(path))
})
}
#[expect(
clippy::too_many_arguments,
reason = "compact list rendering shares explicit grid/list selection and thumbnail inputs"
)]
pub(super) fn compact_asset_list(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
selected: &Option<AssetSelection>,
folders: &[FolderSnapshot],
assets: &[AssetRow],
cache_snapshot: &ThumbnailCacheSnapshot,
visible_order: &[AssetSelection],
) {
for folder in folders {
let selection = AssetSelection::Folder(folder.path.clone());
let is_selected = world.resource::<EditorAssets>().is_selected(&selection);
let response = ui
.horizontal(|ui| {
ui.label(icon_text(icons::FOLDER, 14.0).color(TEXT_DIM));
ui.add_sized(
[fit_width(ui, 120.0, f32::INFINITY), 22.0],
egui::Button::selectable(is_selected, folder.name.as_str()),
)
})
.inner;
if response.double_clicked() {
navigate_content_folder(world, folder.path.clone());
} else if response.clicked() {
apply_content_click_selection(world, ui, selection.clone(), visible_order);
}
if response.drag_started() {
world
.resource_mut::<EditorAssets>()
.start_drag(selection.clone());
}
if response.secondary_clicked() {
prepare_context_menu_selection(world, selection);
}
response.context_menu(|ui| folder_context_menu(world, ui, folder));
ui.small(egui::RichText::new("Folder").color(TEXT_DIM));
ui.add_space(4.0);
}
for row in assets {
let is_selected = world.resource::<EditorAssets>().is_selected(&row.selection);
let document_status = asset_document_status(world, row.asset.path.as_deref());
let status = AssetCardStatus::for_document(
document_status.as_ref(),
document_status
.as_ref()
.is_some_and(|snapshot| snapshot.dirty),
false,
);
let has_children = has_embedded_assets(world, &row.asset);
let expanded = row.asset.path.as_deref().is_some_and(|path| {
world
.resource::<AssetBrowserUiState>()
.expanded_assets
.contains(path)
});
let mut response = None;
ui.horizontal(|ui| {
if has_children {
let icon = if expanded {
icons::CARET_DOWN
} else {
icons::CARET_RIGHT
};
if ui
.add_sized(
[20.0, 20.0],
egui::Button::new(icon_text(icon, 12.0)).frame(false),
)
.clicked()
{
if let Some(path) = row.asset.path.as_ref() {
toggle_asset_expanded(world, path);
}
}
}
ui.label(icon_text(kind_icon(&row.asset.kind), 14.0).color(TEXT_DIM));
draw_asset_status_marker(ui, status);
response = Some(ui.add_sized(
[fit_width(ui, 120.0, f32::INFINITY), 22.0],
egui::Button::selectable(is_selected, row.asset.label.as_str()),
));
ui.menu_button(icon_text(icons::DOTS_THREE_VERTICAL, 13.0), |ui| {
asset_context_menu(world, ui, &row.asset, selected_entities);
});
});
let response = response.expect("compact asset list response");
let size = row
.file_size
.map(format_bytes)
.unwrap_or_else(|| "-".to_string());
let modified = row
.modified
.map(format_modified)
.unwrap_or_else(|| "-".to_string());
let path = row.asset.path.as_deref().unwrap_or("Built-in");
ui.add(
egui::Label::new(
egui::RichText::new(format!(
"{} | {} | {} | {}",
kind_label(&row.asset.kind),
size,
modified,
path
))
.color(TEXT_DIM),
)
.truncate(),
);
ui.add_space(4.0);
if response.double_clicked() {
activate_content_asset(world, &row.asset);
} else if response.clicked() {
apply_content_click_selection(world, ui, row.selection.clone(), visible_order);
}
if response.drag_started() {
world
.resource_mut::<EditorAssets>()
.start_drag(row.selection.clone());
}
if response.secondary_clicked() {
prepare_context_menu_selection(world, row.selection.clone());
}
response.context_menu(|ui| {
asset_context_menu(world, ui, &row.asset, selected_entities);
});
if expanded {
embedded_asset_shelf(
world,
ui,
selected_entities,
selected,
&row.asset,
cache_snapshot,
56.0,
);
}
}
}
pub(super) fn draw_folder_cell(
ui: &mut egui::Ui,
folder: &FolderSnapshot,
thumbnail_size: f32,
is_selected: bool,
) -> egui::Response {
let thumb_size = thumbnail_size.clamp(48.0, 112.0);
let cell_size = egui::vec2(thumb_size + 20.0, thumb_size + 30.0);
let (rect, response) = ui.allocate_exact_size(cell_size, egui::Sense::click_and_drag());
let fill = if is_selected {
crate::ui::theme::SELECTION_BG_MUTED
} else if response.hovered() {
ELEVATED_BG
} else {
WIDGET_BG
};
ui.painter().rect(
rect,
4.0,
fill,
egui::Stroke::new(1.0_f32, if is_selected { ACCENT } else { BORDER }),
egui::StrokeKind::Inside,
);
ui.painter().text(
rect.center_top() + egui::vec2(0.0, 10.0 + thumb_size * 0.45),
egui::Align2::CENTER_CENTER,
icons::FOLDER_SIMPLE.as_str(),
egui::FontId::new(
(thumb_size * 0.48).max(24.0),
egui::FontFamily::Name("phosphor-regular".into()),
),
TEXT,
);
ui.painter().text(
egui::pos2(rect.center().x, rect.max.y - 6.0),
egui::Align2::CENTER_BOTTOM,
folder.name.as_str(),
egui::FontId::new(11.0, egui::FontFamily::Proportional),
TEXT,
);
response
}
@@ -0,0 +1,640 @@
use super::*;
pub(crate) fn begin_gltf_material_extraction(world: &mut World, source: &str) {
begin_model_material_extraction(world, source, None);
}
pub(crate) fn begin_actor_material_extraction(
world: &mut World,
source: &str,
entity: Entity,
slot_id: shared::ComponentInstanceId,
source_sub_asset_id: String,
) {
begin_model_material_extraction(
world,
source,
Some(GltfMaterialExtractionTarget {
entity,
slot_id,
source_sub_asset_id,
}),
);
}
pub(super) fn begin_model_material_extraction(
world: &mut World,
source: &str,
actor_target: Option<GltfMaterialExtractionTarget>,
) {
let destination = world.resource::<EditorAssets>().current_folder.clone();
match crate::assets::plan_model_material_extraction(Path::new(source), Path::new(&destination))
{
Ok(materials) if materials.is_empty() => {
world.resource_mut::<SceneIo>().status =
format!("No convertible source materials were found in {source}");
}
Ok(materials) => {
let materials = materials
.into_iter()
.map(|material| {
let included = actor_target.as_ref().is_none_or(|target| {
material
.asset
.provenance
.as_ref()
.is_some_and(|provenance| {
provenance.source_sub_asset_id == target.source_sub_asset_id
})
});
let path = material
.asset
.provenance
.as_ref()
.and_then(|provenance| {
crate::assets::find_matching_extracted_material(
Path::new(&destination),
Path::new(source),
&provenance.source_sub_asset_id,
)
})
.unwrap_or(material.path);
GltfMaterialExtractionEntry {
included,
source_index: material.source_index,
source_name: material.source_name,
write_mode: if path.exists() {
MaterialExtractionWriteMode::Undecided
} else {
MaterialExtractionWriteMode::CreateNew
},
path: path.to_string_lossy().replace('\\', "/"),
asset: material.asset,
}
})
.collect::<Vec<_>>();
if actor_target.is_some() && !materials.iter().any(|material| material.included) {
world.resource_mut::<SceneIo>().status =
"The selected imported material could not be matched for extraction".into();
return;
}
world
.resource_mut::<AssetBrowserUiState>()
.pending_gltf_extraction = Some(GltfMaterialExtractionDraft {
source: source.to_string(),
destination,
materials,
actor_target,
});
}
Err(error) => {
world.resource_mut::<SceneIo>().status =
format!("Material extraction review failed: {error}");
}
}
}
pub(super) fn draw_gltf_material_extraction_modal(world: &mut World, ctx: &egui::Context) {
let Some(mut draft) = world
.resource::<AssetBrowserUiState>()
.pending_gltf_extraction
.clone()
else {
return;
};
let mut cancel = false;
let mut extract = false;
let validation_error = gltf_extraction_validation_error(&draft);
let included = draft
.materials
.iter()
.filter(|material| material.included)
.count();
egui::Window::new("Extract Editable Model Materials")
.collapsible(false)
.resizable(true)
.default_width(880.0)
.min_width(680.0)
.show(ctx, |ui| {
ui.label(format!("Source: {}", draft.source));
ui.label(format!("Destination: {}", draft.destination));
ui.small(
egui::RichText::new(
"Review converted PBR values, texture references, final project paths, and any provenance-matched diff. Existing files require an explicit guarded Apply or Create New decision.",
)
.color(TEXT_DIM),
);
ui.separator();
egui::ScrollArea::vertical()
.max_height(420.0)
.show(ui, |ui| {
for material in &mut draft.materials {
ui.push_id(material.source_index, |ui| {
egui::Frame::group(ui.style()).show(ui, |ui| {
ui.horizontal(|ui| {
ui.checkbox(&mut material.included, "");
ui.strong(format!(
"{} · source material {}",
material.source_name, material.source_index
));
});
ui.horizontal(|ui| {
ui.label("Project path");
let changed = ui
.add(
egui::TextEdit::singleline(&mut material.path)
.desired_width(f32::INFINITY),
)
.changed();
if changed {
material.write_mode = if Path::new(material.path.trim()).exists() {
MaterialExtractionWriteMode::Undecided
} else {
MaterialExtractionWriteMode::CreateNew
};
}
});
let resolved = material_asset_desc(&material.asset);
ui.small(format!(
"Metallic {:.3} · Roughness {:.3} · {}",
resolved.metallic,
resolved.roughness,
gltf_material_texture_summary(&material.asset)
));
ui.small(format!(
"Alpha {:?} · Double sided {} · provenance {}",
material.asset.render_state.alpha_mode,
material.asset.render_state.double_sided,
material
.asset
.provenance
.as_ref()
.map(|provenance| provenance.source_sub_asset_id.as_str())
.unwrap_or("missing")
));
match review_existing_extraction_target(material) {
Ok(Some(review)) if review.provenance_matches => {
ui.separator();
ui.strong("Existing extracted Material found");
if review.changes.is_empty() {
ui.small("Diff: converted values are unchanged; applying refreshes source provenance.");
} else {
ui.small(format!("Diff: {}", review.changes.join(" · ")));
}
ui.horizontal(|ui| {
let selected = matches!(
&material.write_mode,
MaterialExtractionWriteMode::ApplyExisting {
expected_fingerprint,
..
} if expected_fingerprint == &review.fingerprint
);
if ui
.selectable_label(selected, "Apply Reviewed Update")
.on_hover_text(
"Replace this Material transactionally only if its reviewed bytes have not changed.",
)
.clicked()
{
material.write_mode =
MaterialExtractionWriteMode::ApplyExisting {
expected_fingerprint: review.fingerprint,
previous_bytes: review.bytes,
};
}
if ui.button("Create New Copy").clicked() {
material.path = unique_extraction_copy_path(
Path::new(material.path.trim()),
)
.to_string_lossy()
.replace('\\', "/");
material.write_mode =
MaterialExtractionWriteMode::CreateNew;
}
});
}
Ok(Some(_)) => {
ui.small(
egui::RichText::new(
"Existing Material provenance does not match this source slot; Apply is blocked.",
)
.color(WARNING),
);
if ui.button("Create New Copy").clicked() {
material.path = unique_extraction_copy_path(
Path::new(material.path.trim()),
)
.to_string_lossy()
.replace('\\', "/");
material.write_mode =
MaterialExtractionWriteMode::CreateNew;
}
}
Ok(None) => {
material.write_mode = MaterialExtractionWriteMode::CreateNew;
ui.small("Create new editable project Material");
}
Err(error) => {
ui.small(egui::RichText::new(error).color(WARNING));
}
}
});
ui.add_space(4.0);
});
}
});
ui.separator();
ui.horizontal(|ui| {
if ui.button("Cancel").clicked() {
cancel = true;
}
if ui
.add_enabled(
validation_error.is_none(),
egui::Button::new(format!("Extract {included} Material(s)")),
)
.clicked()
{
extract = true;
}
});
if let Some(error) = validation_error.as_deref() {
ui.small(egui::RichText::new(error).color(WARNING));
}
});
if cancel {
world
.resource_mut::<AssetBrowserUiState>()
.pending_gltf_extraction = None;
} else if extract {
match commit_gltf_material_extraction(world, &draft) {
Ok((count, mapped_slots, warning)) => {
world
.resource_mut::<AssetBrowserUiState>()
.pending_gltf_extraction = None;
let scope = if draft.actor_target.is_some() {
"actor slot"
} else {
"model slot"
};
let mut status = format!(
"Extracted {count} editable model material(s) into {} and assigned {mapped_slots} {scope}(s)",
draft.destination
);
if let Some(warning) = warning {
status.push_str(&format!("; {warning}"));
}
world.resource_mut::<SceneIo>().status = status;
}
Err(error) => {
world.resource_mut::<SceneIo>().status = error;
world
.resource_mut::<AssetBrowserUiState>()
.pending_gltf_extraction = Some(draft);
}
}
} else {
world
.resource_mut::<AssetBrowserUiState>()
.pending_gltf_extraction = Some(draft);
}
}
pub(super) fn gltf_extraction_validation_error(
draft: &GltfMaterialExtractionDraft,
) -> Option<String> {
let selected = draft
.materials
.iter()
.filter(|material| material.included)
.collect::<Vec<_>>();
if selected.is_empty() {
return Some("Select at least one source material to extract.".into());
}
let mut paths = HashSet::new();
for material in selected {
let path = Path::new(material.path.trim());
if let Err(error) = content_pipeline::validate_asset_path(path) {
return Some(format!("Invalid project path {}: {error}", path.display()));
}
if path.extension().and_then(|extension| extension.to_str()) != Some("ron") {
return Some(format!(
"Material path must end in .ron: {}",
path.display()
));
}
let normalized = material.path.trim().replace('\\', "/");
if !paths.insert(normalized) {
return Some("Two selected materials have the same project path.".into());
}
match &material.write_mode {
MaterialExtractionWriteMode::Undecided => {
return Some(format!(
"Review the existing Material diff and choose Apply or Create New: {}",
path.display()
));
}
MaterialExtractionWriteMode::CreateNew if path.exists() => {
return Some(format!("Project path already exists: {}", path.display()));
}
MaterialExtractionWriteMode::ApplyExisting {
expected_fingerprint,
previous_bytes,
} => match review_existing_extraction_target(material) {
Ok(Some(review))
if review.provenance_matches
&& review.fingerprint == *expected_fingerprint
&& review.bytes == *previous_bytes => {}
Ok(Some(_)) => {
return Some(format!(
"Existing Material changed or has different provenance: {}",
path.display()
));
}
Ok(None) => {
return Some(format!("Apply target no longer exists: {}", path.display()));
}
Err(error) => return Some(error),
},
MaterialExtractionWriteMode::CreateNew => {}
}
}
None
}
pub(super) struct ExistingExtractionReview {
pub(super) fingerprint: String,
pub(super) bytes: Vec<u8>,
pub(super) provenance_matches: bool,
pub(super) changes: Vec<&'static str>,
}
pub(super) fn review_existing_extraction_target(
material: &GltfMaterialExtractionEntry,
) -> Result<Option<ExistingExtractionReview>, String> {
let path = Path::new(material.path.trim());
if !path.exists() {
return Ok(None);
}
let bytes = fs::read(path).map_err(|error| {
format!(
"Could not read existing Material {}: {error}",
path.display()
)
})?;
let existing: MaterialAsset = ron::de::from_bytes(&bytes)
.map_err(|error| format!("Existing target is not a valid Material: {error}"))?;
let fingerprint = content_pipeline::tree_fingerprint(path)?;
let provenance_matches = existing
.provenance
.as_ref()
.zip(material.asset.provenance.as_ref())
.is_some_and(|(existing, incoming)| {
existing.source_path == incoming.source_path
&& existing.source_sub_asset_id == incoming.source_sub_asset_id
});
let mut changes = Vec::new();
if existing.label != material.asset.label {
changes.push("label");
}
if existing.shader != material.asset.shader || existing.shader_ref != material.asset.shader_ref
{
changes.push("shader selection");
}
if existing.render_state != material.asset.render_state {
changes.push("render state");
}
if existing.inputs != material.asset.inputs {
changes.push("PBR values or textures");
}
if existing
.provenance
.as_ref()
.map(|value| &value.source_fingerprint)
!= material
.asset
.provenance
.as_ref()
.map(|value| &value.source_fingerprint)
{
changes.push("source revision");
}
Ok(Some(ExistingExtractionReview {
fingerprint,
bytes,
provenance_matches,
changes,
}))
}
pub(super) fn unique_extraction_copy_path(path: &Path) -> PathBuf {
let parent = path.parent().unwrap_or_else(|| Path::new("assets"));
let file_name = path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("material.material.ron");
let stem = file_name
.strip_suffix(".material.ron")
.or_else(|| file_name.strip_suffix(".ron"))
.unwrap_or(file_name);
(2..)
.map(|suffix| parent.join(format!("{stem}_{suffix}.material.ron")))
.find(|candidate| !candidate.exists())
.expect("numeric material suffix space is effectively unbounded")
}
pub(super) fn gltf_material_texture_summary(asset: &MaterialAsset) -> String {
let mut textures = Vec::new();
if asset
.inputs
.texture("base_color")
.is_some_and(|value| value.texture.is_some())
{
textures.push("base color");
}
if asset
.inputs
.texture("normal")
.is_some_and(|value| value.texture.is_some())
{
textures.push("normal");
}
if asset
.inputs
.texture("roughness")
.is_some_and(|value| value.texture.is_some())
|| asset
.inputs
.texture("metallic")
.is_some_and(|value| value.texture.is_some())
{
textures.push("metal/rough");
}
if asset
.inputs
.texture("emissive")
.is_some_and(|value| value.texture.is_some())
{
textures.push("emissive");
}
if textures.is_empty() {
"no converted textures".into()
} else {
format!("textures: {}", textures.join(", "))
}
}
pub(super) fn material_asset_desc(asset: &MaterialAsset) -> MaterialDesc {
let mut material = MaterialDesc {
shader: asset.shader.clone(),
..Default::default()
};
asset.inputs.apply_to_material_desc(&mut material);
material
}
pub(super) fn commit_gltf_material_extraction(
world: &mut World,
draft: &GltfMaterialExtractionDraft,
) -> Result<(usize, usize, Option<String>), String> {
if let Some(error) = gltf_extraction_validation_error(draft) {
return Err(error);
}
let included = draft
.materials
.iter()
.filter(|material| material.included)
.cloned()
.collect::<Vec<_>>();
let operations = included
.iter()
.map(|material| {
ron::ser::to_string_pretty(&material.asset, ron::ser::PrettyConfig::default())
.map(|ron| {
let path = PathBuf::from(material.path.trim());
let bytes = format!("{ron}\n").into_bytes();
match &material.write_mode {
MaterialExtractionWriteMode::CreateNew => {
content_pipeline::ContentOperation::WriteFile { path, bytes }
}
MaterialExtractionWriteMode::ApplyExisting {
expected_fingerprint,
previous_bytes,
} => content_pipeline::ContentOperation::ReplaceFile {
path,
bytes,
expected_fingerprint: expected_fingerprint.clone(),
previous_bytes: previous_bytes.clone(),
},
MaterialExtractionWriteMode::Undecided => {
unreachable!("extraction validation rejects undecided existing targets")
}
}
})
.map_err(|error| format!("Material extraction serialization failed: {error}"))
})
.collect::<Result<Vec<_>, _>>()?;
let count = operations.len();
let manifest = world
.resource::<AssetRegistry>()
.records
.iter()
.find(|record| record.path == draft.source)
.ok_or_else(|| format!("Model is not registered: {}", draft.source))?
.model_import()
.static_mesh_manifest_path
.as_deref()
.ok_or_else(|| format!("Model has no generated mesh manifest: {}", draft.source))
.and_then(load_static_mesh_manifest)?;
let bindings = included
.iter()
.map(|material| ExtractedMaterialBinding {
source_index: material.source_index,
path: material.path.trim().replace('\\', "/"),
})
.collect::<Vec<_>>();
if let Some(target) = draft.actor_target.as_ref() {
validate_actor_material_extraction_target(world, target)?;
}
let mapped_slots = std::cell::Cell::new(0);
let committed = commit_content_operations_internal_with_registry_update(
world,
operations,
true,
|document| {
if draft.actor_target.is_none() {
mapped_slots.set(bind_extracted_material_slots(
document,
&draft.source,
&manifest,
&bindings,
)?);
}
Ok(())
},
);
if !committed {
return Err(world.resource::<SceneIo>().status.clone());
}
if let Some(target) = draft.actor_target.as_ref() {
let binding = included
.iter()
.find(|material| {
material
.asset
.provenance
.as_ref()
.is_some_and(|provenance| {
provenance.source_sub_asset_id == target.source_sub_asset_id
})
})
.ok_or_else(|| "Selected source material was not included in extraction".to_string())?;
let path = binding.path.trim().replace('\\', "/");
let record = world
.resource::<AssetRegistry>()
.records
.iter()
.find(|record| record.path == path)
.ok_or_else(|| format!("Extracted Material was not registered: {path}"))?;
let reference = MaterialRef::new(
EditorAssetRef::new(
record.id.as_string(),
"material:source",
record.label.clone(),
)
.with_source_path(path),
);
assign_extracted_material_to_actor_slot(world, target, reference)?;
mapped_slots.set(1);
}
let warning = if draft.actor_target.is_none() {
refresh_extracted_model_artifacts(world, &draft.source).err()
} else {
None
};
Ok((count, mapped_slots.get(), warning))
}
pub(super) fn validate_actor_material_extraction_target(
world: &World,
target: &GltfMaterialExtractionTarget,
) -> Result<(), String> {
let exists = world
.get::<shared::Primitive>(target.entity)
.is_some_and(|primitive| primitive.surface.id == target.slot_id)
|| world
.get::<shared::StaticMeshRenderer>(target.entity)
.is_some_and(|renderer| renderer.materials.slot(&target.slot_id).is_some())
|| world
.get::<shared::SkinnedMeshRenderer>(target.entity)
.is_some_and(|renderer| renderer.materials.slot(&target.slot_id).is_some());
if exists {
Ok(())
} else {
Err("The actor or exact material slot changed while extraction was open".into())
}
}
@@ -0,0 +1,506 @@
use super::*;
pub(super) fn content_header(
world: &mut World,
ui: &mut egui::Ui,
current_folder: &str,
folders: &[FolderSnapshot],
assets: &[AssetRow],
) {
ui.horizontal_wrapped(|ui| {
ui.label(panel_heading("Assets"));
ui.separator();
breadcrumb(world, ui, current_folder);
});
let direct_assets = assets
.iter()
.filter(|row| row.asset.folder_path == current_folder)
.count();
let direct_folders = folders
.iter()
.filter(|folder| folder.parent.as_deref() == Some(current_folder))
.count();
ui.small(
egui::RichText::new(format!("{direct_folders} folders, {direct_assets} assets"))
.color(TEXT_DIM),
);
}
pub(super) fn prefetch_asset_row_thumbnails(world: &mut World, rows: &[AssetRow]) {
let requests: Vec<(String, String, EditorAssetKind)> = rows
.iter()
.filter(|row| {
matches!(
row.asset.kind,
EditorAssetKind::Texture | EditorAssetKind::Model | EditorAssetKind::Material
)
})
.filter_map(|row| {
Some((
asset_cache_key(&row.asset),
row.asset.path.clone()?,
row.asset.kind.clone(),
))
})
.collect();
if requests.is_empty() {
return;
}
let asset_server = world.resource::<AssetServer>().clone();
world.resource_scope(|world, mut cache: Mut<AssetThumbnailCache>| {
world.resource_scope(|_world, mut studio: Mut<ThumbnailStudio>| {
for (key, path, kind) in &requests {
match kind {
EditorAssetKind::Texture => {
cache.request_texture(key.clone(), path.clone(), &asset_server);
}
EditorAssetKind::Model => {
cache.request_model(key.clone(), path.clone(), &mut studio);
}
EditorAssetKind::Material => {
cache.request_material_asset(key.clone(), path.clone(), &mut studio);
}
_ => {}
}
}
});
});
}
pub(super) fn breadcrumb(world: &mut World, ui: &mut egui::Ui, current_folder: &str) {
let mut parts = Vec::new();
let mut cursor = Some(current_folder.to_string());
while let Some(path) = cursor {
let label = if path == BUILTINS_FOLDER {
"Built-ins".to_string()
} else {
Path::new(&path)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or(&path)
.to_string()
};
cursor = path.rfind('/').map(|index| path[..index].to_string());
parts.push((path, label));
}
parts.reverse();
for (index, (path, label)) in parts.iter().enumerate() {
if index > 0 {
ui.label(egui::RichText::new("/").color(TEXT_DIM));
}
if ui.link(label).clicked() {
navigate_content_folder(world, path.clone());
}
}
}
pub(super) fn selection_footer(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
) {
let selection = world.resource::<EditorAssets>().selected.clone();
let selection_count = world.resource::<EditorAssets>().selections.len();
if selection_count > 1 {
let has_authored_content = !selected_content_paths(world).is_empty();
ui.label(format!("{selection_count} items selected"));
ui.horizontal_wrapped(|ui| {
if ui
.add_enabled(has_authored_content, egui::Button::new("Cut"))
.clicked()
{
set_content_clipboard(world, true);
}
if ui
.add_enabled(has_authored_content, egui::Button::new("Copy"))
.clicked()
{
set_content_clipboard(world, false);
}
if ui
.add_enabled(has_authored_content, egui::Button::new("Duplicate"))
.clicked()
{
duplicate_selection(world);
}
if ui
.add_enabled(has_authored_content, egui::Button::new("Move To Trash"))
.clicked()
{
request_delete_for_selection(world);
}
});
return;
}
let selected_embedded = selection
.as_ref()
.and_then(|selection| embedded_asset_for_selection(world, selection));
if let Some(AssetSelection::Folder(path)) = selection.clone() {
ui.add(egui::Label::new(format!("Selected folder: {path}")).truncate());
ui.horizontal_wrapped(|ui| {
if ui.button("Open").clicked() {
navigate_content_folder(world, path.clone());
}
if ui.button("Import Here").clicked() {
request_import_to_destination(world, path.clone());
}
if ui.button("Import To...").clicked() {
begin_import_to(world);
}
});
} else if let Some(AssetSelection::SubAsset { label, kind, .. }) = selection.clone() {
ui.add(
egui::Label::new(format!(
"Selected: {}: {}",
subasset_kind_label(kind),
label
))
.truncate(),
);
ui.horizontal_wrapped(|ui| match kind {
AssetSubAssetKind::Mesh => {
if selected_embedded
.as_ref()
.is_some_and(|embedded| embedded.requires_skinned_hierarchy)
{
if ui.button("Place Skinned Model").clicked() {
if let Some(selection) = selection.as_ref() {
place_subasset_operator(world, selection.clone(), Vec3::ZERO);
}
}
} else if ui.button("Place At Origin").clicked() {
if let Some(selection) = selection.as_ref() {
place_subasset_operator(world, selection.clone(), Vec3::ZERO);
}
}
}
AssetSubAssetKind::Texture => {
if ui.button("Apply Texture To Selection").clicked() {
if let Some(asset) = texture_asset_from_subasset_selection(world, &selection) {
apply_texture_operator(world, asset, selected_entities);
}
}
}
AssetSubAssetKind::Material => {
ui.small(egui::RichText::new("Embedded source material").color(TEXT_DIM));
}
AssetSubAssetKind::Skeleton => {
ui.small(egui::RichText::new("Inspect-only rig metadata").color(TEXT_DIM));
}
AssetSubAssetKind::AnimationClip => {
let animated_actor = selected_entities
.as_slice()
.iter()
.copied()
.find(|entity| world.get::<shared::SkinnedMeshRenderer>(*entity).is_some());
let action = if animated_actor.is_some() {
"Assign To Selected Actor"
} else {
"Create Animated Actor"
};
if ui.button(action).clicked() {
if let Some(selection) = selection.as_ref() {
if let Some(entity) = animated_actor {
assign_animation_clip_operator(world, selection.clone(), entity);
} else {
place_subasset_operator(world, selection.clone(), Vec3::ZERO);
}
}
}
}
});
} else if let Some(asset) = world.resource::<EditorAssets>().selected_asset().cloned() {
ui.add(egui::Label::new(format!("Selected: {}", asset_label(&asset))).truncate());
ui.horizontal_wrapped(|ui| {
if matches!(asset.kind, EditorAssetKind::Texture)
&& ui.button("Apply Texture To Selection").clicked()
{
apply_texture_operator(world, asset.clone(), selected_entities);
}
if matches!(
asset.kind,
EditorAssetKind::Primitive(_)
| EditorAssetKind::Light(_)
| EditorAssetKind::Model
| EditorAssetKind::AudioClip
| EditorAssetKind::Prefab
) && ui.button("Place At Origin").clicked()
{
place_asset_operator(world, asset.clone(), Vec3::ZERO);
}
if matches!(asset.kind, EditorAssetKind::Level) && ui.button("Open Scene").clicked() {
open_level_asset(world, &asset);
}
});
} else {
ui.label(egui::RichText::new("No asset selected").color(TEXT_DIM));
}
}
pub(super) fn folder_tree_branch(
world: &mut World,
ui: &mut egui::Ui,
folders: &[FolderSnapshot],
node_path: &str,
depth: usize,
current_folder: &str,
) {
let Some(folder) = folders.iter().find(|folder| folder.path == node_path) else {
return;
};
let path = &folder.path;
let name = &folder.name;
let children: Vec<&FolderSnapshot> = folders
.iter()
.filter(|child| child.parent.as_deref() == Some(path.as_str()))
.collect();
let expanded = children.is_empty()
|| world
.resource::<AssetBrowserUiState>()
.expanded_folders
.contains(path);
let selected = current_folder == *path;
ui.horizontal(|ui| {
ui.add_space(depth as f32 * 12.0);
if children.is_empty() {
ui.add_sized(
[18.0, 20.0],
egui::Label::new(icon_text(icons::DOT_OUTLINE, 12.0).color(TEXT_DIM)),
);
} else {
let icon = if expanded {
icons::CARET_DOWN
} else {
icons::CARET_RIGHT
};
if ui
.add_sized(
[18.0, 18.0],
egui::Button::new(icon_text(icon, 12.0)).frame(false),
)
.clicked()
{
let mut state = world.resource_mut::<AssetBrowserUiState>();
if expanded {
state.expanded_folders.remove(path);
} else {
state.expanded_folders.insert(path.clone());
}
}
}
ui.label(icon_text(icons::FOLDER, 14.0).color(TEXT_DIM));
let folder_response = ui.add_sized(
[fit_width(ui, 72.0, f32::INFINITY), 20.0],
egui::Button::selectable(selected, name.as_str()),
);
if folder_response.clicked() {
navigate_content_folder(world, path.clone());
}
if folder_response.secondary_clicked() {
prepare_context_menu_selection(world, AssetSelection::Folder(path.clone()));
}
folder_response.context_menu(|ui| folder_context_menu(world, ui, folder));
handle_asset_drop_to_folder(world, ui, &folder_response, path);
});
if expanded {
for child in children {
folder_tree_branch(world, ui, folders, &child.path, depth + 1, current_folder);
}
}
}
pub(super) fn child_folders_for_content(
folders: &[FolderSnapshot],
current_folder: &str,
search: &str,
) -> Vec<FolderSnapshot> {
if !search.trim().is_empty() {
return Vec::new();
}
let mut children: Vec<FolderSnapshot> = folders
.iter()
.filter(|folder| folder.parent.as_deref() == Some(current_folder))
.cloned()
.collect();
children.sort_by(|a, b| natural_cmp(&a.name, &b.name));
children
}
pub(super) fn visible_assets(
assets: &[AssetRow],
current_folder: &str,
state: &AssetBrowserStateSnapshot,
) -> Vec<AssetRow> {
let search = state.search.trim().to_ascii_lowercase();
let mut rows: Vec<AssetRow> = assets
.iter()
.filter(|row| {
if state.recursive {
row.asset.folder_path == current_folder
|| row
.asset
.folder_path
.strip_prefix(current_folder)
.is_some_and(|rest| rest.starts_with('/'))
} else {
row.asset.folder_path == current_folder
}
})
.filter(|row| asset_matches_kind_filter(&row.asset, state.kind_filter))
.filter(|row| {
search.is_empty()
|| row.asset.label.to_ascii_lowercase().contains(&search)
|| row
.asset
.path
.as_deref()
.unwrap_or_default()
.to_ascii_lowercase()
.contains(&search)
})
.cloned()
.collect();
rows.sort_by(|a, b| match state.sort {
AssetSort::Name => natural_cmp(&a.asset.label, &b.asset.label),
AssetSort::Kind => kind_label(&a.asset.kind).cmp(kind_label(&b.asset.kind)),
AssetSort::Modified => b.modified.cmp(&a.modified),
AssetSort::Size => b.file_size.cmp(&a.file_size),
});
rows
}
pub(super) fn visible_selection_order(
folders: &[FolderSnapshot],
assets: &[AssetRow],
) -> Vec<AssetSelection> {
folders
.iter()
.map(|folder| AssetSelection::Folder(folder.path.clone()))
.chain(assets.iter().map(|row| row.selection.clone()))
.collect()
}
pub(super) fn apply_content_click_selection(
world: &mut World,
ui: &egui::Ui,
selection: AssetSelection,
visible_order: &[AssetSelection],
) {
let modifiers = ui.input(|input| input.modifiers);
let mut assets = world.resource_mut::<EditorAssets>();
if modifiers.shift {
assets.select_range(selection, visible_order, modifiers.command);
} else if modifiers.command {
assets.toggle_selection(selection);
} else {
assets.select(selection);
}
}
pub(super) fn handle_content_shortcuts(
world: &mut World,
ctx: &egui::Context,
visible_order: &[AssetSelection],
content_contains_pointer: bool,
) {
if !content_contains_pointer
|| ctx.egui_wants_keyboard_input()
|| ctx.any_popup_open()
|| content_browser_modal_active(world)
{
return;
}
let (select_all, copy, cut, paste, duplicate, new_folder, undo, rename, delete) =
ctx.input(|input| {
let modifiers = input.modifiers;
let command_only = modifiers.command && !modifiers.shift && !modifiers.alt;
let command_shift = modifiers.command && modifiers.shift && !modifiers.alt;
let no_modifiers =
!modifiers.command && !modifiers.ctrl && !modifiers.shift && !modifiers.alt;
(
command_only && input.key_pressed(egui::Key::A),
command_only && input.key_pressed(egui::Key::C),
command_only && input.key_pressed(egui::Key::X),
command_only && input.key_pressed(egui::Key::V),
command_only && input.key_pressed(egui::Key::D),
command_shift && input.key_pressed(egui::Key::N),
command_only && input.key_pressed(egui::Key::Z),
no_modifiers && input.key_pressed(egui::Key::F2),
no_modifiers && input.key_pressed(egui::Key::Delete),
)
});
let consumed = if select_all {
Some((egui::Modifiers::COMMAND, egui::Key::A))
} else if copy {
Some((egui::Modifiers::COMMAND, egui::Key::C))
} else if cut {
Some((egui::Modifiers::COMMAND, egui::Key::X))
} else if paste {
Some((egui::Modifiers::COMMAND, egui::Key::V))
} else if duplicate {
Some((egui::Modifiers::COMMAND, egui::Key::D))
} else if new_folder {
Some((
egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
egui::Key::N,
))
} else if undo {
Some((egui::Modifiers::COMMAND, egui::Key::Z))
} else if rename {
Some((egui::Modifiers::NONE, egui::Key::F2))
} else if delete {
Some((egui::Modifiers::NONE, egui::Key::Delete))
} else {
None
};
if let Some((modifiers, key)) = consumed {
ctx.input_mut(|input| {
input.consume_key(modifiers, key);
});
}
if select_all {
world
.resource_mut::<EditorAssets>()
.select_all(visible_order);
} else if copy {
set_content_clipboard(world, false);
} else if cut {
set_content_clipboard(world, true);
} else if paste {
paste_content_clipboard(world);
} else if duplicate {
duplicate_selection(world);
} else if new_folder {
let current_folder = world.resource::<EditorAssets>().current_folder.clone();
if current_folder != BUILTINS_FOLDER {
begin_new_folder(world, current_folder);
}
} else if undo {
undo_last_content_operation(world);
} else if rename {
begin_rename(world);
} else if delete {
request_delete_for_selection(world);
}
}
pub(super) fn content_browser_modal_active(world: &World) -> bool {
let state = world.resource::<AssetBrowserUiState>();
state.pending_delete.is_some()
|| state.pending_path_edit.is_some()
|| state.pending_content_transaction.is_some()
|| state.pending_import_destination.is_some()
|| state.pending_gltf_extraction.is_some()
|| state.pending_pbr_grouping.is_some()
|| state.show_trash
|| world
.get_resource::<crate::scene_io::PendingAssetImportReview>()
.is_some_and(|pending| pending.0.is_some())
|| world
.get_resource::<PendingExternalMoveRepair>()
.and_then(|pending| pending.review.as_ref())
.is_some_and(|review| review.open)
}
@@ -0,0 +1,595 @@
use super::*;
pub(super) fn assign_extracted_material_to_actor_slot(
world: &mut World,
target: &GltfMaterialExtractionTarget,
reference: MaterialRef,
) -> Result<(), String> {
use crate::history::reflected_component_transaction;
if let Some(mut primitive) = world.get::<shared::Primitive>(target.entity).cloned() {
if primitive.surface.id == target.slot_id {
primitive.surface.material = Some(reference);
return reflected_component_transaction(
world,
target.entity,
"Extract and Assign Material",
shared::AUTHORING_COMPONENT_PRIMITIVE,
shared::COMPONENT_PRIMITIVE,
move |world, entity| {
world.entity_mut(entity).insert(primitive);
Ok(())
},
);
}
}
if let Some(mut renderer) = world
.get::<shared::StaticMeshRenderer>(target.entity)
.cloned()
{
if let Some(slot) = renderer.materials.slot_mut(&target.slot_id) {
slot.material = Some(reference);
return reflected_component_transaction(
world,
target.entity,
"Extract and Assign Material",
shared::AUTHORING_COMPONENT_STATIC_MESH_RENDERER,
shared::COMPONENT_STATIC_MESH_RENDERER,
move |world, entity| {
world.entity_mut(entity).insert(renderer);
Ok(())
},
);
}
}
if let Some(mut renderer) = world
.get::<shared::SkinnedMeshRenderer>(target.entity)
.cloned()
{
if let Some(slot) = renderer.materials.slot_mut(&target.slot_id) {
slot.material = Some(reference);
return reflected_component_transaction(
world,
target.entity,
"Extract and Assign Material",
shared::AUTHORING_COMPONENT_SKINNED_MESH_RENDERER,
shared::COMPONENT_SKINNED_MESH_RENDERER,
move |world, entity| {
world.entity_mut(entity).insert(renderer);
Ok(())
},
);
}
}
Err("The actor or exact material slot changed before assignment".into())
}
pub(super) fn bind_extracted_material_slots(
document: &mut AssetRegistryDocument,
source: &str,
manifest: &crate::assets::static_mesh::StaticMeshManifest,
bindings: &[ExtractedMaterialBinding],
) -> Result<usize, String> {
let material_bindings = bindings
.iter()
.map(|binding| {
let record = document
.records
.iter()
.find(|record| record.path == binding.path)
.ok_or_else(|| {
format!("Extracted Material was not registered: {}", binding.path)
})?;
let expected_source_id =
material_id_from_label(&format!("Material{}", binding.source_index));
let reference = MaterialRef::new(
EditorAssetRef::new(record.id.as_string(), "", record.label.clone())
.with_source_path(record.path.clone()),
);
Ok((expected_source_id, reference))
})
.collect::<Result<Vec<_>, String>>()?;
let model = document
.records
.iter_mut()
.find(|record| record.path == source)
.ok_or_else(|| format!("Model is not registered: {source}"))?;
let settings = model
.import_settings
.model_mut()
.ok_or_else(|| format!("Asset is not a model: {source}"))?;
let mut mapped_slots = 0;
for part in &manifest.parts {
let Some((_, reference)) = material_bindings.iter().find(|(source_id, _)| {
part_effective_material_id(part).as_deref() == Some(source_id.as_str())
}) else {
continue;
};
let slot_id = shared::ComponentInstanceId::new(format!("slot:{}", part_effective_id(part)));
let selection = ModelMaterialSelection::Project(reference.clone());
if let Some(existing) = settings
.material_slots
.iter_mut()
.find(|entry| entry.slot_id == slot_id)
{
existing.selection = selection;
} else {
settings
.material_slots
.push(ModelMaterialSlotSelection { slot_id, selection });
}
mapped_slots += 1;
}
settings
.material_slots
.sort_by(|left, right| left.slot_id.0.cmp(&right.slot_id.0));
Ok(mapped_slots)
}
pub(super) fn refresh_extracted_model_artifacts(
world: &mut World,
source: &str,
) -> Result<(), String> {
let mut registry = world.resource_mut::<AssetRegistry>();
let record = find_asset_mut_by_path(&mut registry, source)
.ok_or_else(|| format!("Model is no longer registered: {source}"))?;
refresh_model_artifacts(record)?;
save_registry(&registry)?;
registry.index_dirty = false;
Ok(())
}
pub(super) fn begin_pbr_grouping(world: &mut World, folder: String) {
let paths = match fs::read_dir(&folder) {
Ok(entries) => entries
.filter_map(Result::ok)
.filter_map(|entry| {
entry
.file_type()
.ok()
.filter(|kind| kind.is_file())
.map(|_| entry.path())
})
.collect::<Vec<_>>(),
Err(error) => {
world.resource_mut::<SceneIo>().status =
format!("Could not inspect {folder} for PBR textures: {error}");
return;
}
};
let groups = content_pipeline::detect_pbr_texture_groups(paths);
let textures = groups
.into_iter()
.flat_map(|group| {
group
.textures
.into_iter()
.map(move |texture| PbrTextureDraft {
path: texture.path.to_string_lossy().replace('\\', "/"),
target: group.key.clone(),
role: texture.role,
confidence: texture.confidence,
included: texture.role != content_pipeline::PbrTextureRole::Unknown,
})
})
.collect::<Vec<_>>();
if textures.is_empty() {
world.resource_mut::<SceneIo>().status =
format!("No supported texture files found directly in {folder}");
return;
}
world
.resource_mut::<AssetBrowserUiState>()
.pending_pbr_grouping = Some(PbrGroupingDraft { folder, textures });
}
pub(super) fn draw_pbr_grouping_modal(world: &mut World, ctx: &egui::Context) {
let Some(mut draft) = world
.resource::<AssetBrowserUiState>()
.pending_pbr_grouping
.clone()
else {
return;
};
let mut cancel = false;
let mut create = false;
egui::Window::new("Create PBR Materials From Folder")
.collapsible(false)
.resizable(true)
.default_width(820.0)
.min_width(620.0)
.show(ctx, |ui| {
ui.label(format!("Source folder: {}", draft.folder));
ui.small(
egui::RichText::new(
"Review detected maps. Edit Target to merge or split material groups; unresolved files remain visible but are excluded by default.",
)
.color(TEXT_DIM),
);
ui.separator();
egui::Grid::new("pbr_grouping_review")
.num_columns(5)
.striped(true)
.spacing([10.0, 6.0])
.show(ui, |ui| {
ui.strong("Use");
ui.strong("Texture");
ui.strong("Target");
ui.strong("Role");
ui.strong("Confidence");
ui.end_row();
for (index, texture) in draft.textures.iter_mut().enumerate() {
ui.checkbox(&mut texture.included, "");
let name = Path::new(&texture.path)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or(&texture.path);
ui.add(egui::Label::new(name).truncate()).on_hover_text(&texture.path);
ui.add_sized([170.0, 20.0], egui::TextEdit::singleline(&mut texture.target));
egui::ComboBox::from_id_salt(("pbr_role", index))
.selected_text(texture.role.label())
.show_ui(ui, |ui| {
for role in content_pipeline::PbrTextureRole::ALL {
ui.selectable_value(&mut texture.role, role, role.label());
}
});
ui.label(pbr_confidence_label(texture.confidence));
ui.end_row();
}
});
ui.separator();
let group_count = pbr_draft_group_count(&draft);
let valid = group_count > 0
&& draft.textures.iter().filter(|texture| texture.included).all(|texture| {
valid_content_name(&texture.target)
&& texture.role != content_pipeline::PbrTextureRole::Unknown
});
ui.horizontal(|ui| {
if ui.button("Cancel").clicked() {
cancel = true;
}
if ui
.add_enabled(
valid,
egui::Button::new(format!("Create {group_count} Material(s)")),
)
.clicked()
{
create = true;
}
});
if !valid {
ui.small(
egui::RichText::new(
"Included rows need a valid Target and a resolved texture role.",
)
.color(WARNING),
);
}
});
if cancel {
world
.resource_mut::<AssetBrowserUiState>()
.pending_pbr_grouping = None;
} else if create {
match create_pbr_materials(world, &draft) {
Ok(()) => {
world
.resource_mut::<AssetBrowserUiState>()
.pending_pbr_grouping = None;
}
Err(error) => {
world.resource_mut::<SceneIo>().status = error;
world
.resource_mut::<AssetBrowserUiState>()
.pending_pbr_grouping = Some(draft);
}
}
} else {
world
.resource_mut::<AssetBrowserUiState>()
.pending_pbr_grouping = Some(draft);
}
}
pub(super) fn pbr_confidence_label(
confidence: content_pipeline::PbrMatchConfidence,
) -> &'static str {
match confidence {
content_pipeline::PbrMatchConfidence::High => "High",
content_pipeline::PbrMatchConfidence::Medium => "Medium",
content_pipeline::PbrMatchConfidence::Low => "Low",
content_pipeline::PbrMatchConfidence::Unresolved => "Unresolved",
}
}
pub(super) fn pbr_draft_group_count(draft: &PbrGroupingDraft) -> usize {
draft
.textures
.iter()
.filter(|texture| texture.included)
.map(|texture| texture.target.trim())
.collect::<HashSet<_>>()
.len()
}
pub(super) fn create_pbr_materials(
world: &mut World,
draft: &PbrGroupingDraft,
) -> Result<(), String> {
let mut groups: BTreeMap<String, Vec<&PbrTextureDraft>> = BTreeMap::new();
for texture in draft.textures.iter().filter(|texture| texture.included) {
if !valid_content_name(&texture.target)
|| texture.role == content_pipeline::PbrTextureRole::Unknown
{
return Err("Every included texture needs a valid target and resolved role".into());
}
groups
.entry(texture.target.trim().to_string())
.or_default()
.push(texture);
}
if groups.is_empty() {
return Err("Select at least one texture before creating materials".into());
}
let records = world
.resource::<crate::asset_db::AssetRegistry>()
.records
.clone();
let mut reserved = HashSet::new();
let mut operations = Vec::new();
for (target, textures) in groups {
let destination = unique_material_destination(&draft.folder, &target, &mut reserved);
let asset = material_asset_from_pbr_group(&target, &textures, &records);
let ron = ron::ser::to_string_pretty(&asset, ron::ser::PrettyConfig::default())
.map_err(|error| format!("Could not serialize material {target}: {error}"))?;
operations.push(content_pipeline::ContentOperation::WriteFile {
path: PathBuf::from(destination),
bytes: ron.into_bytes(),
});
}
if !commit_content_operations(world, operations) {
return Err(world.resource::<SceneIo>().status.clone());
}
Ok(())
}
pub(super) fn unique_material_destination(
folder: &str,
target: &str,
reserved: &mut HashSet<String>,
) -> String {
let stem = target
.trim()
.chars()
.map(|character| {
if character.is_ascii_alphanumeric() || matches!(character, '-' | '_') {
character
} else {
'_'
}
})
.collect::<String>();
let stem = stem.trim_matches('_');
let stem = if stem.is_empty() { "Material" } else { stem };
for suffix in 1.. {
let file = if suffix == 1 {
format!("{stem}.material.ron")
} else {
format!("{stem}_{suffix}.material.ron")
};
let path = Path::new(folder)
.join(file)
.to_string_lossy()
.replace('\\', "/");
if !Path::new(&path).exists() && reserved.insert(path.clone()) {
return path;
}
}
unreachable!()
}
pub(super) fn material_asset_from_pbr_group(
target: &str,
textures: &[&PbrTextureDraft],
records: &[crate::asset_db::AssetRecord],
) -> MaterialAsset {
let mut material = MaterialDesc::default();
for texture in textures {
match texture.role {
content_pipeline::PbrTextureRole::BaseColor => {
material.base_color_texture = Some(texture.path.clone());
}
content_pipeline::PbrTextureRole::Normal => {
material.normal_map_texture = Some(texture.path.clone());
}
content_pipeline::PbrTextureRole::PackedOrm => {
material.metallic_roughness_texture = Some(texture.path.clone());
material.textures.push(MaterialTextureBinding {
name: "occlusion_texture".into(),
texture: Some(pbr_texture_reference(&texture.path, records)),
channel: TextureChannel::R,
});
}
content_pipeline::PbrTextureRole::Roughness => {
material.textures.push(MaterialTextureBinding {
name: "roughness_texture".into(),
texture: Some(pbr_texture_reference(&texture.path, records)),
channel: TextureChannel::G,
});
}
content_pipeline::PbrTextureRole::Metallic => {
material.textures.push(MaterialTextureBinding {
name: "metallic_texture".into(),
texture: Some(pbr_texture_reference(&texture.path, records)),
channel: TextureChannel::B,
});
}
content_pipeline::PbrTextureRole::Occlusion => {
material.textures.push(MaterialTextureBinding {
name: "occlusion_texture".into(),
texture: Some(pbr_texture_reference(&texture.path, records)),
channel: TextureChannel::R,
});
}
content_pipeline::PbrTextureRole::Height => {
material.textures.push(MaterialTextureBinding {
name: "height_texture".into(),
texture: Some(pbr_texture_reference(&texture.path, records)),
channel: TextureChannel::R,
});
}
content_pipeline::PbrTextureRole::Unknown => {}
}
}
MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: target.replace(['_', '-'], " "),
shader: material.shader.clone(),
shader_ref: None,
render_state: shared::MaterialRenderState::default(),
provenance: None,
inputs: MaterialInputSet::from_material_desc(&material),
}
}
pub(super) fn pbr_texture_reference(
path: &str,
records: &[crate::asset_db::AssetRecord],
) -> EditorAssetRef {
let label = Path::new(path)
.file_stem()
.and_then(|stem| stem.to_str())
.unwrap_or("Texture");
let id = records
.iter()
.find(|record| record.path == path)
.map(|record| record.id.as_string())
.unwrap_or_default();
EditorAssetRef::new(id, "texture:source", label).with_source_path(path)
}
pub(super) fn commit_content_operations(
world: &mut World,
operations: Vec<content_pipeline::ContentOperation>,
) -> bool {
commit_content_operations_internal(world, operations, true)
}
pub(super) fn commit_content_operations_internal(
world: &mut World,
operations: Vec<content_pipeline::ContentOperation>,
record_undo: bool,
) -> bool {
commit_content_operations_internal_with_registry_update(world, operations, record_undo, |_| {
Ok(())
})
}
pub(super) fn commit_content_operations_internal_with_registry_update(
world: &mut World,
operations: Vec<content_pipeline::ContentOperation>,
record_undo: bool,
registry_update: impl FnOnce(&mut AssetRegistryDocument) -> Result<(), String>,
) -> bool {
let previous_folder = world.resource::<EditorAssets>().current_folder.clone();
let mut resulting_folder = previous_folder.clone();
for operation in &operations {
if let content_pipeline::ContentOperation::Move {
source,
destination,
} = operation
{
let source = source.to_string_lossy().replace('\\', "/");
let destination = destination.to_string_lossy().replace('\\', "/");
if resulting_folder == source
|| resulting_folder
.strip_prefix(&source)
.is_some_and(|suffix| suffix.starts_with('/'))
{
resulting_folder = format!("{destination}{}", &resulting_folder[source.len()..]);
}
}
}
let mut document = world
.resource::<crate::asset_db::AssetRegistry>()
.document();
let preview = match content_pipeline::preview_transaction(Path::new("."), operations, &document)
{
Ok(preview) => preview,
Err(error) => {
world.resource_mut::<SceneIo>().status = format!("Content operation blocked: {error}");
return false;
}
};
if !preview.is_committable() {
world.resource_mut::<SceneIo>().status = format!(
"Content operation has {} collision(s)",
preview.collisions.len()
);
return false;
}
crate::assets::begin_content_watch_transaction(world);
let commit_result = content_pipeline::commit_transaction_with_registry_update(
Path::new("."),
&preview,
&mut document,
registry_update,
);
crate::assets::end_content_watch_transaction(world);
if let Err(error) = commit_result {
world.resource_mut::<SceneIo>().status = error;
return false;
}
let undo_entry = record_undo
.then(|| build_content_undo_entry(Path::new("."), &preview))
.flatten();
{
let mut registry = world.resource_mut::<crate::asset_db::AssetRegistry>();
registry.schema_version = document.schema_version;
registry.defaults = document.defaults;
registry.records = document.records;
registry.index_dirty = false;
registry.migration_required = false;
}
let resulting_selections: Vec<AssetSelection> = preview
.operations
.iter()
.map(|operation| match operation {
content_pipeline::ContentOperation::CreateFolder { path } => {
AssetSelection::Folder(path.to_string_lossy().replace('\\', "/"))
}
content_pipeline::ContentOperation::Move { destination, .. }
| content_pipeline::ContentOperation::Copy { destination, .. } => {
let normalized = destination.to_string_lossy().replace('\\', "/");
if Path::new(&normalized).is_dir() {
AssetSelection::Folder(normalized)
} else {
AssetSelection::File(normalized)
}
}
content_pipeline::ContentOperation::WriteFile { path, .. }
| content_pipeline::ContentOperation::ReplaceFile { path, .. } => {
AssetSelection::File(path.to_string_lossy().replace('\\', "/"))
}
})
.collect();
{
let mut assets = world.resource_mut::<EditorAssets>();
assets.current_folder = resulting_folder;
assets.refresh();
assets.select_all(&resulting_selections);
}
invalidate_on_catalog_refresh(world);
if let Some(entry) = undo_entry {
push_content_undo(world, entry);
}
world.resource_mut::<SceneIo>().status = format!(
"Content transaction committed ({} item(s), {} reference rewrite(s))",
preview.operations.len(),
preview.reference_rewrites.len()
);
true
}
@@ -0,0 +1,455 @@
fn content_navigation_fixture() -> EditorAssets {
let props = AssetSelection::Folder("assets/Props".into());
EditorAssets {
folders: vec![
crate::assets::AssetFolder {
path: "assets".into(),
name: "assets".into(),
parent: None,
},
crate::assets::AssetFolder {
path: "assets/Props".into(),
name: "Props".into(),
parent: Some("assets".into()),
},
],
assets: Vec::new(),
current_folder: "assets".into(),
selected: Some(props.clone()),
selections: vec![props.clone()],
selection_anchor: Some(props.clone()),
dragging: Some(props),
status: String::new(),
catalog_revision: 1,
}
}
#[test]
fn folder_navigation_clears_hidden_selection_and_drag_state() {
let mut world = World::new();
world.insert_resource(content_navigation_fixture());
navigate_content_folder(&mut world, "assets/Props".into());
let assets = world.resource::<EditorAssets>();
assert_eq!(assets.current_folder, "assets/Props");
assert!(assets.selected.is_none());
assert!(assets.selections.is_empty());
assert!(assets.selection_anchor.is_none());
assert!(assets.dragging.is_none());
}
#[test]
fn visibility_filter_changes_clear_hidden_selection_but_noops_preserve_it() {
let mut world = World::new();
world.insert_resource(content_navigation_fixture());
clear_selection_when_visible_results_change(&mut world, false);
assert_eq!(world.resource::<EditorAssets>().selections.len(), 1);
clear_selection_when_visible_results_change(&mut world, true);
let assets = world.resource::<EditorAssets>();
assert!(assets.selected.is_none());
assert!(assets.selections.is_empty());
assert_eq!(
assets.status,
"Selection cleared because visible results changed"
);
}
#[test]
fn context_targeting_preserves_selected_batches_and_selects_unselected_subassets() {
let mut world = World::new();
let mut assets = content_navigation_fixture();
assets.assets.push(EditorAsset {
label: "Desk".into(),
path: Some("assets/desk.glb".into()),
folder_path: "assets".into(),
kind: EditorAssetKind::Model,
});
let folder = AssetSelection::Folder("assets/Props".into());
let model = AssetSelection::File("assets/desk.glb".into());
assets.select_all(&[folder.clone(), model.clone()]);
world.insert_resource(assets);
prepare_context_menu_selection(&mut world, model);
assert_eq!(world.resource::<EditorAssets>().selections.len(), 2);
let subasset = AssetSelection::SubAsset {
parent_path: "assets/desk.glb".into(),
sub_asset_id: "mesh:0".into(),
label: "Desk Top".into(),
kind: AssetSubAssetKind::Mesh,
source_path: None,
};
prepare_context_menu_selection(&mut world, subasset.clone());
let assets = world.resource::<EditorAssets>();
assert_eq!(assets.selected, Some(subasset.clone()));
assert_eq!(assets.selections, vec![subasset]);
}
#[test]
fn batch_selection_counts_distinguish_nested_and_non_filesystem_items() {
let mut world = World::new();
let mut assets = content_navigation_fixture();
assets.assets.extend([
EditorAsset {
label: "Desk".into(),
path: Some("assets/Props/desk.glb".into()),
folder_path: "assets/Props".into(),
kind: EditorAssetKind::Model,
},
EditorAsset {
label: "Cube".into(),
path: None,
folder_path: BUILTINS_FOLDER.into(),
kind: EditorAssetKind::Primitive(shared::PrimitiveShape::Box),
},
]);
assets.selections = vec![
AssetSelection::Folder("assets/Props".into()),
AssetSelection::File("assets/Props/desk.glb".into()),
AssetSelection::SubAsset {
parent_path: "assets/Props/desk.glb".into(),
sub_asset_id: "mesh:0".into(),
label: "Desk Top".into(),
kind: AssetSubAssetKind::Mesh,
source_path: None,
},
AssetSelection::Builtin("Cube".into()),
];
assets.selected = assets.selections.last().cloned();
world.insert_resource(assets);
assert_eq!(selected_content_paths(&world), vec!["assets/Props"]);
assert_eq!(collapsed_and_unaffected_selection_counts(&world), (1, 2));
}
#[test]
fn cancelling_reviewed_content_transaction_restores_browser_and_scene_state() {
let mut world = World::new();
let mut assets = content_navigation_fixture();
assets.status = "Before review".into();
world.insert_resource(assets);
let mut scene_io = SceneIo::default();
scene_io.status = "Scene status before review".into();
world.insert_resource(scene_io);
let snapshot = capture_content_browser_snapshot(&world);
let pending = PendingContentTransaction {
preview: content_pipeline::ContentTransactionPreview {
operations: Vec::new(),
affected_asset_ids: Vec::new(),
reference_rewrites: Vec::new(),
collisions: Vec::new(),
},
guarded_paths: Vec::new(),
clear_cut_clipboard: false,
clear_drag: false,
browser_snapshot: snapshot.clone(),
};
{
let mut assets = world.resource_mut::<EditorAssets>();
assets.current_folder = "assets/Changed".into();
assets.clear_selection();
assets.dragging = None;
assets.status = "Review open".into();
}
world.resource_mut::<SceneIo>().status = "Transaction review".into();
restore_cancelled_content_transaction(&mut world, &pending);
let assets = world.resource::<EditorAssets>();
assert_eq!(assets.current_folder, snapshot.current_folder);
assert_eq!(assets.selected, snapshot.selected);
assert_eq!(assets.selections, snapshot.selections);
assert_eq!(assets.selection_anchor, snapshot.selection_anchor);
assert_eq!(assets.dragging, snapshot.dragging);
assert_eq!(assets.status, snapshot.asset_status);
assert_eq!(world.resource::<SceneIo>().status, snapshot.scene_status);
}
#[test]
fn cancelling_drag_review_restores_selection_but_clears_stale_drag() {
let mut world = World::new();
world.insert_resource(content_navigation_fixture());
world.insert_resource(SceneIo::default());
let pending = PendingContentTransaction {
preview: content_pipeline::ContentTransactionPreview {
operations: Vec::new(),
affected_asset_ids: Vec::new(),
reference_rewrites: Vec::new(),
collisions: Vec::new(),
},
guarded_paths: Vec::new(),
clear_cut_clipboard: false,
clear_drag: true,
browser_snapshot: capture_content_browser_snapshot(&world),
};
restore_cancelled_content_transaction(&mut world, &pending);
let assets = world.resource::<EditorAssets>();
assert!(assets.selected.is_some());
assert_eq!(assets.selections.len(), 1);
assert!(assets.dragging.is_none());
}
#[test]
fn reviewed_model_import_rolls_back_files_when_artifact_processing_fails() {
let root = std::env::temp_dir().join(format!(
"blacksite-reviewed-model-import-{}",
uuid::Uuid::new_v4()
));
let project = root.join("project");
let destination = PathBuf::from("assets/Target");
fs::create_dir_all(project.join(&destination)).unwrap();
let source = root.join("broken.gltf");
fs::write(
&source,
r#"{"asset":{"version":"2.0"},"buffers":[{"uri":"mesh.bin","byteLength":12}]}"#,
)
.unwrap();
fs::write(root.join("mesh.bin"), [0_u8]).unwrap();
let plan = crate::assets::plan_external_assets_import_at(
&project,
std::slice::from_ref(&source),
&destination,
)
.unwrap();
let mut world = World::new();
world.insert_resource(AssetRegistry::default());
let error = commit_reviewed_asset_import(&mut world, &plan).unwrap_err();
assert!(error.contains("processing rolled back"));
assert!(!project.join("assets/Target/broken.gltf").exists());
assert!(!project.join("assets/Target/mesh.bin").exists());
assert!(!project.join(content_pipeline::REGISTRY_PATH).exists());
assert!(!project
.join(content_pipeline::RUNTIME_CATALOG_PATH)
.exists());
assert!(world.resource::<AssetRegistry>().records.is_empty());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn import_to_keeps_browser_location_and_pins_explicit_destination() {
let mut world = World::new();
let mut assets = content_navigation_fixture();
assets.current_folder = "assets/Props".into();
world.insert_resource(assets);
world.insert_resource(AssetBrowserUiState::default());
world.init_resource::<SceneIo>();
begin_import_to(&mut world);
assert_eq!(
world
.resource::<AssetBrowserUiState>()
.pending_import_destination
.as_deref(),
Some("assets/Props")
);
request_import_to_destination(&mut world, "assets/Props".into());
assert_eq!(
world.resource::<SceneIo>().request,
Some(SceneIoRequest::ImportAssets {
destination: "assets/Props".into()
})
);
assert_eq!(
world.resource::<EditorAssets>().current_folder,
"assets/Props"
);
}
#[test]
fn locating_content_asset_navigates_to_parent_and_selects_the_file() {
let mut world = World::new();
let mut assets = content_navigation_fixture();
assets.assets.push(EditorAsset {
label: "Desk".into(),
path: Some("assets/Props/desk.material.ron".into()),
folder_path: "assets/Props".into(),
kind: EditorAssetKind::Material,
});
world.insert_resource(assets);
locate_content_asset(&mut world, "assets/Props/desk.material.ron");
let assets = world.resource::<EditorAssets>();
assert_eq!(assets.current_folder, "assets/Props");
assert_eq!(
assets.selected,
Some(AssetSelection::File(
"assets/Props/desk.material.ron".into()
))
);
assert_eq!(assets.selections, vec![assets.selected.clone().unwrap()]);
assert_eq!(assets.status, "Located assets/Props/desk.material.ron");
}
#[test]
fn locating_missing_content_asset_reports_the_broken_reference() {
let mut world = World::new();
world.insert_resource(content_navigation_fixture());
locate_content_asset(&mut world, "assets/Props/missing.material.ron");
let assets = world.resource::<EditorAssets>();
assert_eq!(assets.current_folder, "assets");
assert!(assets.selected.is_some());
assert_eq!(
assets.status,
"Referenced project asset is missing: assets/Props/missing.material.ron"
);
}
#[test]
fn model_material_clear_restores_source_and_removes_only_target_orphan() {
let active_slot = shared::ComponentInstanceId::new("slot:active");
let removed_orphan = shared::ComponentInstanceId::new("slot:removed");
let retained_orphan = shared::ComponentInstanceId::new("slot:retained");
let material = MaterialRef::new(
EditorAssetRef::new("material-id", "", "Desk")
.with_source_path("assets/Props/desk.material.ron"),
);
let mut settings = ImportSettings {
material_slots: vec![ModelMaterialSlotSelection {
slot_id: active_slot.clone(),
selection: ModelMaterialSelection::Project(material.clone()),
}],
orphaned_material_slots: vec![
shared::OrphanedModelMaterialSelection {
slot_id: removed_orphan.clone(),
last_known_name: "Removed".into(),
material: material.clone(),
},
shared::OrphanedModelMaterialSelection {
slot_id: retained_orphan.clone(),
last_known_name: "Retained".into(),
material,
},
],
..Default::default()
};
set_model_material_slot_selection(
&mut settings,
&active_slot,
ModelMaterialSelection::Source,
);
assert!(clear_orphaned_model_material_selection(
&mut settings,
&removed_orphan
));
assert!(matches!(
settings.material_slots[0].selection,
ModelMaterialSelection::Source
));
assert_eq!(settings.orphaned_material_slots.len(), 1);
assert_eq!(settings.orphaned_material_slots[0].slot_id, retained_orphan);
assert!(!clear_orphaned_model_material_selection(
&mut settings,
&removed_orphan
));
}
#[test]
fn rename_target_never_falls_back_to_an_unselected_current_folder() {
let mut assets = content_navigation_fixture();
assets.current_folder = "assets/Props".into();
assets.clear_selection();
let mut world = World::new();
world.insert_resource(assets);
assert_eq!(selected_content_path(&world), None);
}
#[test]
fn embedded_subassets_never_become_filesystem_operation_targets() {
let selection = AssetSelection::SubAsset {
parent_path: "assets/Props/desk.glb".into(),
sub_asset_id: "mesh:top".into(),
label: "Desk Top".into(),
kind: AssetSubAssetKind::Mesh,
source_path: None,
};
let mut assets = content_navigation_fixture();
assets.assets.push(EditorAsset {
label: "Desk".into(),
path: Some("assets/Props/desk.glb".into()),
folder_path: "assets/Props".into(),
kind: EditorAssetKind::Model,
});
assets.selected = Some(selection.clone());
assets.selections = vec![selection];
let mut world = World::new();
world.insert_resource(assets);
assert_eq!(selected_content_path(&world), None);
assert!(selected_content_paths(&world).is_empty());
assert!(build_delete_request(&world).is_none());
}
#[test]
fn details_width_respects_content_and_pane_minimums() {
assert_eq!(details_width_for_layout(1_000.0, 220.0, 100.0), 200.0);
assert_eq!(details_width_for_layout(1_000.0, 220.0, 900.0), 600.0);
assert_eq!(details_width_for_layout(1_000.0, 220.0, 420.0), 420.0);
}
#[test]
fn details_width_uses_reclaimed_tree_space() {
assert_eq!(details_width_for_layout(1_000.0, 0.0, 900.0), 830.0);
}
#[test]
fn content_shortcuts_are_suppressed_while_a_browser_modal_is_active() {
let mut world = World::new();
world.insert_resource(AssetBrowserUiState::default());
assert!(!content_browser_modal_active(&world));
world
.resource_mut::<AssetBrowserUiState>()
.pending_path_edit = Some(ContentPathEdit {
kind: ContentPathEditKind::NewFolder {
parent: "assets".into(),
},
name: "New Folder".into(),
});
assert!(content_browser_modal_active(&world));
}
#[test]
fn external_move_review_requires_complete_non_reused_identity_choices() {
let fingerprint = shared::AssetSourceFingerprint::from_bytes(b"matching source");
let conflict = |new_path: &str| content_pipeline::ExternalMoveConflict {
new_path: new_path.into(),
candidate_paths: vec!["assets/Old/A.png".into(), "assets/Old/B.png".into()],
kind: shared::AssetKind::Texture,
fingerprint: fingerprint.clone(),
};
let mut review = crate::assets::ExternalMoveRepairReview {
root: PathBuf::from("/unused"),
previous: shared::AssetRegistryDocument::default(),
conflicts: vec![conflict("assets/New/A.png"), conflict("assets/New/B.png")],
choices: vec![None, None],
open: true,
};
assert!(!external_move_choices_valid(&review));
review.choices = vec![
Some(ExternalMoveRepairChoice::Preserve(
"assets/Old/A.png".into(),
)),
Some(ExternalMoveRepairChoice::Preserve(
"assets/Old/A.png".into(),
)),
];
assert!(!external_move_choices_valid(&review));
review.choices[1] = Some(ExternalMoveRepairChoice::RegisterNew);
assert!(external_move_choices_valid(&review));
}
@@ -0,0 +1,481 @@
#[test]
fn cut_paste_keeps_exact_target_name_so_collisions_reach_review() {
let mut reserved = HashSet::new();
let source = Path::new("assets/Props/desk.material.ron");
let destination =
paste_destination(Path::new("assets/Archive"), source, true, &mut reserved);
assert_eq!(
destination,
PathBuf::from("assets/Archive/desk.material.ron")
);
assert!(reserved.is_empty());
}
#[test]
fn created_content_undo_is_trash_first_and_fingerprint_guarded() {
let root = std::env::temp_dir().join(format!(
"blacksite-content-create-undo-{}",
uuid::Uuid::new_v4()
));
let created = PathBuf::from("assets/Props/New Folder");
fs::create_dir_all(root.join(&created)).unwrap();
let preview = content_pipeline::ContentTransactionPreview {
operations: vec![content_pipeline::ContentOperation::CreateFolder {
path: created.clone(),
}],
affected_asset_ids: Vec::new(),
reference_rewrites: Vec::new(),
collisions: Vec::new(),
};
let undo = build_content_undo_entry(&root, &preview).unwrap();
assert!(matches!(
&undo.action,
ContentUndoAction::TrashCreated(paths) if paths == std::slice::from_ref(&created)
));
assert_eq!(first_changed_content_undo_source(&root, &undo), None);
fs::write(root.join(&created).join("external.txt"), b"external").unwrap();
assert_eq!(
first_changed_content_undo_source(&root, &undo),
Some(created)
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn copied_content_undo_targets_only_the_created_destination() {
let root = std::env::temp_dir().join(format!(
"blacksite-content-copy-undo-{}",
uuid::Uuid::new_v4()
));
let source = PathBuf::from("assets/Props/source.txt");
let destination = PathBuf::from("assets/Props/source_copy.txt");
fs::create_dir_all(root.join("assets/Props")).unwrap();
fs::write(root.join(&source), b"source").unwrap();
fs::write(root.join(&destination), b"source").unwrap();
let preview = content_pipeline::ContentTransactionPreview {
operations: vec![content_pipeline::ContentOperation::Copy {
source: source.clone(),
destination: destination.clone(),
}],
affected_asset_ids: Vec::new(),
reference_rewrites: Vec::new(),
collisions: Vec::new(),
};
let undo = build_content_undo_entry(&root, &preview).unwrap();
assert!(matches!(
&undo.action,
ContentUndoAction::TrashCreated(paths) if paths == &[destination]
));
assert_eq!(fs::read(root.join(source)).unwrap(), b"source");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn trash_restore_undo_is_guarded_by_the_complete_batch() {
let root = std::env::temp_dir().join(format!(
"blacksite-content-trash-undo-{}",
uuid::Uuid::new_v4()
));
let batch = PathBuf::from("assets/.trash/test-batch");
fs::create_dir_all(root.join(&batch).join("assets/Props")).unwrap();
fs::write(root.join(&batch).join("assets/Props/item.txt"), b"item").unwrap();
let fingerprint = content_pipeline::tree_fingerprint(&root.join(&batch)).unwrap();
let undo = ContentUndoEntry {
label: "Move Item to Trash".into(),
action: ContentUndoAction::RestoreTrash(batch.clone()),
guarded_sources: vec![(batch.clone(), fingerprint)],
};
assert_eq!(first_changed_content_undo_source(&root, &undo), None);
fs::write(root.join(&batch).join("assets/Props/item.txt"), b"external").unwrap();
assert_eq!(first_changed_content_undo_source(&root, &undo), Some(batch));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn manual_trash_restore_forgets_only_its_matching_undo_entry() {
let matching = PathBuf::from("assets/.trash/matching");
let other = PathBuf::from("assets/.trash/other");
let mut state = AssetBrowserUiState {
content_undo: vec![
ContentUndoEntry {
label: "Move A to Trash".into(),
action: ContentUndoAction::RestoreTrash(matching.clone()),
guarded_sources: Vec::new(),
},
ContentUndoEntry {
label: "Move B to Trash".into(),
action: ContentUndoAction::RestoreTrash(other.clone()),
guarded_sources: Vec::new(),
},
],
..Default::default()
};
forget_restored_trash_undo(&mut state, &matching);
assert_eq!(state.content_undo.len(), 1);
assert!(matches!(
&state.content_undo[0].action,
ContentUndoAction::RestoreTrash(path) if path == &other
));
}
#[test]
fn audio_filter_matches_only_audio_clips() {
let audio = EditorAsset {
label: "Impact".into(),
path: Some("assets/audio/impact.ogg".into()),
folder_path: "assets/audio".into(),
kind: EditorAssetKind::AudioClip,
};
let texture = EditorAsset {
kind: EditorAssetKind::Texture,
..audio.clone()
};
assert!(asset_matches_kind_filter(&audio, AssetKindFilter::Audio));
assert!(!asset_matches_kind_filter(&texture, AssetKindFilter::Audio));
assert_eq!(kind_filter_label(AssetKindFilter::Audio), "Audio");
}
#[test]
fn audio_details_label_supported_formats() {
assert_eq!(audio_format_label("assets/audio/music.oga"), "Ogg audio");
assert_eq!(audio_format_label("assets/audio/voice.spx"), "Speex");
assert_eq!(audio_format_label("assets/audio/source.WAV"), "WAV");
assert_eq!(audio_format_label("assets/audio/source.mp3"), "MP3");
assert_eq!(audio_format_label("assets/audio/source.flac"), "FLAC");
}
#[test]
fn pbr_grouping_builds_standard_and_surface_texture_bindings() {
let base = PbrTextureDraft {
path: "assets/Props/desk_diff_2k.jpg".into(),
target: "desk".into(),
role: content_pipeline::PbrTextureRole::BaseColor,
confidence: content_pipeline::PbrMatchConfidence::High,
included: true,
};
let normal = PbrTextureDraft {
path: "assets/Props/desk_nor_gl_2k.jpg".into(),
role: content_pipeline::PbrTextureRole::Normal,
..base.clone()
};
let arm = PbrTextureDraft {
path: "assets/Props/desk_arm_2k.jpg".into(),
role: content_pipeline::PbrTextureRole::PackedOrm,
..base.clone()
};
let asset = material_asset_from_pbr_group("desk", &[&base, &normal, &arm], &[]);
let mut material = MaterialDesc::default();
asset.inputs.apply_to_material_desc(&mut material);
assert_eq!(
material.base_color_texture.as_deref(),
Some("assets/Props/desk_diff_2k.jpg")
);
assert_eq!(
material.normal_map_texture.as_deref(),
Some("assets/Props/desk_nor_gl_2k.jpg")
);
assert_eq!(
material.metallic_roughness_texture.as_deref(),
Some("assets/Props/desk_arm_2k.jpg")
);
assert!(material
.textures
.iter()
.any(|binding| binding.name == "occlusion_texture"));
}
#[test]
fn pbr_group_count_reflects_manual_merge_and_exclusions() {
let draft = PbrGroupingDraft {
folder: "assets/Props".into(),
textures: vec![
PbrTextureDraft {
path: "assets/Props/a.png".into(),
target: "shared".into(),
role: content_pipeline::PbrTextureRole::BaseColor,
confidence: content_pipeline::PbrMatchConfidence::High,
included: true,
},
PbrTextureDraft {
path: "assets/Props/b.png".into(),
target: "shared".into(),
role: content_pipeline::PbrTextureRole::Normal,
confidence: content_pipeline::PbrMatchConfidence::High,
included: true,
},
PbrTextureDraft {
path: "assets/Props/c.png".into(),
target: "ignored".into(),
role: content_pipeline::PbrTextureRole::Unknown,
confidence: content_pipeline::PbrMatchConfidence::Unresolved,
included: false,
},
],
};
assert_eq!(pbr_draft_group_count(&draft), 1);
}
#[test]
fn gltf_extraction_review_rejects_duplicate_and_external_paths() {
let asset = MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: "Desk".into(),
shader: shared::ShaderRefDesc::default(),
shader_ref: None,
render_state: Default::default(),
provenance: Some(shared::MaterialProvenance {
source_path: "assets/desk.gltf".into(),
source_fingerprint: "abc".into(),
source_sub_asset_id: "material:0".into(),
source_label: "Desk".into(),
}),
inputs: Default::default(),
};
let entry = GltfMaterialExtractionEntry {
included: true,
source_index: 0,
source_name: "Desk".into(),
path: format!(
"assets/extraction-review-{}/desk.material.ron",
uuid::Uuid::new_v4()
),
asset: asset.clone(),
write_mode: MaterialExtractionWriteMode::CreateNew,
};
let mut draft = GltfMaterialExtractionDraft {
source: "assets/desk.gltf".into(),
destination: "assets".into(),
materials: vec![entry.clone()],
actor_target: None,
};
assert_eq!(gltf_extraction_validation_error(&draft), None);
draft.materials.push(GltfMaterialExtractionEntry {
source_index: 1,
..entry
});
assert!(gltf_extraction_validation_error(&draft)
.is_some_and(|error| error.contains("same project path")));
draft.materials.truncate(1);
draft.materials[0].path = "../outside.material.ron".into();
assert!(gltf_extraction_validation_error(&draft)
.is_some_and(|error| error.contains("Invalid project path")));
}
#[test]
fn gltf_extraction_existing_material_requires_reviewed_guarded_apply() {
let folder = PathBuf::from(format!(
"assets/.extraction-review-{}",
uuid::Uuid::new_v4()
));
fs::create_dir_all(&folder).unwrap();
let path = folder.join("desk.material.ron");
let provenance = shared::MaterialProvenance {
source_path: "assets/desk.gltf".into(),
source_fingerprint: "old".into(),
source_sub_asset_id: "material:0".into(),
source_label: "Desk".into(),
};
let existing = MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: "Locally Edited Desk".into(),
shader: shared::ShaderRefDesc::default(),
shader_ref: None,
render_state: Default::default(),
provenance: Some(provenance.clone()),
inputs: Default::default(),
};
fs::write(&path, ron::ser::to_string(&existing).unwrap()).unwrap();
let mut incoming = existing.clone();
incoming.label = "Desk".into();
incoming.provenance.as_mut().unwrap().source_fingerprint = "new".into();
let entry = GltfMaterialExtractionEntry {
included: true,
source_index: 0,
source_name: "Desk".into(),
path: path.to_string_lossy().replace('\\', "/"),
asset: incoming,
write_mode: MaterialExtractionWriteMode::Undecided,
};
let mut draft = GltfMaterialExtractionDraft {
source: provenance.source_path,
destination: folder.to_string_lossy().replace('\\', "/"),
materials: vec![entry],
actor_target: None,
};
assert!(gltf_extraction_validation_error(&draft)
.is_some_and(|error| error.contains("choose Apply or Create New")));
let review = review_existing_extraction_target(&draft.materials[0])
.unwrap()
.unwrap();
assert!(review.provenance_matches);
assert!(review.changes.contains(&"label"));
assert!(review.changes.contains(&"source revision"));
draft.materials[0].write_mode = MaterialExtractionWriteMode::ApplyExisting {
expected_fingerprint: review.fingerprint,
previous_bytes: review.bytes,
};
assert_eq!(gltf_extraction_validation_error(&draft), None);
fs::write(&path, "external edit").unwrap();
assert!(gltf_extraction_validation_error(&draft).is_some());
fs::remove_dir_all(folder).unwrap();
}
#[test]
fn actor_extraction_assignment_changes_only_the_exact_primitive_slot() {
let mut app = App::new();
app.add_plugins(shared::SharedTypesPlugin);
app.init_resource::<crate::history::EditorHistory>();
let entity = app
.world_mut()
.spawn((
shared::LevelObject,
shared::ActorKind::StaticMesh,
shared::Primitive::default(),
))
.id();
let target = GltfMaterialExtractionTarget {
entity,
slot_id: shared::ComponentInstanceId::new(shared::PRIMITIVE_SURFACE_SLOT_ID),
source_sub_asset_id: "material:0".into(),
};
let reference = MaterialRef::new(
EditorAssetRef::new("material-id", "material:source", "Desk")
.with_source_path("assets/Props/desk.material.ron"),
);
validate_actor_material_extraction_target(app.world(), &target).unwrap();
assign_extracted_material_to_actor_slot(app.world_mut(), &target, reference.clone())
.unwrap();
assert_eq!(
app.world()
.get::<shared::Primitive>(entity)
.unwrap()
.surface
.material
.as_ref(),
Some(&reference)
);
assert!(app
.world()
.resource::<crate::history::EditorHistory>()
.can_undo());
}
#[test]
fn extracted_material_binding_maps_every_draw_slot_using_the_source_material() {
use crate::assets::static_mesh::{
StaticMeshImportSnapshot, StaticMeshManifest, StaticMeshMetadata, StaticMeshPart,
StaticMeshSource,
};
let model_path = "assets/Props/desk.gltf";
let material_path = "assets/Props/desk.material.ron";
let material_id = shared::AssetId::new();
let mut document = AssetRegistryDocument {
records: vec![
shared::AssetRecord {
id: shared::AssetId::new(),
path: model_path.into(),
label: "Desk".into(),
kind: AssetKind::Model,
source_fingerprint: None,
import_settings: shared::AssetImportSettings::Model(ImportSettings::default()),
dependencies: Vec::new(),
},
shared::AssetRecord {
id: material_id.clone(),
path: material_path.into(),
label: "Desk Steel".into(),
kind: AssetKind::Material,
source_fingerprint: None,
import_settings: shared::AssetImportSettings::None,
dependencies: Vec::new(),
},
],
..Default::default()
};
let part = |id: &str, material_index: usize| StaticMeshPart {
id: id.into(),
name: id.into(),
mesh_label: format!("Mesh{material_index}/Primitive0"),
material_id: Some(material_id_from_label(&format!("Material{material_index}"))),
material_slot_name: "Desk Steel".into(),
material_label: Some(format!("Material{material_index}")),
local_transform: Transform::default(),
source_node: None,
source_mesh: None,
source_material: Some("Desk Steel".into()),
skinned: false,
};
let manifest = StaticMeshManifest {
schema_version: crate::assets::static_mesh::STATIC_MESH_MANIFEST_SCHEMA,
asset_id: document.records[0].id.as_string(),
label: "Desk".into(),
source: StaticMeshSource {
path: model_path.into(),
format: "gltf".into(),
fingerprint: shared::AssetSourceFingerprint::from_bytes(b"desk"),
dependencies: Vec::new(),
},
import: StaticMeshImportSnapshot {
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: ModelPlacementMode::StaticAsset,
hierarchy_mode: ModelHierarchyMode::SingleActor,
material_policy: Default::default(),
material_slots: Vec::new(),
orphaned_material_slots: Vec::new(),
},
metadata: StaticMeshMetadata {
mesh_count: 3,
material_count: 2,
node_count: 3,
animation_count: 0,
skin_count: 0,
light_count: 0,
camera_count: 0,
},
parts: vec![part("draw:a", 0), part("draw:b", 0), part("draw:c", 1)],
warnings: Vec::new(),
};
let mapped = bind_extracted_material_slots(
&mut document,
model_path,
&manifest,
&[ExtractedMaterialBinding {
source_index: 0,
path: material_path.into(),
}],
)
.unwrap();
assert_eq!(mapped, 2);
let slots = &document.records[0].model_import().material_slots;
assert_eq!(slots.len(), 2);
assert!(slots.iter().all(|slot| {
matches!(
&slot.selection,
ModelMaterialSelection::Project(reference)
if reference.0.asset_id == material_id.as_string()
&& reference.0.source_path.as_deref() == Some(material_path)
)
}));
}
@@ -0,0 +1,557 @@
use super::*;
pub(super) fn asset_toolbar(world: &mut World, ui: &mut egui::Ui) {
let current_folder = world.resource::<EditorAssets>().current_folder.clone();
let selection_count = world.resource::<EditorAssets>().selections.len();
let has_editable_selection = !selected_content_paths(world).is_empty();
let can_rename = selection_count == 1 && has_editable_selection;
ui.horizontal(|ui| {
if icon_button_small(ui, icons::ARROWS_CLOCKWISE, "Refresh").clicked() {
crate::assets::refresh_content_browser(world);
}
let pending_repairs = world
.get_resource::<PendingExternalMoveRepair>()
.and_then(|pending| pending.review.as_ref())
.map_or(0, |review| review.conflicts.len());
if ui
.add_enabled(
pending_repairs > 0,
egui::Button::new(format!("Resolve Moves ({pending_repairs})")),
)
.on_hover_text("Choose which stable asset identities match ambiguous external moves")
.clicked()
{
if let Some(review) = world
.resource_mut::<PendingExternalMoveRepair>()
.review
.as_mut()
{
review.open = true;
}
}
if icon_button_small(ui, icons::UPLOAD, "Import Here").clicked() {
request_import_to_destination(world, current_folder.clone());
}
if ui
.add_enabled(
current_folder != BUILTINS_FOLDER,
egui::Button::new("Import To..."),
)
.clicked()
{
begin_import_to(world);
}
if icon_button_small(ui, icons::ARROW_UP, "Parent folder").clicked() {
navigate_to_parent(world);
}
if ui
.add_enabled(
current_folder != BUILTINS_FOLDER,
egui::Button::new("New Folder"),
)
.clicked()
{
begin_new_folder(world, current_folder.clone());
}
if ui
.add_enabled(can_rename, egui::Button::new("Rename"))
.clicked()
{
begin_rename(world);
}
if ui
.add_enabled(has_editable_selection, egui::Button::new("Duplicate"))
.clicked()
{
duplicate_selection(world);
}
let can_undo_content = !world
.resource::<AssetBrowserUiState>()
.content_undo
.is_empty();
if ui
.add_enabled(can_undo_content, egui::Button::new("Undo Content"))
.clicked()
{
undo_last_content_operation(world);
}
if ui
.add_enabled(has_editable_selection, egui::Button::new("Cut"))
.clicked()
{
set_content_clipboard(world, true);
}
if ui
.add_enabled(has_editable_selection, egui::Button::new("Copy"))
.clicked()
{
set_content_clipboard(world, false);
}
let can_paste = world.resource::<AssetBrowserUiState>().clipboard.is_some()
&& world.resource::<EditorAssets>().current_folder != BUILTINS_FOLDER;
if ui
.add_enabled(can_paste, egui::Button::new("Paste"))
.clicked()
{
paste_content_clipboard(world);
}
if ui.small_button("Open Trash").clicked() {
world.resource_mut::<AssetBrowserUiState>().show_trash = true;
}
ui.separator();
let visible_results_changed = {
let mut state = world.resource_mut::<AssetBrowserUiState>();
let mut visible_results_changed = ui
.add(
egui::TextEdit::singleline(&mut state.search)
.hint_text("Search assets...")
.desired_width(fit_width(ui, 120.0, 190.0)),
)
.changed();
visible_results_changed |= ui.checkbox(&mut state.recursive, "Subfolders").changed();
let previous_kind_filter = state.kind_filter;
egui::ComboBox::from_id_salt("asset_kind_filter")
.selected_text(kind_filter_label(state.kind_filter))
.show_ui(ui, |ui| {
ui.selectable_value(&mut state.kind_filter, AssetKindFilter::All, "All");
ui.selectable_value(&mut state.kind_filter, AssetKindFilter::Model, "Models");
ui.selectable_value(
&mut state.kind_filter,
AssetKindFilter::Texture,
"Textures",
);
ui.selectable_value(
&mut state.kind_filter,
AssetKindFilter::Material,
"Materials",
);
ui.selectable_value(&mut state.kind_filter, AssetKindFilter::Audio, "Audio");
ui.selectable_value(&mut state.kind_filter, AssetKindFilter::Level, "Levels");
ui.selectable_value(&mut state.kind_filter, AssetKindFilter::Prefab, "Prefabs");
ui.selectable_value(
&mut state.kind_filter,
AssetKindFilter::Builtin,
"Built-ins",
);
});
visible_results_changed |= state.kind_filter != previous_kind_filter;
egui::ComboBox::from_id_salt("asset_sort")
.selected_text(sort_label(state.sort))
.show_ui(ui, |ui| {
ui.selectable_value(&mut state.sort, AssetSort::Name, "Name");
ui.selectable_value(&mut state.sort, AssetSort::Kind, "Type");
ui.selectable_value(&mut state.sort, AssetSort::Modified, "Modified");
ui.selectable_value(&mut state.sort, AssetSort::Size, "Size");
});
ui.separator();
if tool_button(
ui,
icons::GRID_FOUR,
state.view == AssetBrowserView::Grid,
"Grid view",
)
.clicked()
{
state.view = AssetBrowserView::Grid;
}
if tool_button(
ui,
icons::LIST,
state.view == AssetBrowserView::List,
"List view",
)
.clicked()
{
state.view = AssetBrowserView::List;
}
if ui.available_width() > 180.0 {
ui.label(icon_text(icons::IMAGE_SQUARE, 13.0).color(TEXT_DIM));
ui.add_sized(
[96.0, 20.0],
egui::Slider::new(&mut state.thumbnail_size, 48.0..=112.0).show_value(false),
);
}
ui.checkbox(&mut state.show_details, "Details");
visible_results_changed
};
clear_selection_when_visible_results_change(world, visible_results_changed);
});
}
pub(super) fn clear_selection_when_visible_results_change(world: &mut World, changed: bool) {
if changed && !world.resource::<EditorAssets>().selections.is_empty() {
let mut assets = world.resource_mut::<EditorAssets>();
assets.clear_selection();
assets.status = "Selection cleared because visible results changed".into();
}
}
pub(super) fn request_import_to_destination(world: &mut World, destination: String) {
let destination = if destination == BUILTINS_FOLDER {
ASSETS_ROOT.to_string()
} else {
destination
};
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::ImportAssets { destination });
}
pub(super) fn begin_import_to(world: &mut World) {
let current = world.resource::<EditorAssets>().current_folder.clone();
let destination = if current == BUILTINS_FOLDER {
ASSETS_ROOT.to_string()
} else {
current
};
world
.resource_mut::<AssetBrowserUiState>()
.pending_import_destination = Some(destination);
}
pub(super) fn draw_import_to_modal(world: &mut World, context: &egui::Context) {
let Some(selected) = world
.resource::<AssetBrowserUiState>()
.pending_import_destination
.clone()
else {
return;
};
let mut folders = world
.resource::<EditorAssets>()
.folders
.iter()
.filter(|folder| {
folder.path == ASSETS_ROOT || folder.path.starts_with(&format!("{ASSETS_ROOT}/"))
})
.map(|folder| (folder.path.clone(), folder.name.clone()))
.collect::<Vec<_>>();
folders.sort_by(|left, right| left.0.cmp(&right.0));
let mut action = context
.input(|input| input.key_pressed(egui::Key::Escape))
.then_some(false);
let mut next_selection = None;
egui::Window::new("Import To Project Folder")
.id(egui::Id::new("asset_browser_import_to"))
.collapsible(false)
.resizable(true)
.default_width(460.0)
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
.show(context, |ui| {
ui.label("Choose the destination beneath the managed project content root.");
ui.add_space(8.0);
egui::ScrollArea::vertical()
.id_salt("asset_browser_import_to_folders")
.max_height(320.0)
.auto_shrink([false, false])
.show(ui, |ui| {
for (path, name) in &folders {
let depth = path.matches('/').count();
ui.horizontal(|ui| {
ui.add_space(depth.saturating_sub(1) as f32 * 14.0);
if ui
.selectable_label(path == &selected, format!("{name} — {path}"))
.clicked()
{
next_selection = Some(path.clone());
}
});
}
});
ui.add_space(8.0);
ui.label(format!("Destination: {selected}"));
ui.small(
egui::RichText::new(
"Imported files keep their source names here; safe dependency-relative bundle paths are preserved.",
)
.color(TEXT_DIM),
);
ui.add_space(12.0);
ui.horizontal(|ui| {
if ui.button("Cancel").clicked() {
action = Some(false);
}
if ui.button("Choose Files...").clicked() {
action = Some(true);
}
});
});
if let Some(next_selection) = next_selection {
world
.resource_mut::<AssetBrowserUiState>()
.pending_import_destination = Some(next_selection);
}
match action {
Some(true) => {
world
.resource_mut::<AssetBrowserUiState>()
.pending_import_destination = None;
request_import_to_destination(world, selected);
}
Some(false) => {
world
.resource_mut::<AssetBrowserUiState>()
.pending_import_destination = None;
}
None => {}
}
}
pub(crate) fn draw_asset_import_review_modal(world: &mut World, context: &egui::Context) {
let Some(pending) = world
.resource::<crate::scene_io::PendingAssetImportReview>()
.0
.clone()
else {
return;
};
let plan = &pending.plan;
let mut action = context
.input(|input| input.key_pressed(egui::Key::Escape))
.then_some(false);
egui::Window::new("Review Asset Import")
.id(egui::Id::new("asset_import_transaction_review"))
.collapsible(false)
.resizable(true)
.default_width(640.0)
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
.show(context, |ui| {
ui.label(format!("Destination: {}", plan.destination.display()));
ui.small(
egui::RichText::new(
"Every source dependency and final project path is fingerprinted before the batch publishes.",
)
.color(TEXT_DIM),
);
ui.add_space(8.0);
egui::ScrollArea::vertical()
.id_salt("asset_import_transaction_entries")
.max_height(360.0)
.auto_shrink([false, false])
.show(ui, |ui| {
for entry in &plan.entries {
egui::Frame::new()
.fill(WIDGET_BG.linear_multiply(0.8))
.stroke(egui::Stroke::new(1.0_f32, BORDER))
.corner_radius(egui::CornerRadius::same(4))
.inner_margin(egui::Margin::symmetric(8, 6))
.show(ui, |ui| {
ui.label(egui::RichText::new(entry.source.display().to_string()).strong());
if entry.adopt_in_place {
ui.small("Adopt existing project file in place");
} else {
for target in &entry.targets {
ui.small(format!("→ {}", target.display()));
}
}
if entry.source_files.len() > 1 {
ui.small(
egui::RichText::new(format!(
"{} source bundle files",
entry.source_files.len()
))
.color(TEXT_DIM),
);
}
});
ui.add_space(4.0);
}
});
if !plan.conflicts.is_empty() {
ui.add_space(8.0);
ui.colored_label(egui::Color32::LIGHT_RED, "Resolve these collisions before import:");
for conflict in &plan.conflicts {
ui.colored_label(egui::Color32::LIGHT_RED, format!("• {conflict}"));
}
}
ui.add_space(12.0);
ui.horizontal(|ui| {
if ui.button("Cancel").clicked() {
action = Some(false);
}
if ui
.add_enabled(
plan.can_commit(),
egui::Button::new(format!("Import {} Asset(s)", plan.imported_count())),
)
.clicked()
{
action = Some(true);
}
});
});
match action {
Some(false) => {
world
.resource_mut::<crate::scene_io::PendingAssetImportReview>()
.0 = None;
world.resource_mut::<SceneIo>().status = pending.previous_status;
}
Some(true) => match commit_reviewed_asset_import(world, plan) {
Ok(count) => {
world
.resource_mut::<crate::scene_io::PendingAssetImportReview>()
.0 = None;
world.resource_mut::<EditorAssets>().refresh();
invalidate_on_catalog_refresh(world);
world.resource_mut::<SceneIo>().status = format!("Imported {count} asset(s)");
}
Err(error) => {
world.resource_mut::<SceneIo>().status = format!("Import failed: {error}");
}
},
None => {}
}
}
pub(super) fn commit_reviewed_asset_import(
world: &mut World,
plan: &crate::assets::ExternalAssetImportPlan,
) -> Result<usize, String> {
let previous = world.resource::<AssetRegistry>().document();
let imported_paths = plan
.entries
.iter()
.flat_map(|entry| entry.targets.iter())
.map(|path| path.to_string_lossy().replace('\\', "/"))
.collect::<HashSet<_>>();
let mut files_committed = false;
let mut publication_backups: Vec<(PathBuf, Option<Vec<u8>>)> = Vec::new();
crate::assets::begin_content_watch_transaction(world);
let result: Result<(usize, AssetRegistryDocument), String> = (|| {
let count = crate::assets::commit_external_assets_import(plan)?;
files_committed = true;
let mut processed = content_pipeline::scan_project(&plan.project_root, &previous)?;
let mut model_plans = Vec::new();
for record in processed.registry.records.iter_mut().filter(|record| {
record.kind == AssetKind::Model && imported_paths.contains(&record.path)
}) {
let model_plan = crate::assets::plan_model_artifacts_at(&plan.project_root, record)
.map_err(|error| {
format!("could not process imported model {}: {error}", record.path)
})?;
*record = model_plan.record.clone();
model_plans.push(model_plan);
}
processed.runtime_catalog = shared::RuntimeContentCatalog::from(&processed.registry);
let mut texture_plans = Vec::new();
for record in processed
.registry
.records
.iter()
.filter(|record| record.kind == AssetKind::Texture)
{
let texture_plan = content_pipeline::plan_texture_artifact(&plan.project_root, record)
.map_err(|error| format!("could not process Texture {}: {error}", record.path))?;
content_pipeline::apply_texture_plan_to_catalog(
&mut processed.runtime_catalog,
&record.id,
&texture_plan,
)?;
texture_plans.push(texture_plan);
}
let mut material_plans = Vec::new();
for record in processed.registry.records.iter().filter(|record| {
matches!(
record.kind,
AssetKind::Material | AssetKind::MaterialInstance
)
}) {
if let Some(material_plan) = content_pipeline::plan_material_artifact(
&plan.project_root,
record,
&processed.registry,
)? {
content_pipeline::apply_material_plan_to_catalog(
&mut processed.runtime_catalog,
&record.id,
&material_plan,
)?;
material_plans.push(material_plan);
}
}
let mut publication_paths = model_plans
.iter()
.flat_map(|model_plan| {
[
model_plan.static_path.clone(),
model_plan.animation_path.clone(),
]
})
.collect::<Vec<_>>();
publication_paths.extend(
texture_plans
.iter()
.map(|texture_plan| texture_plan.output_path.clone()),
);
publication_paths.extend(
material_plans
.iter()
.map(|material_plan| material_plan.output_path.clone()),
);
publication_paths.push(plan.project_root.join(content_pipeline::REGISTRY_PATH));
publication_paths.push(
plan.project_root
.join(content_pipeline::RUNTIME_CATALOG_PATH),
);
publication_paths.sort();
publication_paths.dedup();
publication_backups = publication_paths
.iter()
.map(|path| (path.clone(), fs::read(path).ok()))
.collect();
for model_plan in &model_plans {
crate::assets::publish_model_artifacts(model_plan)?;
}
for texture_plan in &texture_plans {
content_pipeline::publish_texture_artifact(texture_plan)?;
}
for material_plan in &material_plans {
content_pipeline::publish_material_artifact(material_plan)?;
}
content_pipeline::publish_content_documents_with_catalog(
&plan.project_root,
&processed.registry,
&processed.runtime_catalog,
)?;
Ok((count, processed.registry))
})();
let result = match result {
Ok((count, document)) => {
apply_registry_document(world, document);
Ok(count)
}
Err(error) => {
for (path, bytes) in publication_backups.iter().rev() {
restore_import_publication_file(path, bytes.as_deref());
}
let rollback_error = files_committed
.then(|| crate::assets::rollback_external_assets_import(plan))
.and_then(Result::err);
Err(match rollback_error {
Some(rollback_error) => format!(
"import processing failed: {error}; file rollback was incomplete: {rollback_error}"
),
None => format!("import processing rolled back: {error}"),
})
}
};
crate::assets::end_content_watch_transaction(world);
result
}
pub(super) fn restore_import_publication_file(path: &Path, bytes: Option<&[u8]>) {
if let Some(bytes) = bytes {
let _ = fs::write(path, bytes);
} else {
let _ = fs::remove_file(path);
}
}
@@ -0,0 +1,725 @@
use super::*;
pub(super) fn build_content_undo_entry(
project_root: &Path,
preview: &content_pipeline::ContentTransactionPreview,
) -> Option<ContentUndoEntry> {
let all_replacements = preview.operations.iter().all(|operation| {
matches!(
operation,
content_pipeline::ContentOperation::ReplaceFile { .. }
)
});
let all_moves = preview
.operations
.iter()
.all(|operation| matches!(operation, content_pipeline::ContentOperation::Move { .. }));
let (label, action, guarded_paths) = if all_replacements {
let inverse_operations = preview
.operations
.iter()
.rev()
.filter_map(|operation| match operation {
content_pipeline::ContentOperation::ReplaceFile {
path,
bytes,
previous_bytes,
..
} => Some(content_pipeline::ContentOperation::ReplaceFile {
path: path.clone(),
bytes: previous_bytes.clone(),
expected_fingerprint: content_pipeline::tree_fingerprint(
&project_root.join(path),
)
.ok()?,
previous_bytes: bytes.clone(),
}),
_ => None,
})
.collect::<Vec<_>>();
if inverse_operations.len() != preview.operations.len() {
return None;
}
let guarded_paths = inverse_operations
.iter()
.filter_map(|operation| match operation {
content_pipeline::ContentOperation::ReplaceFile { path, .. } => Some(path.clone()),
_ => None,
})
.collect::<Vec<_>>();
(
format!("Apply {} Material update(s)", inverse_operations.len()),
ContentUndoAction::Apply(inverse_operations),
guarded_paths,
)
} else if all_moves {
let inverse_operations: Vec<_> = preview
.operations
.iter()
.rev()
.filter_map(|operation| match operation {
content_pipeline::ContentOperation::Move {
source,
destination,
} => Some(content_pipeline::ContentOperation::Move {
source: destination.clone(),
destination: source.clone(),
}),
_ => None,
})
.collect();
if inverse_operations.is_empty() {
return None;
}
let guarded_paths = inverse_operations
.iter()
.filter_map(|operation| match operation {
content_pipeline::ContentOperation::Move { source, .. } => Some(source.clone()),
_ => None,
})
.collect::<Vec<_>>();
(
format!("Move {} content item(s)", inverse_operations.len()),
ContentUndoAction::Apply(inverse_operations),
guarded_paths,
)
} else {
let mut created_paths = Vec::with_capacity(preview.operations.len());
let mut copy_count = 0;
let mut folder_count = 0;
for operation in &preview.operations {
match operation {
content_pipeline::ContentOperation::CreateFolder { path } => {
folder_count += 1;
created_paths.push(path.clone());
}
content_pipeline::ContentOperation::Copy { destination, .. } => {
copy_count += 1;
created_paths.push(destination.clone());
}
content_pipeline::ContentOperation::WriteFile { path, .. } => {
created_paths.push(path.clone());
}
content_pipeline::ContentOperation::ReplaceFile { .. } => return None,
content_pipeline::ContentOperation::Move { .. } => return None,
}
}
if created_paths.is_empty() {
return None;
}
let label = if copy_count == preview.operations.len() {
format!("Copy {copy_count} content item(s)")
} else if folder_count == preview.operations.len() {
format!("Create {folder_count} folder(s)")
} else {
format!("Create {} content item(s)", created_paths.len())
};
(
label,
ContentUndoAction::TrashCreated(created_paths.clone()),
created_paths,
)
};
let guarded_sources = guarded_paths
.into_iter()
.filter_map(|path| {
content_pipeline::tree_fingerprint(&project_root.join(&path))
.ok()
.map(|fingerprint| (path, fingerprint))
})
.collect::<Vec<_>>();
let expected_guard_count = match &action {
ContentUndoAction::Apply(operations) => operations.len(),
ContentUndoAction::TrashCreated(paths) => paths.len(),
ContentUndoAction::RestoreTrash(_) => 1,
};
(guarded_sources.len() == expected_guard_count).then_some(ContentUndoEntry {
label,
action,
guarded_sources,
})
}
pub(super) fn undo_last_content_operation(world: &mut World) {
let Some(entry) = world
.resource::<AssetBrowserUiState>()
.content_undo
.last()
.cloned()
else {
return;
};
if let Some(path) = first_changed_content_undo_source(Path::new("."), &entry) {
world.resource_mut::<SceneIo>().status = format!(
"Cannot undo {}: {} changed outside the transaction",
entry.label,
path.display()
);
return;
}
let undone = match &entry.action {
ContentUndoAction::Apply(operations) => {
commit_content_operations_internal(world, operations.clone(), false)
}
ContentUndoAction::TrashCreated(paths) => trash_created_content_for_undo(world, paths),
ContentUndoAction::RestoreTrash(batch_path) => {
restore_trashed_content_for_undo(world, batch_path)
}
};
if undone {
world
.resource_mut::<AssetBrowserUiState>()
.content_undo
.pop();
world.resource_mut::<SceneIo>().status = format!("Undid {}", entry.label);
}
}
pub(super) fn first_changed_content_undo_source(
project_root: &Path,
entry: &ContentUndoEntry,
) -> Option<PathBuf> {
entry.guarded_sources.iter().find_map(|(path, expected)| {
let actual = content_pipeline::tree_fingerprint(&project_root.join(path));
(actual.as_deref() != Ok(expected.as_str())).then(|| path.clone())
})
}
pub(super) fn trash_created_content_for_undo(world: &mut World, paths: &[PathBuf]) -> bool {
let mut document = world
.resource::<crate::asset_db::AssetRegistry>()
.document();
crate::assets::begin_content_watch_transaction(world);
let trash_result = content_pipeline::trash_content(Path::new("."), paths, &mut document);
crate::assets::end_content_watch_transaction(world);
if let Err(error) = trash_result {
world.resource_mut::<SceneIo>().status = error;
return false;
}
apply_registry_document(world, document);
let current_folder = world.resource::<EditorAssets>().current_folder.clone();
{
let mut assets = world.resource_mut::<EditorAssets>();
assets.clear_selection();
assets.refresh();
if !Path::new(&current_folder).is_dir() {
assets.current_folder = nearest_existing_content_folder(&current_folder);
}
}
invalidate_on_catalog_refresh(world);
true
}
pub(super) fn restore_trashed_content_for_undo(world: &mut World, batch_path: &Path) -> bool {
let mut document = world
.resource::<crate::asset_db::AssetRegistry>()
.document();
crate::assets::begin_content_watch_transaction(world);
let restore_result =
content_pipeline::restore_trash_batch(Path::new("."), batch_path, &mut document);
crate::assets::end_content_watch_transaction(world);
let restored = match restore_result {
Ok(restored) => restored,
Err(error) => {
world.resource_mut::<SceneIo>().status = error;
return false;
}
};
apply_registry_document(world, document);
let selections = restored
.original_paths
.iter()
.map(|path| {
if Path::new(path).is_dir() {
AssetSelection::Folder(path.clone())
} else {
AssetSelection::File(path.clone())
}
})
.collect::<Vec<_>>();
{
let mut assets = world.resource_mut::<EditorAssets>();
assets.refresh();
assets.select_all(&selections);
}
invalidate_on_catalog_refresh(world);
true
}
pub(super) fn nearest_existing_content_folder(folder: &str) -> String {
let mut candidate = Path::new(folder);
loop {
if candidate.is_dir() && candidate.starts_with(ASSETS_ROOT) {
return candidate.to_string_lossy().replace('\\', "/");
}
let Some(parent) = candidate.parent() else {
return ASSETS_ROOT.into();
};
candidate = parent;
}
}
pub(super) fn request_delete_for_asset(world: &mut World, asset: &EditorAsset) {
let selection = AssetSelection::from_asset(asset);
if !world.resource::<EditorAssets>().is_selected(&selection) {
world.resource_mut::<EditorAssets>().select(selection);
}
request_delete_for_selection(world);
}
pub(super) fn request_delete_for_selection(world: &mut World) {
if let Some(request) = build_delete_request(world) {
world.resource_mut::<AssetBrowserUiState>().pending_delete = Some(request);
}
}
pub(super) fn external_move_choices_valid(
review: &crate::assets::ExternalMoveRepairReview,
) -> bool {
if review.choices.len() != review.conflicts.len() || review.choices.iter().any(Option::is_none)
{
return false;
}
let mut preserved = HashSet::new();
review
.conflicts
.iter()
.zip(&review.choices)
.all(|(conflict, choice)| match choice {
Some(ExternalMoveRepairChoice::Preserve(path)) => {
conflict.candidate_paths.contains(path) && preserved.insert(path)
}
Some(ExternalMoveRepairChoice::RegisterNew) => true,
None => false,
})
}
pub(super) fn draw_external_move_repair_modal(world: &mut World, ctx: &egui::Context) {
let Some(mut review) = world
.get_resource::<PendingExternalMoveRepair>()
.and_then(|pending| pending.review.clone())
.filter(|review| review.open)
else {
return;
};
let mut action = None;
egui::Window::new("Resolve Ambiguous External Moves")
.collapsible(false)
.resizable(true)
.default_width(620.0)
.show(ctx, |ui| {
ui.label(
"The same imported bytes match multiple missing registry records. Choose which stable identity moved to each new path.",
);
ui.small(
egui::RichText::new(
"Register as New intentionally assigns a fresh ID. No registry or manifest changes are published until every row is resolved.",
)
.color(TEXT_DIM),
);
ui.separator();
egui::ScrollArea::vertical()
.id_salt("external_move_repair_rows")
.max_height(420.0)
.auto_shrink([false, true])
.show(ui, |ui| {
for (index, conflict) in review.conflicts.iter().enumerate() {
ui.group(|ui| {
ui.label(egui::RichText::new(&conflict.new_path).strong());
ui.small(format!(
"{:?} · {} candidate identities",
conflict.kind,
conflict.candidate_paths.len()
));
let selected_text = match review.choices.get(index).and_then(Option::as_ref) {
Some(ExternalMoveRepairChoice::Preserve(path)) => {
format!("Preserve ID from {path}")
}
Some(ExternalMoveRepairChoice::RegisterNew) => {
"Register as New Asset".into()
}
None => "Choose stable identity…".into(),
};
egui::ComboBox::from_id_salt(("external_move_choice", index))
.selected_text(selected_text)
.width(ui.available_width().max(240.0))
.show_ui(ui, |ui| {
for candidate in &conflict.candidate_paths {
let used_elsewhere = review
.choices
.iter()
.enumerate()
.any(|(other_index, choice)| {
other_index != index
&& choice.as_ref()
== Some(&ExternalMoveRepairChoice::Preserve(
candidate.clone(),
))
});
ui.add_enabled_ui(!used_elsewhere, |ui| {
ui.selectable_value(
&mut review.choices[index],
Some(ExternalMoveRepairChoice::Preserve(
candidate.clone(),
)),
format!("Preserve ID from {candidate}"),
);
});
}
ui.separator();
ui.selectable_value(
&mut review.choices[index],
Some(ExternalMoveRepairChoice::RegisterNew),
"Register as New Asset",
);
});
});
ui.add_space(6.0);
}
});
ui.separator();
ui.horizontal(|ui| {
if ui.button("Review Later").clicked() {
action = Some(false);
}
if ui
.add_enabled(
external_move_choices_valid(&review),
egui::Button::new("Apply Identity Repairs"),
)
.clicked()
{
action = Some(true);
}
});
});
match action {
Some(false) => review.open = false,
Some(true) => {}
None => {}
}
world.resource_mut::<PendingExternalMoveRepair>().review = Some(review);
if action == Some(true) {
if let Err(error) = crate::assets::commit_external_move_repairs(world) {
world.resource_mut::<SceneIo>().status =
format!("External move repair failed: {error}");
}
}
}
pub(super) fn build_delete_request(world: &World) -> Option<AssetDeleteRequest> {
let assets = world.resource::<EditorAssets>();
let selections: Vec<AssetSelection> = assets
.selections
.iter()
.filter(|selection| {
authored_content_path(selection)
.is_some_and(|path| !matches!(path, ASSETS_ROOT | BUILTINS_FOLDER))
})
.cloned()
.collect();
if selections.is_empty() {
return None;
}
let selected_paths: Vec<String> = selected_content_paths(world);
let mut files = selected_paths.clone();
let mut warnings = Vec::new();
for selection in &selections {
let Some(asset) = assets.asset_for_selection(selection) else {
continue;
};
let Some(path) = asset.path.as_deref() else {
continue;
};
if !matches!(asset.kind, EditorAssetKind::Model) {
continue;
}
if let Some(record) = world
.get_resource::<crate::asset_db::AssetRegistry>()
.and_then(|registry| find_asset_by_path(registry, path))
{
let settings = record.model_import();
if let Some(manifest) = settings.static_mesh_manifest_path.clone() {
files.push(manifest);
}
if let Some(manifest) = settings.animation_manifest_path.clone() {
files.push(manifest);
}
if !record.dependencies.is_empty() {
warnings.push(format!(
"{} imported dependencies will be kept because they may be shared.",
record.dependencies.len()
));
}
}
}
if let Some(registry) = world.get_resource::<crate::asset_db::AssetRegistry>() {
let sources = selected_paths.iter().map(PathBuf::from).collect::<Vec<_>>();
match content_pipeline::find_reference_usages(
Path::new("."),
&sources,
&registry.document(),
) {
Ok(usages) if !usages.is_empty() => {
warnings.push(format!(
"{} external reference(s) will become unresolved:",
usages.len()
));
warnings.extend(
usages
.into_iter()
.map(|usage| format!("{} — {}", usage.document.display(), usage.reference)),
);
}
Ok(_) => {}
Err(error) => warnings.push(format!(
"Reference usage scan failed; review could be incomplete: {error}"
)),
}
}
dedup_strings(&mut files);
let label = if selections.len() == 1 {
selections[0].display_label().to_string()
} else {
format!("{} selected items", selections.len())
};
Some(AssetDeleteRequest {
label,
files,
warnings,
})
}
pub(super) fn draw_delete_modal(world: &mut World, ctx: &egui::Context) {
let pending = world
.resource::<AssetBrowserUiState>()
.pending_delete
.clone();
let Some(request) = pending else {
return;
};
let mut action = None;
egui::Window::new("Move Content To Trash")
.collapsible(false)
.resizable(false)
.default_width(360.0)
.show(ctx, |ui| {
ui.label(format!("Move {} to assets/.trash?", request.label));
ui.separator();
ui.label(panel_heading("Files"));
for file in &request.files {
ui.add(egui::Label::new(file).wrap());
}
if !request.warnings.is_empty() {
ui.separator();
ui.label(panel_heading("Warnings"));
for warning in &request.warnings {
ui.small(egui::RichText::new(warning).color(TEXT_DIM));
}
}
ui.separator();
ui.horizontal(|ui| {
if ui.button("Cancel").clicked() {
action = Some(false);
}
if ui.button("Move To Trash").clicked() {
action = Some(true);
}
});
});
match action {
Some(false) => {
world.resource_mut::<AssetBrowserUiState>().pending_delete = None;
}
Some(true) => {
execute_delete_request(world, &request);
world.resource_mut::<AssetBrowserUiState>().pending_delete = None;
}
None => {}
}
}
pub(super) fn draw_trash_modal(world: &mut World, ctx: &egui::Context) {
if !world.resource::<AssetBrowserUiState>().show_trash {
return;
}
let batches = content_pipeline::list_trash_batches(Path::new("."));
let mut close = false;
let mut restore = None;
egui::Window::new("Content Trash")
.collapsible(false)
.resizable(true)
.default_width(520.0)
.min_width(380.0)
.show(ctx, |ui| {
ui.label("Restore a complete transaction to its original project paths.");
ui.small(
egui::RichText::new(
"Restore is blocked when a destination or stable registry ID is already in use.",
)
.color(TEXT_DIM),
);
ui.separator();
match &batches {
Err(error) => {
ui.label(egui::RichText::new(error).color(ERROR));
}
Ok(batches) if batches.is_empty() => {
ui.label(egui::RichText::new("Trash is empty.").color(TEXT_DIM));
}
Ok(batches) => {
egui::ScrollArea::vertical()
.max_height(420.0)
.show(ui, |ui| {
for batch in batches {
egui::Frame::group(ui.style()).show(ui, |ui| {
ui.horizontal(|ui| {
ui.strong(&batch.batch_id);
ui.with_layout(
egui::Layout::right_to_left(egui::Align::Center),
|ui| {
if ui.button("Restore").clicked() {
restore = Some(batch.clone());
}
},
);
});
for path in &batch.original_paths {
ui.small(path);
}
});
ui.add_space(4.0);
}
});
}
}
ui.separator();
if ui.button("Close").clicked() {
close = true;
}
});
if let Some(batch) = restore {
let mut document = world
.resource::<crate::asset_db::AssetRegistry>()
.document();
crate::assets::begin_content_watch_transaction(world);
let restore_result =
content_pipeline::restore_trash_batch(Path::new("."), &batch.path, &mut document);
crate::assets::end_content_watch_transaction(world);
match restore_result {
Ok(restored) => {
apply_registry_document(world, document);
forget_restored_trash_undo(
&mut world.resource_mut::<AssetBrowserUiState>(),
&batch.path,
);
let selections = restored
.original_paths
.iter()
.map(|path| {
if Path::new(path).is_dir() {
AssetSelection::Folder(path.clone())
} else {
AssetSelection::File(path.clone())
}
})
.collect::<Vec<_>>();
{
let mut assets = world.resource_mut::<EditorAssets>();
assets.refresh();
assets.select_all(&selections);
}
invalidate_on_catalog_refresh(world);
world.resource_mut::<SceneIo>().status = format!(
"Restored {} content item(s) from Trash",
restored.original_paths.len()
);
}
Err(error) => world.resource_mut::<SceneIo>().status = error,
}
}
if close {
world.resource_mut::<AssetBrowserUiState>().show_trash = false;
}
}
pub(super) fn forget_restored_trash_undo(state: &mut AssetBrowserUiState, batch_path: &Path) {
state.content_undo.retain(|entry| {
!matches!(
&entry.action,
ContentUndoAction::RestoreTrash(path) if path == batch_path
)
});
}
pub(super) fn execute_delete_request(world: &mut World, request: &AssetDeleteRequest) {
let paths = request
.files
.iter()
.map(PathBuf::from)
.filter(|path| path.exists())
.collect::<Vec<_>>();
let mut document = world
.resource::<crate::asset_db::AssetRegistry>()
.document();
crate::assets::begin_content_watch_transaction(world);
let trash_result = content_pipeline::trash_content(Path::new("."), &paths, &mut document);
crate::assets::end_content_watch_transaction(world);
let batch = match trash_result {
Ok(batch) => batch,
Err(error) => {
world.resource_mut::<SceneIo>().status = error;
return;
}
};
apply_registry_document(world, document);
if let Ok(fingerprint) = content_pipeline::tree_fingerprint(&batch.path) {
push_content_undo(
world,
ContentUndoEntry {
label: format!("Move {} to Trash", request.label),
action: ContentUndoAction::RestoreTrash(batch.path.clone()),
guarded_sources: vec![(batch.path.clone(), fingerprint)],
},
);
}
{
let mut assets = world.resource_mut::<EditorAssets>();
assets.clear_selection();
assets.refresh();
}
invalidate_on_catalog_refresh(world);
world.resource_mut::<SceneIo>().status = format!(
"Moved {} file(s) for {} to {} (restorable from Trash)",
paths.len(),
request.label,
batch.path.to_string_lossy()
);
}
pub(super) fn push_content_undo(world: &mut World, entry: ContentUndoEntry) {
let mut state = world.resource_mut::<AssetBrowserUiState>();
state.content_undo.push(entry);
if state.content_undo.len() > 32 {
state.content_undo.remove(0);
}
}
pub(super) fn apply_registry_document(world: &mut World, document: shared::AssetRegistryDocument) {
let mut registry = world.resource_mut::<crate::asset_db::AssetRegistry>();
registry.schema_version = document.schema_version;
registry.defaults = document.defaults;
registry.records = document.records;
registry.index_dirty = false;
registry.migration_required = false;
}
pub(super) fn dedup_strings(values: &mut Vec<String>) {
let mut seen = HashSet::new();
values.retain(|value| seen.insert(value.clone()));
}
@@ -0,0 +1,761 @@
use super::*;
pub(super) fn empty_content(ui: &mut egui::Ui, search: &str) {
ui.add_space(24.0);
ui.vertical_centered(|ui| {
ui.label(
egui::RichText::new(icons::FOLDER_OPEN.as_str()).font(egui::FontId::new(
28.0,
egui::FontFamily::Name("phosphor-regular".into()),
)),
);
if search.trim().is_empty() {
ui.label(egui::RichText::new("Folder is empty").color(TEXT_DIM));
} else {
ui.label(egui::RichText::new("No matching assets").color(TEXT_DIM));
}
});
}
pub(super) fn navigate_to_parent(world: &mut World) {
let current = world.resource::<EditorAssets>().current_folder.clone();
if let Some(parent) = current.rfind('/').map(|index| current[..index].to_string()) {
navigate_content_folder(world, parent);
}
}
pub(super) fn navigate_content_folder(world: &mut World, folder: String) {
let mut assets = world.resource_mut::<EditorAssets>();
assets.current_folder = folder.clone();
assets.clear_selection();
assets.clear_drag();
assets.status = format!("Opened {folder}");
}
pub(super) fn locate_content_asset(world: &mut World, path: &str) {
let normalized = path.replace('\\', "/");
let selection = AssetSelection::File(normalized.clone());
if !world
.resource::<EditorAssets>()
.selection_exists(&selection)
{
let status = format!("Referenced project asset is missing: {normalized}");
world.resource_mut::<EditorAssets>().status = status.clone();
if let Some(mut scene_io) = world.get_resource_mut::<SceneIo>() {
scene_io.status = status;
}
return;
}
let parent = Path::new(&normalized)
.parent()
.map(|path| path.to_string_lossy().replace('\\', "/"))
.unwrap_or_else(|| ASSETS_ROOT.to_string());
navigate_content_folder(world, parent);
let mut assets = world.resource_mut::<EditorAssets>();
assets.select(selection);
assets.status = format!("Located {normalized}");
}
pub(super) fn asset_matches_kind_filter(asset: &EditorAsset, filter: AssetKindFilter) -> bool {
match filter {
AssetKindFilter::All => true,
AssetKindFilter::Model => matches!(asset.kind, EditorAssetKind::Model),
AssetKindFilter::Texture => matches!(asset.kind, EditorAssetKind::Texture),
AssetKindFilter::Material => matches!(asset.kind, EditorAssetKind::Material),
AssetKindFilter::Audio => matches!(asset.kind, EditorAssetKind::AudioClip),
AssetKindFilter::Level => matches!(asset.kind, EditorAssetKind::Level),
AssetKindFilter::Prefab => matches!(asset.kind, EditorAssetKind::Prefab),
AssetKindFilter::Builtin => asset.path.is_none(),
}
}
pub(super) fn kind_filter_label(filter: AssetKindFilter) -> &'static str {
match filter {
AssetKindFilter::All => "All",
AssetKindFilter::Model => "Models",
AssetKindFilter::Texture => "Textures",
AssetKindFilter::Material => "Materials",
AssetKindFilter::Audio => "Audio",
AssetKindFilter::Level => "Levels",
AssetKindFilter::Prefab => "Prefabs",
AssetKindFilter::Builtin => "Built-ins",
}
}
pub(super) fn sort_label(sort: AssetSort) -> &'static str {
match sort {
AssetSort::Name => "Name",
AssetSort::Kind => "Type",
AssetSort::Modified => "Modified",
AssetSort::Size => "Size",
}
}
pub(super) fn kind_label(kind: &EditorAssetKind) -> &'static str {
match kind {
EditorAssetKind::Primitive(_) => "Primitive",
EditorAssetKind::Light(_) => "Light",
EditorAssetKind::Model => "Model",
EditorAssetKind::Texture => "Texture",
EditorAssetKind::Material => "Material",
EditorAssetKind::AudioClip => "Audio Clip",
EditorAssetKind::Level => "Level",
EditorAssetKind::Prefab => "Prefab",
EditorAssetKind::PostProcessVolume => "Post Process Volume",
EditorAssetKind::PostProcessEffect => "Post FX",
EditorAssetKind::RenderingProfile => "Rendering Profile",
EditorAssetKind::ShaderSchema => "Shader Schema",
}
}
pub(super) fn file_size(path: &str) -> Option<u64> {
fs::metadata(path).ok().map(|metadata| metadata.len())
}
pub(super) fn audio_format_label(path: &str) -> &'static str {
match Path::new(path)
.extension()
.and_then(|extension| extension.to_str())
.map(str::to_ascii_lowercase)
.as_deref()
{
Some("ogg" | "oga") => "Ogg audio",
Some("spx") => "Speex",
Some("wav") => "WAV",
Some("mp3") => "MP3",
Some("flac") => "FLAC",
_ => "Unknown",
}
}
pub(super) fn modified_time(path: &str) -> Option<SystemTime> {
fs::metadata(path)
.ok()
.and_then(|metadata| metadata.modified().ok())
}
pub(super) fn format_bytes(bytes: u64) -> String {
const KIB: f64 = 1024.0;
const MIB: f64 = KIB * 1024.0;
const GIB: f64 = MIB * 1024.0;
let bytes = bytes as f64;
if bytes >= GIB {
format!("{:.1} GB", bytes / GIB)
} else if bytes >= MIB {
format!("{:.1} MB", bytes / MIB)
} else if bytes >= KIB {
format!("{:.1} KB", bytes / KIB)
} else {
format!("{bytes:.0} B")
}
}
pub(super) fn format_modified(time: SystemTime) -> String {
let Ok(duration) = SystemTime::now().duration_since(time) else {
return "Just now".to_string();
};
let days = duration.as_secs() / 86_400;
if days == 0 {
"Today".to_string()
} else if days == 1 {
"Yesterday".to_string()
} else if days < 30 {
format!("{days} days ago")
} else if days < 365 {
format!("{} months ago", days / 30)
} else {
format!("{} years ago", days / 365)
}
}
pub(super) fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
a.to_ascii_lowercase().cmp(&b.to_ascii_lowercase())
}
pub(super) fn asset_context_menu(
world: &mut World,
ui: &mut egui::Ui,
asset: &EditorAsset,
selected_entities: &SelectedEntities,
) {
let menu_selection = AssetSelection::from_asset(asset);
prepare_context_menu_selection(world, menu_selection);
let selected_count = world.resource::<EditorAssets>().selections.len();
if selected_count > 1 {
ui.label(egui::RichText::new(format!("{selected_count} items selected")).color(TEXT_DIM));
batch_content_menu(world, ui);
return;
}
if ui.button("Select").clicked() {
world
.resource_mut::<EditorAssets>()
.select(AssetSelection::from_asset(asset));
ui.close();
}
if matches!(
asset.kind,
EditorAssetKind::Primitive(_)
| EditorAssetKind::Light(_)
| EditorAssetKind::Model
| EditorAssetKind::AudioClip
| EditorAssetKind::Prefab
) && ui.button("Place at Origin").clicked()
{
place_asset_operator(world, asset.clone(), Vec3::ZERO);
ui.close();
}
if matches!(asset.kind, EditorAssetKind::Level) && ui.button("Open Scene").clicked() {
open_level_asset(world, asset);
ui.close();
}
if matches!(asset.kind, EditorAssetKind::Model) && has_embedded_assets(world, asset) {
let expanded = asset.path.as_deref().is_some_and(|path| {
world
.resource::<AssetBrowserUiState>()
.expanded_assets
.contains(path)
});
if ui
.button(if expanded {
"Collapse Contents"
} else {
"Expand Contents"
})
.clicked()
{
if let Some(path) = asset.path.as_ref() {
toggle_asset_expanded(world, path);
}
ui.close();
}
}
if matches!(asset.kind, EditorAssetKind::Texture)
&& ui.button("Apply as Base Color Texture").clicked()
{
apply_texture_operator(world, asset.clone(), selected_entities);
ui.close();
}
if asset.path.is_some()
&& matches!(asset.kind, EditorAssetKind::Material)
&& ui.button("Apply Material To Selection").clicked()
{
apply_material_operator(world, asset.clone(), selected_entities);
ui.close();
}
if matches!(asset.kind, EditorAssetKind::Material) {
if let Some(path) = asset.path.as_deref() {
if ui.button("Create Material Instance").clicked() {
create_material_instance_from_base(world, path, &asset.label);
ui.close();
}
}
}
if matches!(asset.kind, EditorAssetKind::Model) && ui.button("Reimport").clicked() {
reimport_asset(world, asset);
ui.close();
}
if matches!(
asset.kind,
EditorAssetKind::Texture | EditorAssetKind::Model | EditorAssetKind::Material
) && ui.button("Regenerate Thumbnail").clicked()
{
regenerate_asset_thumbnail(world, asset);
ui.close();
}
if asset.path.is_some() {
ui.separator();
if ui.button("Rename").clicked() {
begin_rename(world);
ui.close();
}
if ui.button("Cut").clicked() {
set_content_clipboard(world, true);
ui.close();
}
if ui.button("Copy").clicked() {
set_content_clipboard(world, false);
ui.close();
}
if ui.button("Duplicate").clicked() {
duplicate_selection(world);
ui.close();
}
ui.separator();
if ui.button("Move To Trash").clicked() {
request_delete_for_asset(world, asset);
ui.close();
}
}
}
pub(super) fn prepare_context_menu_selection(world: &mut World, selection: AssetSelection) {
if !world.resource::<EditorAssets>().is_selected(&selection) {
world.resource_mut::<EditorAssets>().select(selection);
}
}
pub(super) fn batch_content_menu(world: &mut World, ui: &mut egui::Ui) {
let authored_count = selected_content_paths(world).len();
let (nested_count, unaffected_count) = collapsed_and_unaffected_selection_counts(world);
let has_authored_content = authored_count > 0;
if nested_count > 0 {
ui.small(
egui::RichText::new(format!(
"{nested_count} nested item(s) already included by a selected parent"
))
.color(TEXT_DIM),
);
}
if unaffected_count > 0 {
ui.small(
egui::RichText::new(format!(
"{unaffected_count} embedded, built-in, or protected item(s) unaffected"
))
.color(TEXT_DIM),
);
}
let can_undo = !world
.resource::<AssetBrowserUiState>()
.content_undo
.is_empty();
if ui
.add_enabled(can_undo, egui::Button::new("Undo Last Content Operation"))
.clicked()
{
undo_last_content_operation(world);
ui.close();
}
ui.separator();
if ui
.add_enabled(
has_authored_content,
egui::Button::new(format!("Cut {authored_count} Item(s)")),
)
.clicked()
{
set_content_clipboard(world, true);
ui.close();
}
if ui
.add_enabled(
has_authored_content,
egui::Button::new(format!("Copy {authored_count} Item(s)")),
)
.clicked()
{
set_content_clipboard(world, false);
ui.close();
}
if ui
.add_enabled(
has_authored_content,
egui::Button::new(format!("Duplicate {authored_count} Item(s)")),
)
.clicked()
{
duplicate_selection(world);
ui.close();
}
ui.separator();
if ui
.add_enabled(
has_authored_content,
egui::Button::new(format!("Move {authored_count} Item(s) To Trash")),
)
.clicked()
{
request_delete_for_selection(world);
ui.close();
}
}
pub(super) fn folder_context_menu(world: &mut World, ui: &mut egui::Ui, folder: &FolderSnapshot) {
let selected_count = world.resource::<EditorAssets>().selections.len();
if selected_count > 1 {
ui.label(egui::RichText::new(format!("{selected_count} items selected")).color(TEXT_DIM));
batch_content_menu(world, ui);
return;
}
if ui.button("Open").clicked() {
navigate_content_folder(world, folder.path.clone());
ui.close();
}
if folder.path != BUILTINS_FOLDER {
if ui.button("Import Here...").clicked() {
request_import_to_destination(world, folder.path.clone());
ui.close();
}
if ui.button("Import To...").clicked() {
begin_import_to(world);
ui.close();
}
if ui.button("Create Materials From Folder...").clicked() {
begin_pbr_grouping(world, folder.path.clone());
ui.close();
}
if ui.button("Create Material Here").clicked() {
create_material_here(world, &folder.path);
ui.close();
}
if ui.button("New Folder").clicked() {
begin_new_folder(world, folder.path.clone());
ui.close();
}
if ui.button("Open Trash...").clicked() {
world.resource_mut::<AssetBrowserUiState>().show_trash = true;
ui.close();
}
let can_paste = world.resource::<AssetBrowserUiState>().clipboard.is_some();
if ui
.add_enabled(can_paste, egui::Button::new("Paste Into"))
.clicked()
{
paste_content_clipboard_into(world, &folder.path);
ui.close();
}
}
if !matches!(folder.path.as_str(), ASSETS_ROOT | BUILTINS_FOLDER) {
ui.separator();
if ui.button("Rename").clicked() {
world
.resource_mut::<EditorAssets>()
.select(AssetSelection::Folder(folder.path.clone()));
begin_rename(world);
ui.close();
}
if ui.button("Cut").clicked() {
set_content_clipboard(world, true);
ui.close();
}
if ui.button("Copy").clicked() {
set_content_clipboard(world, false);
ui.close();
}
if ui.button("Duplicate").clicked() {
duplicate_selection(world);
ui.close();
}
if ui.button("Move To Trash").clicked() {
request_delete_for_selection(world);
ui.close();
}
}
}
pub(super) fn empty_space_context_menu(
world: &mut World,
ui: &mut egui::Ui,
current_folder: &str,
visible_order: &[AssetSelection],
) {
if !world.resource::<EditorAssets>().selections.is_empty() {
world.resource_mut::<EditorAssets>().clear_selection();
}
if current_folder != BUILTINS_FOLDER {
if ui.button("Import Here...").clicked() {
request_import_to_destination(world, current_folder.to_string());
ui.close();
}
if ui.button("Import To...").clicked() {
begin_import_to(world);
ui.close();
}
if ui.button("Create Materials From Folder...").clicked() {
begin_pbr_grouping(world, current_folder.to_string());
ui.close();
}
if ui.button("Create Material Here").clicked() {
create_material_here(world, current_folder);
ui.close();
}
if ui.button("New Folder").clicked() {
begin_new_folder(world, current_folder.to_string());
ui.close();
}
if ui.button("Open Trash...").clicked() {
world.resource_mut::<AssetBrowserUiState>().show_trash = true;
ui.close();
}
let can_paste = world.resource::<AssetBrowserUiState>().clipboard.is_some();
if ui
.add_enabled(can_paste, egui::Button::new("Paste"))
.clicked()
{
paste_content_clipboard(world);
ui.close();
}
ui.separator();
}
let can_undo = !world
.resource::<AssetBrowserUiState>()
.content_undo
.is_empty();
if ui
.add_enabled(can_undo, egui::Button::new("Undo Last Content Operation"))
.clicked()
{
undo_last_content_operation(world);
ui.close();
}
if ui
.add_enabled(!visible_order.is_empty(), egui::Button::new("Select All"))
.clicked()
{
world
.resource_mut::<EditorAssets>()
.select_all(visible_order);
ui.close();
}
if ui.button("Refresh").clicked() {
crate::assets::refresh_content_browser(world);
ui.close();
}
ui.separator();
let view = world.resource::<AssetBrowserUiState>().view;
if ui
.selectable_label(view == AssetBrowserView::Grid, "Grid View")
.clicked()
{
world.resource_mut::<AssetBrowserUiState>().view = AssetBrowserView::Grid;
ui.close();
}
if ui
.selectable_label(view == AssetBrowserView::List, "List View")
.clicked()
{
world.resource_mut::<AssetBrowserUiState>().view = AssetBrowserView::List;
ui.close();
}
}
pub(super) fn subasset_context_menu(
world: &mut World,
ui: &mut egui::Ui,
embedded: &EmbeddedAsset,
selected_entities: &SelectedEntities,
) {
if ui.button("Select").clicked() {
world
.resource_mut::<EditorAssets>()
.select(embedded.selection.clone());
ui.close();
}
match embedded.kind {
AssetSubAssetKind::Mesh => {
if embedded.requires_skinned_hierarchy {
if ui.button("Place Skinned Model at Origin").clicked() {
place_subasset_operator(world, embedded.selection.clone(), Vec3::ZERO);
ui.close();
}
} else if ui.button("Place at Origin").clicked() {
place_subasset_operator(world, embedded.selection.clone(), Vec3::ZERO);
ui.close();
}
}
AssetSubAssetKind::Texture => {
if ui.button("Apply as Base Color Texture").clicked() {
if let Some(asset) =
texture_asset_from_subasset_selection(world, &Some(embedded.selection.clone()))
{
apply_texture_operator(world, asset, selected_entities);
}
ui.close();
}
}
AssetSubAssetKind::Material => {
ui.label(egui::RichText::new("Embedded source material").color(TEXT_DIM));
}
AssetSubAssetKind::Skeleton => {
ui.label(egui::RichText::new("Inspect-only rig metadata").color(TEXT_DIM));
}
AssetSubAssetKind::AnimationClip => {
let animated_actor = selected_entities
.as_slice()
.iter()
.copied()
.find(|entity| world.get::<shared::SkinnedMeshRenderer>(*entity).is_some());
let action = if animated_actor.is_some() {
"Assign To Selected Actor"
} else {
"Create Animated Actor"
};
if ui.button(action).clicked() {
if let Some(entity) = animated_actor {
assign_animation_clip_operator(world, embedded.selection.clone(), entity);
} else {
place_subasset_operator(world, embedded.selection.clone(), Vec3::ZERO);
}
ui.close();
}
}
}
if matches!(
embedded.kind,
AssetSubAssetKind::Mesh | AssetSubAssetKind::Material | AssetSubAssetKind::Texture
) && ui.button("Regenerate Thumbnail").clicked()
{
regenerate_subasset_thumbnail(world, embedded);
ui.close();
}
if let AssetSelection::SubAsset { parent_path, .. } = &embedded.selection {
if ui.button("Select Parent Asset").clicked() {
world
.resource_mut::<EditorAssets>()
.select(AssetSelection::File(parent_path.clone()));
ui.close();
}
}
}
pub(super) fn regenerate_asset_thumbnail(world: &mut World, asset: &EditorAsset) {
let Some(path) = asset.path.clone() else {
return;
};
let key = asset_cache_key(asset);
let kind = asset.kind.clone();
let asset_server = world.resource::<AssetServer>().clone();
crate::assets::retry_thumbnail(world, &key);
world.resource_scope(|world, mut cache: Mut<AssetThumbnailCache>| match kind {
EditorAssetKind::Texture => {
cache.request_texture(key.clone(), path.clone(), &asset_server);
}
EditorAssetKind::Model => {
world.resource_scope(|_world, mut studio: Mut<ThumbnailStudio>| {
cache.request_model(key.clone(), path.clone(), &mut studio);
});
}
EditorAssetKind::Material => {
world.resource_scope(|_world, mut studio: Mut<ThumbnailStudio>| {
cache.request_material_asset(key.clone(), path.clone(), &mut studio);
});
}
_ => {}
});
world.resource_mut::<SceneIo>().status = format!("Regenerating thumbnail for {}", asset.label);
}
pub(super) fn regenerate_subasset_thumbnail(world: &mut World, embedded: &EmbeddedAsset) {
let AssetSelection::SubAsset { parent_path, .. } = &embedded.selection else {
return;
};
let key = embedded.thumbnail_key.clone();
let asset_server = world.resource::<AssetServer>().clone();
crate::assets::retry_thumbnail(world, &key);
world.resource_scope(
|world, mut cache: Mut<AssetThumbnailCache>| match embedded.kind {
AssetSubAssetKind::Mesh => {
let Some(mesh_label) = embedded.mesh_label.clone() else {
return;
};
world.resource_scope(|_world, mut studio: Mut<ThumbnailStudio>| {
cache.request_mesh_subasset(
key.clone(),
parent_path.clone(),
mesh_label,
embedded.material_label.clone(),
embedded.requires_skinned_hierarchy,
&mut studio,
);
});
}
AssetSubAssetKind::Material => {
let Some(material_label) = embedded.material_label.clone() else {
return;
};
world.resource_scope(|_world, mut studio: Mut<ThumbnailStudio>| {
cache.request_source_material(
key.clone(),
parent_path.clone(),
material_label,
&mut studio,
);
});
}
AssetSubAssetKind::Texture => {
if let Some(texture_path) = embedded.texture_path.clone() {
cache.request_texture(key.clone(), texture_path, &asset_server);
}
}
AssetSubAssetKind::Skeleton | AssetSubAssetKind::AnimationClip => {}
},
);
world.resource_mut::<SceneIo>().status =
format!("Regenerating thumbnail for {}", embedded.label);
}
pub(super) fn reimport_asset(world: &mut World, asset: &EditorAsset) {
let Some(path) = asset.path.as_deref() else {
return;
};
let mut status = format!("Reimported {}", asset.label);
if let Some(mut registry) = world.get_resource_mut::<crate::asset_db::AssetRegistry>() {
if let Some(record) = find_asset_mut_by_path(&mut registry, path) {
if let Err(error) = refresh_model_artifacts(record) {
status = format!("Reimport failed for {}: {error}", asset.label);
warn!("{status}");
}
}
if let Err(error) = save_registry(&registry) {
status = format!("Asset registry save failed: {error}");
warn!("{status}");
} else {
registry.index_dirty = false;
}
}
invalidate_on_catalog_refresh(world);
world.resource_mut::<SceneIo>().status = status;
}
pub(super) fn selected_content_path(world: &World) -> Option<String> {
let assets = world.resource::<EditorAssets>();
assets
.selected
.as_ref()
.and_then(authored_content_path)
.map(str::to_string)
}
pub(super) fn authored_content_path(selection: &AssetSelection) -> Option<&str> {
match selection {
AssetSelection::Folder(path) | AssetSelection::File(path) => Some(path),
AssetSelection::Builtin(_) | AssetSelection::SubAsset { .. } => None,
}
}
pub(super) fn selected_content_paths(world: &World) -> Vec<String> {
let assets = world.resource::<EditorAssets>();
let mut paths: Vec<String> = assets
.selections
.iter()
.filter_map(authored_content_path)
.filter(|path| !matches!(*path, ASSETS_ROOT | BUILTINS_FOLDER))
.map(str::to_string)
.collect();
paths.sort();
paths.dedup();
let all_paths = paths.clone();
paths.retain(|candidate| {
!all_paths.iter().any(|parent| {
parent != candidate
&& candidate
.strip_prefix(parent)
.is_some_and(|suffix| suffix.starts_with('/'))
})
});
paths
}
pub(super) fn collapsed_and_unaffected_selection_counts(world: &World) -> (usize, usize) {
let assets = world.resource::<EditorAssets>();
let raw_authored_count = assets
.selections
.iter()
.filter_map(authored_content_path)
.filter(|path| !matches!(*path, ASSETS_ROOT | BUILTINS_FOLDER))
.count();
let effective_count = selected_content_paths(world).len();
(
raw_authored_count.saturating_sub(effective_count),
assets.selections.len().saturating_sub(raw_authored_count),
)
}
@@ -0,0 +1,32 @@
use super::*;
pub(crate) fn validate_material_conflict_destination(
world: &World,
destination: &Path,
) -> Result<String, String> {
let root = PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root);
let root = root.canonicalize().unwrap_or(root);
let absolute = if destination.is_absolute() {
destination.to_path_buf()
} else {
root.join(destination)
};
let absolute = absolute
.parent()
.and_then(|parent| parent.canonicalize().ok())
.and_then(|parent| destination.file_name().map(|name| parent.join(name)))
.unwrap_or(absolute);
let relative = absolute.strip_prefix(&root).map_err(|_| {
format!(
"Material assets must stay inside {}",
root.join("assets").display()
)
})?;
if !relative.starts_with("assets") {
return Err(format!(
"Material assets must stay inside {}",
root.join("assets").display()
));
}
Ok(relative.to_string_lossy().replace('\\', "/"))
}
+119 -22
View File
@@ -1,13 +1,13 @@
//! Asset browser UI state and view enums.
use std::collections::HashSet;
use std::path::PathBuf;
use bevy::prelude::*;
use shared::{MaterialAsset, MaterialInstanceAsset};
use crate::asset_db::ImportSettings;
use crate::assets::{AssetSelection, ASSETS_ROOT, BUILTINS_FOLDER};
use crate::project::collaboration::FileSnapshot;
use bevy::prelude::*;
use shared::MaterialAsset;
pub(crate) const ASSET_DETAILS_DEFAULT_WIDTH: f32 = 260.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AssetBrowserView {
@@ -44,42 +44,133 @@ pub struct AssetBrowserUiState {
pub(crate) thumbnail_size: f32,
pub(crate) recursive: bool,
pub(crate) show_details: bool,
/// Width of the details pane for the current editor session.
pub(crate) details_width: f32,
pub(crate) expanded_folders: HashSet<String>,
pub(crate) expanded_assets: HashSet<String>,
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>,
pub(crate) clipboard: Option<ContentClipboard>,
pub(crate) pending_path_edit: Option<ContentPathEdit>,
pub(crate) pending_content_transaction: Option<PendingContentTransaction>,
/// Selected project folder while the explicit Import To review is open.
pub(crate) pending_import_destination: Option<String>,
pub(crate) content_undo: Vec<ContentUndoEntry>,
pub(crate) pending_gltf_extraction: Option<GltfMaterialExtractionDraft>,
pub(crate) pending_pbr_grouping: Option<PbrGroupingDraft>,
pub(crate) show_trash: bool,
}
#[derive(Debug, Clone)]
pub(crate) struct ContentClipboard {
pub(crate) sources: Vec<String>,
pub(crate) cut: bool,
}
#[derive(Debug, Clone)]
pub(crate) struct ContentUndoEntry {
pub(crate) label: String,
pub(crate) action: ContentUndoAction,
pub(crate) guarded_sources: Vec<(PathBuf, String)>,
}
#[derive(Debug, Clone)]
pub(crate) enum ContentUndoAction {
Apply(Vec<content_pipeline::ContentOperation>),
TrashCreated(Vec<PathBuf>),
RestoreTrash(PathBuf),
}
#[derive(Debug, Clone)]
pub(crate) struct PendingContentTransaction {
pub(crate) preview: content_pipeline::ContentTransactionPreview,
pub(crate) guarded_paths: Vec<(PathBuf, String)>,
pub(crate) clear_cut_clipboard: bool,
pub(crate) clear_drag: bool,
pub(crate) browser_snapshot: ContentBrowserSnapshot,
}
/// Browser-local state captured before a reviewed content operation begins.
/// Cancel restores this verbatim; commit deliberately replaces it with the result selection.
#[derive(Debug, Clone)]
pub(crate) struct ContentBrowserSnapshot {
pub(crate) current_folder: String,
pub(crate) selected: Option<AssetSelection>,
pub(crate) selections: Vec<AssetSelection>,
pub(crate) selection_anchor: Option<AssetSelection>,
pub(crate) dragging: Option<AssetSelection>,
pub(crate) asset_status: String,
pub(crate) scene_status: String,
}
#[derive(Debug, Clone)]
pub(crate) enum ContentPathEditKind {
Rename { source: String },
NewFolder { parent: String },
}
#[derive(Debug, Clone)]
pub(crate) struct ContentPathEdit {
pub(crate) kind: ContentPathEditKind,
pub(crate) name: String,
}
#[derive(Debug, Clone)]
pub(crate) struct AssetDeleteRequest {
pub(crate) selection: AssetSelection,
pub(crate) label: String,
pub(crate) files: Vec<String>,
pub(crate) warnings: Vec<String>,
}
#[derive(Debug, Clone)]
pub(crate) struct ImportSettingsDraft {
pub(crate) path: String,
pub(crate) settings: ImportSettings,
pub(crate) struct GltfMaterialExtractionDraft {
pub(crate) source: String,
pub(crate) destination: String,
pub(crate) materials: Vec<GltfMaterialExtractionEntry>,
/// When present, extraction publishes only this imported source and assigns only this actor slot.
pub(crate) actor_target: Option<GltfMaterialExtractionTarget>,
}
#[derive(Debug, Clone)]
pub(crate) struct MaterialAssetDraft {
pub(crate) struct GltfMaterialExtractionTarget {
pub(crate) entity: Entity,
pub(crate) slot_id: shared::ComponentInstanceId,
pub(crate) source_sub_asset_id: String,
}
#[derive(Debug, Clone)]
pub(crate) struct GltfMaterialExtractionEntry {
pub(crate) included: bool,
pub(crate) source_index: usize,
pub(crate) source_name: String,
pub(crate) path: String,
pub(crate) asset: MaterialAsset,
pub(crate) disk_snapshot: FileSnapshot,
pub(crate) error: Option<String>,
pub(crate) write_mode: MaterialExtractionWriteMode,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum MaterialExtractionWriteMode {
/// An existing provenance match must be explicitly reviewed before publishing.
Undecided,
CreateNew,
ApplyExisting {
expected_fingerprint: String,
previous_bytes: Vec<u8>,
},
}
#[derive(Debug, Clone)]
pub(crate) struct MaterialInstanceAssetDraft {
pub(crate) struct PbrGroupingDraft {
pub(crate) folder: String,
pub(crate) textures: Vec<PbrTextureDraft>,
}
#[derive(Debug, Clone)]
pub(crate) struct PbrTextureDraft {
pub(crate) path: String,
pub(crate) asset: MaterialInstanceAsset,
pub(crate) disk_snapshot: FileSnapshot,
pub(crate) error: Option<String>,
pub(crate) target: String,
pub(crate) role: content_pipeline::PbrTextureRole,
pub(crate) confidence: content_pipeline::PbrMatchConfidence,
pub(crate) included: bool,
}
impl Default for AssetBrowserUiState {
@@ -95,12 +186,18 @@ impl Default for AssetBrowserUiState {
thumbnail_size: 72.0,
recursive: false,
show_details: true,
details_width: ASSET_DETAILS_DEFAULT_WIDTH,
expanded_folders,
expanded_assets: HashSet::new(),
pending_delete: None,
import_draft: None,
material_draft: None,
material_instance_draft: None,
clipboard: None,
pending_path_edit: None,
pending_content_transaction: None,
pending_import_destination: None,
content_undo: Vec::new(),
pending_gltf_extraction: None,
pending_pbr_grouping: None,
show_trash: false,
}
}
}
+225
View File
@@ -0,0 +1,225 @@
//! Reusable Content Browser and Material Library asset cards.
use bevy_egui::egui;
use egui_phosphor_icons::icons;
use crate::assets::{kind_icon, EditorAsset};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct AssetCardStatus {
pub dirty: bool,
pub processing: bool,
pub error: bool,
}
impl AssetCardStatus {
pub fn for_document(
snapshot: Option<&crate::asset_documents::AuthoredDocumentSnapshot>,
dirty: bool,
failed: bool,
) -> Self {
use crate::asset_documents::{AuthoredDocumentState, DerivedProcessingState};
Self {
dirty,
processing: snapshot.is_some_and(|status| {
matches!(
status.processing,
DerivedProcessingState::Queued | DerivedProcessingState::Processing
)
}),
error: failed
|| snapshot.is_some_and(|status| {
matches!(
status.state,
AuthoredDocumentState::ExternalConflict | AuthoredDocumentState::SaveFailed
) || status.processing == DerivedProcessingState::Failed
}),
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn draw_asset_card(
ui: &mut egui::Ui,
asset: &EditorAsset,
texture_id: Option<egui::TextureId>,
pending: bool,
failure: Option<&str>,
selected: bool,
thumbnail_size: f32,
status: AssetCardStatus,
) -> egui::Response {
let response = draw_asset_cell(
ui,
asset,
texture_id,
pending,
failure,
selected,
thumbnail_size,
);
draw_asset_status_rail(ui, response.rect, status);
response
}
pub fn draw_asset_status_rail(ui: &egui::Ui, rect: egui::Rect, status: AssetCardStatus) {
let mut y = rect.top() + 11.0;
let x = rect.right() - 11.0;
if status.error {
ui.painter().text(
egui::pos2(x, y),
egui::Align2::CENTER_CENTER,
icons::WARNING_CIRCLE.as_str(),
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-regular".into())),
super::theme::ERROR,
);
y += 12.0;
}
if status.processing {
ui.painter().text(
egui::pos2(x, y),
egui::Align2::CENTER_CENTER,
icons::CIRCLE_NOTCH.as_str(),
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-regular".into())),
super::theme::ACCENT,
);
y += 12.0;
}
if status.dirty {
ui.painter()
.circle_filled(egui::pos2(x, y), 4.0, super::theme::WARNING);
}
}
/// Draws the same authored-document status model in a fixed-width list cell.
pub fn draw_asset_status_marker(ui: &mut egui::Ui, status: AssetCardStatus) {
let (rect, response) = ui.allocate_exact_size(egui::vec2(20.0, 20.0), egui::Sense::hover());
let (glyph, color) = if status.error {
(Some(icons::WARNING_CIRCLE), super::theme::ERROR)
} else if status.processing {
(Some(icons::CIRCLE_NOTCH), super::theme::ACCENT)
} else if status.dirty {
(None, super::theme::WARNING)
} else {
return;
};
if let Some(glyph) = glyph {
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
glyph.as_str(),
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-regular".into())),
color,
);
} else {
ui.painter().circle_filled(rect.center(), 4.0, color);
}
response.on_hover_text(if status.error {
"Asset has a save, conflict, or processing error"
} else if status.processing {
"Derived asset processing is running"
} else {
"Asset has unsaved changes"
});
}
#[allow(clippy::too_many_arguments)]
fn draw_asset_cell(
ui: &mut egui::Ui,
asset: &EditorAsset,
texture_id: Option<egui::TextureId>,
pending: bool,
failed: Option<&str>,
selected: bool,
thumbnail_size: f32,
) -> egui::Response {
let thumb_size = thumbnail_size.clamp(48.0, 112.0);
let cell_size = egui::vec2(thumb_size + 20.0, thumb_size + 42.0);
let (rect, response) = ui.allocate_exact_size(cell_size, egui::Sense::click_and_drag());
let fill = if selected {
super::theme::SELECTION_BG_MUTED
} else if response.hovered() {
super::theme::ELEVATED_BG
} else {
super::theme::WIDGET_BG
};
ui.painter().rect(
rect,
4.0,
fill,
egui::Stroke::new(
1.0_f32,
if selected {
super::theme::ACCENT_HOVER
} else {
super::theme::BORDER
},
),
egui::StrokeKind::Inside,
);
let thumbnail_rect = egui::Rect::from_min_size(
rect.min + egui::vec2(10.0, 8.0),
egui::vec2(thumb_size, thumb_size),
);
let painter = ui.painter().with_clip_rect(thumbnail_rect);
if let Some(texture_id) = texture_id {
painter.image(
texture_id,
thumbnail_rect,
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
egui::Color32::WHITE,
);
} else {
let (icon, color) = if pending {
(icons::CIRCLE_NOTCH, super::theme::TEXT_DIM)
} else if failed.is_some() {
(icons::WARNING_CIRCLE, super::theme::TEXT_DIM)
} else {
(kind_icon(&asset.kind), super::theme::TEXT)
};
painter.text(
thumbnail_rect.center(),
egui::Align2::CENTER_CENTER,
icon.as_str(),
egui::FontId::new(26.0, egui::FontFamily::Name("phosphor-regular".into())),
color,
);
}
let label_rect = egui::Rect::from_min_max(
egui::pos2(rect.min.x + 6.0, thumbnail_rect.max.y + 4.0),
egui::pos2(rect.max.x - 6.0, rect.max.y - 4.0),
);
let label_color = if selected {
super::theme::TEXT_SELECTED
} else {
super::theme::TEXT
};
let font = egui::FontId::proportional(11.0);
let mut job =
egui::text::LayoutJob::simple(asset.label.clone(), font, label_color, label_rect.width());
job.halign = egui::Align::Center;
job.wrap.max_rows = 2;
job.wrap.break_anywhere = true;
job.wrap.overflow_character = Some('…');
let galley = ui.painter().layout_job(job);
let label_painter = ui.painter().with_clip_rect(label_rect);
label_painter.galley(
egui::pos2(
label_rect.center().x - galley.rect.width() * 0.5,
label_rect.center().y - galley.rect.height() * 0.5,
),
galley.clone(),
label_color,
);
if let Some(reason) = failed {
response.on_hover_text(reason)
} else if galley.elided {
response.on_hover_text(&asset.label)
} else {
response
}
}
+1 -1
View File
@@ -99,7 +99,7 @@ pub fn audio_source_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: E
ui.painter().rect_stroke(
clip_response.rect.expand(3.0),
3.0,
egui::Stroke::new(1.5, SELECTION),
egui::Stroke::new(1.5_f32, SELECTION),
egui::StrokeKind::Outside,
);
if ui.input(|input| input.pointer.any_released()) {
+18
View File
@@ -97,6 +97,24 @@ pub fn request_build(world: &mut World, run_after: bool) {
.set_status("Save all modified scene tabs before building a package");
return;
}
if world
.get_resource::<crate::asset_documents::AuthoredAssetDocumentStore>()
.is_some_and(|store| store.has_dirty_documents())
{
world
.resource_mut::<SceneIo>()
.set_status("Save all modified asset documents before building a package");
return;
}
if world
.get_resource::<crate::asset_documents::AuthoredAssetDocumentStore>()
.is_some_and(|store| store.has_pending_or_failed_processing())
{
world.resource_mut::<SceneIo>().set_status(
"Asset processing is pending or failed; wait for completion or resolve diagnostics before packaging",
);
return;
}
let engine_root = engine_workspace_root();
let root = PathBuf::from(&world.resource::<ProjectWorkspace>().root);
let profile = world.resource::<BuildPanel>().selected_profile.clone();
+30 -56
View File
@@ -9,6 +9,10 @@ use bevy::reflect::GetTypeRegistration;
use bevy_egui::egui;
use egui_phosphor_icons::icons;
mod dispatch;
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditorComponentCategory {
Authoring,
@@ -44,10 +48,9 @@ pub struct EditorComponentDescriptor {
#[derive(Resource, Debug, Clone)]
pub struct EditorComponentRegistry {
pub descriptors: Vec<EditorComponentDescriptor>,
inspectors: HashMap<&'static str, ComponentInspectorFn>,
pub(super) inspectors: HashMap<&'static str, ComponentInspectorFn>,
}
/// Synchronous inspector callbacks run while [`crate::ui::UiState`] is scoped out of `World`.
/// They must not request that resource. Keep extension-owned transient state in independently
/// registered resources, use [`crate::ui::request_ui_selection`] and
/// [`crate::ui::request_editor_tab`] for host UI changes, or defer other cross-panel work through
@@ -333,8 +336,7 @@ impl Default for EditorComponentRegistry {
"shared::components::BrushDesc",
"shared::animation::SkinnedMeshRenderer",
],
hydration_effect:
"Hydrates into generated mesh children and material bindings.",
hydration_effect: "Hydrates into generated mesh children and material bindings.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_SKINNED_MESH_RENDERER,
@@ -346,17 +348,17 @@ impl Default for EditorComponentRegistry {
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"],
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.",
hydration_effect: "Hydrates through a dedicated scene root containing Bevy skinned meshes and joints.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_BRUSH,
@@ -370,7 +372,7 @@ impl Default for EditorComponentRegistry {
icon: icons::CUBE.as_str(),
description: "Creates authored convex brush geometry for blockout.",
search_terms: &["brush", "blockout", "convex", "csg", "geometry"],
recommended: &["shared::components::MaterialDesc"],
recommended: &[],
conflicts_with: &[
"shared::components::Primitive",
"shared::components::StaticMeshRenderer",
@@ -402,18 +404,18 @@ impl Default for EditorComponentRegistry {
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_MATERIAL,
type_name: "shared::components::MaterialDesc",
display_name: "Authoring Material",
display_name: "Brush Fallback Material",
category: EditorComponentCategory::Rendering,
addable: true,
addable: false,
removable: true,
reorderable: true,
hidden: false,
icon: icons::PALETTE.as_str(),
description: "Defines an authored material directly on this actor.",
description: "Legacy fallback used only by authored brush geometry.",
search_terms: &["material", "shader", "texture"],
recommended: &[],
conflicts_with: &[],
hydration_effect: "Hydrates into Bevy material assets for renderable actors.",
hydration_effect: "Hydrates a legacy brush fallback; primitives and mesh renderers use material slots.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_RIGID_BODY,
@@ -474,11 +476,17 @@ impl Default for EditorComponentRegistry {
hidden: false,
icon: icons::FILM_SLATE.as_str(),
description: "Authors named animation states for an imported model rig.",
search_terms: &["animation", "controller", "state", "clip", "skeleton", "rig"],
search_terms: &[
"animation",
"controller",
"state",
"clip",
"skeleton",
"rig",
],
recommended: &["shared::animation::SkinnedMeshRenderer"],
conflicts_with: &[],
hydration_effect:
"Hydrates into a Bevy animation graph and player bound to the imported model.",
hydration_effect: "Hydrates into a Bevy animation graph and player bound to the imported model.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_AUDIO_SOURCE,
@@ -494,8 +502,7 @@ impl Default for EditorComponentRegistry {
search_terms: &["audio", "sound", "clip", "speaker", "spatial"],
recommended: &[],
conflicts_with: &["shared::components::AudioListenerDesc"],
hydration_effect:
"Hydrates into runtime Bevy audio voices with bus and attenuation control.",
hydration_effect: "Hydrates into runtime Bevy audio voices with bus and attenuation control.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_AUDIO_LISTENER,
@@ -511,8 +518,7 @@ impl Default for EditorComponentRegistry {
search_terms: &["audio", "sound", "listener", "ears", "spatial"],
recommended: &[],
conflicts_with: &["shared::components::AudioSourceDesc"],
hydration_effect:
"The highest-priority enabled listener becomes the runtime listener.",
hydration_effect: "The highest-priority enabled listener becomes the runtime listener.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_PRIMITIVE,
@@ -532,8 +538,7 @@ impl Default for EditorComponentRegistry {
"shared::components::BrushDesc",
"shared::animation::SkinnedMeshRenderer",
],
hydration_effect:
"Hydrates into generated primitive render and collision data.",
hydration_effect: "Hydrates into generated primitive render and collision data.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_PLAYER_SPAWN,
@@ -549,8 +554,7 @@ impl Default for EditorComponentRegistry {
search_terms: &["player", "spawn", "start"],
recommended: &[],
conflicts_with: &[],
hydration_effect:
"Used by PIE/session startup; no saved runtime player is created.",
hydration_effect: "Used by PIE/session startup; no saved runtime player is created.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_WEAPON_SPAWN,
@@ -630,8 +634,7 @@ impl Default for EditorComponentRegistry {
search_terms: &["post", "process", "volume", "rendering", "fx"],
recommended: &[],
conflicts_with: &[],
hydration_effect:
"Affects active camera rendering when the camera is inside the volume.",
hydration_effect: "Affects active camera rendering when the camera is inside the volume.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_NAVIGATION_BOUNDS,
@@ -881,32 +884,3 @@ where
.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());
}
}
@@ -0,0 +1,28 @@
//! Inspector callback registration and completeness checks.
use super::{ComponentInspectorFn, EditorComponentRegistry};
impl EditorComponentRegistry {
pub fn register_inspector_for_existing(
&mut self,
type_name: &'static str,
inspector: ComponentInspectorFn,
) -> Result<(), String> {
if self.by_type_name(type_name).is_none() {
return Err(format!(
"cannot register inspector for unknown component `{type_name}`"
));
}
if self.inspectors.insert(type_name, inspector).is_some() {
return Err(format!("component `{type_name}` already has an inspector"));
}
Ok(())
}
pub fn visible_descriptors_have_inspectors(&self) -> bool {
self.descriptors
.iter()
.filter(|descriptor| !descriptor.hidden)
.all(|descriptor| self.inspectors.contains_key(descriptor.type_name))
}
}
@@ -0,0 +1,37 @@
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());
}
#[test]
fn every_visible_builtin_registers_one_inspector_callback() {
let mut world = World::new();
world.init_resource::<EditorComponentRegistry>();
crate::ui::inspector::register_builtin_component_inspectors(&mut world);
assert!(world
.resource::<EditorComponentRegistry>()
.visible_descriptors_have_inspectors());
}
@@ -0,0 +1,308 @@
//! Penpot 420×350 material color popup with live preview and reversible dismissal.
mod popup;
use bevy_egui::egui;
use super::typography::TypeRole;
pub(super) const POPUP_SIZE: egui::Vec2 = egui::vec2(420.0, 350.0);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum PickerMode {
Wheel,
Sliders,
Presets,
}
#[derive(Debug, Clone)]
pub(super) struct PickerSession {
original: [f32; 4],
current: [f32; 4],
mode: PickerMode,
hex: String,
opened_at: f64,
owner_rect: egui::Rect,
original_intensity: Option<f32>,
current_intensity: Option<f32>,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ColorPickerResponse {
pub changed: bool,
pub applied: bool,
pub cancelled: bool,
}
pub(crate) fn color_control(
ui: &mut egui::Ui,
salt: impl std::hash::Hash,
label: &str,
rgba: &mut [f32; 4],
) -> ColorPickerResponse {
color_control_impl(ui, salt, label, rgba, None)
}
pub(crate) fn color_control_with_intensity(
ui: &mut egui::Ui,
salt: impl std::hash::Hash,
label: &str,
rgba: &mut [f32; 4],
intensity: &mut f32,
) -> ColorPickerResponse {
color_control_impl(ui, salt, label, rgba, Some(intensity))
}
fn color_control_impl(
ui: &mut egui::Ui,
salt: impl std::hash::Hash,
label: &str,
rgba: &mut [f32; 4],
intensity: Option<&mut f32>,
) -> ColorPickerResponse {
let palette = super::palette(ui);
let id = ui.make_persistent_id(("penpot_color_picker", salt));
let (rect, response) = ui.allocate_exact_size(egui::vec2(130.0, 22.0), egui::Sense::click());
let swatch_rect = egui::Rect::from_min_size(rect.min, egui::vec2(24.0, 22.0));
let hex_rect =
egui::Rect::from_min_size(rect.min + egui::vec2(30.0, 0.0), egui::vec2(100.0, 22.0));
popup::checker(ui.painter(), swatch_rect, palette.control, palette.elevated);
ui.painter()
.rect_filled(swatch_rect.shrink(1.0), 4.0, color32(*rgba));
ui.painter().rect_stroke(
swatch_rect,
4.0,
egui::Stroke::new(1.0_f32, palette.border_strong),
egui::StrokeKind::Inside,
);
ui.painter().rect(
hex_rect,
4.0,
palette.control,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
ui.painter().text(
hex_rect.left_center() + egui::vec2(9.0, 0.0),
egui::Align2::LEFT_CENTER,
hex(*rgba),
TypeRole::Body.font(),
palette.text_primary,
);
if response.clicked() {
let opened_at = ui.input(|input| input.time);
ui.ctx().data_mut(|data| {
data.insert_temp(
id,
PickerSession {
original: *rgba,
current: *rgba,
mode: PickerMode::Wheel,
hex: hex(*rgba),
opened_at,
owner_rect: ui.clip_rect(),
original_intensity: intensity.as_deref().copied(),
current_intensity: intensity.as_deref().copied(),
},
);
});
}
let before = *rgba;
let mut result = ColorPickerResponse::default();
let Some(mut session) = ui.ctx().data_mut(|data| data.get_temp::<PickerSession>(id)) else {
return result;
};
let screen_rect = ui.ctx().content_rect();
let popup_rect = centered_popup_rect(session.owner_rect, screen_rect);
let scrim = egui::Area::new(id.with("modal_scrim"))
.order(egui::Order::Foreground)
.fixed_pos(session.owner_rect.min)
.show(ui.ctx(), |ui| {
let (rect, response) =
ui.allocate_exact_size(session.owner_rect.size(), egui::Sense::click());
ui.painter()
.rect_filled(rect, 0.0, egui::Color32::from_black_alpha(132));
response
})
.inner;
let popup_response = egui::Area::new(id.with("popup"))
.order(egui::Order::Foreground)
.fixed_pos(popup_rect.min)
.show(ui.ctx(), |ui| {
ui.set_min_size(POPUP_SIZE);
ui.set_max_size(POPUP_SIZE);
popup::show(ui, label, &mut session, &mut result)
})
.response;
let escape = ui.input(|input| input.key_pressed(egui::Key::Escape));
let outside_click = scrim.clicked()
|| ui.input(|input| {
input.pointer.any_pressed()
&& input.time > session.opened_at
&& input
.pointer
.interact_pos()
.is_some_and(|position| !popup_response.rect.contains(position))
});
if escape || outside_click {
result.cancelled = true;
}
if result.cancelled {
*rgba = session.original;
if let (Some(target), Some(original)) = (intensity, session.original_intensity) {
*target = original;
}
ui.ctx().data_mut(|data| data.remove::<PickerSession>(id));
} else {
*rgba = session.current;
if let (Some(target), Some(current)) = (intensity, session.current_intensity) {
*target = current;
}
if result.applied {
ui.ctx().data_mut(|data| data.remove::<PickerSession>(id));
} else {
ui.ctx().data_mut(|data| data.insert_temp(id, session));
}
}
result.changed = *rgba != before;
result
}
fn centered_popup_rect(owner: egui::Rect, screen: egui::Rect) -> egui::Rect {
const SCREEN_MARGIN: f32 = 12.0;
let desired = owner.center() - POPUP_SIZE * 0.5;
let minimum = screen.min + egui::vec2(SCREEN_MARGIN, SCREEN_MARGIN);
let maximum = screen.max - POPUP_SIZE - egui::vec2(SCREEN_MARGIN, SCREEN_MARGIN);
let x = if maximum.x >= minimum.x {
desired.x.clamp(minimum.x, maximum.x)
} else {
screen.center().x - POPUP_SIZE.x * 0.5
};
let y = if maximum.y >= minimum.y {
desired.y.clamp(minimum.y, maximum.y)
} else {
screen.center().y - POPUP_SIZE.y * 0.5
};
egui::Rect::from_min_size(egui::pos2(x, y), POPUP_SIZE)
}
pub(super) fn set_current(session: &mut PickerSession, value: [f32; 4]) {
session.current = value.map(|component| component.clamp(0.0, 1.0));
session.hex = hex(session.current);
}
pub(super) fn color32(value: [f32; 4]) -> egui::Color32 {
egui::Color32::from_rgba_unmultiplied(
byte(value[0]),
byte(value[1]),
byte(value[2]),
byte(value[3]),
)
}
pub(super) fn rgba(value: egui::Color32) -> [f32; 4] {
[
value.r() as f32 / 255.0,
value.g() as f32 / 255.0,
value.b() as f32 / 255.0,
value.a() as f32 / 255.0,
]
}
pub(super) fn byte(value: f32) -> u8 {
(value.clamp(0.0, 1.0) * 255.0).round() as u8
}
pub(super) fn hex(value: [f32; 4]) -> String {
if byte(value[3]) == 255 {
format!(
"#{:02X}{:02X}{:02X}",
byte(value[0]),
byte(value[1]),
byte(value[2])
)
} else {
format!(
"#{:02X}{:02X}{:02X}{:02X}",
byte(value[0]),
byte(value[1]),
byte(value[2]),
byte(value[3])
)
}
}
pub(super) fn parse_hex(value: &str) -> Option<[f32; 4]> {
let value = value.trim().trim_start_matches('#');
if !matches!(value.len(), 6 | 8) {
return None;
}
let rgb = u32::from_str_radix(&value[..6], 16).ok()?;
let alpha = if value.len() == 8 {
u8::from_str_radix(&value[6..], 16).ok()?
} else {
255
};
Some([
((rgb >> 16) & 0xFF) as f32 / 255.0,
((rgb >> 8) & 0xFF) as f32 / 255.0,
(rgb & 0xFF) as f32 / 255.0,
alpha as f32 / 255.0,
])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn popup_centers_on_inspector_owner_and_stays_on_screen() {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0));
let inspector =
egui::Rect::from_min_size(egui::pos2(800.0, 40.0), egui::vec2(640.0, 820.0));
let popup = centered_popup_rect(inspector, screen);
assert_eq!(popup.size(), POPUP_SIZE);
assert_eq!(popup.center(), inspector.center());
let edge = centered_popup_rect(
egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(200.0, 200.0)),
screen,
);
assert!(edge.left() >= 12.0);
assert!(edge.top() >= 12.0);
}
#[test]
fn penpot_hex_round_trip_preserves_rgba() {
let value = [0.2, 0.4, 0.6, 0.8];
let parsed = parse_hex(&hex(value)).expect("valid generated hex");
for (left, right) in value.into_iter().zip(parsed) {
assert!((left - right).abs() <= 1.0 / 255.0);
}
}
#[test]
fn cancel_restores_opening_value_and_apply_keeps_live_preview() {
let original = [0.1, 0.2, 0.3, 1.0];
let mut session = PickerSession {
original,
current: [0.8, 0.7, 0.6, 0.5],
mode: PickerMode::Wheel,
hex: String::new(),
opened_at: 0.0,
owner_rect: egui::Rect::ZERO,
original_intensity: None,
current_intensity: None,
};
let applied = session.current;
set_current(&mut session, applied);
assert_eq!(session.original, original);
assert_eq!(session.current, applied);
}
}
@@ -0,0 +1,765 @@
//! Fixed-coordinate renderer for the exported Penpot color overlay.
mod sliders;
use bevy_egui::egui::{self, ecolor::Hsva};
use egui_phosphor_icons::{icons, Icon};
use super::{
byte, color32, parse_hex, rgba, set_current, ColorPickerResponse, PickerMode, PickerSession,
POPUP_SIZE,
};
use crate::ui::design_system::typography::TypeRole;
const RECENTS: [egui::Color32; 8] = colors([
0xE7D4B4, 0x53D3E6, 0xCA6CE0, 0xF06B75, 0x55C58A, 0xF3C85B, 0x6F88EF, 0xF3F5F7,
]);
const PRESETS: [egui::Color32; 24] = colors([
0xE7D4B4, 0xF2EEE8, 0xD5B59C, 0xA8795B, 0x734C3C, 0x3B2D29, 0xE45D68, 0xF09A55, 0xE9D05B,
0x79C267, 0x45B7A6, 0x4FA9D8, 0x5A78DE, 0x8E68D8, 0xC26BC7, 0xE68DB5, 0xF5F7FA, 0xC4CCD5,
0x8995A3, 0x56616E, 0x303842, 0x1D242C, 0x101419, 0x07090C,
]);
const PLANNED_EYEDROPPER: &str = "Planned — screen sampling pending";
const fn colors<const N: usize>(values: [u32; N]) -> [egui::Color32; N] {
let mut result = [egui::Color32::BLACK; N];
let mut index = 0;
while index < N {
let value = values[index];
result[index] = egui::Color32::from_rgb(
((value >> 16) & 0xFF) as u8,
((value >> 8) & 0xFF) as u8,
(value & 0xFF) as u8,
);
index += 1;
}
result
}
struct Geometry;
impl Geometry {
const HEADER_HEIGHT: f32 = 38.0;
const CONTENT: egui::Rect =
egui::Rect::from_min_max(egui::pos2(12.0, 74.0), egui::pos2(408.0, 276.0));
const WHEEL_EDITOR: egui::Rect =
egui::Rect::from_min_max(egui::pos2(12.0, 74.0), egui::pos2(190.0, 276.0));
const VALUES: egui::Rect =
egui::Rect::from_min_max(egui::pos2(198.0, 82.0), egui::pos2(396.0, 268.0));
const RECENTS: egui::Rect =
egui::Rect::from_min_max(egui::pos2(12.0, 282.0), egui::pos2(408.0, 310.0));
const FOOTER: egui::Rect =
egui::Rect::from_min_max(egui::pos2(12.0, 316.0), egui::pos2(408.0, 342.0));
fn rect(root: egui::Rect, local: egui::Rect) -> egui::Rect {
local.translate(root.min.to_vec2())
}
fn at(root: egui::Rect, x: f32, y: f32, width: f32, height: f32) -> egui::Rect {
egui::Rect::from_min_size(root.min + egui::vec2(x, y), egui::vec2(width, height))
}
}
pub(super) fn show(
ui: &mut egui::Ui,
label: &str,
session: &mut PickerSession,
result: &mut ColorPickerResponse,
) -> egui::Response {
let palette = crate::ui::design_system::palette(ui);
let (root, response) = ui.allocate_exact_size(POPUP_SIZE, egui::Sense::hover());
ui.painter().rect(
root,
7.0,
palette.panel,
egui::Stroke::new(1.0_f32, palette.border_strong),
egui::StrokeKind::Inside,
);
ui.painter().line_segment(
[
root.min + egui::vec2(0.0, Geometry::HEADER_HEIGHT),
root.min + egui::vec2(root.width(), Geometry::HEADER_HEIGHT),
],
egui::Stroke::new(1.0_f32, palette.border),
);
header(ui, root, label, session, result);
mode_tabs(ui, root, session);
intensity_control(ui, root, session);
match session.mode {
PickerMode::Wheel => wheel_mode(ui, root, session),
PickerMode::Sliders => sliders::show(ui, root, session),
PickerMode::Presets => presets_mode(ui, root, session),
}
recent_row(ui, root, session);
footer(ui, root, result);
response
}
fn intensity_control(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let Some(intensity) = session.current_intensity.as_mut() else {
return;
};
let palette = crate::ui::design_system::palette(ui);
text(
ui,
root.min + egui::vec2(272.0, 55.0),
egui::Align2::LEFT_CENTER,
"Intensity",
TypeRole::Small.font(),
palette.text_muted,
);
ui.put(
Geometry::at(root, 326.0, 43.0, 82.0, 24.0),
egui::DragValue::new(intensity)
.range(0.0..=50_000.0)
.speed(10.0),
)
.on_hover_text("Emissive luminance multiplier in nits");
}
fn header(
ui: &mut egui::Ui,
root: egui::Rect,
label: &str,
session: &PickerSession,
result: &mut ColorPickerResponse,
) {
let palette = crate::ui::design_system::palette(ui);
text(
ui,
root.min + egui::vec2(12.0, 19.0),
egui::Align2::LEFT_CENTER,
label,
TypeRole::Section.font(),
palette.text_primary,
);
text(
ui,
root.min + egui::vec2(84.0, 19.0),
egui::Align2::LEFT_CENTER,
"sRGB · RGBA",
TypeRole::Small.font(),
palette.text_muted,
);
paint_swatch(
ui,
Geometry::at(root, 348.0, 7.0, 26.0, 24.0),
color32(session.current),
egui::Sense::hover(),
"Current color",
);
if icon_button(
ui,
Geometry::at(root, 384.0, 7.0, 24.0, 24.0),
icons::X,
"Cancel color changes",
true,
)
.clicked()
{
result.cancelled = true;
}
}
fn mode_tabs(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let palette = crate::ui::design_system::palette(ui);
for (index, (mode, icon, label, width)) in [
(PickerMode::Wheel, icons::CIRCLE, "Wheel", 76.0),
(PickerMode::Sliders, icons::SLIDERS, "Sliders", 76.0),
(PickerMode::Presets, icons::SQUARES_FOUR, "Presets", 78.0),
]
.into_iter()
.enumerate()
{
let x = [12.0, 92.0, 172.0][index];
let rect = Geometry::at(root, x, 42.0, width, 26.0);
let selected = session.mode == mode;
let response = ui.put(
rect,
egui::Button::new(crate::ui::design_system::controls::icon_label(
icon,
label,
TypeRole::Body,
12.0,
if selected {
palette.text_primary
} else {
palette.text_secondary
},
))
.fill(if selected {
palette.accent_dark
} else {
palette.control
})
.stroke(egui::Stroke::new(
1.0_f32,
if selected {
palette.accent
} else {
palette.border
},
))
.corner_radius(4.0),
);
if selected {
ui.painter().rect_filled(
egui::Rect::from_center_size(
egui::pos2(rect.center().x, rect.bottom() - 1.0),
egui::vec2(60.0, 2.0),
),
1.0,
palette.accent,
);
}
if response.clicked() {
session.mode = mode;
}
}
}
fn wheel_mode(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let palette = crate::ui::design_system::palette(ui);
let ring = Geometry::at(root, 29.0, 88.0, 144.0, 144.0);
let sv = Geometry::at(root, 65.0, 124.0, 72.0, 72.0);
let editor = Geometry::rect(root, Geometry::WHEEL_EDITOR);
let response = ui.interact(
editor,
ui.make_persistent_id("penpot_color_wheel"),
egui::Sense::click_and_drag(),
);
let mut hsva = Hsva::from_rgba_unmultiplied(
session.current[0],
session.current[1],
session.current[2],
session.current[3],
);
paint_hue_wheel(ui.painter(), ring, hsva.h, palette.text_primary);
paint_sv(
ui.painter(),
sv,
hsva.h,
hsva.s,
hsva.v,
palette.text_primary,
);
if response.clicked() || response.dragged() {
if let Some(position) = response.interact_pointer_pos() {
let delta = position - ring.center();
if sv.contains(position) {
hsva.s = ((position.x - sv.left()) / sv.width()).clamp(0.0, 1.0);
hsva.v = (1.0 - (position.y - sv.top()) / sv.height()).clamp(0.0, 1.0);
} else if (52.0..=76.0).contains(&delta.length()) {
hsva.h = (delta.angle() / std::f32::consts::TAU + 0.25).rem_euclid(1.0);
}
let [r, g, b] = hsva.to_rgb();
set_current(session, [r, g, b, hsva.a]);
}
}
text(
ui,
root.min + egui::vec2(101.0, 252.0),
egui::Align2::CENTER_CENTER,
"Drag ring or field",
TypeRole::Small.font(),
palette.text_muted,
);
values(ui, root, session);
}
fn values(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let palette = crate::ui::design_system::palette(ui);
let _values_bounds = Geometry::rect(root, Geometry::VALUES);
caption(ui, root, 198.0, 82.0, "CURRENT");
caption(ui, root, 302.0, 82.0, "PREVIOUS");
paint_swatch(
ui,
Geometry::at(root, 198.0, 96.0, 94.0, 30.0),
color32(session.current),
egui::Sense::hover(),
"Current live value",
);
paint_swatch(
ui,
Geometry::at(root, 302.0, 96.0, 94.0, 30.0),
color32(session.original),
egui::Sense::hover(),
"Value when the picker opened",
);
caption(ui, root, 198.0, 132.0, "HEX");
let hex_field = Geometry::at(root, 198.0, 144.0, 166.0, 24.0);
field_background(ui, hex_field);
let edit_rect = egui::Rect::from_min_max(
hex_field.min,
egui::pos2(hex_field.right() - 24.0, hex_field.bottom()),
);
let edit = ui.put(
edit_rect.shrink2(egui::vec2(5.0, 2.0)),
egui::TextEdit::singleline(&mut session.hex)
.font(TypeRole::Body.font())
.frame(egui::Frame::NONE),
);
if edit.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)) {
if let Some(value) = parse_hex(&session.hex) {
set_current(session, value);
}
}
if bare_icon(
ui,
egui::Rect::from_min_size(
egui::pos2(hex_field.right() - 24.0, hex_field.top()),
egui::vec2(24.0, 24.0),
),
icons::COPY,
"Copy HEX",
palette.text_secondary,
)
.clicked()
{
ui.ctx().copy_text(session.hex.clone());
}
let eyedropper = Geometry::at(root, 370.0, 144.0, 26.0, 24.0);
field_background(ui, eyedropper);
bare_icon(
ui,
eyedropper,
icons::EYEDROPPER,
PLANNED_EYEDROPPER,
palette.text_muted,
);
caption(ui, root, 198.0, 174.0, "RGBA");
let mut bytes = session.current.map(byte);
let before_bytes = bytes;
for (index, prefix) in ["R ", "G ", "B ", "A "].into_iter().enumerate() {
let rect = Geometry::at(root, 198.0 + index as f32 * 49.0, 186.0, 45.0, 24.0);
ui.put(
rect,
egui::DragValue::new(&mut bytes[index])
.range(0..=255)
.prefix(prefix),
);
}
if bytes != before_bytes {
set_current(session, bytes.map(|component| component as f32 / 255.0));
}
caption(ui, root, 198.0, 216.0, "HSV");
let mut hsva = Hsva::from_rgba_unmultiplied(
session.current[0],
session.current[1],
session.current[2],
session.current[3],
);
let mut hsv = [hsva.h * 360.0, hsva.s * 100.0, hsva.v * 100.0];
let before_hsv = hsv;
for (index, suffix) in ["°", "%", "%"].into_iter().enumerate() {
let rect = Geometry::at(root, 198.0 + index as f32 * 66.0, 228.0, 61.0, 24.0);
ui.put(
rect,
egui::DragValue::new(&mut hsv[index])
.range(if index == 0 { 0.0..=360.0 } else { 0.0..=100.0 })
.suffix(suffix)
.max_decimals(0),
);
}
if hsv != before_hsv {
hsva.h = hsv[0] / 360.0;
hsva.s = hsv[1] / 100.0;
hsva.v = hsv[2] / 100.0;
let [r, g, b] = hsva.to_rgb();
set_current(session, [r, g, b, hsva.a]);
}
caption(ui, root, 198.0, 258.0, "ALPHA");
alpha_control(ui, Geometry::at(root, 240.0, 256.0, 156.0, 14.0), session);
}
fn presets_mode(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let palette = crate::ui::design_system::palette(ui);
let content = Geometry::rect(root, Geometry::CONTENT);
ui.painter().rect_filled(content, 4.0, palette.recessed);
caption(ui, root, 24.0, 86.0, "MATERIAL PALETTE");
for (index, color) in PRESETS.into_iter().enumerate() {
let column = index % 8;
let row = index / 8;
let rect = Geometry::at(
root,
24.0 + column as f32 * 47.0,
104.0 + row as f32 * 52.0,
34.0,
34.0,
);
if paint_swatch(ui, rect, color, egui::Sense::click(), "Use preset color").clicked() {
set_current(session, rgba(color));
}
}
}
fn recent_row(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let palette = crate::ui::design_system::palette(ui);
let row = Geometry::rect(root, Geometry::RECENTS);
ui.painter().rect_filled(row, 4.0, palette.section);
text(
ui,
root.min + egui::vec2(20.0, 296.0),
egui::Align2::LEFT_CENTER,
"RECENT",
TypeRole::Caption.font(),
palette.text_muted,
);
for (index, color) in RECENTS.into_iter().enumerate() {
let rect = Geometry::at(root, 74.0 + index as f32 * 36.0, 286.0, 28.0, 20.0);
if paint_swatch(ui, rect, color, egui::Sense::click(), "Use recent color").clicked() {
set_current(session, rgba(color));
}
}
}
fn footer(ui: &mut egui::Ui, root: egui::Rect, result: &mut ColorPickerResponse) {
let palette = crate::ui::design_system::palette(ui);
let footer = Geometry::rect(root, Geometry::FOOTER);
text(
ui,
footer.left_center(),
egui::Align2::LEFT_CENTER,
"Enter apply · Esc cancel",
TypeRole::Small.font(),
palette.text_muted,
);
if labeled_button(
ui,
Geometry::at(root, 254.0, 316.0, 72.0, 26.0),
icons::X,
"Cancel",
false,
)
.clicked()
{
result.cancelled = true;
}
if labeled_button(
ui,
Geometry::at(root, 334.0, 316.0, 74.0, 26.0),
icons::CHECK,
"Apply",
true,
)
.clicked()
{
result.applied = true;
}
}
fn alpha_control(ui: &mut egui::Ui, rect: egui::Rect, session: &mut PickerSession) {
let palette = crate::ui::design_system::palette(ui);
checker(ui.painter(), rect, palette.control, palette.elevated);
let response = ui.interact(
rect.expand2(egui::vec2(0.0, 4.0)),
ui.make_persistent_id("penpot_color_alpha"),
egui::Sense::click_and_drag(),
);
if response.clicked() || response.dragged() {
if let Some(position) = response.interact_pointer_pos() {
let mut value = session.current;
value[3] = ((position.x - rect.left()) / rect.width()).clamp(0.0, 1.0);
set_current(session, value);
}
}
let x = egui::lerp(rect.left()..=rect.right(), session.current[3]);
ui.painter().rect_filled(
egui::Rect::from_min_max(rect.min, egui::pos2(x, rect.bottom())),
2.0,
palette.accent.gamma_multiply(0.65),
);
ui.painter().rect_filled(
egui::Rect::from_center_size(egui::pos2(x, rect.center().y), egui::vec2(10.0, 18.0)),
3.0,
palette.text_primary,
);
}
fn paint_hue_wheel(
painter: &egui::Painter,
rect: egui::Rect,
selected_hue: f32,
marker_color: egui::Color32,
) {
let center = rect.center();
let outer = 72.0;
let inner = 54.0;
let mut mesh = egui::Mesh::default();
const SEGMENTS: usize = 72;
for segment in 0..SEGMENTS {
let h0 = segment as f32 / SEGMENTS as f32;
let h1 = (segment + 1) as f32 / SEGMENTS as f32;
let a0 = (h0 - 0.25) * std::f32::consts::TAU;
let a1 = (h1 - 0.25) * std::f32::consts::TAU;
let start = mesh.vertices.len() as u32;
let c0 = egui::Color32::from(Hsva::new(h0, 1.0, 1.0, 1.0));
let c1 = egui::Color32::from(Hsva::new(h1, 1.0, 1.0, 1.0));
for (radius, angle, color) in [
(inner, a0, c0),
(outer, a0, c0),
(outer, a1, c1),
(inner, a1, c1),
] {
mesh.colored_vertex(
center + egui::vec2(angle.cos(), angle.sin()) * radius,
color,
);
}
mesh.add_triangle(start, start + 1, start + 2);
mesh.add_triangle(start, start + 2, start + 3);
}
painter.add(mesh);
let angle = (selected_hue - 0.25) * std::f32::consts::TAU;
let marker = center + egui::vec2(angle.cos(), angle.sin()) * 63.0;
painter.circle_stroke(marker, 5.0, egui::Stroke::new(2.0_f32, marker_color));
}
fn paint_sv(
painter: &egui::Painter,
rect: egui::Rect,
hue: f32,
saturation: f32,
value: f32,
marker_color: egui::Color32,
) {
let mut mesh = egui::Mesh::default();
for (position, color) in [
(rect.left_top(), egui::Color32::WHITE),
(
rect.right_top(),
egui::Color32::from(Hsva::new(hue, 1.0, 1.0, 1.0)),
),
(rect.right_bottom(), egui::Color32::BLACK),
(rect.left_bottom(), egui::Color32::BLACK),
] {
mesh.colored_vertex(position, color);
}
mesh.add_triangle(0, 1, 2);
mesh.add_triangle(0, 2, 3);
painter.add(mesh);
let marker = egui::pos2(
egui::lerp(rect.x_range(), saturation),
egui::lerp(rect.y_range(), 1.0 - value),
);
painter.circle_stroke(marker, 5.0, egui::Stroke::new(2.0_f32, marker_color));
}
pub(super) fn checker(
painter: &egui::Painter,
rect: egui::Rect,
dark: egui::Color32,
light: egui::Color32,
) {
let size = 6.0;
let columns = (rect.width() / size).ceil() as usize;
let rows = (rect.height() / size).ceil() as usize;
for row in 0..rows {
for column in 0..columns {
let cell = egui::Rect::from_min_size(
rect.min + egui::vec2(column as f32 * size, row as f32 * size),
egui::vec2(size, size),
)
.intersect(rect);
painter.rect_filled(
cell,
0.0,
if (row + column) % 2 == 0 { dark } else { light },
);
}
}
}
fn paint_swatch(
ui: &mut egui::Ui,
rect: egui::Rect,
color: egui::Color32,
sense: egui::Sense,
tooltip: &str,
) -> egui::Response {
let palette = crate::ui::design_system::palette(ui);
checker(ui.painter(), rect, palette.control, palette.elevated);
ui.painter().rect_filled(rect.shrink(1.0), 3.0, color);
ui.painter().rect_stroke(
rect,
3.0,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
ui.interact(
rect,
ui.make_persistent_id(("color_swatch", rect.min.x.to_bits(), rect.min.y.to_bits())),
sense,
)
.on_hover_text(tooltip)
}
fn icon_button(
ui: &mut egui::Ui,
rect: egui::Rect,
icon: Icon,
tooltip: &str,
enabled: bool,
) -> egui::Response {
let palette = crate::ui::design_system::palette(ui);
ui.put(
rect,
egui::Button::new(egui::RichText::new(icon.as_str()).font(egui::FontId::new(
13.0,
egui::FontFamily::Name("phosphor-regular".into()),
)))
.fill(palette.control)
.stroke(egui::Stroke::new(1.0_f32, palette.border))
.corner_radius(4.0)
.sense(if enabled {
egui::Sense::click()
} else {
egui::Sense::hover()
}),
)
.on_hover_text(tooltip)
}
fn bare_icon(
ui: &mut egui::Ui,
rect: egui::Rect,
icon: Icon,
tooltip: &str,
color: egui::Color32,
) -> egui::Response {
let response = ui.interact(
rect,
ui.make_persistent_id(("color_icon", tooltip)),
if tooltip == PLANNED_EYEDROPPER {
egui::Sense::hover()
} else {
egui::Sense::click()
},
);
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
icon.as_str(),
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-regular".into())),
color,
);
response.on_hover_text(tooltip)
}
fn labeled_button(
ui: &mut egui::Ui,
rect: egui::Rect,
icon: Icon,
label: &str,
accent: bool,
) -> egui::Response {
let palette = crate::ui::design_system::palette(ui);
ui.push_id(("color_picker_footer_action", label), |ui| {
ui.put(
rect,
egui::Button::new(crate::ui::design_system::controls::icon_label(
icon,
label,
TypeRole::Control,
12.0,
palette.text_primary,
))
.fill(if accent {
palette.accent
} else {
palette.control
})
.stroke(egui::Stroke::new(
1.0_f32,
if accent {
palette.accent
} else {
palette.border
},
))
.corner_radius(4.0),
)
})
.inner
}
fn field_background(ui: &egui::Ui, rect: egui::Rect) {
let palette = crate::ui::design_system::palette(ui);
ui.painter().rect(
rect,
4.0,
palette.control,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
}
fn caption(ui: &egui::Ui, root: egui::Rect, x: f32, y: f32, value: &str) {
let palette = crate::ui::design_system::palette(ui);
text(
ui,
root.min + egui::vec2(x, y),
egui::Align2::LEFT_TOP,
value,
TypeRole::Caption.font(),
palette.text_muted,
);
}
fn text(
ui: &egui::Ui,
position: egui::Pos2,
align: egui::Align2,
value: &str,
font: egui::FontId,
color: egui::Color32,
) {
ui.painter().text(position, align, value, font, color);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exported_popup_regions_match_penpot_geometry() {
assert_eq!(POPUP_SIZE, egui::vec2(420.0, 350.0));
assert_eq!(Geometry::HEADER_HEIGHT, 38.0);
assert_eq!(Geometry::CONTENT.size(), egui::vec2(396.0, 202.0));
assert_eq!(Geometry::WHEEL_EDITOR.size(), egui::vec2(178.0, 202.0));
assert_eq!(Geometry::VALUES.size(), egui::vec2(198.0, 186.0));
assert_eq!(Geometry::RECENTS.size(), egui::vec2(396.0, 28.0));
assert_eq!(Geometry::FOOTER.size(), egui::vec2(396.0, 26.0));
}
#[test]
fn exported_value_and_action_fields_retain_exact_sizes() {
let root = egui::Rect::from_min_size(egui::Pos2::ZERO, POPUP_SIZE);
assert_eq!(
Geometry::at(root, 198.0, 144.0, 166.0, 24.0).size(),
egui::vec2(166.0, 24.0)
);
assert_eq!(
Geometry::at(root, 370.0, 144.0, 26.0, 24.0).size(),
egui::vec2(26.0, 24.0)
);
assert_eq!(
Geometry::at(root, 240.0, 256.0, 156.0, 14.0).size(),
egui::vec2(156.0, 14.0)
);
assert_eq!(
Geometry::at(root, 334.0, 316.0, 74.0, 26.0).size(),
egui::vec2(74.0, 26.0)
);
}
#[test]
fn disabled_eyedropper_has_no_state_or_action_contract() {
assert_eq!(PLANNED_EYEDROPPER, "Planned — screen sampling pending");
}
}
@@ -0,0 +1,167 @@
//! Fixed Penpot geometry for the color picker's RGBA and HSV channel modes.
use bevy_egui::egui::{self, ecolor::Hsva};
use super::super::{byte, set_current, PickerSession};
use super::{caption, text, Geometry};
use crate::ui::design_system::typography::TypeRole;
/// Each 186 px channel group owns a 178 px row: a single-letter channel label,
/// a 104 px track, and a 44 px value field.
struct SliderGeometry;
impl SliderGeometry {
const RGBA_X: f32 = 12.0;
const HSV_X: f32 = 206.0;
const TITLE_Y: f32 = 74.0;
const FIRST_ROW_Y: f32 = 90.0;
const ROW_STRIDE: f32 = 30.0;
const LABEL_WIDTH: f32 = 18.0;
const TRACK_X: f32 = 24.0;
const TRACK_WIDTH: f32 = 104.0;
const VALUE_X: f32 = 134.0;
const VALUE_WIDTH: f32 = 44.0;
const ROW_HEIGHT: f32 = 24.0;
}
pub(super) fn show(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let palette = crate::ui::design_system::palette(ui);
let content = Geometry::rect(root, Geometry::CONTENT);
ui.painter().rect_filled(content, 4.0, palette.recessed);
caption(
ui,
root,
SliderGeometry::RGBA_X,
SliderGeometry::TITLE_Y,
"RGBA CHANNELS",
);
caption(
ui,
root,
SliderGeometry::HSV_X,
SliderGeometry::TITLE_Y,
"HSV CHANNELS",
);
let mut bytes = session.current.map(|component| f32::from(byte(component)));
let before_bytes = bytes;
for (index, label) in ["R", "G", "B", "A"].into_iter().enumerate() {
slider_channel(
ui,
root,
SliderGeometry::RGBA_X,
index,
label,
&mut bytes[index],
0.0..=255.0,
"",
);
}
if bytes != before_bytes {
set_current(session, bytes.map(|component| component / 255.0));
}
let mut hsva = Hsva::from_rgba_unmultiplied(
session.current[0],
session.current[1],
session.current[2],
session.current[3],
);
let mut values = [
hsva.h * 360.0,
hsva.s * 100.0,
hsva.v * 100.0,
hsva.a * 100.0,
];
let before = values;
for (index, label) in ["H", "S", "V", "A"].into_iter().enumerate() {
let range = if index == 0 { 0.0..=360.0 } else { 0.0..=100.0 };
slider_channel(
ui,
root,
SliderGeometry::HSV_X,
index,
label,
&mut values[index],
range,
if index == 0 { "°" } else { "%" },
);
}
if values != before {
hsva.h = values[0] / 360.0;
hsva.s = values[1] / 100.0;
hsva.v = values[2] / 100.0;
hsva.a = values[3] / 100.0;
let [r, g, b] = hsva.to_rgb();
set_current(session, [r, g, b, hsva.a]);
}
}
#[allow(clippy::too_many_arguments)]
fn slider_channel(
ui: &mut egui::Ui,
root: egui::Rect,
group_x: f32,
index: usize,
label: &str,
value: &mut f32,
range: std::ops::RangeInclusive<f32>,
suffix: &str,
) {
let palette = crate::ui::design_system::palette(ui);
let y = SliderGeometry::FIRST_ROW_Y + index as f32 * SliderGeometry::ROW_STRIDE;
let label_rect = Geometry::at(
root,
group_x,
y,
SliderGeometry::LABEL_WIDTH,
SliderGeometry::ROW_HEIGHT,
);
text(
ui,
label_rect.left_center(),
egui::Align2::LEFT_CENTER,
label,
TypeRole::Body.font(),
palette.text_secondary,
);
ui.put(
Geometry::at(
root,
group_x + SliderGeometry::TRACK_X,
y,
SliderGeometry::TRACK_WIDTH,
SliderGeometry::ROW_HEIGHT,
),
egui::Slider::new(value, range.clone()).show_value(false),
);
ui.put(
Geometry::at(
root,
group_x + SliderGeometry::VALUE_X,
y,
SliderGeometry::VALUE_WIDTH,
SliderGeometry::ROW_HEIGHT,
),
egui::DragValue::new(value)
.range(range)
.suffix(suffix)
.max_decimals(0),
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sliders_mode_matches_the_two_exported_channel_groups() {
assert_eq!(SliderGeometry::HSV_X - SliderGeometry::RGBA_X, 194.0);
assert_eq!(SliderGeometry::TRACK_WIDTH, 104.0);
assert_eq!(SliderGeometry::VALUE_WIDTH, 44.0);
assert_eq!(SliderGeometry::VALUE_X + SliderGeometry::VALUE_WIDTH, 178.0);
assert_eq!(SliderGeometry::ROW_STRIDE, 30.0);
assert_eq!(SliderGeometry::ROW_HEIGHT, 24.0);
}
}
@@ -0,0 +1,356 @@
//! Reusable Penpot-styled editor controls with no world or asset-store access.
use bevy_egui::egui;
use egui_phosphor_icons::{icons, Icon};
use std::ops::RangeInclusive;
use super::palette;
use super::typography::TypeRole;
const SCALAR_CONTROL_WIDTH: f32 = 132.0;
const SCALAR_TRACK_X: f32 = 0.0;
const SCALAR_TRACK_WIDTH: f32 = 78.0;
const SCALAR_TRACK_INTERACTION_HEIGHT: f32 = 10.0;
const SCALAR_NUMBER_X: f32 = 84.0;
const SCALAR_NUMBER_WIDTH: f32 = 48.0;
const SCALAR_THUMB_RADIUS: f32 = 4.0;
pub(crate) fn section_frame(ui: &egui::Ui) -> egui::Frame {
let palette = palette(ui);
egui::Frame::new()
.fill(palette.section)
.stroke(egui::Stroke::new(1.0_f32, palette.border))
.corner_radius(egui::CornerRadius::same(5))
}
pub(crate) fn section_header(ui: &mut egui::Ui, title: &str, open: &mut bool) -> egui::Response {
section_header_with_summary(ui, title, None, open)
}
pub(crate) fn section_header_with_summary(
ui: &mut egui::Ui,
title: &str,
summary: Option<&str>,
open: &mut bool,
) -> egui::Response {
let palette = palette(ui);
let (rect, response) = ui.allocate_exact_size(
egui::vec2(
ui.available_width().max(1.0),
super::INPUT_SECTION_HEADER_HEIGHT,
),
egui::Sense::click(),
);
ui.painter().rect_filled(rect, 4.0, palette.elevated);
ui.painter().text(
rect.left_center() + egui::vec2(12.0, 0.0),
egui::Align2::CENTER_CENTER,
if *open {
icons::CARET_DOWN.as_str()
} else {
icons::CARET_RIGHT.as_str()
},
egui::FontId::new(10.0, egui::FontFamily::Name("phosphor-regular".into())),
palette.text_secondary,
);
ui.painter().text(
rect.left_center() + egui::vec2(28.0, 0.0),
egui::Align2::LEFT_CENTER,
title,
TypeRole::Section.font(),
palette.text_primary,
);
if let Some(summary) = summary {
ui.painter().text(
rect.right_center() - egui::vec2(12.0, 0.0),
egui::Align2::RIGHT_CENTER,
summary,
TypeRole::Small.font(),
palette.text_muted,
);
}
if response.clicked() {
*open = !*open;
}
response
}
/// Compose a Phosphor glyph and Source Sans label without asking either font to render the
/// other's codepoints. This is the canonical path for icon-plus-text controls in a design-system
/// scope.
pub(crate) fn icon_label(
icon: Icon,
label: &str,
role: TypeRole,
icon_size: f32,
color: egui::Color32,
) -> egui::WidgetText {
let mut job = egui::text::LayoutJob::default();
job.append(
icon.as_str(),
0.0,
egui::TextFormat {
font_id: egui::FontId::new(
icon_size,
egui::FontFamily::Name("phosphor-regular".into()),
),
color,
..Default::default()
},
);
if !label.is_empty() {
job.append(
label,
6.0,
egui::TextFormat {
font_id: role.font(),
color,
..Default::default()
},
);
}
job.into()
}
pub(crate) fn icon_button(
ui: &mut egui::Ui,
icon: Icon,
tooltip: &str,
enabled: bool,
) -> egui::Response {
let palette = palette(ui);
let response = ui.add_enabled(
enabled,
egui::Button::new(egui::RichText::new(icon.as_str()).font(egui::FontId::new(
14.0,
egui::FontFamily::Name("phosphor-regular".into()),
)))
.min_size(egui::vec2(24.0, 24.0))
.fill(palette.control)
.stroke(egui::Stroke::new(1.0_f32, palette.border))
.corner_radius(egui::CornerRadius::same(4)),
);
response.on_hover_text(tooltip)
}
pub(crate) fn status(ui: &mut egui::Ui, color: egui::Color32, label: &str, tooltip: &str) {
let palette = palette(ui);
let (dot, response) = ui.allocate_exact_size(egui::vec2(8.0, 14.0), egui::Sense::hover());
ui.painter().circle_filled(dot.center(), 4.0, color);
response.on_hover_text(tooltip);
ui.label(TypeRole::Body.text(label).color(palette.text_secondary));
}
pub(crate) fn switch(ui: &mut egui::Ui, value: &mut bool) -> egui::Response {
let palette = palette(ui);
let (rect, mut response) = ui.allocate_exact_size(egui::vec2(31.0, 16.0), egui::Sense::click());
if response.clicked() {
*value = !*value;
response.mark_changed();
}
let fill = if *value {
palette.accent_dark
} else {
palette.control
};
let stroke = if *value {
palette.accent
} else {
palette.border_strong
};
ui.painter().rect(
rect,
8.0,
fill,
egui::Stroke::new(1.0_f32, stroke),
egui::StrokeKind::Inside,
);
let x = if *value {
rect.right() - 8.0
} else {
rect.left() + 8.0
};
ui.painter()
.circle_filled(egui::pos2(x, rect.center().y), 5.0, palette.text_primary);
response
}
/// Fixed 128×24 two-option control used by the Penpot material Surface section.
///
/// Returning the selected side keeps the control independent from material state and prevents
/// stock `selectable_label` padding from changing its geometry.
pub(crate) fn two_option_segmented(
ui: &mut egui::Ui,
left_label: &str,
right_label: &str,
right_selected: bool,
) -> Option<bool> {
const WIDTH: f32 = 128.0;
const HEIGHT: f32 = 24.0;
const OPTION_WIDTH: f32 = WIDTH * 0.5;
let palette = palette(ui);
let (rect, _) = ui.allocate_exact_size(egui::vec2(WIDTH, HEIGHT), egui::Sense::hover());
ui.painter().rect(
rect,
4.0,
palette.control,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
let left = egui::Rect::from_min_size(rect.min, egui::vec2(OPTION_WIDTH, HEIGHT));
let right = egui::Rect::from_min_size(
rect.min + egui::vec2(OPTION_WIDTH, 0.0),
egui::vec2(OPTION_WIDTH, HEIGHT),
);
let mut selection = None;
for (option_rect, label, selected, value) in [
(left, left_label, !right_selected, false),
(right, right_label, right_selected, true),
] {
let response = ui.interact(
option_rect,
ui.make_persistent_id(("two_option_segment", label)),
egui::Sense::click(),
);
let fill = if selected {
palette.accent_dark
} else if response.hovered() {
palette.elevated
} else {
palette.control
};
ui.painter().rect_filled(option_rect.shrink(1.0), 3.0, fill);
if selected {
ui.painter().rect_stroke(
option_rect,
3.0,
egui::Stroke::new(1.0_f32, palette.accent),
egui::StrokeKind::Inside,
);
}
ui.painter().text(
option_rect.center(),
egui::Align2::CENTER_CENTER,
label,
TypeRole::Control.font(),
if selected {
palette.text_primary
} else {
palette.text_secondary
},
);
if response.clicked() && right_selected != value {
selection = Some(value);
}
}
selection
}
/// Exact Penpot scalar editor used by material inputs.
///
/// The track and numeric field are painted as independent controls so egui's stock slider
/// padding cannot move the thumb into the value field at the reference width.
pub(crate) fn scalar_control(
ui: &mut egui::Ui,
salt: impl std::hash::Hash,
value: &mut f32,
range: RangeInclusive<f32>,
max_decimals: usize,
) -> egui::Response {
let palette = palette(ui);
let before = *value;
let width = SCALAR_CONTROL_WIDTH.min(ui.available_width().max(1.0));
let (rect, base_response) =
ui.allocate_exact_size(egui::vec2(width, 22.0), egui::Sense::hover());
let number_width = SCALAR_NUMBER_WIDTH.min(width);
let number_x = SCALAR_NUMBER_X.min((width - number_width).max(0.0));
let track_width = SCALAR_TRACK_WIDTH.min((number_x - 6.0).max(1.0));
let slider_rect = egui::Rect::from_min_size(
rect.min + egui::vec2(SCALAR_TRACK_X, 6.0),
egui::vec2(track_width, SCALAR_TRACK_INTERACTION_HEIGHT),
);
let track_rect =
egui::Rect::from_center_size(slider_rect.center(), egui::vec2(track_width, 3.0));
let slider_response = ui.interact(
slider_rect,
ui.make_persistent_id(("penpot_scalar", salt)),
egui::Sense::click_and_drag(),
);
if slider_response.clicked() || slider_response.dragged() {
if let Some(pointer) = slider_response.interact_pointer_pos() {
let start = *range.start();
let end = *range.end();
let normalized = ((pointer.x - track_rect.left()) / track_rect.width()).clamp(0.0, 1.0);
*value = egui::lerp(start..=end, normalized);
}
}
let start = *range.start();
let end = *range.end();
let normalized = if end > start {
((*value - start) / (end - start)).clamp(0.0, 1.0)
} else {
0.0
};
ui.painter().rect_filled(track_rect, 2.0, palette.border);
let fill = egui::Rect::from_min_max(
track_rect.left_top(),
egui::pos2(
egui::lerp(track_rect.x_range(), normalized),
track_rect.bottom(),
),
);
ui.painter().rect_filled(fill, 2.0, palette.accent);
let thumb_center = egui::pos2(
egui::lerp(track_rect.x_range(), normalized),
track_rect.center().y,
);
ui.painter().circle(
thumb_center,
SCALAR_THUMB_RADIUS,
palette.text_primary,
egui::Stroke::new(1.0_f32, palette.accent),
);
let number_rect = egui::Rect::from_min_size(
rect.min + egui::vec2(number_x, 0.0),
egui::vec2(number_width, 22.0),
);
let number_response = ui.put(
number_rect,
egui::DragValue::new(value)
.speed(0.01)
.range(range)
.max_decimals(max_decimals),
);
let mut response = base_response.union(slider_response).union(number_response);
if *value != before {
response.mark_changed();
}
response
}
#[cfg(test)]
mod scalar_tests {
use super::*;
#[test]
fn penpot_scalar_geometry_matches_the_current_export() {
assert!((SCALAR_NUMBER_X - (SCALAR_TRACK_X + SCALAR_TRACK_WIDTH) - 6.0).abs() < 0.001);
assert_eq!(SCALAR_CONTROL_WIDTH, SCALAR_NUMBER_X + SCALAR_NUMBER_WIDTH);
assert_eq!(SCALAR_TRACK_INTERACTION_HEIGHT, 10.0);
assert_eq!(SCALAR_THUMB_RADIUS, 4.0);
}
}
#[cfg(test)]
mod segmented_tests {
#[test]
fn penpot_segmented_control_has_two_fixed_halves() {
const WIDTH: f32 = 128.0;
const OPTION_WIDTH: f32 = WIDTH * 0.5;
assert_eq!(OPTION_WIDTH, 64.0);
assert_eq!(OPTION_WIDTH * 2.0, WIDTH);
}
}
+154
View File
@@ -0,0 +1,154 @@
//! Penpot-led editor design-system primitives.
//!
//! The first consumer is the Material Slot panel. These semantic tokens and controls are kept
//! independent from material/world state so later editor panels can migrate without copying style.
pub(crate) mod color_picker;
pub(crate) mod controls;
pub(crate) mod property_grid;
pub(crate) mod typography;
use bevy_egui::egui::{self, Color32, CornerRadius, Stroke};
use crate::ui::theme::EditorVisualPalette;
#[cfg(test)]
pub(crate) const REFERENCE_WIDTH: f32 = 620.0;
pub(crate) const INSPECTOR_MIN_WIDTH: f32 = 420.0;
pub(crate) const OUTER_PADDING: f32 = 12.0;
pub(crate) const SECTION_GAP: f32 = 8.0;
pub(crate) const MATERIALS_HEADING_HEIGHT: f32 = 32.0;
pub(crate) const HEADER_HEIGHT: f32 = 82.0;
pub(crate) const COLLAPSED_HEADER_HEIGHT: f32 = 52.0;
pub(crate) const MATERIAL_PREVIEW_SIZE: f32 = 64.0;
pub(crate) const MATERIAL_IDENTITY_WIDTH: f32 = 229.5;
pub(crate) const SURFACE_SECTION_HEIGHT: f32 = 46.0;
pub(crate) const COMPACT_SURFACE_SECTION_HEIGHT: f32 = 46.0;
pub(crate) const INPUT_SECTION_HEADER_HEIGHT: f32 = 24.0;
pub(crate) const PARAMETER_ROW_HEIGHT: f32 = 32.0;
pub(crate) const COMPACT_PARAMETER_ROW_HEIGHT: f32 = 58.0;
pub(crate) const UV_SECTION_HEIGHT: f32 = 54.0;
pub(crate) const COMPACT_UV_SECTION_HEIGHT: f32 = 94.0;
pub(crate) const ADVANCED_COLLAPSED_HEIGHT: f32 = 30.0;
pub(crate) const ADVANCED_EXPANDED_HEIGHT: f32 = 178.0;
pub(crate) const CONTROL_HEIGHT: f32 = 24.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DesignPalette {
pub accent: Color32,
pub accent_dark: Color32,
pub panel: Color32,
pub section: Color32,
pub recessed: Color32,
pub control: Color32,
pub elevated: Color32,
pub row_even: Color32,
pub row_odd: Color32,
pub checker: Color32,
pub border: Color32,
pub border_strong: Color32,
pub text_primary: Color32,
pub text_secondary: Color32,
pub text_muted: Color32,
pub healthy: Color32,
pub warning: Color32,
pub error: Color32,
}
impl From<EditorVisualPalette> for DesignPalette {
fn from(value: EditorVisualPalette) -> Self {
Self {
accent: value.selection,
accent_dark: value.selection_bg,
panel: value.panel,
section: value.widget,
recessed: value.panel_dark,
control: value.widget,
elevated: value.elevated,
row_even: value.panel,
row_odd: value.widget,
checker: value.elevated,
border: value.border,
border_strong: value.border_strong,
text_primary: value.text,
text_secondary: value.text_dim,
text_muted: value.text_muted,
healthy: value.success,
warning: value.warning,
error: value.error,
}
}
}
pub(crate) fn palette(ui: &egui::Ui) -> DesignPalette {
crate::ui::theme::editor_palette(ui.ctx()).into()
}
/// Applies the Penpot material-panel visual language locally without restyling the whole editor.
pub(crate) fn scope<R>(ui: &mut egui::Ui, add_contents: impl FnOnce(&mut egui::Ui) -> R) -> R {
let palette = palette(ui);
ui.scope(|ui| {
let style = ui.style_mut();
style.spacing.item_spacing = egui::vec2(8.0, 4.0);
style.spacing.button_padding = egui::vec2(8.0, 3.0);
style.spacing.interact_size = egui::vec2(31.0, CONTROL_HEIGHT);
style.visuals.widgets.noninteractive.bg_fill = palette.section;
style.visuals.widgets.noninteractive.bg_stroke = Stroke::new(1.0_f32, palette.border);
style.visuals.widgets.noninteractive.fg_stroke =
Stroke::new(1.0_f32, palette.text_secondary);
style.visuals.widgets.inactive.bg_fill = palette.control;
style.visuals.widgets.inactive.weak_bg_fill = palette.control;
style.visuals.widgets.inactive.bg_stroke = Stroke::new(1.0_f32, palette.border);
style.visuals.widgets.inactive.fg_stroke = Stroke::new(1.0_f32, palette.text_primary);
style.visuals.widgets.hovered.bg_fill = palette.elevated;
style.visuals.widgets.hovered.weak_bg_fill = palette.elevated;
style.visuals.widgets.hovered.bg_stroke = Stroke::new(1.0_f32, palette.border_strong);
style.visuals.widgets.hovered.fg_stroke = Stroke::new(1.0_f32, palette.text_primary);
style.visuals.widgets.active.bg_fill = palette.accent_dark;
style.visuals.widgets.active.weak_bg_fill = palette.accent_dark;
style.visuals.widgets.active.bg_stroke = Stroke::new(1.0_f32, palette.accent);
style.visuals.widgets.active.fg_stroke = Stroke::new(1.0_f32, palette.text_primary);
style.visuals.selection.bg_fill = palette.accent_dark;
style.visuals.selection.stroke = Stroke::new(1.0_f32, palette.accent);
style.visuals.window_fill = palette.panel;
style.visuals.window_stroke = Stroke::new(1.0_f32, palette.border_strong);
style.visuals.window_corner_radius = CornerRadius::same(7);
style.visuals.menu_corner_radius = CornerRadius::same(5);
style.visuals.override_text_color = Some(palette.text_primary);
typography::install_local_text_styles(style);
add_contents(ui)
})
.inner
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn penpot_geometry_tokens_are_exact() {
assert_eq!(REFERENCE_WIDTH, 620.0);
assert_eq!(MATERIALS_HEADING_HEIGHT, 32.0);
assert_eq!(HEADER_HEIGHT, 82.0);
assert_eq!(COLLAPSED_HEADER_HEIGHT, 52.0);
assert_eq!(MATERIAL_PREVIEW_SIZE, 64.0);
assert_eq!(MATERIAL_IDENTITY_WIDTH, 229.5);
assert_eq!(SURFACE_SECTION_HEIGHT, 46.0);
assert_eq!(COMPACT_SURFACE_SECTION_HEIGHT, 46.0);
assert_eq!(INPUT_SECTION_HEADER_HEIGHT, 24.0);
assert_eq!(PARAMETER_ROW_HEIGHT, 32.0);
assert_eq!(COMPACT_PARAMETER_ROW_HEIGHT, 58.0);
assert_eq!(UV_SECTION_HEIGHT, 54.0);
assert_eq!(COMPACT_UV_SECTION_HEIGHT, 94.0);
assert_eq!(ADVANCED_COLLAPSED_HEIGHT, 30.0);
assert_eq!(ADVANCED_EXPANDED_HEIGHT, 178.0);
}
#[test]
fn material_design_palette_uses_blacksite_semantics() {
let palette = DesignPalette::from(crate::ui::theme::BLACKSITE_PALETTE);
assert_eq!(palette.accent, crate::ui::theme::SELECTION);
assert_eq!(palette.panel, crate::ui::theme::PANEL_BG);
assert_eq!(palette.text_primary, crate::ui::theme::TEXT);
}
}
@@ -0,0 +1,260 @@
//! Testable geometry for dense Penpot material property rows.
use super::{COMPACT_PARAMETER_ROW_HEIGHT, PARAMETER_ROW_HEIGHT};
use bevy_egui::egui;
pub(crate) const WIDE_SECTION_WIDTH: f32 = 569.0;
pub(crate) const RESPONSIVE_BREAKPOINT: f32 = WIDE_SECTION_WIDTH;
/// The actor component chrome can consume up to twelve pixels of the exported 372 px compact
/// canvas. At 360 px the complete texture row still fits: 12 px inset + 336 px group + 12 px inset.
const COMPACT_INLINE_ACTION_FIT_WIDTH: f32 = 357.0;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct PropertyGridGeometry {
pub stacked: bool,
pub row_height: f32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct PropertyRowRects {
pub row: egui::Rect,
pub label: egui::Rect,
pub value: egui::Rect,
pub channel: egui::Rect,
pub texture_group: egui::Rect,
pub texture_field: egui::Rect,
pub locate: egui::Rect,
pub clear: egui::Rect,
pub inline_texture_actions: bool,
}
impl PropertyGridGeometry {
pub(crate) fn for_width(section_width: f32) -> Self {
if section_width + f32::EPSILON >= RESPONSIVE_BREAKPOINT {
Self {
stacked: false,
row_height: PARAMETER_ROW_HEIGHT,
}
} else {
Self {
stacked: true,
row_height: COMPACT_PARAMETER_ROW_HEIGHT,
}
}
}
pub(crate) fn row_rects(self, row: egui::Rect) -> PropertyRowRects {
let inset = 12.0_f32.min(row.width() * 0.5);
let inner_width = (row.width() - inset * 2.0).max(1.0);
if !self.stacked {
let texture_group_width = (inner_width - 286.5).max(60.0);
let texture_field_width = (texture_group_width - 60.0).max(1.0);
let texture_group = egui::Rect::from_min_size(
row.min + egui::vec2(298.5, 5.0),
egui::vec2(texture_group_width, 22.0),
);
return PropertyRowRects {
row,
label: egui::Rect::from_min_size(
row.min + egui::vec2(12.0, 5.0),
egui::vec2(82.0, 22.0),
),
value: egui::Rect::from_min_size(
row.min + egui::vec2(96.0, 5.0),
egui::vec2(132.0, 22.0),
),
channel: egui::Rect::from_min_size(
row.min + egui::vec2(234.0, 5.0),
egui::vec2(48.0, 22.0),
),
texture_group,
texture_field: egui::Rect::from_min_size(
texture_group.min,
egui::vec2(texture_field_width, 22.0),
),
locate: egui::Rect::from_min_size(
texture_group.min + egui::vec2(texture_field_width + 6.0, 0.0),
egui::vec2(24.0, 22.0),
),
clear: egui::Rect::from_min_size(
texture_group.min + egui::vec2(texture_field_width + 36.0, 0.0),
egui::vec2(24.0, 22.0),
),
inline_texture_actions: true,
};
}
let channel_width = 48.0_f32.min(inner_width);
let channel_x = inset + inner_width - channel_width;
let value_x = (inset + 84.0).min(channel_x);
let value_width = (channel_x - value_x - 6.35).max(1.0);
let texture_group = egui::Rect::from_min_size(
row.min + egui::vec2(inset, 31.0),
egui::vec2(inner_width, 22.0),
);
let inline_texture_actions = row.width() + f32::EPSILON >= COMPACT_INLINE_ACTION_FIT_WIDTH;
let texture_field_width = if inline_texture_actions {
(inner_width - 60.0).max(1.0)
} else {
(inner_width - 30.0).max(1.0)
};
let overflow_or_locate_x = texture_field_width + 6.0;
PropertyRowRects {
row,
label: egui::Rect::from_min_size(
row.min + egui::vec2(inset, 5.0),
egui::vec2(78.0_f32.min(inner_width), 22.0),
),
value: egui::Rect::from_min_size(
row.min + egui::vec2(value_x, 5.0),
egui::vec2(value_width, 22.0),
),
channel: egui::Rect::from_min_size(
row.min + egui::vec2(channel_x, 5.0),
egui::vec2(channel_width, 22.0),
),
texture_group,
texture_field: egui::Rect::from_min_size(
texture_group.min,
egui::vec2(texture_field_width, 22.0),
),
locate: egui::Rect::from_min_size(
texture_group.min + egui::vec2(overflow_or_locate_x, 0.0),
egui::vec2(24.0, 22.0),
),
clear: egui::Rect::from_min_size(
texture_group.min
+ egui::vec2(
if inline_texture_actions {
texture_field_width + 36.0
} else {
inner_width
},
0.0,
),
egui::vec2(if inline_texture_actions { 24.0 } else { 0.0 }, 22.0),
),
inline_texture_actions,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn penpot_exact_reference_geometry_matches_columns() {
let geometry = PropertyGridGeometry::for_width(569.0);
assert!(!geometry.stacked);
assert_eq!(geometry.row_height, 32.0);
}
#[test]
fn penpot_below_reference_width_reflows_without_compression() {
let geometry = PropertyGridGeometry::for_width(568.0);
assert!(geometry.stacked);
assert_eq!(geometry.row_height, 58.0);
}
#[test]
fn row_rects_match_exported_wide_geometry() {
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(569.0, 32.0));
let rects = PropertyGridGeometry::for_width(569.0).row_rects(row);
assert_eq!(rects.label.min, egui::pos2(12.0, 5.0));
assert_eq!(rects.value.min, egui::pos2(96.0, 5.0));
assert!((rects.value.width() - 132.0).abs() < 0.001);
assert_eq!(rects.value.height(), 22.0);
assert_eq!(
rects.channel,
egui::Rect::from_min_size(egui::pos2(234.0, 5.0), egui::vec2(48.0, 22.0))
);
assert_eq!(
rects.texture_group,
egui::Rect::from_min_size(egui::pos2(298.5, 5.0), egui::vec2(258.5, 22.0))
);
assert_eq!(rects.texture_field.size(), egui::vec2(198.5, 22.0));
assert_eq!(rects.locate.min, egui::pos2(503.0, 5.0));
assert_eq!(rects.clear.min, egui::pos2(533.0, 5.0));
assert!(rects.inline_texture_actions);
}
#[test]
fn row_rects_match_exported_compact_geometry() {
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(369.0, 58.0));
let rects = PropertyGridGeometry::for_width(369.0).row_rects(row);
assert_eq!(rects.label.min, egui::pos2(12.0, 5.0));
assert_eq!(rects.value.min, egui::pos2(96.0, 5.0));
assert_eq!(
rects.channel,
egui::Rect::from_min_size(egui::pos2(309.0, 5.0), egui::vec2(48.0, 22.0))
);
assert_eq!(
rects.texture_group,
egui::Rect::from_min_size(egui::pos2(12.0, 31.0), egui::vec2(345.0, 22.0))
);
assert_eq!(rects.texture_field.size(), egui::vec2(285.0, 22.0));
assert_eq!(rects.locate.min, egui::pos2(303.0, 31.0));
assert_eq!(rects.clear.min, egui::pos2(333.0, 31.0));
assert!(rects.inline_texture_actions);
}
#[test]
fn transient_row_rects_are_finite_and_contained() {
for width in [356.0, 300.0, 240.0] {
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 58.0));
let rects = PropertyGridGeometry::for_width(width).row_rects(row);
for rect in [
rects.label,
rects.value,
rects.channel,
rects.texture_group,
rects.texture_field,
rects.locate,
rects.clear,
] {
assert!(rect.is_finite());
assert!(row.contains_rect(rect));
}
assert!(!rects.inline_texture_actions);
}
}
#[test]
fn inspector_chrome_reduced_floor_keeps_compact_texture_actions() {
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(363.0, 58.0));
let rects = PropertyGridGeometry::for_width(363.0).row_rects(row);
assert!(rects.inline_texture_actions);
assert_eq!(rects.texture_group.min, egui::pos2(12.0, 31.0));
assert_eq!(rects.texture_group.max, egui::pos2(351.0, 53.0));
assert!(row.contains_rect(rects.locate));
assert!(row.contains_rect(rects.clear));
}
#[test]
fn penpot_wide_growth_only_expands_texture_field() {
let reference_row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(569.0, 32.0));
let wide_row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(669.0, 32.0));
let reference = PropertyGridGeometry::for_width(569.0).row_rects(reference_row);
let wide = PropertyGridGeometry::for_width(669.0).row_rects(wide_row);
assert_eq!(wide.label, reference.label);
assert_eq!(wide.value, reference.value);
assert_eq!(wide.channel, reference.channel);
assert_eq!(
wide.texture_field.width(),
reference.texture_field.width() + 100.0
);
}
#[test]
fn penpot_very_narrow_first_line_never_exceeds_inner_width() {
let geometry = PropertyGridGeometry::for_width(300.0);
assert!(geometry.stacked);
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 58.0));
let rects = geometry.row_rects(row);
assert!(row.contains_rect(rects.label));
assert!(row.contains_rect(rects.value));
assert!(row.contains_rect(rects.channel));
assert_eq!(rects.texture_group.width(), 276.0);
}
}
@@ -0,0 +1,80 @@
//! Source Sans typography roles used by the Penpot-led editor visual system.
use bevy_egui::egui::{self, FontFamily, FontId, RichText, Style, TextStyle};
use crate::ui::fonts::{SOURCE_SANS_BOLD, SOURCE_SANS_REGULAR};
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum TypeRole {
Caption,
Small,
Body,
Control,
Section,
Title,
}
impl TypeRole {
pub(crate) const fn size(self) -> f32 {
match self {
Self::Caption => 9.0,
Self::Small => 10.0,
Self::Body => 11.0,
Self::Control => 12.0,
Self::Section => 12.0,
Self::Title => 16.0,
}
}
pub(crate) const fn bold(self) -> bool {
matches!(self, Self::Section | Self::Title)
}
pub(crate) fn font(self) -> FontId {
let family = if self.bold() {
SOURCE_SANS_BOLD
} else {
SOURCE_SANS_REGULAR
};
FontId::new(self.size(), FontFamily::Name(family.into()))
}
pub(crate) fn text(self, value: impl Into<String>) -> RichText {
RichText::new(value).font(self.font())
}
}
pub(crate) fn install_local_text_styles(style: &mut Style) {
style
.text_styles
.insert(TextStyle::Body, TypeRole::Body.font());
style
.text_styles
.insert(TextStyle::Button, TypeRole::Control.font());
style
.text_styles
.insert(TextStyle::Small, TypeRole::Small.font());
style
.text_styles
.insert(TextStyle::Heading, TypeRole::Title.font());
style.text_styles.insert(
TextStyle::Monospace,
FontId::new(11.0, egui::FontFamily::Monospace),
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn penpot_type_scale_and_weights_are_stable() {
assert_eq!(TypeRole::Caption.size(), 9.0);
assert_eq!(TypeRole::Small.size(), 10.0);
assert_eq!(TypeRole::Body.size(), 11.0);
assert_eq!(TypeRole::Section.size(), 12.0);
assert_eq!(TypeRole::Title.size(), 16.0);
assert!(!TypeRole::Body.bold());
assert!(TypeRole::Section.bold());
}
}
+38
View File
@@ -0,0 +1,38 @@
//! Shared authored-document state presentation for editor authoring surfaces.
use bevy_egui::egui;
use crate::asset_documents::{
AuthoredDocumentSnapshot, AuthoredDocumentState, DerivedProcessingState,
};
use super::theme::{ACCENT, ERROR, WARNING};
pub(crate) fn authored_document_status_ui(ui: &mut egui::Ui, snapshot: &AuthoredDocumentSnapshot) {
ui.horizontal_wrapped(|ui| {
if snapshot.dirty {
ui.small(egui::RichText::new("UNSAVED").color(WARNING).strong());
}
match snapshot.state {
AuthoredDocumentState::ExternalConflict => {
ui.small(egui::RichText::new("CONFLICT").color(ERROR).strong());
}
AuthoredDocumentState::SaveFailed => {
ui.small(egui::RichText::new("SAVE FAILED").color(ERROR).strong());
}
AuthoredDocumentState::Saving => {
ui.small(egui::RichText::new("SAVING").color(ACCENT));
}
AuthoredDocumentState::Clean | AuthoredDocumentState::Dirty => {}
}
match snapshot.processing {
DerivedProcessingState::Queued | DerivedProcessingState::Processing => {
ui.small(egui::RichText::new("PROCESSING").color(ACCENT));
}
DerivedProcessingState::Failed => {
ui.small(egui::RichText::new("PROCESS FAILED").color(ERROR));
}
DerivedProcessingState::Idle => {}
}
});
}
+37 -2
View File
@@ -1,7 +1,11 @@
//! Phosphor icon font registration for the primary egui context.
//! Editor text and icon font registration for the primary egui context.
use bevy::prelude::*;
use bevy_egui::{EguiContext, PrimaryEguiContext};
use std::sync::Arc;
pub(crate) const SOURCE_SANS_REGULAR: &str = "blacksite-source-sans-regular";
pub(crate) const SOURCE_SANS_BOLD: &str = "blacksite-source-sans-bold";
pub struct EditorFontsPlugin;
@@ -15,9 +19,40 @@ fn configure_editor_fonts(mut contexts: Query<&mut EguiContext, Added<PrimaryEgu
let Some(mut ctx) = contexts.iter_mut().next() else {
return;
};
ctx.get_mut().set_fonts(editor_font_definitions());
}
pub(crate) fn editor_font_definitions() -> bevy_egui::egui::FontDefinitions {
let mut fonts = bevy_egui::egui::FontDefinitions::default();
egui_phosphor_icons::add_fonts(&mut fonts);
fonts.font_data.insert(
SOURCE_SANS_REGULAR.to_owned(),
Arc::new(bevy_egui::egui::FontData::from_static(include_bytes!(
"../../assets/fonts/source-sans/SourceSansPro-Regular.ttf"
))),
);
fonts.font_data.insert(
SOURCE_SANS_BOLD.to_owned(),
Arc::new(bevy_egui::egui::FontData::from_static(include_bytes!(
"../../assets/fonts/source-sans/SourceSansPro-Bold.ttf"
))),
);
let proportional = fonts
.families
.entry(bevy_egui::egui::FontFamily::Proportional)
.or_default();
proportional.insert(0, SOURCE_SANS_REGULAR.to_owned());
fonts.families.insert(
bevy_egui::egui::FontFamily::Name(SOURCE_SANS_REGULAR.into()),
vec![SOURCE_SANS_REGULAR.to_owned()],
);
fonts.families.insert(
bevy_egui::egui::FontFamily::Name(SOURCE_SANS_BOLD.into()),
vec![SOURCE_SANS_BOLD.to_owned(), SOURCE_SANS_REGULAR.to_owned()],
);
// Phosphor families contain icon glyphs only. Text fallbacks give egui a
// replacement glyph for malformed/missing icons without changing icon lookup.
let text_fallbacks = fonts
@@ -38,5 +73,5 @@ fn configure_editor_fonts(mut contexts: Query<&mut EguiContext, Added<PrimaryEgu
}
}
}
ctx.get_mut().set_fonts(fonts);
fonts
}
+5 -5
View File
@@ -252,7 +252,7 @@ fn draw_root_drop_zone(
} else {
PANEL_BG_DARK
},
egui::Stroke::new(1.0, if hovered { SELECTION } else { TEXT_MUTED }),
egui::Stroke::new(1.0_f32, if hovered { SELECTION } else { TEXT_MUTED }),
egui::StrokeKind::Inside,
);
ui.painter().text(
@@ -431,7 +431,7 @@ fn draw_authored_node(
ui.painter().line_segment(
[response.rect.left_top(), response.rect.left_bottom()],
egui::Stroke::new(
if primary { 3.0 } else { 2.0 },
if primary { 3.0_f32 } else { 2.0_f32 },
if primary {
SELECTION
} else {
@@ -591,7 +591,7 @@ fn draw_drop_before(
};
ui.painter().line_segment(
[rect.left_center(), rect.right_center()],
egui::Stroke::new(2.0, color),
egui::Stroke::new(2.0_f32, color),
);
ui.painter().circle_filled(rect.left_center(), 3.5, color);
}
@@ -612,7 +612,7 @@ fn draw_attach_target_feedback(ui: &egui::Ui, rect: egui::Rect, invalid: bool) {
ui.painter().rect_stroke(
rect,
2.0,
egui::Stroke::new(2.0, color),
egui::Stroke::new(2.0_f32, color),
egui::StrokeKind::Inside,
);
if rect.width() > 150.0 {
@@ -696,7 +696,7 @@ fn draw_runtime_node(
ui.painter().line_segment(
[response.rect.left_top(), response.rect.left_bottom()],
egui::Stroke::new(
if primary { 3.0 } else { 2.0 },
if primary { 3.0_f32 } else { 2.0_f32 },
if primary {
SELECTION
} else {
File diff suppressed because it is too large. Load diff
Loaded 100 of 438 files, more files were not shown because too many files have changed in this diff. Show more