feat: complete M2 content workspace and inspector
This commit is contained in:
1 parent
931f561e7f
commit
cf6eaba534
438 files changed
+59749
-19043
No files matched your search
+72
-1059
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(),
|
||||
¶meter.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(), ¶meter.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(¶meter.value, &property.property_type)?;
|
||||
if !parameter_value_is_finite(¶meter.value) {
|
||||
return Err(format!(
|
||||
"parameter `{}` contains a non-finite value",
|
||||
parameter.name
|
||||
));
|
||||
}
|
||||
if let (MaterialParameterValue::Float(value), ShaderPropertyType::Float { min, max }) =
|
||||
(¶meter.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")
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user